@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
|
@@ -1,25 +1,25 @@
|
|
|
1
|
-
"use strict";var Tn=Object.defineProperty;var Os=Object.getOwnPropertyDescriptor;var As=Object.getOwnPropertyNames;var Cs=Object.prototype.hasOwnProperty;var Te=(t,e)=>()=>(t&&(e=t(t=0)),e);var vn=(t,e)=>{for(var n in e)Tn(t,n,{get:e[n],enumerable:!0})},Ls=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of As(e))!Cs.call(t,o)&&o!==n&&Tn(t,o,{get:()=>e[o],enumerable:!(r=Os(e,o))||r.enumerable});return t};var Ds=t=>Ls(Tn({},"__esModule",{value:!0}),t);function Mr(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++]=wn,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<Nr)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${Nr})`);let n=0,r=t[n++];if(r!==wn)throw new Error(`decodeEnvelope: unsupported envelope version ${r} (expected ${wn})`);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),c=e.lookupCodec(s);if(c==null)throw new Error(`decodeEnvelope: codec "${s}" not registered (envelope codec_v=${i})`);return{codec:c,codecVersion:i,payload:a}}function Or(t){t.registerCodec(Is)}var Is,wn,Nr,kn=Te(()=>{"use strict";Is={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)}},wn=1,Nr=4});function Nt(t){if(t==null)return Xe;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var Xe,Mt=Te(()=>{"use strict";Xe={type:"system",id:""}});function Et(){return Ze>0||pt}function Ar(){return Ze>0}function mt(t){Ze>0?ft.push(t):t()}function ee(t){Ze+=1;let e=!1;try{t()}catch(n){throw e=!0,n}finally{if(Ze-=1,Ze===0)if(e){if(!pt){let n=ft.splice(0);for(let r of n)try{r()}catch{}Be.length=0,Ve.length=0,et.length=0}}else Ps()}}function Ps(){let t=!pt;t&&(pt=!0);let e=[],n=0;try{for(;Be.length>0||Ve.length>0||et.length>0||t&&ft.length>0;){if(t&&ft.length>0){let s=ft.splice(0);for(let i of s)try{i()}catch(a){e.push(a)}continue}if(n+=1,n>1e3)throw Be.length=0,Ve.length=0,et.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let o=(Be.length>0?Be:Ve.length>0?Ve:et).splice(0);for(let s of o)try{s()}catch(i){e.push(i)}}}finally{t&&(pt=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function Ot(t,e,n){if(e.length===0)return;if(e.length===1){let d=n(e[0][0]);if(d<3||!Et()){t(e);return}(d>=5?et:d===4?Ve:Be).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 c=Et();if(o>0){let d=e.slice(0,o);t(d)}if(s>o){let d=e.slice(o,s);c?Be.push(()=>t(d)):t(d)}if(i>s){let d=e.slice(s,i);c?Ve.push(()=>t(d)):t(d)}if(r>i){let d=e.slice(i,r);c?et.push(()=>t(d)):t(d)}}var Ze,pt,Be,Ve,et,ft,xe=Te(()=>{"use strict";Ze=0,pt=!1,Be=[],Ve=[],et=[],ft=[]});function B(){return Math.trunc(performance.now()*1e6)}function ce(){return Date.now()*1e6}var pe=Te(()=>{"use strict"});var De,D,J,V,_e,Ne,Ae,fe,$,C,Ke,At,Cr,Ct,Lr,Dr,Lt,xn,Rn,Sn,Dt,re=Te(()=>{"use strict";De=Symbol.for("graphrefly/START"),D=Symbol.for("graphrefly/DATA"),J=Symbol.for("graphrefly/DIRTY"),V=Symbol.for("graphrefly/RESOLVED"),_e=Symbol.for("graphrefly/INVALIDATE"),Ne=Symbol.for("graphrefly/PAUSE"),Ae=Symbol.for("graphrefly/RESUME"),fe=Symbol.for("graphrefly/TEARDOWN"),$=Symbol.for("graphrefly/COMPLETE"),C=Symbol.for("graphrefly/ERROR"),Ke=Object.freeze([J]),At=Object.freeze([V]),Cr=Object.freeze([_e]),Ct=Object.freeze([De]),Lr=Object.freeze([$]),Dr=Object.freeze([fe]),Lt=Object.freeze([Ke]),xn=Object.freeze([At]),Rn=Object.freeze([Cr]),Sn=Object.freeze([Lr]),Dt=Object.freeze([Dr])});function Ir(t){t.registerMessageType(De,{tier:0,wireCrossing:!1}),t.registerMessageType(J,{tier:1,wireCrossing:!1}),t.registerMessageType(_e,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(Ne,{tier:2,wireCrossing:!1}),t.registerMessageType(Ae,{tier:2,wireCrossing:!1}),t.registerMessageType(D,{tier:3,wireCrossing:!0}),t.registerMessageType(V,{tier:3,wireCrossing:!0}),t.registerMessageType($,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(C,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(fe,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var It,Pr=Te(()=>{"use strict";re();It=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 Gr(t){return Array.isArray(t)?[...t]:[t]}function Gs(t,e){return t.has(e)||t.has("*")}function Fr(t){let e=[];return t((o,s)=>{e.push({kind:"allow",actions:new Set(Gr(o)),where:s?.where??(()=>!0)})},(o,s)=>{e.push({kind:"deny",actions:new Set(Gr(o)),where:s?.where??(()=>!0)})}),(o,s)=>{let i=!1,a=!1;for(let c of e)Gs(c.actions,s)&&c.where(o)&&(c.kind==="deny"?i=!0:a=!0);return i?!1:a}}function _n(t){let e=Fs.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 Me,Fs,tt=Te(()=>{"use strict";Me=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}};Fs=["human","llm","wallet","system"]});function Nn(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(Nn);if(typeof t=="object"&&t!==null){let e={};for(let n of Object.keys(t).sort())e[n]=Nn(t[n]);return e}return null}function Bs(t){let e=js.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,c=3144134277,d=1013904242,u=2773480762,l=1359893119,p=2600822924,f=528734635,m=1541459225,y=new Uint32Array(64),g=(b,v)=>b>>>v|b<<32-v;for(let b=0;b<o;b+=64){for(let S=0;S<16;S++)y[S]=i.getUint32(b+S*4,!1);for(let S=16;S<64;S++){let E=y[S-15],M=y[S-2],A=g(E,7)^g(E,18)^E>>>3,j=g(M,17)^g(M,19)^M>>>10;y[S]=y[S-16]+A+y[S-7]+j>>>0}let v=a,x=c,w=d,k=u,T=l,R=p,N=f,_=m;for(let S=0;S<64;S++){let E=g(T,6)^g(T,11)^g(T,25),M=T&R^~T&N,A=_+E+M+$s[S]+y[S]>>>0,j=g(v,2)^g(v,13)^g(v,22),K=v&x^v&w^x&w,Z=j+K>>>0;_=N,N=R,R=T,T=k+A>>>0,k=w,w=x,x=v,v=A+Z>>>0}a=a+v>>>0,c=c+x>>>0,d=d+w>>>0,u=u+k>>>0,l=l+T>>>0,p=p+R>>>0,f=f+N>>>0,m=m+_>>>0}let h=b=>b.toString(16).padStart(8,"0");return h(a)+h(c)+h(d)+h(u)+h(l)+h(p)+h(f)+h(m)}function Mn(t){let e=Nn(t??null),n=JSON.stringify(e);return Bs(n).slice(0,16)}function Vs(){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 En(t,e,n){let r=n?.id??Vs();if(t===0)return{id:r,version:0};let s=(n?.hash??Mn)(e);return{id:r,version:0,cid:s,prev:null}}function $r(t,e,n){t.version+=1,"cid"in t&&(t.prev=t.cid,t.cid=n(e))}var $s,js,jr=Te(()=>{"use strict";$s=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]),js=new TextEncoder});function Kr(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function On(t){t.prevData=void 0,t.dirty=!1,t.involvedThisWave=!1,t.dataBatch.length=0,t.terminal=void 0}function Pt(t){return t.length===0?t:typeof t[0]=="symbol"?[t]:t}function te(t,e,n){let r=Ur(t)?t:[],o=typeof t=="function"?t:typeof e=="function"?e:void 0,s={};return Ur(t)?s=(An(e)?e:n)??{}:An(t)?s=t:s=(An(e)?e:n)??{},new ue(r,o,s)}var Br,Vr,Ks,Us,nt,ue,Ur,An,Re=Te(()=>{"use strict";kn();Mt();xe();pe();Pr();tt();re();jr();Br=()=>{},Vr=100;Ks=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},Us=(t,e,n,r)=>{let o=t;if(o._status==="completed"||o._status==="errored")return;let s=o._cached,i=s===void 0?[Ct]:[Ct,[D,s]];o._status==="dirty"&&i.push(Ke),Ot(e,i,o._config.tierOf)},nt=new It({onMessage:Ks,onSubscribe:Us});Ir(nt);Or(nt);ue=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??nt,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??Mn;let o=r.versioning??this._config.defaultVersioning;this._versioningLevel=o,this._versioning=o!=null?En(o,this._cached===void 0?void 0:this._cached,{id:r.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(Kr);let s={};for(let[a,c]of Object.entries(r.meta??{})){let d={initial:c,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([[D,a]])},down(a){i._emit(Pt(a))},up(a){i._emitUp(Pt(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,c=i?.version??0,d=En(e,s,{id:a,hash:o});d.version=c,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 Me({actor:o,action:s,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(o,s))throw new Me({actor:o,action:s,nodeName:this.name})}this._lastMutation={actor:o,timestamp_ns:ce()}}down(e,n){let r=Pt(e);r.length!==0&&(this._checkGuard(n),this._emit(r))}emit(e,n){this._checkGuard(n),this._emit([[D,e]])}up(e,n){if(this._deps.length===0)return;let r=Pt(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 c=Nt(n);if(!this._guard(c,"observe"))throw new Me({actor:c,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 c of this._deps)On(c);if(this._partial===!1){for(let c of this._deps)if(c.prevData!==void 0||c.dataBatch.length!==0||c.terminal!==void 0||c.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(c){throw this._sinkCount-=1,c}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(c){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof s=="function")try{s()}catch{}throw c}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=Br,s.unsub=s.node.subscribe(i=>{if(s.unsub===null)return;let a=this._config.tierOf,c=!1;for(let d of i)a(d[0])>=3&&(c=!0),this._config.onMessage(this,d,{direction:"down-in",depIndex:o},this._actions);c&&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{}On(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=Kr(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Lt),r.unsub=Br;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{}}On(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!==De){if(o===J){this._depDirtied(r);return}if(o===_e){if(this._depInvalidated(r),this._cached===void 0)return;this._emit(Rn);return}if(o===Ne||o===Ae){this._emit([n]);return}if(o===fe){this._emit(Dt);return}if(o===D)this._depSettledAsData(r,n[1]);else if(o===V)this._depSettledAsResolved(r);else if(o===$)this._depSettledAsTerminal(r,!0);else if(o===C)this._depSettledAsTerminal(r,n[1]);else{this._emit([n]);return}if(!this._fn){(o===D||o===V)&&this._emit([n]),(o===$||o===C)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Lt))}_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(xn),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(Sn)}_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>Vr?(this._rerunDepth=0,this._emit([[C,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${Vr} \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"?[Ke,e[0]]:e;let r=!0,o=!1,s=!1,i=-1;for(let c of e){let d=n(c[0]);d<i&&(r=!1),d===3&&(o=!0),c[0]===J&&(s=!0),i=d}let a=e;if(!r){let c=e.map((d,u)=>({m:d,i:u,tier:n(d[0])}));c.sort((d,u)=>d.tier-u.tier||d.i-u.i),a=c.map(d=>d.m)}if(o&&!s&&this._status!=="dirty"){let c=0;for(;c<a.length&&n(a[c][0])===0;)c++;return c===0?[Ke,...a]:[...a.slice(0,c),Ke,...a.slice(c)]}return a}_emit(e){if(e.length===0)return;for(let a=0;a<e.length;a++){let c=e[a];if(c[0]===C&&c[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(c=>c[0]===fe||c[0]===_e);if(a.length===0)return;n=a}n=this._frameBatch(n);let o=null;for(let a=0;a<n.length;a++){let c=n[a],d=c[0];if(d!==Ne&&d!==Ae){o?.push(c);continue}if(c.length<2)throw new Error(`Node "${this.name}": [[${d===Ne?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let u=!0;if(this._pausable!==!1){let l=c[1];if(d===Ne)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))u=!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())}}u?o?.push(c):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]===fe))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(Dt)}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,c=[];for(let d of s)a(d[0])===3?this._pauseBuffer.push(d):c.push(d);c.length>0&&this._dispatchOrAccumulate(c)}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 u of e)n(u[0])===3&&i++;let a=i<=1,c=-1;if(this._versioning!=null&&i>1){for(let u=e.length-1;u>=0;u--)if(e[u][0]===D){c=u;break}}for(let u=0;u<e.length;u++){let l=e[u],p=l[0];if(p===D){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=u;break}if(f){r==null&&(r=e.slice(0,u)),r.push(At),this._status="resolved";continue}this._cached=l[1],this._versioning!=null&&(c<0||u===c)&&$r(this._versioning,l[1],this._hashFn)}this._status="settled",r?.push(l)}else if(r?.push(l),p===J)this._status="dirty";else if(p===V)this._status="resolved";else if(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===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===_e){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===fe&&(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(Ar()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],mt(()=>this._flushBatchPending()));for(let n of e)this._batchPendingMessages.push(n);return}Ot(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);Ot(this._deliverToSinks,n,this._config.tierOf)}},Ur=t=>Array.isArray(t),An=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function I(t,e){return te([],{...e,initial:t})}function ne(t,e){return te((r,o,s)=>t(o,s)??void 0,{describeKind:"producer",...e})}function O(t,e,n){return te(t,(o,s,i)=>{let a=o.map((c,d)=>c!=null&&c.length>0?c.at(-1):i.prevData[d]);s.emit(e(a,i))},{describeKind:"derived",...n})}function ve(t,e,n){return te(t,(o,s,i)=>{let a=o.map((c,d)=>c!=null&&c.length>0?c.at(-1):i.prevData[d]);return e(a,s,i)??void 0},{describeKind:"effect",...n})}var q=Te(()=>{"use strict";Re()});var Yr={};vn(Yr,{NS_PER_MS:()=>ze,NS_PER_SEC:()=>ot,constant:()=>zr,decorrelatedJitter:()=>Jr,exponential:()=>Wr,fibonacci:()=>qr,linear:()=>Hr,resolveBackoffPreset:()=>Gt,withMaxAttempts:()=>qs});function Ue(t){return t<0?0:t}function Hs(t,e){return e==="none"?t:e==="full"?Math.random()*t:t/2+Math.random()*(t/2)}function Ws(t,e){return t+Math.random()*(e-t)}function zr(t){let e=Ue(t);return()=>e}function Hr(t,e){let n=Ue(t),r=e===void 0?n:Ue(e);return o=>n+r*Math.max(0,o)}function Wr(t){let e=Ue(t?.baseNs??1e8),n=t?.factor!==void 0&&t.factor<1?1:t?.factor??2,r=Ue(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,c=1;for(let d=0;d<Math.max(0,s);d++){if(c>=a){c=a;break}c*=n}i=e*c,i>r&&(i=r)}return Hs(i,o)}}function qr(t=100*1e6,e=30*1e9){let n=Ue(t),r=Ue(e);function o(s){if(s<=0)return 1;let i=1,a=2;for(let c=1;c<s;c++){let d=i+a;i=a,a=d}return a}return s=>{let i=o(s)*n;return i<=r?i:r}}function Jr(t=100*1e6,e=30*1e9){return(n,r,o)=>{let i=Math.min(e,(o??t)*3);return Ws(t,i)}}function qs(t,e){return(n,r,o)=>n>=e?null:t(n,r,o)}function Gt(t){if(t==="constant")return zr(1*1e9);if(t==="linear")return Hr(1*1e9);if(t==="exponential")return Wr();if(t==="fibonacci")return qr();if(t==="decorrelatedJitter")return Jr();throw new Error(`Unknown backoff preset: "${String(t)}". Use one of: constant, linear, exponential, fibonacci, decorrelatedJitter`)}var ze,ot,Ln=Te(()=>{"use strict";ze=1e6,ot=1e9});var se,Ie=Te(()=>{"use strict";se=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 Xr={};vn(Xr,{CircuitOpenError:()=>Fe,RateLimiterOverflowError:()=>Ft,TimeoutError:()=>$t,circuitBreaker:()=>ht,fallback:()=>oi,rateLimiter:()=>Zs,retry:()=>Dn,timeout:()=>si,tokenBucket:()=>yt,withBreaker:()=>Xs,withStatus:()=>ei});function He(t){return{describeKind:"derived",...t}}function Js(t){return t<0?0:t}function jt(t){return t[1]}function Qr(t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError("backoff strategy must return a finite number");return t<0?0:t}function Dn(t,e){return typeof t=="function"?Qs(t,e):Ys(t,e)}function Ys(t,e){let n=e?.count,r=e?.backoff,o=n!==void 0?n:r===void 0?0:2147483647;if(o<0)throw new RangeError("retry count must be >= 0");let s=r===void 0?null:typeof r=="string"?Gt(r):r;return ne(i=>{let a=0,c=!1,d=null,u,l=new se;function p(){u?.(),u=void 0}function f(y){if(c)return;if(a>=o){p(),i.down([[C,y]]);return}let g=s===null?0:s(a,y,d);if(g==null){p(),i.down([[C,y]]);return}let h;try{h=Qr(g)}catch{p(),i.down([[C,y]]);return}d=h,a+=1,p();let b=h>0?h/1e6:1;l.start(b,()=>{c||m()})}function m(){l.cancel(),p(),u=t.subscribe(y=>{if(!c)for(let g of y){let h=g[0];if(h===J)i.down([[J]]);else if(h===D)a=0,d=null,i.emit(g[1]);else if(h===V)i.down([[V]]);else if(h===$)p(),i.down([[$]]);else if(h===C){f(jt(g));return}else i.down([g])}})}return m(),()=>{c=!0,l.cancel(),p()}},{...He(),initial:t.cache})}function Qs(t,e){let n=e?.count,r=e?.backoff,o=n!==void 0?n:r===void 0?0:2147483647;if(o<0)throw new RangeError("retry count must be >= 0");let s=r===void 0?null:typeof r=="string"?Gt(r):r;return ne(i=>{let a=0,c=!1,d=null,u,l=new se;function p(){u?.(),u=void 0}function f(y){if(c)return;if(a>=o){p(),i.down([[C,y]]);return}let g=s===null?0:s(a,y,d);if(g==null){p(),i.down([[C,y]]);return}let h;try{h=Qr(g)}catch{p(),i.down([[C,y]]);return}d=h,a+=1,p();let b=h>0?h/1e6:1;l.start(b,()=>{c||m()})}function m(){l.cancel(),p();let y;try{y=t()}catch(g){f(g);return}u=y.subscribe(g=>{if(!c)for(let h of g){let b=h[0];if(b===J)i.down([[J]]);else if(b===D)a=0,d=null,i.emit(h[1]);else if(b===V)i.down([[V]]);else if(b===$)p(),i.down([[$]]);else if(b===C){f(jt(h));return}else i.down([h])}})}return m(),()=>{c=!0,l.cancel(),p()}},{...He(),initial:e?.initial})}function ht(t){let e=Math.max(1,t?.failureThreshold??5),n=Js(t?.cooldownNs??30*1e9),r=t?.cooldown??null,o=Math.max(1,t?.halfOpenMax??1),s=t?.now??B,i="closed",a=0,c=0,d=0,u=n,l=0;function p(){if(!r)return n;let y=r(c);return y!==null?y:n}function f(){i="open",u=p(),d=s(),l=0}return{canExecute(){return i==="closed"?!0:i==="open"?s()-d>=u?(i="half-open",l=1,!0):!1:l<o?(l++,!0):!1},recordSuccess(){i==="half-open"?(i="closed",a=0,c=0):i==="closed"&&(a=0)},recordFailure(y){if(i==="half-open"){c++,f();return}i==="closed"&&(a++,a>=e&&f())},get state(){return i},get failureCount(){return a},reset(){i="closed",a=0,c=0,l=0}}}function Xs(t,e){let n=e?.onOpen??"skip";return r=>{let o=te([],(s,i)=>{function a(){o.meta.breakerState.down([[D,t.state]])}let c=r.subscribe(d=>{for(let u of d){let l=u[0];l===J?i.down([[J]]):l===D?t.canExecute()?(a(),i.emit(u[1])):(a(),n==="error"?i.down([[C,new Fe]]):i.down([[V]])):l===V?i.down([[V]]):l===$?(t.recordSuccess(),a(),i.down([[$]])):l===C?(t.recordFailure(jt(u)),a(),i.down([u])):i.down([u])}});return a(),c},{...He(),meta:{breakerState:t.state},completeWhenDepsComplete:!1,initial:r.cache});return{node:o,breakerState:o.meta.breakerState}}}function yt(t,e){if(t<=0)throw new RangeError("capacity must be > 0");if(e<0)throw new RangeError("refillPerSecond must be >= 0");let n=t,r=B();function o(s){if(e>0){let i=s-r;n=Math.min(t,n+i/1e9*e)}r=s}return{available(){return o(B()),n},tryConsume(s=1){if(s<=0)return!0;let i=B();return o(i),n>=s?(n-=s,!0):!1},putBack(s=1){s<=0||(o(B()),n=Math.min(t,n+s))}}}function Zs(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 ne(a=>{let c=yt(n,i),d=[],u=new se,l=!1,p=1e9/i;function f(){for(;d.length>0;)if(c.tryConsume(1))a.emit(d.shift());else{u.start(Math.max(1,p/1e6),f);return}}let m=t.subscribe(y=>{for(let g of y){if(l)return;let h=g[0];if(h===J)a.down([[J]]);else if(h===D){if(o!==void 0&&d.length>=o){if(s!=="drop-newest")if(s==="drop-oldest")d.shift(),d.push(g[1]);else{l=!0,u.cancel(),d.length=0,a.down([[C,new Ft(o)]]);return}}else d.push(g[1]);f()}else if(h===V)a.down([[V]]);else if(h===$)l=!0,u.cancel(),d.length=0,a.down([[$]]);else if(h===C)l=!0,u.cancel(),d.length=0,a.down([g]);else if(h===fe){l=!0,u.cancel(),d.length=0,a.down([g]);return}else a.down([g])}});return()=>{l=!0,u.cancel(),m()}},{...He(),initial:t.cache})}function ei(t,e){let n=e?.initialStatus??"pending",r=te([],(o,s)=>{let i=n;return r.meta.status.down([[D,n]]),r.meta.error.down([[D,null]]),t.subscribe(c=>{for(let d of c){let u=d[0];if(u===J)s.down([[J]]);else if(u===D)i==="errored"?ee(()=>{r.meta.error.down([[D,null]]),r.meta.status.down([[D,"active"]])}):r.meta.status.down([[D,"active"]]),i="active",s.emit(d[1]);else if(u===V)s.down([[V]]);else if(u===$)r.meta.status.down([[D,"completed"]]),i="completed",s.down([[$]]);else if(u===C){let l=jt(d);ee(()=>{r.meta.error.down([[D,l]]),r.meta.status.down([[D,"errored"]])}),i="errored",s.down([d])}else s.down([d])}})},{...He(),meta:{status:n,error:null},completeWhenDepsComplete:!1,resubscribable:!0,initial:t.cache});return{node:r,status:r.meta.status,error:r.meta.error}}function ti(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function ni(t){return t!=null&&typeof t.then=="function"}function ri(t){return t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function"}function oi(t,e){return ne(n=>{let r,o;function s(){o?.(),o=void 0,ti(e)||ni(e)||ri(e)?r=G(e).subscribe(a=>{n.down(a)}):(n.emit(e),n.down([[$]]))}return o=t.subscribe(i=>{for(let a of i){let c=a[0];if(c===J)n.down([[J]]);else if(c===D)n.emit(a[1]);else if(c===V)n.down([[V]]);else if(c===$)n.down([[$]]);else if(c===C){s();return}else if(c===fe){r?.(),n.down([a]);return}else n.down([a])}}),()=>{o?.(),r?.()}},{...He(),initial:t.cache})}function si(t,e){if(e<=0)throw new RangeError("timeoutNs must be > 0");return ne(n=>{let r=!1,o=new se;function s(){let a=e/1e6;o.start(a,()=>{r||(r=!0,i(),n.down([[C,new $t(e)]]))})}let i=t.subscribe(a=>{for(let c of a){if(r)return;let d=c[0];if(d===J)n.down([[J]]);else if(d===D)s(),n.emit(c[1]);else if(d===V)n.down([[V]]);else if(d===$){o.cancel(),r=!0,n.down([[$]]);return}else if(d===C){o.cancel(),r=!0,n.down([c]);return}else if(d===fe){o.cancel(),r=!0,n.down([c]);return}else n.down([c])}});return s(),()=>{r=!0,o.cancel(),i()}},{...He(),initial:t.cache})}var Fe,Ft,$t,st=Te(()=>{"use strict";xe();pe();re();Re();q();Ln();Q();Ie();Fe=class extends Error{name="CircuitOpenError";constructor(){super("Circuit breaker is open")}};Ft=class extends Error{name="RateLimiterOverflowError";constructor(e){super(`rateLimiter buffer overflow (maxBuffer=${e})`)}};$t=class extends Error{name="TimeoutError";constructor(e){super(`Timed out after ${e/1e6}ms`)}}});function Bt(t){return{describeKind:"producer",...t}}function to(t,e){let{signal:n,period:r,...o}=e??{};return ne(s=>{let i=!1,a=0,c,d,u=()=>{i=!0,c!==void 0&&clearTimeout(c),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([[$]])))},p=()=>{i||(u(),s.down([[C,n.reason]]))};if(n?.aborted){p();return}return c=setTimeout(l,t),n?.addEventListener("abort",p,{once:!0}),u},Bt(o))}function no(t,e){return ne(n=>{let r=!1;try{for(let o of t){if(r)return;n.emit(o)}r||n.down([[$]])}catch(o){r||n.down([[C,o]])}return()=>{r=!0}},Bt(e))}function ii(t){return t!=null&&typeof t.then=="function"}function Vt(t,e){let{signal:n,...r}=e??{};return ne(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([[$]]))},a=>{s||(s=!0,n?.removeEventListener("abort",i),o.down([[C,a]]))}),()=>{s=!0,n?.removeEventListener("abort",i)}},Bt(r))}function Pn(t,e){let{signal:n,...r}=e??{};return ne(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,c=!1,d=t[Symbol.asyncIterator](),u=()=>{c||a.aborted||Promise.resolve(d.next()).then(l=>{if(!(c||a.aborted)){if(l.done){o.down([[$]]);return}o.emit(l.value),u()}},l=>{!c&&!a.aborted&&o.down([[C,l]])})};return u(),()=>{c=!0,n?.removeEventListener("abort",i),s.abort(),Promise.resolve(d.return?.()).catch(()=>{})}},Bt(r))}function ai(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function G(t,e){if(ai(t))return t;if(ii(t))return Vt(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return Pn(t,e);if(typeof n[Symbol.iterator]=="function")return no(t,e)}return di(t)}function di(...t){return no(t,void 0)}function bt(t,e,n){return te([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 we(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]===D){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]===$){r=!0,n(new Error("completed without DATA")),s?(s(),s=void 0):o=!0;return}}}),o&&(s?.(),s=void 0)})}function Zr(t,e,n){return new Promise((r,o)=>{let s=!1,i=!1,a,c=n?.skipCurrent===!0;a=t.subscribe(d=>{for(let u of d){if(s)return;if(!(c&&u[0]===D)){if(u[0]===D){let l=u[1];if(e(l)){s=!0,r(l),a?(a(),a=void 0):i=!0;return}}if(u[0]===C){s=!0,o(u[1]),a?(a(),a=void 0):i=!0;return}if(u[0]===$){s=!0,o(new Error("completed without matching value")),a?(a(),a=void 0):i=!0;return}}}}),c=!1,i&&(a?.(),a=void 0)})}async function ro(t,e){let n=e?.predicate??(s=>s!=null),r=e?.skipCurrent;if(e?.timeoutMs==null||e.timeoutMs<=0)return await Zr(t,n,{skipCurrent:r});if(In===void 0){let[s,i]=await Promise.all([Promise.resolve().then(()=>(st(),Xr)),Promise.resolve().then(()=>(Ln(),Yr))]);In=s.timeout,eo=i.NS_PER_MS}let o=In(t,e.timeoutMs*eo);return await Zr(o,n,{skipCurrent:r})}function oo(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 c of a){if(c[0]===D&&c[1]===!0){n.abort(r),i();return}if(c[0]===C){n.abort(c[1]),i();return}if(c[0]===$){i();return}}}),s&&(o?.(),o=void 0),{signal:n.signal,dispose:()=>{o&&(o(),o=void 0)}}}function Y(t){return t.subscribe(()=>{})}var In,eo,Q=Te(()=>{"use strict";re();Re();q()});var Vd={};vn(Vd,{AgentLoopGraph:()=>hn,AllTiersExhaustedError:()=>kt,BudgetExhaustedError:()=>Zt,ChatStreamGraph:()=>mn,CircuitOpenError:()=>Fe,DEFAULT_DECAY_RATE:()=>wr,FallbackMissError:()=>ki,LLMTimeoutError:()=>dt,ReplayCacheMissError:()=>Je,ToolRegistryGraph:()=>gn,admissionFilter3D:()=>kd,admissionScored:()=>ps,agentLoop:()=>Td,agentMemory:()=>Nd,anthropicAdapter:()=>Gn,canonicalJson:()=>Kn,cascadingLlmAdapter:()=>rr,chatStream:()=>hr,composePricing:()=>Vi,computePrice:()=>Yn,contentGate:()=>gd,costMeterExtractor:()=>cd,createAdapter:()=>Pi,createCapabilitiesRegistry:()=>zs,createPricingRegistry:()=>ji,dryRunAdapter:()=>We,fallbackAdapter:()=>Un,fromLLM:()=>na,frozenContext:()=>ia,gatedStream:()=>id,gaugesAsContext:()=>Md,googleAdapter:()=>zn,graphFromSpec:()=>Ns,graphFromSpecReactive:()=>Pd,handoff:()=>vd,keywordFlagExtractor:()=>ld,knobsAsTools:()=>Fd,llmConsolidator:()=>vr,llmExtractor:()=>Tr,memoryRetrieval:()=>Sr,memoryWithKG:()=>xr,memoryWithTiers:()=>Rr,memoryWithVectors:()=>kr,observableAdapter:()=>Fi,openAICompatAdapter:()=>Wn,parseRateLimitFromError:()=>er,pricingFor:()=>Ki,promptNode:()=>ar,redactor:()=>hd,registryPricing:()=>Bi,resilientAdapter:()=>ta,streamExtractor:()=>pd,streamingPromptNode:()=>sd,suggestStrategy:()=>Ms,suggestStrategyReactive:()=>jd,systemPromptBuilder:()=>ad,tier:()=>Zi,toolCallExtractor:()=>md,toolExecution:()=>yr,toolRegistry:()=>br,toolSelector:()=>wd,validateGraphDef:()=>Bd,withBreaker:()=>Qn,withBudgetGate:()=>Zn,withDryRun:()=>zi,withRateLimiter:()=>nr,withReplayCache:()=>vt,withRetry:()=>or,withTimeout:()=>sr,zeroPrice:()=>Xt});module.exports=Ds(Vd);q();xe();pe();re();q();var Cn=class{_version=0;_store=new Map;_maxSize;_defaultTtl;constructor(e={}){let{maxSize:n,defaultTtl:r}=e;if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(r!==void 0&&r<=0)throw new RangeError("defaultTtl must be positive");this._maxSize=n,this._defaultTtl=r}get version(){return this._version}get size(){return this._store.size}has(e){let n=this._store.get(e);return n===void 0?!1:this._isExpired(n)?(this._store.delete(e),this._version+=1,!1):(this._touchLru(e,n),!0)}get(e){let n=this._store.get(e);if(n!==void 0){if(this._isExpired(n)){this._store.delete(e),this._version+=1;return}return this._touchLru(e,n),n.value}}set(e,n,r){let o=this._resolveExpiresAt(r);this._store.has(e)&&this._store.delete(e),this._store.set(e,{value:n,expiresAt:o}),this._evictLruWhileOver(),this._version+=1}setMany(e,n){let r=this._resolveExpiresAt(n),o=0;try{for(let[s,i]of e)this._store.has(s)&&this._store.delete(s),this._store.set(s,{value:i,expiresAt:r}),o+=1}finally{o>0&&(this._evictLruWhileOver(),this._version+=1)}}delete(e){let n=this._store.delete(e);return n&&(this._version+=1),n}deleteMany(e){let n=0;try{for(let r of e)this._store.delete(r)&&(n+=1)}finally{n>0&&(this._version+=1)}return n}clear(){let e=this._store.size;return e===0?0:(this._store.clear(),this._version+=1,e)}pruneExpired(){let e=B(),n=0;for(let[r,o]of this._store)this._isExpired(o,e)&&(this._store.delete(r),n+=1);return n>0&&(this._version+=1),n}toMap(){let e=B(),n=new Map;for(let[r,o]of this._store)this._isExpired(o,e)||n.set(r,o.value);return n}_resolveExpiresAt(e){let n=e??this._defaultTtl;if(n!==void 0){if(!Number.isFinite(n)||n<=0)throw new RangeError(`MapBackend: ttl must be a positive finite number (got ${n})`);return B()+n*1e9}}_isExpired(e,n){return e.expiresAt===void 0?!1:(n??B())>=e.expiresAt}_touchLru(e,n){this._store.delete(e),this._store.set(e,n)}_evictLruWhileOver(){if(this._maxSize!==void 0)for(;this._store.size>this._maxSize;){let e=this._store.keys().next().value;if(e===void 0)break;this._store.delete(e)}}};function rt(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 Cn({maxSize:n,defaultTtl:r}),c=I(a.toMap(),{name:e,describeKind:"state",equals:(p,f)=>p===f,...o!=null?{versioning:o}:{}});function d(){let p=a.toMap();ee(()=>{c.down([[J]]),c.down([[D,p]])})}function u(){if(!i)return;let p=a.toMap(),f=i.archiveThreshold,m=i.maxSize,y=[];for(let[h,b]of p)y.push({key:h,value:b,score:i.score(h,b)});y.sort((h,b)=>h.score-b.score);let g=new Set;if(f!==void 0)for(let h of y)if(h.score<f)g.add(h.key);else break;if(m!==void 0&&y.length-g.size>m)for(let h of y){if(y.length-g.size<=m)break;g.has(h.key)||g.add(h.key)}if(g.size!==0)for(let h of y)g.has(h.key)&&(i.onArchive?.(h.key,h.value,h.score),a.delete(h.key))}function l(p,f="mutation"){let m=a.version;try{return p()}finally{a.version!==m&&(f==="mutation"&&u(),d())}}return{entries:c,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(){}}}function gt(t,e){return`${t}::${e}`}function zs(t){let e=rt({name:"capabilitiesRegistry"}),n=d=>{e.set(gt(d.provider,d.id),d)};if(t)for(let d of t)n(d);let r=(d,u)=>{let l=e.get(gt(d,u));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 y=m.id;u.startsWith(y)&&(!f||y.length>f.id.length)&&(f=m)}return f},o=128,s=new Map,i=new Map,a=(d,u,l,p)=>{for(d.has(u)&&d.delete(u),d.set(u,l);d.size>p;){let f=d.keys().next().value;if(f===void 0)break;d.delete(f)}},c=O([e.entries],([d])=>Array.from(d.values()),{name:"capabilitiesRegistry/entries",initial:[]});return{register:n,lookup:r,remove(d,u){let l=e.has(gt(d,u));return l&&e.delete(gt(d,u)),l},entries(){let d=e.entries.cache;return(function*(){if(d)for(let u of d.values())yield u})()},lookupNode(d,u){let l=gt(d,u),p=s.get(l);if(p)return s.delete(l),s.set(l,p),p;let f=O([e.entries],()=>r(d,u),{name:`capabilitiesRegistry/lookup/${d}::${u}`,initial:void 0});return a(s,l,f,o),f},entriesNode:c,byProvider(d){let u=i.get(d);if(u)return i.delete(d),i.set(d,u),u;let l=O([c],([p])=>p.filter(f=>f.provider===d),{name:`capabilitiesRegistry/byProvider/${d}`,initial:[]});return a(i,d,l,o),l}}}pe();re();Re();q();Q();function Kt(t){return{describeKind:"derived",...t}}function ci(t){return{describeKind:"derived",partial:!0,...t}}function so(t,e,n){return te([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]])},Kt(n))}function io(t,e,n){let r=n?.where??(s=>s!=null),o=!1;return te([t],(s,i)=>{let a=s[0];if(a==null||a.length===0){i.down([[V]]);return}for(let c of a)!o&&r(c)&&(o=!0,e(c)),i.emit(c)},Kt(n))}function ao(t,e,n){return te([t,e],(r,o,s)=>{let i=r[0],a=r[1],c=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,c])}else o.down([[V]])},ci(n))}function ui(t,e,n){let r,o=!1,s=()=>{o||(o=!0,n())};return r=t.subscribe(i=>{let a=!1,c=!1;for(let d of i)d[0]!==De&&(d[0]===D?e.emit(d[1]):d[0]===$?a=!0:d[0]===C?(c=!0,e.down([d])):(d[0]===J||d[0]===V)&&e.down([d]));c?(r?.(),r=void 0,s()):a&&s()}),()=>{r?.(),r=void 0}}function ae(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return te([t],(i,a,c)=>{if(c.terminalDeps[0]!=null&&c.terminalDeps[0]!==!0){s();return}if(c.terminalDeps[0]===!0){o=!0,r||a.down([[$]]);return}let d=i[0];if(!(d==null||d.length===0))return s(),r=ui(G(e(d[d.length-1])),a,()=>{s(),o&&a.down([[$]])}),{deactivate:()=>{s(),o=!1}}},{...Kt(n),completeWhenDepsComplete:!1})}function co(t,e,n){return ne(r=>{let o=t.subscribe(s=>{for(let i of s)if(i[0]===D)r.emit(i[1]);else if(i[0]===C)try{r.emit(e(i[1]))}catch(a){r.down([[C,a]])}else i[0]===$&&r.down([[$]])});return()=>{o()}},Kt(n))}var Tt=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}};async function*it(t,e){let n=e?.parse??(w=>w),r=e?.signal,o=new TextDecoder,s="",i="message",a=[],c,d,u=[],l=()=>{if(a.length===0&&i==="message"&&c===void 0){a=[];return}let w=a.join(`
|
|
2
|
-
`);u.push({event:i,data:n(
|
|
1
|
+
"use strict";var Mn=Object.defineProperty;var Qs=Object.getOwnPropertyDescriptor;var Xs=Object.getOwnPropertyNames;var Zs=Object.prototype.hasOwnProperty;var Te=(t,e)=>()=>(t&&(e=t(t=0)),e);var En=(t,e)=>{for(var n in e)Mn(t,n,{get:e[n],enumerable:!0})},ei=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Xs(e))!Zs.call(t,o)&&o!==n&&Mn(t,o,{get:()=>e[o],enumerable:!(r=Qs(e,o))||r.enumerable});return t};var ti=t=>ei(Mn({},"__esModule",{value:!0}),t);function Kr(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++]=On,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 zr(t,e){if(t.length<Vr)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${Vr})`);let n=0,r=t[n++];if(r!==On)throw new Error(`decodeEnvelope: unsupported envelope version ${r} (expected ${On})`);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),c=e.lookupCodec(s);if(c==null)throw new Error(`decodeEnvelope: codec "${s}" not registered (envelope codec_v=${i})`);return{codec:c,codecVersion:i,payload:a}}function Ur(t){t.registerCodec(ni)}var ni,On,Vr,An=Te(()=>{"use strict";ni={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)}},On=1,Vr=4});function It(t){if(t==null)return rt;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var rt,Pt=Te(()=>{"use strict";rt={type:"system",id:""}});function Gt(){return ot>0||Tt}function Hr(){return ot>0}function it(t){ot>0?vt.push(t):t()}function te(t){ot+=1;let e=!1;try{t()}catch(n){throw e=!0,n}finally{if(ot-=1,ot===0)if(e){if(!Tt){let n=vt.splice(0);for(let r of n)try{r()}catch{}qe.length=0,We.length=0,st.length=0}}else ri()}}function ri(){let t=!Tt;t&&(Tt=!0);let e=[],n=0;try{for(;qe.length>0||We.length>0||st.length>0||t&&vt.length>0;){if(t&&vt.length>0){let s=vt.splice(0);for(let i of s)try{i()}catch(a){e.push(a)}continue}if(n+=1,n>1e3)throw qe.length=0,We.length=0,st.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let o=(qe.length>0?qe:We.length>0?We:st).splice(0);for(let s of o)try{s()}catch(i){e.push(i)}}}finally{t&&(Tt=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function Ft(t,e,n){if(e.length===0)return;if(e.length===1){let d=n(e[0][0]);if(d<3||!Gt()){t(e);return}(d>=5?st:d===4?We:qe).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 c=Gt();if(o>0){let d=e.slice(0,o);t(d)}if(s>o){let d=e.slice(o,s);c?qe.push(()=>t(d)):t(d)}if(i>s){let d=e.slice(s,i);c?We.push(()=>t(d)):t(d)}if(r>i){let d=e.slice(i,r);c?st.push(()=>t(d)):t(d)}}var ot,Tt,qe,We,st,vt,Se=Te(()=>{"use strict";ot=0,Tt=!1,qe=[],We=[],st=[],vt=[]});function K(){return Math.trunc(performance.now()*1e6)}function ie(){return Date.now()*1e6}var ge=Te(()=>{"use strict"});var $e,D,Q,U,Me,Ee,Ie,me,B,I,Je,$t,qr,jt,Wr,Jr,Bt,Cn,Ln,Dn,Vt,se=Te(()=>{"use strict";$e=Symbol.for("graphrefly/START"),D=Symbol.for("graphrefly/DATA"),Q=Symbol.for("graphrefly/DIRTY"),U=Symbol.for("graphrefly/RESOLVED"),Me=Symbol.for("graphrefly/INVALIDATE"),Ee=Symbol.for("graphrefly/PAUSE"),Ie=Symbol.for("graphrefly/RESUME"),me=Symbol.for("graphrefly/TEARDOWN"),B=Symbol.for("graphrefly/COMPLETE"),I=Symbol.for("graphrefly/ERROR"),Je=Object.freeze([Q]),$t=Object.freeze([U]),qr=Object.freeze([Me]),jt=Object.freeze([$e]),Wr=Object.freeze([B]),Jr=Object.freeze([me]),Bt=Object.freeze([Je]),Cn=Object.freeze([$t]),Ln=Object.freeze([qr]),Dn=Object.freeze([Wr]),Vt=Object.freeze([Jr])});function Yr(t){t.registerMessageType($e,{tier:0,wireCrossing:!1}),t.registerMessageType(Q,{tier:1,wireCrossing:!1}),t.registerMessageType(Me,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(Ee,{tier:2,wireCrossing:!1}),t.registerMessageType(Ie,{tier:2,wireCrossing:!1}),t.registerMessageType(D,{tier:3,wireCrossing:!0}),t.registerMessageType(U,{tier:3,wireCrossing:!0}),t.registerMessageType(B,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(I,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(me,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var Kt,Qr=Te(()=>{"use strict";se();Kt=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 Xr(t){return Array.isArray(t)?[...t]:[t]}function oi(t,e){return t.has(e)||t.has("*")}function Zr(t){let e=[];return t((o,s)=>{e.push({kind:"allow",actions:new Set(Xr(o)),where:s?.where??(()=>!0)})},(o,s)=>{e.push({kind:"deny",actions:new Set(Xr(o)),where:s?.where??(()=>!0)})}),(o,s)=>{let i=!1,a=!1;for(let c of e)oi(c.actions,s)&&c.where(o)&&(c.kind==="deny"?i=!0:a=!0);return i?!1:a}}function In(t){let e=si.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 Oe,si,at=Te(()=>{"use strict";Oe=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}};si=["human","llm","wallet","system"]});function Pn(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(Pn);if(typeof t=="object"&&t!==null){let e={};for(let n of Object.keys(t).sort())e[n]=Pn(t[n]);return e}return null}function di(t){let e=ai.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,c=3144134277,d=1013904242,u=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 N=0;N<16;N++)h[N]=i.getUint32(b+N*4,!1);for(let N=16;N<64;N++){let E=h[N-15],x=h[N-2],O=g(E,7)^g(E,18)^E>>>3,V=g(x,17)^g(x,19)^x>>>10;h[N]=h[N-16]+O+h[N-7]+V>>>0}let v=a,R=c,_=d,S=u,T=l,w=p,k=f,M=m;for(let N=0;N<64;N++){let E=g(T,6)^g(T,11)^g(T,25),x=T&w^~T&k,O=M+E+x+ii[N]+h[N]>>>0,V=g(v,2)^g(v,13)^g(v,22),$=v&R^v&_^R&_,Y=V+$>>>0;M=k,k=w,w=T,T=S+O>>>0,S=_,_=R,R=v,v=O+Y>>>0}a=a+v>>>0,c=c+R>>>0,d=d+_>>>0,u=u+S>>>0,l=l+T>>>0,p=p+w>>>0,f=f+k>>>0,m=m+M>>>0}let y=b=>b.toString(16).padStart(8,"0");return y(a)+y(c)+y(d)+y(u)+y(l)+y(p)+y(f)+y(m)}function Gn(t){let e=Pn(t??null),n=JSON.stringify(e);return di(n).slice(0,16)}function ci(){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 Fn(t,e,n){let r=n?.id??ci();if(t===0)return{id:r,version:0};let s=(n?.hash??Gn)(e);return{id:r,version:0,cid:s,prev:null}}function eo(t,e,n){t.version+=1,"cid"in t&&(t.prev=t.cid,t.cid=n(e))}var ii,ai,to=Te(()=>{"use strict";ii=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]),ai=new TextEncoder});function oo(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function $n(t){t.prevData=void 0,t.dirty=!1,t.involvedThisWave=!1,t.dataBatch.length=0,t.terminal=void 0}function zt(t){return t.length===0?t:typeof t[0]=="symbol"?[t]:t}function ne(t,e,n){let r=so(t)?t:[],o=typeof t=="function"?t:typeof e=="function"?e:void 0,s={};return so(t)?s=(jn(e)?e:n)??{}:jn(t)?s=t:s=(jn(e)?e:n)??{},new le(r,o,s)}var no,ro,ui,li,dt,le,so,jn,ke=Te(()=>{"use strict";An();Pt();Se();ge();Qr();at();se();to();no=()=>{},ro=100;ui=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},li=(t,e,n,r)=>{let o=t;if(o._status==="completed"||o._status==="errored")return;let s=o._cached,i=s===void 0?[jt]:[jt,[D,s]];o._status==="dirty"&&i.push(Je),Ft(e,i,o._config.tierOf)},dt=new Kt({onMessage:ui,onSubscribe:li});Yr(dt);Ur(dt);le=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??dt,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??Gn;let o=r.versioning??this._config.defaultVersioning;this._versioningLevel=o,this._versioning=o!=null?Fn(o,this._cached===void 0?void 0:this._cached,{id:r.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(oo);let s={};for(let[a,c]of Object.entries(r.meta??{})){let d={initial:c,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([[D,a]])},down(a){i._emit(zt(a))},up(a){i._emitUp(zt(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,c=i?.version??0,d=Fn(e,s,{id:a,hash:o});d.version=c,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=It(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=It(e?.actor),s=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(o,s))throw new Oe({actor:o,action:s,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(o,s))throw new Oe({actor:o,action:s,nodeName:this.name})}this._lastMutation={actor:o,timestamp_ns:ie()}}down(e,n){let r=zt(e);r.length!==0&&(this._checkGuard(n),this._emit(r))}emit(e,n){this._checkGuard(n),this._emit([[D,e]])}up(e,n){if(this._deps.length===0)return;let r=zt(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 c=It(n);if(!this._guard(c,"observe"))throw new Oe({actor:c,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 c of this._deps)$n(c);if(this._partial===!1){for(let c of this._deps)if(c.prevData!==void 0||c.dataBatch.length!==0||c.terminal!==void 0||c.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(c){throw this._sinkCount-=1,c}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(c){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof s=="function")try{s()}catch{}throw c}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=no,s.unsub=s.node.subscribe(i=>{if(s.unsub===null)return;let a=this._config.tierOf,c=!1;for(let d of i)a(d[0])>=3&&(c=!0),this._config.onMessage(this,d,{direction:"down-in",depIndex:o},this._actions);c&&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{}$n(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=oo(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Bt),r.unsub=no;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{}}$n(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!==$e){if(o===Q){this._depDirtied(r);return}if(o===Me){if(this._depInvalidated(r),this._cached===void 0)return;this._emit(Ln);return}if(o===Ee||o===Ie){this._emit([n]);return}if(o===me){this._emit(Vt);return}if(o===D)this._depSettledAsData(r,n[1]);else if(o===U)this._depSettledAsResolved(r);else if(o===B)this._depSettledAsTerminal(r,!0);else if(o===I)this._depSettledAsTerminal(r,n[1]);else{this._emit([n]);return}if(!this._fn){(o===D||o===U)&&this._emit([n]),(o===B||o===I)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Bt))}_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(Cn),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(Dn)}_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>ro?(this._rerunDepth=0,this._emit([[I,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${ro} \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"?[Je,e[0]]:e;let r=!0,o=!1,s=!1,i=-1;for(let c of e){let d=n(c[0]);d<i&&(r=!1),d===3&&(o=!0),c[0]===Q&&(s=!0),i=d}let a=e;if(!r){let c=e.map((d,u)=>({m:d,i:u,tier:n(d[0])}));c.sort((d,u)=>d.tier-u.tier||d.i-u.i),a=c.map(d=>d.m)}if(o&&!s&&this._status!=="dirty"){let c=0;for(;c<a.length&&n(a[c][0])===0;)c++;return c===0?[Je,...a]:[...a.slice(0,c),Je,...a.slice(c)]}return a}_emit(e){if(e.length===0)return;for(let a=0;a<e.length;a++){let c=e[a];if(c[0]===I&&c[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(c=>c[0]===me||c[0]===Me);if(a.length===0)return;n=a}n=this._frameBatch(n);let o=null;for(let a=0;a<n.length;a++){let c=n[a],d=c[0];if(d!==Ee&&d!==Ie){o?.push(c);continue}if(c.length<2)throw new Error(`Node "${this.name}": [[${d===Ee?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let u=!0;if(this._pausable!==!1){let l=c[1];if(d===Ee)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))u=!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())}}u?o?.push(c):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]===me))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(Vt)}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,c=[];for(let d of s)a(d[0])===3?this._pauseBuffer.push(d):c.push(d);c.length>0&&this._dispatchOrAccumulate(c)}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 u of e)n(u[0])===3&&i++;let a=i<=1,c=-1;if(this._versioning!=null&&i>1){for(let u=e.length-1;u>=0;u--)if(e[u][0]===D){c=u;break}}for(let u=0;u<e.length;u++){let l=e[u],p=l[0];if(p===D){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=u;break}if(f){r==null&&(r=e.slice(0,u)),r.push($t),this._status="resolved";continue}this._cached=l[1],this._versioning!=null&&(c<0||u===c)&&eo(this._versioning,l[1],this._hashFn)}this._status="settled",r?.push(l)}else if(r?.push(l),p===Q)this._status="dirty";else if(p===U)this._status="resolved";else if(p===B){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===Me){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===me&&(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(Hr()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],it(()=>this._flushBatchPending()));for(let n of e)this._batchPendingMessages.push(n);return}Ft(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);Ft(this._deliverToSinks,n,this._config.tierOf)}},so=t=>Array.isArray(t),jn=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function P(t,e){return ne([],{...e,initial:t})}function oe(t,e){return ne((r,o,s)=>t(o,s)??void 0,{describeKind:"producer",...e})}function C(t,e,n){return ne(t,(o,s,i)=>{let a=o.map((c,d)=>c!=null&&c.length>0?c.at(-1):i.prevData[d]);s.emit(e(a,i))},{describeKind:"derived",...n})}function xe(t,e,n){return ne(t,(o,s,i)=>{let a=o.map((c,d)=>c!=null&&c.length>0?c.at(-1):i.prevData[d]);return e(a,s,i)??void 0},{describeKind:"effect",...n})}var W=Te(()=>{"use strict";ke()});var po={};En(po,{NS_PER_MS:()=>Qe,NS_PER_SEC:()=>ct,constant:()=>io,decorrelatedJitter:()=>lo,exponential:()=>co,fibonacci:()=>uo,linear:()=>ao,resolveBackoffPreset:()=>Ut,withMaxAttempts:()=>gi});function Ye(t){return t<0?0:t}function fi(t,e){return e==="none"?t:e==="full"?Math.random()*t:t/2+Math.random()*(t/2)}function mi(t,e){return t+Math.random()*(e-t)}function io(t){let e=Ye(t);return()=>e}function ao(t,e){let n=Ye(t),r=e===void 0?n:Ye(e);return o=>n+r*Math.max(0,o)}function co(t){let e=Ye(t?.baseNs??1e8),n=t?.factor!==void 0&&t.factor<1?1:t?.factor??2,r=Ye(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,c=1;for(let d=0;d<Math.max(0,s);d++){if(c>=a){c=a;break}c*=n}i=e*c,i>r&&(i=r)}return fi(i,o)}}function uo(t=100*1e6,e=30*1e9){let n=Ye(t),r=Ye(e);function o(s){if(s<=0)return 1;let i=1,a=2;for(let c=1;c<s;c++){let d=i+a;i=a,a=d}return a}return s=>{let i=o(s)*n;return i<=r?i:r}}function lo(t=100*1e6,e=30*1e9){return(n,r,o)=>{let i=Math.min(e,(o??t)*3);return mi(t,i)}}function gi(t,e){return(n,r,o)=>n>=e?null:t(n,r,o)}function Ut(t){if(t==="constant")return io(1*1e9);if(t==="linear")return ao(1*1e9);if(t==="exponential")return co();if(t==="fibonacci")return uo();if(t==="decorrelatedJitter")return lo();throw new Error(`Unknown backoff preset: "${String(t)}". Use one of: constant, linear, exponential, fibonacci, decorrelatedJitter`)}var Qe,ct,Vn=Te(()=>{"use strict";Qe=1e6,ct=1e9});function Ht(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 hi(t){return t._describeKind!=null?t._describeKind:t._deps.length>0?"derived":t._fn!=null?"producer":"state"}function ut(t){let e=new WeakSet,n={};for(let[r,o]of fo(t))n[r]=Kn(o,e);return n}function Kn(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=>Kn(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 fo(r))o[s]=Kn(i,e);return o}return"<unserializable>"}function fo(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 ae(t,e){let n={factory:t};return e!==void 0&&(n.factoryArgs=e),n}function yi(t){let e={};for(let[n,r]of Object.entries(t.meta))try{e[n]=r.cache}catch{}return e}function zn(t,e){let n=e==null,r=!n&&e!=null?[...e].filter(d=>d.startsWith("meta.")).map(d=>d.slice(5)):null,o=n||e.has("meta")||r!=null&&r.length>0,s="state",i=[];t instanceof le&&(s=hi(t),i=t._deps.map(d=>d.node.name??""));let a={type:s,deps:i};(n||e.has("status"))&&(a.status=t.status);let c=t instanceof le?t._guard:void 0;if(o){let d={...yi(t)};if(c!=null&&d.access===void 0&&(d.access=In(c)),r!=null&&r.length>0&&!e.has("meta")){let u={};for(let l of r)l in d&&(u[l]=d[l]);a.meta=u}else a.meta=d}if(t.name!=null&&(a.name=t.name),n||e.has("value")){t.status==="sentinel"&&(a.sentinel=!0);try{a.value=t.cache}catch{}}if((n||e.has("v"))&&t.v!=null){let d={id:t.v.id,version:t.v.version};"cid"in t.v&&(d.cid=t.v.cid,d.prev=t.v.prev),a.v=d}return(n||e.has("guard"))&&c!=null&&(a.guard=In(c)),(n||e.has("lastMutation"))&&t.lastMutation!=null&&(a.lastMutation=t.lastMutation),a}var Ae=Te(()=>{"use strict";at();ke()});var ce,je=Te(()=>{"use strict";ce=class{_timer;_gen=0;start(e,n){this.cancel(),this._gen+=1;let r=this._gen;this._timer=setTimeout(()=>{this._timer=void 0,r===this._gen&&n()},e)}cancel(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}get pending(){return this._timer!==void 0}}});var ho={};En(ho,{CircuitOpenError:()=>Ke,RateLimiterOverflowError:()=>qt,TimeoutError:()=>Wt,circuitBreaker:()=>kt,fallback:()=>Ni,rateLimiter:()=>ki,retry:()=>Un,timeout:()=>Mi,tokenBucket:()=>xt,withBreaker:()=>wi,withStatus:()=>xi});function Xe(t){return{describeKind:"derived",...t}}function bi(t){return t<0?0:t}function Jt(t){return t[1]}function mo(t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError("backoff strategy must return a finite number");return t<0?0:t}function Un(t,e){return typeof t=="function"?vi(t,e):Ti(t,e)}function go(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 Ti(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"?Ut(r):r;return oe(i=>{let a=0,c=!1,d=null,u,l=new ce;function p(){u?.(),u=void 0}function f(h){if(c)return;if(a>=o){p(),i.down([[I,h]]);return}let g=s===null?0:s(a,h,d);if(g==null){p(),i.down([[I,h]]);return}let y;try{y=mo(g)}catch{p(),i.down([[I,h]]);return}d=y,a+=1,p();let b=y>0?y/1e6:1;l.start(b,()=>{c||m()})}function m(){l.cancel(),p(),u=t.subscribe(h=>{if(!c)for(let g of h){let y=g[0];if(y===Q)i.down([[Q]]);else if(y===D)a=0,d=null,i.emit(g[1]);else if(y===U)i.down([[U]]);else if(y===B)p(),i.down([[B]]);else if(y===I){f(Jt(g));return}else i.down([g])}})}return m(),()=>{c=!0,l.cancel(),p()}},{...Xe(),initial:t.cache,meta:{...ae("retry",go(e))}})}function vi(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"?Ut(r):r;return oe(i=>{let a=0,c=!1,d=null,u,l=new ce;function p(){u?.(),u=void 0}function f(h){if(c)return;if(a>=o){p(),i.down([[I,h]]);return}let g=s===null?0:s(a,h,d);if(g==null){p(),i.down([[I,h]]);return}let y;try{y=mo(g)}catch{p(),i.down([[I,h]]);return}d=y,a+=1,p();let b=y>0?y/1e6:1;l.start(b,()=>{c||m()})}function m(){l.cancel(),p();let h;try{h=t()}catch(g){f(g);return}u=h.subscribe(g=>{if(!c)for(let y of g){let b=y[0];if(b===Q)i.down([[Q]]);else if(b===D)a=0,d=null,i.emit(y[1]);else if(b===U)i.down([[U]]);else if(b===B)p(),i.down([[B]]);else if(b===I){f(Jt(y));return}else i.down([y])}})}return m(),()=>{c=!0,l.cancel(),p()}},{...Xe(),initial:e?.initial,meta:{...ae("retry",go(e))}})}function kt(t){let e=Math.max(1,t?.failureThreshold??5),n=bi(t?.cooldownNs??30*1e9),r=t?.cooldown??null,o=Math.max(1,t?.halfOpenMax??1),s=t?.now??K,i="closed",a=0,c=0,d=0,u=n,l=0;function p(){if(!r)return n;let h=r(c);return h!==null?h:n}function f(){i="open",u=p(),d=s(),l=0}return{canExecute(){return i==="closed"?!0:i==="open"?s()-d>=u?(i="half-open",l=1,!0):!1:l<o?(l++,!0):!1},recordSuccess(){i==="half-open"?(i="closed",a=0,c=0):i==="closed"&&(a=0)},recordFailure(h){if(i==="half-open"){c++,f();return}i==="closed"&&(a++,a>=e&&f())},get state(){return i},get failureCount(){return a},reset(){i="closed",a=0,c=0,l=0}}}function wi(t,e){let n=e?.onOpen??"skip";return r=>{let o=ne([],(s,i)=>{function a(){o.meta.breakerState.down([[D,t.state]])}let c=r.subscribe(d=>{for(let u of d){let l=u[0];l===Q?i.down([[Q]]):l===D?t.canExecute()?(a(),i.emit(u[1])):(a(),n==="error"?i.down([[I,new Ke]]):i.down([[U]])):l===U?i.down([[U]]):l===B?(t.recordSuccess(),a(),i.down([[B]])):l===I?(t.recordFailure(Jt(u)),a(),i.down([u])):i.down([u])}});return a(),c},{...Xe(),meta:{breakerState:t.state,...ae("withBreaker",{onOpen:n})},completeWhenDepsComplete:!1,initial:r.cache});return{node:o,breakerState:o.meta.breakerState}}}function xt(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=K();function o(s){if(e>0){let i=s-r;n=Math.min(t,n+i/1e9*e)}r=s}return{available(){return o(K()),n},tryConsume(s=1){if(s<=0)return!0;let i=K();return o(i),n>=s?(n-=s,!0):!1},putBack(s=1){s<=0||(o(K()),n=Math.min(t,n+s))}}}function ki(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 oe(a=>{let c=xt(n,i),d=[],u=new ce,l=!1,p=1e9/i;function f(){for(;d.length>0;)if(c.tryConsume(1))a.emit(d.shift());else{u.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===Q)a.down([[Q]]);else if(y===D){if(o!==void 0&&d.length>=o){if(s!=="drop-newest")if(s==="drop-oldest")d.shift(),d.push(g[1]);else{l=!0,u.cancel(),d.length=0,a.down([[I,new qt(o)]]);return}}else d.push(g[1]);f()}else if(y===U)a.down([[U]]);else if(y===B)l=!0,u.cancel(),d.length=0,a.down([[B]]);else if(y===I)l=!0,u.cancel(),d.length=0,a.down([g]);else if(y===me){l=!0,u.cancel(),d.length=0,a.down([g]);return}else a.down([g])}});return()=>{l=!0,u.cancel(),m()}},{...Xe(),initial:t.cache,meta:{...ae("rateLimiter",e)}})}function xi(t,e){let n=e?.initialStatus??"pending",r=ne([],(o,s)=>{let i=n;return r.meta.status.down([[D,n]]),r.meta.error.down([[D,null]]),t.subscribe(c=>{for(let d of c){let u=d[0];if(u===Q)s.down([[Q]]);else if(u===D)i==="errored"?te(()=>{r.meta.error.down([[D,null]]),r.meta.status.down([[D,"active"]])}):r.meta.status.down([[D,"active"]]),i="active",s.emit(d[1]);else if(u===U)s.down([[U]]);else if(u===B)r.meta.status.down([[D,"completed"]]),i="completed",s.down([[B]]);else if(u===I){let l=Jt(d);te(()=>{r.meta.error.down([[D,l]]),r.meta.status.down([[D,"errored"]])}),i="errored",s.down([d])}else s.down([d])}})},{...Xe(),meta:{status:n,error:null,...ae("withStatus",{initialStatus:n})},completeWhenDepsComplete:!1,resubscribable:!0,initial:t.cache});return{node:r,status:r.meta.status,error:r.meta.error}}function Ri(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function Si(t){return t!=null&&typeof t.then=="function"}function _i(t){return t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function"}function Ni(t,e){return oe(n=>{let r,o;function s(){o?.(),o=void 0,Ri(e)||Si(e)||_i(e)?r=F(e).subscribe(a=>{n.down(a)}):(n.emit(e),n.down([[B]]))}return o=t.subscribe(i=>{for(let a of i){let c=a[0];if(c===Q)n.down([[Q]]);else if(c===D)n.emit(a[1]);else if(c===U)n.down([[U]]);else if(c===B)n.down([[B]]);else if(c===I){s();return}else if(c===me){r?.(),n.down([a]);return}else n.down([a])}}),()=>{o?.(),r?.()}},{...Xe(),initial:t.cache,meta:{...ae("fallback")}})}function Mi(t,e){if(e<=0)throw new RangeError("timeoutNs must be > 0");return oe(n=>{let r=!1,o=new ce;function s(){let a=e/1e6;o.start(a,()=>{r||(r=!0,i(),n.down([[I,new Wt(e)]]))})}let i=t.subscribe(a=>{for(let c of a){if(r)return;let d=c[0];if(d===Q)n.down([[Q]]);else if(d===D)s(),n.emit(c[1]);else if(d===U)n.down([[U]]);else if(d===B){o.cancel(),r=!0,n.down([[B]]);return}else if(d===I){o.cancel(),r=!0,n.down([c]);return}else if(d===me){o.cancel(),r=!0,n.down([c]);return}else n.down([c])}});return s(),()=>{r=!0,o.cancel(),i()}},{...Xe(),initial:t.cache,meta:{...ae("timeout",{timeoutNs:e})}})}var Ke,qt,Wt,lt=Te(()=>{"use strict";Se();ge();se();Ae();ke();W();Vn();ee();je();Ke=class extends Error{name="CircuitOpenError";constructor(){super("Circuit breaker is open")}};qt=class extends Error{name="RateLimiterOverflowError";constructor(e){super(`rateLimiter buffer overflow (maxBuffer=${e})`)}};Wt=class extends Error{name="TimeoutError";constructor(e){super(`Timed out after ${e/1e6}ms`)}}});function Yt(t){return{describeKind:"producer",...t}}function To(t,e){let{signal:n,period:r,...o}=e??{};return oe(s=>{let i=!1,a=0,c,d,u=()=>{i=!0,c!==void 0&&clearTimeout(c),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([[B]])))},p=()=>{i||(u(),s.down([[I,n.reason]]))};if(n?.aborted){p();return}return c=setTimeout(l,t),n?.addEventListener("abort",p,{once:!0}),u},Yt(o))}function vo(t,e){return oe(n=>{let r=!1;try{for(let o of t){if(r)return;n.emit(o)}r||n.down([[B]])}catch(o){r||n.down([[I,o]])}return()=>{r=!0}},Yt(e))}function Ei(t){return t!=null&&typeof t.then=="function"}function Qt(t,e){let{signal:n,...r}=e??{};return oe(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([[B]]))},a=>{s||(s=!0,n?.removeEventListener("abort",i),o.down([[I,a]]))}),()=>{s=!0,n?.removeEventListener("abort",i)}},Yt(r))}function qn(t,e){let{signal:n,...r}=e??{};return oe(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,c=!1,d=t[Symbol.asyncIterator](),u=()=>{c||a.aborted||Promise.resolve(d.next()).then(l=>{if(!(c||a.aborted)){if(l.done){o.down([[B]]);return}o.emit(l.value),u()}},l=>{!c&&!a.aborted&&o.down([[I,l]])})};return u(),()=>{c=!0,n?.removeEventListener("abort",i),s.abort(),Promise.resolve(d.return?.()).catch(()=>{})}},Yt(r))}function Oi(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function F(t,e){if(Oi(t))return t;if(Ei(t))return Qt(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return qn(t,e);if(typeof n[Symbol.iterator]=="function")return vo(t,e)}return Ai(t)}function Ai(...t){return vo(t,void 0)}function Rt(t,e,n){return ne([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 Re(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]===D){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]===B){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,c=n?.skipCurrent===!0;a=t.subscribe(d=>{for(let u of d){if(s)return;if(!(c&&u[0]===D)){if(u[0]===D){let l=u[1];if(e(l)){s=!0,r(l),a?(a(),a=void 0):i=!0;return}}if(u[0]===I){s=!0,o(u[1]),a?(a(),a=void 0):i=!0;return}if(u[0]===B){s=!0,o(new Error("completed without matching value")),a?(a(),a=void 0):i=!0;return}}}}),c=!1,i&&(a?.(),a=void 0)})}async function wo(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(Hn===void 0){let[s,i]=await Promise.all([Promise.resolve().then(()=>(lt(),ho)),Promise.resolve().then(()=>(Vn(),po))]);Hn=s.timeout,bo=i.NS_PER_MS}let o=Hn(t,e.timeoutMs*bo);return await yo(o,n,{skipCurrent:r})}function ko(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 c of a){if(c[0]===D&&c[1]===!0){n.abort(r),i();return}if(c[0]===I){n.abort(c[1]),i();return}if(c[0]===B){i();return}}}),s&&(o?.(),o=void 0),{signal:n.signal,dispose:()=>{o&&(o(),o=void 0)}}}function J(t){return t.subscribe(()=>{})}var Hn,bo,ee=Te(()=>{"use strict";se();ke();W()});var cc={};En(cc,{AgentLoopGraph:()=>Sn,AllTiersExhaustedError:()=>Mt,BudgetExhaustedError:()=>cn,ChatStreamGraph:()=>xn,CircuitOpenError:()=>Ke,DEFAULT_DECAY_RATE:()=>Pr,FallbackMissError:()=>Ui,LLMTimeoutError:()=>mt,ReplayCacheMissError:()=>tt,ToolRegistryGraph:()=>Rn,admissionFilter3D:()=>Kd,admissionScored:()=>Es,agentLoop:()=>jd,agentMemory:()=>qd,anthropicAdapter:()=>Wn,canonicalJson:()=>er,cascadingLlmAdapter:()=>mr,chatStream:()=>Or,composePricing:()=>la,computePrice:()=>ar,contentGate:()=>Pd,costMeterExtractor:()=>Od,createAdapter:()=>sa,createCapabilitiesRegistry:()=>pi,createPricingRegistry:()=>ca,dryRunAdapter:()=>Ze,fallbackAdapter:()=>tr,fromLLM:()=>Sa,frozenContext:()=>Ea,gatedStream:()=>Nd,gaugesAsContext:()=>Wd,googleAdapter:()=>nr,graphFromSpec:()=>Ws,graphFromSpecReactive:()=>rc,handoff:()=>Bd,keywordFlagExtractor:()=>Cd,knobsAsTools:()=>sc,llmConsolidator:()=>Dr,llmExtractor:()=>Lr,memoryRetrieval:()=>jr,memoryWithKG:()=>Fr,memoryWithTiers:()=>$r,memoryWithVectors:()=>Gr,observableAdapter:()=>aa,openAICompatAdapter:()=>or,parseRateLimitFromError:()=>lr,pricingFor:()=>pa,promptNode:()=>br,redactor:()=>Gd,registryPricing:()=>ua,resilientAdapter:()=>Ra,streamExtractor:()=>Ld,streamingPromptNode:()=>_d,suggestStrategy:()=>Js,suggestStrategyReactive:()=>ac,systemPromptBuilder:()=>Md,tier:()=>ka,toolCallExtractor:()=>Id,toolExecution:()=>Ar,toolRegistry:()=>Cr,toolSelector:()=>Vd,validateGraphDef:()=>dc,withBreaker:()=>dr,withBudgetGate:()=>ur,withDryRun:()=>ma,withRateLimiter:()=>fr,withReplayCache:()=>_t,withRetry:()=>gr,withTimeout:()=>hr,zeroPrice:()=>dn});module.exports=ti(cc);W();Se();ge();se();W();var Bn=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=K(),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=K(),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 K()+n*1e9}}_isExpired(e,n){return e.expiresAt===void 0?!1:(n??K())>=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 Le(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 Bn({maxSize:n,defaultTtl:r}),c=P(a.toMap(),{name:e,describeKind:"state",equals:(p,f)=>p===f,...o!=null?{versioning:o}:{}});function d(){let p=a.toMap();te(()=>{c.down([[Q]]),c.down([[D,p]])})}function u(){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"&&u(),d())}}return{entries:c,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(){}}}function wt(t,e){return`${t}::${e}`}function pi(t){let e=Le({name:"capabilitiesRegistry"}),n=d=>{e.set(wt(d.provider,d.id),d)};if(t)for(let d of t)n(d);let r=(d,u)=>{let l=e.get(wt(d,u));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;u.startsWith(h)&&(!f||h.length>f.id.length)&&(f=m)}return f},o=128,s=new Map,i=new Map,a=(d,u,l,p)=>{for(d.has(u)&&d.delete(u),d.set(u,l);d.size>p;){let f=d.keys().next().value;if(f===void 0)break;d.delete(f)}},c=C([e.entries],([d])=>Array.from(d.values()),{name:"capabilitiesRegistry/entries",initial:[]});return{register:n,lookup:r,remove(d,u){let l=e.has(wt(d,u));return l&&e.delete(wt(d,u)),l},entries(){let d=e.entries.cache;return(function*(){if(d)for(let u of d.values())yield u})()},lookupNode(d,u){let l=wt(d,u),p=s.get(l);if(p)return s.delete(l),s.set(l,p),p;let f=C([e.entries],()=>r(d,u),{name:`capabilitiesRegistry/lookup/${d}::${u}`,initial:void 0});return a(s,l,f,o),f},entriesNode:c,byProvider(d){let u=i.get(d);if(u)return i.delete(d),i.set(d,u),u;let l=C([c],([p])=>p.filter(f=>f.provider===d),{name:`capabilitiesRegistry/byProvider/${d}`,initial:[]});return a(i,d,l,o),l}}}ge();se();Ae();ke();W();ee();function Xt(t){return{describeKind:"derived",...t}}function Ci(t){return{describeKind:"derived",partial:!0,...t}}function xo(t,e,n){return ne([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[U]]);return}let i=!1;for(let a of s)e(a)&&(o.emit(a),i=!0);i||o.down([[U]])},{...Xt(n),meta:{...ae("filter"),...n?.meta??{}}})}function Ro(t,e,n){let r=n?.where??(s=>s!=null),o=!1;return ne([t],(s,i)=>{let a=s[0];if(a==null||a.length===0){i.down([[U]]);return}for(let c of a)!o&&r(c)&&(o=!0,e(c)),i.emit(c)},Xt(n))}function So(t,e,n){return ne([t,e],(r,o,s)=>{let i=r[0],a=r[1],c=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([[U]]);return}for(let d of i)o.emit([d,c])}else o.down([[U]])},{...Ci(n),meta:{...ae("withLatestFrom"),...n?.meta??{}}})}function Li(t,e,n){let r,o=!1,s=()=>{o||(o=!0,n())};return r=t.subscribe(i=>{let a=!1,c=!1;for(let d of i)d[0]!==$e&&(d[0]===D?e.emit(d[1]):d[0]===B?a=!0:d[0]===I?(c=!0,e.down([d])):(d[0]===Q||d[0]===U)&&e.down([d]));c?(r?.(),r=void 0,s()):a&&s()}),()=>{r?.(),r=void 0}}function pe(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return ne([t],(i,a,c)=>{if(c.terminalDeps[0]!=null&&c.terminalDeps[0]!==!0){s();return}if(c.terminalDeps[0]===!0){o=!0,r||a.down([[B]]);return}let d=i[0];if(!(d==null||d.length===0))return s(),r=Li(F(e(d[d.length-1])),a,()=>{s(),o&&a.down([[B]])}),{deactivate:()=>{s(),o=!1}}},{...Xt(n),completeWhenDepsComplete:!1,meta:{...ae("switchMap"),...n?.meta??{}}})}function _o(t,e,n){return oe(r=>{let o=t.subscribe(s=>{for(let i of s)if(i[0]===D)r.emit(i[1]);else if(i[0]===I)try{r.emit(e(i[1]))}catch(a){r.down([[I,a]])}else i[0]===B&&r.down([[B]])});return()=>{o()}},Xt(n))}var St=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}};async function*pt(t,e){let n=e?.parse??(_=>_),r=e?.signal,o=new TextDecoder,s="",i="message",a=[],c,d,u=[],l=()=>{if(a.length===0&&i==="message"&&c===void 0){a=[];return}let _=a.join(`
|
|
2
|
+
`);u.push({event:i,data:n(_),id:c,retry:d}),i="message",a=[],c=void 0,d=void 0},p=_=>{if(_===""){l();return}if(_.startsWith(":"))return;let S=_.indexOf(":"),T=S<0?_:_.slice(0,S),w=S<0?"":_.slice(S+1);switch(w.startsWith(" ")&&(w=w.slice(1)),T){case"event":i=w;break;case"data":a.push(w);break;case"id":w.includes("\0")||(c=w);break;case"retry":{let k=Number(w);Number.isFinite(k)&&(d=k);break}}},f=(_,S)=>{s+=o.decode(_,{stream:!S});let T=s.split(/\r?\n/);s=T.pop()??"";for(let w of T)p(w)},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(()=>{}))},R=()=>{v()};if(r){if(r.aborted)return;r.addEventListener("abort",R,{once:!0})}try{if(h){for(g=h.getReader();!r?.aborted;){let{value:_,done:S}=await g.read();if(S)break;for(f(_,!1);u.length>0;)yield u.shift()}f(new Uint8Array,!0)}else{for(y=t[Symbol.asyncIterator]();!r?.aborted;){let S=await y.next();if(S.done)break;for(f(S.value,!1);u.length>0;)yield u.shift()}f(new Uint8Array,!0)}if(s.trim()){for(let _ of s.split(/\r?\n/))p(_);l()}for(;u.length>0;)yield u.shift()}finally{r&&r.removeEventListener("abort",R),v()}}async function Be(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}function Wn(t={}){return t.sdk?Fi(t):Gi(t)}function Zt(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}=Di(t,e?.systemPrompt),a={model:o,messages:i.map(Ii),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(Pi)),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 Di(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(`
|
|
3
3
|
|
|
4
|
-
`):void 0,chat:r}}function pi(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 fi(t){return{name:t.name,description:t.description,input_schema:t.parameters}}function zt(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 Fn(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 uo(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:Fn(t.usage),finishReason:t.stop_reason,latencyMs:e,model:t.model,provider:"anthropic"}}function mi(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 c=Ut(i,a,t.model,!1),d=B(),u=await o(`${n}/v1/messages`,{method:"POST",headers:s(),body:JSON.stringify(c),signal:a?.signal});if(!u.ok)throw await Pe(u,"Anthropic");let l=await u.json(),p=Math.max(0,(B()-d)/1e6);return uo(l,p)},async*stream(i,a){let c=Ut(i,a,t.model,!0),d=await o(`${n}/v1/messages`,{method:"POST",headers:{...s(),accept:"text/event-stream"},body:JSON.stringify(c),signal:a?.signal});if(!d.ok)throw await Pe(d,"Anthropic");if(!d.body)throw new Error("anthropicAdapter: streaming response has no body");let u,l,p=new Map;for await(let f of it(d.body,{signal:a?.signal})){let m=f.data;if(!m)continue;let y;try{y=JSON.parse(m)}catch{continue}switch(y.type){case"message_start":{u=zt(u,y.message.usage);break}case"content_block_start":{let g=y,h=g.content_block;h.type==="tool_use"&&(p.set(g.index,{id:String(h.id??""),name:String(h.name??""),argBuf:""}),yield{type:"tool-call-delta",delta:{id:String(h.id??""),name:String(h.name??"")}});break}case"content_block_delta":{let g=y,h=g.delta;if(h.type==="text_delta"&&typeof h.text=="string")yield{type:"token",delta:h.text};else if(h.type==="input_json_delta"&&typeof h.partial_json=="string"){let b=p.get(g.index);b&&(b.argBuf+=h.partial_json),yield{type:"tool-call-delta",delta:{argumentsDelta:h.partial_json}}}else h.type==="thinking_delta"&&typeof h.thinking=="string"&&(yield{type:"thinking",delta:h.thinking});break}case"message_delta":{let g=y;g.delta.stop_reason&&(l=g.delta.stop_reason),g.delta.usage&&(u=zt(u,g.delta.usage));break}case"message_stop":break}}u&&(yield{type:"usage",usage:Fn(u)}),yield{type:"finish",reason:l??"stop"}}}}function gi(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=Ut(n,r,t.model,!1),s=B(),i=await e.messages.create(o,{signal:r?.signal}),a=Math.max(0,(B()-s)/1e6);return uo(i,a)},async*stream(n,r){if(!e.messages.stream)throw new Error("sdkBackedAnthropic: SDK instance does not expose .messages.stream");let o=Ut(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=zt(s,a.message.usage);break;case"content_block_delta":{let c=a.delta;c?.type==="text_delta"&&typeof c.text=="string"?yield{type:"token",delta:c.text}:c?.type==="input_json_delta"&&typeof c.partial_json=="string"?yield{type:"tool-call-delta",delta:{argumentsDelta:c.partial_json}}:c?.type==="thinking_delta"&&typeof c.thinking=="string"&&(yield{type:"thinking",delta:c.thinking});break}case"message_delta":{let c=a;c.delta.stop_reason&&(i=c.delta.stop_reason),c.delta.usage&&(s=zt(s,c.delta.usage));break}}s&&(yield{type:"usage",usage:Fn(s)}),yield{type:"finish",reason:i??"stop"}}}}Ie();function Ht(){let t=new Error("aborted");return t.name="AbortError",t}function lo(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Ht()):new Promise((n,r)=>{let o=new se,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(Ht())},e.addEventListener("abort",s,{once:!0}))})}function We(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 c=[...a].reverse().find(d=>d.role==="user");return c?`echo: ${c.content}`:"dry-run: no user message"}),i=t.usage??((a,c)=>{let d=a.reduce((u,l)=>u+l.content.length,0);return{input:{regular:Math.ceil(d/4)},output:{regular:Math.ceil(c.length/4)}}});return{provider:e,model:n,async invoke(a,c){if(await lo(r,c?.signal),c?.signal?.aborted)throw Ht();let d=s(a,c),u=i(a,d);return{content:d,usage:u,finishReason:"stop",model:c?.model??n,provider:e,tier:c?.tier,metadata:{dryRun:!0}}},async*stream(a,c){let d=s(a,c),u=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(c?.signal?.aborted)throw Ht();await lo(p,c?.signal),yield{type:"token",delta:d.slice(f,f+o)}}yield{type:"usage",usage:u},yield{type:"finish",reason:"stop"}}}}pe();async function Wt(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+=po[r[s]];return o}var po=new Array(256);for(let t=0;t<256;t++)po[t]=t.toString(16).padStart(2,"0");function $n(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map($n);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=$n(e[o]);return r}function fo(t){return JSON.stringify($n(t),void 0,0)}var hi=new TextEncoder,yi=new TextDecoder("utf-8",{fatal:!0}),bi={name:"json",version:1,encode(t){return hi.encode(fo(t))},decode(t){return JSON.parse(yi.decode(t))}};function Ti(){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 vi(t,e={}){let n=e.codec??bi,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,u){if(!(e.filter&&!e.filter(d,u))&&(s.set(d,u),i+=1,o!==void 0&&i%o===0||!e.debounceMs))return c()},load(d){let u=t.read(d);if(u!==void 0)return u instanceof Uint8Array?u.length===0?void 0:n.decode(u):Promise.resolve(u).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 c()},async rollback(){s=new Map}};function c(){if(s.size===0)return;let d=s;s=new Map;let u=[];for(let[l,p]of d){let f=n.encode(p),m=t.write(l,f);m instanceof Promise&&u.push(m)}if(u.length>0)return Promise.all(u).then(()=>{})}return a}function jn(t){return vi(Ti(),t)}pe();var Bn=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 Vn(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 mo(t){let{storage:e,keyContext:n,keyPrefix:r,mode:o="read-write"}=t,s=n??(a=>a);async function i(a){let c=Vn(s(a)),d=await Wt(c);return r?`${r}:${d}`:d}return{keyFor:i,async lookup(a){if(o==="write")return;let c=await i(a),d=await e.load(c);if(d===void 0){if(o==="read-strict")throw new Bn(c,a);return}return d},async store(a,c){if(o==="read")return;let d=await i(a);await e.save(d,c)},async forget(a){if(o==="read"||o==="write"||!e.delete)return;let c=await i(a);await e.delete(c)}}}Q();function go(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),c;a!=null&&typeof a.then=="function"?c=Promise.resolve(a):a!=null&&typeof a=="object"&&"subscribe"in a&&"cache"in a?c=we(a):a!=null&&typeof a=="object"&&Symbol.asyncIterator in a?c=(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?c=(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?.()}})():c=Promise.resolve(a);let d,u=()=>{r.get(s)===d&&r.delete(s)};return d=c.then(l=>(u(),l),l=>{throw u(),l}),r.set(s,d),d}}Q();Ie();function ho(t){let{storage:e,mode:n="read-write",keyFn:r,keyPrefix:o="llm-replay"}=t,i=mo({storage:e,keyPrefix:o,mode:n==="read-strict"?"read":n,keyContext:({messages:c,opts:d})=>{let{signal:u,keyContext:l,...p}=d??{};return{messages:c,opts:p}}});async function a(c,d){if(r){if(r.length<=1){let l={messages:c,opts:d,context:d?.keyContext},p=await r(l);return`${o}:${p}`}let u=await r(c,d);return`${o}:${u}`}return i.keyFor({messages:c,opts:d})}return{keyFor:a,async lookup(c,d){if(n!=="write"){if(r){let u=await a(c,d),l=await e.load(u);return l===void 0?void 0:l}return i.lookup({messages:c,opts:d})}},async store(c,d,u){if(n!=="read"){if(r){let l=await a(c,d);await e.save(l,u);return}await i.store({messages:c,opts:d},u)}},async forget(c,d){if(!(n==="read"||n==="write")&&e.delete){if(r){let u=await a(c,d);await e.delete(u);return}await i.forget({messages:c,opts:d})}}}}pe();re();q();Q();function ge(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 qt(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(u=>{throw r(u),u}):d.then(n)}if(t!=null&&typeof t=="object"&&"content"in t)return n(t);let s=G(t);if(r){let d=!1;s.subscribe(u=>{for(let l of u){if(d)return;l[0]===C&&(d=!0,r(l[1]))}})}let i,a=!1,c=io(s,d=>{i=n(d),a=!0});return O([c],([d])=>d==null?null:a?i:n(d),{name:o??"adapt/invokeTap"})}function qe(t){let e=t.endNs??B();return{timestamp:e,wallClock:t.startWallClockNs??ce(),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 Ce(){return{input:{regular:0},output:{regular:0}}}var yo=Symbol.for("graphrefly.adapter.middlewareLayers");function me(t,e,n){let o=[...n?wi(n):[],e];return Object.defineProperty(t,yo,{value:Object.freeze(o),enumerable:!1,writable:!1,configurable:!1}),t}function wi(t){let e=t[yo];return Array.isArray(e)?e:[]}var Je=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 vt(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",c=ho({storage:e.storage,mode:n==="write-only"?"write":n,keyFn:e.keyFn,keyPrefix:i}),d=p=>p<=0?Promise.resolve():new Promise(f=>{new se().start(p,()=>f())}),u=go(async({messages:p,invokeOpts:f})=>await we(G(t.invoke(p,f))),{keyFn:({_precomputedKey:p})=>p}),l=ge(t,{async invoke(p,f){let m=await c.keyFor(p,f),y=await c.lookup(p,f);if(y?.response){let h=y.response;return{...h,metadata:{...h.metadata??{},replayCache:"hit"}}}if(n==="read-strict")throw new Je(m,"invoke");let g=await u({messages:p,invokeOpts:f,_precomputedKey:m});return a||await c.store(p,f,{response:g,storedAtNs:ce()}),g},async*stream(p,f){if(!r){for await(let k of t.stream(p,f))yield k;return}let m=await c.keyFor(p,f),y=await c.lookup(p,f);if(y){let k=y.response;if(y.streamChunks&&y.streamCadenceMs)for(let T=0;T<y.streamChunks.length;T++){let R=y.streamCadenceMs[T]??0,N=s>0?R/s:0;N>0&&await d(N),yield{type:"token",delta:y.streamChunks[T]?.delta??""}}else k.content&&(yield{type:"token",delta:k.content});k.usage&&(yield{type:"usage",usage:k.usage}),yield{type:"finish",reason:k.finishReason??"stop"};return}if(n==="read-strict")throw new Je(m,"stream");let g="",h,b,v=[],x=[],w;for await(let k of t.stream(p,f)){if(k.type==="token"&&(g+=k.delta,o)){let T=B(),R=w===void 0?0:(T-w)/1e6;x.push(R),w=T,v.push({delta:k.delta})}k.type==="usage"&&(h=k.usage),k.type==="finish"&&(b=k.reason),yield k}if((g||h)&&!a){let T={response:{content:g,usage:h??{input:{regular:0},output:{regular:0}},finishReason:b,model:t.model??f?.model??"",provider:t.provider},storedAtNs:ce(),...o?{streamChunks:v,streamCadenceMs:x}:{}};await c.store(p,f,T)}}});return me(l,"withReplayCache",t),l}var Kn=Vn;var ki=Je;function bo(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 To(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 xi(t,e){if("key"in t)return t.key;let n=Kn({messages:t.messages,opts:t.invokeOpts??{}}),r=await Wt(n);return`${e}:${r}`}function Ri(t){let e={response:t.response,storedAtNs:ce()};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 Si(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=jn(),o=t.fixtures,s=(async()=>{for(let i of o){let a=await xi(i,e);await r.save(a,Ri(i))}})();return s.catch(()=>{}),{tier:r,seedReady:s}}return t.fixturesStorage?{tier:t.fixturesStorage,seedReady:Promise.resolve()}:{tier:void 0,seedReady:Promise.resolve()}}function Un(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"?We({provider:e,model:n,respond:()=>"[unreachable: read-strict mode throws on miss]"}):{provider:e,model:n,async invoke(u,l){let p=t.respond?t.respond(u,l):bo(e,n);return To(p,e,n)},async*stream(u,l){let p=t.respond?t.respond(u,l):bo(e,n),f=To(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 u=Si(t,o);i=u.tier??jn(),a=u.seedReady}let c=t.record?"read-write":r==="throw"?"read-strict":"read",d=vt(s,{storage:i,mode:c,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(u,l){return await a,d.invoke(u,l)},async*stream(u,l){await a;for await(let p of d.stream(u,l))yield p}}}pe();function zn(t={}){return t.sdk?Ei(t):Mi(t)}function Jt(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 c of i.toolCalls)a.push({functionCall:{name:c.name,args:c.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(`
|
|
4
|
+
`):void 0,chat:r}}function Ii(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 Pi(t){return{name:t.name,description:t.description,input_schema:t.parameters}}function en(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 Jn(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 No(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:Jn(t.usage),finishReason:t.stop_reason,latencyMs:e,model:t.model,provider:"anthropic"}}function Gi(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 c=Zt(i,a,t.model,!1),d=K(),u=await o(`${n}/v1/messages`,{method:"POST",headers:s(),body:JSON.stringify(c),signal:a?.signal});if(!u.ok)throw await Be(u,"Anthropic");let l=await u.json(),p=Math.max(0,(K()-d)/1e6);return No(l,p)},async*stream(i,a){let c=Zt(i,a,t.model,!0),d=await o(`${n}/v1/messages`,{method:"POST",headers:{...s(),accept:"text/event-stream"},body:JSON.stringify(c),signal:a?.signal});if(!d.ok)throw await Be(d,"Anthropic");if(!d.body)throw new Error("anthropicAdapter: streaming response has no body");let u,l,p=new Map;for await(let f of pt(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":{u=en(u,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&&(u=en(u,g.delta.usage));break}case"message_stop":break}}u&&(yield{type:"usage",usage:Jn(u)}),yield{type:"finish",reason:l??"stop"}}}}function Fi(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=Zt(n,r,t.model,!1),s=K(),i=await e.messages.create(o,{signal:r?.signal}),a=Math.max(0,(K()-s)/1e6);return No(i,a)},async*stream(n,r){if(!e.messages.stream)throw new Error("sdkBackedAnthropic: SDK instance does not expose .messages.stream");let o=Zt(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=en(s,a.message.usage);break;case"content_block_delta":{let c=a.delta;c?.type==="text_delta"&&typeof c.text=="string"?yield{type:"token",delta:c.text}:c?.type==="input_json_delta"&&typeof c.partial_json=="string"?yield{type:"tool-call-delta",delta:{argumentsDelta:c.partial_json}}:c?.type==="thinking_delta"&&typeof c.thinking=="string"&&(yield{type:"thinking",delta:c.thinking});break}case"message_delta":{let c=a;c.delta.stop_reason&&(i=c.delta.stop_reason),c.delta.usage&&(s=en(s,c.delta.usage));break}}s&&(yield{type:"usage",usage:Jn(s)}),yield{type:"finish",reason:i??"stop"}}}}je();function tn(){let t=new Error("aborted");return t.name="AbortError",t}function Mo(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(tn()):new Promise((n,r)=>{let o=new ce,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(tn())},e.addEventListener("abort",s,{once:!0}))})}function Ze(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 c=[...a].reverse().find(d=>d.role==="user");return c?`echo: ${c.content}`:"dry-run: no user message"}),i=t.usage??((a,c)=>{let d=a.reduce((u,l)=>u+l.content.length,0);return{input:{regular:Math.ceil(d/4)},output:{regular:Math.ceil(c.length/4)}}});return{provider:e,model:n,async invoke(a,c){if(await Mo(r,c?.signal),c?.signal?.aborted)throw tn();let d=s(a,c),u=i(a,d);return{content:d,usage:u,finishReason:"stop",model:c?.model??n,provider:e,tier:c?.tier,metadata:{dryRun:!0}}},async*stream(a,c){let d=s(a,c),u=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(c?.signal?.aborted)throw tn();await Mo(p,c?.signal),yield{type:"token",delta:d.slice(f,f+o)}}yield{type:"usage",usage:u},yield{type:"finish",reason:"stop"}}}}ge();async function nn(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+=Eo[r[s]];return o}var Eo=new Array(256);for(let t=0;t<256;t++)Eo[t]=t.toString(16).padStart(2,"0");function Yn(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(Yn);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=Yn(e[o]);return r}function Oo(t){return JSON.stringify(Yn(t),void 0,0)}var $i=new TextEncoder,ji=new TextDecoder("utf-8",{fatal:!0}),Bi={name:"json",version:1,encode(t){return $i.encode(Oo(t))},decode(t){return JSON.parse(ji.decode(t))}};function Vi(){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 Ki(t,e={}){let n=e.codec??Bi,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,u){if(!(e.filter&&!e.filter(d,u))&&(s.set(d,u),i+=1,o!==void 0&&i%o===0||!e.debounceMs))return c()},load(d){let u=t.read(d);if(u!==void 0)return u instanceof Uint8Array?u.length===0?void 0:n.decode(u):Promise.resolve(u).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 c()},async rollback(){s=new Map}};function c(){if(s.size===0)return;let d=s;s=new Map;let u=[];for(let[l,p]of d){let f=n.encode(p),m=t.write(l,f);m instanceof Promise&&u.push(m)}if(u.length>0)return Promise.all(u).then(()=>{})}return a}function Qn(t){return Ki(Vi(),t)}ge();var Xn=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 Zn(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 Ao(t){let{storage:e,keyContext:n,keyPrefix:r,mode:o="read-write"}=t,s=n??(a=>a);async function i(a){let c=Zn(s(a)),d=await nn(c);return r?`${r}:${d}`:d}return{keyFor:i,async lookup(a){if(o==="write")return;let c=await i(a),d=await e.load(c);if(d===void 0){if(o==="read-strict")throw new Xn(c,a);return}return d},async store(a,c){if(o==="read")return;let d=await i(a);await e.save(d,c)},async forget(a){if(o==="read"||o==="write"||!e.delete)return;let c=await i(a);await e.delete(c)}}}ee();function Co(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),c;a!=null&&typeof a.then=="function"?c=Promise.resolve(a):a!=null&&typeof a=="object"&&"subscribe"in a&&"cache"in a?c=Re(a):a!=null&&typeof a=="object"&&Symbol.asyncIterator in a?c=(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?c=(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?.()}})():c=Promise.resolve(a);let d,u=()=>{r.get(s)===d&&r.delete(s)};return d=c.then(l=>(u(),l),l=>{throw u(),l}),r.set(s,d),d}}ee();je();function Lo(t){let{storage:e,mode:n="read-write",keyFn:r,keyPrefix:o="llm-replay"}=t,i=Ao({storage:e,keyPrefix:o,mode:n==="read-strict"?"read":n,keyContext:({messages:c,opts:d})=>{let{signal:u,keyContext:l,...p}=d??{};return{messages:c,opts:p}}});async function a(c,d){if(r){if(r.length<=1){let l={messages:c,opts:d,context:d?.keyContext},p=await r(l);return`${o}:${p}`}let u=await r(c,d);return`${o}:${u}`}return i.keyFor({messages:c,opts:d})}return{keyFor:a,async lookup(c,d){if(n!=="write"){if(r){let u=await a(c,d),l=await e.load(u);return l===void 0?void 0:l}return i.lookup({messages:c,opts:d})}},async store(c,d,u){if(n!=="read"){if(r){let l=await a(c,d);await e.save(l,u);return}await i.store({messages:c,opts:d},u)}},async forget(c,d){if(!(n==="read"||n==="write")&&e.delete){if(r){let u=await a(c,d);await e.delete(u);return}await i.forget({messages:c,opts:d})}}}}ge();se();W();ee();function be(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 rn(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(u=>{throw r(u),u}):d.then(n)}if(t!=null&&typeof t=="object"&&"content"in t)return n(t);let s=F(t);if(r){let d=!1;s.subscribe(u=>{for(let l of u){if(d)return;l[0]===I&&(d=!0,r(l[1]))}})}let i,a=!1,c=Ro(s,d=>{i=n(d),a=!0});return C([c],([d])=>d==null?null:a?i:n(d),{name:o??"adapt/invokeTap"})}function et(t){let e=t.endNs??K();return{timestamp:e,wallClock:t.startWallClockNs??ie(),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 Pe(){return{input:{regular:0},output:{regular:0}}}var Do=Symbol.for("graphrefly.adapter.middlewareLayers");function ye(t,e,n){let o=[...n?zi(n):[],e];return Object.defineProperty(t,Do,{value:Object.freeze(o),enumerable:!1,writable:!1,configurable:!1}),t}function zi(t){let e=t[Do];return Array.isArray(e)?e:[]}var tt=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 _t(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",c=Lo({storage:e.storage,mode:n==="write-only"?"write":n,keyFn:e.keyFn,keyPrefix:i}),d=p=>p<=0?Promise.resolve():new Promise(f=>{new ce().start(p,()=>f())}),u=Co(async({messages:p,invokeOpts:f})=>await Re(F(t.invoke(p,f))),{keyFn:({_precomputedKey:p})=>p}),l=be(t,{async invoke(p,f){let m=await c.keyFor(p,f),h=await c.lookup(p,f);if(h?.response){let y=h.response;return{...y,metadata:{...y.metadata??{},replayCache:"hit"}}}if(n==="read-strict")throw new tt(m,"invoke");let g=await u({messages:p,invokeOpts:f,_precomputedKey:m});return a||await c.store(p,f,{response:g,storedAtNs:ie()}),g},async*stream(p,f){if(!r){for await(let S of t.stream(p,f))yield S;return}let m=await c.keyFor(p,f),h=await c.lookup(p,f);if(h){let S=h.response;if(h.streamChunks&&h.streamCadenceMs)for(let T=0;T<h.streamChunks.length;T++){let w=h.streamCadenceMs[T]??0,k=s>0?w/s:0;k>0&&await d(k),yield{type:"token",delta:h.streamChunks[T]?.delta??""}}else S.content&&(yield{type:"token",delta:S.content});S.usage&&(yield{type:"usage",usage:S.usage}),yield{type:"finish",reason:S.finishReason??"stop"};return}if(n==="read-strict")throw new tt(m,"stream");let g="",y,b,v=[],R=[],_;for await(let S of t.stream(p,f)){if(S.type==="token"&&(g+=S.delta,o)){let T=K(),w=_===void 0?0:(T-_)/1e6;R.push(w),_=T,v.push({delta:S.delta})}S.type==="usage"&&(y=S.usage),S.type==="finish"&&(b=S.reason),yield S}if((g||y)&&!a){let T={response:{content:g,usage:y??{input:{regular:0},output:{regular:0}},finishReason:b,model:t.model??f?.model??"",provider:t.provider},storedAtNs:ie(),...o?{streamChunks:v,streamCadenceMs:R}:{}};await c.store(p,f,T)}}});return ye(l,"withReplayCache",t),l}var er=Zn;var Ui=tt;function Io(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 Po(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 Hi(t,e){if("key"in t)return t.key;let n=er({messages:t.messages,opts:t.invokeOpts??{}}),r=await nn(n);return`${e}:${r}`}function qi(t){let e={response:t.response,storedAtNs:ie()};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 Wi(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=Qn(),o=t.fixtures,s=(async()=>{for(let i of o){let a=await Hi(i,e);await r.save(a,qi(i))}})();return s.catch(()=>{}),{tier:r,seedReady:s}}return t.fixturesStorage?{tier:t.fixturesStorage,seedReady:Promise.resolve()}:{tier:void 0,seedReady:Promise.resolve()}}function tr(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"?Ze({provider:e,model:n,respond:()=>"[unreachable: read-strict mode throws on miss]"}):{provider:e,model:n,async invoke(u,l){let p=t.respond?t.respond(u,l):Io(e,n);return Po(p,e,n)},async*stream(u,l){let p=t.respond?t.respond(u,l):Io(e,n),f=Po(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 u=Wi(t,o);i=u.tier??Qn(),a=u.seedReady}let c=t.record?"read-write":r==="throw"?"read-strict":"read",d=_t(s,{storage:i,mode:c,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(u,l){return await a,d.invoke(u,l)},async*stream(u,l){await a;for await(let p of d.stream(u,l))yield p}}}ge();function nr(t={}){return t.sdk?Xi(t):Qi(t)}function on(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 c of i.toolCalls)a.push({functionCall:{name:c.name,args:c.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(`
|
|
5
5
|
|
|
6
|
-
`)}]});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(_i)}]),e?.providerExtras&&Object.assign(o,e.providerExtras),o}function _i(t){return{name:t.name,description:t.description,parameters:t.parameters}}function vo(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 Hn(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 wo(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:Hn(t.usageMetadata),finishReason:n?.finishReason,latencyMs:e,model:t.modelVersion,provider:"google"}}function Ni(t){if(t.apiKey)return t.apiKey;let e=globalThis.process?.env;return e?.GOOGLE_API_KEY??e?.GEMINI_API_KEY}function Mi(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=Ni(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),c=Jt(s,i),d=B(),u=`${e}/models/${encodeURIComponent(a)}:generateContent?${o()}`,l=await n(u,{method:"POST",headers:{"content-type":"application/json",...t.headers??{}},body:JSON.stringify(c),signal:i?.signal});if(!l.ok)throw await Pe(l,"Google");let p=await l.json(),f=Math.max(0,(B()-d)/1e6);return wo(p,f)},async*stream(s,i){let a=r(i),c=Jt(s,i),d=`${e}/models/${encodeURIComponent(a)}:streamGenerateContent?alt=sse&${o()}`,u=await n(d,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",...t.headers??{}},body:JSON.stringify(c),signal:i?.signal});if(!u.ok)throw await Pe(u,"Google");if(!u.body)throw new Error("googleAdapter: streaming response has no body");let l,p;for await(let f of it(u.body,{signal:i?.signal})){if(!f.data)continue;let m;try{m=JSON.parse(f.data)}catch{continue}let y=m.candidates?.[0];for(let g of y?.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??{})}});y?.finishReason&&(p=y.finishReason),m.usageMetadata&&(l=m.usageMetadata)}l&&(yield{type:"usage",usage:Hn(l)}),yield{type:"finish",reason:p??"stop"}}}}function Ei(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=Jt(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=vo(o,s,r?.signal),a=B(),c=await e.models.generateContent(i),d=Math.max(0,(B()-a)/1e6);return wo(c,d)},async*stream(n,r){if(!e.models.generateContentStream)throw new Error("sdkBackedGoogle: SDK instance does not expose generateContentStream");let o=Jt(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=vo(o,s,r?.signal),a,c,d=await e.models.generateContentStream(i);for await(let u of d){let l=u.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&&(c=l.finishReason),u.usageMetadata&&(a=u.usageMetadata)}a&&(yield{type:"usage",usage:Hn(a)}),yield{type:"finish",reason:c??"stop"}}}}pe();var Oi={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 Wn(t={}){return t.sdk?Ii(t):Di(t)}function Yt(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(Ai);e?.systemPrompt&&!t.some(c=>c.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(Ci)),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 Ai(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 Ci(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}}function qn(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 ko(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:Li(a.function.arguments)}));return{content:s,toolCalls:i.length>0?i:void 0,usage:qn(t.usage),finishReason:r?.finish_reason,latencyMs:e,model:t.model,provider:n}}function Li(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!=null?e:{_raw:t}}catch{return{_raw:t}}}function xo(t){let e=t.preset??"openai",n=Oi[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 Di(t){let{provider:e,baseURL:n,apiKey:r}=xo(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,c){let d=Yt(a,c,t.model,!1,t.bodyExtras),u=B(),l=await o(`${n}/chat/completions`,{method:"POST",headers:i(),body:JSON.stringify(d),signal:c?.signal});if(!l.ok)throw await Pe(l,e);let p=await l.json(),f=Math.max(0,(B()-u)/1e6);return ko(p,f,e)},async*stream(a,c){let d=Yt(a,c,t.model,!0,t.bodyExtras),u=await o(`${n}/chat/completions`,{method:"POST",headers:{...i(),accept:"text/event-stream"},body:JSON.stringify(d),signal:c?.signal});if(!u.ok)throw await Pe(u,e);if(!u.body)throw new Error(`openAICompatAdapter[${e}]: streaming response has no body`);let l,p;for await(let f of it(u.body,{signal:c?.signal})){if(!f.data||f.data==="[DONE]")continue;let m;try{m=JSON.parse(f.data)}catch{continue}let y=m.choices;if(y){let g=y[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 h of g.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:h.id,name:h.function?.name,argumentsDelta:h.function?.arguments}};g?.finish_reason&&(p=g.finish_reason)}m.usage&&(l=m.usage,yield{type:"usage",usage:qn(l)})}yield{type:"finish",reason:p??"stop"}}}}function Ii(t){let e=t.sdk;if(!e)throw new Error("sdkBackedOpenAI: sdk instance required");let{provider:n}=xo(t);return{provider:n,model:t.model,async invoke(r,o){let s=Yt(r,o,t.model,!1,t.bodyExtras),i=B(),a=await e.chat.completions.create(s,{signal:o?.signal}),c=Math.max(0,(B()-i)/1e6);return ko(a,c,n)},async*stream(r,o){let s=Yt(r,o,t.model,!0,t.bodyExtras),i=await e.chat.completions.create(s,{signal:o?.signal}),a,c;for await(let d of i){let u=d.choices;if(u){let p=u[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&&(c=p.finish_reason)}let l=d.usage;l&&(a=l,yield{type:"usage",usage:qn(l)})}yield{type:"finish",reason:c??"stop"}}}}function Pi(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 Gn(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 zn(e)}case"dry-run":{let e={model:t.model,...t.extras};return We(e)}case"fallback":{let e={provider:t.provider,model:t.model,...t.extras};return Un(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 Wn(e)}default:{let e=t.provider;throw new Error(`createAdapter: unknown provider: ${String(e)}`)}}}pe();q();xe();re();Re();q();var Jn=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 wt(t){return t.subscribe(()=>{})}var Gi=64;function Le(t,e={}){let{name:n,maxSize:r,versioning:o,guard:s,backend:i}=e,a=i??new Jn(t,r),c=I(a.toArray(),{name:n,describeKind:"state",equals:(T,R)=>T===R,...o!=null?{versioning:o}:{},...s!=null?{guard:s}:{}});function d(){let T=a.toArray();ee(()=>{c.down([[J]],{internal:!0}),c.down([[D,T]],{internal:!0})})}let u=new Map,l=new Map,p=new Map;function f(T,R){return`${T}:${R===void 0?"END":R}`}function m(T){if(T.size<Gi)return;let R=T.keys().next();if(R.done)return;let N=T.get(R.value);N!==void 0&&N.dispose(),T.delete(R.value)}function y(T){let R=a.version;try{return T()}finally{a.version!==R&&d()}}function g(T){if(!Number.isInteger(T)||T<0)throw new RangeError(`tail: n must be a non-negative integer (got ${T})`);let R=u.get(T);if(R!==void 0)return u.delete(T),u.set(T,R),R.node;m(u);let N=O([c],([S])=>{let E=S;return T===0||E.length===0?[]:E.slice(Math.max(0,E.length-T))},{initial:a.tail(T),describeKind:"derived"}),_=wt(N);return u.set(T,{node:N,dispose:_}),N}function h(T,R){if(!Number.isInteger(T)||T<0)throw new RangeError(`slice: start must be a non-negative integer (got ${T})`);if(R!==void 0&&(!Number.isInteger(R)||R<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${R})`);let N=f(T,R),_=l.get(N);if(_!==void 0)return l.delete(N),l.set(N,_),_.node;m(l);let S=O([c],([M])=>{let A=M;return R===void 0?A.slice(T):A.slice(T,R)},{initial:a.slice(T,R),describeKind:"derived"}),E=wt(S);return l.set(N,{node:S,dispose:E}),S}function b(T){let R=p.get(T);if(R!==void 0)return R.node;let N=O([c,T],([S,E])=>{let M=S,A=Math.max(0,Math.trunc(E??0));return M.slice(A)},{initial:[],describeKind:"derived"}),_=wt(N);return p.set(T,{node:N,dispose:_}),N}let v,x;function w(){v===void 0&&(v=te([c],(T,R,N)=>{let _=T[0],E=_!=null&&_.length>0?_.at(-1):N.prevData[0];if(E==null||E.length===0){R.down([[V]]);return}R.emit(E[E.length-1])},{name:n!=null?`${n}::lastValue`:"lastValue",describeKind:"derived",initial:a.size===0?void 0:a.at(a.size-1)}),x=O([c],([T])=>T.length>0,{name:n!=null?`${n}::hasLatest`:"hasLatest",describeKind:"derived",initial:a.size>0}),wt(v),wt(x))}let k={entries:c,get size(){return a.size},at(T){return a.at(T)},append(T){y(()=>a.append(T))},appendMany(T){T.length!==0&&y(()=>a.appendMany(T))},clear(){y(()=>a.clear())},trimHead(T){y(()=>a.trimHead(T))},withLatest(){return w(),c},get lastValue(){return w(),v},get hasLatest(){return w(),x},view(T){switch(T.kind){case"tail":return g(T.n);case"slice":return h(T.start,T.stop);case"fromCursor":return b(T.cursor)}},attach(T){let R=T.subscribe(N=>{for(let _ of N)_[0]===D&&k.append(_[1])});return()=>R()},attachStorage(T){if(T.length===0)return()=>{};let R=new Map;for(let _ of T)R.set(_,a.size);(async()=>{for(let _ of T)if(typeof _.loadEntries=="function")try{let S=await Promise.resolve(_.loadEntries());S.entries.length>0&&a.size===0&&(a.restore(S.entries),R.set(_,S.entries.length),d());break}catch{}})();let N=c.subscribe(_=>{for(let S of _){if(S[0]!==D)continue;let E=S[1];for(let M of T){let A=R.get(M)??0;if(E.length<A){try{let K=M.appendEntries(E);K instanceof Promise&&K.catch(()=>{})}catch{}R.set(M,E.length);continue}if(E.length===A)continue;let j=E.slice(A);R.set(M,E.length);try{let K=M.appendEntries(j);K instanceof Promise&&K.catch(()=>{})}catch{}}}});return()=>N()},disposeAllViews(){for(let T of u.values())T.dispose();u.clear();for(let T of l.values())T.dispose();l.clear();for(let T of p.values())T.dispose();p.clear()},dispose(){for(let T of u.values())T.dispose();u.clear();for(let T of l.values())T.dispose();l.clear();for(let T of p.values())T.dispose();p.clear()}};return k}Q();function Ee(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 Ge(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 Ro(){return{input:{regular:0},output:{regular:0}}}function Fi(t,e){let n=e?.logMax??1e3,r=Le(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:n}),o=I(null,{name:"adapterStats/lastCall"}),s=O([r.entries],([y])=>y.length,{name:"adapterStats/totalCalls",initial:0}),i=O([r.entries],([y])=>y.reduce((g,h)=>g+Ee(h.usage),0),{name:"adapterStats/totalInputTokens",initial:0}),a=O([r.entries],([y])=>y.reduce((g,h)=>g+Ge(h.usage),0),{name:"adapterStats/totalOutputTokens",initial:0}),c=[Y(s),Y(i),Y(a)],d=y=>{r.append(y),o.emit(y)},u=()=>{r.clear(),o.emit(null)},l=ge(t,{invoke(y,g){let h=B(),b=ce(),v=t.model??g?.model??"",x=k=>(d(qe({provider:t.provider,model:t.model??g?.model??k.model??"",tier:g?.tier??k.tier,usage:k.usage??Ce(),startNs:h,startWallClockNs:b,method:"invoke"})),k),w=k=>{let T=k;d(qe({provider:t.provider,model:v,tier:g?.tier,usage:Ce(),startNs:h,startWallClockNs:b,method:"invoke",error:{type:T?.name??"Error",message:T?.message??String(k)}}))};return qt(t.invoke(y,g),{onResp:x,onError:w,name:"adapterStats/invokeTap"})},async*stream(y,g){let h=B(),b=ce(),v=t.model??g?.model??"",x;try{for await(let w of t.stream(y,g))w.type==="usage"&&(x=w.usage),yield w;d(qe({provider:t.provider,model:v,tier:g?.tier,usage:x??Ce(),startNs:h,startWallClockNs:b,method:"stream"}))}catch(w){let k=w;throw d(qe({provider:t.provider,model:v,tier:g?.tier,usage:x??Ce(),startNs:h,startWallClockNs:b,method:"stream",error:{type:k?.name??"Error",message:k?.message??String(w)}})),w}}});me(l,"observableAdapter",t);let p=!1;return{adapter:l,stats:{lastCall:o,allCalls:r,totalCalls:s,totalInputTokens:i,totalOutputTokens:a,reset:u,dispose:()=>{if(!p){p=!0;for(let y of c)y();c.length=0}}}}}function $i(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function Xt(t="USD"){return{total:0,currency:t}}function Yn(t,e,n){let r=Ee(t),o=e.currency??"USD",s=n?.withBreakdown===!0,i=s?{}:null,a=0,c=(g,h,b)=>{if(!h||b==null)return;let v=$i(b,r),x=h*v/1e6;a+=x,s&&(i[g]=(i[g]??0)+x)},d=t.input,u=e.input;if(u&&(c("input.regular",d.regular,u.regular),c("input.cacheRead",d.cacheRead??0,u.cacheRead),c("input.cacheWrite5m",d.cacheWrite5m??0,u.cacheWrite5m),c("input.cacheWrite1h",d.cacheWrite1h??0,u.cacheWrite1h),c("input.cacheWriteOther",d.cacheWriteOther??0,u.cacheWriteOther),c("input.audio",d.audio??0,u.audio),c("input.image",d.image??0,u.image),c("input.video",d.video??0,u.video),c("input.toolUse",d.toolUse??0,u.toolUse),d.extensions&&u.extensions))for(let[g,h]of Object.entries(d.extensions))c(`input.ext.${g}`,h,u.extensions[g]);let l=t.output,p=e.output;if(p&&(c("output.regular",l.regular,p.regular),c("output.reasoning",l.reasoning??0,p.reasoning),c("output.audio",l.audio??0,p.audio),c("output.predictionAccepted",l.predictionAccepted??0,p.predictionAccepted),c("output.predictionRejected",l.predictionRejected??0,p.predictionRejected),l.extensions&&p.extensions))for(let[g,h]of Object.entries(l.extensions))c(`output.ext.${g}`,h,p.extensions[g]);let f=n?.tier;if(f&&e.tierMultipliers){let g=e.tierMultipliers[f];if(g!=null&&(a*=g,s))for(let h of Object.keys(i))i[h]*=g}let m=t.auxiliary,y=e.auxiliary;if(m&&y)for(let[g,h]of Object.entries(m)){let b=y[g];if(b==null||!h)continue;let v=h*b;a+=v,s&&(i[`auxiliary.${g}`]=v)}return s?{total:a,currency:o,breakdown:i}:{total:a,currency:o}}function Qt(t,e){return`${t}::${e}`}function ji(t){let e=new Map,n=new Map,r=(o,s,i)=>{e.set(Qt(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(Qt(o,s));if(i)return i.pricing;let a=n.get(o);if(!a)return;let c;for(let d of a)if(s.startsWith(d)&&(!c||d.length>c.key.length)){let u=e.get(Qt(o,d));u&&(c={key:d,pricing:u.pricing})}return c?.pricing},remove(o,s){let i=e.delete(Qt(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 Bi(t,e="USD"){return(n,r)=>{let o=t.lookup(r.provider,r.model);return o?Yn(n,o,{tier:r.tier,withBreakdown:r.withBreakdown}):Xt(e)}}function Vi(...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):Xt()}}function Ki(t,e,n){return t?.pricing?Yn(e,t.pricing,n):Xt()}st();Q();function Qn(t,e={}){let n=e.breaker??ht(e),r=ge(t,{async invoke(o,s){if(!n.canExecute())throw new Fe;try{let i=await we(G(t.invoke(o,s)));return n.recordSuccess(),i}catch(i){throw n.recordFailure(i),i}},async*stream(o,s){if(!n.canExecute())throw new Fe;try{for await(let i of t.stream(o,s))yield i;n.recordSuccess()}catch(i){throw n.recordFailure(i),i}}});return me(r,"withBreaker",t),{adapter:r,breaker:n}}pe();re();q();Q();var Zt=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"},Xn=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),So=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function Zn(t,e){let n=Le(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),r=I(So(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),o=O([r],([d])=>{let u=d;return!(e.caps.calls!=null&&u.calls>=e.caps.calls||e.caps.inputTokens!=null&&u.inputTokens>=e.caps.inputTokens||e.caps.outputTokens!=null&&u.outputTokens>=e.caps.outputTokens||e.caps.usd!=null&&u.usd>=e.caps.usd)},{name:e.name?`${e.name}/isOpen`:"budgetGate/isOpen",initial:!0});if(Y(o),e.onExhausted!=null){let d=e.onExhausted,u=!1,l=!0;o.subscribe(p=>{for(let f of p)if(f[0]===D){let m=f[1];if(u&&l&&m===!1){let y=_o(r.cache??Xn,e.caps);y&&d(y)}l=m,u=!0}})}let s=()=>{if(o.cache===!1){let d=r.cache??Xn,u=_o(d,e.caps);return new Zt(u??"budget",e.caps[u??"calls"]??0,Ui(d,u??"calls"))}},i=(d,u)=>{let l=t.provider,p=qe({provider:l,model:u.model,tier:u.tier,usage:d,startNs:u.startNs,method:u.method,...u.error?{error:u.error}:{}});n.append(p);let f=r.cache??Xn,m=e.pricingFn?f.usd+e.pricingFn(d,{model:u.model,provider:l,tier:u.tier}).total:f.usd;r.emit({calls:f.calls+1,inputTokens:f.inputTokens+Ee(d),outputTokens:f.outputTokens+Ge(d),usd:m})},a=()=>{n.clear(),r.emit(So())},c=ge(t,{invoke(d,u){let l=s();if(l)return Promise.reject(l);let p=B(),f=t.model??u?.model??"",m=g=>(i(g.usage??Ce(),{model:t.model??u?.model??g.model??"",tier:u?.tier??g.tier,startNs:p,method:"invoke"}),g),y=g=>{let h=g;i(Ce(),{model:f,tier:u?.tier,startNs:p,method:"invoke",error:{type:h?.name??"Error",message:h?.message??String(g)}})};return qt(t.invoke(d,u),{onResp:m,onError:y,name:"budgetGate/invokeTap"})},async*stream(d,u){let l=s();if(l)throw l;let p=B(),f;try{for await(let m of t.stream(d,u))m.type==="usage"&&(f=m.usage),yield m;i(f??Ce(),{model:t.model??u?.model??"",tier:u?.tier,startNs:p,method:"stream"})}catch(m){let y=m;throw i(f??Ce(),{model:t.model??u?.model??"",tier:u?.tier,startNs:p,method:"stream",error:{type:y?.name??"Error",message:y?.message??String(m)}}),m}}});return me(c,"withBudgetGate",t),{adapter:c,budget:{totals:r,isOpen:o,log:n,reset:a}}}function _o(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 Ui(t,e){switch(e){case"calls":return t.calls;case"inputTokens":return t.inputTokens;case"outputTokens":return t.outputTokens;case"usd":return t.usd}}Q();function zi(t,e){let n=e.mock??We({provider:t.provider,model:t.model}),r=typeof e.enabled=="boolean"?e.enabled:void 0,o=r===void 0?G(e.enabled):void 0,s;o&&(s=Y(o));let i=()=>r!==void 0?r:!!o?.cache,a=ge(t,{invoke(d,u){return i()?n.invoke(d,u):t.invoke(d,u)},stream(d,u){return i()?n.stream(d,u):t.stream(d,u)}});return me(a,"withDryRun",t),{adapter:a,dispose:()=>{s&&(s(),s=void 0)}}}function er(t){if(t==null||typeof t!="object")return;let e=t,n=e.status,r=Hi(e.headers);if(n!==429&&n!==503&&!Xi(e.message))return;let o={},s=r("retry-after"),i=qi(s);i!=null&&(o.retryAfterMs=i);let a=r("anthropic-ratelimit-requests-reset");if(a){let f=No(a);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let c=r("anthropic-ratelimit-tokens-reset");if(c){let f=No(c);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let d=en(r,"x-ratelimit-limit-requests");d!=null&&(o.rpmCap=d);let u=en(r,"x-ratelimit-limit-tokens");u!=null&&(o.tpmCap=u);let l=en(r,"x-ratelimit-remaining-requests"),p=en(r,"x-ratelimit-remaining-tokens");if(l!=null&&d!=null&&d>0&&(o.usageHint??={},o.usageHint.rpm=1-l/d),p!=null&&u!=null&&u>0&&(o.usageHint??={},o.usageHint.tpm=1-p/u),o.retryAfterMs==null&&e.message){let f=Yi(e.message);f!=null&&(o.retryAfterMs=f)}return e.headers&&(o.metadata={headers:Wi(e.headers)}),o.retryAfterMs==null&&o.rpmCap==null&&o.tpmCap==null&&o.usageHint==null?o.metadata?o:void 0:o}function Hi(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 Wi(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 en(t,e){let n=t(e);if(n==null)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function qi(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 No(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var Ji=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function Yi(t){let e=Ji.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 Qi=/rate\s*limit|too\s*many\s*requests|quota|429/i;function Xi(t){return!!t&&Qi.test(t)}pe();re();q();st();Q();Ie();function tr(t){let e=new Error(t);return e.name="AbortError",e}function Eo(t={}){let e=Math.max(1,t.burstMultiplier??1),n=t.clampCooldownMs??6e4,r=t.rpm!=null?G(t.rpm):I(Number.POSITIVE_INFINITY),o=t.tpm!=null?G(t.tpm):I(Number.POSITIVE_INFINITY),s=I(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),i=I(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),a=I({},{name:"adaptiveRateLimiter/lastSignal"}),c=O([r,s],([M,A])=>Math.min(Number(M??1/0),Number(A??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),d=O([o,i],([M,A])=>Math.min(Number(M??1/0),Number(A??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),u=at(Number(r.cache??Number.POSITIVE_INFINITY),e),l=at(Number(o.cache??Number.POSITIVE_INFINITY),e),p=!1,f=!1,m=c.subscribe(M=>{for(let A of M)if(A[0]===D){let j=Number(A[1]);Number.isFinite(j)&&j>0?(u=at(j,e),p=!1):j===1/0?(u=at(1/0,e),p=!1):j<=0&&(p=!0)}}),y=d.subscribe(M=>{for(let A of M)if(A[0]===D){let j=Number(A[1]);Number.isFinite(j)&&j>0?(l=at(j,e),f=!1):j===1/0?(l=at(1/0,e),f=!1):j<=0&&(f=!0)}}),g=0,h=new se,b=new se,v;t.adaptation!=null&&(v=G(t.adaptation).subscribe(A=>{for(let j of A)j[0]===D&&x(j[1])}));function x(M){if(a.emit(M),M.rpmCap!=null&&Number.isFinite(M.rpmCap)&&M.rpmCap>=0&&(s.emit(M.rpmCap),Number.isFinite(n)&&n>0&&h.start(n,()=>s.emit(Number.POSITIVE_INFINITY))),M.tpmCap!=null&&Number.isFinite(M.tpmCap)&&M.tpmCap>=0&&(i.emit(M.tpmCap),Number.isFinite(n)&&n>0&&b.start(n,()=>i.emit(Number.POSITIVE_INFINITY))),M.retryAfterMs!=null&&M.retryAfterMs>0){let A=B()+M.retryAfterMs*1e6;A>g&&(g=A)}}let w=I(0,{name:"adaptiveRateLimiter/pending"}),k=I(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),T=I(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),R=M=>{w.emit((w.cache??0)+M)},N=()=>{k.emit(u.available()),T.emit(l.available())};async function _(M={}){let A=M.requestCost??1,j=M.tokenCost??0,K=M.signal;R(1);try{for(;;){if(K?.aborted)throw tr("AdaptiveRateLimiter.acquire aborted");let Z=B();if(g>Z){let F=Math.ceil((g-Z)/1e6);await tn(F,K);continue}if(A>0&&p||j>0&&f){await tn(250,K);continue}let ke=u,U=l;if(!ke.tryConsume(A)){await tn(Mo(ke,A),K);continue}if(!(j>0?U.tryConsume(j):!0)){ke.putBack(A),await tn(Mo(U,j),K);continue}N();return}}finally{R(-1)}}function S(M){M>0?l.tryConsume(M):M<0&&l.putBack(-M),N()}function E(){m(),y(),v?.(),h.cancel(),b.cancel()}return{effectiveRpm:c,effectiveTpm:d,lastSignal:a,pending:w,rpmAvailable:k,tpmAvailable:T,acquire:_,recordUsage:S,recordSignal:x,dispose:E}}function at(t,e){if(!Number.isFinite(t)||t===1/0)return yt(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let n=Math.max(1,t*e),r=t/60;return yt(n,r)}function Mo(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 tn(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(tr("AdaptiveRateLimiter.acquire aborted")):new Promise((n,r)=>{let o=new se,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(tr("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",s,{once:!0}))})}Q();function nr(t,e={}){let n=e.limiter??Eo({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=er(i);a&&n.recordSignal(a)},s=ge(t,{async invoke(i,a){let c=r(i,a);await n.acquire({requestCost:1,tokenCost:c,signal:a?.signal});try{let d=await we(G(t.invoke(i,a))),u=d.usage??Ro(),p=Ee(u)+Ge(u)-c;return p>0&&n.recordUsage(p),d}catch(d){throw o(d),d}},async*stream(i,a){let c=r(i,a);await n.acquire({requestCost:1,tokenCost:c,signal:a?.signal});try{let d=0;for await(let l of t.stream(i,a))l.type==="usage"&&(d=Ee(l.usage)+Ge(l.usage)),yield l;let u=d-c;u>0&&n.recordUsage(u)}catch(d){throw o(d),d}}});return me(s,"withRateLimiter",t),{adapter:s,limiter:n}}st();Q();var kt=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 rr(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:ht(s.breaker):void 0})),r=e.streamRetryBeforeFirstChunk??!0,o={provider:"cascading",model:void 0,async invoke(s,i){let a=[],c=new Map;for(let u=0;u<n.length;u++){let l=n[u];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 we(G(l.adapter.invoke(s,i)));return l.breaker?.recordSuccess(),{...p,metadata:{...p.metadata??{},tier:l.name}}}catch(p){c.set(l.name,p),l.breaker?.recordFailure(p);let f=n[u+1];f&&e.onFallback?.(l.name,f.name,p)}}let d={skipped:a,failed:c};throw e.onExhausted?.(d),new kt(d)},async*stream(s,i){let a=[],c=new Map;for(let u=0;u<n.length;u++){let l=n[u];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(c.set(l.name,f),l.breaker?.recordFailure(f),p||!r)throw f;let m=n[u+1];m&&e.onFallback?.(l.name,m.name,f)}}let d={skipped:a,failed:c};throw e.onExhausted?.(d),new kt(d)}};return me(o,`cascade[${n.map(s=>s.name).join(",")}]`),o}function Zi(t,e,n){let r={name:t,adapter:e};return n?.breaker&&(r.breaker=n.breaker),n?.filter&&(r.filter=n.filter),r}Q();Ie();function nn(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function Oo(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(nn()):new Promise((n,r)=>{let o=new se,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(nn())},e.addEventListener("abort",s,{once:!0}))})}function or(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??ea,c=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 y=m*(.5+Math.random());return Math.min(o,y)},u=ge(t,{async invoke(l,p){if(p?.signal?.aborted)throw nn();let f,m=r;for(let y=1;y<=n;y++)try{return await we(G(t.invoke(l,p)))}catch(g){if(f=g,y>=n||!a(g,y))throw g;let h=d(y,m);m=h,await Oo(h,p?.signal)}throw f},async*stream(l,p){if(p?.signal?.aborted)throw nn();if(!c){for await(let y of t.stream(l,p))yield y;return}let f,m=r;for(let y=1;y<=n;y++){let g=!1;try{for await(let h of t.stream(l,p))g=!0,yield h;return}catch(h){if(f=h,g||y>=n||!a(h,y))throw h;let b=d(y,m);m=b,await Oo(b,p?.signal)}}throw f}});return me(u,"withRetry",t),u}function ea(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}Q();Ie();var dt=class extends Error{constructor(n){super(`LLM call timed out after ${n}ms`);this.ms=n}name="LLMTimeoutError"};function sr(t,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let n=s=>{let i=new AbortController,a=!1,c,d=new se;return s&&(s.aborted?i.abort(s.reason):(c=()=>{d.cancel(),i.abort(s.reason)},s.addEventListener("abort",c,{once:!0}))),d.start(e,()=>{a=!0,i.abort(new dt(e))}),{signal:i.signal,cancel:()=>{d.cancel(),s&&c&&s.removeEventListener("abort",c)},timedOut:()=>a}},r=(s,i)=>{if(!i||s instanceof dt)throw s;let a=s;if(a?.name==="AbortError"||a?.name==="DOMException"&&Number(a.code)===20||s?.message==="aborted"){let d=new dt(e);throw d.cause=s,d}throw s},o=ge(t,{async invoke(s,i){let{signal:a,cancel:c,timedOut:d}=n(i?.signal);try{return await we(G(t.invoke(s,{...i,signal:a})))}catch(u){return r(u,d())}finally{c()}},async*stream(s,i){let{signal:a,cancel:c,timedOut:d}=n(i?.signal);try{for await(let u of t.stream(s,{...i,signal:a}))yield u}catch(u){r(u,d())}finally{c()}}});return me(o,"withTimeout",t),o}function ta(t,e={}){let n={adapter:t},r=t;if(e.rateLimit){let o=nr(r,e.rateLimit);r=o.adapter,n.rateLimiter=o.limiter}if(e.budget){let o=Zn(r,e.budget);r=o.adapter,n.budget=o.budget}if(e.breaker){let o=Qn(r,e.breaker);r=o.adapter,n.breaker=o.breaker}if(e.timeoutMs!=null&&(r=sr(r,e.timeoutMs)),e.retry&&(r=or(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=rr([{name:e.name??"primary",adapter:r},{name:"fallback",adapter:e.fallback}],o)}return e.cache&&(r=vt(r,e.cache)),n.adapter=r,n}q();Q();function na(t,e,n){let r=G(e);return ae(r,s=>{if(!s||s.length===0)return I(null);let i=n?.tools;return t.invoke(s,{model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,tools:i,systemPrompt:n?.systemPrompt})})}Re();Q();re();Q();Ie();re();Q();function Ao(t,e){let n=t.cache??0;return n>=e?!1:(t.down([[J],[D,n+1]]),!0)}function $e(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}function H(t,e){return $e("ai",t,e)}function ra(t){return t!=null&&typeof t.then=="function"}function ir(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function oa(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var sa=3e4;function Co(t,e){if(t.status==="settled"){let r=t.cache;if(r!==void 0)return Promise.resolve(r)}let n=e?.timeoutMs??sa;return new Promise((r,o)=>{let s=new se,i=t.subscribe(a=>{for(let c of a){if(c[0]===D){s.cancel(),i(),r(c[1]);return}if(c[0]===C){s.cancel(),i(),o(c[1]);return}if(c[0]===$){s.cancel(),i(),o(new Error("firstDataFromNode: completed without producing a value"));return}}});s.start(n,()=>{i(),o(new Error(`firstDataFromNode: timed out after ${n}ms`))})})}async function xt(t){return ra(t)?xt(await t):ir(t)?Co(t):oa(t)?Co(G(t)):t}function ct(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function ia(t,e){let n=G(t),r=e?.refreshTrigger!=null?G(e.refreshTrigger):null;return r==null?te([n],(o,s,i)=>{if(i.store.emitted===!0)return;let c=o[0],d=c!=null&&c.length>0?c.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:H("frozen_context")}):te([n,r],(o,s,i)=>{let a=o[1];if(!(a!=null&&a.length>0))return;let d=o[0],u=d!=null&&d.length>0?d.at(-1):i.prevData[0];s.emit(u)},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:H("frozen_context")})}re();q();Q();function Lo(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function aa(t,e=200){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function ar(t,e,n,r){let o=r?.format??"text",s=r?.name??"prompt_node",i=O(e,c=>{if(c.some(u=>u==null))return[];let d=typeof n=="string"?n:n(...c);return d?[{role:"user",content:d}]:[]},{name:`${s}::messages`,meta:H("prompt_node")});return ae(i,c=>!c||c.length===0?I(null):ne(d=>{let u=!1,l=!1,p,f={model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt};if(r?.abort){let h=oo(r.abort);f.signal=h.signal,p=h.dispose}let m;try{m=t.invoke(c,f)}catch(h){return u=!0,d.down([[C,h]]),()=>{p?.()}}let g=G(m).subscribe(h=>{if(!(l||u))for(let b of h){if(u)return;if(b[0]===D){let v=b[1];try{let x=Lo(v),w=o==="json"?JSON.parse(ct(x)):x;d.emit(w)}catch(x){let w=Lo(v),k=new Error(`promptNode: failed to parse LLM response as JSON: ${x.message}
|
|
7
|
-
Raw content (first 200 chars): ${
|
|
8
|
-
`)}function
|
|
9
|
-
`)}function ba(t,e,n,r,o){let{x:s,y:i,w:a,h:c}=r;if(a<2||c<2){c>0&&jo(t,e,s,i,a,o);return}je(t,e,s,i,n.boxTL);for(let u=s+1;u<s+a-1;u+=1)je(t,e,u,i,n.boxH);je(t,e,s+a-1,i,n.boxTR);for(let u=i+1;u<i+c-1;u+=1){je(t,e,s,u,n.boxV);for(let l=s+1;l<s+a-1;l+=1)Uo(t,e,l,u," ","empty");je(t,e,s+a-1,u,n.boxV)}je(t,e,s,i+c-1,n.boxBL);for(let u=s+1;u<s+a-1;u+=1)je(t,e,u,i+c-1,n.boxH);je(t,e,s+a-1,i+c-1,n.boxBR);let d=i+Math.floor(c/2);jo(t,e,s+1,d,a-2,o)}function je(t,e,n,r,o){Uo(t,e,n,r,o,o===" "?"empty":o==="\u2500"||o==="-"?"boxH":o==="\u2502"||o==="|"?"boxV":"boxCorner")}function Uo(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 jo(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=n,a=o;for(let c of s){let d=dn(c);if(d!==0){if(a<d)break;i>=0&&i<t[r].length&&(t[r][i]=c,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 Ta(t,e,n,r){let o=r.points;if(o.length<2)return;for(let c=0;c+1<o.length;c+=1)va(t,e,n,o[c],o[c+1]);for(let c=1;c+1<o.length;c+=1){let d=o[c-1],u=o[c],l=o[c+1],p=wa(d,u,l,n);p&&Vo(t,e,u.x,u.y,p,"edgeCorner")}let s=o[o.length-1],i=o[o.length-2],a=ka(i,s,n);a&&Vo(t,e,s.x,s.y,a,"arrow")}function va(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 c=i;c<=a;c+=1)Bo(t,e,c,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 c=i;c<=a;c+=1)Bo(t,e,s,c,n,"v")}}}function Bo(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 Vo(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 wa(t,e,n,r){let o=t.y===e.y,s=e.y===n.y;if(o===s)return;if(o){let c=t.x<e.x,d=n.y>e.y;return c&&d?r.cornerTR:c&&!d?r.cornerBR:!c&&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 ka(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 xa(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===32;)e-=1;return t.slice(0,e)}function Wo(t){let e=Ra(t);Sa(e),_a(e),Na(e),Ma(e,t);let n=Aa(e,t),{width:r,height:o}=La(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 Ra(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 Sa(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 c=(e.get(a.id)??0)-1;e.set(a.id,c),c<=0&&n.push(a)}}}for(let s of t.nodes.values())s.layer<0&&(s.layer=0)}function _a(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),c=a.layer-i.layer;if(c<=0){i.out=i.out.filter(l=>l!==s),a.in=a.in.filter(l=>l!==s);continue}if(c===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<c;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:c};d.out.push(m),f.in.push(m),r.push(m),d=f}let u={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:d.id,toId:a.id,hopIndex:c-1,chainLen:c};d.out.push(u),a.in.push(u),r.push(u)}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 Na(t){for(let n=0;n<4;n+=1){for(let r=1;r<t.layers.length;r+=1)zo(t,t.layers[r],"in"),cn(t.layers[r]);for(let r=t.layers.length-2;r>=0;r-=1)zo(t,t.layers[r],"out"),cn(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=Ho(t,s[i],s[i+1],"in");[s[i],s[i+1]]=[s[i+1],s[i]],cn(s),Ho(t,s[i],s[i+1],"in")<a?r=!0:([s[i],s[i+1]]=[s[i+1],s[i]],cn(s))}}if(!r)break}}function zo(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 c of s){let d=t.nodes.get(n==="in"?c.fromId:c.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 cn(t){for(let e=0;e<t.length;e+=1)t[e].order=e}function Ho(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 c of s){let d=t.nodes.get(r==="in"?a.fromId:a.toId)?.order??0,u=t.nodes.get(r==="in"?c.fromId:c.toId)?.order??0;(e.order<n.order&&d>u||e.order>n.order&&d<u)&&(i+=1)}return i}function Ma(t,e){e.direction==="LR"?Ea(t,e):Oa(t,e)}function Ea(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}qo(t,e,"y")}function Oa(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}qo(t,e,"x")}function qo(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 c=new Map;for(let u of a){let l=s===0?u.in:u.out;if(l.length===0)continue;let p=[];for(let m of l){let y=t.nodes.get(s===0?m.fromId:m.toId);if(!y)continue;let g=n==="y"?y.y:y.x;p.push(g+Math.floor(r(y)/2))}if(p.length===0)continue;p.sort((m,y)=>m-y);let f=p[Math.floor(p.length/2)];c.set(u.id,f-Math.floor(r(u)/2))}let d=0;for(let u of a){let l=c.get(u.id),p=n==="y"?u.y:u.x,m=Math.max(l??p,d);n==="y"?u.y=m:u.x=m,d=m+r(u)+o}}}}function Aa(t,e){let n=new Map;for(let d of t.hops){let u=n.get(d.chainId);u?u.push(d):n.set(d.chainId,[d])}for(let d of n.values())d.sort((u,l)=>u.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 u=t.layers[d],l=t.layers[d+1],p=0;for(let R of u)p=Math.max(p,o(R)+s(R));let f=Number.POSITIVE_INFINITY;for(let R of l)f=Math.min(f,o(R));let m=Number.isFinite(f)?f-1:p,y=Math.max(1,m-p+1),g=[];for(let R of u)for(let N of R.out)g.push(N);g.sort((R,N)=>{let _=i(t.nodes.get(R.fromId)),S=i(t.nodes.get(N.fromId));if(_!==S)return _-S;let E=i(t.nodes.get(R.toId)),M=i(t.nodes.get(N.toId));return E-M});let h=[],b=new Map;for(let R of g){let N=i(t.nodes.get(R.fromId)),_=i(t.nodes.get(R.toId)),S=Math.min(N,_),E=Math.max(N,_),M=-1;for(let A=0;A<h.length;A+=1){let j=h[A],K=!0;for(let Z of j)if(Z.lo<=E&&S<=Z.hi){K=!1;break}if(K){j.push({lo:S,hi:E}),M=A;break}}M<0&&(h.push([{lo:S,hi:E}]),M=h.length-1),b.set(R,M)}let v=h.length,x=y>=Math.max(3,v+2),w=x?p+1:p,k=x?m-1:m,T=Math.max(1,k-w+1);for(let R of g){let N=b.get(R),_;if(v<=1)_=w+Math.floor(T/2);else{let S=(T-1)/(v-1);_=w+Math.floor(N*S)}a.set(R,Math.max(p,Math.min(m,_)))}}let c=[];for(let[,d]of n){let u=[];for(let p=0;p<d.length;p+=1){let f=d[p],m=t.nodes.get(f.fromId),y=t.nodes.get(f.toId),g=a.get(f),h=m.isVirtual?o(m):o(m)+s(m),b=y.isVirtual?o(y):o(y)-1,v=i(m),x=i(y);p===0&&un(u,r,h,v),v!==x&&(un(u,r,g,v),un(u,r,g,x)),un(u,r,b,x)}let l=d[0];c.push({from:l.chainFrom,to:l.chainTo,points:Ca(u)})}return c}function un(t,e,n,r){t.push(e?{x:n,y:r}:{x:r,y:n})}function Ca(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 La(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 Da=24,Ia=4,Pa=1,Ga=3;function Jo(t,e){let n=Fa(e.direction),r=Math.max(3,e.maxLabelWidth??Da),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)),c=new Map,d=new Map;for(let f of s){let m=$o(f,r);c.set(f,m),d.set(f,dn(m)+4)}let u=Wo({nodes:s,edges:a,widthCells:f=>d.get(f)??3,heightCells:()=>Ga,layerGap:Ia,nodeGap:Pa,direction:n}),l=Ko(u,{charset:o,labelOf:f=>c.get(f)??f}),p=e.logger;return p&&p(l),l}function Fa(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)}`)}Re();function Yo(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),y=m instanceof ue?m:null,g=y?Do(y.cache):0,h=y?y._sinkCount:0,b=f.deps?.length??0,v=f.type==="effect"&&h===0,x=h===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:h,depCount:b,isOrphanEffect:v,orphanKind:x})}let c=a.reduce((p,f)=>p+f.valueSizeBytes,0),d=(p,f)=>[...a].sort(f??((m,y)=>y[p]-m[p])).slice(0,n),u=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:c,hotspots:{byValueSize:d("valueSizeBytes"),bySubscriberCount:d("subscriberCount"),byDepCount:d("depCount")},orphans:u,orphanEffects:l}}var oe="::",Se="__meta__",Ye=1;function Qo(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 $a(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(`
|
|
10
|
-
`)}function
|
|
11
|
-
`);return e.logger?.(s),s}function
|
|
12
|
-
`)}function
|
|
13
|
-
`)}function qa(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ln(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+=qa(r)}return e+="$",new RegExp(e)}var Ja={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"},Ya={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function pn(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 Qa(t){return t==="none"?Ya:t==="ansi"||t==null?Ja:{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 Zo(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 Xa(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 ur(t,e,n){if(t==="")throw new Error(`Graph "${e}": ${n} name must be non-empty`);if(t.includes(oe))throw new Error(`Graph "${e}": ${n} "${t}" must not contain '${oe}' (path separator)`);if(t===Se)throw new Error(`Graph "${e}": ${n} name "${Se}" is reserved for meta companion paths`);Xa(t,e,n)}function Za(t,e){if(t==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let n=t.split(oe);for(let r of n)if(r==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return n}function ed(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 os(t){for(let e of t._mounts.values())os(e);for(let e of t._nodes.values())try{e.down([[fe]],{internal:!0})}catch{}}var ie=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(oe))throw new Error(`Graph name must not contain '${oe}' (got "${e}")`);if(e===Se)throw new Error(`Graph name "${Se}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...n??{}}),this.config=n?.config??nt,this._traceRing=new Tt(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=ne(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(ur(s,this.name,"add"),this._mounts.has(s))throw new Error(`Graph "${this.name}": name "${s}" is already a mount point`);if(this._nodes.has(s))throw new Error(`Graph "${this.name}": node "${s}" already exists`);let a=this._nodeToName.get(e);if(a!==void 0)throw new Error(`Graph "${this.name}": node instance already registered as "${a}"`);return this._nodes.set(s,e),this._nodeToName.set(e,s),this._emitTopology({kind:"added",name:s,nodeKind:"node"}),i!=null&&(this._annotations.set(s,i),this.config.inspectorEnabled&&this._traceRing.push({path:s,annotation:i,timestamp_ns:B()})),e}setVersioning(e){if(e!=null)for(let n of this._nodes.values())n instanceof ue&&n._applyVersioning(e)}remove(e){ur(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,c]of i)a.includes(`${oe}${Se}${oe}`)||s.nodes.push(a);return s.nodes.sort(),s.mounts.push(e),s.mounts.push(...n._collectSubgraphs(`${e}${oe}`)),this._mounts.delete(e),n._parent=void 0,os(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([[fe]],{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=ln(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(oe))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([[D,n]],{actor:r?.actor,internal:o,delivery:"write"})}setAll(e,n){let r=Symbol.iterator in e?e:Object.entries(e);ee(()=>{for(let[o,s]of r)this.set(o,s,n)})}invalidate(e,n){let r=n?.internal===!0;this.node(e).down([[_e]],{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([[$]],{actor:n?.actor,internal:r,delivery:"write"})}edges(e){let n=e?.recursive===!0,r=new Map;if(!n){for(let[c,d]of this._nodes)r.set(d,c);let a=[];for(let[c,d]of this._nodes)if(d instanceof ue)for(let u of d._deps){let l=r.get(u.node);l!=null&&a.push([l,c])}return a.sort((c,d)=>c[0]<d[0]?-1:c[0]>d[0]?1:c[1]<d[1]?-1:c[1]>d[1]?1:0),a}let o=[];this._collectObserveTargets("",o);let s=new Map;for(let[a,c]of o)s.set(c,a);let i=[];for(let[a,c]of o)if(c instanceof ue)for(let d of c._deps){let u=s.get(d.node);u!=null&&i.push([u,a])}return i.sort((a,c)=>a[0]<c[0]?-1:a[0]>c[0]?1:a[1]<c[1]?-1:a[1]>c[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(ur(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=Za(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]===Se)return this._resolveMetaChainFromNode(s,o,n.join(oe));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(oe)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${r}"`);return i.resolve(o.join(oe))}_resolveMetaChainFromNode(e,n,r){let o=e,s=0,i=[...n];for(;s<i.length;){if(i[s]!==Se)throw new Error(`Graph "${this.name}": expected ${Se} segment in meta path "${r}"`);if(s+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${Se} in "${r}"`);let a=i[s+1],c=o.meta[a];if(!c)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${r}"`);o=c,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 c of this._mounts.values())c._signalDeliver(e,n,r,o);let i=n.internal===!0?{internal:!0}:{actor:n.actor,delivery:"signal"},a=ed(e,this.config);for(let c of[...this._nodes.keys()].sort()){let d=this._nodes.get(c);if(!r.has(d)){r.add(d);try{d.down(e,i)}catch(u){if(u instanceof Me)throw u;o.push(u)}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(c){if(c instanceof Me)throw c;s.push(c)}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=rn(e?.detail,e?.fields),s=e?.format==="spec",i=s?rn("minimal"):o,a=[];this._collectObserveTargets("",a);let c=new Map;for(let[k,T]of a)c.set(T,k);let d=[];{let k=a.map(([,N])=>N),T=new Set(c.values()),R=0;for(;k.length>0;){let N=k.shift();if(N instanceof ue)for(let _ of N._deps){let S=_.node;if(c.has(S))continue;let E=S.name??"",M=E;if(!M||T.has(M))if(E){let A=2;for(;T.has(`${E}#${A}`);)A++;M=`${E}#${A}`}else for(M=`__internal__/${R++}`;T.has(M);)M=`__internal__/${R++}`;c.set(S,M),T.add(M),d.push([M,S]),k.push(S)}}}let u=[...a,...d],l={};for(let[k,T]of u){if(n!=null&&!T.allowsObserve(n))continue;let R=dr(T,i),N=T instanceof ue?T._deps.map(M=>c.get(M.node)??M.node.name??""):[],{name:_,...S}=R,E={...S,deps:N};if(!s){let M=this._annotations.get(k);M!=null&&(E.annotation=M)}if(r!=null)if(typeof r=="function"){let M=r;if(!(M.length>=2?M(k,E):M(E)))continue}else{let M=!0;for(let[A,j]of Object.entries(r)){let K=A==="deps_includes"?"depsIncludes":A==="meta_has"?"metaHas":A;if(K==="depsIncludes"){if(!E.deps.includes(String(j))){M=!1;break}continue}if(K==="metaHas"){if(!Object.hasOwn(E.meta??{},String(j))){M=!1;break}continue}if(E[K]!==j){M=!1;break}}if(!M)continue}l[k]=E}let p=new Set(Object.keys(l)),f=[];for(let[k,T]of u)if(T instanceof ue)for(let R of T._deps){let N=c.get(R.node);N!=null&&f.push([N,k])}f.sort((k,T)=>k[0]<T[0]?-1:k[0]>T[0]?1:k[1]<T[1]?-1:k[1]>T[1]?1:0);let m=f.map(([k,T])=>({from:k,to:T}));(n!=null||r!=null)&&(m=m.filter(k=>p.has(k.from)&&p.has(k.to)));let y=this._collectSubgraphs(""),g=n!=null||r!=null?y.filter(k=>{let T=`${k}${oe}`;return[...p].some(R=>R===k||R.startsWith(T))}):y,h=this,b=e,v={name:this.name,nodes:l,edges:m,subgraphs:g,expand(k){let T={...b,format:void 0};return Array.isArray(k)?(T.fields=k,T.detail=void 0):(T.detail=k,T.fields=void 0),h.describe(T)}},x=e??{},w=x.format;return w==="json"?Ua(v,x):w==="pretty"?za(v,x):w==="mermaid"?ns(v,x):w==="mermaid-url"?Ha(v,x):w==="d2"?Wa(v,x):w==="ascii"?Jo(v,x):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}${oe}`))}return n}resourceProfile(e){return Yo(this,e)}reachable(e,n,r={}){return r.withDetail===!0?pr(this.describe(),e,n,{...r,withDetail:!0}):pr(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,c]of Object.entries(o.nodes))c.lastMutation!=null&&i.set(a,c.lastMutation);return Io(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=I(o,{name:`${r}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,c=!1,d=()=>{a||c||(a=!0,mt(()=>{a=!1,!c&&(o+=1,s.emit(o))}))},u=i.onEvent(g=>{let h=g.type;h!=="data"&&h!=="error"&&h!=="complete"&&h!=="teardown"||d()}),l=[],p=new WeakSet,f=g=>{if(p.has(g)||c)return;p.add(g);let h=g.topology.subscribe(b=>{for(let v of b){if(v[0]!==D)continue;let x=v[1];if(d(),x.kind==="added"&&x.nodeKind==="mount"){let w=g._mounts.get(x.name);w!=null&&f(w)}}});l.push(h);for(let b of g._mounts.keys()){let v=g._mounts.get(b);v!=null&&f(v)}};f(this);let m;try{m=O([s],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(g,h)=>g===h})}catch(g){u();for(let h of l)h();throw i.dispose(),g}let y=Y(m);return{node:m,dispose(){c=!0,u();for(let g of l)g();l.length=0,i.dispose(),y()}}}_explainReactive(e,n,r){let o=0,s=I(o,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,c=!1,d=i.onEvent(f=>{let m=f.type;m!=="data"&&m!=="error"&&m!=="complete"&&m!=="teardown"||a||c||(a=!0,mt(()=>{a=!1,!c&&(o+=1,s.emit(o))}))}),u={...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{}},l;try{l=O([s],()=>this._explainStatic(e,n,u),{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&&td(f.steps,m.steps)})}catch(f){throw d(),i.dispose(),f}let p=Y(l);return{node:l,dispose(){c=!0,d(),i.dispose(),p()}}}_pathsMatching(e){let n=ln(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}${oe}${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}${oe}${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}${oe}${Se}${oe}${o}`;r.push([i,s]),this._appendMetaObserveTargets(i,s,r)}}observe(e,n){let r=typeof e=="string",s=Zo(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 u=e,l=this.resolve(u);if(a!=null&&!l.allowsObserve(a))throw new Me({actor:a,action:"observe",nodeName:u});return i?this._buildStructuredObserver([[u,l]],s,"one"):{subscribe(p){return l.subscribe(p)},up(p){try{l.up?.(p)}catch(f){if(f instanceof Me)return;throw f}}}}let c=[];this._collectObserveTargets("",c),c.sort((u,l)=>u[0]<l[0]?-1:u[0]>l[0]?1:0);let d=a==null?c:c.filter(([,u])=>u.allowsObserve(a));return i?this._buildStructuredObserver(d,s,"all"):{subscribe:u=>{let l=d.map(([p,f])=>f.subscribe(m=>{u(p,m)}));return()=>{for(let p of l)p()}},up:(u,l)=>{try{this.resolve(u).up?.(l)}catch(p){if(p instanceof Me)return;throw p}}}}_buildStructuredObserver(e,n,r){let o=r==="one"?e[0]?.[0]:void 0,s=i=>{if(r==="one"&&o!=null){let u=this.resolve(o);return this._buildStructuredObserver([[o,u]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((u,l)=>u[0]<l[0]?-1:u[0]>l[0]?1:0);let c=i.actor,d=c==null?a:a.filter(([,u])=>u.allowsObserve(c));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",c=this.config.inspectorEnabled,d=(s||i)&&c,u=n.maxEvents,l=u!=null&&u>0?new Tt(u):null,p=[],f=new Set,m={},y=new Set,g=0,h=0,b=0,v=0,x=0,w=0,k=!1,T=!1,R=0,N=new Map,_=new Map,S=new Map,E=L=>{l?l.push(L):p.push(L);for(let z of f)z(L)},M=()=>o?{timestamp_ns:B(),in_batch:Et(),batch_id:R}:{},A=(L,z)=>{if(!(!d||!(L instanceof ue)))return L._setInspectorHook(de=>{if(de.kind==="dep_message")N.set(L,de.depIndex);else if(de.kind==="run"){let he=de.batchData.map((X,be)=>X!=null&&X.length>0?X.at(-1):de.prevData[be]);_.set(L,he);let ye=de.batchData.map(X=>X!=null?[...X]:void 0);S.set(L,ye),i&&E({type:"derived",path:z,dep_values:he,dep_batches:ye,...M()})}})},j=L=>{let z=N.get(L),de=_.get(L);if(!s||de==null)return{};let ye=(z!=null&&z>=0&&L instanceof ue?L._deps[z]:void 0)?.node,X=ye?.v,be=S.get(L);return{trigger_dep_index:z,trigger_dep_name:ye?.name,...X!=null?{trigger_version:{id:X.id,version:X.version}}:{},dep_values:[...de],...be!=null?{dep_batches:be}:{}}},K=[],Z=[];for(let[L,z]of e){let de=A(z,L);de&&K.push(de),Z.push(z.subscribe(he=>{R++;for(let ye of he){let X=ye[0],be=M();if(X===D){m[L]=ye[1];let bn=z instanceof ue?z.lastMutation?.actor??Xe:Xe;E({type:"data",path:L,data:ye[1],actor:bn,...be,...j(z)})}else if(a)X===J?g++:X===V?h++:X===_e?b++:X===Ne?v++:X===Ae?x++:X===fe?w++:X===$&&!y.has(L)?k=!0:X===C&&(T=!0,y.add(L));else if(X===J)g++,E({type:"dirty",path:L,...be});else if(X===V)h++,E({type:"resolved",path:L,...be,...j(z)});else if(X===_e)b++,E({type:"invalidate",path:L,...be});else if(X===Ne)v++,E({type:"pause",path:L,lockId:ye[1],...be});else if(X===Ae)x++,E({type:"resume",path:L,lockId:ye[1],...be});else if(X===$)y.has(L)||(k=!0),E({type:"complete",path:L,...be});else if(X===C){T=!0,y.add(L);let bn=z instanceof ue?z.lastMutation?.actor??Xe:Xe;E({type:"error",path:L,data:ye[1],actor:bn,...be})}else X===fe&&(w++,E({type:"teardown",path:L,...be}))}}))}let ke=!1,U=()=>{if(!ke){ke=!0;for(let L of Z)L();for(let L of K)L();for(let L of P)L({value:void 0,done:!0});P.length=0}},W=[],P=[];f.add(L=>{let z=P.shift();z?z({value:L,done:!1}):W.push(L)});let F={get values(){return m},get dirtyCount(){return g},get resolvedCount(){return h},get invalidateCount(){return b},get pauseCount(){return v},get resumeCount(){return x},get teardownCount(){return w},get events(){return l?l.toArray():[...p]},get anyCompletedCleanly(){return k},get anyErrored(){return T},get completedWithoutErrors(){return k&&!T},onEvent(L){return f.add(L),()=>f.delete(L)},dispose:U,expand(L){U();let z={...n};return typeof L=="string"?z.detail=L:Object.assign(z,L),r(Zo(z))},[Symbol.asyncIterator](){return{next(){return W.length>0?Promise.resolve({value:W.shift(),done:!1}):ke?Promise.resolve({value:void 0,done:!0}):new Promise(L=>P.push(L))},return(){return U(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger(F,n),F}_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)),c=Qa(n.theme),d=r==="stage-log"?B():0,u=m=>m==null?"":n.stageLabels?.[m]??m,l=(m,y)=>m.length>y?`${m.slice(0,y-1)}\u2026`:m,p=m=>m.type==="data"||m.type==="error"?l(pn(m.data),120):"",f=m=>{if(r==="stage-log"){let T=(B()-d)/1e9,R=u(m.path).padEnd(9);if(m.type==="data"){let N=p(m);return`[${T.toFixed(3)}s] ${R} \u2190${N?` ${N}`:""}`}if(m.type==="error"){let N=p(m);return`[${T.toFixed(3)}s] ${R} \u2717${N?` ${N}`:""}`}return m.type==="complete"?`[${T.toFixed(3)}s] ${R} \u25A0 complete`:`[${T.toFixed(3)}s] ${R} ${m.type}`}if(r==="json")try{return JSON.stringify(m)}catch{return JSON.stringify({type:m.type,path:m.path,data:"[unserializable]"})}let y=c[m.type]??"",g=m.path?`${c.path}${m.path}${c.reset} `:"",h=m.type==="data"||m.type==="error",b=m.type==="pause"||m.type==="resume",v=h?` ${pn(m.data)}`:b?` ${pn(m.lockId)}`:"",x=m.type==="data"||m.type==="resolved"||m.type==="derived"?m:void 0,w=x?.trigger_dep_name!=null?` <- ${x.trigger_dep_name}`:x?.trigger_dep_index!=null?` <- #${x.trigger_dep_index}`:"",k=m.in_batch?" [batch]":"";return`${g}${y}${m.type.toUpperCase()}${c.reset}${v}${w}${k}`};e.onEvent(m=>{a(m.type)&&o(f(m),m)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){Qo(this._disposers,this.name),this.signal([[fe]],{internal:!0}),Qo(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:c,guard:d,...u}=r.nodes[a];o[a]=u}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 Mr(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,n){let r=n?.config??nt,{codec:o,codecVersion:s,payload:i}=Er(e,r);return o.decode(i,s)}restore(e,n){if(Xo(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=>ln(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 c=this.tryResolve(s)?.v;if(c!=null&&c.id===i.v.id&&c.version===i.v.version)continue}try{this.set(s,i.value)}catch(a){n?.onError?.(s,a)}}}}}static fromSnapshot(e,n){Xo(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,y)=>{let g=m.split(oe).length,h=y.split(oe).length;return g!==h?g-h:m<y?-1:m>y?1:0})){let m=f.split(oe),y=s;for(let g of m)y._mounts.has(g)||y.mount(g,new t(g)),y=y._mounts.get(g)}let i=o?Object.entries(o).map(([f,m])=>({re:ln(f),factory:m})):[],a=f=>{for(let m of i)if(m.re.test(f))return m.factory},c=f=>{let m=f.split(oe),y=m.pop();if(y==null||y.length===0)throw new Error(`invalid snapshot path "${f}"`);let g=s;for(let h of m){let b=g._mounts.get(h);if(!b)throw new Error(`unknown mount "${h}" in path "${f}"`);g=b}return[g,y]},d=Object.entries(e.nodes).filter(([f])=>!f.includes(`${oe}${Se}${oe}`)).sort((f,m)=>f[0]<m[0]?-1:f[0]>m[0]?1:0),u=new Map(d),l=new Map,p=!0;for(;u.size>0&&p;){p=!1;for(let[f,m]of[...u.entries()]){let y=m?.deps??[];if(!y.every(w=>l.has(w)))continue;let[g,h]=c(f),b={...m?.meta??{}},v=a(f),x;if(m?.type==="state")x=I(m.value,{meta:b});else{if(v==null)continue;x=v(h,{path:f,type:m.type,value:m.value,meta:b,deps:y,resolvedDeps:y.map(w=>l.get(w))})}g.add(x,{name:h}),l.set(f,x),u.delete(f),p=!0}}if(u.size>0){let f=[...u.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,u)=>{if(d.disposed)return;let l=$a(u.nodes);if(d.lastSnapshot!=null&&l!==""&&l===d.lastFingerprint)return;let p=d.seq+1,f=ce(),g=d.lastSnapshot==null||p%d.compactEvery===0?{name:this.name,mode:"full",snapshot:u,seq:p,timestamp_ns:f,format_version:Ye}:{name:this.name,mode:"diff",diff:ss(d.lastSnapshot,u),seq:p,timestamp_ns:f,format_version:Ye};if(d.tier.filter&&!d.tier.filter(g))return;let h;try{h=d.tier.save(g)}catch(b){n.onError?.(b,d.tier);return}if(h&&typeof h.then=="function"){let x=(d.savePending??Promise.resolve()).then(()=>h,()=>h).then(()=>{d.disposed||(d.seq=p,d.lastSnapshot=u,d.lastFingerprint=l)},w=>{n.onError?.(w,d.tier)});d.savePending=x.finally(()=>{d.savePending===x&&(d.savePending=void 0)})}else d.seq=p,d.lastSnapshot=u,d.lastFingerprint=l},s=(d,u)=>{try{o(d,u)}catch(l){n.onError?.(l,d.tier)}},i=(d,u)=>{if(!u.some(m=>{let y=this.config.messageTier(m[0]);return y>=3&&y<5}))return;if(n.filter){let m=this.tryResolve(d);if(m==null)return;let y=dr(m,rn("standard"));if(!n.filter(d,y))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 se),m.timer.start(m.debounceMs,()=>{m.disposed||s(m,this.snapshot())})))},a;if(n.paths!=null){let u=(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 u)l()}}else a=this.observe().subscribe((d,u)=>i(d,u));let c=()=>{a();for(let d of r)d.disposed=!0,d.timer?.cancel();this._storageDisposers.delete(c)};return this._storageDisposers.add(c),{dispose:c}}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===Ye&&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(c){r?.onError?.(c,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===Ye&&i.nodes!=null?i:void 0;if(a!=null)try{return t.fromSnapshot(a,r)}catch(c){r?.onError?.(c,o)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${e}" across ${n.length} tier(s)`)}_annotations=new Map;_traceRing;trace(e,n,r){if(e!=null&&n!=null){if(this.tryResolve(e)==null)return;if(this._annotations.set(e,n),this.config.inspectorEnabled){let o={path:e,annotation:n,timestamp_ns:B(),...r?.actor!=null?{actor:r.actor}:{}};this._traceRing.push(o)}return}return e!=null?this.config.inspectorEnabled?this._annotations.get(e):void 0:this.config.inspectorEnabled?this._traceRing.toArray():[]}annotation(e){return this._annotations.get(e)}clearTrace(){this._annotations.clear(),this._traceRing.clear()}pruneTrace(e){let n=this._traceRing.toArray().filter(o=>!e(o)),r=this._traceRing.size-n.length;this._traceRing.clear();for(let o of n)this._traceRing.push(o);return r}static diff(e,n){let r=new Set(Object.keys(e.nodes)),o=new Set(Object.keys(n.nodes)),s=[...o].filter(b=>!r.has(b)).sort(),i=[...r].filter(b=>!o.has(b)).sort(),a=[],c=[];for(let b of r){if(!o.has(b))continue;let v=e.nodes[b],x=n.nodes[b],w=v.v,k=x.v;w!=null&&k!=null&&w.id===k.id&&w.version!==k.version&&c.push({path:b,id:w.id,from:w.version,to:k.version});let T=w!=null&&k!=null&&w.id===k.id&&w.version===k.version;for(let R of["type","status","sentinel"]){let N=v[R],_=x[R];N!==_&&a.push({path:b,field:R,from:N,to:_})}if(!T)for(let R of["value","meta"]){let N=v[R],_=x[R];ja(N,_)||a.push({path:b,field:R,from:N,to:_})}}let d=b=>`${b.from} ${b.to}`,u=new Set(e.edges.map(d)),l=new Set(n.edges.map(d)),p=n.edges.filter(b=>!u.has(d(b))),f=e.edges.filter(b=>!l.has(d(b))),m=new Set(e.subgraphs),y=new Set(n.subgraphs),g=[...y].filter(b=>!m.has(b)).sort(),h=[...m].filter(b=>!y.has(b)).sort();return{nodesAdded:s,nodesRemoved:i,nodesChanged:a,versionChanges:c,edgesAdded:p,edgesRemoved:f,subgraphsAdded:g,subgraphsRemoved:h}}};function ss(t,e){let n=ie.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 pr(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,c=new Map,d=new Map,u=new Set;for(let[v,x]of Object.entries(t.nodes)){if(!v)continue;u.add(v);let w=x.deps??[];i.set(v,w);for(let k of w)k&&(u.add(k),a.has(k)||a.set(k,new Set),a.get(k).add(v))}for(let v of t.edges){if(v==null||typeof v!="object")continue;let x=typeof v.from=="string"?v.from:"",w=typeof v.to=="string"?v.to:"";!x||!w||(u.add(x),u.add(w),d.has(x)||d.set(x,new Set),d.get(x).add(w),c.has(w)||c.set(w,new Set),c.get(w).add(x))}if(!u.has(e))return r.withDetail?o:[];let l=r.both===!0,p=v=>{if(l){let T=i.get(v)??[],R=c.get(v),N=a.get(v),_=d.get(v),S=[...T];return R&&S.push(...R),N&&S.push(...N),_&&S.push(..._),S}if(n==="upstream"){let T=i.get(v)??[],R=c.get(v);return R?[...T,...R]:T}let x=a.get(v),w=d.get(v),k=x?[...x]:[];return w&&k.push(...w),k},f=new Set([e]),m=new Map,y=[{path:e,depth:0}],g=0,h=!1;for(;g<y.length;){let v=y[g++];if(s!=null&&v.depth>=s){p(v.path).length>0&&(h=!0);continue}for(let x of p(v.path))!x||f.has(x)||(f.add(x),m.set(x,v.depth+1),y.push({path:x,depth:v.depth+1}))}let b=[...m.keys()].sort((v,x)=>v<x?-1:v>x?1:0);return r.withDetail?{paths:b,depths:m,truncated:h}:b}function td(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}function is(t,e){return $e("messaging",t,e)}var nd=1024,fr=class extends ie{_log;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=Le([],{name:"events",maxSize:n.retainedLimit??nd}),this._log.withLatest(),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=O([this.events],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:is("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(Y(this.latest)),this.hasLatest=O([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:is("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(Y(this.hasLatest)),this.addDisposer(()=>{this.events.down([[$]])}),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}};function mr(t,e){return new fr(t,e)}xe();pe();re();Re();q();xe();pe();tt();re();var rd=Fr((t,e)=>{t("observe"),t("signal"),e("write")});function as(t){let e=Le([],{name:t.name,maxSize:t.retainedLimit??1024,guard:t.guard??rd,...t.versioning!=null?{versioning:t.versioning}:{}});return e.withLatest(),t.graph&&t.graph.add(e.entries,{name:t.name}),e}function ds(t){if(t===null||typeof t!="object"||Object.isFrozen(t))return t;for(let e of Object.keys(t))ds(t[e]);return Object.freeze(t)}function od(t){let n=(t.cache??0)+1;return t.down([[J],[D,n]]),n}function ut(t,e){let n=e.freeze??!0;return function(...o){let s=n?o.map(ds):o,i=ce(),a,c,d=!1,u;try{ee(()=>{e.seq&&(u=od(e.seq));try{if(a=t(...s),e.onSuccess){let l=e.onSuccess(s,a,{t_ns:i,seq:u});if(l!==void 0){let p=e.handlerVersion!=null?{...l,handlerVersion:e.handlerVersion}:l;e.audit.append(p)}}}catch(l){throw c=l,d=!0,l}})}catch(l){if(d&&e.onFailure){let p=c instanceof Error?c.name:typeof c,f=e.onFailure(s,c,{t_ns:i,seq:u,errorType:p});if(f!==void 0){let m=e.handlerVersion!=null?{...f,handlerVersion:e.handlerVersion}:f;e.audit.append(m)}}throw d?c:l}return a}}function Rt(t,e){return $e("orchestration",t,e)}var fn=class extends ie{constructor(e,n){super(e,n)}task(e,n,r={}){let o=(r.deps??[]).map(i=>this._resolveStep(i)),s=O(o,n,{name:e,describeKind:"derived",meta:Rt("task",r.meta)});return this.add(s,{name:e}),s}classify(e,n,r,o={}){let s=this._resolveStep(n),i=O([s],([a])=>{try{return{tag:r(a),value:a}}catch(c){return{tag:"error",value:a,error:c}}},{name:e,describeKind:"derived",meta:Rt("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=O(s,a=>{let c={};for(let d=0;d<o.length;d++)c[o[d]]=a[d];return c},{name:e,describeKind:"derived",meta:Rt("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 ie(`${e}_state`),c=I([],{name:"pending",equals:()=>!1}),d=I(s,{name:"isOpen"}),u=O([c],([U])=>U.length,{name:"count"}),l=I(0,{name:"droppedCount"}),p=as({name:"decisions",retainedLimit:1024,graph:a});a.add(c,{name:"pending"}),a.add(d,{name:"isOpen"}),a.add(u,{name:"count"}),a.add(l,{name:"droppedCount"}),this.mount(`${e}_state`,a);let f=[],m=!1,y=!1,g=s,h=d.subscribe(U=>{for(let W of U)W[0]===D&&(g=W[1])});this.addDisposer(h);function b(){c.emit([...f])}function v(U,W,P){p.append({action:U,t_ns:ce(),...W!==void 0?{items:W,count:W.length}:{},...P!==void 0?{unflushed:P}:{},...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}function x(U){if(f.push(U),f.length>o){let W=f.shift();l.emit(l.cache+1),v("drop",[W])}b()}function w(U){let W=f.splice(0,U);return b(),W}let k=te([i],(U,W,P)=>{let F=P.terminalDeps[0];if(F!==void 0){m=!0;let z=f.length;f=[],b(),v("teardown",void 0,z),W.down(F===!0?[[$]]:[[C,F]]);return}let L=U[0];if(L==null||L.length===0){W.down([[V]]);return}for(let z of L)g?W.emit(z):(x(z),W.down([[V]]))},{name:e,describeKind:"derived",meta:Rt("gate",r.meta)});if(this.add(k,{name:e}),r.approver!=null){r.approver.cache&&(d.emit(!0),g=!0,r.onceOnly&&(y=!0));let W=r.approver.subscribe(P=>{for(let F of P){if(F[0]!==D)continue;let L=!!F[1];if(L&&!g){if(r.onceOnly){if(y)continue;y=!0}ee(()=>{d.emit(!0);let z=w(f.length);v("open",z);for(let de of z){if(m)break;k.emit(de)}})}else if(!L&&g){if(r.onceOnly&&y)continue;ee(()=>{d.emit(!1),v("close")})}}});this.addDisposer(W)}let T=U=>{if(m)throw new Error(`gate: ${U}() called after gate was torn down`)},R=(U=1)=>{T("approve");let W=w(U);for(let P of W){if(m)break;k.emit(P)}},N=(U=1)=>{T("reject"),w(U)},_=(U,W=1)=>{T("modify");let P=[...f],F=w(W);for(let L=0;L<F.length&&!m;L++)k.emit(U(F[L],L,P))},S=()=>{T("open"),d.emit(!0);let U=w(f.length);for(let W of U){if(m)break;k.emit(W)}},E=()=>{T("close"),!(r.onceOnly&&y)&&d.emit(!1)},M=ut(R,{audit:p,freeze:!1,onSuccess:(U,W,P)=>({action:"approve",count:U[0]??1,t_ns:P.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(U,W,P)=>({action:"drop",t_ns:P.t_ns,errorType:P.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),A=ut(N,{audit:p,freeze:!1,onSuccess:(U,W,P)=>({action:"reject",count:U[0]??1,t_ns:P.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(U,W,P)=>({action:"drop",t_ns:P.t_ns,errorType:P.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),j=ut(_,{audit:p,freeze:!1,onSuccess:(U,W,P)=>({action:"modify",count:U[1]??1,t_ns:P.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(U,W,P)=>({action:"drop",t_ns:P.t_ns,errorType:P.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),K=ut(S,{audit:p,freeze:!1,onSuccess:(U,W,P)=>({action:"open",t_ns:P.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(U,W,P)=>({action:"drop",t_ns:P.t_ns,errorType:P.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),Z=ut(E,{audit:p,freeze:!1,onSuccess:(U,W,P)=>({action:"close",t_ns:P.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(U,W,P)=>({action:"drop",t_ns:P.t_ns,errorType:P.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})});return this.addDisposer(u.subscribe(()=>{})),{node:k,pending:c,count:u,isOpen:d,droppedCount:l,decisions:p,audit:p,approve:M,reject:A,modify:j,open:K,close:Z}}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=te([s],(c,d,u)=>{let l=u.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"?[[$]]:[[C,f.error]]);return}let p=c[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:Rt("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 gr(t,e){return new fn(t,e)}async function cs(t,e,n,r){let o="",s=0;for await(let i of t.stream(e,n))r.publish({...i,seq:s++,ts:ce()}),i.type==="token"&&(o+=i.delta);return o}function us(t,e){if(e==="json")try{return JSON.parse(ct(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 ls(t,e){return O([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:H("accumulated_text"),initial:""})}function sd(t,e,n,r){let o=r?.name??"llm",s=r?.format??"text",i=mr(`${o}/stream`,{...r?.retainedLimit!=null?{retainedLimit:r.retainedLimit}:{}}),a=O(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:H("prompt_node::messages"),initial:[]}),c=ae(a,l=>{let p=l;if(!p||p.length===0)return I(null);let f=new AbortController;async function*m(){try{let y=await cs(t,p,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt,signal:f.signal},i);yield us(y,s)}finally{f.abort()}}return G(m())}),d=ls(i,`${o}::accumulatedText`),u=Y(c);return{output:c,deltaTopic:i,accumulatedText:d,dispose:()=>{u(),i.destroy()}}}function id(t,e,n,r,o,s){let i=I(0,{name:`${e}/cancel`}),a=0,c=[...r,i],d=s?.name??e,u=s?.format??"text",l=mr(`${d}/stream`,{...s?.retainedLimit!=null?{retainedLimit:s.retainedLimit}:{}}),p=O(c,T=>{let R=T.slice(0,-1);if(R.some(_=>_==null))return[];let N=typeof o=="string"?o:o(...R);return N?[{role:"user",content:N}]:[]},{name:`${d}::messages`,meta:H("prompt_node::messages"),initial:[]}),f=ae(p,T=>{let R=T;if(!R||R.length===0)return I(null);let N=new AbortController;async function*_(){try{let S=await cs(n,R,{model:s?.model,temperature:s?.temperature,maxTokens:s?.maxTokens,systemPrompt:s?.systemPrompt,signal:N.signal},l);yield us(S,u)}finally{N.abort()}}return G(_())}),m=ls(l,`${d}::accumulatedText`),y=so(f,T=>T!=null);t.add(y,{name:`${e}/raw`});let g=gr(`${e}/gate-graph`);t.mount(`${e}/gate-graph`,g),g.add(y,{name:`${e}/raw`});let h=g.gate(`${e}/gate`,`${e}/raw`,s?.gate),b=Y(f),v=Y(h.node),x=Y(m);t.addDisposer(b),t.addDisposer(v),t.addDisposer(x);let w=h.reject.bind(h),k={...h,reject(T=1){ee(()=>{w(T),i.emit(++a)})}};return{output:h.node,deltaTopic:l,accumulatedText:m,gate:k,dispose:()=>{b(),v(),x(),l.destroy()}}}q();Q();function ad(t,e){let n=e?.separator??`
|
|
6
|
+
`)}]});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(Ji)}]),e?.providerExtras&&Object.assign(o,e.providerExtras),o}function Ji(t){return{name:t.name,description:t.description,parameters:t.parameters}}function Go(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 rr(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 Fo(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:rr(t.usageMetadata),finishReason:n?.finishReason,latencyMs:e,model:t.modelVersion,provider:"google"}}function Yi(t){if(t.apiKey)return t.apiKey;let e=globalThis.process?.env;return e?.GOOGLE_API_KEY??e?.GEMINI_API_KEY}function Qi(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=Yi(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),c=on(s,i),d=K(),u=`${e}/models/${encodeURIComponent(a)}:generateContent?${o()}`,l=await n(u,{method:"POST",headers:{"content-type":"application/json",...t.headers??{}},body:JSON.stringify(c),signal:i?.signal});if(!l.ok)throw await Be(l,"Google");let p=await l.json(),f=Math.max(0,(K()-d)/1e6);return Fo(p,f)},async*stream(s,i){let a=r(i),c=on(s,i),d=`${e}/models/${encodeURIComponent(a)}:streamGenerateContent?alt=sse&${o()}`,u=await n(d,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",...t.headers??{}},body:JSON.stringify(c),signal:i?.signal});if(!u.ok)throw await Be(u,"Google");if(!u.body)throw new Error("googleAdapter: streaming response has no body");let l,p;for await(let f of pt(u.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:rr(l)}),yield{type:"finish",reason:p??"stop"}}}}function Xi(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=on(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=Go(o,s,r?.signal),a=K(),c=await e.models.generateContent(i),d=Math.max(0,(K()-a)/1e6);return Fo(c,d)},async*stream(n,r){if(!e.models.generateContentStream)throw new Error("sdkBackedGoogle: SDK instance does not expose generateContentStream");let o=on(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=Go(o,s,r?.signal),a,c,d=await e.models.generateContentStream(i);for await(let u of d){let l=u.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&&(c=l.finishReason),u.usageMetadata&&(a=u.usageMetadata)}a&&(yield{type:"usage",usage:rr(a)}),yield{type:"finish",reason:c??"stop"}}}}ge();var Zi={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 or(t={}){return t.sdk?oa(t):ra(t)}function sn(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(ea);e?.systemPrompt&&!t.some(c=>c.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(ta)),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 ea(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 ta(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}}function sr(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 $o(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:na(a.function.arguments)}));return{content:s,toolCalls:i.length>0?i:void 0,usage:sr(t.usage),finishReason:r?.finish_reason,latencyMs:e,model:t.model,provider:n}}function na(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!=null?e:{_raw:t}}catch{return{_raw:t}}}function jo(t){let e=t.preset??"openai",n=Zi[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 ra(t){let{provider:e,baseURL:n,apiKey:r}=jo(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,c){let d=sn(a,c,t.model,!1,t.bodyExtras),u=K(),l=await o(`${n}/chat/completions`,{method:"POST",headers:i(),body:JSON.stringify(d),signal:c?.signal});if(!l.ok)throw await Be(l,e);let p=await l.json(),f=Math.max(0,(K()-u)/1e6);return $o(p,f,e)},async*stream(a,c){let d=sn(a,c,t.model,!0,t.bodyExtras),u=await o(`${n}/chat/completions`,{method:"POST",headers:{...i(),accept:"text/event-stream"},body:JSON.stringify(d),signal:c?.signal});if(!u.ok)throw await Be(u,e);if(!u.body)throw new Error(`openAICompatAdapter[${e}]: streaming response has no body`);let l,p;for await(let f of pt(u.body,{signal:c?.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:sr(l)})}yield{type:"finish",reason:p??"stop"}}}}function oa(t){let e=t.sdk;if(!e)throw new Error("sdkBackedOpenAI: sdk instance required");let{provider:n}=jo(t);return{provider:n,model:t.model,async invoke(r,o){let s=sn(r,o,t.model,!1,t.bodyExtras),i=K(),a=await e.chat.completions.create(s,{signal:o?.signal}),c=Math.max(0,(K()-i)/1e6);return $o(a,c,n)},async*stream(r,o){let s=sn(r,o,t.model,!0,t.bodyExtras),i=await e.chat.completions.create(s,{signal:o?.signal}),a,c;for await(let d of i){let u=d.choices;if(u){let p=u[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&&(c=p.finish_reason)}let l=d.usage;l&&(a=l,yield{type:"usage",usage:sr(l)})}yield{type:"finish",reason:c??"stop"}}}}function sa(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 Wn(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 nr(e)}case"dry-run":{let e={model:t.model,...t.extras};return Ze(e)}case"fallback":{let e={provider:t.provider,model:t.model,...t.extras};return tr(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 or(e)}default:{let e=t.provider;throw new Error(`createAdapter: unknown provider: ${String(e)}`)}}}ge();W();Se();se();ke();W();var ir=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 Nt(t){return t.subscribe(()=>{})}var ia=64;function Ge(t,e={}){let{name:n,maxSize:r,versioning:o,guard:s,backend:i}=e,a=i??new ir(t,r),c=P(a.toArray(),{name:n,describeKind:"state",equals:(T,w)=>T===w,...o!=null?{versioning:o}:{},...s!=null?{guard:s}:{}});function d(){let T=a.toArray();te(()=>{c.down([[Q]],{internal:!0}),c.down([[D,T]],{internal:!0})})}let u=new Map,l=new Map,p=new Map;function f(T,w){return`${T}:${w===void 0?"END":w}`}function m(T){if(T.size<ia)return;let w=T.keys().next();if(w.done)return;let k=T.get(w.value);k!==void 0&&k.dispose(),T.delete(w.value)}function h(T){let w=a.version;try{return T()}finally{a.version!==w&&d()}}function g(T){if(!Number.isInteger(T)||T<0)throw new RangeError(`tail: n must be a non-negative integer (got ${T})`);let w=u.get(T);if(w!==void 0)return u.delete(T),u.set(T,w),w.node;m(u);let k=C([c],([N])=>{let E=N;return T===0||E.length===0?[]:E.slice(Math.max(0,E.length-T))},{initial:a.tail(T),describeKind:"derived"}),M=Nt(k);return u.set(T,{node:k,dispose:M}),k}function y(T,w){if(!Number.isInteger(T)||T<0)throw new RangeError(`slice: start must be a non-negative integer (got ${T})`);if(w!==void 0&&(!Number.isInteger(w)||w<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${w})`);let k=f(T,w),M=l.get(k);if(M!==void 0)return l.delete(k),l.set(k,M),M.node;m(l);let N=C([c],([x])=>{let O=x;return w===void 0?O.slice(T):O.slice(T,w)},{initial:a.slice(T,w),describeKind:"derived"}),E=Nt(N);return l.set(k,{node:N,dispose:E}),N}function b(T){let w=p.get(T);if(w!==void 0)return w.node;let k=C([c,T],([N,E])=>{let x=N,O=Math.max(0,Math.trunc(E??0));return x.slice(O)},{initial:[],describeKind:"derived"}),M=Nt(k);return p.set(T,{node:k,dispose:M}),k}let v,R;function _(){v===void 0&&(v=ne([c],(T,w,k)=>{let M=T[0],E=M!=null&&M.length>0?M.at(-1):k.prevData[0];if(E==null||E.length===0){w.down([[U]]);return}w.emit(E[E.length-1])},{name:n!=null?`${n}::lastValue`:"lastValue",describeKind:"derived",initial:a.size===0?void 0:a.at(a.size-1)}),R=C([c],([T])=>T.length>0,{name:n!=null?`${n}::hasLatest`:"hasLatest",describeKind:"derived",initial:a.size>0}),Nt(v),Nt(R))}let S={entries:c,get size(){return a.size},at(T){return a.at(T)},append(T){h(()=>a.append(T))},appendMany(T){T.length!==0&&h(()=>a.appendMany(T))},clear(){h(()=>a.clear())},trimHead(T){h(()=>a.trimHead(T))},withLatest(){return _(),c},get lastValue(){return _(),v},get hasLatest(){return _(),R},view(T){switch(T.kind){case"tail":return g(T.n);case"slice":return y(T.start,T.stop);case"fromCursor":return b(T.cursor)}},attach(T){let w=T.subscribe(k=>{for(let M of k)M[0]===D&&S.append(M[1])});return()=>w()},attachStorage(T){if(T.length===0)return()=>{};let w=new Map;for(let M of T)w.set(M,a.size);(async()=>{for(let M of T)if(typeof M.loadEntries=="function")try{let N=await Promise.resolve(M.loadEntries());N.entries.length>0&&a.size===0&&(a.restore(N.entries),w.set(M,N.entries.length),d());break}catch{}})();let k=c.subscribe(M=>{for(let N of M){if(N[0]!==D)continue;let E=N[1];for(let x of T){let O=w.get(x)??0;if(E.length<O){try{let $=x.appendEntries(E);$ instanceof Promise&&$.catch(()=>{})}catch{}w.set(x,E.length);continue}if(E.length===O)continue;let V=E.slice(O);w.set(x,E.length);try{let $=x.appendEntries(V);$ instanceof Promise&&$.catch(()=>{})}catch{}}}});return()=>k()},disposeAllViews(){for(let T of u.values())T.dispose();u.clear();for(let T of l.values())T.dispose();l.clear();for(let T of p.values())T.dispose();p.clear()},dispose(){for(let T of u.values())T.dispose();u.clear();for(let T of l.values())T.dispose();l.clear();for(let T of p.values())T.dispose();p.clear()}};return S}ee();function De(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 Ve(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 Bo(){return{input:{regular:0},output:{regular:0}}}function aa(t,e){let n=e?.logMax??1e3,r=Ge(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:n}),o=P(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+De(y.usage),0),{name:"adapterStats/totalInputTokens",initial:0}),a=C([r.entries],([h])=>h.reduce((g,y)=>g+Ve(y.usage),0),{name:"adapterStats/totalOutputTokens",initial:0}),c=[J(s),J(i),J(a)],d=h=>{r.append(h),o.emit(h)},u=()=>{r.clear(),o.emit(null)},l=be(t,{invoke(h,g){let y=K(),b=ie(),v=t.model??g?.model??"",R=S=>(d(et({provider:t.provider,model:t.model??g?.model??S.model??"",tier:g?.tier??S.tier,usage:S.usage??Pe(),startNs:y,startWallClockNs:b,method:"invoke"})),S),_=S=>{let T=S;d(et({provider:t.provider,model:v,tier:g?.tier,usage:Pe(),startNs:y,startWallClockNs:b,method:"invoke",error:{type:T?.name??"Error",message:T?.message??String(S)}}))};return rn(t.invoke(h,g),{onResp:R,onError:_,name:"adapterStats/invokeTap"})},async*stream(h,g){let y=K(),b=ie(),v=t.model??g?.model??"",R;try{for await(let _ of t.stream(h,g))_.type==="usage"&&(R=_.usage),yield _;d(et({provider:t.provider,model:v,tier:g?.tier,usage:R??Pe(),startNs:y,startWallClockNs:b,method:"stream"}))}catch(_){let S=_;throw d(et({provider:t.provider,model:v,tier:g?.tier,usage:R??Pe(),startNs:y,startWallClockNs:b,method:"stream",error:{type:S?.name??"Error",message:S?.message??String(_)}})),_}}});ye(l,"observableAdapter",t);let p=!1;return{adapter:l,stats:{lastCall:o,allCalls:r,totalCalls:s,totalInputTokens:i,totalOutputTokens:a,reset:u,dispose:()=>{if(!p){p=!0;for(let h of c)h();c.length=0}}}}}function da(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function dn(t="USD"){return{total:0,currency:t}}function ar(t,e,n){let r=De(t),o=e.currency??"USD",s=n?.withBreakdown===!0,i=s?{}:null,a=0,c=(g,y,b)=>{if(!y||b==null)return;let v=da(b,r),R=y*v/1e6;a+=R,s&&(i[g]=(i[g]??0)+R)},d=t.input,u=e.input;if(u&&(c("input.regular",d.regular,u.regular),c("input.cacheRead",d.cacheRead??0,u.cacheRead),c("input.cacheWrite5m",d.cacheWrite5m??0,u.cacheWrite5m),c("input.cacheWrite1h",d.cacheWrite1h??0,u.cacheWrite1h),c("input.cacheWriteOther",d.cacheWriteOther??0,u.cacheWriteOther),c("input.audio",d.audio??0,u.audio),c("input.image",d.image??0,u.image),c("input.video",d.video??0,u.video),c("input.toolUse",d.toolUse??0,u.toolUse),d.extensions&&u.extensions))for(let[g,y]of Object.entries(d.extensions))c(`input.ext.${g}`,y,u.extensions[g]);let l=t.output,p=e.output;if(p&&(c("output.regular",l.regular,p.regular),c("output.reasoning",l.reasoning??0,p.reasoning),c("output.audio",l.audio??0,p.audio),c("output.predictionAccepted",l.predictionAccepted??0,p.predictionAccepted),c("output.predictionRejected",l.predictionRejected??0,p.predictionRejected),l.extensions&&p.extensions))for(let[g,y]of Object.entries(l.extensions))c(`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 an(t,e){return`${t}::${e}`}function ca(t){let e=new Map,n=new Map,r=(o,s,i)=>{e.set(an(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(an(o,s));if(i)return i.pricing;let a=n.get(o);if(!a)return;let c;for(let d of a)if(s.startsWith(d)&&(!c||d.length>c.key.length)){let u=e.get(an(o,d));u&&(c={key:d,pricing:u.pricing})}return c?.pricing},remove(o,s){let i=e.delete(an(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 ua(t,e="USD"){return(n,r)=>{let o=t.lookup(r.provider,r.model);return o?ar(n,o,{tier:r.tier,withBreakdown:r.withBreakdown}):dn(e)}}function la(...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):dn()}}function pa(t,e,n){return t?.pricing?ar(e,t.pricing,n):dn()}lt();ee();function dr(t,e={}){let n=e.breaker??kt(e),r=be(t,{async invoke(o,s){if(!n.canExecute())throw new Ke;try{let i=await Re(F(t.invoke(o,s)));return n.recordSuccess(),i}catch(i){throw n.recordFailure(i),i}},async*stream(o,s){if(!n.canExecute())throw new Ke;try{for await(let i of t.stream(o,s))yield i;n.recordSuccess()}catch(i){throw n.recordFailure(i),i}}});return ye(r,"withBreaker",t),{adapter:r,breaker:n}}ge();se();W();ee();var cn=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"},cr=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),Vo=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function ur(t,e){let n=Ge(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),r=P(Vo(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),o=C([r],([d])=>{let u=d;return!(e.caps.calls!=null&&u.calls>=e.caps.calls||e.caps.inputTokens!=null&&u.inputTokens>=e.caps.inputTokens||e.caps.outputTokens!=null&&u.outputTokens>=e.caps.outputTokens||e.caps.usd!=null&&u.usd>=e.caps.usd)},{name:e.name?`${e.name}/isOpen`:"budgetGate/isOpen",initial:!0});if(J(o),e.onExhausted!=null){let d=e.onExhausted,u=!1,l=!0;o.subscribe(p=>{for(let f of p)if(f[0]===D){let m=f[1];if(u&&l&&m===!1){let h=Ko(r.cache??cr,e.caps);h&&d(h)}l=m,u=!0}})}let s=()=>{if(o.cache===!1){let d=r.cache??cr,u=Ko(d,e.caps);return new cn(u??"budget",e.caps[u??"calls"]??0,fa(d,u??"calls"))}},i=(d,u)=>{let l=t.provider,p=et({provider:l,model:u.model,tier:u.tier,usage:d,startNs:u.startNs,method:u.method,...u.error?{error:u.error}:{}});n.append(p);let f=r.cache??cr,m=e.pricingFn?f.usd+e.pricingFn(d,{model:u.model,provider:l,tier:u.tier}).total:f.usd;r.emit({calls:f.calls+1,inputTokens:f.inputTokens+De(d),outputTokens:f.outputTokens+Ve(d),usd:m})},a=()=>{n.clear(),r.emit(Vo())},c=be(t,{invoke(d,u){let l=s();if(l)return Promise.reject(l);let p=K(),f=t.model??u?.model??"",m=g=>(i(g.usage??Pe(),{model:t.model??u?.model??g.model??"",tier:u?.tier??g.tier,startNs:p,method:"invoke"}),g),h=g=>{let y=g;i(Pe(),{model:f,tier:u?.tier,startNs:p,method:"invoke",error:{type:y?.name??"Error",message:y?.message??String(g)}})};return rn(t.invoke(d,u),{onResp:m,onError:h,name:"budgetGate/invokeTap"})},async*stream(d,u){let l=s();if(l)throw l;let p=K(),f;try{for await(let m of t.stream(d,u))m.type==="usage"&&(f=m.usage),yield m;i(f??Pe(),{model:t.model??u?.model??"",tier:u?.tier,startNs:p,method:"stream"})}catch(m){let h=m;throw i(f??Pe(),{model:t.model??u?.model??"",tier:u?.tier,startNs:p,method:"stream",error:{type:h?.name??"Error",message:h?.message??String(m)}}),m}}});return ye(c,"withBudgetGate",t),{adapter:c,budget:{totals:r,isOpen:o,log:n,reset:a}}}function Ko(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 fa(t,e){switch(e){case"calls":return t.calls;case"inputTokens":return t.inputTokens;case"outputTokens":return t.outputTokens;case"usd":return t.usd}}ee();function ma(t,e){let n=e.mock??Ze({provider:t.provider,model:t.model}),r=typeof e.enabled=="boolean"?e.enabled:void 0,o=r===void 0?F(e.enabled):void 0,s;o&&(s=J(o));let i=()=>r!==void 0?r:!!o?.cache,a=be(t,{invoke(d,u){return i()?n.invoke(d,u):t.invoke(d,u)},stream(d,u){return i()?n.stream(d,u):t.stream(d,u)}});return ye(a,"withDryRun",t),{adapter:a,dispose:()=>{s&&(s(),s=void 0)}}}function lr(t){if(t==null||typeof t!="object")return;let e=t,n=e.status,r=ga(e.headers);if(n!==429&&n!==503&&!wa(e.message))return;let o={},s=r("retry-after"),i=ya(s);i!=null&&(o.retryAfterMs=i);let a=r("anthropic-ratelimit-requests-reset");if(a){let f=zo(a);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let c=r("anthropic-ratelimit-tokens-reset");if(c){let f=zo(c);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let d=un(r,"x-ratelimit-limit-requests");d!=null&&(o.rpmCap=d);let u=un(r,"x-ratelimit-limit-tokens");u!=null&&(o.tpmCap=u);let l=un(r,"x-ratelimit-remaining-requests"),p=un(r,"x-ratelimit-remaining-tokens");if(l!=null&&d!=null&&d>0&&(o.usageHint??={},o.usageHint.rpm=1-l/d),p!=null&&u!=null&&u>0&&(o.usageHint??={},o.usageHint.tpm=1-p/u),o.retryAfterMs==null&&e.message){let f=Ta(e.message);f!=null&&(o.retryAfterMs=f)}return e.headers&&(o.metadata={headers:ha(e.headers)}),o.retryAfterMs==null&&o.rpmCap==null&&o.tpmCap==null&&o.usageHint==null?o.metadata?o:void 0:o}function ga(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 ha(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 un(t,e){let n=t(e);if(n==null)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function ya(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 zo(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var ba=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function Ta(t){let e=ba.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 va=/rate\s*limit|too\s*many\s*requests|quota|429/i;function wa(t){return!!t&&va.test(t)}ge();se();W();lt();ee();je();function pr(t){let e=new Error(t);return e.name="AbortError",e}function Ho(t={}){let e=Math.max(1,t.burstMultiplier??1),n=t.clampCooldownMs??6e4,r=t.rpm!=null?F(t.rpm):P(Number.POSITIVE_INFINITY),o=t.tpm!=null?F(t.tpm):P(Number.POSITIVE_INFINITY),s=P(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),i=P(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),a=P({},{name:"adaptiveRateLimiter/lastSignal"}),c=C([r,s],([x,O])=>Math.min(Number(x??1/0),Number(O??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),d=C([o,i],([x,O])=>Math.min(Number(x??1/0),Number(O??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),u=ft(Number(r.cache??Number.POSITIVE_INFINITY),e),l=ft(Number(o.cache??Number.POSITIVE_INFINITY),e),p=!1,f=!1,m=c.subscribe(x=>{for(let O of x)if(O[0]===D){let V=Number(O[1]);Number.isFinite(V)&&V>0?(u=ft(V,e),p=!1):V===1/0?(u=ft(1/0,e),p=!1):V<=0&&(p=!0)}}),h=d.subscribe(x=>{for(let O of x)if(O[0]===D){let V=Number(O[1]);Number.isFinite(V)&&V>0?(l=ft(V,e),f=!1):V===1/0?(l=ft(1/0,e),f=!1):V<=0&&(f=!0)}}),g=0,y=new ce,b=new ce,v;t.adaptation!=null&&(v=F(t.adaptation).subscribe(O=>{for(let V of O)V[0]===D&&R(V[1])}));function R(x){if(a.emit(x),x.rpmCap!=null&&Number.isFinite(x.rpmCap)&&x.rpmCap>=0&&(s.emit(x.rpmCap),Number.isFinite(n)&&n>0&&y.start(n,()=>s.emit(Number.POSITIVE_INFINITY))),x.tpmCap!=null&&Number.isFinite(x.tpmCap)&&x.tpmCap>=0&&(i.emit(x.tpmCap),Number.isFinite(n)&&n>0&&b.start(n,()=>i.emit(Number.POSITIVE_INFINITY))),x.retryAfterMs!=null&&x.retryAfterMs>0){let O=K()+x.retryAfterMs*1e6;O>g&&(g=O)}}let _=P(0,{name:"adaptiveRateLimiter/pending"}),S=P(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),T=P(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),w=x=>{_.emit((_.cache??0)+x)},k=()=>{S.emit(u.available()),T.emit(l.available())};async function M(x={}){let O=x.requestCost??1,V=x.tokenCost??0,$=x.signal;w(1);try{for(;;){if($?.aborted)throw pr("AdaptiveRateLimiter.acquire aborted");let Y=K();if(g>Y){let L=Math.ceil((g-Y)/1e6);await ln(L,$);continue}if(O>0&&p||V>0&&f){await ln(250,$);continue}let X=u,G=l;if(!X.tryConsume(O)){await ln(Uo(X,O),$);continue}if(!(V>0?G.tryConsume(V):!0)){X.putBack(O),await ln(Uo(G,V),$);continue}k();return}}finally{w(-1)}}function N(x){x>0?l.tryConsume(x):x<0&&l.putBack(-x),k()}function E(){m(),h(),v?.(),y.cancel(),b.cancel()}return{effectiveRpm:c,effectiveTpm:d,lastSignal:a,pending:_,rpmAvailable:S,tpmAvailable:T,acquire:M,recordUsage:N,recordSignal:R,dispose:E}}function ft(t,e){if(!Number.isFinite(t)||t===1/0)return xt(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let n=Math.max(1,t*e),r=t/60;return xt(n,r)}function Uo(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 ln(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(pr("AdaptiveRateLimiter.acquire aborted")):new Promise((n,r)=>{let o=new ce,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(pr("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",s,{once:!0}))})}ee();function fr(t,e={}){let n=e.limiter??Ho({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=lr(i);a&&n.recordSignal(a)},s=be(t,{async invoke(i,a){let c=r(i,a);await n.acquire({requestCost:1,tokenCost:c,signal:a?.signal});try{let d=await Re(F(t.invoke(i,a))),u=d.usage??Bo(),p=De(u)+Ve(u)-c;return p>0&&n.recordUsage(p),d}catch(d){throw o(d),d}},async*stream(i,a){let c=r(i,a);await n.acquire({requestCost:1,tokenCost:c,signal:a?.signal});try{let d=0;for await(let l of t.stream(i,a))l.type==="usage"&&(d=De(l.usage)+Ve(l.usage)),yield l;let u=d-c;u>0&&n.recordUsage(u)}catch(d){throw o(d),d}}});return ye(s,"withRateLimiter",t),{adapter:s,limiter:n}}lt();ee();var Mt=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 mr(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:kt(s.breaker):void 0})),r=e.streamRetryBeforeFirstChunk??!0,o={provider:"cascading",model:void 0,async invoke(s,i){let a=[],c=new Map;for(let u=0;u<n.length;u++){let l=n[u];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 Re(F(l.adapter.invoke(s,i)));return l.breaker?.recordSuccess(),{...p,metadata:{...p.metadata??{},tier:l.name}}}catch(p){c.set(l.name,p),l.breaker?.recordFailure(p);let f=n[u+1];f&&e.onFallback?.(l.name,f.name,p)}}let d={skipped:a,failed:c};throw e.onExhausted?.(d),new Mt(d)},async*stream(s,i){let a=[],c=new Map;for(let u=0;u<n.length;u++){let l=n[u];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(c.set(l.name,f),l.breaker?.recordFailure(f),p||!r)throw f;let m=n[u+1];m&&e.onFallback?.(l.name,m.name,f)}}let d={skipped:a,failed:c};throw e.onExhausted?.(d),new Mt(d)}};return ye(o,`cascade[${n.map(s=>s.name).join(",")}]`),o}function ka(t,e,n){let r={name:t,adapter:e};return n?.breaker&&(r.breaker=n.breaker),n?.filter&&(r.filter=n.filter),r}ee();je();function pn(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function qo(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(pn()):new Promise((n,r)=>{let o=new ce,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(pn())},e.addEventListener("abort",s,{once:!0}))})}function gr(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??xa,c=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)},u=be(t,{async invoke(l,p){if(p?.signal?.aborted)throw pn();let f,m=r;for(let h=1;h<=n;h++)try{return await Re(F(t.invoke(l,p)))}catch(g){if(f=g,h>=n||!a(g,h))throw g;let y=d(h,m);m=y,await qo(y,p?.signal)}throw f},async*stream(l,p){if(p?.signal?.aborted)throw pn();if(!c){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 qo(b,p?.signal)}}throw f}});return ye(u,"withRetry",t),u}function xa(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}ee();je();var mt=class extends Error{constructor(n){super(`LLM call timed out after ${n}ms`);this.ms=n}name="LLMTimeoutError"};function hr(t,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let n=s=>{let i=new AbortController,a=!1,c,d=new ce;return s&&(s.aborted?i.abort(s.reason):(c=()=>{d.cancel(),i.abort(s.reason)},s.addEventListener("abort",c,{once:!0}))),d.start(e,()=>{a=!0,i.abort(new mt(e))}),{signal:i.signal,cancel:()=>{d.cancel(),s&&c&&s.removeEventListener("abort",c)},timedOut:()=>a}},r=(s,i)=>{if(!i||s instanceof mt)throw s;let a=s;if(a?.name==="AbortError"||a?.name==="DOMException"&&Number(a.code)===20||s?.message==="aborted"){let d=new mt(e);throw d.cause=s,d}throw s},o=be(t,{async invoke(s,i){let{signal:a,cancel:c,timedOut:d}=n(i?.signal);try{return await Re(F(t.invoke(s,{...i,signal:a})))}catch(u){return r(u,d())}finally{c()}},async*stream(s,i){let{signal:a,cancel:c,timedOut:d}=n(i?.signal);try{for await(let u of t.stream(s,{...i,signal:a}))yield u}catch(u){r(u,d())}finally{c()}}});return ye(o,"withTimeout",t),o}function Ra(t,e={}){let n={adapter:t},r=t;if(e.rateLimit){let o=fr(r,e.rateLimit);r=o.adapter,n.rateLimiter=o.limiter}if(e.budget){let o=ur(r,e.budget);r=o.adapter,n.budget=o.budget}if(e.breaker){let o=dr(r,e.breaker);r=o.adapter,n.breaker=o.breaker}if(e.timeoutMs!=null&&(r=hr(r,e.timeoutMs)),e.retry&&(r=gr(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=mr([{name:e.name??"primary",adapter:r},{name:"fallback",adapter:e.fallback}],o)}return e.cache&&(r=_t(r,e.cache)),n.adapter=r,n}W();ee();function Sa(t,e,n){let r=F(e);return pe(r,s=>{if(!s||s.length===0)return P(null);let i=n?.tools;return t.invoke(s,{model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,tools:i,systemPrompt:n?.systemPrompt})})}Ae();ke();ee();se();ee();je();se();ee();function Wo(t,e){let n=t.cache??0;return n>=e?!1:(t.down([[Q],[D,n+1]]),!0)}function Fe(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}function H(t,e){return Fe("ai",t,e)}function _a(t){return t!=null&&typeof t.then=="function"}function yr(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function Na(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var Ma=3e4;function Jo(t,e){if(t.status==="settled"){let r=t.cache;if(r!==void 0)return Promise.resolve(r)}let n=e?.timeoutMs??Ma;return new Promise((r,o)=>{let s=new ce,i=t.subscribe(a=>{for(let c of a){if(c[0]===D){s.cancel(),i(),r(c[1]);return}if(c[0]===I){s.cancel(),i(),o(c[1]);return}if(c[0]===B){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 Et(t){return _a(t)?Et(await t):yr(t)?Jo(t):Na(t)?Jo(F(t)):t}function gt(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function Ea(t,e){let n=F(t),r=e?.refreshTrigger!=null?F(e.refreshTrigger):null,o=e?.name!==void 0?{name:e.name}:void 0,s=ae("frozenContext",o);return r==null?ne([n],(i,a,c)=>{if(c.store.emitted===!0)return;let u=i[0],l=u!=null&&u.length>0?u.at(-1):c.prevData[0];if(l!==void 0)return c.store.emitted=!0,a.emit(l),{invalidate:()=>{c.store.emitted=!1}}},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:H("frozen_context",{...s})}):ne([n,r],(i,a,c)=>{let d=i[1];if(!(d!=null&&d.length>0))return;let l=i[0],p=l!=null&&l.length>0?l.at(-1):c.prevData[0];a.emit(p)},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:H("frozen_context",{...s})})}se();W();ee();function Yo(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function Oa(t,e=200){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function br(t,e,n,r){let o=r?.format??"text",s=r?.name??"prompt_node",i=C(e,c=>{if(c.some(u=>u==null))return[];let d=typeof n=="string"?n:n(...c);return d?[{role:"user",content:d}]:[]},{name:`${s}::messages`,meta:H("prompt_node")});return pe(i,c=>!c||c.length===0?P(null):oe(d=>{let u=!1,l=!1,p,f={model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt};if(r?.abort){let y=ko(r.abort);f.signal=y.signal,p=y.dispose}let m;try{m=t.invoke(c,f)}catch(y){return u=!0,d.down([[I,y]]),()=>{p?.()}}let g=F(m).subscribe(y=>{if(!(l||u))for(let b of y){if(u)return;if(b[0]===D){let v=b[1];try{let R=Yo(v),_=o==="json"?JSON.parse(gt(R)):R;d.emit(_)}catch(R){let _=Yo(v),S=new Error(`promptNode: failed to parse LLM response as JSON: ${R.message}
|
|
7
|
+
Raw content (first 200 chars): ${Oa(_)}`);u=!0,d.down([[I,S]]);return}}else if(b[0]===I){u=!0,d.down([[I,b[1]]]);return}else if(b[0]===B){u=!0,d.down([[B]]);return}else d.down([b])}});return()=>{l=!0,g(),p?.()}},{name:`${s}::call`,meta:H("prompt_node::call")}),{name:`${s}::output`,meta:r?.meta?{...H("prompt_node::output"),...r.meta}:H("prompt_node::output")})}Se();ge();Ae();W();ee();Pt();at();se();W();var he={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},Aa=Symbol.for("sizeof");function Qo(t){let e=new WeakSet,n=new WeakSet,r=[t],o=0;for(;r.length>0;){let s=r.pop();o+=Ca(s,e,n,r)}return o}function Ca(t,e,n,r){if(t==null)return 0;switch(typeof t){case"number":return he.number;case"boolean":return he.boolean;case"string":return he.string+t.length*2;case"bigint":return he.bigint+La(t);case"symbol":return he.symbol;case"function":return e.has(t)?0:(e.add(t),he.function);case"undefined":return 0}let s=t;if(e.has(s))return 0;e.add(s);let i=s[Aa];if(typeof i=="function")try{let d=i.call(s);if(typeof d=="number"&&Number.isFinite(d))return d}catch{}if(s instanceof Date)return he.date;if(s instanceof RegExp)return he.regexp+s.source.length*2;if(s instanceof Error){let d=s.message?s.message.length*2:0,u=s.stack?s.stack.length*2:0;return he.error+d+u}if(typeof URL<"u"&&s instanceof URL)return he.url+s.href.length*2;if(typeof Promise<"u"&&s instanceof Promise)return he.promise;if(s instanceof WeakMap)return he.weakmap;if(s instanceof WeakSet)return he.weakset;if(s instanceof Map){let d=he.map;for(let[u,l]of s)d+=he.mapEntry,r.push(u),r.push(l);return d}if(s instanceof Set){let d=he.set;for(let u of s)d+=he.setEntry,r.push(u);return d}if(Array.isArray(s)){let d=he.array+s.length*8;for(let u of s)r.push(u);return d}if(s instanceof ArrayBuffer)return n.has(s)?0:(n.add(s),s.byteLength);if(ArrayBuffer.isView(s)){let d=s;return n.has(d.buffer)?48:(n.add(d.buffer),d.buffer.byteLength+48)}let a=he.object,c=Object.keys(s);for(let d of c){a+=he.string+d.length*2;try{r.push(s[d])}catch{}}return a}function La(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 Xo(t,e,n,r={}){let o=e in t.nodes,s=n in t.nodes;if(!o)return fn(e,n,"no-such-from");if(!s)return fn(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=Da(t,e,r);if(d!=null)return d}let c=mn(e,t.nodes[e],0,r);return gn(e,n,[c])}if(i===0)return fn(e,n,"no-path");let a=Zo(t,e,n,i);return a.found?gn(e,n,es(t,a.pathOrder,r)):fn(e,n,a.truncated?"max-depth-exceeded":"no-path")}function Zo(t,e,n,r){let o=new Map,s=[{path:n,depth:0}],i=new Set([n]),a=0,c=!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&&(c=!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:c};let d=[{path:e}],u=e;for(;u!==n;){let l=o.get(u);if(l==null)return{found:!1,pathOrder:[],truncated:!1};d[d.length-1].depIndices=l.depIndices,d.push({path:l.from}),u=l.from}return{found:!0,pathOrder:d,truncated:!1}}function Da(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=mn(e,r,0,n);a.dep_index=s[0];let c=mn(e,r,1,n);return gn(e,e,[a,c])}let i=null;for(let a=0;a<o.length;a++){let c=o[a];if(!c||c===e)continue;let d=Zo(t,c,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:gn(e,e,es(t,i.pathOrder,n))}function es(t,e,n){return e.map((r,o)=>{let s=t.nodes[r.path],i=mn(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 mn(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 gn(t,e,n){return ts(t,e,!0,"ok",n)}function fn(t,e,n){return ts(t,e,!1,n,[])}function ts(t,e,n,r,o){let s=Ia(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 Ia(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 c=` ${i.hop===0?"\xB7":"\u2193"} ${i.path} (${i.type}${i.status?`/${i.status}`:""})`;if(s.push(c),"value"in i&&s.push(` value: ${Pa(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(`
|
|
8
|
+
`)}function Pa(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)}}Pt();Se();ge();at();se();Ae();ke();W();ge();function Tr(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(!Tr(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)||!Tr(t[s],e[s]))return!1;return!0}function ns(t,e){return`${t}\0${e}`}function vr(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)),c=[];for(let g of a)i.has(g)||c.push(g);c.sort();for(let g of c)n.push({type:"node-added",path:g,node:{...e.nodes[g]}});let d=[];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||Tr(y??{},b??{})||d.push(g)}d.sort();for(let g of d)n.push({type:"node-meta-changed",path:g,prevMeta:t.nodes[g]?.meta??{},nextMeta:e.nodes[g]?.meta??{}});let u=new Map;for(let g of t.edges)u.set(ns(g.from,g.to),g);let l=new Map;for(let g of e.edges)l.set(ns(g.from,g.to),g);let p=[];for(let[g,y]of l)u.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 u)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:K()}}ee();je();An();function wr(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 hn(t){let e=0;for(let n of t)e+=wr(n.codePointAt(0));return e}function rs(t,e){if(e<=0)return"";let n=0,r="";for(let o of t){let s=wr(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-=wr(i.codePointAt(0))}return`${r}\u2026`}r+=o,n+=s}return r}var Ga={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"},Fa={horizontal:"-",vertical:"|",cornerTL:"+",cornerTR:"+",cornerBL:"+",cornerBR:"+",tDown:"+",tUp:"+",tRight:"+",tLeft:"+",cross:"+",arrowRight:">",arrowDown:"v",arrowLeft:"<",arrowUp:"^",boxTL:"+",boxTR:"+",boxBL:"+",boxBR:"+",boxH:"-",boxV:"|"};function as(t,e){let n=e.charset==="ascii"?Fa:Ga,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)ja(s,i,n,a);for(let a of t.boxes)$a(s,i,n,a,e.labelOf(a.id));return s.map(a=>za(a.join(""))).join(`
|
|
9
|
+
`)}function $a(t,e,n,r,o){let{x:s,y:i,w:a,h:c}=r;if(a<2||c<2){c>0&&os(t,e,s,i,a,o);return}ze(t,e,s,i,n.boxTL);for(let u=s+1;u<s+a-1;u+=1)ze(t,e,u,i,n.boxH);ze(t,e,s+a-1,i,n.boxTR);for(let u=i+1;u<i+c-1;u+=1){ze(t,e,s,u,n.boxV);for(let l=s+1;l<s+a-1;l+=1)ds(t,e,l,u," ","empty");ze(t,e,s+a-1,u,n.boxV)}ze(t,e,s,i+c-1,n.boxBL);for(let u=s+1;u<s+a-1;u+=1)ze(t,e,u,i+c-1,n.boxH);ze(t,e,s+a-1,i+c-1,n.boxBR);let d=i+Math.floor(c/2);os(t,e,s+1,d,a-2,o)}function ze(t,e,n,r,o){ds(t,e,n,r,o,o===" "?"empty":o==="\u2500"||o==="-"?"boxH":o==="\u2502"||o==="|"?"boxV":"boxCorner")}function ds(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 os(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=n,a=o;for(let c of s){let d=hn(c);if(d!==0){if(a<d)break;i>=0&&i<t[r].length&&(t[r][i]=c,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 ja(t,e,n,r){let o=r.points;if(o.length<2)return;for(let c=0;c+1<o.length;c+=1)Ba(t,e,n,o[c],o[c+1]);for(let c=1;c+1<o.length;c+=1){let d=o[c-1],u=o[c],l=o[c+1],p=Va(d,u,l,n);p&&is(t,e,u.x,u.y,p,"edgeCorner")}let s=o[o.length-1],i=o[o.length-2],a=Ka(i,s,n);a&&is(t,e,s.x,s.y,a,"arrow")}function Ba(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 c=i;c<=a;c+=1)ss(t,e,c,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 c=i;c<=a;c+=1)ss(t,e,s,c,n,"v")}}}function ss(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 is(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 Va(t,e,n,r){let o=t.y===e.y,s=e.y===n.y;if(o===s)return;if(o){let c=t.x<e.x,d=n.y>e.y;return c&&d?r.cornerTR:c&&!d?r.cornerBR:!c&&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 Ka(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 za(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===32;)e-=1;return t.slice(0,e)}function ls(t){let e=Ua(t);Ha(e),qa(e),Wa(e),Ja(e,t);let n=Xa(e,t),{width:r,height:o}=ed(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 Ua(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 Ha(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 c=(e.get(a.id)??0)-1;e.set(a.id,c),c<=0&&n.push(a)}}}for(let s of t.nodes.values())s.layer<0&&(s.layer=0)}function qa(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),c=a.layer-i.layer;if(c<=0){i.out=i.out.filter(l=>l!==s),a.in=a.in.filter(l=>l!==s);continue}if(c===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<c;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:c};d.out.push(m),f.in.push(m),r.push(m),d=f}let u={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:d.id,toId:a.id,hopIndex:c-1,chainLen:c};d.out.push(u),a.in.push(u),r.push(u)}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 Wa(t){for(let n=0;n<4;n+=1){for(let r=1;r<t.layers.length;r+=1)cs(t,t.layers[r],"in"),yn(t.layers[r]);for(let r=t.layers.length-2;r>=0;r-=1)cs(t,t.layers[r],"out"),yn(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=us(t,s[i],s[i+1],"in");[s[i],s[i+1]]=[s[i+1],s[i]],yn(s),us(t,s[i],s[i+1],"in")<a?r=!0:([s[i],s[i+1]]=[s[i+1],s[i]],yn(s))}}if(!r)break}}function cs(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 c of s){let d=t.nodes.get(n==="in"?c.fromId:c.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 yn(t){for(let e=0;e<t.length;e+=1)t[e].order=e}function us(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 c of s){let d=t.nodes.get(r==="in"?a.fromId:a.toId)?.order??0,u=t.nodes.get(r==="in"?c.fromId:c.toId)?.order??0;(e.order<n.order&&d>u||e.order>n.order&&d<u)&&(i+=1)}return i}function Ja(t,e){e.direction==="LR"?Ya(t,e):Qa(t,e)}function Ya(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}ps(t,e,"y")}function Qa(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}ps(t,e,"x")}function ps(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 c=new Map;for(let u of a){let l=s===0?u.in:u.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)];c.set(u.id,f-Math.floor(r(u)/2))}let d=0;for(let u of a){let l=c.get(u.id),p=n==="y"?u.y:u.x,m=Math.max(l??p,d);n==="y"?u.y=m:u.x=m,d=m+r(u)+o}}}}function Xa(t,e){let n=new Map;for(let d of t.hops){let u=n.get(d.chainId);u?u.push(d):n.set(d.chainId,[d])}for(let d of n.values())d.sort((u,l)=>u.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 u=t.layers[d],l=t.layers[d+1],p=0;for(let w of u)p=Math.max(p,o(w)+s(w));let f=Number.POSITIVE_INFINITY;for(let w of l)f=Math.min(f,o(w));let m=Number.isFinite(f)?f-1:p,h=Math.max(1,m-p+1),g=[];for(let w of u)for(let k of w.out)g.push(k);g.sort((w,k)=>{let M=i(t.nodes.get(w.fromId)),N=i(t.nodes.get(k.fromId));if(M!==N)return M-N;let E=i(t.nodes.get(w.toId)),x=i(t.nodes.get(k.toId));return E-x});let y=[],b=new Map;for(let w of g){let k=i(t.nodes.get(w.fromId)),M=i(t.nodes.get(w.toId)),N=Math.min(k,M),E=Math.max(k,M),x=-1;for(let O=0;O<y.length;O+=1){let V=y[O],$=!0;for(let Y of V)if(Y.lo<=E&&N<=Y.hi){$=!1;break}if($){V.push({lo:N,hi:E}),x=O;break}}x<0&&(y.push([{lo:N,hi:E}]),x=y.length-1),b.set(w,x)}let v=y.length,R=h>=Math.max(3,v+2),_=R?p+1:p,S=R?m-1:m,T=Math.max(1,S-_+1);for(let w of g){let k=b.get(w),M;if(v<=1)M=_+Math.floor(T/2);else{let N=(T-1)/(v-1);M=_+Math.floor(k*N)}a.set(w,Math.max(p,Math.min(m,M)))}}let c=[];for(let[,d]of n){let u=[];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),R=i(h);p===0&&bn(u,r,y,v),v!==R&&(bn(u,r,g,v),bn(u,r,g,R)),bn(u,r,b,R)}let l=d[0];c.push({from:l.chainFrom,to:l.chainTo,points:Za(u)})}return c}function bn(t,e,n,r){t.push(e?{x:n,y:r}:{x:r,y:n})}function Za(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 ed(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 td=24,nd=4,rd=1,od=3;function fs(t,e){let n=sd(e.direction),r=Math.max(3,e.maxLabelWidth??td),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)),c=new Map,d=new Map;for(let f of s){let m=rs(f,r);c.set(f,m),d.set(f,hn(m)+4)}let u=ls({nodes:s,edges:a,widthCells:f=>d.get(f)??3,heightCells:()=>od,layerGap:nd,nodeGap:rd,direction:n}),l=as(u,{charset:o,labelOf:f=>c.get(f)??f}),p=e.logger;return p&&p(l),l}function sd(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)}`)}ke();function ms(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 le?m:null,g=h?Qo(h.cache):0,y=h?h._sinkCount:0,b=f.deps?.length??0,v=f.type==="effect"&&y===0,R=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:R})}let c=a.reduce((p,f)=>p+f.valueSizeBytes,0),d=(p,f)=>[...a].sort(f??((m,h)=>h[p]-m[p])).slice(0,n),u=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:c,hotspots:{byValueSize:d("valueSizeBytes"),bySubscriberCount:d("subscriberCount"),byDepCount:d("depCount")},orphans:u,orphanEffects:l}}var de="::",_e="__meta__",nt=1;function gs(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 bs(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"&&typeof t.down=="function"}function id(t){if(t!=null)return bs(t)?t.cache:t}function ad(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(`
|
|
10
|
+
`)}function hs(t){if(t.version!==nt)throw new Error(`unsupported snapshot version ${String(t.version)} (expected ${nt})`);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 dd(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,c=s.constructor;if(a!==c)return!1;if(o instanceof Date)return o.getTime()===s.getTime();if(o instanceof RegExp)return o.source===s.source&&o.flags===s.flags;if(Array.isArray(o)){let p=s;if(o.length!==p.length)return!1;for(let f=0;f<o.length;f++)if(!r(o[f],p[f]))return!1;return!0}if(o instanceof Map){let p=s;if(o.size!==p.size)return!1;for(let[f,m]of o)if(!p.has(f)||!r(m,p.get(f)))return!1;return!0}if(o instanceof Set){let p=s;if(o.size!==p.size)return!1;for(let f of o){let m=!1;for(let h of p)if(r(f,h)){m=!0;break}if(!m)return!1}return!0}if(ArrayBuffer.isView(o)){let p=o,f=s;if(p.length!==f.length)return!1;for(let m=0;m<p.length;m++)if(p[m]!==f[m])return!1;return!0}let d=Object.keys(o),u=Object.keys(s);if(d.length!==u.length)return!1;let l=new Set(u);for(let p of d)if(!l.has(p)||!r(o[p],s[p]))return!1;return!0};return r(t,e)}function xr(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(xr);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=xr(e[o]);return r}function cd(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function ud(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function ld(t){return t==="TD"?"down":t==="BT"?"up":t==="RL"?"left":"right"}function Ts(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 vs(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 pd(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(xr(i),null,e.indent??2);return e.logger?.(a),a}function fd(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}): ${vn(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(`
|
|
11
|
+
`);return e.logger?.(s),s}function ws(t,e){let n=vs(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}["${cd(i)}"]`)}for(let[i,a]of Ts(t)){let c=o.get(i),d=o.get(a);!c||!d||s.push(` ${c} --> ${d}`)}return s.join(`
|
|
12
|
+
`)}function md(t,e){let n=ws(t,e);return ks(n)}function ks(t,e){let n=e?.theme??"default",r=e?.autoSync??!0,s=JSON.stringify({code:t,mermaid:{theme:n},autoSync:r}),i=new TextEncoder().encode(s),a="";for(let d=0;d<i.length;d++)a+=String.fromCharCode(i[d]);return`https://mermaid.live/edit#base64:${globalThis.btoa(a).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`}function gd(t,e){let n=vs(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: ${ld(n)}`];for(let i of r){let a=o.get(i);s.push(`${a}: "${ud(i)}"`)}for(let[i,a]of Ts(t)){let c=o.get(i),d=o.get(a);!c||!d||s.push(`${c} -> ${d}`)}return s.join(`
|
|
13
|
+
`)}function hd(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Tn(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+=hd(r)}return e+="$",new RegExp(e)}var yd={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"},bd={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function vn(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 Td(t){return t==="none"?bd:t==="ansi"||t==null?yd:{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 ys(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 vd(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 kr(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===_e)throw new Error(`Graph "${e}": ${n} name "${_e}" is reserved for meta companion paths`);vd(t,e,n)}function wd(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 kd(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 xs(t){for(let e of t._mounts.values())xs(e);for(let e of t._nodes.values())try{e.down([[me]],{internal:!0})}catch{}}var ue=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(de))throw new Error(`Graph name must not contain '${de}' (got "${e}")`);if(e===_e)throw new Error(`Graph name "${_e}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...n??{}}),this.config=n?.config??dt,this._traceRing=new St(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=oe(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(kr(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:K()})),e}setVersioning(e){if(e!=null)for(let n of this._nodes.values())n instanceof le&&n._applyVersioning(e)}remove(e){kr(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,c]of i)a.includes(`${de}${_e}${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,xs(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([[me]],{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=Tn(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([[D,n]],{actor:r?.actor,internal:o,delivery:"write"})}setAll(e,n){let r=Symbol.iterator in e?e:Object.entries(e);te(()=>{for(let[o,s]of r)this.set(o,s,n)})}invalidate(e,n){let r=n?.internal===!0;this.node(e).down([[Me]],{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([[B]],{actor:n?.actor,internal:r,delivery:"write"})}edges(e){let n=e?.recursive===!0,r=new Map;if(!n){for(let[c,d]of this._nodes)r.set(d,c);let a=[];for(let[c,d]of this._nodes)if(d instanceof le)for(let u of d._deps){let l=r.get(u.node);l!=null&&a.push([l,c])}return a.sort((c,d)=>c[0]<d[0]?-1:c[0]>d[0]?1:c[1]<d[1]?-1:c[1]>d[1]?1:0),a}let o=[];this._collectObserveTargets("",o);let s=new Map;for(let[a,c]of o)s.set(c,a);let i=[];for(let[a,c]of o)if(c instanceof le)for(let d of c._deps){let u=s.get(d.node);u!=null&&i.push([u,a])}return i.sort((a,c)=>a[0]<c[0]?-1:a[0]>c[0]?1:a[1]<c[1]?-1:a[1]>c[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(kr(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=wd(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]===_e)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]!==_e)throw new Error(`Graph "${this.name}": expected ${_e} segment in meta path "${r}"`);if(s+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${_e} in "${r}"`);let a=i[s+1],c=o.meta[a];if(!c)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${r}"`);o=c,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 c of this._mounts.values())c._signalDeliver(e,n,r,o);let i=n.internal===!0?{internal:!0}:{actor:n.actor,delivery:"signal"},a=kd(e,this.config);for(let c of[...this._nodes.keys()].sort()){let d=this._nodes.get(c);if(!r.has(d)){r.add(d);try{d.down(e,i)}catch(u){if(u instanceof Oe)throw u;o.push(u)}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(c){if(c instanceof Oe)throw c;s.push(c)}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=id(e?.actor),r=e?.filter,o=Ht(e?.detail,e?.fields),s=e?.format==="spec",i=s?Ht("minimal"):o,a=[];this._collectObserveTargets("",a);let c=new Map;for(let[S,T]of a)c.set(T,S);let d=[];{let S=a.map(([,k])=>k),T=new Set(c.values()),w=0;for(;S.length>0;){let k=S.shift();if(k instanceof le)for(let M of k._deps){let N=M.node;if(c.has(N))continue;let E=N.name??"",x=E;if(!x||T.has(x))if(E){let O=2;for(;T.has(`${E}#${O}`);)O++;x=`${E}#${O}`}else for(x=`__internal__/${w++}`;T.has(x);)x=`__internal__/${w++}`;c.set(N,x),T.add(x),d.push([x,N]),S.push(N)}}}let u=[...a,...d],l={};for(let[S,T]of u){if(n!=null&&!T.allowsObserve(n))continue;let w=zn(T,i),k=T instanceof le?T._deps.map(x=>c.get(x.node)??x.node.name??""):[],{name:M,...N}=w,E={...N,deps:k};if(!s){let x=this._annotations.get(S);x!=null&&(E.annotation=x)}if(r!=null)if(typeof r=="function"){let x=r;if(!(x.length>=2?x(S,E):x(E)))continue}else{let x=!0;for(let[O,V]of Object.entries(r)){let $=O==="deps_includes"?"depsIncludes":O==="meta_has"?"metaHas":O;if($==="depsIncludes"){if(!E.deps.includes(String(V))){x=!1;break}continue}if($==="metaHas"){if(!Object.hasOwn(E.meta??{},String(V))){x=!1;break}continue}if(E[$]!==V){x=!1;break}}if(!x)continue}l[S]=E}let p=new Set(Object.keys(l)),f=[];for(let[S,T]of u)if(T instanceof le)for(let w of T._deps){let k=c.get(w.node);k!=null&&f.push([k,S])}f.sort((S,T)=>S[0]<T[0]?-1:S[0]>T[0]?1:S[1]<T[1]?-1:S[1]>T[1]?1:0);let m=f.map(([S,T])=>({from:S,to:T}));(n!=null||r!=null)&&(m=m.filter(S=>p.has(S.from)&&p.has(S.to)));let h=this._collectSubgraphs(""),g=n!=null||r!=null?h.filter(S=>{let T=`${S}${de}`;return[...p].some(w=>w===S||w.startsWith(T))}):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(S){let T={...b,format:void 0};return Array.isArray(S)?(T.fields=S,T.detail=void 0):(T.detail=S,T.fields=void 0),y.describe(T)}},R=e??{},_=R.format;return _==="json"?pd(v,R):_==="pretty"?fd(v,R):_==="mermaid"?ws(v,R):_==="mermaid-url"?md(v,R):_==="d2"?gd(v,R):_==="ascii"?fs(v,R):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 ms(this,e)}reachable(e,n,r={}){return r.withDetail===!0?Rr(this.describe(),e,n,{...r,withDetail:!0}):Rr(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,c]of Object.entries(o.nodes))c.lastMutation!=null&&i.set(a,c.lastMutation);return Xo(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=P(o,{name:`${r}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,c=!1,d=()=>{a||c||(a=!0,it(()=>{a=!1,!c&&(o+=1,s.emit(o))}))},u=i.onEvent(b=>{let v=b.type;v!=="data"&&v!=="error"&&v!=="complete"&&v!=="teardown"||d()}),l=[],p=new WeakSet,f=b=>{if(p.has(b)||c)return;p.add(b);let v=b.topology.subscribe(R=>{for(let _ of R){if(_[0]!==D)continue;let S=_[1];if(d(),S.kind==="added"&&S.nodeKind==="mount"){let T=b._mounts.get(S.name);T!=null&&f(T)}}});l.push(v);for(let R of b._mounts.keys()){let _=b._mounts.get(R);_!=null&&f(_)}};f(this);let m,h=e.actor;bs(h)&&(m=h.subscribe(b=>{let v=!1,R=!1;for(let _ of b){let S=_[0];S===D?v=!0:(S===B||S===I||S===me)&&(R=!0)}v&&d(),R&&(m?.(),m=void 0,d())}));let g;try{g=C([s],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(b,v)=>b===v})}catch(b){u(),m?.();for(let v of l)v();throw i.dispose(),b}let y=J(g);return{node:g,dispose(){c=!0,u(),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=vr(o,s),a=P(i,{name:r,meta:{domain:"audit",kind:"describe-diff"},equals:(p,f)=>p===f}),c=this._describeReactive({...e,format:void 0,reactiveName:void 0}),d=!1,u=c.node.subscribe(p=>{if(!d)for(let f of p){if(f[0]!==D)continue;let m=f[1],h=vr(s,m);s=m,h.events.length!==0&&a.emit(h)}}),l=J(a);return{node:a,dispose(){d=!0,u(),c.dispose(),a.down([[me,"describe-diff disposed"]]),l()}}}_explainReactive(e,n,r){let o=0,s=P(o,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,c=!1,d=i.onEvent(f=>{let m=f.type;m!=="data"&&m!=="error"&&m!=="complete"&&m!=="teardown"||a||c||(a=!0,it(()=>{a=!1,!c&&(o+=1,s.emit(o))}))}),u={...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{}},l;try{l=C([s],()=>this._explainStatic(e,n,u),{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&&xd(f.steps,m.steps)})}catch(f){throw d(),i.dispose(),f}let p=J(l);return{node:l,dispose(){c=!0,d(),i.dispose(),p()}}}_pathsMatching(e){let n=Tn(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}${_e}${de}${o}`;r.push([i,s]),this._appendMetaObserveTargets(i,s,r)}}observe(e,n){let r=typeof e=="string",s=ys(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 u=e,l=this.resolve(u);if(a!=null&&!l.allowsObserve(a))throw new Oe({actor:a,action:"observe",nodeName:u});return i?this._buildStructuredObserver([[u,l]],s,"one"):{subscribe(p){return l.subscribe(p)},up(p){try{l.up?.(p)}catch(f){if(f instanceof Oe)return;throw f}}}}let c=[];this._collectObserveTargets("",c),c.sort((u,l)=>u[0]<l[0]?-1:u[0]>l[0]?1:0);let d=a==null?c:c.filter(([,u])=>u.allowsObserve(a));return i?this._buildStructuredObserver(d,s,"all"):{subscribe:u=>{let l=d.map(([p,f])=>f.subscribe(m=>{u(p,m)}));return()=>{for(let p of l)p()}},up:(u,l)=>{try{this.resolve(u).up?.(l)}catch(p){if(p instanceof Oe)return;throw p}}}}_observeReactive(e,n){let r=n.tiers,o=r!=null?new Set(r):null,s=n.reactiveName??"observe";return oe(i=>{let a=[],c=!1,d=!1,u=()=>{if(a.length===0||d)return;let h={events:a.slice(),flushedAt_ns:K()};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=>{d||(a.push(h),!c&&(c=!0,it(()=>{c=!1,u()})))};for(let h of p.events)f(h);let m=p.onEvent(f);return()=>{d=!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 u=this.resolve(o);return this._buildStructuredObserver([[o,u]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((u,l)=>u[0]<l[0]?-1:u[0]>l[0]?1:0);let c=i.actor,d=c==null?a:a.filter(([,u])=>u.allowsObserve(c));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",c=this.config.inspectorEnabled,d=(s||i)&&c,u=n.maxEvents,l=u!=null&&u>0?new St(u):null,p=[],f=new Set,m=n.tiers!=null?new Set(n.tiers):null,h={},g=new Set,y=0,b=0,v=0,R=0,_=0,S=0,T=!1,w=!1,k=0,M=new Map,N=new Map,E=new Map,x=j=>{if(!(m!=null&&!m.has(j.type))){l?l.push(j):p.push(j);for(let Z of f)Z(j)}},O=j=>m==null||m.has(j),V=()=>o?{timestamp_ns:K(),in_batch:Gt(),batch_id:k}:{},$=(j,Z)=>{if(!(!d||!(j instanceof le)))return j._setInspectorHook(ve=>{if(ve.kind==="dep_message")M.set(j,ve.depIndex);else if(ve.kind==="run"){let He=ve.batchData.map((re,we)=>re!=null&&re.length>0?re.at(-1):ve.prevData[we]);N.set(j,He);let Ne=ve.batchData.map(re=>re!=null?[...re]:void 0);E.set(j,Ne),i&&x({type:"derived",path:Z,dep_values:He,dep_batches:Ne,...V()})}})},Y=j=>{let Z=M.get(j),ve=N.get(j);if(!s||ve==null)return{};let Ne=(Z!=null&&Z>=0&&j instanceof le?j._deps[Z]:void 0)?.node,re=Ne?.v,we=E.get(j);return{trigger_dep_index:Z,trigger_dep_name:Ne?.name,...re!=null?{trigger_version:{id:re.id,version:re.version}}:{},dep_values:[...ve],...we!=null?{dep_batches:we}:{}}},X=[],G=[];for(let[j,Z]of e){let ve=$(Z,j);ve&&X.push(ve),G.push(Z.subscribe(He=>{k++;for(let Ne of He){let re=Ne[0],we=V();if(re===D){h[j]=Ne[1];let Nn=Z instanceof le?Z.lastMutation?.actor??rt:rt;x({type:"data",path:j,data:Ne[1],actor:Nn,...we,...Y(Z)})}else if(a)re===Q?O("dirty")&&y++:re===U?O("resolved")&&b++:re===Me?O("invalidate")&&v++:re===Ee?O("pause")&&R++:re===Ie?O("resume")&&_++:re===me?O("teardown")&&S++:re===B&&!g.has(j)?O("complete")&&(T=!0):re===I&&O("error")&&(w=!0,g.add(j));else if(re===Q)O("dirty")&&y++,x({type:"dirty",path:j,...we});else if(re===U)O("resolved")&&b++,x({type:"resolved",path:j,...we,...Y(Z)});else if(re===Me)O("invalidate")&&v++,x({type:"invalidate",path:j,...we});else if(re===Ee)O("pause")&&R++,x({type:"pause",path:j,lockId:Ne[1],...we});else if(re===Ie)O("resume")&&_++,x({type:"resume",path:j,lockId:Ne[1],...we});else if(re===B)O("complete")&&!g.has(j)&&(T=!0),x({type:"complete",path:j,...we});else if(re===I){O("error")&&(w=!0,g.add(j));let Nn=Z instanceof le?Z.lastMutation?.actor??rt:rt;x({type:"error",path:j,data:Ne[1],actor:Nn,...we})}else re===me&&(O("teardown")&&S++,x({type:"teardown",path:j,...we}))}}))}let z=!1,A=()=>{if(!z){z=!0;for(let j of G)j();for(let j of X)j();for(let j of q)j({value:void 0,done:!0});q.length=0}},L=[],q=[];f.add(j=>{let Z=q.shift();Z?Z({value:j,done:!1}):L.push(j)});let fe={get values(){return h},get dirtyCount(){return y},get resolvedCount(){return b},get invalidateCount(){return v},get pauseCount(){return R},get resumeCount(){return _},get teardownCount(){return S},get events(){return l?l.toArray():[...p]},get anyCompletedCleanly(){return T},get anyErrored(){return w},get completedWithoutErrors(){return T&&!w},onEvent(j){return f.add(j),()=>f.delete(j)},dispose:A,expand(j){A();let Z={...n};return typeof j=="string"?Z.detail=j:Object.assign(Z,j),r(ys(Z))},[Symbol.asyncIterator](){return{next(){return L.length>0?Promise.resolve({value:L.shift(),done:!1}):z?Promise.resolve({value:void 0,done:!0}):new Promise(j=>q.push(j))},return(){return A(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger(fe,n),fe}_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)),c=Td(n.theme),d=r==="stage-log"?K():0,u=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(vn(m.data),120):"",f=m=>{if(r==="stage-log"){let T=(K()-d)/1e9,w=u(m.path).padEnd(9);if(m.type==="data"){let k=p(m);return`[${T.toFixed(3)}s] ${w} \u2190${k?` ${k}`:""}`}if(m.type==="error"){let k=p(m);return`[${T.toFixed(3)}s] ${w} \u2717${k?` ${k}`:""}`}return m.type==="complete"?`[${T.toFixed(3)}s] ${w} \u25A0 complete`:`[${T.toFixed(3)}s] ${w} ${m.type}`}if(r==="json")try{return JSON.stringify(m)}catch{return JSON.stringify({type:m.type,path:m.path,data:"[unserializable]"})}let h=c[m.type]??"",g=m.path?`${c.path}${m.path}${c.reset} `:"",y=m.type==="data"||m.type==="error",b=m.type==="pause"||m.type==="resume",v=y?` ${vn(m.data)}`:b?` ${vn(m.lockId)}`:"",R=m.type==="data"||m.type==="resolved"||m.type==="derived"?m:void 0,_=R?.trigger_dep_name!=null?` <- ${R.trigger_dep_name}`:R?.trigger_dep_index!=null?` <- #${R.trigger_dep_index}`:"",S=m.in_batch?" [batch]":"";return`${g}${h}${m.type.toUpperCase()}${c.reset}${v}${_}${S}`};e.onEvent(m=>{a(m.type)&&o(f(m),m)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){gs(this._disposers,this.name),this.signal([[me]],{internal:!0}),gs(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:c,guard:d,...u}=r.nodes[a];o[a]=u}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 Kr(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,n){let r=n?.config??dt,{codec:o,codecVersion:s,payload:i}=zr(e,r);return o.decode(i,s)}restore(e,n){if(hs(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=>Tn(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 c=this.tryResolve(s)?.v;if(c!=null&&c.id===i.v.id&&c.version===i.v.version)continue}try{this.set(s,i.value)}catch(a){n?.onError?.(s,a)}}}}}static fromSnapshot(e,n){hs(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:Tn(f),factory:m})):[],a=f=>{for(let m of i)if(m.re.test(f))return m.factory},c=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}${_e}${de}`)).sort((f,m)=>f[0]<m[0]?-1:f[0]>m[0]?1:0),u=new Map(d),l=new Map,p=!0;for(;u.size>0&&p;){p=!1;for(let[f,m]of[...u.entries()]){let h=m?.deps??[];if(!h.every(_=>l.has(_)))continue;let[g,y]=c(f),b={...m?.meta??{}},v=a(f),R;if(m?.type==="state")R=P(m.value,{meta:b});else{if(v==null)continue;R=v(y,{path:f,type:m.type,value:m.value,meta:b,deps:h,resolvedDeps:h.map(_=>l.get(_))})}g.add(R,{name:y}),l.set(f,R),u.delete(f),p=!0}}if(u.size>0){let f=[...u.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,u)=>{if(d.disposed)return;let l=ad(u.nodes);if(d.lastSnapshot!=null&&l!==""&&l===d.lastFingerprint)return;let p=d.seq+1,f=ie(),g=d.lastSnapshot==null||p%d.compactEvery===0?{name:this.name,mode:"full",snapshot:u,seq:p,timestamp_ns:f,format_version:nt}:{name:this.name,mode:"diff",diff:Rs(d.lastSnapshot,u),seq:p,timestamp_ns:f,format_version:nt};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 R=(d.savePending??Promise.resolve()).then(()=>y,()=>y).then(()=>{d.disposed||(d.seq=p,d.lastSnapshot=u,d.lastFingerprint=l)},_=>{n.onError?.(_,d.tier)});d.savePending=R.finally(()=>{d.savePending===R&&(d.savePending=void 0)})}else d.seq=p,d.lastSnapshot=u,d.lastFingerprint=l},s=(d,u)=>{try{o(d,u)}catch(l){n.onError?.(l,d.tier)}},i=(d,u)=>{if(!u.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=zn(m,Ht("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 ce),m.timer.start(m.debounceMs,()=>{m.disposed||s(m,this.snapshot())})))},a;if(n.paths!=null){let u=(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 u)l()}}else a=this.observe().subscribe((d,u)=>i(d,u));let c=()=>{a();for(let d of r)d.disposed=!0,d.timer?.cancel();this._storageDisposers.delete(c)};return this._storageDisposers.add(c),{dispose:c}}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===nt&&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(c){r?.onError?.(c,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===nt&&i.nodes!=null?i:void 0;if(a!=null)try{return t.fromSnapshot(a,r)}catch(c){r?.onError?.(c,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:K(),...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=[],c=[];for(let b of r){if(!o.has(b))continue;let v=e.nodes[b],R=n.nodes[b],_=v.v,S=R.v;_!=null&&S!=null&&_.id===S.id&&_.version!==S.version&&c.push({path:b,id:_.id,from:_.version,to:S.version});let T=_!=null&&S!=null&&_.id===S.id&&_.version===S.version;for(let w of["type","status","sentinel"]){let k=v[w],M=R[w];k!==M&&a.push({path:b,field:w,from:k,to:M})}if(!T)for(let w of["value","meta"]){let k=v[w],M=R[w];dd(k,M)||a.push({path:b,field:w,from:k,to:M})}}let d=b=>`${b.from} ${b.to}`,u=new Set(e.edges.map(d)),l=new Set(n.edges.map(d)),p=n.edges.filter(b=>!u.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:c,edgesAdded:p,edgesRemoved:f,subgraphsAdded:g,subgraphsRemoved:y}}};function Rs(t,e){let n=ue.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 Rr(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,c=new Map,d=new Map,u=new Set;for(let[v,R]of Object.entries(t.nodes)){if(!v)continue;u.add(v);let _=R.deps??[];i.set(v,_);for(let S of _)S&&(u.add(S),a.has(S)||a.set(S,new Set),a.get(S).add(v))}for(let v of t.edges){if(v==null||typeof v!="object")continue;let R=typeof v.from=="string"?v.from:"",_=typeof v.to=="string"?v.to:"";!R||!_||(u.add(R),u.add(_),d.has(R)||d.set(R,new Set),d.get(R).add(_),c.has(_)||c.set(_,new Set),c.get(_).add(R))}if(!u.has(e))return r.withDetail?o:[];let l=r.both===!0,p=v=>{if(l){let T=i.get(v)??[],w=c.get(v),k=a.get(v),M=d.get(v),N=[...T];return w&&N.push(...w),k&&N.push(...k),M&&N.push(...M),N}if(n==="upstream"){let T=i.get(v)??[],w=c.get(v);return w?[...T,...w]:T}let R=a.get(v),_=d.get(v),S=R?[...R]:[];return _&&S.push(..._),S},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 R of p(v.path))!R||f.has(R)||(f.add(R),m.set(R,v.depth+1),h.push({path:R,depth:v.depth+1}))}let b=[...m.keys()].sort((v,R)=>v<R?-1:v>R?1:0);return r.withDetail?{paths:b,depths:m,truncated:y}:b}function xd(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}function Ss(t,e){return Fe("messaging",t,e)}var Rd=1024,Sr=class extends ue{_log;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=Ge([],{name:"events",maxSize:n.retainedLimit??Rd}),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:Ss("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(J(this.latest)),this.hasLatest=C([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:Ss("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(J(this.hasLatest)),this.addDisposer(()=>{this.events.down([[B]])}),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}};function _r(t,e){return new Sr(t,e)}Se();ge();se();Ae();ke();W();Se();ge();at();se();W();var Sd=Zr((t,e)=>{t("observe"),t("signal"),e("write")});function ht(t){let e=Ge([],{name:t.name,maxSize:t.retainedLimit??1024,guard:t.guard??Sd,...t.versioning!=null?{versioning:t.versioning}:{}});return e.withLatest(),t.graph&&t.graph.add(e.entries,{name:t.name}),e}function Nr(t){if(t===null||typeof t!="object"||Object.isFrozen(t))return t;for(let e of Object.keys(t))Nr(t[e]);return Object.freeze(t)}function Ot(t){let e=t.cache,r=(typeof e=="number"&&Number.isFinite(e)?e:0)+1;return t.down([[Q],[D,r]]),r}function wn(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 Ce(t,e){let n=e.freeze??!0;return function(...o){let s=n?o.map(Nr):o,i=ie(),a=e.seq?Ot(e.seq):void 0;try{let c=t(...s);return e.onSuccess&&wn(e.audit,e.onSuccess,s,c,{t_ns:i,seq:a},e.handlerVersion),c}catch(c){if(e.onFailure){let d=c instanceof Error?c.name:typeof c;wn(e.audit,e.onFailure,s,c,{t_ns:i,seq:a,errorType:d},e.handlerVersion)}throw c}}}function yt(t,e){let n=e.freeze??!0;return function(...o){let s=n?o.map(Nr):o,i=ie(),a,c,d=!1,u;try{te(()=>{e.seq&&(u=Ot(e.seq));try{a=t(...s),e.onSuccess&&wn(e.audit,e.onSuccess,s,a,{t_ns:i,seq:u},e.handlerVersion)}catch(l){throw c=l,d=!0,l}})}catch(l){if(d&&e.onFailure){let p=c instanceof Error?c.name:typeof c;wn(e.audit,e.onFailure,s,c,{t_ns:i,seq:u,errorType:p},e.handlerVersion)}throw d?c:l}return a}}function Mr(t,e,n=0){let r=P(n,{name:e,describeKind:"state"});return t.add(r,{name:e}),r}function At(t,e){return Fe("orchestration",t,e)}var kn=class extends ue{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:At("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(c){return{tag:"error",value:a,error:c}}},{name:e,describeKind:"derived",meta:At("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 c={};for(let d=0;d<o.length;d++)c[o[d]]=a[d];return c},{name:e,describeKind:"derived",meta:At("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 ue(`${e}_state`),c=P([],{name:"pending",equals:()=>!1}),d=P(s,{name:"isOpen"}),u=C([c],([G])=>G.length,{name:"count"}),l=P(0,{name:"droppedCount"}),p=ht({name:"decisions",retainedLimit:1024,graph:a});a.add(c,{name:"pending"}),a.add(d,{name:"isOpen"}),a.add(u,{name:"count"}),a.add(l,{name:"droppedCount"}),this.mount(`${e}_state`,a);let f=[],m=!1,h=!1,g=s,y=d.subscribe(G=>{for(let z of G)z[0]===D&&(g=z[1])});this.addDisposer(y);function b(){c.emit([...f])}function v(G,z,A){p.append({action:G,t_ns:ie(),...z!==void 0?{items:z,count:z.length}:{},...A!==void 0?{unflushed:A}:{},...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}function R(G){if(f.push(G),f.length>o){let z=f.shift();l.emit(l.cache+1),v("drop",[z])}b()}function _(G){let z=f.splice(0,G);return b(),z}let S=ne([i],(G,z,A)=>{let L=A.terminalDeps[0];if(L!==void 0){m=!0;let fe=f.length;f=[],b(),v("teardown",void 0,fe),z.down(L===!0?[[B]]:[[I,L]]);return}let q=G[0];if(q==null||q.length===0){z.down([[U]]);return}for(let fe of q)g?z.emit(fe):(R(fe),z.down([[U]]))},{name:e,describeKind:"derived",meta:At("gate",r.meta)});if(this.add(S,{name:e}),r.approver!=null){r.approver.cache&&(d.emit(!0),g=!0,r.onceOnly&&(h=!0));let z=r.approver.subscribe(A=>{for(let L of A){if(L[0]!==D)continue;let q=!!L[1];if(q&&!g){if(r.onceOnly){if(h)continue;h=!0}te(()=>{d.emit(!0);let fe=_(f.length);v("open",fe);for(let j of fe){if(m)break;S.emit(j)}})}else if(!q&&g){if(r.onceOnly&&h)continue;te(()=>{d.emit(!1),v("close")})}}});this.addDisposer(z)}let T=G=>{if(m)throw new Error(`gate: ${G}() called after gate was torn down`)},w=(G=1)=>{T("approve");let z=_(G);for(let A of z){if(m)break;S.emit(A)}},k=(G=1)=>{T("reject"),_(G)},M=(G,z=1)=>{T("modify");let A=[...f],L=_(z);for(let q=0;q<L.length&&!m;q++)S.emit(G(L[q],q,A))},N=()=>{T("open"),d.emit(!0);let G=_(f.length);for(let z of G){if(m)break;S.emit(z)}},E=()=>{T("close"),!(r.onceOnly&&h)&&d.emit(!1)},x=yt(w,{audit:p,freeze:!1,onSuccess:(G,z,A)=>({action:"approve",count:G[0]??1,t_ns:A.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(G,z,A)=>({action:"drop",t_ns:A.t_ns,errorType:A.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),O=yt(k,{audit:p,freeze:!1,onSuccess:(G,z,A)=>({action:"reject",count:G[0]??1,t_ns:A.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(G,z,A)=>({action:"drop",t_ns:A.t_ns,errorType:A.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),V=yt(M,{audit:p,freeze:!1,onSuccess:(G,z,A)=>({action:"modify",count:G[1]??1,t_ns:A.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(G,z,A)=>({action:"drop",t_ns:A.t_ns,errorType:A.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),$=yt(N,{audit:p,freeze:!1,onSuccess:(G,z,A)=>({action:"open",t_ns:A.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(G,z,A)=>({action:"drop",t_ns:A.t_ns,errorType:A.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),Y=yt(E,{audit:p,freeze:!1,onSuccess:(G,z,A)=>({action:"close",t_ns:A.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(G,z,A)=>({action:"drop",t_ns:A.t_ns,errorType:A.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})});return this.addDisposer(u.subscribe(()=>{})),{node:S,pending:c,count:u,isOpen:d,droppedCount:l,decisions:p,audit:p,approve:x,reject:O,modify:V,open:$,close:Y}}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=ne([s],(c,d,u)=>{let l=u.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"?[[B]]:[[I,f.error]]);return}let p=c[0];if(p==null||p.length===0){d.down([[U]]);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:At("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 Er(t,e){let n=new kn(t,e),{factory:r,factoryArgs:o,...s}=e??{};return n.tagFactory("pipelineGraph",ut(s)),n}async function _s(t,e,n,r){let o="",s=0;for await(let i of t.stream(e,n))r.publish({...i,seq:s++,ts:ie()}),i.type==="token"&&(o+=i.delta);return o}function Ns(t,e){if(e==="json")try{return JSON.parse(gt(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 Ms(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:H("accumulated_text"),initial:""})}function _d(t,e,n,r){let o=r?.name??"llm",s=r?.format??"text",i=_r(`${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:H("prompt_node::messages"),initial:[]}),c=pe(a,l=>{let p=l;if(!p||p.length===0)return P(null);let f=new AbortController;async function*m(){try{let h=await _s(t,p,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt,signal:f.signal},i);yield Ns(h,s)}finally{f.abort()}}return F(m())},{meta:ae("streamingPromptNode")}),d=Ms(i,`${o}::accumulatedText`),u=J(c);return{output:c,deltaTopic:i,accumulatedText:d,dispose:()=>{u(),i.destroy()}}}function Nd(t,e,n,r,o,s){let i=P(0,{name:`${e}/cancel`}),a=0,c=[...r,i],d=s?.name??e,u=s?.format??"text",l=_r(`${d}/stream`,{...s?.retainedLimit!=null?{retainedLimit:s.retainedLimit}:{}}),p=C(c,T=>{let w=T.slice(0,-1);if(w.some(M=>M==null))return[];let k=typeof o=="string"?o:o(...w);return k?[{role:"user",content:k}]:[]},{name:`${d}::messages`,meta:H("prompt_node::messages"),initial:[]}),f=pe(p,T=>{let w=T;if(!w||w.length===0)return P(null);let k=new AbortController;async function*M(){try{let N=await _s(n,w,{model:s?.model,temperature:s?.temperature,maxTokens:s?.maxTokens,systemPrompt:s?.systemPrompt,signal:k.signal},l);yield Ns(N,u)}finally{k.abort()}}return F(M())},{meta:ae("gatedStream")}),m=Ms(l,`${d}::accumulatedText`),h=xo(f,T=>T!=null);t.add(h,{name:`${e}/raw`});let g=Er(`${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=J(f),v=J(y.node),R=J(m);t.addDisposer(b),t.addDisposer(v),t.addDisposer(R);let _=y.reject.bind(y),S={...y,reject(T=1){te(()=>{_(T),i.emit(++a)})}};return{output:y.node,deltaTopic:l,accumulatedText:m,gate:S,dispose:()=>{b(),v(),R(),l.destroy()}}}W();ee();function Md(t,e){let n=e?.separator??`
|
|
14
14
|
|
|
15
|
-
`,r=t.map(i=>typeof i=="string"?I(i):G(i)),o=O(r,i=>i.filter(a=>a!=null&&a!=="").join(n),{name:e?.name??"systemPrompt",describeKind:"derived",meta:H("system_prompt"),initial:""}),s=Y(o);return Object.assign(o,{dispose:s})}q();var dd=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens&&t.estimated===e.estimated;function cd(t,e){let n=e?.charsPerToken??4,r={chunkCount:0,charCount:0,estimatedTokens:0,estimated:!0};return O([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=Ee(i.usage)+Ge(i.usage));let c=a.sawUsage?a.usageTokens:Math.ceil(a.charCount/n);return{chunkCount:a.chunkCount,charCount:a.charCount,estimatedTokens:c,estimated:!a.sawUsage}},{name:e?.name??"cost-meter",describeKind:"derived",initial:r,meta:H("cost_meter_extractor"),equals:dd})}q();var ud=(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 ld(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 O([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,c=s.store.scannedTo,d=Math.max(0,c-n),u=i.slice(d),l=!1;for(let{pattern:p,label:f,compiled:m}of r){m.lastIndex=0;for(let y of u.matchAll(m)){let g=d+(y.index??0);g+y[0].length<=c||(a.push({label:f,pattern:p,match:y[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:H("keyword_flag_extractor"),equals:ud})}q();function pd(t,e,n){return O([t],([r])=>r==null?null:e(r),{name:n?.name??"extractor",describeKind:"derived",initial:null,meta:H("stream_extractor"),...n?.equals?{equals:n.equals}:{}})}q();var fd=(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 md(t,e){return O([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 c=o.indexOf("{",i);if(c===-1){r.store.scanFrom=o.length;break}let d=0,u=-1,l=!1;for(let f=c;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)){u=f;break}}if(u===-1){r.store.scanFrom=c;break}let p=o.slice(c,u+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:c}),a=!0)}catch{}i=u+1,r.store.scanFrom=i}return a?[...s]:s.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:H("tool_call_extractor"),equals:fd})}q();function gd(t,e,n,r){let o=n*(r?.hardMultiplier??1.5),s=typeof e!="function",i=[t];return s&&i.push(e),O(i,a=>{let c=a[0]??"";if(c.length===0)return"allow";let d=s?a[1]??0:e(c);return d>=o?"block":d>=n?"review":"allow"},{name:r?.name??"content-gate",initial:"allow"})}q();function hd(t,e,n,r){let o=n??(()=>"[REDACTED]");function s(i){let a=i;for(let c of e){let d=c.global?c:new RegExp(c.source,`${c.flags}g`);a=a.replace(d,u=>o(u,c))}return a}return O([t],([i])=>s(i??""),{name:r?.name??"redactor",initial:""})}xe();re();Re();q();Q();q();var mn=class extends ie{_log;messages;latest;messageCount;constructor(e,n={}){super(e,n.graph),this._log=Le([],{name:"messages",maxSize:n.maxMessages}),this.messages=this._log.entries,this.add(this.messages,{name:"messages"}),this.latest=O([this.messages],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:H("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(Y(this.latest)),this.messageCount=O([this.messages],([r])=>r.length,{name:"messageCount",describeKind:"derived",meta:H("chat_message_count"),initial:0}),this.add(this.messageCount,{name:"messageCount"}),this.addDisposer(Y(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 hr(t,e){return new mn(t,e)}q();st();function yr(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 c=0;c<i.length;c++){let d=i[c],u=a[c];if(d?.id!==u?.id||d?.content!==u?.content)return!1}return!0};return ae(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(c=>yd(c,n,r,o));return O(a,c=>c,{name:"toolExecution::batch",equals:s})})}function yd(t,e,n,r){let o=Dn(()=>e.executeReactive(t.name,t.arguments),{count:n}),s=O([o],([i])=>({id:t.id,content:typeof i=="string"?i:JSON.stringify(i)}));return r==="propagate"?s:co(s,i=>({id:t.id,content:JSON.stringify({error:String(i)})}))}re();q();Q();var gn=class extends ie{definitions;schemas;_bundle;constructor(e,n={}){super(e,n.graph),this._bundle=rt({name:"definitions"}),this.definitions=this._bundle.entries,this.add(this.definitions,{name:"definitions"}),this.schemas=O([this.definitions],([r])=>[...(r??new Map).values()],{name:"schemas",describeKind:"derived",meta:H("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(Y(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 ne(o=>{let s=new AbortController,i;try{let c=r.handler(n,{signal:s.signal});i=bd(c,s.signal)}catch(c){return o.down([[C,c]]),()=>{s.abort()}}let a=i.subscribe(c=>{o.down(c)});return()=>{s.abort(),a()}},{name:`executeReactive::${e}`,meta:H("tool_execute_reactive")})}getDefinition(e){return this._bundle.entries.cache?.get(e)}};function br(t,e){return new gn(t,e)}function bd(t,e){return ir(t)?t:t!=null&&typeof t.then=="function"?Vt(t,{signal:e}):t!=null&&typeof t=="object"&&Symbol.asyncIterator in t?Pn(t,{signal:e}):Vt(Promise.resolve(t),{signal:e})}var hn=class extends ie{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;_terminalResult;_disposeRunWiring;_running=!1;_currentAbortController=null;constructor(e,n){if(super(e,n.graph),this.chat=hr(`${e}-chat`,{maxMessages:n.maxMessages}),this.mount("chat",this.chat),this.tools=br(`${e}-tools`),this.mount("tools",this.tools),n.tools)for(let P of n.tools)this.tools.register(P);this.status=I("idle",{name:"status",describeKind:"state",meta:H("agent_status")}),this.add(this.status,{name:"status"}),this.turn=I(0,{name:"turn",describeKind:"state",meta:H("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.aborted=I(!1,{name:"aborted",describeKind:"state",meta:H("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let r=0,o=this.turn.subscribe(P=>{for(let F of P)F[0]===D&&(r=F[1])}),s=!1,i=this.aborted.subscribe(P=>{for(let F of P)F[0]===D&&(s=F[1])}),a=this.chat.messages.cache??[],c=this.chat.messages.subscribe(P=>{for(let F of P)F[0]===D&&(a=F[1])}),d=this.tools.schemas.cache??[],u=this.tools.schemas.subscribe(P=>{for(let F of P)F[0]===D&&(d=F[1])}),l=n.adapter,p=n.systemPrompt,f=n.model,m=n.temperature,y=n.maxTokens,g=n.maxTurns??10,h=n.stopWhen,b=this.chat,v=this.tools,x=this.status,w=this.turn,k=this.aborted,T=te([x],(P,F,L)=>{if(St(P,L.prevData,0,"idle")!=="thinking"||s||r>=g){F.down([[V]]);return}if(a.length===0){F.down([[V]]);return}F.emit({messages:a,tools:d})},{name:"promptInput",describeKind:"derived",meta:H("agent_prompt_input",{closureReads:["aborted","turn","chat.messages","tools.schemas"]})}),R=ae(T,P=>{let F=new AbortController;return this._currentAbortController=F,s&&F.abort(new Error("agentLoop: aborted")),G(l.invoke(P.messages,{tools:P.tools.length>0?P.tools:void 0,systemPrompt:p,model:f,temperature:m,maxTokens:y,signal:F.signal}),{signal:F.signal})},{equals:()=>!1}),N=I(null,{name:"lastResponse",describeKind:"state",meta:H("agent_last_response")});this.lastResponse=N;let _=te([N,x],(P,F,L)=>{let z=St(P,L.prevData,0,null);if(St(P,L.prevData,1,"idle")!=="acting"){F.down([[V]]);return}let he=z?.toolCalls;if(he==null||he.length===0){F.down([[V]]);return}F.emit(he)},{name:"toolCallsRaw",describeKind:"derived",meta:H("agent_tool_calls_raw")}),S=n.interceptToolCalls?n.interceptToolCalls(_):_;this.toolCalls=S;let E=yr({toolCalls:S,tools:v,retryCount:1});this.toolResults=E;let M=ve([R],([P])=>{if(s)return;let F=P,L=r+1,z=F.toolCalls!=null&&F.toolCalls.length>0,de=F.finishReason==="end_turn"&&(!F.toolCalls||F.toolCalls.length===0),he=h?.(F)===!0,ye=L>=g,X=he||de||!z||ye?"done":"acting";ee(()=>{N.emit(F),x.emit(X),w.emit(L),b.append("assistant",F.content,{toolCalls:F.toolCalls})})}),A=ve([E],([P])=>{if(s)return;let F=P;if(F.length===0)return;let L=r>=g?"done":"thinking";ee(()=>{x.emit(L);for(let z of F)b.appendToolResult(z.id,z.content)})}),j=x.cache??"idle",K=x.subscribe(P=>{for(let F of P)F[0]===D&&(j=F[1])}),Z=ve([k],([P])=>{P===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),j!=="done"&&x.emit("done"))}),ke=Y(M),U=Y(A),W=Y(Z);this._terminalResult=te([x,N],(P,F,L)=>{let z=St(P,L.prevData,0,"idle"),de=St(P,L.prevData,1,null);if(z==="done"){if(de!=null){F.emit(de);return}let he=new Error("agentLoop: aborted");he.name="AbortError",F.down([[C,he]]);return}if(z==="error"){F.down([[C,new Error("agentLoop: errored")]]);return}F.down([[V]])},{name:"terminalResult",describeKind:"derived",meta:H("agent_terminal_result")}),this.add(T,{name:"promptInput"}),this.add(R,{name:"llmResponse"}),this.add(this.lastResponse,{name:"lastResponse"}),this.toolCalls===_?this.add(this.toolCalls,{name:"toolCalls"}):(this.add(_,{name:"toolCallsRaw"}),this.add(this.toolCalls,{name:"toolCalls"})),this.add(E,{name:"toolResults"}),this.add(this._terminalResult,{name:"terminalResult"}),this.addDisposer(o),this.addDisposer(i),this.addDisposer(K),this.addDisposer(c),this.addDisposer(u),this.addDisposer(ke),this.addDisposer(U),this.addDisposer(W),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{ee(()=>{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=ro(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 St(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 Td(t,e){return new hn(t,e)}q();Q();function vd(t,e,n){let r=G(t),o=n?.condition!=null?G(n.condition):null,s=I(null,{name:n?.name?`${n.name}::null`:"handoff::null"});if(o==null)return ae(r,a=>{if(a==null)return s;let c=I(a);return e(c)});let i=O([r,o],([a,c])=>({v:a,open:c===!0}),{name:n?.name?`${n.name}::router`:"handoff::router",describeKind:"derived"});return ae(i,({v:a,open:c})=>{if(a==null)return s;if(!c)return I(a);let d=I(a);return e(d)})}q();Q();function wd(t,e,n){let r=G(t),o=e.map(i=>G(i)),s=[r,...o];return O(s,i=>{let a=i[0]??[],c=i.slice(1);return a.filter(d=>{for(let u of c)if(u!=null&&!u(d))return!1;return!0})},{name:n?.name??"tool-selector",describeKind:"derived",meta:H("tool_selector"),equals:(i,a)=>{let c=i,d=a;if(c.length!==d.length)return!1;for(let u=0;u<c.length;u++)if(c[u]!==d[u])return!1;return!0}})}function ps(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 kd(t){let e={persistence:t.persistenceThreshold??.3,personalValue:t.personalValueThreshold??.3},n=ps({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}q();xe();re();q();Q();function xd(t){return typeof t=="object"&&t!==null&&"cache"in t&&typeof t.subscribe=="function"}function fs(t){t.subscribe(()=>{})}function _t(t){return t instanceof Map?t:new Map}function ms(t,e){if(!Array.isArray(e.upsert))throw new TypeError("distill extraction requires upsert: Array<{ key, value }>");ee(()=>{for(let{key:n,value:r}of e.upsert)t.set(n,r);for(let n of e.remove??[])t.delete(n)})}function gs(t,e,n){let r=G(t),o=rt(n.mapOptions??{}),s=n.budget??2e3,a=n.context!==void 0&&n.context!==null?G(n.context):I(null),c=_t(o.entries.cache);o.entries.subscribe(f=>{for(let m of f)m[0]===D&&(c=_t(m[1]))});let d=ae(r,f=>e(f,c));if(bt(d,f=>{ms(o,f)}),n.evict){let f=new Map,m=O([o.entries],([y])=>{let g=[],h=_t(y);for(let b of f.keys())h.has(b)||(f.get(b)(),f.delete(b));for(let[b,v]of h){let x=n.evict(b,v);if(xd(x)){if(!f.has(b)){let w=bt(x,k=>{k===!0&&o.has(b)&&o.delete(b)});f.set(b,w)}continue}if(typeof x=="boolean"){x&&g.push(b);continue}throw new TypeError("distill evict() must return boolean or Node<boolean>")}return g});bt(m,y=>{for(let g of y)o.delete(g)})}let u=n.consolidateTrigger!==void 0&&n.consolidateTrigger!==null;if(n.consolidate&&u){let f=G(n.consolidateTrigger),m=ae(f,()=>n.consolidate(c));bt(m,y=>{ms(o,y)})}let l=O([o.entries,a],([f,m])=>{let y=[..._t(f).entries()].map(([b,v])=>({key:b,value:v,score:n.score(v,m),cost:n.cost(v)}));y.sort((b,v)=>v.score-b.score);let g=[],h=s;for(let b of y)b.cost<=h&&(g.push({key:b.key,value:b.value,score:b.score}),h-=b.cost);return g}),p=O([o.entries],([f])=>_t(f).size);return fs(l),fs(p),{store:o,compact:l,size:p}}Q();q();function hs(t,e,n,r){let o=n.name??r;return s=>{let i=I(s);return ar(n.adapter,[i],a=>e(a),{name:o,format:"json",systemPrompt:t,model:n.model,temperature:n.temperature??0,maxTokens:n.maxTokens})}}function Tr(t,e){let n=e.maxExistingKeys??100,r=hs(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 vr(t,e){let n=hs(t,r=>JSON.stringify({memories:r}),e,"llmConsolidator");return r=>{let o=[...r.entries()].map(([s,i])=>({key:s,value:i}));return n(o)}}xe();pe();q();Q();pe();q();function ys(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 Rd(t){if(t!==void 0&&t<1)throw new RangeError("maxSize must be >= 1")}function Qe(t){return new Map(t)}function Oe(t){return t.cache??new Map}function yn(t){return t.cache??[]}function Sd(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,c=e[i]??0;r+=a*c,o+=a*a,s+=c*c}return o===0||s===0?0:r/Math.sqrt(o*s)}function bs(t={}){let e=t.maxSize,n=t.policy??"fifo";Rd(e);let r=I(new Map,{name:t.name,describeKind:"state"});function o(i){if(e!==void 0)for(;i.size>e;){let a;for(let c of i.values()){if(!a){a=c;continue}let d=n==="lru"?c.lastAccessNs:c.createdAtNs,u=n==="lru"?a.lastAccessNs:a.createdAtNs;d<u&&(a=c)}if(!a)break;i.delete(a.id)}}function s(i){r.emit(i)}return{entries:r,upsert(i,a){let c=B(),d=Oe(r),u=d.get(i),l=Qe(d);l.set(i,{id:i,value:a,createdAtNs:u?.createdAtNs??c,lastAccessNs:c}),o(l),s(l)},remove(i){let a=Qe(Oe(r));a.delete(i)&&s(a)},clear(){Oe(r).size!==0&&s(new Map)},get(i){let a=Oe(r),c=a.get(i);if(c){if(n==="lru"){let d=B(),u=Qe(a);u.set(i,{...c,lastAccessNs:d}),s(u)}return c.value}},has(i){return Oe(r).has(i)}}}function Ts(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=I(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,c,d){s(c);let u=Qe(Oe(o));u.set(a,{id:a,vector:[...c],meta:d}),e==="hnsw"&&r.upsert(a,c,d),i(u)},remove(a){let c=Qe(Oe(o));c.delete(a)&&(e==="hnsw"&&r.remove(a),i(c))},clear(){Oe(o).size!==0&&(e==="hnsw"&&r.clear(),i(new Map))},search(a,c=5){return s(a),c<=0?[]:e==="hnsw"?r.search(a,c):[...Oe(o).values()].map(u=>({id:u.id,score:Sd(a,u.vector),meta:u.meta})).sort((u,l)=>l.score-u.score).slice(0,c)}}}function vs(t){let e=new ie(t),n=I(new Map,{name:"entities",describeKind:"state"}),r=I([],{name:"edges",describeKind:"state"}),o=O([r],([c])=>{let d=c??[],u=new Map;for(let l of d){let p=u.get(l.from)??[];u.set(l.from,Object.freeze([...p,l]))}return u},{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(c){n.emit(c)}function i(c){r.emit(c)}return Object.assign(e,{upsertEntity(c,d){let u=Qe(Oe(n));u.set(c,d),s(u)},removeEntity(c){let d=Qe(Oe(n)),u=d.delete(c),l=yn(r),p=l.filter(f=>f.from!==c&&f.to!==c);!u&&p.length===l.length||(s(d),i(p))},link(c,d,u,l=1){let p=`${c}\0${d}\0${u}`,f=yn(r),m=new Set(f.map(g=>`${g.from}\0${g.to}\0${g.relation}`)),y=[...f];if(m.has(p))for(let g=0;g<y.length;g+=1){let h=y[g];if(h.from===c&&h.to===d&&h.relation===u){y[g]={...h,weight:l};break}}else y.push({from:c,to:d,relation:u,weight:l});i(y)},unlink(c,d,u){let l=yn(r),p=l.filter(f=>u===void 0?!(f.from===c&&f.to===d):!(f.from===c&&f.to===d&&f.relation===u));p.length!==l.length&&i(p)},related(c,d){return yn(r).filter(u=>(u.from===c||u.to===c)&&(d===void 0||u.relation===d))}})}var wr=Math.LN2/604800;function lt(t){return t instanceof Map?t:new Map}function kr(t,e,n){let r=Ts({dimension:n.dimension});t.add(r.entries,{name:"vectorIndex"});let s=ve([e.store.entries],([i])=>{let a=lt(i);for(let[c,d]of a){let u=n.embedFn(d);u&&r.upsert(c,u,d)}}).subscribe(()=>{});return t.addDisposer(s),{vectors:r,dispose:()=>s()}}function xr(t,e,n,r){let o=r.mountPath??n,s=vs(`${n}-kg`);if(t.mount(o,s),!r.entityFn)return{kg:s,dispose:()=>{}};let i=r.entityFn,c=ve([e.store.entries],([d])=>{let u=lt(d);for(let[l,p]of u){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(c),{kg:s,dispose:()=>c()}}function Rr(t,e,n){let r=n.decayRate??wr,o=n.maxActive??1e3,s=n.archiveThreshold??.1,i=n.permanentFilter??(()=>!1),a=bs({name:"permanent"});t.add(a.entries,{name:"permanent"});let c=new Set,d=b=>c.has(b)?"permanent":lt(e.store.entries.cache).has(b)?"active":"archived",u=(b,v)=>{c.add(b),a.upsert(b,v)},l=new Map,p=e.store.entries,f=n.context?G(n.context):I(null),y=ve([p,f],([b,v])=>{let x=lt(b),w=B(),k=[],T=[];for(let[N,_]of x){if(l.has(N)||l.set(N,w),i(N,_)){T.push({key:N,value:_});continue}let S=n.score(_,v),E=l.get(N)??w,M=Number(w-E)/1e9;ys(S,M,r)<s&&k.push(N)}for(let N of l.keys())x.has(N)||l.delete(N);for(let{key:N,value:_}of T)c.has(N)||u(N,_);let R=x.size-c.size;if(R>o){let N=[...x.entries()].filter(([S])=>!c.has(S)).map(([S,E])=>({key:S,score:n.score(E,v)})).sort((S,E)=>S.score-E.score),_=R-o;for(let S=0;S<_&&S<N.length;S++){let E=N[S].key;k.includes(E)||k.push(E)}}k.length>0&&ee(()=>{for(let N of k)e.store.delete(N)})}).subscribe(()=>{}),g=null;n.archiveTier&&(g=t.attachSnapshotStorage([n.archiveTier],n.archiveStorageOptions??{}));let h=()=>{y(),g?.dispose()};return t.addDisposer(h),{tiers:{permanent:a,activeEntries:p,archiveHandle:g,tierOf:d,markPermanent:u},dispose:h}}function _d(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 Sr(t,e,n,r,o){let s=o.topK??20,i=o.graphDepth??1,a=o.budget??2e3,c=o.contextWeight??0,d=o.context?G(o.context):I(null),u=(g,h,b)=>{let v=new Map,x=[];if(n&&b.vector){x=n.search(b.vector,s);for(let _ of x){let S=g.get(_.id);S&&v.set(_.id,{value:S,sources:new Set(["vector"])})}}let w=[];if(r){let _=[...b.entityIds??[],...v.keys()],S=new Set,E=_;for(let M=0;M<i;M++){let A=[];for(let j of E)if(!S.has(j)){S.add(j);for(let K of r.related(j)){let Z=K.to;if(!S.has(Z)){A.push(Z);let ke=g.get(Z);if(ke){let U=v.get(Z);U?U.sources.add("graph"):v.set(Z,{value:ke,sources:new Set(["graph"])}),w.push(Z)}}}}E=A}}for(let[_,S]of g)v.has(_)||v.set(_,{value:S,sources:new Set(["store"])});let k=b.context?.length??0,T=[];for(let[_,{value:S,sources:E}]of v){let M=o.contextOf?o.contextOf(S):void 0,A=o.score(S,h);if(c>0&&k>0){let K=_d(b.context,M);K>0&&(A=A*(1+c*K/k))}let j=M?{key:_,value:S,score:A,sources:[...E],context:M}:{key:_,value:S,score:A,sources:[...E]};T.push(j)}T.sort((_,S)=>S.score-_.score);let R=[],N=0;for(let _ of T){let S=o.cost(_.value);if(N+S>a&&R.length>0)break;R.push(_),N+=S}return{packed:R,trace:{vectorCandidates:x,graphExpanded:w,ranked:T,packed:R}}},l=(g,h)=>{if(g===h)return!0;if(g.length!==h.length)return!1;for(let b=0;b<g.length;b++)if(g[b]!==h[b])return!1;return!0},p=I([],{name:"retrieval",describeKind:"state",meta:H("retrieval_pipeline"),equals:l});t.add(p,{name:"retrieval"});let f=I(null,{name:"retrievalTrace",describeKind:"state",meta:H("retrieval_trace")});return t.add(f,{name:"retrievalTrace"}),{retrieval:p,retrievalTrace:f,retrieve:g=>{let h=lt(e.store.entries.cache),{packed:b,trace:v}=u(h,d.cache,g);return ee(()=>{p.emit(b),f.emit(v)}),b},retrieveReactive:g=>{let h=G(g),b=O([e.store.entries,d,h],([w,k,T])=>{if(T==null)return{packed:[],trace:null};let R=lt(w),{packed:N,trace:_}=u(R,k,T);return{packed:N,trace:_}},{name:"retrievalReactive::result",describeKind:"derived",meta:H("retrieval_reactive_result"),initial:{packed:[],trace:null}}),x=ve([b],([w])=>{let k=w;ee(()=>{p.emit(k.packed),k.trace&&f.emit(k.trace)})}).subscribe(()=>{});return t.addDisposer(x),O([b],([w])=>w.packed,{name:"retrievalReactive",describeKind:"derived",meta:H("retrieval_reactive"),initial:[],equals:l})}}}function Nd(t,e,n){let r=new ie(t,n.graph),o;if(n.extractFn)o=n.extractFn;else if(n.adapter&&n.extractPrompt)o=Tr(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=G(e),v=n.admissionFilter;i=O([b],([x])=>{if(v(x))return x},{name:"admissionFilter",describeKind:"derived"})}let a;n.consolidateFn?a=n.consolidateFn:n.adapter&&n.consolidatePrompt&&(a=vr(n.consolidatePrompt,{adapter:n.adapter}));let c=n.consolidateTrigger;if(!c&&a&&n.reflection?.enabled!==!1){let b=n.reflection?.interval??3e5;c=to(b,{period:b})}let d={score:n.score,cost:n.cost,budget:n.budget??2e3,context:n.context,consolidate:a,consolidateTrigger:c},u=gs(i,s,d);r.add(u.store.entries,{name:"store"}),r.add(u.compact,{name:"compact"}),r.add(u.size,{name:"size"});let l=null;n.vectorDimensions&&n.vectorDimensions>0&&n.embedFn&&(l=kr(r,u,{dimension:n.vectorDimensions,embedFn:n.embedFn}).vectors);let p=null;n.enableKnowledgeGraph&&(p=xr(r,u,t,{mountPath:"kg",entityFn:n.entityFn}).kg);let f=null;n.tiers&&(f=Rr(r,u,{...n.tiers,score:n.score,context:n.context}).tiers);let m=null,y=null,g=null,h=null;if(l||p){let b=Sr(r,u,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,y=b.retrievalTrace,g=b.retrieve,h=b.retrieveReactive}return Object.assign(r,{distillBundle:u,compact:u.compact,size:u.size,vectors:l,kg:p,memoryTiers:f,retrieval:m,retrievalTrace:y,retrieve:g,retrieveReactive:h})}function Md(t,e,n){let r=t.describe({actor:e,detail:"full"}),o=n?.groupByTags??!0,s=n?.separator??`
|
|
16
|
-
`,i=[],a=n?.sinceVersion;for(let[c,d]of Object.entries(r.nodes)){let u=d.meta??{},l=u.description,p=u.format;if(!l&&!p)continue;if(a!=null&&d.v!=null){let
|
|
15
|
+
`,r=t.map(i=>typeof i=="string"?P(i):F(i)),o=C(r,i=>i.filter(a=>a!=null&&a!=="").join(n),{name:e?.name??"systemPrompt",describeKind:"derived",meta:H("system_prompt"),initial:""}),s=J(o);return Object.assign(o,{dispose:s})}W();var Ed=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens&&t.estimated===e.estimated;function Od(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=De(i.usage)+Ve(i.usage));let c=a.sawUsage?a.usageTokens:Math.ceil(a.charCount/n);return{chunkCount:a.chunkCount,charCount:a.charCount,estimatedTokens:c,estimated:!a.sawUsage}},{name:e?.name??"cost-meter",describeKind:"derived",initial:r,meta:H("cost_meter_extractor"),equals:Ed})}W();var Ad=(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 Cd(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,c=s.store.scannedTo,d=Math.max(0,c-n),u=i.slice(d),l=!1;for(let{pattern:p,label:f,compiled:m}of r){m.lastIndex=0;for(let h of u.matchAll(m)){let g=d+(h.index??0);g+h[0].length<=c||(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:H("keyword_flag_extractor"),equals:Ad})}W();function Ld(t,e,n){return C([t],([r])=>r==null?null:e(r),{name:n?.name??"extractor",describeKind:"derived",initial:null,meta:H("stream_extractor"),...n?.equals?{equals:n.equals}:{}})}W();var Dd=(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 Id(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 c=o.indexOf("{",i);if(c===-1){r.store.scanFrom=o.length;break}let d=0,u=-1,l=!1;for(let f=c;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)){u=f;break}}if(u===-1){r.store.scanFrom=c;break}let p=o.slice(c,u+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:c}),a=!0)}catch{}i=u+1,r.store.scanFrom=i}return a?[...s]:s.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:H("tool_call_extractor"),equals:Dd})}W();function Pd(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 c=a[0]??"";if(c.length===0)return"allow";let d=s?a[1]??0:e(c);return d>=o?"block":d>=n?"review":"allow"},{name:r?.name??"content-gate",initial:"allow"})}W();function Gd(t,e,n,r){let o=n??(()=>"[REDACTED]");function s(i){let a=i;for(let c of e){let d=c.global?c:new RegExp(c.source,`${c.flags}g`);a=a.replace(d,u=>o(u,c))}return a}return C([t],([i])=>s(i??""),{name:r?.name??"redactor",initial:""})}Se();se();Ae();ke();W();ee();W();var xn=class extends ue{_log;messages;latest;messageCount;constructor(e,n={}){super(e,n.graph),this._log=Ge([],{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:H("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(J(this.latest)),this.messageCount=C([this.messages],([r])=>r.length,{name:"messageCount",describeKind:"derived",meta:H("chat_message_count"),initial:0}),this.add(this.messageCount,{name:"messageCount"}),this.addDisposer(J(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 Or(t,e){return new xn(t,e)}W();lt();function Ar(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 c=0;c<i.length;c++){let d=i[c],u=a[c];if(d?.id!==u?.id||d?.content!==u?.content)return!1}return!0};return pe(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(c=>Fd(c,n,r,o));return C(a,c=>c,{name:"toolExecution::batch",equals:s})})}function Fd(t,e,n,r){let o=Un(()=>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:_o(s,i=>({id:t.id,content:JSON.stringify({error:String(i)})}))}se();W();ee();var Rn=class extends ue{definitions;schemas;_bundle;constructor(e,n={}){super(e,n.graph),this._bundle=Le({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:H("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(J(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 oe(o=>{let s=new AbortController,i;try{let c=r.handler(n,{signal:s.signal});i=$d(c,s.signal)}catch(c){return o.down([[I,c]]),()=>{s.abort()}}let a=i.subscribe(c=>{o.down(c)});return()=>{s.abort(),a()}},{name:`executeReactive::${e}`,meta:H("tool_execute_reactive")})}getDefinition(e){return this._bundle.entries.cache?.get(e)}};function Cr(t,e){return new Rn(t,e)}function $d(t,e){return yr(t)?t:t!=null&&typeof t.then=="function"?Qt(t,{signal:e}):t!=null&&typeof t=="object"&&Symbol.asyncIterator in t?qn(t,{signal:e}):Qt(Promise.resolve(t),{signal:e})}var Sn=class extends ue{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;_terminalResult;_disposeRunWiring;_running=!1;_currentAbortController=null;constructor(e,n){if(super(e,n.graph),this.chat=Or(`${e}-chat`,{maxMessages:n.maxMessages}),this.mount("chat",this.chat),this.tools=Cr(`${e}-tools`),this.mount("tools",this.tools),n.tools)for(let A of n.tools)this.tools.register(A);this.status=P("idle",{name:"status",describeKind:"state",meta:H("agent_status")}),this.add(this.status,{name:"status"}),this.turn=P(0,{name:"turn",describeKind:"state",meta:H("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.aborted=P(!1,{name:"aborted",describeKind:"state",meta:H("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let r=0,o=this.turn.subscribe(A=>{for(let L of A)L[0]===D&&(r=L[1])}),s=!1,i=this.aborted.subscribe(A=>{for(let L of A)L[0]===D&&(s=L[1])}),a=this.chat.messages.cache??[],c=this.chat.messages.subscribe(A=>{for(let L of A)L[0]===D&&(a=L[1])}),d=this.tools.schemas.cache??[],u=this.tools.schemas.subscribe(A=>{for(let L of A)L[0]===D&&(d=L[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,R=this.status,_=this.turn,S=this.aborted,T=ne([R],(A,L,q)=>{if(Ct(A,q.prevData,0,"idle")!=="thinking"||s||r>=g){L.down([[U]]);return}if(a.length===0){L.down([[U]]);return}L.emit({messages:a,tools:d})},{name:"promptInput",describeKind:"derived",meta:H("agent_prompt_input",{closureReads:["aborted","turn","chat.messages","tools.schemas"]})}),w=pe(T,A=>{let L=new AbortController;return this._currentAbortController=L,s&&L.abort(new Error("agentLoop: aborted")),F(l.invoke(A.messages,{tools:A.tools.length>0?A.tools:void 0,systemPrompt:p,model:f,temperature:m,maxTokens:h,signal:L.signal}),{signal:L.signal})},{equals:()=>!1}),k=P(null,{name:"lastResponse",describeKind:"state",meta:H("agent_last_response")});this.lastResponse=k;let M=ne([k,R],(A,L,q)=>{let fe=Ct(A,q.prevData,0,null);if(Ct(A,q.prevData,1,"idle")!=="acting"){L.down([[U]]);return}let Z=fe?.toolCalls;if(Z==null||Z.length===0){L.down([[U]]);return}L.emit(Z)},{name:"toolCallsRaw",describeKind:"derived",meta:H("agent_tool_calls_raw")}),N=n.interceptToolCalls?n.interceptToolCalls(M):M;this.toolCalls=N;let E=Ar({toolCalls:N,tools:v,retryCount:1});this.toolResults=E;let x=xe([w],([A])=>{if(s)return;let L=A,q=r+1,fe=L.toolCalls!=null&&L.toolCalls.length>0,j=L.finishReason==="end_turn"&&(!L.toolCalls||L.toolCalls.length===0),Z=y?.(L)===!0,ve=q>=g,He=Z||j||!fe||ve?"done":"acting";te(()=>{k.emit(L),R.emit(He),_.emit(q),b.append("assistant",L.content,{toolCalls:L.toolCalls})})}),O=xe([E],([A])=>{if(s)return;let L=A;if(L.length===0)return;let q=r>=g?"done":"thinking";te(()=>{R.emit(q);for(let fe of L)b.appendToolResult(fe.id,fe.content)})}),V=R.cache??"idle",$=R.subscribe(A=>{for(let L of A)L[0]===D&&(V=L[1])}),Y=xe([S],([A])=>{A===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),V!=="done"&&R.emit("done"))}),X=J(x),G=J(O),z=J(Y);this._terminalResult=ne([R,k],(A,L,q)=>{let fe=Ct(A,q.prevData,0,"idle"),j=Ct(A,q.prevData,1,null);if(fe==="done"){if(j!=null){L.emit(j);return}let Z=new Error("agentLoop: aborted");Z.name="AbortError",L.down([[I,Z]]);return}if(fe==="error"){L.down([[I,new Error("agentLoop: errored")]]);return}L.down([[U]])},{name:"terminalResult",describeKind:"derived",meta:H("agent_terminal_result")}),this.add(T,{name:"promptInput"}),this.add(w,{name:"llmResponse"}),this.add(this.lastResponse,{name:"lastResponse"}),this.toolCalls===M?this.add(this.toolCalls,{name:"toolCalls"}):(this.add(M,{name:"toolCallsRaw"}),this.add(this.toolCalls,{name:"toolCalls"})),this.add(E,{name:"toolResults"}),this.add(this._terminalResult,{name:"terminalResult"}),this.addDisposer(o),this.addDisposer(i),this.addDisposer($),this.addDisposer(c),this.addDisposer(u),this.addDisposer(X),this.addDisposer(G),this.addDisposer(z),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{te(()=>{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=wo(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 Ct(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 jd(t,e){let n=new Sn(t,e);return n.tagFactory("agentLoop",ut(e)),n}Ae();W();ee();function Bd(t,e,n){let r=F(t),o=n?.condition!=null?F(n.condition):null,s=P(null,{name:n?.name?`${n.name}::null`:"handoff::null"});if(o==null)return pe(r,a=>{if(a==null)return s;let c=P(a);return e(c)},{meta:ae("handoff")});let i=C([r,o],([a,c])=>({v:a,open:c===!0}),{name:n?.name?`${n.name}::router`:"handoff::router",describeKind:"derived"});return pe(i,({v:a,open:c})=>{if(a==null)return s;if(!c)return P(a);let d=P(a);return e(d)},{meta:ae("handoff")})}Ae();W();ee();function Vd(t,e,n){let r=F(t),o=e.map(i=>F(i)),s=[r,...o];return C(s,i=>{let a=i[0]??[],c=i.slice(1);return a.filter(d=>{for(let u of c)if(u!=null&&!u(d))return!1;return!0})},{name:n?.name??"tool-selector",describeKind:"derived",meta:{...H("tool_selector"),...ae("toolSelector")},equals:(i,a)=>{let c=i,d=a;if(c.length!==d.length)return!1;for(let u=0;u<c.length;u++)if(c[u]!==d[u])return!1;return!0}})}function Es(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 Kd(t){let e={persistence:t.persistenceThreshold??.3,personalValue:t.personalValueThreshold??.3},n=Es({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}se();Ae();W();Se();se();Ae();W();ee();function zd(t){return typeof t=="object"&&t!==null&&"cache"in t&&typeof t.subscribe=="function"}function Os(t){t.subscribe(()=>{})}function Lt(t){return t instanceof Map?t:new Map}function As(t,e){if(!Array.isArray(e.upsert))throw new TypeError("distill extraction requires upsert: Array<{ key, value }>");te(()=>{for(let{key:n,value:r}of e.upsert)t.set(n,r);for(let n of e.remove??[])t.delete(n)})}function Cs(t,e,n){let r=F(t),o=Le(n.mapOptions??{}),s=n.budget??2e3,a=n.context!==void 0&&n.context!==null?F(n.context):P(null),c=Lt(o.entries.cache);o.entries.subscribe(f=>{for(let m of f)m[0]===D&&(c=Lt(m[1]))});let d=F(e(r,o.entries));if(Rt(d,f=>{As(o,f)}),n.evict){let f=new Map,m=C([o.entries],([h])=>{let g=[],y=Lt(h);for(let b of f.keys())y.has(b)||(f.get(b)(),f.delete(b));for(let[b,v]of y){let R=n.evict(b,v);if(zd(R)){if(!f.has(b)){let _=Rt(R,S=>{S===!0&&o.has(b)&&o.delete(b)});f.set(b,_)}continue}if(typeof R=="boolean"){R&&g.push(b);continue}throw new TypeError("distill evict() must return boolean or Node<boolean>")}return g});Rt(m,h=>{for(let g of h)o.delete(g)})}let u=n.consolidateTrigger!==void 0&&n.consolidateTrigger!==null;if(n.consolidate&&u){let f=F(n.consolidateTrigger),m=pe(f,()=>n.consolidate(c));Rt(m,h=>{As(o,h)})}let l=C([o.entries,a],([f,m])=>{let h=[...Lt(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:{...ae("distill",{budget:s})}}),p=C([o.entries],([f])=>Lt(f).size);return Os(l),Os(p),{store:o,compact:l,size:p}}ee();W();function Ls(t,e,n,r){let o=n.name??r;return s=>{let i=P(s);return br(n.adapter,[i],a=>e(a),{name:o,format:"json",systemPrompt:t,model:n.model,temperature:n.temperature??0,maxTokens:n.maxTokens})}}function Lr(t,e){let n=e.maxExistingKeys??100,r=Ls(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 Dr(t,e){let n=Ls(t,r=>JSON.stringify({memories:r}),e,"llmConsolidator");return r=>{let o=[...r.entries()].map(([s,i])=>({key:s,value:i}));return n(o)}}Se();ge();W();ee();ge();ke();W();function Ue(t,e){return Fe("memory",t,e)}function Dt(t,e){return t instanceof le?t:P(t,e?{name:e}:void 0)}function Gs(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 Ir(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 c=t[a]??0,d=e[a]??0;r+=c*d,o+=c*c,s+=d*d}if(o===0||s===0)return 0;let i=r/Math.sqrt(o*s);return Number.isFinite(i)?i:0}function Ud(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 Fs(t={}){let e=t.maxSize;if(e!==void 0&&e<1)throw new RangeError("lightCollection: maxSize must be >= 1");let n=Le({name:t.name,...e!==void 0?{maxSize:e}:{}}),r=n.entries,o=ht({name:t.name?`${t.name}_events`:"events",retainedLimit:1024}),s=(f,m)=>{let h=K(),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()},c=Ce(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}})}),d=Ce(i,{audit:o,onSuccess:([f],m,h)=>({action:"remove",id:f,t_ns:h.t_ns})}),u=Ce(a,{audit:o,onSuccess:(f,m,h)=>({action:"clear",t_ns:h.t_ns})});function l(f){let m=Dt(f,"id");return C([r,m],([h,g])=>h?.get(g),{describeKind:"derived",meta:Ue("light_collection_item")})}function p(f){let m=Dt(f,"id");return C([r,m],([h,g])=>h?.has(g)??!1,{describeKind:"derived",meta:Ue("light_collection_has")})}return{entries:r,events:o,upsert:c,remove:d,clear:u,itemNode:l,hasNode:p}}function $s(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 ue(t.name??"vector_index"),c;function d(k){if(n!==void 0){if(k.length!==n)throw new RangeError(`vector dimension mismatch: expected ${n}, got ${k.length}`);return}if(r){if(c===void 0){c=k.length;return}if(k.length!==c)throw new RangeError(`vector dimension mismatch: inferred ${c} from first upsert, got ${k.length}. Pass \`strictDimension: false\` to opt into zero-pad behavior, or set an explicit \`dimension\`.`)}}let u=s??(k=>k.upsertedAtNs),l=!1,p=ht({name:"events",retainedLimit:1024,graph:a}),f=Mr(a,"seq",0),m=Le({name:"entries",...o!==void 0?{retention:{score:(k,M)=>u(M),maxSize:o,onArchive:k=>{l||(e==="hnsw"&&i.remove(k),p.append({action:"evict",id:k,t_ns:ie(),seq:Ot(f)}))}}}:{}});if(a.add(m.entries,{name:"entries"}),a.addDisposer(J(m.entries)),i?.dispose){let k=i.dispose.bind(i);a.addDisposer(()=>k())}let h=(k,M,N)=>{d(M),e==="hnsw"&&i.upsert(k,M,N);let E=(()=>{if(N!==void 0)return N===null||typeof N!="object"?N:Array.isArray(N)?[...N]:{...N}})(),x={id:k,vector:[...M],...E!==void 0?{meta:E}:{},upsertedAtNs:K()};m.set(k,x)},g=k=>{m.has(k)&&(e==="hnsw"&&i.remove(k),m.delete(k))},y=()=>{if(m.size!==0){l=!0;try{m.clear(),e==="hnsw"&&i.clear()}finally{l=!1}c=void 0}},b=()=>{if(e!=="hnsw")return;let k=m.entries.cache;if(k){i.clear();for(let M of k.values())i.upsert(M.id,M.vector,M.meta)}},v=Ce(h,{audit:p,freeze:!1,seq:f,onSuccess:([k],M,N)=>({action:"upsert",id:k,t_ns:N.t_ns,seq:N.seq})}),R=Ce(g,{audit:p,seq:f,onSuccess:([k],M,N)=>({action:"remove",id:k,t_ns:N.t_ns,seq:N.seq})}),_=Ce(y,{audit:p,seq:f,onSuccess:(k,M,N)=>({action:"clear",t_ns:N.t_ns,seq:N.seq})}),S=Ce(b,{audit:p,seq:f,onSuccess:(k,M,N)=>({action:"reindex",t_ns:N.t_ns,seq:N.seq})});function T(k,M=5){let N=Dt(M,"k");return C([m.entries,k,N],E=>{let x=E[0],O=E[1],V=E[2],$=Number.isFinite(V)?Math.max(0,Math.floor(V)):0;if(!x||x.size===0||$<=0)return[];if(O==null||O.length===0)return[];let Y=n??(r?c:void 0);return Y!==void 0&&O.length!==Y?[]:e==="hnsw"?[...i.search(O,$)]:[...x.values()].map(G=>({id:G.id,score:Ir(O,G.vector),...G.meta!==void 0?{meta:G.meta}:{}})).sort((G,z)=>z.score-G.score).slice(0,$)},{describeKind:"derived",equals:(E,x)=>Ud(E,x),meta:Ue("vector_search")})}return Object.assign(a,{backend:e,events:p,entries:m.entries,upsert:v,remove:R,clear:_,reindex:S,searchNode:T})}var Ds="\0";function _n(t,e,n){return`${t}${Ds}${e}${Ds}${n}`}function Is(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 Ps(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 js(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 ue(t),o=Le({name:"entities",...e.entitiesMaxSize!==void 0?{maxSize:e.entitiesMaxSize}:{}}),s=Le({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],([w])=>Is(w,"from"),{name:"adjacencyOut",describeKind:"derived",initial:new Map,equals:Ps,meta:Ue("adjacency_out")}),a=C([s.entries],([w])=>Is(w,"to"),{name:"adjacencyIn",describeKind:"derived",initial:new Map,equals:Ps,meta:Ue("adjacency_in")});r.add(i,{name:"adjacencyOut"}),r.add(a,{name:"adjacencyIn"}),r.addDisposer(J(i)),r.addDisposer(J(a));let c=C([o.entries],([w])=>(w??new Map).size,{name:"entityCount",describeKind:"derived",initial:0,meta:Ue("entity_count")}),d=C([s.entries],([w])=>(w??new Map).size,{name:"edgeCount",describeKind:"derived",initial:0,meta:Ue("edge_count")});r.add(c,{name:"entityCount"}),r.add(d,{name:"edgeCount"}),r.addDisposer(J(c)),r.addDisposer(J(d));let u=ht({name:"events",retainedLimit:1024,graph:r}),l=Mr(r,"seq",0);function p(w){let k=i.cache,M=a.cache;return(k?.get(w)?.length??0)>0||(M?.get(w)?.length??0)>0}function f(w){if(n==="remove")for(let k of w)o.has(k)&&(p(k)||(o.delete(k),u.append({action:"orphanRemove",id:k,t_ns:ie(),seq:Ot(l)})))}let m=(w,k)=>{o.set(w,k)},h=w=>{let k=s.entries.cache,M=new Set;if(k){let N=[];for(let[E,x]of k)(x.from===w||x.to===w)&&(N.push(E),x.from!==w&&M.add(x.from),x.to!==w&&M.add(x.to));N.length>0&&s.deleteMany(N)}o.has(w)&&o.delete(w),f([...M])},g=(w,k,M,N=1)=>{s.set(_n(w,k,M),{from:w,to:k,relation:M,weight:N})},y=(w,k,M)=>{if(M!==void 0)s.delete(_n(w,k,M));else{let N=s.entries.cache;if(!N)return;let E=[];for(let[x,O]of N)O.from===w&&O.to===k&&E.push(x);E.length>0&&s.deleteMany(E)}f([w,k])},b=Ce(m,{audit:u,seq:l,onSuccess:([w],k,M)=>({action:"upsertEntity",id:w,t_ns:M.t_ns,seq:M.seq})}),v=Ce(h,{audit:u,seq:l,onSuccess:([w],k,M)=>({action:"removeEntity",id:w,t_ns:M.t_ns,seq:M.seq})}),R=Ce(g,{audit:u,seq:l,onSuccess:([w,k,M,N],E,x)=>({action:"link",from:w,to:k,relation:M,weight:N??1,t_ns:x.t_ns,seq:x.seq})}),_=Ce(y,{audit:u,seq:l,onSuccess:([w,k,M],N,E)=>({action:"unlink",from:w,to:k,...M!==void 0?{relation:M}:{},t_ns:E.t_ns,seq:E.seq})});function S(w,k){let M=Dt(w,"id"),N=k!==void 0?Dt(k,"relation"):void 0;return C(N?[i,a,M,N]:[i,a,M],x=>{let O=x[0],V=x[1],$=x[2],Y=N?x[3]:void 0,X=O.get($)??[],G=V.get($)??[],z=new Set,A=[];for(let L of X){let q=_n(L.from,L.to,L.relation);z.has(q)||Y!==void 0&&L.relation!==Y||(z.add(q),A.push(L))}for(let L of G){let q=_n(L.from,L.to,L.relation);z.has(q)||Y!==void 0&&L.relation!==Y||(z.add(q),A.push(L))}return A},{describeKind:"derived",equals:(x,O)=>{let V=x,$=O;if(V===$)return!0;if(V==null||$==null||V.length!==$.length)return!1;for(let Y=0;Y<V.length;Y+=1){let X=V[Y],G=$[Y];if(X.from!==G.from||X.to!==G.to||X.relation!==G.relation||X.weight!==G.weight)return!1}return!0},meta:Ue("related")})}return Object.assign(r,{events:u,entities:o.entries,edges:s.entries,adjacencyOut:i,adjacencyIn:a,entityCount:c,edgeCount:d,upsertEntity:b,removeEntity:v,link:R,unlink:_,relatedNode:S})}var Pr=Math.LN2/604800;function bt(t){return t instanceof Map?t:new Map}function Gr(t,e,n){let r=$s({dimension:n.dimension});t.add(r.entries,{name:"vectorIndex"});let s=xe([e.store.entries],([i])=>{let a=bt(i);for(let[c,d]of a){let u=n.embedFn(d);u&&r.upsert(c,u,d)}}).subscribe(()=>{});return t.addDisposer(s),{vectors:r,dispose:()=>s()}}function Fr(t,e,n,r){let o=r.mountPath??n,s=js(`${n}-kg`);if(t.mount(o,s),!r.entityFn)return{kg:s,dispose:()=>{}};let i=r.entityFn,c=xe([e.store.entries],([d])=>{let u=bt(d);for(let[l,p]of u){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(c),{kg:s,dispose:()=>c()}}function $r(t,e,n){let r=n.decayRate??Pr,o=n.maxActive??1e3,s=n.archiveThreshold??.1,i=n.permanentFilter??(()=>!1),a=Fs({name:"permanent"});t.add(a.entries,{name:"permanent"});let c=new Set,d=b=>c.has(b)?"permanent":bt(e.store.entries.cache).has(b)?"active":"archived",u=(b,v)=>{c.add(b),a.upsert(b,v)},l=new Map,p=e.store.entries,f=n.context?F(n.context):P(null),h=xe([p,f],([b,v])=>{let R=bt(b),_=K(),S=[],T=[];for(let[k,M]of R){if(l.has(k)||l.set(k,_),i(k,M)){T.push({key:k,value:M});continue}let N=n.score(M,v),E=l.get(k)??_,x=Number(_-E)/1e9;Gs(N,x,r)<s&&S.push(k)}for(let k of l.keys())R.has(k)||l.delete(k);for(let{key:k,value:M}of T)c.has(k)||u(k,M);let w=R.size-c.size;if(w>o){let k=[...R.entries()].filter(([N])=>!c.has(N)).map(([N,E])=>({key:N,score:n.score(E,v)})).sort((N,E)=>N.score-E.score),M=w-o;for(let N=0;N<M&&N<k.length;N++){let E=k[N].key;S.includes(E)||S.push(E)}}S.length>0&&te(()=>{for(let k of S)e.store.delete(k)})}).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:u},dispose:y}}function Hd(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 jr(t,e,n,r,o){let s=o.topK??20,i=o.graphDepth??1,a=o.budget??2e3,c=o.contextWeight??0,d=o.context?F(o.context):P(null),u=(g,y,b)=>{let v=new Map,R=[];if(n&&b.vector){let M=b.vector,N=n.entries.cache;if(N&&N.size>0&&s>0){R=[...N.values()].map(x=>({id:x.id,score:Ir(M,x.vector),...x.meta!==void 0?{meta:x.meta}:{}})).sort((x,O)=>O.score-x.score).slice(0,s);for(let x of R){let O=g.get(x.id);O&&v.set(x.id,{value:O,sources:new Set(["vector"])})}}}let _=[];if(r){let M=r.adjacencyOut.cache,N=r.adjacencyIn.cache,E=[...b.entityIds??[],...v.keys()],x=new Set,O=E;for(let V=0;V<i;V++){let $=[];for(let Y of O){if(x.has(Y))continue;x.add(Y);let X=M?.get(Y)??[],G=N?.get(Y)??[];for(let z of X){let A=z.to;if(!x.has(A)){$.push(A);let L=g.get(A);if(L){let q=v.get(A);q?q.sources.add("graph"):v.set(A,{value:L,sources:new Set(["graph"])}),_.push(A)}}}for(let z of G){let A=z.from;if(!x.has(A)){$.push(A);let L=g.get(A);if(L){let q=v.get(A);q?q.sources.add("graph"):v.set(A,{value:L,sources:new Set(["graph"])}),_.push(A)}}}}O=$}}for(let[M,N]of g)v.has(M)||v.set(M,{value:N,sources:new Set(["store"])});let S=b.context?.length??0,T=[];for(let[M,{value:N,sources:E}]of v){let x=o.contextOf?o.contextOf(N):void 0,O=o.score(N,y);if(c>0&&S>0){let $=Hd(b.context,x);$>0&&(O=O*(1+c*$/S))}let V=x?{key:M,value:N,score:O,sources:[...E],context:x}:{key:M,value:N,score:O,sources:[...E]};T.push(V)}T.sort((M,N)=>N.score-M.score);let w=[],k=0;for(let M of T){let N=o.cost(M.value);if(k+N>a&&w.length>0)break;w.push(M),k+=N}return{packed:w,trace:{vectorCandidates:R,graphExpanded:_,ranked:T,packed:w}}},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=P([],{name:"retrieval",describeKind:"state",meta:H("retrieval_pipeline"),equals:l});t.add(p,{name:"retrieval"});let f=P(null,{name:"retrievalTrace",describeKind:"state",meta:H("retrieval_trace")});return t.add(f,{name:"retrievalTrace"}),{retrieval:p,retrievalTrace:f,retrieve:g=>{let y=bt(e.store.entries.cache),{packed:b,trace:v}=u(y,d.cache,g);return te(()=>{p.emit(b),f.emit(v)}),b},retrieveReactive:g=>{let y=F(g),b=C([e.store.entries,d,y],([_,S,T])=>{if(T==null)return{packed:[],trace:null};let w=bt(_),{packed:k,trace:M}=u(w,S,T);return{packed:k,trace:M}},{name:"retrievalReactive::result",describeKind:"derived",meta:H("retrieval_reactive_result"),initial:{packed:[],trace:null}}),R=xe([b],([_])=>{let S=_;te(()=>{p.emit(S.packed),S.trace&&f.emit(S.trace)})}).subscribe(()=>{});return t.addDisposer(R),C([b],([_])=>_.packed,{name:"retrievalReactive",describeKind:"derived",meta:H("retrieval_reactive"),initial:[],equals:l})}}}function qd(t,e,n){let r=new ue(t,n.graph);r.tagFactory("agentMemory",ut(n));let o;if(n.extractFn)o=n.extractFn;else if(n.adapter&&n.extractPrompt)o=Lr(n.extractPrompt,{adapter:n.adapter});else throw new Error("agentMemory: provide either extractFn or adapter + extractPrompt");let s=(b,v)=>{let R=v.cache??new Map,_=v.subscribe(S=>{for(let T of S)T[0]===D&&(R=T[1])});return r.addDisposer(_),pe(b,S=>S==null?{upsert:[]}:o(S,R))},i=e;if(n.admissionFilter){let b=F(e),v=n.admissionFilter;i=C([b],([R])=>{if(v(R))return R},{name:"admissionFilter",describeKind:"derived"})}let a;n.consolidateFn?a=n.consolidateFn:n.adapter&&n.consolidatePrompt&&(a=Dr(n.consolidatePrompt,{adapter:n.adapter}));let c=n.consolidateTrigger;if(!c&&a&&n.reflection?.enabled!==!1){let b=n.reflection?.interval??3e5;c=To(b,{period:b})}let d={score:n.score,cost:n.cost,budget:n.budget??2e3,context:n.context,consolidate:a,consolidateTrigger:c},u=Cs(i,s,d);r.add(u.store.entries,{name:"store"}),r.add(u.compact,{name:"compact"}),r.add(u.size,{name:"size"});let l=null;n.vectorDimensions&&n.vectorDimensions>0&&n.embedFn&&(l=Gr(r,u,{dimension:n.vectorDimensions,embedFn:n.embedFn}).vectors);let p=null;n.enableKnowledgeGraph&&(p=Fr(r,u,t,{mountPath:"kg",entityFn:n.entityFn}).kg);let f=null;n.tiers&&(f=$r(r,u,{...n.tiers,score:n.score,context:n.context}).tiers);let m=null,h=null,g=null,y=null;if(l||p){let b=jr(r,u,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:u,compact:u.compact,size:u.size,vectors:l,kg:p,memoryTiers:f,retrieval:m,retrievalTrace:h,retrieve:g,retrieveReactive:y})}function Wd(t,e,n){let r=t.describe({actor:e,detail:"full"}),o=n?.groupByTags??!0,s=n?.separator??`
|
|
16
|
+
`,i=[],a=n?.sinceVersion;for(let[c,d]of Object.entries(r.nodes)){let u=d.meta??{},l=u.description,p=u.format;if(!l&&!p)continue;if(a!=null&&d.v!=null){let y=a.get(c);if(y!=null&&y.id===d.v.id&&d.v.version<=y.version)continue}let f=l??c,m=d.value,h=u.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:c,description:f,formatted:g})}if(i.length===0)return"";if(o){let c=new Map,d=[];for(let l of i){let f=r.nodes[l.path].meta?.tags;if(f&&f.length>0){let m=f[0],h=c.get(m);h||(h=[],c.set(m,h)),h.push(l)}else d.push(l)}if(c.size===0)return i.map(l=>`- ${l.description}: ${l.formatted}`).join(s);let u=[];for(let[l,p]of[...c.entries()].sort((f,m)=>f[0].localeCompare(m[0])))u.push(`[${l}]${s}${p.map(f=>`- ${f.description}: ${f.formatted}`).join(s)}`);return d.length>0&&u.push(d.map(l=>`- ${l.description}: ${l.formatted}`).join(s)),u.join(s+s)}return i.map(c=>`- ${c.description}: ${c.formatted}`).join(s)}se();W();ee();W();Se();se();ke();W();function Bs(t,e){return Fe("reduction",t,e)}function Vs(t,e,n,r){let o=r?.maxIterations??10,s=`__feedback_${e}`,i=P(0,{meta:Bs("feedback_counter",{maxIterations:o,feedbackFrom:e,feedbackTo:n})});t.add(i,{name:s});let a=t.resolve(e),c=t.resolve(n),d=`__feedback_effect_${e}`,u=ne([],(l,p)=>{let f=a.subscribe(m=>{for(let h of m){let g=h[0];if(g===D){let y=h[1];if(y==null)return;te(()=>{Wo(i,o)&&c.emit(y)})}else if(g===B||g===I){let y=g===I&&h.length>1?[I,h[1]]:[g];i.down([y])}}});return()=>f()},{name:d,describeKind:"effect",meta:{...Bs("feedback_effect",{feedbackFrom:e,feedbackTo:n}),_internal:!0}});return t.add(u,{name:d}),t.addDisposer(J(u)),t}function Us(t){return typeof t=="object"&&t!==null&&"factory"in t}function Jd(t){return typeof t=="object"&&t!==null&&"factory"in t}function Yd(t){return Us(t)?t.factory:t}function Qd(t){return Jd(t)?t.factory:t}function Ks(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 Xd(t){let e={},n=!1;for(let[i,a]of Object.entries(t.nodes)){if(a.type==="template"){e[i]=a;continue}let c=Ks(a);e[i]=c,c!==a&&(n=!0)}let r=t.templates,o;if(r){o={};for(let[i,a]of Object.entries(r)){let c={},d=!1;for(let[u,l]of Object.entries(a.nodes)){let p=Ks(l);c[u]=p,p!==l&&(d=!0)}o[i]=d?{...a,nodes:c}:a,d&&(n=!0)}}if(!n)return t;let s={...t,nodes:e};return o&&(s.templates=o),s}function Zd(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 c=Br(a.fn,r);n.push(`Node "${s}": fn "${a.fn}" not found in catalog`+(c?`. Did you mean "${c}"?`:""))}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 c=Br(a.source,o);n.push(`Node "${s}": source "${a.source}" not found in catalog`+(c?`. Did you mean "${c}"?`:""))}if(a.fn&&a.config&&e.fns?.[a.fn]){let c=e.fns[a.fn];if(Us(c)&&c.configSchema){for(let[d,u]of Object.entries(c.configSchema))if(u.required!==!1&&!(d in a.config)&&n.push(`Node "${s}": config missing required field "${d}"`),d in a.config&&u.enum){let l=a.config[d];u.enum.includes(l)||n.push(`Node "${s}": config.${d} = ${JSON.stringify(l)}, expected one of: ${u.enum.join(", ")}`)}}}}if(t.templates){for(let[s,i]of Object.entries(t.templates))for(let[a,c]of Object.entries(i.nodes))if(c.fn&&r.size>0&&!r.has(c.fn)){let d=Br(c.fn,r);n.push(`Template "${s}" node "${a}": fn "${c.fn}" not found in catalog`+(d?`. Did you mean "${d}"?`:""))}}return{valid:n.length===0,errors:n,warnings:[]}}function Br(t,e){let n=null,r=1/0,o=t.toLowerCase();for(let s of e){let i=ec(o,s.toLowerCase());i<r&&i<=Math.max(3,Math.floor(t.length/2))&&(r=i,n=s)}return n}function ec(t,e){let n=t.length,r=e.length,o=Array.from({length:n+1},(s,i)=>Array.from({length:r+1},(a,c)=>i===0?c:c===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 zs=new Set(["state","producer","derived","effect","operator","template"]),tc=new Set(["state","producer","derived","effect","operator"]);function nc(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,c]of Object.entries(r.templates))if(c!=null&&typeof c=="object"){let d=c;i.set(a,{params:Array.isArray(d.params)?d.params:[]})}}if(r.templates!=null)if(typeof r.templates!="object"||Array.isArray(r.templates))e.push("'templates' must be an object");else for(let[a,c]of Object.entries(r.templates)){if(c==null||typeof c!="object"){e.push(`Template "${a}": must be an object`);continue}let d=c;if(Array.isArray(d.params)||e.push(`Template "${a}": missing 'params' array`),d.nodes==null||typeof d.nodes!="object"||Array.isArray(d.nodes))e.push(`Template "${a}": missing or invalid 'nodes' object`);else{let u=new Set(Array.isArray(d.params)?d.params:[]),l=new Set(Object.keys(d.nodes));for(let[p,f]of Object.entries(d.nodes)){if(f==null||typeof f!="object"){e.push(`Template "${a}" node "${p}": must be an object`);continue}let m=f;if((typeof m.type!="string"||!tc.has(m.type))&&e.push(`Template "${a}" node "${p}": invalid type`),Array.isArray(m.deps))for(let h of m.deps)!l.has(h)&&!u.has(h)&&e.push(`Template "${a}" node "${p}": dep "${h}" is not an inner node or param`)}typeof d.output!="string"?e.push(`Template "${a}": missing 'output' string`):d.nodes[d.output]||e.push(`Template "${a}": output "${d.output}" is not a declared node`)}}for(let[a,c]of Object.entries(r.nodes)){if(c==null||typeof c!="object"){e.push(`Node "${a}": must be an object`);continue}let d=c;if(typeof d.type!="string"||!zs.has(d.type)){e.push(`Node "${a}": invalid type "${String(d.type)}" (expected: ${[...zs].join(", ")})`);continue}if(s.set(a,d.type),d.type==="template")if(typeof d.template!="string"||!i.has(d.template))e.push(`Node "${a}": template "${String(d.template)}" not found in templates`);else if(d.bind==null||typeof d.bind!="object"||Array.isArray(d.bind))e.push(`Node "${a}": template ref requires 'bind' object`);else{let u=i.get(d.template),l=d.bind;for(let p of u.params)p in l||e.push(`Node "${a}": template param "${p}" is not bound (template "${d.template}")`);for(let[,p]of Object.entries(l))typeof p=="string"&&!o.has(p)&&e.push(`Node "${a}": bind target "${p}" does not reference an existing node`)}else{if(Array.isArray(d.deps))for(let u of d.deps)u===a?e.push(`Node "${a}": self-referencing dep`):o.has(u)||e.push(`Node "${a}": dep "${u}" does not reference an existing node`);(d.type==="derived"||d.type==="effect"||d.type==="operator")&&!Array.isArray(d.deps)&&e.push(`Node "${a}": ${d.type} node should have a 'deps' array`)}}if(r.feedback!=null)if(!Array.isArray(r.feedback))e.push("'feedback' must be an array");else for(let a=0;a<r.feedback.length;a++){let c=r.feedback[a];if(c==null||typeof c!="object"){e.push(`Feedback [${a}]: must be an object`);continue}let d=c;typeof d.from!="string"||!o.has(d.from)?e.push(`Feedback [${a}]: 'from' "${String(d.from)}" does not reference an existing node`):s.get(d.from)==="effect"&&n.push(`Feedback [${a}]: 'from' "${d.from}" is an effect node \u2014 effects emit no DATA, so the feedback edge will never fire. Did you mean a derived/state node upstream?`),typeof d.from=="string"&&d.from===d.to&&e.push(`Feedback [${a}]: 'from' and 'to' must be different nodes`),typeof d.to!="string"||!o.has(d.to)?e.push(`Feedback [${a}]: 'to' "${String(d.to)}" does not reference an existing node`):typeof d.to=="string"&&s.get(d.to)!=="state"&&e.push(`Feedback [${a}]: 'to' node "${d.to}" must be a state node (got "${s.get(d.to)??"unknown"}")`)}return{valid:e.length===0,errors:e,warnings:n}}function Hs(t,e){let n=nc(t);if(!n.valid)throw new Error(`compileSpec: invalid GraphSpec:
|
|
17
17
|
${n.errors.join(`
|
|
18
|
-
`)}`);let r=e?.catalog??{},
|
|
19
|
-
${
|
|
20
|
-
`)}`);let
|
|
21
|
-
${
|
|
22
|
-
`)}`)}if(
|
|
18
|
+
`)}`);let r=t.factory,o=t.factoryArgs;if(typeof r=="string"){let b=e?.catalog?.graphFactories?.[r];if(b)return b(o)}t=Xd(t);let s=e?.catalog??{},i=e?.onMissing??"placeholder",a=new ue(t.name),c=t.templates??{},d=Zd(t,s);if(!d.valid)throw new Error(`compileSpec: catalog validation errors:
|
|
19
|
+
${d.errors.join(`
|
|
20
|
+
`)}`);let u=[],l=(b,v,R)=>{if(R){u.push({path:b,kind:"source",name:R});return}v&&u.push({path:b,kind:"fn",name:v})},p=b=>{let v=s.fns?.[b];return v?Yd(v):void 0},f=b=>{let v=s.sources?.[b];return v?Qd(v):void 0},m=new Map,h=[];for(let[b,v]of Object.entries(t.nodes)){if(v.type==="template")continue;let R=v;if(R.type==="state"){let _=P(R.initial,{name:b,meta:R.meta?{...R.meta}:void 0});a.add(_,{name:b}),m.set(b,_)}else if(R.type==="producer"){let _=R.source?f(R.source):void 0,S=R.fn?p(R.fn):void 0;if(_){let T=_(R.config??{});a.add(T,{name:b}),m.set(b,T)}else if(S){let T=S([],R.config??{});a.add(T,{name:b}),m.set(b,T)}else{l(b,R.fn,R.source);let T=oe(()=>{},{name:b,meta:{...R.meta,_specFn:R.fn,_specSource:R.source}});a.add(T,{name:b}),m.set(b,T)}}else h.push([b,R])}let g=!0,y=new Map(h);for(;y.size>0&&g;){g=!1;for(let[b,v]of[...y.entries()]){let R=v.deps??[];if(!R.every(w=>m.has(w)))continue;let _=R.map(w=>m.get(w)),S=v.fn?p(v.fn):void 0,T;S?T=S(_,v.config??{}):v.type==="effect"?(v.fn&&l(b,v.fn,void 0),T=xe(_,()=>{})):(v.fn&&l(b,v.fn,void 0),T=C(_,w=>w[0])),a.add(T,{name:b}),m.set(b,T),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 R=v,_=c[R.template],S=new ue(b),T=new Map,w=[];for(let[E,x]of Object.entries(_.nodes)){let O=(x.deps??[]).map($=>$.startsWith("$")&&R.bind[$]?R.bind[$]:$),V={...x,deps:O};if(x.type==="state"){let $=P(x.initial,{name:E,meta:x.meta?{...x.meta}:void 0});S.add($,{name:E}),T.set(E,$)}else if(x.type==="producer"){let $=x.source?f(x.source):void 0,Y=x.fn?p(x.fn):void 0;if($){let X=$(x.config??{});S.add(X,{name:E}),T.set(E,X)}else if(Y){let X=Y([],x.config??{});S.add(X,{name:E}),T.set(E,X)}else{l(`${b}.${E}`,x.fn,x.source);let X=oe(()=>{},{name:E,meta:{...x.meta,_specFn:x.fn,_specSource:x.source}});S.add(X,{name:E}),T.set(E,X)}}else w.push([E,V])}let k=!0,M=new Map(w);for(;M.size>0&&k;){k=!1;for(let[E,x]of[...M.entries()]){let O=x.deps??[];if(!O.every(G=>T.has(G)||m.has(G)))continue;let $=O.map(G=>T.get(G)??m.get(G)),Y=x.fn?p(x.fn):void 0,X;Y?X=Y($,x.config??{}):x.type==="effect"?(x.fn&&l(`${b}.${E}`,x.fn,void 0),X=xe($,()=>{})):(x.fn&&l(`${b}.${E}`,x.fn,void 0),X=C($,G=>G[0])),S.add(X,{name:E}),T.set(E,X),M.delete(E),k=!0}}if(M.size>0){let E=[...M.keys()].sort().join(", ");throw new Error(`compileSpec: template "${R.template}" has unresolvable deps: ${E}`)}a.mount(b,S);let N=`${b}::${_.output}`;m.set(b,a.resolve(N));try{let E=a.resolve(N);E.meta._templateName?.emit(R.template),E.meta._templateBind?.emit(R.bind)}catch{}}for(let b of t.feedback??[])Vs(a,b.from,b.to,{maxIterations:b.maxIterations});if(u.length>0){if(i==="error"){let b=u.map(v=>` - ${v.path}: missing ${v.kind} "${v.name}"`);throw new Error(`compileSpec: ${u.length} catalog entr${u.length===1?"y":"ies"} missing \u2014 pass them via opts.catalog or set opts.onMissing to "warn"/"placeholder":
|
|
21
|
+
${b.join(`
|
|
22
|
+
`)}`)}if(i==="warn"){let b=e?.onWarn??(v=>console.warn(v));for(let v of u)b(`compileSpec: ${v.path} references missing ${v.kind} "${v.name}" \u2014 substituted placeholder`)}}return a}var qs=`You are a graph architect for GraphReFly, a reactive graph protocol.
|
|
23
23
|
|
|
24
24
|
Given a natural-language description, produce a JSON graph specification with this structure:
|
|
25
25
|
|
|
@@ -52,9 +52,9 @@ Rules:
|
|
|
52
52
|
- "operator" nodes are parameterized transformations with deps.
|
|
53
53
|
- Use "deps" inside each node to declare dependencies \u2014 no separate "edges" array.
|
|
54
54
|
- meta.description is required for every node.
|
|
55
|
-
- Return ONLY valid JSON, no markdown fences or commentary.`;async function
|
|
55
|
+
- Return ONLY valid JSON, no markdown fences or commentary.`;async function Ws(t,e,n){let o=[{role:"system",content:n?.systemPromptExtra?`${qs}
|
|
56
56
|
|
|
57
|
-
${n.systemPromptExtra}`:
|
|
57
|
+
${n.systemPromptExtra}`:qs},{role:"user",content:t}],s=e.invoke(o,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens,signal:n?.signal}),a=(await Et(s)).content.trim();a.startsWith("```")&&(a=gt(a));let c;try{c=JSON.parse(a)}catch{throw new Error(`graphFromSpec: LLM response is not valid JSON: ${a.slice(0,200)}`)}return Hs(c,{catalog:n?.catalog})}function rc(t,e,n){let r=F(t);return pe(r,o=>!o||typeof o!="string"||o.trim().length===0?P(null):oe(s=>{let i=new AbortController,a=!1;return Ws(o,e,{...n,signal:i.signal}).then(c=>{if(a){c.destroy();return}s.emit(c),s.down([[B]])}).catch(c=>{a||s.down([[I,c]])}),()=>{a=!0,i.abort()}},{name:"graphFromSpec::call"}))}function oc(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 sc(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 c=a.meta??{},d=c.access;if(d==="human"||d==="system")continue;let u=c.description??`Set the value of ${i}`,l=oc(c),p={type:"object",required:["value"],properties:{value:l},additionalProperties:!1},f=i.replace(/::/g,"__");r.push({type:"function",function:{name:f,description:u,parameters:p}}),o.push({name:i,description:u,inputSchema:p});let m=t,h=e,g=a.v;s.push({name:i,description:u,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}}se();W();ee();var ic=`You are a reactive graph optimizer for GraphReFly.
|
|
58
58
|
|
|
59
59
|
Given a graph's current structure (from describe()) and a problem statement, suggest topology and parameter changes to solve the problem.
|
|
60
60
|
|
|
@@ -75,4 +75,4 @@ Return ONLY valid JSON with this structure:
|
|
|
75
75
|
Rules:
|
|
76
76
|
- Only suggest operations that reference existing nodes (for remove/disconnect/set_value/update_meta) or new nodes you define (for add_node).
|
|
77
77
|
- Keep changes minimal \u2014 prefer the smallest set of operations that solves the problem.
|
|
78
|
-
- Return ONLY valid JSON, no markdown fences or commentary.`;async function
|
|
78
|
+
- Return ONLY valid JSON, no markdown fences or commentary.`;async function Js(t,e,n,r){let{expand:o,...s}=t.describe({actor:r?.actor,detail:"standard"}),i=[{role:"system",content:ic},{role:"user",content:JSON.stringify({graph:s,problem:e})}],a=n.invoke(i,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens,signal:r?.signal}),d=(await Et(a)).content.trim();d.startsWith("```")&&(d=d.replace(/^```(?:json)?\s*/,"").replace(/\s*```$/,""));let u;try{u=JSON.parse(d)}catch{throw new Error(`suggestStrategy: LLM response is not valid JSON: ${d.slice(0,200)}`)}let l=u;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 ac(t,e,n,r){let o=F(e),s=So(o,t);return pe(s,i=>{if(i==null)return P(null);let[a,c]=i;return!c||!a||typeof a!="string"||a.trim().length===0?P(null):c.destroyed?P(null):oe(d=>{let u=new AbortController,l=!1;return Js(c,a,n,{...r,signal:u.signal}).then(p=>{l||(d.emit(p),d.down([[B]]))}).catch(p=>{l||d.down([[I,p]])}),()=>{l=!0,u.abort()}},{name:"suggestStrategy::call"})})}var Ys=new Set(["state","derived","producer","operator","effect"]);function dc(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"||!Ys.has(i.type))&&e.push(`Node "${o}": invalid type "${String(i.type)}" (expected: ${[...Ys].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 c=`${a.from}->${a.to}`;o.has(c)&&e.push(`Edge [${s}]: duplicate edge ${c}`),o.add(c)}}return{valid:e.length===0,errors:e}}0&&(module.exports={AgentLoopGraph,AllTiersExhaustedError,BudgetExhaustedError,ChatStreamGraph,CircuitOpenError,DEFAULT_DECAY_RATE,FallbackMissError,LLMTimeoutError,ReplayCacheMissError,ToolRegistryGraph,admissionFilter3D,admissionScored,agentLoop,agentMemory,anthropicAdapter,canonicalJson,cascadingLlmAdapter,chatStream,composePricing,computePrice,contentGate,costMeterExtractor,createAdapter,createCapabilitiesRegistry,createPricingRegistry,dryRunAdapter,fallbackAdapter,fromLLM,frozenContext,gatedStream,gaugesAsContext,googleAdapter,graphFromSpec,graphFromSpecReactive,handoff,keywordFlagExtractor,knobsAsTools,llmConsolidator,llmExtractor,memoryRetrieval,memoryWithKG,memoryWithTiers,memoryWithVectors,observableAdapter,openAICompatAdapter,parseRateLimitFromError,pricingFor,promptNode,redactor,registryPricing,resilientAdapter,streamExtractor,streamingPromptNode,suggestStrategy,suggestStrategyReactive,systemPromptBuilder,tier,toolCallExtractor,toolExecution,toolRegistry,toolSelector,validateGraphDef,withBreaker,withBudgetGate,withDryRun,withRateLimiter,withReplayCache,withRetry,withTimeout,zeroPrice});
|