@graphrefly/graphrefly 0.30.0 → 0.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{cascading-dNCtjW8j.d.cts → cascading-BfQmSmjU.d.cts} +21 -2
- package/dist/{cascading-BszPheHD.d.ts → cascading-D3sapjue.d.ts} +21 -2
- package/dist/{chunk-T5SHIKJD.js → chunk-3JRKP4BH.js} +1 -1
- package/dist/{chunk-GJR3P6JG.js → chunk-3Q2WXM6X.js} +1 -1
- package/dist/chunk-4KAUNEKV.js +3 -0
- package/dist/{chunk-SLMYTGTU.js → chunk-4UUDNFYG.js} +1 -1
- package/dist/chunk-4VXL3UZK.js +1 -0
- package/dist/{chunk-AV3PIDFQ.js → chunk-4ZPO2EL5.js} +1 -1
- package/dist/{chunk-VWPRPPKR.js → chunk-5LJAQTSS.js} +1 -1
- package/dist/{chunk-W4TSQ6RJ.js → chunk-7AJKUA36.js} +1 -1
- package/dist/{chunk-RD52SNH2.js → chunk-7EJTWGKW.js} +1 -1
- package/dist/{chunk-GNCBXARM.js → chunk-7EQPXQ7H.js} +1 -1
- package/dist/chunk-7QMVU3IX.js +1 -0
- package/dist/{chunk-BA5URFYW.js → chunk-A4JT4SAD.js} +1 -1
- package/dist/chunk-ASDKRNOJ.js +60 -0
- package/dist/{chunk-Y32RJO24.js → chunk-CZVYLXFK.js} +1 -1
- package/dist/{chunk-567NWZ3T.js → chunk-DWIAG62L.js} +1 -1
- package/dist/{chunk-33FA6V4B.js → chunk-EBQ6FXKW.js} +1 -1
- package/dist/chunk-FTA5TB2A.js +1 -0
- package/dist/{chunk-P7JXGKDO.js → chunk-GF5T7PGC.js} +1 -1
- package/dist/{chunk-WANIEEKV.js → chunk-I4U3TPK2.js} +1 -1
- package/dist/{chunk-KA6MMXIY.js → chunk-JMGGCSIC.js} +1 -1
- package/dist/chunk-JXRZXP3N.js +1 -0
- package/dist/{chunk-5Z4HDCO6.js → chunk-K54OKWNY.js} +1 -1
- package/dist/{chunk-DDPYNMGG.js → chunk-KN4Q5MQO.js} +1 -1
- package/dist/chunk-LWGLBCMU.js +1 -0
- package/dist/{chunk-TWMEGG45.js → chunk-N2KKISCE.js} +1 -1
- package/dist/{chunk-4OFIQ66T.js → chunk-OKQUPJRY.js} +1 -1
- package/dist/chunk-PNTBXOQ6.js +5 -0
- package/dist/chunk-PSQNYY72.js +7 -0
- package/dist/{chunk-XHVB6G6M.js → chunk-PZP4MEXK.js} +1 -1
- package/dist/{chunk-7TDOES3L.js → chunk-Q2SY7M7K.js} +1 -1
- package/dist/{chunk-OL33ZI6R.js → chunk-RWGJQQLT.js} +1 -1
- package/dist/chunk-SGS4OJGS.js +1 -0
- package/dist/chunk-UMH3HSP7.js +1 -0
- package/dist/{chunk-BZP5T4X6.js → chunk-W6FQIFVE.js} +1 -1
- package/dist/{chunk-SHYH5SXV.js → chunk-WLPVGXQ6.js} +1 -1
- package/dist/chunk-WQ7I7JVU.js +1 -0
- package/dist/{chunk-XQAXYVXX.js → chunk-WYJTXYWX.js} +1 -1
- package/dist/{chunk-3NEPQO2E.js → chunk-X2VHDT26.js} +1 -1
- package/dist/{chunk-GLSM33ZM.js → chunk-XEFAMCEA.js} +1 -1
- package/dist/{chunk-AUY2YKCO.js → chunk-XRSHMHEG.js} +1 -1
- package/dist/chunk-Y26UN6J5.js +18 -0
- package/dist/{chunk-BKPLTBL5.js → chunk-YQJPYEAL.js} +1 -1
- package/dist/{chunk-73Z3W2RN.js → chunk-YZ6VYLFD.js} +1 -1
- package/dist/{chunk-4JJCCD5S.js → chunk-YZKGGMPT.js} +1 -1
- package/dist/chunk-Z3UWIJ3A.js +1 -0
- package/dist/{chunk-Y36UZ5VS.js → chunk-ZM7C2FUM.js} +1 -1
- package/dist/compat/index.cjs +1 -1
- package/dist/compat/index.js +1 -1
- package/dist/compat/jotai/index.cjs +1 -1
- package/dist/compat/jotai/index.js +1 -1
- package/dist/compat/nanostores/index.cjs +1 -1
- package/dist/compat/nanostores/index.js +1 -1
- package/dist/compat/nestjs/index.cjs +5 -5
- package/dist/compat/nestjs/index.js +1 -1
- package/dist/compat/zustand/index.cjs +1 -1
- package/dist/compat/zustand/index.js +1 -1
- package/dist/{composite-DGspwCqk.d.ts → composite-BY9hMxN7.d.ts} +1 -1
- package/dist/{composite-nrRumJ7l.d.cts → composite-CH0S8DFn.d.cts} +1 -1
- package/dist/content-addressed-storage-BUiREIuj.d.ts +124 -0
- package/dist/content-addressed-storage-DqIWCmZG.d.cts +124 -0
- package/dist/core/index.cjs +1 -1
- package/dist/core/index.js +1 -1
- package/dist/extra/browser.cjs +1 -1
- package/dist/extra/browser.js +1 -1
- package/dist/extra/index.cjs +18 -18
- package/dist/extra/index.d.cts +6 -5
- package/dist/extra/index.d.ts +6 -5
- package/dist/extra/index.js +1 -1
- package/dist/extra/node.cjs +2 -2
- package/dist/extra/node.js +1 -1
- package/dist/extra/operators.cjs +1 -1
- package/dist/extra/operators.d.cts +41 -1
- package/dist/extra/operators.d.ts +41 -1
- package/dist/extra/operators.js +1 -1
- package/dist/extra/reactive.cjs +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.d.cts +62 -2
- package/dist/extra/sources.d.ts +62 -2
- package/dist/extra/sources.js +1 -1
- package/dist/extra/storage-browser.cjs +1 -1
- package/dist/extra/storage-browser.js +1 -1
- package/dist/{fallback-BaTS7vVY.d.cts → fallback-Cb3GH1O7.d.cts} +6 -14
- package/dist/{fallback-eOm3LNxP.d.ts → fallback-DRjJ_ZM8.d.ts} +6 -14
- package/dist/graph/index.cjs +4 -4
- package/dist/graph/index.js +1 -1
- package/dist/{index-ClB7TCfL.d.cts → index-BMe3pCom.d.cts} +1 -1
- package/dist/{index-Dljd76bC.d.ts → index-BXzl1NDD.d.ts} +1 -1
- package/dist/{index-ClgKmOHe.d.ts → index-Bd6oFZqO.d.ts} +223 -115
- package/dist/{index-BJHQUCZx.d.ts → index-CJymKyzT.d.ts} +81 -6
- package/dist/{index-D6ajK8Mh.d.cts → index-CZChc85Q.d.cts} +223 -115
- package/dist/{index-BXbQUn4n.d.ts → index-CcS0t-l2.d.ts} +1 -1
- package/dist/{index-B2HBxvMb.d.ts → index-CwhcFzTA.d.ts} +1 -1
- package/dist/{index-B8Aj_z8S.d.cts → index-D-kHVedZ.d.cts} +1 -1
- package/dist/{index-ybtSyjWB.d.cts → index-DD7RhHNJ.d.cts} +1 -1
- package/dist/{index-BHu_Wba0.d.cts → index-Dm3_D5Ta.d.cts} +1 -1
- package/dist/{index-Cc8VQIgL.d.ts → index-DxMS0cHM.d.ts} +1 -1
- package/dist/{index-BS220yqj.d.cts → index-gJQqJTKx.d.cts} +81 -6
- package/dist/index.cjs +99 -121
- package/dist/index.d.cts +14 -13
- package/dist/index.d.ts +14 -13
- package/dist/index.js +1 -1
- package/dist/patterns/ai/browser.cjs +5 -22
- package/dist/patterns/ai/browser.d.cts +3 -3
- package/dist/patterns/ai/browser.d.ts +3 -3
- package/dist/patterns/ai/browser.js +1 -1
- package/dist/patterns/ai/index.cjs +27 -44
- package/dist/patterns/ai/index.d.cts +9 -7
- package/dist/patterns/ai/index.d.ts +9 -7
- package/dist/patterns/ai/index.js +1 -1
- package/dist/patterns/ai/node.cjs +2 -2
- package/dist/patterns/ai/node.d.cts +5 -4
- package/dist/patterns/ai/node.d.ts +5 -4
- package/dist/patterns/ai/node.js +1 -1
- package/dist/patterns/audit/index.cjs +3 -3
- package/dist/patterns/audit/index.js +1 -1
- package/dist/patterns/cqrs/index.cjs +6 -6
- package/dist/patterns/cqrs/index.js +1 -1
- package/dist/patterns/demo-shell/index.cjs +1 -1
- package/dist/patterns/demo-shell/index.js +1 -1
- package/dist/patterns/domain-templates/index.cjs +4 -4
- package/dist/patterns/domain-templates/index.js +1 -1
- package/dist/patterns/graphspec/index.cjs +6 -6
- package/dist/patterns/graphspec/index.d.cts +2 -2
- package/dist/patterns/graphspec/index.d.ts +2 -2
- package/dist/patterns/graphspec/index.js +1 -1
- package/dist/patterns/guarded-execution/index.cjs +7 -7
- package/dist/patterns/guarded-execution/index.js +1 -1
- package/dist/patterns/harness/index.cjs +11 -11
- package/dist/patterns/harness/index.d.cts +2 -2
- package/dist/patterns/harness/index.d.ts +2 -2
- package/dist/patterns/harness/index.js +1 -1
- package/dist/patterns/job-queue/index.cjs +5 -5
- package/dist/patterns/job-queue/index.js +1 -1
- package/dist/patterns/lens/index.cjs +5 -5
- package/dist/patterns/lens/index.d.cts +2 -2
- package/dist/patterns/lens/index.d.ts +2 -2
- package/dist/patterns/lens/index.js +1 -1
- package/dist/patterns/memory/index.cjs +4 -4
- package/dist/patterns/memory/index.js +1 -1
- package/dist/patterns/messaging/index.cjs +5 -5
- package/dist/patterns/messaging/index.js +1 -1
- package/dist/patterns/orchestration/index.cjs +1 -1
- package/dist/patterns/orchestration/index.js +1 -1
- package/dist/patterns/reactive-layout/index.cjs +1 -1
- package/dist/patterns/reactive-layout/index.js +1 -1
- package/dist/patterns/reduction/index.cjs +5 -5
- package/dist/patterns/reduction/index.js +1 -1
- package/dist/patterns/refine-loop/index.cjs +8 -8
- package/dist/patterns/refine-loop/index.js +1 -1
- package/dist/patterns/resilient-pipeline/index.cjs +1 -1
- package/dist/patterns/resilient-pipeline/index.js +1 -1
- package/dist/patterns/surface/index.cjs +7 -7
- package/dist/patterns/surface/index.d.cts +3 -3
- package/dist/patterns/surface/index.d.ts +3 -3
- package/dist/patterns/surface/index.js +1 -1
- package/dist/{reactive-map-BvDrRuwt.d.ts → reactive-map-CtRaCddO.d.ts} +59 -1
- package/dist/{reactive-map-CmlPPKHN.d.cts → reactive-map-IJIfZxoh.d.cts} +59 -1
- package/dist/{resilience-XRUF267O.js → resilience-IVNDYORD.js} +1 -1
- package/dist/{types-O3GzJY2U.d.cts → types-BgMqbc7N.d.cts} +41 -14
- package/dist/{types-u64Ose53.d.ts → types-CdfO2QTt.d.ts} +41 -14
- package/package.json +1 -1
- package/dist/chunk-2GQREQ6C.js +0 -1
- package/dist/chunk-4C2OR2GH.js +0 -18
- package/dist/chunk-5JDE5JHE.js +0 -1
- package/dist/chunk-7JDLFI6N.js +0 -1
- package/dist/chunk-AMBYCIOH.js +0 -3
- package/dist/chunk-ISCENNXS.js +0 -1
- package/dist/chunk-IUK4EFCE.js +0 -1
- package/dist/chunk-KASHOCF5.js +0 -1
- package/dist/chunk-LI3E75VE.js +0 -64
- package/dist/chunk-MGKAO4EK.js +0 -7
- package/dist/chunk-NSG4C6BF.js +0 -23
- package/dist/chunk-VIEUJSTT.js +0 -1
package/dist/chunk-LI3E75VE.js
DELETED
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
import{a as mt,b as ct,d as pt,e as ft}from"./chunk-4OFIQ66T.js";import{e as dt}from"./chunk-VWPRPPKR.js";import{e as De}from"./chunk-33FA6V4B.js";import{a as Ct,b as Pt,c as jt,d as _t,e as Dt,f as _e}from"./chunk-NSG4C6BF.js";import{a as Me,b as At,c as St,d as Et,e as It,f as Ot}from"./chunk-7JDLFI6N.js";import{c as it}from"./chunk-5Z4HDCO6.js";import{b as ut}from"./chunk-IUK4EFCE.js";import{b as rt,c as Re,d as nt,f as je}from"./chunk-OL33ZI6R.js";import{k as Z}from"./chunk-MGKAO4EK.js";import{a as X}from"./chunk-ESMPEKEV.js";import{P as lt,v as J}from"./chunk-5JDE5JHE.js";import{b as ge}from"./chunk-AUY2YKCO.js";import{A as K,f as ot,m as w,w as at,y as st}from"./chunk-KASHOCF5.js";import{D as se,E as v,F as Pe,G as x,H as ie,m as ae,o as W,p as Te}from"./chunk-W4TSQ6RJ.js";import{b as q,d as fe,i as re,j as Y}from"./chunk-CK2E7BTU.js";import{b as Nt}from"./chunk-QYADASLV.js";var _r={};Nt(_r,{AgentLoopGraph:()=>Oe,AllTiersExhaustedError:()=>Dt,BudgetExhaustedError:()=>Ne,ChatStreamGraph:()=>Ee,CircuitOpenError:()=>Re,DEFAULT_DECAY_RATE:()=>Xe,FallbackMissError:()=>It,LLMTimeoutError:()=>he,ReplayCacheMissError:()=>At,ToolRegistryGraph:()=>Ie,admissionFilter3D:()=>Cr,agentLoop:()=>Rr,agentMemory:()=>Ar,anthropicAdapter:()=>Ct,canonicalJson:()=>Et,cascadingLlmAdapter:()=>_e,chatStream:()=>ze,composePricing:()=>Kt,computePrice:()=>yt,contentGate:()=>kr,costMeterExtractor:()=>gr,createAdapter:()=>_t,createCapabilitiesRegistry:()=>Ft,createPricingRegistry:()=>$t,dryRunAdapter:()=>Me,dryRunPreset:()=>rr,fallbackAdapter:()=>Ot,fromLLM:()=>nr,frozenContext:()=>lr,gatedStream:()=>cr,gaugesAsContext:()=>Sr,googleAdapter:()=>Pt,graphFromSpec:()=>Er,handoff:()=>Lr,keywordFlagExtractor:()=>hr,knobsAsTools:()=>Or,llmConsolidator:()=>Qe,llmExtractor:()=>Ye,observableAdapter:()=>Gt,openAICompatAdapter:()=>jt,parseRateLimitFromError:()=>Ke,promptNode:()=>dr,redactor:()=>vr,registryPricing:()=>Wt,resilientAdapter:()=>tr,streamExtractor:()=>br,streamingPromptNode:()=>mr,suggestStrategy:()=>jr,systemPromptBuilder:()=>pr,toolCallExtractor:()=>Mr,toolRegistry:()=>Je,toolSelector:()=>wr,validateGraphDef:()=>Ze,withBreaker:()=>Be,withBudgetGate:()=>We,withDryRun:()=>Vt,withRateLimiter:()=>Ve,withReplayCache:()=>St,withRetry:()=>He,withTimeout:()=>qe,zeroPrice:()=>Ge});function Le(t,e){return`${t}::${e}`}function Ft(t){let e=new Map,r=new Map,o=n=>{e.set(Le(n.provider,n.id),n);let a=r.get(n.provider);a||(a=new Set,r.set(n.provider,a)),a.add(n.id)};if(t)for(let n of t)o(n);return{register:o,lookup(n,a){let s=e.get(Le(n,a));if(s)return s;let i=r.get(n);if(!i)return;let l;for(let m of i)if(a.startsWith(m)&&(!l||m.length>l.key.length)){let d=e.get(Le(n,m));d&&(l={key:m,cap:d})}return l?.cap},remove(n,a){let s=e.delete(Le(n,a));if(s){let i=r.get(n);i?.delete(a),i&&i.size===0&&r.delete(n)}return s},entries(){return e.values()}}}function ne(t){let e=t.input,r=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 r;let o=0;for(let n of Object.values(e.extensions))o+=n;return r+o}function le(t){let e=t.output,r=e.regular+(e.reasoning??0)+(e.audio??0)+(e.predictionAccepted??0)+(e.predictionRejected??0);if(!e.extensions)return r;let o=0;for(let n of Object.values(e.extensions))o+=n;return r+o}function gt(){return{input:{regular:0},output:{regular:0}}}function Gt(t,e){let r=e?.logMax??1e3,o=ge(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:r}),n=v(null,{name:"adapterStats/lastCall"}),a=v(0,{name:"adapterStats/totalCalls"}),s=v(0,{name:"adapterStats/totalInputTokens"}),i=v(0,{name:"adapterStats/totalOutputTokens"}),l=p=>{o.append(p),n.emit(p),a.emit((a.cache??0)+1),s.emit((s.cache??0)+ne(p.usage)),i.emit((i.cache??0)+le(p.usage))},m=()=>{o.clear(),n.emit(null),a.emit(0),s.emit(0),i.emit(0)};return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),invoke(p,c){let f=W(),y=Te(),g=t.invoke(p,c),T=b=>{let A=W();return l({timestamp:A,wallClock:y,provider:t.provider,model:t.model??c?.model??b.model??"",tier:c?.tier??b.tier,usage:b.usage??Fe(),latencyMs:Math.max(0,(A-f)/1e6),method:"invoke"}),b};if(g!=null&&typeof g.then=="function")return g.then(T);if(g!=null&&typeof g=="object"&&"content"in g)return T(g);let C=!1;return x([w(g)],([b])=>b==null||C?b:(C=!0,T(b)),{name:"adapterStats/invokeTap"})},async*stream(p,c){let f=W(),y=Te(),g;try{for await(let C of t.stream(p,c))C.type==="usage"&&(g=C.usage),yield C;let T=W();l({timestamp:T,wallClock:y,provider:t.provider,model:t.model??c?.model??"",tier:c?.tier,usage:g??Fe(),latencyMs:Math.max(0,(T-f)/1e6),method:"stream"})}catch(T){let C=W(),b=T;throw l({timestamp:C,wallClock:y,provider:t.provider,model:t.model??c?.model??"",tier:c?.tier,usage:g??Fe(),latencyMs:Math.max(0,(C-f)/1e6),method:"stream",error:{type:b?.name??"Error",message:b?.message??String(T)}}),T}}},stats:{lastCall:n,allCalls:o,totalCalls:a,totalInputTokens:s,totalOutputTokens:i,reset:m}}}function Fe(){return{input:{regular:0},output:{regular:0}}}function Bt(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function Ge(t="USD"){return{total:0,currency:t}}function yt(t,e,r){let o=ne(t),n=e.currency??"USD",a=r?.withBreakdown===!0,s=a?{}:null,i=0,l=(g,T,C)=>{if(!T||C==null)return;let b=Bt(C,o),A=T*b/1e6;i+=A,a&&(s[g]=(s[g]??0)+A)},m=t.input,d=e.input;if(d&&(l("input.regular",m.regular,d.regular),l("input.cacheRead",m.cacheRead??0,d.cacheRead),l("input.cacheWrite5m",m.cacheWrite5m??0,d.cacheWrite5m),l("input.cacheWrite1h",m.cacheWrite1h??0,d.cacheWrite1h),l("input.cacheWriteOther",m.cacheWriteOther??0,d.cacheWriteOther),l("input.audio",m.audio??0,d.audio),l("input.image",m.image??0,d.image),l("input.video",m.video??0,d.video),l("input.toolUse",m.toolUse??0,d.toolUse),m.extensions&&d.extensions))for(let[g,T]of Object.entries(m.extensions))l(`input.ext.${g}`,T,d.extensions[g]);let u=t.output,p=e.output;if(p&&(l("output.regular",u.regular,p.regular),l("output.reasoning",u.reasoning??0,p.reasoning),l("output.audio",u.audio??0,p.audio),l("output.predictionAccepted",u.predictionAccepted??0,p.predictionAccepted),l("output.predictionRejected",u.predictionRejected??0,p.predictionRejected),u.extensions&&p.extensions))for(let[g,T]of Object.entries(u.extensions))l(`output.ext.${g}`,T,p.extensions[g]);let c=r?.tier;if(c&&e.tierMultipliers){let g=e.tierMultipliers[c];if(g!=null&&(i*=g,a))for(let T of Object.keys(s))s[T]*=g}let f=t.auxiliary,y=e.auxiliary;if(f&&y)for(let[g,T]of Object.entries(f)){let C=y[g];if(C==null||!T)continue;let b=T*C;i+=b,a&&(s[`auxiliary.${g}`]=b)}return a?{total:i,currency:n,breakdown:s}:{total:i,currency:n}}function we(t,e){return`${t}::${e}`}function $t(t){let e=new Map,r=new Map,o=(n,a,s)=>{e.set(we(n,a),{provider:n,model:a,pricing:s});let i=r.get(n);i||(i=new Set,r.set(n,i)),i.add(a)};if(t)for(let[n,a,s]of t)o(n,a,s);return{register:o,lookup(n,a){let s=e.get(we(n,a));if(s)return s.pricing;let i=r.get(n);if(!i)return;let l;for(let m of i)if(a.startsWith(m)&&(!l||m.length>l.key.length)){let d=e.get(we(n,m));d&&(l={key:m,pricing:d.pricing})}return l?.pricing},remove(n,a){let s=e.delete(we(n,a));if(s){let i=r.get(n);i?.delete(a),i&&i.size===0&&r.delete(n)}return s},entries(){let n=e.values();return(function*(){for(let{provider:a,model:s,pricing:i}of n)yield[a,s,i]})()}}}function Wt(t,e="USD"){return(r,o)=>{let n=t.lookup(o.provider,o.model);return n?yt(r,n,{tier:o.tier,withBreakdown:o.withBreakdown}):Ge(e)}}function Kt(...t){return(e,r)=>{for(let o of t){let n=o(e,r);if(n.total!==0)return n}return t.length>0?t[0](e,r):Ge()}}function Be(t,e={}){let r=e.breaker??nt(e);return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(n,a){if(!r.canExecute())throw new Re;try{let s=await Promise.resolve(t.invoke(n,a));return r.recordSuccess(),s}catch(s){throw r.recordFailure(s),s}},async*stream(n,a){if(!r.canExecute())throw new Re;try{for await(let s of t.stream(n,a))yield s;r.recordSuccess()}catch(s){throw r.recordFailure(s),s}}},breaker:r}}var Ne=class extends Error{constructor(r,o,n){super(`Budget exhausted: ${r} (limit=${o}, observed=${n})`);this.which=r;this.limit=o;this.observed=n}name="BudgetExhaustedError"},$e=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),ht=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function We(t,e){let r=ge(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),o=v(ht(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),n=x([o],([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(K(n),e.onExhausted!=null){let d=e.onExhausted,u=!1,p=!0;n.subscribe(c=>{for(let f of c)if(f[0]===q){let y=f[1];if(u&&p&&y===!1){let g=bt(o.cache??$e,e.caps);g&&d(g)}p=y,u=!0}})}let a=()=>{if(n.cache===!1){let d=o.cache??$e,u=bt(d,e.caps);return new Ne(u??"budget",e.caps[u??"calls"]??0,Ut(d,u??"calls"))}},s=(d,u)=>{let p=t.provider,c={timestamp:W(),wallClock:Te(),provider:p,model:u.model,tier:u.tier,usage:d,latencyMs:u.latencyMs,method:u.method,...u.error?{error:u.error}:{}};r.append(c);let f=o.cache??$e,y=e.pricingFn?f.usd+e.pricingFn(d,{model:u.model,provider:p,tier:u.tier}).total:f.usd;o.emit({calls:f.calls+1,inputTokens:f.inputTokens+ne(d),outputTokens:f.outputTokens+le(d),usd:y})},i=()=>{r.clear(),o.emit(ht())},l=()=>({input:{regular:0},output:{regular:0}});return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),invoke(d,u){let p=a();if(p)return Promise.reject(p);let c=W(),f=t.invoke(d,u),y=T=>{let C=Math.max(0,(W()-c)/1e6);return s(T.usage??l(),{model:t.model??u?.model??T.model??"",tier:u?.tier??T.tier,latencyMs:C,method:"invoke"}),T};if(f!=null&&typeof f.then=="function")return f.then(y);if(f!=null&&typeof f=="object"&&"content"in f)return y(f);let g=!1;return x([w(f)],([T])=>T==null||g?T:(g=!0,y(T)),{name:"budgetGate/invokeTap"})},async*stream(d,u){let p=a();if(p)throw p;let c=W(),f;try{for await(let y of t.stream(d,u))y.type==="usage"&&(f=y.usage),yield y;s(f??l(),{model:t.model??u?.model??"",tier:u?.tier,latencyMs:Math.max(0,(W()-c)/1e6),method:"stream"})}catch(y){let g=y;throw s(f??l(),{model:t.model??u?.model??"",tier:u?.tier,latencyMs:Math.max(0,(W()-c)/1e6),method:"stream",error:{type:g?.name??"Error",message:g?.message??String(y)}}),y}}},budget:{totals:o,isOpen:n,log:r,reset:i}}}function bt(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 Ut(t,e){switch(e){case"calls":return t.calls;case"inputTokens":return t.inputTokens;case"outputTokens":return t.outputTokens;case"usd":return t.usd}}function Vt(t,e){let r=e.mock??Me({provider:t.provider,model:t.model}),o=typeof e.enabled=="boolean"?e.enabled:void 0,n=o===void 0?w(e.enabled):void 0,a;n&&(a=K(n));let s=()=>o!==void 0?o:!!n?.cache;return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),invoke(m,d){return s()?r.invoke(m,d):t.invoke(m,d)},stream(m,d){return s()?r.stream(m,d):t.stream(m,d)}},dispose:()=>{a&&(a(),a=void 0)}}}function Ke(t){if(t==null||typeof t!="object")return;let e=t,r=e.status,o=Ht(e.headers);if(r!==429&&r!==503&&!Xt(e.message))return;let n={},a=o("retry-after"),s=zt(a);s!=null&&(n.retryAfterMs=s);let i=o("anthropic-ratelimit-requests-reset");if(i){let c=Tt(i);c!=null&&(n.retryAfterMs=Math.max(n.retryAfterMs??0,c))}let l=o("anthropic-ratelimit-tokens-reset");if(l){let c=Tt(l);c!=null&&(n.retryAfterMs=Math.max(n.retryAfterMs??0,c))}let m=Ce(o,"x-ratelimit-limit-requests");m!=null&&(n.rpmCap=m);let d=Ce(o,"x-ratelimit-limit-tokens");d!=null&&(n.tpmCap=d);let u=Ce(o,"x-ratelimit-remaining-requests"),p=Ce(o,"x-ratelimit-remaining-tokens");if(u!=null&&m!=null&&m>0&&(n.usageHint??={},n.usageHint.rpm=1-u/m),p!=null&&d!=null&&d>0&&(n.usageHint??={},n.usageHint.tpm=1-p/d),n.retryAfterMs==null&&e.message){let c=Yt(e.message);c!=null&&(n.retryAfterMs=c)}return e.headers&&(n.metadata={headers:qt(e.headers)}),n.retryAfterMs==null&&n.rpmCap==null&&n.tpmCap==null&&n.usageHint==null?n.metadata?n:void 0:n}function Ht(t){if(!t)return()=>{};if(typeof t.get=="function"){let o=t;return n=>o.get(n)??o.get(n.toLowerCase())??void 0}let e=t,r={};for(let[o,n]of Object.entries(e)){let a=Array.isArray(n)?n.join(", "):n;a!=null&&(r[o.toLowerCase()]=a)}return o=>r[o.toLowerCase()]}function qt(t){let e={};if(typeof t.forEach=="function")return t.forEach((r,o)=>{e[o]=r}),e;for(let[r,o]of Object.entries(t))o!=null&&(e[r]=Array.isArray(o)?o.join(", "):o);return e}function Ce(t,e){let r=t(e);if(r==null)return;let o=Number(r);return Number.isFinite(o)?o:void 0}function zt(t){if(!t)return;let e=t.trim(),r=Number(e);if(Number.isFinite(r)&&r>=0)return r*1e3;let o=Date.parse(e);if(Number.isFinite(o)){let n=o-Date.now();if(n>0)return n}}function Tt(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var Jt=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function Yt(t){let e=Jt.exec(t);if(!e)return;let r=Number(e[1]);if(!Number.isFinite(r))return;let o=(e[2]??"s").toLowerCase();if(o==="ms")return r;if(o.startsWith("s"))return r*1e3;if(o.startsWith("m"))return r*6e4}var Qt=/rate\s*limit|too\s*many\s*requests|quota|429/i;function Xt(t){return!!t&&Qt.test(t)}function Ue(t){let e=new Error(t);return e.name="AbortError",e}function kt(t={}){let e=Math.max(1,t.burstMultiplier??1),r=t.clampCooldownMs??6e4,o=t.rpm!=null?w(t.rpm):v(Number.POSITIVE_INFINITY),n=t.tpm!=null?w(t.tpm):v(Number.POSITIVE_INFINITY),a=v(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),s=v(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),i=v({},{name:"adaptiveRateLimiter/lastSignal"}),l=x([o,a],([L,E])=>Math.min(Number(L??1/0),Number(E??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),m=x([n,s],([L,E])=>Math.min(Number(L??1/0),Number(E??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),d=ye(Number(o.cache??Number.POSITIVE_INFINITY),e),u=ye(Number(n.cache??Number.POSITIVE_INFINITY),e),p=!1,c=!1,f=l.subscribe(L=>{for(let E of L)if(E[0]===q){let P=Number(E[1]);Number.isFinite(P)&&P>0?(d=ye(P,e),p=!1):P===1/0?(d=ye(1/0,e),p=!1):P<=0&&(p=!0)}}),y=m.subscribe(L=>{for(let E of L)if(E[0]===q){let P=Number(E[1]);Number.isFinite(P)&&P>0?(u=ye(P,e),c=!1):P===1/0?(u=ye(1/0,e),c=!1):P<=0&&(c=!0)}}),g=0,T=new X,C=new X,b;t.adaptation!=null&&(b=w(t.adaptation).subscribe(E=>{for(let P of E)P[0]===q&&A(P[1])}));function A(L){if(i.emit(L),L.rpmCap!=null&&Number.isFinite(L.rpmCap)&&L.rpmCap>=0&&(a.emit(L.rpmCap),Number.isFinite(r)&&r>0&&T.start(r,()=>a.emit(Number.POSITIVE_INFINITY))),L.tpmCap!=null&&Number.isFinite(L.tpmCap)&&L.tpmCap>=0&&(s.emit(L.tpmCap),Number.isFinite(r)&&r>0&&C.start(r,()=>s.emit(Number.POSITIVE_INFINITY))),L.retryAfterMs!=null&&L.retryAfterMs>0){let E=W()+L.retryAfterMs*1e6;E>g&&(g=E)}}let O=v(0,{name:"adaptiveRateLimiter/pending"}),U=v(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),B=v(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),V=L=>{O.emit((O.cache??0)+L)},_=()=>{U.emit(d.available()),B.emit(u.available())};async function H(L={}){let E=L.requestCost??1,P=L.tokenCost??0,M=L.signal;V(1);try{for(;;){if(M?.aborted)throw Ue("AdaptiveRateLimiter.acquire aborted");let h=W();if(g>h){let ee=Math.ceil((g-h)/1e6);await Ae(ee,M);continue}if(E>0&&p||P>0&&c){await Ae(250,M);continue}let k=d,R=u;if(!k.tryConsume(E)){await Ae(Mt(k,E),M);continue}if(!(P>0?R.tryConsume(P):!0)){k.putBack(E),await Ae(Mt(R,P),M);continue}_();return}}finally{V(-1)}}function $(L){L>0?u.tryConsume(L):L<0&&u.putBack(-L),_()}function F(){f(),y(),b?.(),T.cancel(),C.cancel()}return{effectiveRpm:l,effectiveTpm:m,lastSignal:i,pending:O,rpmAvailable:U,tpmAvailable:B,acquire:H,recordUsage:$,recordSignal:A,dispose:F}}function ye(t,e){if(!Number.isFinite(t)||t===1/0)return je(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let r=Math.max(1,t*e),o=t/60;return je(r,o)}function Mt(t,e){let r=t.available(),o=Math.max(0,e-r);return o<=0?25:Math.min(5e3,Math.max(50,o*100))}function Ae(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Ue("AdaptiveRateLimiter.acquire aborted")):new Promise((r,o)=>{let n=new X,a,s=()=>{n.cancel(),e&&a&&e.removeEventListener("abort",a)};n.start(t,()=>{s(),r()}),e&&(a=()=>{s(),o(Ue("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",a,{once:!0}))})}function Ve(t,e={}){let r=e.limiter??kt({name:e.name??"rateLimiter",rpm:e.rpm,tpm:e.tpm,adaptation:e.adaptation,burstMultiplier:e.burstMultiplier}),o=(s,i)=>e.costFn?e.costFn(s,i):0,n=s=>{let i=Ke(s);i&&r.recordSignal(i)};return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(s,i){let l=o(s,i);await r.acquire({requestCost:1,tokenCost:l,signal:i?.signal});try{let m=t.invoke(s,i),d=await Zt(m),u=d.usage??gt(),c=ne(u)+le(u)-l;return c>0&&r.recordUsage(c),d}catch(m){throw n(m),m}},async*stream(s,i){let l=o(s,i);await r.acquire({requestCost:1,tokenCost:l,signal:i?.signal});try{let m=0;for await(let u of t.stream(s,i))u.type==="usage"&&(m=ne(u.usage)+le(u.usage)),yield u;let d=m-l;d>0&&r.recordUsage(d)}catch(m){throw n(m),m}}},limiter:r}}async function Zt(t){return t!=null&&typeof t.then=="function"?await t:t&&typeof t=="object"&&"content"in t?t:await at(w(t))}function Se(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function vt(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Se()):new Promise((r,o)=>{let n=new X,a,s=()=>{n.cancel(),e&&a&&e.removeEventListener("abort",a)};n.start(t,()=>{s(),r()}),e&&(a=()=>{s(),o(Se())},e.addEventListener("abort",a,{once:!0}))})}function He(t,e={}){let r=e.attempts??3,o=e.baseDelayMs??500,n=e.maxDelayMs??1e4,a=e.strategy??"decorrelated",s=e.jitter??!0,i=e.shouldRetry??er,l=e.retryStreaming??!0,m=(d,u)=>{if(a==="decorrelated"){let y=Math.min(n,Math.max(o,u*3));return o+Math.random()*(y-o)}let p=a==="exp"?o*2**(d-1):o*d,c=Math.min(n,p);if(!s)return c;let f=c*(.5+Math.random());return Math.min(n,f)};return{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(d,u){if(u?.signal?.aborted)throw Se();let p,c=o;for(let f=1;f<=r;f++)try{return await Promise.resolve(t.invoke(d,u))}catch(y){if(p=y,f>=r||!i(y,f))throw y;let g=m(f,c);c=g,await vt(g,u?.signal)}throw p},async*stream(d,u){if(u?.signal?.aborted)throw Se();if(!l){for await(let f of t.stream(d,u))yield f;return}let p,c=o;for(let f=1;f<=r;f++){let y=!1;try{for await(let g of t.stream(d,u))y=!0,yield g;return}catch(g){if(p=g,y||f>=r||!i(g,f))throw g;let T=m(f,c);c=T,await vt(T,u?.signal)}}throw p}}}function er(t,e){if(t==null)return!1;let r=t;return r.name==="LLMTimeoutError"?!0:r.name==="AbortError"||r.message==="aborted"||r.name==="DOMException"&&r.code!=null&&Number(r.code)===20||r.name==="BudgetExhaustedError"||r.name==="CircuitOpenError"?!1:r.status!=null?r.status===429||r.status>=500&&r.status<600:r.code&&typeof r.code=="string"&&/^E[A-Z]+$/.test(r.code)?!0:r.message?/network|timeout|socket|fetch|econn|eai_/i.test(r.message):!1}var he=class extends Error{constructor(r){super(`LLM call timed out after ${r}ms`);this.ms=r}name="LLMTimeoutError"};function qe(t,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let r=n=>{let a=new AbortController,s=!1,i;n&&(n.aborted?a.abort(n.reason):(i=()=>a.abort(n.reason),n.addEventListener("abort",i,{once:!0})));let l=new X;return l.start(e,()=>{s=!0,a.abort(new he(e))}),{signal:a.signal,cancel:()=>{l.cancel(),n&&i&&n.removeEventListener("abort",i)},timedOut:()=>s}},o=(n,a)=>{if(!a||n instanceof he)throw n;let s=n;if(s?.name==="AbortError"||s?.name==="DOMException"&&Number(s.code)===20||n?.message==="aborted"){let l=new he(e);throw l.cause=n,l}throw n};return{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(n,a){let{signal:s,cancel:i,timedOut:l}=r(a?.signal);try{return await Promise.resolve(t.invoke(n,{...a,signal:s}))}catch(m){return o(m,l())}finally{i()}},async*stream(n,a){let{signal:s,cancel:i,timedOut:l}=r(a?.signal);try{for await(let m of t.stream(n,{...a,signal:s}))yield m}catch(m){o(m,l())}finally{i()}}}}function tr(t,e={}){let r={adapter:t},o=t;if(e.rateLimit){let n=Ve(o,e.rateLimit);o=n.adapter,r.rateLimiter=n.limiter}if(e.budget){let n=We(o,e.budget);o=n.adapter,r.budget=n.budget}if(e.breaker){let n=Be(o,e.breaker);o=n.adapter,r.breaker=n.breaker}if(e.timeoutMs!=null&&(o=qe(o,e.timeoutMs)),e.retry&&(o=He(o,e.retry)),e.fallback){if(e.name==="fallback")throw new RangeError('resilientAdapter: `name` cannot be "fallback" \u2014 collides with the secondary tier label.');let n={};e.onFallback&&(n.onFallback=e.onFallback),e.onExhausted&&(n.onExhausted=e.onExhausted),o=_e([{name:e.name??"primary",adapter:o},{name:"fallback",adapter:e.fallback}],n)}return r.adapter=o,r}function rr(){return Me()}function nr(t,e,r){let o=w(e);return J(o,a=>{if(!a||a.length===0)return v(null);let s=r?.tools;return t.invoke(a,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,tools:s,systemPrompt:r?.systemPrompt})})}function N(t,e){return it("ai",t,e)}function or(t){return t!=null&&typeof t.then=="function"}function ar(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function sr(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var ir=3e4;function xt(t,e){if(t.status==="settled"){let o=t.cache;if(o!==void 0)return Promise.resolve(o)}let r=e?.timeoutMs??ir;return new Promise((o,n)=>{let a=new X,s=t.subscribe(i=>{for(let l of i){if(l[0]===q){a.cancel(),s(),o(l[1]);return}if(l[0]===Y){a.cancel(),s(),n(l[1]);return}if(l[0]===re){a.cancel(),s(),n(new Error("firstDataFromNode: completed without producing a value"));return}}});a.start(r,()=>{s(),n(new Error(`firstDataFromNode: timed out after ${r}ms`))})})}async function ue(t){return or(t)?ue(await t):ar(t)?xt(t):sr(t)?xt(w(t)):t}function de(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function lr(t,e){let r=w(t),o=e?.refreshTrigger!=null?w(e.refreshTrigger):null;return o==null?se([r],(n,a,s)=>{if(s.store.emitted===!0)return;let l=n[0],m=l!=null&&l.length>0?l.at(-1):s.prevData[0];if(m!==void 0)return s.store.emitted=!0,a.emit(m),{invalidate:()=>{s.store.emitted=!1}}},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:N("frozen_context")}):se([r,o],(n,a,s)=>{let i=n[1];if(!(i!=null&&i.length>0))return;let m=n[0],d=m!=null&&m.length>0?m.at(-1):s.prevData[0];a.emit(d)},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:N("frozen_context")})}function ur(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function dr(t,e,r,o){let n=o?.format??"text",a=o?.retries??0,s=o?.cache??!1,i=s?new Map:null,l=x(e,d=>{if(d.some(c=>c==null))return[];let u=typeof r=="string"?r:r(...d);if(!u)return[];let p=[];return o?.systemPrompt&&p.push({role:"system",content:o.systemPrompt}),p.push({role:"user",content:u}),p},{name:o?.name?`${o.name}::messages`:"prompt_node::messages",meta:N("prompt_node"),initial:[]});return J(l,d=>{if(!d||d.length===0)return v(null);let u=s?JSON.stringify(d.map(c=>[c.role,c.content])):"";if(i?.has(u))return v(i.get(u));async function p(c){try{let f=await new Promise((T,C)=>{let b=t.invoke(d,{model:o?.model,temperature:o?.temperature,maxTokens:o?.maxTokens,systemPrompt:o?.systemPrompt});b&&typeof b.then=="function"?b.then(T,C):b&&typeof b.subscribe=="function"?T(b.cache):T(b)}),y=ur(f),g;return n==="json"?g=JSON.parse(de(y)):g=y,i?.set(u,g),g}catch(f){if(c>0)return p(c-1);throw f}}return p(a)})}function mr(t,e,r,o){let n=o?.name??"llm",a=o?.format??"text",s=De(`${n}/stream`),i=x(e,d=>{if(d.some(c=>c==null))return[];let u=typeof r=="string"?r:r(...d);if(!u)return[];let p=[];return o?.systemPrompt&&p.push({role:"system",content:o.systemPrompt}),p.push({role:"user",content:u}),p}),l=J(i,d=>{let u=d;if(!u||u.length===0)return v(null);let p=new AbortController;async function*c(){let f="",y=0;try{for await(let T of t.stream(u,{model:o?.model,temperature:o?.temperature,maxTokens:o?.maxTokens,systemPrompt:o?.systemPrompt,signal:p.signal})){if(T.type!=="token")continue;let C=T.delta;f+=C,s.publish({source:n,token:C,accumulated:f,index:y++})}let g;if(a==="json")try{g=JSON.parse(de(f))}catch{g=null}else g=f;yield g}finally{p.abort()}}return w(c())}),m=K(l);return{output:l,stream:s,dispose:()=>{m(),s.destroy()}}}function cr(t,e,r,o,n,a){let s=v(0,{name:`${e}/cancel`}),i=0,l=[...o,s],m=a?.name??e,d=a?.format??"text",u=De(`${m}/stream`),p=x(l,b=>{let A=b.slice(0,-1);if(A.some(B=>B==null))return[];let O=typeof n=="string"?n:n(...A);if(!O)return[];let U=[];return a?.systemPrompt&&U.push({role:"system",content:a.systemPrompt}),U.push({role:"user",content:O}),U}),c=J(p,b=>{let A=b;if(!A||A.length===0)return v(null);let O=new AbortController;async function*U(){let B="",V=0;try{for await(let H of r.stream(A,{model:a?.model,temperature:a?.temperature,maxTokens:a?.maxTokens,systemPrompt:a?.systemPrompt,signal:O.signal})){if(H.type!=="token")continue;let $=H.delta;B+=$,u.publish({source:m,token:$,accumulated:B,index:V++})}let _;if(d==="json")try{_=JSON.parse(de(B))}catch{_=null}else _=B;yield _}finally{O.abort()}}return w(U())}),f=K(c),y=x([c],([b])=>{if(b!=null)return b},{name:`${e}/filter`});t.add(y,{name:`${e}/raw`});let g=dt(t,`${e}/gate`,`${e}/raw`,a?.gate),T=g.reject.bind(g),C={...g,reject(b=1){T(b),s.emit(++i)}};return{output:g.node,stream:u,gate:C,dispose:()=>{f(),u.destroy()}}}function pr(t,e){let r=e?.separator??`
|
|
2
|
-
|
|
3
|
-
`,o=t.map(s=>typeof s=="string"?v(s):w(s)),n=x(o,s=>s.filter(i=>i!=null&&i!=="").join(r),{name:e?.name??"systemPrompt",describeKind:"derived",meta:N("system_prompt"),initial:""}),a=K(n);return Object.assign(n,{dispose:a})}var fr=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens;function gr(t,e){let r=e?.charsPerToken??4;return x([t.latest],([o])=>{if(o==null)return{chunkCount:0,charCount:0,estimatedTokens:0};let n=o,a=n.accumulated.length;return{chunkCount:n.index+1,charCount:a,estimatedTokens:Math.ceil(a/r)}},{name:e?.name??"cost-meter",describeKind:"derived",initial:{chunkCount:0,charCount:0,estimatedTokens:0},meta:N("cost_meter_extractor"),equals:fr})}var yr=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++){let o=t[r],n=e[r];if(o.label!==n.label||o.pattern!==n.pattern||o.match!==n.match||o.position!==n.position)return!1}return!0};function hr(t,e){let r=e.maxPatternLength??128;return x([t.latest],([o],n)=>{if(o==null)return[];let a=o.accumulated;"flags"in n.store||(n.store.flags=[],n.store.scannedTo=0);let s=n.store.flags,i=n.store.scannedTo,l=Math.max(0,i-r),m=a.slice(l),d=!1;for(let{pattern:u,label:p}of e.patterns){let c=new RegExp(u.source,`${u.flags.replace("g","")}g`);for(let f of m.matchAll(c)){let y=l+f.index;y+f[0].length<=i||(s.push({label:p,pattern:u,match:f[0],position:y}),d=!0)}}return n.store.scannedTo=a.length,d?[...s]:s.slice()},{name:e.name??"keyword-flag-extractor",describeKind:"derived",initial:[],meta:N("keyword_flag_extractor"),equals:yr})}function br(t,e,r){return x([t.latest],([o])=>o==null?null:e(o.accumulated),{name:r?.name??"extractor",describeKind:"derived",initial:null,meta:N("stream_extractor"),...r?.equals?{equals:r.equals}:{}})}var Tr=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++){let o=t[r],n=e[r];if(o.startIndex!==n.startIndex||o.name!==n.name||o.raw!==n.raw)return!1}return!0};function Mr(t,e){return x([t.latest],([r],o)=>{if(r==null)return[];let n=r.accumulated;"calls"in o.store||(o.store.calls=[],o.store.scanFrom=0);let a=o.store.calls,s=o.store.scanFrom,i=!1;for(;s<n.length;){let l=n.indexOf("{",s);if(l===-1){o.store.scanFrom=n.length;break}let m=0,d=-1,u=!1;for(let c=l;c<n.length;c++){let f=n[c];if(u)f==="\\"&&c+1<n.length?c++:f==='"'&&(u=!1);else if(f==='"')u=!0;else if(f==="{")m++;else if(f==="}"&&(m--,m===0)){d=c;break}}if(d===-1){o.store.scanFrom=l;break}let p=n.slice(l,d+1);try{let c=JSON.parse(p);typeof c.name=="string"&&c.arguments!=null&&typeof c.arguments=="object"&&(a.push({name:c.name,arguments:c.arguments,raw:p,startIndex:l}),i=!0)}catch{}s=d+1,o.store.scanFrom=s}return i?[...a]:a.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:N("tool_call_extractor"),equals:Tr})}function kr(t,e,r,o){let n=r*(o?.hardMultiplier??1.5),a=typeof e!="function",s=[t.latest];return a&&s.push(e),x(s,i=>{let l=i[0];if(l==null)return"allow";let m=a?i[1]??0:e(l.accumulated);return m>=n?"block":m>=r?"review":"allow"},{name:o?.name??"content-gate",initial:"allow"})}function vr(t,e,r,o){let n=r??(()=>"[REDACTED]");function a(s){let i=s;for(let l of e){let m=l.global?l:new RegExp(l.source,`${l.flags}g`);i=i.replace(m,d=>n(d,l))}return i}return x([t.latest],([s])=>{if(s==null)return{source:"",token:"",accumulated:"",index:-1};let i=s,l=a(i.accumulated),m=a(i.token);return{source:i.source,token:m,accumulated:l,index:i.index}},{name:o?.name??"redactor"})}var Ee=class extends Z{_log;messages;latest;messageCount;constructor(e,r={}){super(e,r.graph),this._log=ge([],{name:"messages",maxSize:r.maxMessages}),this.messages=this._log.entries,this.add(this.messages,{name:"messages"}),this.latest=x([this.messages],([o])=>{let n=o;return n.length===0?null:n[n.length-1]},{name:"latest",describeKind:"derived",meta:N("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(K(this.latest)),this.messageCount=x([this.messages],([o])=>o.length,{name:"messageCount",describeKind:"derived",meta:N("chat_message_count"),initial:0}),this.add(this.messageCount,{name:"messageCount"}),this.addDisposer(K(this.messageCount))}append(e,r,o){this._log.append({role:e,content:r,...o})}appendToolResult(e,r){this._log.append({role:"tool",content:r,toolCallId:e})}clear(){this._log.clear()}allMessages(){return this.messages.cache}};function ze(t,e){return new Ee(t,e)}var Ie=class extends Z{definitions;schemas;constructor(e,r={}){super(e,r.graph),this.definitions=v(new Map,{name:"definitions",describeKind:"state",meta:N("tool_definitions")}),this.add(this.definitions,{name:"definitions"}),this.schemas=x([this.definitions],([o])=>[...(o??new Map).values()],{name:"schemas",describeKind:"derived",meta:N("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(K(this.schemas))}register(e){let r=this.definitions.cache,o=new Map(r);o.set(e.name,e),this.definitions.emit(o)}unregister(e){let r=this.definitions.cache;if(!r.has(e))return;let o=new Map(r);o.delete(e),this.definitions.emit(o)}async execute(e,r){let n=this.definitions.cache.get(e);if(!n)throw new Error(`toolRegistry: unknown tool "${e}"`);let a=n.handler(r);return ue(a)}getDefinition(e){return this.definitions.cache?.get(e)}};function Je(t,e){return new Ie(t,e)}var Oe=class extends Z{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;turnCount;_terminalResult;_disposeRunWiring;_runVersion=0;_running=!1;_currentAbortController=null;constructor(e,r){if(super(e,r.graph),this.chat=ze(`${e}-chat`,{maxMessages:r.maxMessages}),this.mount("chat",this.chat),this.tools=Je(`${e}-tools`),this.mount("tools",this.tools),r.tools)for(let M of r.tools)this.tools.register(M);this.status=v("idle",{name:"status",describeKind:"state",meta:N("agent_status")}),this.add(this.status,{name:"status"}),this.turn=v(0,{name:"turn",describeKind:"state",meta:N("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.turnCount=this.turn,this.aborted=v(!1,{name:"aborted",describeKind:"state",meta:N("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let o=0,n=this.turn.subscribe(M=>{for(let h of M)h[0]===q&&(o=h[1])}),a=!1,s=this.aborted.subscribe(M=>{for(let h of M)h[0]===q&&(a=h[1])}),i=r.adapter,l=r.systemPrompt,m=r.model,d=r.temperature,u=r.maxTokens,p=r.maxTurns??10,c=r.stopWhen,f=this.chat,y=this.tools,g=this.status,T=this.turn,C=this.aborted,b=se([g],(M,h,k)=>{if(ke(M,k.prevData,0,"idle")!=="thinking"||a||o>=p){h.down([[fe]]);return}let I=f.allMessages();if(I.length===0){h.down([[fe]]);return}let S=y.schemas.cache??[];h.emit({messages:I,tools:S})},{name:"promptInput",describeKind:"derived",meta:N("agent_prompt_input")}),A=J(b,M=>{let h=new AbortController;return this._currentAbortController=h,a&&h.abort(new Error("agentLoop: aborted")),w(Promise.resolve(i.invoke(M.messages,{tools:M.tools.length>0?M.tools:void 0,systemPrompt:l,model:m,temperature:d,maxTokens:u,signal:h.signal})),{signal:h.signal})},{equals:()=>!1}),O=v(null,{name:"lastResponse",describeKind:"state",meta:N("agent_last_response")});this.lastResponse=O;let U=se([O,g],(M,h,k)=>{let R=ke(M,k.prevData,0,null);if(ke(M,k.prevData,1,"idle")!=="acting"){h.down([[fe]]);return}let S=R?.toolCalls;if(S==null||S.length===0){h.down([[fe]]);return}h.emit(S)},{name:"toolCalls",describeKind:"derived",meta:N("agent_tool_calls")}),B=r.interceptToolCalls?r.interceptToolCalls(U):U;this.toolCalls=B;let V=(M,h)=>{if(M===h)return!0;if(M.length!==h.length)return!1;for(let k=0;k<M.length;k++){let R=M[k],I=h[k];if(R?.id!==I?.id||R?.content!==I?.content)return!1}return!0},_=J(B,M=>{if(M==null||M.length===0)throw new Error("agentLoop: toolResultsNode received an empty tool-call batch as DATA \u2014 toolCallsNode gating invariant broken (should emit RESOLVED for empty). Audit toolCallsNode.");let h=M.map(k=>xr(k,y));return x(h,k=>k.map((R,I)=>{let S=R;return S!=null&&typeof S=="object"&&"id"in S&&"content"in S?S:{id:M[I].id,content:JSON.stringify(R??null)}}),{name:"toolResults_batch",equals:V})});this.toolResults=_;let H=ie([A],([M])=>{if(a)return;let h=M,k=o+1,R=h.toolCalls!=null&&h.toolCalls.length>0,I=h.finishReason==="end_turn"&&(!h.toolCalls||h.toolCalls.length===0),S=c?.(h)===!0,ee=k>=p,te=S||I||!R||ee?"done":"acting";ae(()=>{O.emit(h),g.emit(te),T.emit(k),f.append("assistant",h.content,{toolCalls:h.toolCalls})})}),$=ie([_],([M])=>{if(a)return;let h=M;if(h.length===0)return;let k=o>=p?"done":"thinking";ae(()=>{g.emit(k);for(let R of h)f.appendToolResult(R.id,R.content)})}),F=ie([C],([M])=>{M===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),g.emit("done"))}),L=K(H),E=K($),P=K(F);this._terminalResult=se([g,O],(M,h,k)=>{let R=ke(M,k.prevData,0,"idle"),I=ke(M,k.prevData,1,null);if(R==="done"){if(I!=null){h.emit({response:I,runVersion:this._runVersion});return}let S=new Error("agentLoop: aborted");S.name="AbortError",h.down([[Y,S]]);return}if(R==="error"){h.down([[Y,new Error("agentLoop: errored")]]);return}h.down([[fe]])},{name:"terminalResult",describeKind:"derived",meta:N("agent_terminal_result")}),this.addDisposer(n),this.addDisposer(s),this.addDisposer(L),this.addDisposer(E),this.addDisposer(P),this._disposeRunWiring=()=>{}}async run(e,r){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 o=++this._runVersion;ae(()=>{this.turn.emit(0),this.aborted.emit(!1),this.status.emit("idle")}),e!=null&&this.chat.append("user",e),this.status.emit("thinking");let n;if(r!=null)if(r.aborted)this.aborted.emit(!0);else{let a=()=>this.aborted.emit(!0);r.addEventListener("abort",a,{once:!0}),n=()=>r.removeEventListener("abort",a)}try{return(await st(this._terminalResult,{predicate:s=>s!=null&&typeof s=="object"&&s.runVersion===o})).response}finally{n?.(),this._running=!1,this._currentAbortController=null}}abort(){this.aborted.emit(!0)}destroy(){try{this._disposeRunWiring()}catch{}super.destroy()}};function xr(t,e){let r=rt(()=>w(Promise.resolve().then(()=>e.execute(t.name,t.arguments))),{count:1}),o=x([r],([n])=>({id:t.id,content:typeof n=="string"?n:JSON.stringify(n)}));return lt(o,n=>({id:t.id,content:JSON.stringify({error:String(n)})}))}function ke(t,e,r,o){let n=t[r];if(n!=null&&n.length>0)return n[n.length-1];let a=e[r];return a!==void 0?a:o}function Rr(t,e){return new Oe(t,e)}function Lr(t,e,r){let o=w(t),n=r?.condition!=null?w(r.condition):null,a=v(null,{name:r?.name?`${r.name}::null`:"handoff::null"});if(n==null)return J(o,i=>{if(i==null)return a;let l=v(i);return e(l)});let s=x([o,n],([i,l])=>({v:i,open:l===!0}),{name:r?.name?`${r.name}::router`:"handoff::router",describeKind:"derived"});return J(s,({v:i,open:l})=>{if(i==null)return a;if(!l)return v(i);let m=v(i);return e(m)})}function wr(t,e,r){let o=w(t),n=e.map(s=>w(s)),a=[o,...n];return x(a,s=>{let i=s[0]??[],l=s.slice(1);return i.filter(m=>{for(let d of l)if(d!=null&&!d(m))return!1;return!0})},{name:r?.name??"tool-selector",describeKind:"derived",meta:N("tool_selector"),equals:(s,i)=>{let l=s,m=i;if(l.length!==m.length)return!1;for(let d=0;d<l.length;d++)if(l[d]!==m[d])return!1;return!0}})}function Nr(t){return{persistence:.5,structure:.5,personalValue:.5}}function Cr(t={}){let e=t.scoreFn??Nr,r=t.persistenceThreshold??.3,o=t.personalValueThreshold??.3,n=t.requireStructured??!1;return a=>{let s=e(a);return!(s.persistence<r||s.personalValue<o||n&&s.structure<=0)}}function Ye(t,e){return(r,o)=>{let n=[...o.keys()].slice(0,100),a=[{role:"system",content:t},{role:"user",content:JSON.stringify({input:r,existingKeys:n})}];return Pe(s=>{let i=!0,l=e.adapter.invoke(a,{model:e.model,temperature:e.temperature??0,maxTokens:e.maxTokens}),d=w(l).subscribe(u=>{if(!i)return;let p=!1;for(let c of u){if(p)break;if(c[0]===q){let f=c[1];try{let y=JSON.parse(f.content);s.emit(y),s.down([[re]])}catch{s.down([[Y,new Error("llmExtractor: failed to parse LLM response as JSON")]])}p=!0}else c[0]===Y?(s.down([[Y,c[1]]]),p=!0):c[0]===re?(s.down([[re]]),p=!0):s.down([[c[0],c[1]]])}});return()=>{d(),i=!1}})}}function Qe(t,e){return r=>{let o=[...r.entries()].map(([a,s])=>({key:a,value:s})),n=[{role:"system",content:t},{role:"user",content:JSON.stringify({memories:o})}];return Pe(a=>{let s=!0,i=e.adapter.invoke(n,{model:e.model,temperature:e.temperature??0,maxTokens:e.maxTokens}),m=w(i).subscribe(d=>{if(!s)return;let u=!1;for(let p of d){if(u)break;if(p[0]===q){let c=p[1];try{let f=JSON.parse(c.content);a.emit(f),a.down([[re]])}catch{a.down([[Y,new Error("llmConsolidator: failed to parse LLM response as JSON")]])}u=!0}else p[0]===Y?(a.down([[Y,p[1]]]),u=!0):p[0]===re?(a.down([[re]]),u=!0):a.down([[p[0],p[1]]])}});return()=>{m(),s=!1}})}}var Xe=Math.LN2/604800;function ve(t){return t instanceof Map?t:new Map}function Ar(t,e,r){let o=new Z(t,r.graph),n=[],a;if(r.extractFn)a=r.extractFn;else if(r.adapter&&r.extractPrompt)a=Ye(r.extractPrompt,{adapter:r.adapter});else throw new Error("agentMemory: provide either extractFn or adapter + extractPrompt");let s=(b,A)=>b==null?{upsert:[]}:a(b,A),i=e;if(r.admissionFilter){let b=w(e),A=r.admissionFilter;i=x([b],([O])=>{if(A(O))return O},{name:"admissionFilter",describeKind:"derived"})}let l;r.consolidateFn?l=r.consolidateFn:r.adapter&&r.consolidatePrompt&&(l=Qe(r.consolidatePrompt,{adapter:r.adapter}));let m=r.consolidateTrigger;if(!m&&l&&r.reflection?.enabled!==!1){let b=r.reflection?.interval??3e5;m=ot(b,{period:b})}let d={score:r.score,cost:r.cost,budget:r.budget??2e3,context:r.context,consolidate:l,consolidateTrigger:m},u=ut(i,s,d);o.add(u.store.entries,{name:"store"}),o.add(u.compact,{name:"compact"}),o.add(u.size,{name:"size"});let p=null;r.vectorDimensions&&r.vectorDimensions>0&&r.embedFn&&(p=pt({dimension:r.vectorDimensions}),o.add(p.entries,{name:"vectorIndex"}));let c=null;r.enableKnowledgeGraph&&(c=ft(`${t}-kg`),o.mount("kg",c));let f=null;if(r.tiers){let b=r.tiers,A=b.decayRate??Xe,O=b.maxActive??1e3,U=b.archiveThreshold??.1,B=b.permanentFilter??(()=>!1),V=ct({name:"permanent"});o.add(V.entries,{name:"permanent"});let _=new Set,H=h=>_.has(h)?"permanent":ve(u.store.entries.cache).has(h)?"active":"archived",$=(h,k)=>{_.add(h),V.upsert(h,k)},F=new Map,L=u.store.entries,E=r.context?w(r.context):v(null),P=ie([L,E],([h,k])=>{let R=ve(h),I=W(),S=[],ee=[];for(let[D,Q]of R){if(F.has(D)||F.set(D,I),B(D,Q)){ee.push({key:D,value:Q});continue}let z=r.score(Q,k),j=F.get(D)??I,G=Number(I-j)/1e9;mt(z,G,A)<U&&S.push(D)}for(let D of F.keys())R.has(D)||F.delete(D);for(let{key:D,value:Q}of ee)_.has(D)||$(D,Q);let te=R.size-_.size;if(te>O){let D=[...R.entries()].filter(([z])=>!_.has(z)).map(([z,j])=>({key:z,score:r.score(j,k)})).sort((z,j)=>z.score-j.score),Q=te-O;for(let z=0;z<Q&&z<D.length;z++){let j=D[z].key;S.includes(j)||S.push(j)}}S.length>0&&ae(()=>{for(let D of S)u.store.delete(D)})});n.push(P.subscribe(()=>{}));let M=null;b.archiveTier&&(M=o.attachStorage([b.archiveTier],b.archiveStorageOptions??{})),f={permanent:V,activeEntries:L,archiveHandle:M,tierOf:H,markPermanent:$}}if(p||c){let b=r.embedFn,A=r.entityFn,O=u.store.entries,U=ie([O],([B])=>{let V=ve(B);for(let[_,H]of V){if(p&&b){let $=b(H);$&&p.upsert(_,$,H)}if(c&&A){let $=A(_,H);if($){for(let F of $.entities??[])c.upsertEntity(F.id,F.value);for(let F of $.relations??[])c.link(F.from,F.to,F.relation,F.weight)}}}});n.push(U.subscribe(()=>{}))}let y=null,g=null,T=null,C=null;if(p||c){let b=r.retrieval?.topK??20,A=r.retrieval?.graphDepth??1,O=r.budget??2e3,U=r.cost,B=r.score,V=r.contextOf,_=r.contextWeight??0,H=r.context?w(r.context):v(null),$=(M,h)=>{if(!M||!h)return 0;let k=Math.min(M.length,h.length),R=0;for(;R<k&&M[R]===h[R];)R++;return R},F=(M,h,k)=>{let R=new Map,I=[];if(p&&k.vector){I=p.search(k.vector,b);for(let j of I){let G=M.get(j.id);G&&R.set(j.id,{value:G,sources:new Set(["vector"])})}}let S=[];if(c){let j=[...k.entityIds??[],...R.keys()],G=new Set,me=j;for(let ce=0;ce<A;ce++){let oe=[];for(let be of me){if(G.has(be))continue;G.add(be);let xe=c.related(be);for(let wt of xe){let pe=wt.to;if(!G.has(pe)){oe.push(pe);let et=M.get(pe);if(et){let tt=R.get(pe);tt?tt.sources.add("graph"):R.set(pe,{value:et,sources:new Set(["graph"])}),S.push(pe)}}}}me=oe}}for(let[j,G]of M)R.has(j)||R.set(j,{value:G,sources:new Set(["store"])});let ee=k.context?.length??0,te=[];for(let[j,{value:G,sources:me}]of R){let ce=V?V(G):void 0,oe=B(G,h);if(_>0&&ee>0){let xe=$(k.context,ce);xe>0&&(oe=oe*(1+_*xe/ee))}let be=ce?{key:j,value:G,score:oe,sources:[...me],context:ce}:{key:j,value:G,score:oe,sources:[...me]};te.push(be)}te.sort((j,G)=>G.score-j.score);let D=[],Q=0;for(let j of te){let G=U(j.value);if(Q+G>O&&D.length>0)break;D.push(j),Q+=G}return{packed:D,trace:{vectorCandidates:I,graphExpanded:S,ranked:te,packed:D}}},L=v([],{name:"retrieval",describeKind:"state",meta:N("retrieval_pipeline")});o.add(L,{name:"retrieval"}),y=L;let E=v(null,{name:"retrievalTrace",describeKind:"state",meta:N("retrieval_trace")});o.add(E,{name:"retrievalTrace"}),g=E,T=M=>{let h=ve(u.store.entries.cache),{packed:k,trace:R}=F(h,H.cache,M);return ae(()=>{L.emit(k),E.emit(R)}),k},C=M=>{let h=w(M);return x([u.store.entries,H,h],([k,R,I])=>{if(I==null)return[];let S=ve(k);return F(S,R,I).packed},{name:"retrievalReactive",describeKind:"derived",meta:N("retrieval_reactive"),initial:[]})}}return o.addDisposer(()=>{for(let b of n)b();n.length=0}),Object.assign(o,{distillBundle:u,compact:u.compact,size:u.size,vectors:p,kg:c,memoryTiers:f,retrieval:y,retrievalTrace:g,retrieve:T,retrieveReactive:C})}function Sr(t,e,r){let o=t.describe({actor:e,detail:"full"}),n=r?.groupByTags??!0,a=r?.separator??`
|
|
4
|
-
`,s=[],i=r?.sinceVersion;for(let[l,m]of Object.entries(o.nodes)){let d=m.meta??{},u=d.description,p=d.format;if(!u&&!p)continue;if(i!=null&&m.v!=null){let T=i.get(l);if(T!=null&&T.id===m.v.id&&m.v.version<=T.version)continue}let c=u??l,f=m.value,y=d.unit,g;p==="currency"&&typeof f=="number"?g=`$${f.toFixed(2)}`:p==="percentage"&&typeof f=="number"?g=`${(f*100).toFixed(1)}%`:f==null?g="(no value)":g=String(f),y&&p!=="currency"&&p!=="percentage"&&(g=`${g} ${y}`),s.push({path:l,description:c,formatted:g})}if(s.length===0)return"";if(n){let l=new Map,m=[];for(let u of s){let c=o.nodes[u.path].meta?.tags;if(c&&c.length>0){let f=c[0],y=l.get(f);y||(y=[],l.set(f,y)),y.push(u)}else m.push(u)}if(l.size===0)return s.map(u=>`- ${u.description}: ${u.formatted}`).join(a);let d=[];for(let[u,p]of[...l.entries()].sort((c,f)=>c[0].localeCompare(f[0])))d.push(`[${u}]${a}${p.map(c=>`- ${c.description}: ${c.formatted}`).join(a)}`);return m.length>0&&d.push(m.map(u=>`- ${u.description}: ${u.formatted}`).join(a)),d.join(a+a)}return s.map(l=>`- ${l.description}: ${l.formatted}`).join(a)}var Rt=new Set(["state","derived","producer","operator","effect"]);function Ze(t){let e=[];if(t==null||typeof t!="object")return{valid:!1,errors:["Definition must be a non-null object"]};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};let o=new Set(Object.keys(r.nodes));for(let[n,a]of Object.entries(r.nodes)){if(a==null||typeof a!="object"){e.push(`Node "${n}": must be an object`);continue}let s=a;if((typeof s.type!="string"||!Rt.has(s.type))&&e.push(`Node "${n}": invalid type "${String(s.type)}" (expected: ${[...Rt].join(", ")})`),Array.isArray(s.deps))for(let i of s.deps)typeof i=="string"&&!o.has(i)&&e.push(`Node "${n}": dep "${i}" does not reference an existing node`)}if(!Array.isArray(r.edges))r.edges!==void 0&&e.push("'edges' must be an array");else{let n=new Set;for(let a=0;a<r.edges.length;a++){let s=r.edges[a];if(s==null||typeof s!="object"){e.push(`Edge [${a}]: must be an object`);continue}let i=s;(typeof i.from!="string"||!o.has(i.from))&&e.push(`Edge [${a}]: 'from' "${String(i.from)}" does not reference an existing node`),(typeof i.to!="string"||!o.has(i.to))&&e.push(`Edge [${a}]: 'to' "${String(i.to)}" does not reference an existing node`);let l=`${i.from}->${i.to}`;n.has(l)&&e.push(`Edge [${a}]: duplicate edge ${l}`),n.add(l)}}return{valid:e.length===0,errors:e}}var Lt=`You are a graph architect for GraphReFly, a reactive graph protocol.
|
|
5
|
-
|
|
6
|
-
Given a natural-language description, produce a JSON graph definition with this structure:
|
|
7
|
-
|
|
8
|
-
{
|
|
9
|
-
"name": "<graph_name>",
|
|
10
|
-
"nodes": {
|
|
11
|
-
"<node_name>": {
|
|
12
|
-
"type": "state" | "derived" | "producer" | "operator" | "effect",
|
|
13
|
-
"value": <initial_value_or_null>,
|
|
14
|
-
"deps": ["<dep_node_name>", ...],
|
|
15
|
-
"meta": {
|
|
16
|
-
"description": "<human-readable purpose>",
|
|
17
|
-
"type": "string" | "number" | "boolean" | "integer" | "enum",
|
|
18
|
-
"range": [min, max],
|
|
19
|
-
"values": ["a", "b"],
|
|
20
|
-
"format": "currency" | "percentage" | "status",
|
|
21
|
-
"access": "human" | "llm" | "both" | "system",
|
|
22
|
-
"unit": "<unit>",
|
|
23
|
-
"tags": ["<tag>"]
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
},
|
|
27
|
-
"edges": [
|
|
28
|
-
{ "from": "<source_node>", "to": "<target_node>" }
|
|
29
|
-
]
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
Rules:
|
|
33
|
-
- "state" nodes have no deps and hold user/LLM-writable values (knobs).
|
|
34
|
-
- "derived" nodes have deps and compute from them.
|
|
35
|
-
- "effect" nodes have deps but produce side effects (no return value).
|
|
36
|
-
- "producer" nodes have no deps but generate values asynchronously.
|
|
37
|
-
- Edges wire output of one node as input to another. They must match deps.
|
|
38
|
-
- meta.description is required for every node.
|
|
39
|
-
- Return ONLY valid JSON, no markdown fences or commentary.`;async function Er(t,e,r){let n=[{role:"system",content:r?.systemPromptExtra?`${Lt}
|
|
40
|
-
|
|
41
|
-
${r.systemPromptExtra}`:Lt},{role:"user",content:t}],a=e.invoke(n,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens}),i=(await ue(a)).content.trim();i.startsWith("```")&&(i=de(i));let l;try{l=JSON.parse(i)}catch{throw new Error(`graphFromSpec: LLM response is not valid JSON: ${i.slice(0,200)}`)}let m=Ze(l);if(!m.valid)throw new Error(`graphFromSpec: invalid graph definition:
|
|
42
|
-
${m.errors.join(`
|
|
43
|
-
`)}`);let d=l;return d.version===void 0&&(d.version=1),Array.isArray(d.subgraphs)||(d.subgraphs=[]),Z.fromSnapshot(d,r?.build)}function Ir(t){let e={},r=t.type;return r==="enum"&&Array.isArray(t.values)?(e.type="string",e.enum=t.values):r==="integer"?e.type="integer":r==="number"?e.type="number":r==="boolean"?e.type="boolean":r==="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 Or(t,e){let r=t.describe({actor:e,detail:"full"}),o=[],n=[],a=[];for(let[s,i]of Object.entries(r.nodes)){if(i.type!=="state"||s.includes("::__meta__::")||i.status==="completed"||i.status==="errored")continue;let l=i.meta??{},m=l.access;if(m==="human"||m==="system")continue;let d=l.description??`Set the value of ${s}`,u=Ir(l),p={type:"object",required:["value"],properties:{value:u},additionalProperties:!1},c=s.replace(/::/g,"__");o.push({type:"function",function:{name:c,description:d,parameters:p}}),n.push({name:s,description:d,inputSchema:p});let f=t,y=e,g=i.v;a.push({name:s,description:d,parameters:p,handler(T){return f.set(s,T.value,y?{actor:y}:void 0),T.value},...g!=null?{version:{id:g.id,version:g.version}}:{}})}return{openai:o,mcp:n,definitions:a}}var Pr=`You are a reactive graph optimizer for GraphReFly.
|
|
44
|
-
|
|
45
|
-
Given a graph's current structure (from describe()) and a problem statement, suggest topology and parameter changes to solve the problem.
|
|
46
|
-
|
|
47
|
-
Return ONLY valid JSON with this structure:
|
|
48
|
-
{
|
|
49
|
-
"summary": "<one-line summary of the strategy>",
|
|
50
|
-
"reasoning": "<explanation of why these changes help>",
|
|
51
|
-
"operations": [
|
|
52
|
-
{ "type": "add_node", "name": "<name>", "nodeType": "state|derived|effect|producer|operator", "meta": {...}, "initial": <value> },
|
|
53
|
-
{ "type": "remove_node", "name": "<name>" },
|
|
54
|
-
{ "type": "connect", "from": "<source>", "to": "<target>" },
|
|
55
|
-
{ "type": "disconnect", "from": "<source>", "to": "<target>" },
|
|
56
|
-
{ "type": "set_value", "name": "<name>", "value": <new_value> },
|
|
57
|
-
{ "type": "update_meta", "name": "<name>", "key": "<meta_key>", "value": <new_value> }
|
|
58
|
-
]
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
Rules:
|
|
62
|
-
- Only suggest operations that reference existing nodes (for remove/disconnect/set_value/update_meta) or new nodes you define (for add_node).
|
|
63
|
-
- Keep changes minimal \u2014 prefer the smallest set of operations that solves the problem.
|
|
64
|
-
- Return ONLY valid JSON, no markdown fences or commentary.`;async function jr(t,e,r,o){let{expand:n,...a}=t.describe({actor:o?.actor,detail:"standard"}),s=[{role:"system",content:Pr},{role:"user",content:JSON.stringify({graph:a,problem:e})}],i=r.invoke(s,{model:o?.model,temperature:o?.temperature??0,maxTokens:o?.maxTokens}),m=(await ue(i)).content.trim();m.startsWith("```")&&(m=m.replace(/^```(?:json)?\s*/,"").replace(/\s*```$/,""));let d;try{d=JSON.parse(m)}catch{throw new Error(`suggestStrategy: LLM response is not valid JSON: ${m.slice(0,200)}`)}let u=d;if(typeof u.summary!="string")throw new Error("suggestStrategy: missing 'summary' in response");if(typeof u.reasoning!="string")throw new Error("suggestStrategy: missing 'reasoning' in response");if(!Array.isArray(u.operations))throw new Error("suggestStrategy: missing 'operations' array in response");return{summary:u.summary,reasoning:u.reasoning,operations:u.operations}}export{Ft as a,Gt as b,Ge as c,yt as d,$t as e,Wt as f,Kt as g,Be as h,Ne as i,We as j,Vt as k,Ke as l,Ve as m,He as n,he as o,qe as p,tr as q,rr as r,nr as s,lr as t,dr as u,mr as v,cr as w,pr as x,gr as y,hr as z,br as A,Mr as B,kr as C,vr as D,Ee as E,ze as F,Ie as G,Je as H,Oe as I,Rr as J,Lr as K,wr as L,Cr as M,Ye as N,Qe as O,Xe as P,Ar as Q,Sr as R,Ze as S,Er as T,Or as U,jr as V,_r as W};
|
package/dist/chunk-MGKAO4EK.js
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import{a as Le}from"./chunk-ESMPEKEV.js";import{a as se,b as Se}from"./chunk-TWMEGG45.js";import{A as Ee}from"./chunk-KASHOCF5.js";import{A as Oe,C as L,E as re,F as Me,G as _e,e as $e,f as Te,i as Y,k as Ne,l as we,m as Ae,o as K,p as Pe,s as W}from"./chunk-W4TSQ6RJ.js";import{b as Z,c as be,d as ye,e as ee,f as ve,g as xe,h as V,i as te,j as ne}from"./chunk-CK2E7BTU.js";function Ie(e,t,n,r={}){let o=t in e.nodes,s=n in e.nodes;if(!o)return oe(t,n,"no-such-from");if(!s)return oe(t,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(t===n){if(r.findCycle===!0){let u=lt(e,t,r);if(u!=null)return u}let l=ie(t,e.nodes[t],0,r);return ae(t,n,[l])}if(i===0)return oe(t,n,"no-path");let a=je(e,t,n,i);return a.found?ae(t,n,Be(e,a.pathOrder,r)):oe(t,n,a.truncated?"max-depth-exceeded":"no-path")}function je(e,t,n,r){let o=new Map,s=[{path:n,depth:0}],i=new Set([n]),a=0,l=!1;for(;a<s.length;){let h=s[a++];if(h.path===t)break;if(r!=null&&h.depth>=r){let g=e.nodes[h.path];g?.deps&&g.deps.length>0&&(l=!0);continue}let p=e.nodes[h.path];if(p==null)continue;let f=p.deps??[],c=new Map;for(let g=0;g<f.length;g++){let b=f[g];if(!b)continue;let v=c.get(b);v==null&&(v=[],c.set(b,v)),v.push(g)}for(let[g,b]of c)i.has(g)||(i.add(g),o.set(g,{from:h.path,depIndices:b}),s.push({path:g,depth:h.depth+1}))}if(!o.has(t))return{found:!1,pathOrder:[],truncated:l};let u=[{path:t}],d=t;for(;d!==n;){let h=o.get(d);if(h==null)return{found:!1,pathOrder:[],truncated:!1};u[u.length-1].depIndices=h.depIndices,u.push({path:h.from}),d=h.from}return{found:!0,pathOrder:u,truncated:!1}}function lt(e,t,n){let r=e.nodes[t];if(r==null)return null;let o=r.deps??[],s=[];for(let a=0;a<o.length;a++)o[a]===t&&s.push(a);if(s.length>0){let a=ie(t,r,0,n);a.dep_index=s[0];let l=ie(t,r,1,n);return ae(t,t,[a,l])}let i=null;for(let a=0;a<o.length;a++){let l=o[a];if(!l||l===t)continue;let u=je(e,l,t,n.maxDepth);u.found&&(i==null||u.pathOrder.length<i.pathOrder.length)&&(i=u,i={found:!0,pathOrder:[{path:t,depIndices:[a]},...u.pathOrder],truncated:!1})}return i==null?null:ae(t,t,Be(e,i.pathOrder,n))}function Be(e,t,n){return t.map((r,o)=>{let s=e.nodes[r.path],i=ie(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 ie(e,t,n,r){let o={path:e,type:t.type,hop:n};t.status!==void 0&&(o.status=t.status),"value"in t&&(o.value=t.value),t.v!=null&&(o.v=t.v);let s=r.annotations?.get(e)??t.annotation;s!=null&&(o.annotation=s);let i=r.lastMutations?.get(e)??t.lastMutation;return i!=null&&(o.lastMutation=i),o}function ae(e,t,n){return Fe(e,t,!0,"ok",n)}function oe(e,t,n){return Fe(e,t,!1,n,[])}function Fe(e,t,n,r,o){let s=ct(e,t,n,r,o);return{from:e,to:t,found:n,reason:r,steps:o,text:s,toJSON(){return{from:e,to:t,found:n,reason:r,steps:o}}}}function ct(e,t,n,r,o){if(!n)switch(r){case"no-such-from":return`explainPath: no node named "${e}"`;case"no-such-to":return`explainPath: no node named "${t}"`;case"max-depth-exceeded":return`explainPath: no path from "${e}" to "${t}" within maxDepth`;default:return`explainPath: no path from "${e}" to "${t}"`}let s=[`Causal path: ${e} \u2192 ${t} (${o.length} step(s))`];for(let i of o){let l=` ${i.hop===0?"\xB7":"\u2193"} ${i.path} (${i.type}${i.status?`/${i.status}`:""})`;if(s.push(l),"value"in i&&s.push(` value: ${dt(i.value)}`),i.annotation!=null&&s.push(` annotation: ${i.annotation}`),i.lastMutation!=null){let u=i.lastMutation.actor;s.push(` actor: ${u.type}${u.id?`:${u.id}`:""}`)}}return s.join(`
|
|
2
|
-
`)}function dt(e){if(e===void 0)return"<sentinel>";if(e===null)return"null";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);try{let t=JSON.stringify(e);return t.length>80?`${t.slice(0,77)}...`:t}catch{return String(e)}}var A={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},ft=Symbol.for("sizeof");function ze(e){let t=new WeakSet,n=new WeakSet,r=[e],o=0;for(;r.length>0;){let s=r.pop();o+=pt(s,t,n,r)}return o}function pt(e,t,n,r){if(e==null)return 0;switch(typeof e){case"number":return A.number;case"boolean":return A.boolean;case"string":return A.string+e.length*2;case"bigint":return A.bigint+ht(e);case"symbol":return A.symbol;case"function":return t.has(e)?0:(t.add(e),A.function);case"undefined":return 0}let s=e;if(t.has(s))return 0;t.add(s);let i=s[ft];if(typeof i=="function")try{let u=i.call(s);if(typeof u=="number"&&Number.isFinite(u))return u}catch{}if(s instanceof Date)return A.date;if(s instanceof RegExp)return A.regexp+s.source.length*2;if(s instanceof Error){let u=s.message?s.message.length*2:0,d=s.stack?s.stack.length*2:0;return A.error+u+d}if(typeof URL<"u"&&s instanceof URL)return A.url+s.href.length*2;if(typeof Promise<"u"&&s instanceof Promise)return A.promise;if(s instanceof WeakMap)return A.weakmap;if(s instanceof WeakSet)return A.weakset;if(s instanceof Map){let u=A.map;for(let[d,h]of s)u+=A.mapEntry,r.push(d),r.push(h);return u}if(s instanceof Set){let u=A.set;for(let d of s)u+=A.setEntry,r.push(d);return u}if(Array.isArray(s)){let u=A.array+s.length*8;for(let d of s)r.push(d);return u}if(s instanceof ArrayBuffer)return n.has(s)?0:(n.add(s),s.byteLength);if(ArrayBuffer.isView(s)){let u=s;return n.has(u.buffer)?48:(n.add(u.buffer),u.buffer.byteLength+48)}let a=A.object,l=Object.keys(s);for(let u of l){a+=A.string+u.length*2;try{r.push(s[u])}catch{}}return a}function ht(e){let t=e<0n?-e:e;if(t===0n)return 0;let n=t.toString(2).length;return Math.ceil(n/32)*8}function He(e,t){let n=t?.topN??10,r=e.describe({detail:"standard"}),o=[],s=e._collectObserveTargets;typeof s=="function"&&s.call(e,"",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 c=i.get(p),g=c instanceof L?c:null,b=g?ze(g.cache):0,v=g?g._sinkCount:0,w=f.deps?.length??0,m=f.type==="effect"&&v===0,y=v===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:b,subscriberCount:v,depCount:w,isOrphanEffect:m,orphanKind:y})}let l=a.reduce((p,f)=>p+f.valueSizeBytes,0),u=(p,f)=>[...a].sort(f??((c,g)=>g[p]-c[p])).slice(0,n),d=a.filter(p=>p.orphanKind!=null),h=a.filter(p=>p.isOrphanEffect);return{nodeCount:a.length,edgeCount:r.edges.length,subgraphCount:r.subgraphs.length,nodes:a,totalValueSizeBytes:l,hotspots:{byValueSize:u("valueSizeBytes"),bySubscriberCount:u("subscriberCount"),byDepCount:u("depCount")},orphans:d,orphanEffects:h}}var X=class{constructor(t){this.capacity=t;if(!Number.isInteger(t)||t<=0)throw new Error(`RingBuffer capacity must be a positive integer (got ${t})`);this.buf=new Array(t)}buf;head=0;_size=0;get size(){return this._size}get maxSize(){return this.capacity}push(t){let n=(this.head+this._size)%this.capacity;this.buf[n]=t,this._size<this.capacity?this._size++:this.head=(this.head+1)%this.capacity}shift(){if(this._size===0)return;let t=this.buf[this.head];return this.buf[this.head]=void 0,this.head=(this.head+1)%this.capacity,this._size--,t}at(t){if(this._size===0)return;let n=t<0?this._size+t:t;if(!(n<0||n>=this._size))return this.buf[(this.head+n)%this.capacity]}toArray(){let t=new Array(this._size);for(let n=0;n<this._size;n++)t[n]=this.buf[(this.head+n)%this.capacity];return t}clear(){for(let t=0;t<this._size;t++)this.buf[(this.head+t)%this.capacity]=void 0;this.head=0,this._size=0}};function Re(e){return e>=768&&e<=879||e>=1155&&e<=1161||e>=1425&&e<=1469||e>=1552&&e<=1562||e>=1611&&e<=1631||e>=1648&&e===1648||e>=1750&&e<=1756||e>=1759&&e<=1764||e>=1767&&e<=1768||e>=1770&&e<=1773||e>=1840&&e<=1866||e>=1958&&e<=1968||e>=2304&&e<=2307||e>=2362&&e<=2383||e>=2385&&e<=2391||e>=2402&&e<=2403||e>=2433&&e<=2435||e>=2492&&e<=2509||e>=2561&&e<=2563||e>=2620&&e<=2641||e>=2672&&e<=2673||e>=2677&&e===2677||e>=3633&&e===3633||e>=3636&&e<=3642||e>=3655&&e<=3662||e>=3761&&e===3761||e>=3764&&e<=3772||e>=3784&&e<=3790||e>=7616&&e<=7679||e>=8400&&e<=8447||e>=65024&&e<=65039||e>=65056&&e<=65071||e===8205?0:e>=4352&&e<=4447||e>=8986&&e<=8987||e>=9001&&e<=9002||e>=9193&&e<=9203||e>=9208&&e<=9210||e>=9725&&e<=9726||e>=9748&&e<=9749||e>=9800&&e<=9811||e===9855||e===9875||e===9889||e>=9898&&e<=9899||e>=9917&&e<=9918||e>=9924&&e<=9925||e===9934||e===9940||e===9962||e>=9970&&e<=9971||e===9973||e===9978||e===9981||e===9986||e===9989||e>=9992&&e<=9997||e===9999||e>=10067&&e<=10069||e===10071||e>=10133&&e<=10135||e===10160||e===10175||e>=10548&&e<=10549||e>=11013&&e<=11015||e>=11035&&e<=11036||e===11088||e===11093||e>=11904&&e<=12350||e>=12352&&e<=12447||e>=12448&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12784&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=19968&&e<=40959||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65131||e>=65281&&e<=65376||e>=65504&&e<=65510||e>=126980&&e===126980||e===127183||e>=127344&&e<=127345||e===127358||e===127359||e===127374||e>=127377&&e<=127386||e>=127456&&e<=127487||e>=127488&&e<=127490||e===127514||e===127535||e>=127538&&e<=127546||e>=127568&&e<=127569||e>=127744&&e<=129535||e>=129536&&e<=129791||e>=129792&&e<=130047||e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}function ue(e){let t=0;for(let n of e)t+=Re(n.codePointAt(0));return t}function Ve(e,t){if(t<=0)return"";let n=0,r="";for(let o of e){let s=Re(o.codePointAt(0));if(n+s>t){if(t<=1)return"\u2026";for(;n+1>t&&r.length>0;){let i=[...r].pop();r=r.slice(0,-i.length),n-=Re(i.codePointAt(0))}return`${r}\u2026`}r+=o,n+=s}return r}var gt={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"},mt={horizontal:"-",vertical:"|",cornerTL:"+",cornerTR:"+",cornerBL:"+",cornerBR:"+",tDown:"+",tUp:"+",tRight:"+",tLeft:"+",cross:"+",arrowRight:">",arrowDown:"v",arrowLeft:"<",arrowUp:"^",boxTL:"+",boxTR:"+",boxBL:"+",boxBR:"+",boxH:"-",boxV:"|"};function Ue(e,t){let n=t.charset==="ascii"?mt:gt,r=e.width,o=e.height,s=Array.from({length:o},()=>Array.from({length:r},()=>" ")),i=Array.from({length:o},()=>Array.from({length:r},()=>"empty"));for(let a of e.edges)yt(s,i,n,a);for(let a of e.boxes)bt(s,i,n,a,t.labelOf(a.id));return s.map(a=>Ot(a.join(""))).join(`
|
|
3
|
-
`)}function bt(e,t,n,r,o){let{x:s,y:i,w:a,h:l}=r;if(a<2||l<2){l>0&&Ke(e,t,s,i,a,o);return}H(e,t,s,i,n.boxTL);for(let d=s+1;d<s+a-1;d+=1)H(e,t,d,i,n.boxH);H(e,t,s+a-1,i,n.boxTR);for(let d=i+1;d<i+l-1;d+=1){H(e,t,s,d,n.boxV);for(let h=s+1;h<s+a-1;h+=1)Je(e,t,h,d," ","empty");H(e,t,s+a-1,d,n.boxV)}H(e,t,s,i+l-1,n.boxBL);for(let d=s+1;d<s+a-1;d+=1)H(e,t,d,i+l-1,n.boxH);H(e,t,s+a-1,i+l-1,n.boxBR);let u=i+Math.floor(l/2);Ke(e,t,s+1,u,a-2,o)}function H(e,t,n,r,o){Je(e,t,n,r,o,o===" "?"empty":o==="\u2500"||o==="-"?"boxH":o==="\u2502"||o==="|"?"boxV":"boxCorner")}function Je(e,t,n,r,o,s){if(r<0||r>=e.length)return;let i=e[r];n<0||n>=i.length||(i[n]=o,t[r][n]=s)}function Ke(e,t,n,r,o,s){if(r<0||r>=e.length)return;let i=n,a=o;for(let l of s){let u=ue(l);if(u!==0){if(a<u)break;i>=0&&i<e[r].length&&(e[r][i]=l,t[r][i]="label",u===2&&i+1<e[r].length&&(e[r][i+1]="",t[r][i+1]="label")),i+=u,a-=u}}for(;a>0;)i>=0&&i<e[r].length&&(e[r][i]=" ",t[r][i]="empty"),i+=1,a-=1}function yt(e,t,n,r){let o=r.points;if(o.length<2)return;for(let l=0;l+1<o.length;l+=1)vt(e,t,n,o[l],o[l+1]);for(let l=1;l+1<o.length;l+=1){let u=o[l-1],d=o[l],h=o[l+1],p=xt(u,d,h,n);p&&qe(e,t,d.x,d.y,p,"edgeCorner")}let s=o[o.length-1],i=o[o.length-2],a=wt(i,s,n);a&&qe(e,t,s.x,s.y,a,"arrow")}function vt(e,t,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 l=i;l<=a;l+=1)We(e,t,l,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 l=i;l<=a;l+=1)We(e,t,s,l,n,"v")}}}function We(e,t,n,r,o,s){if(r<0||r>=e.length)return;let i=e[r];if(n<0||n>=i.length)return;let a=t[r][n];if(!(a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label")){if(a==="empty"){i[n]=s==="h"?o.horizontal:o.vertical,t[r][n]=s==="h"?"edgeH":"edgeV";return}if(a==="edgeH"&&s==="v"){i[n]=o.cross,t[r][n]="edgeCorner";return}if(a==="edgeV"&&s==="h"){i[n]=o.cross,t[r][n]="edgeCorner";return}}}function qe(e,t,n,r,o,s){if(r<0||r>=e.length)return;let i=e[r];if(n<0||n>=i.length)return;let a=t[r][n];a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label"||(i[n]=o,t[r][n]=s)}function xt(e,t,n,r){let o=e.y===t.y,s=t.y===n.y;if(o===s)return;if(o){let l=e.x<t.x,u=n.y>t.y;return l&&u?r.cornerTR:l&&!u?r.cornerBR:!l&&u?r.cornerTL:r.cornerBL}let i=e.y<t.y,a=n.x>t.x;return i&&a?r.cornerBL:i&&!a?r.cornerBR:!i&&a?r.cornerTL:r.cornerTR}function wt(e,t,n){if(t.x>e.x)return n.arrowRight;if(t.x<e.x)return n.arrowLeft;if(t.y>e.y)return n.arrowDown;if(t.y<e.y)return n.arrowUp}function Ot(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===32;)t-=1;return e.slice(0,t)}function Qe(e){let t=_t(e);Et(t),St(t),Rt(t),Dt(t,e);let n=kt(t,e),{width:r,height:o}=Tt(t),s=[];for(let i of t.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 _t(e){let t=new Map;for(let o of e.nodes)t.set(o,{id:o,isVirtual:!1,layer:-1,order:0,x:0,y:0,w:e.widthCells(o),h:e.heightCells(o),in:[],out:[]});let n=[],r=0;for(let o of e.edges){if(o.from===o.to)continue;let s=t.get(o.from),i=t.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:t,layers:[],hops:n}}function Et(e){let t=new Map;for(let s of e.nodes.values())t.set(s.id,s.in.length);let n=[];for(let s of e.nodes.values())(t.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=e.nodes.get(i.toId);a.layer=Math.max(a.layer,s.layer+1);let l=(t.get(a.id)??0)-1;t.set(a.id,l),l<=0&&n.push(a)}}}for(let s of e.nodes.values())s.layer<0&&(s.layer=0)}function St(e){let t=Math.max(0,...Array.from(e.nodes.values(),s=>s.layer)),n=Array.from({length:t+1},()=>[]);for(let s of e.nodes.values())n[s.layer].push(s);let r=[],o=0;for(let s of e.hops){let i=e.nodes.get(s.fromId),a=e.nodes.get(s.toId),l=a.layer-i.layer;if(l<=0){i.out=i.out.filter(h=>h!==s),a.in=a.in.filter(h=>h!==s);continue}if(l===1){s.hopIndex=0,s.chainLen=1,r.push(s);continue}i.out=i.out.filter(h=>h!==s),a.in=a.in.filter(h=>h!==s);let u=i;for(let h=1;h<l;h+=1){let p=`__virt_${o++}__`,f={id:p,isVirtual:!0,layer:i.layer+h,order:0,x:0,y:0,w:0,h:1,in:[],out:[]};e.nodes.set(p,f),n[f.layer].push(f);let c={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:u.id,toId:p,hopIndex:h-1,chainLen:l};u.out.push(c),f.in.push(c),r.push(c),u=f}let d={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:u.id,toId:a.id,hopIndex:l-1,chainLen:l};u.out.push(d),a.in.push(d),r.push(d)}for(let s of n)for(let i=0;i<s.length;i+=1)s[i].order=i;e.layers=n,e.hops=r}function Rt(e){for(let n=0;n<4;n+=1){for(let r=1;r<e.layers.length;r+=1)Ye(e,e.layers[r],"in"),le(e.layers[r]);for(let r=e.layers.length-2;r>=0;r-=1)Ye(e,e.layers[r],"out"),le(e.layers[r])}for(let n=0;n<2;n+=1){let r=!1;for(let o=1;o<e.layers.length;o+=1){let s=e.layers[o];for(let i=0;i+1<s.length;i+=1){let a=Xe(e,s[i],s[i+1],"in");[s[i],s[i+1]]=[s[i+1],s[i]],le(s),Xe(e,s[i],s[i+1],"in")<a?r=!0:([s[i],s[i+1]]=[s[i+1],s[i]],le(s))}}if(!r)break}}function Ye(e,t,n){let r=new Map;for(let o of t){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 l of s){let u=e.nodes.get(n==="in"?l.fromId:l.toId);u&&(i+=u.order,a+=1)}r.set(o.id,a===0?o.order:i/a)}t.sort((o,s)=>{let i=r.get(o.id),a=r.get(s.id);return i!==a?i-a:o.order-s.order})}function le(e){for(let t=0;t<e.length;t+=1)e[t].order=t}function Xe(e,t,n,r){let o=r==="in"?t.in:t.out,s=r==="in"?n.in:n.out,i=0;for(let a of o)for(let l of s){let u=e.nodes.get(r==="in"?a.fromId:a.toId)?.order??0,d=e.nodes.get(r==="in"?l.fromId:l.toId)?.order??0;(t.order<n.order&&u>d||t.order>n.order&&u<d)&&(i+=1)}return i}function Dt(e,t){t.direction==="LR"?Gt(e,t):Ct(e,t)}function Gt(e,t){let n=[],r=0;for(let o=0;o<e.layers.length;o+=1){n.push(r);let s=0;for(let i of e.layers[o])s=Math.max(s,i.w);r+=s+t.layerGap}for(let o=0;o<e.layers.length;o+=1)for(let s of e.layers[o])s.x=n[o];for(let o of e.layers){let s=0;for(let i of o)i.y=s,s+=i.h+t.nodeGap}Ze(e,t,"y")}function Ct(e,t){let n=[],r=0;for(let o=0;o<e.layers.length;o+=1){n.push(r);let s=0;for(let i of e.layers[o])s=Math.max(s,i.h);r+=s+t.layerGap}for(let o=0;o<e.layers.length;o+=1)for(let s of e.layers[o])s.y=n[o];for(let o of e.layers){let s=0;for(let i of o)i.x=s,s+=i.w+t.nodeGap}Ze(e,t,"x")}function Ze(e,t,n){let r=s=>n==="y"?s.h:s.w,o=t.nodeGap;for(let s=0;s<2;s+=1){let i=s===0?e.layers.slice(1):e.layers.slice(0,-1).reverse();for(let a of i){let l=new Map;for(let d of a){let h=s===0?d.in:d.out;if(h.length===0)continue;let p=[];for(let c of h){let g=e.nodes.get(s===0?c.fromId:c.toId);if(!g)continue;let b=n==="y"?g.y:g.x;p.push(b+Math.floor(r(g)/2))}if(p.length===0)continue;p.sort((c,g)=>c-g);let f=p[Math.floor(p.length/2)];l.set(d.id,f-Math.floor(r(d)/2))}let u=0;for(let d of a){let h=l.get(d.id),p=n==="y"?d.y:d.x,c=Math.max(h??p,u);n==="y"?d.y=c:d.x=c,u=c+r(d)+o}}}}function kt(e,t){let n=new Map;for(let u of e.hops){let d=n.get(u.chainId);d?d.push(u):n.set(u.chainId,[u])}for(let u of n.values())u.sort((d,h)=>d.hopIndex-h.hopIndex);let r=t.direction==="LR",o=u=>r?u.x:u.y,s=u=>r?u.w:u.h,i=u=>r?u.y+Math.floor(u.h/2):u.x+Math.floor(u.w/2),a=new Map;for(let u=0;u+1<e.layers.length;u+=1){let d=e.layers[u],h=e.layers[u+1],p=0;for(let E of d)p=Math.max(p,o(E)+s(E));let f=Number.POSITIVE_INFINITY;for(let E of h)f=Math.min(f,o(E));let c=Number.isFinite(f)?f-1:p,g=Math.max(1,c-p+1),b=[];for(let E of d)for(let R of E.out)b.push(R);b.sort((E,R)=>{let k=i(e.nodes.get(E.fromId)),$=i(e.nodes.get(R.fromId));if(k!==$)return k-$;let G=i(e.nodes.get(E.toId)),D=i(e.nodes.get(R.toId));return G-D});let v=[],w=new Map;for(let E of b){let R=i(e.nodes.get(E.fromId)),k=i(e.nodes.get(E.toId)),$=Math.min(R,k),G=Math.max(R,k),D=-1;for(let P=0;P<v.length;P+=1){let F=v[P],z=!0;for(let U of F)if(U.lo<=G&&$<=U.hi){z=!1;break}if(z){F.push({lo:$,hi:G}),D=P;break}}D<0&&(v.push([{lo:$,hi:G}]),D=v.length-1),w.set(E,D)}let m=v.length,y=g>=Math.max(3,m+2),S=y?p+1:p,x=y?c-1:c,O=Math.max(1,x-S+1);for(let E of b){let R=w.get(E),k;if(m<=1)k=S+Math.floor(O/2);else{let $=(O-1)/(m-1);k=S+Math.floor(R*$)}a.set(E,Math.max(p,Math.min(c,k)))}}let l=[];for(let[,u]of n){let d=[];for(let p=0;p<u.length;p+=1){let f=u[p],c=e.nodes.get(f.fromId),g=e.nodes.get(f.toId),b=a.get(f),v=c.isVirtual?o(c):o(c)+s(c),w=g.isVirtual?o(g):o(g)-1,m=i(c),y=i(g);p===0&&ce(d,r,v,m),m!==y&&(ce(d,r,b,m),ce(d,r,b,y)),ce(d,r,w,y)}let h=u[0];l.push({from:h.chainFrom,to:h.chainTo,points:$t(d)})}return l}function ce(e,t,n,r){e.push(t?{x:n,y:r}:{x:r,y:n})}function $t(e){let t=[];for(let n of e){let r=t[t.length-1];(!r||r.x!==n.x||r.y!==n.y)&&t.push(n)}return t}function Tt(e){let t=0,n=0;for(let r of e.layers)for(let o of r)t=Math.max(t,o.x+o.w),n=Math.max(n,o.y+o.h);return{width:t,height:n}}var Nt=24,At=4,Pt=1,Mt=3;function et(e,t){let n=Lt(t.direction),r=Math.max(3,t.maxLabelWidth??Nt),o=t.asciiCharset??"unicode",s=Object.keys(e.nodes).sort(),i=new Set(s),a=e.edges.filter(f=>i.has(f.from)&&i.has(f.to)),l=new Map,u=new Map;for(let f of s){let c=Ve(f,r);l.set(f,c),u.set(f,ue(c)+4)}let d=Qe({nodes:s,edges:a,widthCells:f=>u.get(f)??3,heightCells:()=>Mt,layerGap:At,nodeGap:Pt,direction:n}),h=Ue(d,{charset:o,labelOf:f=>l.get(f)??f}),p=t.logger;return p&&p(h),h}function Lt(e){if(e===void 0||e==="LR")return"LR";if(e==="TD")return"TD";throw new Error(`ascii describe supports direction "LR" or "TD" only; got ${String(e)}`)}var N="::",B="__meta__",q=1;function tt(e,t){let n=Math.max(16,e.size*4),r=0;for(;e.size>0;){if(r++>=n){console.error(`[Graph "${t}".destroy] disposer drain exceeded cap (${n}); ${e.size} disposer(s) discarded`),e.clear();return}let o=e.values().next();if(o.done)return;let s=o.value;e.delete(s);try{s()}catch(i){console.error(`[Graph "${t}".destroy] disposer threw:`,i)}}}function It(e){let t=[];for(let n of Object.keys(e).sort()){let r=e[n].v;r!=null&&t.push(`${n} ${r.id} ${r.version}`)}return t.join(`
|
|
4
|
-
`)}function nt(e){if(e.version!==q)throw new Error(`unsupported snapshot version ${String(e.version)} (expected ${q})`);for(let t of["name","nodes","edges","subgraphs"])if(!(t in e))throw new Error(`snapshot missing required key "${t}"`);if(typeof e.name!="string")throw new TypeError("snapshot 'name' must be a string");if(typeof e.nodes!="object"||e.nodes===null||Array.isArray(e.nodes))throw new TypeError("snapshot 'nodes' must be an object");if(!Array.isArray(e.edges))throw new TypeError("snapshot 'edges' must be an array");if(!Array.isArray(e.subgraphs))throw new TypeError("snapshot 'subgraphs' must be an array")}function jt(e,t){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,l=s.constructor;if(a!==l)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,c]of o)if(!p.has(f)||!r(c,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 c=!1;for(let g of p)if(r(f,g)){c=!0;break}if(!c)return!1}return!0}if(ArrayBuffer.isView(o)){let p=o,f=s;if(p.length!==f.length)return!1;for(let c=0;c<p.length;c++)if(p[c]!==f[c])return!1;return!0}let u=Object.keys(o),d=Object.keys(s);if(u.length!==d.length)return!1;let h=new Set(d);for(let p of u)if(!h.has(p)||!r(o[p],s[p]))return!1;return!0};return r(e,t)}function Ge(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(Ge);let t=e,n=Object.keys(t).sort(),r={};for(let o of n)r[o]=Ge(t[o]);return r}function Bt(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Ft(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}function zt(e){return e==="TD"?"down":e==="BT"?"up":e==="RL"?"left":"right"}function ot(e){let t=new Set,n=[];function r(o,s){let i=`${o}\0${s}`;t.has(i)||(t.add(i),n.push([o,s]))}for(let[o,s]of Object.entries(e.nodes)){let i=s.deps;if(i)for(let a of i)r(a,o)}for(let o of e.edges)r(o.from,o.to);return n}function it(e){if(e===void 0)return"LR";if(e==="TD"||e==="LR"||e==="BT"||e==="RL")return e;throw new Error(`invalid diagram direction ${String(e)}; expected one of: TD, LR, BT, RL`)}function Ht(e,t){let n=t.includeEdges??!0,r=t.includeSubgraphs??!0,{expand:o,...s}=e,i={...s,edges:n?e.edges:[],subgraphs:r?e.subgraphs:[]},a=JSON.stringify(Ge(i),null,t.indent??2);return t.logger?.(a),a}function Vt(e,t){let n=t.includeEdges??!0,r=t.includeSubgraphs??!0,o=[];o.push(`Graph ${e.name}`),o.push("Nodes:");for(let i of Object.keys(e.nodes).sort()){let a=e.nodes[i];o.push(`- ${i} (${a.type}/${a.status}): ${fe(a.value)}`)}if(n){o.push("Edges:");for(let i of e.edges)o.push(`- ${i.from} -> ${i.to}`)}if(r){o.push("Subgraphs:");for(let i of e.subgraphs)o.push(`- ${i}`)}let s=o.join(`
|
|
5
|
-
`);return t.logger?.(s),s}function at(e,t){let n=it(t.direction),r=Object.keys(e.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}["${Bt(i)}"]`)}for(let[i,a]of ot(e)){let l=o.get(i),u=o.get(a);!l||!u||s.push(` ${l} --> ${u}`)}return s.join(`
|
|
6
|
-
`)}function Kt(e,t){let n=at(e,t);return Wt(n)}function Wt(e,t){let n=t?.theme??"default",r=t?.autoSync??!0,s=JSON.stringify({code:e,mermaid:{theme:n},autoSync:r}),i=new TextEncoder().encode(s),a="";for(let u=0;u<i.length;u++)a+=String.fromCharCode(i[u]);return`https://mermaid.live/edit#base64:${globalThis.btoa(a).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`}function qt(e,t){let n=it(t.direction),r=Object.keys(e.nodes).sort(),o=new Map;for(let i=0;i<r.length;i+=1)o.set(r[i],`n${i}`);let s=[`direction: ${zt(n)}`];for(let i of r){let a=o.get(i);s.push(`${a}: "${Ft(i)}"`)}for(let[i,a]of ot(e)){let l=o.get(i),u=o.get(a);!l||!u||s.push(`${l} -> ${u}`)}return s.join(`
|
|
7
|
-
`)}function Ut(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function de(e){let t="^";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="*"){t+=".*";continue}if(r==="?"){t+=".";continue}if(r==="["){let o=e.indexOf("]",n+1);if(o<=n+1){t+="\\[";continue}let s=e.slice(n+1,o);s.startsWith("!")&&(s=`^${s.slice(1)}`),s=s.replace(/\\/g,"\\\\"),t+=`[${s}]`,n=o;continue}t+=Ut(r)}return t+="$",new RegExp(t)}var Jt={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"},Yt={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function fe(e){if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean"||e==null)return String(e);try{return JSON.stringify(e)}catch{return"[unserializable]"}}function Xt(e){return e==="none"?Yt:e==="ansi"||e==null?Jt:{data:e.data??"",dirty:e.dirty??"",resolved:e.resolved??"",invalidate:e.invalidate??"",pause:e.pause??"",resume:e.resume??"",complete:e.complete??"",error:e.error??"",teardown:e.teardown??"",derived:e.derived??"",path:e.path??"",reset:e.reset??""}}function rt(e){if(e==null)return{};let t=e.detail;return t==="full"?{...e,structured:e.structured??!0,timeline:e.timeline??!0,causal:e.causal??!0,derived:e.derived??!0}:t==="minimal"?{...e,structured:e.structured??!0}:e.format==="stage-log"?{...e,structured:e.structured??!0,timeline:e.timeline??!0}:e}function Qt(e,t,n){for(let r=0;r<e.length;r++){let o=e.charCodeAt(r);if(o<32||o===127)throw new Error(`Graph "${t}": ${n} "${e}" must not contain control character (U+${o.toString(16).padStart(4,"0").toUpperCase()} at index ${r})`)}}function De(e,t,n){if(e==="")throw new Error(`Graph "${t}": ${n} name must be non-empty`);if(e.includes(N))throw new Error(`Graph "${t}": ${n} "${e}" must not contain '${N}' (path separator)`);if(e===B)throw new Error(`Graph "${t}": ${n} name "${B}" is reserved for meta companion paths`);Qt(e,t,n)}function Zt(e,t){if(e==="")throw new Error(`Graph "${t}": resolve path must be non-empty`);let n=e.split(N);for(let r of n)if(r==="")throw new Error(`Graph "${t}": resolve path has empty segment`);return n}function en(e,t){let n=!1;for(let o of e)if(!t.isMetaPassthrough(o[0])){n=!0;break}return n?e.filter(o=>t.isMetaPassthrough(o[0])):e}function ut(e){for(let t of e._mounts.values())ut(t);for(let t of e._nodes.values())try{t.down([[V]],{internal:!0})}catch{}}var Ce=class e{name;opts;config;_nodes=new Map;_nodeToName=new WeakMap;_mounts=new Map;_parent=void 0;_storageDisposers=new Set;_disposers=new Set;_topology;_topologyEmitters=new Set;constructor(t,n){if(t==="")throw new Error("Graph name must be non-empty");if(t.includes(N))throw new Error(`Graph name must not contain '${N}' (got "${t}")`);if(t===B)throw new Error(`Graph name "${B}" is reserved for meta companion paths`);this.name=t,this.opts=Object.freeze({...n??{}}),this.config=n?.config??Oe,this._traceRing=new X(n?.traceCapacity??1e3),n?.versioning!=null&&this.setVersioning(n.versioning)}ancestors(t=!0){let n=[],r=t?this:this._parent;for(;r!=null;)n.push(r),r=r._parent;return n}get topology(){return this._topology==null&&(this._topology=Me(t=>{let n=r=>{t.emit(r)};return this._topologyEmitters.add(n),()=>{this._topologyEmitters.delete(n)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(t){if(!(this._topology==null||this._topologyEmitters.size===0))for(let n of this._topologyEmitters)n(t)}add(t,n){let r=t.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(De(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(t);if(a!==void 0)throw new Error(`Graph "${this.name}": node instance already registered as "${a}"`);return this._nodes.set(s,t),this._nodeToName.set(t,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()})),t}setVersioning(t){if(t!=null)for(let n of this._nodes.values())n instanceof L&&n._applyVersioning(t)}remove(t){De(t,this.name,"remove");let n=this._mounts.get(t);if(n){let s={kind:"mount",nodes:[],mounts:[]},i=[];n._collectObserveTargets("",i);for(let[a,l]of i)a.includes(`${N}${B}${N}`)||s.nodes.push(a);return s.nodes.sort(),s.mounts.push(t),s.mounts.push(...n._collectSubgraphs(`${t}${N}`)),this._mounts.delete(t),n._parent=void 0,ut(n),this._emitTopology({kind:"removed",name:t,nodeKind:"mount",audit:s}),s}let r=this._nodes.get(t);if(!r)throw new Error(`Graph "${this.name}": unknown node or mount "${t}"`);this._nodes.delete(t),this._nodeToName.delete(r),r.down([[V]],{internal:!0});let o={kind:"node",nodes:[t],mounts:[]};return this._emitTopology({kind:"removed",name:t,nodeKind:"node",audit:o}),o}removeAll(t){let n=typeof t=="function"?t:(()=>{let s=de(t);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 t=[...this._nodes.keys()].sort(),n=this._nodes,r=0;return{[Symbol.iterator](){return this},next(){if(r>=t.length)return{value:void 0,done:!0};let o=t[r++];return{value:[o,n.get(o)],done:!1}}}}node(t){if(t==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(t.includes(N))return this.resolve(t);let n=this._nodes.get(t);if(!n)throw new Error(`Graph "${this.name}": unknown node "${t}"`);return n}get(t){return this.node(t).cache}set(t,n,r){let o=r?.internal===!0;this.node(t).down([[Z,n]],{actor:r?.actor,internal:o,delivery:"write"})}setAll(t,n){let r=Symbol.iterator in t?t:Object.entries(t);Ae(()=>{for(let[o,s]of r)this.set(o,s,n)})}invalidate(t,n){let r=n?.internal===!0;this.node(t).down([[ee]],{actor:n?.actor,internal:r,delivery:"write"})}error(t,n,r){let o=r?.internal===!0;this.node(t).down([[ne,n]],{actor:r?.actor,internal:o,delivery:"write"})}complete(t,n){let r=n?.internal===!0;this.node(t).down([[te]],{actor:n?.actor,internal:r,delivery:"write"})}edges(t){let n=t?.recursive===!0,r=new Map;if(!n){for(let[l,u]of this._nodes)r.set(u,l);let a=[];for(let[l,u]of this._nodes)if(u instanceof L)for(let d of u._deps){let h=r.get(d.node);h!=null&&a.push([h,l])}return a.sort((l,u)=>l[0]<u[0]?-1:l[0]>u[0]?1:l[1]<u[1]?-1:l[1]>u[1]?1:0),a}let o=[];this._collectObserveTargets("",o);let s=new Map;for(let[a,l]of o)s.set(l,a);let i=[];for(let[a,l]of o)if(l instanceof L)for(let u of l._deps){let d=s.get(u.node);d!=null&&i.push([d,a])}return i.sort((a,l)=>a[0]<l[0]?-1:a[0]>l[0]?1:a[1]<l[1]?-1:a[1]>l[1]?1:0),i}mount(t,n){if(De(t,this.name,"mount"),this._nodes.has(t))throw new Error(`Graph "${this.name}": cannot mount at "${t}" \u2014 node with that name exists`);if(this._mounts.has(t))throw new Error(`Graph "${this.name}": mount "${t}" already exists`);if(n===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(n._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${n._parent.name}"`);for(let r=this;r!=null;r=r._parent)if(r===n)throw new Error(`Graph "${this.name}": mount("${t}", \u2026) would create a mount cycle`);return this._mounts.set(t,n),n._parent=this,this._emitTopology({kind:"added",name:t,nodeKind:"mount"}),n}resolve(t){let n=Zt(t,this.name);return this._resolveFromSegments(n)}tryResolve(t){try{return this.resolve(t)}catch{return}}_resolveFromSegments(t){let n=t;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]===B)return this._resolveMetaChainFromNode(s,o,n.join(N));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(N)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${r}"`);return i.resolve(o.join(N))}_resolveMetaChainFromNode(t,n,r){let o=t,s=0,i=[...n];for(;s<i.length;){if(i[s]!==B)throw new Error(`Graph "${this.name}": expected ${B} segment in meta path "${r}"`);if(s+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${B} in "${r}"`);let a=i[s+1],l=o.meta[a];if(!l)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${r}"`);o=l,s+=2}return o}signal(t,n){if(n?.internal!==!0){for(let o of t)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(t,n??{},new Set,r),r.length>0)throw r[0]}_signalDeliver(t,n,r,o){for(let l of this._mounts.values())l._signalDeliver(t,n,r,o);let i=n.internal===!0?{internal:!0}:{actor:n.actor,delivery:"signal"},a=en(t,this.config);for(let l of[...this._nodes.keys()].sort()){let u=this._nodes.get(l);if(!r.has(u)){r.add(u);try{u.down(t,i)}catch(d){if(d instanceof W)throw d;o.push(d)}a.length!==0&&this._signalMetaSubtree(u,a,r,i,o)}}}_signalMetaSubtree(t,n,r,o,s){for(let i of Object.keys(t.meta).sort()){let a=t.meta[i];if(!r.has(a)){r.add(a);try{a.down(n,o)}catch(l){if(l instanceof W)throw l;s.push(l)}this._signalMetaSubtree(a,n,r,o,s)}}}describe(t){if(t?.reactive===!0)return this._describeReactive(t);let n=t?.actor,r=t?.filter,o=se(t?.detail,t?.fields),s=t?.format==="spec",i=s?se("minimal"):o,a=[];this._collectObserveTargets("",a);let l=new Map;for(let[x,O]of a)l.set(O,x);let u=[];{let x=a.map(([,R])=>R),O=new Set(l.values()),E=0;for(;x.length>0;){let R=x.shift();if(R instanceof L)for(let k of R._deps){let $=k.node;if(l.has($))continue;let G=$.name??"",D=G;if(!D||O.has(D))if(G){let P=2;for(;O.has(`${G}#${P}`);)P++;D=`${G}#${P}`}else for(D=`__internal__/${E++}`;O.has(D);)D=`__internal__/${E++}`;l.set($,D),O.add(D),u.push([D,$]),x.push($)}}}let d=[...a,...u],h={};for(let[x,O]of d){if(n!=null&&!O.allowsObserve(n))continue;let E=Se(O,i),R=O instanceof L?O._deps.map(D=>l.get(D.node)??D.node.name??""):[],{name:k,...$}=E,G={...$,deps:R};if(!s){let D=this._annotations.get(x);D!=null&&(G.annotation=D)}if(r!=null)if(typeof r=="function"){let D=r;if(!(D.length>=2?D(x,G):D(G)))continue}else{let D=!0;for(let[P,F]of Object.entries(r)){let z=P==="deps_includes"?"depsIncludes":P==="meta_has"?"metaHas":P;if(z==="depsIncludes"){if(!G.deps.includes(String(F))){D=!1;break}continue}if(z==="metaHas"){if(!Object.hasOwn(G.meta??{},String(F))){D=!1;break}continue}if(G[z]!==F){D=!1;break}}if(!D)continue}h[x]=G}let p=new Set(Object.keys(h)),f=[];for(let[x,O]of d)if(O instanceof L)for(let E of O._deps){let R=l.get(E.node);R!=null&&f.push([R,x])}f.sort((x,O)=>x[0]<O[0]?-1:x[0]>O[0]?1:x[1]<O[1]?-1:x[1]>O[1]?1:0);let c=f.map(([x,O])=>({from:x,to:O}));(n!=null||r!=null)&&(c=c.filter(x=>p.has(x.from)&&p.has(x.to)));let g=this._collectSubgraphs(""),b=n!=null||r!=null?g.filter(x=>{let O=`${x}${N}`;return[...p].some(E=>E===x||E.startsWith(O))}):g,v=this,w=t,m={name:this.name,nodes:h,edges:c,subgraphs:b,expand(x){let O={...w,format:void 0};return Array.isArray(x)?(O.fields=x,O.detail=void 0):(O.detail=x,O.fields=void 0),v.describe(O)}},y=t??{},S=y.format;return S==="json"?Ht(m,y):S==="pretty"?Vt(m,y):S==="mermaid"?at(m,y):S==="mermaid-url"?Kt(m,y):S==="d2"?qt(m,y):S==="ascii"?et(m,y):m}_collectSubgraphs(t){let n=[];for(let r of[...this._mounts.keys()].sort()){let o=t===""?r:`${t}${r}`;n.push(o),n.push(...this._mounts.get(r)._collectSubgraphs(`${o}${N}`))}return n}resourceProfile(t){return He(this,t)}reachable(t,n,r={}){return r.withDetail===!0?st(this.describe(),t,n,{...r,withDetail:!0}):st(this.describe(),t,n,r)}explain(t,n,r){return r?.reactive===!0?this._explainReactive(t,n,r):this._explainStatic(t,n,r)}_explainStatic(t,n,r){let o=this.describe({detail:"full"}),s=new Map(this._annotations),i=new Map;for(let[a,l]of Object.entries(o.nodes))l.lastMutation!=null&&i.set(a,l.lastMutation);return Ie(o,t,n,{...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{},annotations:s,lastMutations:i})}_describeReactive(t){let n={...t,reactive:!1},r=t.reactiveName??"describe",o=0,s=re(o,{name:`${r}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,l=!1,u=()=>{a||l||(a=!0,we(()=>{a=!1,!l&&(o+=1,s.emit(o))}))},d=i.onEvent(b=>{let v=b.type;v!=="data"&&v!=="error"&&v!=="complete"&&v!=="teardown"||u()}),h=[],p=new WeakSet,f=b=>{if(p.has(b)||l)return;p.add(b);let v=b.topology.subscribe(w=>{for(let m of w){if(m[0]!==Z)continue;let y=m[1];if(u(),y.kind==="added"&&y.nodeKind==="mount"){let S=b._mounts.get(y.name);S!=null&&f(S)}}});h.push(v);for(let w of b._mounts.keys()){let m=b._mounts.get(w);m!=null&&f(m)}};f(this);let c;try{c=_e([s],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(b,v)=>b===v})}catch(b){d();for(let v of h)v();throw i.dispose(),b}let g=Ee(c);return{node:c,dispose(){l=!0,d();for(let b of h)b();h.length=0,i.dispose(),g()}}}_explainReactive(t,n,r){let o=0,s=re(o,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,l=!1,u=i.onEvent(f=>{let c=f.type;c!=="data"&&c!=="error"&&c!=="complete"&&c!=="teardown"||a||l||(a=!0,we(()=>{a=!1,!l&&(o+=1,s.emit(o))}))}),d={...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{}},h;try{h=_e([s],()=>this._explainStatic(t,n,d),{name:r?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:t,to:n},equals:(f,c)=>f.found===c.found&&f.reason===c.reason&&f.steps.length===c.steps.length&&nn(f.steps,c.steps)})}catch(f){throw u(),i.dispose(),f}let p=Ee(h);return{node:h,dispose(){l=!0,u(),i.dispose(),p()}}}_pathsMatching(t){let n=de(t),r=[];return this._collectObserveTargets("",r),r.map(([o])=>o).filter(o=>n.test(o))}_collectObserveTargets(t,n){for(let r of[...this._mounts.keys()].sort()){let o=t===""?r:`${t}${N}${r}`;this._mounts.get(r)._collectObserveTargets(o,n)}for(let r of[...this._nodes.keys()].sort()){let o=this._nodes.get(r),s=t===""?r:`${t}${N}${r}`;n.push([s,o]),this._appendMetaObserveTargets(s,o,n)}}_appendMetaObserveTargets(t,n,r){for(let o of Object.keys(n.meta).sort()){let s=n.meta[o],i=`${t}${N}${B}${N}${o}`;r.push([i,s]),this._appendMetaObserveTargets(i,s,r)}}observe(t,n){let r=typeof t=="string",s=rt(r?n:t),i=s.structured===!0||s.timeline===!0||s.causal===!0||s.derived===!0||s.detail==="minimal"||s.detail==="full"||s.format!=null,a=s.actor;if(r){let d=t,h=this.resolve(d);if(a!=null&&!h.allowsObserve(a))throw new W({actor:a,action:"observe",nodeName:d});return i?this._buildStructuredObserver([[d,h]],s,"one"):{subscribe(p){return h.subscribe(p)},up(p){try{h.up?.(p)}catch(f){if(f instanceof W)return;throw f}}}}let l=[];this._collectObserveTargets("",l),l.sort((d,h)=>d[0]<h[0]?-1:d[0]>h[0]?1:0);let u=a==null?l:l.filter(([,d])=>d.allowsObserve(a));return i?this._buildStructuredObserver(u,s,"all"):{subscribe:d=>{let h=u.map(([p,f])=>f.subscribe(c=>{d(p,c)}));return()=>{for(let p of h)p()}},up:(d,h)=>{try{this.resolve(d).up?.(h)}catch(p){if(p instanceof W)return;throw p}}}}_buildStructuredObserver(t,n,r){let o=r==="one"?t[0]?.[0]:void 0,s=i=>{if(r==="one"&&o!=null){let d=this.resolve(o);return this._buildStructuredObserver([[o,d]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((d,h)=>d[0]<h[0]?-1:d[0]>h[0]?1:0);let l=i.actor,u=l==null?a:a.filter(([,d])=>d.allowsObserve(l));return this._buildStructuredObserver(u,i,"all")};return this._createObserveResult(t,n,s)}_createObserveResult(t,n,r){let o=n.timeline===!0,s=n.causal===!0,i=n.derived===!0,a=n.detail==="minimal",l=this.config.inspectorEnabled,u=(s||i)&&l,d=n.maxEvents,h=d!=null&&d>0?new X(d):null,p=[],f=new Set,c={},g=new Set,b=0,v=0,w=0,m=0,y=0,S=0,x=!1,O=!1,E=0,R=new Map,k=new Map,$=new Map,G=_=>{h?h.push(_):p.push(_);for(let T of f)T(_)},D=()=>o?{timestamp_ns:K(),in_batch:Ne(),batch_id:E}:{},P=(_,T)=>{if(!(!u||!(_ instanceof L)))return _._setInspectorHook(I=>{if(I.kind==="dep_message")R.set(_,I.depIndex);else if(I.kind==="run"){let J=I.batchData.map((C,M)=>C!=null&&C.length>0?C.at(-1):I.prevData[M]);k.set(_,J);let j=I.batchData.map(C=>C!=null?[...C]:void 0);$.set(_,j),i&&G({type:"derived",path:T,dep_values:J,dep_batches:j,...D()})}})},F=_=>{let T=R.get(_),I=k.get(_);if(!s||I==null)return{};let j=(T!=null&&T>=0&&_ instanceof L?_._deps[T]:void 0)?.node,C=j?.v,M=$.get(_);return{trigger_dep_index:T,trigger_dep_name:j?.name,...C!=null?{trigger_version:{id:C.id,version:C.version}}:{},dep_values:[...I],...M!=null?{dep_batches:M}:{}}},z=[],U=[];for(let[_,T]of t){let I=P(T,_);I&&z.push(I),U.push(T.subscribe(J=>{E++;for(let j of J){let C=j[0],M=D();if(C===Z){c[_]=j[1];let me=T instanceof L?T.lastMutation?.actor??Y:Y;G({type:"data",path:_,data:j[1],actor:me,...M,...F(T)})}else if(a)C===be?b++:C===ye?v++:C===ee?w++:C===ve?m++:C===xe?y++:C===V?S++:C===te&&!g.has(_)?x=!0:C===ne&&(O=!0,g.add(_));else if(C===be)b++,G({type:"dirty",path:_,...M});else if(C===ye)v++,G({type:"resolved",path:_,...M,...F(T)});else if(C===ee)w++,G({type:"invalidate",path:_,...M});else if(C===ve)m++,G({type:"pause",path:_,lockId:j[1],...M});else if(C===xe)y++,G({type:"resume",path:_,lockId:j[1],...M});else if(C===te)g.has(_)||(x=!0),G({type:"complete",path:_,...M});else if(C===ne){O=!0,g.add(_);let me=T instanceof L?T.lastMutation?.actor??Y:Y;G({type:"error",path:_,data:j[1],actor:me,...M})}else C===V&&(S++,G({type:"teardown",path:_,...M}))}}))}let pe=!1,he=()=>{if(!pe){pe=!0;for(let _ of U)_();for(let _ of z)_();for(let _ of Q)_({value:void 0,done:!0});Q.length=0}},ge=[],Q=[];f.add(_=>{let T=Q.shift();T?T({value:_,done:!1}):ge.push(_)});let ke={get values(){return c},get dirtyCount(){return b},get resolvedCount(){return v},get invalidateCount(){return w},get pauseCount(){return m},get resumeCount(){return y},get teardownCount(){return S},get events(){return h?h.toArray():[...p]},get anyCompletedCleanly(){return x},get anyErrored(){return O},get completedWithoutErrors(){return x&&!O},onEvent(_){return f.add(_),()=>f.delete(_)},dispose:he,expand(_){he();let T={...n};return typeof _=="string"?T.detail=_:Object.assign(T,_),r(rt(T))},[Symbol.asyncIterator](){return{next(){return ge.length>0?Promise.resolve({value:ge.shift(),done:!1}):pe?Promise.resolve({value:void 0,done:!0}):new Promise(_=>Q.push(_))},return(){return he(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger(ke,n),ke}_attachFormatLogger(t,n){let r=n.format;if(r==null)return;let o=n.logger??(c=>console.log(c)),s=n.includeTypes?new Set(n.includeTypes):null,i=n.excludeTypes?new Set(n.excludeTypes):null,a=s==null&&i==null?()=>!0:c=>(s==null||s.has(c))&&(i==null||!i.has(c)),l=Xt(n.theme),u=r==="stage-log"?K():0,d=c=>c==null?"":n.stageLabels?.[c]??c,h=(c,g)=>c.length>g?`${c.slice(0,g-1)}\u2026`:c,p=c=>c.type==="data"||c.type==="error"?h(fe(c.data),120):"",f=c=>{if(r==="stage-log"){let O=(K()-u)/1e9,E=d(c.path).padEnd(9);if(c.type==="data"){let R=p(c);return`[${O.toFixed(3)}s] ${E} \u2190${R?` ${R}`:""}`}if(c.type==="error"){let R=p(c);return`[${O.toFixed(3)}s] ${E} \u2717${R?` ${R}`:""}`}return c.type==="complete"?`[${O.toFixed(3)}s] ${E} \u25A0 complete`:`[${O.toFixed(3)}s] ${E} ${c.type}`}if(r==="json")try{return JSON.stringify(c)}catch{return JSON.stringify({type:c.type,path:c.path,data:"[unserializable]"})}let g=l[c.type]??"",b=c.path?`${l.path}${c.path}${l.reset} `:"",v=c.type==="data"||c.type==="error",w=c.type==="pause"||c.type==="resume",m=v?` ${fe(c.data)}`:w?` ${fe(c.lockId)}`:"",y=c.type==="data"||c.type==="resolved"||c.type==="derived"?c:void 0,S=y?.trigger_dep_name!=null?` <- ${y.trigger_dep_name}`:y?.trigger_dep_index!=null?` <- #${y.trigger_dep_index}`:"",x=c.in_batch?" [batch]":"";return`${b}${g}${c.type.toUpperCase()}${l.reset}${m}${S}${x}`};t.onEvent(c=>{a(c.type)&&o(f(c),c)})}addDisposer(t){return this._disposers.add(t),()=>{this._disposers.delete(t)}}destroy(){tt(this._disposers,this.name),this.signal([[V]],{internal:!0}),tt(this._storageDisposers,this.name);for(let t of[...this._mounts.values()])t._parent=void 0,t._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0}_destroyClearOnly(){for(let t of[...this._mounts.values()])t._parent=void 0,t._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0}snapshot(t){let{expand:n,...r}=this.describe({detail:"full"}),o={};for(let a of Object.keys(r.nodes).sort()){let{lastMutation:l,guard:u,...d}=r.nodes[a];o[a]=d}let s=[...r.subgraphs].sort(),i={...r,version:1,nodes:o,subgraphs:s};if(t?.format==null)return i;if(t.format==="json-string")return JSON.stringify(i);if(t.format==="bytes"){if(t.codec==null)throw new Error("snapshot({format: 'bytes'}) requires a `codec` name");let a=this.config.lookupCodec(t.codec);if(a==null)throw new Error(`snapshot: codec "${t.codec}" is not registered on this graph's config. Call config.registerCodec(...) before creating nodes.`);return $e(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(t.format)}"`)}static decode(t,n){let r=n?.config??Oe,{codec:o,codecVersion:s,payload:i}=Te(t,r);return o.decode(i,s)}restore(t,n){if(nt(t),t.name!==this.name)throw new Error(`Graph "${this.name}": restore snapshot name "${t.name}" does not match this graph`);let r=n?.only==null?null:(Array.isArray(n.only)?n.only:[n.only]).map(s=>de(s)),o=n?.includeProducers===!0;for(let s of Object.keys(t.nodes).sort()){if(r!==null&&!r.some(a=>a.test(s)))continue;let i=t.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 l=this.tryResolve(s)?.v;if(l!=null&&l.id===i.v.id&&l.version===i.v.version)continue}try{this.set(s,i.value)}catch(a){n?.onError?.(s,a)}}}}}static fromSnapshot(t,n){nt(t);let r=typeof n=="function"?n:n?.build,o=typeof n=="function"?void 0:n?.factories,s=new e(t.name);if(r)return r(s),s.restore(t),s;for(let f of[...t.subgraphs].sort((c,g)=>{let b=c.split(N).length,v=g.split(N).length;return b!==v?b-v:c<g?-1:c>g?1:0})){let c=f.split(N),g=s;for(let b of c)g._mounts.has(b)||g.mount(b,new e(b)),g=g._mounts.get(b)}let i=o?Object.entries(o).map(([f,c])=>({re:de(f),factory:c})):[],a=f=>{for(let c of i)if(c.re.test(f))return c.factory},l=f=>{let c=f.split(N),g=c.pop();if(g==null||g.length===0)throw new Error(`invalid snapshot path "${f}"`);let b=s;for(let v of c){let w=b._mounts.get(v);if(!w)throw new Error(`unknown mount "${v}" in path "${f}"`);b=w}return[b,g]},u=Object.entries(t.nodes).filter(([f])=>!f.includes(`${N}${B}${N}`)).sort((f,c)=>f[0]<c[0]?-1:f[0]>c[0]?1:0),d=new Map(u),h=new Map,p=!0;for(;d.size>0&&p;){p=!1;for(let[f,c]of[...d.entries()]){let g=c?.deps??[];if(!g.every(S=>h.has(S)))continue;let[b,v]=l(f),w={...c?.meta??{}},m=a(f),y;if(c?.type==="state")y=re(c.value,{meta:w});else{if(m==null)continue;y=m(v,{path:f,type:c.type,value:c.value,meta:w,deps:g,resolvedDeps:g.map(S=>h.get(S))})}b.add(y,{name:v}),h.set(f,y),d.delete(f),p=!0}}if(d.size>0){let f=[...d.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${f}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return s.restore(t),s}toJSON(){return this.snapshot()}attachStorage(t,n={}){let r=t.map(u=>({tier:u,debounceMs:Math.max(0,u.debounceMs??0),compactEvery:Math.max(1,u.compactEvery??10),timer:void 0,seq:0,lastSnapshot:void 0,lastFingerprint:"",disposed:!1,savePending:void 0}));n.autoRestore===!0&&this._cascadeRestore(t,n.onError);let o=(u,d)=>{if(u.disposed)return;let h=It(d.nodes);if(u.lastSnapshot!=null&&h!==""&&h===u.lastFingerprint)return;let p=u.seq+1,f=Pe(),b=u.lastSnapshot==null||p%u.compactEvery===0?{mode:"full",snapshot:d,seq:p,timestamp_ns:f,format_version:q}:{mode:"diff",diff:tn(u.lastSnapshot,d),seq:p,timestamp_ns:f,format_version:q};if(u.tier.filter&&!u.tier.filter(this.name,b))return;let v;try{v=u.tier.save(this.name,b)}catch(w){n.onError?.(w,u.tier);return}if(v&&typeof v.then=="function"){let y=(u.savePending??Promise.resolve()).then(()=>v,()=>v).then(()=>{u.disposed||(u.seq=p,u.lastSnapshot=d,u.lastFingerprint=h)},S=>{n.onError?.(S,u.tier)});u.savePending=y.finally(()=>{u.savePending===y&&(u.savePending=void 0)})}else u.seq=p,u.lastSnapshot=d,u.lastFingerprint=h},s=(u,d)=>{try{o(u,d)}catch(h){n.onError?.(h,u.tier)}},i=(u,d)=>{if(!d.some(c=>{let g=this.config.messageTier(c[0]);return g>=3&&g<5}))return;if(n.filter){let c=this.tryResolve(u);if(c==null)return;let g=Se(c,se("standard"));if(!n.filter(u,g))return}let p,f=()=>(p==null&&(p=this.snapshot()),p);for(let c of r)c.disposed||(c.debounceMs===0?s(c,f()):(c.timer==null&&(c.timer=new Le),c.timer.start(c.debounceMs,()=>{c.disposed||s(c,this.snapshot())})))},a;if(n.paths!=null){let d=(typeof n.paths=="string"?this._pathsMatching(n.paths):n.paths).map(h=>{let p=this.tryResolve(h);return p==null?()=>{}:p.subscribe(f=>i(h,f))});a=()=>{for(let h of d)h()}}else a=this.observe().subscribe((u,d)=>i(u,d));let l=()=>{a();for(let u of r)u.disposed=!0,u.timer?.cancel();this._storageDisposers.delete(l)};return this._storageDisposers.add(l),{dispose:l}}async _cascadeRestore(t,n){for(let r of t){let o;try{o=await r.load(this.name)}catch(i){n?.(i,r);continue}if(o==null||typeof o!="object"||Array.isArray(o))continue;let s=o;try{if(s.mode==="full"&&s.snapshot!=null)return this.restore(s.snapshot),!0;if(s.version===q&&s.nodes!=null)return this.restore(s),!0}catch(i){n?.(i,r)}}return!1}static async fromStorage(t,n,r){for(let o of n){let s;try{s=await o.load(t)}catch(l){r?.onError?.(l,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===q&&i.nodes!=null?i:void 0;if(a!=null)try{return e.fromSnapshot(a,r)}catch(l){r?.onError?.(l,o)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${t}" across ${n.length} tier(s)`)}_annotations=new Map;_traceRing;trace(t,n,r){if(t!=null&&n!=null){if(this.tryResolve(t)==null)return;if(this._annotations.set(t,n),this.config.inspectorEnabled){let o={path:t,annotation:n,timestamp_ns:K(),...r?.actor!=null?{actor:r.actor}:{}};this._traceRing.push(o)}return}return t!=null?this.config.inspectorEnabled?this._annotations.get(t):void 0:this.config.inspectorEnabled?this._traceRing.toArray():[]}annotation(t){return this._annotations.get(t)}clearTrace(){this._annotations.clear(),this._traceRing.clear()}pruneTrace(t){let n=this._traceRing.toArray().filter(o=>!t(o)),r=this._traceRing.size-n.length;this._traceRing.clear();for(let o of n)this._traceRing.push(o);return r}static diff(t,n){let r=new Set(Object.keys(t.nodes)),o=new Set(Object.keys(n.nodes)),s=[...o].filter(w=>!r.has(w)).sort(),i=[...r].filter(w=>!o.has(w)).sort(),a=[],l=[];for(let w of r){if(!o.has(w))continue;let m=t.nodes[w],y=n.nodes[w],S=m.v,x=y.v;S!=null&&x!=null&&S.id===x.id&&S.version!==x.version&&l.push({path:w,id:S.id,from:S.version,to:x.version});let O=S!=null&&x!=null&&S.id===x.id&&S.version===x.version;for(let E of["type","status","sentinel"]){let R=m[E],k=y[E];R!==k&&a.push({path:w,field:E,from:R,to:k})}if(!O)for(let E of["value","meta"]){let R=m[E],k=y[E];jt(R,k)||a.push({path:w,field:E,from:R,to:k})}}let u=w=>`${w.from} ${w.to}`,d=new Set(t.edges.map(u)),h=new Set(n.edges.map(u)),p=n.edges.filter(w=>!d.has(u(w))),f=t.edges.filter(w=>!h.has(u(w))),c=new Set(t.subgraphs),g=new Set(n.subgraphs),b=[...g].filter(w=>!c.has(w)).sort(),v=[...c].filter(w=>!g.has(w)).sort();return{nodesAdded:s,nodesRemoved:i,nodesChanged:a,versionChanges:l,edgesAdded:p,edgesRemoved:f,subgraphsAdded:b,subgraphsRemoved:v}}};function tn(e,t){let n=Ce.diff(e,t),r={};for(let o of n.nodesAdded){let s=t.nodes[o];s!=null&&(r[o]=s)}return{...n,nodesAddedFull:r}}function st(e,t,n,r={}){let o={paths:[],depths:new Map,truncated:!1};if(!t)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,l=new Map,u=new Map,d=new Set;for(let[m,y]of Object.entries(e.nodes)){if(!m)continue;d.add(m);let S=y.deps??[];i.set(m,S);for(let x of S)x&&(d.add(x),a.has(x)||a.set(x,new Set),a.get(x).add(m))}for(let m of e.edges){if(m==null||typeof m!="object")continue;let y=typeof m.from=="string"?m.from:"",S=typeof m.to=="string"?m.to:"";!y||!S||(d.add(y),d.add(S),u.has(y)||u.set(y,new Set),u.get(y).add(S),l.has(S)||l.set(S,new Set),l.get(S).add(y))}if(!d.has(t))return r.withDetail?o:[];let h=r.both===!0,p=m=>{if(h){let O=i.get(m)??[],E=l.get(m),R=a.get(m),k=u.get(m),$=[...O];return E&&$.push(...E),R&&$.push(...R),k&&$.push(...k),$}if(n==="upstream"){let O=i.get(m)??[],E=l.get(m);return E?[...O,...E]:O}let y=a.get(m),S=u.get(m),x=y?[...y]:[];return S&&x.push(...S),x},f=new Set([t]),c=new Map,g=[{path:t,depth:0}],b=0,v=!1;for(;b<g.length;){let m=g[b++];if(s!=null&&m.depth>=s){p(m.path).length>0&&(v=!0);continue}for(let y of p(m.path))!y||f.has(y)||(f.add(y),c.set(y,m.depth+1),g.push({path:y,depth:m.depth+1}))}let w=[...c.keys()].sort((m,y)=>m<y?-1:m>y?1:0);return r.withDetail?{paths:w,depths:c,truncated:v}:w}function nn(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++){let r=e[n],o=t[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}export{X as a,ue as b,Ie as c,A as d,ft as e,ze as f,He as g,B as h,q as i,Wt as j,Ce as k,tn as l,st as m};
|
package/dist/chunk-NSG4C6BF.js
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import{a as v,f as M}from"./chunk-7JDLFI6N.js";import{d as S}from"./chunk-OL33ZI6R.js";import{o as h}from"./chunk-W4TSQ6RJ.js";function O(e={}){return e.sdk?Q(e):z(e)}function _(e,t,o,n){let r=t?.model??o;if(!r)throw new Error("anthropicAdapter: model must be set via options.model or invokeOpts.model");let{system:s,chat:a}=W(e,t?.systemPrompt),i={model:r,messages:a.map(Y),max_tokens:t?.maxTokens??4096};return s&&(i.system=s),t?.temperature!=null&&(i.temperature=t.temperature),t?.tools&&t.tools.length>0&&(i.tools=t.tools.map(V)),t?.maxReasoningTokens!=null&&(i.thinking={type:"enabled",budget_tokens:t.maxReasoningTokens}),t?.cacheHint,n&&(i.stream=!0),t?.providerExtras&&Object.assign(i,t.providerExtras),i}function W(e,t){let o=[];t&&o.push(t);let n=[];for(let r of e)r.role==="system"?o.push(r.content):n.push(r);return{system:o.length>0?o.join(`
|
|
2
|
-
|
|
3
|
-
`):void 0,chat:n}}function Y(e){if(e.role==="tool")return{role:"user",content:[{type:"tool_result",tool_use_id:e.toolCallId,content:e.content}]};if(e.role==="assistant"&&e.toolCalls&&e.toolCalls.length>0){let t=[];e.content&&t.push({type:"text",text:e.content});for(let o of e.toolCalls)t.push({type:"tool_use",id:o.id,name:o.name,input:o.arguments});return{role:"assistant",content:t}}return{role:e.role,content:e.content}}function V(e){return{name:e.name,description:e.description,input_schema:e.parameters}}function A(e,t){if(!e)return{...t};let o={...e};return t.input_tokens!=null&&(o.input_tokens=t.input_tokens),t.output_tokens!=null&&(o.output_tokens=t.output_tokens),t.cache_read_input_tokens!=null&&(o.cache_read_input_tokens=t.cache_read_input_tokens),t.cache_creation_input_tokens!=null&&(o.cache_creation_input_tokens=t.cache_creation_input_tokens),t.cache_creation&&(o.cache_creation={...e.cache_creation??{},...t.cache_creation}),t.server_tool_use&&(o.server_tool_use={...e.server_tool_use??{},...t.server_tool_use}),o}function w(e){let t={input:{regular:e?.input_tokens??0},output:{regular:e?.output_tokens??0},raw:e};return e?.cache_read_input_tokens&&(t.input.cacheRead=e.cache_read_input_tokens),e?.cache_creation?(e.cache_creation.ephemeral_5m_input_tokens&&(t.input.cacheWrite5m=e.cache_creation.ephemeral_5m_input_tokens),e.cache_creation.ephemeral_1h_input_tokens&&(t.input.cacheWrite1h=e.cache_creation.ephemeral_1h_input_tokens)):e?.cache_creation_input_tokens&&(t.input.cacheWrite5m=e.cache_creation_input_tokens),e?.server_tool_use?.web_search_requests&&(t.auxiliary={webSearchRequests:e.server_tool_use.web_search_requests}),t}function P(e,t){let o=[],n=[];for(let r of e.content)if(r.type==="text"&&typeof r.text=="string")o.push(r.text);else if(r.type==="tool_use"){let s=r;n.push({id:s.id,name:s.name,arguments:s.input??{}})}return{content:o.join(""),toolCalls:n.length>0?n:void 0,usage:w(e.usage),finishReason:e.stop_reason,latencyMs:t,model:e.model,provider:"anthropic"}}function z(e){let t=e.apiKey??globalThis.process?.env?.ANTHROPIC_API_KEY,o=e.baseURL??"https://api.anthropic.com",n=e.anthropicVersion??"2023-06-01",r=e.fetchImpl??fetch,s=()=>{if(!t)throw new Error("anthropicAdapter: apiKey required for invoke/stream (or provide opts.sdk)");return{"x-api-key":t,"anthropic-version":n,"content-type":"application/json",...e.headers??{}}};return{provider:"anthropic",model:e.model,async invoke(a,i){let c=_(a,i,e.model,!1),u=h(),d=await r(`${o}/v1/messages`,{method:"POST",headers:s(),body:JSON.stringify(c),signal:i?.signal});if(!d.ok)throw await T(d);let l=await d.json(),p=Math.max(0,(h()-u)/1e6);return P(l,p)},async*stream(a,i){let c=_(a,i,e.model,!0),u=await r(`${o}/v1/messages`,{method:"POST",headers:{...s(),accept:"text/event-stream"},body:JSON.stringify(c),signal:i?.signal});if(!u.ok)throw await T(u);if(!u.body)throw new Error("anthropicAdapter: streaming response has no body");let d,l,p=new Map;for await(let f of X(u.body)){let k=f.data;if(!k)continue;let y;try{y=JSON.parse(k)}catch{continue}switch(y.type){case"message_start":{d=A(d,y.message.usage);break}case"content_block_start":{let g=y,m=g.content_block;m.type==="tool_use"&&(p.set(g.index,{id:String(m.id??""),name:String(m.name??""),argBuf:""}),yield{type:"tool-call-delta",delta:{id:String(m.id??""),name:String(m.name??"")}});break}case"content_block_delta":{let g=y,m=g.delta;if(m.type==="text_delta"&&typeof m.text=="string")yield{type:"token",delta:m.text};else if(m.type==="input_json_delta"&&typeof m.partial_json=="string"){let E=p.get(g.index);E&&(E.argBuf+=m.partial_json),yield{type:"tool-call-delta",delta:{argumentsDelta:m.partial_json}}}else m.type==="thinking_delta"&&typeof m.thinking=="string"&&(yield{type:"thinking",delta:m.thinking});break}case"message_delta":{let g=y;g.delta.stop_reason&&(l=g.delta.stop_reason),g.delta.usage&&(d=A(d,g.delta.usage));break}case"message_stop":break}}d&&(yield{type:"usage",usage:w(d)}),yield{type:"finish",reason:l??"stop"}}}}function Q(e){let t=e.sdk;if(!t)throw new Error("sdkBackedAnthropic: sdk instance required");return{provider:"anthropic",model:e.model,async invoke(o,n){let r=_(o,n,e.model,!1),s=h(),a=await t.messages.create(r,{signal:n?.signal}),i=Math.max(0,(h()-s)/1e6);return P(a,i)},async*stream(o,n){if(!t.messages.stream)throw new Error("sdkBackedAnthropic: SDK instance does not expose .messages.stream");let r=_(o,n,e.model,!0),s,a;for await(let i of t.messages.stream(r,{signal:n?.signal}))switch(i.type){case"message_start":s=A(s,i.message.usage);break;case"content_block_delta":{let c=i.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=i;c.delta.stop_reason&&(a=c.delta.stop_reason),c.delta.usage&&(s=A(s,c.delta.usage));break}}s&&(yield{type:"usage",usage:w(s)}),yield{type:"finish",reason:a??"stop"}}}}async function*X(e){let t=e.getReader(),o=new TextDecoder,n="";try{for(;;){let{done:r,value:s}=await t.read();if(r){n.length>0&&(yield I(n));return}n+=o.decode(s,{stream:!0});let a=U(n);for(;a!==null;){let i=n.slice(0,a.index);n=n.slice(a.index+a.length);let c=I(i);(c.data||c.event)&&(yield c),a=U(n)}}}finally{t.releaseLock()}}function I(e){let t={},o=[];for(let n of e.split(`
|
|
4
|
-
`)){let r=n.endsWith("\r")?n.slice(0,-1):n;if(!r||r.startsWith(":"))continue;let s=r.indexOf(":"),a=s===-1?r:r.slice(0,s),i=s===-1?"":r.slice(s+1).replace(/^ /,"");a==="data"?o.push(i):a==="event"?t.event=i:a==="id"&&(t.id=i)}return o.length>0&&(t.data=o.join(`
|
|
5
|
-
`)),t}function U(e){let t=e.indexOf(`\r
|
|
6
|
-
\r
|
|
7
|
-
`),o=e.indexOf(`
|
|
8
|
-
|
|
9
|
-
`),n=null;return t!==-1&&(n={index:t,length:4}),o!==-1&&(n===null||o<n.index)&&(n={index:o,length:2}),n}async function T(e){let t;try{t=await e.text()}catch{t=""}let o=new Error(`Anthropic API ${e.status}: ${e.statusText}${t?` \u2014 ${t}`:""}`);return o.status=e.status,o.headers=e.headers,o}function j(e={}){return e.sdk?ne(e):te(e)}function b(e,t){let o=[],n=[];t?.systemPrompt&&o.push(t.systemPrompt);for(let a of e){if(a.role==="system"){o.push(a.content);continue}if(a.role==="tool"){n.push({role:"user",parts:[{functionResponse:{name:a.name??a.toolCallId??"tool",response:{result:a.content}}}]});continue}if(a.role==="assistant"&&a.toolCalls&&a.toolCalls.length>0){let i=[];a.content&&i.push({text:a.content});for(let c of a.toolCalls)i.push({functionCall:{name:c.name,args:c.arguments}});n.push({role:"model",parts:i});continue}n.push({role:a.role==="assistant"?"model":"user",parts:[{text:a.content}]})}let r={contents:n};o.length>0&&(r.systemInstruction={role:"system",parts:[{text:o.join(`
|
|
10
|
-
|
|
11
|
-
`)}]});let s={};return t?.maxTokens!=null&&(s.maxOutputTokens=t.maxTokens),t?.temperature!=null&&(s.temperature=t.temperature),t?.maxReasoningTokens!=null&&(s.thinkingConfig={thinkingBudget:t.maxReasoningTokens}),Object.keys(s).length>0&&(r.generationConfig=s),t?.tools&&t.tools.length>0&&(r.tools=[{functionDeclarations:t.tools.map(Z)}]),t?.providerExtras&&Object.assign(r,t.providerExtras),r}function Z(e){return{name:e.name,description:e.description,parameters:e.parameters}}function L(e){let t={input:{regular:0},output:{regular:0},raw:e};if(!e)return t;let o=e.promptTokenCount??0,n=e.cachedContentTokenCount??0;if(t.input.regular=Math.max(0,o-n),n>0&&(t.input.cacheRead=n),e.toolUsePromptTokenCount&&(t.input.toolUse=e.toolUsePromptTokenCount),e.promptTokensDetails)for(let r of e.promptTokensDetails){let s=r.modality?.toLowerCase();s==="image"?t.input.image=(t.input.image??0)+r.tokenCount:s==="audio"?t.input.audio=(t.input.audio??0)+r.tokenCount:s==="video"&&(t.input.video=(t.input.video??0)+r.tokenCount)}return t.output.regular=e.candidatesTokenCount??0,e.thoughtsTokenCount&&(t.output.reasoning=e.thoughtsTokenCount),t}function $(e,t){let o=e.candidates?.[0],n=o?.content?.parts??[],r=[],s=[],a=0;for(let i of n)typeof i.text=="string"&&r.push(i.text),i.functionCall&&s.push({id:`${i.functionCall.name}-${a++}`,name:i.functionCall.name,arguments:i.functionCall.args??{}});return{content:r.join(""),toolCalls:s.length>0?s:void 0,usage:L(e.usageMetadata),finishReason:o?.finishReason,latencyMs:t,model:e.modelVersion,provider:"google"}}function ee(e){if(e.apiKey)return e.apiKey;let t=globalThis.process?.env;return t?.GOOGLE_API_KEY??t?.GEMINI_API_KEY}function te(e){let t=e.baseURL??"https://generativelanguage.googleapis.com/v1beta",o=e.fetchImpl??fetch,n=s=>{let a=s?.model??e.model;if(!a)throw new Error("googleAdapter: model must be set via options.model or invokeOpts.model");return a},r=()=>{let s=ee(e);if(!s)throw new Error("googleAdapter: apiKey required for invoke/stream");return`key=${encodeURIComponent(s)}`};return{provider:"google",model:e.model,async invoke(s,a){let i=n(a),c=b(s,a),u=h(),d=`${t}/models/${encodeURIComponent(i)}:generateContent?${r()}`,l=await o(d,{method:"POST",headers:{"content-type":"application/json",...e.headers??{}},body:JSON.stringify(c),signal:a?.signal});if(!l.ok)throw await D(l);let p=await l.json(),f=Math.max(0,(h()-u)/1e6);return $(p,f)},async*stream(s,a){let i=n(a),c=b(s,a),u=`${t}/models/${encodeURIComponent(i)}:streamGenerateContent?alt=sse&${r()}`,d=await o(u,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",...e.headers??{}},body:JSON.stringify(c),signal:a?.signal});if(!d.ok)throw await D(d);if(!d.body)throw new Error("googleAdapter: streaming response has no body");let l,p;for await(let f of oe(d.body)){if(!f.data)continue;let k;try{k=JSON.parse(f.data)}catch{continue}let y=k.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),k.usageMetadata&&(l=k.usageMetadata)}l&&(yield{type:"usage",usage:L(l)}),yield{type:"finish",reason:p??"stop"}}}}function ne(e){let t=e.sdk;if(!t)throw new Error("sdkBackedGoogle: sdk instance required");return{provider:"google",model:e.model,async invoke(o,n){let r=b(o,n),s=n?.model??e.model;if(!s)throw new Error("googleAdapter: model required");let a=h(),i=await t.models.generateContent({...r,model:s},{signal:n?.signal}),c=Math.max(0,(h()-a)/1e6);return $(i,c)},async*stream(o,n){if(!t.models.generateContentStream)throw new Error("sdkBackedGoogle: SDK instance does not expose generateContentStream");let r=b(o,n),s=n?.model??e.model;if(!s)throw new Error("googleAdapter: model required");let a,i;for await(let c of t.models.generateContentStream({...r,model:s},{signal:n?.signal})){let u=c.candidates?.[0];for(let d of u?.content?.parts??[])typeof d.text=="string"&&(d.thought?yield{type:"thinking",delta:d.text}:yield{type:"token",delta:d.text}),d.functionCall&&(yield{type:"tool-call-delta",delta:{name:d.functionCall.name,argumentsDelta:JSON.stringify(d.functionCall.args??{})}});u?.finishReason&&(i=u.finishReason),c.usageMetadata&&(a=c.usageMetadata)}a&&(yield{type:"usage",usage:L(a)}),yield{type:"finish",reason:i??"stop"}}}}async function*oe(e){let t=e.getReader(),o=new TextDecoder,n="";try{for(;;){let{done:r,value:s}=await t.read();if(r){n.length>0&&(yield G(n));return}n+=o.decode(s,{stream:!0});let a=K(n);for(;a!==null;){let i=n.slice(0,a.index);n=n.slice(a.index+a.length);let c=G(i);(c.data||c.event)&&(yield c),a=K(n)}}}finally{t.releaseLock()}}function G(e){let t={},o=[];for(let n of e.split(`
|
|
12
|
-
`)){let r=n.endsWith("\r")?n.slice(0,-1):n;if(!r||r.startsWith(":"))continue;let s=r.indexOf(":"),a=s===-1?r:r.slice(0,s),i=s===-1?"":r.slice(s+1).replace(/^ /,"");a==="data"?o.push(i):a==="event"?t.event=i:a==="id"&&(t.id=i)}return o.length>0&&(t.data=o.join(`
|
|
13
|
-
`)),t}function K(e){let t=e.indexOf(`\r
|
|
14
|
-
\r
|
|
15
|
-
`),o=e.indexOf(`
|
|
16
|
-
|
|
17
|
-
`),n=null;return t!==-1&&(n={index:t,length:4}),o!==-1&&(n===null||o<n.index)&&(n={index:o,length:2}),n}async function D(e){let t;try{t=await e.text()}catch{t=""}let o=new Error(`Google API ${e.status}: ${e.statusText}${t?` \u2014 ${t}`:""}`);return o.status=e.status,o.headers=e.headers,o}var re={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 J(e={}){return e.sdk?de(e):ce(e)}function R(e,t,o,n,r){let s=t?.model??o;if(!s)throw new Error("openAICompatAdapter: model must be set via options.model or invokeOpts.model");let a=e.map(ae);t?.systemPrompt&&!e.some(c=>c.role==="system")&&a.unshift({role:"system",content:t.systemPrompt});let i={model:s,messages:a};return t?.maxTokens!=null&&(i.max_tokens=t.maxTokens),t?.temperature!=null&&(i.temperature=t.temperature),t?.tools&&t.tools.length>0&&(i.tools=t.tools.map(se)),t?.maxReasoningTokens!=null&&(i.reasoning={max_tokens:t.maxReasoningTokens}),n&&(i.stream=!0,i.stream_options={include_usage:!0}),r&&Object.assign(i,r),t?.providerExtras&&Object.assign(i,t.providerExtras),i}function ae(e){return e.role==="tool"?{role:"tool",tool_call_id:e.toolCallId,content:e.content}:e.role==="assistant"&&e.toolCalls&&e.toolCalls.length>0?{role:"assistant",content:e.content||null,tool_calls:e.toolCalls.map(t=>({id:t.id,type:"function",function:{name:t.name,arguments:JSON.stringify(t.arguments)}}))}:{role:e.role,content:e.content}}function se(e){return{type:"function",function:{name:e.name,description:e.description,parameters:e.parameters}}}function C(e){let t={input:{regular:0},output:{regular:0},raw:e};if(!e)return t;let o=e.prompt_tokens??0,n=e.prompt_tokens_details?.cached_tokens??0;e.prompt_cache_hit_tokens!=null?(n=e.prompt_cache_hit_tokens,t.input.regular=e.prompt_cache_miss_tokens??Math.max(0,o-n)):t.input.regular=Math.max(0,o-n),n>0&&(t.input.cacheRead=n),e.prompt_tokens_details?.audio_tokens&&(t.input.audio=e.prompt_tokens_details.audio_tokens);let r=e.completion_tokens??0,s=e.completion_tokens_details?.reasoning_tokens??0;return t.output.regular=Math.max(0,r-s),s>0&&(t.output.reasoning=s),e.completion_tokens_details?.audio_tokens&&(t.output.audio=e.completion_tokens_details.audio_tokens),e.completion_tokens_details?.accepted_prediction_tokens&&(t.output.predictionAccepted=e.completion_tokens_details.accepted_prediction_tokens),e.completion_tokens_details?.rejected_prediction_tokens&&(t.output.predictionRejected=e.completion_tokens_details.rejected_prediction_tokens),t}function F(e,t,o){let n=e.choices[0],r=n?.message,s=r?.content??"",a=(r?.tool_calls??[]).map(i=>({id:i.id,name:i.function.name,arguments:ie(i.function.arguments)}));return{content:s,toolCalls:a.length>0?a:void 0,usage:C(e.usage),finishReason:n?.finish_reason,latencyMs:t,model:e.model,provider:o}}function ie(e){try{let t=JSON.parse(e);return typeof t=="object"&&t!=null?t:{_raw:e}}catch{return{_raw:e}}}function H(e){let t=e.preset??"openai",o=re[t],n=e.baseURL??o.baseURL,r=e.provider??o.provider,s=o.apiKeyEnv,a=e.apiKey??(s?globalThis.process?.env?.[s]:void 0);return{provider:r,baseURL:n,apiKey:a}}function ce(e){let{provider:t,baseURL:o,apiKey:n}=H(e),r=e.fetchImpl??fetch,s=t!=="ollama",a=()=>{let i={"content-type":"application/json",...e.headers??{}};if(s){if(!n)throw new Error(`openAICompatAdapter[${t}]: apiKey required for invoke/stream`);i.authorization=`Bearer ${n}`}return i};return{provider:t,model:e.model,async invoke(i,c){let u=R(i,c,e.model,!1,e.bodyExtras),d=h(),l=await r(`${o}/chat/completions`,{method:"POST",headers:a(),body:JSON.stringify(u),signal:c?.signal});if(!l.ok)throw await q(l,t);let p=await l.json(),f=Math.max(0,(h()-d)/1e6);return F(p,f,t)},async*stream(i,c){let u=R(i,c,e.model,!0,e.bodyExtras),d=await r(`${o}/chat/completions`,{method:"POST",headers:{...a(),accept:"text/event-stream"},body:JSON.stringify(u),signal:c?.signal});if(!d.ok)throw await q(d,t);if(!d.body)throw new Error(`openAICompatAdapter[${t}]: streaming response has no body`);let l,p;for await(let f of le(d.body)){if(!f.data||f.data==="[DONE]")continue;let k;try{k=JSON.parse(f.data)}catch{continue}let y=k.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 m of g.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:m.id,name:m.function?.name,argumentsDelta:m.function?.arguments}};g?.finish_reason&&(p=g.finish_reason)}k.usage&&(l=k.usage,yield{type:"usage",usage:C(l)})}yield{type:"finish",reason:p??"stop"}}}}function de(e){let t=e.sdk;if(!t)throw new Error("sdkBackedOpenAI: sdk instance required");let{provider:o}=H(e);return{provider:o,model:e.model,async invoke(n,r){let s=R(n,r,e.model,!1,e.bodyExtras),a=h(),i=await t.chat.completions.create(s,{signal:r?.signal}),c=Math.max(0,(h()-a)/1e6);return F(i,c,o)},async*stream(n,r){let s=R(n,r,e.model,!0,e.bodyExtras),a=await t.chat.completions.create(s,{signal:r?.signal}),i,c;for await(let u of a){let d=u.choices;if(d){let p=d[0];if(p?.delta?.content&&(yield{type:"token",delta:p.delta.content}),p?.delta?.reasoning_content&&(yield{type:"thinking",delta:p.delta.reasoning_content}),p?.delta?.tool_calls)for(let f of p.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:f.id,name:f.function?.name,argumentsDelta:f.function?.arguments}};p?.finish_reason&&(c=p.finish_reason)}let l=u.usage;l&&(i=l,yield{type:"usage",usage:C(l)})}yield{type:"finish",reason:c??"stop"}}}}async function*le(e){let t=e.getReader(),o=new TextDecoder,n="";try{for(;;){let{done:r,value:s}=await t.read();if(r){n.length>0&&(yield B(n));return}n+=o.decode(s,{stream:!0});let a=N(n);for(;a!==null;){let i=n.slice(0,a.index);n=n.slice(a.index+a.length);let c=B(i);(c.data||c.event)&&(yield c),a=N(n)}}}finally{t.releaseLock()}}function B(e){let t={},o=[];for(let n of e.split(`
|
|
18
|
-
`)){let r=n.endsWith("\r")?n.slice(0,-1):n;if(!r||r.startsWith(":"))continue;let s=r.indexOf(":"),a=s===-1?r:r.slice(0,s),i=s===-1?"":r.slice(s+1).replace(/^ /,"");a==="data"?o.push(i):a==="event"?t.event=i:a==="id"&&(t.id=i)}return o.length>0&&(t.data=o.join(`
|
|
19
|
-
`)),t}function N(e){let t=e.indexOf(`\r
|
|
20
|
-
\r
|
|
21
|
-
`),o=e.indexOf(`
|
|
22
|
-
|
|
23
|
-
`),n=null;return t!==-1&&(n={index:t,length:4}),o!==-1&&(n===null||o<n.index)&&(n={index:o,length:2}),n}async function q(e,t){let o;try{o=await e.text()}catch{o=""}let n=new Error(`${t} API ${e.status}: ${e.statusText}${o?` \u2014 ${o}`:""}`);return n.status=e.status,n.headers=e.headers,n}function Re(e){switch(e.provider){case"anthropic":{let t={apiKey:e.apiKey,model:e.model,baseURL:e.baseURL,headers:e.headers,sdk:e.sdk,fetchImpl:e.fetchImpl,...e.extras};return O(t)}case"google":{let t={apiKey:e.apiKey,model:e.model,baseURL:e.baseURL,headers:e.headers,sdk:e.sdk,fetchImpl:e.fetchImpl,...e.extras};return j(t)}case"dry-run":{let t={model:e.model,...e.extras};return v(t)}case"fallback":{let t={provider:e.provider,model:e.model,...e.extras};return M(t)}case"openai":case"openrouter":case"groq":case"ollama":case"deepseek":case"xai":{let t={preset:e.provider,apiKey:e.apiKey,model:e.model,baseURL:e.baseURL,headers:e.headers,bodyExtras:e.bodyExtras,sdk:e.sdk,fetchImpl:e.fetchImpl,...e.extras};return J(t)}default:{let t=e.provider;throw new Error(`createAdapter: unknown provider: ${String(t)}`)}}}var x=class extends Error{name="AllTiersExhaustedError";skipped;failed;constructor(t){let o=[];t.failed.size>0&&o.push(`failed=[${[...t.failed.keys()].join(",")}]`),t.skipped.length>0&&o.push(`skipped=[${t.skipped.map(n=>`${n.name}(${n.reason})`).join(",")}]`),super(`All LLM adapter tiers exhausted: ${o.join(" ")}`),this.skipped=t.skipped,this.failed=t.failed}};function Le(e,t={}){if(e.length===0)throw new RangeError("cascadingLlmAdapter: tiers must be non-empty");let o=e.map(r=>({name:r.name,adapter:r.adapter,filter:r.filter,breaker:r.breaker?"canExecute"in r.breaker?r.breaker:S(r.breaker):void 0})),n=t.streamRetryBeforeFirstChunk??!0;return{provider:"cascading",model:void 0,async invoke(r,s){let a=[],i=new Map;for(let u=0;u<o.length;u++){let d=o[u];if(d.filter&&!d.filter(r,s)){a.push({name:d.name,reason:"filter"});continue}if(d.breaker&&!d.breaker.canExecute()){a.push({name:d.name,reason:"breaker"});continue}try{let l=await Promise.resolve(d.adapter.invoke(r,s));return d.breaker?.recordSuccess(),{...l,metadata:{...l.metadata??{},tier:d.name}}}catch(l){i.set(d.name,l),d.breaker?.recordFailure(l);let p=o[u+1];p&&t.onFallback?.(d.name,p.name,l)}}let c={skipped:a,failed:i};throw t.onExhausted?.(c),new x(c)},async*stream(r,s){let a=[],i=new Map;for(let u=0;u<o.length;u++){let d=o[u];if(d.filter&&!d.filter(r,s)){a.push({name:d.name,reason:"filter"});continue}if(d.breaker&&!d.breaker.canExecute()){a.push({name:d.name,reason:"breaker"});continue}let l=!1;try{for await(let p of d.adapter.stream(r,s))l=!0,yield p;d.breaker?.recordSuccess();return}catch(p){if(i.set(d.name,p),d.breaker?.recordFailure(p),l||!n)throw p;let f=o[u+1];f&&t.onFallback?.(d.name,f.name,p)}}let c={skipped:a,failed:i};throw t.onExhausted?.(c),new x(c)}}}export{O as a,j as b,J as c,Re as d,x as e,Le as f};
|
package/dist/chunk-VIEUJSTT.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as R}from"./chunk-5Z4HDCO6.js";import{k}from"./chunk-MGKAO4EK.js";import{b as N}from"./chunk-AUY2YKCO.js";import{A as g}from"./chunk-KASHOCF5.js";import{D as T,E as S,G as y,m as q,p as w,t as u}from"./chunk-W4TSQ6RJ.js";import{b as A}from"./chunk-QYADASLV.js";var P={};A(P,{CqrsGraph:()=>h,MemoryEventStore:()=>_,cqrs:()=>O});var j=u((i,e)=>{i("write"),i("signal"),e("observe")}),D=u((i,e)=>{i("observe"),i("signal"),e("write")}),H=u((i,e)=>{i("observe"),i("signal"),e("write")});function m(i,e){return R("cqrs",i,e)}var _=class{_store=new Map;persist(e){let t=this._store.get(e.type);t||(t=[],this._store.set(e.type,t)),t.push(e)}loadEvents(e,t){let n=this._store.get(e)??[],r=t?.timestampNs,s=t?.seq,o=r==null?[...n]:n.filter(d=>d.timestampNs>r||d.timestampNs===r&&d.seq>(s??-1)),a=o.length>0?o[o.length-1]:void 0;return{events:o,cursor:a?{timestampNs:a.timestampNs,seq:a.seq}:t}}clear(){this._store.clear()}},h=class extends k{_eventLogs=new Map;_commandHandlers=new Map;_projections=new Set;_sagas=new Set;_keepaliveDisposers=[];_eventStore;_seq=0;constructor(e,t={}){super(e,t.graph)}destroy(){for(let e of this._keepaliveDisposers)e();this._keepaliveDisposers.length=0,super.destroy()}event(e){let t=this._eventLogs.get(e);if(t)return t.node;let n=N([],{name:e,versioning:0}),r=n.entries,s=y([r],([o])=>o,{name:e,describeKind:"state",meta:m("event",{event_name:e}),guard:H,initial:r.cache});return this.add(s,{name:e}),this._keepaliveDisposers.push(g(s)),this._eventLogs.set(e,{log:n,node:s}),s}_appendEvent(e,t){let n=this._eventLogs.get(e);if(n||(this.event(e),n=this._eventLogs.get(e)),n.node.status==="completed"||n.node.status==="errored")throw new Error(`Cannot dispatch to terminated event stream "${e}" (status: ${n.node.status}).`);let r=n.log.entries.v,s={type:e,payload:t,timestampNs:w(),seq:++this._seq,...r!=null?{v0:{id:r.id,version:r.version}}:{}};n.log.append(s),this._eventStore&&this._eventStore.persist(s)}command(e,t){let n=S(void 0,{name:e,describeKind:"state",meta:{...m("command",{command_name:e}),error:null},guard:j});return this.add(n,{name:e}),this._commandHandlers.set(e,t),n}dispatch(e,t){let n=this._commandHandlers.get(e);if(!n)throw new Error(`Unknown command: "${e}". Register with .command() first.`);let r=this.resolve(e);q(()=>{r.emit(t,{internal:!0});try{n(t,{emit:(s,o)=>this._appendEvent(s,o)}),r.meta.error.emit(null,{internal:!0})}catch(s){throw r.meta.error.emit(s,{internal:!0}),s}})}projection(e,t,n,r){let s=t.map(a=>(this._eventLogs.has(a)||this.event(a),this._eventLogs.get(a).node)),o=y(s,a=>{let d=[];for(let v of a){let p=v;d.push(...p)}return d.sort((v,p)=>v.timestampNs-p.timestampNs||v.seq-p.seq),n(r,d)},{name:e,describeKind:"derived",meta:m("projection",{projection_name:e,source_events:t}),guard:D,initial:r});return this.add(o,{name:e}),this._keepaliveDisposers.push(g(o)),this._projections.add(e),o}saga(e,t,n){let r=t.map(d=>(this._eventLogs.has(d)||this.event(d),this._eventLogs.get(d).node)),s=new Map,o={},a=T(r,(d,v)=>{let p=o.n.meta.error;for(let c=0;c<d.length;c++){let E=d[c];if(E==null||E.length===0)continue;let l=E.at(-1);if(!l)continue;let f=t[c],C=s.get(f)??0;if(l.length>C){let b=l.slice(C);for(let L of b)try{n(L),p.emit(null,{internal:!0})}catch(x){p.emit(x,{internal:!0})}s.set(f,l.length)}}},{name:e,describeKind:"effect",meta:{...m("saga",{saga_name:e,source_events:t}),error:null}});return o.n=a,this.add(a,{name:e}),this._keepaliveDisposers.push(g(a)),this._sagas.add(e),a}useEventStore(e){this._eventStore=e}async rebuildProjection(e,t,n){if(!this._eventStore)throw new Error("No event store wired. Call useEventStore() first.");let r=[];for(let s of e){let o=await this._eventStore.loadEvents(s);r.push(...o.events)}return r.sort((s,o)=>s.timestampNs-o.timestampNs||s.seq-o.seq),t(n,r)}};function O(i,e){return new h(i,e)}export{_ as a,h as b,O as c,P as d};
|