@graphrefly/graphrefly 0.33.0 → 0.34.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-3Y4BXFFR.js +1 -0
- package/dist/chunk-65WWQ5CB.js +43 -0
- package/dist/chunk-A3GDELMY.js +61 -0
- package/dist/chunk-KN2UMFT6.js +5 -0
- package/dist/{index--BTb6HUO.d.ts → index-3L3RC3VJ.d.ts} +250 -4
- package/dist/{index-C_cXlbu0.d.cts → index-CQtnGFrZ.d.cts} +250 -4
- package/dist/{index-DDf8PoPO.d.ts → index-CbCNoogR.d.ts} +71 -16
- package/dist/{index-Dgcd59CJ.d.cts → index-IxinNgAH.d.cts} +71 -16
- package/dist/index.cjs +57 -57
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/patterns/ai/browser.cjs +5 -5
- package/dist/patterns/ai/browser.js +1 -1
- package/dist/patterns/ai/index.cjs +19 -19
- package/dist/patterns/ai/index.d.cts +1 -1
- package/dist/patterns/ai/index.d.ts +1 -1
- package/dist/patterns/ai/index.js +1 -1
- package/dist/patterns/harness/index.cjs +10 -10
- package/dist/patterns/harness/index.d.cts +3 -3
- package/dist/patterns/harness/index.d.ts +3 -3
- package/dist/patterns/harness/index.js +1 -1
- package/dist/patterns/orchestration/index.cjs +7 -7
- package/dist/patterns/orchestration/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-DUK7LTJO.js +0 -43
- package/dist/chunk-HIJ2RKVP.js +0 -1
- package/dist/chunk-O2WY22L7.js +0 -5
- package/dist/chunk-Z4GXBOWO.js +0 -61
|
@@ -1,25 +1,25 @@
|
|
|
1
|
-
"use strict";var Nn=Object.defineProperty;var Ss=Object.getOwnPropertyDescriptor;var Ns=Object.getOwnPropertyNames;var _s=Object.prototype.hasOwnProperty;var ke=(t,e)=>()=>(t&&(e=t(t=0)),e);var _n=(t,e)=>{for(var n in e)Nn(t,n,{get:e[n],enumerable:!0})},Ms=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ns(e))!_s.call(t,o)&&o!==n&&Nn(t,o,{get:()=>e[o],enumerable:!(r=Ss(e,o))||r.enumerable});return t};var Es=t=>Ms(Nn({},"__esModule",{value:!0}),t);function Or(t,e){let n=new TextEncoder().encode(t.name);if(n.length===0||n.length>255)throw new Error(`encodeEnvelope: codec name "${t.name}" encodes to ${n.length} bytes (must be 1\u2013255)`);let r=t.version;if(!Number.isInteger(r)||r<0||r>65535)throw new Error(`encodeEnvelope: codec.version ${r} out of u16 range (expected integer 0\u201365535)`);let o=2+n.length+2+e.length;if(o>4294967295)throw new Error(`encodeEnvelope: total envelope size ${o} exceeds 2^32-1 bytes (payload ${e.length} bytes)`);let s=new Uint8Array(o),i=0;return s[i++]=Mn,s[i++]=n.length,s.set(n,i),i+=n.length,s[i++]=r>>>8&255,s[i++]=r&255,s.set(e,i),s}function Ar(t,e){if(t.length<Er)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${Er})`);let n=0,r=t[n++];if(r!==Mn)throw new Error(`decodeEnvelope: unsupported envelope version ${r} (expected ${Mn})`);let o=t[n++];if(o===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(n+o+2>t.length)throw new Error(`decodeEnvelope: envelope truncated (need ${n+o+2} bytes, have ${t.length})`);let s=new TextDecoder().decode(t.subarray(n,n+o));n+=o;let i=(t[n]<<8|t[n+1])>>>0;n+=2;let a=t.subarray(n),l=e.lookupCodec(s);if(l==null)throw new Error(`decodeEnvelope: codec "${s}" not registered (envelope codec_v=${i})`);return{codec:l,codecVersion:i,payload:a}}function Cr(t){t.registerCodec(Os)}var Os,Mn,Er,En=ke(()=>{"use strict";Os={name:"json",version:1,contentType:"application/json",encode(t){let e=JSON.stringify(t);return new TextEncoder().encode(e)},decode(t,e){let n=new TextDecoder().decode(t);return JSON.parse(n)}},Mn=1,Er=4});function Ct(t){if(t==null)return nt;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var nt,Lt=ke(()=>{"use strict";nt={type:"system",id:""}});function Dt(){return rt>0||gt}function Lr(){return rt>0}function yt(t){rt>0?ht.push(t):t()}function re(t){rt+=1;let e=!1;try{t()}catch(n){throw e=!0,n}finally{if(rt-=1,rt===0)if(e){if(!gt){let n=ht.splice(0);for(let r of n)try{r()}catch{}Ke.length=0,Ue.length=0,ot.length=0}}else As()}}function As(){let t=!gt;t&&(gt=!0);let e=[],n=0;try{for(;Ke.length>0||Ue.length>0||ot.length>0||t&&ht.length>0;){if(t&&ht.length>0){let s=ht.splice(0);for(let i of s)try{i()}catch(a){e.push(a)}continue}if(n+=1,n>1e3)throw Ke.length=0,Ue.length=0,ot.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let o=(Ke.length>0?Ke:Ue.length>0?Ue:ot).splice(0);for(let s of o)try{s()}catch(i){e.push(i)}}}finally{t&&(gt=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function It(t,e,n){if(e.length===0)return;if(e.length===1){let c=n(e[0][0]);if(c<3||!Dt()){t(e);return}(c>=5?ot:c===4?Ue:Ke).push(()=>t(e));return}let r=e.length,o=r,s=r,i=r,a=0;for(;a<r&&n(e[a][0])<3;)a++;for(o=a;a<r&&n(e[a][0])===3;)a++;for(s=a;a<r&&n(e[a][0])===4;)a++;i=a;let l=Dt();if(o>0){let c=e.slice(0,o);t(c)}if(s>o){let c=e.slice(o,s);l?Ke.push(()=>t(c)):t(c)}if(i>s){let c=e.slice(s,i);l?Ue.push(()=>t(c)):t(c)}if(r>i){let c=e.slice(i,r);l?ot.push(()=>t(c)):t(c)}}var rt,gt,Ke,Ue,ot,ht,Re=ke(()=>{"use strict";rt=0,gt=!1,Ke=[],Ue=[],ot=[],ht=[]});function V(){return Math.trunc(performance.now()*1e6)}function Te(){return Date.now()*1e6}var he=ke(()=>{"use strict"});var Ge,I,J,H,Se,Ne,Ae,ge,$,C,ze,Pt,Dr,Gt,Ir,Pr,Ft,On,An,Cn,$t,le=ke(()=>{"use strict";Ge=Symbol.for("graphrefly/START"),I=Symbol.for("graphrefly/DATA"),J=Symbol.for("graphrefly/DIRTY"),H=Symbol.for("graphrefly/RESOLVED"),Se=Symbol.for("graphrefly/INVALIDATE"),Ne=Symbol.for("graphrefly/PAUSE"),Ae=Symbol.for("graphrefly/RESUME"),ge=Symbol.for("graphrefly/TEARDOWN"),$=Symbol.for("graphrefly/COMPLETE"),C=Symbol.for("graphrefly/ERROR"),ze=Object.freeze([J]),Pt=Object.freeze([H]),Dr=Object.freeze([Se]),Gt=Object.freeze([Ge]),Ir=Object.freeze([$]),Pr=Object.freeze([ge]),Ft=Object.freeze([ze]),On=Object.freeze([Pt]),An=Object.freeze([Dr]),Cn=Object.freeze([Ir]),$t=Object.freeze([Pr])});function Gr(t){t.registerMessageType(Ge,{tier:0,wireCrossing:!1}),t.registerMessageType(J,{tier:1,wireCrossing:!1}),t.registerMessageType(Se,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(Ne,{tier:2,wireCrossing:!1}),t.registerMessageType(Ae,{tier:2,wireCrossing:!1}),t.registerMessageType(I,{tier:3,wireCrossing:!0}),t.registerMessageType(H,{tier:3,wireCrossing:!0}),t.registerMessageType($,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(C,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(ge,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var jt,Fr=ke(()=>{"use strict";le();jt=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_rigorRecorder;_frozen=!1;tierOf;constructor(e){this._onMessage=e.onMessage,this._onSubscribe=e.onSubscribe,this._defaultVersioning=e.defaultVersioning,this._defaultHashFn=e.defaultHashFn,this.tierOf=n=>{let r=this._messageTypes.get(n);return r!=null?r.tier:1}}get onMessage(){return this._frozen=!0,this._onMessage}get onSubscribe(){return this._frozen=!0,this._onSubscribe}set onMessage(e){this._assertUnfrozen(),this._onMessage=e}set onSubscribe(e){this._assertUnfrozen(),this._onSubscribe=e}get defaultVersioning(){return this._defaultVersioning}set defaultVersioning(e){this._assertUnfrozen(),this._defaultVersioning=e}get defaultHashFn(){return this._defaultHashFn}set defaultHashFn(e){this._assertUnfrozen(),this._defaultHashFn=e}get inspectorEnabled(){return this._inspectorEnabled}set inspectorEnabled(e){this._inspectorEnabled=e}get globalInspector(){return this._globalInspector}set globalInspector(e){this._globalInspector=e}get rigorRecorder(){return this._rigorRecorder}set rigorRecorder(e){this._rigorRecorder=e}registerMessageType(e,n){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:n.tier,wireCrossing:n.wireCrossing??n.tier>=3,metaPassthrough:n.metaPassthrough??!0}),this}messageTier(e){let n=this._messageTypes.get(e);return n!=null?n.tier:1}isWireCrossing(e){let n=this._messageTypes.get(e);return n!=null?n.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let n=this._messageTypes.get(e);return n!=null?n.metaPassthrough:!0}isKnownMessageType(e){return this._messageTypes.has(e)}registerCodec(e){return this._assertUnfrozen(),this._codecs.set(e.name,e),this}lookupCodec(e){return this._codecs.get(e)}_isFrozen(){return this._frozen}_assertUnfrozen(){if(this._frozen)throw new Error("GraphReFlyConfig is frozen: a node has already captured this config. Register custom types and set hooks before creating any node.")}}});function Ln(t){let e=Cs.filter(n=>t({type:n,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(n=>n==="human"||n==="llm"||n==="system")?"both":e.length===1?e[0]:e.join("+")}var _e,Cs,bt=ke(()=>{"use strict";_e=class extends Error{actor;action;nodeName;constructor(e,n){super(n??`GuardDenied: action "${String(e.action)}" denied for actor type "${String(e.actor.type)}"`),this.name="GuardDenied",this.actor=e.actor,this.action=e.action,this.nodeName=e.nodeName}get node(){return this.nodeName}},Cs=["human","llm","wallet","system"]});function Dn(t){if(t===void 0)return null;if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`Cannot hash non-finite number: ${t}`);if(Number.isInteger(t)&&!Number.isSafeInteger(t))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${t}. Cross-language cid parity is not guaranteed for unsafe integers.`);return t}if(typeof t=="string"||typeof t=="boolean"||t===null)return t;if(Array.isArray(t))return t.map(Dn);if(typeof t=="object"&&t!==null){let e={};for(let n of Object.keys(t).sort())e[n]=Dn(t[n]);return e}return null}function Is(t){let e=Ds.encode(t),n=e.length,r=n*8,o=n+9+63&-64,s=new Uint8Array(o);s.set(e),s[n]=128;let i=new DataView(s.buffer);i.setUint32(o-4,r>>>0,!1),i.setUint32(o-8,Math.floor(r/4294967296)>>>0,!1);let a=1779033703,l=3144134277,c=1013904242,d=2773480762,u=1359893119,p=2600822924,f=528734635,m=1541459225,h=new Uint32Array(64),g=(b,T)=>b>>>T|b<<32-T;for(let b=0;b<o;b+=64){for(let R=0;R<16;R++)h[R]=i.getUint32(b+R*4,!1);for(let R=16;R<64;R++){let E=h[R-15],M=h[R-2],L=g(E,7)^g(E,18)^E>>>3,j=g(M,17)^g(M,19)^M>>>10;h[R]=h[R-16]+L+h[R-7]+j>>>0}let T=a,k=l,w=c,v=d,x=u,S=p,N=f,_=m;for(let R=0;R<64;R++){let E=g(x,6)^g(x,11)^g(x,25),M=x&S^~x&N,L=_+E+M+Ls[R]+h[R]>>>0,j=g(T,2)^g(T,13)^g(T,22),W=T&k^T&w^k&w,B=j+W>>>0;_=N,N=S,S=x,x=v+L>>>0,v=w,w=k,k=T,T=L+B>>>0}a=a+T>>>0,l=l+k>>>0,c=c+w>>>0,d=d+v>>>0,u=u+x>>>0,p=p+S>>>0,f=f+N>>>0,m=m+_>>>0}let y=b=>b.toString(16).padStart(8,"0");return y(a)+y(l)+y(c)+y(d)+y(u)+y(p)+y(f)+y(m)}function In(t){let e=Dn(t??null),n=JSON.stringify(e);return Is(n).slice(0,16)}function Ps(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),n=e()+e()+e()+e();return`${n.slice(0,8)}-${n.slice(8,12)}-4${n.slice(13,16)}-${(parseInt(n.slice(16,17),16)&3|8).toString(16)}${n.slice(17,20)}-${n.slice(20,32)}`}function Pn(t,e,n){let r=n?.id??Ps();if(t===0)return{id:r,version:0};let s=(n?.hash??In)(e);return{id:r,version:0,cid:s,prev:null}}function $r(t,e,n){t.version+=1,"cid"in t&&(t.prev=t.cid,t.cid=n(e))}var Ls,Ds,jr=ke(()=>{"use strict";Ls=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ds=new TextEncoder});function Kr(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function Gn(t){t.prevData=void 0,t.dirty=!1,t.involvedThisWave=!1,t.dataBatch.length=0,t.terminal=void 0}function Bt(t){return t.length===0?t:typeof t[0]=="symbol"?[t]:t}function ie(t,e,n){let r=Ur(t)?t:[],o=typeof t=="function"?t:typeof e=="function"?e:void 0,s={};return Ur(t)?s=(Fn(e)?e:n)??{}:Fn(t)?s=t:s=(Fn(e)?e:n)??{},new fe(r,o,s)}var Br,Vr,Gs,Fs,st,fe,Ur,Fn,Me=ke(()=>{"use strict";En();Lt();Re();he();Fr();bt();le();jr();Br=()=>{},Vr=100;Gs=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},Fs=(t,e,n,r)=>{let o=t;if(o._status==="completed"||o._status==="errored")return;let s=o._cached,i=s===void 0?[Gt]:[Gt,[I,s]];o._status==="dirty"&&i.push(ze),It(e,i,o._config.tierOf)},st=new jt({onMessage:Gs,onSubscribe:Fs});Gr(st);Cr(st);fe=class t{_optsName;_describeKind;meta;_hasMeta;_config;_deps;_sinks=null;_sinkCount=0;_cached;_status;_cleanup;_store={};_waveHasNewData=!1;_hasNewTerminal=!1;_hasCalledFnOnce=!1;_paused=!1;_pendingWave=!1;_isExecutingFn=!1;_pendingRerun=!1;_rerunDepth=0;_dirtyDepCount=0;_batchPendingMessages=null;_pauseLocks=null;_pauseBuffer=null;_fn;_equals;_resubscribable;_resetOnTeardown;_autoComplete;_autoError;_pausable;_partial;_guard;_extraGuards;_hashFn;_versioning;_versioningLevel;_lastMutation;_inspectorHooks;_actions;constructor(e,n,r){this._config=r.config??st,this._config.onMessage,this._optsName=r.name,this._describeKind=r.describeKind,this._equals=r.equals??Object.is,this._resubscribable=r.resubscribable??!1,this._resetOnTeardown=r.resetOnTeardown??!1,this._autoComplete=r.completeWhenDepsComplete??!0,this._autoError=r.errorWhenDepsError??!0,this._pausable=r.pausable??!0,this._guard=r.guard,this._fn=n,this._partial=r.partial??!1,this._cached=r.initial!==void 0?r.initial:void 0,this._status=e.length===0&&n==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=r.versioningHash??this._config.defaultHashFn??In;let o=r.versioning??this._config.defaultVersioning;this._versioningLevel=o,this._versioning=o!=null?Pn(o,this._cached===void 0?void 0:this._cached,{id:r.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(Kr);let s={};for(let[a,l]of Object.entries(r.meta??{})){let c={initial:l,name:`${r.name??"node"}:meta:${a}`,describeKind:"state",config:this._config};r.guard!=null&&(c.guard=r.guard),s[a]=new t([],void 0,c)}Object.freeze(s),this.meta=s,this._hasMeta=Object.keys(s).length>0;let i=this;this._actions={emit(a){i._emit([[I,a]])},down(a){i._emit(Bt(a))},up(a){i._emitUp(Bt(a))}},this.down=this.down.bind(this),this.up=this.up.bind(this)}get _isTerminal(){return this._status==="completed"||this._status==="errored"}get name(){return this._optsName}get status(){return this._status}get cache(){return this._cached===void 0?void 0:this._cached}get lastMutation(){return this._lastMutation}get v(){return this._versioning}hasGuard(){return this._guard!=null}_applyVersioning(e,n){if(this._isExecutingFn)throw new Error(`Node "${this.name}": _applyVersioning cannot run mid-fn \u2014 call it outside of \`_execFn\` (typically at graph setup time before the first subscribe).`);let r=this._versioningLevel;if(r!=null&&e<=r)return;let o=n?.hash??this._hashFn;o!==this._hashFn&&(this._hashFn=o);let s=this._cached===void 0?void 0:this._cached,i=this._versioning,a=i?.id??n?.id,l=i?.version??0,c=Pn(e,s,{id:a,hash:o});c.version=l,this._versioning=c,this._versioningLevel=e}_setInspectorHook(e){return e==null?()=>{}:(this._inspectorHooks==null&&(this._inspectorHooks=new Set),this._inspectorHooks.add(e),()=>{this._inspectorHooks?.delete(e),this._inspectorHooks?.size===0&&(this._inspectorHooks=void 0)})}_pushGuard(e){return this._extraGuards==null&&(this._extraGuards=new Set),this._extraGuards.add(e),()=>{this._extraGuards?.delete(e),this._extraGuards?.size===0&&(this._extraGuards=void 0)}}allowsObserve(e){if(this._guard==null&&this._extraGuards==null)return!0;let n=Ct(e);if(this._guard!=null&&!this._guard(n,"observe"))return!1;if(this._extraGuards!=null){for(let r of this._extraGuards)if(!r(n,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let n=this._guard!=null||this._extraGuards!=null,r=e?.actor!=null;if(!n&&!r)return;let o=Ct(e?.actor),s=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(o,s))throw new _e({actor:o,action:s,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(o,s))throw new _e({actor:o,action:s,nodeName:this.name})}this._lastMutation={actor:o,timestamp_ns:Te()}}down(e,n){let r=Bt(e);r.length!==0&&(this._checkGuard(n),this._emit(r))}emit(e,n){this._checkGuard(n),this._emit([[I,e]])}up(e,n){if(this._deps.length===0)return;let r=Bt(e);if(r.length===0)return;this._checkGuard(n);let o=n??{internal:!0};this._validateUpTiers(r);for(let s of this._deps)s.node.up?.(r,o)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let n of this._deps)n.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let n=this._config.tierOf;for(let r of e){let o=n(r[0]);if(o===3||o===4)throw new Error(`Node "${this.name}": tier-${o} messages cannot flow up \u2014 DATA/RESOLVED/COMPLETE/ERROR are downstream-only. Use \`down(...)\` for value delivery; \`up(...)\` is for control signals (DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN).`)}}subscribe(e,n){if(n!=null&&this._guard!=null){let l=Ct(n);if(!this._guard(l,"observe"))throw new _e({actor:l,action:"observe",nodeName:this.name})}let o=this._isTerminal&&this._resubscribable;if(o){this._cached=void 0,this._status="sentinel",this._store={},this._hasCalledFnOnce=!1,this._waveHasNewData=!1,this._hasNewTerminal=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._isExecutingFn=!1,this._rerunDepth=0,this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null;for(let l of this._deps)Gn(l);if(this._partial===!1){for(let l of this._deps)if(l.prevData!==void 0||l.dataBatch.length!==0||l.terminal!==void 0||l.dirty)throw new Error(`resubscribable-reset invariant: DepRecord not fully reset for node ${this._optsName??"(anonymous)"}`)}}this._sinkCount+=1;let s;try{s=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:o},this._actions)}catch(l){throw this._sinkCount-=1,l}this._sinks==null?this._sinks=e:typeof this._sinks=="function"?this._sinks=new Set([this._sinks,e]):this._sinks.add(e);let i=this._isTerminal;if(this._sinkCount===1&&!i)try{this._activate()}catch(l){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof s=="function")try{s()}catch{}throw l}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let a=!1;return()=>{a||(a=!0,this._sinkCount-=1,this._removeSink(e),typeof s=="function"&&s(),this._sinks==null&&this._deactivate())}}_removeSink(e){if(this._sinks===e)this._sinks=null;else if(this._sinks!=null&&typeof this._sinks!="function")if(this._sinks.delete(e),this._sinks.size===1){let[n]=this._sinks;this._sinks=n}else this._sinks.size===0&&(this._sinks=null)}_activate(){if(this._deps.length===0){this._fn&&this._execFn();return}this._dirtyDepCount=0;let e=this._deps.length,n=0;try{for(let r=0;r<e;r++){let o=r,s=this._deps[r];s.unsub=Br,s.unsub=s.node.subscribe(i=>{if(s.unsub===null)return;let a=this._config.tierOf,l=!1;for(let c of i)a(c[0])>=3&&(l=!0),this._config.onMessage(this,c,{direction:"down-in",depIndex:o},this._actions);l&&this._maybeRunFnOnSettlement()}),n++}}catch(r){this._deps[n].unsub=null;for(let o=0;o<n;o++){let s=this._deps[o];if(s.unsub!=null){let i=s.unsub;s.unsub=null;try{i()}catch{}Gn(s)}}throw this._dirtyDepCount=0,r}}_addDep(e){for(let o=0;o<this._deps.length;o++)if(this._deps[o].node===e)return o;let n=this._deps.length,r=Kr(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Ft),r.unsub=Br;try{r.unsub=e.subscribe(o=>{if(r.unsub===null)return;let s=this._config.tierOf,i=!1;for(let a of o)s(a[0])>=3&&(i=!0),this._config.onMessage(this,a,{direction:"down-in",depIndex:n},this._actions);i&&this._maybeRunFnOnSettlement()})}catch(o){throw r.unsub=null,this._deps.pop(),this._dirtyDepCount--,o}return n}_deactivate(e=!1){let n=this._cleanup;if(this._cleanup=void 0,typeof n=="function")try{n()}catch(r){this._emit([[C,this._wrapFnError("cleanup threw",r)]])}else if(n!=null&&typeof n=="object"){let r=n.deactivate;if(typeof r=="function")try{r()}catch(o){this._emit([[C,this._wrapFnError("cleanup.deactivate threw",o)]])}}for(let r of this._deps){if(r.unsub!=null){let o=r.unsub;r.unsub=null;try{o()}catch{}}Gn(r)}this._waveHasNewData=!1,this._hasNewTerminal=!1,this._hasCalledFnOnce=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._rerunDepth=0,this._store={},this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null,this._fn!=null&&(this._cached=void 0),e||(this._fn!=null||this._deps.length>0)&&(!this._isTerminal||this._resubscribable)&&(this._status="sentinel")}_onDepMessage(e,n){let r=this._deps[e],o=n[0];if(this._inspectorHooks!=null){let s={kind:"dep_message",depIndex:e,message:n};for(let i of this._inspectorHooks)i(s)}if(o!==Ge){if(o===J){this._depDirtied(r);return}if(o===Se){if(this._depInvalidated(r),this._cached===void 0)return;this._emit(An);return}if(o===Ne||o===Ae){this._emit([n]);return}if(o===ge){this._emit($t);return}if(o===I)this._depSettledAsData(r,n[1]);else if(o===H)this._depSettledAsResolved(r);else if(o===$)this._depSettledAsTerminal(r,!0);else if(o===C)this._depSettledAsTerminal(r,n[1]);else{this._emit([n]);return}if(!this._fn){(o===I||o===H)&&this._emit([n]),(o===$||o===C)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Ft))}_depSettledAsData(e,n){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.involvedThisWave=!0,e.dataBatch.push(n),this._waveHasNewData=!0}_depSettledAsResolved(e){e.dirty&&(e.dirty=!1,this._dirtyDepCount--)}_depSettledAsTerminal(e,n){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.terminal=n,e.involvedThisWave=!0,this._hasNewTerminal=!0}_depInvalidated(e){e.prevData=void 0,e.terminal=void 0,e.dataBatch.length=0,e.dirty?e.involvedThisWave=!1:(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++)}_maybeRunFnOnSettlement(){if(!(this._isTerminal&&!this._resubscribable)&&!(this._dirtyDepCount>0)){if(!this._partial&&!this._hasCalledFnOnce)for(let e=0;e<this._deps.length;e++){let n=this._deps[e];if(n.dataBatch.length===0&&n.prevData===void 0&&n.terminal===void 0){this._maybeAutoTerminalAfterWave();return}}if(this._paused){this._pendingWave=!0;return}if(!this._waveHasNewData&&!this._hasNewTerminal&&this._hasCalledFnOnce){this._clearWaveFlags(),this._emit(On),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(n=>n.terminal!==void 0&&n.terminal!==!0);if(e!=null){this._autoError&&this._emit([[C,e.terminal]]);return}this._autoComplete&&this._deps.every(n=>n.terminal!==void 0)&&this._emit(Cn)}_execFn(){if(!this._fn||this._isTerminal&&!this._resubscribable)return;if(this._isExecutingFn){this._pendingRerun=!0;return}let e=this._cleanup;if(typeof e=="function"){this._cleanup=void 0;try{e()}catch(i){this._emit([[C,this._wrapFnError("cleanup threw",i)]]);return}}else if(e!=null&&typeof e=="object"){let i=e.beforeRun;if(typeof i=="function"){e.beforeRun=void 0;try{i()}catch(a){this._emit([[C,this._wrapFnError("cleanup.beforeRun threw",a)]]);return}}}let n=this._deps.map(i=>i.involvedThisWave?i.dataBatch.length>0?[...i.dataBatch]:[]:void 0),r=this._deps.map(i=>i.prevData);for(let i=0;i<this._deps.length;i++){let a=n[i];a!=null&&a.length>0&&(this._deps[i].prevData=a[a.length-1])}let o=this._deps.map(i=>i.terminal),s={prevData:r,terminalDeps:o,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let i={kind:"run",batchData:n,prevData:r};for(let a of this._inspectorHooks)a(i)}this._isExecutingFn=!0;try{let i=this._fn(n,this._actions,s);if(typeof i=="function")this._cleanup=i;else if(i!=null&&typeof i=="object"){let a=i;(typeof a.beforeRun=="function"||typeof a.deactivate=="function"||typeof a.invalidate=="function")&&(this._cleanup=i)}}catch(i){this._emit([[C,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>Vr?(this._rerunDepth=0,this._emit([[C,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${Vr} \u2014 likely a reactive cycle`)]])):this._maybeRunFnOnSettlement()):this._rerunDepth=0,this._clearWaveFlags()}}_clearWaveFlags(){this._waveHasNewData=!1,this._hasNewTerminal=!1;for(let e of this._deps)e.involvedThisWave=!1,e.dataBatch.length=0}_wrapFnError(e,n){let r=n instanceof Error?n.message:String(n);return new Error(`Node "${this.name}": ${e}: ${r}`,{cause:n})}_frameBatch(e){let n=this._config.tierOf;if(e.length===1)return n(e[0][0])===3&&this._status!=="dirty"?[ze,e[0]]:e;let r=!0,o=!1,s=!1,i=-1;for(let l of e){let c=n(l[0]);c<i&&(r=!1),c===3&&(o=!0),l[0]===J&&(s=!0),i=c}let a=e;if(!r){let l=e.map((c,d)=>({m:c,i:d,tier:n(c[0])}));l.sort((c,d)=>c.tier-d.tier||c.i-d.i),a=l.map(c=>c.m)}if(o&&!s&&this._status!=="dirty"){let l=0;for(;l<a.length&&n(a[l][0])===0;)l++;return l===0?[ze,...a]:[...a.slice(0,l),ze,...a.slice(l)]}return a}_emit(e){if(e.length===0)return;for(let a=0;a<e.length;a++){let l=e[a];if(l[0]===C&&l[1]===void 0)throw new TypeError('[ERROR, payload] requires a non-undefined payload (spec \xA71.2). Pass an Error object or domain tag instead \u2014 e.g. node.down([[ERROR, new Error("reason")]])')}let n=e;if(this._isTerminal&&!this._resubscribable){let a=e.filter(l=>l[0]===ge||l[0]===Se);if(a.length===0)return;n=a}n=this._frameBatch(n);let o=null;for(let a=0;a<n.length;a++){let l=n[a],c=l[0];if(c!==Ne&&c!==Ae){o?.push(l);continue}if(l.length<2)throw new Error(`Node "${this.name}": [[${c===Ne?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let d=!0;if(this._pausable!==!1){let u=l[1];if(c===Ne)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(u),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(u))d=!1;else if(this._pauseLocks.delete(u),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let p=this._pauseBuffer;this._pauseBuffer=[],this._emit(p)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}d?o?.push(l):o==null&&(o=n.slice(0,a))}if(o!=null){if(o.length===0)return;n=o}if(this._hasMeta&&n.some(a=>a[0]===ge))for(let a of Object.keys(this.meta))try{this.meta[a]._emit($t)}catch{}let{finalMessages:s,equalsError:i}=this._updateState(n);if(s.length>0&&this._config.inspectorEnabled){let a=this._config.globalInspector;if(a!=null)try{a({kind:"emit",node:this,messages:s})}catch{}}if(s.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let a=this._config.tierOf,l=[];for(let c of s)a(c[0])===3?this._pauseBuffer.push(c):l.push(c);l.length>0&&this._dispatchOrAccumulate(l)}else this._dispatchOrAccumulate(s);i!=null&&this._emit([[C,i]])}_updateState(e){let n=this._config.tierOf,r,o,s=-1,i=0;for(let d of e)n(d[0])===3&&i++;let a=i<=1,l=-1;if(this._versioning!=null&&i>1){for(let d=e.length-1;d>=0;d--)if(e[d][0]===I){l=d;break}}for(let d=0;d<e.length;d++){let u=e[d],p=u[0];if(p===I){if(u.length>=2){let f=!1;if(a&&this._cached!==void 0)try{f=this._equals(this._cached,u[1])}catch(m){o=this._wrapFnError("equals threw",m),s=d;break}if(f){r==null&&(r=e.slice(0,d)),r.push(Pt),this._status="resolved";continue}this._cached=u[1],this._versioning!=null&&(l<0||d===l)&&$r(this._versioning,u[1],this._hashFn)}this._status="settled",r?.push(u)}else if(r?.push(u),p===J)this._status="dirty";else if(p===H)this._status="resolved";else if(p===$){this._status="completed";{let f=this._config.rigorRecorder;if(f!=null)try{f.onTerminalTransition(this,"completed",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===C){this._status="errored";{let f=this._config.rigorRecorder;if(f!=null)try{f.onTerminalTransition(this,"errored",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===Se){if(this._cached!==void 0){let m=this._config.rigorRecorder;if(m!=null)try{m.onNonVacuousInvalidate(this,this._cached)}catch{}}this._cached=void 0,this._status="dirty";let f=this._cleanup;if(typeof f=="function"){this._cleanup=void 0;try{f()}catch{}}else if(f!=null&&typeof f=="object"){let m=f.invalidate;if(typeof m=="function")try{m()}catch{}}}else p===ge&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let c=s>=0?r??e.slice(0,s):r??e;return o!=null?{finalMessages:c,equalsError:o}:{finalMessages:c}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let n=[...this._sinks];for(let r of n)r(e)};_dispatchOrAccumulate(e){if(Lr()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],yt(()=>this._flushBatchPending()));for(let n of e)this._batchPendingMessages.push(n);return}It(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let n=this._frameBatch(e);It(this._deliverToSinks,n,this._config.tierOf)}},Ur=t=>Array.isArray(t),Fn=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function O(t,e){return ie([],{...e,initial:t})}function se(t,e){return ie((r,o,s)=>t(o,s)??void 0,{describeKind:"producer",...e})}function A(t,e,n){return ie(t,(o,s,i)=>{let a=o.map((l,c)=>l!=null&&l.length>0?l.at(-1):i.prevData[c]);s.emit(e(a,i))},{describeKind:"derived",...n})}function ye(t,e,n){return ie(t,(o,s,i)=>{let a=o.map((l,c)=>l!=null&&l.length>0?l.at(-1):i.prevData[c]);return e(a,s,i)??void 0},{describeKind:"effect",...n})}var q=ke(()=>{"use strict";Me()});var Yr={};_n(Yr,{NS_PER_MS:()=>We,NS_PER_SEC:()=>at,constant:()=>zr,decorrelatedJitter:()=>Jr,exponential:()=>Wr,fibonacci:()=>qr,linear:()=>Hr,resolveBackoffPreset:()=>Vt,withMaxAttempts:()=>Vs});function He(t){return t<0?0:t}function js(t,e){return e==="none"?t:e==="full"?Math.random()*t:t/2+Math.random()*(t/2)}function Bs(t,e){return t+Math.random()*(e-t)}function zr(t){let e=He(t);return()=>e}function Hr(t,e){let n=He(t),r=e===void 0?n:He(e);return o=>n+r*Math.max(0,o)}function Wr(t){let e=He(t?.baseNs??1e8),n=t?.factor!==void 0&&t.factor<1?1:t?.factor??2,r=He(t?.maxDelayNs??30*1e9),o=t?.jitter??"none";return s=>{let i;if(e===0)i=0;else if(n===1)i=e;else{let a=r/e,l=1;for(let c=0;c<Math.max(0,s);c++){if(l>=a){l=a;break}l*=n}i=e*l,i>r&&(i=r)}return js(i,o)}}function qr(t=100*1e6,e=30*1e9){let n=He(t),r=He(e);function o(s){if(s<=0)return 1;let i=1,a=2;for(let l=1;l<s;l++){let c=i+a;i=a,a=c}return a}return s=>{let i=o(s)*n;return i<=r?i:r}}function Jr(t=100*1e6,e=30*1e9){return(n,r,o)=>{let i=Math.min(e,(o??t)*3);return Bs(t,i)}}function Vs(t,e){return(n,r,o)=>n>=e?null:t(n,r,o)}function Vt(t){if(t==="constant")return zr(1*1e9);if(t==="linear")return Hr(1*1e9);if(t==="exponential")return Wr();if(t==="fibonacci")return qr();if(t==="decorrelatedJitter")return Jr();throw new Error(`Unknown backoff preset: "${String(t)}". Use one of: constant, linear, exponential, fibonacci, decorrelatedJitter`)}var We,at,jn=ke(()=>{"use strict";We=1e6,at=1e9});var de,De=ke(()=>{"use strict";de=class{_timer;_gen=0;start(e,n){this.cancel(),this._gen+=1;let r=this._gen;this._timer=setTimeout(()=>{this._timer=void 0,r===this._gen&&n()},e)}cancel(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}get pending(){return this._timer!==void 0}}});var Xr={};_n(Xr,{CircuitOpenError:()=>Fe,RateLimiterOverflowError:()=>Kt,TimeoutError:()=>Ut,circuitBreaker:()=>vt,fallback:()=>Qs,rateLimiter:()=>Hs,retry:()=>Us,retrySource:()=>Bn,timeout:()=>Xs,tokenBucket:()=>wt,withBreaker:()=>zs,withStatus:()=>Ws});function qe(t){return{describeKind:"derived",...t}}function Ks(t){return t<0?0:t}function zt(t){return t[1]}function Qr(t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError("backoff strategy must return a finite number");return t<0?0:t}function Us(t,e){let n=e?.count,r=e?.backoff,o=n!==void 0?n:r===void 0?0:2147483647;if(o<0)throw new RangeError("retry count must be >= 0");let s=r===void 0?null:typeof r=="string"?Vt(r):r;return se(i=>{let a=0,l=!1,c=null,d,u=new de;function p(){d?.(),d=void 0}function f(h){if(l)return;if(a>=o){p(),i.down([[C,h]]);return}let g=s===null?0:s(a,h,c);if(g==null){p(),i.down([[C,h]]);return}let y;try{y=Qr(g)}catch{p(),i.down([[C,h]]);return}c=y,a+=1,p();let b=y>0?y/1e6:1;u.start(b,()=>{l||m()})}function m(){u.cancel(),p(),d=t.subscribe(h=>{if(!l)for(let g of h){let y=g[0];if(y===J)i.down([[J]]);else if(y===I)a=0,c=null,i.emit(g[1]);else if(y===H)i.down([[H]]);else if(y===$)p(),i.down([[$]]);else if(y===C){f(zt(g));return}else i.down([g])}})}return m(),()=>{l=!0,u.cancel(),p()}},{...qe(),initial:t.cache})}function Bn(t,e){let n=e?.count,r=e?.backoff,o=n!==void 0?n:r===void 0?0:2147483647;if(o<0)throw new RangeError("retry count must be >= 0");let s=r===void 0?null:typeof r=="string"?Vt(r):r;return se(i=>{let a=0,l=!1,c=null,d,u=new de;function p(){d?.(),d=void 0}function f(h){if(l)return;if(a>=o){p(),i.down([[C,h]]);return}let g=s===null?0:s(a,h,c);if(g==null){p(),i.down([[C,h]]);return}let y;try{y=Qr(g)}catch{p(),i.down([[C,h]]);return}c=y,a+=1,p();let b=y>0?y/1e6:1;u.start(b,()=>{l||m()})}function m(){u.cancel(),p();let h;try{h=t()}catch(g){f(g);return}d=h.subscribe(g=>{if(!l)for(let y of g){let b=y[0];if(b===J)i.down([[J]]);else if(b===I)a=0,c=null,i.emit(y[1]);else if(b===H)i.down([[H]]);else if(b===$)p(),i.down([[$]]);else if(b===C){f(zt(y));return}else i.down([y])}})}return m(),()=>{l=!0,u.cancel(),p()}},{...qe(),initial:e?.initial})}function vt(t){let e=Math.max(1,t?.failureThreshold??5),n=Ks(t?.cooldownNs??30*1e9),r=t?.cooldown??null,o=Math.max(1,t?.halfOpenMax??1),s=t?.now??V,i="closed",a=0,l=0,c=0,d=n,u=0;function p(){if(!r)return n;let h=r(l);return h!==null?h:n}function f(){i="open",d=p(),c=s(),u=0}return{canExecute(){return i==="closed"?!0:i==="open"?s()-c>=d?(i="half-open",u=1,!0):!1:u<o?(u++,!0):!1},recordSuccess(){i==="half-open"?(i="closed",a=0,l=0):i==="closed"&&(a=0)},recordFailure(h){if(i==="half-open"){l++,f();return}i==="closed"&&(a++,a>=e&&f())},get state(){return i},get failureCount(){return a},reset(){i="closed",a=0,l=0,u=0}}}function zs(t,e){let n=e?.onOpen??"skip";return r=>{let o=ie([],(s,i)=>{function a(){o.meta.breakerState.down([[I,t.state]])}let l=r.subscribe(c=>{for(let d of c){let u=d[0];u===J?i.down([[J]]):u===I?t.canExecute()?(a(),i.emit(d[1])):(a(),n==="error"?i.down([[C,new Fe]]):i.down([[H]])):u===H?i.down([[H]]):u===$?(t.recordSuccess(),a(),i.down([[$]])):u===C?(t.recordFailure(zt(d)),a(),i.down([d])):i.down([d])}});return a(),l},{...qe(),meta:{breakerState:t.state},completeWhenDepsComplete:!1,initial:r.cache});return{node:o,breakerState:o.meta.breakerState}}}function wt(t,e){if(t<=0)throw new RangeError("capacity must be > 0");if(e<0)throw new RangeError("refillPerSecond must be >= 0");let n=t,r=V();function o(s){if(e>0){let i=s-r;n=Math.min(t,n+i/1e9*e)}r=s}return{available(){return o(V()),n},tryConsume(s=1){if(s<=0)return!0;let i=V();return o(i),n>=s?(n-=s,!0):!1},putBack(s=1){s<=0||(o(V()),n=Math.min(t,n+s))}}}function Hs(t,e){let{maxEvents:n,windowNs:r}=e;if(n<=0)throw new RangeError("maxEvents must be > 0");if(r<=0)throw new RangeError("windowNs must be > 0");let o=e.maxBuffer;if(o!==void 0&&o<1)throw new RangeError("maxBuffer must be >= 1");let s=e.onOverflow??"drop-newest",i=n*1e9/r;return se(a=>{let l=wt(n,i),c=[],d=new de,u=!1,p=1e9/i;function f(){for(;c.length>0;)if(l.tryConsume(1))a.emit(c.shift());else{d.start(Math.max(1,p/1e6),f);return}}let m=t.subscribe(h=>{for(let g of h){if(u)return;let y=g[0];if(y===J)a.down([[J]]);else if(y===I){if(o!==void 0&&c.length>=o){if(s!=="drop-newest")if(s==="drop-oldest")c.shift(),c.push(g[1]);else{u=!0,d.cancel(),c.length=0,a.down([[C,new Kt(o)]]);return}}else c.push(g[1]);f()}else if(y===H)a.down([[H]]);else if(y===$)u=!0,d.cancel(),c.length=0,a.down([[$]]);else if(y===C)u=!0,d.cancel(),c.length=0,a.down([g]);else if(y===ge){u=!0,d.cancel(),c.length=0,a.down([g]);return}else a.down([g])}});return()=>{u=!0,d.cancel(),m()}},{...qe(),initial:t.cache})}function Ws(t,e){let n=e?.initialStatus??"pending",r=ie([],(o,s)=>{let i=n;return r.meta.status.down([[I,n]]),r.meta.error.down([[I,null]]),t.subscribe(l=>{for(let c of l){let d=c[0];if(d===J)s.down([[J]]);else if(d===I)i==="errored"?re(()=>{r.meta.error.down([[I,null]]),r.meta.status.down([[I,"active"]])}):r.meta.status.down([[I,"active"]]),i="active",s.emit(c[1]);else if(d===H)s.down([[H]]);else if(d===$)r.meta.status.down([[I,"completed"]]),i="completed",s.down([[$]]);else if(d===C){let u=zt(c);re(()=>{r.meta.error.down([[I,u]]),r.meta.status.down([[I,"errored"]])}),i="errored",s.down([c])}else s.down([c])}})},{...qe(),meta:{status:n,error:null},completeWhenDepsComplete:!1,resubscribable:!0,initial:t.cache});return{node:r,status:r.meta.status,error:r.meta.error}}function qs(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function Js(t){return t!=null&&typeof t.then=="function"}function Ys(t){return t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function"}function Qs(t,e){return se(n=>{let r,o;function s(){o?.(),o=void 0,qs(e)||Js(e)||Ys(e)?r=P(e).subscribe(a=>{n.down(a)}):(n.emit(e),n.down([[$]]))}return o=t.subscribe(i=>{for(let a of i){let l=a[0];if(l===J)n.down([[J]]);else if(l===I)n.emit(a[1]);else if(l===H)n.down([[H]]);else if(l===$)n.down([[$]]);else if(l===C){s();return}else if(l===ge){r?.(),n.down([a]);return}else n.down([a])}}),()=>{o?.(),r?.()}},{...qe(),initial:t.cache})}function Xs(t,e){if(e<=0)throw new RangeError("timeoutNs must be > 0");return se(n=>{let r=!1,o=new de;function s(){let a=e/1e6;o.start(a,()=>{r||(r=!0,i(),n.down([[C,new Ut(e)]]))})}let i=t.subscribe(a=>{for(let l of a){if(r)return;let c=l[0];if(c===J)n.down([[J]]);else if(c===I)s(),n.emit(l[1]);else if(c===H)n.down([[H]]);else if(c===$){o.cancel(),r=!0,n.down([[$]]);return}else if(c===C){o.cancel(),r=!0,n.down([l]);return}else if(c===ge){o.cancel(),r=!0,n.down([l]);return}else n.down([l])}});return s(),()=>{r=!0,o.cancel(),i()}},{...qe(),initial:t.cache})}var Fe,Kt,Ut,ct=ke(()=>{"use strict";Re();he();le();Me();q();jn();ne();De();Fe=class extends Error{name="CircuitOpenError";constructor(){super("Circuit breaker is open")}};Kt=class extends Error{name="RateLimiterOverflowError";constructor(e){super(`rateLimiter buffer overflow (maxBuffer=${e})`)}};Ut=class extends Error{name="TimeoutError";constructor(e){super(`Timed out after ${e/1e6}ms`)}}});function Ht(t){return{describeKind:"producer",...t}}function to(t,e){let{signal:n,period:r,...o}=e??{};return se(s=>{let i=!1,a=0,l,c,d=()=>{i=!0,l!==void 0&&clearTimeout(l),c!==void 0&&clearInterval(c),n?.removeEventListener("abort",p)},u=()=>{i||(r!=null?(s.emit(a++),c=setInterval(()=>{i||s.emit(a++)},r)):(i=!0,n?.removeEventListener("abort",p),s.emit(a++),s.down([[$]])))},p=()=>{i||(d(),s.down([[C,n.reason]]))};if(n?.aborted){p();return}return l=setTimeout(u,t),n?.addEventListener("abort",p,{once:!0}),d},Ht(o))}function no(t,e){return se(n=>{let r=!1;try{for(let o of t){if(r)return;n.emit(o)}r||n.down([[$]])}catch(o){r||n.down([[C,o]])}return()=>{r=!0}},Ht(e))}function Zs(t){return t!=null&&typeof t.then=="function"}function Wt(t,e){let{signal:n,...r}=e??{};return se(o=>{let s=!1,i=()=>{s||(s=!0,o.down([[C,n.reason]]))};if(n?.aborted){i();return}return n?.addEventListener("abort",i,{once:!0}),Promise.resolve(t).then(a=>{s||(s=!0,n?.removeEventListener("abort",i),o.emit(a),o.down([[$]]))},a=>{s||(s=!0,n?.removeEventListener("abort",i),o.down([[C,a]]))}),()=>{s=!0,n?.removeEventListener("abort",i)}},Ht(r))}function Kn(t,e){let{signal:n,...r}=e??{};return se(o=>{let s=new AbortController,i=()=>s.abort(n?.reason);n?.aborted?s.abort(n.reason):n?.addEventListener("abort",i,{once:!0});let a=n??s.signal,l=!1,c=t[Symbol.asyncIterator](),d=()=>{l||a.aborted||Promise.resolve(c.next()).then(u=>{if(!(l||a.aborted)){if(u.done){o.down([[$]]);return}o.emit(u.value),d()}},u=>{!l&&!a.aborted&&o.down([[C,u]])})};return d(),()=>{l=!0,n?.removeEventListener("abort",i),s.abort(),Promise.resolve(c.return?.()).catch(()=>{})}},Ht(r))}function ei(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function P(t,e){if(ei(t))return t;if(Zs(t))return Wt(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return Kn(t,e);if(typeof n[Symbol.iterator]=="function")return no(t,e)}return ti(t)}function ti(...t){return no(t,void 0)}function kt(t,e,n){return ie([t],(o,s)=>{let i=o[0];if(i!=null&&i.length>0)for(let a of i)e(a)},{describeKind:"effect",...n}).subscribe(()=>{})}function xe(t){return new Promise((e,n)=>{let r=!1,o=!1,s;s=t.subscribe(i=>{for(let a of i){if(r)return;if(a[0]===I){r=!0,e(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===C){r=!0,n(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===$){r=!0,n(new Error("completed without DATA")),s?(s(),s=void 0):o=!0;return}}}),o&&(s?.(),s=void 0)})}function Zr(t,e,n){return new Promise((r,o)=>{let s=!1,i=!1,a,l=n?.skipCurrent===!0;a=t.subscribe(c=>{for(let d of c){if(s)return;if(!(l&&d[0]===I)){if(d[0]===I){let u=d[1];if(e(u)){s=!0,r(u),a?(a(),a=void 0):i=!0;return}}if(d[0]===C){s=!0,o(d[1]),a?(a(),a=void 0):i=!0;return}if(d[0]===$){s=!0,o(new Error("completed without matching value")),a?(a(),a=void 0):i=!0;return}}}}),l=!1,i&&(a?.(),a=void 0)})}async function ro(t,e){let n=e?.predicate??(s=>s!=null),r=e?.skipCurrent;if(e?.timeoutMs==null||e.timeoutMs<=0)return await Zr(t,n,{skipCurrent:r});if(Vn===void 0){let[s,i]=await Promise.all([Promise.resolve().then(()=>(ct(),Xr)),Promise.resolve().then(()=>(jn(),Yr))]);Vn=s.timeout,eo=i.NS_PER_MS}let o=Vn(t,e.timeoutMs*eo);return await Zr(o,n,{skipCurrent:r})}function oo(t,e){let n=new AbortController,r=e?.reason??new Error("cancelled via nodeSignal"),o,s=!1,i=()=>{o?(o(),o=void 0):s=!0};return o=t.subscribe(a=>{if(!n.signal.aborted)for(let l of a){if(l[0]===I&&l[1]===!0){n.abort(r),i();return}if(l[0]===C){n.abort(l[1]),i();return}if(l[0]===$){i();return}}}),s&&(o?.(),o=void 0),{signal:n.signal,dispose:()=>{o&&(o(),o=void 0)}}}function Z(t){return t.subscribe(()=>{})}var Vn,eo,ne=ke(()=>{"use strict";le();Me();q()});var Ic={};_n(Ic,{AgentLoopGraph:()=>vn,AllTiersExhaustedError:()=>St,BudgetExhaustedError:()=>on,ChatStreamGraph:()=>bn,CircuitOpenError:()=>Fe,DEFAULT_DECAY_RATE:()=>Et,FallbackMissError:()=>di,LLMTimeoutError:()=>ut,ReplayCacheMissError:()=>Qe,ToolRegistryGraph:()=>Tn,admissionFilter3D:()=>uc,admissionScored:()=>ds,agentLoop:()=>cc,agentMemory:()=>gc,anthropicAdapter:()=>Un,canonicalJson:()=>Jn,cascadingLlmAdapter:()=>lr,chatStream:()=>wr,composePricing:()=>Oi,computePrice:()=>nr,contentGate:()=>oc,costMeterExtractor:()=>Xa,createAdapter:()=>Ri,createCapabilitiesRegistry:()=>$s,createPricingRegistry:()=>Mi,dryRunAdapter:()=>Je,fallbackAdapter:()=>Yn,fromLLM:()=>Ui,frozenContext:()=>qi,gatedStream:()=>Ja,gaugesAsContext:()=>wc,googleAdapter:()=>Qn,graphFromSpec:()=>ws,graphFromSpecReactive:()=>Ec,handoff:()=>lc,keywordFlagExtractor:()=>ec,knobsAsTools:()=>Ac,llmConsolidator:()=>Sr,llmExtractor:()=>Rr,memoryRetrieval:()=>vc,memoryWithKG:()=>yc,memoryWithTiers:()=>bc,memoryWithVectors:()=>hc,observableAdapter:()=>Ni,openAICompatAdapter:()=>Zn,parseRateLimitFromError:()=>ir,pricingFor:()=>Ai,promptNode:()=>fr,redactor:()=>sc,registryPricing:()=>Ei,resilientAdapter:()=>Ki,streamExtractor:()=>tc,streamingPromptNode:()=>qa,suggestStrategy:()=>ks,suggestStrategyReactive:()=>Lc,systemPromptBuilder:()=>Ya,tier:()=>Bi,toolCallExtractor:()=>rc,toolExecution:()=>kr,toolRegistry:()=>xr,toolSelector:()=>dc,validateGraphDef:()=>Dc,withBreaker:()=>rr,withBudgetGate:()=>sr,withDryRun:()=>Li,withRateLimiter:()=>cr,withReplayCache:()=>Rt,withRetry:()=>dr,withTimeout:()=>ur,zeroPrice:()=>rn});module.exports=Es(Ic);q();Re();he();le();q();var $n=class{_version=0;_store=new Map;_maxSize;_defaultTtl;constructor(e={}){let{maxSize:n,defaultTtl:r}=e;if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(r!==void 0&&r<=0)throw new RangeError("defaultTtl must be positive");this._maxSize=n,this._defaultTtl=r}get version(){return this._version}get size(){return this._store.size}has(e){let n=this._store.get(e);return n===void 0?!1:this._isExpired(n)?(this._store.delete(e),this._version+=1,!1):(this._touchLru(e,n),!0)}get(e){let n=this._store.get(e);if(n!==void 0){if(this._isExpired(n)){this._store.delete(e),this._version+=1;return}return this._touchLru(e,n),n.value}}set(e,n,r){let o=this._resolveExpiresAt(r);this._store.has(e)&&this._store.delete(e),this._store.set(e,{value:n,expiresAt:o}),this._evictLruWhileOver(),this._version+=1}setMany(e,n){let r=this._resolveExpiresAt(n),o=0;try{for(let[s,i]of e)this._store.has(s)&&this._store.delete(s),this._store.set(s,{value:i,expiresAt:r}),o+=1}finally{o>0&&(this._evictLruWhileOver(),this._version+=1)}}delete(e){let n=this._store.delete(e);return n&&(this._version+=1),n}deleteMany(e){let n=0;try{for(let r of e)this._store.delete(r)&&(n+=1)}finally{n>0&&(this._version+=1)}return n}clear(){let e=this._store.size;return e===0?0:(this._store.clear(),this._version+=1,e)}pruneExpired(){let e=V(),n=0;for(let[r,o]of this._store)this._isExpired(o,e)&&(this._store.delete(r),n+=1);return n>0&&(this._version+=1),n}toMap(){let e=V(),n=new Map;for(let[r,o]of this._store)this._isExpired(o,e)||n.set(r,o.value);return n}_resolveExpiresAt(e){let n=e??this._defaultTtl;if(n!==void 0){if(!Number.isFinite(n)||n<=0)throw new RangeError(`MapBackend: ttl must be a positive finite number (got ${n})`);return V()+n*1e9}}_isExpired(e,n){return e.expiresAt===void 0?!1:(n??V())>=e.expiresAt}_touchLru(e,n){this._store.delete(e),this._store.set(e,n)}_evictLruWhileOver(){if(this._maxSize!==void 0)for(;this._store.size>this._maxSize;){let e=this._store.keys().next().value;if(e===void 0)break;this._store.delete(e)}}};function it(t={}){let{name:e,maxSize:n,defaultTtl:r,versioning:o,backend:s,retention:i}=t;if(i&&n!==void 0)throw new RangeError("reactiveMap: `maxSize` (LRU) and `retention` (score-based) are mutually exclusive. Pick one eviction policy.");if(i&&i.archiveThreshold===void 0&&i.maxSize===void 0)throw new RangeError("reactiveMap: `retention` requires at least one of `archiveThreshold` or `maxSize` to trigger archival.");let a=s??new $n({maxSize:n,defaultTtl:r}),l=O(a.toMap(),{name:e,describeKind:"state",equals:(p,f)=>p===f,...o!=null?{versioning:o}:{}});function c(){let p=a.toMap();re(()=>{l.down([[J]]),l.down([[I,p]])})}function d(){if(!i)return;let p=a.toMap(),f=i.archiveThreshold,m=i.maxSize,h=[];for(let[y,b]of p)h.push({key:y,value:b,score:i.score(y,b)});h.sort((y,b)=>y.score-b.score);let g=new Set;if(f!==void 0)for(let y of h)if(y.score<f)g.add(y.key);else break;if(m!==void 0&&h.length-g.size>m)for(let y of h){if(h.length-g.size<=m)break;g.has(y.key)||g.add(y.key)}if(g.size!==0)for(let y of h)g.has(y.key)&&(i.onArchive?.(y.key,y.value,y.score),a.delete(y.key))}function u(p,f="mutation"){let m=a.version;try{return p()}finally{a.version!==m&&(f==="mutation"&&d(),c())}}return{entries:l,has(p){return u(()=>a.has(p),"read")},get(p){return u(()=>a.get(p),"read")},set(p,f,m){u(()=>a.set(p,f,m?.ttl))},setMany(p,f){u(()=>a.setMany(p,f?.ttl))},delete(p){u(()=>a.delete(p))},deleteMany(p){u(()=>a.deleteMany(p))},clear(){u(()=>a.clear())},pruneExpired(){u(()=>a.pruneExpired())},get size(){return a.size},dispose(){}}}function Tt(t,e){return`${t}::${e}`}function $s(t){let e=it({name:"capabilitiesRegistry"}),n=c=>{e.set(Tt(c.provider,c.id),c)};if(t)for(let c of t)n(c);let r=(c,d)=>{let u=e.get(Tt(c,d));if(u)return u;let p=e.entries.cache;if(!p)return;let f;for(let[,m]of p){if(m.provider!==c)continue;let h=m.id;d.startsWith(h)&&(!f||h.length>f.id.length)&&(f=m)}return f},o=128,s=new Map,i=new Map,a=(c,d,u,p)=>{for(c.has(d)&&c.delete(d),c.set(d,u);c.size>p;){let f=c.keys().next().value;if(f===void 0)break;c.delete(f)}},l=A([e.entries],([c])=>Array.from(c.values()),{name:"capabilitiesRegistry/entries",initial:[]});return{register:n,lookup:r,remove(c,d){let u=e.has(Tt(c,d));return u&&e.delete(Tt(c,d)),u},entries(){let c=e.entries.cache;return(function*(){if(c)for(let d of c.values())yield d})()},lookupNode(c,d){let u=Tt(c,d),p=s.get(u);if(p)return s.delete(u),s.set(u,p),p;let f=A([e.entries],()=>r(c,d),{name:`capabilitiesRegistry/lookup/${c}::${d}`,initial:void 0});return a(s,u,f,o),f},entriesNode:l,byProvider(c){let d=i.get(c);if(d)return i.delete(c),i.set(c,d),d;let u=A([l],([p])=>p.filter(f=>f.provider===c),{name:`capabilitiesRegistry/byProvider/${c}`,initial:[]});return a(i,c,u,o),u}}}he();le();Me();q();ne();function qt(t){return{describeKind:"derived",...t}}function ni(t){return{describeKind:"derived",partial:!0,...t}}function so(t,e,n){return ie([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[H]]);return}let i=!1;for(let a of s)e(a)&&(o.emit(a),i=!0);i||o.down([[H]])},qt(n))}function io(t,e,n){let r=n?.where??(s=>s!=null),o=!1;return ie([t],(s,i)=>{let a=s[0];if(a==null||a.length===0){i.down([[H]]);return}for(let l of a)!o&&r(l)&&(o=!0,e(l)),i.emit(l)},qt(n))}function ao(t,e,n){return ie([t,e],(r,o,s)=>{let i=r[0],a=r[1],l=a!=null&&a.length>0?a.at(-1):s.prevData[1];if(i!=null&&i.length>0){if(!(a!=null&&a.length>0)&&s.prevData[1]===void 0){o.down([[H]]);return}for(let c of i)o.emit([c,l])}else o.down([[H]])},ni(n))}function ri(t,e,n){let r,o=!1,s=()=>{o||(o=!0,n())};return r=t.subscribe(i=>{let a=!1,l=!1;for(let c of i)c[0]!==Ge&&(c[0]===I?e.emit(c[1]):c[0]===$?a=!0:c[0]===C?(l=!0,e.down([c])):(c[0]===J||c[0]===H)&&e.down([c]));l?(r?.(),r=void 0,s()):a&&s()}),()=>{r?.(),r=void 0}}function ue(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return ie([t],(i,a,l)=>{if(l.terminalDeps[0]!=null&&l.terminalDeps[0]!==!0){s();return}if(l.terminalDeps[0]===!0){o=!0,r||a.down([[$]]);return}let c=i[0];if(!(c==null||c.length===0))return s(),r=ri(P(e(c[c.length-1])),a,()=>{s(),o&&a.down([[$]])}),{deactivate:()=>{s(),o=!1}}},{...qt(n),completeWhenDepsComplete:!1})}function co(t,e,n){return se(r=>{let o=t.subscribe(s=>{for(let i of s)if(i[0]===I)r.emit(i[1]);else if(i[0]===C)try{r.emit(e(i[1]))}catch(a){r.down([[C,a]])}else i[0]===$&&r.down([[$]])});return()=>{o()}},qt(n))}var xt=class{constructor(e){this.capacity=e;if(!Number.isInteger(e)||e<=0)throw new Error(`RingBuffer capacity must be a positive integer (got ${e})`);this.buf=new Array(e)}buf;head=0;_size=0;get size(){return this._size}get maxSize(){return this.capacity}push(e){let n=(this.head+this._size)%this.capacity;this.buf[n]=e,this._size<this.capacity?this._size++:this.head=(this.head+1)%this.capacity}shift(){if(this._size===0)return;let e=this.buf[this.head];return this.buf[this.head]=void 0,this.head=(this.head+1)%this.capacity,this._size--,e}at(e){if(this._size===0)return;let n=e<0?this._size+e:e;if(!(n<0||n>=this._size))return this.buf[(this.head+n)%this.capacity]}toArray(){let e=new Array(this._size);for(let n=0;n<this._size;n++)e[n]=this.buf[(this.head+n)%this.capacity];return e}clear(){for(let e=0;e<this._size;e++)this.buf[(this.head+e)%this.capacity]=void 0;this.head=0,this._size=0}};async function*lt(t,e){let n=e?.parse??(w=>w),r=e?.signal,o=new TextDecoder,s="",i="message",a=[],l,c,d=[],u=()=>{if(a.length===0&&i==="message"&&l===void 0){a=[];return}let w=a.join(`
|
|
2
|
-
`);
|
|
1
|
+
"use strict";var gn=Object.defineProperty;var ks=Object.getOwnPropertyDescriptor;var xs=Object.getOwnPropertyNames;var Rs=Object.prototype.hasOwnProperty;var be=(t,e)=>()=>(t&&(e=t(t=0)),e);var hn=(t,e)=>{for(var n in e)gn(t,n,{get:e[n],enumerable:!0})},Ss=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of xs(e))!Rs.call(t,o)&&o!==n&&gn(t,o,{get:()=>e[o],enumerable:!(r=ks(e,o))||r.enumerable});return t};var Ns=t=>Ss(gn({},"__esModule",{value:!0}),t);function kr(t,e){let n=new TextEncoder().encode(t.name);if(n.length===0||n.length>255)throw new Error(`encodeEnvelope: codec name "${t.name}" encodes to ${n.length} bytes (must be 1\u2013255)`);let r=t.version;if(!Number.isInteger(r)||r<0||r>65535)throw new Error(`encodeEnvelope: codec.version ${r} out of u16 range (expected integer 0\u201365535)`);let o=2+n.length+2+e.length;if(o>4294967295)throw new Error(`encodeEnvelope: total envelope size ${o} exceeds 2^32-1 bytes (payload ${e.length} bytes)`);let s=new Uint8Array(o),i=0;return s[i++]=yn,s[i++]=n.length,s.set(n,i),i+=n.length,s[i++]=r>>>8&255,s[i++]=r&255,s.set(e,i),s}function xr(t,e){if(t.length<wr)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${wr})`);let n=0,r=t[n++];if(r!==yn)throw new Error(`decodeEnvelope: unsupported envelope version ${r} (expected ${yn})`);let o=t[n++];if(o===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(n+o+2>t.length)throw new Error(`decodeEnvelope: envelope truncated (need ${n+o+2} bytes, have ${t.length})`);let s=new TextDecoder().decode(t.subarray(n,n+o));n+=o;let i=(t[n]<<8|t[n+1])>>>0;n+=2;let a=t.subarray(n),d=e.lookupCodec(s);if(d==null)throw new Error(`decodeEnvelope: codec "${s}" not registered (envelope codec_v=${i})`);return{codec:d,codecVersion:i,payload:a}}function Rr(t){t.registerCodec(_s)}var _s,yn,wr,bn=be(()=>{"use strict";_s={name:"json",version:1,contentType:"application/json",encode(t){let e=JSON.stringify(t);return new TextEncoder().encode(e)},decode(t,e){let n=new TextDecoder().decode(t);return JSON.parse(n)}},yn=1,wr=4});function Rt(t){if(t==null)return Xe;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var Xe,St=be(()=>{"use strict";Xe={type:"system",id:""}});function Nt(){return Ze>0||lt}function Sr(){return Ze>0}function pt(t){Ze>0?ct.push(t):t()}function X(t){Ze+=1;let e=!1;try{t()}catch(n){throw e=!0,n}finally{if(Ze-=1,Ze===0)if(e){if(!lt){let n=ct.splice(0);for(let r of n)try{r()}catch{}je.length=0,Be.length=0,et.length=0}}else Ms()}}function Ms(){let t=!lt;t&&(lt=!0);let e=[],n=0;try{for(;je.length>0||Be.length>0||et.length>0||t&&ct.length>0;){if(t&&ct.length>0){let s=ct.splice(0);for(let i of s)try{i()}catch(a){e.push(a)}continue}if(n+=1,n>1e3)throw je.length=0,Be.length=0,et.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let o=(je.length>0?je:Be.length>0?Be:et).splice(0);for(let s of o)try{s()}catch(i){e.push(i)}}}finally{t&&(lt=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function _t(t,e,n){if(e.length===0)return;if(e.length===1){let u=n(e[0][0]);if(u<3||!Nt()){t(e);return}(u>=5?et:u===4?Be:je).push(()=>t(e));return}let r=e.length,o=r,s=r,i=r,a=0;for(;a<r&&n(e[a][0])<3;)a++;for(o=a;a<r&&n(e[a][0])===3;)a++;for(s=a;a<r&&n(e[a][0])===4;)a++;i=a;let d=Nt();if(o>0){let u=e.slice(0,o);t(u)}if(s>o){let u=e.slice(o,s);d?je.push(()=>t(u)):t(u)}if(i>s){let u=e.slice(s,i);d?Be.push(()=>t(u)):t(u)}if(r>i){let u=e.slice(i,r);d?et.push(()=>t(u)):t(u)}}var Ze,lt,je,Be,et,ct,ke=be(()=>{"use strict";Ze=0,lt=!1,je=[],Be=[],et=[],ct=[]});function F(){return Math.trunc(performance.now()*1e6)}function pe(){return Date.now()*1e6}var ce=be(()=>{"use strict"});var Ie,C,z,B,xe,Re,Oe,ue,G,O,Ve,Mt,Nr,Et,_r,Mr,Ot,Tn,vn,wn,At,ne=be(()=>{"use strict";Ie=Symbol.for("graphrefly/START"),C=Symbol.for("graphrefly/DATA"),z=Symbol.for("graphrefly/DIRTY"),B=Symbol.for("graphrefly/RESOLVED"),xe=Symbol.for("graphrefly/INVALIDATE"),Re=Symbol.for("graphrefly/PAUSE"),Oe=Symbol.for("graphrefly/RESUME"),ue=Symbol.for("graphrefly/TEARDOWN"),G=Symbol.for("graphrefly/COMPLETE"),O=Symbol.for("graphrefly/ERROR"),Ve=Object.freeze([z]),Mt=Object.freeze([B]),Nr=Object.freeze([xe]),Et=Object.freeze([Ie]),_r=Object.freeze([G]),Mr=Object.freeze([ue]),Ot=Object.freeze([Ve]),Tn=Object.freeze([Mt]),vn=Object.freeze([Nr]),wn=Object.freeze([_r]),At=Object.freeze([Mr])});function Er(t){t.registerMessageType(Ie,{tier:0,wireCrossing:!1}),t.registerMessageType(z,{tier:1,wireCrossing:!1}),t.registerMessageType(xe,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(Re,{tier:2,wireCrossing:!1}),t.registerMessageType(Oe,{tier:2,wireCrossing:!1}),t.registerMessageType(C,{tier:3,wireCrossing:!0}),t.registerMessageType(B,{tier:3,wireCrossing:!0}),t.registerMessageType(G,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(O,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(ue,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var Ct,Or=be(()=>{"use strict";ne();Ct=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_rigorRecorder;_frozen=!1;tierOf;constructor(e){this._onMessage=e.onMessage,this._onSubscribe=e.onSubscribe,this._defaultVersioning=e.defaultVersioning,this._defaultHashFn=e.defaultHashFn,this.tierOf=n=>{let r=this._messageTypes.get(n);return r!=null?r.tier:1}}get onMessage(){return this._frozen=!0,this._onMessage}get onSubscribe(){return this._frozen=!0,this._onSubscribe}set onMessage(e){this._assertUnfrozen(),this._onMessage=e}set onSubscribe(e){this._assertUnfrozen(),this._onSubscribe=e}get defaultVersioning(){return this._defaultVersioning}set defaultVersioning(e){this._assertUnfrozen(),this._defaultVersioning=e}get defaultHashFn(){return this._defaultHashFn}set defaultHashFn(e){this._assertUnfrozen(),this._defaultHashFn=e}get inspectorEnabled(){return this._inspectorEnabled}set inspectorEnabled(e){this._inspectorEnabled=e}get globalInspector(){return this._globalInspector}set globalInspector(e){this._globalInspector=e}get rigorRecorder(){return this._rigorRecorder}set rigorRecorder(e){this._rigorRecorder=e}registerMessageType(e,n){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:n.tier,wireCrossing:n.wireCrossing??n.tier>=3,metaPassthrough:n.metaPassthrough??!0}),this}messageTier(e){let n=this._messageTypes.get(e);return n!=null?n.tier:1}isWireCrossing(e){let n=this._messageTypes.get(e);return n!=null?n.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let n=this._messageTypes.get(e);return n!=null?n.metaPassthrough:!0}isKnownMessageType(e){return this._messageTypes.has(e)}registerCodec(e){return this._assertUnfrozen(),this._codecs.set(e.name,e),this}lookupCodec(e){return this._codecs.get(e)}_isFrozen(){return this._frozen}_assertUnfrozen(){if(this._frozen)throw new Error("GraphReFlyConfig is frozen: a node has already captured this config. Register custom types and set hooks before creating any node.")}}});function kn(t){let e=Es.filter(n=>t({type:n,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(n=>n==="human"||n==="llm"||n==="system")?"both":e.length===1?e[0]:e.join("+")}var Se,Es,ft=be(()=>{"use strict";Se=class extends Error{actor;action;nodeName;constructor(e,n){super(n??`GuardDenied: action "${String(e.action)}" denied for actor type "${String(e.actor.type)}"`),this.name="GuardDenied",this.actor=e.actor,this.action=e.action,this.nodeName=e.nodeName}get node(){return this.nodeName}},Es=["human","llm","wallet","system"]});function xn(t){if(t===void 0)return null;if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`Cannot hash non-finite number: ${t}`);if(Number.isInteger(t)&&!Number.isSafeInteger(t))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${t}. Cross-language cid parity is not guaranteed for unsafe integers.`);return t}if(typeof t=="string"||typeof t=="boolean"||t===null)return t;if(Array.isArray(t))return t.map(xn);if(typeof t=="object"&&t!==null){let e={};for(let n of Object.keys(t).sort())e[n]=xn(t[n]);return e}return null}function Cs(t){let e=As.encode(t),n=e.length,r=n*8,o=n+9+63&-64,s=new Uint8Array(o);s.set(e),s[n]=128;let i=new DataView(s.buffer);i.setUint32(o-4,r>>>0,!1),i.setUint32(o-8,Math.floor(r/4294967296)>>>0,!1);let a=1779033703,d=3144134277,u=1013904242,l=2773480762,c=1359893119,p=2600822924,f=528734635,m=1541459225,h=new Uint32Array(64),g=(b,v)=>b>>>v|b<<32-v;for(let b=0;b<o;b+=64){for(let R=0;R<16;R++)h[R]=i.getUint32(b+R*4,!1);for(let R=16;R<64;R++){let I=h[R-15],M=h[R-2],L=g(I,7)^g(I,18)^I>>>3,j=g(M,17)^g(M,19)^M>>>10;h[R]=h[R-16]+L+h[R-7]+j>>>0}let v=a,k=d,w=u,T=l,x=c,S=p,N=f,_=m;for(let R=0;R<64;R++){let I=g(x,6)^g(x,11)^g(x,25),M=x&S^~x&N,L=_+I+M+Os[R]+h[R]>>>0,j=g(v,2)^g(v,13)^g(v,22),K=v&k^v&w^k&w,Q=j+K>>>0;_=N,N=S,S=x,x=T+L>>>0,T=w,w=k,k=v,v=L+Q>>>0}a=a+v>>>0,d=d+k>>>0,u=u+w>>>0,l=l+T>>>0,c=c+x>>>0,p=p+S>>>0,f=f+N>>>0,m=m+_>>>0}let y=b=>b.toString(16).padStart(8,"0");return y(a)+y(d)+y(u)+y(l)+y(c)+y(p)+y(f)+y(m)}function Rn(t){let e=xn(t??null),n=JSON.stringify(e);return Cs(n).slice(0,16)}function Ls(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),n=e()+e()+e()+e();return`${n.slice(0,8)}-${n.slice(8,12)}-4${n.slice(13,16)}-${(parseInt(n.slice(16,17),16)&3|8).toString(16)}${n.slice(17,20)}-${n.slice(20,32)}`}function Sn(t,e,n){let r=n?.id??Ls();if(t===0)return{id:r,version:0};let s=(n?.hash??Rn)(e);return{id:r,version:0,cid:s,prev:null}}function Ar(t,e,n){t.version+=1,"cid"in t&&(t.prev=t.cid,t.cid=n(e))}var Os,As,Cr=be(()=>{"use strict";Os=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),As=new TextEncoder});function Ir(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function Nn(t){t.prevData=void 0,t.dirty=!1,t.involvedThisWave=!1,t.dataBatch.length=0,t.terminal=void 0}function Lt(t){return t.length===0?t:typeof t[0]=="symbol"?[t]:t}function ee(t,e,n){let r=Pr(t)?t:[],o=typeof t=="function"?t:typeof e=="function"?e:void 0,s={};return Pr(t)?s=(_n(e)?e:n)??{}:_n(t)?s=t:s=(_n(e)?e:n)??{},new ie(r,o,s)}var Lr,Dr,Ds,Is,tt,ie,Pr,_n,Ne=be(()=>{"use strict";bn();St();ke();ce();Or();ft();ne();Cr();Lr=()=>{},Dr=100;Ds=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},Is=(t,e,n,r)=>{let o=t;if(o._status==="completed"||o._status==="errored")return;let s=o._cached,i=s===void 0?[Et]:[Et,[C,s]];o._status==="dirty"&&i.push(Ve),_t(e,i,o._config.tierOf)},tt=new Ct({onMessage:Ds,onSubscribe:Is});Er(tt);Rr(tt);ie=class t{_optsName;_describeKind;meta;_hasMeta;_config;_deps;_sinks=null;_sinkCount=0;_cached;_status;_cleanup;_store={};_waveHasNewData=!1;_hasNewTerminal=!1;_hasCalledFnOnce=!1;_paused=!1;_pendingWave=!1;_isExecutingFn=!1;_pendingRerun=!1;_rerunDepth=0;_dirtyDepCount=0;_batchPendingMessages=null;_pauseLocks=null;_pauseBuffer=null;_fn;_equals;_resubscribable;_resetOnTeardown;_autoComplete;_autoError;_pausable;_partial;_guard;_extraGuards;_hashFn;_versioning;_versioningLevel;_lastMutation;_inspectorHooks;_actions;constructor(e,n,r){this._config=r.config??tt,this._config.onMessage,this._optsName=r.name,this._describeKind=r.describeKind,this._equals=r.equals??Object.is,this._resubscribable=r.resubscribable??!1,this._resetOnTeardown=r.resetOnTeardown??!1,this._autoComplete=r.completeWhenDepsComplete??!0,this._autoError=r.errorWhenDepsError??!0,this._pausable=r.pausable??!0,this._guard=r.guard,this._fn=n,this._partial=r.partial??!1,this._cached=r.initial!==void 0?r.initial:void 0,this._status=e.length===0&&n==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=r.versioningHash??this._config.defaultHashFn??Rn;let o=r.versioning??this._config.defaultVersioning;this._versioningLevel=o,this._versioning=o!=null?Sn(o,this._cached===void 0?void 0:this._cached,{id:r.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(Ir);let s={};for(let[a,d]of Object.entries(r.meta??{})){let u={initial:d,name:`${r.name??"node"}:meta:${a}`,describeKind:"state",config:this._config};r.guard!=null&&(u.guard=r.guard),s[a]=new t([],void 0,u)}Object.freeze(s),this.meta=s,this._hasMeta=Object.keys(s).length>0;let i=this;this._actions={emit(a){i._emit([[C,a]])},down(a){i._emit(Lt(a))},up(a){i._emitUp(Lt(a))}},this.down=this.down.bind(this),this.up=this.up.bind(this)}get _isTerminal(){return this._status==="completed"||this._status==="errored"}get name(){return this._optsName}get status(){return this._status}get cache(){return this._cached===void 0?void 0:this._cached}get lastMutation(){return this._lastMutation}get v(){return this._versioning}hasGuard(){return this._guard!=null}_applyVersioning(e,n){if(this._isExecutingFn)throw new Error(`Node "${this.name}": _applyVersioning cannot run mid-fn \u2014 call it outside of \`_execFn\` (typically at graph setup time before the first subscribe).`);let r=this._versioningLevel;if(r!=null&&e<=r)return;let o=n?.hash??this._hashFn;o!==this._hashFn&&(this._hashFn=o);let s=this._cached===void 0?void 0:this._cached,i=this._versioning,a=i?.id??n?.id,d=i?.version??0,u=Sn(e,s,{id:a,hash:o});u.version=d,this._versioning=u,this._versioningLevel=e}_setInspectorHook(e){return e==null?()=>{}:(this._inspectorHooks==null&&(this._inspectorHooks=new Set),this._inspectorHooks.add(e),()=>{this._inspectorHooks?.delete(e),this._inspectorHooks?.size===0&&(this._inspectorHooks=void 0)})}_pushGuard(e){return this._extraGuards==null&&(this._extraGuards=new Set),this._extraGuards.add(e),()=>{this._extraGuards?.delete(e),this._extraGuards?.size===0&&(this._extraGuards=void 0)}}allowsObserve(e){if(this._guard==null&&this._extraGuards==null)return!0;let n=Rt(e);if(this._guard!=null&&!this._guard(n,"observe"))return!1;if(this._extraGuards!=null){for(let r of this._extraGuards)if(!r(n,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let n=this._guard!=null||this._extraGuards!=null,r=e?.actor!=null;if(!n&&!r)return;let o=Rt(e?.actor),s=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(o,s))throw new Se({actor:o,action:s,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(o,s))throw new Se({actor:o,action:s,nodeName:this.name})}this._lastMutation={actor:o,timestamp_ns:pe()}}down(e,n){let r=Lt(e);r.length!==0&&(this._checkGuard(n),this._emit(r))}emit(e,n){this._checkGuard(n),this._emit([[C,e]])}up(e,n){if(this._deps.length===0)return;let r=Lt(e);if(r.length===0)return;this._checkGuard(n);let o=n??{internal:!0};this._validateUpTiers(r);for(let s of this._deps)s.node.up?.(r,o)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let n of this._deps)n.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let n=this._config.tierOf;for(let r of e){let o=n(r[0]);if(o===3||o===4)throw new Error(`Node "${this.name}": tier-${o} messages cannot flow up \u2014 DATA/RESOLVED/COMPLETE/ERROR are downstream-only. Use \`down(...)\` for value delivery; \`up(...)\` is for control signals (DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN).`)}}subscribe(e,n){if(n!=null&&this._guard!=null){let d=Rt(n);if(!this._guard(d,"observe"))throw new Se({actor:d,action:"observe",nodeName:this.name})}let o=this._isTerminal&&this._resubscribable;if(o){this._cached=void 0,this._status="sentinel",this._store={},this._hasCalledFnOnce=!1,this._waveHasNewData=!1,this._hasNewTerminal=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._isExecutingFn=!1,this._rerunDepth=0,this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null;for(let d of this._deps)Nn(d);if(this._partial===!1){for(let d of this._deps)if(d.prevData!==void 0||d.dataBatch.length!==0||d.terminal!==void 0||d.dirty)throw new Error(`resubscribable-reset invariant: DepRecord not fully reset for node ${this._optsName??"(anonymous)"}`)}}this._sinkCount+=1;let s;try{s=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:o},this._actions)}catch(d){throw this._sinkCount-=1,d}this._sinks==null?this._sinks=e:typeof this._sinks=="function"?this._sinks=new Set([this._sinks,e]):this._sinks.add(e);let i=this._isTerminal;if(this._sinkCount===1&&!i)try{this._activate()}catch(d){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof s=="function")try{s()}catch{}throw d}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let a=!1;return()=>{a||(a=!0,this._sinkCount-=1,this._removeSink(e),typeof s=="function"&&s(),this._sinks==null&&this._deactivate())}}_removeSink(e){if(this._sinks===e)this._sinks=null;else if(this._sinks!=null&&typeof this._sinks!="function")if(this._sinks.delete(e),this._sinks.size===1){let[n]=this._sinks;this._sinks=n}else this._sinks.size===0&&(this._sinks=null)}_activate(){if(this._deps.length===0){this._fn&&this._execFn();return}this._dirtyDepCount=0;let e=this._deps.length,n=0;try{for(let r=0;r<e;r++){let o=r,s=this._deps[r];s.unsub=Lr,s.unsub=s.node.subscribe(i=>{if(s.unsub===null)return;let a=this._config.tierOf,d=!1;for(let u of i)a(u[0])>=3&&(d=!0),this._config.onMessage(this,u,{direction:"down-in",depIndex:o},this._actions);d&&this._maybeRunFnOnSettlement()}),n++}}catch(r){this._deps[n].unsub=null;for(let o=0;o<n;o++){let s=this._deps[o];if(s.unsub!=null){let i=s.unsub;s.unsub=null;try{i()}catch{}Nn(s)}}throw this._dirtyDepCount=0,r}}_addDep(e){for(let o=0;o<this._deps.length;o++)if(this._deps[o].node===e)return o;let n=this._deps.length,r=Ir(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Ot),r.unsub=Lr;try{r.unsub=e.subscribe(o=>{if(r.unsub===null)return;let s=this._config.tierOf,i=!1;for(let a of o)s(a[0])>=3&&(i=!0),this._config.onMessage(this,a,{direction:"down-in",depIndex:n},this._actions);i&&this._maybeRunFnOnSettlement()})}catch(o){throw r.unsub=null,this._deps.pop(),this._dirtyDepCount--,o}return n}_deactivate(e=!1){let n=this._cleanup;if(this._cleanup=void 0,typeof n=="function")try{n()}catch(r){this._emit([[O,this._wrapFnError("cleanup threw",r)]])}else if(n!=null&&typeof n=="object"){let r=n.deactivate;if(typeof r=="function")try{r()}catch(o){this._emit([[O,this._wrapFnError("cleanup.deactivate threw",o)]])}}for(let r of this._deps){if(r.unsub!=null){let o=r.unsub;r.unsub=null;try{o()}catch{}}Nn(r)}this._waveHasNewData=!1,this._hasNewTerminal=!1,this._hasCalledFnOnce=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._rerunDepth=0,this._store={},this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null,this._fn!=null&&(this._cached=void 0),e||(this._fn!=null||this._deps.length>0)&&(!this._isTerminal||this._resubscribable)&&(this._status="sentinel")}_onDepMessage(e,n){let r=this._deps[e],o=n[0];if(this._inspectorHooks!=null){let s={kind:"dep_message",depIndex:e,message:n};for(let i of this._inspectorHooks)i(s)}if(o!==Ie){if(o===z){this._depDirtied(r);return}if(o===xe){if(this._depInvalidated(r),this._cached===void 0)return;this._emit(vn);return}if(o===Re||o===Oe){this._emit([n]);return}if(o===ue){this._emit(At);return}if(o===C)this._depSettledAsData(r,n[1]);else if(o===B)this._depSettledAsResolved(r);else if(o===G)this._depSettledAsTerminal(r,!0);else if(o===O)this._depSettledAsTerminal(r,n[1]);else{this._emit([n]);return}if(!this._fn){(o===C||o===B)&&this._emit([n]),(o===G||o===O)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Ot))}_depSettledAsData(e,n){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.involvedThisWave=!0,e.dataBatch.push(n),this._waveHasNewData=!0}_depSettledAsResolved(e){e.dirty&&(e.dirty=!1,this._dirtyDepCount--)}_depSettledAsTerminal(e,n){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.terminal=n,e.involvedThisWave=!0,this._hasNewTerminal=!0}_depInvalidated(e){e.prevData=void 0,e.terminal=void 0,e.dataBatch.length=0,e.dirty?e.involvedThisWave=!1:(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++)}_maybeRunFnOnSettlement(){if(!(this._isTerminal&&!this._resubscribable)&&!(this._dirtyDepCount>0)){if(!this._partial&&!this._hasCalledFnOnce)for(let e=0;e<this._deps.length;e++){let n=this._deps[e];if(n.dataBatch.length===0&&n.prevData===void 0&&n.terminal===void 0){this._maybeAutoTerminalAfterWave();return}}if(this._paused){this._pendingWave=!0;return}if(!this._waveHasNewData&&!this._hasNewTerminal&&this._hasCalledFnOnce){this._clearWaveFlags(),this._emit(Tn),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(n=>n.terminal!==void 0&&n.terminal!==!0);if(e!=null){this._autoError&&this._emit([[O,e.terminal]]);return}this._autoComplete&&this._deps.every(n=>n.terminal!==void 0)&&this._emit(wn)}_execFn(){if(!this._fn||this._isTerminal&&!this._resubscribable)return;if(this._isExecutingFn){this._pendingRerun=!0;return}let e=this._cleanup;if(typeof e=="function"){this._cleanup=void 0;try{e()}catch(i){this._emit([[O,this._wrapFnError("cleanup threw",i)]]);return}}else if(e!=null&&typeof e=="object"){let i=e.beforeRun;if(typeof i=="function"){e.beforeRun=void 0;try{i()}catch(a){this._emit([[O,this._wrapFnError("cleanup.beforeRun threw",a)]]);return}}}let n=this._deps.map(i=>i.involvedThisWave?i.dataBatch.length>0?[...i.dataBatch]:[]:void 0),r=this._deps.map(i=>i.prevData);for(let i=0;i<this._deps.length;i++){let a=n[i];a!=null&&a.length>0&&(this._deps[i].prevData=a[a.length-1])}let o=this._deps.map(i=>i.terminal),s={prevData:r,terminalDeps:o,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let i={kind:"run",batchData:n,prevData:r};for(let a of this._inspectorHooks)a(i)}this._isExecutingFn=!0;try{let i=this._fn(n,this._actions,s);if(typeof i=="function")this._cleanup=i;else if(i!=null&&typeof i=="object"){let a=i;(typeof a.beforeRun=="function"||typeof a.deactivate=="function"||typeof a.invalidate=="function")&&(this._cleanup=i)}}catch(i){this._emit([[O,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>Dr?(this._rerunDepth=0,this._emit([[O,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${Dr} \u2014 likely a reactive cycle`)]])):this._maybeRunFnOnSettlement()):this._rerunDepth=0,this._clearWaveFlags()}}_clearWaveFlags(){this._waveHasNewData=!1,this._hasNewTerminal=!1;for(let e of this._deps)e.involvedThisWave=!1,e.dataBatch.length=0}_wrapFnError(e,n){let r=n instanceof Error?n.message:String(n);return new Error(`Node "${this.name}": ${e}: ${r}`,{cause:n})}_frameBatch(e){let n=this._config.tierOf;if(e.length===1)return n(e[0][0])===3&&this._status!=="dirty"?[Ve,e[0]]:e;let r=!0,o=!1,s=!1,i=-1;for(let d of e){let u=n(d[0]);u<i&&(r=!1),u===3&&(o=!0),d[0]===z&&(s=!0),i=u}let a=e;if(!r){let d=e.map((u,l)=>({m:u,i:l,tier:n(u[0])}));d.sort((u,l)=>u.tier-l.tier||u.i-l.i),a=d.map(u=>u.m)}if(o&&!s&&this._status!=="dirty"){let d=0;for(;d<a.length&&n(a[d][0])===0;)d++;return d===0?[Ve,...a]:[...a.slice(0,d),Ve,...a.slice(d)]}return a}_emit(e){if(e.length===0)return;for(let a=0;a<e.length;a++){let d=e[a];if(d[0]===O&&d[1]===void 0)throw new TypeError('[ERROR, payload] requires a non-undefined payload (spec \xA71.2). Pass an Error object or domain tag instead \u2014 e.g. node.down([[ERROR, new Error("reason")]])')}let n=e;if(this._isTerminal&&!this._resubscribable){let a=e.filter(d=>d[0]===ue||d[0]===xe);if(a.length===0)return;n=a}n=this._frameBatch(n);let o=null;for(let a=0;a<n.length;a++){let d=n[a],u=d[0];if(u!==Re&&u!==Oe){o?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${u===Re?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let l=!0;if(this._pausable!==!1){let c=d[1];if(u===Re)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(c),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(c))l=!1;else if(this._pauseLocks.delete(c),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let p=this._pauseBuffer;this._pauseBuffer=[],this._emit(p)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}l?o?.push(d):o==null&&(o=n.slice(0,a))}if(o!=null){if(o.length===0)return;n=o}if(this._hasMeta&&n.some(a=>a[0]===ue))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(At)}catch{}let{finalMessages:s,equalsError:i}=this._updateState(n);if(s.length>0&&this._config.inspectorEnabled){let a=this._config.globalInspector;if(a!=null)try{a({kind:"emit",node:this,messages:s})}catch{}}if(s.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let a=this._config.tierOf,d=[];for(let u of s)a(u[0])===3?this._pauseBuffer.push(u):d.push(u);d.length>0&&this._dispatchOrAccumulate(d)}else this._dispatchOrAccumulate(s);i!=null&&this._emit([[O,i]])}_updateState(e){let n=this._config.tierOf,r,o,s=-1,i=0;for(let l of e)n(l[0])===3&&i++;let a=i<=1,d=-1;if(this._versioning!=null&&i>1){for(let l=e.length-1;l>=0;l--)if(e[l][0]===C){d=l;break}}for(let l=0;l<e.length;l++){let c=e[l],p=c[0];if(p===C){if(c.length>=2){let f=!1;if(a&&this._cached!==void 0)try{f=this._equals(this._cached,c[1])}catch(m){o=this._wrapFnError("equals threw",m),s=l;break}if(f){r==null&&(r=e.slice(0,l)),r.push(Mt),this._status="resolved";continue}this._cached=c[1],this._versioning!=null&&(d<0||l===d)&&Ar(this._versioning,c[1],this._hashFn)}this._status="settled",r?.push(c)}else if(r?.push(c),p===z)this._status="dirty";else if(p===B)this._status="resolved";else if(p===G){this._status="completed";{let f=this._config.rigorRecorder;if(f!=null)try{f.onTerminalTransition(this,"completed",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===O){this._status="errored";{let f=this._config.rigorRecorder;if(f!=null)try{f.onTerminalTransition(this,"errored",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===xe){if(this._cached!==void 0){let m=this._config.rigorRecorder;if(m!=null)try{m.onNonVacuousInvalidate(this,this._cached)}catch{}}this._cached=void 0,this._status="dirty";let f=this._cleanup;if(typeof f=="function"){this._cleanup=void 0;try{f()}catch{}}else if(f!=null&&typeof f=="object"){let m=f.invalidate;if(typeof m=="function")try{m()}catch{}}}else p===ue&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let u=s>=0?r??e.slice(0,s):r??e;return o!=null?{finalMessages:u,equalsError:o}:{finalMessages:u}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let n=[...this._sinks];for(let r of n)r(e)};_dispatchOrAccumulate(e){if(Sr()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],pt(()=>this._flushBatchPending()));for(let n of e)this._batchPendingMessages.push(n);return}_t(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let n=this._frameBatch(e);_t(this._deliverToSinks,n,this._config.tierOf)}},Pr=t=>Array.isArray(t),_n=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function A(t,e){return ee([],{...e,initial:t})}function Z(t,e){return ee((r,o,s)=>t(o,s)??void 0,{describeKind:"producer",...e})}function E(t,e,n){return ee(t,(o,s,i)=>{let a=o.map((d,u)=>d!=null&&d.length>0?d.at(-1):i.prevData[u]);s.emit(e(a,i))},{describeKind:"derived",...n})}function Te(t,e,n){return ee(t,(o,s,i)=>{let a=o.map((d,u)=>d!=null&&d.length>0?d.at(-1):i.prevData[u]);return e(a,s,i)??void 0},{describeKind:"effect",...n})}var U=be(()=>{"use strict";Ne()});var Vr={};hn(Vr,{NS_PER_MS:()=>Ue,NS_PER_SEC:()=>rt,constant:()=>Gr,decorrelatedJitter:()=>Br,exponential:()=>Fr,fibonacci:()=>jr,linear:()=>$r,resolveBackoffPreset:()=>Dt,withMaxAttempts:()=>Fs});function Ke(t){return t<0?0:t}function Gs(t,e){return e==="none"?t:e==="full"?Math.random()*t:t/2+Math.random()*(t/2)}function $s(t,e){return t+Math.random()*(e-t)}function Gr(t){let e=Ke(t);return()=>e}function $r(t,e){let n=Ke(t),r=e===void 0?n:Ke(e);return o=>n+r*Math.max(0,o)}function Fr(t){let e=Ke(t?.baseNs??1e8),n=t?.factor!==void 0&&t.factor<1?1:t?.factor??2,r=Ke(t?.maxDelayNs??30*1e9),o=t?.jitter??"none";return s=>{let i;if(e===0)i=0;else if(n===1)i=e;else{let a=r/e,d=1;for(let u=0;u<Math.max(0,s);u++){if(d>=a){d=a;break}d*=n}i=e*d,i>r&&(i=r)}return Gs(i,o)}}function jr(t=100*1e6,e=30*1e9){let n=Ke(t),r=Ke(e);function o(s){if(s<=0)return 1;let i=1,a=2;for(let d=1;d<s;d++){let u=i+a;i=a,a=u}return a}return s=>{let i=o(s)*n;return i<=r?i:r}}function Br(t=100*1e6,e=30*1e9){return(n,r,o)=>{let i=Math.min(e,(o??t)*3);return $s(t,i)}}function Fs(t,e){return(n,r,o)=>n>=e?null:t(n,r,o)}function Dt(t){if(t==="constant")return Gr(1*1e9);if(t==="linear")return $r(1*1e9);if(t==="exponential")return Fr();if(t==="fibonacci")return jr();if(t==="decorrelatedJitter")return Br();throw new Error(`Unknown backoff preset: "${String(t)}". Use one of: constant, linear, exponential, fibonacci, decorrelatedJitter`)}var Ue,rt,En=be(()=>{"use strict";Ue=1e6,rt=1e9});var re,Ce=be(()=>{"use strict";re=class{_timer;_gen=0;start(e,n){this.cancel(),this._gen+=1;let r=this._gen;this._timer=setTimeout(()=>{this._timer=void 0,r===this._gen&&n()},e)}cancel(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}get pending(){return this._timer!==void 0}}});var Ur={};hn(Ur,{CircuitOpenError:()=>Pe,RateLimiterOverflowError:()=>It,TimeoutError:()=>Pt,circuitBreaker:()=>gt,fallback:()=>qs,rateLimiter:()=>Ks,retry:()=>Bs,retrySource:()=>On,timeout:()=>Js,tokenBucket:()=>ht,withBreaker:()=>Vs,withStatus:()=>Us});function ze(t){return{describeKind:"derived",...t}}function js(t){return t<0?0:t}function Gt(t){return t[1]}function Kr(t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError("backoff strategy must return a finite number");return t<0?0:t}function Bs(t,e){let n=e?.count,r=e?.backoff,o=n!==void 0?n:r===void 0?0:2147483647;if(o<0)throw new RangeError("retry count must be >= 0");let s=r===void 0?null:typeof r=="string"?Dt(r):r;return Z(i=>{let a=0,d=!1,u=null,l,c=new re;function p(){l?.(),l=void 0}function f(h){if(d)return;if(a>=o){p(),i.down([[O,h]]);return}let g=s===null?0:s(a,h,u);if(g==null){p(),i.down([[O,h]]);return}let y;try{y=Kr(g)}catch{p(),i.down([[O,h]]);return}u=y,a+=1,p();let b=y>0?y/1e6:1;c.start(b,()=>{d||m()})}function m(){c.cancel(),p(),l=t.subscribe(h=>{if(!d)for(let g of h){let y=g[0];if(y===z)i.down([[z]]);else if(y===C)a=0,u=null,i.emit(g[1]);else if(y===B)i.down([[B]]);else if(y===G)p(),i.down([[G]]);else if(y===O){f(Gt(g));return}else i.down([g])}})}return m(),()=>{d=!0,c.cancel(),p()}},{...ze(),initial:t.cache})}function On(t,e){let n=e?.count,r=e?.backoff,o=n!==void 0?n:r===void 0?0:2147483647;if(o<0)throw new RangeError("retry count must be >= 0");let s=r===void 0?null:typeof r=="string"?Dt(r):r;return Z(i=>{let a=0,d=!1,u=null,l,c=new re;function p(){l?.(),l=void 0}function f(h){if(d)return;if(a>=o){p(),i.down([[O,h]]);return}let g=s===null?0:s(a,h,u);if(g==null){p(),i.down([[O,h]]);return}let y;try{y=Kr(g)}catch{p(),i.down([[O,h]]);return}u=y,a+=1,p();let b=y>0?y/1e6:1;c.start(b,()=>{d||m()})}function m(){c.cancel(),p();let h;try{h=t()}catch(g){f(g);return}l=h.subscribe(g=>{if(!d)for(let y of g){let b=y[0];if(b===z)i.down([[z]]);else if(b===C)a=0,u=null,i.emit(y[1]);else if(b===B)i.down([[B]]);else if(b===G)p(),i.down([[G]]);else if(b===O){f(Gt(y));return}else i.down([y])}})}return m(),()=>{d=!0,c.cancel(),p()}},{...ze(),initial:e?.initial})}function gt(t){let e=Math.max(1,t?.failureThreshold??5),n=js(t?.cooldownNs??30*1e9),r=t?.cooldown??null,o=Math.max(1,t?.halfOpenMax??1),s=t?.now??F,i="closed",a=0,d=0,u=0,l=n,c=0;function p(){if(!r)return n;let h=r(d);return h!==null?h:n}function f(){i="open",l=p(),u=s(),c=0}return{canExecute(){return i==="closed"?!0:i==="open"?s()-u>=l?(i="half-open",c=1,!0):!1:c<o?(c++,!0):!1},recordSuccess(){i==="half-open"?(i="closed",a=0,d=0):i==="closed"&&(a=0)},recordFailure(h){if(i==="half-open"){d++,f();return}i==="closed"&&(a++,a>=e&&f())},get state(){return i},get failureCount(){return a},reset(){i="closed",a=0,d=0,c=0}}}function Vs(t,e){let n=e?.onOpen??"skip";return r=>{let o=ee([],(s,i)=>{function a(){o.meta.breakerState.down([[C,t.state]])}let d=r.subscribe(u=>{for(let l of u){let c=l[0];c===z?i.down([[z]]):c===C?t.canExecute()?(a(),i.emit(l[1])):(a(),n==="error"?i.down([[O,new Pe]]):i.down([[B]])):c===B?i.down([[B]]):c===G?(t.recordSuccess(),a(),i.down([[G]])):c===O?(t.recordFailure(Gt(l)),a(),i.down([l])):i.down([l])}});return a(),d},{...ze(),meta:{breakerState:t.state},completeWhenDepsComplete:!1,initial:r.cache});return{node:o,breakerState:o.meta.breakerState}}}function ht(t,e){if(t<=0)throw new RangeError("capacity must be > 0");if(e<0)throw new RangeError("refillPerSecond must be >= 0");let n=t,r=F();function o(s){if(e>0){let i=s-r;n=Math.min(t,n+i/1e9*e)}r=s}return{available(){return o(F()),n},tryConsume(s=1){if(s<=0)return!0;let i=F();return o(i),n>=s?(n-=s,!0):!1},putBack(s=1){s<=0||(o(F()),n=Math.min(t,n+s))}}}function Ks(t,e){let{maxEvents:n,windowNs:r}=e;if(n<=0)throw new RangeError("maxEvents must be > 0");if(r<=0)throw new RangeError("windowNs must be > 0");let o=e.maxBuffer;if(o!==void 0&&o<1)throw new RangeError("maxBuffer must be >= 1");let s=e.onOverflow??"drop-newest",i=n*1e9/r;return Z(a=>{let d=ht(n,i),u=[],l=new re,c=!1,p=1e9/i;function f(){for(;u.length>0;)if(d.tryConsume(1))a.emit(u.shift());else{l.start(Math.max(1,p/1e6),f);return}}let m=t.subscribe(h=>{for(let g of h){if(c)return;let y=g[0];if(y===z)a.down([[z]]);else if(y===C){if(o!==void 0&&u.length>=o){if(s!=="drop-newest")if(s==="drop-oldest")u.shift(),u.push(g[1]);else{c=!0,l.cancel(),u.length=0,a.down([[O,new It(o)]]);return}}else u.push(g[1]);f()}else if(y===B)a.down([[B]]);else if(y===G)c=!0,l.cancel(),u.length=0,a.down([[G]]);else if(y===O)c=!0,l.cancel(),u.length=0,a.down([g]);else if(y===ue){c=!0,l.cancel(),u.length=0,a.down([g]);return}else a.down([g])}});return()=>{c=!0,l.cancel(),m()}},{...ze(),initial:t.cache})}function Us(t,e){let n=e?.initialStatus??"pending",r=ee([],(o,s)=>{let i=n;return r.meta.status.down([[C,n]]),r.meta.error.down([[C,null]]),t.subscribe(d=>{for(let u of d){let l=u[0];if(l===z)s.down([[z]]);else if(l===C)i==="errored"?X(()=>{r.meta.error.down([[C,null]]),r.meta.status.down([[C,"active"]])}):r.meta.status.down([[C,"active"]]),i="active",s.emit(u[1]);else if(l===B)s.down([[B]]);else if(l===G)r.meta.status.down([[C,"completed"]]),i="completed",s.down([[G]]);else if(l===O){let c=Gt(u);X(()=>{r.meta.error.down([[C,c]]),r.meta.status.down([[C,"errored"]])}),i="errored",s.down([u])}else s.down([u])}})},{...ze(),meta:{status:n,error:null},completeWhenDepsComplete:!1,resubscribable:!0,initial:t.cache});return{node:r,status:r.meta.status,error:r.meta.error}}function zs(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function Hs(t){return t!=null&&typeof t.then=="function"}function Ws(t){return t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function"}function qs(t,e){return Z(n=>{let r,o;function s(){o?.(),o=void 0,zs(e)||Hs(e)||Ws(e)?r=P(e).subscribe(a=>{n.down(a)}):(n.emit(e),n.down([[G]]))}return o=t.subscribe(i=>{for(let a of i){let d=a[0];if(d===z)n.down([[z]]);else if(d===C)n.emit(a[1]);else if(d===B)n.down([[B]]);else if(d===G)n.down([[G]]);else if(d===O){s();return}else if(d===ue){r?.(),n.down([a]);return}else n.down([a])}}),()=>{o?.(),r?.()}},{...ze(),initial:t.cache})}function Js(t,e){if(e<=0)throw new RangeError("timeoutNs must be > 0");return Z(n=>{let r=!1,o=new re;function s(){let a=e/1e6;o.start(a,()=>{r||(r=!0,i(),n.down([[O,new Pt(e)]]))})}let i=t.subscribe(a=>{for(let d of a){if(r)return;let u=d[0];if(u===z)n.down([[z]]);else if(u===C)s(),n.emit(d[1]);else if(u===B)n.down([[B]]);else if(u===G){o.cancel(),r=!0,n.down([[G]]);return}else if(u===O){o.cancel(),r=!0,n.down([d]);return}else if(u===ue){o.cancel(),r=!0,n.down([d]);return}else n.down([d])}});return s(),()=>{r=!0,o.cancel(),i()}},{...ze(),initial:t.cache})}var Pe,It,Pt,ot=be(()=>{"use strict";ke();ce();ne();Ne();U();En();J();Ce();Pe=class extends Error{name="CircuitOpenError";constructor(){super("Circuit breaker is open")}};It=class extends Error{name="RateLimiterOverflowError";constructor(e){super(`rateLimiter buffer overflow (maxBuffer=${e})`)}};Pt=class extends Error{name="TimeoutError";constructor(e){super(`Timed out after ${e/1e6}ms`)}}});function $t(t){return{describeKind:"producer",...t}}function Wr(t,e){let{signal:n,period:r,...o}=e??{};return Z(s=>{let i=!1,a=0,d,u,l=()=>{i=!0,d!==void 0&&clearTimeout(d),u!==void 0&&clearInterval(u),n?.removeEventListener("abort",p)},c=()=>{i||(r!=null?(s.emit(a++),u=setInterval(()=>{i||s.emit(a++)},r)):(i=!0,n?.removeEventListener("abort",p),s.emit(a++),s.down([[G]])))},p=()=>{i||(l(),s.down([[O,n.reason]]))};if(n?.aborted){p();return}return d=setTimeout(c,t),n?.addEventListener("abort",p,{once:!0}),l},$t(o))}function qr(t,e){return Z(n=>{let r=!1;try{for(let o of t){if(r)return;n.emit(o)}r||n.down([[G]])}catch(o){r||n.down([[O,o]])}return()=>{r=!0}},$t(e))}function Ys(t){return t!=null&&typeof t.then=="function"}function Ft(t,e){let{signal:n,...r}=e??{};return Z(o=>{let s=!1,i=()=>{s||(s=!0,o.down([[O,n.reason]]))};if(n?.aborted){i();return}return n?.addEventListener("abort",i,{once:!0}),Promise.resolve(t).then(a=>{s||(s=!0,n?.removeEventListener("abort",i),o.emit(a),o.down([[G]]))},a=>{s||(s=!0,n?.removeEventListener("abort",i),o.down([[O,a]]))}),()=>{s=!0,n?.removeEventListener("abort",i)}},$t(r))}function Cn(t,e){let{signal:n,...r}=e??{};return Z(o=>{let s=new AbortController,i=()=>s.abort(n?.reason);n?.aborted?s.abort(n.reason):n?.addEventListener("abort",i,{once:!0});let a=n??s.signal,d=!1,u=t[Symbol.asyncIterator](),l=()=>{d||a.aborted||Promise.resolve(u.next()).then(c=>{if(!(d||a.aborted)){if(c.done){o.down([[G]]);return}o.emit(c.value),l()}},c=>{!d&&!a.aborted&&o.down([[O,c]])})};return l(),()=>{d=!0,n?.removeEventListener("abort",i),s.abort(),Promise.resolve(u.return?.()).catch(()=>{})}},$t(r))}function Qs(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function P(t,e){if(Qs(t))return t;if(Ys(t))return Ft(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return Cn(t,e);if(typeof n[Symbol.iterator]=="function")return qr(t,e)}return Xs(t)}function Xs(...t){return qr(t,void 0)}function yt(t,e,n){return ee([t],(o,s)=>{let i=o[0];if(i!=null&&i.length>0)for(let a of i)e(a)},{describeKind:"effect",...n}).subscribe(()=>{})}function ve(t){return new Promise((e,n)=>{let r=!1,o=!1,s;s=t.subscribe(i=>{for(let a of i){if(r)return;if(a[0]===C){r=!0,e(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===O){r=!0,n(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===G){r=!0,n(new Error("completed without DATA")),s?(s(),s=void 0):o=!0;return}}}),o&&(s?.(),s=void 0)})}function zr(t,e,n){return new Promise((r,o)=>{let s=!1,i=!1,a,d=n?.skipCurrent===!0;a=t.subscribe(u=>{for(let l of u){if(s)return;if(!(d&&l[0]===C)){if(l[0]===C){let c=l[1];if(e(c)){s=!0,r(c),a?(a(),a=void 0):i=!0;return}}if(l[0]===O){s=!0,o(l[1]),a?(a(),a=void 0):i=!0;return}if(l[0]===G){s=!0,o(new Error("completed without matching value")),a?(a(),a=void 0):i=!0;return}}}}),d=!1,i&&(a?.(),a=void 0)})}async function Jr(t,e){let n=e?.predicate??(s=>s!=null),r=e?.skipCurrent;if(e?.timeoutMs==null||e.timeoutMs<=0)return await zr(t,n,{skipCurrent:r});if(An===void 0){let[s,i]=await Promise.all([Promise.resolve().then(()=>(ot(),Ur)),Promise.resolve().then(()=>(En(),Vr))]);An=s.timeout,Hr=i.NS_PER_MS}let o=An(t,e.timeoutMs*Hr);return await zr(o,n,{skipCurrent:r})}function Yr(t,e){let n=new AbortController,r=e?.reason??new Error("cancelled via nodeSignal"),o,s=!1,i=()=>{o?(o(),o=void 0):s=!0};return o=t.subscribe(a=>{if(!n.signal.aborted)for(let d of a){if(d[0]===C&&d[1]===!0){n.abort(r),i();return}if(d[0]===O){n.abort(d[1]),i();return}if(d[0]===G){i();return}}}),s&&(o?.(),o=void 0),{signal:n.signal,dispose:()=>{o&&(o(),o=void 0)}}}function q(t){return t.subscribe(()=>{})}var An,Hr,J=be(()=>{"use strict";ne();Ne();U()});var _u={};hn(_u,{AgentLoopGraph:()=>pn,AllTiersExhaustedError:()=>vt,BudgetExhaustedError:()=>Yt,ChatStreamGraph:()=>ln,CircuitOpenError:()=>Pe,DEFAULT_DECAY_RATE:()=>gr,FallbackMissError:()=>ai,LLMTimeoutError:()=>at,ReplayCacheMissError:()=>qe,ToolRegistryGraph:()=>cn,admissionFilter3D:()=>au,admissionScored:()=>os,agentLoop:()=>ou,agentMemory:()=>pu,anthropicAdapter:()=>Ln,canonicalJson:()=>$n,cascadingLlmAdapter:()=>Xn,chatStream:()=>lr,composePricing:()=>_i,computePrice:()=>zn,contentGate:()=>eu,costMeterExtractor:()=>qa,createAdapter:()=>wi,createCapabilitiesRegistry:()=>Ps,createPricingRegistry:()=>Si,dryRunAdapter:()=>He,fallbackAdapter:()=>Fn,fromLLM:()=>Bi,frozenContext:()=>zi,gatedStream:()=>za,gaugesAsContext:()=>fu,googleAdapter:()=>jn,graphFromSpec:()=>Ts,graphFromSpecReactive:()=>wu,handoff:()=>su,keywordFlagExtractor:()=>Ya,knobsAsTools:()=>xu,llmConsolidator:()=>mr,llmExtractor:()=>fr,memoryRetrieval:()=>Tr,memoryWithKG:()=>yr,memoryWithTiers:()=>br,memoryWithVectors:()=>hr,observableAdapter:()=>xi,openAICompatAdapter:()=>Vn,parseRateLimitFromError:()=>Jn,pricingFor:()=>Mi,promptNode:()=>nr,redactor:()=>tu,registryPricing:()=>Ni,resilientAdapter:()=>ji,streamExtractor:()=>Qa,streamingPromptNode:()=>Ua,suggestStrategy:()=>vs,suggestStrategyReactive:()=>Su,systemPromptBuilder:()=>Ha,tier:()=>$i,toolCallExtractor:()=>Za,toolExecution:()=>cr,toolRegistry:()=>pr,toolSelector:()=>iu,validateGraphDef:()=>Nu,withBreaker:()=>Hn,withBudgetGate:()=>qn,withDryRun:()=>Oi,withRateLimiter:()=>Qn,withReplayCache:()=>Tt,withRetry:()=>Zn,withTimeout:()=>er,zeroPrice:()=>Jt});module.exports=Ns(_u);U();ke();ce();ne();U();var Mn=class{_version=0;_store=new Map;_maxSize;_defaultTtl;constructor(e={}){let{maxSize:n,defaultTtl:r}=e;if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(r!==void 0&&r<=0)throw new RangeError("defaultTtl must be positive");this._maxSize=n,this._defaultTtl=r}get version(){return this._version}get size(){return this._store.size}has(e){let n=this._store.get(e);return n===void 0?!1:this._isExpired(n)?(this._store.delete(e),this._version+=1,!1):(this._touchLru(e,n),!0)}get(e){let n=this._store.get(e);if(n!==void 0){if(this._isExpired(n)){this._store.delete(e),this._version+=1;return}return this._touchLru(e,n),n.value}}set(e,n,r){let o=this._resolveExpiresAt(r);this._store.has(e)&&this._store.delete(e),this._store.set(e,{value:n,expiresAt:o}),this._evictLruWhileOver(),this._version+=1}setMany(e,n){let r=this._resolveExpiresAt(n),o=0;try{for(let[s,i]of e)this._store.has(s)&&this._store.delete(s),this._store.set(s,{value:i,expiresAt:r}),o+=1}finally{o>0&&(this._evictLruWhileOver(),this._version+=1)}}delete(e){let n=this._store.delete(e);return n&&(this._version+=1),n}deleteMany(e){let n=0;try{for(let r of e)this._store.delete(r)&&(n+=1)}finally{n>0&&(this._version+=1)}return n}clear(){let e=this._store.size;return e===0?0:(this._store.clear(),this._version+=1,e)}pruneExpired(){let e=F(),n=0;for(let[r,o]of this._store)this._isExpired(o,e)&&(this._store.delete(r),n+=1);return n>0&&(this._version+=1),n}toMap(){let e=F(),n=new Map;for(let[r,o]of this._store)this._isExpired(o,e)||n.set(r,o.value);return n}_resolveExpiresAt(e){let n=e??this._defaultTtl;if(n!==void 0){if(!Number.isFinite(n)||n<=0)throw new RangeError(`MapBackend: ttl must be a positive finite number (got ${n})`);return F()+n*1e9}}_isExpired(e,n){return e.expiresAt===void 0?!1:(n??F())>=e.expiresAt}_touchLru(e,n){this._store.delete(e),this._store.set(e,n)}_evictLruWhileOver(){if(this._maxSize!==void 0)for(;this._store.size>this._maxSize;){let e=this._store.keys().next().value;if(e===void 0)break;this._store.delete(e)}}};function nt(t={}){let{name:e,maxSize:n,defaultTtl:r,versioning:o,backend:s,retention:i}=t;if(i&&n!==void 0)throw new RangeError("reactiveMap: `maxSize` (LRU) and `retention` (score-based) are mutually exclusive. Pick one eviction policy.");if(i&&i.archiveThreshold===void 0&&i.maxSize===void 0)throw new RangeError("reactiveMap: `retention` requires at least one of `archiveThreshold` or `maxSize` to trigger archival.");let a=s??new Mn({maxSize:n,defaultTtl:r}),d=A(a.toMap(),{name:e,describeKind:"state",equals:(p,f)=>p===f,...o!=null?{versioning:o}:{}});function u(){let p=a.toMap();X(()=>{d.down([[z]]),d.down([[C,p]])})}function l(){if(!i)return;let p=a.toMap(),f=i.archiveThreshold,m=i.maxSize,h=[];for(let[y,b]of p)h.push({key:y,value:b,score:i.score(y,b)});h.sort((y,b)=>y.score-b.score);let g=new Set;if(f!==void 0)for(let y of h)if(y.score<f)g.add(y.key);else break;if(m!==void 0&&h.length-g.size>m)for(let y of h){if(h.length-g.size<=m)break;g.has(y.key)||g.add(y.key)}if(g.size!==0)for(let y of h)g.has(y.key)&&(i.onArchive?.(y.key,y.value,y.score),a.delete(y.key))}function c(p,f="mutation"){let m=a.version;try{return p()}finally{a.version!==m&&(f==="mutation"&&l(),u())}}return{entries:d,has(p){return c(()=>a.has(p),"read")},get(p){return c(()=>a.get(p),"read")},set(p,f,m){c(()=>a.set(p,f,m?.ttl))},setMany(p,f){c(()=>a.setMany(p,f?.ttl))},delete(p){c(()=>a.delete(p))},deleteMany(p){c(()=>a.deleteMany(p))},clear(){c(()=>a.clear())},pruneExpired(){c(()=>a.pruneExpired())},get size(){return a.size},dispose(){}}}function mt(t,e){return`${t}::${e}`}function Ps(t){let e=nt({name:"capabilitiesRegistry"}),n=u=>{e.set(mt(u.provider,u.id),u)};if(t)for(let u of t)n(u);let r=(u,l)=>{let c=e.get(mt(u,l));if(c)return c;let p=e.entries.cache;if(!p)return;let f;for(let[,m]of p){if(m.provider!==u)continue;let h=m.id;l.startsWith(h)&&(!f||h.length>f.id.length)&&(f=m)}return f},o=128,s=new Map,i=new Map,a=(u,l,c,p)=>{for(u.has(l)&&u.delete(l),u.set(l,c);u.size>p;){let f=u.keys().next().value;if(f===void 0)break;u.delete(f)}},d=E([e.entries],([u])=>Array.from(u.values()),{name:"capabilitiesRegistry/entries",initial:[]});return{register:n,lookup:r,remove(u,l){let c=e.has(mt(u,l));return c&&e.delete(mt(u,l)),c},entries(){let u=e.entries.cache;return(function*(){if(u)for(let l of u.values())yield l})()},lookupNode(u,l){let c=mt(u,l),p=s.get(c);if(p)return s.delete(c),s.set(c,p),p;let f=E([e.entries],()=>r(u,l),{name:`capabilitiesRegistry/lookup/${u}::${l}`,initial:void 0});return a(s,c,f,o),f},entriesNode:d,byProvider(u){let l=i.get(u);if(l)return i.delete(u),i.set(u,l),l;let c=E([d],([p])=>p.filter(f=>f.provider===u),{name:`capabilitiesRegistry/byProvider/${u}`,initial:[]});return a(i,u,c,o),c}}}ce();ne();Ne();U();J();function jt(t){return{describeKind:"derived",...t}}function Zs(t){return{describeKind:"derived",partial:!0,...t}}function Qr(t,e,n){return ee([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[B]]);return}let i=!1;for(let a of s)e(a)&&(o.emit(a),i=!0);i||o.down([[B]])},jt(n))}function Xr(t,e,n){let r=n?.where??(s=>s!=null),o=!1;return ee([t],(s,i)=>{let a=s[0];if(a==null||a.length===0){i.down([[B]]);return}for(let d of a)!o&&r(d)&&(o=!0,e(d)),i.emit(d)},jt(n))}function Zr(t,e,n){return ee([t,e],(r,o,s)=>{let i=r[0],a=r[1],d=a!=null&&a.length>0?a.at(-1):s.prevData[1];if(i!=null&&i.length>0){if(!(a!=null&&a.length>0)&&s.prevData[1]===void 0){o.down([[B]]);return}for(let u of i)o.emit([u,d])}else o.down([[B]])},Zs(n))}function ei(t,e,n){let r,o=!1,s=()=>{o||(o=!0,n())};return r=t.subscribe(i=>{let a=!1,d=!1;for(let u of i)u[0]!==Ie&&(u[0]===C?e.emit(u[1]):u[0]===G?a=!0:u[0]===O?(d=!0,e.down([u])):(u[0]===z||u[0]===B)&&e.down([u]));d?(r?.(),r=void 0,s()):a&&s()}),()=>{r?.(),r=void 0}}function oe(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return ee([t],(i,a,d)=>{if(d.terminalDeps[0]!=null&&d.terminalDeps[0]!==!0){s();return}if(d.terminalDeps[0]===!0){o=!0,r||a.down([[G]]);return}let u=i[0];if(!(u==null||u.length===0))return s(),r=ei(P(e(u[u.length-1])),a,()=>{s(),o&&a.down([[G]])}),{deactivate:()=>{s(),o=!1}}},{...jt(n),completeWhenDepsComplete:!1})}function eo(t,e,n){return Z(r=>{let o=t.subscribe(s=>{for(let i of s)if(i[0]===C)r.emit(i[1]);else if(i[0]===O)try{r.emit(e(i[1]))}catch(a){r.down([[O,a]])}else i[0]===G&&r.down([[G]])});return()=>{o()}},jt(n))}var bt=class{constructor(e){this.capacity=e;if(!Number.isInteger(e)||e<=0)throw new Error(`RingBuffer capacity must be a positive integer (got ${e})`);this.buf=new Array(e)}buf;head=0;_size=0;get size(){return this._size}get maxSize(){return this.capacity}push(e){let n=(this.head+this._size)%this.capacity;this.buf[n]=e,this._size<this.capacity?this._size++:this.head=(this.head+1)%this.capacity}shift(){if(this._size===0)return;let e=this.buf[this.head];return this.buf[this.head]=void 0,this.head=(this.head+1)%this.capacity,this._size--,e}at(e){if(this._size===0)return;let n=e<0?this._size+e:e;if(!(n<0||n>=this._size))return this.buf[(this.head+n)%this.capacity]}toArray(){let e=new Array(this._size);for(let n=0;n<this._size;n++)e[n]=this.buf[(this.head+n)%this.capacity];return e}clear(){for(let e=0;e<this._size;e++)this.buf[(this.head+e)%this.capacity]=void 0;this.head=0,this._size=0}};async function*st(t,e){let n=e?.parse??(w=>w),r=e?.signal,o=new TextDecoder,s="",i="message",a=[],d,u,l=[],c=()=>{if(a.length===0&&i==="message"&&d===void 0){a=[];return}let w=a.join(`
|
|
2
|
+
`);l.push({event:i,data:n(w),id:d,retry:u}),i="message",a=[],d=void 0,u=void 0},p=w=>{if(w===""){c();return}if(w.startsWith(":"))return;let T=w.indexOf(":"),x=T<0?w:w.slice(0,T),S=T<0?"":w.slice(T+1);switch(S.startsWith(" ")&&(S=S.slice(1)),x){case"event":i=S;break;case"data":a.push(S);break;case"id":S.includes("\0")||(d=S);break;case"retry":{let N=Number(S);Number.isFinite(N)&&(u=N);break}}},f=(w,T)=>{s+=o.decode(w,{stream:!T});let x=s.split(/\r?\n/);s=x.pop()??"";for(let S of x)p(S)},m=t,h=t instanceof ReadableStream?t:m&&typeof m=="object"&&m.body instanceof ReadableStream?m.body:null,g,y,b=!1,v=()=>{b||(b=!0,g&&g.cancel().catch(()=>{}),y&&typeof y.return=="function"&&Promise.resolve(y.return()).catch(()=>{}))},k=()=>{v()};if(r){if(r.aborted)return;r.addEventListener("abort",k,{once:!0})}try{if(h){for(g=h.getReader();!r?.aborted;){let{value:w,done:T}=await g.read();if(T)break;for(f(w,!1);l.length>0;)yield l.shift()}f(new Uint8Array,!0)}else{for(y=t[Symbol.asyncIterator]();!r?.aborted;){let T=await y.next();if(T.done)break;for(f(T.value,!1);l.length>0;)yield l.shift()}f(new Uint8Array,!0)}if(s.trim()){for(let w of s.split(/\r?\n/))p(w);c()}for(;l.length>0;)yield l.shift()}finally{r&&r.removeEventListener("abort",k),v()}}async function Le(t,e){let n;try{n=await t.text()}catch{n=""}let r=e??"HTTP",o=new Error(`${r} API ${t.status}: ${t.statusText}${n?` \u2014 ${n}`:""}`);return o.status=t.status,o.headers=t.headers,o}function Ln(t={}){return t.sdk?si(t):oi(t)}function Bt(t,e,n,r){let o=e?.model??n;if(!o)throw new Error("anthropicAdapter: model must be set via options.model or invokeOpts.model");let{system:s,chat:i}=ti(t,e?.systemPrompt),a={model:o,messages:i.map(ni),max_tokens:e?.maxTokens??4096};return s&&(a.system=s),e?.temperature!=null&&(a.temperature=e.temperature),e?.tools&&e.tools.length>0&&(a.tools=e.tools.map(ri)),e?.maxReasoningTokens!=null&&(a.thinking={type:"enabled",budget_tokens:e.maxReasoningTokens}),e?.cacheHint,r&&(a.stream=!0),e?.providerExtras&&Object.assign(a,e.providerExtras),a}function ti(t,e){let n=[];e&&n.push(e);let r=[];for(let o of t)o.role==="system"?n.push(o.content):r.push(o);return{system:n.length>0?n.join(`
|
|
3
3
|
|
|
4
|
-
`):void 0,chat:r}}function si(t){if(t.role==="tool")return{role:"user",content:[{type:"tool_result",tool_use_id:t.toolCallId,content:t.content}]};if(t.role==="assistant"&&t.toolCalls&&t.toolCalls.length>0){let e=[];t.content&&e.push({type:"text",text:t.content});for(let n of t.toolCalls)e.push({type:"tool_use",id:n.id,name:n.name,input:n.arguments});return{role:"assistant",content:e}}return{role:t.role,content:t.content}}function ii(t){return{name:t.name,description:t.description,input_schema:t.parameters}}function Yt(t,e){if(!t)return{...e};let n={...t};return e.input_tokens!=null&&(n.input_tokens=e.input_tokens),e.output_tokens!=null&&(n.output_tokens=e.output_tokens),e.cache_read_input_tokens!=null&&(n.cache_read_input_tokens=e.cache_read_input_tokens),e.cache_creation_input_tokens!=null&&(n.cache_creation_input_tokens=e.cache_creation_input_tokens),e.cache_creation&&(n.cache_creation={...t.cache_creation??{},...e.cache_creation}),e.server_tool_use&&(n.server_tool_use={...t.server_tool_use??{},...e.server_tool_use}),n}function zn(t){let e={input:{regular:t?.input_tokens??0},output:{regular:t?.output_tokens??0},raw:t};return t?.cache_read_input_tokens&&(e.input.cacheRead=t.cache_read_input_tokens),t?.cache_creation?(t.cache_creation.ephemeral_5m_input_tokens&&(e.input.cacheWrite5m=t.cache_creation.ephemeral_5m_input_tokens),t.cache_creation.ephemeral_1h_input_tokens&&(e.input.cacheWrite1h=t.cache_creation.ephemeral_1h_input_tokens)):t?.cache_creation_input_tokens&&(e.input.cacheWrite5m=t.cache_creation_input_tokens),t?.server_tool_use?.web_search_requests&&(e.auxiliary={webSearchRequests:t.server_tool_use.web_search_requests}),e}function lo(t,e){let n=[],r=[];for(let o of t.content)if(o.type==="text"&&typeof o.text=="string")n.push(o.text);else if(o.type==="tool_use"){let s=o;r.push({id:s.id,name:s.name,arguments:s.input??{}})}return{content:n.join(""),toolCalls:r.length>0?r:void 0,usage:zn(t.usage),finishReason:t.stop_reason,latencyMs:e,model:t.model,provider:"anthropic"}}function ai(t){let e=t.apiKey??globalThis.process?.env?.ANTHROPIC_API_KEY,n=t.baseURL??"https://api.anthropic.com",r=t.anthropicVersion??"2023-06-01",o=t.fetchImpl??fetch,s=()=>{if(!e)throw new Error("anthropicAdapter: apiKey required for invoke/stream (or provide opts.sdk)");return{"x-api-key":e,"anthropic-version":r,"content-type":"application/json",...t.headers??{}}};return{provider:"anthropic",model:t.model,async invoke(i,a){let l=Jt(i,a,t.model,!1),c=V(),d=await o(`${n}/v1/messages`,{method:"POST",headers:s(),body:JSON.stringify(l),signal:a?.signal});if(!d.ok)throw await Ie(d,"Anthropic");let u=await d.json(),p=Math.max(0,(V()-c)/1e6);return lo(u,p)},async*stream(i,a){let l=Jt(i,a,t.model,!0),c=await o(`${n}/v1/messages`,{method:"POST",headers:{...s(),accept:"text/event-stream"},body:JSON.stringify(l),signal:a?.signal});if(!c.ok)throw await Ie(c,"Anthropic");if(!c.body)throw new Error("anthropicAdapter: streaming response has no body");let d,u,p=new Map;for await(let f of lt(c.body,{signal:a?.signal})){let m=f.data;if(!m)continue;let h;try{h=JSON.parse(m)}catch{continue}switch(h.type){case"message_start":{d=Yt(d,h.message.usage);break}case"content_block_start":{let g=h,y=g.content_block;y.type==="tool_use"&&(p.set(g.index,{id:String(y.id??""),name:String(y.name??""),argBuf:""}),yield{type:"tool-call-delta",delta:{id:String(y.id??""),name:String(y.name??"")}});break}case"content_block_delta":{let g=h,y=g.delta;if(y.type==="text_delta"&&typeof y.text=="string")yield{type:"token",delta:y.text};else if(y.type==="input_json_delta"&&typeof y.partial_json=="string"){let b=p.get(g.index);b&&(b.argBuf+=y.partial_json),yield{type:"tool-call-delta",delta:{argumentsDelta:y.partial_json}}}else y.type==="thinking_delta"&&typeof y.thinking=="string"&&(yield{type:"thinking",delta:y.thinking});break}case"message_delta":{let g=h;g.delta.stop_reason&&(u=g.delta.stop_reason),g.delta.usage&&(d=Yt(d,g.delta.usage));break}case"message_stop":break}}d&&(yield{type:"usage",usage:zn(d)}),yield{type:"finish",reason:u??"stop"}}}}function ci(t){let e=t.sdk;if(!e)throw new Error("sdkBackedAnthropic: sdk instance required");return{provider:"anthropic",model:t.model,async invoke(n,r){let o=Jt(n,r,t.model,!1),s=V(),i=await e.messages.create(o,{signal:r?.signal}),a=Math.max(0,(V()-s)/1e6);return lo(i,a)},async*stream(n,r){if(!e.messages.stream)throw new Error("sdkBackedAnthropic: SDK instance does not expose .messages.stream");let o=Jt(n,r,t.model,!0),s,i;for await(let a of e.messages.stream(o,{signal:r?.signal}))switch(a.type){case"message_start":s=Yt(s,a.message.usage);break;case"content_block_delta":{let l=a.delta;l?.type==="text_delta"&&typeof l.text=="string"?yield{type:"token",delta:l.text}:l?.type==="input_json_delta"&&typeof l.partial_json=="string"?yield{type:"tool-call-delta",delta:{argumentsDelta:l.partial_json}}:l?.type==="thinking_delta"&&typeof l.thinking=="string"&&(yield{type:"thinking",delta:l.thinking});break}case"message_delta":{let l=a;l.delta.stop_reason&&(i=l.delta.stop_reason),l.delta.usage&&(s=Yt(s,l.delta.usage));break}}s&&(yield{type:"usage",usage:zn(s)}),yield{type:"finish",reason:i??"stop"}}}}De();function Qt(){let t=new Error("aborted");return t.name="AbortError",t}function uo(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Qt()):new Promise((n,r)=>{let o=new de,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(Qt())},e.addEventListener("abort",s,{once:!0}))})}function Je(t={}){let e=t.provider??"dry-run",n=t.model??"dry-run-v1",r=t.latencyMs??0,o=Math.max(1,t.streamChunkSize??16),s=t.respond??(a=>{let l=[...a].reverse().find(c=>c.role==="user");return l?`echo: ${l.content}`:"dry-run: no user message"}),i=t.usage??((a,l)=>{let c=a.reduce((d,u)=>d+u.content.length,0);return{input:{regular:Math.ceil(c/4)},output:{regular:Math.ceil(l.length/4)}}});return{provider:e,model:n,async invoke(a,l){if(await uo(r,l?.signal),l?.signal?.aborted)throw Qt();let c=s(a,l),d=i(a,c);return{content:c,usage:d,finishReason:"stop",model:l?.model??n,provider:e,tier:l?.tier,metadata:{dryRun:!0}}},async*stream(a,l){let c=s(a,l),d=i(a,c),u=Math.ceil(c.length/o)||1,p=r>0?r/u:0;for(let f=0;f<c.length;f+=o){if(l?.signal?.aborted)throw Qt();await uo(p,l?.signal),yield{type:"token",delta:c.slice(f,f+o)}}yield{type:"usage",usage:d},yield{type:"finish",reason:"stop"}}}}he();async function Xt(t){let e=typeof t=="string"?new TextEncoder().encode(t):t,n=await globalThis.crypto.subtle.digest("SHA-256",e),r=new Uint8Array(n),o="";for(let s=0;s<r.length;s++)o+=po[r[s]];return o}var po=new Array(256);for(let t=0;t<256;t++)po[t]=t.toString(16).padStart(2,"0");function Hn(){let t=new Map;return{save(e,n){t.set(e,JSON.parse(JSON.stringify(n)))},load(e){let n=t.get(e);return n===void 0?null:JSON.parse(JSON.stringify(n))},clear(e){t.delete(e)},list(){return[...t.keys()].sort()}}}he();var Wn=class extends Error{constructor(n,r){super(`content-addressed lookup miss in read-strict mode: ${n}`);this.key=n;this.context=r;this.name="ContentAddressedMissError"}};function qn(t){let e=new Set,n=r=>{if(r===null||typeof r!="object")return r;let o=r;if(e.has(o))return{__cycle:!0};e.add(o);try{if(Array.isArray(r))return r.map(n);let s={};for(let i of Object.keys(r).sort())s[i]=n(r[i]);return s}finally{e.delete(o)}};return JSON.stringify(n(t))}function fo(t){let{storage:e,keyContext:n,keyPrefix:r,mode:o="read-write"}=t,s=n??(a=>a);async function i(a){let l=qn(s(a)),c=await Xt(l);return r?`${r}:${c}`:c}return{keyFor:i,async lookup(a){if(o==="write")return;let l=await i(a),c=await e.load(l);if(c==null){if(o==="read-strict")throw new Wn(l,a);return}return c},async store(a,l){if(o==="read")return;let c=await i(a);await e.save(c,l)},async forget(a){if(o==="read"||o==="write"||!e.clear)return;let l=await i(a);await e.clear(l)}}}ne();function mo(t,e={}){let n=e.keyFn??(o=>String(o)),r=new Map;return o=>{let s=n(o),i=r.get(s);if(i)return i;let a=t(o),l;a!=null&&typeof a.then=="function"?l=Promise.resolve(a):a!=null&&typeof a=="object"&&"subscribe"in a&&"cache"in a?l=xe(a):a!=null&&typeof a=="object"&&Symbol.asyncIterator in a?l=(async()=>{let u=a[Symbol.asyncIterator]();try{let{value:p,done:f}=await u.next();if(f)throw new Error("singleFromAny: factory returned empty async iterable");return p}finally{await u.return?.()}})():a!=null&&typeof a=="object"&&Symbol.iterator in a?l=(async()=>{let u=a[Symbol.iterator]();try{let{value:p,done:f}=u.next();if(f)throw new Error("singleFromAny: factory returned empty iterable");return p}finally{u.return?.()}})():l=Promise.resolve(a);let c,d=()=>{r.get(s)===c&&r.delete(s)};return c=l.then(u=>(d(),u),u=>{throw d(),u}),r.set(s,c),c}}ne();De();function go(t){let{storage:e,mode:n="read-write",keyFn:r,keyPrefix:o="llm-replay"}=t,i=fo({storage:e,keyPrefix:o,mode:n==="read-strict"?"read":n,keyContext:({messages:l,opts:c})=>{let{signal:d,keyContext:u,...p}=c??{};return{messages:l,opts:p}}});async function a(l,c){if(r){if(r.length<=1){let u={messages:l,opts:c,context:c?.keyContext},p=await r(u);return`${o}:${p}`}let d=await r(l,c);return`${o}:${d}`}return i.keyFor({messages:l,opts:c})}return{keyFor:a,async lookup(l,c){if(n!=="write"){if(r){let d=await a(l,c),u=await e.load(d);return u??void 0}return i.lookup({messages:l,opts:c})}},async store(l,c,d){if(n!=="read"){if(r){let u=await a(l,c);await e.save(u,d);return}await i.store({messages:l,opts:c},d)}},async forget(l,c){if(!(n==="read"||n==="write")&&e.clear){if(r){let d=await a(l,c);await e.clear(d);return}await i.forget({messages:l,opts:c})}}}}he();le();q();ne();function ve(t,e,n){return{provider:n?.provider??t.provider,model:n?.model??t.model,capabilities:n?.capabilities??t.capabilities?.bind(t),invoke:e.invoke,stream:e.stream}}function Zt(t,e){let{onResp:n,onError:r,name:o}=e;if(t!=null&&typeof t.then=="function"){let c=t;return r?c.then(n).catch(d=>{throw r(d),d}):c.then(n)}if(t!=null&&typeof t=="object"&&"content"in t)return n(t);let s=P(t);if(r){let c=!1;s.subscribe(d=>{for(let u of d){if(c)return;u[0]===C&&(c=!0,r(u[1]))}})}let i,a=!1,l=io(s,c=>{i=n(c),a=!0});return A([l],([c])=>c==null?null:a?i:n(c),{name:o??"adapt/invokeTap"})}function Ye(t){let e=t.endNs??V();return{timestamp:e,wallClock:t.startWallClockNs??Te(),provider:t.provider,model:t.model,tier:t.tier,usage:t.usage,latencyMs:Math.max(0,(e-t.startNs)/1e6),method:t.method,...t.error?{error:t.error}:{}}}function Ce(){return{input:{regular:0},output:{regular:0}}}var ho=Symbol.for("graphrefly.adapter.middlewareLayers");function be(t,e,n){let o=[...n?li(n):[],e];return Object.defineProperty(t,ho,{value:Object.freeze(o),enumerable:!1,writable:!1,configurable:!1}),t}function li(t){let e=t[ho];return Array.isArray(e)?e:[]}var Qe=class extends Error{constructor(n,r){super(`withReplayCache: no cached response for ${r} (key=${n}, mode=read-strict)`);this.key=n;this.method=r}name="ReplayCacheMissError"};function Rt(t,e){let n=e.mode??"read-write",r=e.cacheStreaming??!1,o=e.captureStreamCadence??!1,s=e.replaySpeed??1,i=e.keyPrefix??"llm-replay",a=n==="read"||n==="read-strict",l=go({storage:e.storage,mode:n==="write-only"?"write":n,keyFn:e.keyFn,keyPrefix:i}),c=p=>p<=0?Promise.resolve():new Promise(f=>{new de().start(p,()=>f())}),d=mo(async({messages:p,invokeOpts:f})=>await xe(P(t.invoke(p,f))),{keyFn:({_precomputedKey:p})=>p}),u=ve(t,{async invoke(p,f){let m=await l.keyFor(p,f),h=await l.lookup(p,f);if(h?.response){let y=h.response;return{...y,metadata:{...y.metadata??{},replayCache:"hit"}}}if(n==="read-strict")throw new Qe(m,"invoke");let g=await d({messages:p,invokeOpts:f,_precomputedKey:m});return a||await l.store(p,f,{response:g,storedAtNs:Te()}),g},async*stream(p,f){if(!r){for await(let v of t.stream(p,f))yield v;return}let m=await l.keyFor(p,f),h=await l.lookup(p,f);if(h){let v=h.response;if(h.streamChunks&&h.streamCadenceMs)for(let x=0;x<h.streamChunks.length;x++){let S=h.streamCadenceMs[x]??0,N=s>0?S/s:0;N>0&&await c(N),yield{type:"token",delta:h.streamChunks[x]?.delta??""}}else v.content&&(yield{type:"token",delta:v.content});v.usage&&(yield{type:"usage",usage:v.usage}),yield{type:"finish",reason:v.finishReason??"stop"};return}if(n==="read-strict")throw new Qe(m,"stream");let g="",y,b,T=[],k=[],w;for await(let v of t.stream(p,f)){if(v.type==="token"&&(g+=v.delta,o)){let x=V(),S=w===void 0?0:(x-w)/1e6;k.push(S),w=x,T.push({delta:v.delta})}v.type==="usage"&&(y=v.usage),v.type==="finish"&&(b=v.reason),yield v}if((g||y)&&!a){let x={response:{content:g,usage:y??{input:{regular:0},output:{regular:0}},finishReason:b,model:t.model??f?.model??"",provider:t.provider},storedAtNs:Te(),...o?{streamChunks:T,streamCadenceMs:k}:{}};await l.store(p,f,x)}}});return be(u,"withReplayCache",t),u}var Jn=qn;var di=Qe;function yo(t,e){return{content:"[fallback: no cached response available for this request]",usage:{input:{regular:0},output:{regular:0}},finishReason:"stop",model:e,provider:t,metadata:{degraded:!0,reason:"no-fixture"}}}function bo(t,e,n){return typeof t=="string"?{content:t,usage:{input:{regular:0},output:{regular:0}},finishReason:"stop",model:n,provider:e,metadata:{degraded:!0,reason:"respond"}}:t}async function ui(t,e){if("key"in t)return t.key;let n=Jn({messages:t.messages,opts:t.invokeOpts??{}}),r=await Xt(n);return`${e}:${r}`}function pi(t){let e={response:t.response,storedAtNs:Te()};if("key"in t&&t.stream){let n=t.stream.chunks.filter(r=>r.type==="token");return{...e,streamChunks:n.map(r=>({delta:r.delta})),streamCadenceMs:t.stream.delaysMs??n.map(()=>0)}}return e}function fi(t,e){let n=[];if(t.fixtures!=null&&n.push("fixtures"),t.fixturesStorage!=null&&n.push("fixturesStorage"),n.length>1)throw new TypeError(`fallbackAdapter: \`fixtures\` and \`fixturesStorage\` are mutually exclusive; got both ${n.join(" and ")}. Pick one source. For filesystem directories use the node subpath's \`fallbackAdapter\`.`);if(t.fixtures){let r=Hn(),o=t.fixtures,s=(async()=>{for(let i of o){let a=await ui(i,e);await r.save(a,pi(i))}})();return s.catch(()=>{}),{tier:r,seedReady:s}}return t.fixturesStorage?{tier:t.fixturesStorage,seedReady:Promise.resolve()}:{tier:void 0,seedReady:Promise.resolve()}}function Yn(t={}){let e=t.provider??"fallback",n=t.model??"fallback",r=t.onMiss??"respond",o=t.keyPrefix??"fallback",s=t.record?t.record.adapter:r==="throw"?Je({provider:e,model:n,respond:()=>"[unreachable: read-strict mode throws on miss]"}):{provider:e,model:n,async invoke(d,u){let p=t.respond?t.respond(d,u):yo(e,n);return bo(p,e,n)},async*stream(d,u){let p=t.respond?t.respond(d,u):yo(e,n),f=bo(p,e,n);yield{type:"token",delta:f.content},f.usage&&(yield{type:"usage",usage:f.usage}),yield{type:"finish",reason:f.finishReason??"stop"}}},i,a=Promise.resolve();if(t.record){if(!t.record.storage)throw new TypeError("fallbackAdapter: `record.storage` is required in record mode. For filesystem `record.dir` convenience, use the node subpath's `fallbackAdapter`.");i=t.record.storage}else{let d=fi(t,o);i=d.tier??Hn(),a=d.seedReady}let l=t.record?"read-write":r==="throw"?"read-strict":"read",c=Rt(s,{storage:i,mode:l,keyPrefix:o,cacheStreaming:!0,captureStreamCadence:!0,replaySpeed:t.replaySpeed,...t.keyFn?{keyFn:t.keyFn}:{}});return{provider:e,model:n,capabilities:c.capabilities?.bind(c),async invoke(d,u){return await a,c.invoke(d,u)},async*stream(d,u){await a;for await(let p of c.stream(d,u))yield p}}}he();function Qn(t={}){return t.sdk?yi(t):hi(t)}function en(t,e){let n=[],r=[];e?.systemPrompt&&n.push(e.systemPrompt);for(let i of t){if(i.role==="system"){n.push(i.content);continue}if(i.role==="tool"){r.push({role:"user",parts:[{functionResponse:{name:i.name??i.toolCallId??"tool",response:{result:i.content}}}]});continue}if(i.role==="assistant"&&i.toolCalls&&i.toolCalls.length>0){let a=[];i.content&&a.push({text:i.content});for(let l of i.toolCalls)a.push({functionCall:{name:l.name,args:l.arguments}});r.push({role:"model",parts:a});continue}r.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let o={contents:r};n.length>0&&(o.systemInstruction={role:"system",parts:[{text:n.join(`
|
|
4
|
+
`):void 0,chat:r}}function ni(t){if(t.role==="tool")return{role:"user",content:[{type:"tool_result",tool_use_id:t.toolCallId,content:t.content}]};if(t.role==="assistant"&&t.toolCalls&&t.toolCalls.length>0){let e=[];t.content&&e.push({type:"text",text:t.content});for(let n of t.toolCalls)e.push({type:"tool_use",id:n.id,name:n.name,input:n.arguments});return{role:"assistant",content:e}}return{role:t.role,content:t.content}}function ri(t){return{name:t.name,description:t.description,input_schema:t.parameters}}function Vt(t,e){if(!t)return{...e};let n={...t};return e.input_tokens!=null&&(n.input_tokens=e.input_tokens),e.output_tokens!=null&&(n.output_tokens=e.output_tokens),e.cache_read_input_tokens!=null&&(n.cache_read_input_tokens=e.cache_read_input_tokens),e.cache_creation_input_tokens!=null&&(n.cache_creation_input_tokens=e.cache_creation_input_tokens),e.cache_creation&&(n.cache_creation={...t.cache_creation??{},...e.cache_creation}),e.server_tool_use&&(n.server_tool_use={...t.server_tool_use??{},...e.server_tool_use}),n}function Dn(t){let e={input:{regular:t?.input_tokens??0},output:{regular:t?.output_tokens??0},raw:t};return t?.cache_read_input_tokens&&(e.input.cacheRead=t.cache_read_input_tokens),t?.cache_creation?(t.cache_creation.ephemeral_5m_input_tokens&&(e.input.cacheWrite5m=t.cache_creation.ephemeral_5m_input_tokens),t.cache_creation.ephemeral_1h_input_tokens&&(e.input.cacheWrite1h=t.cache_creation.ephemeral_1h_input_tokens)):t?.cache_creation_input_tokens&&(e.input.cacheWrite5m=t.cache_creation_input_tokens),t?.server_tool_use?.web_search_requests&&(e.auxiliary={webSearchRequests:t.server_tool_use.web_search_requests}),e}function to(t,e){let n=[],r=[];for(let o of t.content)if(o.type==="text"&&typeof o.text=="string")n.push(o.text);else if(o.type==="tool_use"){let s=o;r.push({id:s.id,name:s.name,arguments:s.input??{}})}return{content:n.join(""),toolCalls:r.length>0?r:void 0,usage:Dn(t.usage),finishReason:t.stop_reason,latencyMs:e,model:t.model,provider:"anthropic"}}function oi(t){let e=t.apiKey??globalThis.process?.env?.ANTHROPIC_API_KEY,n=t.baseURL??"https://api.anthropic.com",r=t.anthropicVersion??"2023-06-01",o=t.fetchImpl??fetch,s=()=>{if(!e)throw new Error("anthropicAdapter: apiKey required for invoke/stream (or provide opts.sdk)");return{"x-api-key":e,"anthropic-version":r,"content-type":"application/json",...t.headers??{}}};return{provider:"anthropic",model:t.model,async invoke(i,a){let d=Bt(i,a,t.model,!1),u=F(),l=await o(`${n}/v1/messages`,{method:"POST",headers:s(),body:JSON.stringify(d),signal:a?.signal});if(!l.ok)throw await Le(l,"Anthropic");let c=await l.json(),p=Math.max(0,(F()-u)/1e6);return to(c,p)},async*stream(i,a){let d=Bt(i,a,t.model,!0),u=await o(`${n}/v1/messages`,{method:"POST",headers:{...s(),accept:"text/event-stream"},body:JSON.stringify(d),signal:a?.signal});if(!u.ok)throw await Le(u,"Anthropic");if(!u.body)throw new Error("anthropicAdapter: streaming response has no body");let l,c,p=new Map;for await(let f of st(u.body,{signal:a?.signal})){let m=f.data;if(!m)continue;let h;try{h=JSON.parse(m)}catch{continue}switch(h.type){case"message_start":{l=Vt(l,h.message.usage);break}case"content_block_start":{let g=h,y=g.content_block;y.type==="tool_use"&&(p.set(g.index,{id:String(y.id??""),name:String(y.name??""),argBuf:""}),yield{type:"tool-call-delta",delta:{id:String(y.id??""),name:String(y.name??"")}});break}case"content_block_delta":{let g=h,y=g.delta;if(y.type==="text_delta"&&typeof y.text=="string")yield{type:"token",delta:y.text};else if(y.type==="input_json_delta"&&typeof y.partial_json=="string"){let b=p.get(g.index);b&&(b.argBuf+=y.partial_json),yield{type:"tool-call-delta",delta:{argumentsDelta:y.partial_json}}}else y.type==="thinking_delta"&&typeof y.thinking=="string"&&(yield{type:"thinking",delta:y.thinking});break}case"message_delta":{let g=h;g.delta.stop_reason&&(c=g.delta.stop_reason),g.delta.usage&&(l=Vt(l,g.delta.usage));break}case"message_stop":break}}l&&(yield{type:"usage",usage:Dn(l)}),yield{type:"finish",reason:c??"stop"}}}}function si(t){let e=t.sdk;if(!e)throw new Error("sdkBackedAnthropic: sdk instance required");return{provider:"anthropic",model:t.model,async invoke(n,r){let o=Bt(n,r,t.model,!1),s=F(),i=await e.messages.create(o,{signal:r?.signal}),a=Math.max(0,(F()-s)/1e6);return to(i,a)},async*stream(n,r){if(!e.messages.stream)throw new Error("sdkBackedAnthropic: SDK instance does not expose .messages.stream");let o=Bt(n,r,t.model,!0),s,i;for await(let a of e.messages.stream(o,{signal:r?.signal}))switch(a.type){case"message_start":s=Vt(s,a.message.usage);break;case"content_block_delta":{let d=a.delta;d?.type==="text_delta"&&typeof d.text=="string"?yield{type:"token",delta:d.text}:d?.type==="input_json_delta"&&typeof d.partial_json=="string"?yield{type:"tool-call-delta",delta:{argumentsDelta:d.partial_json}}:d?.type==="thinking_delta"&&typeof d.thinking=="string"&&(yield{type:"thinking",delta:d.thinking});break}case"message_delta":{let d=a;d.delta.stop_reason&&(i=d.delta.stop_reason),d.delta.usage&&(s=Vt(s,d.delta.usage));break}}s&&(yield{type:"usage",usage:Dn(s)}),yield{type:"finish",reason:i??"stop"}}}}Ce();function Kt(){let t=new Error("aborted");return t.name="AbortError",t}function no(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Kt()):new Promise((n,r)=>{let o=new re,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(Kt())},e.addEventListener("abort",s,{once:!0}))})}function He(t={}){let e=t.provider??"dry-run",n=t.model??"dry-run-v1",r=t.latencyMs??0,o=Math.max(1,t.streamChunkSize??16),s=t.respond??(a=>{let d=[...a].reverse().find(u=>u.role==="user");return d?`echo: ${d.content}`:"dry-run: no user message"}),i=t.usage??((a,d)=>{let u=a.reduce((l,c)=>l+c.content.length,0);return{input:{regular:Math.ceil(u/4)},output:{regular:Math.ceil(d.length/4)}}});return{provider:e,model:n,async invoke(a,d){if(await no(r,d?.signal),d?.signal?.aborted)throw Kt();let u=s(a,d),l=i(a,u);return{content:u,usage:l,finishReason:"stop",model:d?.model??n,provider:e,tier:d?.tier,metadata:{dryRun:!0}}},async*stream(a,d){let u=s(a,d),l=i(a,u),c=Math.ceil(u.length/o)||1,p=r>0?r/c:0;for(let f=0;f<u.length;f+=o){if(d?.signal?.aborted)throw Kt();await no(p,d?.signal),yield{type:"token",delta:u.slice(f,f+o)}}yield{type:"usage",usage:l},yield{type:"finish",reason:"stop"}}}}ce();async function Ut(t){let e=typeof t=="string"?new TextEncoder().encode(t):t,n=await globalThis.crypto.subtle.digest("SHA-256",e),r=new Uint8Array(n),o="";for(let s=0;s<r.length;s++)o+=ro[r[s]];return o}var ro=new Array(256);for(let t=0;t<256;t++)ro[t]=t.toString(16).padStart(2,"0");function In(){let t=new Map;return{save(e,n){t.set(e,JSON.parse(JSON.stringify(n)))},load(e){let n=t.get(e);return n===void 0?null:JSON.parse(JSON.stringify(n))},clear(e){t.delete(e)},list(){return[...t.keys()].sort()}}}ce();var Pn=class extends Error{constructor(n,r){super(`content-addressed lookup miss in read-strict mode: ${n}`);this.key=n;this.context=r;this.name="ContentAddressedMissError"}};function Gn(t){let e=new Set,n=r=>{if(r===null||typeof r!="object")return r;let o=r;if(e.has(o))return{__cycle:!0};e.add(o);try{if(Array.isArray(r))return r.map(n);let s={};for(let i of Object.keys(r).sort())s[i]=n(r[i]);return s}finally{e.delete(o)}};return JSON.stringify(n(t))}function oo(t){let{storage:e,keyContext:n,keyPrefix:r,mode:o="read-write"}=t,s=n??(a=>a);async function i(a){let d=Gn(s(a)),u=await Ut(d);return r?`${r}:${u}`:u}return{keyFor:i,async lookup(a){if(o==="write")return;let d=await i(a),u=await e.load(d);if(u==null){if(o==="read-strict")throw new Pn(d,a);return}return u},async store(a,d){if(o==="read")return;let u=await i(a);await e.save(u,d)},async forget(a){if(o==="read"||o==="write"||!e.clear)return;let d=await i(a);await e.clear(d)}}}J();function so(t,e={}){let n=e.keyFn??(o=>String(o)),r=new Map;return o=>{let s=n(o),i=r.get(s);if(i)return i;let a=t(o),d;a!=null&&typeof a.then=="function"?d=Promise.resolve(a):a!=null&&typeof a=="object"&&"subscribe"in a&&"cache"in a?d=ve(a):a!=null&&typeof a=="object"&&Symbol.asyncIterator in a?d=(async()=>{let c=a[Symbol.asyncIterator]();try{let{value:p,done:f}=await c.next();if(f)throw new Error("singleFromAny: factory returned empty async iterable");return p}finally{await c.return?.()}})():a!=null&&typeof a=="object"&&Symbol.iterator in a?d=(async()=>{let c=a[Symbol.iterator]();try{let{value:p,done:f}=c.next();if(f)throw new Error("singleFromAny: factory returned empty iterable");return p}finally{c.return?.()}})():d=Promise.resolve(a);let u,l=()=>{r.get(s)===u&&r.delete(s)};return u=d.then(c=>(l(),c),c=>{throw l(),c}),r.set(s,u),u}}J();Ce();function io(t){let{storage:e,mode:n="read-write",keyFn:r,keyPrefix:o="llm-replay"}=t,i=oo({storage:e,keyPrefix:o,mode:n==="read-strict"?"read":n,keyContext:({messages:d,opts:u})=>{let{signal:l,keyContext:c,...p}=u??{};return{messages:d,opts:p}}});async function a(d,u){if(r){if(r.length<=1){let c={messages:d,opts:u,context:u?.keyContext},p=await r(c);return`${o}:${p}`}let l=await r(d,u);return`${o}:${l}`}return i.keyFor({messages:d,opts:u})}return{keyFor:a,async lookup(d,u){if(n!=="write"){if(r){let l=await a(d,u),c=await e.load(l);return c??void 0}return i.lookup({messages:d,opts:u})}},async store(d,u,l){if(n!=="read"){if(r){let c=await a(d,u);await e.save(c,l);return}await i.store({messages:d,opts:u},l)}},async forget(d,u){if(!(n==="read"||n==="write")&&e.clear){if(r){let l=await a(d,u);await e.clear(l);return}await i.forget({messages:d,opts:u})}}}}ce();ne();U();J();function fe(t,e,n){return{provider:n?.provider??t.provider,model:n?.model??t.model,capabilities:n?.capabilities??t.capabilities?.bind(t),invoke:e.invoke,stream:e.stream}}function zt(t,e){let{onResp:n,onError:r,name:o}=e;if(t!=null&&typeof t.then=="function"){let u=t;return r?u.then(n).catch(l=>{throw r(l),l}):u.then(n)}if(t!=null&&typeof t=="object"&&"content"in t)return n(t);let s=P(t);if(r){let u=!1;s.subscribe(l=>{for(let c of l){if(u)return;c[0]===O&&(u=!0,r(c[1]))}})}let i,a=!1,d=Xr(s,u=>{i=n(u),a=!0});return E([d],([u])=>u==null?null:a?i:n(u),{name:o??"adapt/invokeTap"})}function We(t){let e=t.endNs??F();return{timestamp:e,wallClock:t.startWallClockNs??pe(),provider:t.provider,model:t.model,tier:t.tier,usage:t.usage,latencyMs:Math.max(0,(e-t.startNs)/1e6),method:t.method,...t.error?{error:t.error}:{}}}function Ae(){return{input:{regular:0},output:{regular:0}}}var ao=Symbol.for("graphrefly.adapter.middlewareLayers");function le(t,e,n){let o=[...n?ii(n):[],e];return Object.defineProperty(t,ao,{value:Object.freeze(o),enumerable:!1,writable:!1,configurable:!1}),t}function ii(t){let e=t[ao];return Array.isArray(e)?e:[]}var qe=class extends Error{constructor(n,r){super(`withReplayCache: no cached response for ${r} (key=${n}, mode=read-strict)`);this.key=n;this.method=r}name="ReplayCacheMissError"};function Tt(t,e){let n=e.mode??"read-write",r=e.cacheStreaming??!1,o=e.captureStreamCadence??!1,s=e.replaySpeed??1,i=e.keyPrefix??"llm-replay",a=n==="read"||n==="read-strict",d=io({storage:e.storage,mode:n==="write-only"?"write":n,keyFn:e.keyFn,keyPrefix:i}),u=p=>p<=0?Promise.resolve():new Promise(f=>{new re().start(p,()=>f())}),l=so(async({messages:p,invokeOpts:f})=>await ve(P(t.invoke(p,f))),{keyFn:({_precomputedKey:p})=>p}),c=fe(t,{async invoke(p,f){let m=await d.keyFor(p,f),h=await d.lookup(p,f);if(h?.response){let y=h.response;return{...y,metadata:{...y.metadata??{},replayCache:"hit"}}}if(n==="read-strict")throw new qe(m,"invoke");let g=await l({messages:p,invokeOpts:f,_precomputedKey:m});return a||await d.store(p,f,{response:g,storedAtNs:pe()}),g},async*stream(p,f){if(!r){for await(let T of t.stream(p,f))yield T;return}let m=await d.keyFor(p,f),h=await d.lookup(p,f);if(h){let T=h.response;if(h.streamChunks&&h.streamCadenceMs)for(let x=0;x<h.streamChunks.length;x++){let S=h.streamCadenceMs[x]??0,N=s>0?S/s:0;N>0&&await u(N),yield{type:"token",delta:h.streamChunks[x]?.delta??""}}else T.content&&(yield{type:"token",delta:T.content});T.usage&&(yield{type:"usage",usage:T.usage}),yield{type:"finish",reason:T.finishReason??"stop"};return}if(n==="read-strict")throw new qe(m,"stream");let g="",y,b,v=[],k=[],w;for await(let T of t.stream(p,f)){if(T.type==="token"&&(g+=T.delta,o)){let x=F(),S=w===void 0?0:(x-w)/1e6;k.push(S),w=x,v.push({delta:T.delta})}T.type==="usage"&&(y=T.usage),T.type==="finish"&&(b=T.reason),yield T}if((g||y)&&!a){let x={response:{content:g,usage:y??{input:{regular:0},output:{regular:0}},finishReason:b,model:t.model??f?.model??"",provider:t.provider},storedAtNs:pe(),...o?{streamChunks:v,streamCadenceMs:k}:{}};await d.store(p,f,x)}}});return le(c,"withReplayCache",t),c}var $n=Gn;var ai=qe;function uo(t,e){return{content:"[fallback: no cached response available for this request]",usage:{input:{regular:0},output:{regular:0}},finishReason:"stop",model:e,provider:t,metadata:{degraded:!0,reason:"no-fixture"}}}function lo(t,e,n){return typeof t=="string"?{content:t,usage:{input:{regular:0},output:{regular:0}},finishReason:"stop",model:n,provider:e,metadata:{degraded:!0,reason:"respond"}}:t}async function ui(t,e){if("key"in t)return t.key;let n=$n({messages:t.messages,opts:t.invokeOpts??{}}),r=await Ut(n);return`${e}:${r}`}function di(t){let e={response:t.response,storedAtNs:pe()};if("key"in t&&t.stream){let n=t.stream.chunks.filter(r=>r.type==="token");return{...e,streamChunks:n.map(r=>({delta:r.delta})),streamCadenceMs:t.stream.delaysMs??n.map(()=>0)}}return e}function li(t,e){let n=[];if(t.fixtures!=null&&n.push("fixtures"),t.fixturesStorage!=null&&n.push("fixturesStorage"),n.length>1)throw new TypeError(`fallbackAdapter: \`fixtures\` and \`fixturesStorage\` are mutually exclusive; got both ${n.join(" and ")}. Pick one source. For filesystem directories use the node subpath's \`fallbackAdapter\`.`);if(t.fixtures){let r=In(),o=t.fixtures,s=(async()=>{for(let i of o){let a=await ui(i,e);await r.save(a,di(i))}})();return s.catch(()=>{}),{tier:r,seedReady:s}}return t.fixturesStorage?{tier:t.fixturesStorage,seedReady:Promise.resolve()}:{tier:void 0,seedReady:Promise.resolve()}}function Fn(t={}){let e=t.provider??"fallback",n=t.model??"fallback",r=t.onMiss??"respond",o=t.keyPrefix??"fallback",s=t.record?t.record.adapter:r==="throw"?He({provider:e,model:n,respond:()=>"[unreachable: read-strict mode throws on miss]"}):{provider:e,model:n,async invoke(l,c){let p=t.respond?t.respond(l,c):uo(e,n);return lo(p,e,n)},async*stream(l,c){let p=t.respond?t.respond(l,c):uo(e,n),f=lo(p,e,n);yield{type:"token",delta:f.content},f.usage&&(yield{type:"usage",usage:f.usage}),yield{type:"finish",reason:f.finishReason??"stop"}}},i,a=Promise.resolve();if(t.record){if(!t.record.storage)throw new TypeError("fallbackAdapter: `record.storage` is required in record mode. For filesystem `record.dir` convenience, use the node subpath's `fallbackAdapter`.");i=t.record.storage}else{let l=li(t,o);i=l.tier??In(),a=l.seedReady}let d=t.record?"read-write":r==="throw"?"read-strict":"read",u=Tt(s,{storage:i,mode:d,keyPrefix:o,cacheStreaming:!0,captureStreamCadence:!0,replaySpeed:t.replaySpeed,...t.keyFn?{keyFn:t.keyFn}:{}});return{provider:e,model:n,capabilities:u.capabilities?.bind(u),async invoke(l,c){return await a,u.invoke(l,c)},async*stream(l,c){await a;for await(let p of u.stream(l,c))yield p}}}ce();function jn(t={}){return t.sdk?mi(t):fi(t)}function Ht(t,e){let n=[],r=[];e?.systemPrompt&&n.push(e.systemPrompt);for(let i of t){if(i.role==="system"){n.push(i.content);continue}if(i.role==="tool"){r.push({role:"user",parts:[{functionResponse:{name:i.name??i.toolCallId??"tool",response:{result:i.content}}}]});continue}if(i.role==="assistant"&&i.toolCalls&&i.toolCalls.length>0){let a=[];i.content&&a.push({text:i.content});for(let d of i.toolCalls)a.push({functionCall:{name:d.name,args:d.arguments}});r.push({role:"model",parts:a});continue}r.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let o={contents:r};n.length>0&&(o.systemInstruction={role:"system",parts:[{text:n.join(`
|
|
5
5
|
|
|
6
|
-
`)}]});let s={};return e?.maxTokens!=null&&(s.maxOutputTokens=e.maxTokens),e?.temperature!=null&&(s.temperature=e.temperature),e?.maxReasoningTokens!=null&&(s.thinkingConfig={thinkingBudget:e.maxReasoningTokens}),Object.keys(s).length>0&&(o.generationConfig=s),e?.tools&&e.tools.length>0&&(o.tools=[{functionDeclarations:e.tools.map(mi)}]),e?.providerExtras&&Object.assign(o,e.providerExtras),o}function mi(t){return{name:t.name,description:t.description,parameters:t.parameters}}function Xn(t){let e={input:{regular:0},output:{regular:0},raw:t};if(!t)return e;let n=t.promptTokenCount??0,r=t.cachedContentTokenCount??0;if(e.input.regular=Math.max(0,n-r),r>0&&(e.input.cacheRead=r),t.toolUsePromptTokenCount&&(e.input.toolUse=t.toolUsePromptTokenCount),t.promptTokensDetails)for(let o of t.promptTokensDetails){let s=o.modality?.toLowerCase();s==="image"?e.input.image=(e.input.image??0)+o.tokenCount:s==="audio"?e.input.audio=(e.input.audio??0)+o.tokenCount:s==="video"&&(e.input.video=(e.input.video??0)+o.tokenCount)}return e.output.regular=t.candidatesTokenCount??0,t.thoughtsTokenCount&&(e.output.reasoning=t.thoughtsTokenCount),e}function To(t,e){let n=t.candidates?.[0],r=n?.content?.parts??[],o=[],s=[],i=0;for(let a of r)typeof a.text=="string"&&o.push(a.text),a.functionCall&&s.push({id:`${a.functionCall.name}-${i++}`,name:a.functionCall.name,arguments:a.functionCall.args??{}});return{content:o.join(""),toolCalls:s.length>0?s:void 0,usage:Xn(t.usageMetadata),finishReason:n?.finishReason,latencyMs:e,model:t.modelVersion,provider:"google"}}function gi(t){if(t.apiKey)return t.apiKey;let e=globalThis.process?.env;return e?.GOOGLE_API_KEY??e?.GEMINI_API_KEY}function hi(t){let e=t.baseURL??"https://generativelanguage.googleapis.com/v1beta",n=t.fetchImpl??fetch,r=s=>{let i=s?.model??t.model;if(!i)throw new Error("googleAdapter: model must be set via options.model or invokeOpts.model");return i},o=()=>{let s=gi(t);if(!s)throw new Error("googleAdapter: apiKey required for invoke/stream");return`key=${encodeURIComponent(s)}`};return{provider:"google",model:t.model,async invoke(s,i){let a=r(i),l=en(s,i),c=V(),d=`${e}/models/${encodeURIComponent(a)}:generateContent?${o()}`,u=await n(d,{method:"POST",headers:{"content-type":"application/json",...t.headers??{}},body:JSON.stringify(l),signal:i?.signal});if(!u.ok)throw await Ie(u,"Google");let p=await u.json(),f=Math.max(0,(V()-c)/1e6);return To(p,f)},async*stream(s,i){let a=r(i),l=en(s,i),c=`${e}/models/${encodeURIComponent(a)}:streamGenerateContent?alt=sse&${o()}`,d=await n(c,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",...t.headers??{}},body:JSON.stringify(l),signal:i?.signal});if(!d.ok)throw await Ie(d,"Google");if(!d.body)throw new Error("googleAdapter: streaming response has no body");let u,p;for await(let f of lt(d.body,{signal:i?.signal})){if(!f.data)continue;let m;try{m=JSON.parse(f.data)}catch{continue}let h=m.candidates?.[0];for(let g of h?.content?.parts??[])typeof g.text=="string"&&(g.thought?yield{type:"thinking",delta:g.text}:yield{type:"token",delta:g.text}),g.functionCall&&(yield{type:"tool-call-delta",delta:{name:g.functionCall.name,argumentsDelta:JSON.stringify(g.functionCall.args??{})}});h?.finishReason&&(p=h.finishReason),m.usageMetadata&&(u=m.usageMetadata)}u&&(yield{type:"usage",usage:Xn(u)}),yield{type:"finish",reason:p??"stop"}}}}function yi(t){let e=t.sdk;if(!e)throw new Error("sdkBackedGoogle: sdk instance required");return{provider:"google",model:t.model,async invoke(n,r){let o=en(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=V(),a=await e.models.generateContent({...o,model:s},{signal:r?.signal}),l=Math.max(0,(V()-i)/1e6);return To(a,l)},async*stream(n,r){if(!e.models.generateContentStream)throw new Error("sdkBackedGoogle: SDK instance does not expose generateContentStream");let o=en(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i,a;for await(let l of e.models.generateContentStream({...o,model:s},{signal:r?.signal})){let c=l.candidates?.[0];for(let d of c?.content?.parts??[])typeof d.text=="string"&&(d.thought?yield{type:"thinking",delta:d.text}:yield{type:"token",delta:d.text}),d.functionCall&&(yield{type:"tool-call-delta",delta:{name:d.functionCall.name,argumentsDelta:JSON.stringify(d.functionCall.args??{})}});c?.finishReason&&(a=c.finishReason),l.usageMetadata&&(i=l.usageMetadata)}i&&(yield{type:"usage",usage:Xn(i)}),yield{type:"finish",reason:a??"stop"}}}}he();var bi={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 Zn(t={}){return t.sdk?xi(t):ki(t)}function tn(t,e,n,r,o){let s=e?.model??n;if(!s)throw new Error("openAICompatAdapter: model must be set via options.model or invokeOpts.model");let i=t.map(Ti);e?.systemPrompt&&!t.some(l=>l.role==="system")&&i.unshift({role:"system",content:e.systemPrompt});let a={model:s,messages:i};return e?.maxTokens!=null&&(a.max_tokens=e.maxTokens),e?.temperature!=null&&(a.temperature=e.temperature),e?.tools&&e.tools.length>0&&(a.tools=e.tools.map(vi)),e?.maxReasoningTokens!=null&&(a.reasoning={max_tokens:e.maxReasoningTokens}),r&&(a.stream=!0,a.stream_options={include_usage:!0}),o&&Object.assign(a,o),e?.providerExtras&&Object.assign(a,e.providerExtras),a}function Ti(t){return t.role==="tool"?{role:"tool",tool_call_id:t.toolCallId,content:t.content}:t.role==="assistant"&&t.toolCalls&&t.toolCalls.length>0?{role:"assistant",content:t.content||null,tool_calls:t.toolCalls.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.arguments)}}))}:{role:t.role,content:t.content}}function vi(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}}function er(t){let e={input:{regular:0},output:{regular:0},raw:t};if(!t)return e;let n=t.prompt_tokens??0,r=t.prompt_tokens_details?.cached_tokens??0;t.prompt_cache_hit_tokens!=null?(r=t.prompt_cache_hit_tokens,e.input.regular=t.prompt_cache_miss_tokens??Math.max(0,n-r)):e.input.regular=Math.max(0,n-r),r>0&&(e.input.cacheRead=r),t.prompt_tokens_details?.audio_tokens&&(e.input.audio=t.prompt_tokens_details.audio_tokens);let o=t.completion_tokens??0,s=t.completion_tokens_details?.reasoning_tokens??0;return e.output.regular=Math.max(0,o-s),s>0&&(e.output.reasoning=s),t.completion_tokens_details?.audio_tokens&&(e.output.audio=t.completion_tokens_details.audio_tokens),t.completion_tokens_details?.accepted_prediction_tokens&&(e.output.predictionAccepted=t.completion_tokens_details.accepted_prediction_tokens),t.completion_tokens_details?.rejected_prediction_tokens&&(e.output.predictionRejected=t.completion_tokens_details.rejected_prediction_tokens),e}function vo(t,e,n){let r=t.choices[0],o=r?.message,s=o?.content??"",i=(o?.tool_calls??[]).map(a=>({id:a.id,name:a.function.name,arguments:wi(a.function.arguments)}));return{content:s,toolCalls:i.length>0?i:void 0,usage:er(t.usage),finishReason:r?.finish_reason,latencyMs:e,model:t.model,provider:n}}function wi(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!=null?e:{_raw:t}}catch{return{_raw:t}}}function wo(t){let e=t.preset??"openai",n=bi[e],r=t.baseURL??n.baseURL,o=t.provider??n.provider,s=n.apiKeyEnv,i=t.apiKey??(s?globalThis.process?.env?.[s]:void 0);return{provider:o,baseURL:r,apiKey:i}}function ki(t){let{provider:e,baseURL:n,apiKey:r}=wo(t),o=t.fetchImpl??fetch,s=e!=="ollama",i=()=>{let a={"content-type":"application/json",...t.headers??{}};if(s){if(!r)throw new Error(`openAICompatAdapter[${e}]: apiKey required for invoke/stream`);a.authorization=`Bearer ${r}`}return a};return{provider:e,model:t.model,async invoke(a,l){let c=tn(a,l,t.model,!1,t.bodyExtras),d=V(),u=await o(`${n}/chat/completions`,{method:"POST",headers:i(),body:JSON.stringify(c),signal:l?.signal});if(!u.ok)throw await Ie(u,e);let p=await u.json(),f=Math.max(0,(V()-d)/1e6);return vo(p,f,e)},async*stream(a,l){let c=tn(a,l,t.model,!0,t.bodyExtras),d=await o(`${n}/chat/completions`,{method:"POST",headers:{...i(),accept:"text/event-stream"},body:JSON.stringify(c),signal:l?.signal});if(!d.ok)throw await Ie(d,e);if(!d.body)throw new Error(`openAICompatAdapter[${e}]: streaming response has no body`);let u,p;for await(let f of lt(d.body,{signal:l?.signal})){if(!f.data||f.data==="[DONE]")continue;let m;try{m=JSON.parse(f.data)}catch{continue}let h=m.choices;if(h){let g=h[0];if(g?.delta?.content&&(yield{type:"token",delta:g.delta.content}),g?.delta?.reasoning_content&&(yield{type:"thinking",delta:g.delta.reasoning_content}),g?.delta?.tool_calls)for(let y of g.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:y.id,name:y.function?.name,argumentsDelta:y.function?.arguments}};g?.finish_reason&&(p=g.finish_reason)}m.usage&&(u=m.usage,yield{type:"usage",usage:er(u)})}yield{type:"finish",reason:p??"stop"}}}}function xi(t){let e=t.sdk;if(!e)throw new Error("sdkBackedOpenAI: sdk instance required");let{provider:n}=wo(t);return{provider:n,model:t.model,async invoke(r,o){let s=tn(r,o,t.model,!1,t.bodyExtras),i=V(),a=await e.chat.completions.create(s,{signal:o?.signal}),l=Math.max(0,(V()-i)/1e6);return vo(a,l,n)},async*stream(r,o){let s=tn(r,o,t.model,!0,t.bodyExtras),i=await e.chat.completions.create(s,{signal:o?.signal}),a,l;for await(let c of i){let d=c.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&&(l=p.finish_reason)}let u=c.usage;u&&(a=u,yield{type:"usage",usage:er(u)})}yield{type:"finish",reason:l??"stop"}}}}function Ri(t){switch(t.provider){case"anthropic":{let e={apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return Un(e)}case"google":{let e={apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return Qn(e)}case"dry-run":{let e={model:t.model,...t.extras};return Je(e)}case"fallback":{let e={provider:t.provider,model:t.model,...t.extras};return Yn(e)}case"openai":case"openrouter":case"groq":case"ollama":case"deepseek":case"xai":{let e={preset:t.provider,apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,bodyExtras:t.bodyExtras,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return Zn(e)}default:{let e=t.provider;throw new Error(`createAdapter: unknown provider: ${String(e)}`)}}}he();q();Re();le();q();var tr=class{_version=0;_maxSize;_buf;_head=0;_size=0;constructor(e,n){if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(this._maxSize=n,n!==void 0){if(this._buf=new Array(n),e&&e.length>0){let r=Math.min(e.length,n),o=e.length-r;for(let s=0;s<r;s++)this._buf[s]=e[o+s];this._size=r}}else this._buf=e?[...e]:[],this._size=this._buf.length}get version(){return this._version}get size(){return this._size}at(e){if(!Number.isInteger(e))return;let n=e>=0?e:this._size+e;if(!(n<0||n>=this._size))return this._maxSize!==void 0?this._buf[(this._head+n)%this._maxSize]:this._buf[n]}append(e){this._rawAppend(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._maxSize!==void 0&&e.length>this._maxSize?e.length-this._maxSize:0;for(let r=n;r<e.length;r++)this._rawAppend(e[r]);this._version+=1}clear(){if(this._size===0)return 0;let e=this._size;if(this._maxSize===void 0)this._buf.length=0;else for(let n=0;n<e;n++)this._buf[(this._head+n)%this._maxSize]=void 0;return this._head=0,this._size=0,this._version+=1,e}trimHead(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`trimHead: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return 0;let n=Math.min(e,this._size);if(this._maxSize===void 0)this._buf.splice(0,n);else{for(let r=0;r<n;r++)this._buf[(this._head+r)%this._maxSize]=void 0;this._head=(this._head+n)%this._maxSize}return this._size-=n,this._version+=1,n}slice(e,n){if(!Number.isInteger(e)||e<0)throw new RangeError(`slice: start must be a non-negative integer (got ${e})`);if(n!==void 0&&(!Number.isInteger(n)||n<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${n})`);let r=n===void 0?this._size:Math.min(Math.max(n,0),this._size),o=Math.min(e,this._size);if(o>=r)return[];let s=r-o;if(this._maxSize===void 0)return this._buf.slice(o,r);let i=new Array(s);for(let a=0;a<s;a++)i[a]=this._buf[(this._head+o+a)%this._maxSize];return i}tail(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`tail: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return[];let n=Math.min(e,this._size);return this.slice(this._size-n,this._size)}toArray(){if(this._maxSize===void 0)return[...this._buf];let e=new Array(this._size);for(let n=0;n<this._size;n++)e[n]=this._buf[(this._head+n)%this._maxSize];return e}_rawAppend(e){if(this._maxSize===void 0){this._buf.push(e),this._size=this._buf.length;return}this._size<this._maxSize?(this._buf[(this._head+this._size)%this._maxSize]=e,this._size+=1):(this._buf[this._head]=e,this._head=(this._head+1)%this._maxSize)}};function ko(t){return t.subscribe(()=>{})}var Si=64;function $e(t,e={}){let{name:n,maxSize:r,versioning:o,backend:s}=e,i=s??new tr(t,r),a=O(i.toArray(),{name:n,describeKind:"state",equals:(m,h)=>m===h,...o!=null?{versioning:o}:{}});function l(){let m=i.toArray();re(()=>{a.down([[J]]),a.down([[I,m]])})}let c=new Map,d=new Map;function u(m,h){return`${m}:${h===void 0?"END":h}`}function p(m){if(m.size<Si)return;let h=m.keys().next();if(h.done)return;let g=m.get(h.value);g!==void 0&&g.dispose(),m.delete(h.value)}function f(m){let h=i.version;try{return m()}finally{i.version!==h&&l()}}return{entries:a,get size(){return i.size},at(m){return i.at(m)},append(m){f(()=>i.append(m))},appendMany(m){m.length!==0&&f(()=>i.appendMany(m))},clear(){f(()=>i.clear())},trimHead(m){f(()=>i.trimHead(m))},tail(m){if(!Number.isInteger(m)||m<0)throw new RangeError(`tail: n must be a non-negative integer (got ${m})`);let h=c.get(m);if(h!==void 0)return c.delete(m),c.set(m,h),h.node;p(c);let g=A([a],([b])=>{let T=b;return m===0||T.length===0?[]:T.slice(Math.max(0,T.length-m))},{initial:i.tail(m),describeKind:"derived"}),y=ko(g);return c.set(m,{node:g,dispose:y}),g},slice(m,h){if(!Number.isInteger(m)||m<0)throw new RangeError(`slice: start must be a non-negative integer (got ${m})`);if(h!==void 0&&(!Number.isInteger(h)||h<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${h})`);let g=u(m,h),y=d.get(g);if(y!==void 0)return d.delete(g),d.set(g,y),y.node;p(d);let b=A([a],([k])=>{let w=k;return h===void 0?w.slice(m):w.slice(m,h)},{initial:i.slice(m,h),describeKind:"derived"}),T=ko(b);return d.set(g,{node:b,dispose:T}),b},disposeTail(m){let h=c.get(m);return h===void 0?!1:(h.dispose(),c.delete(m),!0)},disposeSlice(m,h){let g=u(m,h),y=d.get(g);return y===void 0?!1:(y.dispose(),d.delete(g),!0)},disposeAllViews(){for(let m of c.values())m.dispose();c.clear();for(let m of d.values())m.dispose();d.clear()},dispose(){for(let m of c.values())m.dispose();c.clear();for(let m of d.values())m.dispose();d.clear()}}}ne();function Ee(t){let e=t.input,n=e.regular+(e.cacheRead??0)+(e.cacheWrite5m??0)+(e.cacheWrite1h??0)+(e.cacheWriteOther??0)+(e.audio??0)+(e.image??0)+(e.video??0)+(e.toolUse??0);if(!e.extensions)return n;let r=0;for(let o of Object.values(e.extensions))r+=o;return n+r}function Pe(t){let e=t.output,n=e.regular+(e.reasoning??0)+(e.audio??0)+(e.predictionAccepted??0)+(e.predictionRejected??0);if(!e.extensions)return n;let r=0;for(let o of Object.values(e.extensions))r+=o;return n+r}function xo(){return{input:{regular:0},output:{regular:0}}}function Ni(t,e){let n=e?.logMax??1e3,r=$e(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:n}),o=O(null,{name:"adapterStats/lastCall"}),s=A([r.entries],([h])=>h.length,{name:"adapterStats/totalCalls",initial:0}),i=A([r.entries],([h])=>h.reduce((g,y)=>g+Ee(y.usage),0),{name:"adapterStats/totalInputTokens",initial:0}),a=A([r.entries],([h])=>h.reduce((g,y)=>g+Pe(y.usage),0),{name:"adapterStats/totalOutputTokens",initial:0}),l=[Z(s),Z(i),Z(a)],c=h=>{r.append(h),o.emit(h)},d=()=>{r.clear(),o.emit(null)},u=ve(t,{invoke(h,g){let y=V(),b=Te(),T=t.model??g?.model??"",k=v=>(c(Ye({provider:t.provider,model:t.model??g?.model??v.model??"",tier:g?.tier??v.tier,usage:v.usage??Ce(),startNs:y,startWallClockNs:b,method:"invoke"})),v),w=v=>{let x=v;c(Ye({provider:t.provider,model:T,tier:g?.tier,usage:Ce(),startNs:y,startWallClockNs:b,method:"invoke",error:{type:x?.name??"Error",message:x?.message??String(v)}}))};return Zt(t.invoke(h,g),{onResp:k,onError:w,name:"adapterStats/invokeTap"})},async*stream(h,g){let y=V(),b=Te(),T=t.model??g?.model??"",k;try{for await(let w of t.stream(h,g))w.type==="usage"&&(k=w.usage),yield w;c(Ye({provider:t.provider,model:T,tier:g?.tier,usage:k??Ce(),startNs:y,startWallClockNs:b,method:"stream"}))}catch(w){let v=w;throw c(Ye({provider:t.provider,model:T,tier:g?.tier,usage:k??Ce(),startNs:y,startWallClockNs:b,method:"stream",error:{type:v?.name??"Error",message:v?.message??String(w)}})),w}}});be(u,"observableAdapter",t);let p=!1;return{adapter:u,stats:{lastCall:o,allCalls:r,totalCalls:s,totalInputTokens:i,totalOutputTokens:a,reset:d,dispose:()=>{if(!p){p=!0;for(let h of l)h();l.length=0}}}}}function _i(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function rn(t="USD"){return{total:0,currency:t}}function nr(t,e,n){let r=Ee(t),o=e.currency??"USD",s=n?.withBreakdown===!0,i=s?{}:null,a=0,l=(g,y,b)=>{if(!y||b==null)return;let T=_i(b,r),k=y*T/1e6;a+=k,s&&(i[g]=(i[g]??0)+k)},c=t.input,d=e.input;if(d&&(l("input.regular",c.regular,d.regular),l("input.cacheRead",c.cacheRead??0,d.cacheRead),l("input.cacheWrite5m",c.cacheWrite5m??0,d.cacheWrite5m),l("input.cacheWrite1h",c.cacheWrite1h??0,d.cacheWrite1h),l("input.cacheWriteOther",c.cacheWriteOther??0,d.cacheWriteOther),l("input.audio",c.audio??0,d.audio),l("input.image",c.image??0,d.image),l("input.video",c.video??0,d.video),l("input.toolUse",c.toolUse??0,d.toolUse),c.extensions&&d.extensions))for(let[g,y]of Object.entries(c.extensions))l(`input.ext.${g}`,y,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,y]of Object.entries(u.extensions))l(`output.ext.${g}`,y,p.extensions[g]);let f=n?.tier;if(f&&e.tierMultipliers){let g=e.tierMultipliers[f];if(g!=null&&(a*=g,s))for(let y of Object.keys(i))i[y]*=g}let m=t.auxiliary,h=e.auxiliary;if(m&&h)for(let[g,y]of Object.entries(m)){let b=h[g];if(b==null||!y)continue;let T=y*b;a+=T,s&&(i[`auxiliary.${g}`]=T)}return s?{total:a,currency:o,breakdown:i}:{total:a,currency:o}}function nn(t,e){return`${t}::${e}`}function Mi(t){let e=new Map,n=new Map,r=(o,s,i)=>{e.set(nn(o,s),{provider:o,model:s,pricing:i});let a=n.get(o);a||(a=new Set,n.set(o,a)),a.add(s)};if(t)for(let[o,s,i]of t)r(o,s,i);return{register:r,lookup(o,s){let i=e.get(nn(o,s));if(i)return i.pricing;let a=n.get(o);if(!a)return;let l;for(let c of a)if(s.startsWith(c)&&(!l||c.length>l.key.length)){let d=e.get(nn(o,c));d&&(l={key:c,pricing:d.pricing})}return l?.pricing},remove(o,s){let i=e.delete(nn(o,s));if(i){let a=n.get(o);a?.delete(s),a&&a.size===0&&n.delete(o)}return i},entries(){let o=e.values();return(function*(){for(let{provider:s,model:i,pricing:a}of o)yield[s,i,a]})()}}}function Ei(t,e="USD"){return(n,r)=>{let o=t.lookup(r.provider,r.model);return o?nr(n,o,{tier:r.tier,withBreakdown:r.withBreakdown}):rn(e)}}function Oi(...t){return(e,n)=>{for(let r of t){let o=r(e,n);if(o.total!==0)return o}return t.length>0?t[0](e,n):rn()}}function Ai(t,e,n){return t?.pricing?nr(e,t.pricing,n):rn()}ct();ne();function rr(t,e={}){let n=e.breaker??vt(e),r=ve(t,{async invoke(o,s){if(!n.canExecute())throw new Fe;try{let i=await xe(P(t.invoke(o,s)));return n.recordSuccess(),i}catch(i){throw n.recordFailure(i),i}},async*stream(o,s){if(!n.canExecute())throw new Fe;try{for await(let i of t.stream(o,s))yield i;n.recordSuccess()}catch(i){throw n.recordFailure(i),i}}});return be(r,"withBreaker",t),{adapter:r,breaker:n}}he();le();q();ne();var on=class extends Error{constructor(n,r,o){super(`Budget exhausted: ${n} (limit=${r}, observed=${o})`);this.which=n;this.limit=r;this.observed=o}name="BudgetExhaustedError"},or=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),Ro=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function sr(t,e){let n=$e(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),r=O(Ro(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),o=A([r],([c])=>{let d=c;return!(e.caps.calls!=null&&d.calls>=e.caps.calls||e.caps.inputTokens!=null&&d.inputTokens>=e.caps.inputTokens||e.caps.outputTokens!=null&&d.outputTokens>=e.caps.outputTokens||e.caps.usd!=null&&d.usd>=e.caps.usd)},{name:e.name?`${e.name}/isOpen`:"budgetGate/isOpen",initial:!0});if(Z(o),e.onExhausted!=null){let c=e.onExhausted,d=!1,u=!0;o.subscribe(p=>{for(let f of p)if(f[0]===I){let m=f[1];if(d&&u&&m===!1){let h=So(r.cache??or,e.caps);h&&c(h)}u=m,d=!0}})}let s=()=>{if(o.cache===!1){let c=r.cache??or,d=So(c,e.caps);return new on(d??"budget",e.caps[d??"calls"]??0,Ci(c,d??"calls"))}},i=(c,d)=>{let u=t.provider,p=Ye({provider:u,model:d.model,tier:d.tier,usage:c,startNs:d.startNs,method:d.method,...d.error?{error:d.error}:{}});n.append(p);let f=r.cache??or,m=e.pricingFn?f.usd+e.pricingFn(c,{model:d.model,provider:u,tier:d.tier}).total:f.usd;r.emit({calls:f.calls+1,inputTokens:f.inputTokens+Ee(c),outputTokens:f.outputTokens+Pe(c),usd:m})},a=()=>{n.clear(),r.emit(Ro())},l=ve(t,{invoke(c,d){let u=s();if(u)return Promise.reject(u);let p=V(),f=t.model??d?.model??"",m=g=>(i(g.usage??Ce(),{model:t.model??d?.model??g.model??"",tier:d?.tier??g.tier,startNs:p,method:"invoke"}),g),h=g=>{let y=g;i(Ce(),{model:f,tier:d?.tier,startNs:p,method:"invoke",error:{type:y?.name??"Error",message:y?.message??String(g)}})};return Zt(t.invoke(c,d),{onResp:m,onError:h,name:"budgetGate/invokeTap"})},async*stream(c,d){let u=s();if(u)throw u;let p=V(),f;try{for await(let m of t.stream(c,d))m.type==="usage"&&(f=m.usage),yield m;i(f??Ce(),{model:t.model??d?.model??"",tier:d?.tier,startNs:p,method:"stream"})}catch(m){let h=m;throw i(f??Ce(),{model:t.model??d?.model??"",tier:d?.tier,startNs:p,method:"stream",error:{type:h?.name??"Error",message:h?.message??String(m)}}),m}}});return be(l,"withBudgetGate",t),{adapter:l,budget:{totals:r,isOpen:o,log:n,reset:a}}}function So(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 Ci(t,e){switch(e){case"calls":return t.calls;case"inputTokens":return t.inputTokens;case"outputTokens":return t.outputTokens;case"usd":return t.usd}}ne();function Li(t,e){let n=e.mock??Je({provider:t.provider,model:t.model}),r=typeof e.enabled=="boolean"?e.enabled:void 0,o=r===void 0?P(e.enabled):void 0,s;o&&(s=Z(o));let i=()=>r!==void 0?r:!!o?.cache,a=ve(t,{invoke(c,d){return i()?n.invoke(c,d):t.invoke(c,d)},stream(c,d){return i()?n.stream(c,d):t.stream(c,d)}});return be(a,"withDryRun",t),{adapter:a,dispose:()=>{s&&(s(),s=void 0)}}}function ir(t){if(t==null||typeof t!="object")return;let e=t,n=e.status,r=Di(e.headers);if(n!==429&&n!==503&&!ji(e.message))return;let o={},s=r("retry-after"),i=Pi(s);i!=null&&(o.retryAfterMs=i);let a=r("anthropic-ratelimit-requests-reset");if(a){let f=No(a);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let l=r("anthropic-ratelimit-tokens-reset");if(l){let f=No(l);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let c=sn(r,"x-ratelimit-limit-requests");c!=null&&(o.rpmCap=c);let d=sn(r,"x-ratelimit-limit-tokens");d!=null&&(o.tpmCap=d);let u=sn(r,"x-ratelimit-remaining-requests"),p=sn(r,"x-ratelimit-remaining-tokens");if(u!=null&&c!=null&&c>0&&(o.usageHint??={},o.usageHint.rpm=1-u/c),p!=null&&d!=null&&d>0&&(o.usageHint??={},o.usageHint.tpm=1-p/d),o.retryAfterMs==null&&e.message){let f=Fi(e.message);f!=null&&(o.retryAfterMs=f)}return e.headers&&(o.metadata={headers:Ii(e.headers)}),o.retryAfterMs==null&&o.rpmCap==null&&o.tpmCap==null&&o.usageHint==null?o.metadata?o:void 0:o}function Di(t){if(!t)return()=>{};if(typeof t.get=="function"){let r=t;return o=>r.get(o)??r.get(o.toLowerCase())??void 0}let e=t,n={};for(let[r,o]of Object.entries(e)){let s=Array.isArray(o)?o.join(", "):o;s!=null&&(n[r.toLowerCase()]=s)}return r=>n[r.toLowerCase()]}function Ii(t){let e={};if(typeof t.forEach=="function")return t.forEach((n,r)=>{e[r]=n}),e;for(let[n,r]of Object.entries(t))r!=null&&(e[n]=Array.isArray(r)?r.join(", "):r);return e}function sn(t,e){let n=t(e);if(n==null)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function Pi(t){if(!t)return;let e=t.trim(),n=Number(e);if(Number.isFinite(n)&&n>=0)return n*1e3;let r=Date.parse(e);if(Number.isFinite(r)){let o=r-Date.now();if(o>0)return o}}function No(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var Gi=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function Fi(t){let e=Gi.exec(t);if(!e)return;let n=Number(e[1]);if(!Number.isFinite(n))return;let r=(e[2]??"s").toLowerCase();if(r==="ms")return n;if(r.startsWith("s"))return n*1e3;if(r.startsWith("m"))return n*6e4}var $i=/rate\s*limit|too\s*many\s*requests|quota|429/i;function ji(t){return!!t&&$i.test(t)}he();le();q();ct();ne();De();function ar(t){let e=new Error(t);return e.name="AbortError",e}function Mo(t={}){let e=Math.max(1,t.burstMultiplier??1),n=t.clampCooldownMs??6e4,r=t.rpm!=null?P(t.rpm):O(Number.POSITIVE_INFINITY),o=t.tpm!=null?P(t.tpm):O(Number.POSITIVE_INFINITY),s=O(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),i=O(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),a=O({},{name:"adaptiveRateLimiter/lastSignal"}),l=A([r,s],([M,L])=>Math.min(Number(M??1/0),Number(L??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),c=A([o,i],([M,L])=>Math.min(Number(M??1/0),Number(L??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),d=dt(Number(r.cache??Number.POSITIVE_INFINITY),e),u=dt(Number(o.cache??Number.POSITIVE_INFINITY),e),p=!1,f=!1,m=l.subscribe(M=>{for(let L of M)if(L[0]===I){let j=Number(L[1]);Number.isFinite(j)&&j>0?(d=dt(j,e),p=!1):j===1/0?(d=dt(1/0,e),p=!1):j<=0&&(p=!0)}}),h=c.subscribe(M=>{for(let L of M)if(L[0]===I){let j=Number(L[1]);Number.isFinite(j)&&j>0?(u=dt(j,e),f=!1):j===1/0?(u=dt(1/0,e),f=!1):j<=0&&(f=!0)}}),g=0,y=new de,b=new de,T;t.adaptation!=null&&(T=P(t.adaptation).subscribe(L=>{for(let j of L)j[0]===I&&k(j[1])}));function k(M){if(a.emit(M),M.rpmCap!=null&&Number.isFinite(M.rpmCap)&&M.rpmCap>=0&&(s.emit(M.rpmCap),Number.isFinite(n)&&n>0&&y.start(n,()=>s.emit(Number.POSITIVE_INFINITY))),M.tpmCap!=null&&Number.isFinite(M.tpmCap)&&M.tpmCap>=0&&(i.emit(M.tpmCap),Number.isFinite(n)&&n>0&&b.start(n,()=>i.emit(Number.POSITIVE_INFINITY))),M.retryAfterMs!=null&&M.retryAfterMs>0){let L=V()+M.retryAfterMs*1e6;L>g&&(g=L)}}let w=O(0,{name:"adaptiveRateLimiter/pending"}),v=O(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),x=O(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),S=M=>{w.emit((w.cache??0)+M)},N=()=>{v.emit(d.available()),x.emit(u.available())};async function _(M={}){let L=M.requestCost??1,j=M.tokenCost??0,W=M.signal;S(1);try{for(;;){if(W?.aborted)throw ar("AdaptiveRateLimiter.acquire aborted");let B=V();if(g>B){let G=Math.ceil((g-B)/1e6);await an(G,W);continue}if(L>0&&p||j>0&&f){await an(250,W);continue}let ee=d,Y=u;if(!ee.tryConsume(L)){await an(_o(ee,L),W);continue}if(!(j>0?Y.tryConsume(j):!0)){ee.putBack(L),await an(_o(Y,j),W);continue}N();return}}finally{S(-1)}}function R(M){M>0?u.tryConsume(M):M<0&&u.putBack(-M),N()}function E(){m(),h(),T?.(),y.cancel(),b.cancel()}return{effectiveRpm:l,effectiveTpm:c,lastSignal:a,pending:w,rpmAvailable:v,tpmAvailable:x,acquire:_,recordUsage:R,recordSignal:k,dispose:E}}function dt(t,e){if(!Number.isFinite(t)||t===1/0)return wt(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let n=Math.max(1,t*e),r=t/60;return wt(n,r)}function _o(t,e){let n=t.available(),r=Math.max(0,e-n);return r<=0?25:Math.min(5e3,Math.max(50,r*100))}function an(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(ar("AdaptiveRateLimiter.acquire aborted")):new Promise((n,r)=>{let o=new de,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(ar("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",s,{once:!0}))})}ne();function cr(t,e={}){let n=e.limiter??Mo({name:e.name??"rateLimiter",rpm:e.rpm,tpm:e.tpm,adaptation:e.adaptation,burstMultiplier:e.burstMultiplier}),r=(i,a)=>e.costFn?e.costFn(i,a):0,o=i=>{let a=ir(i);a&&n.recordSignal(a)},s=ve(t,{async invoke(i,a){let l=r(i,a);await n.acquire({requestCost:1,tokenCost:l,signal:a?.signal});try{let c=await xe(P(t.invoke(i,a))),d=c.usage??xo(),p=Ee(d)+Pe(d)-l;return p>0&&n.recordUsage(p),c}catch(c){throw o(c),c}},async*stream(i,a){let l=r(i,a);await n.acquire({requestCost:1,tokenCost:l,signal:a?.signal});try{let c=0;for await(let u of t.stream(i,a))u.type==="usage"&&(c=Ee(u.usage)+Pe(u.usage)),yield u;let d=c-l;d>0&&n.recordUsage(d)}catch(c){throw o(c),c}}});return be(s,"withRateLimiter",t),{adapter:s,limiter:n}}ct();ne();var St=class extends Error{name="AllTiersExhaustedError";skipped;failed;constructor(e){let n=[];e.failed.size>0&&n.push(`failed=[${[...e.failed.keys()].join(",")}]`),e.skipped.length>0&&n.push(`skipped=[${e.skipped.map(r=>`${r.name}(${r.reason})`).join(",")}]`),super(`All LLM adapter tiers exhausted: ${n.join(" ")}`),this.skipped=e.skipped,this.failed=e.failed}};function lr(t,e={}){if(t.length===0)throw new RangeError("cascadingLlmAdapter: tiers must be non-empty");let n=t.map(s=>({name:s.name,adapter:s.adapter,filter:s.filter,breaker:s.breaker?"canExecute"in s.breaker?s.breaker:vt(s.breaker):void 0})),r=e.streamRetryBeforeFirstChunk??!0,o={provider:"cascading",model:void 0,async invoke(s,i){let a=[],l=new Map;for(let d=0;d<n.length;d++){let u=n[d];if(u.filter&&!u.filter(s,i)){a.push({name:u.name,reason:"filter"});continue}if(u.breaker&&!u.breaker.canExecute()){a.push({name:u.name,reason:"breaker"});continue}try{let p=await xe(P(u.adapter.invoke(s,i)));return u.breaker?.recordSuccess(),{...p,metadata:{...p.metadata??{},tier:u.name}}}catch(p){l.set(u.name,p),u.breaker?.recordFailure(p);let f=n[d+1];f&&e.onFallback?.(u.name,f.name,p)}}let c={skipped:a,failed:l};throw e.onExhausted?.(c),new St(c)},async*stream(s,i){let a=[],l=new Map;for(let d=0;d<n.length;d++){let u=n[d];if(u.filter&&!u.filter(s,i)){a.push({name:u.name,reason:"filter"});continue}if(u.breaker&&!u.breaker.canExecute()){a.push({name:u.name,reason:"breaker"});continue}let p=!1;try{for await(let f of u.adapter.stream(s,i))p=!0,yield f;u.breaker?.recordSuccess();return}catch(f){if(l.set(u.name,f),u.breaker?.recordFailure(f),p||!r)throw f;let m=n[d+1];m&&e.onFallback?.(u.name,m.name,f)}}let c={skipped:a,failed:l};throw e.onExhausted?.(c),new St(c)}};return be(o,`cascade[${n.map(s=>s.name).join(",")}]`),o}function Bi(t,e,n){let r={name:t,adapter:e};return n?.breaker&&(r.breaker=n.breaker),n?.filter&&(r.filter=n.filter),r}ne();De();function cn(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function Eo(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(cn()):new Promise((n,r)=>{let o=new de,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(cn())},e.addEventListener("abort",s,{once:!0}))})}function dr(t,e={}){let n=e.attempts??3,r=e.baseDelayMs??500,o=e.maxDelayMs??1e4,s=e.strategy??"decorrelated",i=e.jitter??!0,a=e.shouldRetry??Vi,l=e.retryStreaming??!0,c=(u,p)=>{if(s==="decorrelated"){let g=Math.min(o,Math.max(r,p*3));return r+Math.random()*(g-r)}let f=s==="exp"?r*2**(u-1):r*u,m=Math.min(o,f);if(!i)return m;let h=m*(.5+Math.random());return Math.min(o,h)},d=ve(t,{async invoke(u,p){if(p?.signal?.aborted)throw cn();let f,m=r;for(let h=1;h<=n;h++)try{return await xe(P(t.invoke(u,p)))}catch(g){if(f=g,h>=n||!a(g,h))throw g;let y=c(h,m);m=y,await Eo(y,p?.signal)}throw f},async*stream(u,p){if(p?.signal?.aborted)throw cn();if(!l){for await(let h of t.stream(u,p))yield h;return}let f,m=r;for(let h=1;h<=n;h++){let g=!1;try{for await(let y of t.stream(u,p))g=!0,yield y;return}catch(y){if(f=y,g||h>=n||!a(y,h))throw y;let b=c(h,m);m=b,await Eo(b,p?.signal)}}throw f}});return be(d,"withRetry",t),d}function Vi(t,e){if(t==null)return!1;let n=t;return n.name==="LLMTimeoutError"?!0:n.name==="AbortError"||n.message==="aborted"||n.name==="DOMException"&&n.code!=null&&Number(n.code)===20||n.name==="BudgetExhaustedError"||n.name==="CircuitOpenError"?!1:n.status!=null?n.status===429||n.status>=500&&n.status<600:n.code&&typeof n.code=="string"&&/^E[A-Z]+$/.test(n.code)?!0:n.message?/network|timeout|socket|fetch|econn|eai_/i.test(n.message):!1}ne();De();var ut=class extends Error{constructor(n){super(`LLM call timed out after ${n}ms`);this.ms=n}name="LLMTimeoutError"};function ur(t,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let n=s=>{let i=new AbortController,a=!1,l,c=new de;return s&&(s.aborted?i.abort(s.reason):(l=()=>{c.cancel(),i.abort(s.reason)},s.addEventListener("abort",l,{once:!0}))),c.start(e,()=>{a=!0,i.abort(new ut(e))}),{signal:i.signal,cancel:()=>{c.cancel(),s&&l&&s.removeEventListener("abort",l)},timedOut:()=>a}},r=(s,i)=>{if(!i||s instanceof ut)throw s;let a=s;if(a?.name==="AbortError"||a?.name==="DOMException"&&Number(a.code)===20||s?.message==="aborted"){let c=new ut(e);throw c.cause=s,c}throw s},o=ve(t,{async invoke(s,i){let{signal:a,cancel:l,timedOut:c}=n(i?.signal);try{return await xe(P(t.invoke(s,{...i,signal:a})))}catch(d){return r(d,c())}finally{l()}},async*stream(s,i){let{signal:a,cancel:l,timedOut:c}=n(i?.signal);try{for await(let d of t.stream(s,{...i,signal:a}))yield d}catch(d){r(d,c())}finally{l()}}});return be(o,"withTimeout",t),o}function Ki(t,e={}){let n={adapter:t},r=t;if(e.rateLimit){let o=cr(r,e.rateLimit);r=o.adapter,n.rateLimiter=o.limiter}if(e.budget){let o=sr(r,e.budget);r=o.adapter,n.budget=o.budget}if(e.breaker){let o=rr(r,e.breaker);r=o.adapter,n.breaker=o.breaker}if(e.timeoutMs!=null&&(r=ur(r,e.timeoutMs)),e.retry&&(r=dr(r,e.retry)),e.fallback){if(e.name==="fallback")throw new RangeError('resilientAdapter: `name` cannot be "fallback" \u2014 collides with the secondary tier label.');let o={};e.onFallback&&(o.onFallback=e.onFallback),e.onExhausted&&(o.onExhausted=e.onExhausted),r=lr([{name:e.name??"primary",adapter:r},{name:"fallback",adapter:e.fallback}],o)}return e.cache&&(r=Rt(r,e.cache)),n.adapter=r,n}q();ne();function Ui(t,e,n){let r=P(e);return ue(r,s=>{if(!s||s.length===0)return O(null);let i=n?.tools;return t.invoke(s,{model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,tools:i,systemPrompt:n?.systemPrompt})})}Me();ne();le();ne();De();le();ne();function Oo(t,e){let n=t.cache??0;return n>=e?!1:(t.down([[J],[I,n+1]]),!0)}function je(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}function z(t,e){return je("ai",t,e)}function zi(t){return t!=null&&typeof t.then=="function"}function pr(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function Hi(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var Wi=3e4;function Ao(t,e){if(t.status==="settled"){let r=t.cache;if(r!==void 0)return Promise.resolve(r)}let n=e?.timeoutMs??Wi;return new Promise((r,o)=>{let s=new de,i=t.subscribe(a=>{for(let l of a){if(l[0]===I){s.cancel(),i(),r(l[1]);return}if(l[0]===C){s.cancel(),i(),o(l[1]);return}if(l[0]===$){s.cancel(),i(),o(new Error("firstDataFromNode: completed without producing a value"));return}}});s.start(n,()=>{i(),o(new Error(`firstDataFromNode: timed out after ${n}ms`))})})}async function Nt(t){return zi(t)?Nt(await t):pr(t)?Ao(t):Hi(t)?Ao(P(t)):t}function pt(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function qi(t,e){let n=P(t),r=e?.refreshTrigger!=null?P(e.refreshTrigger):null;return r==null?ie([n],(o,s,i)=>{if(i.store.emitted===!0)return;let l=o[0],c=l!=null&&l.length>0?l.at(-1):i.prevData[0];if(c!==void 0)return i.store.emitted=!0,s.emit(c),{invalidate:()=>{i.store.emitted=!1}}},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:z("frozen_context")}):ie([n,r],(o,s,i)=>{let a=o[1];if(!(a!=null&&a.length>0))return;let c=o[0],d=c!=null&&c.length>0?c.at(-1):i.prevData[0];s.emit(d)},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:z("frozen_context")})}le();q();ne();function Co(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function Ji(t,e=200){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function fr(t,e,n,r){let o=r?.format??"text",s=r?.name??"prompt_node",i=A(e,l=>{if(l.some(d=>d==null))return[];let c=typeof n=="string"?n:n(...l);return c?[{role:"user",content:c}]:[]},{name:`${s}::messages`,meta:z("prompt_node")});return ue(i,l=>!l||l.length===0?O(null):se(c=>{let d=!1,u=!1,p,f={model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt};if(r?.abort){let y=oo(r.abort);f.signal=y.signal,p=y.dispose}let m;try{m=t.invoke(l,f)}catch(y){return d=!0,c.down([[C,y]]),()=>{p?.()}}let g=P(m).subscribe(y=>{if(!(u||d))for(let b of y){if(d)return;if(b[0]===I){let T=b[1];try{let k=Co(T),w=o==="json"?JSON.parse(pt(k)):k;c.emit(w)}catch(k){let w=Co(T),v=new Error(`promptNode: failed to parse LLM response as JSON: ${k.message}
|
|
7
|
-
Raw content (first 200 chars): ${
|
|
8
|
-
`)}function
|
|
9
|
-
`)}function ia(t,e,n,r,o){let{x:s,y:i,w:a,h:l}=r;if(a<2||l<2){l>0&&$o(t,e,s,i,a,o);return}Be(t,e,s,i,n.boxTL);for(let d=s+1;d<s+a-1;d+=1)Be(t,e,d,i,n.boxH);Be(t,e,s+a-1,i,n.boxTR);for(let d=i+1;d<i+l-1;d+=1){Be(t,e,s,d,n.boxV);for(let u=s+1;u<s+a-1;u+=1)Ko(t,e,u,d," ","empty");Be(t,e,s+a-1,d,n.boxV)}Be(t,e,s,i+l-1,n.boxBL);for(let d=s+1;d<s+a-1;d+=1)Be(t,e,d,i+l-1,n.boxH);Be(t,e,s+a-1,i+l-1,n.boxBR);let c=i+Math.floor(l/2);$o(t,e,s+1,c,a-2,o)}function Be(t,e,n,r,o){Ko(t,e,n,r,o,o===" "?"empty":o==="\u2500"||o==="-"?"boxH":o==="\u2502"||o==="|"?"boxV":"boxCorner")}function Ko(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];n<0||n>=i.length||(i[n]=o,e[r][n]=s)}function $o(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=n,a=o;for(let l of s){let c=fn(l);if(c!==0){if(a<c)break;i>=0&&i<t[r].length&&(t[r][i]=l,e[r][i]="label",c===2&&i+1<t[r].length&&(t[r][i+1]="",e[r][i+1]="label")),i+=c,a-=c}}for(;a>0;)i>=0&&i<t[r].length&&(t[r][i]=" ",e[r][i]="empty"),i+=1,a-=1}function aa(t,e,n,r){let o=r.points;if(o.length<2)return;for(let l=0;l+1<o.length;l+=1)ca(t,e,n,o[l],o[l+1]);for(let l=1;l+1<o.length;l+=1){let c=o[l-1],d=o[l],u=o[l+1],p=la(c,d,u,n);p&&Bo(t,e,d.x,d.y,p,"edgeCorner")}let s=o[o.length-1],i=o[o.length-2],a=da(i,s,n);a&&Bo(t,e,s.x,s.y,a,"arrow")}function ca(t,e,n,r,o){if(!(r.x===o.x&&r.y===o.y)){if(r.y===o.y){let s=r.y,i=Math.min(r.x,o.x),a=Math.max(r.x,o.x);for(let l=i;l<=a;l+=1)jo(t,e,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)jo(t,e,s,l,n,"v")}}}function jo(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];if(n<0||n>=i.length)return;let a=e[r][n];if(!(a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label")){if(a==="empty"){i[n]=s==="h"?o.horizontal:o.vertical,e[r][n]=s==="h"?"edgeH":"edgeV";return}if(a==="edgeH"&&s==="v"){i[n]=o.cross,e[r][n]="edgeCorner";return}if(a==="edgeV"&&s==="h"){i[n]=o.cross,e[r][n]="edgeCorner";return}}}function Bo(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];if(n<0||n>=i.length)return;let a=e[r][n];a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label"||(i[n]=o,e[r][n]=s)}function la(t,e,n,r){let o=t.y===e.y,s=e.y===n.y;if(o===s)return;if(o){let l=t.x<e.x,c=n.y>e.y;return l&&c?r.cornerTR:l&&!c?r.cornerBR:!l&&c?r.cornerTL:r.cornerBL}let i=t.y<e.y,a=n.x>e.x;return i&&a?r.cornerBL:i&&!a?r.cornerBR:!i&&a?r.cornerTL:r.cornerTR}function da(t,e,n){if(e.x>t.x)return n.arrowRight;if(e.x<t.x)return n.arrowLeft;if(e.y>t.y)return n.arrowDown;if(e.y<t.y)return n.arrowUp}function ua(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===32;)e-=1;return t.slice(0,e)}function Ho(t){let e=pa(t);fa(e),ma(e),ga(e),ha(e,t);let n=Ta(e,t),{width:r,height:o}=wa(e),s=[];for(let i of e.layers)for(let a of i)a.isVirtual||s.push({id:a.id,layer:a.layer,order:a.order,x:a.x,y:a.y,w:a.w,h:a.h});return{boxes:s,edges:n,width:r,height:o}}function pa(t){let e=new Map;for(let o of t.nodes)e.set(o,{id:o,isVirtual:!1,layer:-1,order:0,x:0,y:0,w:t.widthCells(o),h:t.heightCells(o),in:[],out:[]});let n=[],r=0;for(let o of t.edges){if(o.from===o.to)continue;let s=e.get(o.from),i=e.get(o.to);if(!s||!i)continue;let a={chainId:r++,chainFrom:o.from,chainTo:o.to,fromId:o.from,toId:o.to,hopIndex:0,chainLen:1};s.out.push(a),i.in.push(a),n.push(a)}return{nodes:e,layers:[],hops:n}}function fa(t){let e=new Map;for(let s of t.nodes.values())e.set(s.id,s.in.length);let n=[];for(let s of t.nodes.values())(e.get(s.id)??0)===0&&(s.layer=0,n.push(s));let r=new Set,o=0;for(;o<n.length;){let s=n[o++];if(!r.has(s.id)){r.add(s.id);for(let i of s.out){let a=t.nodes.get(i.toId);a.layer=Math.max(a.layer,s.layer+1);let l=(e.get(a.id)??0)-1;e.set(a.id,l),l<=0&&n.push(a)}}}for(let s of t.nodes.values())s.layer<0&&(s.layer=0)}function ma(t){let e=Math.max(0,...Array.from(t.nodes.values(),s=>s.layer)),n=Array.from({length:e+1},()=>[]);for(let s of t.nodes.values())n[s.layer].push(s);let r=[],o=0;for(let s of t.hops){let i=t.nodes.get(s.fromId),a=t.nodes.get(s.toId),l=a.layer-i.layer;if(l<=0){i.out=i.out.filter(u=>u!==s),a.in=a.in.filter(u=>u!==s);continue}if(l===1){s.hopIndex=0,s.chainLen=1,r.push(s);continue}i.out=i.out.filter(u=>u!==s),a.in=a.in.filter(u=>u!==s);let c=i;for(let u=1;u<l;u+=1){let p=`__virt_${o++}__`,f={id:p,isVirtual:!0,layer:i.layer+u,order:0,x:0,y:0,w:0,h:1,in:[],out:[]};t.nodes.set(p,f),n[f.layer].push(f);let m={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:c.id,toId:p,hopIndex:u-1,chainLen:l};c.out.push(m),f.in.push(m),r.push(m),c=f}let d={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:c.id,toId:a.id,hopIndex:l-1,chainLen:l};c.out.push(d),a.in.push(d),r.push(d)}for(let s of n)for(let i=0;i<s.length;i+=1)s[i].order=i;t.layers=n,t.hops=r}function ga(t){for(let n=0;n<4;n+=1){for(let r=1;r<t.layers.length;r+=1)Uo(t,t.layers[r],"in"),mn(t.layers[r]);for(let r=t.layers.length-2;r>=0;r-=1)Uo(t,t.layers[r],"out"),mn(t.layers[r])}for(let n=0;n<2;n+=1){let r=!1;for(let o=1;o<t.layers.length;o+=1){let s=t.layers[o];for(let i=0;i+1<s.length;i+=1){let a=zo(t,s[i],s[i+1],"in");[s[i],s[i+1]]=[s[i+1],s[i]],mn(s),zo(t,s[i],s[i+1],"in")<a?r=!0:([s[i],s[i+1]]=[s[i+1],s[i]],mn(s))}}if(!r)break}}function Uo(t,e,n){let r=new Map;for(let o of e){let s=n==="in"?o.in:o.out;if(s.length===0){r.set(o.id,o.order);continue}let i=0,a=0;for(let l of s){let c=t.nodes.get(n==="in"?l.fromId:l.toId);c&&(i+=c.order,a+=1)}r.set(o.id,a===0?o.order:i/a)}e.sort((o,s)=>{let i=r.get(o.id),a=r.get(s.id);return i!==a?i-a:o.order-s.order})}function mn(t){for(let e=0;e<t.length;e+=1)t[e].order=e}function zo(t,e,n,r){let o=r==="in"?e.in:e.out,s=r==="in"?n.in:n.out,i=0;for(let a of o)for(let l of s){let c=t.nodes.get(r==="in"?a.fromId:a.toId)?.order??0,d=t.nodes.get(r==="in"?l.fromId:l.toId)?.order??0;(e.order<n.order&&c>d||e.order>n.order&&c<d)&&(i+=1)}return i}function ha(t,e){e.direction==="LR"?ya(t,e):ba(t,e)}function ya(t,e){let n=[],r=0;for(let o=0;o<t.layers.length;o+=1){n.push(r);let s=0;for(let i of t.layers[o])s=Math.max(s,i.w);r+=s+e.layerGap}for(let o=0;o<t.layers.length;o+=1)for(let s of t.layers[o])s.x=n[o];for(let o of t.layers){let s=0;for(let i of o)i.y=s,s+=i.h+e.nodeGap}Wo(t,e,"y")}function ba(t,e){let n=[],r=0;for(let o=0;o<t.layers.length;o+=1){n.push(r);let s=0;for(let i of t.layers[o])s=Math.max(s,i.h);r+=s+e.layerGap}for(let o=0;o<t.layers.length;o+=1)for(let s of t.layers[o])s.y=n[o];for(let o of t.layers){let s=0;for(let i of o)i.x=s,s+=i.w+e.nodeGap}Wo(t,e,"x")}function Wo(t,e,n){let r=s=>n==="y"?s.h:s.w,o=e.nodeGap;for(let s=0;s<2;s+=1){let i=s===0?t.layers.slice(1):t.layers.slice(0,-1).reverse();for(let a of i){let l=new Map;for(let d of a){let u=s===0?d.in:d.out;if(u.length===0)continue;let p=[];for(let m of u){let h=t.nodes.get(s===0?m.fromId:m.toId);if(!h)continue;let g=n==="y"?h.y:h.x;p.push(g+Math.floor(r(h)/2))}if(p.length===0)continue;p.sort((m,h)=>m-h);let f=p[Math.floor(p.length/2)];l.set(d.id,f-Math.floor(r(d)/2))}let c=0;for(let d of a){let u=l.get(d.id),p=n==="y"?d.y:d.x,m=Math.max(u??p,c);n==="y"?d.y=m:d.x=m,c=m+r(d)+o}}}}function Ta(t,e){let n=new Map;for(let c of t.hops){let d=n.get(c.chainId);d?d.push(c):n.set(c.chainId,[c])}for(let c of n.values())c.sort((d,u)=>d.hopIndex-u.hopIndex);let r=e.direction==="LR",o=c=>r?c.x:c.y,s=c=>r?c.w:c.h,i=c=>r?c.y+Math.floor(c.h/2):c.x+Math.floor(c.w/2),a=new Map;for(let c=0;c+1<t.layers.length;c+=1){let d=t.layers[c],u=t.layers[c+1],p=0;for(let S of d)p=Math.max(p,o(S)+s(S));let f=Number.POSITIVE_INFINITY;for(let S of u)f=Math.min(f,o(S));let m=Number.isFinite(f)?f-1:p,h=Math.max(1,m-p+1),g=[];for(let S of d)for(let N of S.out)g.push(N);g.sort((S,N)=>{let _=i(t.nodes.get(S.fromId)),R=i(t.nodes.get(N.fromId));if(_!==R)return _-R;let E=i(t.nodes.get(S.toId)),M=i(t.nodes.get(N.toId));return E-M});let y=[],b=new Map;for(let S of g){let N=i(t.nodes.get(S.fromId)),_=i(t.nodes.get(S.toId)),R=Math.min(N,_),E=Math.max(N,_),M=-1;for(let L=0;L<y.length;L+=1){let j=y[L],W=!0;for(let B of j)if(B.lo<=E&&R<=B.hi){W=!1;break}if(W){j.push({lo:R,hi:E}),M=L;break}}M<0&&(y.push([{lo:R,hi:E}]),M=y.length-1),b.set(S,M)}let T=y.length,k=h>=Math.max(3,T+2),w=k?p+1:p,v=k?m-1:m,x=Math.max(1,v-w+1);for(let S of g){let N=b.get(S),_;if(T<=1)_=w+Math.floor(x/2);else{let R=(x-1)/(T-1);_=w+Math.floor(N*R)}a.set(S,Math.max(p,Math.min(m,_)))}}let l=[];for(let[,c]of n){let d=[];for(let p=0;p<c.length;p+=1){let f=c[p],m=t.nodes.get(f.fromId),h=t.nodes.get(f.toId),g=a.get(f),y=m.isVirtual?o(m):o(m)+s(m),b=h.isVirtual?o(h):o(h)-1,T=i(m),k=i(h);p===0&&gn(d,r,y,T),T!==k&&(gn(d,r,g,T),gn(d,r,g,k)),gn(d,r,b,k)}let u=c[0];l.push({from:u.chainFrom,to:u.chainTo,points:va(d)})}return l}function gn(t,e,n,r){t.push(e?{x:n,y:r}:{x:r,y:n})}function va(t){let e=[];for(let n of t){let r=e[e.length-1];(!r||r.x!==n.x||r.y!==n.y)&&e.push(n)}return e}function wa(t){let e=0,n=0;for(let r of t.layers)for(let o of r)e=Math.max(e,o.x+o.w),n=Math.max(n,o.y+o.h);return{width:e,height:n}}var ka=24,xa=4,Ra=1,Sa=3;function qo(t,e){let n=Na(e.direction),r=Math.max(3,e.maxLabelWidth??ka),o=e.asciiCharset??"unicode",s=Object.keys(t.nodes).sort(),i=new Set(s),a=t.edges.filter(f=>i.has(f.from)&&i.has(f.to)),l=new Map,c=new Map;for(let f of s){let m=Fo(f,r);l.set(f,m),c.set(f,fn(m)+4)}let d=Ho({nodes:s,edges:a,widthCells:f=>c.get(f)??3,heightCells:()=>Sa,layerGap:xa,nodeGap:Ra,direction:n}),u=Vo(d,{charset:o,labelOf:f=>l.get(f)??f}),p=e.logger;return p&&p(u),u}function Na(t){if(t===void 0||t==="LR")return"LR";if(t==="TD")return"TD";throw new Error(`ascii describe supports direction "LR" or "TD" only; got ${String(t)}`)}Me();function Jo(t,e){let n=e?.topN??10,r=t.describe({detail:"standard"}),o=[],s=t._collectObserveTargets;typeof s=="function"&&s.call(t,"",o);let i=new Map;for(let[p,f]of o)i.set(p,f);let a=[];for(let[p,f]of Object.entries(r.nodes)){let m=i.get(p),h=m instanceof fe?m:null,g=h?Lo(h.cache):0,y=h?h._sinkCount:0,b=f.deps?.length??0,T=f.type==="effect"&&y===0,k=y===0?f.type==="effect"?"orphan-effect":f.type==="derived"?"idle-derived":f.type==="producer"?"idle-producer":null:null;a.push({path:p,type:f.type,status:f.status??"unknown",valueSizeBytes:g,subscriberCount:y,depCount:b,isOrphanEffect:T,orphanKind:k})}let l=a.reduce((p,f)=>p+f.valueSizeBytes,0),c=(p,f)=>[...a].sort(f??((m,h)=>h[p]-m[p])).slice(0,n),d=a.filter(p=>p.orphanKind!=null),u=a.filter(p=>p.isOrphanEffect);return{nodeCount:a.length,edgeCount:r.edges.length,subgraphCount:r.subgraphs.length,nodes:a,totalValueSizeBytes:l,hotspots:{byValueSize:c("valueSizeBytes"),bySubscriberCount:c("subscriberCount"),byDepCount:c("depCount")},orphans:d,orphanEffects:u}}var ce="::",we="__meta__",Xe=1;function Yo(t,e){let n=Math.max(16,t.size*4),r=0;for(;t.size>0;){if(r++>=n){console.error(`[Graph "${e}".destroy] disposer drain exceeded cap (${n}); ${t.size} disposer(s) discarded`),t.clear();return}let o=t.values().next();if(o.done)return;let s=o.value;t.delete(s);try{s()}catch(i){console.error(`[Graph "${e}".destroy] disposer threw:`,i)}}}function _a(t){let e=[];for(let n of Object.keys(t).sort()){let r=t[n].v;r!=null&&e.push(`${n} ${r.id} ${r.version}`)}return e.join(`
|
|
10
|
-
`)}function
|
|
11
|
-
`);return e.logger?.(s),s}function
|
|
12
|
-
`)}function
|
|
13
|
-
`)}function Pa(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function hn(t){let e="^";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="*"){e+=".*";continue}if(r==="?"){e+=".";continue}if(r==="["){let o=t.indexOf("]",n+1);if(o<=n+1){e+="\\[";continue}let s=t.slice(n+1,o);s.startsWith("!")&&(s=`^${s.slice(1)}`),s=s.replace(/\\/g,"\\\\"),e+=`[${s}]`,n=o;continue}e+=Pa(r)}return e+="$",new RegExp(e)}var Ga={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"},Fa={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function yn(t){if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||t==null)return String(t);try{return JSON.stringify(t)}catch{return"[unserializable]"}}function $a(t){return t==="none"?Fa:t==="ansi"||t==null?Ga:{data:t.data??"",dirty:t.dirty??"",resolved:t.resolved??"",invalidate:t.invalidate??"",pause:t.pause??"",resume:t.resume??"",complete:t.complete??"",error:t.error??"",teardown:t.teardown??"",derived:t.derived??"",path:t.path??"",reset:t.reset??""}}function Xo(t){if(t==null)return{};let e=t.detail;return e==="full"?{...t,structured:t.structured??!0,timeline:t.timeline??!0,causal:t.causal??!0,derived:t.derived??!0}:e==="minimal"?{...t,structured:t.structured??!0}:t.format==="stage-log"?{...t,structured:t.structured??!0,timeline:t.timeline??!0}:t}function ja(t,e,n){for(let r=0;r<t.length;r++){let o=t.charCodeAt(r);if(o<32||o===127)throw new Error(`Graph "${e}": ${n} "${t}" must not contain control character (U+${o.toString(16).padStart(4,"0").toUpperCase()} at index ${r})`)}}function hr(t,e,n){if(t==="")throw new Error(`Graph "${e}": ${n} name must be non-empty`);if(t.includes(ce))throw new Error(`Graph "${e}": ${n} "${t}" must not contain '${ce}' (path separator)`);if(t===we)throw new Error(`Graph "${e}": ${n} name "${we}" is reserved for meta companion paths`);ja(t,e,n)}function Ba(t,e){if(t==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let n=t.split(ce);for(let r of n)if(r==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return n}function Va(t,e){let n=!1;for(let o of t)if(!e.isMetaPassthrough(o[0])){n=!0;break}return n?t.filter(o=>e.isMetaPassthrough(o[0])):t}function rs(t){for(let e of t._mounts.values())rs(e);for(let e of t._nodes.values())try{e.down([[ge]],{internal:!0})}catch{}}var pe=class t{name;opts;config;_nodes=new Map;_nodeToName=new WeakMap;_mounts=new Map;_parent=void 0;_storageDisposers=new Set;_disposers=new Set;_destroyed=!1;_topology;_topologyEmitters=new Set;constructor(e,n){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(ce))throw new Error(`Graph name must not contain '${ce}' (got "${e}")`);if(e===we)throw new Error(`Graph name "${we}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...n??{}}),this.config=n?.config??st,this._traceRing=new xt(n?.traceCapacity??1e3),n?.versioning!=null&&this.setVersioning(n.versioning)}ancestors(e=!0){let n=[],r=e?this:this._parent;for(;r!=null;)n.push(r),r=r._parent;return n}get topology(){return this._topology==null&&(this._topology=se(e=>{let n=r=>{e.emit(r)};return this._topologyEmitters.add(n),()=>{this._topologyEmitters.delete(n)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(e){if(!(this._topology==null||this._topologyEmitters.size===0))for(let n of this._topologyEmitters)n(e)}add(e,n){let r=e.name,o=n?.name??r;if(o==null||o==="")throw new Error(`Graph "${this.name}": graph.add requires a non-empty name \u2014 pass via opts.name or set it on the node (e.g. state(0, { name: "x" }))`);let s=o,i=n?.annotation;if(hr(s,this.name,"add"),this._mounts.has(s))throw new Error(`Graph "${this.name}": name "${s}" is already a mount point`);if(this._nodes.has(s))throw new Error(`Graph "${this.name}": node "${s}" already exists`);let a=this._nodeToName.get(e);if(a!==void 0)throw new Error(`Graph "${this.name}": node instance already registered as "${a}"`);return this._nodes.set(s,e),this._nodeToName.set(e,s),this._emitTopology({kind:"added",name:s,nodeKind:"node"}),i!=null&&(this._annotations.set(s,i),this.config.inspectorEnabled&&this._traceRing.push({path:s,annotation:i,timestamp_ns:V()})),e}setVersioning(e){if(e!=null)for(let n of this._nodes.values())n instanceof fe&&n._applyVersioning(e)}remove(e){hr(e,this.name,"remove");let n=this._mounts.get(e);if(n){let s={kind:"mount",nodes:[],mounts:[]},i=[];n._collectObserveTargets("",i);for(let[a,l]of i)a.includes(`${ce}${we}${ce}`)||s.nodes.push(a);return s.nodes.sort(),s.mounts.push(e),s.mounts.push(...n._collectSubgraphs(`${e}${ce}`)),this._mounts.delete(e),n._parent=void 0,rs(n),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:s}),s}let r=this._nodes.get(e);if(!r)throw new Error(`Graph "${this.name}": unknown node or mount "${e}"`);this._nodes.delete(e),this._nodeToName.delete(r),r.down([[ge]],{internal:!0});let o={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:o}),o}removeAll(e){let n=typeof e=="function"?e:(()=>{let s=hn(e);return i=>s.test(i)})(),r={kind:"mount",nodes:[],mounts:[]},o=[...this._nodes.keys(),...this._mounts.keys()].filter(s=>n(s));for(let s of o){let i=this.remove(s);r.nodes.push(...i.nodes),r.mounts.push(...i.mounts)}return r.nodes.sort(),r.mounts.sort(),r}[Symbol.iterator](){let e=[...this._nodes.keys()].sort(),n=this._nodes,r=0;return{[Symbol.iterator](){return this},next(){if(r>=e.length)return{value:void 0,done:!0};let o=e[r++];return{value:[o,n.get(o)],done:!1}}}}node(e){if(e==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(e.includes(ce))return this.resolve(e);let n=this._nodes.get(e);if(!n)throw new Error(`Graph "${this.name}": unknown node "${e}"`);return n}get(e){return this.node(e).cache}set(e,n,r){let o=r?.internal===!0;this.node(e).down([[I,n]],{actor:r?.actor,internal:o,delivery:"write"})}setAll(e,n){let r=Symbol.iterator in e?e:Object.entries(e);re(()=>{for(let[o,s]of r)this.set(o,s,n)})}invalidate(e,n){let r=n?.internal===!0;this.node(e).down([[Se]],{actor:n?.actor,internal:r,delivery:"write"})}error(e,n,r){let o=r?.internal===!0;this.node(e).down([[C,n]],{actor:r?.actor,internal:o,delivery:"write"})}complete(e,n){let r=n?.internal===!0;this.node(e).down([[$]],{actor:n?.actor,internal:r,delivery:"write"})}edges(e){let n=e?.recursive===!0,r=new Map;if(!n){for(let[l,c]of this._nodes)r.set(c,l);let a=[];for(let[l,c]of this._nodes)if(c instanceof fe)for(let d of c._deps){let u=r.get(d.node);u!=null&&a.push([u,l])}return a.sort((l,c)=>l[0]<c[0]?-1:l[0]>c[0]?1:l[1]<c[1]?-1:l[1]>c[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 fe)for(let c of l._deps){let d=s.get(c.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(e,n){if(hr(e,this.name,"mount"),this._nodes.has(e))throw new Error(`Graph "${this.name}": cannot mount at "${e}" \u2014 node with that name exists`);if(this._mounts.has(e))throw new Error(`Graph "${this.name}": mount "${e}" already exists`);if(n===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(n._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${n._parent.name}"`);for(let r=this;r!=null;r=r._parent)if(r===n)throw new Error(`Graph "${this.name}": mount("${e}", \u2026) would create a mount cycle`);return this._mounts.set(e,n),n._parent=this,this._emitTopology({kind:"added",name:e,nodeKind:"mount"}),n}resolve(e){let n=Ba(e,this.name);return this._resolveFromSegments(n)}tryResolve(e){try{return this.resolve(e)}catch{return}}_resolveFromSegments(e){let n=e;if(n[0]===this.name&&(n=n.slice(1),n.length===0))throw new Error(`Graph "${this.name}": resolve path ends at graph name only`);let r=n[0],o=n.slice(1);if(o.length===0){let a=this._nodes.get(r);if(a)return a;throw this._mounts.has(r)?new Error(`Graph "${this.name}": path ends at subgraph "${r}" \u2014 not a node (GRAPHREFLY-SPEC \xA73.5)`):new Error(`Graph "${this.name}": unknown name "${r}"`)}let s=this._nodes.get(r);if(s&&o.length>0&&o[0]===we)return this._resolveMetaChainFromNode(s,o,n.join(ce));let i=this._mounts.get(r);if(!i)throw this._nodes.has(r)?new Error(`Graph "${this.name}": "${r}" is a node; trailing path "${o.join(ce)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${r}"`);return i.resolve(o.join(ce))}_resolveMetaChainFromNode(e,n,r){let o=e,s=0,i=[...n];for(;s<i.length;){if(i[s]!==we)throw new Error(`Graph "${this.name}": expected ${we} segment in meta path "${r}"`);if(s+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${we} 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(e,n){if(n?.internal!==!0){for(let o of e)if(this.config.messageTier(o[0])===3)throw new Error(`Graph "${this.name}": Graph.signal() rejects tier-3 messages (DATA / RESOLVED). Broadcast is for control-plane tiers (START / DIRTY / INVALIDATE / PAUSE / RESUME / COMPLETE / ERROR / TEARDOWN). For per-node value writes, use Graph.set or graph.node(name).down(...).`)}let r=[];if(this._signalDeliver(e,n??{},new Set,r),r.length>0)throw r[0]}_signalDeliver(e,n,r,o){for(let l of this._mounts.values())l._signalDeliver(e,n,r,o);let i=n.internal===!0?{internal:!0}:{actor:n.actor,delivery:"signal"},a=Va(e,this.config);for(let l of[...this._nodes.keys()].sort()){let c=this._nodes.get(l);if(!r.has(c)){r.add(c);try{c.down(e,i)}catch(d){if(d instanceof _e)throw d;o.push(d)}a.length!==0&&this._signalMetaSubtree(c,a,r,i,o)}}}_signalMetaSubtree(e,n,r,o,s){for(let i of Object.keys(e.meta).sort()){let a=e.meta[i];if(!r.has(a)){r.add(a);try{a.down(n,o)}catch(l){if(l instanceof _e)throw l;s.push(l)}this._signalMetaSubtree(a,n,r,o,s)}}}describe(e){if(e?.reactive===!0)return this._describeReactive(e);let n=e?.actor,r=e?.filter,o=ln(e?.detail,e?.fields),s=e?.format==="spec",i=s?ln("minimal"):o,a=[];this._collectObserveTargets("",a);let l=new Map;for(let[v,x]of a)l.set(x,v);let c=[];{let v=a.map(([,N])=>N),x=new Set(l.values()),S=0;for(;v.length>0;){let N=v.shift();if(N instanceof fe)for(let _ of N._deps){let R=_.node;if(l.has(R))continue;let E=R.name??"",M=E;if(!M||x.has(M))if(E){let L=2;for(;x.has(`${E}#${L}`);)L++;M=`${E}#${L}`}else for(M=`__internal__/${S++}`;x.has(M);)M=`__internal__/${S++}`;l.set(R,M),x.add(M),c.push([M,R]),v.push(R)}}}let d=[...a,...c],u={};for(let[v,x]of d){if(n!=null&&!x.allowsObserve(n))continue;let S=mr(x,i),N=x instanceof fe?x._deps.map(M=>l.get(M.node)??M.node.name??""):[],{name:_,...R}=S,E={...R,deps:N};if(!s){let M=this._annotations.get(v);M!=null&&(E.annotation=M)}if(r!=null)if(typeof r=="function"){let M=r;if(!(M.length>=2?M(v,E):M(E)))continue}else{let M=!0;for(let[L,j]of Object.entries(r)){let W=L==="deps_includes"?"depsIncludes":L==="meta_has"?"metaHas":L;if(W==="depsIncludes"){if(!E.deps.includes(String(j))){M=!1;break}continue}if(W==="metaHas"){if(!Object.hasOwn(E.meta??{},String(j))){M=!1;break}continue}if(E[W]!==j){M=!1;break}}if(!M)continue}u[v]=E}let p=new Set(Object.keys(u)),f=[];for(let[v,x]of d)if(x instanceof fe)for(let S of x._deps){let N=l.get(S.node);N!=null&&f.push([N,v])}f.sort((v,x)=>v[0]<x[0]?-1:v[0]>x[0]?1:v[1]<x[1]?-1:v[1]>x[1]?1:0);let m=f.map(([v,x])=>({from:v,to:x}));(n!=null||r!=null)&&(m=m.filter(v=>p.has(v.from)&&p.has(v.to)));let h=this._collectSubgraphs(""),g=n!=null||r!=null?h.filter(v=>{let x=`${v}${ce}`;return[...p].some(S=>S===v||S.startsWith(x))}):h,y=this,b=e,T={name:this.name,nodes:u,edges:m,subgraphs:g,expand(v){let x={...b,format:void 0};return Array.isArray(v)?(x.fields=v,x.detail=void 0):(x.detail=v,x.fields=void 0),y.describe(x)}},k=e??{},w=k.format;return w==="json"?Ca(T,k):w==="pretty"?La(T,k):w==="mermaid"?ts(T,k):w==="mermaid-url"?Da(T,k):w==="d2"?Ia(T,k):w==="ascii"?qo(T,k):T}_collectSubgraphs(e){let n=[];for(let r of[...this._mounts.keys()].sort()){let o=e===""?r:`${e}${r}`;n.push(o),n.push(...this._mounts.get(r)._collectSubgraphs(`${o}${ce}`))}return n}resourceProfile(e){return Jo(this,e)}reachable(e,n,r={}){return r.withDetail===!0?br(this.describe(),e,n,{...r,withDetail:!0}):br(this.describe(),e,n,r)}explain(e,n,r){return r?.reactive===!0?this._explainReactive(e,n,r):this._explainStatic(e,n,r)}_explainStatic(e,n,r){let o=this.describe({detail:"full"}),s=new Map(this._annotations),i=new Map;for(let[a,l]of Object.entries(o.nodes))l.lastMutation!=null&&i.set(a,l.lastMutation);return Do(o,e,n,{...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{},annotations:s,lastMutations:i})}_describeReactive(e){let n={...e,reactive:!1},r=e.reactiveName??"describe",o=0,s=O(o,{name:`${r}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,l=!1,c=()=>{a||l||(a=!0,yt(()=>{a=!1,!l&&(o+=1,s.emit(o))}))},d=i.onEvent(g=>{let y=g.type;y!=="data"&&y!=="error"&&y!=="complete"&&y!=="teardown"||c()}),u=[],p=new WeakSet,f=g=>{if(p.has(g)||l)return;p.add(g);let y=g.topology.subscribe(b=>{for(let T of b){if(T[0]!==I)continue;let k=T[1];if(c(),k.kind==="added"&&k.nodeKind==="mount"){let w=g._mounts.get(k.name);w!=null&&f(w)}}});u.push(y);for(let b of g._mounts.keys()){let T=g._mounts.get(b);T!=null&&f(T)}};f(this);let m;try{m=A([s],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(g,y)=>g===y})}catch(g){d();for(let y of u)y();throw i.dispose(),g}let h=Z(m);return{node:m,dispose(){l=!0,d();for(let g of u)g();u.length=0,i.dispose(),h()}}}_explainReactive(e,n,r){let o=0,s=O(o,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,l=!1,c=i.onEvent(f=>{let m=f.type;m!=="data"&&m!=="error"&&m!=="complete"&&m!=="teardown"||a||l||(a=!0,yt(()=>{a=!1,!l&&(o+=1,s.emit(o))}))}),d={...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{}},u;try{u=A([s],()=>this._explainStatic(e,n,d),{name:r?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:e,to:n},equals:(f,m)=>f.found===m.found&&f.reason===m.reason&&f.steps.length===m.steps.length&&Ka(f.steps,m.steps)})}catch(f){throw c(),i.dispose(),f}let p=Z(u);return{node:u,dispose(){l=!0,c(),i.dispose(),p()}}}_pathsMatching(e){let n=hn(e),r=[];return this._collectObserveTargets("",r),r.map(([o])=>o).filter(o=>n.test(o))}_collectObserveTargets(e,n){for(let r of[...this._mounts.keys()].sort()){let o=e===""?r:`${e}${ce}${r}`;this._mounts.get(r)._collectObserveTargets(o,n)}for(let r of[...this._nodes.keys()].sort()){let o=this._nodes.get(r),s=e===""?r:`${e}${ce}${r}`;n.push([s,o]),this._appendMetaObserveTargets(s,o,n)}}_appendMetaObserveTargets(e,n,r){for(let o of Object.keys(n.meta).sort()){let s=n.meta[o],i=`${e}${ce}${we}${ce}${o}`;r.push([i,s]),this._appendMetaObserveTargets(i,s,r)}}observe(e,n){let r=typeof e=="string",s=Xo(r?n:e),i=s.structured===!0||s.timeline===!0||s.causal===!0||s.derived===!0||s.detail==="minimal"||s.detail==="full"||s.format!=null,a=s.actor;if(r){let d=e,u=this.resolve(d);if(a!=null&&!u.allowsObserve(a))throw new _e({actor:a,action:"observe",nodeName:d});return i?this._buildStructuredObserver([[d,u]],s,"one"):{subscribe(p){return u.subscribe(p)},up(p){try{u.up?.(p)}catch(f){if(f instanceof _e)return;throw f}}}}let l=[];this._collectObserveTargets("",l),l.sort((d,u)=>d[0]<u[0]?-1:d[0]>u[0]?1:0);let c=a==null?l:l.filter(([,d])=>d.allowsObserve(a));return i?this._buildStructuredObserver(c,s,"all"):{subscribe:d=>{let u=c.map(([p,f])=>f.subscribe(m=>{d(p,m)}));return()=>{for(let p of u)p()}},up:(d,u)=>{try{this.resolve(d).up?.(u)}catch(p){if(p instanceof _e)return;throw p}}}}_buildStructuredObserver(e,n,r){let o=r==="one"?e[0]?.[0]:void 0,s=i=>{if(r==="one"&&o!=null){let d=this.resolve(o);return this._buildStructuredObserver([[o,d]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((d,u)=>d[0]<u[0]?-1:d[0]>u[0]?1:0);let l=i.actor,c=l==null?a:a.filter(([,d])=>d.allowsObserve(l));return this._buildStructuredObserver(c,i,"all")};return this._createObserveResult(e,n,s)}_createObserveResult(e,n,r){let o=n.timeline===!0,s=n.causal===!0,i=n.derived===!0,a=n.detail==="minimal",l=this.config.inspectorEnabled,c=(s||i)&&l,d=n.maxEvents,u=d!=null&&d>0?new xt(d):null,p=[],f=new Set,m={},h=new Set,g=0,y=0,b=0,T=0,k=0,w=0,v=!1,x=!1,S=0,N=new Map,_=new Map,R=new Map,E=D=>{u?u.push(D):p.push(D);for(let F of f)F(D)},M=()=>o?{timestamp_ns:V(),in_batch:Dt(),batch_id:S}:{},L=(D,F)=>{if(!(!c||!(D instanceof fe)))return D._setInspectorHook(X=>{if(X.kind==="dep_message")N.set(D,X.depIndex);else if(X.kind==="run"){let te=X.batchData.map((U,Q)=>U!=null&&U.length>0?U.at(-1):X.prevData[Q]);_.set(D,te);let ae=X.batchData.map(U=>U!=null?[...U]:void 0);R.set(D,ae),i&&E({type:"derived",path:F,dep_values:te,dep_batches:ae,...M()})}})},j=D=>{let F=N.get(D),X=_.get(D);if(!s||X==null)return{};let ae=(F!=null&&F>=0&&D instanceof fe?D._deps[F]:void 0)?.node,U=ae?.v,Q=R.get(D);return{trigger_dep_index:F,trigger_dep_name:ae?.name,...U!=null?{trigger_version:{id:U.id,version:U.version}}:{},dep_values:[...X],...Q!=null?{dep_batches:Q}:{}}},W=[],B=[];for(let[D,F]of e){let X=L(F,D);X&&W.push(X),B.push(F.subscribe(te=>{S++;for(let ae of te){let U=ae[0],Q=M();if(U===I){m[D]=ae[1];let Le=F instanceof fe?F.lastMutation?.actor??nt:nt;E({type:"data",path:D,data:ae[1],actor:Le,...Q,...j(F)})}else if(a)U===J?g++:U===H?y++:U===Se?b++:U===Ne?T++:U===Ae?k++:U===ge?w++:U===$&&!h.has(D)?v=!0:U===C&&(x=!0,h.add(D));else if(U===J)g++,E({type:"dirty",path:D,...Q});else if(U===H)y++,E({type:"resolved",path:D,...Q,...j(F)});else if(U===Se)b++,E({type:"invalidate",path:D,...Q});else if(U===Ne)T++,E({type:"pause",path:D,lockId:ae[1],...Q});else if(U===Ae)k++,E({type:"resume",path:D,lockId:ae[1],...Q});else if(U===$)h.has(D)||(v=!0),E({type:"complete",path:D,...Q});else if(U===C){x=!0,h.add(D);let Le=F instanceof fe?F.lastMutation?.actor??nt:nt;E({type:"error",path:D,data:ae[1],actor:Le,...Q})}else U===ge&&(w++,E({type:"teardown",path:D,...Q}))}}))}let ee=!1,Y=()=>{if(!ee){ee=!0;for(let D of B)D();for(let D of W)D();for(let D of K)D({value:void 0,done:!0});K.length=0}},oe=[],K=[];f.add(D=>{let F=K.shift();F?F({value:D,done:!1}):oe.push(D)});let G={get values(){return m},get dirtyCount(){return g},get resolvedCount(){return y},get invalidateCount(){return b},get pauseCount(){return T},get resumeCount(){return k},get teardownCount(){return w},get events(){return u?u.toArray():[...p]},get anyCompletedCleanly(){return v},get anyErrored(){return x},get completedWithoutErrors(){return v&&!x},onEvent(D){return f.add(D),()=>f.delete(D)},dispose:Y,expand(D){Y();let F={...n};return typeof D=="string"?F.detail=D:Object.assign(F,D),r(Xo(F))},[Symbol.asyncIterator](){return{next(){return oe.length>0?Promise.resolve({value:oe.shift(),done:!1}):ee?Promise.resolve({value:void 0,done:!0}):new Promise(D=>K.push(D))},return(){return Y(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger(G,n),G}_attachFormatLogger(e,n){let r=n.format;if(r==null)return;let o=n.logger??(m=>console.log(m)),s=n.includeTypes?new Set(n.includeTypes):null,i=n.excludeTypes?new Set(n.excludeTypes):null,a=s==null&&i==null?()=>!0:m=>(s==null||s.has(m))&&(i==null||!i.has(m)),l=$a(n.theme),c=r==="stage-log"?V():0,d=m=>m==null?"":n.stageLabels?.[m]??m,u=(m,h)=>m.length>h?`${m.slice(0,h-1)}\u2026`:m,p=m=>m.type==="data"||m.type==="error"?u(yn(m.data),120):"",f=m=>{if(r==="stage-log"){let x=(V()-c)/1e9,S=d(m.path).padEnd(9);if(m.type==="data"){let N=p(m);return`[${x.toFixed(3)}s] ${S} \u2190${N?` ${N}`:""}`}if(m.type==="error"){let N=p(m);return`[${x.toFixed(3)}s] ${S} \u2717${N?` ${N}`:""}`}return m.type==="complete"?`[${x.toFixed(3)}s] ${S} \u25A0 complete`:`[${x.toFixed(3)}s] ${S} ${m.type}`}if(r==="json")try{return JSON.stringify(m)}catch{return JSON.stringify({type:m.type,path:m.path,data:"[unserializable]"})}let h=l[m.type]??"",g=m.path?`${l.path}${m.path}${l.reset} `:"",y=m.type==="data"||m.type==="error",b=m.type==="pause"||m.type==="resume",T=y?` ${yn(m.data)}`:b?` ${yn(m.lockId)}`:"",k=m.type==="data"||m.type==="resolved"||m.type==="derived"?m:void 0,w=k?.trigger_dep_name!=null?` <- ${k.trigger_dep_name}`:k?.trigger_dep_index!=null?` <- #${k.trigger_dep_index}`:"",v=m.in_batch?" [batch]":"";return`${g}${h}${m.type.toUpperCase()}${l.reset}${T}${w}${v}`};e.onEvent(m=>{a(m.type)&&o(f(m),m)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){Yo(this._disposers,this.name),this.signal([[ge]],{internal:!0}),Yo(this._storageDisposers,this.name);for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}get destroyed(){return this._destroyed}_destroyClearOnly(){for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}snapshot(e){let{expand:n,...r}=this.describe({detail:"full"}),o={};for(let a of Object.keys(r.nodes).sort()){let{lastMutation:l,guard:c,...d}=r.nodes[a];o[a]=d}let s=[...r.subgraphs].sort(),i={...r,version:1,nodes:o,subgraphs:s};if(e?.format==null)return i;if(e.format==="json-string")return JSON.stringify(i);if(e.format==="bytes"){if(e.codec==null)throw new Error("snapshot({format: 'bytes'}) requires a `codec` name");let a=this.config.lookupCodec(e.codec);if(a==null)throw new Error(`snapshot: codec "${e.codec}" is not registered on this graph's config. Call config.registerCodec(...) before creating nodes.`);return Or(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,n){let r=n?.config??st,{codec:o,codecVersion:s,payload:i}=Ar(e,r);return o.decode(i,s)}restore(e,n){if(Qo(e),e.name!==this.name)throw new Error(`Graph "${this.name}": restore snapshot name "${e.name}" does not match this graph`);let r=n?.only==null?null:(Array.isArray(n.only)?n.only:[n.only]).map(s=>hn(s)),o=n?.includeProducers===!0;for(let s of Object.keys(e.nodes).sort()){if(r!==null&&!r.some(a=>a.test(s)))continue;let i=e.nodes[s];if(i!==void 0){if(!("value"in i)||i.value===void 0){"value"in i&&i.value===void 0&&n?.onError?.(s,new Error(`restore: slice.value is undefined for "${s}" (undefined is the global SENTINEL; not valid DATA)`));continue}if(!(i.type==="derived"||i.type==="effect")&&!(i.type==="producer"&&!o)){if(i.v!=null){let 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(e,n){Qo(e);let r=typeof n=="function"?n:n?.build,o=typeof n=="function"?void 0:n?.factories,s=new t(e.name);if(r)return r(s),s.restore(e),s;for(let f of[...e.subgraphs].sort((m,h)=>{let g=m.split(ce).length,y=h.split(ce).length;return g!==y?g-y:m<h?-1:m>h?1:0})){let m=f.split(ce),h=s;for(let g of m)h._mounts.has(g)||h.mount(g,new t(g)),h=h._mounts.get(g)}let i=o?Object.entries(o).map(([f,m])=>({re:hn(f),factory:m})):[],a=f=>{for(let m of i)if(m.re.test(f))return m.factory},l=f=>{let m=f.split(ce),h=m.pop();if(h==null||h.length===0)throw new Error(`invalid snapshot path "${f}"`);let g=s;for(let y of m){let b=g._mounts.get(y);if(!b)throw new Error(`unknown mount "${y}" in path "${f}"`);g=b}return[g,h]},c=Object.entries(e.nodes).filter(([f])=>!f.includes(`${ce}${we}${ce}`)).sort((f,m)=>f[0]<m[0]?-1:f[0]>m[0]?1:0),d=new Map(c),u=new Map,p=!0;for(;d.size>0&&p;){p=!1;for(let[f,m]of[...d.entries()]){let h=m?.deps??[];if(!h.every(w=>u.has(w)))continue;let[g,y]=l(f),b={...m?.meta??{}},T=a(f),k;if(m?.type==="state")k=O(m.value,{meta:b});else{if(T==null)continue;k=T(y,{path:f,type:m.type,value:m.value,meta:b,deps:h,resolvedDeps:h.map(w=>u.get(w))})}g.add(k,{name:y}),u.set(f,k),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(e),s}toJSON(){return this.snapshot()}attachStorage(e,n={}){let r=e.map(c=>({tier:c,debounceMs:Math.max(0,c.debounceMs??0),compactEvery:Math.max(1,c.compactEvery??10),timer:void 0,seq:0,lastSnapshot:void 0,lastFingerprint:"",disposed:!1,savePending:void 0}));n.autoRestore===!0&&this._cascadeRestore(e,n.onError);let o=(c,d)=>{if(c.disposed)return;let u=_a(d.nodes);if(c.lastSnapshot!=null&&u!==""&&u===c.lastFingerprint)return;let p=c.seq+1,f=Te(),g=c.lastSnapshot==null||p%c.compactEvery===0?{mode:"full",snapshot:d,seq:p,timestamp_ns:f,format_version:Xe}:{mode:"diff",diff:os(c.lastSnapshot,d),seq:p,timestamp_ns:f,format_version:Xe};if(c.tier.filter&&!c.tier.filter(this.name,g))return;let y;try{y=c.tier.save(this.name,g)}catch(b){n.onError?.(b,c.tier);return}if(y&&typeof y.then=="function"){let k=(c.savePending??Promise.resolve()).then(()=>y,()=>y).then(()=>{c.disposed||(c.seq=p,c.lastSnapshot=d,c.lastFingerprint=u)},w=>{n.onError?.(w,c.tier)});c.savePending=k.finally(()=>{c.savePending===k&&(c.savePending=void 0)})}else c.seq=p,c.lastSnapshot=d,c.lastFingerprint=u},s=(c,d)=>{try{o(c,d)}catch(u){n.onError?.(u,c.tier)}},i=(c,d)=>{if(!d.some(m=>{let h=this.config.messageTier(m[0]);return h>=3&&h<5}))return;if(n.filter){let m=this.tryResolve(c);if(m==null)return;let h=mr(m,ln("standard"));if(!n.filter(c,h))return}let p,f=()=>(p==null&&(p=this.snapshot()),p);for(let m of r)m.disposed||(m.debounceMs===0?s(m,f()):(m.timer==null&&(m.timer=new de),m.timer.start(m.debounceMs,()=>{m.disposed||s(m,this.snapshot())})))},a;if(n.paths!=null){let d=(typeof n.paths=="string"?this._pathsMatching(n.paths):n.paths).map(u=>{let p=this.tryResolve(u);return p==null?()=>{}:p.subscribe(f=>i(u,f))});a=()=>{for(let u of d)u()}}else a=this.observe().subscribe((c,d)=>i(c,d));let l=()=>{a();for(let c of r)c.disposed=!0,c.timer?.cancel();this._storageDisposers.delete(l)};return this._storageDisposers.add(l),{dispose:l}}async _cascadeRestore(e,n){for(let r of e){let o;try{o=await r.load(this.name)}catch(i){n?.(i,r);continue}if(o==null||typeof o!="object"||Array.isArray(o))continue;let s=o;try{if(s.mode==="full"&&s.snapshot!=null)return this.restore(s.snapshot),!0;if(s.version===Xe&&s.nodes!=null)return this.restore(s),!0}catch(i){n?.(i,r)}}return!1}static async fromStorage(e,n,r){for(let o of n){let s;try{s=await o.load(e)}catch(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===Xe&&i.nodes!=null?i:void 0;if(a!=null)try{return t.fromSnapshot(a,r)}catch(l){r?.onError?.(l,o)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${e}" across ${n.length} tier(s)`)}_annotations=new Map;_traceRing;trace(e,n,r){if(e!=null&&n!=null){if(this.tryResolve(e)==null)return;if(this._annotations.set(e,n),this.config.inspectorEnabled){let o={path:e,annotation:n,timestamp_ns:V(),...r?.actor!=null?{actor:r.actor}:{}};this._traceRing.push(o)}return}return e!=null?this.config.inspectorEnabled?this._annotations.get(e):void 0:this.config.inspectorEnabled?this._traceRing.toArray():[]}annotation(e){return this._annotations.get(e)}clearTrace(){this._annotations.clear(),this._traceRing.clear()}pruneTrace(e){let n=this._traceRing.toArray().filter(o=>!e(o)),r=this._traceRing.size-n.length;this._traceRing.clear();for(let o of n)this._traceRing.push(o);return r}static diff(e,n){let r=new Set(Object.keys(e.nodes)),o=new Set(Object.keys(n.nodes)),s=[...o].filter(b=>!r.has(b)).sort(),i=[...r].filter(b=>!o.has(b)).sort(),a=[],l=[];for(let b of r){if(!o.has(b))continue;let T=e.nodes[b],k=n.nodes[b],w=T.v,v=k.v;w!=null&&v!=null&&w.id===v.id&&w.version!==v.version&&l.push({path:b,id:w.id,from:w.version,to:v.version});let x=w!=null&&v!=null&&w.id===v.id&&w.version===v.version;for(let S of["type","status","sentinel"]){let N=T[S],_=k[S];N!==_&&a.push({path:b,field:S,from:N,to:_})}if(!x)for(let S of["value","meta"]){let N=T[S],_=k[S];Ma(N,_)||a.push({path:b,field:S,from:N,to:_})}}let c=b=>`${b.from} ${b.to}`,d=new Set(e.edges.map(c)),u=new Set(n.edges.map(c)),p=n.edges.filter(b=>!d.has(c(b))),f=e.edges.filter(b=>!u.has(c(b))),m=new Set(e.subgraphs),h=new Set(n.subgraphs),g=[...h].filter(b=>!m.has(b)).sort(),y=[...m].filter(b=>!h.has(b)).sort();return{nodesAdded:s,nodesRemoved:i,nodesChanged:a,versionChanges:l,edgesAdded:p,edgesRemoved:f,subgraphsAdded:g,subgraphsRemoved:y}}};function os(t,e){let n=pe.diff(t,e),r={};for(let o of n.nodesAdded){let s=e.nodes[o];s!=null&&(r[o]=s)}return{...n,nodesAddedFull:r}}function br(t,e,n,r={}){let o={paths:[],depths:new Map,truncated:!1};if(!e)return r.withDetail?o:[];if(!r.both&&n!=="upstream"&&n!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let s=r.maxDepth;if(s!=null&&(!Number.isInteger(s)||s<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(s===0)return r.withDetail?o:[];let i=new Map,a=new Map,l=new Map,c=new Map,d=new Set;for(let[T,k]of Object.entries(t.nodes)){if(!T)continue;d.add(T);let w=k.deps??[];i.set(T,w);for(let v of w)v&&(d.add(v),a.has(v)||a.set(v,new Set),a.get(v).add(T))}for(let T of t.edges){if(T==null||typeof T!="object")continue;let k=typeof T.from=="string"?T.from:"",w=typeof T.to=="string"?T.to:"";!k||!w||(d.add(k),d.add(w),c.has(k)||c.set(k,new Set),c.get(k).add(w),l.has(w)||l.set(w,new Set),l.get(w).add(k))}if(!d.has(e))return r.withDetail?o:[];let u=r.both===!0,p=T=>{if(u){let x=i.get(T)??[],S=l.get(T),N=a.get(T),_=c.get(T),R=[...x];return S&&R.push(...S),N&&R.push(...N),_&&R.push(..._),R}if(n==="upstream"){let x=i.get(T)??[],S=l.get(T);return S?[...x,...S]:x}let k=a.get(T),w=c.get(T),v=k?[...k]:[];return w&&v.push(...w),v},f=new Set([e]),m=new Map,h=[{path:e,depth:0}],g=0,y=!1;for(;g<h.length;){let T=h[g++];if(s!=null&&T.depth>=s){p(T.path).length>0&&(y=!0);continue}for(let k of p(T.path))!k||f.has(k)||(f.add(k),m.set(k,T.depth+1),h.push({path:k,depth:T.depth+1}))}let b=[...m.keys()].sort((T,k)=>T<k?-1:T>k?1:0);return r.withDetail?{paths:b,depths:m,truncated:y}:b}function Ka(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.path!==o.path||r.type!==o.type||r.status!==o.status||r.hop!==o.hop||r.dep_index!==o.dep_index||r.annotation!==o.annotation||r.value!==o.value||r.lastMutation!==o.lastMutation)return!1;let s=r.v,i=o.v;if(s!==i&&(s==null||i==null||s.id!==i.id||s.version!==i.version))return!1}return!0}function ss(t,e){return je("messaging",t,e)}var Tr=class extends pe{_log;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=$e([],{name:"events",maxSize:n.retainedLimit}),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=A([this.events],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:ss("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(Z(this.latest)),this.hasLatest=A([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:ss("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(Z(this.hasLatest)),this.addDisposer(()=>{this.events.down([[$]])}),this.addDisposer(()=>this._log.disposeAllViews())}publish(e){this._log.append(e)}retained(){return this.events.cache}};function vr(t,e){return new Tr(t,e)}Re();le();Me();q();function Ua(t,e){if(typeof e=="string")return{node:t.resolve(e),path:e};let n=za(t,e);if(!n)throw new Error("orchestration dep node must already be registered in the graph so explicit edges can be recorded; pass a string path or register the node first");return{node:e,path:n}}function za(t,e){let n=t.describe(),r=`::${we}::`;for(let o of Object.keys(n.nodes).sort())if(!o.includes(r))try{if(t.resolve(o)===e)return o}catch{}}function Ha(t,e,n,r){t.add(n,{name:e})}function Wa(t,e){return je("orchestration",t,e)}function is(t,e,n,r){let o=r?.maxPending??1/0;if(o<1&&o!==1/0)throw new RangeError("gate: maxPending must be >= 1");let s=r?.startOpen??!1,i=Ua(t,n),a=O([],{name:"pending",equals:()=>!1}),l=O(s,{name:"isOpen"}),c=A([a],([v])=>v.length,{name:"count"}),d=O(null,{name:"lastRejected",equals:()=>!1}),u=[],p=!1,f=s,m=l.subscribe(v=>{for(let x of v)x[0]===I&&(f=x[1])});function h(){a.emit([...u])}function g(v){u.push(v),u.length>o&&u.shift(),h()}function y(v){let x=u.splice(0,v);return h(),x}function b(v){if(p)throw new Error(`gate: ${v}() called after gate was torn down`)}let T=ie([i.node],(v,x,S)=>{let N=S.terminalDeps[0];if(N!==void 0){p=!0,u=[],h(),x.down(N===!0?[[$]]:[[C,N]]);return}let _=v[0];if(_==null||_.length===0){x.down([[H]]);return}for(let R of _)f?x.emit(R):(g(R),x.down([[H]]))},{name:e,describeKind:"derived",meta:Wa("gate",r?.meta)}),k={node:T,pending:a,count:c,isOpen:l,lastRejected:d,approve(v=1){b("approve");let x=y(v);for(let S of x){if(p)break;T.emit(S)}},reject(v=1){b("reject");let x=[...u],S=Math.min(v,x.length);if(S===0){y(v);return}re(()=>{for(let N=0;N<S;N++)d.emit(x[N]);y(v)})},modify(v,x=1){b("modify");let S=[...u],N=y(x);for(let _=0;_<N.length&&!p;_++)T.emit(v(N[_],_,S))},open(){b("open"),re(()=>{l.emit(!0);let v=y(u.length);for(let x of v){if(p)break;T.emit(x)}})},close(){b("close"),l.emit(!1)}};t.addDisposer(c.subscribe(()=>{})),t.addDisposer(m),Ha(t,e,T,i.path?[i.path]:[]);let w=new pe(`${e}_state`);return w.add(a,{name:"pending"}),w.add(l,{name:"isOpen"}),w.add(c,{name:"count"}),w.add(d,{name:"lastRejected"}),t.mount(`${e}_state`,w),t.addDisposer(d.subscribe(()=>{})),k}async function as(t,e,n,r){let o="",s=0;for await(let i of t.stream(e,n))r.publish({...i,seq:s++,ts:Te()}),i.type==="token"&&(o+=i.delta);return o}function cs(t,e){if(e==="json")try{return JSON.parse(pt(t))}catch(n){let r=t.slice(0,160);throw new Error(`streamingPromptNode: format:"json" \u2014 failed to parse accumulated text as JSON: ${n.message}; content preview: ${r}`)}return t}function ls(t,e){return A([t.latest],([n],r)=>{let o=r.store;if(n==null)return o.acc??"";let s=n;return s.seq===0&&(o.acc=""),s.type==="token"&&(o.acc=(o.acc??"")+s.delta),o.acc??""},{name:e,meta:z("accumulated_text"),initial:""})}function qa(t,e,n,r){let o=r?.name??"llm",s=r?.format??"text",i=vr(`${o}/stream`,{...r?.retainedLimit!=null?{retainedLimit:r.retainedLimit}:{}}),a=A(e,u=>{if(u.some(f=>f==null))return[];let p=typeof n=="string"?n:n(...u);return p?[{role:"user",content:p}]:[]},{name:`${o}::messages`,meta:z("prompt_node::messages"),initial:[]}),l=ue(a,u=>{let p=u;if(!p||p.length===0)return O(null);let f=new AbortController;async function*m(){try{let h=await as(t,p,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt,signal:f.signal},i);yield cs(h,s)}finally{f.abort()}}return P(m())}),c=ls(i,`${o}::accumulatedText`),d=Z(l);return{output:l,deltaTopic:i,accumulatedText:c,dispose:()=>{d(),i.destroy()}}}function Ja(t,e,n,r,o,s){let i=O(0,{name:`${e}/cancel`}),a=0,l=[...r,i],c=s?.name??e,d=s?.format??"text",u=vr(`${c}/stream`,{...s?.retainedLimit!=null?{retainedLimit:s.retainedLimit}:{}}),p=A(l,v=>{let x=v.slice(0,-1);if(x.some(N=>N==null))return[];let S=typeof o=="string"?o:o(...x);return S?[{role:"user",content:S}]:[]},{name:`${c}::messages`,meta:z("prompt_node::messages"),initial:[]}),f=ue(p,v=>{let x=v;if(!x||x.length===0)return O(null);let S=new AbortController;async function*N(){try{let _=await as(n,x,{model:s?.model,temperature:s?.temperature,maxTokens:s?.maxTokens,systemPrompt:s?.systemPrompt,signal:S.signal},u);yield cs(_,d)}finally{S.abort()}}return P(N())}),m=ls(u,`${c}::accumulatedText`),h=so(f,v=>v!=null);t.add(h,{name:`${e}/raw`});let g=is(t,`${e}/gate`,`${e}/raw`,s?.gate),y=Z(f),b=Z(g.node),T=Z(m);t.addDisposer(y),t.addDisposer(b),t.addDisposer(T);let k=g.reject.bind(g),w={...g,reject(v=1){re(()=>{k(v),i.emit(++a)})}};return{output:g.node,deltaTopic:u,accumulatedText:m,gate:w,dispose:()=>{y(),b(),T(),u.destroy()}}}q();ne();function Ya(t,e){let n=e?.separator??`
|
|
6
|
+
`)}]});let s={};return e?.maxTokens!=null&&(s.maxOutputTokens=e.maxTokens),e?.temperature!=null&&(s.temperature=e.temperature),e?.maxReasoningTokens!=null&&(s.thinkingConfig={thinkingBudget:e.maxReasoningTokens}),Object.keys(s).length>0&&(o.generationConfig=s),e?.tools&&e.tools.length>0&&(o.tools=[{functionDeclarations:e.tools.map(ci)}]),e?.providerExtras&&Object.assign(o,e.providerExtras),o}function ci(t){return{name:t.name,description:t.description,parameters:t.parameters}}function co(t,e,n){let r={},o=t.generationConfig;o&&(typeof o.maxOutputTokens=="number"&&(r.maxOutputTokens=o.maxOutputTokens),typeof o.temperature=="number"&&(r.temperature=o.temperature),o.thinkingConfig&&(r.thinkingConfig=o.thinkingConfig)),t.systemInstruction&&(r.systemInstruction=t.systemInstruction),t.tools&&(r.tools=t.tools);for(let[s,i]of Object.entries(t))s==="contents"||s==="generationConfig"||s==="systemInstruction"||s==="tools"||s==="abortSignal"||s==="model"||(r[s]=i);return n&&(r.abortSignal=n),{model:e,contents:t.contents,config:Object.keys(r).length>0?r:void 0}}function Bn(t){let e={input:{regular:0},output:{regular:0},raw:t};if(!t)return e;let n=t.promptTokenCount??0,r=t.cachedContentTokenCount??0;if(e.input.regular=Math.max(0,n-r),r>0&&(e.input.cacheRead=r),t.toolUsePromptTokenCount&&(e.input.toolUse=t.toolUsePromptTokenCount),t.promptTokensDetails)for(let o of t.promptTokensDetails){let s=o.modality?.toLowerCase();s==="image"?e.input.image=(e.input.image??0)+o.tokenCount:s==="audio"?e.input.audio=(e.input.audio??0)+o.tokenCount:s==="video"&&(e.input.video=(e.input.video??0)+o.tokenCount)}return e.output.regular=t.candidatesTokenCount??0,t.thoughtsTokenCount&&(e.output.reasoning=t.thoughtsTokenCount),e}function po(t,e){let n=t.candidates?.[0],r=n?.content?.parts??[],o=[],s=[],i=0;for(let a of r)typeof a.text=="string"&&o.push(a.text),a.functionCall&&s.push({id:`${a.functionCall.name}-${i++}`,name:a.functionCall.name,arguments:a.functionCall.args??{}});return{content:o.join(""),toolCalls:s.length>0?s:void 0,usage:Bn(t.usageMetadata),finishReason:n?.finishReason,latencyMs:e,model:t.modelVersion,provider:"google"}}function pi(t){if(t.apiKey)return t.apiKey;let e=globalThis.process?.env;return e?.GOOGLE_API_KEY??e?.GEMINI_API_KEY}function fi(t){let e=t.baseURL??"https://generativelanguage.googleapis.com/v1beta",n=t.fetchImpl??fetch,r=s=>{let i=s?.model??t.model;if(!i)throw new Error("googleAdapter: model must be set via options.model or invokeOpts.model");return i},o=()=>{let s=pi(t);if(!s)throw new Error("googleAdapter: apiKey required for invoke/stream");return`key=${encodeURIComponent(s)}`};return{provider:"google",model:t.model,async invoke(s,i){let a=r(i),d=Ht(s,i),u=F(),l=`${e}/models/${encodeURIComponent(a)}:generateContent?${o()}`,c=await n(l,{method:"POST",headers:{"content-type":"application/json",...t.headers??{}},body:JSON.stringify(d),signal:i?.signal});if(!c.ok)throw await Le(c,"Google");let p=await c.json(),f=Math.max(0,(F()-u)/1e6);return po(p,f)},async*stream(s,i){let a=r(i),d=Ht(s,i),u=`${e}/models/${encodeURIComponent(a)}:streamGenerateContent?alt=sse&${o()}`,l=await n(u,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",...t.headers??{}},body:JSON.stringify(d),signal:i?.signal});if(!l.ok)throw await Le(l,"Google");if(!l.body)throw new Error("googleAdapter: streaming response has no body");let c,p;for await(let f of st(l.body,{signal:i?.signal})){if(!f.data)continue;let m;try{m=JSON.parse(f.data)}catch{continue}let h=m.candidates?.[0];for(let g of h?.content?.parts??[])typeof g.text=="string"&&(g.thought?yield{type:"thinking",delta:g.text}:yield{type:"token",delta:g.text}),g.functionCall&&(yield{type:"tool-call-delta",delta:{name:g.functionCall.name,argumentsDelta:JSON.stringify(g.functionCall.args??{})}});h?.finishReason&&(p=h.finishReason),m.usageMetadata&&(c=m.usageMetadata)}c&&(yield{type:"usage",usage:Bn(c)}),yield{type:"finish",reason:p??"stop"}}}}function mi(t){let e=t.sdk;if(!e)throw new Error("sdkBackedGoogle: sdk instance required");return{provider:"google",model:t.model,async invoke(n,r){let o=Ht(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=co(o,s,r?.signal),a=F(),d=await e.models.generateContent(i),u=Math.max(0,(F()-a)/1e6);return po(d,u)},async*stream(n,r){if(!e.models.generateContentStream)throw new Error("sdkBackedGoogle: SDK instance does not expose generateContentStream");let o=Ht(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=co(o,s,r?.signal),a,d,u=await e.models.generateContentStream(i);for await(let l of u){let c=l.candidates?.[0];for(let p of c?.content?.parts??[])typeof p.text=="string"&&(p.thought?yield{type:"thinking",delta:p.text}:yield{type:"token",delta:p.text}),p.functionCall&&(yield{type:"tool-call-delta",delta:{name:p.functionCall.name,argumentsDelta:JSON.stringify(p.functionCall.args??{})}});c?.finishReason&&(d=c.finishReason),l.usageMetadata&&(a=l.usageMetadata)}a&&(yield{type:"usage",usage:Bn(a)}),yield{type:"finish",reason:d??"stop"}}}}ce();var gi={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 Vn(t={}){return t.sdk?vi(t):Ti(t)}function Wt(t,e,n,r,o){let s=e?.model??n;if(!s)throw new Error("openAICompatAdapter: model must be set via options.model or invokeOpts.model");let i=t.map(hi);e?.systemPrompt&&!t.some(d=>d.role==="system")&&i.unshift({role:"system",content:e.systemPrompt});let a={model:s,messages:i};return e?.maxTokens!=null&&(a.max_tokens=e.maxTokens),e?.temperature!=null&&(a.temperature=e.temperature),e?.tools&&e.tools.length>0&&(a.tools=e.tools.map(yi)),e?.maxReasoningTokens!=null&&(a.reasoning={max_tokens:e.maxReasoningTokens}),r&&(a.stream=!0,a.stream_options={include_usage:!0}),o&&Object.assign(a,o),e?.providerExtras&&Object.assign(a,e.providerExtras),a}function hi(t){return t.role==="tool"?{role:"tool",tool_call_id:t.toolCallId,content:t.content}:t.role==="assistant"&&t.toolCalls&&t.toolCalls.length>0?{role:"assistant",content:t.content||null,tool_calls:t.toolCalls.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.arguments)}}))}:{role:t.role,content:t.content}}function yi(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}}function Kn(t){let e={input:{regular:0},output:{regular:0},raw:t};if(!t)return e;let n=t.prompt_tokens??0,r=t.prompt_tokens_details?.cached_tokens??0;t.prompt_cache_hit_tokens!=null?(r=t.prompt_cache_hit_tokens,e.input.regular=t.prompt_cache_miss_tokens??Math.max(0,n-r)):e.input.regular=Math.max(0,n-r),r>0&&(e.input.cacheRead=r),t.prompt_tokens_details?.audio_tokens&&(e.input.audio=t.prompt_tokens_details.audio_tokens);let o=t.completion_tokens??0,s=t.completion_tokens_details?.reasoning_tokens??0;return e.output.regular=Math.max(0,o-s),s>0&&(e.output.reasoning=s),t.completion_tokens_details?.audio_tokens&&(e.output.audio=t.completion_tokens_details.audio_tokens),t.completion_tokens_details?.accepted_prediction_tokens&&(e.output.predictionAccepted=t.completion_tokens_details.accepted_prediction_tokens),t.completion_tokens_details?.rejected_prediction_tokens&&(e.output.predictionRejected=t.completion_tokens_details.rejected_prediction_tokens),e}function fo(t,e,n){let r=t.choices[0],o=r?.message,s=o?.content??"",i=(o?.tool_calls??[]).map(a=>({id:a.id,name:a.function.name,arguments:bi(a.function.arguments)}));return{content:s,toolCalls:i.length>0?i:void 0,usage:Kn(t.usage),finishReason:r?.finish_reason,latencyMs:e,model:t.model,provider:n}}function bi(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!=null?e:{_raw:t}}catch{return{_raw:t}}}function mo(t){let e=t.preset??"openai",n=gi[e],r=t.baseURL??n.baseURL,o=t.provider??n.provider,s=n.apiKeyEnv,i=t.apiKey??(s?globalThis.process?.env?.[s]:void 0);return{provider:o,baseURL:r,apiKey:i}}function Ti(t){let{provider:e,baseURL:n,apiKey:r}=mo(t),o=t.fetchImpl??fetch,s=e!=="ollama",i=()=>{let a={"content-type":"application/json",...t.headers??{}};if(s){if(!r)throw new Error(`openAICompatAdapter[${e}]: apiKey required for invoke/stream`);a.authorization=`Bearer ${r}`}return a};return{provider:e,model:t.model,async invoke(a,d){let u=Wt(a,d,t.model,!1,t.bodyExtras),l=F(),c=await o(`${n}/chat/completions`,{method:"POST",headers:i(),body:JSON.stringify(u),signal:d?.signal});if(!c.ok)throw await Le(c,e);let p=await c.json(),f=Math.max(0,(F()-l)/1e6);return fo(p,f,e)},async*stream(a,d){let u=Wt(a,d,t.model,!0,t.bodyExtras),l=await o(`${n}/chat/completions`,{method:"POST",headers:{...i(),accept:"text/event-stream"},body:JSON.stringify(u),signal:d?.signal});if(!l.ok)throw await Le(l,e);if(!l.body)throw new Error(`openAICompatAdapter[${e}]: streaming response has no body`);let c,p;for await(let f of st(l.body,{signal:d?.signal})){if(!f.data||f.data==="[DONE]")continue;let m;try{m=JSON.parse(f.data)}catch{continue}let h=m.choices;if(h){let g=h[0];if(g?.delta?.content&&(yield{type:"token",delta:g.delta.content}),g?.delta?.reasoning_content&&(yield{type:"thinking",delta:g.delta.reasoning_content}),g?.delta?.tool_calls)for(let y of g.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:y.id,name:y.function?.name,argumentsDelta:y.function?.arguments}};g?.finish_reason&&(p=g.finish_reason)}m.usage&&(c=m.usage,yield{type:"usage",usage:Kn(c)})}yield{type:"finish",reason:p??"stop"}}}}function vi(t){let e=t.sdk;if(!e)throw new Error("sdkBackedOpenAI: sdk instance required");let{provider:n}=mo(t);return{provider:n,model:t.model,async invoke(r,o){let s=Wt(r,o,t.model,!1,t.bodyExtras),i=F(),a=await e.chat.completions.create(s,{signal:o?.signal}),d=Math.max(0,(F()-i)/1e6);return fo(a,d,n)},async*stream(r,o){let s=Wt(r,o,t.model,!0,t.bodyExtras),i=await e.chat.completions.create(s,{signal:o?.signal}),a,d;for await(let u of i){let l=u.choices;if(l){let p=l[0];if(p?.delta?.content&&(yield{type:"token",delta:p.delta.content}),p?.delta?.reasoning_content&&(yield{type:"thinking",delta:p.delta.reasoning_content}),p?.delta?.tool_calls)for(let f of p.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:f.id,name:f.function?.name,argumentsDelta:f.function?.arguments}};p?.finish_reason&&(d=p.finish_reason)}let c=u.usage;c&&(a=c,yield{type:"usage",usage:Kn(c)})}yield{type:"finish",reason:d??"stop"}}}}function wi(t){switch(t.provider){case"anthropic":{let e={apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return Ln(e)}case"google":{let e={apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return jn(e)}case"dry-run":{let e={model:t.model,...t.extras};return He(e)}case"fallback":{let e={provider:t.provider,model:t.model,...t.extras};return Fn(e)}case"openai":case"openrouter":case"groq":case"ollama":case"deepseek":case"xai":{let e={preset:t.provider,apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,bodyExtras:t.bodyExtras,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return Vn(e)}default:{let e=t.provider;throw new Error(`createAdapter: unknown provider: ${String(e)}`)}}}ce();U();ke();ne();U();var Un=class{_version=0;_maxSize;_buf;_head=0;_size=0;constructor(e,n){if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(this._maxSize=n,n!==void 0){if(this._buf=new Array(n),e&&e.length>0){let r=Math.min(e.length,n),o=e.length-r;for(let s=0;s<r;s++)this._buf[s]=e[o+s];this._size=r}}else this._buf=e?[...e]:[],this._size=this._buf.length}get version(){return this._version}get size(){return this._size}at(e){if(!Number.isInteger(e))return;let n=e>=0?e:this._size+e;if(!(n<0||n>=this._size))return this._maxSize!==void 0?this._buf[(this._head+n)%this._maxSize]:this._buf[n]}append(e){this._rawAppend(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._maxSize!==void 0&&e.length>this._maxSize?e.length-this._maxSize:0;for(let r=n;r<e.length;r++)this._rawAppend(e[r]);this._version+=1}clear(){if(this._size===0)return 0;let e=this._size;if(this._maxSize===void 0)this._buf.length=0;else for(let n=0;n<e;n++)this._buf[(this._head+n)%this._maxSize]=void 0;return this._head=0,this._size=0,this._version+=1,e}trimHead(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`trimHead: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return 0;let n=Math.min(e,this._size);if(this._maxSize===void 0)this._buf.splice(0,n);else{for(let r=0;r<n;r++)this._buf[(this._head+r)%this._maxSize]=void 0;this._head=(this._head+n)%this._maxSize}return this._size-=n,this._version+=1,n}slice(e,n){if(!Number.isInteger(e)||e<0)throw new RangeError(`slice: start must be a non-negative integer (got ${e})`);if(n!==void 0&&(!Number.isInteger(n)||n<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${n})`);let r=n===void 0?this._size:Math.min(Math.max(n,0),this._size),o=Math.min(e,this._size);if(o>=r)return[];let s=r-o;if(this._maxSize===void 0)return this._buf.slice(o,r);let i=new Array(s);for(let a=0;a<s;a++)i[a]=this._buf[(this._head+o+a)%this._maxSize];return i}tail(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`tail: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return[];let n=Math.min(e,this._size);return this.slice(this._size-n,this._size)}toArray(){if(this._maxSize===void 0)return[...this._buf];let e=new Array(this._size);for(let n=0;n<this._size;n++)e[n]=this._buf[(this._head+n)%this._maxSize];return e}_rawAppend(e){if(this._maxSize===void 0){this._buf.push(e),this._size=this._buf.length;return}this._size<this._maxSize?(this._buf[(this._head+this._size)%this._maxSize]=e,this._size+=1):(this._buf[this._head]=e,this._head=(this._head+1)%this._maxSize)}};function go(t){return t.subscribe(()=>{})}var ki=64;function Ge(t,e={}){let{name:n,maxSize:r,versioning:o,backend:s}=e,i=s??new Un(t,r),a=A(i.toArray(),{name:n,describeKind:"state",equals:(m,h)=>m===h,...o!=null?{versioning:o}:{}});function d(){let m=i.toArray();X(()=>{a.down([[z]]),a.down([[C,m]])})}let u=new Map,l=new Map;function c(m,h){return`${m}:${h===void 0?"END":h}`}function p(m){if(m.size<ki)return;let h=m.keys().next();if(h.done)return;let g=m.get(h.value);g!==void 0&&g.dispose(),m.delete(h.value)}function f(m){let h=i.version;try{return m()}finally{i.version!==h&&d()}}return{entries:a,get size(){return i.size},at(m){return i.at(m)},append(m){f(()=>i.append(m))},appendMany(m){m.length!==0&&f(()=>i.appendMany(m))},clear(){f(()=>i.clear())},trimHead(m){f(()=>i.trimHead(m))},tail(m){if(!Number.isInteger(m)||m<0)throw new RangeError(`tail: n must be a non-negative integer (got ${m})`);let h=u.get(m);if(h!==void 0)return u.delete(m),u.set(m,h),h.node;p(u);let g=E([a],([b])=>{let v=b;return m===0||v.length===0?[]:v.slice(Math.max(0,v.length-m))},{initial:i.tail(m),describeKind:"derived"}),y=go(g);return u.set(m,{node:g,dispose:y}),g},slice(m,h){if(!Number.isInteger(m)||m<0)throw new RangeError(`slice: start must be a non-negative integer (got ${m})`);if(h!==void 0&&(!Number.isInteger(h)||h<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${h})`);let g=c(m,h),y=l.get(g);if(y!==void 0)return l.delete(g),l.set(g,y),y.node;p(l);let b=E([a],([k])=>{let w=k;return h===void 0?w.slice(m):w.slice(m,h)},{initial:i.slice(m,h),describeKind:"derived"}),v=go(b);return l.set(g,{node:b,dispose:v}),b},disposeTail(m){let h=u.get(m);return h===void 0?!1:(h.dispose(),u.delete(m),!0)},disposeSlice(m,h){let g=c(m,h),y=l.get(g);return y===void 0?!1:(y.dispose(),l.delete(g),!0)},disposeAllViews(){for(let m of u.values())m.dispose();u.clear();for(let m of l.values())m.dispose();l.clear()},dispose(){for(let m of u.values())m.dispose();u.clear();for(let m of l.values())m.dispose();l.clear()}}}J();function Me(t){let e=t.input,n=e.regular+(e.cacheRead??0)+(e.cacheWrite5m??0)+(e.cacheWrite1h??0)+(e.cacheWriteOther??0)+(e.audio??0)+(e.image??0)+(e.video??0)+(e.toolUse??0);if(!e.extensions)return n;let r=0;for(let o of Object.values(e.extensions))r+=o;return n+r}function De(t){let e=t.output,n=e.regular+(e.reasoning??0)+(e.audio??0)+(e.predictionAccepted??0)+(e.predictionRejected??0);if(!e.extensions)return n;let r=0;for(let o of Object.values(e.extensions))r+=o;return n+r}function ho(){return{input:{regular:0},output:{regular:0}}}function xi(t,e){let n=e?.logMax??1e3,r=Ge(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:n}),o=A(null,{name:"adapterStats/lastCall"}),s=E([r.entries],([h])=>h.length,{name:"adapterStats/totalCalls",initial:0}),i=E([r.entries],([h])=>h.reduce((g,y)=>g+Me(y.usage),0),{name:"adapterStats/totalInputTokens",initial:0}),a=E([r.entries],([h])=>h.reduce((g,y)=>g+De(y.usage),0),{name:"adapterStats/totalOutputTokens",initial:0}),d=[q(s),q(i),q(a)],u=h=>{r.append(h),o.emit(h)},l=()=>{r.clear(),o.emit(null)},c=fe(t,{invoke(h,g){let y=F(),b=pe(),v=t.model??g?.model??"",k=T=>(u(We({provider:t.provider,model:t.model??g?.model??T.model??"",tier:g?.tier??T.tier,usage:T.usage??Ae(),startNs:y,startWallClockNs:b,method:"invoke"})),T),w=T=>{let x=T;u(We({provider:t.provider,model:v,tier:g?.tier,usage:Ae(),startNs:y,startWallClockNs:b,method:"invoke",error:{type:x?.name??"Error",message:x?.message??String(T)}}))};return zt(t.invoke(h,g),{onResp:k,onError:w,name:"adapterStats/invokeTap"})},async*stream(h,g){let y=F(),b=pe(),v=t.model??g?.model??"",k;try{for await(let w of t.stream(h,g))w.type==="usage"&&(k=w.usage),yield w;u(We({provider:t.provider,model:v,tier:g?.tier,usage:k??Ae(),startNs:y,startWallClockNs:b,method:"stream"}))}catch(w){let T=w;throw u(We({provider:t.provider,model:v,tier:g?.tier,usage:k??Ae(),startNs:y,startWallClockNs:b,method:"stream",error:{type:T?.name??"Error",message:T?.message??String(w)}})),w}}});le(c,"observableAdapter",t);let p=!1;return{adapter:c,stats:{lastCall:o,allCalls:r,totalCalls:s,totalInputTokens:i,totalOutputTokens:a,reset:l,dispose:()=>{if(!p){p=!0;for(let h of d)h();d.length=0}}}}}function Ri(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function Jt(t="USD"){return{total:0,currency:t}}function zn(t,e,n){let r=Me(t),o=e.currency??"USD",s=n?.withBreakdown===!0,i=s?{}:null,a=0,d=(g,y,b)=>{if(!y||b==null)return;let v=Ri(b,r),k=y*v/1e6;a+=k,s&&(i[g]=(i[g]??0)+k)},u=t.input,l=e.input;if(l&&(d("input.regular",u.regular,l.regular),d("input.cacheRead",u.cacheRead??0,l.cacheRead),d("input.cacheWrite5m",u.cacheWrite5m??0,l.cacheWrite5m),d("input.cacheWrite1h",u.cacheWrite1h??0,l.cacheWrite1h),d("input.cacheWriteOther",u.cacheWriteOther??0,l.cacheWriteOther),d("input.audio",u.audio??0,l.audio),d("input.image",u.image??0,l.image),d("input.video",u.video??0,l.video),d("input.toolUse",u.toolUse??0,l.toolUse),u.extensions&&l.extensions))for(let[g,y]of Object.entries(u.extensions))d(`input.ext.${g}`,y,l.extensions[g]);let c=t.output,p=e.output;if(p&&(d("output.regular",c.regular,p.regular),d("output.reasoning",c.reasoning??0,p.reasoning),d("output.audio",c.audio??0,p.audio),d("output.predictionAccepted",c.predictionAccepted??0,p.predictionAccepted),d("output.predictionRejected",c.predictionRejected??0,p.predictionRejected),c.extensions&&p.extensions))for(let[g,y]of Object.entries(c.extensions))d(`output.ext.${g}`,y,p.extensions[g]);let f=n?.tier;if(f&&e.tierMultipliers){let g=e.tierMultipliers[f];if(g!=null&&(a*=g,s))for(let y of Object.keys(i))i[y]*=g}let m=t.auxiliary,h=e.auxiliary;if(m&&h)for(let[g,y]of Object.entries(m)){let b=h[g];if(b==null||!y)continue;let v=y*b;a+=v,s&&(i[`auxiliary.${g}`]=v)}return s?{total:a,currency:o,breakdown:i}:{total:a,currency:o}}function qt(t,e){return`${t}::${e}`}function Si(t){let e=new Map,n=new Map,r=(o,s,i)=>{e.set(qt(o,s),{provider:o,model:s,pricing:i});let a=n.get(o);a||(a=new Set,n.set(o,a)),a.add(s)};if(t)for(let[o,s,i]of t)r(o,s,i);return{register:r,lookup(o,s){let i=e.get(qt(o,s));if(i)return i.pricing;let a=n.get(o);if(!a)return;let d;for(let u of a)if(s.startsWith(u)&&(!d||u.length>d.key.length)){let l=e.get(qt(o,u));l&&(d={key:u,pricing:l.pricing})}return d?.pricing},remove(o,s){let i=e.delete(qt(o,s));if(i){let a=n.get(o);a?.delete(s),a&&a.size===0&&n.delete(o)}return i},entries(){let o=e.values();return(function*(){for(let{provider:s,model:i,pricing:a}of o)yield[s,i,a]})()}}}function Ni(t,e="USD"){return(n,r)=>{let o=t.lookup(r.provider,r.model);return o?zn(n,o,{tier:r.tier,withBreakdown:r.withBreakdown}):Jt(e)}}function _i(...t){return(e,n)=>{for(let r of t){let o=r(e,n);if(o.total!==0)return o}return t.length>0?t[0](e,n):Jt()}}function Mi(t,e,n){return t?.pricing?zn(e,t.pricing,n):Jt()}ot();J();function Hn(t,e={}){let n=e.breaker??gt(e),r=fe(t,{async invoke(o,s){if(!n.canExecute())throw new Pe;try{let i=await ve(P(t.invoke(o,s)));return n.recordSuccess(),i}catch(i){throw n.recordFailure(i),i}},async*stream(o,s){if(!n.canExecute())throw new Pe;try{for await(let i of t.stream(o,s))yield i;n.recordSuccess()}catch(i){throw n.recordFailure(i),i}}});return le(r,"withBreaker",t),{adapter:r,breaker:n}}ce();ne();U();J();var Yt=class extends Error{constructor(n,r,o){super(`Budget exhausted: ${n} (limit=${r}, observed=${o})`);this.which=n;this.limit=r;this.observed=o}name="BudgetExhaustedError"},Wn=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),yo=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function qn(t,e){let n=Ge(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),r=A(yo(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),o=E([r],([u])=>{let l=u;return!(e.caps.calls!=null&&l.calls>=e.caps.calls||e.caps.inputTokens!=null&&l.inputTokens>=e.caps.inputTokens||e.caps.outputTokens!=null&&l.outputTokens>=e.caps.outputTokens||e.caps.usd!=null&&l.usd>=e.caps.usd)},{name:e.name?`${e.name}/isOpen`:"budgetGate/isOpen",initial:!0});if(q(o),e.onExhausted!=null){let u=e.onExhausted,l=!1,c=!0;o.subscribe(p=>{for(let f of p)if(f[0]===C){let m=f[1];if(l&&c&&m===!1){let h=bo(r.cache??Wn,e.caps);h&&u(h)}c=m,l=!0}})}let s=()=>{if(o.cache===!1){let u=r.cache??Wn,l=bo(u,e.caps);return new Yt(l??"budget",e.caps[l??"calls"]??0,Ei(u,l??"calls"))}},i=(u,l)=>{let c=t.provider,p=We({provider:c,model:l.model,tier:l.tier,usage:u,startNs:l.startNs,method:l.method,...l.error?{error:l.error}:{}});n.append(p);let f=r.cache??Wn,m=e.pricingFn?f.usd+e.pricingFn(u,{model:l.model,provider:c,tier:l.tier}).total:f.usd;r.emit({calls:f.calls+1,inputTokens:f.inputTokens+Me(u),outputTokens:f.outputTokens+De(u),usd:m})},a=()=>{n.clear(),r.emit(yo())},d=fe(t,{invoke(u,l){let c=s();if(c)return Promise.reject(c);let p=F(),f=t.model??l?.model??"",m=g=>(i(g.usage??Ae(),{model:t.model??l?.model??g.model??"",tier:l?.tier??g.tier,startNs:p,method:"invoke"}),g),h=g=>{let y=g;i(Ae(),{model:f,tier:l?.tier,startNs:p,method:"invoke",error:{type:y?.name??"Error",message:y?.message??String(g)}})};return zt(t.invoke(u,l),{onResp:m,onError:h,name:"budgetGate/invokeTap"})},async*stream(u,l){let c=s();if(c)throw c;let p=F(),f;try{for await(let m of t.stream(u,l))m.type==="usage"&&(f=m.usage),yield m;i(f??Ae(),{model:t.model??l?.model??"",tier:l?.tier,startNs:p,method:"stream"})}catch(m){let h=m;throw i(f??Ae(),{model:t.model??l?.model??"",tier:l?.tier,startNs:p,method:"stream",error:{type:h?.name??"Error",message:h?.message??String(m)}}),m}}});return le(d,"withBudgetGate",t),{adapter:d,budget:{totals:r,isOpen:o,log:n,reset:a}}}function bo(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 Ei(t,e){switch(e){case"calls":return t.calls;case"inputTokens":return t.inputTokens;case"outputTokens":return t.outputTokens;case"usd":return t.usd}}J();function Oi(t,e){let n=e.mock??He({provider:t.provider,model:t.model}),r=typeof e.enabled=="boolean"?e.enabled:void 0,o=r===void 0?P(e.enabled):void 0,s;o&&(s=q(o));let i=()=>r!==void 0?r:!!o?.cache,a=fe(t,{invoke(u,l){return i()?n.invoke(u,l):t.invoke(u,l)},stream(u,l){return i()?n.stream(u,l):t.stream(u,l)}});return le(a,"withDryRun",t),{adapter:a,dispose:()=>{s&&(s(),s=void 0)}}}function Jn(t){if(t==null||typeof t!="object")return;let e=t,n=e.status,r=Ai(e.headers);if(n!==429&&n!==503&&!Gi(e.message))return;let o={},s=r("retry-after"),i=Li(s);i!=null&&(o.retryAfterMs=i);let a=r("anthropic-ratelimit-requests-reset");if(a){let f=To(a);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let d=r("anthropic-ratelimit-tokens-reset");if(d){let f=To(d);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let u=Qt(r,"x-ratelimit-limit-requests");u!=null&&(o.rpmCap=u);let l=Qt(r,"x-ratelimit-limit-tokens");l!=null&&(o.tpmCap=l);let c=Qt(r,"x-ratelimit-remaining-requests"),p=Qt(r,"x-ratelimit-remaining-tokens");if(c!=null&&u!=null&&u>0&&(o.usageHint??={},o.usageHint.rpm=1-c/u),p!=null&&l!=null&&l>0&&(o.usageHint??={},o.usageHint.tpm=1-p/l),o.retryAfterMs==null&&e.message){let f=Ii(e.message);f!=null&&(o.retryAfterMs=f)}return e.headers&&(o.metadata={headers:Ci(e.headers)}),o.retryAfterMs==null&&o.rpmCap==null&&o.tpmCap==null&&o.usageHint==null?o.metadata?o:void 0:o}function Ai(t){if(!t)return()=>{};if(typeof t.get=="function"){let r=t;return o=>r.get(o)??r.get(o.toLowerCase())??void 0}let e=t,n={};for(let[r,o]of Object.entries(e)){let s=Array.isArray(o)?o.join(", "):o;s!=null&&(n[r.toLowerCase()]=s)}return r=>n[r.toLowerCase()]}function Ci(t){let e={};if(typeof t.forEach=="function")return t.forEach((n,r)=>{e[r]=n}),e;for(let[n,r]of Object.entries(t))r!=null&&(e[n]=Array.isArray(r)?r.join(", "):r);return e}function Qt(t,e){let n=t(e);if(n==null)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function Li(t){if(!t)return;let e=t.trim(),n=Number(e);if(Number.isFinite(n)&&n>=0)return n*1e3;let r=Date.parse(e);if(Number.isFinite(r)){let o=r-Date.now();if(o>0)return o}}function To(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var Di=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function Ii(t){let e=Di.exec(t);if(!e)return;let n=Number(e[1]);if(!Number.isFinite(n))return;let r=(e[2]??"s").toLowerCase();if(r==="ms")return n;if(r.startsWith("s"))return n*1e3;if(r.startsWith("m"))return n*6e4}var Pi=/rate\s*limit|too\s*many\s*requests|quota|429/i;function Gi(t){return!!t&&Pi.test(t)}ce();ne();U();ot();J();Ce();function Yn(t){let e=new Error(t);return e.name="AbortError",e}function wo(t={}){let e=Math.max(1,t.burstMultiplier??1),n=t.clampCooldownMs??6e4,r=t.rpm!=null?P(t.rpm):A(Number.POSITIVE_INFINITY),o=t.tpm!=null?P(t.tpm):A(Number.POSITIVE_INFINITY),s=A(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),i=A(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),a=A({},{name:"adaptiveRateLimiter/lastSignal"}),d=E([r,s],([M,L])=>Math.min(Number(M??1/0),Number(L??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),u=E([o,i],([M,L])=>Math.min(Number(M??1/0),Number(L??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),l=it(Number(r.cache??Number.POSITIVE_INFINITY),e),c=it(Number(o.cache??Number.POSITIVE_INFINITY),e),p=!1,f=!1,m=d.subscribe(M=>{for(let L of M)if(L[0]===C){let j=Number(L[1]);Number.isFinite(j)&&j>0?(l=it(j,e),p=!1):j===1/0?(l=it(1/0,e),p=!1):j<=0&&(p=!0)}}),h=u.subscribe(M=>{for(let L of M)if(L[0]===C){let j=Number(L[1]);Number.isFinite(j)&&j>0?(c=it(j,e),f=!1):j===1/0?(c=it(1/0,e),f=!1):j<=0&&(f=!0)}}),g=0,y=new re,b=new re,v;t.adaptation!=null&&(v=P(t.adaptation).subscribe(L=>{for(let j of L)j[0]===C&&k(j[1])}));function k(M){if(a.emit(M),M.rpmCap!=null&&Number.isFinite(M.rpmCap)&&M.rpmCap>=0&&(s.emit(M.rpmCap),Number.isFinite(n)&&n>0&&y.start(n,()=>s.emit(Number.POSITIVE_INFINITY))),M.tpmCap!=null&&Number.isFinite(M.tpmCap)&&M.tpmCap>=0&&(i.emit(M.tpmCap),Number.isFinite(n)&&n>0&&b.start(n,()=>i.emit(Number.POSITIVE_INFINITY))),M.retryAfterMs!=null&&M.retryAfterMs>0){let L=F()+M.retryAfterMs*1e6;L>g&&(g=L)}}let w=A(0,{name:"adaptiveRateLimiter/pending"}),T=A(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),x=A(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),S=M=>{w.emit((w.cache??0)+M)},N=()=>{T.emit(l.available()),x.emit(c.available())};async function _(M={}){let L=M.requestCost??1,j=M.tokenCost??0,K=M.signal;S(1);try{for(;;){if(K?.aborted)throw Yn("AdaptiveRateLimiter.acquire aborted");let Q=F();if(g>Q){let $=Math.ceil((g-Q)/1e6);await Xt($,K);continue}if(L>0&&p||j>0&&f){await Xt(250,K);continue}let we=l,_e=c;if(!we.tryConsume(L)){await Xt(vo(we,L),K);continue}if(!(j>0?_e.tryConsume(j):!0)){we.putBack(L),await Xt(vo(_e,j),K);continue}N();return}}finally{S(-1)}}function R(M){M>0?c.tryConsume(M):M<0&&c.putBack(-M),N()}function I(){m(),h(),v?.(),y.cancel(),b.cancel()}return{effectiveRpm:d,effectiveTpm:u,lastSignal:a,pending:w,rpmAvailable:T,tpmAvailable:x,acquire:_,recordUsage:R,recordSignal:k,dispose:I}}function it(t,e){if(!Number.isFinite(t)||t===1/0)return ht(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let n=Math.max(1,t*e),r=t/60;return ht(n,r)}function vo(t,e){let n=t.available(),r=Math.max(0,e-n);return r<=0?25:Math.min(5e3,Math.max(50,r*100))}function Xt(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Yn("AdaptiveRateLimiter.acquire aborted")):new Promise((n,r)=>{let o=new re,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(Yn("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",s,{once:!0}))})}J();function Qn(t,e={}){let n=e.limiter??wo({name:e.name??"rateLimiter",rpm:e.rpm,tpm:e.tpm,adaptation:e.adaptation,burstMultiplier:e.burstMultiplier}),r=(i,a)=>e.costFn?e.costFn(i,a):0,o=i=>{let a=Jn(i);a&&n.recordSignal(a)},s=fe(t,{async invoke(i,a){let d=r(i,a);await n.acquire({requestCost:1,tokenCost:d,signal:a?.signal});try{let u=await ve(P(t.invoke(i,a))),l=u.usage??ho(),p=Me(l)+De(l)-d;return p>0&&n.recordUsage(p),u}catch(u){throw o(u),u}},async*stream(i,a){let d=r(i,a);await n.acquire({requestCost:1,tokenCost:d,signal:a?.signal});try{let u=0;for await(let c of t.stream(i,a))c.type==="usage"&&(u=Me(c.usage)+De(c.usage)),yield c;let l=u-d;l>0&&n.recordUsage(l)}catch(u){throw o(u),u}}});return le(s,"withRateLimiter",t),{adapter:s,limiter:n}}ot();J();var vt=class extends Error{name="AllTiersExhaustedError";skipped;failed;constructor(e){let n=[];e.failed.size>0&&n.push(`failed=[${[...e.failed.keys()].join(",")}]`),e.skipped.length>0&&n.push(`skipped=[${e.skipped.map(r=>`${r.name}(${r.reason})`).join(",")}]`),super(`All LLM adapter tiers exhausted: ${n.join(" ")}`),this.skipped=e.skipped,this.failed=e.failed}};function Xn(t,e={}){if(t.length===0)throw new RangeError("cascadingLlmAdapter: tiers must be non-empty");let n=t.map(s=>({name:s.name,adapter:s.adapter,filter:s.filter,breaker:s.breaker?"canExecute"in s.breaker?s.breaker:gt(s.breaker):void 0})),r=e.streamRetryBeforeFirstChunk??!0,o={provider:"cascading",model:void 0,async invoke(s,i){let a=[],d=new Map;for(let l=0;l<n.length;l++){let c=n[l];if(c.filter&&!c.filter(s,i)){a.push({name:c.name,reason:"filter"});continue}if(c.breaker&&!c.breaker.canExecute()){a.push({name:c.name,reason:"breaker"});continue}try{let p=await ve(P(c.adapter.invoke(s,i)));return c.breaker?.recordSuccess(),{...p,metadata:{...p.metadata??{},tier:c.name}}}catch(p){d.set(c.name,p),c.breaker?.recordFailure(p);let f=n[l+1];f&&e.onFallback?.(c.name,f.name,p)}}let u={skipped:a,failed:d};throw e.onExhausted?.(u),new vt(u)},async*stream(s,i){let a=[],d=new Map;for(let l=0;l<n.length;l++){let c=n[l];if(c.filter&&!c.filter(s,i)){a.push({name:c.name,reason:"filter"});continue}if(c.breaker&&!c.breaker.canExecute()){a.push({name:c.name,reason:"breaker"});continue}let p=!1;try{for await(let f of c.adapter.stream(s,i))p=!0,yield f;c.breaker?.recordSuccess();return}catch(f){if(d.set(c.name,f),c.breaker?.recordFailure(f),p||!r)throw f;let m=n[l+1];m&&e.onFallback?.(c.name,m.name,f)}}let u={skipped:a,failed:d};throw e.onExhausted?.(u),new vt(u)}};return le(o,`cascade[${n.map(s=>s.name).join(",")}]`),o}function $i(t,e,n){let r={name:t,adapter:e};return n?.breaker&&(r.breaker=n.breaker),n?.filter&&(r.filter=n.filter),r}J();Ce();function Zt(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function ko(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Zt()):new Promise((n,r)=>{let o=new re,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(Zt())},e.addEventListener("abort",s,{once:!0}))})}function Zn(t,e={}){let n=e.attempts??3,r=e.baseDelayMs??500,o=e.maxDelayMs??1e4,s=e.strategy??"decorrelated",i=e.jitter??!0,a=e.shouldRetry??Fi,d=e.retryStreaming??!0,u=(c,p)=>{if(s==="decorrelated"){let g=Math.min(o,Math.max(r,p*3));return r+Math.random()*(g-r)}let f=s==="exp"?r*2**(c-1):r*c,m=Math.min(o,f);if(!i)return m;let h=m*(.5+Math.random());return Math.min(o,h)},l=fe(t,{async invoke(c,p){if(p?.signal?.aborted)throw Zt();let f,m=r;for(let h=1;h<=n;h++)try{return await ve(P(t.invoke(c,p)))}catch(g){if(f=g,h>=n||!a(g,h))throw g;let y=u(h,m);m=y,await ko(y,p?.signal)}throw f},async*stream(c,p){if(p?.signal?.aborted)throw Zt();if(!d){for await(let h of t.stream(c,p))yield h;return}let f,m=r;for(let h=1;h<=n;h++){let g=!1;try{for await(let y of t.stream(c,p))g=!0,yield y;return}catch(y){if(f=y,g||h>=n||!a(y,h))throw y;let b=u(h,m);m=b,await ko(b,p?.signal)}}throw f}});return le(l,"withRetry",t),l}function Fi(t,e){if(t==null)return!1;let n=t;return n.name==="LLMTimeoutError"?!0:n.name==="AbortError"||n.message==="aborted"||n.name==="DOMException"&&n.code!=null&&Number(n.code)===20||n.name==="BudgetExhaustedError"||n.name==="CircuitOpenError"?!1:n.status!=null?n.status===429||n.status>=500&&n.status<600:n.code&&typeof n.code=="string"&&/^E[A-Z]+$/.test(n.code)?!0:n.message?/network|timeout|socket|fetch|econn|eai_/i.test(n.message):!1}J();Ce();var at=class extends Error{constructor(n){super(`LLM call timed out after ${n}ms`);this.ms=n}name="LLMTimeoutError"};function er(t,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let n=s=>{let i=new AbortController,a=!1,d,u=new re;return s&&(s.aborted?i.abort(s.reason):(d=()=>{u.cancel(),i.abort(s.reason)},s.addEventListener("abort",d,{once:!0}))),u.start(e,()=>{a=!0,i.abort(new at(e))}),{signal:i.signal,cancel:()=>{u.cancel(),s&&d&&s.removeEventListener("abort",d)},timedOut:()=>a}},r=(s,i)=>{if(!i||s instanceof at)throw s;let a=s;if(a?.name==="AbortError"||a?.name==="DOMException"&&Number(a.code)===20||s?.message==="aborted"){let u=new at(e);throw u.cause=s,u}throw s},o=fe(t,{async invoke(s,i){let{signal:a,cancel:d,timedOut:u}=n(i?.signal);try{return await ve(P(t.invoke(s,{...i,signal:a})))}catch(l){return r(l,u())}finally{d()}},async*stream(s,i){let{signal:a,cancel:d,timedOut:u}=n(i?.signal);try{for await(let l of t.stream(s,{...i,signal:a}))yield l}catch(l){r(l,u())}finally{d()}}});return le(o,"withTimeout",t),o}function ji(t,e={}){let n={adapter:t},r=t;if(e.rateLimit){let o=Qn(r,e.rateLimit);r=o.adapter,n.rateLimiter=o.limiter}if(e.budget){let o=qn(r,e.budget);r=o.adapter,n.budget=o.budget}if(e.breaker){let o=Hn(r,e.breaker);r=o.adapter,n.breaker=o.breaker}if(e.timeoutMs!=null&&(r=er(r,e.timeoutMs)),e.retry&&(r=Zn(r,e.retry)),e.fallback){if(e.name==="fallback")throw new RangeError('resilientAdapter: `name` cannot be "fallback" \u2014 collides with the secondary tier label.');let o={};e.onFallback&&(o.onFallback=e.onFallback),e.onExhausted&&(o.onExhausted=e.onExhausted),r=Xn([{name:e.name??"primary",adapter:r},{name:"fallback",adapter:e.fallback}],o)}return e.cache&&(r=Tt(r,e.cache)),n.adapter=r,n}U();J();function Bi(t,e,n){let r=P(e);return oe(r,s=>{if(!s||s.length===0)return A(null);let i=n?.tools;return t.invoke(s,{model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,tools:i,systemPrompt:n?.systemPrompt})})}Ne();J();ne();J();Ce();ne();J();function xo(t,e){let n=t.cache??0;return n>=e?!1:(t.down([[z],[C,n+1]]),!0)}function $e(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}function V(t,e){return $e("ai",t,e)}function Vi(t){return t!=null&&typeof t.then=="function"}function tr(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function Ki(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var Ui=3e4;function Ro(t,e){if(t.status==="settled"){let r=t.cache;if(r!==void 0)return Promise.resolve(r)}let n=e?.timeoutMs??Ui;return new Promise((r,o)=>{let s=new re,i=t.subscribe(a=>{for(let d of a){if(d[0]===C){s.cancel(),i(),r(d[1]);return}if(d[0]===O){s.cancel(),i(),o(d[1]);return}if(d[0]===G){s.cancel(),i(),o(new Error("firstDataFromNode: completed without producing a value"));return}}});s.start(n,()=>{i(),o(new Error(`firstDataFromNode: timed out after ${n}ms`))})})}async function wt(t){return Vi(t)?wt(await t):tr(t)?Ro(t):Ki(t)?Ro(P(t)):t}function ut(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function zi(t,e){let n=P(t),r=e?.refreshTrigger!=null?P(e.refreshTrigger):null;return r==null?ee([n],(o,s,i)=>{if(i.store.emitted===!0)return;let d=o[0],u=d!=null&&d.length>0?d.at(-1):i.prevData[0];if(u!==void 0)return i.store.emitted=!0,s.emit(u),{invalidate:()=>{i.store.emitted=!1}}},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:V("frozen_context")}):ee([n,r],(o,s,i)=>{let a=o[1];if(!(a!=null&&a.length>0))return;let u=o[0],l=u!=null&&u.length>0?u.at(-1):i.prevData[0];s.emit(l)},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:V("frozen_context")})}ne();U();J();function So(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function Hi(t,e=200){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function nr(t,e,n,r){let o=r?.format??"text",s=r?.name??"prompt_node",i=E(e,d=>{if(d.some(l=>l==null))return[];let u=typeof n=="string"?n:n(...d);return u?[{role:"user",content:u}]:[]},{name:`${s}::messages`,meta:V("prompt_node")});return oe(i,d=>!d||d.length===0?A(null):Z(u=>{let l=!1,c=!1,p,f={model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt};if(r?.abort){let y=Yr(r.abort);f.signal=y.signal,p=y.dispose}let m;try{m=t.invoke(d,f)}catch(y){return l=!0,u.down([[O,y]]),()=>{p?.()}}let g=P(m).subscribe(y=>{if(!(c||l))for(let b of y){if(l)return;if(b[0]===C){let v=b[1];try{let k=So(v),w=o==="json"?JSON.parse(ut(k)):k;u.emit(w)}catch(k){let w=So(v),T=new Error(`promptNode: failed to parse LLM response as JSON: ${k.message}
|
|
7
|
+
Raw content (first 200 chars): ${Hi(w)}`);l=!0,u.down([[O,T]]);return}}else if(b[0]===O){l=!0,u.down([[O,b[1]]]);return}else if(b[0]===G){l=!0,u.down([[G]]);return}else u.down([b])}});return()=>{c=!0,g(),p?.()}},{name:`${s}::call`,meta:V("prompt_node::call")}),{name:`${s}::output`,meta:r?.meta?{...V("prompt_node::output"),...r.meta}:V("prompt_node::output")})}ke();ce();U();J();St();ft();ne();ft();Ne();function en(t,e){if(e!=null&&e.length>0)return new Set(e);switch(t){case"standard":return new Set(["type","status","value","deps","meta","v"]);case"full":return null;default:return new Set(["type","deps"])}}function Wi(t){return t._describeKind!=null?t._describeKind:t._deps.length>0?"derived":t._fn!=null?"producer":"state"}function qi(t){let e={};for(let[n,r]of Object.entries(t.meta))try{e[n]=r.cache}catch{}return e}function rr(t,e){let n=e==null,r=!n&&e!=null?[...e].filter(u=>u.startsWith("meta.")).map(u=>u.slice(5)):null,o=n||e.has("meta")||r!=null&&r.length>0,s="state",i=[];t instanceof ie&&(s=Wi(t),i=t._deps.map(u=>u.node.name??""));let a={type:s,deps:i};(n||e.has("status"))&&(a.status=t.status);let d=t instanceof ie?t._guard:void 0;if(o){let u={...qi(t)};if(d!=null&&u.access===void 0&&(u.access=kn(d)),r!=null&&r.length>0&&!e.has("meta")){let l={};for(let c of r)c in u&&(l[c]=u[c]);a.meta=l}else a.meta=u}if(t.name!=null&&(a.name=t.name),n||e.has("value")){t.status==="sentinel"&&(a.sentinel=!0);try{a.value=t.cache}catch{}}if((n||e.has("v"))&&t.v!=null){let u={id:t.v.id,version:t.v.version};"cid"in t.v&&(u.cid=t.v.cid,u.prev=t.v.prev),a.v=u}return(n||e.has("guard"))&&d!=null&&(a.guard=kn(d)),(n||e.has("lastMutation"))&&t.lastMutation!=null&&(a.lastMutation=t.lastMutation),a}U();var ae={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},Ji=Symbol.for("sizeof");function No(t){let e=new WeakSet,n=new WeakSet,r=[t],o=0;for(;r.length>0;){let s=r.pop();o+=Yi(s,e,n,r)}return o}function Yi(t,e,n,r){if(t==null)return 0;switch(typeof t){case"number":return ae.number;case"boolean":return ae.boolean;case"string":return ae.string+t.length*2;case"bigint":return ae.bigint+Qi(t);case"symbol":return ae.symbol;case"function":return e.has(t)?0:(e.add(t),ae.function);case"undefined":return 0}let s=t;if(e.has(s))return 0;e.add(s);let i=s[Ji];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 ae.date;if(s instanceof RegExp)return ae.regexp+s.source.length*2;if(s instanceof Error){let u=s.message?s.message.length*2:0,l=s.stack?s.stack.length*2:0;return ae.error+u+l}if(typeof URL<"u"&&s instanceof URL)return ae.url+s.href.length*2;if(typeof Promise<"u"&&s instanceof Promise)return ae.promise;if(s instanceof WeakMap)return ae.weakmap;if(s instanceof WeakSet)return ae.weakset;if(s instanceof Map){let u=ae.map;for(let[l,c]of s)u+=ae.mapEntry,r.push(l),r.push(c);return u}if(s instanceof Set){let u=ae.set;for(let l of s)u+=ae.setEntry,r.push(l);return u}if(Array.isArray(s)){let u=ae.array+s.length*8;for(let l of s)r.push(l);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=ae.object,d=Object.keys(s);for(let u of d){a+=ae.string+u.length*2;try{r.push(s[u])}catch{}}return a}function Qi(t){let e=t<0n?-t:t;if(e===0n)return 0;let n=e.toString(2).length;return Math.ceil(n/32)*8}function _o(t,e,n,r={}){let o=e in t.nodes,s=n in t.nodes;if(!o)return tn(e,n,"no-such-from");if(!s)return tn(e,n,"no-such-to");let i=r.maxDepth;if(i!=null&&(!Number.isInteger(i)||i<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(e===n){if(r.findCycle===!0){let u=Xi(t,e,r);if(u!=null)return u}let d=nn(e,t.nodes[e],0,r);return rn(e,n,[d])}if(i===0)return tn(e,n,"no-path");let a=Mo(t,e,n,i);return a.found?rn(e,n,Eo(t,a.pathOrder,r)):tn(e,n,a.truncated?"max-depth-exceeded":"no-path")}function Mo(t,e,n,r){let o=new Map,s=[{path:n,depth:0}],i=new Set([n]),a=0,d=!1;for(;a<s.length;){let c=s[a++];if(c.path===e)break;if(r!=null&&c.depth>=r){let h=t.nodes[c.path];h?.deps&&h.deps.length>0&&(d=!0);continue}let p=t.nodes[c.path];if(p==null)continue;let f=p.deps??[],m=new Map;for(let h=0;h<f.length;h++){let g=f[h];if(!g)continue;let y=m.get(g);y==null&&(y=[],m.set(g,y)),y.push(h)}for(let[h,g]of m)i.has(h)||(i.add(h),o.set(h,{from:c.path,depIndices:g}),s.push({path:h,depth:c.depth+1}))}if(!o.has(e))return{found:!1,pathOrder:[],truncated:d};let u=[{path:e}],l=e;for(;l!==n;){let c=o.get(l);if(c==null)return{found:!1,pathOrder:[],truncated:!1};u[u.length-1].depIndices=c.depIndices,u.push({path:c.from}),l=c.from}return{found:!0,pathOrder:u,truncated:!1}}function Xi(t,e,n){let r=t.nodes[e];if(r==null)return null;let o=r.deps??[],s=[];for(let a=0;a<o.length;a++)o[a]===e&&s.push(a);if(s.length>0){let a=nn(e,r,0,n);a.dep_index=s[0];let d=nn(e,r,1,n);return rn(e,e,[a,d])}let i=null;for(let a=0;a<o.length;a++){let d=o[a];if(!d||d===e)continue;let u=Mo(t,d,e,n.maxDepth);u.found&&(i==null||u.pathOrder.length<i.pathOrder.length)&&(i=u,i={found:!0,pathOrder:[{path:e,depIndices:[a]},...u.pathOrder],truncated:!1})}return i==null?null:rn(e,e,Eo(t,i.pathOrder,n))}function Eo(t,e,n){return e.map((r,o)=>{let s=t.nodes[r.path],i=nn(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 nn(t,e,n,r){let o={path:t,type:e.type,hop:n};e.status!==void 0&&(o.status=e.status),"value"in e&&(o.value=e.value),e.v!=null&&(o.v=e.v);let s=r.annotations?.get(t)??e.annotation;s!=null&&(o.annotation=s);let i=r.lastMutations?.get(t)??e.lastMutation;return i!=null&&(o.lastMutation=i),o}function rn(t,e,n){return Oo(t,e,!0,"ok",n)}function tn(t,e,n){return Oo(t,e,!1,n,[])}function Oo(t,e,n,r,o){let s=Zi(t,e,n,r,o);return{from:t,to:e,found:n,reason:r,steps:o,text:s,toJSON(){return{from:t,to:e,found:n,reason:r,steps:o}}}}function Zi(t,e,n,r,o){if(!n)switch(r){case"no-such-from":return`explainPath: no node named "${t}"`;case"no-such-to":return`explainPath: no node named "${e}"`;case"max-depth-exceeded":return`explainPath: no path from "${t}" to "${e}" within maxDepth`;default:return`explainPath: no path from "${t}" to "${e}"`}let s=[`Causal path: ${t} \u2192 ${e} (${o.length} step(s))`];for(let i of o){let d=` ${i.hop===0?"\xB7":"\u2193"} ${i.path} (${i.type}${i.status?`/${i.status}`:""})`;if(s.push(d),"value"in i&&s.push(` value: ${ea(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(`
|
|
8
|
+
`)}function ea(t){if(t===void 0)return"<sentinel>";if(t===null)return"null";if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return e.length>80?`${e.slice(0,77)}...`:e}catch{return String(t)}}St();ke();ce();ft();ne();Ne();U();J();Ce();bn();function or(t){return t>=768&&t<=879||t>=1155&&t<=1161||t>=1425&&t<=1469||t>=1552&&t<=1562||t>=1611&&t<=1631||t>=1648&&t===1648||t>=1750&&t<=1756||t>=1759&&t<=1764||t>=1767&&t<=1768||t>=1770&&t<=1773||t>=1840&&t<=1866||t>=1958&&t<=1968||t>=2304&&t<=2307||t>=2362&&t<=2383||t>=2385&&t<=2391||t>=2402&&t<=2403||t>=2433&&t<=2435||t>=2492&&t<=2509||t>=2561&&t<=2563||t>=2620&&t<=2641||t>=2672&&t<=2673||t>=2677&&t===2677||t>=3633&&t===3633||t>=3636&&t<=3642||t>=3655&&t<=3662||t>=3761&&t===3761||t>=3764&&t<=3772||t>=3784&&t<=3790||t>=7616&&t<=7679||t>=8400&&t<=8447||t>=65024&&t<=65039||t>=65056&&t<=65071||t===8205?0:t>=4352&&t<=4447||t>=8986&&t<=8987||t>=9001&&t<=9002||t>=9193&&t<=9203||t>=9208&&t<=9210||t>=9725&&t<=9726||t>=9748&&t<=9749||t>=9800&&t<=9811||t===9855||t===9875||t===9889||t>=9898&&t<=9899||t>=9917&&t<=9918||t>=9924&&t<=9925||t===9934||t===9940||t===9962||t>=9970&&t<=9971||t===9973||t===9978||t===9981||t===9986||t===9989||t>=9992&&t<=9997||t===9999||t>=10067&&t<=10069||t===10071||t>=10133&&t<=10135||t===10160||t===10175||t>=10548&&t<=10549||t>=11013&&t<=11015||t>=11035&&t<=11036||t===11088||t===11093||t>=11904&&t<=12350||t>=12352&&t<=12447||t>=12448&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12784&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=19968&&t<=40959||t>=43360&&t<=43388||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65131||t>=65281&&t<=65376||t>=65504&&t<=65510||t>=126980&&t===126980||t===127183||t>=127344&&t<=127345||t===127358||t===127359||t===127374||t>=127377&&t<=127386||t>=127456&&t<=127487||t>=127488&&t<=127490||t===127514||t===127535||t>=127538&&t<=127546||t>=127568&&t<=127569||t>=127744&&t<=129535||t>=129536&&t<=129791||t>=129792&&t<=130047||t>=131072&&t<=196605||t>=196608&&t<=262141?2:1}function on(t){let e=0;for(let n of t)e+=or(n.codePointAt(0));return e}function Ao(t,e){if(e<=0)return"";let n=0,r="";for(let o of t){let s=or(o.codePointAt(0));if(n+s>e){if(e<=1)return"\u2026";for(;n+1>e&&r.length>0;){let i=[...r].pop();r=r.slice(0,-i.length),n-=or(i.codePointAt(0))}return`${r}\u2026`}r+=o,n+=s}return r}var ta={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"},na={horizontal:"-",vertical:"|",cornerTL:"+",cornerTR:"+",cornerBL:"+",cornerBR:"+",tDown:"+",tUp:"+",tRight:"+",tLeft:"+",cross:"+",arrowRight:">",arrowDown:"v",arrowLeft:"<",arrowUp:"^",boxTL:"+",boxTR:"+",boxBL:"+",boxBR:"+",boxH:"-",boxV:"|"};function Io(t,e){let n=e.charset==="ascii"?na:ta,r=t.width,o=t.height,s=Array.from({length:o},()=>Array.from({length:r},()=>" ")),i=Array.from({length:o},()=>Array.from({length:r},()=>"empty"));for(let a of t.edges)oa(s,i,n,a);for(let a of t.boxes)ra(s,i,n,a,e.labelOf(a.id));return s.map(a=>ua(a.join(""))).join(`
|
|
9
|
+
`)}function ra(t,e,n,r,o){let{x:s,y:i,w:a,h:d}=r;if(a<2||d<2){d>0&&Co(t,e,s,i,a,o);return}Fe(t,e,s,i,n.boxTL);for(let l=s+1;l<s+a-1;l+=1)Fe(t,e,l,i,n.boxH);Fe(t,e,s+a-1,i,n.boxTR);for(let l=i+1;l<i+d-1;l+=1){Fe(t,e,s,l,n.boxV);for(let c=s+1;c<s+a-1;c+=1)Po(t,e,c,l," ","empty");Fe(t,e,s+a-1,l,n.boxV)}Fe(t,e,s,i+d-1,n.boxBL);for(let l=s+1;l<s+a-1;l+=1)Fe(t,e,l,i+d-1,n.boxH);Fe(t,e,s+a-1,i+d-1,n.boxBR);let u=i+Math.floor(d/2);Co(t,e,s+1,u,a-2,o)}function Fe(t,e,n,r,o){Po(t,e,n,r,o,o===" "?"empty":o==="\u2500"||o==="-"?"boxH":o==="\u2502"||o==="|"?"boxV":"boxCorner")}function Po(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];n<0||n>=i.length||(i[n]=o,e[r][n]=s)}function Co(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=n,a=o;for(let d of s){let u=on(d);if(u!==0){if(a<u)break;i>=0&&i<t[r].length&&(t[r][i]=d,e[r][i]="label",u===2&&i+1<t[r].length&&(t[r][i+1]="",e[r][i+1]="label")),i+=u,a-=u}}for(;a>0;)i>=0&&i<t[r].length&&(t[r][i]=" ",e[r][i]="empty"),i+=1,a-=1}function oa(t,e,n,r){let o=r.points;if(o.length<2)return;for(let d=0;d+1<o.length;d+=1)sa(t,e,n,o[d],o[d+1]);for(let d=1;d+1<o.length;d+=1){let u=o[d-1],l=o[d],c=o[d+1],p=ia(u,l,c,n);p&&Do(t,e,l.x,l.y,p,"edgeCorner")}let s=o[o.length-1],i=o[o.length-2],a=aa(i,s,n);a&&Do(t,e,s.x,s.y,a,"arrow")}function sa(t,e,n,r,o){if(!(r.x===o.x&&r.y===o.y)){if(r.y===o.y){let s=r.y,i=Math.min(r.x,o.x),a=Math.max(r.x,o.x);for(let d=i;d<=a;d+=1)Lo(t,e,d,s,n,"h")}else if(r.x===o.x){let s=r.x,i=Math.min(r.y,o.y),a=Math.max(r.y,o.y);for(let d=i;d<=a;d+=1)Lo(t,e,s,d,n,"v")}}}function Lo(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];if(n<0||n>=i.length)return;let a=e[r][n];if(!(a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label")){if(a==="empty"){i[n]=s==="h"?o.horizontal:o.vertical,e[r][n]=s==="h"?"edgeH":"edgeV";return}if(a==="edgeH"&&s==="v"){i[n]=o.cross,e[r][n]="edgeCorner";return}if(a==="edgeV"&&s==="h"){i[n]=o.cross,e[r][n]="edgeCorner";return}}}function Do(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];if(n<0||n>=i.length)return;let a=e[r][n];a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label"||(i[n]=o,e[r][n]=s)}function ia(t,e,n,r){let o=t.y===e.y,s=e.y===n.y;if(o===s)return;if(o){let d=t.x<e.x,u=n.y>e.y;return d&&u?r.cornerTR:d&&!u?r.cornerBR:!d&&u?r.cornerTL:r.cornerBL}let i=t.y<e.y,a=n.x>e.x;return i&&a?r.cornerBL:i&&!a?r.cornerBR:!i&&a?r.cornerTL:r.cornerTR}function aa(t,e,n){if(e.x>t.x)return n.arrowRight;if(e.x<t.x)return n.arrowLeft;if(e.y>t.y)return n.arrowDown;if(e.y<t.y)return n.arrowUp}function ua(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===32;)e-=1;return t.slice(0,e)}function Fo(t){let e=da(t);la(e),ca(e),pa(e),fa(e,t);let n=ha(e,t),{width:r,height:o}=ba(e),s=[];for(let i of e.layers)for(let a of i)a.isVirtual||s.push({id:a.id,layer:a.layer,order:a.order,x:a.x,y:a.y,w:a.w,h:a.h});return{boxes:s,edges:n,width:r,height:o}}function da(t){let e=new Map;for(let o of t.nodes)e.set(o,{id:o,isVirtual:!1,layer:-1,order:0,x:0,y:0,w:t.widthCells(o),h:t.heightCells(o),in:[],out:[]});let n=[],r=0;for(let o of t.edges){if(o.from===o.to)continue;let s=e.get(o.from),i=e.get(o.to);if(!s||!i)continue;let a={chainId:r++,chainFrom:o.from,chainTo:o.to,fromId:o.from,toId:o.to,hopIndex:0,chainLen:1};s.out.push(a),i.in.push(a),n.push(a)}return{nodes:e,layers:[],hops:n}}function la(t){let e=new Map;for(let s of t.nodes.values())e.set(s.id,s.in.length);let n=[];for(let s of t.nodes.values())(e.get(s.id)??0)===0&&(s.layer=0,n.push(s));let r=new Set,o=0;for(;o<n.length;){let s=n[o++];if(!r.has(s.id)){r.add(s.id);for(let i of s.out){let a=t.nodes.get(i.toId);a.layer=Math.max(a.layer,s.layer+1);let d=(e.get(a.id)??0)-1;e.set(a.id,d),d<=0&&n.push(a)}}}for(let s of t.nodes.values())s.layer<0&&(s.layer=0)}function ca(t){let e=Math.max(0,...Array.from(t.nodes.values(),s=>s.layer)),n=Array.from({length:e+1},()=>[]);for(let s of t.nodes.values())n[s.layer].push(s);let r=[],o=0;for(let s of t.hops){let i=t.nodes.get(s.fromId),a=t.nodes.get(s.toId),d=a.layer-i.layer;if(d<=0){i.out=i.out.filter(c=>c!==s),a.in=a.in.filter(c=>c!==s);continue}if(d===1){s.hopIndex=0,s.chainLen=1,r.push(s);continue}i.out=i.out.filter(c=>c!==s),a.in=a.in.filter(c=>c!==s);let u=i;for(let c=1;c<d;c+=1){let p=`__virt_${o++}__`,f={id:p,isVirtual:!0,layer:i.layer+c,order:0,x:0,y:0,w:0,h:1,in:[],out:[]};t.nodes.set(p,f),n[f.layer].push(f);let m={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:u.id,toId:p,hopIndex:c-1,chainLen:d};u.out.push(m),f.in.push(m),r.push(m),u=f}let l={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:u.id,toId:a.id,hopIndex:d-1,chainLen:d};u.out.push(l),a.in.push(l),r.push(l)}for(let s of n)for(let i=0;i<s.length;i+=1)s[i].order=i;t.layers=n,t.hops=r}function pa(t){for(let n=0;n<4;n+=1){for(let r=1;r<t.layers.length;r+=1)Go(t,t.layers[r],"in"),sn(t.layers[r]);for(let r=t.layers.length-2;r>=0;r-=1)Go(t,t.layers[r],"out"),sn(t.layers[r])}for(let n=0;n<2;n+=1){let r=!1;for(let o=1;o<t.layers.length;o+=1){let s=t.layers[o];for(let i=0;i+1<s.length;i+=1){let a=$o(t,s[i],s[i+1],"in");[s[i],s[i+1]]=[s[i+1],s[i]],sn(s),$o(t,s[i],s[i+1],"in")<a?r=!0:([s[i],s[i+1]]=[s[i+1],s[i]],sn(s))}}if(!r)break}}function Go(t,e,n){let r=new Map;for(let o of e){let s=n==="in"?o.in:o.out;if(s.length===0){r.set(o.id,o.order);continue}let i=0,a=0;for(let d of s){let u=t.nodes.get(n==="in"?d.fromId:d.toId);u&&(i+=u.order,a+=1)}r.set(o.id,a===0?o.order:i/a)}e.sort((o,s)=>{let i=r.get(o.id),a=r.get(s.id);return i!==a?i-a:o.order-s.order})}function sn(t){for(let e=0;e<t.length;e+=1)t[e].order=e}function $o(t,e,n,r){let o=r==="in"?e.in:e.out,s=r==="in"?n.in:n.out,i=0;for(let a of o)for(let d of s){let u=t.nodes.get(r==="in"?a.fromId:a.toId)?.order??0,l=t.nodes.get(r==="in"?d.fromId:d.toId)?.order??0;(e.order<n.order&&u>l||e.order>n.order&&u<l)&&(i+=1)}return i}function fa(t,e){e.direction==="LR"?ma(t,e):ga(t,e)}function ma(t,e){let n=[],r=0;for(let o=0;o<t.layers.length;o+=1){n.push(r);let s=0;for(let i of t.layers[o])s=Math.max(s,i.w);r+=s+e.layerGap}for(let o=0;o<t.layers.length;o+=1)for(let s of t.layers[o])s.x=n[o];for(let o of t.layers){let s=0;for(let i of o)i.y=s,s+=i.h+e.nodeGap}jo(t,e,"y")}function ga(t,e){let n=[],r=0;for(let o=0;o<t.layers.length;o+=1){n.push(r);let s=0;for(let i of t.layers[o])s=Math.max(s,i.h);r+=s+e.layerGap}for(let o=0;o<t.layers.length;o+=1)for(let s of t.layers[o])s.y=n[o];for(let o of t.layers){let s=0;for(let i of o)i.x=s,s+=i.w+e.nodeGap}jo(t,e,"x")}function jo(t,e,n){let r=s=>n==="y"?s.h:s.w,o=e.nodeGap;for(let s=0;s<2;s+=1){let i=s===0?t.layers.slice(1):t.layers.slice(0,-1).reverse();for(let a of i){let d=new Map;for(let l of a){let c=s===0?l.in:l.out;if(c.length===0)continue;let p=[];for(let m of c){let h=t.nodes.get(s===0?m.fromId:m.toId);if(!h)continue;let g=n==="y"?h.y:h.x;p.push(g+Math.floor(r(h)/2))}if(p.length===0)continue;p.sort((m,h)=>m-h);let f=p[Math.floor(p.length/2)];d.set(l.id,f-Math.floor(r(l)/2))}let u=0;for(let l of a){let c=d.get(l.id),p=n==="y"?l.y:l.x,m=Math.max(c??p,u);n==="y"?l.y=m:l.x=m,u=m+r(l)+o}}}}function ha(t,e){let n=new Map;for(let u of t.hops){let l=n.get(u.chainId);l?l.push(u):n.set(u.chainId,[u])}for(let u of n.values())u.sort((l,c)=>l.hopIndex-c.hopIndex);let r=e.direction==="LR",o=u=>r?u.x:u.y,s=u=>r?u.w:u.h,i=u=>r?u.y+Math.floor(u.h/2):u.x+Math.floor(u.w/2),a=new Map;for(let u=0;u+1<t.layers.length;u+=1){let l=t.layers[u],c=t.layers[u+1],p=0;for(let S of l)p=Math.max(p,o(S)+s(S));let f=Number.POSITIVE_INFINITY;for(let S of c)f=Math.min(f,o(S));let m=Number.isFinite(f)?f-1:p,h=Math.max(1,m-p+1),g=[];for(let S of l)for(let N of S.out)g.push(N);g.sort((S,N)=>{let _=i(t.nodes.get(S.fromId)),R=i(t.nodes.get(N.fromId));if(_!==R)return _-R;let I=i(t.nodes.get(S.toId)),M=i(t.nodes.get(N.toId));return I-M});let y=[],b=new Map;for(let S of g){let N=i(t.nodes.get(S.fromId)),_=i(t.nodes.get(S.toId)),R=Math.min(N,_),I=Math.max(N,_),M=-1;for(let L=0;L<y.length;L+=1){let j=y[L],K=!0;for(let Q of j)if(Q.lo<=I&&R<=Q.hi){K=!1;break}if(K){j.push({lo:R,hi:I}),M=L;break}}M<0&&(y.push([{lo:R,hi:I}]),M=y.length-1),b.set(S,M)}let v=y.length,k=h>=Math.max(3,v+2),w=k?p+1:p,T=k?m-1:m,x=Math.max(1,T-w+1);for(let S of g){let N=b.get(S),_;if(v<=1)_=w+Math.floor(x/2);else{let R=(x-1)/(v-1);_=w+Math.floor(N*R)}a.set(S,Math.max(p,Math.min(m,_)))}}let d=[];for(let[,u]of n){let l=[];for(let p=0;p<u.length;p+=1){let f=u[p],m=t.nodes.get(f.fromId),h=t.nodes.get(f.toId),g=a.get(f),y=m.isVirtual?o(m):o(m)+s(m),b=h.isVirtual?o(h):o(h)-1,v=i(m),k=i(h);p===0&&an(l,r,y,v),v!==k&&(an(l,r,g,v),an(l,r,g,k)),an(l,r,b,k)}let c=u[0];d.push({from:c.chainFrom,to:c.chainTo,points:ya(l)})}return d}function an(t,e,n,r){t.push(e?{x:n,y:r}:{x:r,y:n})}function ya(t){let e=[];for(let n of t){let r=e[e.length-1];(!r||r.x!==n.x||r.y!==n.y)&&e.push(n)}return e}function ba(t){let e=0,n=0;for(let r of t.layers)for(let o of r)e=Math.max(e,o.x+o.w),n=Math.max(n,o.y+o.h);return{width:e,height:n}}var Ta=24,va=4,wa=1,ka=3;function Bo(t,e){let n=xa(e.direction),r=Math.max(3,e.maxLabelWidth??Ta),o=e.asciiCharset??"unicode",s=Object.keys(t.nodes).sort(),i=new Set(s),a=t.edges.filter(f=>i.has(f.from)&&i.has(f.to)),d=new Map,u=new Map;for(let f of s){let m=Ao(f,r);d.set(f,m),u.set(f,on(m)+4)}let l=Fo({nodes:s,edges:a,widthCells:f=>u.get(f)??3,heightCells:()=>ka,layerGap:va,nodeGap:wa,direction:n}),c=Io(l,{charset:o,labelOf:f=>d.get(f)??f}),p=e.logger;return p&&p(c),c}function xa(t){if(t===void 0||t==="LR")return"LR";if(t==="TD")return"TD";throw new Error(`ascii describe supports direction "LR" or "TD" only; got ${String(t)}`)}Ne();function Vo(t,e){let n=e?.topN??10,r=t.describe({detail:"standard"}),o=[],s=t._collectObserveTargets;typeof s=="function"&&s.call(t,"",o);let i=new Map;for(let[p,f]of o)i.set(p,f);let a=[];for(let[p,f]of Object.entries(r.nodes)){let m=i.get(p),h=m instanceof ie?m:null,g=h?No(h.cache):0,y=h?h._sinkCount:0,b=f.deps?.length??0,v=f.type==="effect"&&y===0,k=y===0?f.type==="effect"?"orphan-effect":f.type==="derived"?"idle-derived":f.type==="producer"?"idle-producer":null:null;a.push({path:p,type:f.type,status:f.status??"unknown",valueSizeBytes:g,subscriberCount:y,depCount:b,isOrphanEffect:v,orphanKind:k})}let d=a.reduce((p,f)=>p+f.valueSizeBytes,0),u=(p,f)=>[...a].sort(f??((m,h)=>h[p]-m[p])).slice(0,n),l=a.filter(p=>p.orphanKind!=null),c=a.filter(p=>p.isOrphanEffect);return{nodeCount:a.length,edgeCount:r.edges.length,subgraphCount:r.subgraphs.length,nodes:a,totalValueSizeBytes:d,hotspots:{byValueSize:u("valueSizeBytes"),bySubscriberCount:u("subscriberCount"),byDepCount:u("depCount")},orphans:l,orphanEffects:c}}var te="::",me="__meta__",Je=1;function Ko(t,e){let n=Math.max(16,t.size*4),r=0;for(;t.size>0;){if(r++>=n){console.error(`[Graph "${e}".destroy] disposer drain exceeded cap (${n}); ${t.size} disposer(s) discarded`),t.clear();return}let o=t.values().next();if(o.done)return;let s=o.value;t.delete(s);try{s()}catch(i){console.error(`[Graph "${e}".destroy] disposer threw:`,i)}}}function Ra(t){let e=[];for(let n of Object.keys(t).sort()){let r=t[n].v;r!=null&&e.push(`${n} ${r.id} ${r.version}`)}return e.join(`
|
|
10
|
+
`)}function Uo(t){if(t.version!==Je)throw new Error(`unsupported snapshot version ${String(t.version)} (expected ${Je})`);for(let e of["name","nodes","edges","subgraphs"])if(!(e in t))throw new Error(`snapshot missing required key "${e}"`);if(typeof t.name!="string")throw new TypeError("snapshot 'name' must be a string");if(typeof t.nodes!="object"||t.nodes===null||Array.isArray(t.nodes))throw new TypeError("snapshot 'nodes' must be an object");if(!Array.isArray(t.edges))throw new TypeError("snapshot 'edges' must be an array");if(!Array.isArray(t.subgraphs))throw new TypeError("snapshot 'subgraphs' must be an array")}function Sa(t,e){let n=new WeakMap,r=(o,s)=>{if(Object.is(o,s))return!0;if(o==null||s==null||typeof o!="object"||typeof s!="object")return!1;let i=n.get(o);if(i==null&&(i=new WeakSet,n.set(o,i)),i.has(s))return!0;i.add(s);let a=o.constructor,d=s.constructor;if(a!==d)return!1;if(o instanceof Date)return o.getTime()===s.getTime();if(o instanceof RegExp)return o.source===s.source&&o.flags===s.flags;if(Array.isArray(o)){let p=s;if(o.length!==p.length)return!1;for(let f=0;f<o.length;f++)if(!r(o[f],p[f]))return!1;return!0}if(o instanceof Map){let p=s;if(o.size!==p.size)return!1;for(let[f,m]of o)if(!p.has(f)||!r(m,p.get(f)))return!1;return!0}if(o instanceof Set){let p=s;if(o.size!==p.size)return!1;for(let f of o){let m=!1;for(let h of p)if(r(f,h)){m=!0;break}if(!m)return!1}return!0}if(ArrayBuffer.isView(o)){let p=o,f=s;if(p.length!==f.length)return!1;for(let m=0;m<p.length;m++)if(p[m]!==f[m])return!1;return!0}let u=Object.keys(o),l=Object.keys(s);if(u.length!==l.length)return!1;let c=new Set(l);for(let p of u)if(!c.has(p)||!r(o[p],s[p]))return!1;return!0};return r(t,e)}function ir(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(ir);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=ir(e[o]);return r}function Na(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function _a(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Ma(t){return t==="TD"?"down":t==="BT"?"up":t==="RL"?"left":"right"}function Ho(t){let e=new Set,n=[];function r(o,s){let i=`${o}\0${s}`;e.has(i)||(e.add(i),n.push([o,s]))}for(let[o,s]of Object.entries(t.nodes)){let i=s.deps;if(i)for(let a of i)r(a,o)}for(let o of t.edges)r(o.from,o.to);return n}function Wo(t){if(t===void 0)return"LR";if(t==="TD"||t==="LR"||t==="BT"||t==="RL")return t;throw new Error(`invalid diagram direction ${String(t)}; expected one of: TD, LR, BT, RL`)}function Ea(t,e){let n=e.includeEdges??!0,r=e.includeSubgraphs??!0,{expand:o,...s}=t,i={...s,edges:n?t.edges:[],subgraphs:r?t.subgraphs:[]},a=JSON.stringify(ir(i),null,e.indent??2);return e.logger?.(a),a}function Oa(t,e){let n=e.includeEdges??!0,r=e.includeSubgraphs??!0,o=[];o.push(`Graph ${t.name}`),o.push("Nodes:");for(let i of Object.keys(t.nodes).sort()){let a=t.nodes[i];o.push(`- ${i} (${a.type}/${a.status}): ${dn(a.value)}`)}if(n){o.push("Edges:");for(let i of t.edges)o.push(`- ${i.from} -> ${i.to}`)}if(r){o.push("Subgraphs:");for(let i of t.subgraphs)o.push(`- ${i}`)}let s=o.join(`
|
|
11
|
+
`);return e.logger?.(s),s}function qo(t,e){let n=Wo(e.direction),r=Object.keys(t.nodes).sort(),o=new Map;for(let i=0;i<r.length;i+=1)o.set(r[i],`n${i}`);let s=[`flowchart ${n}`];for(let i of r){let a=o.get(i);s.push(` ${a}["${Na(i)}"]`)}for(let[i,a]of Ho(t)){let d=o.get(i),u=o.get(a);!d||!u||s.push(` ${d} --> ${u}`)}return s.join(`
|
|
12
|
+
`)}function Aa(t,e){let n=qo(t,e);return Jo(n)}function Jo(t,e){let n=e?.theme??"default",r=e?.autoSync??!0,s=JSON.stringify({code:t,mermaid:{theme:n},autoSync:r}),i=new TextEncoder().encode(s),a="";for(let u=0;u<i.length;u++)a+=String.fromCharCode(i[u]);return`https://mermaid.live/edit#base64:${globalThis.btoa(a).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`}function Ca(t,e){let n=Wo(e.direction),r=Object.keys(t.nodes).sort(),o=new Map;for(let i=0;i<r.length;i+=1)o.set(r[i],`n${i}`);let s=[`direction: ${Ma(n)}`];for(let i of r){let a=o.get(i);s.push(`${a}: "${_a(i)}"`)}for(let[i,a]of Ho(t)){let d=o.get(i),u=o.get(a);!d||!u||s.push(`${d} -> ${u}`)}return s.join(`
|
|
13
|
+
`)}function La(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function un(t){let e="^";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="*"){e+=".*";continue}if(r==="?"){e+=".";continue}if(r==="["){let o=t.indexOf("]",n+1);if(o<=n+1){e+="\\[";continue}let s=t.slice(n+1,o);s.startsWith("!")&&(s=`^${s.slice(1)}`),s=s.replace(/\\/g,"\\\\"),e+=`[${s}]`,n=o;continue}e+=La(r)}return e+="$",new RegExp(e)}var Da={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"},Ia={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function dn(t){if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||t==null)return String(t);try{return JSON.stringify(t)}catch{return"[unserializable]"}}function Pa(t){return t==="none"?Ia:t==="ansi"||t==null?Da:{data:t.data??"",dirty:t.dirty??"",resolved:t.resolved??"",invalidate:t.invalidate??"",pause:t.pause??"",resume:t.resume??"",complete:t.complete??"",error:t.error??"",teardown:t.teardown??"",derived:t.derived??"",path:t.path??"",reset:t.reset??""}}function zo(t){if(t==null)return{};let e=t.detail;return e==="full"?{...t,structured:t.structured??!0,timeline:t.timeline??!0,causal:t.causal??!0,derived:t.derived??!0}:e==="minimal"?{...t,structured:t.structured??!0}:t.format==="stage-log"?{...t,structured:t.structured??!0,timeline:t.timeline??!0}:t}function Ga(t,e,n){for(let r=0;r<t.length;r++){let o=t.charCodeAt(r);if(o<32||o===127)throw new Error(`Graph "${e}": ${n} "${t}" must not contain control character (U+${o.toString(16).padStart(4,"0").toUpperCase()} at index ${r})`)}}function sr(t,e,n){if(t==="")throw new Error(`Graph "${e}": ${n} name must be non-empty`);if(t.includes(te))throw new Error(`Graph "${e}": ${n} "${t}" must not contain '${te}' (path separator)`);if(t===me)throw new Error(`Graph "${e}": ${n} name "${me}" is reserved for meta companion paths`);Ga(t,e,n)}function $a(t,e){if(t==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let n=t.split(te);for(let r of n)if(r==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return n}function Fa(t,e){let n=!1;for(let o of t)if(!e.isMetaPassthrough(o[0])){n=!0;break}return n?t.filter(o=>e.isMetaPassthrough(o[0])):t}function Yo(t){for(let e of t._mounts.values())Yo(e);for(let e of t._nodes.values())try{e.down([[ue]],{internal:!0})}catch{}}var se=class t{name;opts;config;_nodes=new Map;_nodeToName=new WeakMap;_mounts=new Map;_parent=void 0;_storageDisposers=new Set;_disposers=new Set;_destroyed=!1;_topology;_topologyEmitters=new Set;constructor(e,n){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(te))throw new Error(`Graph name must not contain '${te}' (got "${e}")`);if(e===me)throw new Error(`Graph name "${me}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...n??{}}),this.config=n?.config??tt,this._traceRing=new bt(n?.traceCapacity??1e3),n?.versioning!=null&&this.setVersioning(n.versioning)}ancestors(e=!0){let n=[],r=e?this:this._parent;for(;r!=null;)n.push(r),r=r._parent;return n}get topology(){return this._topology==null&&(this._topology=Z(e=>{let n=r=>{e.emit(r)};return this._topologyEmitters.add(n),()=>{this._topologyEmitters.delete(n)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(e){if(!(this._topology==null||this._topologyEmitters.size===0))for(let n of this._topologyEmitters)n(e)}add(e,n){let r=e.name,o=n?.name??r;if(o==null||o==="")throw new Error(`Graph "${this.name}": graph.add requires a non-empty name \u2014 pass via opts.name or set it on the node (e.g. state(0, { name: "x" }))`);let s=o,i=n?.annotation;if(sr(s,this.name,"add"),this._mounts.has(s))throw new Error(`Graph "${this.name}": name "${s}" is already a mount point`);if(this._nodes.has(s))throw new Error(`Graph "${this.name}": node "${s}" already exists`);let a=this._nodeToName.get(e);if(a!==void 0)throw new Error(`Graph "${this.name}": node instance already registered as "${a}"`);return this._nodes.set(s,e),this._nodeToName.set(e,s),this._emitTopology({kind:"added",name:s,nodeKind:"node"}),i!=null&&(this._annotations.set(s,i),this.config.inspectorEnabled&&this._traceRing.push({path:s,annotation:i,timestamp_ns:F()})),e}setVersioning(e){if(e!=null)for(let n of this._nodes.values())n instanceof ie&&n._applyVersioning(e)}remove(e){sr(e,this.name,"remove");let n=this._mounts.get(e);if(n){let s={kind:"mount",nodes:[],mounts:[]},i=[];n._collectObserveTargets("",i);for(let[a,d]of i)a.includes(`${te}${me}${te}`)||s.nodes.push(a);return s.nodes.sort(),s.mounts.push(e),s.mounts.push(...n._collectSubgraphs(`${e}${te}`)),this._mounts.delete(e),n._parent=void 0,Yo(n),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:s}),s}let r=this._nodes.get(e);if(!r)throw new Error(`Graph "${this.name}": unknown node or mount "${e}"`);this._nodes.delete(e),this._nodeToName.delete(r),r.down([[ue]],{internal:!0});let o={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:o}),o}removeAll(e){let n=typeof e=="function"?e:(()=>{let s=un(e);return i=>s.test(i)})(),r={kind:"mount",nodes:[],mounts:[]},o=[...this._nodes.keys(),...this._mounts.keys()].filter(s=>n(s));for(let s of o){let i=this.remove(s);r.nodes.push(...i.nodes),r.mounts.push(...i.mounts)}return r.nodes.sort(),r.mounts.sort(),r}[Symbol.iterator](){let e=[...this._nodes.keys()].sort(),n=this._nodes,r=0;return{[Symbol.iterator](){return this},next(){if(r>=e.length)return{value:void 0,done:!0};let o=e[r++];return{value:[o,n.get(o)],done:!1}}}}node(e){if(e==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(e.includes(te))return this.resolve(e);let n=this._nodes.get(e);if(!n)throw new Error(`Graph "${this.name}": unknown node "${e}"`);return n}get(e){return this.node(e).cache}set(e,n,r){let o=r?.internal===!0;this.node(e).down([[C,n]],{actor:r?.actor,internal:o,delivery:"write"})}setAll(e,n){let r=Symbol.iterator in e?e:Object.entries(e);X(()=>{for(let[o,s]of r)this.set(o,s,n)})}invalidate(e,n){let r=n?.internal===!0;this.node(e).down([[xe]],{actor:n?.actor,internal:r,delivery:"write"})}error(e,n,r){let o=r?.internal===!0;this.node(e).down([[O,n]],{actor:r?.actor,internal:o,delivery:"write"})}complete(e,n){let r=n?.internal===!0;this.node(e).down([[G]],{actor:n?.actor,internal:r,delivery:"write"})}edges(e){let n=e?.recursive===!0,r=new Map;if(!n){for(let[d,u]of this._nodes)r.set(u,d);let a=[];for(let[d,u]of this._nodes)if(u instanceof ie)for(let l of u._deps){let c=r.get(l.node);c!=null&&a.push([c,d])}return a.sort((d,u)=>d[0]<u[0]?-1:d[0]>u[0]?1:d[1]<u[1]?-1:d[1]>u[1]?1:0),a}let o=[];this._collectObserveTargets("",o);let s=new Map;for(let[a,d]of o)s.set(d,a);let i=[];for(let[a,d]of o)if(d instanceof ie)for(let u of d._deps){let l=s.get(u.node);l!=null&&i.push([l,a])}return i.sort((a,d)=>a[0]<d[0]?-1:a[0]>d[0]?1:a[1]<d[1]?-1:a[1]>d[1]?1:0),i}mount(e,n){if(sr(e,this.name,"mount"),this._nodes.has(e))throw new Error(`Graph "${this.name}": cannot mount at "${e}" \u2014 node with that name exists`);if(this._mounts.has(e))throw new Error(`Graph "${this.name}": mount "${e}" already exists`);if(n===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(n._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${n._parent.name}"`);for(let r=this;r!=null;r=r._parent)if(r===n)throw new Error(`Graph "${this.name}": mount("${e}", \u2026) would create a mount cycle`);return this._mounts.set(e,n),n._parent=this,this._emitTopology({kind:"added",name:e,nodeKind:"mount"}),n}resolve(e){let n=$a(e,this.name);return this._resolveFromSegments(n)}tryResolve(e){try{return this.resolve(e)}catch{return}}_resolveFromSegments(e){let n=e;if(n[0]===this.name&&(n=n.slice(1),n.length===0))throw new Error(`Graph "${this.name}": resolve path ends at graph name only`);let r=n[0],o=n.slice(1);if(o.length===0){let a=this._nodes.get(r);if(a)return a;throw this._mounts.has(r)?new Error(`Graph "${this.name}": path ends at subgraph "${r}" \u2014 not a node (GRAPHREFLY-SPEC \xA73.5)`):new Error(`Graph "${this.name}": unknown name "${r}"`)}let s=this._nodes.get(r);if(s&&o.length>0&&o[0]===me)return this._resolveMetaChainFromNode(s,o,n.join(te));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(te)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${r}"`);return i.resolve(o.join(te))}_resolveMetaChainFromNode(e,n,r){let o=e,s=0,i=[...n];for(;s<i.length;){if(i[s]!==me)throw new Error(`Graph "${this.name}": expected ${me} segment in meta path "${r}"`);if(s+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${me} in "${r}"`);let a=i[s+1],d=o.meta[a];if(!d)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${r}"`);o=d,s+=2}return o}signal(e,n){if(n?.internal!==!0){for(let o of e)if(this.config.messageTier(o[0])===3)throw new Error(`Graph "${this.name}": Graph.signal() rejects tier-3 messages (DATA / RESOLVED). Broadcast is for control-plane tiers (START / DIRTY / INVALIDATE / PAUSE / RESUME / COMPLETE / ERROR / TEARDOWN). For per-node value writes, use Graph.set or graph.node(name).down(...).`)}let r=[];if(this._signalDeliver(e,n??{},new Set,r),r.length>0)throw r[0]}_signalDeliver(e,n,r,o){for(let d of this._mounts.values())d._signalDeliver(e,n,r,o);let i=n.internal===!0?{internal:!0}:{actor:n.actor,delivery:"signal"},a=Fa(e,this.config);for(let d of[...this._nodes.keys()].sort()){let u=this._nodes.get(d);if(!r.has(u)){r.add(u);try{u.down(e,i)}catch(l){if(l instanceof Se)throw l;o.push(l)}a.length!==0&&this._signalMetaSubtree(u,a,r,i,o)}}}_signalMetaSubtree(e,n,r,o,s){for(let i of Object.keys(e.meta).sort()){let a=e.meta[i];if(!r.has(a)){r.add(a);try{a.down(n,o)}catch(d){if(d instanceof Se)throw d;s.push(d)}this._signalMetaSubtree(a,n,r,o,s)}}}describe(e){if(e?.reactive===!0)return this._describeReactive(e);let n=e?.actor,r=e?.filter,o=en(e?.detail,e?.fields),s=e?.format==="spec",i=s?en("minimal"):o,a=[];this._collectObserveTargets("",a);let d=new Map;for(let[T,x]of a)d.set(x,T);let u=[];{let T=a.map(([,N])=>N),x=new Set(d.values()),S=0;for(;T.length>0;){let N=T.shift();if(N instanceof ie)for(let _ of N._deps){let R=_.node;if(d.has(R))continue;let I=R.name??"",M=I;if(!M||x.has(M))if(I){let L=2;for(;x.has(`${I}#${L}`);)L++;M=`${I}#${L}`}else for(M=`__internal__/${S++}`;x.has(M);)M=`__internal__/${S++}`;d.set(R,M),x.add(M),u.push([M,R]),T.push(R)}}}let l=[...a,...u],c={};for(let[T,x]of l){if(n!=null&&!x.allowsObserve(n))continue;let S=rr(x,i),N=x instanceof ie?x._deps.map(M=>d.get(M.node)??M.node.name??""):[],{name:_,...R}=S,I={...R,deps:N};if(!s){let M=this._annotations.get(T);M!=null&&(I.annotation=M)}if(r!=null)if(typeof r=="function"){let M=r;if(!(M.length>=2?M(T,I):M(I)))continue}else{let M=!0;for(let[L,j]of Object.entries(r)){let K=L==="deps_includes"?"depsIncludes":L==="meta_has"?"metaHas":L;if(K==="depsIncludes"){if(!I.deps.includes(String(j))){M=!1;break}continue}if(K==="metaHas"){if(!Object.hasOwn(I.meta??{},String(j))){M=!1;break}continue}if(I[K]!==j){M=!1;break}}if(!M)continue}c[T]=I}let p=new Set(Object.keys(c)),f=[];for(let[T,x]of l)if(x instanceof ie)for(let S of x._deps){let N=d.get(S.node);N!=null&&f.push([N,T])}f.sort((T,x)=>T[0]<x[0]?-1:T[0]>x[0]?1:T[1]<x[1]?-1:T[1]>x[1]?1:0);let m=f.map(([T,x])=>({from:T,to:x}));(n!=null||r!=null)&&(m=m.filter(T=>p.has(T.from)&&p.has(T.to)));let h=this._collectSubgraphs(""),g=n!=null||r!=null?h.filter(T=>{let x=`${T}${te}`;return[...p].some(S=>S===T||S.startsWith(x))}):h,y=this,b=e,v={name:this.name,nodes:c,edges:m,subgraphs:g,expand(T){let x={...b,format:void 0};return Array.isArray(T)?(x.fields=T,x.detail=void 0):(x.detail=T,x.fields=void 0),y.describe(x)}},k=e??{},w=k.format;return w==="json"?Ea(v,k):w==="pretty"?Oa(v,k):w==="mermaid"?qo(v,k):w==="mermaid-url"?Aa(v,k):w==="d2"?Ca(v,k):w==="ascii"?Bo(v,k):v}_collectSubgraphs(e){let n=[];for(let r of[...this._mounts.keys()].sort()){let o=e===""?r:`${e}${r}`;n.push(o),n.push(...this._mounts.get(r)._collectSubgraphs(`${o}${te}`))}return n}resourceProfile(e){return Vo(this,e)}reachable(e,n,r={}){return r.withDetail===!0?ar(this.describe(),e,n,{...r,withDetail:!0}):ar(this.describe(),e,n,r)}explain(e,n,r){return r?.reactive===!0?this._explainReactive(e,n,r):this._explainStatic(e,n,r)}_explainStatic(e,n,r){let o=this.describe({detail:"full"}),s=new Map(this._annotations),i=new Map;for(let[a,d]of Object.entries(o.nodes))d.lastMutation!=null&&i.set(a,d.lastMutation);return _o(o,e,n,{...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{},annotations:s,lastMutations:i})}_describeReactive(e){let n={...e,reactive:!1},r=e.reactiveName??"describe",o=0,s=A(o,{name:`${r}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=()=>{a||d||(a=!0,pt(()=>{a=!1,!d&&(o+=1,s.emit(o))}))},l=i.onEvent(g=>{let y=g.type;y!=="data"&&y!=="error"&&y!=="complete"&&y!=="teardown"||u()}),c=[],p=new WeakSet,f=g=>{if(p.has(g)||d)return;p.add(g);let y=g.topology.subscribe(b=>{for(let v of b){if(v[0]!==C)continue;let k=v[1];if(u(),k.kind==="added"&&k.nodeKind==="mount"){let w=g._mounts.get(k.name);w!=null&&f(w)}}});c.push(y);for(let b of g._mounts.keys()){let v=g._mounts.get(b);v!=null&&f(v)}};f(this);let m;try{m=E([s],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(g,y)=>g===y})}catch(g){l();for(let y of c)y();throw i.dispose(),g}let h=q(m);return{node:m,dispose(){d=!0,l();for(let g of c)g();c.length=0,i.dispose(),h()}}}_explainReactive(e,n,r){let o=0,s=A(o,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=i.onEvent(f=>{let m=f.type;m!=="data"&&m!=="error"&&m!=="complete"&&m!=="teardown"||a||d||(a=!0,pt(()=>{a=!1,!d&&(o+=1,s.emit(o))}))}),l={...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{}},c;try{c=E([s],()=>this._explainStatic(e,n,l),{name:r?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:e,to:n},equals:(f,m)=>f.found===m.found&&f.reason===m.reason&&f.steps.length===m.steps.length&&ja(f.steps,m.steps)})}catch(f){throw u(),i.dispose(),f}let p=q(c);return{node:c,dispose(){d=!0,u(),i.dispose(),p()}}}_pathsMatching(e){let n=un(e),r=[];return this._collectObserveTargets("",r),r.map(([o])=>o).filter(o=>n.test(o))}_collectObserveTargets(e,n){for(let r of[...this._mounts.keys()].sort()){let o=e===""?r:`${e}${te}${r}`;this._mounts.get(r)._collectObserveTargets(o,n)}for(let r of[...this._nodes.keys()].sort()){let o=this._nodes.get(r),s=e===""?r:`${e}${te}${r}`;n.push([s,o]),this._appendMetaObserveTargets(s,o,n)}}_appendMetaObserveTargets(e,n,r){for(let o of Object.keys(n.meta).sort()){let s=n.meta[o],i=`${e}${te}${me}${te}${o}`;r.push([i,s]),this._appendMetaObserveTargets(i,s,r)}}observe(e,n){let r=typeof e=="string",s=zo(r?n:e),i=s.structured===!0||s.timeline===!0||s.causal===!0||s.derived===!0||s.detail==="minimal"||s.detail==="full"||s.format!=null,a=s.actor;if(r){let l=e,c=this.resolve(l);if(a!=null&&!c.allowsObserve(a))throw new Se({actor:a,action:"observe",nodeName:l});return i?this._buildStructuredObserver([[l,c]],s,"one"):{subscribe(p){return c.subscribe(p)},up(p){try{c.up?.(p)}catch(f){if(f instanceof Se)return;throw f}}}}let d=[];this._collectObserveTargets("",d),d.sort((l,c)=>l[0]<c[0]?-1:l[0]>c[0]?1:0);let u=a==null?d:d.filter(([,l])=>l.allowsObserve(a));return i?this._buildStructuredObserver(u,s,"all"):{subscribe:l=>{let c=u.map(([p,f])=>f.subscribe(m=>{l(p,m)}));return()=>{for(let p of c)p()}},up:(l,c)=>{try{this.resolve(l).up?.(c)}catch(p){if(p instanceof Se)return;throw p}}}}_buildStructuredObserver(e,n,r){let o=r==="one"?e[0]?.[0]:void 0,s=i=>{if(r==="one"&&o!=null){let l=this.resolve(o);return this._buildStructuredObserver([[o,l]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((l,c)=>l[0]<c[0]?-1:l[0]>c[0]?1:0);let d=i.actor,u=d==null?a:a.filter(([,l])=>l.allowsObserve(d));return this._buildStructuredObserver(u,i,"all")};return this._createObserveResult(e,n,s)}_createObserveResult(e,n,r){let o=n.timeline===!0,s=n.causal===!0,i=n.derived===!0,a=n.detail==="minimal",d=this.config.inspectorEnabled,u=(s||i)&&d,l=n.maxEvents,c=l!=null&&l>0?new bt(l):null,p=[],f=new Set,m={},h=new Set,g=0,y=0,b=0,v=0,k=0,w=0,T=!1,x=!1,S=0,N=new Map,_=new Map,R=new Map,I=D=>{c?c.push(D):p.push(D);for(let W of f)W(D)},M=()=>o?{timestamp_ns:F(),in_batch:Nt(),batch_id:S}:{},L=(D,W)=>{if(!(!u||!(D instanceof ie)))return D._setInspectorHook(de=>{if(de.kind==="dep_message")N.set(D,de.depIndex);else if(de.kind==="run"){let ge=de.batchData.map((Y,ye)=>Y!=null&&Y.length>0?Y.at(-1):de.prevData[ye]);_.set(D,ge);let he=de.batchData.map(Y=>Y!=null?[...Y]:void 0);R.set(D,he),i&&I({type:"derived",path:W,dep_values:ge,dep_batches:he,...M()})}})},j=D=>{let W=N.get(D),de=_.get(D);if(!s||de==null)return{};let he=(W!=null&&W>=0&&D instanceof ie?D._deps[W]:void 0)?.node,Y=he?.v,ye=R.get(D);return{trigger_dep_index:W,trigger_dep_name:he?.name,...Y!=null?{trigger_version:{id:Y.id,version:Y.version}}:{},dep_values:[...de],...ye!=null?{dep_batches:ye}:{}}},K=[],Q=[];for(let[D,W]of e){let de=L(W,D);de&&K.push(de),Q.push(W.subscribe(ge=>{S++;for(let he of ge){let Y=he[0],ye=M();if(Y===C){m[D]=he[1];let mn=W instanceof ie?W.lastMutation?.actor??Xe:Xe;I({type:"data",path:D,data:he[1],actor:mn,...ye,...j(W)})}else if(a)Y===z?g++:Y===B?y++:Y===xe?b++:Y===Re?v++:Y===Oe?k++:Y===ue?w++:Y===G&&!h.has(D)?T=!0:Y===O&&(x=!0,h.add(D));else if(Y===z)g++,I({type:"dirty",path:D,...ye});else if(Y===B)y++,I({type:"resolved",path:D,...ye,...j(W)});else if(Y===xe)b++,I({type:"invalidate",path:D,...ye});else if(Y===Re)v++,I({type:"pause",path:D,lockId:he[1],...ye});else if(Y===Oe)k++,I({type:"resume",path:D,lockId:he[1],...ye});else if(Y===G)h.has(D)||(T=!0),I({type:"complete",path:D,...ye});else if(Y===O){x=!0,h.add(D);let mn=W instanceof ie?W.lastMutation?.actor??Xe:Xe;I({type:"error",path:D,data:he[1],actor:mn,...ye})}else Y===ue&&(w++,I({type:"teardown",path:D,...ye}))}}))}let we=!1,_e=()=>{if(!we){we=!0;for(let D of Q)D();for(let D of K)D();for(let D of H)D({value:void 0,done:!0});H.length=0}},Qe=[],H=[];f.add(D=>{let W=H.shift();W?W({value:D,done:!1}):Qe.push(D)});let $={get values(){return m},get dirtyCount(){return g},get resolvedCount(){return y},get invalidateCount(){return b},get pauseCount(){return v},get resumeCount(){return k},get teardownCount(){return w},get events(){return c?c.toArray():[...p]},get anyCompletedCleanly(){return T},get anyErrored(){return x},get completedWithoutErrors(){return T&&!x},onEvent(D){return f.add(D),()=>f.delete(D)},dispose:_e,expand(D){_e();let W={...n};return typeof D=="string"?W.detail=D:Object.assign(W,D),r(zo(W))},[Symbol.asyncIterator](){return{next(){return Qe.length>0?Promise.resolve({value:Qe.shift(),done:!1}):we?Promise.resolve({value:void 0,done:!0}):new Promise(D=>H.push(D))},return(){return _e(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger($,n),$}_attachFormatLogger(e,n){let r=n.format;if(r==null)return;let o=n.logger??(m=>console.log(m)),s=n.includeTypes?new Set(n.includeTypes):null,i=n.excludeTypes?new Set(n.excludeTypes):null,a=s==null&&i==null?()=>!0:m=>(s==null||s.has(m))&&(i==null||!i.has(m)),d=Pa(n.theme),u=r==="stage-log"?F():0,l=m=>m==null?"":n.stageLabels?.[m]??m,c=(m,h)=>m.length>h?`${m.slice(0,h-1)}\u2026`:m,p=m=>m.type==="data"||m.type==="error"?c(dn(m.data),120):"",f=m=>{if(r==="stage-log"){let x=(F()-u)/1e9,S=l(m.path).padEnd(9);if(m.type==="data"){let N=p(m);return`[${x.toFixed(3)}s] ${S} \u2190${N?` ${N}`:""}`}if(m.type==="error"){let N=p(m);return`[${x.toFixed(3)}s] ${S} \u2717${N?` ${N}`:""}`}return m.type==="complete"?`[${x.toFixed(3)}s] ${S} \u25A0 complete`:`[${x.toFixed(3)}s] ${S} ${m.type}`}if(r==="json")try{return JSON.stringify(m)}catch{return JSON.stringify({type:m.type,path:m.path,data:"[unserializable]"})}let h=d[m.type]??"",g=m.path?`${d.path}${m.path}${d.reset} `:"",y=m.type==="data"||m.type==="error",b=m.type==="pause"||m.type==="resume",v=y?` ${dn(m.data)}`:b?` ${dn(m.lockId)}`:"",k=m.type==="data"||m.type==="resolved"||m.type==="derived"?m:void 0,w=k?.trigger_dep_name!=null?` <- ${k.trigger_dep_name}`:k?.trigger_dep_index!=null?` <- #${k.trigger_dep_index}`:"",T=m.in_batch?" [batch]":"";return`${g}${h}${m.type.toUpperCase()}${d.reset}${v}${w}${T}`};e.onEvent(m=>{a(m.type)&&o(f(m),m)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){Ko(this._disposers,this.name),this.signal([[ue]],{internal:!0}),Ko(this._storageDisposers,this.name);for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}get destroyed(){return this._destroyed}_destroyClearOnly(){for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}snapshot(e){let{expand:n,...r}=this.describe({detail:"full"}),o={};for(let a of Object.keys(r.nodes).sort()){let{lastMutation:d,guard:u,...l}=r.nodes[a];o[a]=l}let s=[...r.subgraphs].sort(),i={...r,version:1,nodes:o,subgraphs:s};if(e?.format==null)return i;if(e.format==="json-string")return JSON.stringify(i);if(e.format==="bytes"){if(e.codec==null)throw new Error("snapshot({format: 'bytes'}) requires a `codec` name");let a=this.config.lookupCodec(e.codec);if(a==null)throw new Error(`snapshot: codec "${e.codec}" is not registered on this graph's config. Call config.registerCodec(...) before creating nodes.`);return kr(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,n){let r=n?.config??tt,{codec:o,codecVersion:s,payload:i}=xr(e,r);return o.decode(i,s)}restore(e,n){if(Uo(e),e.name!==this.name)throw new Error(`Graph "${this.name}": restore snapshot name "${e.name}" does not match this graph`);let r=n?.only==null?null:(Array.isArray(n.only)?n.only:[n.only]).map(s=>un(s)),o=n?.includeProducers===!0;for(let s of Object.keys(e.nodes).sort()){if(r!==null&&!r.some(a=>a.test(s)))continue;let i=e.nodes[s];if(i!==void 0){if(!("value"in i)||i.value===void 0){"value"in i&&i.value===void 0&&n?.onError?.(s,new Error(`restore: slice.value is undefined for "${s}" (undefined is the global SENTINEL; not valid DATA)`));continue}if(!(i.type==="derived"||i.type==="effect")&&!(i.type==="producer"&&!o)){if(i.v!=null){let d=this.tryResolve(s)?.v;if(d!=null&&d.id===i.v.id&&d.version===i.v.version)continue}try{this.set(s,i.value)}catch(a){n?.onError?.(s,a)}}}}}static fromSnapshot(e,n){Uo(e);let r=typeof n=="function"?n:n?.build,o=typeof n=="function"?void 0:n?.factories,s=new t(e.name);if(r)return r(s),s.restore(e),s;for(let f of[...e.subgraphs].sort((m,h)=>{let g=m.split(te).length,y=h.split(te).length;return g!==y?g-y:m<h?-1:m>h?1:0})){let m=f.split(te),h=s;for(let g of m)h._mounts.has(g)||h.mount(g,new t(g)),h=h._mounts.get(g)}let i=o?Object.entries(o).map(([f,m])=>({re:un(f),factory:m})):[],a=f=>{for(let m of i)if(m.re.test(f))return m.factory},d=f=>{let m=f.split(te),h=m.pop();if(h==null||h.length===0)throw new Error(`invalid snapshot path "${f}"`);let g=s;for(let y of m){let b=g._mounts.get(y);if(!b)throw new Error(`unknown mount "${y}" in path "${f}"`);g=b}return[g,h]},u=Object.entries(e.nodes).filter(([f])=>!f.includes(`${te}${me}${te}`)).sort((f,m)=>f[0]<m[0]?-1:f[0]>m[0]?1:0),l=new Map(u),c=new Map,p=!0;for(;l.size>0&&p;){p=!1;for(let[f,m]of[...l.entries()]){let h=m?.deps??[];if(!h.every(w=>c.has(w)))continue;let[g,y]=d(f),b={...m?.meta??{}},v=a(f),k;if(m?.type==="state")k=A(m.value,{meta:b});else{if(v==null)continue;k=v(y,{path:f,type:m.type,value:m.value,meta:b,deps:h,resolvedDeps:h.map(w=>c.get(w))})}g.add(k,{name:y}),c.set(f,k),l.delete(f),p=!0}}if(l.size>0){let f=[...l.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${f}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return s.restore(e),s}toJSON(){return this.snapshot()}attachStorage(e,n={}){let r=e.map(u=>({tier:u,debounceMs:Math.max(0,u.debounceMs??0),compactEvery:Math.max(1,u.compactEvery??10),timer:void 0,seq:0,lastSnapshot:void 0,lastFingerprint:"",disposed:!1,savePending:void 0}));n.autoRestore===!0&&this._cascadeRestore(e,n.onError);let o=(u,l)=>{if(u.disposed)return;let c=Ra(l.nodes);if(u.lastSnapshot!=null&&c!==""&&c===u.lastFingerprint)return;let p=u.seq+1,f=pe(),g=u.lastSnapshot==null||p%u.compactEvery===0?{mode:"full",snapshot:l,seq:p,timestamp_ns:f,format_version:Je}:{mode:"diff",diff:Qo(u.lastSnapshot,l),seq:p,timestamp_ns:f,format_version:Je};if(u.tier.filter&&!u.tier.filter(this.name,g))return;let y;try{y=u.tier.save(this.name,g)}catch(b){n.onError?.(b,u.tier);return}if(y&&typeof y.then=="function"){let k=(u.savePending??Promise.resolve()).then(()=>y,()=>y).then(()=>{u.disposed||(u.seq=p,u.lastSnapshot=l,u.lastFingerprint=c)},w=>{n.onError?.(w,u.tier)});u.savePending=k.finally(()=>{u.savePending===k&&(u.savePending=void 0)})}else u.seq=p,u.lastSnapshot=l,u.lastFingerprint=c},s=(u,l)=>{try{o(u,l)}catch(c){n.onError?.(c,u.tier)}},i=(u,l)=>{if(!l.some(m=>{let h=this.config.messageTier(m[0]);return h>=3&&h<5}))return;if(n.filter){let m=this.tryResolve(u);if(m==null)return;let h=rr(m,en("standard"));if(!n.filter(u,h))return}let p,f=()=>(p==null&&(p=this.snapshot()),p);for(let m of r)m.disposed||(m.debounceMs===0?s(m,f()):(m.timer==null&&(m.timer=new re),m.timer.start(m.debounceMs,()=>{m.disposed||s(m,this.snapshot())})))},a;if(n.paths!=null){let l=(typeof n.paths=="string"?this._pathsMatching(n.paths):n.paths).map(c=>{let p=this.tryResolve(c);return p==null?()=>{}:p.subscribe(f=>i(c,f))});a=()=>{for(let c of l)c()}}else a=this.observe().subscribe((u,l)=>i(u,l));let d=()=>{a();for(let u of r)u.disposed=!0,u.timer?.cancel();this._storageDisposers.delete(d)};return this._storageDisposers.add(d),{dispose:d}}async _cascadeRestore(e,n){for(let r of e){let o;try{o=await r.load(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===Je&&s.nodes!=null)return this.restore(s),!0}catch(i){n?.(i,r)}}return!1}static async fromStorage(e,n,r){for(let o of n){let s;try{s=await o.load(e)}catch(d){r?.onError?.(d,o);continue}if(s==null||typeof s!="object"||Array.isArray(s))continue;let i=s,a=i.mode==="full"&&i.snapshot!=null?i.snapshot:i.version===Je&&i.nodes!=null?i:void 0;if(a!=null)try{return t.fromSnapshot(a,r)}catch(d){r?.onError?.(d,o)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${e}" across ${n.length} tier(s)`)}_annotations=new Map;_traceRing;trace(e,n,r){if(e!=null&&n!=null){if(this.tryResolve(e)==null)return;if(this._annotations.set(e,n),this.config.inspectorEnabled){let o={path:e,annotation:n,timestamp_ns:F(),...r?.actor!=null?{actor:r.actor}:{}};this._traceRing.push(o)}return}return e!=null?this.config.inspectorEnabled?this._annotations.get(e):void 0:this.config.inspectorEnabled?this._traceRing.toArray():[]}annotation(e){return this._annotations.get(e)}clearTrace(){this._annotations.clear(),this._traceRing.clear()}pruneTrace(e){let n=this._traceRing.toArray().filter(o=>!e(o)),r=this._traceRing.size-n.length;this._traceRing.clear();for(let o of n)this._traceRing.push(o);return r}static diff(e,n){let r=new Set(Object.keys(e.nodes)),o=new Set(Object.keys(n.nodes)),s=[...o].filter(b=>!r.has(b)).sort(),i=[...r].filter(b=>!o.has(b)).sort(),a=[],d=[];for(let b of r){if(!o.has(b))continue;let v=e.nodes[b],k=n.nodes[b],w=v.v,T=k.v;w!=null&&T!=null&&w.id===T.id&&w.version!==T.version&&d.push({path:b,id:w.id,from:w.version,to:T.version});let x=w!=null&&T!=null&&w.id===T.id&&w.version===T.version;for(let S of["type","status","sentinel"]){let N=v[S],_=k[S];N!==_&&a.push({path:b,field:S,from:N,to:_})}if(!x)for(let S of["value","meta"]){let N=v[S],_=k[S];Sa(N,_)||a.push({path:b,field:S,from:N,to:_})}}let u=b=>`${b.from} ${b.to}`,l=new Set(e.edges.map(u)),c=new Set(n.edges.map(u)),p=n.edges.filter(b=>!l.has(u(b))),f=e.edges.filter(b=>!c.has(u(b))),m=new Set(e.subgraphs),h=new Set(n.subgraphs),g=[...h].filter(b=>!m.has(b)).sort(),y=[...m].filter(b=>!h.has(b)).sort();return{nodesAdded:s,nodesRemoved:i,nodesChanged:a,versionChanges:d,edgesAdded:p,edgesRemoved:f,subgraphsAdded:g,subgraphsRemoved:y}}};function Qo(t,e){let n=se.diff(t,e),r={};for(let o of n.nodesAdded){let s=e.nodes[o];s!=null&&(r[o]=s)}return{...n,nodesAddedFull:r}}function ar(t,e,n,r={}){let o={paths:[],depths:new Map,truncated:!1};if(!e)return r.withDetail?o:[];if(!r.both&&n!=="upstream"&&n!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let s=r.maxDepth;if(s!=null&&(!Number.isInteger(s)||s<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(s===0)return r.withDetail?o:[];let i=new Map,a=new Map,d=new Map,u=new Map,l=new Set;for(let[v,k]of Object.entries(t.nodes)){if(!v)continue;l.add(v);let w=k.deps??[];i.set(v,w);for(let T of w)T&&(l.add(T),a.has(T)||a.set(T,new Set),a.get(T).add(v))}for(let v of t.edges){if(v==null||typeof v!="object")continue;let k=typeof v.from=="string"?v.from:"",w=typeof v.to=="string"?v.to:"";!k||!w||(l.add(k),l.add(w),u.has(k)||u.set(k,new Set),u.get(k).add(w),d.has(w)||d.set(w,new Set),d.get(w).add(k))}if(!l.has(e))return r.withDetail?o:[];let c=r.both===!0,p=v=>{if(c){let x=i.get(v)??[],S=d.get(v),N=a.get(v),_=u.get(v),R=[...x];return S&&R.push(...S),N&&R.push(...N),_&&R.push(..._),R}if(n==="upstream"){let x=i.get(v)??[],S=d.get(v);return S?[...x,...S]:x}let k=a.get(v),w=u.get(v),T=k?[...k]:[];return w&&T.push(...w),T},f=new Set([e]),m=new Map,h=[{path:e,depth:0}],g=0,y=!1;for(;g<h.length;){let v=h[g++];if(s!=null&&v.depth>=s){p(v.path).length>0&&(y=!0);continue}for(let k of p(v.path))!k||f.has(k)||(f.add(k),m.set(k,v.depth+1),h.push({path:k,depth:v.depth+1}))}let b=[...m.keys()].sort((v,k)=>v<k?-1:v>k?1:0);return r.withDetail?{paths:b,depths:m,truncated:y}:b}function ja(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.path!==o.path||r.type!==o.type||r.status!==o.status||r.hop!==o.hop||r.dep_index!==o.dep_index||r.annotation!==o.annotation||r.value!==o.value||r.lastMutation!==o.lastMutation)return!1;let s=r.v,i=o.v;if(s!==i&&(s==null||i==null||s.id!==i.id||s.version!==i.version))return!1}return!0}function Xo(t,e){return $e("messaging",t,e)}var ur=class extends se{_log;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=Ge([],{name:"events",maxSize:n.retainedLimit}),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=E([this.events],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:Xo("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(q(this.latest)),this.hasLatest=E([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:Xo("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(q(this.hasLatest)),this.addDisposer(()=>{this.events.down([[G]])}),this.addDisposer(()=>this._log.disposeAllViews())}publish(e){this._log.append(e)}retained(){return this.events.cache}};function dr(t,e){return new ur(t,e)}ke();ne();Ne();U();function Ba(t,e){if(typeof e=="string")return{node:t.resolve(e),path:e};let n=Zo(t,e);if(!n)throw new Error("orchestration dep node must already be registered in the graph so explicit edges can be recorded; pass a string path or register the node first");return{node:e,path:n}}function Zo(t,e){let n=t.describe(),r=`::${me}::`;for(let o of Object.keys(n.nodes).sort())if(!o.includes(r))try{if(t.resolve(o)===e)return o}catch{}}function Va(t,e,n,r){t.add(n,{name:e})}function Ka(t,e){return $e("orchestration",t,e)}function es(t,e,n,r){let o=r?.maxPending??1/0;if(o<1&&o!==1/0)throw new RangeError("gate: maxPending must be >= 1");let s=r?.startOpen??!1;typeof n!="string"&&!Zo(t,n)&&t.add(n,{name:`${e}/source`});let i=Ba(t,n),a=A([],{name:"pending",equals:()=>!1}),d=A(s,{name:"isOpen"}),u=E([a],([T])=>T.length,{name:"count"}),l=A(null,{name:"lastRejected",equals:()=>!1}),c=[],p=!1,f=s,m=d.subscribe(T=>{for(let x of T)x[0]===C&&(f=x[1])});function h(){a.emit([...c])}function g(T){c.push(T),c.length>o&&c.shift(),h()}function y(T){let x=c.splice(0,T);return h(),x}function b(T){if(p)throw new Error(`gate: ${T}() called after gate was torn down`)}let v=ee([i.node],(T,x,S)=>{let N=S.terminalDeps[0];if(N!==void 0){p=!0,c=[],h(),x.down(N===!0?[[G]]:[[O,N]]);return}let _=T[0];if(_==null||_.length===0){x.down([[B]]);return}for(let R of _)f?x.emit(R):(g(R),x.down([[B]]))},{name:e,describeKind:"derived",meta:Ka("gate",r?.meta)}),k={node:v,pending:a,count:u,isOpen:d,lastRejected:l,approve(T=1){b("approve");let x=y(T);for(let S of x){if(p)break;v.emit(S)}},reject(T=1){b("reject"),X(()=>{let x=[...c],S=Math.min(T,x.length);for(let N=0;N<S;N++)l.emit(x[N]);y(T)})},modify(T,x=1){b("modify");let S=[...c],N=y(x);for(let _=0;_<N.length&&!p;_++)v.emit(T(N[_],_,S))},open(){b("open"),X(()=>{d.emit(!0);let T=y(c.length);for(let x of T){if(p)break;v.emit(x)}})},close(){b("close"),d.emit(!1)}};t.addDisposer(u.subscribe(()=>{})),t.addDisposer(m),Va(t,e,v,i.path?[i.path]:[]);let w=new se(`${e}_state`);return w.add(a,{name:"pending"}),w.add(d,{name:"isOpen"}),w.add(u,{name:"count"}),w.add(l,{name:"lastRejected"}),t.mount(`${e}_state`,w),t.addDisposer(l.subscribe(()=>{})),k}async function ts(t,e,n,r){let o="",s=0;for await(let i of t.stream(e,n))r.publish({...i,seq:s++,ts:pe()}),i.type==="token"&&(o+=i.delta);return o}function ns(t,e){if(e==="json")try{return JSON.parse(ut(t))}catch(n){let r=t.slice(0,160);throw new Error(`streamingPromptNode: format:"json" \u2014 failed to parse accumulated text as JSON: ${n.message}; content preview: ${r}`)}return t}function rs(t,e){return E([t.latest],([n],r)=>{let o=r.store;if(n==null)return o.acc??"";let s=n;return s.seq===0&&(o.acc=""),s.type==="token"&&(o.acc=(o.acc??"")+s.delta),o.acc??""},{name:e,meta:V("accumulated_text"),initial:""})}function Ua(t,e,n,r){let o=r?.name??"llm",s=r?.format??"text",i=dr(`${o}/stream`,{...r?.retainedLimit!=null?{retainedLimit:r.retainedLimit}:{}}),a=E(e,c=>{if(c.some(f=>f==null))return[];let p=typeof n=="string"?n:n(...c);return p?[{role:"user",content:p}]:[]},{name:`${o}::messages`,meta:V("prompt_node::messages"),initial:[]}),d=oe(a,c=>{let p=c;if(!p||p.length===0)return A(null);let f=new AbortController;async function*m(){try{let h=await ts(t,p,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt,signal:f.signal},i);yield ns(h,s)}finally{f.abort()}}return P(m())}),u=rs(i,`${o}::accumulatedText`),l=q(d);return{output:d,deltaTopic:i,accumulatedText:u,dispose:()=>{l(),i.destroy()}}}function za(t,e,n,r,o,s){let i=A(0,{name:`${e}/cancel`}),a=0,d=[...r,i],u=s?.name??e,l=s?.format??"text",c=dr(`${u}/stream`,{...s?.retainedLimit!=null?{retainedLimit:s.retainedLimit}:{}}),p=E(d,T=>{let x=T.slice(0,-1);if(x.some(N=>N==null))return[];let S=typeof o=="string"?o:o(...x);return S?[{role:"user",content:S}]:[]},{name:`${u}::messages`,meta:V("prompt_node::messages"),initial:[]}),f=oe(p,T=>{let x=T;if(!x||x.length===0)return A(null);let S=new AbortController;async function*N(){try{let _=await ts(n,x,{model:s?.model,temperature:s?.temperature,maxTokens:s?.maxTokens,systemPrompt:s?.systemPrompt,signal:S.signal},c);yield ns(_,l)}finally{S.abort()}}return P(N())}),m=rs(c,`${u}::accumulatedText`),h=Qr(f,T=>T!=null);t.add(h,{name:`${e}/raw`});let g=es(t,`${e}/gate`,`${e}/raw`,s?.gate),y=q(f),b=q(g.node),v=q(m);t.addDisposer(y),t.addDisposer(b),t.addDisposer(v);let k=g.reject.bind(g),w={...g,reject(T=1){X(()=>{k(T),i.emit(++a)})}};return{output:g.node,deltaTopic:c,accumulatedText:m,gate:w,dispose:()=>{y(),b(),v(),c.destroy()}}}U();J();function Ha(t,e){let n=e?.separator??`
|
|
14
14
|
|
|
15
|
-
`,r=t.map(i=>typeof i=="string"?O(i):P(i)),o=A(r,i=>i.filter(a=>a!=null&&a!=="").join(n),{name:e?.name??"systemPrompt",describeKind:"derived",meta:z("system_prompt"),initial:""}),s=Z(o);return Object.assign(o,{dispose:s})}q();var Qa=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens&&t.estimated===e.estimated;function Xa(t,e){let n=e?.charsPerToken??4,r={chunkCount:0,charCount:0,estimatedTokens:0,estimated:!0};return A([t.latest],([o],s)=>{if(o==null)return r;let i=o;"chunkCount"in s.store||(s.store.chunkCount=0,s.store.charCount=0,s.store.usageTokens=0,s.store.sawUsage=!1);let a=s.store;i.type==="token"?(a.chunkCount+=1,a.charCount+=i.delta.length):i.type==="usage"&&(a.sawUsage=!0,a.usageTokens=Ee(i.usage)+Pe(i.usage));let l=a.sawUsage?a.usageTokens:Math.ceil(a.charCount/n);return{chunkCount:a.chunkCount,charCount:a.charCount,estimatedTokens:l,estimated:!a.sawUsage}},{name:e?.name??"cost-meter",describeKind:"derived",initial:r,meta:z("cost_meter_extractor"),equals:Qa})}q();var Za=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.label!==o.label||r.pattern!==o.pattern||r.match!==o.match||r.position!==o.position)return!1}return!0};function ec(t,e){let n=e.maxPatternLength??128;for(let o of e.patterns)if(o.pattern.source.length>n)throw new Error(`keywordFlagExtractor: pattern "${o.label}" literal exceeds maxPatternLength (${o.pattern.source.length} > ${n}); raise the option or shorten the pattern.`);let r=e.patterns.map(o=>({label:o.label,pattern:o.pattern,compiled:new RegExp(o.pattern.source,`${o.pattern.flags.replace("g","")}g`)}));return A([t],([o],s)=>{if(o==null)return[];let i=o;"flags"in s.store||(s.store.flags=[],s.store.scannedTo=0);let a=s.store.flags,l=s.store.scannedTo,c=Math.max(0,l-n),d=i.slice(c),u=!1;for(let{pattern:p,label:f,compiled:m}of r){m.lastIndex=0;for(let h of d.matchAll(m)){let g=c+(h.index??0);g+h[0].length<=l||(a.push({label:f,pattern:p,match:h[0],position:g}),u=!0)}}return s.store.scannedTo=i.length,u?[...a]:a.slice()},{name:e.name??"keyword-flag-extractor",describeKind:"derived",initial:[],meta:z("keyword_flag_extractor"),equals:Za})}q();function tc(t,e,n){return A([t],([r])=>r==null?null:e(r),{name:n?.name??"extractor",describeKind:"derived",initial:null,meta:z("stream_extractor"),...n?.equals?{equals:n.equals}:{}})}q();var nc=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.startIndex!==o.startIndex||r.name!==o.name||r.raw!==o.raw)return!1}return!0};function rc(t,e){return A([t],([n],r)=>{if(n==null)return[];let o=n;"calls"in r.store||(r.store.calls=[],r.store.scanFrom=0);let s=r.store.calls,i=r.store.scanFrom,a=!1;for(;i<o.length;){let l=o.indexOf("{",i);if(l===-1){r.store.scanFrom=o.length;break}let c=0,d=-1,u=!1;for(let f=l;f<o.length;f++){let m=o[f];if(u)m==="\\"&&f+1<o.length?f++:m==='"'&&(u=!1);else if(m==='"')u=!0;else if(m==="{")c++;else if(m==="}"&&(c--,c===0)){d=f;break}}if(d===-1){r.store.scanFrom=l;break}let p=o.slice(l,d+1);try{let f=JSON.parse(p);typeof f.name=="string"&&f.arguments!=null&&typeof f.arguments=="object"&&(s.push({name:f.name,arguments:f.arguments,raw:p,startIndex:l}),a=!0)}catch{}i=d+1,r.store.scanFrom=i}return a?[...s]:s.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:z("tool_call_extractor"),equals:nc})}q();function oc(t,e,n,r){let o=n*(r?.hardMultiplier??1.5),s=typeof e!="function",i=[t];return s&&i.push(e),A(i,a=>{let l=a[0]??"";if(l.length===0)return"allow";let c=s?a[1]??0:e(l);return c>=o?"block":c>=n?"review":"allow"},{name:r?.name??"content-gate",initial:"allow"})}q();function sc(t,e,n,r){let o=n??(()=>"[REDACTED]");function s(i){let a=i;for(let l of e){let c=l.global?l:new RegExp(l.source,`${l.flags}g`);a=a.replace(c,d=>o(d,l))}return a}return A([t],([i])=>s(i??""),{name:r?.name??"redactor",initial:""})}Re();le();Me();q();ne();q();var bn=class extends pe{_log;messages;latest;messageCount;constructor(e,n={}){super(e,n.graph),this._log=$e([],{name:"messages",maxSize:n.maxMessages}),this.messages=this._log.entries,this.add(this.messages,{name:"messages"}),this.latest=A([this.messages],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:z("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(Z(this.latest)),this.messageCount=A([this.messages],([r])=>r.length,{name:"messageCount",describeKind:"derived",meta:z("chat_message_count"),initial:0}),this.add(this.messageCount,{name:"messageCount"}),this.addDisposer(Z(this.messageCount))}append(e,n,r){this._log.append({role:e,content:n,...r})}appendToolResult(e,n){this._log.append({role:"tool",content:n,toolCallId:e})}clear(){this._log.clear()}allMessages(){return this.messages.cache}};function wr(t,e){return new bn(t,e)}q();ct();function kr(t){let{toolCalls:e,tools:n}=t,r=t.retryCount??1,o=t.onError??"rescue",s=(i,a)=>{if(i===a)return!0;if(i.length!==a.length)return!1;for(let l=0;l<i.length;l++){let c=i[l],d=a[l];if(c?.id!==d?.id||c?.content!==d?.content)return!1}return!0};return ue(e,i=>{if(i==null||i.length===0)throw new Error("toolExecution: received an empty tool-call batch as DATA \u2014 callers must upstream-filter empty batches (emit RESOLVED) so switchMap is only dispatched for non-empty batches.");let a=i.map(l=>ic(l,n,r,o));return A(a,l=>l,{name:"toolExecution::batch",equals:s})})}function ic(t,e,n,r){let o=Bn(()=>e.executeReactive(t.name,t.arguments),{count:n}),s=A([o],([i])=>({id:t.id,content:typeof i=="string"?i:JSON.stringify(i)}));return r==="propagate"?s:co(s,i=>({id:t.id,content:JSON.stringify({error:String(i)})}))}le();q();ne();var Tn=class extends pe{definitions;schemas;_bundle;constructor(e,n={}){super(e,n.graph),this._bundle=it({name:"definitions"}),this.definitions=this._bundle.entries,this.add(this.definitions,{name:"definitions"}),this.schemas=A([this.definitions],([r])=>[...(r??new Map).values()],{name:"schemas",describeKind:"derived",meta:z("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(Z(this.schemas))}register(e){this._bundle.set(e.name,e)}unregister(e){this._bundle.delete(e)}executeReactive(e,n){let r=this._bundle.get(e);if(!r)throw new Error(`toolRegistry: unknown tool "${e}"`);return se(o=>{let s=new AbortController,i;try{let l=r.handler(n,{signal:s.signal});i=ac(l,s.signal)}catch(l){return o.down([[C,l]]),()=>{s.abort()}}let a=i.subscribe(l=>{o.down(l)});return()=>{s.abort(),a()}},{name:`executeReactive::${e}`,meta:z("tool_execute_reactive")})}getDefinition(e){return this._bundle.entries.cache?.get(e)}};function xr(t,e){return new Tn(t,e)}function ac(t,e){return pr(t)?t:t!=null&&typeof t.then=="function"?Wt(t,{signal:e}):t!=null&&typeof t=="object"&&Symbol.asyncIterator in t?Kn(t,{signal:e}):Wt(Promise.resolve(t),{signal:e})}var vn=class extends pe{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;_terminalResult;_disposeRunWiring;_running=!1;_currentAbortController=null;constructor(e,n){if(super(e,n.graph),this.chat=wr(`${e}-chat`,{maxMessages:n.maxMessages}),this.mount("chat",this.chat),this.tools=xr(`${e}-tools`),this.mount("tools",this.tools),n.tools)for(let K of n.tools)this.tools.register(K);this.status=O("idle",{name:"status",describeKind:"state",meta:z("agent_status")}),this.add(this.status,{name:"status"}),this.turn=O(0,{name:"turn",describeKind:"state",meta:z("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.aborted=O(!1,{name:"aborted",describeKind:"state",meta:z("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let r=0,o=this.turn.subscribe(K=>{for(let G of K)G[0]===I&&(r=G[1])}),s=!1,i=this.aborted.subscribe(K=>{for(let G of K)G[0]===I&&(s=G[1])}),a=this.chat.messages.cache??[],l=this.chat.messages.subscribe(K=>{for(let G of K)G[0]===I&&(a=G[1])}),c=this.tools.schemas.cache??[],d=this.tools.schemas.subscribe(K=>{for(let G of K)G[0]===I&&(c=G[1])}),u=n.adapter,p=n.systemPrompt,f=n.model,m=n.temperature,h=n.maxTokens,g=n.maxTurns??10,y=n.stopWhen,b=this.chat,T=this.tools,k=this.status,w=this.turn,v=this.aborted,x=ie([k],(K,G,D)=>{if(_t(K,D.prevData,0,"idle")!=="thinking"||s||r>=g){G.down([[H]]);return}if(a.length===0){G.down([[H]]);return}G.emit({messages:a,tools:c})},{name:"promptInput",describeKind:"derived",meta:z("agent_prompt_input")}),S=ue(x,K=>{let G=new AbortController;return this._currentAbortController=G,s&&G.abort(new Error("agentLoop: aborted")),P(u.invoke(K.messages,{tools:K.tools.length>0?K.tools:void 0,systemPrompt:p,model:f,temperature:m,maxTokens:h,signal:G.signal}),{signal:G.signal})},{equals:()=>!1}),N=O(null,{name:"lastResponse",describeKind:"state",meta:z("agent_last_response")});this.lastResponse=N;let _=ie([N,k],(K,G,D)=>{let F=_t(K,D.prevData,0,null);if(_t(K,D.prevData,1,"idle")!=="acting"){G.down([[H]]);return}let te=F?.toolCalls;if(te==null||te.length===0){G.down([[H]]);return}G.emit(te)},{name:"toolCallsRaw",describeKind:"derived",meta:z("agent_tool_calls_raw")}),R=n.interceptToolCalls?n.interceptToolCalls(_):_;this.toolCalls=R;let E=kr({toolCalls:R,tools:T,retryCount:1});this.toolResults=E;let M=ye([S],([K])=>{if(s)return;let G=K,D=r+1,F=G.toolCalls!=null&&G.toolCalls.length>0,X=G.finishReason==="end_turn"&&(!G.toolCalls||G.toolCalls.length===0),te=y?.(G)===!0,ae=D>=g,U=te||X||!F||ae?"done":"acting";re(()=>{N.emit(G),k.emit(U),w.emit(D),b.append("assistant",G.content,{toolCalls:G.toolCalls})})}),L=ye([E],([K])=>{if(s)return;let G=K;if(G.length===0)return;let D=r>=g?"done":"thinking";re(()=>{k.emit(D);for(let F of G)b.appendToolResult(F.id,F.content)})}),j=k.cache??"idle",W=k.subscribe(K=>{for(let G of K)G[0]===I&&(j=G[1])}),B=ye([v],([K])=>{K===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),j!=="done"&&k.emit("done"))}),ee=Z(M),Y=Z(L),oe=Z(B);this._terminalResult=ie([k,N],(K,G,D)=>{let F=_t(K,D.prevData,0,"idle"),X=_t(K,D.prevData,1,null);if(F==="done"){if(X!=null){G.emit(X);return}let te=new Error("agentLoop: aborted");te.name="AbortError",G.down([[C,te]]);return}if(F==="error"){G.down([[C,new Error("agentLoop: errored")]]);return}G.down([[H]])},{name:"terminalResult",describeKind:"derived",meta:z("agent_terminal_result")}),this.add(x,{name:"promptInput"}),this.add(S,{name:"llmResponse"}),this.add(this.lastResponse,{name:"lastResponse"}),this.toolCalls===_?this.add(this.toolCalls,{name:"toolCalls"}):(this.add(_,{name:"toolCallsRaw"}),this.add(this.toolCalls,{name:"toolCalls"})),this.add(E,{name:"toolResults"}),this.add(this._terminalResult,{name:"terminalResult"}),this.addDisposer(o),this.addDisposer(i),this.addDisposer(W),this.addDisposer(l),this.addDisposer(d),this.addDisposer(ee),this.addDisposer(Y),this.addDisposer(oe),this._disposeRunWiring=()=>{}}async run(e,n){if(this._running)throw new RangeError(`agentLoop "${this.name}": run() called while a previous run() is still pending \u2014 await the previous run before starting another, or call abort() first`);this._running=!0;let r;try{re(()=>{this.turn.emit(0),this.aborted.emit(!1),this.status.emit("idle"),this.lastResponse.emit(null)}),e!=null&&this.chat.append("user",e);let o=ro(this._terminalResult,{skipCurrent:!0});if(n!=null)if(n.aborted)this.aborted.emit(!0);else{let s=()=>this.aborted.emit(!0);n.addEventListener("abort",s,{once:!0}),r=()=>n.removeEventListener("abort",s)}return n?.aborted!==!0&&this.status.emit("thinking"),await o}finally{r?.(),this._running=!1,this._currentAbortController=null}}abort(){this.aborted.emit(!0)}destroy(){try{this._disposeRunWiring()}catch{}super.destroy()}};function _t(t,e,n,r){let o=t[n];if(o!=null&&o.length>0)return o[o.length-1];let s=e[n];return s!==void 0?s:r}function cc(t,e){return new vn(t,e)}q();ne();function lc(t,e,n){let r=P(t),o=n?.condition!=null?P(n.condition):null,s=O(null,{name:n?.name?`${n.name}::null`:"handoff::null"});if(o==null)return ue(r,a=>{if(a==null)return s;let l=O(a);return e(l)});let i=A([r,o],([a,l])=>({v:a,open:l===!0}),{name:n?.name?`${n.name}::router`:"handoff::router",describeKind:"derived"});return ue(i,({v:a,open:l})=>{if(a==null)return s;if(!l)return O(a);let c=O(a);return e(c)})}q();ne();function dc(t,e,n){let r=P(t),o=e.map(i=>P(i)),s=[r,...o];return A(s,i=>{let a=i[0]??[],l=i.slice(1);return a.filter(c=>{for(let d of l)if(d!=null&&!d(c))return!1;return!0})},{name:n?.name??"tool-selector",describeKind:"derived",meta:z("tool_selector"),equals:(i,a)=>{let l=i,c=a;if(l.length!==c.length)return!1;for(let d=0;d<l.length;d++)if(l[d]!==c[d])return!1;return!0}})}function ds(t){let e=t.thresholds??{};return n=>{let r=t.scoreFn(n);for(let o of Object.keys(e)){let s=e[o];if(s===void 0)continue;let i=r[o];if((Number.isFinite(i)?i:Number.NEGATIVE_INFINITY)<s)return!1}return!0}}function uc(t){let e={persistence:t.persistenceThreshold??.3,personalValue:t.personalValueThreshold??.3},n=ds({scoreFn:t.scoreFn,thresholds:e});return t.requireStructured?r=>{if(!n(r))return!1;let o=t.scoreFn(r).structure;return Number.isFinite(o)&&o>0}:n}Re();he();q();Re();le();q();ne();function pc(t){return typeof t=="object"&&t!==null&&"cache"in t&&typeof t.subscribe=="function"}function us(t){t.subscribe(()=>{})}function Mt(t){return t instanceof Map?t:new Map}function ps(t,e){if(!Array.isArray(e.upsert))throw new TypeError("distill extraction requires upsert: Array<{ key, value }>");re(()=>{for(let{key:n,value:r}of e.upsert)t.set(n,r);for(let n of e.remove??[])t.delete(n)})}function fs(t,e,n){let r=P(t),o=it(n.mapOptions??{}),s=n.budget??2e3,a=n.context!==void 0&&n.context!==null?P(n.context):O(null),l=Mt(o.entries.cache);o.entries.subscribe(f=>{for(let m of f)m[0]===I&&(l=Mt(m[1]))});let c=ue(r,f=>e(f,l));if(kt(c,f=>{ps(o,f)}),n.evict){let f=new Map,m=A([o.entries],([h])=>{let g=[],y=Mt(h);for(let b of f.keys())y.has(b)||(f.get(b)(),f.delete(b));for(let[b,T]of y){let k=n.evict(b,T);if(pc(k)){if(!f.has(b)){let w=kt(k,v=>{v===!0&&o.has(b)&&o.delete(b)});f.set(b,w)}continue}if(typeof k=="boolean"){k&&g.push(b);continue}throw new TypeError("distill evict() must return boolean or Node<boolean>")}return g});kt(m,h=>{for(let g of h)o.delete(g)})}let d=n.consolidateTrigger!==void 0&&n.consolidateTrigger!==null;if(n.consolidate&&d){let f=P(n.consolidateTrigger),m=ue(f,()=>n.consolidate(l));kt(m,h=>{ps(o,h)})}let u=A([o.entries,a],([f,m])=>{let h=[...Mt(f).entries()].map(([b,T])=>({key:b,value:T,score:n.score(T,m),cost:n.cost(T)}));h.sort((b,T)=>T.score-b.score);let g=[],y=s;for(let b of h)b.cost<=y&&(g.push({key:b.key,value:b.value,score:b.score}),y-=b.cost);return g}),p=A([o.entries],([f])=>Mt(f).size);return us(u),us(p),{store:o,compact:u,size:p}}ne();he();q();function kn(t,e,n,r=0){if(!Number.isFinite(t))return r;if(!Number.isFinite(e)||e<=0||!Number.isFinite(n)||n<=0)return Math.max(r,t);let o=t*Math.exp(-n*e);return Math.max(r,o)}function fc(t){if(t!==void 0&&t<1)throw new RangeError("maxSize must be >= 1")}function Ze(t){return new Map(t)}function Oe(t){return t.cache??new Map}function wn(t){return t.cache??[]}function mc(t,e){let n=Math.max(t.length,e.length),r=0,o=0,s=0;for(let i=0;i<n;i+=1){let a=t[i]??0,l=e[i]??0;r+=a*l,o+=a*a,s+=l*l}return o===0||s===0?0:r/Math.sqrt(o*s)}function xn(t={}){let e=t.maxSize,n=t.policy??"fifo";fc(e);let r=O(new Map,{name:t.name,describeKind:"state"});function o(i){if(e!==void 0)for(;i.size>e;){let a;for(let l of i.values()){if(!a){a=l;continue}let c=n==="lru"?l.lastAccessNs:l.createdAtNs,d=n==="lru"?a.lastAccessNs:a.createdAtNs;c<d&&(a=l)}if(!a)break;i.delete(a.id)}}function s(i){r.emit(i)}return{entries:r,upsert(i,a){let l=V(),c=Oe(r),d=c.get(i),u=Ze(c);u.set(i,{id:i,value:a,createdAtNs:d?.createdAtNs??l,lastAccessNs:l}),o(u),s(u)},remove(i){let a=Ze(Oe(r));a.delete(i)&&s(a)},clear(){Oe(r).size!==0&&s(new Map)},get(i){let a=Oe(r),l=a.get(i);if(l){if(n==="lru"){let c=V(),d=Ze(a);d.set(i,{...l,lastAccessNs:c}),s(d)}return l.value}},has(i){return Oe(r).has(i)}}}function Rn(t={}){let e=t.backend??"flat",n=t.dimension,r;if(e==="hnsw"&&(r=t.hnswFactory?.(),!r))throw new Error('vectorIndex backend "hnsw" requires an optional dependency adapter; install your HNSW package and provide `hnswFactory`.');let o=O(new Map,{describeKind:"state",name:"vector-index"});function s(a){if(n!==void 0&&a.length!==n)throw new RangeError(`vector dimension mismatch: expected ${n}, got ${a.length}`)}function i(a){o.emit(a)}return{backend:e,entries:o,upsert(a,l,c){s(l);let d=Ze(Oe(o));d.set(a,{id:a,vector:[...l],meta:c}),e==="hnsw"&&r.upsert(a,l,c),i(d)},remove(a){let l=Ze(Oe(o));l.delete(a)&&(e==="hnsw"&&r.remove(a),i(l))},clear(){Oe(o).size!==0&&(e==="hnsw"&&r.clear(),i(new Map))},search(a,l=5){return s(a),l<=0?[]:e==="hnsw"?r.search(a,l):[...Oe(o).values()].map(d=>({id:d.id,score:mc(a,d.vector),meta:d.meta})).sort((d,u)=>u.score-d.score).slice(0,l)}}}function Sn(t){let e=new pe(t),n=O(new Map,{name:"entities",describeKind:"state"}),r=O([],{name:"edges",describeKind:"state"}),o=A([r],([l])=>{let c=l??[],d=new Map;for(let u of c){let p=d.get(u.from)??[];d.set(u.from,Object.freeze([...p,u]))}return d},{name:"adjacency",describeKind:"derived",initial:new Map});o.subscribe(()=>{}),e.add(n,{name:"entities"}),e.add(r,{name:"edges"}),e.add(o,{name:"adjacency"});function s(l){n.emit(l)}function i(l){r.emit(l)}return Object.assign(e,{upsertEntity(l,c){let d=Ze(Oe(n));d.set(l,c),s(d)},removeEntity(l){let c=Ze(Oe(n)),d=c.delete(l),u=wn(r),p=u.filter(f=>f.from!==l&&f.to!==l);!d&&p.length===u.length||(s(c),i(p))},link(l,c,d,u=1){let p=`${l}\0${c}\0${d}`,f=wn(r),m=new Set(f.map(g=>`${g.from}\0${g.to}\0${g.relation}`)),h=[...f];if(m.has(p))for(let g=0;g<h.length;g+=1){let y=h[g];if(y.from===l&&y.to===c&&y.relation===d){h[g]={...y,weight:u};break}}else h.push({from:l,to:c,relation:d,weight:u});i(h)},unlink(l,c,d){let u=wn(r),p=u.filter(f=>d===void 0?!(f.from===l&&f.to===c):!(f.from===l&&f.to===c&&f.relation===d));p.length!==u.length&&i(p)},related(l,c){return wn(r).filter(d=>(d.from===l||d.to===l)&&(c===void 0||d.relation===c))}})}q();function ms(t,e,n,r){let o=n.name??r;return s=>{let i=O(s);return fr(n.adapter,[i],a=>e(a),{name:o,format:"json",systemPrompt:t,model:n.model,temperature:n.temperature??0,maxTokens:n.maxTokens})}}function Rr(t,e){let n=e.maxExistingKeys??100,r=ms(t,o=>JSON.stringify({input:o.raw,existingKeys:o.existingKeys}),e,"llmExtractor");return(o,s)=>{let i=n===Number.POSITIVE_INFINITY?[...s.keys()]:[...s.keys()].slice(0,n);return r({raw:o,existingKeys:i})}}function Sr(t,e){let n=ms(t,r=>JSON.stringify({memories:r}),e,"llmConsolidator");return r=>{let o=[...r.entries()].map(([s,i])=>({key:s,value:i}));return n(o)}}var Et=Math.LN2/604800;function Ot(t){return t instanceof Map?t:new Map}function gc(t,e,n){let r=new pe(t,n.graph),o=[],s;if(n.extractFn)s=n.extractFn;else if(n.adapter&&n.extractPrompt)s=Rr(n.extractPrompt,{adapter:n.adapter});else throw new Error("agentMemory: provide either extractFn or adapter + extractPrompt");let i=(T,k)=>T==null?{upsert:[]}:s(T,k),a=e;if(n.admissionFilter){let T=P(e),k=n.admissionFilter;a=A([T],([w])=>{if(k(w))return w},{name:"admissionFilter",describeKind:"derived"})}let l;n.consolidateFn?l=n.consolidateFn:n.adapter&&n.consolidatePrompt&&(l=Sr(n.consolidatePrompt,{adapter:n.adapter}));let c=n.consolidateTrigger;if(!c&&l&&n.reflection?.enabled!==!1){let T=n.reflection?.interval??3e5;c=to(T,{period:T})}let d={score:n.score,cost:n.cost,budget:n.budget??2e3,context:n.context,consolidate:l,consolidateTrigger:c},u=fs(a,i,d);r.add(u.store.entries,{name:"store"}),r.add(u.compact,{name:"compact"}),r.add(u.size,{name:"size"});let p=null;n.vectorDimensions&&n.vectorDimensions>0&&n.embedFn&&(p=Rn({dimension:n.vectorDimensions}),r.add(p.entries,{name:"vectorIndex"}));let f=null;n.enableKnowledgeGraph&&(f=Sn(`${t}-kg`),r.mount("kg",f));let m=null;if(n.tiers){let T=n.tiers,k=T.decayRate??Et,w=T.maxActive??1e3,v=T.archiveThreshold??.1,x=T.permanentFilter??(()=>!1),S=xn({name:"permanent"});r.add(S.entries,{name:"permanent"});let N=new Set,_=B=>N.has(B)?"permanent":Ot(u.store.entries.cache).has(B)?"active":"archived",R=(B,ee)=>{N.add(B),S.upsert(B,ee)},E=new Map,M=u.store.entries,L=n.context?P(n.context):O(null),j=ye([M,L],([B,ee])=>{let Y=Ot(B),oe=V(),K=[],G=[];for(let[F,X]of Y){if(E.has(F)||E.set(F,oe),x(F,X)){G.push({key:F,value:X});continue}let te=n.score(X,ee),ae=E.get(F)??oe,U=Number(oe-ae)/1e9;kn(te,U,k)<v&&K.push(F)}for(let F of E.keys())Y.has(F)||E.delete(F);for(let{key:F,value:X}of G)N.has(F)||R(F,X);let D=Y.size-N.size;if(D>w){let F=[...Y.entries()].filter(([te])=>!N.has(te)).map(([te,ae])=>({key:te,score:n.score(ae,ee)})).sort((te,ae)=>te.score-ae.score),X=D-w;for(let te=0;te<X&&te<F.length;te++){let ae=F[te].key;K.includes(ae)||K.push(ae)}}K.length>0&&re(()=>{for(let F of K)u.store.delete(F)})});o.push(j.subscribe(()=>{}));let W=null;T.archiveTier&&(W=r.attachStorage([T.archiveTier],T.archiveStorageOptions??{})),m={permanent:S,activeEntries:M,archiveHandle:W,tierOf:_,markPermanent:R}}if(p||f){let T=n.embedFn,k=n.entityFn,w=u.store.entries,v=ye([w],([x])=>{let S=Ot(x);for(let[N,_]of S){if(p&&T){let R=T(_);R&&p.upsert(N,R,_)}if(f&&k){let R=k(N,_);if(R){for(let E of R.entities??[])f.upsertEntity(E.id,E.value);for(let E of R.relations??[])f.link(E.from,E.to,E.relation,E.weight)}}}});o.push(v.subscribe(()=>{}))}let h=null,g=null,y=null,b=null;if(p||f){let T=n.retrieval?.topK??20,k=n.retrieval?.graphDepth??1,w=n.budget??2e3,v=n.cost,x=n.score,S=n.contextOf,N=n.contextWeight??0,_=n.context?P(n.context):O(null),R=(B,ee)=>{if(!B||!ee)return 0;let Y=Math.min(B.length,ee.length),oe=0;for(;oe<Y&&B[oe]===ee[oe];)oe++;return oe},E=(B,ee,Y)=>{let oe=new Map,K=[];if(p&&Y.vector){K=p.search(Y.vector,T);for(let U of K){let Q=B.get(U.id);Q&&oe.set(U.id,{value:Q,sources:new Set(["vector"])})}}let G=[];if(f){let U=[...Y.entityIds??[],...oe.keys()],Q=new Set,Le=U;for(let et=0;et<k;et++){let Ve=[];for(let mt of Le){if(Q.has(mt))continue;Q.add(mt);let At=f.related(mt);for(let Rs of At){let tt=Rs.to;if(!Q.has(tt)){Ve.push(tt);let _r=B.get(tt);if(_r){let Mr=oe.get(tt);Mr?Mr.sources.add("graph"):oe.set(tt,{value:_r,sources:new Set(["graph"])}),G.push(tt)}}}}Le=Ve}}for(let[U,Q]of B)oe.has(U)||oe.set(U,{value:Q,sources:new Set(["store"])});let D=Y.context?.length??0,F=[];for(let[U,{value:Q,sources:Le}]of oe){let et=S?S(Q):void 0,Ve=x(Q,ee);if(N>0&&D>0){let At=R(Y.context,et);At>0&&(Ve=Ve*(1+N*At/D))}let mt=et?{key:U,value:Q,score:Ve,sources:[...Le],context:et}:{key:U,value:Q,score:Ve,sources:[...Le]};F.push(mt)}F.sort((U,Q)=>Q.score-U.score);let X=[],te=0;for(let U of F){let Q=v(U.value);if(te+Q>w&&X.length>0)break;X.push(U),te+=Q}return{packed:X,trace:{vectorCandidates:K,graphExpanded:G,ranked:F,packed:X}}},M=(B,ee)=>{if(B===ee)return!0;if(B.length!==ee.length)return!1;for(let Y=0;Y<B.length;Y++)if(B[Y]!==ee[Y])return!1;return!0},L=O([],{name:"retrieval",describeKind:"state",meta:z("retrieval_pipeline"),equals:M});r.add(L,{name:"retrieval"}),h=L;let j=O(null,{name:"retrievalTrace",describeKind:"state",meta:z("retrieval_trace")});r.add(j,{name:"retrievalTrace"}),g=j,y=B=>{let ee=Ot(u.store.entries.cache),{packed:Y,trace:oe}=E(ee,_.cache,B);return re(()=>{L.emit(Y),j.emit(oe)}),Y},b=B=>{let ee=P(B),Y=A([u.store.entries,_,ee],([K,G,D])=>{if(D==null)return{packed:[],trace:null};let F=Ot(K),{packed:X,trace:te}=E(F,G,D);return{packed:X,trace:te}},{name:"retrievalReactive::result",describeKind:"derived",meta:z("retrieval_reactive_result"),initial:{packed:[],trace:null}}),oe=ye([Y],([K])=>{let G=K;re(()=>{L.emit(G.packed),G.trace&&j.emit(G.trace)})});return o.push(oe.subscribe(()=>{})),A([Y],([K])=>K.packed,{name:"retrievalReactive",describeKind:"derived",meta:z("retrieval_reactive"),initial:[],equals:M})}}return r.addDisposer(()=>{for(let T of o)T();o.length=0}),Object.assign(r,{distillBundle:u,compact:u.compact,size:u.size,vectors:p,kg:f,memoryTiers:m,retrieval:h,retrievalTrace:g,retrieve:y,retrieveReactive:b})}Re();he();q();ne();function ft(t){return t instanceof Map?t:new Map}function hc(t,e,n){let r=Rn({dimension:n.dimension});t.add(r.entries,{name:"vectorIndex"});let s=ye([e.store.entries],([i])=>{let a=ft(i);for(let[l,c]of a){let d=n.embedFn(c);d&&r.upsert(l,d,c)}}).subscribe(()=>{});return t.addDisposer(s),{vectors:r,dispose:()=>s()}}function yc(t,e,n,r){let o=Sn(`${n}-kg`);t.mount(n,o);let i=ye([e.store.entries],([a])=>{let l=ft(a);for(let[c,d]of l){let u=r.entityFn(c,d);if(u){for(let p of u.entities??[])o.upsertEntity(p.id,p.value);for(let p of u.relations??[])o.link(p.from,p.to,p.relation,p.weight)}}}).subscribe(()=>{});return t.addDisposer(i),{kg:o,dispose:()=>i()}}function bc(t,e,n){let r=n.decayRate??Et,o=n.maxActive??1e3,s=n.archiveThreshold??.1,i=n.permanentFilter??(()=>!1),a=xn({name:"permanent"});t.add(a.entries,{name:"permanent"});let l=new Set,c=b=>l.has(b)?"permanent":ft(e.store.entries.cache).has(b)?"active":"archived",d=(b,T)=>{l.add(b),a.upsert(b,T)},u=new Map,p=e.store.entries,f=n.context?P(n.context):O(null),h=ye([p,f],([b,T])=>{let k=ft(b),w=V(),v=[],x=[];for(let[N,_]of k){if(u.has(N)||u.set(N,w),i(N,_)){x.push({key:N,value:_});continue}let R=n.score(_,T),E=u.get(N)??w,M=Number(w-E)/1e9;kn(R,M,r)<s&&v.push(N)}for(let N of u.keys())k.has(N)||u.delete(N);for(let{key:N,value:_}of x)l.has(N)||d(N,_);let S=k.size-l.size;if(S>o){let N=[...k.entries()].filter(([R])=>!l.has(R)).map(([R,E])=>({key:R,score:n.score(E,T)})).sort((R,E)=>R.score-E.score),_=S-o;for(let R=0;R<_&&R<N.length;R++){let E=N[R].key;v.includes(E)||v.push(E)}}v.length>0&&re(()=>{for(let N of v)e.store.delete(N)})}).subscribe(()=>{}),g=null;n.archiveTier&&(g=t.attachStorage([n.archiveTier],n.archiveStorageOptions??{}));let y=()=>{h(),g?.dispose()};return t.addDisposer(y),{tiers:{permanent:a,activeEntries:p,archiveHandle:g,tierOf:c,markPermanent:d},dispose:y}}function Tc(t,e){if(!t||!e)return 0;let n=Math.min(t.length,e.length),r=0;for(;r<n&&t[r]===e[r];)r++;return r}function vc(t,e,n,r,o){let s=o.topK??20,i=o.graphDepth??1,a=o.budget??2e3,l=o.contextWeight??0,c=o.context?P(o.context):O(null),d=(g,y,b)=>{let T=new Map,k=[];if(n&&b.vector){k=n.search(b.vector,s);for(let _ of k){let R=g.get(_.id);R&&T.set(_.id,{value:R,sources:new Set(["vector"])})}}let w=[];if(r){let _=[...b.entityIds??[],...T.keys()],R=new Set,E=_;for(let M=0;M<i;M++){let L=[];for(let j of E)if(!R.has(j)){R.add(j);for(let W of r.related(j)){let B=W.to;if(!R.has(B)){L.push(B);let ee=g.get(B);if(ee){let Y=T.get(B);Y?Y.sources.add("graph"):T.set(B,{value:ee,sources:new Set(["graph"])}),w.push(B)}}}}E=L}}for(let[_,R]of g)T.has(_)||T.set(_,{value:R,sources:new Set(["store"])});let v=b.context?.length??0,x=[];for(let[_,{value:R,sources:E}]of T){let M=o.contextOf?o.contextOf(R):void 0,L=o.score(R,y);if(l>0&&v>0){let W=Tc(b.context,M);W>0&&(L=L*(1+l*W/v))}let j=M?{key:_,value:R,score:L,sources:[...E],context:M}:{key:_,value:R,score:L,sources:[...E]};x.push(j)}x.sort((_,R)=>R.score-_.score);let S=[],N=0;for(let _ of x){let R=o.cost(_.value);if(N+R>a&&S.length>0)break;S.push(_),N+=R}return{packed:S,trace:{vectorCandidates:k,graphExpanded:w,ranked:x,packed:S}}},u=(g,y)=>{if(g===y)return!0;if(g.length!==y.length)return!1;for(let b=0;b<g.length;b++)if(g[b]!==y[b])return!1;return!0},p=O([],{name:"retrieval",describeKind:"state",meta:z("retrieval_pipeline"),equals:u});t.add(p,{name:"retrieval"});let f=O(null,{name:"retrievalTrace",describeKind:"state",meta:z("retrieval_trace")});return t.add(f,{name:"retrievalTrace"}),{retrieval:p,retrievalTrace:f,retrieve:g=>{let y=ft(e.store.entries.cache),{packed:b,trace:T}=d(y,c.cache,g);return re(()=>{p.emit(b),f.emit(T)}),b},retrieveReactive:g=>{let y=P(g),b=A([e.store.entries,c,y],([w,v,x])=>{if(x==null)return{packed:[],trace:null};let S=ft(w),{packed:N,trace:_}=d(S,v,x);return{packed:N,trace:_}},{name:"retrievalReactive::result",describeKind:"derived",meta:z("retrieval_reactive_result"),initial:{packed:[],trace:null}}),k=ye([b],([w])=>{let v=w;re(()=>{p.emit(v.packed),v.trace&&f.emit(v.trace)})}).subscribe(()=>{});return t.addDisposer(k),A([b],([w])=>w.packed,{name:"retrievalReactive",describeKind:"derived",meta:z("retrieval_reactive"),initial:[],equals:u})}}}function wc(t,e,n){let r=t.describe({actor:e,detail:"full"}),o=n?.groupByTags??!0,s=n?.separator??`
|
|
16
|
-
`,i=[],a=n?.sinceVersion;for(let[
|
|
15
|
+
`,r=t.map(i=>typeof i=="string"?A(i):P(i)),o=E(r,i=>i.filter(a=>a!=null&&a!=="").join(n),{name:e?.name??"systemPrompt",describeKind:"derived",meta:V("system_prompt"),initial:""}),s=q(o);return Object.assign(o,{dispose:s})}U();var Wa=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens&&t.estimated===e.estimated;function qa(t,e){let n=e?.charsPerToken??4,r={chunkCount:0,charCount:0,estimatedTokens:0,estimated:!0};return E([t.latest],([o],s)=>{if(o==null)return r;let i=o;"chunkCount"in s.store||(s.store.chunkCount=0,s.store.charCount=0,s.store.usageTokens=0,s.store.sawUsage=!1);let a=s.store;i.type==="token"?(a.chunkCount+=1,a.charCount+=i.delta.length):i.type==="usage"&&(a.sawUsage=!0,a.usageTokens=Me(i.usage)+De(i.usage));let d=a.sawUsage?a.usageTokens:Math.ceil(a.charCount/n);return{chunkCount:a.chunkCount,charCount:a.charCount,estimatedTokens:d,estimated:!a.sawUsage}},{name:e?.name??"cost-meter",describeKind:"derived",initial:r,meta:V("cost_meter_extractor"),equals:Wa})}U();var Ja=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.label!==o.label||r.pattern!==o.pattern||r.match!==o.match||r.position!==o.position)return!1}return!0};function Ya(t,e){let n=e.maxPatternLength??128;for(let o of e.patterns)if(o.pattern.source.length>n)throw new Error(`keywordFlagExtractor: pattern "${o.label}" literal exceeds maxPatternLength (${o.pattern.source.length} > ${n}); raise the option or shorten the pattern.`);let r=e.patterns.map(o=>({label:o.label,pattern:o.pattern,compiled:new RegExp(o.pattern.source,`${o.pattern.flags.replace("g","")}g`)}));return E([t],([o],s)=>{if(o==null)return[];let i=o;"flags"in s.store||(s.store.flags=[],s.store.scannedTo=0);let a=s.store.flags,d=s.store.scannedTo,u=Math.max(0,d-n),l=i.slice(u),c=!1;for(let{pattern:p,label:f,compiled:m}of r){m.lastIndex=0;for(let h of l.matchAll(m)){let g=u+(h.index??0);g+h[0].length<=d||(a.push({label:f,pattern:p,match:h[0],position:g}),c=!0)}}return s.store.scannedTo=i.length,c?[...a]:a.slice()},{name:e.name??"keyword-flag-extractor",describeKind:"derived",initial:[],meta:V("keyword_flag_extractor"),equals:Ja})}U();function Qa(t,e,n){return E([t],([r])=>r==null?null:e(r),{name:n?.name??"extractor",describeKind:"derived",initial:null,meta:V("stream_extractor"),...n?.equals?{equals:n.equals}:{}})}U();var Xa=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.startIndex!==o.startIndex||r.name!==o.name||r.raw!==o.raw)return!1}return!0};function Za(t,e){return E([t],([n],r)=>{if(n==null)return[];let o=n;"calls"in r.store||(r.store.calls=[],r.store.scanFrom=0);let s=r.store.calls,i=r.store.scanFrom,a=!1;for(;i<o.length;){let d=o.indexOf("{",i);if(d===-1){r.store.scanFrom=o.length;break}let u=0,l=-1,c=!1;for(let f=d;f<o.length;f++){let m=o[f];if(c)m==="\\"&&f+1<o.length?f++:m==='"'&&(c=!1);else if(m==='"')c=!0;else if(m==="{")u++;else if(m==="}"&&(u--,u===0)){l=f;break}}if(l===-1){r.store.scanFrom=d;break}let p=o.slice(d,l+1);try{let f=JSON.parse(p);typeof f.name=="string"&&f.arguments!=null&&typeof f.arguments=="object"&&(s.push({name:f.name,arguments:f.arguments,raw:p,startIndex:d}),a=!0)}catch{}i=l+1,r.store.scanFrom=i}return a?[...s]:s.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:V("tool_call_extractor"),equals:Xa})}U();function eu(t,e,n,r){let o=n*(r?.hardMultiplier??1.5),s=typeof e!="function",i=[t];return s&&i.push(e),E(i,a=>{let d=a[0]??"";if(d.length===0)return"allow";let u=s?a[1]??0:e(d);return u>=o?"block":u>=n?"review":"allow"},{name:r?.name??"content-gate",initial:"allow"})}U();function tu(t,e,n,r){let o=n??(()=>"[REDACTED]");function s(i){let a=i;for(let d of e){let u=d.global?d:new RegExp(d.source,`${d.flags}g`);a=a.replace(u,l=>o(l,d))}return a}return E([t],([i])=>s(i??""),{name:r?.name??"redactor",initial:""})}ke();ne();Ne();U();J();U();var ln=class extends se{_log;messages;latest;messageCount;constructor(e,n={}){super(e,n.graph),this._log=Ge([],{name:"messages",maxSize:n.maxMessages}),this.messages=this._log.entries,this.add(this.messages,{name:"messages"}),this.latest=E([this.messages],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:V("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(q(this.latest)),this.messageCount=E([this.messages],([r])=>r.length,{name:"messageCount",describeKind:"derived",meta:V("chat_message_count"),initial:0}),this.add(this.messageCount,{name:"messageCount"}),this.addDisposer(q(this.messageCount))}append(e,n,r){this._log.append({role:e,content:n,...r})}appendToolResult(e,n){this._log.append({role:"tool",content:n,toolCallId:e})}clear(){this._log.clear()}allMessages(){return this.messages.cache}};function lr(t,e){return new ln(t,e)}U();ot();function cr(t){let{toolCalls:e,tools:n}=t,r=t.retryCount??1,o=t.onError??"rescue",s=(i,a)=>{if(i===a)return!0;if(i.length!==a.length)return!1;for(let d=0;d<i.length;d++){let u=i[d],l=a[d];if(u?.id!==l?.id||u?.content!==l?.content)return!1}return!0};return oe(e,i=>{if(i==null||i.length===0)throw new Error("toolExecution: received an empty tool-call batch as DATA \u2014 callers must upstream-filter empty batches (emit RESOLVED) so switchMap is only dispatched for non-empty batches.");let a=i.map(d=>nu(d,n,r,o));return E(a,d=>d,{name:"toolExecution::batch",equals:s})})}function nu(t,e,n,r){let o=On(()=>e.executeReactive(t.name,t.arguments),{count:n}),s=E([o],([i])=>({id:t.id,content:typeof i=="string"?i:JSON.stringify(i)}));return r==="propagate"?s:eo(s,i=>({id:t.id,content:JSON.stringify({error:String(i)})}))}ne();U();J();var cn=class extends se{definitions;schemas;_bundle;constructor(e,n={}){super(e,n.graph),this._bundle=nt({name:"definitions"}),this.definitions=this._bundle.entries,this.add(this.definitions,{name:"definitions"}),this.schemas=E([this.definitions],([r])=>[...(r??new Map).values()],{name:"schemas",describeKind:"derived",meta:V("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(q(this.schemas))}register(e){this._bundle.set(e.name,e)}unregister(e){this._bundle.delete(e)}executeReactive(e,n){let r=this._bundle.get(e);if(!r)throw new Error(`toolRegistry: unknown tool "${e}"`);return Z(o=>{let s=new AbortController,i;try{let d=r.handler(n,{signal:s.signal});i=ru(d,s.signal)}catch(d){return o.down([[O,d]]),()=>{s.abort()}}let a=i.subscribe(d=>{o.down(d)});return()=>{s.abort(),a()}},{name:`executeReactive::${e}`,meta:V("tool_execute_reactive")})}getDefinition(e){return this._bundle.entries.cache?.get(e)}};function pr(t,e){return new cn(t,e)}function ru(t,e){return tr(t)?t:t!=null&&typeof t.then=="function"?Ft(t,{signal:e}):t!=null&&typeof t=="object"&&Symbol.asyncIterator in t?Cn(t,{signal:e}):Ft(Promise.resolve(t),{signal:e})}var pn=class extends se{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;_terminalResult;_disposeRunWiring;_running=!1;_currentAbortController=null;constructor(e,n){if(super(e,n.graph),this.chat=lr(`${e}-chat`,{maxMessages:n.maxMessages}),this.mount("chat",this.chat),this.tools=pr(`${e}-tools`),this.mount("tools",this.tools),n.tools)for(let H of n.tools)this.tools.register(H);this.status=A("idle",{name:"status",describeKind:"state",meta:V("agent_status")}),this.add(this.status,{name:"status"}),this.turn=A(0,{name:"turn",describeKind:"state",meta:V("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.aborted=A(!1,{name:"aborted",describeKind:"state",meta:V("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let r=0,o=this.turn.subscribe(H=>{for(let $ of H)$[0]===C&&(r=$[1])}),s=!1,i=this.aborted.subscribe(H=>{for(let $ of H)$[0]===C&&(s=$[1])}),a=this.chat.messages.cache??[],d=this.chat.messages.subscribe(H=>{for(let $ of H)$[0]===C&&(a=$[1])}),u=this.tools.schemas.cache??[],l=this.tools.schemas.subscribe(H=>{for(let $ of H)$[0]===C&&(u=$[1])}),c=n.adapter,p=n.systemPrompt,f=n.model,m=n.temperature,h=n.maxTokens,g=n.maxTurns??10,y=n.stopWhen,b=this.chat,v=this.tools,k=this.status,w=this.turn,T=this.aborted,x=ee([k],(H,$,D)=>{if(kt(H,D.prevData,0,"idle")!=="thinking"||s||r>=g){$.down([[B]]);return}if(a.length===0){$.down([[B]]);return}$.emit({messages:a,tools:u})},{name:"promptInput",describeKind:"derived",meta:V("agent_prompt_input")}),S=oe(x,H=>{let $=new AbortController;return this._currentAbortController=$,s&&$.abort(new Error("agentLoop: aborted")),P(c.invoke(H.messages,{tools:H.tools.length>0?H.tools:void 0,systemPrompt:p,model:f,temperature:m,maxTokens:h,signal:$.signal}),{signal:$.signal})},{equals:()=>!1}),N=A(null,{name:"lastResponse",describeKind:"state",meta:V("agent_last_response")});this.lastResponse=N;let _=ee([N,k],(H,$,D)=>{let W=kt(H,D.prevData,0,null);if(kt(H,D.prevData,1,"idle")!=="acting"){$.down([[B]]);return}let ge=W?.toolCalls;if(ge==null||ge.length===0){$.down([[B]]);return}$.emit(ge)},{name:"toolCallsRaw",describeKind:"derived",meta:V("agent_tool_calls_raw")}),R=n.interceptToolCalls?n.interceptToolCalls(_):_;this.toolCalls=R;let I=cr({toolCalls:R,tools:v,retryCount:1});this.toolResults=I;let M=Te([S],([H])=>{if(s)return;let $=H,D=r+1,W=$.toolCalls!=null&&$.toolCalls.length>0,de=$.finishReason==="end_turn"&&(!$.toolCalls||$.toolCalls.length===0),ge=y?.($)===!0,he=D>=g,Y=ge||de||!W||he?"done":"acting";X(()=>{N.emit($),k.emit(Y),w.emit(D),b.append("assistant",$.content,{toolCalls:$.toolCalls})})}),L=Te([I],([H])=>{if(s)return;let $=H;if($.length===0)return;let D=r>=g?"done":"thinking";X(()=>{k.emit(D);for(let W of $)b.appendToolResult(W.id,W.content)})}),j=k.cache??"idle",K=k.subscribe(H=>{for(let $ of H)$[0]===C&&(j=$[1])}),Q=Te([T],([H])=>{H===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),j!=="done"&&k.emit("done"))}),we=q(M),_e=q(L),Qe=q(Q);this._terminalResult=ee([k,N],(H,$,D)=>{let W=kt(H,D.prevData,0,"idle"),de=kt(H,D.prevData,1,null);if(W==="done"){if(de!=null){$.emit(de);return}let ge=new Error("agentLoop: aborted");ge.name="AbortError",$.down([[O,ge]]);return}if(W==="error"){$.down([[O,new Error("agentLoop: errored")]]);return}$.down([[B]])},{name:"terminalResult",describeKind:"derived",meta:V("agent_terminal_result")}),this.add(x,{name:"promptInput"}),this.add(S,{name:"llmResponse"}),this.add(this.lastResponse,{name:"lastResponse"}),this.toolCalls===_?this.add(this.toolCalls,{name:"toolCalls"}):(this.add(_,{name:"toolCallsRaw"}),this.add(this.toolCalls,{name:"toolCalls"})),this.add(I,{name:"toolResults"}),this.add(this._terminalResult,{name:"terminalResult"}),this.addDisposer(o),this.addDisposer(i),this.addDisposer(K),this.addDisposer(d),this.addDisposer(l),this.addDisposer(we),this.addDisposer(_e),this.addDisposer(Qe),this._disposeRunWiring=()=>{}}async run(e,n){if(this._running)throw new RangeError(`agentLoop "${this.name}": run() called while a previous run() is still pending \u2014 await the previous run before starting another, or call abort() first`);this._running=!0;let r;try{X(()=>{this.turn.emit(0),this.aborted.emit(!1),this.status.emit("idle"),this.lastResponse.emit(null)}),e!=null&&this.chat.append("user",e);let o=Jr(this._terminalResult,{skipCurrent:!0});if(n!=null)if(n.aborted)this.aborted.emit(!0);else{let s=()=>this.aborted.emit(!0);n.addEventListener("abort",s,{once:!0}),r=()=>n.removeEventListener("abort",s)}return n?.aborted!==!0&&this.status.emit("thinking"),await o}finally{r?.(),this._running=!1,this._currentAbortController=null}}abort(){this.aborted.emit(!0)}destroy(){try{this._disposeRunWiring()}catch{}super.destroy()}};function kt(t,e,n,r){let o=t[n];if(o!=null&&o.length>0)return o[o.length-1];let s=e[n];return s!==void 0?s:r}function ou(t,e){return new pn(t,e)}U();J();function su(t,e,n){let r=P(t),o=n?.condition!=null?P(n.condition):null,s=A(null,{name:n?.name?`${n.name}::null`:"handoff::null"});if(o==null)return oe(r,a=>{if(a==null)return s;let d=A(a);return e(d)});let i=E([r,o],([a,d])=>({v:a,open:d===!0}),{name:n?.name?`${n.name}::router`:"handoff::router",describeKind:"derived"});return oe(i,({v:a,open:d})=>{if(a==null)return s;if(!d)return A(a);let u=A(a);return e(u)})}U();J();function iu(t,e,n){let r=P(t),o=e.map(i=>P(i)),s=[r,...o];return E(s,i=>{let a=i[0]??[],d=i.slice(1);return a.filter(u=>{for(let l of d)if(l!=null&&!l(u))return!1;return!0})},{name:n?.name??"tool-selector",describeKind:"derived",meta:V("tool_selector"),equals:(i,a)=>{let d=i,u=a;if(d.length!==u.length)return!1;for(let l=0;l<d.length;l++)if(d[l]!==u[l])return!1;return!0}})}function os(t){let e=t.thresholds??{};return n=>{let r=t.scoreFn(n);for(let o of Object.keys(e)){let s=e[o];if(s===void 0)continue;let i=r[o];if((Number.isFinite(i)?i:Number.NEGATIVE_INFINITY)<s)return!1}return!0}}function au(t){let e={persistence:t.persistenceThreshold??.3,personalValue:t.personalValueThreshold??.3},n=os({scoreFn:t.scoreFn,thresholds:e});return t.requireStructured?r=>{if(!n(r))return!1;let o=t.scoreFn(r).structure;return Number.isFinite(o)&&o>0}:n}U();ke();ne();U();J();function uu(t){return typeof t=="object"&&t!==null&&"cache"in t&&typeof t.subscribe=="function"}function ss(t){t.subscribe(()=>{})}function xt(t){return t instanceof Map?t:new Map}function is(t,e){if(!Array.isArray(e.upsert))throw new TypeError("distill extraction requires upsert: Array<{ key, value }>");X(()=>{for(let{key:n,value:r}of e.upsert)t.set(n,r);for(let n of e.remove??[])t.delete(n)})}function as(t,e,n){let r=P(t),o=nt(n.mapOptions??{}),s=n.budget??2e3,a=n.context!==void 0&&n.context!==null?P(n.context):A(null),d=xt(o.entries.cache);o.entries.subscribe(f=>{for(let m of f)m[0]===C&&(d=xt(m[1]))});let u=oe(r,f=>e(f,d));if(yt(u,f=>{is(o,f)}),n.evict){let f=new Map,m=E([o.entries],([h])=>{let g=[],y=xt(h);for(let b of f.keys())y.has(b)||(f.get(b)(),f.delete(b));for(let[b,v]of y){let k=n.evict(b,v);if(uu(k)){if(!f.has(b)){let w=yt(k,T=>{T===!0&&o.has(b)&&o.delete(b)});f.set(b,w)}continue}if(typeof k=="boolean"){k&&g.push(b);continue}throw new TypeError("distill evict() must return boolean or Node<boolean>")}return g});yt(m,h=>{for(let g of h)o.delete(g)})}let l=n.consolidateTrigger!==void 0&&n.consolidateTrigger!==null;if(n.consolidate&&l){let f=P(n.consolidateTrigger),m=oe(f,()=>n.consolidate(d));yt(m,h=>{is(o,h)})}let c=E([o.entries,a],([f,m])=>{let h=[...xt(f).entries()].map(([b,v])=>({key:b,value:v,score:n.score(v,m),cost:n.cost(v)}));h.sort((b,v)=>v.score-b.score);let g=[],y=s;for(let b of h)b.cost<=y&&(g.push({key:b.key,value:b.value,score:b.score}),y-=b.cost);return g}),p=E([o.entries],([f])=>xt(f).size);return ss(c),ss(p),{store:o,compact:c,size:p}}J();U();function us(t,e,n,r){let o=n.name??r;return s=>{let i=A(s);return nr(n.adapter,[i],a=>e(a),{name:o,format:"json",systemPrompt:t,model:n.model,temperature:n.temperature??0,maxTokens:n.maxTokens})}}function fr(t,e){let n=e.maxExistingKeys??100,r=us(t,o=>JSON.stringify({input:o.raw,existingKeys:o.existingKeys}),e,"llmExtractor");return(o,s)=>{let i=n===Number.POSITIVE_INFINITY?[...s.keys()]:[...s.keys()].slice(0,n);return r({raw:o,existingKeys:i})}}function mr(t,e){let n=us(t,r=>JSON.stringify({memories:r}),e,"llmConsolidator");return r=>{let o=[...r.entries()].map(([s,i])=>({key:s,value:i}));return n(o)}}ke();ce();U();J();ce();U();function ds(t,e,n,r=0){if(!Number.isFinite(t))return r;if(!Number.isFinite(e)||e<=0||!Number.isFinite(n)||n<=0)return Math.max(r,t);let o=t*Math.exp(-n*e);return Math.max(r,o)}function du(t){if(t!==void 0&&t<1)throw new RangeError("maxSize must be >= 1")}function Ye(t){return new Map(t)}function Ee(t){return t.cache??new Map}function fn(t){return t.cache??[]}function lu(t,e){let n=Math.max(t.length,e.length),r=0,o=0,s=0;for(let i=0;i<n;i+=1){let a=t[i]??0,d=e[i]??0;r+=a*d,o+=a*a,s+=d*d}return o===0||s===0?0:r/Math.sqrt(o*s)}function ls(t={}){let e=t.maxSize,n=t.policy??"fifo";du(e);let r=A(new Map,{name:t.name,describeKind:"state"});function o(i){if(e!==void 0)for(;i.size>e;){let a;for(let d of i.values()){if(!a){a=d;continue}let u=n==="lru"?d.lastAccessNs:d.createdAtNs,l=n==="lru"?a.lastAccessNs:a.createdAtNs;u<l&&(a=d)}if(!a)break;i.delete(a.id)}}function s(i){r.emit(i)}return{entries:r,upsert(i,a){let d=F(),u=Ee(r),l=u.get(i),c=Ye(u);c.set(i,{id:i,value:a,createdAtNs:l?.createdAtNs??d,lastAccessNs:d}),o(c),s(c)},remove(i){let a=Ye(Ee(r));a.delete(i)&&s(a)},clear(){Ee(r).size!==0&&s(new Map)},get(i){let a=Ee(r),d=a.get(i);if(d){if(n==="lru"){let u=F(),l=Ye(a);l.set(i,{...d,lastAccessNs:u}),s(l)}return d.value}},has(i){return Ee(r).has(i)}}}function cs(t={}){let e=t.backend??"flat",n=t.dimension,r;if(e==="hnsw"&&(r=t.hnswFactory?.(),!r))throw new Error('vectorIndex backend "hnsw" requires an optional dependency adapter; install your HNSW package and provide `hnswFactory`.');let o=A(new Map,{describeKind:"state",name:"vector-index"});function s(a){if(n!==void 0&&a.length!==n)throw new RangeError(`vector dimension mismatch: expected ${n}, got ${a.length}`)}function i(a){o.emit(a)}return{backend:e,entries:o,upsert(a,d,u){s(d);let l=Ye(Ee(o));l.set(a,{id:a,vector:[...d],meta:u}),e==="hnsw"&&r.upsert(a,d,u),i(l)},remove(a){let d=Ye(Ee(o));d.delete(a)&&(e==="hnsw"&&r.remove(a),i(d))},clear(){Ee(o).size!==0&&(e==="hnsw"&&r.clear(),i(new Map))},search(a,d=5){return s(a),d<=0?[]:e==="hnsw"?r.search(a,d):[...Ee(o).values()].map(l=>({id:l.id,score:lu(a,l.vector),meta:l.meta})).sort((l,c)=>c.score-l.score).slice(0,d)}}}function ps(t){let e=new se(t),n=A(new Map,{name:"entities",describeKind:"state"}),r=A([],{name:"edges",describeKind:"state"}),o=E([r],([d])=>{let u=d??[],l=new Map;for(let c of u){let p=l.get(c.from)??[];l.set(c.from,Object.freeze([...p,c]))}return l},{name:"adjacency",describeKind:"derived",initial:new Map});o.subscribe(()=>{}),e.add(n,{name:"entities"}),e.add(r,{name:"edges"}),e.add(o,{name:"adjacency"});function s(d){n.emit(d)}function i(d){r.emit(d)}return Object.assign(e,{upsertEntity(d,u){let l=Ye(Ee(n));l.set(d,u),s(l)},removeEntity(d){let u=Ye(Ee(n)),l=u.delete(d),c=fn(r),p=c.filter(f=>f.from!==d&&f.to!==d);!l&&p.length===c.length||(s(u),i(p))},link(d,u,l,c=1){let p=`${d}\0${u}\0${l}`,f=fn(r),m=new Set(f.map(g=>`${g.from}\0${g.to}\0${g.relation}`)),h=[...f];if(m.has(p))for(let g=0;g<h.length;g+=1){let y=h[g];if(y.from===d&&y.to===u&&y.relation===l){h[g]={...y,weight:c};break}}else h.push({from:d,to:u,relation:l,weight:c});i(h)},unlink(d,u,l){let c=fn(r),p=c.filter(f=>l===void 0?!(f.from===d&&f.to===u):!(f.from===d&&f.to===u&&f.relation===l));p.length!==c.length&&i(p)},related(d,u){return fn(r).filter(l=>(l.from===d||l.to===d)&&(u===void 0||l.relation===u))}})}var gr=Math.LN2/604800;function dt(t){return t instanceof Map?t:new Map}function hr(t,e,n){let r=cs({dimension:n.dimension});t.add(r.entries,{name:"vectorIndex"});let s=Te([e.store.entries],([i])=>{let a=dt(i);for(let[d,u]of a){let l=n.embedFn(u);l&&r.upsert(d,l,u)}}).subscribe(()=>{});return t.addDisposer(s),{vectors:r,dispose:()=>s()}}function yr(t,e,n,r){let o=r.mountPath??n,s=ps(`${n}-kg`);if(t.mount(o,s),!r.entityFn)return{kg:s,dispose:()=>{}};let i=r.entityFn,d=Te([e.store.entries],([u])=>{let l=dt(u);for(let[c,p]of l){let f=i(c,p);if(f){for(let m of f.entities??[])s.upsertEntity(m.id,m.value);for(let m of f.relations??[])s.link(m.from,m.to,m.relation,m.weight)}}}).subscribe(()=>{});return t.addDisposer(d),{kg:s,dispose:()=>d()}}function br(t,e,n){let r=n.decayRate??gr,o=n.maxActive??1e3,s=n.archiveThreshold??.1,i=n.permanentFilter??(()=>!1),a=ls({name:"permanent"});t.add(a.entries,{name:"permanent"});let d=new Set,u=b=>d.has(b)?"permanent":dt(e.store.entries.cache).has(b)?"active":"archived",l=(b,v)=>{d.add(b),a.upsert(b,v)},c=new Map,p=e.store.entries,f=n.context?P(n.context):A(null),h=Te([p,f],([b,v])=>{let k=dt(b),w=F(),T=[],x=[];for(let[N,_]of k){if(c.has(N)||c.set(N,w),i(N,_)){x.push({key:N,value:_});continue}let R=n.score(_,v),I=c.get(N)??w,M=Number(w-I)/1e9;ds(R,M,r)<s&&T.push(N)}for(let N of c.keys())k.has(N)||c.delete(N);for(let{key:N,value:_}of x)d.has(N)||l(N,_);let S=k.size-d.size;if(S>o){let N=[...k.entries()].filter(([R])=>!d.has(R)).map(([R,I])=>({key:R,score:n.score(I,v)})).sort((R,I)=>R.score-I.score),_=S-o;for(let R=0;R<_&&R<N.length;R++){let I=N[R].key;T.includes(I)||T.push(I)}}T.length>0&&X(()=>{for(let N of T)e.store.delete(N)})}).subscribe(()=>{}),g=null;n.archiveTier&&(g=t.attachStorage([n.archiveTier],n.archiveStorageOptions??{}));let y=()=>{h(),g?.dispose()};return t.addDisposer(y),{tiers:{permanent:a,activeEntries:p,archiveHandle:g,tierOf:u,markPermanent:l},dispose:y}}function cu(t,e){if(!t||!e)return 0;let n=Math.min(t.length,e.length),r=0;for(;r<n&&t[r]===e[r];)r++;return r}function Tr(t,e,n,r,o){let s=o.topK??20,i=o.graphDepth??1,a=o.budget??2e3,d=o.contextWeight??0,u=o.context?P(o.context):A(null),l=(g,y,b)=>{let v=new Map,k=[];if(n&&b.vector){k=n.search(b.vector,s);for(let _ of k){let R=g.get(_.id);R&&v.set(_.id,{value:R,sources:new Set(["vector"])})}}let w=[];if(r){let _=[...b.entityIds??[],...v.keys()],R=new Set,I=_;for(let M=0;M<i;M++){let L=[];for(let j of I)if(!R.has(j)){R.add(j);for(let K of r.related(j)){let Q=K.to;if(!R.has(Q)){L.push(Q);let we=g.get(Q);if(we){let _e=v.get(Q);_e?_e.sources.add("graph"):v.set(Q,{value:we,sources:new Set(["graph"])}),w.push(Q)}}}}I=L}}for(let[_,R]of g)v.has(_)||v.set(_,{value:R,sources:new Set(["store"])});let T=b.context?.length??0,x=[];for(let[_,{value:R,sources:I}]of v){let M=o.contextOf?o.contextOf(R):void 0,L=o.score(R,y);if(d>0&&T>0){let K=cu(b.context,M);K>0&&(L=L*(1+d*K/T))}let j=M?{key:_,value:R,score:L,sources:[...I],context:M}:{key:_,value:R,score:L,sources:[...I]};x.push(j)}x.sort((_,R)=>R.score-_.score);let S=[],N=0;for(let _ of x){let R=o.cost(_.value);if(N+R>a&&S.length>0)break;S.push(_),N+=R}return{packed:S,trace:{vectorCandidates:k,graphExpanded:w,ranked:x,packed:S}}},c=(g,y)=>{if(g===y)return!0;if(g.length!==y.length)return!1;for(let b=0;b<g.length;b++)if(g[b]!==y[b])return!1;return!0},p=A([],{name:"retrieval",describeKind:"state",meta:V("retrieval_pipeline"),equals:c});t.add(p,{name:"retrieval"});let f=A(null,{name:"retrievalTrace",describeKind:"state",meta:V("retrieval_trace")});return t.add(f,{name:"retrievalTrace"}),{retrieval:p,retrievalTrace:f,retrieve:g=>{let y=dt(e.store.entries.cache),{packed:b,trace:v}=l(y,u.cache,g);return X(()=>{p.emit(b),f.emit(v)}),b},retrieveReactive:g=>{let y=P(g),b=E([e.store.entries,u,y],([w,T,x])=>{if(x==null)return{packed:[],trace:null};let S=dt(w),{packed:N,trace:_}=l(S,T,x);return{packed:N,trace:_}},{name:"retrievalReactive::result",describeKind:"derived",meta:V("retrieval_reactive_result"),initial:{packed:[],trace:null}}),k=Te([b],([w])=>{let T=w;X(()=>{p.emit(T.packed),T.trace&&f.emit(T.trace)})}).subscribe(()=>{});return t.addDisposer(k),E([b],([w])=>w.packed,{name:"retrievalReactive",describeKind:"derived",meta:V("retrieval_reactive"),initial:[],equals:c})}}}function pu(t,e,n){let r=new se(t,n.graph),o;if(n.extractFn)o=n.extractFn;else if(n.adapter&&n.extractPrompt)o=fr(n.extractPrompt,{adapter:n.adapter});else throw new Error("agentMemory: provide either extractFn or adapter + extractPrompt");let s=(b,v)=>b==null?{upsert:[]}:o(b,v),i=e;if(n.admissionFilter){let b=P(e),v=n.admissionFilter;i=E([b],([k])=>{if(v(k))return k},{name:"admissionFilter",describeKind:"derived"})}let a;n.consolidateFn?a=n.consolidateFn:n.adapter&&n.consolidatePrompt&&(a=mr(n.consolidatePrompt,{adapter:n.adapter}));let d=n.consolidateTrigger;if(!d&&a&&n.reflection?.enabled!==!1){let b=n.reflection?.interval??3e5;d=Wr(b,{period:b})}let u={score:n.score,cost:n.cost,budget:n.budget??2e3,context:n.context,consolidate:a,consolidateTrigger:d},l=as(i,s,u);r.add(l.store.entries,{name:"store"}),r.add(l.compact,{name:"compact"}),r.add(l.size,{name:"size"});let c=null;n.vectorDimensions&&n.vectorDimensions>0&&n.embedFn&&(c=hr(r,l,{dimension:n.vectorDimensions,embedFn:n.embedFn}).vectors);let p=null;n.enableKnowledgeGraph&&(p=yr(r,l,t,{mountPath:"kg",entityFn:n.entityFn}).kg);let f=null;n.tiers&&(f=br(r,l,{...n.tiers,score:n.score,context:n.context}).tiers);let m=null,h=null,g=null,y=null;if(c||p){let b=Tr(r,l,c,p,{score:n.score,cost:n.cost,budget:n.budget,topK:n.retrieval?.topK,graphDepth:n.retrieval?.graphDepth,contextOf:n.contextOf,contextWeight:n.contextWeight,context:n.context});m=b.retrieval,h=b.retrievalTrace,g=b.retrieve,y=b.retrieveReactive}return Object.assign(r,{distillBundle:l,compact:l.compact,size:l.size,vectors:c,kg:p,memoryTiers:f,retrieval:m,retrievalTrace:h,retrieve:g,retrieveReactive:y})}function fu(t,e,n){let r=t.describe({actor:e,detail:"full"}),o=n?.groupByTags??!0,s=n?.separator??`
|
|
16
|
+
`,i=[],a=n?.sinceVersion;for(let[d,u]of Object.entries(r.nodes)){let l=u.meta??{},c=l.description,p=l.format;if(!c&&!p)continue;if(a!=null&&u.v!=null){let y=a.get(d);if(y!=null&&y.id===u.v.id&&u.v.version<=y.version)continue}let f=c??d,m=u.value,h=l.unit,g;p==="currency"&&typeof m=="number"?g=`$${m.toFixed(2)}`:p==="percentage"&&typeof m=="number"?g=`${(m*100).toFixed(1)}%`:m==null?g="(no value)":g=String(m),h&&p!=="currency"&&p!=="percentage"&&(g=`${g} ${h}`),i.push({path:d,description:f,formatted:g})}if(i.length===0)return"";if(o){let d=new Map,u=[];for(let c of i){let f=r.nodes[c.path].meta?.tags;if(f&&f.length>0){let m=f[0],h=d.get(m);h||(h=[],d.set(m,h)),h.push(c)}else u.push(c)}if(d.size===0)return i.map(c=>`- ${c.description}: ${c.formatted}`).join(s);let l=[];for(let[c,p]of[...d.entries()].sort((f,m)=>f[0].localeCompare(m[0])))l.push(`[${c}]${s}${p.map(f=>`- ${f.description}: ${f.formatted}`).join(s)}`);return u.length>0&&l.push(u.map(c=>`- ${c.description}: ${c.formatted}`).join(s)),l.join(s+s)}return i.map(d=>`- ${d.description}: ${d.formatted}`).join(s)}ne();U();J();U();ke();ne();Ne();U();function fs(t,e){return $e("reduction",t,e)}function ms(t,e,n,r){let o=r?.maxIterations??10,s=`__feedback_${e}`,i=A(0,{meta:fs("feedback_counter",{maxIterations:o,feedbackFrom:e,feedbackTo:n})});t.add(i,{name:s});let a=t.resolve(e),d=t.resolve(n),u=`__feedback_effect_${e}`,l=ee([],(c,p)=>{let f=a.subscribe(m=>{for(let h of m){let g=h[0];if(g===C){let y=h[1];if(y==null)return;X(()=>{xo(i,o)&&d.emit(y)})}else if(g===G||g===O){let y=g===O&&h.length>1?[O,h[1]]:[g];i.down([y])}}});return()=>f()},{name:u,describeKind:"effect",meta:{...fs("feedback_effect",{feedbackFrom:e,feedbackTo:n}),_internal:!0}});return t.add(l,{name:u}),t.addDisposer(q(l)),t}function hs(t){return typeof t=="object"&&t!==null&&"factory"in t}function mu(t){return typeof t=="object"&&t!==null&&"factory"in t}function gu(t){return hs(t)?t.factory:t}function hu(t){return mu(t)?t.factory:t}function yu(t,e){let n=[],r=new Set(Object.keys(e.fns??{})),o=new Set(Object.keys(e.sources??{}));for(let[s,i]of Object.entries(t.nodes)){if(i.type==="template")continue;let a=i;if(a.fn&&r.size>0&&!r.has(a.fn))if(o.has(a.fn))n.push(`Node "${s}": fn "${a.fn}" is a source, not a function. Use it as a producer source instead, or use a function from: ${[...r].join(", ")}`);else{let d=vr(a.fn,r);n.push(`Node "${s}": fn "${a.fn}" not found in catalog`+(d?`. Did you mean "${d}"?`:""))}if(a.source&&o.size>0&&!o.has(a.source))if(r.has(a.source))n.push(`Node "${s}": source "${a.source}" is a function, not a source. Use it as fn instead, or use a source from: ${[...o].join(", ")}`);else{let d=vr(a.source,o);n.push(`Node "${s}": source "${a.source}" not found in catalog`+(d?`. Did you mean "${d}"?`:""))}if(a.fn&&a.config&&e.fns?.[a.fn]){let d=e.fns[a.fn];if(hs(d)&&d.configSchema){for(let[u,l]of Object.entries(d.configSchema))if(l.required!==!1&&!(u in a.config)&&n.push(`Node "${s}": config missing required field "${u}"`),u in a.config&&l.enum){let c=a.config[u];l.enum.includes(c)||n.push(`Node "${s}": config.${u} = ${JSON.stringify(c)}, expected one of: ${l.enum.join(", ")}`)}}}}if(t.templates){for(let[s,i]of Object.entries(t.templates))for(let[a,d]of Object.entries(i.nodes))if(d.fn&&r.size>0&&!r.has(d.fn)){let u=vr(d.fn,r);n.push(`Template "${s}" node "${a}": fn "${d.fn}" not found in catalog`+(u?`. Did you mean "${u}"?`:""))}}return{valid:n.length===0,errors:n,warnings:[]}}function vr(t,e){let n=null,r=1/0,o=t.toLowerCase();for(let s of e){let i=bu(o,s.toLowerCase());i<r&&i<=Math.max(3,Math.floor(t.length/2))&&(r=i,n=s)}return n}function bu(t,e){let n=t.length,r=e.length,o=Array.from({length:n+1},(s,i)=>Array.from({length:r+1},(a,d)=>i===0?d:d===0?i:0));for(let s=1;s<=n;s++)for(let i=1;i<=r;i++)o[s][i]=t[s-1]===e[i-1]?o[s-1][i-1]:1+Math.min(o[s-1][i],o[s][i-1],o[s-1][i-1]);return o[n][r]}var gs=new Set(["state","producer","derived","effect","operator","template"]),Tu=new Set(["state","producer","derived","effect","operator"]);function vu(t){let e=[],n=[];if(t==null||typeof t!="object")return{valid:!1,errors:["GraphSpec must be a non-null object"],warnings:n};let r=t;if((typeof r.name!="string"||r.name.length===0)&&e.push("Missing or empty 'name' field"),r.nodes==null||typeof r.nodes!="object"||Array.isArray(r.nodes))return e.push("Missing or invalid 'nodes' field (must be an object)"),{valid:!1,errors:e,warnings:n};let o=new Set(Object.keys(r.nodes)),s=new Map,i=new Map;if(r.templates!=null&&typeof r.templates=="object"&&!Array.isArray(r.templates)){for(let[a,d]of Object.entries(r.templates))if(d!=null&&typeof d=="object"){let u=d;i.set(a,{params:Array.isArray(u.params)?u.params:[]})}}if(r.templates!=null)if(typeof r.templates!="object"||Array.isArray(r.templates))e.push("'templates' must be an object");else for(let[a,d]of Object.entries(r.templates)){if(d==null||typeof d!="object"){e.push(`Template "${a}": must be an object`);continue}let u=d;if(Array.isArray(u.params)||e.push(`Template "${a}": missing 'params' array`),u.nodes==null||typeof u.nodes!="object"||Array.isArray(u.nodes))e.push(`Template "${a}": missing or invalid 'nodes' object`);else{let l=new Set(Array.isArray(u.params)?u.params:[]),c=new Set(Object.keys(u.nodes));for(let[p,f]of Object.entries(u.nodes)){if(f==null||typeof f!="object"){e.push(`Template "${a}" node "${p}": must be an object`);continue}let m=f;if((typeof m.type!="string"||!Tu.has(m.type))&&e.push(`Template "${a}" node "${p}": invalid type`),Array.isArray(m.deps))for(let h of m.deps)!c.has(h)&&!l.has(h)&&e.push(`Template "${a}" node "${p}": dep "${h}" is not an inner node or param`)}typeof u.output!="string"?e.push(`Template "${a}": missing 'output' string`):u.nodes[u.output]||e.push(`Template "${a}": output "${u.output}" is not a declared node`)}}for(let[a,d]of Object.entries(r.nodes)){if(d==null||typeof d!="object"){e.push(`Node "${a}": must be an object`);continue}let u=d;if(typeof u.type!="string"||!gs.has(u.type)){e.push(`Node "${a}": invalid type "${String(u.type)}" (expected: ${[...gs].join(", ")})`);continue}if(s.set(a,u.type),u.type==="template")if(typeof u.template!="string"||!i.has(u.template))e.push(`Node "${a}": template "${String(u.template)}" not found in templates`);else if(u.bind==null||typeof u.bind!="object"||Array.isArray(u.bind))e.push(`Node "${a}": template ref requires 'bind' object`);else{let l=i.get(u.template),c=u.bind;for(let p of l.params)p in c||e.push(`Node "${a}": template param "${p}" is not bound (template "${u.template}")`);for(let[,p]of Object.entries(c))typeof p=="string"&&!o.has(p)&&e.push(`Node "${a}": bind target "${p}" does not reference an existing node`)}else{if(Array.isArray(u.deps))for(let l of u.deps)l===a?e.push(`Node "${a}": self-referencing dep`):o.has(l)||e.push(`Node "${a}": dep "${l}" does not reference an existing node`);(u.type==="derived"||u.type==="effect"||u.type==="operator")&&!Array.isArray(u.deps)&&e.push(`Node "${a}": ${u.type} node should have a 'deps' array`)}}if(r.feedback!=null)if(!Array.isArray(r.feedback))e.push("'feedback' must be an array");else for(let a=0;a<r.feedback.length;a++){let d=r.feedback[a];if(d==null||typeof d!="object"){e.push(`Feedback [${a}]: must be an object`);continue}let u=d;typeof u.from!="string"||!o.has(u.from)?e.push(`Feedback [${a}]: 'from' "${String(u.from)}" does not reference an existing node`):s.get(u.from)==="effect"&&n.push(`Feedback [${a}]: 'from' "${u.from}" is an effect node \u2014 effects emit no DATA, so the feedback edge will never fire. Did you mean a derived/state node upstream?`),typeof u.from=="string"&&u.from===u.to&&e.push(`Feedback [${a}]: 'from' and 'to' must be different nodes`),typeof u.to!="string"||!o.has(u.to)?e.push(`Feedback [${a}]: 'to' "${String(u.to)}" does not reference an existing node`):typeof u.to=="string"&&s.get(u.to)!=="state"&&e.push(`Feedback [${a}]: 'to' node "${u.to}" must be a state node (got "${s.get(u.to)??"unknown"}")`)}return{valid:e.length===0,errors:e,warnings:n}}function ys(t,e){let n=vu(t);if(!n.valid)throw new Error(`compileSpec: invalid GraphSpec:
|
|
17
17
|
${n.errors.join(`
|
|
18
|
-
`)}`);let r=e?.catalog??{},o=e?.onMissing??"placeholder",s=new
|
|
18
|
+
`)}`);let r=e?.catalog??{},o=e?.onMissing??"placeholder",s=new se(t.name),i=t.templates??{},a=yu(t,r);if(!a.valid)throw new Error(`compileSpec: catalog validation errors:
|
|
19
19
|
${a.errors.join(`
|
|
20
|
-
`)}`);let
|
|
20
|
+
`)}`);let d=[],u=(g,y,b)=>{if(b){d.push({path:g,kind:"source",name:b});return}y&&d.push({path:g,kind:"fn",name:y})},l=g=>{let y=r.fns?.[g];return y?gu(y):void 0},c=g=>{let y=r.sources?.[g];return y?hu(y):void 0},p=new Map,f=[];for(let[g,y]of Object.entries(t.nodes)){if(y.type==="template")continue;let b=y;if(b.type==="state"){let v=A(b.initial,{name:g,meta:b.meta?{...b.meta}:void 0});s.add(v,{name:g}),p.set(g,v)}else if(b.type==="producer"){let v=b.source?c(b.source):void 0,k=b.fn?l(b.fn):void 0;if(v){let w=v(b.config??{});s.add(w,{name:g}),p.set(g,w)}else if(k){let w=k([],b.config??{});s.add(w,{name:g}),p.set(g,w)}else{u(g,b.fn,b.source);let w=Z(()=>{},{name:g,meta:{...b.meta,_specFn:b.fn,_specSource:b.source}});s.add(w,{name:g}),p.set(g,w)}}else f.push([g,b])}let m=!0,h=new Map(f);for(;h.size>0&&m;){m=!1;for(let[g,y]of[...h.entries()]){let b=y.deps??[];if(!b.every(T=>p.has(T)))continue;let v=b.map(T=>p.get(T)),k=y.fn?l(y.fn):void 0,w;k?w=k(v,y.config??{}):y.type==="effect"?(y.fn&&u(g,y.fn,void 0),w=Te(v,()=>{})):(y.fn&&u(g,y.fn,void 0),w=E(v,T=>T[0])),s.add(w,{name:g}),p.set(g,w),h.delete(g),m=!0}}if(h.size>0){let g=[...h.keys()].sort().join(", ");throw new Error(`compileSpec: unresolvable deps for nodes: ${g}`)}for(let[g,y]of Object.entries(t.nodes)){if(y.type!=="template")continue;let b=y,v=i[b.template],k=new se(g),w=new Map,T=[];for(let[_,R]of Object.entries(v.nodes)){let I=(R.deps??[]).map(L=>L.startsWith("$")&&b.bind[L]?b.bind[L]:L),M={...R,deps:I};if(R.type==="state"){let L=A(R.initial,{name:_,meta:R.meta?{...R.meta}:void 0});k.add(L,{name:_}),w.set(_,L)}else if(R.type==="producer"){let L=R.source?c(R.source):void 0,j=R.fn?l(R.fn):void 0;if(L){let K=L(R.config??{});k.add(K,{name:_}),w.set(_,K)}else if(j){let K=j([],R.config??{});k.add(K,{name:_}),w.set(_,K)}else{u(`${g}.${_}`,R.fn,R.source);let K=Z(()=>{},{name:_,meta:{...R.meta,_specFn:R.fn,_specSource:R.source}});k.add(K,{name:_}),w.set(_,K)}}else T.push([_,M])}let x=!0,S=new Map(T);for(;S.size>0&&x;){x=!1;for(let[_,R]of[...S.entries()]){let I=R.deps??[];if(!I.every(Q=>w.has(Q)||p.has(Q)))continue;let L=I.map(Q=>w.get(Q)??p.get(Q)),j=R.fn?l(R.fn):void 0,K;j?K=j(L,R.config??{}):R.type==="effect"?(R.fn&&u(`${g}.${_}`,R.fn,void 0),K=Te(L,()=>{})):(R.fn&&u(`${g}.${_}`,R.fn,void 0),K=E(L,Q=>Q[0])),k.add(K,{name:_}),w.set(_,K),S.delete(_),x=!0}}if(S.size>0){let _=[...S.keys()].sort().join(", ");throw new Error(`compileSpec: template "${b.template}" has unresolvable deps: ${_}`)}s.mount(g,k);let N=`${g}::${v.output}`;p.set(g,s.resolve(N));try{let _=s.resolve(N);_.meta._templateName?.emit(b.template),_.meta._templateBind?.emit(b.bind)}catch{}}for(let g of t.feedback??[])ms(s,g.from,g.to,{maxIterations:g.maxIterations});if(d.length>0){if(o==="error"){let g=d.map(y=>` - ${y.path}: missing ${y.kind} "${y.name}"`);throw new Error(`compileSpec: ${d.length} catalog entr${d.length===1?"y":"ies"} missing \u2014 pass them via opts.catalog or set opts.onMissing to "warn"/"placeholder":
|
|
21
21
|
${g.join(`
|
|
22
|
-
`)}`)}if(o==="warn"){let g=e?.onWarn??(y=>console.warn(y));for(let y of
|
|
22
|
+
`)}`)}if(o==="warn"){let g=e?.onWarn??(y=>console.warn(y));for(let y of d)g(`compileSpec: ${y.path} references missing ${y.kind} "${y.name}" \u2014 substituted placeholder`)}}return s}var bs=`You are a graph architect for GraphReFly, a reactive graph protocol.
|
|
23
23
|
|
|
24
24
|
Given a natural-language description, produce a JSON graph specification with this structure:
|
|
25
25
|
|
|
@@ -52,9 +52,9 @@ Rules:
|
|
|
52
52
|
- "operator" nodes are parameterized transformations with deps.
|
|
53
53
|
- Use "deps" inside each node to declare dependencies \u2014 no separate "edges" array.
|
|
54
54
|
- meta.description is required for every node.
|
|
55
|
-
- Return ONLY valid JSON, no markdown fences or commentary.`;async function
|
|
55
|
+
- Return ONLY valid JSON, no markdown fences or commentary.`;async function Ts(t,e,n){let o=[{role:"system",content:n?.systemPromptExtra?`${bs}
|
|
56
56
|
|
|
57
|
-
${n.systemPromptExtra}`:
|
|
57
|
+
${n.systemPromptExtra}`:bs},{role:"user",content:t}],s=e.invoke(o,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens,signal:n?.signal}),a=(await wt(s)).content.trim();a.startsWith("```")&&(a=ut(a));let d;try{d=JSON.parse(a)}catch{throw new Error(`graphFromSpec: LLM response is not valid JSON: ${a.slice(0,200)}`)}return ys(d,{catalog:n?.catalog})}function wu(t,e,n){let r=P(t);return oe(r,o=>!o||typeof o!="string"||o.trim().length===0?A(null):Z(s=>{let i=new AbortController,a=!1;return Ts(o,e,{...n,signal:i.signal}).then(d=>{if(a){d.destroy();return}s.emit(d),s.down([[G]])}).catch(d=>{a||s.down([[O,d]])}),()=>{a=!0,i.abort()}},{name:"graphFromSpec::call"}))}function ku(t){let e={},n=t.type;return n==="enum"&&Array.isArray(t.values)?(e.type="string",e.enum=t.values):n==="integer"?e.type="integer":n==="number"?e.type="number":n==="boolean"?e.type="boolean":n==="string"?e.type="string":e.type=["string","number","boolean"],Array.isArray(t.range)&&t.range.length===2&&(e.minimum=t.range[0],e.maximum=t.range[1]),typeof t.format=="string"&&(e.description=`Format: ${t.format}`),typeof t.unit=="string"&&(e.description?e.description+=` (${t.unit})`:e.description=`Unit: ${t.unit}`),e}function xu(t,e){let n=t.describe({actor:e,detail:"full"}),r=[],o=[],s=[];for(let[i,a]of Object.entries(n.nodes)){if(a.type!=="state"||i.includes("::__meta__::")||a.status==="completed"||a.status==="errored")continue;let d=a.meta??{},u=d.access;if(u==="human"||u==="system")continue;let l=d.description??`Set the value of ${i}`,c=ku(d),p={type:"object",required:["value"],properties:{value:c},additionalProperties:!1},f=i.replace(/::/g,"__");r.push({type:"function",function:{name:f,description:l,parameters:p}}),o.push({name:i,description:l,inputSchema:p});let m=t,h=e,g=a.v;s.push({name:i,description:l,parameters:p,handler(y){return m.set(i,y.value,h?{actor:h}:void 0),y.value},...g!=null?{version:{id:g.id,version:g.version}}:{}})}return{openai:r,mcp:o,definitions:s}}ne();U();J();var Ru=`You are a reactive graph optimizer for GraphReFly.
|
|
58
58
|
|
|
59
59
|
Given a graph's current structure (from describe()) and a problem statement, suggest topology and parameter changes to solve the problem.
|
|
60
60
|
|
|
@@ -75,4 +75,4 @@ Return ONLY valid JSON with this structure:
|
|
|
75
75
|
Rules:
|
|
76
76
|
- Only suggest operations that reference existing nodes (for remove/disconnect/set_value/update_meta) or new nodes you define (for add_node).
|
|
77
77
|
- Keep changes minimal \u2014 prefer the smallest set of operations that solves the problem.
|
|
78
|
-
- Return ONLY valid JSON, no markdown fences or commentary.`;async function
|
|
78
|
+
- Return ONLY valid JSON, no markdown fences or commentary.`;async function vs(t,e,n,r){let{expand:o,...s}=t.describe({actor:r?.actor,detail:"standard"}),i=[{role:"system",content:Ru},{role:"user",content:JSON.stringify({graph:s,problem:e})}],a=n.invoke(i,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens,signal:r?.signal}),u=(await wt(a)).content.trim();u.startsWith("```")&&(u=u.replace(/^```(?:json)?\s*/,"").replace(/\s*```$/,""));let l;try{l=JSON.parse(u)}catch{throw new Error(`suggestStrategy: LLM response is not valid JSON: ${u.slice(0,200)}`)}let c=l;if(typeof c.summary!="string")throw new Error("suggestStrategy: missing 'summary' in response");if(typeof c.reasoning!="string")throw new Error("suggestStrategy: missing 'reasoning' in response");if(!Array.isArray(c.operations))throw new Error("suggestStrategy: missing 'operations' array in response");return{summary:c.summary,reasoning:c.reasoning,operations:c.operations}}function Su(t,e,n,r){let o=P(e),s=Zr(o,t);return oe(s,i=>{if(i==null)return A(null);let[a,d]=i;return!d||!a||typeof a!="string"||a.trim().length===0?A(null):d.destroyed?A(null):Z(u=>{let l=new AbortController,c=!1;return vs(d,a,n,{...r,signal:l.signal}).then(p=>{c||(u.emit(p),u.down([[G]]))}).catch(p=>{c||u.down([[O,p]])}),()=>{c=!0,l.abort()}},{name:"suggestStrategy::call"})})}var ws=new Set(["state","derived","producer","operator","effect"]);function Nu(t){let e=[];if(t==null||typeof t!="object")return{valid:!1,errors:["Definition must be a non-null object"]};let n=t;if((typeof n.name!="string"||n.name.length===0)&&e.push("Missing or empty 'name' field"),n.nodes==null||typeof n.nodes!="object"||Array.isArray(n.nodes))return e.push("Missing or invalid 'nodes' field (must be an object)"),{valid:!1,errors:e};let r=new Set(Object.keys(n.nodes));for(let[o,s]of Object.entries(n.nodes)){if(s==null||typeof s!="object"){e.push(`Node "${o}": must be an object`);continue}let i=s;if((typeof i.type!="string"||!ws.has(i.type))&&e.push(`Node "${o}": invalid type "${String(i.type)}" (expected: ${[...ws].join(", ")})`),Array.isArray(i.deps))for(let a of i.deps)typeof a=="string"&&!r.has(a)&&e.push(`Node "${o}": dep "${a}" does not reference an existing node`)}if(!Array.isArray(n.edges))n.edges!==void 0&&e.push("'edges' must be an array");else{let o=new Set;for(let s=0;s<n.edges.length;s++){let i=n.edges[s];if(i==null||typeof i!="object"){e.push(`Edge [${s}]: must be an object`);continue}let a=i;(typeof a.from!="string"||!r.has(a.from))&&e.push(`Edge [${s}]: 'from' "${String(a.from)}" does not reference an existing node`),(typeof a.to!="string"||!r.has(a.to))&&e.push(`Edge [${s}]: 'to' "${String(a.to)}" does not reference an existing node`);let d=`${a.from}->${a.to}`;o.has(d)&&e.push(`Edge [${s}]: duplicate edge ${d}`),o.add(d)}}return{valid:e.length===0,errors:e}}0&&(module.exports={AgentLoopGraph,AllTiersExhaustedError,BudgetExhaustedError,ChatStreamGraph,CircuitOpenError,DEFAULT_DECAY_RATE,FallbackMissError,LLMTimeoutError,ReplayCacheMissError,ToolRegistryGraph,admissionFilter3D,admissionScored,agentLoop,agentMemory,anthropicAdapter,canonicalJson,cascadingLlmAdapter,chatStream,composePricing,computePrice,contentGate,costMeterExtractor,createAdapter,createCapabilitiesRegistry,createPricingRegistry,dryRunAdapter,fallbackAdapter,fromLLM,frozenContext,gatedStream,gaugesAsContext,googleAdapter,graphFromSpec,graphFromSpecReactive,handoff,keywordFlagExtractor,knobsAsTools,llmConsolidator,llmExtractor,memoryRetrieval,memoryWithKG,memoryWithTiers,memoryWithVectors,observableAdapter,openAICompatAdapter,parseRateLimitFromError,pricingFor,promptNode,redactor,registryPricing,resilientAdapter,streamExtractor,streamingPromptNode,suggestStrategy,suggestStrategyReactive,systemPromptBuilder,tier,toolCallExtractor,toolExecution,toolRegistry,toolSelector,validateGraphDef,withBreaker,withBudgetGate,withDryRun,withRateLimiter,withReplayCache,withRetry,withTimeout,zeroPrice});
|