@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/index.cjs CHANGED
@@ -1,55 +1,55 @@
1
- "use strict";var Zp=Object.create;var En=Object.defineProperty;var Iu=Object.getOwnPropertyDescriptor;var ef=Object.getOwnPropertyNames;var tf=Object.prototype.hasOwnProperty;var Du=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),fr=t=>{throw TypeError(t)};var nf=(t,e,n)=>e in t?En(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Cu=(t,e)=>En(t,"name",{value:e,configurable:!0});var et=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ne=(t,e)=>{for(var n in e)En(t,n,{get:e[n],enumerable:!0})},rf=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ef(e))!tf.call(t,o)&&o!==n&&En(t,o,{get:()=>e[o],enumerable:!(r=Iu(e,o))||r.enumerable});return t};var of=t=>rf(En({},"__esModule",{value:!0}),t);var Pu=t=>[,,,Zp(t?.[Du("metadata")]??null)],Gu=["class","method","getter","setter","accessor","field","value","get","set"],pr=t=>t!==void 0&&typeof t!="function"?fr("Function expected"):t,sf=(t,e,n,r,o)=>({kind:Gu[t],name:e,metadata:r,addInitializer:s=>n._?fr("Already initialized"):o.push(pr(s||null))}),af=(t,e)=>nf(e,Du("metadata"),t[3]),Fu=(t,e,n,r)=>{for(var o=0,s=t[e>>1],i=s&&s.length;o<i;o++)e&1?s[o].call(n):r=s[o].call(n,r);return r},$u=(t,e,n,r,o,s)=>{var i,a,u,c,d,l=e&7,p=!!(e&8),f=!!(e&16),m=l>3?t.length+1:l?p?1:2:0,g=Gu[l+5],h=l>3&&(t[m-1]=[]),y=t[m]||(t[m]=[]),b=l&&(!f&&!p&&(o=o.prototype),l<5&&(l>3||!f)&&Iu(l<4?o:{get[n](){return Au(this,s)},set[n](T){return Lu(this,s,T)}},n));l?f&&l<4&&Cu(s,(l>2?"set ":l>1?"get ":"")+n):Cu(o,n);for(var v=r.length-1;v>=0;v--)c=sf(l,n,u={},t[3],y),l&&(c.static=p,c.private=f,d=c.access={has:f?T=>uf(o,T):T=>n in T},l^3&&(d.get=f?T=>(l^1?Au:cf)(T,o,l^4?s:b.get):T=>T[n]),l>2&&(d.set=f?(T,w)=>Lu(T,o,w,l^4?s:b.set):(T,w)=>T[n]=w)),a=(0,r[v])(l?l<4?f?s:b[g]:l>4?void 0:{get:b.get,set:b.set}:o,c),u._=1,l^4||a===void 0?pr(a)&&(l>4?h.unshift(a):l?f?s=a:b[g]=a:o=a):typeof a!="object"||a===null?fr("Object expected"):(pr(i=a.get)&&(b.get=i),pr(i=a.set)&&(b.set=i),pr(i=a.init)&&h.unshift(i));return l||af(t,o),b&&En(o,n,b),f?l^4?s:b:o};var Pi=(t,e,n)=>e.has(t)||fr("Cannot "+n),uf=(t,e)=>Object(e)!==e?fr('Cannot use the "in" operator on this value'):t.has(e),Au=(t,e,n)=>(Pi(t,e,"read from private field"),n?n.call(t):e.get(t));var Lu=(t,e,n,r)=>(Pi(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),cf=(t,e,n)=>(Pi(t,e,"access private method"),n);var yt,S,te,F,Ye,Be,Ke,ve,C,O,Rt,_n,No,Mn,Eo,_o,On,mr,hr,gr,Cn,ae=et(()=>{"use strict";yt=Symbol.for("graphrefly/START"),S=Symbol.for("graphrefly/DATA"),te=Symbol.for("graphrefly/DIRTY"),F=Symbol.for("graphrefly/RESOLVED"),Ye=Symbol.for("graphrefly/INVALIDATE"),Be=Symbol.for("graphrefly/PAUSE"),Ke=Symbol.for("graphrefly/RESUME"),ve=Symbol.for("graphrefly/TEARDOWN"),C=Symbol.for("graphrefly/COMPLETE"),O=Symbol.for("graphrefly/ERROR"),Rt=Object.freeze([te]),_n=Object.freeze([F]),No=Object.freeze([Ye]),Mn=Object.freeze([yt]),Eo=Object.freeze([C]),_o=Object.freeze([ve]),On=Object.freeze([Rt]),mr=Object.freeze([_n]),hr=Object.freeze([No]),gr=Object.freeze([Eo]),Cn=Object.freeze([_o])});function Gi(t){return{name:"dag-cbor",version:1,contentType:"application/dag-cbor",encode:e=>t.encode(e),decode:(e,n)=>t.decode(e)}}function Fi(t,e){return{name:"dag-cbor-zstd",version:1,contentType:"application/dag-cbor+zstd",encode:n=>e.compressSync(t.encode(n)),decode:(n,r)=>t.decode(e.decompressSync(n))}}function yr(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++]=An,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 br(t,e){if(t.length<ju)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${ju})`);let n=0,r=t[n++];if(r!==An)throw new Error(`decodeEnvelope: unsupported envelope version ${r} (expected ${An})`);let o=t[n++];if(o===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(n+o+2>t.length)throw new Error(`decodeEnvelope: envelope truncated (need ${n+o+2} bytes, have ${t.length})`);let s=new TextDecoder().decode(t.subarray(n,n+o));n+=o;let i=(t[n]<<8|t[n+1])>>>0;n+=2;let a=t.subarray(n),u=e.lookupCodec(s);if(u==null)throw new Error(`decodeEnvelope: codec "${s}" not registered (envelope codec_v=${i})`);return{codec:u,codecVersion:i,payload:a}}function vr(t){t.registerCodec(Mo)}function $i(t){if(t.length===0)throw new Error("WAL is empty \u2014 need at least one full snapshot");let e=t[0];if(e.mode!=="full")throw new Error("WAL must start with a full record carrying a baseline snapshot");let n=JSON.parse(JSON.stringify(e.snapshot)),r=e.seq;for(let o=1;o<t.length;o++){let s=t[o];if(s.seq<=r)throw new Error(`WAL chain broken at index ${o}: seq=${s.seq} must exceed prev seq=${r}`);if(s.mode==="full"){n=JSON.parse(JSON.stringify(s.snapshot)),r=s.seq;continue}let i=s.diff;for(let u of i.nodesRemoved)delete n.nodes[u];let a=i.nodesAddedFull;if(a!=null)for(let[u,c]of Object.entries(a))n.nodes[u]=JSON.parse(JSON.stringify(c));for(let u of i.nodesChanged){let c=n.nodes[u.path];c!=null&&(c[u.field]=u.to)}r=s.seq}return n}var Mo,An,ju,Oo=et(()=>{"use strict";Mo={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)}};An=1,ju=4});function St(t){if(t==null)return bt;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var bt,Tr=et(()=>{"use strict";bt={type:"system",id:""}});function en(){return Ln>0||wr}function Bu(){return Ln>0}function xr(t){Ln>0?kr.push(t):t()}function Z(t){Ln+=1;let e=!1;try{t()}catch(n){throw e=!0,n}finally{if(Ln-=1,Ln===0)if(e){if(!wr){let n=kr.splice(0);for(let r of n)try{r()}catch{}Xt.length=0,Zt.length=0,In.length=0}}else df()}}function df(){let t=!wr;t&&(wr=!0);let e=[],n=0;try{for(;Xt.length>0||Zt.length>0||In.length>0||t&&kr.length>0;){if(t&&kr.length>0){let s=kr.splice(0);for(let i of s)try{i()}catch(a){e.push(a)}continue}if(n+=1,n>1e3)throw Xt.length=0,Zt.length=0,In.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let o=(Xt.length>0?Xt:Zt.length>0?Zt:In).splice(0);for(let s of o)try{s()}catch(i){e.push(i)}}}finally{t&&(wr=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function Nt(t,e,n){if(e.length===0)return;if(e.length===1){let c=n(e[0][0]);if(c<3||!en()){t(e);return}(c>=5?In:c===4?Zt:Xt).push(()=>t(e));return}let r=e.length,o=r,s=r,i=r,a=0;for(;a<r&&n(e[a][0])<3;)a++;for(o=a;a<r&&n(e[a][0])===3;)a++;for(s=a;a<r&&n(e[a][0])===4;)a++;i=a;let u=en();if(o>0){let c=e.slice(0,o);t(c)}if(s>o){let c=e.slice(o,s);u?Xt.push(()=>t(c)):t(c)}if(i>s){let c=e.slice(s,i);u?Zt.push(()=>t(c)):t(c)}if(r>i){let c=e.slice(i,r);u?In.push(()=>t(c)):t(c)}}var Ln,wr,Xt,Zt,In,kr,Ae=et(()=>{"use strict";Ln=0,wr=!1,Xt=[],Zt=[],In=[],kr=[]});function j(){return Math.trunc(performance.now()*1e6)}function Te(){return Date.now()*1e6}var _e=et(()=>{"use strict"});function Rr(t){t.registerMessageType(yt,{tier:0,wireCrossing:!1}),t.registerMessageType(te,{tier:1,wireCrossing:!1}),t.registerMessageType(Ye,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(Be,{tier:2,wireCrossing:!1}),t.registerMessageType(Ke,{tier:2,wireCrossing:!1}),t.registerMessageType(S,{tier:3,wireCrossing:!0}),t.registerMessageType(F,{tier:3,wireCrossing:!0}),t.registerMessageType(C,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(O,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(ve,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var tn,ji=et(()=>{"use strict";ae();tn=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 Vu(t){return Array.isArray(t)?[...t]:[t]}function lf(t,e){return t.has(e)||t.has("*")}function nn(t){let e=[];return t((o,s)=>{e.push({kind:"allow",actions:new Set(Vu(o)),where:s?.where??(()=>!0)})},(o,s)=>{e.push({kind:"deny",actions:new Set(Vu(o)),where:s?.where??(()=>!0)})}),(o,s)=>{let i=!1,a=!1;for(let u of e)lf(u.actions,s)&&u.where(o)&&(u.kind==="deny"?i=!0:a=!0);return i?!1:a}}function Sr(t){return nn((e,n)=>{for(let r of t){let o=r.actorType==null?null:new Set(Array.isArray(r.actorType)?r.actorType:[r.actorType]),s=r.actorId==null?null:new Set(Array.isArray(r.actorId)?r.actorId:[r.actorId]),i=Object.entries(r.claims??{}),a=u=>{if(o!==null&&!o.has(String(u.type))||s!==null&&!s.has(String(u.id??"")))return!1;for(let[c,d]of i)if(u[c]!==d)return!1;return!0};r.effect==="deny"?n(r.action,{where:a}):e(r.action,{where:a})}})}function Nr(t){let e=pf.filter(n=>t({type:n,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(n=>n==="human"||n==="llm"||n==="system")?"both":e.length===1?e[0]:e.join("+")}var nt,pf,rn=et(()=>{"use strict";nt=class extends Error{actor;action;nodeName;constructor(e,n){super(n??`GuardDenied: action "${String(e.action)}" denied for actor type "${String(e.actor.type)}"`),this.name="GuardDenied",this.actor=e.actor,this.action=e.action,this.nodeName=e.nodeName}get node(){return this.nodeName}};pf=["human","llm","wallet","system"]});function Bi(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(Bi);if(typeof t=="object"&&t!==null){let e={};for(let n of Object.keys(t).sort())e[n]=Bi(t[n]);return e}return null}function hf(t){let e=mf.encode(t),n=e.length,r=n*8,o=n+9+63&-64,s=new Uint8Array(o);s.set(e),s[n]=128;let i=new DataView(s.buffer);i.setUint32(o-4,r>>>0,!1),i.setUint32(o-8,Math.floor(r/4294967296)>>>0,!1);let a=1779033703,u=3144134277,c=1013904242,d=2773480762,l=1359893119,p=2600822924,f=528734635,m=1541459225,g=new Uint32Array(64),h=(b,v)=>b>>>v|b<<32-v;for(let b=0;b<o;b+=64){for(let M=0;M<16;M++)g[M]=i.getUint32(b+M*4,!1);for(let M=16;M<64;M++){let I=g[M-15],L=g[M-2],P=h(I,7)^h(I,18)^I>>>3,J=h(L,17)^h(L,19)^L>>>10;g[M]=g[M-16]+P+g[M-7]+J>>>0}let v=a,T=u,w=c,k=d,x=l,R=p,N=f,A=m;for(let M=0;M<64;M++){let I=h(x,6)^h(x,11)^h(x,25),L=x&R^~x&N,P=A+I+L+ff[M]+g[M]>>>0,J=h(v,2)^h(v,13)^h(v,22),Q=v&T^v&w^T&w,D=J+Q>>>0;A=N,N=R,R=x,x=k+P>>>0,k=w,w=T,T=v,v=P+D>>>0}a=a+v>>>0,u=u+T>>>0,c=c+w>>>0,d=d+k>>>0,l=l+x>>>0,p=p+R>>>0,f=f+N>>>0,m=m+A>>>0}let y=b=>b.toString(16).padStart(8,"0");return y(a)+y(u)+y(c)+y(d)+y(l)+y(p)+y(f)+y(m)}function Ft(t){let e=Bi(t??null),n=JSON.stringify(e);return hf(n).slice(0,16)}function gf(){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 Dn(t,e,n){let r=n?.id??gf();if(t===0)return{id:r,version:0};let s=(n?.hash??Ft)(e);return{id:r,version:0,cid:s,prev:null}}function Er(t,e,n){t.version+=1,"cid"in t&&(t.prev=t.cid,t.cid=n(e))}function Vi(t){return"cid"in t}var ff,mf,Co=et(()=>{"use strict";ff=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]),mf=new TextEncoder});function Wu(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function Ki(t){t.prevData=void 0,t.dirty=!1,t.involvedThisWave=!1,t.dataBatch.length=0,t.terminal=void 0}function Ao(t){return t.length===0?t:typeof t[0]=="symbol"?[t]:t}function Wi(t){if($e._isFrozen())throw new Error("configure() called after a node was created \u2014 the default GraphReFlyConfig is frozen. Call configure(...) at application startup, before any node factories run.");t($e)}function U(t,e,n){let r=qu(t)?t:[],o=typeof t=="function"?t:typeof e=="function"?e:void 0,s={};return qu(t)?s=(Hi(e)?e:n)??{}:Hi(t)?s=t:s=(Hi(e)?e:n)??{},new Ie(r,o,s)}var Ku,Hu,yf,bf,$e,Ie,qu,Hi,Le=et(()=>{"use strict";Oo();Tr();Ae();_e();ji();rn();ae();Co();Ku=()=>{},Hu=100;yf=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},bf=(t,e,n,r)=>{let o=t;if(o._status==="completed"||o._status==="errored")return;let s=o._cached,i=s===void 0?[Mn]:[Mn,[S,s]];o._status==="dirty"&&i.push(Rt),Nt(e,i,o._config.tierOf)},$e=new tn({onMessage:yf,onSubscribe:bf});Rr($e);vr($e);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??$e,this._config.onMessage,this._optsName=r.name,this._describeKind=r.describeKind,this._equals=r.equals??Object.is,this._resubscribable=r.resubscribable??!1,this._resetOnTeardown=r.resetOnTeardown??!1,this._autoComplete=r.completeWhenDepsComplete??!0,this._autoError=r.errorWhenDepsError??!0,this._pausable=r.pausable??!0,this._guard=r.guard,this._fn=n,this._partial=r.partial??!1,this._cached=r.initial!==void 0?r.initial:void 0,this._status=e.length===0&&n==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=r.versioningHash??this._config.defaultHashFn??Ft;let o=r.versioning??this._config.defaultVersioning;this._versioningLevel=o,this._versioning=o!=null?Dn(o,this._cached===void 0?void 0:this._cached,{id:r.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(Wu);let s={};for(let[a,u]of Object.entries(r.meta??{})){let c={initial:u,name:`${r.name??"node"}:meta:${a}`,describeKind:"state",config:this._config};r.guard!=null&&(c.guard=r.guard),s[a]=new t([],void 0,c)}Object.freeze(s),this.meta=s,this._hasMeta=Object.keys(s).length>0;let i=this;this._actions={emit(a){i._emit([[S,a]])},down(a){i._emit(Ao(a))},up(a){i._emitUp(Ao(a))}},this.down=this.down.bind(this),this.up=this.up.bind(this)}get _isTerminal(){return this._status==="completed"||this._status==="errored"}get name(){return this._optsName}get status(){return this._status}get cache(){return this._cached===void 0?void 0:this._cached}get lastMutation(){return this._lastMutation}get v(){return this._versioning}hasGuard(){return this._guard!=null}_applyVersioning(e,n){if(this._isExecutingFn)throw new Error(`Node "${this.name}": _applyVersioning cannot run mid-fn \u2014 call it outside of \`_execFn\` (typically at graph setup time before the first subscribe).`);let r=this._versioningLevel;if(r!=null&&e<=r)return;let o=n?.hash??this._hashFn;o!==this._hashFn&&(this._hashFn=o);let s=this._cached===void 0?void 0:this._cached,i=this._versioning,a=i?.id??n?.id,u=i?.version??0,c=Dn(e,s,{id:a,hash:o});c.version=u,this._versioning=c,this._versioningLevel=e}_setInspectorHook(e){return e==null?()=>{}:(this._inspectorHooks==null&&(this._inspectorHooks=new Set),this._inspectorHooks.add(e),()=>{this._inspectorHooks?.delete(e),this._inspectorHooks?.size===0&&(this._inspectorHooks=void 0)})}_pushGuard(e){return this._extraGuards==null&&(this._extraGuards=new Set),this._extraGuards.add(e),()=>{this._extraGuards?.delete(e),this._extraGuards?.size===0&&(this._extraGuards=void 0)}}allowsObserve(e){if(this._guard==null&&this._extraGuards==null)return!0;let n=St(e);if(this._guard!=null&&!this._guard(n,"observe"))return!1;if(this._extraGuards!=null){for(let r of this._extraGuards)if(!r(n,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let n=this._guard!=null||this._extraGuards!=null,r=e?.actor!=null;if(!n&&!r)return;let o=St(e?.actor),s=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(o,s))throw new nt({actor:o,action:s,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(o,s))throw new nt({actor:o,action:s,nodeName:this.name})}this._lastMutation={actor:o,timestamp_ns:Te()}}down(e,n){let r=Ao(e);r.length!==0&&(this._checkGuard(n),this._emit(r))}emit(e,n){this._checkGuard(n),this._emit([[S,e]])}up(e,n){if(this._deps.length===0)return;let r=Ao(e);if(r.length===0)return;this._checkGuard(n);let o=n??{internal:!0};this._validateUpTiers(r);for(let s of this._deps)s.node.up?.(r,o)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let n of this._deps)n.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let n=this._config.tierOf;for(let r of e){let o=n(r[0]);if(o===3||o===4)throw new Error(`Node "${this.name}": tier-${o} messages cannot flow up \u2014 DATA/RESOLVED/COMPLETE/ERROR are downstream-only. Use \`down(...)\` for value delivery; \`up(...)\` is for control signals (DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN).`)}}subscribe(e,n){if(n!=null&&this._guard!=null){let u=St(n);if(!this._guard(u,"observe"))throw new nt({actor:u,action:"observe",nodeName:this.name})}let o=this._isTerminal&&this._resubscribable;if(o){this._cached=void 0,this._status="sentinel",this._store={},this._hasCalledFnOnce=!1,this._waveHasNewData=!1,this._hasNewTerminal=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._isExecutingFn=!1,this._rerunDepth=0,this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null;for(let u of this._deps)Ki(u);if(this._partial===!1){for(let u of this._deps)if(u.prevData!==void 0||u.dataBatch.length!==0||u.terminal!==void 0||u.dirty)throw new Error(`resubscribable-reset invariant: DepRecord not fully reset for node ${this._optsName??"(anonymous)"}`)}}this._sinkCount+=1;let s;try{s=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:o},this._actions)}catch(u){throw this._sinkCount-=1,u}this._sinks==null?this._sinks=e:typeof this._sinks=="function"?this._sinks=new Set([this._sinks,e]):this._sinks.add(e);let i=this._isTerminal;if(this._sinkCount===1&&!i)try{this._activate()}catch(u){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof s=="function")try{s()}catch{}throw u}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let a=!1;return()=>{a||(a=!0,this._sinkCount-=1,this._removeSink(e),typeof s=="function"&&s(),this._sinks==null&&this._deactivate())}}_removeSink(e){if(this._sinks===e)this._sinks=null;else if(this._sinks!=null&&typeof this._sinks!="function")if(this._sinks.delete(e),this._sinks.size===1){let[n]=this._sinks;this._sinks=n}else this._sinks.size===0&&(this._sinks=null)}_activate(){if(this._deps.length===0){this._fn&&this._execFn();return}this._dirtyDepCount=0;let e=this._deps.length,n=0;try{for(let r=0;r<e;r++){let o=r,s=this._deps[r];s.unsub=Ku,s.unsub=s.node.subscribe(i=>{if(s.unsub===null)return;let a=this._config.tierOf,u=!1;for(let c of i)a(c[0])>=3&&(u=!0),this._config.onMessage(this,c,{direction:"down-in",depIndex:o},this._actions);u&&this._maybeRunFnOnSettlement()}),n++}}catch(r){this._deps[n].unsub=null;for(let o=0;o<n;o++){let s=this._deps[o];if(s.unsub!=null){let i=s.unsub;s.unsub=null;try{i()}catch{}Ki(s)}}throw this._dirtyDepCount=0,r}}_addDep(e){for(let o=0;o<this._deps.length;o++)if(this._deps[o].node===e)return o;let n=this._deps.length,r=Wu(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(On),r.unsub=Ku;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{}}Ki(r)}this._waveHasNewData=!1,this._hasNewTerminal=!1,this._hasCalledFnOnce=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._rerunDepth=0,this._store={},this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null,this._fn!=null&&(this._cached=void 0),e||(this._fn!=null||this._deps.length>0)&&(!this._isTerminal||this._resubscribable)&&(this._status="sentinel")}_onDepMessage(e,n){let r=this._deps[e],o=n[0];if(this._inspectorHooks!=null){let s={kind:"dep_message",depIndex:e,message:n};for(let i of this._inspectorHooks)i(s)}if(o!==yt){if(o===te){this._depDirtied(r);return}if(o===Ye){if(this._depInvalidated(r),this._cached===void 0)return;this._emit(hr);return}if(o===Be||o===Ke){this._emit([n]);return}if(o===ve){this._emit(Cn);return}if(o===S)this._depSettledAsData(r,n[1]);else if(o===F)this._depSettledAsResolved(r);else if(o===C)this._depSettledAsTerminal(r,!0);else if(o===O)this._depSettledAsTerminal(r,n[1]);else{this._emit([n]);return}if(!this._fn){(o===S||o===F)&&this._emit([n]),(o===C||o===O)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(On))}_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(mr),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(gr)}_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>Hu?(this._rerunDepth=0,this._emit([[O,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${Hu} \u2014 likely a reactive cycle`)]])):this._maybeRunFnOnSettlement()):this._rerunDepth=0,this._clearWaveFlags()}}_clearWaveFlags(){this._waveHasNewData=!1,this._hasNewTerminal=!1;for(let e of this._deps)e.involvedThisWave=!1,e.dataBatch.length=0}_wrapFnError(e,n){let r=n instanceof Error?n.message:String(n);return new Error(`Node "${this.name}": ${e}: ${r}`,{cause:n})}_frameBatch(e){let n=this._config.tierOf;if(e.length===1)return n(e[0][0])===3&&this._status!=="dirty"?[Rt,e[0]]:e;let r=!0,o=!1,s=!1,i=-1;for(let u of e){let c=n(u[0]);c<i&&(r=!1),c===3&&(o=!0),u[0]===te&&(s=!0),i=c}let a=e;if(!r){let u=e.map((c,d)=>({m:c,i:d,tier:n(c[0])}));u.sort((c,d)=>c.tier-d.tier||c.i-d.i),a=u.map(c=>c.m)}if(o&&!s&&this._status!=="dirty"){let u=0;for(;u<a.length&&n(a[u][0])===0;)u++;return u===0?[Rt,...a]:[...a.slice(0,u),Rt,...a.slice(u)]}return a}_emit(e){if(e.length===0)return;for(let a=0;a<e.length;a++){let u=e[a];if(u[0]===O&&u[1]===void 0)throw new TypeError('[ERROR, payload] requires a non-undefined payload (spec \xA71.2). Pass an Error object or domain tag instead \u2014 e.g. node.down([[ERROR, new Error("reason")]])')}let n=e;if(this._isTerminal&&!this._resubscribable){let a=e.filter(u=>u[0]===ve||u[0]===Ye);if(a.length===0)return;n=a}n=this._frameBatch(n);let o=null;for(let a=0;a<n.length;a++){let u=n[a],c=u[0];if(c!==Be&&c!==Ke){o?.push(u);continue}if(u.length<2)throw new Error(`Node "${this.name}": [[${c===Be?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let d=!0;if(this._pausable!==!1){let l=u[1];if(c===Be)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(l),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(l))d=!1;else if(this._pauseLocks.delete(l),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let p=this._pauseBuffer;this._pauseBuffer=[],this._emit(p)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}d?o?.push(u):o==null&&(o=n.slice(0,a))}if(o!=null){if(o.length===0)return;n=o}if(this._hasMeta&&n.some(a=>a[0]===ve))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(Cn)}catch{}let{finalMessages:s,equalsError:i}=this._updateState(n);if(s.length>0&&this._config.inspectorEnabled){let a=this._config.globalInspector;if(a!=null)try{a({kind:"emit",node:this,messages:s})}catch{}}if(s.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let a=this._config.tierOf,u=[];for(let c of s)a(c[0])===3?this._pauseBuffer.push(c):u.push(c);u.length>0&&this._dispatchOrAccumulate(u)}else this._dispatchOrAccumulate(s);i!=null&&this._emit([[O,i]])}_updateState(e){let n=this._config.tierOf,r,o,s=-1,i=0;for(let d of e)n(d[0])===3&&i++;let a=i<=1,u=-1;if(this._versioning!=null&&i>1){for(let d=e.length-1;d>=0;d--)if(e[d][0]===S){u=d;break}}for(let d=0;d<e.length;d++){let l=e[d],p=l[0];if(p===S){if(l.length>=2){let f=!1;if(a&&this._cached!==void 0)try{f=this._equals(this._cached,l[1])}catch(m){o=this._wrapFnError("equals threw",m),s=d;break}if(f){r==null&&(r=e.slice(0,d)),r.push(_n),this._status="resolved";continue}this._cached=l[1],this._versioning!=null&&(u<0||d===u)&&Er(this._versioning,l[1],this._hashFn)}this._status="settled",r?.push(l)}else if(r?.push(l),p===te)this._status="dirty";else if(p===F)this._status="resolved";else if(p===C){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===Ye){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===ve&&(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(Bu()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],xr(()=>this._flushBatchPending()));for(let n of e)this._batchPendingMessages.push(n);return}Nt(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let n=this._frameBatch(e);Nt(this._deliverToSinks,n,this._config.tierOf)}},qu=t=>Array.isArray(t),Hi=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function E(t,e){return U([],{...e,initial:t})}function H(t,e){return U((r,o,s)=>t(o,s)??void 0,{describeKind:"producer",...e})}function _(t,e,n){return U(t,(o,s,i)=>{let a=o.map((u,c)=>u!=null&&u.length>0?u.at(-1):i.prevData[c]);s.emit(e(a,i))},{describeKind:"derived",...n})}function de(t,e,n){return U(t,(o,s,i)=>{let a=o.map((u,c)=>u!=null&&u.length>0?u.at(-1):i.prevData[c]);return e(a,s,i)??void 0},{describeKind:"effect",...n})}function _r(t,e,n){let r=new Map;return t.forEach((o,s)=>{r.set(o,s)}),_(t,(o,s)=>e(a=>{let u=r.get(a);if(u==null)throw new Error(`dynamicNode: untracked dep "${a.name??"<unnamed>"}"`);return o[u]},s),n)}function on(t,e){let n,r=new Map,o=(s,i,a)=>{let u=!1,c=d=>{let l=r.get(d);if(l!==void 0){if(l<s.length){let f=s[l];return f!=null&&f.length>0?f.at(-1):a.prevData[l]}return d.cache}u=!0;let p=n._addDep(d);return r.set(d,p),d.cache};try{let d=t(c,a);u||(i.emit(d),a.store.__autoTrackLastDiscoveryError!=null&&delete a.store.__autoTrackLastDiscoveryError)}catch(d){if(!u)throw d;a.store.__autoTrackLastDiscoveryError=d}};return n=new Ie([],o,{describeKind:"derived",...e}),n}function qi(t,...e){let n=t;for(let r of e)n=r(n);return n}var ee=et(()=>{"use strict";Le()});function Cr(t,e,n){let r=new Set;for(let o of t.split(",")){let[s,i]=o.split("/"),a=i?Number.parseInt(i,10):1;if(Number.isNaN(a)||a<1)throw new Error(`Invalid cron step: ${o}`);let u,c;if(s==="*")u=e,c=n;else if(s.includes("-")){let[d,l]=s.split("-");u=Number.parseInt(d,10),c=Number.parseInt(l,10)}else u=Number.parseInt(s,10),c=u;if(Number.isNaN(u)||Number.isNaN(c))throw new Error(`Invalid cron field: ${t}`);if(u<e||c>n)throw new Error(`Cron field out of range: ${t} (${e}-${n})`);if(u>c)throw new Error(`Invalid cron range: ${u}-${c} in ${t}`);for(let d=u;d<=c;d+=a)r.add(d)}return r}function $o(t){let e=t.trim().split(/\s+/);if(e.length!==5)throw new Error(`Invalid cron: expected 5 fields, got ${e.length}`);return{minutes:Cr(e[0],0,59),hours:Cr(e[1],0,23),daysOfMonth:Cr(e[2],1,31),months:Cr(e[3],1,12),daysOfWeek:Cr(e[4],0,6)}}function jo(t,e){return t.minutes.has(e.getMinutes())&&t.hours.has(e.getHours())&&t.daysOfMonth.has(e.getDate())&&t.months.has(e.getMonth()+1)&&t.daysOfWeek.has(e.getDay())}var Ji=et(()=>{"use strict"});var uc={};Ne(uc,{NS_PER_MS:()=>He,NS_PER_SEC:()=>st,constant:()=>Bo,decorrelatedJitter:()=>Wo,exponential:()=>Ko,fibonacci:()=>Ho,linear:()=>Vo,resolveBackoffPreset:()=>$t,withMaxAttempts:()=>Yi});function an(t){return t<0?0:t}function Ef(t,e){return e==="none"?t:e==="full"?Math.random()*t:t/2+Math.random()*(t/2)}function _f(t,e){return t+Math.random()*(e-t)}function Bo(t){let e=an(t);return()=>e}function Vo(t,e){let n=an(t),r=e===void 0?n:an(e);return o=>n+r*Math.max(0,o)}function Ko(t){let e=an(t?.baseNs??1e8),n=t?.factor!==void 0&&t.factor<1?1:t?.factor??2,r=an(t?.maxDelayNs??30*1e9),o=t?.jitter??"none";return s=>{let i;if(e===0)i=0;else if(n===1)i=e;else{let a=r/e,u=1;for(let c=0;c<Math.max(0,s);c++){if(u>=a){u=a;break}u*=n}i=e*u,i>r&&(i=r)}return Ef(i,o)}}function Ho(t=100*1e6,e=30*1e9){let n=an(t),r=an(e);function o(s){if(s<=0)return 1;let i=1,a=2;for(let u=1;u<s;u++){let c=i+a;i=a,a=c}return a}return s=>{let i=o(s)*n;return i<=r?i:r}}function Wo(t=100*1e6,e=30*1e9){return(n,r,o)=>{let i=Math.min(e,(o??t)*3);return _f(t,i)}}function Yi(t,e){return(n,r,o)=>n>=e?null:t(n,r,o)}function $t(t){if(t==="constant")return Bo(1*1e9);if(t==="linear")return Vo(1*1e9);if(t==="exponential")return Ko();if(t==="fibonacci")return Ho();if(t==="decorrelatedJitter")return Wo();throw new Error(`Unknown backoff preset: "${String(t)}". Use one of: constant, linear, exponential, fibonacci, decorrelatedJitter`)}var He,st,Kn=et(()=>{"use strict";He=1e6,st=1e9});var De,vt=et(()=>{"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 dc={};Ne(dc,{CircuitOpenError:()=>lt,RateLimiterOverflowError:()=>un,TimeoutError:()=>cn,circuitBreaker:()=>Tt,fallback:()=>Un,rateLimiter:()=>qn,retry:()=>Hn,retrySource:()=>jt,timeout:()=>zn,tokenBucket:()=>Bt,withBreaker:()=>Wn,withStatus:()=>Vt});function dn(t){return{describeKind:"derived",...t}}function Mf(t){return t<0?0:t}function qo(t){return t[1]}function cc(t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError("backoff strategy must return a finite number");return t<0?0:t}function Hn(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"?$t(r):r;return H(i=>{let a=0,u=!1,c=null,d,l=new De;function p(){d?.(),d=void 0}function f(g){if(u)return;if(a>=o){p(),i.down([[O,g]]);return}let h=s===null?0:s(a,g,c);if(h==null){p(),i.down([[O,g]]);return}let y;try{y=cc(h)}catch{p(),i.down([[O,g]]);return}c=y,a+=1,p();let b=y>0?y/1e6:1;l.start(b,()=>{u||m()})}function m(){l.cancel(),p(),d=t.subscribe(g=>{if(!u)for(let h of g){let y=h[0];if(y===te)i.down([[te]]);else if(y===S)a=0,c=null,i.emit(h[1]);else if(y===F)i.down([[F]]);else if(y===C)p(),i.down([[C]]);else if(y===O){f(qo(h));return}else i.down([h])}})}return m(),()=>{u=!0,l.cancel(),p()}},{...dn(),initial:t.cache})}function jt(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"?$t(r):r;return H(i=>{let a=0,u=!1,c=null,d,l=new De;function p(){d?.(),d=void 0}function f(g){if(u)return;if(a>=o){p(),i.down([[O,g]]);return}let h=s===null?0:s(a,g,c);if(h==null){p(),i.down([[O,g]]);return}let y;try{y=cc(h)}catch{p(),i.down([[O,g]]);return}c=y,a+=1,p();let b=y>0?y/1e6:1;l.start(b,()=>{u||m()})}function m(){l.cancel(),p();let g;try{g=t()}catch(h){f(h);return}d=g.subscribe(h=>{if(!u)for(let y of h){let b=y[0];if(b===te)i.down([[te]]);else if(b===S)a=0,c=null,i.emit(y[1]);else if(b===F)i.down([[F]]);else if(b===C)p(),i.down([[C]]);else if(b===O){f(qo(y));return}else i.down([y])}})}return m(),()=>{u=!0,l.cancel(),p()}},{...dn(),initial:e?.initial})}function Tt(t){let e=Math.max(1,t?.failureThreshold??5),n=Mf(t?.cooldownNs??30*1e9),r=t?.cooldown??null,o=Math.max(1,t?.halfOpenMax??1),s=t?.now??j,i="closed",a=0,u=0,c=0,d=n,l=0;function p(){if(!r)return n;let g=r(u);return g!==null?g:n}function f(){i="open",d=p(),c=s(),l=0}return{canExecute(){return i==="closed"?!0:i==="open"?s()-c>=d?(i="half-open",l=1,!0):!1:l<o?(l++,!0):!1},recordSuccess(){i==="half-open"?(i="closed",a=0,u=0):i==="closed"&&(a=0)},recordFailure(g){if(i==="half-open"){u++,f();return}i==="closed"&&(a++,a>=e&&f())},get state(){return i},get failureCount(){return a},reset(){i="closed",a=0,u=0,l=0}}}function Wn(t,e){let n=e?.onOpen??"skip";return r=>{let o=U([],(s,i)=>{function a(){o.meta.breakerState.down([[S,t.state]])}let u=r.subscribe(c=>{for(let d of c){let l=d[0];l===te?i.down([[te]]):l===S?t.canExecute()?(a(),i.emit(d[1])):(a(),n==="error"?i.down([[O,new lt]]):i.down([[F]])):l===F?i.down([[F]]):l===C?(t.recordSuccess(),a(),i.down([[C]])):l===O?(t.recordFailure(qo(d)),a(),i.down([d])):i.down([d])}});return a(),u},{...dn(),meta:{breakerState:t.state},completeWhenDepsComplete:!1,initial:r.cache});return{node:o,breakerState:o.meta.breakerState}}}function Bt(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=j();function o(s){if(e>0){let i=s-r;n=Math.min(t,n+i/1e9*e)}r=s}return{available(){return o(j()),n},tryConsume(s=1){if(s<=0)return!0;let i=j();return o(i),n>=s?(n-=s,!0):!1},putBack(s=1){s<=0||(o(j()),n=Math.min(t,n+s))}}}function qn(t,e){let{maxEvents:n,windowNs:r}=e;if(n<=0)throw new RangeError("maxEvents must be > 0");if(r<=0)throw new RangeError("windowNs must be > 0");let o=e.maxBuffer;if(o!==void 0&&o<1)throw new RangeError("maxBuffer must be >= 1");let s=e.onOverflow??"drop-newest",i=n*1e9/r;return H(a=>{let u=Bt(n,i),c=[],d=new De,l=!1,p=1e9/i;function f(){for(;c.length>0;)if(u.tryConsume(1))a.emit(c.shift());else{d.start(Math.max(1,p/1e6),f);return}}let m=t.subscribe(g=>{for(let h of g){if(l)return;let y=h[0];if(y===te)a.down([[te]]);else if(y===S){if(o!==void 0&&c.length>=o){if(s!=="drop-newest")if(s==="drop-oldest")c.shift(),c.push(h[1]);else{l=!0,d.cancel(),c.length=0,a.down([[O,new un(o)]]);return}}else c.push(h[1]);f()}else if(y===F)a.down([[F]]);else if(y===C)l=!0,d.cancel(),c.length=0,a.down([[C]]);else if(y===O)l=!0,d.cancel(),c.length=0,a.down([h]);else if(y===ve){l=!0,d.cancel(),c.length=0,a.down([h]);return}else a.down([h])}});return()=>{l=!0,d.cancel(),m()}},{...dn(),initial:t.cache})}function Vt(t,e){let n=e?.initialStatus??"pending",r=U([],(o,s)=>{let i=n;return r.meta.status.down([[S,n]]),r.meta.error.down([[S,null]]),t.subscribe(u=>{for(let c of u){let d=c[0];if(d===te)s.down([[te]]);else if(d===S)i==="errored"?Z(()=>{r.meta.error.down([[S,null]]),r.meta.status.down([[S,"active"]])}):r.meta.status.down([[S,"active"]]),i="active",s.emit(c[1]);else if(d===F)s.down([[F]]);else if(d===C)r.meta.status.down([[S,"completed"]]),i="completed",s.down([[C]]);else if(d===O){let l=qo(c);Z(()=>{r.meta.error.down([[S,l]]),r.meta.status.down([[S,"errored"]])}),i="errored",s.down([c])}else s.down([c])}})},{...dn(),meta:{status:n,error:null},completeWhenDepsComplete:!1,resubscribable:!0,initial:t.cache});return{node:r,status:r.meta.status,error:r.meta.error}}function Of(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function Cf(t){return t!=null&&typeof t.then=="function"}function Af(t){return t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function"}function Un(t,e){return H(n=>{let r,o;function s(){o?.(),o=void 0,Of(e)||Cf(e)||Af(e)?r=X(e).subscribe(a=>{n.down(a)}):(n.emit(e),n.down([[C]]))}return o=t.subscribe(i=>{for(let a of i){let u=a[0];if(u===te)n.down([[te]]);else if(u===S)n.emit(a[1]);else if(u===F)n.down([[F]]);else if(u===C)n.down([[C]]);else if(u===O){s();return}else if(u===ve){r?.(),n.down([a]);return}else n.down([a])}}),()=>{o?.(),r?.()}},{...dn(),initial:t.cache})}function zn(t,e){if(e<=0)throw new RangeError("timeoutNs must be > 0");return H(n=>{let r=!1,o=new De;function s(){let a=e/1e6;o.start(a,()=>{r||(r=!0,i(),n.down([[O,new cn(e)]]))})}let i=t.subscribe(a=>{for(let u of a){if(r)return;let c=u[0];if(c===te)n.down([[te]]);else if(c===S)s(),n.emit(u[1]);else if(c===F)n.down([[F]]);else if(c===C){o.cancel(),r=!0,n.down([[C]]);return}else if(c===O){o.cancel(),r=!0,n.down([u]);return}else if(c===ve){o.cancel(),r=!0,n.down([u]);return}else n.down([u])}});return s(),()=>{r=!0,o.cancel(),i()}},{...dn(),initial:t.cache})}var lt,un,cn,Et=et(()=>{"use strict";Ae();_e();ae();Le();ee();Kn();Re();vt();lt=class extends Error{name="CircuitOpenError";constructor(){super("Circuit breaker is open")}};un=class extends Error{name="RateLimiterOverflowError";constructor(e){super(`rateLimiter buffer overflow (maxBuffer=${e})`)}};cn=class extends Error{name="TimeoutError";constructor(e){super(`Timed out after ${e/1e6}ms`)}}});function ut(t){return{describeKind:"producer",...t}}function Xi(t){return/[\\^$+?.()|[\]{}]/.test(t)?`\\${t}`:t}function pc(t){let e="^";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="*"){t[n+1]==="*"?(e+=".*",n+=1):e+="[^/]*";continue}e+=Xi(r)}return e+="$",new RegExp(e)}function fc(t,e){for(let n of e)if(n.test(t))return!0;return!1}function Lf(t,e){let n=U([t],(o,s)=>{let i=o[0];if(i==null||i.length===0){s.down([[F]]);return}for(let a of i)s.emit(a)},{describeKind:"derived",initial:t.cache}),r=n.subscribe.bind(n);return n.subscribe=(o,s)=>(e(o),r(o,s)),n}function ct(t,e){let{signal:n,period:r,...o}=e??{};return H(s=>{let i=!1,a=0,u,c,d=()=>{i=!0,u!==void 0&&clearTimeout(u),c!==void 0&&clearInterval(c),n?.removeEventListener("abort",p)},l=()=>{i||(r!=null?(s.emit(a++),c=setInterval(()=>{i||s.emit(a++)},r)):(i=!0,n?.removeEventListener("abort",p),s.emit(a++),s.down([[C]])))},p=()=>{i||(d(),s.down([[O,n.reason]]))};if(n?.aborted){p();return}return u=setTimeout(l,t),n?.addEventListener("abort",p,{once:!0}),d},ut(o))}function mc(t){let{signal:e,...n}=t??{};return H(r=>{let o=!1,s,i,a=!1,u=!1,c=typeof requestAnimationFrame=="function"?requestAnimationFrame:void 0,d=typeof cancelAnimationFrame=="function"?cancelAnimationFrame:void 0,l=typeof document<"u"?document:void 0,p=()=>{s!==void 0&&d&&d(s),i!==void 0&&clearTimeout(i),s=void 0,i=void 0},f=()=>{o=!0,p(),a&&(e?.removeEventListener("abort",m),a=!1),u&&l&&(l.removeEventListener("visibilitychange",y),u=!1)},m=()=>{o||(f(),r.down([[O,e.reason]]))},g=b=>{o||(r.emit(b),h())},h=()=>{o||(c&&(!l||l.visibilityState!=="hidden")?s=c(g):i=setTimeout(()=>g(performance.now()),16))},y=()=>{o||(p(),h())};return e?.aborted?(m(),f):(e?.addEventListener("abort",m,{once:!0}),a=e!==void 0,l&&c&&(l.addEventListener("visibilitychange",y),u=!0),h(),f)},ut(n))}function zo(t,e){let n=$o(t),{tickMs:r,output:o,...s}=e??{},i=r??6e4,a=o==="date";return H(u=>{let c=-1,d=()=>{let p=new Date,f=p.getFullYear()*1e8+(p.getMonth()+1)*1e6+p.getDate()*1e4+p.getHours()*100+p.getMinutes();f!==c&&jo(n,p)&&(c=f,u.emit(a?p:Te()))};d();let l=setInterval(d,i);return()=>clearInterval(l)},{...ut(s),name:s.name??`cron:${t}`})}function hc(t,e,n){let{capture:r,passive:o,once:s,...i}=n??{};return H(a=>{let u=d=>{a.emit(d)},c={capture:r,passive:o,once:s};return t.addEventListener(e,u,c),()=>t.removeEventListener(e,u,c)},ut(i))}function Jo(t,e){return H(n=>{let r=!1;try{for(let o of t){if(r)return;n.emit(o)}r||n.down([[C]])}catch(o){r||n.down([[O,o]])}return()=>{r=!0}},ut(e))}function If(t){return t!=null&&typeof t.then=="function"}function Jn(t,e){let{signal:n,...r}=e??{};return H(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([[C]]))},a=>{s||(s=!0,n?.removeEventListener("abort",i),o.down([[O,a]]))}),()=>{s=!0,n?.removeEventListener("abort",i)}},ut(r))}function Ar(t,e){let{signal:n,...r}=e??{};return H(o=>{let s=new AbortController,i=()=>s.abort(n?.reason);n?.aborted?s.abort(n.reason):n?.addEventListener("abort",i,{once:!0});let a=n??s.signal,u=!1,c=t[Symbol.asyncIterator](),d=()=>{u||a.aborted||Promise.resolve(c.next()).then(l=>{if(!(u||a.aborted)){if(l.done){o.down([[C]]);return}o.emit(l.value),d()}},l=>{!u&&!a.aborted&&o.down([[O,l]])})};return d(),()=>{u=!0,n?.removeEventListener("abort",i),s.abort(),Promise.resolve(c.return?.()).catch(()=>{})}},ut(r))}function Df(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function X(t,e){if(Df(t))return t;if(If(t))return Jn(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return Ar(t,e);if(typeof n[Symbol.iterator]=="function")return Jo(t,e)}return Zi(t)}function Zi(...t){return Jo(t,void 0)}function gc(t){return H(e=>{e.down([[C]])},ut(t))}function yc(t){return H(()=>{},ut(t))}function bc(t,e){return H(n=>{n.down([[O,t]])},ut(e))}function Kt(t,e,n){return U([t],(o,s)=>{let i=o[0];if(i!=null&&i.length>0)for(let a of i)e(a)},{describeKind:"effect",...n}).subscribe(()=>{})}function vc(t,e){return U([t],(n,r,o)=>{o.store.buf||(o.store.buf=[]);let s=o.store.buf,i=n[0];if(i!=null&&i.length>0)for(let a of i)s.push(a);if(o.terminalDeps[0]===!0){r.emit([...s]),r.down([[C]]);return}(i==null||i.length===0)&&r.down([[F]])},{describeKind:"derived",completeWhenDepsComplete:!1,...e})}function Tc(t,e){return H(n=>t.subscribe(r=>{n.down(r)}),{...ut(e),initial:t.cache})}function Yo(t,e,n){if(e<1)throw new RangeError("replay expects bufferSize >= 1");let r=[],o=H(s=>t.subscribe(i=>{for(let a of i)a[0]===S&&(r.push(a[1]),r.length>e&&r.shift());s.down(i)}),{...ut(n),initial:t.cache});return Lf(o,s=>{for(let i of r)s([[S,i]])})}function wc(t,e){return Yo(t,1,e)}function Qe(t){return new Promise((e,n)=>{let r=!1,o=!1,s;s=t.subscribe(i=>{for(let a of i){if(r)return;if(a[0]===S){r=!0,e(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===O){r=!0,n(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===C){r=!0,n(new Error("completed without DATA")),s?(s(),s=void 0):o=!0;return}}}),o&&(s?.(),s=void 0)})}function Uo(t,e,n){return new Promise((r,o)=>{let s=!1,i=!1,a,u=n?.skipCurrent===!0;a=t.subscribe(c=>{for(let d of c){if(s)return;if(!(u&&d[0]===S)){if(d[0]===S){let l=d[1];if(e(l)){s=!0,r(l),a?(a(),a=void 0):i=!0;return}}if(d[0]===O){s=!0,o(d[1]),a?(a(),a=void 0):i=!0;return}if(d[0]===C){s=!0,o(new Error("completed without matching value")),a?(a(),a=void 0):i=!0;return}}}}),u=!1,i&&(a?.(),a=void 0)})}async function Qo(t,e){let n=e?.predicate??(s=>s!=null),r=e?.skipCurrent;if(e?.timeoutMs==null||e.timeoutMs<=0)return await Uo(t,n,{skipCurrent:r});if(Qi===void 0){let[s,i]=await Promise.all([Promise.resolve().then(()=>(Et(),dc)),Promise.resolve().then(()=>(Kn(),uc))]);Qi=s.timeout,lc=i.NS_PER_MS}let o=Qi(t,e.timeoutMs*lc);return await Uo(o,n,{skipCurrent:r})}function Xo(t,e){let n=new AbortController,r=e?.reason??new Error("cancelled via nodeSignal"),o,s=!1,i=()=>{o?(o(),o=void 0):s=!0};return o=t.subscribe(a=>{if(!n.signal.aborted)for(let u of a){if(u[0]===S&&u[1]===!0){n.abort(r),i();return}if(u[0]===O){n.abort(u[1]),i();return}if(u[0]===C){i();return}}}),s&&(o?.(),o=void 0),{signal:n.signal,dispose:()=>{o&&(o(),o=void 0)}}}function se(t){return t.subscribe(()=>{})}function ea(t){let e=E(0);return{node:e,increment(){let n=e.cache??0;return n>=t?!1:(e.down([[te],[S,n+1]]),!0)},get(){return e.cache??0},atCap(){return(e.cache??0)>=t}}}var Qi,lc,kc,Re=et(()=>{"use strict";_e();ae();Le();ee();Ji();kc=Yo});var ib={};Ne(ib,{COMPLETE:()=>C,COMPLETE_MSG:()=>Eo,COMPLETE_ONLY_BATCH:()=>gr,CircuitOpenError:()=>lt,ContentAddressedMissError:()=>zr,DATA:()=>S,DEFAULT_ACTOR:()=>bt,DIRTY:()=>te,DIRTY_MSG:()=>Rt,DIRTY_ONLY_BATCH:()=>On,ENVELOPE_VERSION:()=>An,ERROR:()=>O,GRAPH_META_SEGMENT:()=>qe,Graph:()=>Y,GraphReFlyConfig:()=>tn,GuardDenied:()=>nt,INVALIDATE:()=>Ye,INVALIDATE_MSG:()=>No,INVALIDATE_ONLY_BATCH:()=>hr,JsonCodec:()=>Mo,NS_PER_MS:()=>He,NS_PER_SEC:()=>st,NativeIndexBackend:()=>Qr,NativeListBackend:()=>Xr,NativeLogBackend:()=>Gr,NativeMapBackend:()=>qr,NativePubSubBackend:()=>Yr,NodeImpl:()=>Ie,PAUSE:()=>Be,RESOLVED:()=>F,RESOLVED_MSG:()=>_n,RESOLVED_ONLY_BATCH:()=>mr,RESUME:()=>Ke,RateLimiterOverflowError:()=>un,ResettableTimer:()=>De,SIZEOF_OVERHEAD:()=>je,SIZEOF_SYMBOL:()=>is,SNAPSHOT_VERSION:()=>pt,SNAPSHOT_WIRE_VERSION:()=>Ro,START:()=>yt,START_MSG:()=>Mn,SurfaceError:()=>Ce,TEARDOWN:()=>ve,TEARDOWN_MSG:()=>_o,TEARDOWN_ONLY_BATCH:()=>Cn,TimeoutError:()=>cn,accessHintForGuard:()=>Nr,accountability:()=>ai,advanceVersion:()=>Er,ai:()=>oi,asSurfaceError:()=>Ni,audit:()=>kd,autoTrackNode:()=>on,awaitSettled:()=>Qo,batch:()=>Z,buffer:()=>xd,bufferCount:()=>Rd,bufferTime:()=>Nd,cached:()=>wc,canonicalJson:()=>Jr,cascadingCache:()=>Il,catchError:()=>Pd,checkpointToRedis:()=>Nl,checkpointToS3:()=>Sl,circuitBreaker:()=>Tt,combine:()=>va,combineLatest:()=>Ld,compat:()=>ya,concat:()=>hd,concatMap:()=>bd,configure:()=>Wi,constant:()=>Bo,contentAddressedStorage:()=>_s,core:()=>aa,cqrs:()=>fs,createDagCborCodec:()=>Gi,createDagCborZstdCodec:()=>Fi,createGraph:()=>dr,createTransport:()=>Ut,createVersioning:()=>Dn,createWatermarkController:()=>Yn,csvRows:()=>al,debounce:()=>wa,debounceTime:()=>Id,decodeEnvelope:()=>br,decorrelatedJitter:()=>Wo,defaultConfig:()=>$e,defaultHash:()=>Ft,delay:()=>Td,deleteSnapshot:()=>Li,demoShell:()=>ci,derived:()=>_,deserializeError:()=>bn,dictStorage:()=>Wl,diffForWAL:()=>ds,diffSnapshots:()=>Ci,distill:()=>Ns,distinctUntilChanged:()=>pd,domainTemplates:()=>di,downWithBatch:()=>Nt,dynamicNode:()=>_r,effect:()=>de,elementAt:()=>cd,empty:()=>gc,encodeEnvelope:()=>yr,escapeRegexChar:()=>Xi,exhaustMap:()=>yd,explainPath:()=>Dr,exponential:()=>Ko,externalBundle:()=>xs,externalProducer:()=>hn,extra:()=>Aa,fallback:()=>Un,fibonacci:()=>Ho,filter:()=>it,find:()=>ud,first:()=>Rs,firstValueFrom:()=>Qe,firstWhere:()=>Uo,flatMap:()=>vd,forEach:()=>Kt,fromAny:()=>X,fromAsyncIter:()=>Ar,fromCSV:()=>il,fromClickHouseWatch:()=>ll,fromCron:()=>zo,fromDrizzle:()=>Cl,fromEvent:()=>hc,fromHTTP:()=>Na,fromHTTPPoll:()=>qd,fromHTTPStream:()=>Wd,fromIter:()=>Jo,fromKafka:()=>nl,fromKysely:()=>Al,fromMCP:()=>Jd,fromNATS:()=>ml,fromNDJSON:()=>dl,fromOTel:()=>Yd,fromPrisma:()=>Ol,fromPrometheus:()=>tl,fromPromise:()=>Jn,fromPulsar:()=>pl,fromRabbitMQ:()=>gl,fromRaf:()=>mc,fromRedisStream:()=>ol,fromSSE:()=>Hd,fromSqlite:()=>El,fromSqliteCursor:()=>_l,fromStatsD:()=>Zd,fromSyslog:()=>Qd,fromTimer:()=>ct,fromWebSocket:()=>Sa,fromWebSocketReconnect:()=>zd,fromWebhook:()=>Gd,globToRegExp:()=>pc,graph:()=>ca,graphProfile:()=>fn,graphspec:()=>ri,guarded:()=>pi,harness:()=>wi,interval:()=>Md,isBatching:()=>en,isV1:()=>Vi,jobQueue:()=>vi,jotai:()=>Lo,keepalive:()=>se,last:()=>ad,layout:()=>Ri,lens:()=>xi,linear:()=>Vo,listSnapshots:()=>Ai,lru:()=>Ma,makeHttpError:()=>ht,map:()=>Br,matchesAnyPattern:()=>fc,matchesCron:()=>jo,memory:()=>ei,memoryStorage:()=>eo,merge:()=>wt,mergeMap:()=>Ta,mermaidLiveUrl:()=>cs,messaging:()=>zs,monotonicNs:()=>j,nameToSignal:()=>gn,nanostores:()=>Go,ndjsonRows:()=>ul,nestjs:()=>hs,never:()=>yc,node:()=>U,nodeSignal:()=>Xo,normalizeActor:()=>St,of:()=>Zi,onFirstData:()=>Kr,orchestration:()=>Js,pairwise:()=>fd,parseCron:()=>$o,parsePrometheusText:()=>Ea,parseSSEStream:()=>Lt,parseStatsD:()=>el,parseSyslog:()=>Xd,patterns:()=>Ou,pausable:()=>Cd,pipe:()=>qi,policy:()=>nn,policyFromRules:()=>Sr,producer:()=>H,pubsub:()=>$l,race:()=>gd,rateLimiter:()=>qn,reachable:()=>mn,react:()=>gs,reactiveCounter:()=>ea,reactiveIndex:()=>Vl,reactiveList:()=>Ms,reactiveLog:()=>Ue,reactiveMap:()=>Xe,reactiveSink:()=>We,reduce:()=>od,reduction:()=>ni,refine:()=>hi,registerBuiltinCodecs:()=>vr,registerBuiltins:()=>Rr,repeat:()=>Od,replay:()=>Yo,replayWAL:()=>$i,rescue:()=>Hr,resilientPipeline:()=>Si,resolveBackoffPreset:()=>$t,resolveDescribeFields:()=>_t,restoreSnapshot:()=>Oi,retry:()=>Hn,retrySource:()=>jt,runReduction:()=>Ei,sample:()=>wd,saveSnapshot:()=>Mi,scan:()=>rd,serializeError:()=>yn,share:()=>Tc,shareReplay:()=>kc,signalToName:()=>qt,signals:()=>bs,singleFromAny:()=>Os,singleNodeFromAny:()=>Kl,sizeof:()=>Pr,skip:()=>ba,solid:()=>vs,sortJsonValue:()=>Zr,stableJsonString:()=>Hl,state:()=>E,stratify:()=>to,surface:()=>Ii,svelte:()=>Ts,switchMap:()=>Se,take:()=>Vr,takeUntil:()=>id,takeWhile:()=>sd,tap:()=>dd,tapFirst:()=>ld,throttle:()=>ka,throttleTime:()=>Dd,throwError:()=>bc,timeout:()=>zn,toArray:()=>vc,toCSV:()=>bl,toClickHouse:()=>vl,toFile:()=>_a,toHTTP:()=>Fd,toKafka:()=>rl,toLoki:()=>xl,toMongo:()=>kl,toNATS:()=>hl,toObservable:()=>Fo,toPostgres:()=>wl,toPulsar:()=>fl,toRabbitMQ:()=>yl,toReadableStream:()=>Kd,toRedisStream:()=>sl,toS3:()=>Tl,toSSE:()=>Bd,toSSEBytes:()=>Vd,toSqlite:()=>Ml,toTempo:()=>Rl,toWebSocket:()=>Ud,tokenBucket:()=>Bt,validateGraphObservability:()=>ua,valve:()=>Ad,verifiable:()=>Gl,version:()=>sb,vue:()=>ws,wallClockNs:()=>Te,watchTopologyTree:()=>Mt,window:()=>_d,windowCount:()=>Sd,windowTime:()=>Ed,withBreaker:()=>Wn,withLatestFrom:()=>At,withMaxAttempts:()=>Yi,withStatus:()=>Vt,workerBridge:()=>Oa,workerSelf:()=>Ca,zip:()=>md,zustand:()=>ks});module.exports=of(ib);var ya={};Ne(ya,{jotai:()=>Lo,nanostores:()=>Go,nestjs:()=>hs,react:()=>gs,signals:()=>bs,solid:()=>vs,svelte:()=>Ts,vue:()=>ws,zustand:()=>ks});var Lo={};Ne(Lo,{atom:()=>vf});ae();ee();function vf(t,e,n){if(typeof t=="function"){let r=t;return typeof e=="function"?Uu(r,e,n):Uu(r,void 0,e)}return Tf(t,e)}function Mr(t){let e=t.cache,n;if(t.subscribe(o=>{for(let[s,i]of o)s===S&&(e=i),s===O&&(n=i)})(),n)throw n;return e}function Tf(t,e){let n=E(t,{...e,resubscribable:!0,resetOnTeardown:!0});return{get:()=>n.status==="sentinel"?Mr(n):n.cache,set:r=>n.emit(r),update:r=>{let o=n.status==="sentinel"?Mr(n):n.cache;n.emit(r(o))},subscribe:r=>{let o=!0;return n.subscribe(s=>{for(let[i,a]of s)if(i===S){if(o){o=!1;continue}r(a)}})},meta:n.meta,_node:n}}function Uu(t,e,n){let r=on(s=>t(i=>{let a=i._node;return a.status==="sentinel"&&Mr(a),s(a)}),{...n,resubscribable:!0,resetOnTeardown:!0}),o={get:()=>r.status==="sentinel"?Mr(r):r.cache,subscribe:s=>{let i=!0;return r.subscribe(a=>{for(let[u,c]of a)if(u===S){if(i){i=!1;continue}s(c)}})},meta:r.meta,_node:r};if(e){let s=u=>u.get(),i=(u,c)=>u.set(c),a=o;return a.set=u=>e(s,i,u),a.update=u=>{let c=r.status==="sentinel"?Mr(r):r.cache;return e(s,i,u(c))},a}return o}var Go={};Ne(Go,{action:()=>Nf,atom:()=>wf,computed:()=>kf,getValue:()=>Rf,map:()=>xf,onMount:()=>Sf,onStart:()=>Yu,onStop:()=>Qu});Ae();ae();ee();var Do=new WeakMap,Po=new WeakMap;function Io(t,e){let n=e.get(t);if(n)for(let r of n)r()}function Ui(t,e={}){let n=0;return{...e,get:()=>Ju(t),subscribe:o=>{n===0&&Io(t,Do),n++;let s=t.subscribe(i=>{for(let[a,u]of i)a===S&&o(u)});return()=>{s(),n--,n===0&&Io(t,Po)}},listen:o=>{n===0&&Io(t,Do),n++;let s=!0,i=t.subscribe(a=>{for(let[u,c]of a)if(u===S){if(s){s=!1;continue}o(c)}});return()=>{i(),n--,n===0&&Io(t,Po)}},_node:t}}function zu(t){let e=t.cache,n;if(t.subscribe(o=>{for(let[s,i]of o)s===S&&(e=i),s===O&&(n=i)})(),n)throw n;return e}function Ju(t){return t.status==="sentinel"?zu(t):t.cache}function wf(t){let e=E(t,{resubscribable:!0,resetOnTeardown:!0});return Ui(e,{set:n=>e.emit(n)})}function kf(t,e){let n=Array.isArray(t)?t:[t],r=n.map(s=>s._node),o=_r(r,s=>{let i=n.map(a=>{let u=a._node;return u.status==="sentinel"&&zu(u),s(u)});return e(...i)},{resubscribable:!0,resetOnTeardown:!0,equals:Object.is});return Ui(o)}function xf(t){let e=E(t,{resubscribable:!0,resetOnTeardown:!0,equals:()=>!1});return Ui(e,{set:n=>e.emit(n),setKey:(n,r)=>{let o=Ju(e);e.emit({...o,[n]:r})}})}function Rf(t){return t.get()}function Yu(t,e){let n=t._node,r=Do.get(n);r||(r=new Set,Do.set(n,r)),r.add(e)}function Qu(t,e){let n=t._node,r=Po.get(n);r||(r=new Set,Po.set(n,r)),r.add(e)}function Sf(t,e){Yu(t,()=>{let n=e();typeof n=="function"&&Qu(t,n)})}function Nf(t,e,n){return(...r)=>{let o;return Z(()=>{o=n(...r)}),o}}var hs={};Ne(hs,{ACTOR_KEY:()=>es,COMMAND_HANDLERS:()=>$n,CQRS_EVENT_HANDLERS:()=>jn,CRON_HANDLERS:()=>Fn,CommandHandler:()=>oc,EVENT_HANDLERS:()=>Pn,EventHandler:()=>sc,GRAPHREFLY_REQUEST_GRAPH:()=>sn,GRAPHREFLY_ROOT_GRAPH:()=>at,GraphCron:()=>rc,GraphInterval:()=>nc,GraphReflyEventExplorer:()=>ln,GraphReflyGuard:()=>_c,GraphReflyGuardImpl:()=>Lr,GraphReflyModule:()=>ms,INTERVAL_HANDLERS:()=>Gn,InjectCqrsGraph:()=>Zu,InjectGraph:()=>Xu,InjectNode:()=>ec,ObserveGateway:()=>Zo,OnGraphEvent:()=>tc,QUERY_HANDLERS:()=>Bn,QueryHandler:()=>ic,SAGA_HANDLERS:()=>Vn,SagaHandler:()=>ac,fromHeader:()=>Nc,fromJwtPayload:()=>ra,getActor:()=>Ec,getGraphToken:()=>rt,getNodeToken:()=>dt,observeSSE:()=>Rc,observeSubscription:()=>Sc,toObservable:()=>Fo});var zi=require("rxjs");ae();function Fo(t,e){return e?.raw?new zi.Observable(n=>t.subscribe(o=>{if(!n.closed){n.next(o);for(let s of o){if(s[0]===O){n.error(s[1]);return}if(s[0]===C){n.complete();return}}}})):new zi.Observable(n=>t.subscribe(o=>{for(let s of o){if(n.closed)return;if(s[0]===S)n.next(s[1]);else if(s[0]===O){n.error(s[1]);return}else if(s[0]===C){n.complete();return}}}))}var Or=require("@nestjs/common");var at=Symbol.for("graphrefly:root-graph");var sn=Symbol.for("graphrefly:request-graph");function rt(t){return Symbol.for(`graphrefly:graph:${t}`)}function dt(t){return Symbol.for(`graphrefly:node:${t}`)}var Pn=new Map,Gn=new Map,Fn=new Map,$n=new Map,jn=new Map,Bn=new Map,Vn=new Map;function Xu(t){return t==="request"?(0,Or.Inject)(sn):(0,Or.Inject)(t?rt(t):at)}function Zu(t){return(0,Or.Inject)(rt(t))}function ec(t){return(0,Or.Inject)(dt(t))}function tc(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=Pn.get(o)??[];s.push({nodeName:t,methodKey:r}),Pn.set(o,s)})}}function nc(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=Gn.get(o)??[];s.push({ms:t,methodKey:r}),Gn.set(o,s)})}}function rc(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=Fn.get(o)??[];s.push({expr:t,methodKey:r}),Fn.set(o,s)})}}function oc(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=$n.get(s)??[];i.push({cqrsName:t,commandName:e,methodKey:o}),$n.set(s,i)})}}function sc(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=jn.get(s)??[];i.push({cqrsName:t,eventName:e,methodKey:o}),jn.set(s,i)})}}function ic(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=Bn.get(s)??[];i.push({cqrsName:t,projectionName:e,methodKey:o}),Bn.set(s,i)})}}function ac(t,e,n){return(r,o)=>{let s=o.name;o.addInitializer(function(){let i=this.constructor,a=Vn.get(i)??[];a.push({cqrsName:t,eventNames:n,sagaName:e,methodKey:s}),Vn.set(i,a)})}}ae();Re();var xc=0,ln=class{constructor(e,n){this.graph=e;this.moduleRef=n}disposers=[];scheduleNodeNames=[];onModuleInit(){this.wireEvents(),this.wireIntervals(),this.wireCrons(),this.wireCqrsCommands(),this.wireCqrsEvents(),this.wireCqrsQueries(),this.wireCqrsSagas()}onModuleDestroy(){for(let e of this.disposers)e();this.disposers.length=0;for(let e of this.scheduleNodeNames)try{this.graph.remove(e)}catch{}this.scheduleNodeNames.length=0}wireEvents(){for(let[e,n]of Pn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireEventHandler(r,o)}}wireEventHandler(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),i=this.observeNode(n.nodeName).subscribe(a=>{for(let u of a)u[0]===S&&o(u[1])});this.disposers.push(i)}wireIntervals(){for(let[e,n]of Gn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireIntervalHandler(r,e,o)}}wireIntervalHandler(e,n,r){let o=e[r.methodKey];if(typeof o!="function")return;let s=o.bind(e),a=`__schedule__.${n.name??"anonymous"}.${String(r.methodKey)}.${xc++}`,u=ct(r.ms,{period:r.ms,name:a});this.graph.add(u),this.scheduleNodeNames.push(a);let d=this.observeNode(a).subscribe(l=>{for(let p of l)p[0]===S&&s(p[1])});this.disposers.push(d)}wireCrons(){for(let[e,n]of Fn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCronHandler(r,e,o)}}wireCronHandler(e,n,r){let o=e[r.methodKey];if(typeof o!="function")return;let s=o.bind(e),a=`__schedule__.${n.name??"anonymous"}.${String(r.methodKey)}.${xc++}`,u=zo(r.expr,{name:a});this.graph.add(u),this.scheduleNodeNames.push(a);let d=this.observeNode(a).subscribe(l=>{for(let p of l)p[0]===S&&s(p[1])});this.disposers.push(d)}wireCqrsCommands(){for(let[e,n]of $n){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsCommand(r,o)}}wireCqrsCommand(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);s&&s.command(n.commandName,o)}wireCqrsEvents(){for(let[e,n]of jn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsEventHandler(r,o)}}wireCqrsEventHandler(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);if(!s)return;s.event(n.eventName);let a=s.resolve(n.eventName).cache,u=a&&a.length>0?a[a.length-1].seq:0,d=this.observeNodeOn(s,n.eventName).subscribe(l=>{for(let p of l)if(p[0]===S){let f=p[1];for(let m of f)m.seq>u&&(o(m),u=m.seq)}});this.disposers.push(d)}wireCqrsQueries(){for(let[e,n]of Bn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsQuery(r,o)}}wireCqrsQuery(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);if(!s)return;let a=this.observeNodeOn(s,n.projectionName).subscribe(u=>{for(let c of u)c[0]===S&&o(c[1])});this.disposers.push(a)}wireCqrsSagas(){for(let[e,n]of Vn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsSaga(r,o)}}wireCqrsSaga(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);s&&s.saga(n.sagaName,n.eventNames,o)}observeNode(e){return this.graph.observe(e)}observeNodeOn(e,n){return e.observe(n)}resolveCqrsGraph(e){try{return this.moduleRef.get(rt(e),{strict:!1})}catch{return console.warn(`[GraphReFly] CqrsGraph "${e}" not found in DI \u2014 did you import GraphReflyModule.forCqrs({ name: "${e}" })?`),null}}resolveInstance(e){try{return this.moduleRef.get(e,{strict:!1})}catch{return null}}};ae();ae();var Pf=0;function Yn(t,e){if(e.highWaterMark<1)throw new RangeError("highWaterMark must be >= 1");if(e.lowWaterMark<0)throw new RangeError("lowWaterMark must be >= 0");if(e.lowWaterMark>=e.highWaterMark)throw new RangeError("lowWaterMark must be < highWaterMark");let n=Symbol(`bp-${++Pf}`),r=0,o=!1;return{onEnqueue(){return r+=1,!o&&r>=e.highWaterMark?(o=!0,t([[Be,n]]),!0):!1},onDequeue(){return r>0&&(r-=1),o&&r<=e.lowWaterMark?(o=!1,t([[Ke,n]]),!0):!1},get pending(){return r},get paused(){return o},dispose(){o&&(o=!1,t([[Ke,n]]))}}}function Rc(t,e,n){let{actor:r,serialize:o=Gf,keepAliveMs:s,signal:i}=n??{},a=new TextEncoder,u,c=n?.highWaterMark!=null,d,l,p=[],f=!1;return new ReadableStream({start(m){let g,h=()=>{},y=()=>{if(!f){f=!0,g!==void 0&&clearInterval(g),i?.removeEventListener("abort",b),h(),d?.dispose(),l?.(),l=void 0;for(let T of p)m.enqueue(T.frame);p.length=0,m.close()}};u=y;let b=()=>y(),v=t.observe(e,{actor:r});c&&(d=Yn(T=>v.up(T),{highWaterMark:n.highWaterMark,lowWaterMark:n.lowWaterMark??Math.floor(n.highWaterMark/2)})),h=v.subscribe(T=>{for(let w of T){if(f)return;let k=w[0];if(k===S){let x=a.encode(ta("data",o(w[1])));c?(p.push({frame:x,counted:!0}),d.onEnqueue(),l?.(),l=void 0):m.enqueue(x)}else if(k===O){let x=a.encode(ta("error",o(w[1])));c?(p.push({frame:x,counted:!1}),l?.(),l=void 0):m.enqueue(x),y();return}else if(k===C||k===ve){if(k===C){let x=a.encode(ta("complete"));c?(p.push({frame:x,counted:!1}),l?.(),l=void 0):m.enqueue(x)}y();return}}}),s!==void 0&&s>0&&(g=setInterval(()=>{f||(c?(p.push({frame:a.encode(`: keepalive
1
+ "use strict";var of=Object.create;var En=Object.defineProperty;var Gu=Object.getOwnPropertyDescriptor;var sf=Object.getOwnPropertyNames;var af=Object.prototype.hasOwnProperty;var Fu=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),fr=t=>{throw TypeError(t)};var uf=(t,e,n)=>e in t?En(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Iu=(t,e)=>En(t,"name",{value:e,configurable:!0});var tt=(t,e)=>()=>(t&&(e=t(t=0)),e);var we=(t,e)=>{for(var n in e)En(t,n,{get:e[n],enumerable:!0})},df=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of sf(e))!af.call(t,s)&&s!==n&&En(t,s,{get:()=>e[s],enumerable:!(r=Gu(e,s))||r.enumerable});return t};var cf=t=>df(En({},"__esModule",{value:!0}),t);var $u=t=>[,,,of(t?.[Fu("metadata")]??null)],ju=["class","method","getter","setter","accessor","field","value","get","set"],pr=t=>t!==void 0&&typeof t!="function"?fr("Function expected"):t,lf=(t,e,n,r,s)=>({kind:ju[t],name:e,metadata:r,addInitializer:o=>n._?fr("Already initialized"):s.push(pr(o||null))}),pf=(t,e)=>uf(e,Fu("metadata"),t[3]),Bu=(t,e,n,r)=>{for(var s=0,o=t[e>>1],i=o&&o.length;s<i;s++)e&1?o[s].call(n):r=o[s].call(n,r);return r},Vu=(t,e,n,r,s,o)=>{var i,a,u,d,c,l=e&7,p=!!(e&8),f=!!(e&16),m=l>3?t.length+1:l?p?1:2:0,g=ju[l+5],h=l>3&&(t[m-1]=[]),y=t[m]||(t[m]=[]),b=l&&(!f&&!p&&(s=s.prototype),l<5&&(l>3||!f)&&Gu(l<4?s:{get[n](){return Du(this,o)},set[n](T){return Pu(this,o,T)}},n));l?f&&l<4&&Iu(o,(l>2?"set ":l>1?"get ":"")+n):Iu(s,n);for(var v=r.length-1;v>=0;v--)d=lf(l,n,u={},t[3],y),l&&(d.static=p,d.private=f,c=d.access={has:f?T=>ff(s,T):T=>n in T},l^3&&(c.get=f?T=>(l^1?Du:mf)(T,s,l^4?o:b.get):T=>T[n]),l>2&&(c.set=f?(T,w)=>Pu(T,s,w,l^4?o:b.set):(T,w)=>T[n]=w)),a=(0,r[v])(l?l<4?f?o:b[g]:l>4?void 0:{get:b.get,set:b.set}:s,d),u._=1,l^4||a===void 0?pr(a)&&(l>4?h.unshift(a):l?f?o=a:b[g]=a:s=a):typeof a!="object"||a===null?fr("Object expected"):(pr(i=a.get)&&(b.get=i),pr(i=a.set)&&(b.set=i),pr(i=a.init)&&h.unshift(i));return l||pf(t,s),b&&En(s,n,b),f?l^4?o:b:s};var Ci=(t,e,n)=>e.has(t)||fr("Cannot "+n),ff=(t,e)=>Object(e)!==e?fr('Cannot use the "in" operator on this value'):t.has(e),Du=(t,e,n)=>(Ci(t,e,"read from private field"),n?n.call(t):e.get(t));var Pu=(t,e,n,r)=>(Ci(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),mf=(t,e,n)=>(Ci(t,e,"access private method"),n);var yt,R,X,G,Ye,Be,Ke,de,O,M,Rt,_n,wo,Mn,ko,xo,On,mr,hr,gr,Cn,se=tt(()=>{"use strict";yt=Symbol.for("graphrefly/START"),R=Symbol.for("graphrefly/DATA"),X=Symbol.for("graphrefly/DIRTY"),G=Symbol.for("graphrefly/RESOLVED"),Ye=Symbol.for("graphrefly/INVALIDATE"),Be=Symbol.for("graphrefly/PAUSE"),Ke=Symbol.for("graphrefly/RESUME"),de=Symbol.for("graphrefly/TEARDOWN"),O=Symbol.for("graphrefly/COMPLETE"),M=Symbol.for("graphrefly/ERROR"),Rt=Object.freeze([X]),_n=Object.freeze([G]),wo=Object.freeze([Ye]),Mn=Object.freeze([yt]),ko=Object.freeze([O]),xo=Object.freeze([de]),On=Object.freeze([Rt]),mr=Object.freeze([_n]),hr=Object.freeze([wo]),gr=Object.freeze([ko]),Cn=Object.freeze([xo])});function Ai(t){return{name:"dag-cbor",version:1,contentType:"application/dag-cbor",encode:e=>t.encode(e),decode:(e,n)=>t.decode(e)}}function Li(t,e){return{name:"dag-cbor-zstd",version:1,contentType:"application/dag-cbor+zstd",encode:n=>e.compressSync(t.encode(n)),decode:(n,r)=>t.decode(e.decompressSync(n))}}function yr(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 s=2+n.length+2+e.length;if(s>4294967295)throw new Error(`encodeEnvelope: total envelope size ${s} exceeds 2^32-1 bytes (payload ${e.length} bytes)`);let o=new Uint8Array(s),i=0;return o[i++]=An,o[i++]=n.length,o.set(n,i),i+=n.length,o[i++]=r>>>8&255,o[i++]=r&255,o.set(e,i),o}function br(t,e){if(t.length<Ku)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${Ku})`);let n=0,r=t[n++];if(r!==An)throw new Error(`decodeEnvelope: unsupported envelope version ${r} (expected ${An})`);let s=t[n++];if(s===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(n+s+2>t.length)throw new Error(`decodeEnvelope: envelope truncated (need ${n+s+2} bytes, have ${t.length})`);let o=new TextDecoder().decode(t.subarray(n,n+s));n+=s;let i=(t[n]<<8|t[n+1])>>>0;n+=2;let a=t.subarray(n),u=e.lookupCodec(o);if(u==null)throw new Error(`decodeEnvelope: codec "${o}" not registered (envelope codec_v=${i})`);return{codec:u,codecVersion:i,payload:a}}function vr(t){t.registerCodec(Ro)}function Ii(t){if(t.length===0)throw new Error("WAL is empty \u2014 need at least one full snapshot");let e=t[0];if(e.mode!=="full")throw new Error("WAL must start with a full record carrying a baseline snapshot");let n=JSON.parse(JSON.stringify(e.snapshot)),r=e.seq;for(let s=1;s<t.length;s++){let o=t[s];if(o.seq<=r)throw new Error(`WAL chain broken at index ${s}: seq=${o.seq} must exceed prev seq=${r}`);if(o.mode==="full"){n=JSON.parse(JSON.stringify(o.snapshot)),r=o.seq;continue}let i=o.diff;for(let u of i.nodesRemoved)delete n.nodes[u];let a=i.nodesAddedFull;if(a!=null)for(let[u,d]of Object.entries(a))n.nodes[u]=JSON.parse(JSON.stringify(d));for(let u of i.nodesChanged){let d=n.nodes[u.path];d!=null&&(d[u.field]=u.to)}r=o.seq}return n}var Ro,An,Ku,So=tt(()=>{"use strict";Ro={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)}};An=1,Ku=4});function St(t){if(t==null)return bt;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var bt,Tr=tt(()=>{"use strict";bt={type:"system",id:""}});function Zt(){return Ln>0||wr}function Hu(){return Ln>0}function xr(t){Ln>0?kr.push(t):t()}function Y(t){Ln+=1;let e=!1;try{t()}catch(n){throw e=!0,n}finally{if(Ln-=1,Ln===0)if(e){if(!wr){let n=kr.splice(0);for(let r of n)try{r()}catch{}Qt.length=0,Xt.length=0,In.length=0}}else hf()}}function hf(){let t=!wr;t&&(wr=!0);let e=[],n=0;try{for(;Qt.length>0||Xt.length>0||In.length>0||t&&kr.length>0;){if(t&&kr.length>0){let o=kr.splice(0);for(let i of o)try{i()}catch(a){e.push(a)}continue}if(n+=1,n>1e3)throw Qt.length=0,Xt.length=0,In.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let s=(Qt.length>0?Qt:Xt.length>0?Xt:In).splice(0);for(let o of s)try{o()}catch(i){e.push(i)}}}finally{t&&(wr=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function Nt(t,e,n){if(e.length===0)return;if(e.length===1){let d=n(e[0][0]);if(d<3||!Zt()){t(e);return}(d>=5?In:d===4?Xt:Qt).push(()=>t(e));return}let r=e.length,s=r,o=r,i=r,a=0;for(;a<r&&n(e[a][0])<3;)a++;for(s=a;a<r&&n(e[a][0])===3;)a++;for(o=a;a<r&&n(e[a][0])===4;)a++;i=a;let u=Zt();if(s>0){let d=e.slice(0,s);t(d)}if(o>s){let d=e.slice(s,o);u?Qt.push(()=>t(d)):t(d)}if(i>o){let d=e.slice(o,i);u?Xt.push(()=>t(d)):t(d)}if(r>i){let d=e.slice(i,r);u?In.push(()=>t(d)):t(d)}}var Ln,wr,Qt,Xt,In,kr,Ce=tt(()=>{"use strict";Ln=0,wr=!1,Qt=[],Xt=[],In=[],kr=[]});function F(){return Math.trunc(performance.now()*1e6)}function ce(){return Date.now()*1e6}var Ne=tt(()=>{"use strict"});function Rr(t){t.registerMessageType(yt,{tier:0,wireCrossing:!1}),t.registerMessageType(X,{tier:1,wireCrossing:!1}),t.registerMessageType(Ye,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(Be,{tier:2,wireCrossing:!1}),t.registerMessageType(Ke,{tier:2,wireCrossing:!1}),t.registerMessageType(R,{tier:3,wireCrossing:!0}),t.registerMessageType(G,{tier:3,wireCrossing:!0}),t.registerMessageType(O,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(M,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(de,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var en,Di=tt(()=>{"use strict";se();en=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 qu(t){return Array.isArray(t)?[...t]:[t]}function gf(t,e){return t.has(e)||t.has("*")}function tn(t){let e=[];return t((s,o)=>{e.push({kind:"allow",actions:new Set(qu(s)),where:o?.where??(()=>!0)})},(s,o)=>{e.push({kind:"deny",actions:new Set(qu(s)),where:o?.where??(()=>!0)})}),(s,o)=>{let i=!1,a=!1;for(let u of e)gf(u.actions,o)&&u.where(s)&&(u.kind==="deny"?i=!0:a=!0);return i?!1:a}}function Sr(t){return tn((e,n)=>{for(let r of t){let s=r.actorType==null?null:new Set(Array.isArray(r.actorType)?r.actorType:[r.actorType]),o=r.actorId==null?null:new Set(Array.isArray(r.actorId)?r.actorId:[r.actorId]),i=Object.entries(r.claims??{}),a=u=>{if(s!==null&&!s.has(String(u.type))||o!==null&&!o.has(String(u.id??"")))return!1;for(let[d,c]of i)if(u[d]!==c)return!1;return!0};r.effect==="deny"?n(r.action,{where:a}):e(r.action,{where:a})}})}function Nr(t){let e=yf.filter(n=>t({type:n,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(n=>n==="human"||n==="llm"||n==="system")?"both":e.length===1?e[0]:e.join("+")}var rt,yf,nn=tt(()=>{"use strict";rt=class extends Error{actor;action;nodeName;constructor(e,n){super(n??`GuardDenied: action "${String(e.action)}" denied for actor type "${String(e.actor.type)}"`),this.name="GuardDenied",this.actor=e.actor,this.action=e.action,this.nodeName=e.nodeName}get node(){return this.nodeName}};yf=["human","llm","wallet","system"]});function Pi(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(Pi);if(typeof t=="object"&&t!==null){let e={};for(let n of Object.keys(t).sort())e[n]=Pi(t[n]);return e}return null}function Tf(t){let e=vf.encode(t),n=e.length,r=n*8,s=n+9+63&-64,o=new Uint8Array(s);o.set(e),o[n]=128;let i=new DataView(o.buffer);i.setUint32(s-4,r>>>0,!1),i.setUint32(s-8,Math.floor(r/4294967296)>>>0,!1);let a=1779033703,u=3144134277,d=1013904242,c=2773480762,l=1359893119,p=2600822924,f=528734635,m=1541459225,g=new Uint32Array(64),h=(b,v)=>b>>>v|b<<32-v;for(let b=0;b<s;b+=64){for(let C=0;C<16;C++)g[C]=i.getUint32(b+C*4,!1);for(let C=16;C<64;C++){let I=g[C-15],A=g[C-2],P=h(I,7)^h(I,18)^I>>>3,U=h(A,17)^h(A,19)^A>>>10;g[C]=g[C-16]+P+g[C-7]+U>>>0}let v=a,T=u,w=d,k=c,x=l,S=p,E=f,L=m;for(let C=0;C<64;C++){let I=h(x,6)^h(x,11)^h(x,25),A=x&S^~x&E,P=L+I+A+bf[C]+g[C]>>>0,U=h(v,2)^h(v,13)^h(v,22),z=v&T^v&w^T&w,D=U+z>>>0;L=E,E=S,S=x,x=k+P>>>0,k=w,w=T,T=v,v=P+D>>>0}a=a+v>>>0,u=u+T>>>0,d=d+w>>>0,c=c+k>>>0,l=l+x>>>0,p=p+S>>>0,f=f+E>>>0,m=m+L>>>0}let y=b=>b.toString(16).padStart(8,"0");return y(a)+y(u)+y(d)+y(c)+y(l)+y(p)+y(f)+y(m)}function Gt(t){let e=Pi(t??null),n=JSON.stringify(e);return Tf(n).slice(0,16)}function wf(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),n=e()+e()+e()+e();return`${n.slice(0,8)}-${n.slice(8,12)}-4${n.slice(13,16)}-${(parseInt(n.slice(16,17),16)&3|8).toString(16)}${n.slice(17,20)}-${n.slice(20,32)}`}function Dn(t,e,n){let r=n?.id??wf();if(t===0)return{id:r,version:0};let o=(n?.hash??Gt)(e);return{id:r,version:0,cid:o,prev:null}}function Er(t,e,n){t.version+=1,"cid"in t&&(t.prev=t.cid,t.cid=n(e))}function Gi(t){return"cid"in t}var bf,vf,No=tt(()=>{"use strict";bf=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]),vf=new TextEncoder});function zu(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function Fi(t){t.prevData=void 0,t.dirty=!1,t.involvedThisWave=!1,t.dataBatch.length=0,t.terminal=void 0}function Eo(t){return t.length===0?t:typeof t[0]=="symbol"?[t]:t}function ji(t){if($e._isFrozen())throw new Error("configure() called after a node was created \u2014 the default GraphReFlyConfig is frozen. Call configure(...) at application startup, before any node factories run.");t($e)}function V(t,e,n){let r=Ju(t)?t:[],s=typeof t=="function"?t:typeof e=="function"?e:void 0,o={};return Ju(t)?o=($i(e)?e:n)??{}:$i(t)?o=t:o=($i(e)?e:n)??{},new Ae(r,s,o)}var Wu,Uu,kf,xf,$e,Ae,Ju,$i,_e=tt(()=>{"use strict";So();Tr();Ce();Ne();Di();nn();se();No();Wu=()=>{},Uu=100;kf=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},xf=(t,e,n,r)=>{let s=t;if(s._status==="completed"||s._status==="errored")return;let o=s._cached,i=o===void 0?[Mn]:[Mn,[R,o]];s._status==="dirty"&&i.push(Rt),Nt(e,i,s._config.tierOf)},$e=new en({onMessage:kf,onSubscribe:xf});Rr($e);vr($e);Ae=class t{_optsName;_describeKind;meta;_hasMeta;_config;_deps;_sinks=null;_sinkCount=0;_cached;_status;_cleanup;_store={};_waveHasNewData=!1;_hasNewTerminal=!1;_hasCalledFnOnce=!1;_paused=!1;_pendingWave=!1;_isExecutingFn=!1;_pendingRerun=!1;_rerunDepth=0;_dirtyDepCount=0;_batchPendingMessages=null;_pauseLocks=null;_pauseBuffer=null;_fn;_equals;_resubscribable;_resetOnTeardown;_autoComplete;_autoError;_pausable;_partial;_guard;_extraGuards;_hashFn;_versioning;_versioningLevel;_lastMutation;_inspectorHooks;_actions;constructor(e,n,r){this._config=r.config??$e,this._config.onMessage,this._optsName=r.name,this._describeKind=r.describeKind,this._equals=r.equals??Object.is,this._resubscribable=r.resubscribable??!1,this._resetOnTeardown=r.resetOnTeardown??!1,this._autoComplete=r.completeWhenDepsComplete??!0,this._autoError=r.errorWhenDepsError??!0,this._pausable=r.pausable??!0,this._guard=r.guard,this._fn=n,this._partial=r.partial??!1,this._cached=r.initial!==void 0?r.initial:void 0,this._status=e.length===0&&n==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=r.versioningHash??this._config.defaultHashFn??Gt;let s=r.versioning??this._config.defaultVersioning;this._versioningLevel=s,this._versioning=s!=null?Dn(s,this._cached===void 0?void 0:this._cached,{id:r.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(zu);let o={};for(let[a,u]of Object.entries(r.meta??{})){let d={initial:u,name:`${r.name??"node"}:meta:${a}`,describeKind:"state",config:this._config};r.guard!=null&&(d.guard=r.guard),o[a]=new t([],void 0,d)}Object.freeze(o),this.meta=o,this._hasMeta=Object.keys(o).length>0;let i=this;this._actions={emit(a){i._emit([[R,a]])},down(a){i._emit(Eo(a))},up(a){i._emitUp(Eo(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 s=n?.hash??this._hashFn;s!==this._hashFn&&(this._hashFn=s);let o=this._cached===void 0?void 0:this._cached,i=this._versioning,a=i?.id??n?.id,u=i?.version??0,d=Dn(e,o,{id:a,hash:s});d.version=u,this._versioning=d,this._versioningLevel=e}_setInspectorHook(e){return e==null?()=>{}:(this._inspectorHooks==null&&(this._inspectorHooks=new Set),this._inspectorHooks.add(e),()=>{this._inspectorHooks?.delete(e),this._inspectorHooks?.size===0&&(this._inspectorHooks=void 0)})}_pushGuard(e){return this._extraGuards==null&&(this._extraGuards=new Set),this._extraGuards.add(e),()=>{this._extraGuards?.delete(e),this._extraGuards?.size===0&&(this._extraGuards=void 0)}}allowsObserve(e){if(this._guard==null&&this._extraGuards==null)return!0;let n=St(e);if(this._guard!=null&&!this._guard(n,"observe"))return!1;if(this._extraGuards!=null){for(let r of this._extraGuards)if(!r(n,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let n=this._guard!=null||this._extraGuards!=null,r=e?.actor!=null;if(!n&&!r)return;let s=St(e?.actor),o=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(s,o))throw new rt({actor:s,action:o,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(s,o))throw new rt({actor:s,action:o,nodeName:this.name})}this._lastMutation={actor:s,timestamp_ns:ce()}}down(e,n){let r=Eo(e);r.length!==0&&(this._checkGuard(n),this._emit(r))}emit(e,n){this._checkGuard(n),this._emit([[R,e]])}up(e,n){if(this._deps.length===0)return;let r=Eo(e);if(r.length===0)return;this._checkGuard(n);let s=n??{internal:!0};this._validateUpTiers(r);for(let o of this._deps)o.node.up?.(r,s)}_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 s=n(r[0]);if(s===3||s===4)throw new Error(`Node "${this.name}": tier-${s} messages cannot flow up \u2014 DATA/RESOLVED/COMPLETE/ERROR are downstream-only. Use \`down(...)\` for value delivery; \`up(...)\` is for control signals (DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN).`)}}subscribe(e,n){if(n!=null&&this._guard!=null){let u=St(n);if(!this._guard(u,"observe"))throw new rt({actor:u,action:"observe",nodeName:this.name})}let s=this._isTerminal&&this._resubscribable;if(s){this._cached=void 0,this._status="sentinel",this._store={},this._hasCalledFnOnce=!1,this._waveHasNewData=!1,this._hasNewTerminal=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._isExecutingFn=!1,this._rerunDepth=0,this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null;for(let u of this._deps)Fi(u);if(this._partial===!1){for(let u of this._deps)if(u.prevData!==void 0||u.dataBatch.length!==0||u.terminal!==void 0||u.dirty)throw new Error(`resubscribable-reset invariant: DepRecord not fully reset for node ${this._optsName??"(anonymous)"}`)}}this._sinkCount+=1;let o;try{o=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:s},this._actions)}catch(u){throw this._sinkCount-=1,u}this._sinks==null?this._sinks=e:typeof this._sinks=="function"?this._sinks=new Set([this._sinks,e]):this._sinks.add(e);let i=this._isTerminal;if(this._sinkCount===1&&!i)try{this._activate()}catch(u){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof o=="function")try{o()}catch{}throw u}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let a=!1;return()=>{a||(a=!0,this._sinkCount-=1,this._removeSink(e),typeof o=="function"&&o(),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 s=r,o=this._deps[r];o.unsub=Wu,o.unsub=o.node.subscribe(i=>{if(o.unsub===null)return;let a=this._config.tierOf,u=!1;for(let d of i)a(d[0])>=3&&(u=!0),this._config.onMessage(this,d,{direction:"down-in",depIndex:s},this._actions);u&&this._maybeRunFnOnSettlement()}),n++}}catch(r){this._deps[n].unsub=null;for(let s=0;s<n;s++){let o=this._deps[s];if(o.unsub!=null){let i=o.unsub;o.unsub=null;try{i()}catch{}Fi(o)}}throw this._dirtyDepCount=0,r}}_addDep(e){for(let s=0;s<this._deps.length;s++)if(this._deps[s].node===e)return s;let n=this._deps.length,r=zu(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(On),r.unsub=Wu;try{r.unsub=e.subscribe(s=>{if(r.unsub===null)return;let o=this._config.tierOf,i=!1;for(let a of s)o(a[0])>=3&&(i=!0),this._config.onMessage(this,a,{direction:"down-in",depIndex:n},this._actions);i&&this._maybeRunFnOnSettlement()})}catch(s){throw r.unsub=null,this._deps.pop(),this._dirtyDepCount--,s}return n}_deactivate(e=!1){let n=this._cleanup;if(this._cleanup=void 0,typeof n=="function")try{n()}catch(r){this._emit([[M,this._wrapFnError("cleanup threw",r)]])}else if(n!=null&&typeof n=="object"){let r=n.deactivate;if(typeof r=="function")try{r()}catch(s){this._emit([[M,this._wrapFnError("cleanup.deactivate threw",s)]])}}for(let r of this._deps){if(r.unsub!=null){let s=r.unsub;r.unsub=null;try{s()}catch{}}Fi(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],s=n[0];if(this._inspectorHooks!=null){let o={kind:"dep_message",depIndex:e,message:n};for(let i of this._inspectorHooks)i(o)}if(s!==yt){if(s===X){this._depDirtied(r);return}if(s===Ye){if(this._depInvalidated(r),this._cached===void 0)return;this._emit(hr);return}if(s===Be||s===Ke){this._emit([n]);return}if(s===de){this._emit(Cn);return}if(s===R)this._depSettledAsData(r,n[1]);else if(s===G)this._depSettledAsResolved(r);else if(s===O)this._depSettledAsTerminal(r,!0);else if(s===M)this._depSettledAsTerminal(r,n[1]);else{this._emit([n]);return}if(!this._fn){(s===R||s===G)&&this._emit([n]),(s===O||s===M)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(On))}_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(mr),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(n=>n.terminal!==void 0&&n.terminal!==!0);if(e!=null){this._autoError&&this._emit([[M,e.terminal]]);return}this._autoComplete&&this._deps.every(n=>n.terminal!==void 0)&&this._emit(gr)}_execFn(){if(!this._fn||this._isTerminal&&!this._resubscribable)return;if(this._isExecutingFn){this._pendingRerun=!0;return}let e=this._cleanup;if(typeof e=="function"){this._cleanup=void 0;try{e()}catch(i){this._emit([[M,this._wrapFnError("cleanup threw",i)]]);return}}else if(e!=null&&typeof e=="object"){let i=e.beforeRun;if(typeof i=="function"){e.beforeRun=void 0;try{i()}catch(a){this._emit([[M,this._wrapFnError("cleanup.beforeRun threw",a)]]);return}}}let n=this._deps.map(i=>i.involvedThisWave?i.dataBatch.length>0?[...i.dataBatch]:[]:void 0),r=this._deps.map(i=>i.prevData);for(let i=0;i<this._deps.length;i++){let a=n[i];a!=null&&a.length>0&&(this._deps[i].prevData=a[a.length-1])}let s=this._deps.map(i=>i.terminal),o={prevData:r,terminalDeps:s,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,o);if(typeof i=="function")this._cleanup=i;else if(i!=null&&typeof i=="object"){let a=i;(typeof a.beforeRun=="function"||typeof a.deactivate=="function"||typeof a.invalidate=="function")&&(this._cleanup=i)}}catch(i){this._emit([[M,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>Uu?(this._rerunDepth=0,this._emit([[M,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${Uu} \u2014 likely a reactive cycle`)]])):this._maybeRunFnOnSettlement()):this._rerunDepth=0,this._clearWaveFlags()}}_clearWaveFlags(){this._waveHasNewData=!1,this._hasNewTerminal=!1;for(let e of this._deps)e.involvedThisWave=!1,e.dataBatch.length=0}_wrapFnError(e,n){let r=n instanceof Error?n.message:String(n);return new Error(`Node "${this.name}": ${e}: ${r}`,{cause:n})}_frameBatch(e){let n=this._config.tierOf;if(e.length===1)return n(e[0][0])===3&&this._status!=="dirty"?[Rt,e[0]]:e;let r=!0,s=!1,o=!1,i=-1;for(let u of e){let d=n(u[0]);d<i&&(r=!1),d===3&&(s=!0),u[0]===X&&(o=!0),i=d}let a=e;if(!r){let u=e.map((d,c)=>({m:d,i:c,tier:n(d[0])}));u.sort((d,c)=>d.tier-c.tier||d.i-c.i),a=u.map(d=>d.m)}if(s&&!o&&this._status!=="dirty"){let u=0;for(;u<a.length&&n(a[u][0])===0;)u++;return u===0?[Rt,...a]:[...a.slice(0,u),Rt,...a.slice(u)]}return a}_emit(e){if(e.length===0)return;for(let a=0;a<e.length;a++){let u=e[a];if(u[0]===M&&u[1]===void 0)throw new TypeError('[ERROR, payload] requires a non-undefined payload (spec \xA71.2). Pass an Error object or domain tag instead \u2014 e.g. node.down([[ERROR, new Error("reason")]])')}let n=e;if(this._isTerminal&&!this._resubscribable){let a=e.filter(u=>u[0]===de||u[0]===Ye);if(a.length===0)return;n=a}n=this._frameBatch(n);let s=null;for(let a=0;a<n.length;a++){let u=n[a],d=u[0];if(d!==Be&&d!==Ke){s?.push(u);continue}if(u.length<2)throw new Error(`Node "${this.name}": [[${d===Be?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let c=!0;if(this._pausable!==!1){let l=u[1];if(d===Be)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(l),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(l))c=!1;else if(this._pauseLocks.delete(l),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let p=this._pauseBuffer;this._pauseBuffer=[],this._emit(p)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}c?s?.push(u):s==null&&(s=n.slice(0,a))}if(s!=null){if(s.length===0)return;n=s}if(this._hasMeta&&n.some(a=>a[0]===de))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(Cn)}catch{}let{finalMessages:o,equalsError:i}=this._updateState(n);if(o.length>0&&this._config.inspectorEnabled){let a=this._config.globalInspector;if(a!=null)try{a({kind:"emit",node:this,messages:o})}catch{}}if(o.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let a=this._config.tierOf,u=[];for(let d of o)a(d[0])===3?this._pauseBuffer.push(d):u.push(d);u.length>0&&this._dispatchOrAccumulate(u)}else this._dispatchOrAccumulate(o);i!=null&&this._emit([[M,i]])}_updateState(e){let n=this._config.tierOf,r,s,o=-1,i=0;for(let c of e)n(c[0])===3&&i++;let a=i<=1,u=-1;if(this._versioning!=null&&i>1){for(let c=e.length-1;c>=0;c--)if(e[c][0]===R){u=c;break}}for(let c=0;c<e.length;c++){let l=e[c],p=l[0];if(p===R){if(l.length>=2){let f=!1;if(a&&this._cached!==void 0)try{f=this._equals(this._cached,l[1])}catch(m){s=this._wrapFnError("equals threw",m),o=c;break}if(f){r==null&&(r=e.slice(0,c)),r.push(_n),this._status="resolved";continue}this._cached=l[1],this._versioning!=null&&(u<0||c===u)&&Er(this._versioning,l[1],this._hashFn)}this._status="settled",r?.push(l)}else if(r?.push(l),p===X)this._status="dirty";else if(p===G)this._status="resolved";else if(p===O){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===M){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===Ye){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===de&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let d=o>=0?r??e.slice(0,o):r??e;return s!=null?{finalMessages:d,equalsError:s}:{finalMessages:d}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let n=[...this._sinks];for(let r of n)r(e)};_dispatchOrAccumulate(e){if(Hu()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],xr(()=>this._flushBatchPending()));for(let n of e)this._batchPendingMessages.push(n);return}Nt(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let n=this._frameBatch(e);Nt(this._deliverToSinks,n,this._config.tierOf)}},Ju=t=>Array.isArray(t),$i=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function N(t,e){return V([],{...e,initial:t})}function $(t,e){return V((r,s,o)=>t(s,o)??void 0,{describeKind:"producer",...e})}function _(t,e,n){return V(t,(s,o,i)=>{let a=s.map((u,d)=>u!=null&&u.length>0?u.at(-1):i.prevData[d]);o.emit(e(a,i))},{describeKind:"derived",...n})}function le(t,e,n){return V(t,(s,o,i)=>{let a=s.map((u,d)=>u!=null&&u.length>0?u.at(-1):i.prevData[d]);return e(a,o,i)??void 0},{describeKind:"effect",...n})}function _r(t,e,n){let r=new Map;return t.forEach((s,o)=>{r.set(s,o)}),_(t,(s,o)=>e(a=>{let u=r.get(a);if(u==null)throw new Error(`dynamicNode: untracked dep "${a.name??"<unnamed>"}"`);return s[u]},o),n)}function rn(t,e){let n,r=new Map,s=(o,i,a)=>{let u=!1,d=c=>{let l=r.get(c);if(l!==void 0){if(l<o.length){let f=o[l];return f!=null&&f.length>0?f.at(-1):a.prevData[l]}return c.cache}u=!0;let p=n._addDep(c);return r.set(c,p),c.cache};try{let c=t(d,a);u||(i.emit(c),a.store.__autoTrackLastDiscoveryError!=null&&delete a.store.__autoTrackLastDiscoveryError)}catch(c){if(!u)throw c;a.store.__autoTrackLastDiscoveryError=c}};return n=new Ae([],s,{describeKind:"derived",...e}),n}function Bi(t,...e){let n=t;for(let r of e)n=r(n);return n}var Q=tt(()=>{"use strict";_e()});function Cr(t,e,n){let r=new Set;for(let s of t.split(",")){let[o,i]=s.split("/"),a=i?Number.parseInt(i,10):1;if(Number.isNaN(a)||a<1)throw new Error(`Invalid cron step: ${s}`);let u,d;if(o==="*")u=e,d=n;else if(o.includes("-")){let[c,l]=o.split("-");u=Number.parseInt(c,10),d=Number.parseInt(l,10)}else u=Number.parseInt(o,10),d=u;if(Number.isNaN(u)||Number.isNaN(d))throw new Error(`Invalid cron field: ${t}`);if(u<e||d>n)throw new Error(`Cron field out of range: ${t} (${e}-${n})`);if(u>d)throw new Error(`Invalid cron range: ${u}-${d} in ${t}`);for(let c=u;c<=d;c+=a)r.add(c)}return r}function Io(t){let e=t.trim().split(/\s+/);if(e.length!==5)throw new Error(`Invalid cron: expected 5 fields, got ${e.length}`);return{minutes:Cr(e[0],0,59),hours:Cr(e[1],0,23),daysOfMonth:Cr(e[2],1,31),months:Cr(e[3],1,12),daysOfWeek:Cr(e[4],0,6)}}function Do(t,e){return t.minutes.has(e.getMinutes())&&t.hours.has(e.getHours())&&t.daysOfMonth.has(e.getDate())&&t.months.has(e.getMonth()+1)&&t.daysOfWeek.has(e.getDay())}var Hi=tt(()=>{"use strict"});var ld={};we(ld,{NS_PER_MS:()=>He,NS_PER_SEC:()=>it,constant:()=>Po,decorrelatedJitter:()=>jo,exponential:()=>Fo,fibonacci:()=>$o,linear:()=>Go,resolveBackoffPreset:()=>Ft,withMaxAttempts:()=>qi});function sn(t){return t<0?0:t}function Af(t,e){return e==="none"?t:e==="full"?Math.random()*t:t/2+Math.random()*(t/2)}function Lf(t,e){return t+Math.random()*(e-t)}function Po(t){let e=sn(t);return()=>e}function Go(t,e){let n=sn(t),r=e===void 0?n:sn(e);return s=>n+r*Math.max(0,s)}function Fo(t){let e=sn(t?.baseNs??1e8),n=t?.factor!==void 0&&t.factor<1?1:t?.factor??2,r=sn(t?.maxDelayNs??30*1e9),s=t?.jitter??"none";return o=>{let i;if(e===0)i=0;else if(n===1)i=e;else{let a=r/e,u=1;for(let d=0;d<Math.max(0,o);d++){if(u>=a){u=a;break}u*=n}i=e*u,i>r&&(i=r)}return Af(i,s)}}function $o(t=100*1e6,e=30*1e9){let n=sn(t),r=sn(e);function s(o){if(o<=0)return 1;let i=1,a=2;for(let u=1;u<o;u++){let d=i+a;i=a,a=d}return a}return o=>{let i=s(o)*n;return i<=r?i:r}}function jo(t=100*1e6,e=30*1e9){return(n,r,s)=>{let i=Math.min(e,(s??t)*3);return Lf(t,i)}}function qi(t,e){return(n,r,s)=>n>=e?null:t(n,r,s)}function Ft(t){if(t==="constant")return Po(1*1e9);if(t==="linear")return Go(1*1e9);if(t==="exponential")return Fo();if(t==="fibonacci")return $o();if(t==="decorrelatedJitter")return jo();throw new Error(`Unknown backoff preset: "${String(t)}". Use one of: constant, linear, exponential, fibonacci, decorrelatedJitter`)}var He,it,Kn=tt(()=>{"use strict";He=1e6,it=1e9});var Le,vt=tt(()=>{"use strict";Le=class{_timer;_gen=0;start(e,n){this.cancel(),this._gen+=1;let r=this._gen;this._timer=setTimeout(()=>{this._timer=void 0,r===this._gen&&n()},e)}cancel(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}get pending(){return this._timer!==void 0}}});var fd={};we(fd,{CircuitOpenError:()=>lt,RateLimiterOverflowError:()=>an,TimeoutError:()=>un,circuitBreaker:()=>Tt,fallback:()=>Un,rateLimiter:()=>Wn,retry:()=>Hn,retrySource:()=>$t,timeout:()=>zn,tokenBucket:()=>jt,withBreaker:()=>qn,withStatus:()=>Bt});function dn(t){return{describeKind:"derived",...t}}function If(t){return t<0?0:t}function Bo(t){return t[1]}function pd(t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError("backoff strategy must return a finite number");return t<0?0:t}function Hn(t,e){let n=e?.count,r=e?.backoff,s=n!==void 0?n:r===void 0?0:2147483647;if(s<0)throw new RangeError("retry count must be >= 0");let o=r===void 0?null:typeof r=="string"?Ft(r):r;return $(i=>{let a=0,u=!1,d=null,c,l=new Le;function p(){c?.(),c=void 0}function f(g){if(u)return;if(a>=s){p(),i.down([[M,g]]);return}let h=o===null?0:o(a,g,d);if(h==null){p(),i.down([[M,g]]);return}let y;try{y=pd(h)}catch{p(),i.down([[M,g]]);return}d=y,a+=1,p();let b=y>0?y/1e6:1;l.start(b,()=>{u||m()})}function m(){l.cancel(),p(),c=t.subscribe(g=>{if(!u)for(let h of g){let y=h[0];if(y===X)i.down([[X]]);else if(y===R)a=0,d=null,i.emit(h[1]);else if(y===G)i.down([[G]]);else if(y===O)p(),i.down([[O]]);else if(y===M){f(Bo(h));return}else i.down([h])}})}return m(),()=>{u=!0,l.cancel(),p()}},{...dn(),initial:t.cache})}function $t(t,e){let n=e?.count,r=e?.backoff,s=n!==void 0?n:r===void 0?0:2147483647;if(s<0)throw new RangeError("retry count must be >= 0");let o=r===void 0?null:typeof r=="string"?Ft(r):r;return $(i=>{let a=0,u=!1,d=null,c,l=new Le;function p(){c?.(),c=void 0}function f(g){if(u)return;if(a>=s){p(),i.down([[M,g]]);return}let h=o===null?0:o(a,g,d);if(h==null){p(),i.down([[M,g]]);return}let y;try{y=pd(h)}catch{p(),i.down([[M,g]]);return}d=y,a+=1,p();let b=y>0?y/1e6:1;l.start(b,()=>{u||m()})}function m(){l.cancel(),p();let g;try{g=t()}catch(h){f(h);return}c=g.subscribe(h=>{if(!u)for(let y of h){let b=y[0];if(b===X)i.down([[X]]);else if(b===R)a=0,d=null,i.emit(y[1]);else if(b===G)i.down([[G]]);else if(b===O)p(),i.down([[O]]);else if(b===M){f(Bo(y));return}else i.down([y])}})}return m(),()=>{u=!0,l.cancel(),p()}},{...dn(),initial:e?.initial})}function Tt(t){let e=Math.max(1,t?.failureThreshold??5),n=If(t?.cooldownNs??30*1e9),r=t?.cooldown??null,s=Math.max(1,t?.halfOpenMax??1),o=t?.now??F,i="closed",a=0,u=0,d=0,c=n,l=0;function p(){if(!r)return n;let g=r(u);return g!==null?g:n}function f(){i="open",c=p(),d=o(),l=0}return{canExecute(){return i==="closed"?!0:i==="open"?o()-d>=c?(i="half-open",l=1,!0):!1:l<s?(l++,!0):!1},recordSuccess(){i==="half-open"?(i="closed",a=0,u=0):i==="closed"&&(a=0)},recordFailure(g){if(i==="half-open"){u++,f();return}i==="closed"&&(a++,a>=e&&f())},get state(){return i},get failureCount(){return a},reset(){i="closed",a=0,u=0,l=0}}}function qn(t,e){let n=e?.onOpen??"skip";return r=>{let s=V([],(o,i)=>{function a(){s.meta.breakerState.down([[R,t.state]])}let u=r.subscribe(d=>{for(let c of d){let l=c[0];l===X?i.down([[X]]):l===R?t.canExecute()?(a(),i.emit(c[1])):(a(),n==="error"?i.down([[M,new lt]]):i.down([[G]])):l===G?i.down([[G]]):l===O?(t.recordSuccess(),a(),i.down([[O]])):l===M?(t.recordFailure(Bo(c)),a(),i.down([c])):i.down([c])}});return a(),u},{...dn(),meta:{breakerState:t.state},completeWhenDepsComplete:!1,initial:r.cache});return{node:s,breakerState:s.meta.breakerState}}}function jt(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 s(o){if(e>0){let i=o-r;n=Math.min(t,n+i/1e9*e)}r=o}return{available(){return s(F()),n},tryConsume(o=1){if(o<=0)return!0;let i=F();return s(i),n>=o?(n-=o,!0):!1},putBack(o=1){o<=0||(s(F()),n=Math.min(t,n+o))}}}function Wn(t,e){let{maxEvents:n,windowNs:r}=e;if(n<=0)throw new RangeError("maxEvents must be > 0");if(r<=0)throw new RangeError("windowNs must be > 0");let s=e.maxBuffer;if(s!==void 0&&s<1)throw new RangeError("maxBuffer must be >= 1");let o=e.onOverflow??"drop-newest",i=n*1e9/r;return $(a=>{let u=jt(n,i),d=[],c=new Le,l=!1,p=1e9/i;function f(){for(;d.length>0;)if(u.tryConsume(1))a.emit(d.shift());else{c.start(Math.max(1,p/1e6),f);return}}let m=t.subscribe(g=>{for(let h of g){if(l)return;let y=h[0];if(y===X)a.down([[X]]);else if(y===R){if(s!==void 0&&d.length>=s){if(o!=="drop-newest")if(o==="drop-oldest")d.shift(),d.push(h[1]);else{l=!0,c.cancel(),d.length=0,a.down([[M,new an(s)]]);return}}else d.push(h[1]);f()}else if(y===G)a.down([[G]]);else if(y===O)l=!0,c.cancel(),d.length=0,a.down([[O]]);else if(y===M)l=!0,c.cancel(),d.length=0,a.down([h]);else if(y===de){l=!0,c.cancel(),d.length=0,a.down([h]);return}else a.down([h])}});return()=>{l=!0,c.cancel(),m()}},{...dn(),initial:t.cache})}function Bt(t,e){let n=e?.initialStatus??"pending",r=V([],(s,o)=>{let i=n;return r.meta.status.down([[R,n]]),r.meta.error.down([[R,null]]),t.subscribe(u=>{for(let d of u){let c=d[0];if(c===X)o.down([[X]]);else if(c===R)i==="errored"?Y(()=>{r.meta.error.down([[R,null]]),r.meta.status.down([[R,"active"]])}):r.meta.status.down([[R,"active"]]),i="active",o.emit(d[1]);else if(c===G)o.down([[G]]);else if(c===O)r.meta.status.down([[R,"completed"]]),i="completed",o.down([[O]]);else if(c===M){let l=Bo(d);Y(()=>{r.meta.error.down([[R,l]]),r.meta.status.down([[R,"errored"]])}),i="errored",o.down([d])}else o.down([d])}})},{...dn(),meta:{status:n,error:null},completeWhenDepsComplete:!1,resubscribable:!0,initial:t.cache});return{node:r,status:r.meta.status,error:r.meta.error}}function Df(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function Pf(t){return t!=null&&typeof t.then=="function"}function Gf(t){return t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function"}function Un(t,e){return $(n=>{let r,s;function o(){s?.(),s=void 0,Df(e)||Pf(e)||Gf(e)?r=W(e).subscribe(a=>{n.down(a)}):(n.emit(e),n.down([[O]]))}return s=t.subscribe(i=>{for(let a of i){let u=a[0];if(u===X)n.down([[X]]);else if(u===R)n.emit(a[1]);else if(u===G)n.down([[G]]);else if(u===O)n.down([[O]]);else if(u===M){o();return}else if(u===de){r?.(),n.down([a]);return}else n.down([a])}}),()=>{s?.(),r?.()}},{...dn(),initial:t.cache})}function zn(t,e){if(e<=0)throw new RangeError("timeoutNs must be > 0");return $(n=>{let r=!1,s=new Le;function o(){let a=e/1e6;s.start(a,()=>{r||(r=!0,i(),n.down([[M,new un(e)]]))})}let i=t.subscribe(a=>{for(let u of a){if(r)return;let d=u[0];if(d===X)n.down([[X]]);else if(d===R)o(),n.emit(u[1]);else if(d===G)n.down([[G]]);else if(d===O){s.cancel(),r=!0,n.down([[O]]);return}else if(d===M){s.cancel(),r=!0,n.down([u]);return}else if(d===de){s.cancel(),r=!0,n.down([u]);return}else n.down([u])}});return o(),()=>{r=!0,s.cancel(),i()}},{...dn(),initial:t.cache})}var lt,an,un,Et=tt(()=>{"use strict";Ce();Ne();se();_e();Q();Kn();Te();vt();lt=class extends Error{name="CircuitOpenError";constructor(){super("Circuit breaker is open")}};an=class extends Error{name="RateLimiterOverflowError";constructor(e){super(`rateLimiter buffer overflow (maxBuffer=${e})`)}};un=class extends Error{name="TimeoutError";constructor(e){super(`Timed out after ${e/1e6}ms`)}}});function ut(t){return{describeKind:"producer",...t}}function Ui(t){return/[\\^$+?.()|[\]{}]/.test(t)?`\\${t}`:t}function hd(t){let e="^";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="*"){t[n+1]==="*"?(e+=".*",n+=1):e+="[^/]*";continue}e+=Ui(r)}return e+="$",new RegExp(e)}function gd(t,e){for(let n of e)if(n.test(t))return!0;return!1}function Ff(t,e){let n=V([t],(s,o)=>{let i=s[0];if(i==null||i.length===0){o.down([[G]]);return}for(let a of i)o.emit(a)},{describeKind:"derived",initial:t.cache}),r=n.subscribe.bind(n);return n.subscribe=(s,o)=>(e(s),r(s,o)),n}function dt(t,e){let{signal:n,period:r,...s}=e??{};return $(o=>{let i=!1,a=0,u,d,c=()=>{i=!0,u!==void 0&&clearTimeout(u),d!==void 0&&clearInterval(d),n?.removeEventListener("abort",p)},l=()=>{i||(r!=null?(o.emit(a++),d=setInterval(()=>{i||o.emit(a++)},r)):(i=!0,n?.removeEventListener("abort",p),o.emit(a++),o.down([[O]])))},p=()=>{i||(c(),o.down([[M,n.reason]]))};if(n?.aborted){p();return}return u=setTimeout(l,t),n?.addEventListener("abort",p,{once:!0}),c},ut(s))}function yd(t){let{signal:e,...n}=t??{};return $(r=>{let s=!1,o,i,a=!1,u=!1,d=typeof requestAnimationFrame=="function"?requestAnimationFrame:void 0,c=typeof cancelAnimationFrame=="function"?cancelAnimationFrame:void 0,l=typeof document<"u"?document:void 0,p=()=>{o!==void 0&&c&&c(o),i!==void 0&&clearTimeout(i),o=void 0,i=void 0},f=()=>{s=!0,p(),a&&(e?.removeEventListener("abort",m),a=!1),u&&l&&(l.removeEventListener("visibilitychange",y),u=!1)},m=()=>{s||(f(),r.down([[M,e.reason]]))},g=b=>{s||(r.emit(b),h())},h=()=>{s||(d&&(!l||l.visibilityState!=="hidden")?o=d(g):i=setTimeout(()=>g(performance.now()),16))},y=()=>{s||(p(),h())};return e?.aborted?(m(),f):(e?.addEventListener("abort",m,{once:!0}),a=e!==void 0,l&&d&&(l.addEventListener("visibilitychange",y),u=!0),h(),f)},ut(n))}function Ko(t,e){let n=Io(t),{tickMs:r,output:s,...o}=e??{},i=r??6e4,a=s==="date";return $(u=>{let d=-1,c=()=>{let p=new Date,f=p.getFullYear()*1e8+(p.getMonth()+1)*1e6+p.getDate()*1e4+p.getHours()*100+p.getMinutes();f!==d&&Do(n,p)&&(d=f,u.emit(a?p:ce()))};c();let l=setInterval(c,i);return()=>clearInterval(l)},{...ut(o),name:o.name??`cron:${t}`})}function bd(t,e,n){let{capture:r,passive:s,once:o,...i}=n??{};return $(a=>{let u=c=>{a.emit(c)},d={capture:r,passive:s,once:o};return t.addEventListener(e,u,d),()=>t.removeEventListener(e,u,d)},ut(i))}function Ho(t,e){return $(n=>{let r=!1;try{for(let s of t){if(r)return;n.emit(s)}r||n.down([[O]])}catch(s){r||n.down([[M,s]])}return()=>{r=!0}},ut(e))}function $f(t){return t!=null&&typeof t.then=="function"}function Jn(t,e){let{signal:n,...r}=e??{};return $(s=>{let o=!1,i=()=>{o||(o=!0,s.down([[M,n.reason]]))};if(n?.aborted){i();return}return n?.addEventListener("abort",i,{once:!0}),Promise.resolve(t).then(a=>{o||(o=!0,n?.removeEventListener("abort",i),s.emit(a),s.down([[O]]))},a=>{o||(o=!0,n?.removeEventListener("abort",i),s.down([[M,a]]))}),()=>{o=!0,n?.removeEventListener("abort",i)}},ut(r))}function Ar(t,e){let{signal:n,...r}=e??{};return $(s=>{let o=new AbortController,i=()=>o.abort(n?.reason);n?.aborted?o.abort(n.reason):n?.addEventListener("abort",i,{once:!0});let a=n??o.signal,u=!1,d=t[Symbol.asyncIterator](),c=()=>{u||a.aborted||Promise.resolve(d.next()).then(l=>{if(!(u||a.aborted)){if(l.done){s.down([[O]]);return}s.emit(l.value),c()}},l=>{!u&&!a.aborted&&s.down([[M,l]])})};return c(),()=>{u=!0,n?.removeEventListener("abort",i),o.abort(),Promise.resolve(d.return?.()).catch(()=>{})}},ut(r))}function jf(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function W(t,e){if(jf(t))return t;if($f(t))return Jn(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return Ar(t,e);if(typeof n[Symbol.iterator]=="function")return Ho(t,e)}return zi(t)}function zi(...t){return Ho(t,void 0)}function vd(t){return $(e=>{e.down([[O]])},ut(t))}function Td(t){return $(()=>{},ut(t))}function wd(t,e){return $(n=>{n.down([[M,t]])},ut(e))}function Vt(t,e,n){return V([t],(s,o)=>{let i=s[0];if(i!=null&&i.length>0)for(let a of i)e(a)},{describeKind:"effect",...n}).subscribe(()=>{})}function kd(t,e){return V([t],(n,r,s)=>{s.store.buf||(s.store.buf=[]);let o=s.store.buf,i=n[0];if(i!=null&&i.length>0)for(let a of i)o.push(a);if(s.terminalDeps[0]===!0){r.emit([...o]),r.down([[O]]);return}(i==null||i.length===0)&&r.down([[G]])},{describeKind:"derived",completeWhenDepsComplete:!1,...e})}function xd(t,e){return $(n=>t.subscribe(r=>{n.down(r)}),{...ut(e),initial:t.cache})}function qo(t,e,n){if(e<1)throw new RangeError("replay expects bufferSize >= 1");let r=[],s=$(o=>t.subscribe(i=>{for(let a of i)a[0]===R&&(r.push(a[1]),r.length>e&&r.shift());o.down(i)}),{...ut(n),initial:t.cache});return Ff(s,o=>{for(let i of r)o([[R,i]])})}function Rd(t,e){return qo(t,1,e)}function Qe(t){return new Promise((e,n)=>{let r=!1,s=!1,o;o=t.subscribe(i=>{for(let a of i){if(r)return;if(a[0]===R){r=!0,e(a[1]),o?(o(),o=void 0):s=!0;return}if(a[0]===M){r=!0,n(a[1]),o?(o(),o=void 0):s=!0;return}if(a[0]===O){r=!0,n(new Error("completed without DATA")),o?(o(),o=void 0):s=!0;return}}}),s&&(o?.(),o=void 0)})}function Vo(t,e,n){return new Promise((r,s)=>{let o=!1,i=!1,a,u=n?.skipCurrent===!0;a=t.subscribe(d=>{for(let c of d){if(o)return;if(!(u&&c[0]===R)){if(c[0]===R){let l=c[1];if(e(l)){o=!0,r(l),a?(a(),a=void 0):i=!0;return}}if(c[0]===M){o=!0,s(c[1]),a?(a(),a=void 0):i=!0;return}if(c[0]===O){o=!0,s(new Error("completed without matching value")),a?(a(),a=void 0):i=!0;return}}}}),u=!1,i&&(a?.(),a=void 0)})}async function Wo(t,e){let n=e?.predicate??(o=>o!=null),r=e?.skipCurrent;if(e?.timeoutMs==null||e.timeoutMs<=0)return await Vo(t,n,{skipCurrent:r});if(Wi===void 0){let[o,i]=await Promise.all([Promise.resolve().then(()=>(Et(),fd)),Promise.resolve().then(()=>(Kn(),ld))]);Wi=o.timeout,md=i.NS_PER_MS}let s=Wi(t,e.timeoutMs*md);return await Vo(s,n,{skipCurrent:r})}function Uo(t,e){let n=new AbortController,r=e?.reason??new Error("cancelled via nodeSignal"),s,o=!1,i=()=>{s?(s(),s=void 0):o=!0};return s=t.subscribe(a=>{if(!n.signal.aborted)for(let u of a){if(u[0]===R&&u[1]===!0){n.abort(r),i();return}if(u[0]===M){n.abort(u[1]),i();return}if(u[0]===O){i();return}}}),o&&(s?.(),s=void 0),{signal:n.signal,dispose:()=>{s&&(s(),s=void 0)}}}function re(t){return t.subscribe(()=>{})}function Ji(t){let e=N(0);return{node:e,increment(){let n=e.cache??0;return n>=t?!1:(e.down([[X],[R,n+1]]),!0)},get(){return e.cache??0},atCap(){return(e.cache??0)>=t}}}var Wi,md,Sd,Te=tt(()=>{"use strict";Ne();se();_e();Q();Hi();Sd=qo});var pb={};we(pb,{COMPLETE:()=>O,COMPLETE_MSG:()=>ko,COMPLETE_ONLY_BATCH:()=>gr,CircuitOpenError:()=>lt,ContentAddressedMissError:()=>zr,DATA:()=>R,DEFAULT_ACTOR:()=>bt,DIRTY:()=>X,DIRTY_MSG:()=>Rt,DIRTY_ONLY_BATCH:()=>On,ENVELOPE_VERSION:()=>An,ERROR:()=>M,GRAPH_META_SEGMENT:()=>We,Graph:()=>q,GraphReFlyConfig:()=>en,GuardDenied:()=>rt,INVALIDATE:()=>Ye,INVALIDATE_MSG:()=>wo,INVALIDATE_ONLY_BATCH:()=>hr,JsonCodec:()=>Ro,NS_PER_MS:()=>He,NS_PER_SEC:()=>it,NativeIndexBackend:()=>Qr,NativeListBackend:()=>Xr,NativeLogBackend:()=>Gr,NativeMapBackend:()=>Wr,NativePubSubBackend:()=>Yr,NodeImpl:()=>Ae,PAUSE:()=>Be,RESOLVED:()=>G,RESOLVED_MSG:()=>_n,RESOLVED_ONLY_BATCH:()=>mr,RESUME:()=>Ke,RateLimiterOverflowError:()=>an,ResettableTimer:()=>Le,SIZEOF_OVERHEAD:()=>je,SIZEOF_SYMBOL:()=>ts,SNAPSHOT_VERSION:()=>pt,SNAPSHOT_WIRE_VERSION:()=>vo,START:()=>yt,START_MSG:()=>Mn,SurfaceError:()=>Ee,TEARDOWN:()=>de,TEARDOWN_MSG:()=>xo,TEARDOWN_ONLY_BATCH:()=>Cn,TimeoutError:()=>un,accessHintForGuard:()=>Nr,accountability:()=>ni,advanceVersion:()=>Er,ai:()=>Zs,asSurfaceError:()=>wi,audit:()=>Sc,autoTrackNode:()=>rn,awaitSettled:()=>Wo,batch:()=>Y,buffer:()=>Nc,bufferCount:()=>Ec,bufferTime:()=>Mc,cached:()=>Rd,canonicalJson:()=>Jr,cascadingCache:()=>Gl,catchError:()=>$c,checkpointToRedis:()=>Ml,checkpointToS3:()=>_l,circuitBreaker:()=>Tt,combine:()=>ma,combineLatest:()=>Pc,compat:()=>pa,concat:()=>bc,concatMap:()=>wc,configure:()=>ji,constant:()=>Po,contentAddressedStorage:()=>xs,core:()=>na,cqrs:()=>us,createDagCborCodec:()=>Ai,createDagCborZstdCodec:()=>Li,createGraph:()=>cr,createTransport:()=>Wt,createVersioning:()=>Dn,createWatermarkController:()=>Yn,csvRows:()=>cl,debounce:()=>ga,debounceTime:()=>Gc,decodeEnvelope:()=>br,decorrelatedJitter:()=>jo,defaultConfig:()=>$e,defaultHash:()=>Gt,delay:()=>xc,deleteSnapshot:()=>_i,demoShell:()=>oi,derived:()=>_,deserializeError:()=>yn,dictStorage:()=>zl,diffForWAL:()=>ss,diffSnapshots:()=>Ni,distill:()=>ws,distinctUntilChanged:()=>hc,domainTemplates:()=>si,downWithBatch:()=>Nt,dynamicNode:()=>_r,effect:()=>le,elementAt:()=>pc,empty:()=>vd,encodeEnvelope:()=>yr,escapeRegexChar:()=>Ui,exhaustMap:()=>Tc,explainPath:()=>Dr,exponential:()=>Fo,externalBundle:()=>bs,externalProducer:()=>mn,extra:()=>Ea,fallback:()=>Un,fibonacci:()=>$o,filter:()=>Xe,find:()=>lc,first:()=>vs,firstValueFrom:()=>Qe,firstWhere:()=>Vo,flatMap:()=>kc,forEach:()=>Vt,fromAny:()=>W,fromAsyncIter:()=>Ar,fromCSV:()=>dl,fromClickHouseWatch:()=>ml,fromCron:()=>Ko,fromDrizzle:()=>Il,fromEvent:()=>bd,fromHTTP:()=>wa,fromHTTPPoll:()=>Jc,fromHTTPStream:()=>zc,fromIter:()=>Ho,fromKafka:()=>sl,fromKysely:()=>Dl,fromMCP:()=>Xc,fromNATS:()=>yl,fromNDJSON:()=>fl,fromOTel:()=>Zc,fromPrisma:()=>Ll,fromPrometheus:()=>ol,fromPromise:()=>Jn,fromPulsar:()=>hl,fromRabbitMQ:()=>vl,fromRaf:()=>yd,fromRedisStream:()=>al,fromSSE:()=>Uc,fromSqlite:()=>Ol,fromSqliteCursor:()=>Cl,fromStatsD:()=>nl,fromSyslog:()=>el,fromTimer:()=>dt,fromWebSocket:()=>Ta,fromWebSocketReconnect:()=>Qc,fromWebhook:()=>jc,globToRegExp:()=>hd,graph:()=>oa,graphProfile:()=>pn,graphspec:()=>Xs,guarded:()=>ai,harness:()=>gi,interval:()=>Ac,isBatching:()=>Zt,isV1:()=>Gi,jobQueue:()=>mi,jotai:()=>_o,keepalive:()=>re,last:()=>cc,layout:()=>vi,lens:()=>bi,linear:()=>Go,listSnapshots:()=>Ei,lru:()=>Ra,makeHttpError:()=>ht,map:()=>Br,matchesAnyPattern:()=>gd,matchesCron:()=>Do,memory:()=>Js,memoryStorage:()=>eo,merge:()=>wt,mergeMap:()=>ha,mermaidLiveUrl:()=>os,messaging:()=>Ks,monotonicNs:()=>F,nameToSignal:()=>hn,nanostores:()=>Ao,ndjsonRows:()=>ll,nestjs:()=>cs,never:()=>Td,node:()=>V,nodeSignal:()=>Uo,normalizeActor:()=>St,of:()=>zi,onFirstData:()=>Kr,orchestration:()=>Hs,pairwise:()=>gc,parseCron:()=>Io,parsePrometheusText:()=>ka,parseSSEStream:()=>Lt,parseStatsD:()=>rl,parseSyslog:()=>tl,patterns:()=>Lu,pausable:()=>Ic,pipe:()=>Bi,policy:()=>tn,policyFromRules:()=>Sr,producer:()=>$,pubsub:()=>Vl,race:()=>vc,rateLimiter:()=>Wn,reachable:()=>fn,react:()=>ls,reactiveCounter:()=>Ji,reactiveIndex:()=>ql,reactiveList:()=>Rs,reactiveLog:()=>Ue,reactiveMap:()=>Ze,reactiveSink:()=>qe,reduce:()=>ac,reduction:()=>Qs,refine:()=>ci,registerBuiltinCodecs:()=>vr,registerBuiltins:()=>Rr,repeat:()=>Lc,replay:()=>qo,replayWAL:()=>Ii,rescue:()=>Hr,resilientPipeline:()=>Ti,resolveBackoffPreset:()=>Ft,resolveDescribeFields:()=>_t,restoreSnapshot:()=>Si,retry:()=>Hn,retrySource:()=>$t,runReduction:()=>ki,sample:()=>Rc,saveSnapshot:()=>Ri,scan:()=>ic,serializeError:()=>gn,share:()=>xd,shareReplay:()=>Sd,signalToName:()=>qt,signals:()=>fs,singleFromAny:()=>Ss,singleNodeFromAny:()=>Wl,sizeof:()=>Pr,skip:()=>fa,solid:()=>ms,sortJsonValue:()=>Zr,stableJsonString:()=>Ul,state:()=>N,stratify:()=>to,surface:()=>Mi,svelte:()=>hs,switchMap:()=>be,take:()=>Vr,takeUntil:()=>dc,takeWhile:()=>uc,tap:()=>fc,tapFirst:()=>mc,throttle:()=>ya,throttleTime:()=>Fc,throwError:()=>wd,timeout:()=>zn,toArray:()=>kd,toCSV:()=>wl,toClickHouse:()=>kl,toFile:()=>xa,toHTTP:()=>Bc,toKafka:()=>il,toLoki:()=>Nl,toMongo:()=>Sl,toNATS:()=>bl,toObservable:()=>Lo,toPostgres:()=>Rl,toPulsar:()=>gl,toRabbitMQ:()=>Tl,toReadableStream:()=>Wc,toRedisStream:()=>ul,toS3:()=>xl,toSSE:()=>Hc,toSSEBytes:()=>qc,toSqlite:()=>Al,toTempo:()=>El,toWebSocket:()=>Yc,tokenBucket:()=>jt,validateGraphObservability:()=>ra,valve:()=>Dc,verifiable:()=>jl,version:()=>lb,vue:()=>gs,wallClockNs:()=>ce,watchTopologyTree:()=>Mt,window:()=>Cc,windowCount:()=>_c,windowTime:()=>Oc,withBreaker:()=>qn,withLatestFrom:()=>At,withMaxAttempts:()=>qi,withStatus:()=>Bt,workerBridge:()=>Sa,workerSelf:()=>Na,zip:()=>yc,zustand:()=>ys});module.exports=cf(pb);var pa={};we(pa,{jotai:()=>_o,nanostores:()=>Ao,nestjs:()=>cs,react:()=>ls,signals:()=>fs,solid:()=>ms,svelte:()=>hs,vue:()=>gs,zustand:()=>ys});var _o={};we(_o,{atom:()=>Rf});se();Q();function Rf(t,e,n){if(typeof t=="function"){let r=t;return typeof e=="function"?Yu(r,e,n):Yu(r,void 0,e)}return Sf(t,e)}function Mr(t){let e=t.cache,n;if(t.subscribe(s=>{for(let[o,i]of s)o===R&&(e=i),o===M&&(n=i)})(),n)throw n;return e}function Sf(t,e){let n=N(t,{...e,resubscribable:!0,resetOnTeardown:!0});return{get:()=>n.status==="sentinel"?Mr(n):n.cache,set:r=>n.emit(r),update:r=>{let s=n.status==="sentinel"?Mr(n):n.cache;n.emit(r(s))},subscribe:r=>{let s=!0;return n.subscribe(o=>{for(let[i,a]of o)if(i===R){if(s){s=!1;continue}r(a)}})},meta:n.meta,_node:n}}function Yu(t,e,n){let r=rn(o=>t(i=>{let a=i._node;return a.status==="sentinel"&&Mr(a),o(a)}),{...n,resubscribable:!0,resetOnTeardown:!0}),s={get:()=>r.status==="sentinel"?Mr(r):r.cache,subscribe:o=>{let i=!0;return r.subscribe(a=>{for(let[u,d]of a)if(u===R){if(i){i=!1;continue}o(d)}})},meta:r.meta,_node:r};if(e){let o=u=>u.get(),i=(u,d)=>u.set(d),a=s;return a.set=u=>e(o,i,u),a.update=u=>{let d=r.status==="sentinel"?Mr(r):r.cache;return e(o,i,u(d))},a}return s}var Ao={};we(Ao,{action:()=>Cf,atom:()=>Nf,computed:()=>Ef,getValue:()=>Mf,map:()=>_f,onMount:()=>Of,onStart:()=>Zu,onStop:()=>ed});Ce();se();Q();var Oo=new WeakMap,Co=new WeakMap;function Mo(t,e){let n=e.get(t);if(n)for(let r of n)r()}function Vi(t,e={}){let n=0;return{...e,get:()=>Xu(t),subscribe:s=>{n===0&&Mo(t,Oo),n++;let o=t.subscribe(i=>{for(let[a,u]of i)a===R&&s(u)});return()=>{o(),n--,n===0&&Mo(t,Co)}},listen:s=>{n===0&&Mo(t,Oo),n++;let o=!0,i=t.subscribe(a=>{for(let[u,d]of a)if(u===R){if(o){o=!1;continue}s(d)}});return()=>{i(),n--,n===0&&Mo(t,Co)}},_node:t}}function Qu(t){let e=t.cache,n;if(t.subscribe(s=>{for(let[o,i]of s)o===R&&(e=i),o===M&&(n=i)})(),n)throw n;return e}function Xu(t){return t.status==="sentinel"?Qu(t):t.cache}function Nf(t){let e=N(t,{resubscribable:!0,resetOnTeardown:!0});return Vi(e,{set:n=>e.emit(n)})}function Ef(t,e){let n=Array.isArray(t)?t:[t],r=n.map(o=>o._node),s=_r(r,o=>{let i=n.map(a=>{let u=a._node;return u.status==="sentinel"&&Qu(u),o(u)});return e(...i)},{resubscribable:!0,resetOnTeardown:!0,equals:Object.is});return Vi(s)}function _f(t){let e=N(t,{resubscribable:!0,resetOnTeardown:!0,equals:()=>!1});return Vi(e,{set:n=>e.emit(n),setKey:(n,r)=>{let s=Xu(e);e.emit({...s,[n]:r})}})}function Mf(t){return t.get()}function Zu(t,e){let n=t._node,r=Oo.get(n);r||(r=new Set,Oo.set(n,r)),r.add(e)}function ed(t,e){let n=t._node,r=Co.get(n);r||(r=new Set,Co.set(n,r)),r.add(e)}function Of(t,e){Zu(t,()=>{let n=e();typeof n=="function"&&ed(t,n)})}function Cf(t,e,n){return(...r)=>{let s;return Y(()=>{s=n(...r)}),s}}var cs={};we(cs,{ACTOR_KEY:()=>Jo,COMMAND_HANDLERS:()=>$n,CQRS_EVENT_HANDLERS:()=>jn,CRON_HANDLERS:()=>Fn,CommandHandler:()=>ad,EVENT_HANDLERS:()=>Pn,EventHandler:()=>ud,GRAPHREFLY_REQUEST_GRAPH:()=>on,GRAPHREFLY_ROOT_GRAPH:()=>at,GraphCron:()=>id,GraphInterval:()=>sd,GraphReflyEventExplorer:()=>cn,GraphReflyGuard:()=>Cd,GraphReflyGuardImpl:()=>Lr,GraphReflyModule:()=>ds,INTERVAL_HANDLERS:()=>Gn,InjectCqrsGraph:()=>nd,InjectGraph:()=>td,InjectNode:()=>rd,ObserveGateway:()=>zo,OnGraphEvent:()=>od,QUERY_HANDLERS:()=>Bn,QueryHandler:()=>dd,SAGA_HANDLERS:()=>Vn,SagaHandler:()=>cd,fromHeader:()=>Md,fromJwtPayload:()=>Xi,getActor:()=>Od,getGraphToken:()=>ot,getNodeToken:()=>ct,observeSSE:()=>Ed,observeSubscription:()=>_d,toObservable:()=>Lo});var Ki=require("rxjs");se();function Lo(t,e){return e?.raw?new Ki.Observable(n=>t.subscribe(s=>{if(!n.closed){n.next(s);for(let o of s){if(o[0]===M){n.error(o[1]);return}if(o[0]===O){n.complete();return}}}})):new Ki.Observable(n=>t.subscribe(s=>{for(let o of s){if(n.closed)return;if(o[0]===R)n.next(o[1]);else if(o[0]===M){n.error(o[1]);return}else if(o[0]===O){n.complete();return}}}))}var Or=require("@nestjs/common");var at=Symbol.for("graphrefly:root-graph");var on=Symbol.for("graphrefly:request-graph");function ot(t){return Symbol.for(`graphrefly:graph:${t}`)}function ct(t){return Symbol.for(`graphrefly:node:${t}`)}var Pn=new Map,Gn=new Map,Fn=new Map,$n=new Map,jn=new Map,Bn=new Map,Vn=new Map;function td(t){return t==="request"?(0,Or.Inject)(on):(0,Or.Inject)(t?ot(t):at)}function nd(t){return(0,Or.Inject)(ot(t))}function rd(t){return(0,Or.Inject)(ct(t))}function od(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let s=this.constructor,o=Pn.get(s)??[];o.push({nodeName:t,methodKey:r}),Pn.set(s,o)})}}function sd(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let s=this.constructor,o=Gn.get(s)??[];o.push({ms:t,methodKey:r}),Gn.set(s,o)})}}function id(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let s=this.constructor,o=Fn.get(s)??[];o.push({expr:t,methodKey:r}),Fn.set(s,o)})}}function ad(t,e){return(n,r)=>{let s=r.name;r.addInitializer(function(){let o=this.constructor,i=$n.get(o)??[];i.push({cqrsName:t,commandName:e,methodKey:s}),$n.set(o,i)})}}function ud(t,e){return(n,r)=>{let s=r.name;r.addInitializer(function(){let o=this.constructor,i=jn.get(o)??[];i.push({cqrsName:t,eventName:e,methodKey:s}),jn.set(o,i)})}}function dd(t,e){return(n,r)=>{let s=r.name;r.addInitializer(function(){let o=this.constructor,i=Bn.get(o)??[];i.push({cqrsName:t,projectionName:e,methodKey:s}),Bn.set(o,i)})}}function cd(t,e,n){return(r,s)=>{let o=s.name;s.addInitializer(function(){let i=this.constructor,a=Vn.get(i)??[];a.push({cqrsName:t,eventNames:n,sagaName:e,methodKey:o}),Vn.set(i,a)})}}se();Te();var Nd=0,cn=class{constructor(e,n){this.graph=e;this.moduleRef=n}disposers=[];scheduleNodeNames=[];onModuleInit(){this.wireEvents(),this.wireIntervals(),this.wireCrons(),this.wireCqrsCommands(),this.wireCqrsEvents(),this.wireCqrsQueries(),this.wireCqrsSagas()}onModuleDestroy(){for(let e of this.disposers)e();this.disposers.length=0;for(let e of this.scheduleNodeNames)try{this.graph.remove(e)}catch{}this.scheduleNodeNames.length=0}wireEvents(){for(let[e,n]of Pn){let r=this.resolveInstance(e);if(r)for(let s of n)this.wireEventHandler(r,s)}}wireEventHandler(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let s=r.bind(e),i=this.observeNode(n.nodeName).subscribe(a=>{for(let u of a)u[0]===R&&s(u[1])});this.disposers.push(i)}wireIntervals(){for(let[e,n]of Gn){let r=this.resolveInstance(e);if(r)for(let s of n)this.wireIntervalHandler(r,e,s)}}wireIntervalHandler(e,n,r){let s=e[r.methodKey];if(typeof s!="function")return;let o=s.bind(e),a=`__schedule__.${n.name??"anonymous"}.${String(r.methodKey)}.${Nd++}`,u=dt(r.ms,{period:r.ms,name:a});this.graph.add(u),this.scheduleNodeNames.push(a);let c=this.observeNode(a).subscribe(l=>{for(let p of l)p[0]===R&&o(p[1])});this.disposers.push(c)}wireCrons(){for(let[e,n]of Fn){let r=this.resolveInstance(e);if(r)for(let s of n)this.wireCronHandler(r,e,s)}}wireCronHandler(e,n,r){let s=e[r.methodKey];if(typeof s!="function")return;let o=s.bind(e),a=`__schedule__.${n.name??"anonymous"}.${String(r.methodKey)}.${Nd++}`,u=Ko(r.expr,{name:a});this.graph.add(u),this.scheduleNodeNames.push(a);let c=this.observeNode(a).subscribe(l=>{for(let p of l)p[0]===R&&o(p[1])});this.disposers.push(c)}wireCqrsCommands(){for(let[e,n]of $n){let r=this.resolveInstance(e);if(r)for(let s of n)this.wireCqrsCommand(r,s)}}wireCqrsCommand(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let s=r.bind(e),o=this.resolveCqrsGraph(n.cqrsName);o&&o.command(n.commandName,s)}wireCqrsEvents(){for(let[e,n]of jn){let r=this.resolveInstance(e);if(r)for(let s of n)this.wireCqrsEventHandler(r,s)}}wireCqrsEventHandler(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let s=r.bind(e),o=this.resolveCqrsGraph(n.cqrsName);if(!o)return;o.event(n.eventName);let a=o.resolve(n.eventName).cache,u=a&&a.length>0?a[a.length-1].seq:0,c=this.observeNodeOn(o,n.eventName).subscribe(l=>{for(let p of l)if(p[0]===R){let f=p[1];for(let m of f)m.seq>u&&(s(m),u=m.seq)}});this.disposers.push(c)}wireCqrsQueries(){for(let[e,n]of Bn){let r=this.resolveInstance(e);if(r)for(let s of n)this.wireCqrsQuery(r,s)}}wireCqrsQuery(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let s=r.bind(e),o=this.resolveCqrsGraph(n.cqrsName);if(!o)return;let a=this.observeNodeOn(o,n.projectionName).subscribe(u=>{for(let d of u)d[0]===R&&s(d[1])});this.disposers.push(a)}wireCqrsSagas(){for(let[e,n]of Vn){let r=this.resolveInstance(e);if(r)for(let s of n)this.wireCqrsSaga(r,s)}}wireCqrsSaga(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let s=r.bind(e),o=this.resolveCqrsGraph(n.cqrsName);o&&o.saga(n.sagaName,n.eventNames,s)}observeNode(e){return this.graph.observe(e)}observeNodeOn(e,n){return e.observe(n)}resolveCqrsGraph(e){try{return this.moduleRef.get(ot(e),{strict:!1})}catch{return console.warn(`[GraphReFly] CqrsGraph "${e}" not found in DI \u2014 did you import GraphReflyModule.forCqrs({ name: "${e}" })?`),null}}resolveInstance(e){try{return this.moduleRef.get(e,{strict:!1})}catch{return null}}};se();se();var Bf=0;function Yn(t,e){if(e.highWaterMark<1)throw new RangeError("highWaterMark must be >= 1");if(e.lowWaterMark<0)throw new RangeError("lowWaterMark must be >= 0");if(e.lowWaterMark>=e.highWaterMark)throw new RangeError("lowWaterMark must be < highWaterMark");let n=Symbol(`bp-${++Bf}`),r=0,s=!1;return{onEnqueue(){return r+=1,!s&&r>=e.highWaterMark?(s=!0,t([[Be,n]]),!0):!1},onDequeue(){return r>0&&(r-=1),s&&r<=e.lowWaterMark?(s=!1,t([[Ke,n]]),!0):!1},get pending(){return r},get paused(){return s},dispose(){s&&(s=!1,t([[Ke,n]]))}}}function Ed(t,e,n){let{actor:r,serialize:s=Vf,keepAliveMs:o,signal:i}=n??{},a=new TextEncoder,u,d=n?.highWaterMark!=null,c,l,p=[],f=!1;return new ReadableStream({start(m){let g,h=()=>{},y=()=>{if(!f){f=!0,g!==void 0&&clearInterval(g),i?.removeEventListener("abort",b),h(),c?.dispose(),l?.(),l=void 0;for(let T of p)m.enqueue(T.frame);p.length=0,m.close()}};u=y;let b=()=>y(),v=t.observe(e,{actor:r});d&&(c=Yn(T=>v.up(T),{highWaterMark:n.highWaterMark,lowWaterMark:n.lowWaterMark??Math.floor(n.highWaterMark/2)})),h=v.subscribe(T=>{for(let w of T){if(f)return;let k=w[0];if(k===R){let x=a.encode(Yi("data",s(w[1])));d?(p.push({frame:x,counted:!0}),c.onEnqueue(),l?.(),l=void 0):m.enqueue(x)}else if(k===M){let x=a.encode(Yi("error",s(w[1])));d?(p.push({frame:x,counted:!1}),l?.(),l=void 0):m.enqueue(x),y();return}else if(k===O||k===de){if(k===O){let x=a.encode(Yi("complete"));d?(p.push({frame:x,counted:!1}),l?.(),l=void 0):m.enqueue(x)}y();return}}}),o!==void 0&&o>0&&(g=setInterval(()=>{f||(d?(p.push({frame:a.encode(`: keepalive
2
2
 
3
3
  `),counted:!1}),l?.(),l=void 0):m.enqueue(a.encode(`: keepalive
4
4
 
5
- `)))},s)),i?.aborted?b():i?.addEventListener("abort",b,{once:!0})},pull(m){if(c&&!f){if(p.length>0){let g=p.shift();m.enqueue(g.frame),g.counted&&d.onDequeue();return}return new Promise(g=>{l=g})}},cancel(){try{u?.()}catch{}}})}function Sc(t,e,n){let{actor:r,filter:o}=n??{},s=[],i=[],a=!1,u=t.observe(e,{actor:r}),c=n?.highWaterMark!=null?Yn(m=>u.up(m),{highWaterMark:n.highWaterMark,lowWaterMark:n.lowWaterMark??Math.floor(n.highWaterMark/2)}):void 0,d=()=>{a||(a=!0,c?.dispose(),p())},l=m=>{if(!a)if(i.length>0){let g=i.shift();m.done&&m.error?g.reject(m.error):m.done?g.resolve({done:!0,value:void 0}):g.resolve({done:!1,value:m.value})}else s.push(m),m.done||c?.onEnqueue()},p=u.subscribe(m=>{for(let g of m){let h=g[0];if(h===S){let y=g[1];if(o&&!o(y))continue;l({done:!1,value:y})}else if(h===O){let y=g[1]instanceof Error?g[1]:new Error(String(g[1]));l({done:!0,error:y}),d();return}else if(h===C||h===ve){l({done:!0}),d();return}}});return{next(){if(s.length>0){let m=s.shift();return m.done||c?.onDequeue(),m.done&&m.error?Promise.reject(m.error):Promise.resolve(m.done?{done:!0,value:void 0}:{done:!1,value:m.value})}return a?Promise.resolve({done:!0,value:void 0}):new Promise((m,g)=>{i.push({resolve:m,reject:g})})},return(){d();for(let m of i)m.resolve({done:!0,value:void 0});return i.length=0,Promise.resolve({done:!0,value:void 0})},throw(m){return d(),Promise.reject(m)},[Symbol.asyncIterator](){return this}}}var Zo=class{constructor(e,n){this.graph=e;this.extractActor=n?.extractActor??(()=>{}),this.parse=n?.parse??Ff,this.highWaterMark=n?.highWaterMark,this.lowWaterMark=n?.lowWaterMark}clients=new Map;extractActor;parse;highWaterMark;lowWaterMark;handleConnection(e){this.clients.has(e)||this.clients.set(e,new Map)}handleDisconnect(e){let n=this.clients.get(e);if(n){for(let r of n.values())r.wm?.dispose(),r.unsub();this.clients.delete(e)}}handleMessage(e,n,r){let o=r??$f.bind(null,e),s;try{s=typeof n=="string"?this.parse(n):n}catch{o({type:"err",message:"invalid command"});return}s.type==="subscribe"?this.subscribe(e,s.path,o):s.type==="unsubscribe"?this.unsubscribe(e,s.path,o):s.type==="ack"?this.ack(e,s.path,s.count??1):o({type:"err",message:`unknown command type: ${s.type}`})}subscriptionCount(e){return this.clients.get(e)?.size??0}destroy(){for(let[e]of this.clients)this.handleDisconnect(e)}subscribe(e,n,r){let o=this.clients.get(e);if(o||(o=new Map,this.clients.set(e,o)),o.has(n)){r({type:"subscribed",path:n});return}let s=this.extractActor(e),i;try{i=this.graph.observe(n,{actor:s})}catch(d){let l=d instanceof Error?d.message:String(d);r({type:"err",message:l});return}let a=this.highWaterMark!=null?Yn(d=>i.up(d),{highWaterMark:this.highWaterMark,lowWaterMark:this.lowWaterMark??Math.floor(this.highWaterMark/2)}):void 0,u=()=>{a?.dispose(),c(),o.delete(n)},c=i.subscribe(d=>{for(let l of d){let p=l[0];if(p===S)a?.onEnqueue(),na(r,{type:"data",path:n,value:l[1]});else if(p===O){let f=l[1]instanceof Error?l[1].message:String(l[1]);na(r,{type:"error",path:n,error:f}),u();return}else if(p===C||p===ve){na(r,{type:"complete",path:n}),u();return}}});o.set(n,{unsub:c,wm:a}),r({type:"subscribed",path:n})}unsubscribe(e,n,r){let o=this.clients.get(e),s=o?.get(n);s&&(s.wm?.dispose(),s.unsub(),o.delete(n)),r({type:"unsubscribed",path:n})}ack(e,n,r){let o=this.clients.get(e)?.get(n);if(!o?.wm)return;let s=Math.min(Math.max(0,Math.floor(r)),1024);for(let i=0;i<s;i++)o.wm.onDequeue()}};function Gf(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)}catch{return String(t)}}function ta(t,e){let n=`event: ${t}
5
+ `)))},o)),i?.aborted?b():i?.addEventListener("abort",b,{once:!0})},pull(m){if(d&&!f){if(p.length>0){let g=p.shift();m.enqueue(g.frame),g.counted&&c.onDequeue();return}return new Promise(g=>{l=g})}},cancel(){try{u?.()}catch{}}})}function _d(t,e,n){let{actor:r,filter:s}=n??{},o=[],i=[],a=!1,u=t.observe(e,{actor:r}),d=n?.highWaterMark!=null?Yn(m=>u.up(m),{highWaterMark:n.highWaterMark,lowWaterMark:n.lowWaterMark??Math.floor(n.highWaterMark/2)}):void 0,c=()=>{a||(a=!0,d?.dispose(),p())},l=m=>{if(!a)if(i.length>0){let g=i.shift();m.done&&m.error?g.reject(m.error):m.done?g.resolve({done:!0,value:void 0}):g.resolve({done:!1,value:m.value})}else o.push(m),m.done||d?.onEnqueue()},p=u.subscribe(m=>{for(let g of m){let h=g[0];if(h===R){let y=g[1];if(s&&!s(y))continue;l({done:!1,value:y})}else if(h===M){let y=g[1]instanceof Error?g[1]:new Error(String(g[1]));l({done:!0,error:y}),c();return}else if(h===O||h===de){l({done:!0}),c();return}}});return{next(){if(o.length>0){let m=o.shift();return m.done||d?.onDequeue(),m.done&&m.error?Promise.reject(m.error):Promise.resolve(m.done?{done:!0,value:void 0}:{done:!1,value:m.value})}return a?Promise.resolve({done:!0,value:void 0}):new Promise((m,g)=>{i.push({resolve:m,reject:g})})},return(){c();for(let m of i)m.resolve({done:!0,value:void 0});return i.length=0,Promise.resolve({done:!0,value:void 0})},throw(m){return c(),Promise.reject(m)},[Symbol.asyncIterator](){return this}}}var zo=class{constructor(e,n){this.graph=e;this.extractActor=n?.extractActor??(()=>{}),this.parse=n?.parse??Kf,this.highWaterMark=n?.highWaterMark,this.lowWaterMark=n?.lowWaterMark}clients=new Map;extractActor;parse;highWaterMark;lowWaterMark;handleConnection(e){this.clients.has(e)||this.clients.set(e,new Map)}handleDisconnect(e){let n=this.clients.get(e);if(n){for(let r of n.values())r.wm?.dispose(),r.unsub();this.clients.delete(e)}}handleMessage(e,n,r){let s=r??Hf.bind(null,e),o;try{o=typeof n=="string"?this.parse(n):n}catch{s({type:"err",message:"invalid command"});return}o.type==="subscribe"?this.subscribe(e,o.path,s):o.type==="unsubscribe"?this.unsubscribe(e,o.path,s):o.type==="ack"?this.ack(e,o.path,o.count??1):s({type:"err",message:`unknown command type: ${o.type}`})}subscriptionCount(e){return this.clients.get(e)?.size??0}destroy(){for(let[e]of this.clients)this.handleDisconnect(e)}subscribe(e,n,r){let s=this.clients.get(e);if(s||(s=new Map,this.clients.set(e,s)),s.has(n)){r({type:"subscribed",path:n});return}let o=this.extractActor(e),i;try{i=this.graph.observe(n,{actor:o})}catch(c){let l=c instanceof Error?c.message:String(c);r({type:"err",message:l});return}let a=this.highWaterMark!=null?Yn(c=>i.up(c),{highWaterMark:this.highWaterMark,lowWaterMark:this.lowWaterMark??Math.floor(this.highWaterMark/2)}):void 0,u=()=>{a?.dispose(),d(),s.delete(n)},d=i.subscribe(c=>{for(let l of c){let p=l[0];if(p===R)a?.onEnqueue(),Qi(r,{type:"data",path:n,value:l[1]});else if(p===M){let f=l[1]instanceof Error?l[1].message:String(l[1]);Qi(r,{type:"error",path:n,error:f}),u();return}else if(p===O||p===de){Qi(r,{type:"complete",path:n}),u();return}}});s.set(n,{unsub:d,wm:a}),r({type:"subscribed",path:n})}unsubscribe(e,n,r){let s=this.clients.get(e),o=s?.get(n);o&&(o.wm?.dispose(),o.unsub(),s.delete(n)),r({type:"unsubscribed",path:n})}ack(e,n,r){let s=this.clients.get(e)?.get(n);if(!s?.wm)return;let o=Math.min(Math.max(0,Math.floor(r)),1024);for(let i=0;i<o;i++)s.wm.onDequeue()}};function Vf(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)}catch{return String(t)}}function Yi(t,e){let n=`event: ${t}
6
6
  `;if(e!==void 0)for(let r of e.split(`
7
7
  `))n+=`data: ${r}
8
8
  `;return n+=`
9
- `,n}function Ff(t){return JSON.parse(t)}function $f(t,e){try{t.send(JSON.stringify(e))}catch{}}function na(t,e){try{t(e)}catch{}}Tr();var es="graphReflyActor";function ra(t){return e=>{let r=e.switchToHttp().getRequest()?.user;if(r!=null)return t?t(r):r}}function Nc(t="x-graphrefly-actor"){return e=>{let r=e.switchToHttp().getRequest()?.headers?.[t.toLowerCase()];if(!(typeof r!="string"||r.length===0))try{return JSON.parse(r)}catch{return}}}function Ec(t){let e=t?.[es];return e!=null?St(e):bt}var Lr=class{constructor(e){this.extractor=e}canActivate(e){let n=St(this.extractor(e)),r=e.switchToHttp().getRequest();return r!=null&&(r[es]=n),!0}};function _c(t){return new Lr(t??ra())}var jr=require("@nestjs/common"),Xc=require("@nestjs/core");Tr();Ae();_e();rn();ae();rn();Le();function _t(t,e){if(e!=null&&e.length>0)return new Set(e);switch(t){case"standard":return new Set(["type","status","value","deps","meta","v"]);case"full":return null;default:return new Set(["type","deps"])}}function jf(t){return t._describeKind!=null?t._describeKind:t._deps.length>0?"derived":t._fn!=null?"producer":"state"}function Bf(t){let e={};for(let[n,r]of Object.entries(t.meta))try{e[n]=r.cache}catch{}return e}function Ir(t,e){let n=e==null,r=!n&&e!=null?[...e].filter(c=>c.startsWith("meta.")).map(c=>c.slice(5)):null,o=n||e.has("meta")||r!=null&&r.length>0,s="state",i=[];t instanceof Ie&&(s=jf(t),i=t._deps.map(c=>c.node.name??""));let a={type:s,deps:i};(n||e.has("status"))&&(a.status=t.status);let u=t instanceof Ie?t._guard:void 0;if(o){let c={...Bf(t)};if(u!=null&&c.access===void 0&&(c.access=Nr(u)),r!=null&&r.length>0&&!e.has("meta")){let d={};for(let l of r)l in c&&(d[l]=c[l]);a.meta=d}else a.meta=c}if(t.name!=null&&(a.name=t.name),n||e.has("value")){t.status==="sentinel"&&(a.sentinel=!0);try{a.value=t.cache}catch{}}if((n||e.has("v"))&&t.v!=null){let c={id:t.v.id,version:t.v.version};"cid"in t.v&&(c.cid=t.v.cid,c.prev=t.v.prev),a.v=c}return(n||e.has("guard"))&&u!=null&&(a.guard=Nr(u)),(n||e.has("lastMutation"))&&t.lastMutation!=null&&(a.lastMutation=t.lastMutation),a}Le();ee();Re();vt();var pn=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}};Oo();function oa(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 Qn(t){let e=0;for(let n of t)e+=oa(n.codePointAt(0));return e}function Mc(t,e){if(e<=0)return"";let n=0,r="";for(let o of t){let s=oa(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-=oa(i.codePointAt(0))}return`${r}\u2026`}r+=o,n+=s}return r}var Vf={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"},Kf={horizontal:"-",vertical:"|",cornerTL:"+",cornerTR:"+",cornerBL:"+",cornerBR:"+",tDown:"+",tUp:"+",tRight:"+",tLeft:"+",cross:"+",arrowRight:">",arrowDown:"v",arrowLeft:"<",arrowUp:"^",boxTL:"+",boxTR:"+",boxBL:"+",boxBR:"+",boxH:"-",boxV:"|"};function Lc(t,e){let n=e.charset==="ascii"?Kf:Vf,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)Wf(s,i,n,a);for(let a of t.boxes)Hf(s,i,n,a,e.labelOf(a.id));return s.map(a=>Jf(a.join(""))).join(`
10
- `)}function Hf(t,e,n,r,o){let{x:s,y:i,w:a,h:u}=r;if(a<2||u<2){u>0&&Oc(t,e,s,i,a,o);return}Ht(t,e,s,i,n.boxTL);for(let d=s+1;d<s+a-1;d+=1)Ht(t,e,d,i,n.boxH);Ht(t,e,s+a-1,i,n.boxTR);for(let d=i+1;d<i+u-1;d+=1){Ht(t,e,s,d,n.boxV);for(let l=s+1;l<s+a-1;l+=1)Ic(t,e,l,d," ","empty");Ht(t,e,s+a-1,d,n.boxV)}Ht(t,e,s,i+u-1,n.boxBL);for(let d=s+1;d<s+a-1;d+=1)Ht(t,e,d,i+u-1,n.boxH);Ht(t,e,s+a-1,i+u-1,n.boxBR);let c=i+Math.floor(u/2);Oc(t,e,s+1,c,a-2,o)}function Ht(t,e,n,r,o){Ic(t,e,n,r,o,o===" "?"empty":o==="\u2500"||o==="-"?"boxH":o==="\u2502"||o==="|"?"boxV":"boxCorner")}function Ic(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 Oc(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=n,a=o;for(let u of s){let c=Qn(u);if(c!==0){if(a<c)break;i>=0&&i<t[r].length&&(t[r][i]=u,e[r][i]="label",c===2&&i+1<t[r].length&&(t[r][i+1]="",e[r][i+1]="label")),i+=c,a-=c}}for(;a>0;)i>=0&&i<t[r].length&&(t[r][i]=" ",e[r][i]="empty"),i+=1,a-=1}function Wf(t,e,n,r){let o=r.points;if(o.length<2)return;for(let u=0;u+1<o.length;u+=1)qf(t,e,n,o[u],o[u+1]);for(let u=1;u+1<o.length;u+=1){let c=o[u-1],d=o[u],l=o[u+1],p=Uf(c,d,l,n);p&&Ac(t,e,d.x,d.y,p,"edgeCorner")}let s=o[o.length-1],i=o[o.length-2],a=zf(i,s,n);a&&Ac(t,e,s.x,s.y,a,"arrow")}function qf(t,e,n,r,o){if(!(r.x===o.x&&r.y===o.y)){if(r.y===o.y){let s=r.y,i=Math.min(r.x,o.x),a=Math.max(r.x,o.x);for(let u=i;u<=a;u+=1)Cc(t,e,u,s,n,"h")}else if(r.x===o.x){let s=r.x,i=Math.min(r.y,o.y),a=Math.max(r.y,o.y);for(let u=i;u<=a;u+=1)Cc(t,e,s,u,n,"v")}}}function Cc(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 Ac(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];if(n<0||n>=i.length)return;let a=e[r][n];a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label"||(i[n]=o,e[r][n]=s)}function Uf(t,e,n,r){let o=t.y===e.y,s=e.y===n.y;if(o===s)return;if(o){let u=t.x<e.x,c=n.y>e.y;return u&&c?r.cornerTR:u&&!c?r.cornerBR:!u&&c?r.cornerTL:r.cornerBL}let i=t.y<e.y,a=n.x>e.x;return i&&a?r.cornerBL:i&&!a?r.cornerBR:!i&&a?r.cornerTL:r.cornerTR}function zf(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 Jf(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===32;)e-=1;return t.slice(0,e)}function Gc(t){let e=Yf(t);Qf(e),Xf(e),Zf(e),em(e,t);let n=rm(e,t),{width:r,height:o}=sm(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 Yf(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 Qf(t){let e=new Map;for(let s of t.nodes.values())e.set(s.id,s.in.length);let n=[];for(let s of t.nodes.values())(e.get(s.id)??0)===0&&(s.layer=0,n.push(s));let r=new Set,o=0;for(;o<n.length;){let s=n[o++];if(!r.has(s.id)){r.add(s.id);for(let i of s.out){let a=t.nodes.get(i.toId);a.layer=Math.max(a.layer,s.layer+1);let u=(e.get(a.id)??0)-1;e.set(a.id,u),u<=0&&n.push(a)}}}for(let s of t.nodes.values())s.layer<0&&(s.layer=0)}function Xf(t){let e=Math.max(0,...Array.from(t.nodes.values(),s=>s.layer)),n=Array.from({length:e+1},()=>[]);for(let s of t.nodes.values())n[s.layer].push(s);let r=[],o=0;for(let s of t.hops){let i=t.nodes.get(s.fromId),a=t.nodes.get(s.toId),u=a.layer-i.layer;if(u<=0){i.out=i.out.filter(l=>l!==s),a.in=a.in.filter(l=>l!==s);continue}if(u===1){s.hopIndex=0,s.chainLen=1,r.push(s);continue}i.out=i.out.filter(l=>l!==s),a.in=a.in.filter(l=>l!==s);let c=i;for(let l=1;l<u;l+=1){let p=`__virt_${o++}__`,f={id:p,isVirtual:!0,layer:i.layer+l,order:0,x:0,y:0,w:0,h:1,in:[],out:[]};t.nodes.set(p,f),n[f.layer].push(f);let m={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:c.id,toId:p,hopIndex:l-1,chainLen:u};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:u-1,chainLen:u};c.out.push(d),a.in.push(d),r.push(d)}for(let s of n)for(let i=0;i<s.length;i+=1)s[i].order=i;t.layers=n,t.hops=r}function Zf(t){for(let n=0;n<4;n+=1){for(let r=1;r<t.layers.length;r+=1)Dc(t,t.layers[r],"in"),ts(t.layers[r]);for(let r=t.layers.length-2;r>=0;r-=1)Dc(t,t.layers[r],"out"),ts(t.layers[r])}for(let n=0;n<2;n+=1){let r=!1;for(let o=1;o<t.layers.length;o+=1){let s=t.layers[o];for(let i=0;i+1<s.length;i+=1){let a=Pc(t,s[i],s[i+1],"in");[s[i],s[i+1]]=[s[i+1],s[i]],ts(s),Pc(t,s[i],s[i+1],"in")<a?r=!0:([s[i],s[i+1]]=[s[i+1],s[i]],ts(s))}}if(!r)break}}function Dc(t,e,n){let r=new Map;for(let o of e){let s=n==="in"?o.in:o.out;if(s.length===0){r.set(o.id,o.order);continue}let i=0,a=0;for(let u of s){let c=t.nodes.get(n==="in"?u.fromId:u.toId);c&&(i+=c.order,a+=1)}r.set(o.id,a===0?o.order:i/a)}e.sort((o,s)=>{let i=r.get(o.id),a=r.get(s.id);return i!==a?i-a:o.order-s.order})}function ts(t){for(let e=0;e<t.length;e+=1)t[e].order=e}function Pc(t,e,n,r){let o=r==="in"?e.in:e.out,s=r==="in"?n.in:n.out,i=0;for(let a of o)for(let u of s){let c=t.nodes.get(r==="in"?a.fromId:a.toId)?.order??0,d=t.nodes.get(r==="in"?u.fromId:u.toId)?.order??0;(e.order<n.order&&c>d||e.order>n.order&&c<d)&&(i+=1)}return i}function em(t,e){e.direction==="LR"?tm(t,e):nm(t,e)}function tm(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}Fc(t,e,"y")}function nm(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}Fc(t,e,"x")}function Fc(t,e,n){let r=s=>n==="y"?s.h:s.w,o=e.nodeGap;for(let s=0;s<2;s+=1){let i=s===0?t.layers.slice(1):t.layers.slice(0,-1).reverse();for(let a of i){let u=new Map;for(let d of a){let l=s===0?d.in:d.out;if(l.length===0)continue;let p=[];for(let m of l){let g=t.nodes.get(s===0?m.fromId:m.toId);if(!g)continue;let h=n==="y"?g.y:g.x;p.push(h+Math.floor(r(g)/2))}if(p.length===0)continue;p.sort((m,g)=>m-g);let f=p[Math.floor(p.length/2)];u.set(d.id,f-Math.floor(r(d)/2))}let c=0;for(let d of a){let l=u.get(d.id),p=n==="y"?d.y:d.x,m=Math.max(l??p,c);n==="y"?d.y=m:d.x=m,c=m+r(d)+o}}}}function rm(t,e){let n=new Map;for(let c of t.hops){let d=n.get(c.chainId);d?d.push(c):n.set(c.chainId,[c])}for(let c of n.values())c.sort((d,l)=>d.hopIndex-l.hopIndex);let r=e.direction==="LR",o=c=>r?c.x:c.y,s=c=>r?c.w:c.h,i=c=>r?c.y+Math.floor(c.h/2):c.x+Math.floor(c.w/2),a=new Map;for(let c=0;c+1<t.layers.length;c+=1){let d=t.layers[c],l=t.layers[c+1],p=0;for(let R of d)p=Math.max(p,o(R)+s(R));let f=Number.POSITIVE_INFINITY;for(let R of l)f=Math.min(f,o(R));let m=Number.isFinite(f)?f-1:p,g=Math.max(1,m-p+1),h=[];for(let R of d)for(let N of R.out)h.push(N);h.sort((R,N)=>{let A=i(t.nodes.get(R.fromId)),M=i(t.nodes.get(N.fromId));if(A!==M)return A-M;let I=i(t.nodes.get(R.toId)),L=i(t.nodes.get(N.toId));return I-L});let y=[],b=new Map;for(let R of h){let N=i(t.nodes.get(R.fromId)),A=i(t.nodes.get(R.toId)),M=Math.min(N,A),I=Math.max(N,A),L=-1;for(let P=0;P<y.length;P+=1){let J=y[P],Q=!0;for(let D of J)if(D.lo<=I&&M<=D.hi){Q=!1;break}if(Q){J.push({lo:M,hi:I}),L=P;break}}L<0&&(y.push([{lo:M,hi:I}]),L=y.length-1),b.set(R,L)}let v=y.length,T=g>=Math.max(3,v+2),w=T?p+1:p,k=T?m-1:m,x=Math.max(1,k-w+1);for(let R of h){let N=b.get(R),A;if(v<=1)A=w+Math.floor(x/2);else{let M=(x-1)/(v-1);A=w+Math.floor(N*M)}a.set(R,Math.max(p,Math.min(m,A)))}}let u=[];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),g=t.nodes.get(f.toId),h=a.get(f),y=m.isVirtual?o(m):o(m)+s(m),b=g.isVirtual?o(g):o(g)-1,v=i(m),T=i(g);p===0&&ns(d,r,y,v),v!==T&&(ns(d,r,h,v),ns(d,r,h,T)),ns(d,r,b,T)}let l=c[0];u.push({from:l.chainFrom,to:l.chainTo,points:om(d)})}return u}function ns(t,e,n,r){t.push(e?{x:n,y:r}:{x:r,y:n})}function om(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 sm(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 im=24,am=4,um=1,cm=3;function $c(t,e){let n=dm(e.direction),r=Math.max(3,e.maxLabelWidth??im),o=e.asciiCharset??"unicode",s=Object.keys(t.nodes).sort(),i=new Set(s),a=t.edges.filter(f=>i.has(f.from)&&i.has(f.to)),u=new Map,c=new Map;for(let f of s){let m=Mc(f,r);u.set(f,m),c.set(f,Qn(m)+4)}let d=Gc({nodes:s,edges:a,widthCells:f=>c.get(f)??3,heightCells:()=>cm,layerGap:am,nodeGap:um,direction:n}),l=Lc(d,{charset:o,labelOf:f=>u.get(f)??f}),p=e.logger;return p&&p(l),l}function dm(t){if(t===void 0||t==="LR")return"LR";if(t==="TD")return"TD";throw new Error(`ascii describe supports direction "LR" or "TD" only; got ${String(t)}`)}function Dr(t,e,n,r={}){let o=e in t.nodes,s=n in t.nodes;if(!o)return rs(e,n,"no-such-from");if(!s)return rs(e,n,"no-such-to");let i=r.maxDepth;if(i!=null&&(!Number.isInteger(i)||i<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(e===n){if(r.findCycle===!0){let c=lm(t,e,r);if(c!=null)return c}let u=os(e,t.nodes[e],0,r);return ss(e,n,[u])}if(i===0)return rs(e,n,"no-path");let a=jc(t,e,n,i);return a.found?ss(e,n,Bc(t,a.pathOrder,r)):rs(e,n,a.truncated?"max-depth-exceeded":"no-path")}function jc(t,e,n,r){let o=new Map,s=[{path:n,depth:0}],i=new Set([n]),a=0,u=!1;for(;a<s.length;){let l=s[a++];if(l.path===e)break;if(r!=null&&l.depth>=r){let g=t.nodes[l.path];g?.deps&&g.deps.length>0&&(u=!0);continue}let p=t.nodes[l.path];if(p==null)continue;let f=p.deps??[],m=new Map;for(let g=0;g<f.length;g++){let h=f[g];if(!h)continue;let y=m.get(h);y==null&&(y=[],m.set(h,y)),y.push(g)}for(let[g,h]of m)i.has(g)||(i.add(g),o.set(g,{from:l.path,depIndices:h}),s.push({path:g,depth:l.depth+1}))}if(!o.has(e))return{found:!1,pathOrder:[],truncated:u};let c=[{path:e}],d=e;for(;d!==n;){let l=o.get(d);if(l==null)return{found:!1,pathOrder:[],truncated:!1};c[c.length-1].depIndices=l.depIndices,c.push({path:l.from}),d=l.from}return{found:!0,pathOrder:c,truncated:!1}}function lm(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=os(e,r,0,n);a.dep_index=s[0];let u=os(e,r,1,n);return ss(e,e,[a,u])}let i=null;for(let a=0;a<o.length;a++){let u=o[a];if(!u||u===e)continue;let c=jc(t,u,e,n.maxDepth);c.found&&(i==null||c.pathOrder.length<i.pathOrder.length)&&(i=c,i={found:!0,pathOrder:[{path:e,depIndices:[a]},...c.pathOrder],truncated:!1})}return i==null?null:ss(e,e,Bc(t,i.pathOrder,n))}function Bc(t,e,n){return e.map((r,o)=>{let s=t.nodes[r.path],i=os(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 os(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 ss(t,e,n){return Vc(t,e,!0,"ok",n)}function rs(t,e,n){return Vc(t,e,!1,n,[])}function Vc(t,e,n,r,o){let s=pm(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 pm(t,e,n,r,o){if(!n)switch(r){case"no-such-from":return`explainPath: no node named "${t}"`;case"no-such-to":return`explainPath: no node named "${e}"`;case"max-depth-exceeded":return`explainPath: no path from "${t}" to "${e}" within maxDepth`;default:return`explainPath: no path from "${t}" to "${e}"`}let s=[`Causal path: ${t} \u2192 ${e} (${o.length} step(s))`];for(let i of o){let u=` ${i.hop===0?"\xB7":"\u2193"} ${i.path} (${i.type}${i.status?`/${i.status}`:""})`;if(s.push(u),"value"in i&&s.push(` value: ${fm(i.value)}`),i.annotation!=null&&s.push(` annotation: ${i.annotation}`),i.lastMutation!=null){let c=i.lastMutation.actor;s.push(` actor: ${c.type}${c.id?`:${c.id}`:""}`)}}return s.join(`
11
- `)}function fm(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)}}Le();var je={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},is=Symbol.for("sizeof");function Pr(t){let e=new WeakSet,n=new WeakSet,r=[t],o=0;for(;r.length>0;){let s=r.pop();o+=mm(s,e,n,r)}return o}function mm(t,e,n,r){if(t==null)return 0;switch(typeof t){case"number":return je.number;case"boolean":return je.boolean;case"string":return je.string+t.length*2;case"bigint":return je.bigint+hm(t);case"symbol":return je.symbol;case"function":return e.has(t)?0:(e.add(t),je.function);case"undefined":return 0}let s=t;if(e.has(s))return 0;e.add(s);let i=s[is];if(typeof i=="function")try{let c=i.call(s);if(typeof c=="number"&&Number.isFinite(c))return c}catch{}if(s instanceof Date)return je.date;if(s instanceof RegExp)return je.regexp+s.source.length*2;if(s instanceof Error){let c=s.message?s.message.length*2:0,d=s.stack?s.stack.length*2:0;return je.error+c+d}if(typeof URL<"u"&&s instanceof URL)return je.url+s.href.length*2;if(typeof Promise<"u"&&s instanceof Promise)return je.promise;if(s instanceof WeakMap)return je.weakmap;if(s instanceof WeakSet)return je.weakset;if(s instanceof Map){let c=je.map;for(let[d,l]of s)c+=je.mapEntry,r.push(d),r.push(l);return c}if(s instanceof Set){let c=je.set;for(let d of s)c+=je.setEntry,r.push(d);return c}if(Array.isArray(s)){let c=je.array+s.length*8;for(let d of s)r.push(d);return c}if(s instanceof ArrayBuffer)return n.has(s)?0:(n.add(s),s.byteLength);if(ArrayBuffer.isView(s)){let c=s;return n.has(c.buffer)?48:(n.add(c.buffer),c.buffer.byteLength+48)}let a=je.object,u=Object.keys(s);for(let c of u){a+=je.string+c.length*2;try{r.push(s[c])}catch{}}return a}function hm(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 fn(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),g=m instanceof Ie?m:null,h=g?Pr(g.cache):0,y=g?g._sinkCount:0,b=f.deps?.length??0,v=f.type==="effect"&&y===0,T=y===0?f.type==="effect"?"orphan-effect":f.type==="derived"?"idle-derived":f.type==="producer"?"idle-producer":null:null;a.push({path:p,type:f.type,status:f.status??"unknown",valueSizeBytes:h,subscriberCount:y,depCount:b,isOrphanEffect:v,orphanKind:T})}let u=a.reduce((p,f)=>p+f.valueSizeBytes,0),c=(p,f)=>[...a].sort(f??((m,g)=>g[p]-m[p])).slice(0,n),d=a.filter(p=>p.orphanKind!=null),l=a.filter(p=>p.isOrphanEffect);return{nodeCount:a.length,edgeCount:r.edges.length,subgraphCount:r.subgraphs.length,nodes:a,totalValueSizeBytes:u,hotspots:{byValueSize:c("valueSizeBytes"),bySubscriberCount:c("subscriberCount"),byDepCount:c("depCount")},orphans:d,orphanEffects:l}}var Fe="::",qe="__meta__",pt=1;function Kc(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 gm(t){let e=[];for(let n of Object.keys(t).sort()){let r=t[n].v;r!=null&&e.push(`${n} ${r.id} ${r.version}`)}return e.join(`
12
- `)}function Hc(t){if(t.version!==pt)throw new Error(`unsupported snapshot version ${String(t.version)} (expected ${pt})`);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 ym(t,e){let n=new WeakMap,r=(o,s)=>{if(Object.is(o,s))return!0;if(o==null||s==null||typeof o!="object"||typeof s!="object")return!1;let i=n.get(o);if(i==null&&(i=new WeakSet,n.set(o,i)),i.has(s))return!0;i.add(s);let a=o.constructor,u=s.constructor;if(a!==u)return!1;if(o instanceof Date)return o.getTime()===s.getTime();if(o instanceof RegExp)return o.source===s.source&&o.flags===s.flags;if(Array.isArray(o)){let 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 g of p)if(r(f,g)){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 c=Object.keys(o),d=Object.keys(s);if(c.length!==d.length)return!1;let l=new Set(d);for(let p of c)if(!l.has(p)||!r(o[p],s[p]))return!1;return!0};return r(t,e)}function ia(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(ia);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=ia(e[o]);return r}function bm(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function vm(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Tm(t){return t==="TD"?"down":t==="BT"?"up":t==="RL"?"left":"right"}function qc(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 Uc(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 wm(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(ia(i),null,e.indent??2);return e.logger?.(a),a}function km(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}): ${us(a.value)}`)}if(n){o.push("Edges:");for(let i of t.edges)o.push(`- ${i.from} -> ${i.to}`)}if(r){o.push("Subgraphs:");for(let i of t.subgraphs)o.push(`- ${i}`)}let s=o.join(`
13
- `);return e.logger?.(s),s}function zc(t,e){let n=Uc(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}["${bm(i)}"]`)}for(let[i,a]of qc(t)){let u=o.get(i),c=o.get(a);!u||!c||s.push(` ${u} --> ${c}`)}return s.join(`
14
- `)}function xm(t,e){let n=zc(t,e);return cs(n)}function cs(t,e){let n=e?.theme??"default",r=e?.autoSync??!0,s=JSON.stringify({code:t,mermaid:{theme:n},autoSync:r}),i=new TextEncoder().encode(s),a="";for(let c=0;c<i.length;c++)a+=String.fromCharCode(i[c]);return`https://mermaid.live/edit#base64:${globalThis.btoa(a).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`}function Rm(t,e){let n=Uc(e.direction),r=Object.keys(t.nodes).sort(),o=new Map;for(let i=0;i<r.length;i+=1)o.set(r[i],`n${i}`);let s=[`direction: ${Tm(n)}`];for(let i of r){let a=o.get(i);s.push(`${a}: "${vm(i)}"`)}for(let[i,a]of qc(t)){let u=o.get(i),c=o.get(a);!u||!c||s.push(`${u} -> ${c}`)}return s.join(`
15
- `)}function Sm(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function as(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+=Sm(r)}return e+="$",new RegExp(e)}var Nm={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"},Em={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function us(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 _m(t){return t==="none"?Em:t==="ansi"||t==null?Nm:{data:t.data??"",dirty:t.dirty??"",resolved:t.resolved??"",invalidate:t.invalidate??"",pause:t.pause??"",resume:t.resume??"",complete:t.complete??"",error:t.error??"",teardown:t.teardown??"",derived:t.derived??"",path:t.path??"",reset:t.reset??""}}function Wc(t){if(t==null)return{};let e=t.detail;return e==="full"?{...t,structured:t.structured??!0,timeline:t.timeline??!0,causal:t.causal??!0,derived:t.derived??!0}:e==="minimal"?{...t,structured:t.structured??!0}:t.format==="stage-log"?{...t,structured:t.structured??!0,timeline:t.timeline??!0}:t}function Mm(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 sa(t,e,n){if(t==="")throw new Error(`Graph "${e}": ${n} name must be non-empty`);if(t.includes(Fe))throw new Error(`Graph "${e}": ${n} "${t}" must not contain '${Fe}' (path separator)`);if(t===qe)throw new Error(`Graph "${e}": ${n} name "${qe}" is reserved for meta companion paths`);Mm(t,e,n)}function Om(t,e){if(t==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let n=t.split(Fe);for(let r of n)if(r==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return n}function Cm(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 Jc(t){for(let e of t._mounts.values())Jc(e);for(let e of t._nodes.values())try{e.down([[ve]],{internal:!0})}catch{}}var Y=class t{name;opts;config;_nodes=new Map;_nodeToName=new WeakMap;_mounts=new Map;_parent=void 0;_storageDisposers=new Set;_disposers=new Set;_destroyed=!1;_topology;_topologyEmitters=new Set;constructor(e,n){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(Fe))throw new Error(`Graph name must not contain '${Fe}' (got "${e}")`);if(e===qe)throw new Error(`Graph name "${qe}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...n??{}}),this.config=n?.config??$e,this._traceRing=new pn(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=H(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(sa(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:j()})),e}setVersioning(e){if(e!=null)for(let n of this._nodes.values())n instanceof Ie&&n._applyVersioning(e)}remove(e){sa(e,this.name,"remove");let n=this._mounts.get(e);if(n){let s={kind:"mount",nodes:[],mounts:[]},i=[];n._collectObserveTargets("",i);for(let[a,u]of i)a.includes(`${Fe}${qe}${Fe}`)||s.nodes.push(a);return s.nodes.sort(),s.mounts.push(e),s.mounts.push(...n._collectSubgraphs(`${e}${Fe}`)),this._mounts.delete(e),n._parent=void 0,Jc(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([[ve]],{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=as(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(Fe))return this.resolve(e);let n=this._nodes.get(e);if(!n)throw new Error(`Graph "${this.name}": unknown node "${e}"`);return n}get(e){return this.node(e).cache}set(e,n,r){let o=r?.internal===!0;this.node(e).down([[S,n]],{actor:r?.actor,internal:o,delivery:"write"})}setAll(e,n){let r=Symbol.iterator in e?e:Object.entries(e);Z(()=>{for(let[o,s]of r)this.set(o,s,n)})}invalidate(e,n){let r=n?.internal===!0;this.node(e).down([[Ye]],{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([[C]],{actor:n?.actor,internal:r,delivery:"write"})}edges(e){let n=e?.recursive===!0,r=new Map;if(!n){for(let[u,c]of this._nodes)r.set(c,u);let a=[];for(let[u,c]of this._nodes)if(c instanceof Ie)for(let d of c._deps){let l=r.get(d.node);l!=null&&a.push([l,u])}return a.sort((u,c)=>u[0]<c[0]?-1:u[0]>c[0]?1:u[1]<c[1]?-1:u[1]>c[1]?1:0),a}let o=[];this._collectObserveTargets("",o);let s=new Map;for(let[a,u]of o)s.set(u,a);let i=[];for(let[a,u]of o)if(u instanceof Ie)for(let c of u._deps){let d=s.get(c.node);d!=null&&i.push([d,a])}return i.sort((a,u)=>a[0]<u[0]?-1:a[0]>u[0]?1:a[1]<u[1]?-1:a[1]>u[1]?1:0),i}mount(e,n){if(sa(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=Om(e,this.name);return this._resolveFromSegments(n)}tryResolve(e){try{return this.resolve(e)}catch{return}}_resolveFromSegments(e){let n=e;if(n[0]===this.name&&(n=n.slice(1),n.length===0))throw new Error(`Graph "${this.name}": resolve path ends at graph name only`);let r=n[0],o=n.slice(1);if(o.length===0){let a=this._nodes.get(r);if(a)return a;throw this._mounts.has(r)?new Error(`Graph "${this.name}": path ends at subgraph "${r}" \u2014 not a node (GRAPHREFLY-SPEC \xA73.5)`):new Error(`Graph "${this.name}": unknown name "${r}"`)}let s=this._nodes.get(r);if(s&&o.length>0&&o[0]===qe)return this._resolveMetaChainFromNode(s,o,n.join(Fe));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(Fe)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${r}"`);return i.resolve(o.join(Fe))}_resolveMetaChainFromNode(e,n,r){let o=e,s=0,i=[...n];for(;s<i.length;){if(i[s]!==qe)throw new Error(`Graph "${this.name}": expected ${qe} segment in meta path "${r}"`);if(s+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${qe} in "${r}"`);let a=i[s+1],u=o.meta[a];if(!u)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${r}"`);o=u,s+=2}return o}signal(e,n){if(n?.internal!==!0){for(let o of e)if(this.config.messageTier(o[0])===3)throw new Error(`Graph "${this.name}": Graph.signal() rejects tier-3 messages (DATA / RESOLVED). Broadcast is for control-plane tiers (START / DIRTY / INVALIDATE / PAUSE / RESUME / COMPLETE / ERROR / TEARDOWN). For per-node value writes, use Graph.set or graph.node(name).down(...).`)}let r=[];if(this._signalDeliver(e,n??{},new Set,r),r.length>0)throw r[0]}_signalDeliver(e,n,r,o){for(let u of this._mounts.values())u._signalDeliver(e,n,r,o);let i=n.internal===!0?{internal:!0}:{actor:n.actor,delivery:"signal"},a=Cm(e,this.config);for(let u of[...this._nodes.keys()].sort()){let c=this._nodes.get(u);if(!r.has(c)){r.add(c);try{c.down(e,i)}catch(d){if(d instanceof nt)throw d;o.push(d)}a.length!==0&&this._signalMetaSubtree(c,a,r,i,o)}}}_signalMetaSubtree(e,n,r,o,s){for(let i of Object.keys(e.meta).sort()){let a=e.meta[i];if(!r.has(a)){r.add(a);try{a.down(n,o)}catch(u){if(u instanceof nt)throw u;s.push(u)}this._signalMetaSubtree(a,n,r,o,s)}}}describe(e){if(e?.reactive===!0)return this._describeReactive(e);let n=e?.actor,r=e?.filter,o=_t(e?.detail,e?.fields),s=e?.format==="spec",i=s?_t("minimal"):o,a=[];this._collectObserveTargets("",a);let u=new Map;for(let[k,x]of a)u.set(x,k);let c=[];{let k=a.map(([,N])=>N),x=new Set(u.values()),R=0;for(;k.length>0;){let N=k.shift();if(N instanceof Ie)for(let A of N._deps){let M=A.node;if(u.has(M))continue;let I=M.name??"",L=I;if(!L||x.has(L))if(I){let P=2;for(;x.has(`${I}#${P}`);)P++;L=`${I}#${P}`}else for(L=`__internal__/${R++}`;x.has(L);)L=`__internal__/${R++}`;u.set(M,L),x.add(L),c.push([L,M]),k.push(M)}}}let d=[...a,...c],l={};for(let[k,x]of d){if(n!=null&&!x.allowsObserve(n))continue;let R=Ir(x,i),N=x instanceof Ie?x._deps.map(L=>u.get(L.node)??L.node.name??""):[],{name:A,...M}=R,I={...M,deps:N};if(!s){let L=this._annotations.get(k);L!=null&&(I.annotation=L)}if(r!=null)if(typeof r=="function"){let L=r;if(!(L.length>=2?L(k,I):L(I)))continue}else{let L=!0;for(let[P,J]of Object.entries(r)){let Q=P==="deps_includes"?"depsIncludes":P==="meta_has"?"metaHas":P;if(Q==="depsIncludes"){if(!I.deps.includes(String(J))){L=!1;break}continue}if(Q==="metaHas"){if(!Object.hasOwn(I.meta??{},String(J))){L=!1;break}continue}if(I[Q]!==J){L=!1;break}}if(!L)continue}l[k]=I}let p=new Set(Object.keys(l)),f=[];for(let[k,x]of d)if(x instanceof Ie)for(let R of x._deps){let N=u.get(R.node);N!=null&&f.push([N,k])}f.sort((k,x)=>k[0]<x[0]?-1:k[0]>x[0]?1:k[1]<x[1]?-1:k[1]>x[1]?1:0);let m=f.map(([k,x])=>({from:k,to:x}));(n!=null||r!=null)&&(m=m.filter(k=>p.has(k.from)&&p.has(k.to)));let g=this._collectSubgraphs(""),h=n!=null||r!=null?g.filter(k=>{let x=`${k}${Fe}`;return[...p].some(R=>R===k||R.startsWith(x))}):g,y=this,b=e,v={name:this.name,nodes:l,edges:m,subgraphs:h,expand(k){let x={...b,format:void 0};return Array.isArray(k)?(x.fields=k,x.detail=void 0):(x.detail=k,x.fields=void 0),y.describe(x)}},T=e??{},w=T.format;return w==="json"?wm(v,T):w==="pretty"?km(v,T):w==="mermaid"?zc(v,T):w==="mermaid-url"?xm(v,T):w==="d2"?Rm(v,T):w==="ascii"?$c(v,T):v}_collectSubgraphs(e){let n=[];for(let r of[...this._mounts.keys()].sort()){let o=e===""?r:`${e}${r}`;n.push(o),n.push(...this._mounts.get(r)._collectSubgraphs(`${o}${Fe}`))}return n}resourceProfile(e){return fn(this,e)}reachable(e,n,r={}){return r.withDetail===!0?mn(this.describe(),e,n,{...r,withDetail:!0}):mn(this.describe(),e,n,r)}explain(e,n,r){return r?.reactive===!0?this._explainReactive(e,n,r):this._explainStatic(e,n,r)}_explainStatic(e,n,r){let o=this.describe({detail:"full"}),s=new Map(this._annotations),i=new Map;for(let[a,u]of Object.entries(o.nodes))u.lastMutation!=null&&i.set(a,u.lastMutation);return Dr(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=E(o,{name:`${r}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,u=!1,c=()=>{a||u||(a=!0,xr(()=>{a=!1,!u&&(o+=1,s.emit(o))}))},d=i.onEvent(h=>{let y=h.type;y!=="data"&&y!=="error"&&y!=="complete"&&y!=="teardown"||c()}),l=[],p=new WeakSet,f=h=>{if(p.has(h)||u)return;p.add(h);let y=h.topology.subscribe(b=>{for(let v of b){if(v[0]!==S)continue;let T=v[1];if(c(),T.kind==="added"&&T.nodeKind==="mount"){let w=h._mounts.get(T.name);w!=null&&f(w)}}});l.push(y);for(let b of h._mounts.keys()){let v=h._mounts.get(b);v!=null&&f(v)}};f(this);let m;try{m=_([s],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(h,y)=>h===y})}catch(h){d();for(let y of l)y();throw i.dispose(),h}let g=se(m);return{node:m,dispose(){u=!0,d();for(let h of l)h();l.length=0,i.dispose(),g()}}}_explainReactive(e,n,r){let o=0,s=E(o,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,u=!1,c=i.onEvent(f=>{let m=f.type;m!=="data"&&m!=="error"&&m!=="complete"&&m!=="teardown"||a||u||(a=!0,xr(()=>{a=!1,!u&&(o+=1,s.emit(o))}))}),d={...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{}},l;try{l=_([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&&Am(f.steps,m.steps)})}catch(f){throw c(),i.dispose(),f}let p=se(l);return{node:l,dispose(){u=!0,c(),i.dispose(),p()}}}_pathsMatching(e){let n=as(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}${Fe}${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}${Fe}${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}${Fe}${qe}${Fe}${o}`;r.push([i,s]),this._appendMetaObserveTargets(i,s,r)}}observe(e,n){let r=typeof e=="string",s=Wc(r?n:e),i=s.structured===!0||s.timeline===!0||s.causal===!0||s.derived===!0||s.detail==="minimal"||s.detail==="full"||s.format!=null,a=s.actor;if(r){let d=e,l=this.resolve(d);if(a!=null&&!l.allowsObserve(a))throw new nt({actor:a,action:"observe",nodeName:d});return i?this._buildStructuredObserver([[d,l]],s,"one"):{subscribe(p){return l.subscribe(p)},up(p){try{l.up?.(p)}catch(f){if(f instanceof nt)return;throw f}}}}let u=[];this._collectObserveTargets("",u),u.sort((d,l)=>d[0]<l[0]?-1:d[0]>l[0]?1:0);let c=a==null?u:u.filter(([,d])=>d.allowsObserve(a));return i?this._buildStructuredObserver(c,s,"all"):{subscribe:d=>{let l=c.map(([p,f])=>f.subscribe(m=>{d(p,m)}));return()=>{for(let p of l)p()}},up:(d,l)=>{try{this.resolve(d).up?.(l)}catch(p){if(p instanceof nt)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,l)=>d[0]<l[0]?-1:d[0]>l[0]?1:0);let u=i.actor,c=u==null?a:a.filter(([,d])=>d.allowsObserve(u));return this._buildStructuredObserver(c,i,"all")};return this._createObserveResult(e,n,s)}_createObserveResult(e,n,r){let o=n.timeline===!0,s=n.causal===!0,i=n.derived===!0,a=n.detail==="minimal",u=this.config.inspectorEnabled,c=(s||i)&&u,d=n.maxEvents,l=d!=null&&d>0?new pn(d):null,p=[],f=new Set,m={},g=new Set,h=0,y=0,b=0,v=0,T=0,w=0,k=!1,x=!1,R=0,N=new Map,A=new Map,M=new Map,I=G=>{l?l.push(G):p.push(G);for(let q of f)q(G)},L=()=>o?{timestamp_ns:j(),in_batch:en(),batch_id:R}:{},P=(G,q)=>{if(!(!c||!(G instanceof Ie)))return G._setInspectorHook(ce=>{if(ce.kind==="dep_message")N.set(G,ce.depIndex);else if(ce.kind==="run"){let he=ce.batchData.map((oe,ye)=>oe!=null&&oe.length>0?oe.at(-1):ce.prevData[ye]);A.set(G,he);let xe=ce.batchData.map(oe=>oe!=null?[...oe]:void 0);M.set(G,xe),i&&I({type:"derived",path:q,dep_values:he,dep_batches:xe,...L()})}})},J=G=>{let q=N.get(G),ce=A.get(G);if(!s||ce==null)return{};let xe=(q!=null&&q>=0&&G instanceof Ie?G._deps[q]:void 0)?.node,oe=xe?.v,ye=M.get(G);return{trigger_dep_index:q,trigger_dep_name:xe?.name,...oe!=null?{trigger_version:{id:oe.id,version:oe.version}}:{},dep_values:[...ce],...ye!=null?{dep_batches:ye}:{}}},Q=[],D=[];for(let[G,q]of e){let ce=P(q,G);ce&&Q.push(ce),D.push(q.subscribe(he=>{R++;for(let xe of he){let oe=xe[0],ye=L();if(oe===S){m[G]=xe[1];let re=q instanceof Ie?q.lastMutation?.actor??bt:bt;I({type:"data",path:G,data:xe[1],actor:re,...ye,...J(q)})}else if(a)oe===te?h++:oe===F?y++:oe===Ye?b++:oe===Be?v++:oe===Ke?T++:oe===ve?w++:oe===C&&!g.has(G)?k=!0:oe===O&&(x=!0,g.add(G));else if(oe===te)h++,I({type:"dirty",path:G,...ye});else if(oe===F)y++,I({type:"resolved",path:G,...ye,...J(q)});else if(oe===Ye)b++,I({type:"invalidate",path:G,...ye});else if(oe===Be)v++,I({type:"pause",path:G,lockId:xe[1],...ye});else if(oe===Ke)T++,I({type:"resume",path:G,lockId:xe[1],...ye});else if(oe===C)g.has(G)||(k=!0),I({type:"complete",path:G,...ye});else if(oe===O){x=!0,g.add(G);let re=q instanceof Ie?q.lastMutation?.actor??bt:bt;I({type:"error",path:G,data:xe[1],actor:re,...ye})}else oe===ve&&(w++,I({type:"teardown",path:G,...ye}))}}))}let z=!1,W=()=>{if(!z){z=!0;for(let G of D)G();for(let G of Q)G();for(let G of B)G({value:void 0,done:!0});B.length=0}},ie=[],B=[];f.add(G=>{let q=B.shift();q?q({value:G,done:!1}):ie.push(G)});let $={get values(){return m},get dirtyCount(){return h},get resolvedCount(){return y},get invalidateCount(){return b},get pauseCount(){return v},get resumeCount(){return T},get teardownCount(){return w},get events(){return l?l.toArray():[...p]},get anyCompletedCleanly(){return k},get anyErrored(){return x},get completedWithoutErrors(){return k&&!x},onEvent(G){return f.add(G),()=>f.delete(G)},dispose:W,expand(G){W();let q={...n};return typeof G=="string"?q.detail=G:Object.assign(q,G),r(Wc(q))},[Symbol.asyncIterator](){return{next(){return ie.length>0?Promise.resolve({value:ie.shift(),done:!1}):z?Promise.resolve({value:void 0,done:!0}):new Promise(G=>B.push(G))},return(){return W(),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)),u=_m(n.theme),c=r==="stage-log"?j():0,d=m=>m==null?"":n.stageLabels?.[m]??m,l=(m,g)=>m.length>g?`${m.slice(0,g-1)}\u2026`:m,p=m=>m.type==="data"||m.type==="error"?l(us(m.data),120):"",f=m=>{if(r==="stage-log"){let x=(j()-c)/1e9,R=d(m.path).padEnd(9);if(m.type==="data"){let N=p(m);return`[${x.toFixed(3)}s] ${R} \u2190${N?` ${N}`:""}`}if(m.type==="error"){let N=p(m);return`[${x.toFixed(3)}s] ${R} \u2717${N?` ${N}`:""}`}return m.type==="complete"?`[${x.toFixed(3)}s] ${R} \u25A0 complete`:`[${x.toFixed(3)}s] ${R} ${m.type}`}if(r==="json")try{return JSON.stringify(m)}catch{return JSON.stringify({type:m.type,path:m.path,data:"[unserializable]"})}let g=u[m.type]??"",h=m.path?`${u.path}${m.path}${u.reset} `:"",y=m.type==="data"||m.type==="error",b=m.type==="pause"||m.type==="resume",v=y?` ${us(m.data)}`:b?` ${us(m.lockId)}`:"",T=m.type==="data"||m.type==="resolved"||m.type==="derived"?m:void 0,w=T?.trigger_dep_name!=null?` <- ${T.trigger_dep_name}`:T?.trigger_dep_index!=null?` <- #${T.trigger_dep_index}`:"",k=m.in_batch?" [batch]":"";return`${h}${g}${m.type.toUpperCase()}${u.reset}${v}${w}${k}`};e.onEvent(m=>{a(m.type)&&o(f(m),m)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){Kc(this._disposers,this.name),this.signal([[ve]],{internal:!0}),Kc(this._storageDisposers,this.name);for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}get destroyed(){return this._destroyed}_destroyClearOnly(){for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}snapshot(e){let{expand:n,...r}=this.describe({detail:"full"}),o={};for(let a of Object.keys(r.nodes).sort()){let{lastMutation:u,guard: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 yr(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,n){let r=n?.config??$e,{codec:o,codecVersion:s,payload:i}=br(e,r);return o.decode(i,s)}restore(e,n){if(Hc(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=>as(s)),o=n?.includeProducers===!0;for(let s of Object.keys(e.nodes).sort()){if(r!==null&&!r.some(a=>a.test(s)))continue;let i=e.nodes[s];if(i!==void 0){if(!("value"in i)||i.value===void 0){"value"in i&&i.value===void 0&&n?.onError?.(s,new Error(`restore: slice.value is undefined for "${s}" (undefined is the global SENTINEL; not valid DATA)`));continue}if(!(i.type==="derived"||i.type==="effect")&&!(i.type==="producer"&&!o)){if(i.v!=null){let u=this.tryResolve(s)?.v;if(u!=null&&u.id===i.v.id&&u.version===i.v.version)continue}try{this.set(s,i.value)}catch(a){n?.onError?.(s,a)}}}}}static fromSnapshot(e,n){Hc(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,g)=>{let h=m.split(Fe).length,y=g.split(Fe).length;return h!==y?h-y:m<g?-1:m>g?1:0})){let m=f.split(Fe),g=s;for(let h of m)g._mounts.has(h)||g.mount(h,new t(h)),g=g._mounts.get(h)}let i=o?Object.entries(o).map(([f,m])=>({re:as(f),factory:m})):[],a=f=>{for(let m of i)if(m.re.test(f))return m.factory},u=f=>{let m=f.split(Fe),g=m.pop();if(g==null||g.length===0)throw new Error(`invalid snapshot path "${f}"`);let h=s;for(let y of m){let b=h._mounts.get(y);if(!b)throw new Error(`unknown mount "${y}" in path "${f}"`);h=b}return[h,g]},c=Object.entries(e.nodes).filter(([f])=>!f.includes(`${Fe}${qe}${Fe}`)).sort((f,m)=>f[0]<m[0]?-1:f[0]>m[0]?1:0),d=new Map(c),l=new Map,p=!0;for(;d.size>0&&p;){p=!1;for(let[f,m]of[...d.entries()]){let g=m?.deps??[];if(!g.every(w=>l.has(w)))continue;let[h,y]=u(f),b={...m?.meta??{}},v=a(f),T;if(m?.type==="state")T=E(m.value,{meta:b});else{if(v==null)continue;T=v(y,{path:f,type:m.type,value:m.value,meta:b,deps:g,resolvedDeps:g.map(w=>l.get(w))})}h.add(T,{name:y}),l.set(f,T),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 l=gm(d.nodes);if(c.lastSnapshot!=null&&l!==""&&l===c.lastFingerprint)return;let p=c.seq+1,f=Te(),h=c.lastSnapshot==null||p%c.compactEvery===0?{mode:"full",snapshot:d,seq:p,timestamp_ns:f,format_version:pt}:{mode:"diff",diff:ds(c.lastSnapshot,d),seq:p,timestamp_ns:f,format_version:pt};if(c.tier.filter&&!c.tier.filter(this.name,h))return;let y;try{y=c.tier.save(this.name,h)}catch(b){n.onError?.(b,c.tier);return}if(y&&typeof y.then=="function"){let T=(c.savePending??Promise.resolve()).then(()=>y,()=>y).then(()=>{c.disposed||(c.seq=p,c.lastSnapshot=d,c.lastFingerprint=l)},w=>{n.onError?.(w,c.tier)});c.savePending=T.finally(()=>{c.savePending===T&&(c.savePending=void 0)})}else c.seq=p,c.lastSnapshot=d,c.lastFingerprint=l},s=(c,d)=>{try{o(c,d)}catch(l){n.onError?.(l,c.tier)}},i=(c,d)=>{if(!d.some(m=>{let g=this.config.messageTier(m[0]);return g>=3&&g<5}))return;if(n.filter){let m=this.tryResolve(c);if(m==null)return;let g=Ir(m,_t("standard"));if(!n.filter(c,g))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(l=>{let p=this.tryResolve(l);return p==null?()=>{}:p.subscribe(f=>i(l,f))});a=()=>{for(let l of d)l()}}else a=this.observe().subscribe((c,d)=>i(c,d));let u=()=>{a();for(let c of r)c.disposed=!0,c.timer?.cancel();this._storageDisposers.delete(u)};return this._storageDisposers.add(u),{dispose:u}}async _cascadeRestore(e,n){for(let r of e){let o;try{o=await r.load(this.name)}catch(i){n?.(i,r);continue}if(o==null||typeof o!="object"||Array.isArray(o))continue;let s=o;try{if(s.mode==="full"&&s.snapshot!=null)return this.restore(s.snapshot),!0;if(s.version===pt&&s.nodes!=null)return this.restore(s),!0}catch(i){n?.(i,r)}}return!1}static async fromStorage(e,n,r){for(let o of n){let s;try{s=await o.load(e)}catch(u){r?.onError?.(u,o);continue}if(s==null||typeof s!="object"||Array.isArray(s))continue;let i=s,a=i.mode==="full"&&i.snapshot!=null?i.snapshot:i.version===pt&&i.nodes!=null?i:void 0;if(a!=null)try{return t.fromSnapshot(a,r)}catch(u){r?.onError?.(u,o)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${e}" across ${n.length} tier(s)`)}_annotations=new Map;_traceRing;trace(e,n,r){if(e!=null&&n!=null){if(this.tryResolve(e)==null)return;if(this._annotations.set(e,n),this.config.inspectorEnabled){let o={path:e,annotation:n,timestamp_ns:j(),...r?.actor!=null?{actor:r.actor}:{}};this._traceRing.push(o)}return}return e!=null?this.config.inspectorEnabled?this._annotations.get(e):void 0:this.config.inspectorEnabled?this._traceRing.toArray():[]}annotation(e){return this._annotations.get(e)}clearTrace(){this._annotations.clear(),this._traceRing.clear()}pruneTrace(e){let n=this._traceRing.toArray().filter(o=>!e(o)),r=this._traceRing.size-n.length;this._traceRing.clear();for(let o of n)this._traceRing.push(o);return r}static diff(e,n){let r=new Set(Object.keys(e.nodes)),o=new Set(Object.keys(n.nodes)),s=[...o].filter(b=>!r.has(b)).sort(),i=[...r].filter(b=>!o.has(b)).sort(),a=[],u=[];for(let b of r){if(!o.has(b))continue;let v=e.nodes[b],T=n.nodes[b],w=v.v,k=T.v;w!=null&&k!=null&&w.id===k.id&&w.version!==k.version&&u.push({path:b,id:w.id,from:w.version,to:k.version});let x=w!=null&&k!=null&&w.id===k.id&&w.version===k.version;for(let R of["type","status","sentinel"]){let N=v[R],A=T[R];N!==A&&a.push({path:b,field:R,from:N,to:A})}if(!x)for(let R of["value","meta"]){let N=v[R],A=T[R];ym(N,A)||a.push({path:b,field:R,from:N,to:A})}}let c=b=>`${b.from} ${b.to}`,d=new Set(e.edges.map(c)),l=new Set(n.edges.map(c)),p=n.edges.filter(b=>!d.has(c(b))),f=e.edges.filter(b=>!l.has(c(b))),m=new Set(e.subgraphs),g=new Set(n.subgraphs),h=[...g].filter(b=>!m.has(b)).sort(),y=[...m].filter(b=>!g.has(b)).sort();return{nodesAdded:s,nodesRemoved:i,nodesChanged:a,versionChanges:u,edgesAdded:p,edgesRemoved:f,subgraphsAdded:h,subgraphsRemoved:y}}};function ds(t,e){let n=Y.diff(t,e),r={};for(let o of n.nodesAdded){let s=e.nodes[o];s!=null&&(r[o]=s)}return{...n,nodesAddedFull:r}}function mn(t,e,n,r={}){let o={paths:[],depths:new Map,truncated:!1};if(!e)return r.withDetail?o:[];if(!r.both&&n!=="upstream"&&n!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let s=r.maxDepth;if(s!=null&&(!Number.isInteger(s)||s<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(s===0)return r.withDetail?o:[];let i=new Map,a=new Map,u=new Map,c=new Map,d=new Set;for(let[v,T]of Object.entries(t.nodes)){if(!v)continue;d.add(v);let w=T.deps??[];i.set(v,w);for(let k of w)k&&(d.add(k),a.has(k)||a.set(k,new Set),a.get(k).add(v))}for(let v of t.edges){if(v==null||typeof v!="object")continue;let T=typeof v.from=="string"?v.from:"",w=typeof v.to=="string"?v.to:"";!T||!w||(d.add(T),d.add(w),c.has(T)||c.set(T,new Set),c.get(T).add(w),u.has(w)||u.set(w,new Set),u.get(w).add(T))}if(!d.has(e))return r.withDetail?o:[];let l=r.both===!0,p=v=>{if(l){let x=i.get(v)??[],R=u.get(v),N=a.get(v),A=c.get(v),M=[...x];return R&&M.push(...R),N&&M.push(...N),A&&M.push(...A),M}if(n==="upstream"){let x=i.get(v)??[],R=u.get(v);return R?[...x,...R]:x}let T=a.get(v),w=c.get(v),k=T?[...T]:[];return w&&k.push(...w),k},f=new Set([e]),m=new Map,g=[{path:e,depth:0}],h=0,y=!1;for(;h<g.length;){let v=g[h++];if(s!=null&&v.depth>=s){p(v.path).length>0&&(y=!0);continue}for(let T of p(v.path))!T||f.has(T)||(f.add(T),m.set(T,v.depth+1),g.push({path:T,depth:v.depth+1}))}let b=[...m.keys()].sort((v,T)=>v<T?-1:v>T?1:0);return r.withDetail?{paths:b,depths:m,truncated:y}:b}function Am(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.path!==o.path||r.type!==o.type||r.status!==o.status||r.hop!==o.hop||r.dep_index!==o.dep_index||r.annotation!==o.annotation||r.value!==o.value||r.lastMutation!==o.lastMutation)return!1;let s=r.v,i=o.v;if(s!==i&&(s==null||i==null||s.id!==i.id||s.version!==i.version))return!1}return!0}var fs={};Ne(fs,{CqrsGraph:()=>ps,MemoryEventStore:()=>da,cqrs:()=>la});Ae();_e();rn();var aa={};Ne(aa,{COMPLETE:()=>C,COMPLETE_MSG:()=>Eo,COMPLETE_ONLY_BATCH:()=>gr,DATA:()=>S,DEFAULT_ACTOR:()=>bt,DIRTY:()=>te,DIRTY_MSG:()=>Rt,DIRTY_ONLY_BATCH:()=>On,ERROR:()=>O,GraphReFlyConfig:()=>tn,GuardDenied:()=>nt,INVALIDATE:()=>Ye,INVALIDATE_MSG:()=>No,INVALIDATE_ONLY_BATCH:()=>hr,NodeImpl:()=>Ie,PAUSE:()=>Be,RESOLVED:()=>F,RESOLVED_MSG:()=>_n,RESOLVED_ONLY_BATCH:()=>mr,RESUME:()=>Ke,START:()=>yt,START_MSG:()=>Mn,TEARDOWN:()=>ve,TEARDOWN_MSG:()=>_o,TEARDOWN_ONLY_BATCH:()=>Cn,accessHintForGuard:()=>Nr,advanceVersion:()=>Er,autoTrackNode:()=>on,batch:()=>Z,configure:()=>Wi,createVersioning:()=>Dn,defaultConfig:()=>$e,defaultHash:()=>Ft,derived:()=>_,downWithBatch:()=>Nt,dynamicNode:()=>_r,effect:()=>de,isBatching:()=>en,isV1:()=>Vi,monotonicNs:()=>j,node:()=>U,normalizeActor:()=>St,pipe:()=>qi,policy:()=>nn,policyFromRules:()=>Sr,producer:()=>H,registerBuiltins:()=>Rr,resolveDescribeFields:()=>_t,state:()=>E,wallClockNs:()=>Te});Tr();Ae();_e();ji();rn();ae();Le();ee();Co();Ae();ae();ee();var Gr=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 Yc(t){return t.subscribe(()=>{})}var Lm=64;function Ue(t,e={}){let{name:n,maxSize:r,versioning:o,backend:s}=e,i=s??new Gr(t,r),a=E(i.toArray(),{name:n,describeKind:"state",equals:(m,g)=>m===g,...o!=null?{versioning:o}:{}});function u(){let m=i.toArray();Z(()=>{a.down([[te]]),a.down([[S,m]])})}let c=new Map,d=new Map;function l(m,g){return`${m}:${g===void 0?"END":g}`}function p(m){if(m.size<Lm)return;let g=m.keys().next();if(g.done)return;let h=m.get(g.value);h!==void 0&&h.dispose(),m.delete(g.value)}function f(m){let g=i.version;try{return m()}finally{i.version!==g&&u()}}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 g=c.get(m);if(g!==void 0)return c.delete(m),c.set(m,g),g.node;p(c);let h=_([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=Yc(h);return c.set(m,{node:h,dispose:y}),h},slice(m,g){if(!Number.isInteger(m)||m<0)throw new RangeError(`slice: start must be a non-negative integer (got ${m})`);if(g!==void 0&&(!Number.isInteger(g)||g<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${g})`);let h=l(m,g),y=d.get(h);if(y!==void 0)return d.delete(h),d.set(h,y),y.node;p(d);let b=_([a],([T])=>{let w=T;return g===void 0?w.slice(m):w.slice(m,g)},{initial:i.slice(m,g),describeKind:"derived"}),v=Yc(b);return d.set(h,{node:b,dispose:v}),b},disposeTail(m){let g=c.get(m);return g===void 0?!1:(g.dispose(),c.delete(m),!0)},disposeSlice(m,g){let h=l(m,g),y=d.get(h);return y===void 0?!1:(y.dispose(),d.delete(h),!0)},disposeAllViews(){for(let m of c.values())m.dispose();c.clear();for(let m of d.values())m.dispose();d.clear()},dispose(){for(let m of c.values())m.dispose();c.clear();for(let m of d.values())m.dispose();d.clear()}}}var ca={};Ne(ca,{ENVELOPE_VERSION:()=>An,GRAPH_META_SEGMENT:()=>qe,Graph:()=>Y,JsonCodec:()=>Mo,SIZEOF_OVERHEAD:()=>je,SIZEOF_SYMBOL:()=>is,SNAPSHOT_VERSION:()=>pt,createDagCborCodec:()=>Gi,createDagCborZstdCodec:()=>Fi,decodeEnvelope:()=>br,diffForWAL:()=>ds,encodeEnvelope:()=>yr,explainPath:()=>Dr,graphProfile:()=>fn,mermaidLiveUrl:()=>cs,reachable:()=>mn,registerBuiltinCodecs:()=>vr,replayWAL:()=>$i,sizeof:()=>Pr,validateGraphObservability:()=>ua,watchTopologyTree:()=>Mt});Oo();ae();function Mt(t,e){let n=new Map,r=(o,s)=>{if(n.has(o))return;let i={off:()=>{},prefix:s};n.set(o,i);let a=o.topology.subscribe(u=>{for(let c of u){if(c[0]!==S)continue;let d=c[1];if(e(d,o,s),d.kind==="added"&&d.nodeKind==="mount"){let l=o._mounts.get(d.name);if(l instanceof Y){let p=`${s}${d.name}::`;r(l,p)}}else if(d.kind==="removed"&&d.nodeKind==="mount"){let l=`${s}${d.name}::`;for(let[p,f]of Array.from(n.entries()))p!==t&&f.prefix.startsWith(l)&&(f.off(),n.delete(p))}}});i.off=a;for(let[u,c]of o._mounts)if(c instanceof Y){let d=`${s}${u}::`;r(c,d)}};return r(t,""),()=>{for(let o of n.values())o.off();n.clear()}}function ua(t,e={}){let n=[],r=e.requireFound??!0;if(e.skipDescribe!==!0)try{let c=t.describe(),d=new Set(Object.keys(c.nodes)),l=[];for(let[p,f]of Object.entries(c.nodes))for(let m of f.deps)m!==""&&!d.has(m)&&l.push(`${p} \u2192 ${m}`);for(let p of c.edges)d.has(p.from)||l.push(`edge.from: ${p.from}`),d.has(p.to)||l.push(`edge.to: ${p.to}`);l.length>0?n.push({kind:"describe",ok:!1,reason:`describe() has ${l.length} dangling pointer(s); nodes \u2289 deps`,danglingDeps:l}):n.push({kind:"describe",ok:!0,nodeCount:d.size,edgeCount:c.edges.length})}catch(c){n.push({kind:"describe",ok:!1,reason:`describe() threw: ${c instanceof Error?c.message:String(c)}`})}for(let c of e.formats??[])try{let d=t.describe({format:c});typeof d!="string"||d.length===0?n.push({kind:"describe-format",ok:!1,format:c,reason:`describe({ format: "${c}" }) returned empty or non-string output`}):n.push({kind:"describe-format",ok:!0,format:c,length:d.length})}catch(d){n.push({kind:"describe-format",ok:!1,format:c,reason:d instanceof Error?d.message:String(d)})}for(let c of e.paths??[])try{t.resolve(c),n.push({kind:"observe",ok:!0,path:c})}catch(d){n.push({kind:"observe",ok:!1,path:c,reason:d instanceof Error?d.message:String(d)})}for(let[c,d]of e.pairs??[])try{let l=t.explain(c,d);r&&l.found===!1?n.push({kind:"explain",ok:!1,from:c,to:d,reason:`explain(${c} \u2192 ${d}) found no path${l.reason?`: ${l.reason}`:""}`}):n.push({kind:"explain",ok:!0,from:c,to:d,found:l.found,steps:l.steps.length})}catch(l){n.push({kind:"explain",ok:!1,from:c,to:d,reason:l instanceof Error?l.message:String(l)})}let o=n.filter(c=>!c.ok),s=o.length===0,i=e.paths?.length??0,a=e.pairs?.length??0,u=e.formats?.length??0;return{ok:s,checks:n,failures:o,summary(){let c=[e.skipDescribe===!0?null:"describe",u>0?`${u} format${u===1?"":"s"}`:null,i>0?`${i} observe path${i===1?"":"s"}`:null,a>0?`${a} explain pair${a===1?"":"s"}`:null].filter(l=>l!=null),d=c.length>0?c.join(", "):"describe-only";return s?`validateGraphObservability: OK (${d})`:`validateGraphObservability: ${o.length} failure(s) across ${d}`}}}Ae();ae();Le();Re();function ft(t,e){t!=null&&Nt(n=>t.down(n),[[S,e]],$e.tierOf)}function Fr(t,e){let n=t.cache??0;return n>=e?!1:(t.down([[te],[S,n+1]]),!0)}function ze(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}function $r(t){return t.relatedTo?.[0]??t.summary}var Im=nn((t,e)=>{t("write"),t("signal"),e("observe")}),Dm=nn((t,e)=>{t("observe"),t("signal"),e("write")}),Pm=nn((t,e)=>{t("observe"),t("signal"),e("write")});function ls(t,e){return ze("cqrs",t,e)}var da=class{_store=new Map;persist(e){let n=this._store.get(e.type);n||(n=[],this._store.set(e.type,n)),n.push(e)}loadEvents(e,n){let r=this._store.get(e)??[],o=n?.timestampNs,s=n?.seq,i=o==null?[...r]:r.filter(u=>u.timestampNs>o||u.timestampNs===o&&u.seq>(s??-1)),a=i.length>0?i[i.length-1]:void 0;return{events:i,cursor:a?{timestampNs:a.timestampNs,seq:a.seq}:n}}clear(){this._store.clear()}},ps=class extends Y{_eventLogs=new Map;_commandHandlers=new Map;_projections=new Set;_sagas=new Set;_keepaliveDisposers=[];_eventStore;_seq=0;constructor(e,n={}){super(e,n.graph)}destroy(){for(let e of this._keepaliveDisposers)e();this._keepaliveDisposers.length=0,super.destroy()}event(e){let n=this._eventLogs.get(e);if(n)return n.node;let r=Ue([],{name:e,versioning:0}),o=r.entries,s=_([o],([i])=>i,{name:e,describeKind:"state",meta:ls("event",{event_name:e}),guard:Pm,initial:o.cache});return this.add(s,{name:e}),this._keepaliveDisposers.push(se(s)),this._eventLogs.set(e,{log:r,node:s}),s}_appendEvent(e,n){let r=this._eventLogs.get(e);if(r||(this.event(e),r=this._eventLogs.get(e)),r.node.status==="completed"||r.node.status==="errored")throw new Error(`Cannot dispatch to terminated event stream "${e}" (status: ${r.node.status}).`);let o=r.log.entries.v,s={type:e,payload:n,timestampNs:Te(),seq:++this._seq,...o!=null?{v0:{id:o.id,version:o.version}}:{}};r.log.append(s),this._eventStore&&this._eventStore.persist(s)}command(e,n){let r=E(void 0,{name:e,describeKind:"state",meta:{...ls("command",{command_name:e}),error:null},guard:Im});return this.add(r,{name:e}),this._commandHandlers.set(e,n),r}dispatch(e,n){let r=this._commandHandlers.get(e);if(!r)throw new Error(`Unknown command: "${e}". Register with .command() first.`);let o=this.resolve(e);Z(()=>{o.emit(n,{internal:!0});try{r(n,{emit:(s,i)=>this._appendEvent(s,i)}),o.meta.error.emit(null,{internal:!0})}catch(s){throw o.meta.error.emit(s,{internal:!0}),s}})}projection(e,n,r,o){let s=n.map(a=>(this._eventLogs.has(a)||this.event(a),this._eventLogs.get(a).node)),i=_(s,a=>{let u=[];for(let c of a){let d=c;u.push(...d)}return u.sort((c,d)=>c.timestampNs-d.timestampNs||c.seq-d.seq),r(o,u)},{name:e,describeKind:"derived",meta:ls("projection",{projection_name:e,source_events:n}),guard:Dm,initial:o});return this.add(i,{name:e}),this._keepaliveDisposers.push(se(i)),this._projections.add(e),i}saga(e,n,r){let o=n.map(u=>(this._eventLogs.has(u)||this.event(u),this._eventLogs.get(u).node)),s=new Map,i={},a=U(o,(u,c)=>{let d=i.n.meta.error;for(let l=0;l<u.length;l++){let p=u[l];if(p==null||p.length===0)continue;let f=p.at(-1);if(!f)continue;let m=n[l],g=s.get(m)??0;if(f.length>g){let h=f.slice(g);for(let y of h)try{r(y),d.emit(null,{internal:!0})}catch(b){d.emit(b,{internal:!0})}s.set(m,f.length)}}},{name:e,describeKind:"effect",meta:{...ls("saga",{saga_name:e,source_events:n}),error:null}});return i.n=a,this.add(a,{name:e}),this._keepaliveDisposers.push(se(a)),this._sagas.add(e),a}useEventStore(e){this._eventStore=e}async rebuildProjection(e,n,r){if(!this._eventStore)throw new Error("No event store wired. Call useEventStore() first.");let o=[];for(let s of e){let i=await this._eventStore.loadEvents(s);o.push(...i.events)}return o.sort((s,i)=>s.timestampNs-i.timestampNs||s.seq-i.seq),n(r,o)}};function la(t,e){return new ps(t,e)}var fa=class{constructor(e){this.graph=e}onModuleDestroy(){this.graph.destroy()}},ma=class{graph=new Y("request");onModuleDestroy(){this.graph.destroy()}},Qc,pa;Qc=[(0,jr.Module)({})];var Wt=class Wt{static forRoot(e){let n=e??{},r=n.name??"root",o=[{provide:at,useFactory:()=>{let s=new Y(r);return n.build&&n.build(s),n.snapshot&&s.restore(n.snapshot),s}},{provide:Symbol.for("graphrefly:root-lifecycle"),useFactory:s=>new fa(s),inject:[at]},{provide:ln,useFactory:(s,i)=>new ln(s,i),inject:[at,Xc.ModuleRef]}];if(n.nodes)for(let s of n.nodes)o.push({provide:dt(s),useFactory:i=>i.resolve(s),inject:[at]});return n.requestScope&&o.push({provide:Symbol.for("graphrefly:request-lifecycle"),useFactory:()=>new ma,scope:jr.Scope.REQUEST},{provide:sn,useFactory:s=>s.graph,inject:[Symbol.for("graphrefly:request-lifecycle")],scope:jr.Scope.REQUEST}),{module:Wt,global:!0,providers:o,exports:[at,...(n.nodes??[]).map(dt),...n.requestScope?[sn]:[]]}}static forFeature(e){let n=[{provide:rt(e.name),useFactory:r=>{let o=new Y(e.name);return e.build&&e.build(o),e.snapshot&&o.restore(e.snapshot),r.mount(e.name,o),o},inject:[at]}];if(e.nodes)for(let r of e.nodes)n.push({provide:dt(`${e.name}::${r}`),useFactory:o=>o.resolve(r),inject:[rt(e.name)]});return{module:Wt,providers:n,exports:[rt(e.name),...(e.nodes??[]).map(r=>dt(`${e.name}::${r}`))]}}static forCqrs(e){let n=[{provide:rt(e.name),useFactory:r=>{let o=la(e.name,e.cqrs);return e.eventStore&&o.useEventStore(e.eventStore),e.build&&e.build(o),r.mount(e.name,o),o},inject:[at]}];if(e.nodes)for(let r of e.nodes)n.push({provide:dt(`${e.name}::${r}`),useFactory:o=>o.resolve(r),inject:[rt(e.name)]});return{module:Wt,providers:n,exports:[rt(e.name),...(e.nodes??[]).map(r=>dt(`${e.name}::${r}`))]}}};pa=Pu(null),Wt=$u(pa,0,"GraphReflyModule",Qc,Wt),Fu(pa,1,Wt);var ms=Wt;var gs={};Ne(gs,{useStore:()=>Gm,useSubscribe:()=>Zc,useSubscribeRecord:()=>Fm});var Ot=require("react");ae();function Zc(t){return(0,Ot.useSyncExternalStore)(e=>{let n=!1,r=t.subscribe(()=>{n||e()});return()=>{n=!0,r()}},()=>t.cache,()=>t.cache)}function Gm(t){let e=Zc(t),n=(0,Ot.useCallback)(r=>{t.down([[te],[S,r]])},[t]);return[e,n]}function Fm(t,e){let n=(0,Ot.useRef)(e);n.current=e;let r=(0,Ot.useMemo)(()=>{let o=()=>{let i={},a=t.cache??[];for(let u of a){let c=n.current(u),d={};for(let l of Object.keys(c))d[l]=c[l].cache;i[u]=d}return i},s=o();return{subscribe:i=>{let a=!1,u=[],c=()=>{for(let p of u)p();u=[]},d=p=>{c();for(let f of p){let m=n.current(f);for(let g of Object.keys(m)){let h=m[g].subscribe(()=>{s=o(),a||i()});u.push(h)}}s=o(),a||i()},l=t.subscribe(p=>{let f=p.some(m=>m[0]===S||m[0]===F);!a&&f&&d(t.cache??[])});return d(t.cache??[]),()=>{a=!0,l(),c()}},getSnapshot:()=>s}},[t]);return(0,Ot.useSyncExternalStore)(r.subscribe,r.getSnapshot,r.getSnapshot)}var bs={};Ne(bs,{Signal:()=>$m});Ae();ae();ee();var Xn=[];function ys(t){let e=t.cache;return t.subscribe(r=>{for(let[o,s]of r)o===S&&(e=s)})(),e}var ha=class{_node;_equals;constructor(e,n){this._equals=n?.equals??Object.is,this._node=E(e,{...n,resubscribable:!0,resetOnTeardown:!0})}get(){let e=Xn[Xn.length-1];return e?(this._node.status==="sentinel"&&ys(this._node),e(this._node)):this._node.status==="sentinel"?ys(this._node):this._node.cache}set(e){this._equals(this.get(),e)||Z(()=>{this._node.down([[te],[S,e]])})}},ga=class{_node;constructor(e,n){this._node=on(r=>{Xn.push(r);try{return e()}finally{Xn.pop()}},{...n,describeKind:"derived",resubscribable:!0,resetOnTeardown:!0})}get(){let e=Xn[Xn.length-1];return e?(this._node.status==="sentinel"&&ys(this._node),e(this._node)):this._node.status==="sentinel"?ys(this._node):this._node.cache}},$m={State:ha,Computed:ga,sub:(t,e)=>{let n=typeof e=="function"?{data:e,error:void 0,complete:void 0}:e,r=!0;return t._node.subscribe(o=>{for(let[s,i]of o){if(s===S){if(r){r=!1;continue}n.data?.(i)}s===O&&n.error?.(i),s===C&&n.complete?.()}})}};var vs={};Ne(vs,{useStore:()=>jm,useSubscribe:()=>ed,useSubscribeRecord:()=>Bm});var Ct=require("solid-js");ae();function ed(t){let[e,n]=(0,Ct.createSignal)(t.cache,{equals:!1}),r=t.subscribe(()=>{n(()=>t.cache)});return(0,Ct.getOwner)()?(0,Ct.onCleanup)(()=>r()):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribe called outside a Solid reactive owner \u2014 subscription will not be auto-disposed."),e}function jm(t){return[ed(t),r=>{t.down([[te],[S,r]])}]}function Bm(t,e){let[n,r]=(0,Ct.createSignal)({},{equals:!1}),o=[],s=()=>{for(let c of o)c();o=[]},i=()=>{let c={};for(let d of t.cache??[]){let l=e(d),p={};for(let f of Object.keys(l))p[f]=l[f].cache;c[d]=p}return c},a=c=>{s();for(let d of c){let l=e(d);for(let p of Object.keys(l)){let f=l[p].subscribe(()=>{r(()=>i())});o.push(f)}}r(()=>i())},u=t.subscribe(c=>{c.some(d=>d[0]===S||d[0]===F)&&a(t.cache??[])});return a(t.cache??[]),(0,Ct.getOwner)()?(0,Ct.onCleanup)(()=>{u(),s()}):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribeRecord called outside a Solid reactive owner \u2014 subscription will not be auto-disposed."),n}var Ts={};Ne(Ts,{useStore:()=>Km,useSubscribe:()=>Vm,useSubscribeRecord:()=>Hm});ae();function Vm(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n}}}function Km(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n},set(e){t.down([[te],[S,e]])},update(e){let n=e(t.cache);t.down([[te],[S,n]])}}}function Hm(t,e){return{subscribe(n){let r=[],o=()=>{for(let u of r)u();r=[]},s=()=>{let u={};for(let c of t.cache??[]){let d=e(c),l={};for(let p of Object.keys(d))l[p]=d[p].cache;u[c]=l}return u},i=u=>{o();for(let c of u){let d=e(c);for(let l of Object.keys(d)){let p=d[l].subscribe(()=>{n(s())});r.push(p)}}n(s())},a=t.subscribe(u=>{u.some(c=>c[0]===S||c[0]===F)&&i(t.cache??[])});return i(t.cache??[]),()=>{a(),o()}}}}var ws={};Ne(ws,{useStore:()=>qm,useSubscribe:()=>Wm,useSubscribeRecord:()=>Um});var Ve=require("vue");ae();function Wm(t){let e=(0,Ve.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,Ve.getCurrentScope)()?(0,Ve.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribe called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Ve.readonly)(e)}function qm(t){let e=(0,Ve.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,Ve.getCurrentScope)()?(0,Ve.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useStore called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Ve.computed)({get:()=>e.value,set:r=>{t.down([[te],[S,r]])}})}function Um(t,e){let n=(0,Ve.shallowRef)({}),r=new Map;function o(){let a={};for(let[u,c]of r)a[u]={...c.values};n.value=a}function s(a){for(let c of r.values())for(let d of c.subs)d();r.clear();for(let c of a){let d=e(c),l=Object.keys(d),p={},f=[];for(let m of l){let g=d[m];p[m]=g.cache;let h=g.subscribe(()=>{p[m]=g.cache,o()});f.push(h)}r.set(c,{subs:f,values:p})}let u={};for(let[c,d]of r)u[c]={...d.values};n.value=u}return(0,Ve.watch)(()=>[...(typeof t=="function"?t():(0,Ve.isRef)(t)?t.value:t)??[]],a=>s(a??[]),{immediate:!0}),(0,Ve.getCurrentScope)()?(0,Ve.onScopeDispose)(()=>{for(let a of r.values())for(let u of a.subs)u();r.clear()}):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribeRecord called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Ve.readonly)(n)}var ks={};Ne(ks,{create:()=>Jm});ae();ee();var zm=()=>!1;function Jm(t){let e=new Y("zustand"),n=E(void 0,{name:"state",equals:zm});e.add(n,{name:"state"});let r=()=>n.cache,o=(a,u)=>{let c=n.cache,d=typeof a=="function"?a(c):a;n.emit(u?d:{...c,...d})},s={getState:r,setState:o,getInitialState:()=>i,subscribe:a=>{let u=!0,c=n.cache;return n.subscribe(d=>{for(let[l,p]of d)if(l===S){if(u){u=!1;continue}a(p,c),c=p}})},destroy:e.destroy.bind(e)},i=t(o,r,s);return n.emit(i),Object.assign(e,s)}var Aa={};Ne(Aa,{CircuitOpenError:()=>lt,ContentAddressedMissError:()=>zr,NS_PER_MS:()=>He,NS_PER_SEC:()=>st,NativeIndexBackend:()=>Qr,NativeListBackend:()=>Xr,NativeLogBackend:()=>Gr,NativeMapBackend:()=>qr,NativePubSubBackend:()=>Yr,RateLimiterOverflowError:()=>un,ResettableTimer:()=>De,TimeoutError:()=>cn,audit:()=>kd,awaitSettled:()=>Qo,buffer:()=>xd,bufferCount:()=>Rd,bufferTime:()=>Nd,cached:()=>wc,canonicalJson:()=>Jr,cascadingCache:()=>Il,catchError:()=>Pd,checkpointToRedis:()=>Nl,checkpointToS3:()=>Sl,circuitBreaker:()=>Tt,combine:()=>va,combineLatest:()=>Ld,concat:()=>hd,concatMap:()=>bd,constant:()=>Bo,contentAddressedStorage:()=>_s,createTransport:()=>Ut,createWatermarkController:()=>Yn,csvRows:()=>al,debounce:()=>wa,debounceTime:()=>Id,decorrelatedJitter:()=>Wo,delay:()=>Td,deserializeError:()=>bn,dictStorage:()=>Wl,distill:()=>Ns,distinctUntilChanged:()=>pd,elementAt:()=>cd,empty:()=>gc,escapeRegexChar:()=>Xi,exhaustMap:()=>yd,exponential:()=>Ko,externalBundle:()=>xs,externalProducer:()=>hn,fallback:()=>Un,fibonacci:()=>Ho,filter:()=>it,find:()=>ud,first:()=>Rs,firstValueFrom:()=>Qe,firstWhere:()=>Uo,flatMap:()=>vd,forEach:()=>Kt,fromAny:()=>X,fromAsyncIter:()=>Ar,fromCSV:()=>il,fromClickHouseWatch:()=>ll,fromCron:()=>zo,fromDrizzle:()=>Cl,fromEvent:()=>hc,fromHTTP:()=>Na,fromHTTPPoll:()=>qd,fromHTTPStream:()=>Wd,fromIter:()=>Jo,fromKafka:()=>nl,fromKysely:()=>Al,fromMCP:()=>Jd,fromNATS:()=>ml,fromNDJSON:()=>dl,fromOTel:()=>Yd,fromPrisma:()=>Ol,fromPrometheus:()=>tl,fromPromise:()=>Jn,fromPulsar:()=>pl,fromRabbitMQ:()=>gl,fromRaf:()=>mc,fromRedisStream:()=>ol,fromSSE:()=>Hd,fromSqlite:()=>El,fromSqliteCursor:()=>_l,fromStatsD:()=>Zd,fromSyslog:()=>Qd,fromTimer:()=>ct,fromWebSocket:()=>Sa,fromWebSocketReconnect:()=>zd,fromWebhook:()=>Gd,globToRegExp:()=>pc,interval:()=>Md,keepalive:()=>se,last:()=>ad,linear:()=>Vo,lru:()=>Ma,makeHttpError:()=>ht,map:()=>Br,matchesAnyPattern:()=>fc,matchesCron:()=>jo,memoryStorage:()=>eo,merge:()=>wt,mergeMap:()=>Ta,nameToSignal:()=>gn,ndjsonRows:()=>ul,never:()=>yc,nodeSignal:()=>Xo,of:()=>Zi,onFirstData:()=>Kr,pairwise:()=>fd,parseCron:()=>$o,parsePrometheusText:()=>Ea,parseSSEStream:()=>Lt,parseStatsD:()=>el,parseSyslog:()=>Xd,pausable:()=>Cd,pubsub:()=>$l,race:()=>gd,rateLimiter:()=>qn,reactiveCounter:()=>ea,reactiveIndex:()=>Vl,reactiveList:()=>Ms,reactiveLog:()=>Ue,reactiveMap:()=>Xe,reactiveSink:()=>We,reduce:()=>od,repeat:()=>Od,replay:()=>Yo,rescue:()=>Hr,resolveBackoffPreset:()=>$t,retry:()=>Hn,retrySource:()=>jt,sample:()=>wd,scan:()=>rd,serializeError:()=>yn,share:()=>Tc,shareReplay:()=>kc,signalToName:()=>qt,singleFromAny:()=>Os,singleNodeFromAny:()=>Kl,skip:()=>ba,sortJsonValue:()=>Zr,stableJsonString:()=>Hl,stratify:()=>to,switchMap:()=>Se,take:()=>Vr,takeUntil:()=>id,takeWhile:()=>sd,tap:()=>dd,tapFirst:()=>ld,throttle:()=>ka,throttleTime:()=>Dd,throwError:()=>bc,timeout:()=>zn,toArray:()=>vc,toCSV:()=>bl,toClickHouse:()=>vl,toFile:()=>_a,toHTTP:()=>Fd,toKafka:()=>rl,toLoki:()=>xl,toMongo:()=>kl,toNATS:()=>hl,toObservable:()=>Fo,toPostgres:()=>wl,toPulsar:()=>fl,toRabbitMQ:()=>yl,toReadableStream:()=>Kd,toRedisStream:()=>sl,toS3:()=>Tl,toSSE:()=>Bd,toSSEBytes:()=>Vd,toSqlite:()=>Ml,toTempo:()=>Rl,toWebSocket:()=>Ud,tokenBucket:()=>Bt,valve:()=>Ad,verifiable:()=>Gl,window:()=>_d,windowCount:()=>Sd,windowTime:()=>Ed,withBreaker:()=>Wn,withLatestFrom:()=>At,withMaxAttempts:()=>Yi,withStatus:()=>Vt,workerBridge:()=>Oa,workerSelf:()=>Ca,zip:()=>md});Ae();_e();ae();Le();ee();Ae();ae();ee();function td(t){return{describeKind:"producer",...t}}function hn(t,e){return H(n=>{let r=!0,o={emit(i){r&&n.emit(i)},error(i){r&&(r=!1,n.down([[O,i]]))},complete(){r&&(r=!1,n.down([[C]]))}},s;try{let i=t(o);s=typeof i=="function"?i:void 0}catch(i){return o.error(i),()=>{r=!1}}return()=>{r=!1;try{s?.()}catch{}}},td(e))}function xs(t,e,n){let r=!0,o,s=0,i=0,a={},u=[],c=()=>{let f=o;o=void 0;try{f?.()}catch{}};for(let f of e){let m=n?.name?`${n.name}::${f}`:f,g=n?.channelOpts?.[f],h=H(y=>(s++,()=>{i++,s>0&&i>=s&&i>=e.length&&c()}),td({...g,name:m}));a[f]=h,u.push(h)}let d={};for(let f of e)d[f]=m=>{r&&a[f].down([[S,m]])};d.error=f=>{r&&(r=!1,Z(()=>{for(let m of u)m.down([[O,f]])}),c())},d.complete=()=>{r&&(r=!1,Z(()=>{for(let f of u)f.down([[C]])}),c())};let l=t(d);return o=typeof l=="function"?l:void 0,Object.assign(a,{dispose:()=>{r&&(r=!1,Z(()=>{for(let f of u)try{f.down([[C]])}catch{}}),c())}})}_e();ae();Le();ee();Re();function me(t){return{describeKind:"derived",...t}}function nd(t){return{describeKind:"derived",partial:!0,...t}}function Br(t,e,n){return U([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[F]]);return}for(let i of s)o.emit(e(i))},me(n))}function it(t,e,n){return U([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[F]]);return}let i=!1;for(let a of s)e(a)&&(o.emit(a),i=!0);i||o.down([[F]])},me(n))}function rd(t,e,n,r){return U([t],(o,s,i)=>{"acc"in i.store||(i.store.acc=n);let a=o[0];if(a==null||a.length===0){s.down([[F]]);return}for(let u of a)i.store.acc=e(i.store.acc,u),s.emit(i.store.acc)},{...me(r),initial:n,resetOnTeardown:!0})}function od(t,e,n,r){return U([t],(o,s,i)=>{if("acc"in i.store||(i.store.acc=n),i.terminalDeps[0]===!0){s.emit(i.store.acc),s.down([[C]]);return}let a=o[0];if(a==null||a.length===0){s.down([[F]]);return}for(let u of a)i.store.acc=e(i.store.acc,u)},{...me(r),completeWhenDepsComplete:!1})}function Vr(t,e,n){return e<=0?U([t],(r,o,s)=>{s.store.completed||(s.store.completed=!0,o.down([[C]]))},{...me(n),completeWhenDepsComplete:!1}):U([t],(r,o,s)=>{if("taken"in s.store||(s.store.taken=0),s.store.done){o.down([[F]]);return}if(s.terminalDeps[0]===!0){s.store.done=!0,o.down([[C]]);return}let i=r[0];if(i==null||i.length===0){o.down([[F]]);return}for(let a of i)if(s.store.taken++,o.emit(a),s.store.taken>=e){s.store.done=!0,o.down([[C]]);return}},{...me(n),completeWhenDepsComplete:!1})}function ba(t,e,n){return U([t],(r,o,s)=>{"skipped"in s.store||(s.store.skipped=0);let i=r[0];if(i==null||i.length===0){o.down([[F]]);return}let a=!1;for(let u of i)s.store.skipped++,s.store.skipped<=e||(o.emit(u),a=!0);a||o.down([[F]])},me(n))}function sd(t,e,n){return U([t],(r,o,s)=>{if(s.store.done){o.down([[F]]);return}let i=r[0];if(i==null||i.length===0){o.down([[F]]);return}for(let a of i){if(!e(a)){s.store.done=!0,o.down([[C]]);return}o.emit(a)}},{...me(n),completeWhenDepsComplete:!1})}function id(t,e,n){let r=n?.predicate??(i=>i[0]===S),{predicate:o,...s}=n??{};return H(i=>{let a=!1,u=t.subscribe(d=>{if(!a)for(let l of d){if(a)return;l[0]===S?i.emit(l[1]):(l[0]===C||l[0]===O)&&(a=!0,i.down([l]))}}),c=e.subscribe(d=>{if(!a)for(let l of d){if(a)return;if(r(l)){a=!0,i.down([[C]]);return}}});return()=>{u(),c()}},me(s))}function Rs(t,e){return Vr(t,1,e)}function ad(t,e){let{defaultValue:n,...r}=e??{},o=e!=null&&Object.hasOwn(e,"defaultValue");return U([t],(s,i,a)=>{if(a.terminalDeps[0]===!0){a.store.has?i.emit(a.store.latest):o&&i.emit(n),i.down([[C]]);return}let u=s[0];if(u==null||u.length===0){i.down([[F]]);return}a.store.latest=u.at(-1),a.store.has=!0},{...me(r),completeWhenDepsComplete:!1})}function ud(t,e,n){return Vr(it(t,e,n),1,n)}function cd(t,e,n){return Vr(ba(t,e,n),1,n)}function dd(t,e,n){if(typeof e=="function")return U([t],(o,s)=>{let i=o[0];if(i==null||i.length===0){s.down([[F]]);return}for(let a of i)e(a),s.emit(a)},me(n));let r=e;return U([t],(o,s,i)=>{if(i.terminalDeps[0]!==void 0){i.terminalDeps[0]===!0?(r.complete?.(),s.down([[C]])):(r.error?.(i.terminalDeps[0]),s.down([[O,i.terminalDeps[0]]]));return}let a=o[0];if(a==null||a.length===0){s.down([[F]]);return}for(let u of a)r.data?.(u),s.emit(u)},{...me(n),completeWhenDepsComplete:!1})}function Kr(t,e,n){let r=n?.where??(s=>s!=null),o=!1;return U([t],(s,i)=>{let a=s[0];if(a==null||a.length===0){i.down([[F]]);return}for(let u of a)!o&&r(u)&&(o=!0,e(u)),i.emit(u)},me(n))}var ld=Kr;function pd(t,e=Object.is,n){return U([t],(r,o,s)=>{let i=r[0];if(i==null||i.length===0){o.down([[F]]);return}let a=!1;for(let u of i)s.store.hasPrev&&e(s.store.prev,u)||(s.store.prev=u,s.store.hasPrev=!0,o.emit(u),a=!0);a||o.down([[F]])},me(n))}function fd(t,e){return U([t],(n,r,o)=>{let s=n[0];if(s==null||s.length===0){r.down([[F]]);return}let i=!1;for(let a of s)if(!o.store.hasPrev)o.store.prev=a,o.store.hasPrev=!0;else{let u=[o.store.prev,a];o.store.prev=a,r.emit(u),i=!0}i||r.down([[F]])},me(e))}function va(...t){let e=[...t];return _(e,n=>n,{...me(),equals:(n,r)=>{if(n.length!==r.length)return!1;for(let o=0;o<n.length;o++)if(!Object.is(n[o],r[o]))return!1;return!0}})}function At(t,e,n){return U([t,e],(r,o,s)=>{let i=r[0],a=r[1],u=a!=null&&a.length>0?a.at(-1):s.prevData[1];if(i!=null&&i.length>0){if(!(a!=null&&a.length>0)&&s.prevData[1]===void 0){o.down([[F]]);return}for(let c of i)o.emit([c,u])}else o.down([[F]])},nd(n))}function wt(...t){return t.length===0?H(e=>{e.down([[C]])},me()):H(e=>{let n=t.length,r=0,o=[];for(let s of t){let i=s.subscribe(a=>{for(let u of a)u[0]===S?e.emit(u[1]):u[0]===C?(r+=1,r>=n&&e.down([[C]])):u[0]===O&&e.down([u])});o.push(i)}return()=>{for(let s of o)s()}},me())}function md(...t){let e=t.length;return e===0?H(n=>{n.emit([]),n.down([[C]])},me()):H(n=>{let r=Array.from({length:e},()=>[]),o=e;function s(){for(;r.every(a=>a.length>0);){let a=r.map(u=>u.shift());n.emit(a)}}let i=[];for(let a=0;a<e;a++){let u=a,c=t[a].subscribe(d=>{for(let l of d)l[0]===S?(r[u].push(l[1]),s()):l[0]===C?(o-=1,(o===0||r[u].length===0)&&n.down([[C]])):l[0]===O&&n.down([l])});i.push(c)}return()=>{for(let a of i)a()}},me())}function hd(t,e,n){return H(r=>{let o=0,s=[],i,a;return a=e.subscribe(u=>{for(let c of u)o===0?c[0]===S?s.push(c[1]):c[0]===O&&r.down([c]):c[0]===S?r.emit(c[1]):(c[0]===C||c[0]===O)&&r.down([c])}),i=t.subscribe(u=>{for(let c of u)if(o===0)if(c[0]===S)r.emit(c[1]);else if(c[0]===C){o=1;for(let d of s)r.emit(d);s.length=0}else c[0]===O&&r.down([c])}),()=>{i?.(),a?.()}},me(n))}function gd(...t){return t.length===0?H(e=>{e.down([[C]])},me()):t.length===1?U([t[0]],(e,n)=>{let r=e[0];if(r==null||r.length===0){n.down([[F]]);return}for(let o of r)n.emit(o)},me()):H(e=>{let n=null,r=[];for(let o=0;o<t.length;o++){let s=o,i=t[o].subscribe(a=>{for(let u of a){if(n!==null&&s!==n)return;u[0]===S?(n===null&&(n=s),e.emit(u[1])):(u[0]===C||u[0]===O)&&(n===null||s===n)&&e.down([u])}});r.push(i)}return()=>{for(let o of r)o()}},me())}function Ss(t,e,n){let r,o=!1,s=()=>{o||(o=!0,n())};return r=t.subscribe(i=>{let a=!1,u=!1;for(let c of i)c[0]!==yt&&(c[0]===S?e.emit(c[1]):c[0]===C?a=!0:c[0]===O?(u=!0,e.down([c])):(c[0]===te||c[0]===F)&&e.down([c]));u?(r?.(),r=void 0,s()):a&&s()}),()=>{r?.(),r=void 0}}function Se(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return U([t],(i,a,u)=>{if(u.terminalDeps[0]!=null&&u.terminalDeps[0]!==!0){s();return}if(u.terminalDeps[0]===!0){o=!0,r||a.down([[C]]);return}let c=i[0];if(!(c==null||c.length===0))return s(),r=Ss(X(e(c[c.length-1])),a,()=>{s(),o&&a.down([[C]])}),{deactivate:()=>{s(),o=!1}}},{...me(n),completeWhenDepsComplete:!1})}function yd(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return U([t],(i,a,u)=>{if(u.terminalDeps[0]!=null&&u.terminalDeps[0]!==!0){s();return}if(u.terminalDeps[0]===!0){o=!0,r||a.down([[C]]);return}let c=i[0];if(!(c==null||c.length===0))return r===void 0?r=Ss(X(e(c[0])),a,()=>{s(),o&&a.down([[C]])}):a.down([[F]]),{deactivate:()=>{s(),o=!1}}},{...me(n),completeWhenDepsComplete:!1})}function bd(t,e,n){let{maxBuffer:r,...o}=n??{},s=[],i,a=!1,u;function c(){i?.(),i=void 0}function d(){if(!u||i!==void 0)return;if(s.length===0){a&&u.down([[C]]);return}let p=s.shift();i=Ss(X(e(p)),u,()=>{c(),d()})}function l(p){r&&r>0&&s.length>=r&&s.shift(),s.push(p),d()}return U([t],(p,f,m)=>{if(u=f,m.terminalDeps[0]!=null&&m.terminalDeps[0]!==!0){c(),s.length=0;return}if(m.terminalDeps[0]===!0){a=!0,d();return}let g=p[0];if(!(g==null||g.length===0)){for(let h of g)l(h);return{deactivate:()=>{c(),s.length=0,a=!1}}}},{...me(o),completeWhenDepsComplete:!1})}function Ta(t,e,n){let{concurrent:r,...o}=n??{},s=r!=null&&r>0?r:Number.POSITIVE_INFINITY,i=0,a=!1,u=new Set,c=[],d;function l(){a&&i===0&&c.length===0&&d&&d.down([[C]])}function p(h){if(!d)return;i++;let y;y=Ss(X(e(h)),d,()=>{y&&u.delete(y),i--,f(),l()}),u.add(y)}function f(){for(;c.length>0&&i<s;)p(c.shift())}function m(h){i<s?p(h):c.push(h)}function g(){for(let h of u)h();u.clear(),i=0,c.length=0}return U([t],(h,y,b)=>{if(d=y,b.terminalDeps[0]!=null&&b.terminalDeps[0]!==!0){g();return}if(b.terminalDeps[0]===!0){a=!0,l();return}let v=h[0];if(!(v==null||v.length===0)){for(let T of v)m(T);return{deactivate:()=>{g(),a=!1}}}},{...me(o),completeWhenDepsComplete:!1})}var vd=Ta;function Td(t,e,n){return H(r=>{let o=new Set;function s(){for(let a of o)clearTimeout(a);o.clear()}let i=t.subscribe(a=>{for(let u of a)if(u[0]===S){let c=setTimeout(()=>{o.delete(c),r.emit(u[1])},e);o.add(c)}else if(u[0]===C){let c=setTimeout(()=>{o.delete(c),r.down([[C]])},e);o.add(c)}else u[0]===O&&(s(),r.down([u]))});return()=>{i(),s()}},me(n))}function wa(t,e,n){return H(r=>{let o,s;function i(){o!==void 0&&(clearTimeout(o),o=void 0)}let a=t.subscribe(u=>{for(let c of u)c[0]===S?(i(),s=c[1],o=setTimeout(()=>{o=void 0,r.emit(s)},e)):c[0]===C?(o!==void 0&&(i(),r.emit(s)),r.down([[C]])):c[0]===O&&(i(),r.down([c]))});return()=>{a(),i()}},me(n))}function ka(t,e,n){let{leading:r,trailing:o,...s}=n??{},i=r!==!1,a=o===!0,u=e*1e6;return H(c=>{let d,l=-1/0,p,f=!1;function m(){d!==void 0&&(clearTimeout(d),d=void 0)}let g=t.subscribe(h=>{for(let y of h)if(y[0]===S){let b=y[1],v=j();if(i&&v-l>=u)l=v,c.emit(b),m(),a&&(d=setTimeout(()=>{d=void 0,f&&(l=j(),c.emit(p),f=!1)},e));else if(a&&(p=b,f=!0,d===void 0)){let T=(v-l)/1e6;d=setTimeout(()=>{d=void 0,f&&(l=j(),c.emit(p),f=!1)},Math.max(0,e-T))}}else(y[0]===C||y[0]===O)&&(m(),c.down([y]))});return()=>{g(),m()}},me(s))}function wd(t,e,n){return H(r=>{let o,s=!1,i=!1,a=t.subscribe(c=>{if(!s)for(let d of c){if(s)return;d[0]===S?o={v:d[1]}:d[0]===O?(s=!0,r.down([d])):d[0]===C&&(i=!0,o=void 0)}}),u=e.subscribe(c=>{if(!s)for(let d of c){if(s)return;d[0]===S?o!==void 0&&!i&&r.emit(o.v):d[0]===O?(s=!0,r.down([d])):d[0]===C&&(s=!0,r.down([[C]]))}});return()=>{a(),u()}},me(n))}function kd(t,e,n){return H(r=>{let o,s,i=!1;function a(){o!==void 0&&(clearTimeout(o),o=void 0)}let u=t.subscribe(c=>{for(let d of c)d[0]===S?(s=d[1],i=!0,a(),o=setTimeout(()=>{o=void 0,i&&(i=!1,r.emit(s))},e)):(d[0]===C||d[0]===O)&&(a(),r.down([d]))});return()=>{u(),a()}},me(n))}function xd(t,e,n){return H(r=>{let o=[],s=t.subscribe(a=>{for(let u of a)u[0]===S?o.push(u[1]):u[0]===C?(o.length>0&&r.emit([...o]),o.length=0,r.down([[C]])):u[0]===O&&r.down([u])}),i=e.subscribe(a=>{for(let u of a)u[0]===S?o.length>0&&(r.emit([...o]),o.length=0):u[0]===C?r.down([[C]]):u[0]===O&&r.down([u])});return()=>{s(),i(),o.length=0}},me(n))}function Rd(t,e,n){if(e<=0)throw new RangeError("bufferCount expects count > 0");return H(r=>{let o=[],s=t.subscribe(i=>{for(let a of i)a[0]===S?(o.push(a[1]),o.length>=e&&r.emit(o.splice(0,o.length))):a[0]===C?(o.length>0&&r.emit([...o]),o.length=0,r.down([[C]])):a[0]===O&&r.down([a])});return()=>{s(),o.length=0}},me(n))}function Sd(t,e,n){if(e<=0)throw new RangeError("windowCount expects count > 0");return H(r=>{let o,s=0;function i(){let u=H(c=>(o=c.down.bind(c),()=>{o=void 0}),me());s=0,r.emit(u)}let a=t.subscribe(u=>{for(let c of u)c[0]===S?(o||i(),o?.([[S,c[1]]]),s+=1,s>=e&&(o?.([[C]]),o=void 0)):c[0]===C?(o?.([[C]]),o=void 0,r.down([[C]])):c[0]===O&&(o?.([c]),o=void 0,r.down([c]))});return()=>{a(),o?.([[C]]),o=void 0}},me(n))}function Nd(t,e,n){return H(r=>{let o=[],s=setInterval(()=>{o.length>0&&(r.emit([...o]),o.length=0)},e),i=t.subscribe(a=>{for(let u of a)u[0]===S?o.push(u[1]):u[0]===C?(clearInterval(s),o.length>0&&r.emit([...o]),o.length=0,r.down([[C]])):u[0]===O&&(clearInterval(s),r.down([u]))});return()=>{i(),clearInterval(s),o.length=0}},me(n))}function Ed(t,e,n){return H(r=>{let o;function s(){o?.([[C]]),o=void 0}function i(){let c=H(d=>(o=d.down.bind(d),()=>{o=void 0}),me());r.emit(c)}i();let a=setInterval(()=>{s(),i()},e),u=t.subscribe(c=>{for(let d of c)d[0]===S?o?.([[S,d[1]]]):d[0]===C?(clearInterval(a),s(),r.down([[C]])):d[0]===O&&(clearInterval(a),o?.([d]),s(),r.down([d]))});return()=>{u(),clearInterval(a),s()}},me(n))}function _d(t,e,n){return H(r=>{let o;function s(){o?.([[C]]),o=void 0}function i(){let c=H(d=>(o=d.down.bind(d),()=>{o=void 0}),me());r.emit(c)}let a=t.subscribe(c=>{for(let d of c)d[0]===S?(o||i(),o?.([[S,d[1]]])):d[0]===C?(s(),r.down([[C]])):d[0]===O&&(o?.([d]),o=void 0,r.down([d]))}),u=e.subscribe(c=>{for(let d of c)d[0]===S&&(s(),i())});return()=>{a(),u(),s()}},me(n))}function Md(t,e){return H((n,r)=>{"n"in r.store||(r.store.n=0);let o=setInterval(()=>{n.emit(r.store.n),r.store.n=r.store.n+1},t);return()=>clearInterval(o)},me(e))}function Od(t,e,n){if(e<=0)throw new RangeError("repeat expects count > 0");return H(r=>{let o=e,s,i=()=>{s?.(),s=t.subscribe(a=>{let u=!1,c=[];for(let d of a)d[0]===C?u=!0:c.push(d);c.length>0&&r.down(c),u&&(s?.(),s=void 0,o-=1,o>0?i():r.down([[C]]))})};return i(),()=>{s?.()}},me(n))}function Cd(t,e){return U([t],(n,r)=>{let o=n[0];if(o==null||o.length===0){r.down([[F]]);return}for(let s of o)r.emit(s)},me(e))}function Hr(t,e,n){return H(r=>{let o=t.subscribe(s=>{for(let i of s)if(i[0]===S)r.emit(i[1]);else if(i[0]===O)try{r.emit(e(i[1]))}catch(a){r.down([[O,a]])}else i[0]===C&&r.down([[C]])});return()=>{o()}},me(n))}function Ad(t,e,n){return U([t,e],(r,o,s)=>{let i=r[1];if(!(i!=null&&i.length>0?i.at(-1):s.prevData[1])){o.down([[F]]);return}let u=r[0];if(u!=null&&u.length>0){for(let c of u)o.emit(c);return}if(i!=null&&i.length>0&&s.prevData[0]!==void 0){o.emit(s.prevData[0]);return}o.down([[F]])},nd(n))}var Ld=va,Id=wa,Dd=ka,Pd=Hr;ae();Le();ee();Kn();var xa=class{ring;arr;constructor(e){e===Number.POSITIVE_INFINITY||e<=0?(this.arr=[],this.ring=null):(this.ring=new pn(e),this.arr=null)}get length(){return this.ring!=null?this.ring.size:this.arr.length}push(e){this.ring!=null?this.ring.push(e):this.arr.push(e)}shift(){return this.ring!=null?this.ring.shift():this.arr.shift()}drain(){if(this.ring!=null){let n=this.ring.toArray();return this.ring.clear(),n}let e=this.arr;return this.arr=[],e}};function Wr(t){return t instanceof Error?t:new Error(String(t))}function Ym(t){return t===void 0?null:typeof t=="string"?$t(t):t}function We(t,e){let{name:n,onTransportError:r,retry:o,backpressure:s,batchSize:i=Number.POSITIVE_INFINITY,flushIntervalMs:a=0,serialize:u,stopOn:c,onUpstreamMessage:d,onDispose:l,send:p,sendBatch:f,ctx:m}=e;if(!p&&!f)throw new Error("reactiveSink: `send` or `sendBatch` must be provided");let g=m,h=Math.max(1,o?.maxAttempts??1),y=Ym(o?.backoff??(h>1?"exponential":void 0)),b=o?.shouldRetry??(()=>!0),v=f!==void 0||i<Number.POSITIVE_INFINITY||a>0,T=V=>n?`${n}::${V}`:void 0,w=E(void 0,{equals:()=>!1,name:T("sent")}),k=E(null,{name:T("failed")}),x=E(0,{name:T("inFlight")}),R=E(null,{name:T("errors")}),N=v?E(0,{name:T("buffered")}):void 0,A=s?E(!1,{name:T("paused")}):void 0,M=0,I=V=>{M+=V,x.down([[S,M]])},L=V=>{try{r?.(V)}catch{}try{R.down([[S,V]])}catch{}},P=new Set,J=V=>{P.add(V);let fe=()=>P.delete(V);V.then(fe,fe)},Q=(V,fe,Ee)=>{let Me=y?y(fe-1,Ee,null):0,be=Me==null?0:typeof Me=="number"&&Me>0?Me:0,Ge=Math.max(1,Math.ceil(be/1e6));return new Promise(we=>{setTimeout(()=>we(V()),Ge)})},D=V=>V!=null&&typeof V=="object"&&typeof V.then=="function",z=V=>{let fe;try{fe=u?u(V):V}catch(we){let ke=Wr(we);return L({stage:"serialize",error:ke,value:V}),k.down([[S,{value:V,error:ke,attempts:0}]]),Promise.resolve()}let Ee=0,Me=we=>{I(-1);let ke=Wr(we);if(L({stage:"send",error:ke,value:V,attempt:Ee}),!(Ee<h&&b(ke,Ee))){k.down([[S,{value:V,error:ke,attempts:Ee}]]);return}return Q(Ge,Ee,ke)},be=()=>{I(-1),w.down([[S,V]])};function Ge(){Ee+=1,I(1);let we;try{we=p(fe,g)}catch(ke){return Me(ke)??Promise.resolve()}return D(we)?we.then(be,ke=>Me(ke)):(be(),Promise.resolve())}return Ge()},W=s?.maxBuffer??Number.POSITIVE_INFINITY,ie=new xa(W),B,$=!1,G=()=>{N?.down([[S,ie.length]])},q=V=>{A&&A.down([[S,V]])},ce=s?.strategy??"drop-oldest",he=(V,fe)=>{let Ee={value:V,payload:fe};if(ie.length<W)return ie.push(Ee),G(),!0;if(ce==="drop-oldest"){let be=ie.shift();return ie.push(Ee),G(),q(!0),k.down([[S,{value:be.value,error:new Error("backpressure: buffer overflow \u2014 dropped oldest"),attempts:0}]]),!0}if(ce==="drop-newest")return q(!0),k.down([[S,{value:V,error:new Error("backpressure: buffer overflow \u2014 dropped newest"),attempts:0}]]),!1;let Me=new Error("backpressure: buffer overflow");return L({stage:"send",error:Me,value:V}),k.down([[S,{value:V,error:Me,attempts:0}]]),q(!0),!1},xe=V=>{let fe=0,Ee=V.map(we=>we.payload),Me=we=>{I(-1);let ke=Wr(we);if(L({stage:"send",error:ke,value:V.map(Nn=>Nn.value),attempt:fe}),!(fe<h&&b(ke,fe))){for(let{value:Nn}of V)k.down([[S,{value:Nn,error:ke,attempts:fe}]]);return}return Q(Ge,fe,ke)},be=()=>{I(-1);for(let{value:we}of V)w.down([[S,we]])};function Ge(){fe+=1,I(1);let we;try{we=f(Ee,g)}catch(ke){return Me(ke)??Promise.resolve()}return D(we)?we.then(be,ke=>Me(ke)):(be(),Promise.resolve())}return Ge()},oe=async V=>{for(let fe of V)await ye(fe.value,fe.payload)},ye=(V,fe)=>{let Ee=0,Me=we=>{I(-1);let ke=Wr(we);if(L({stage:"send",error:ke,value:V,attempt:Ee}),!(Ee<h&&b(ke,Ee))){k.down([[S,{value:V,error:ke,attempts:Ee}]]);return}return Q(Ge,Ee,ke)},be=()=>{I(-1),w.down([[S,V]])};function Ge(){Ee+=1,I(1);let we;try{we=p(fe,g)}catch(ke){return Me(ke)??Promise.resolve()}return D(we)?we.then(be,ke=>Me(ke)):(be(),Promise.resolve())}return Ge()},re=()=>{if($||ie.length===0)return Promise.resolve();let V=ie.drain();if(G(),q(!1),f!==void 0){let Ee=xe(V);return J(Ee),Ee}let fe=oe(V);return J(fe),fe},ge=()=>{B!==void 0||$||a<=0||(B=setTimeout(()=>{B=void 0,re()},a))},Oe=t.subscribe(V=>{for(let fe of V){let Ee=fe[0];if(Ee!==S)try{d?.(fe)}catch{}if(Ee===S){let Me=fe[1];if(v){let be;if(u)try{be=u(Me)}catch(we){let ke=Wr(we);L({stage:"serialize",error:ke,value:Me}),k.down([[S,{value:Me,error:ke,attempts:0}]]);continue}else be=Me;if(!he(Me,be))continue;ie.length>=i?re():ge()}else{let be=z(Me);J(be)}}else $e.messageTier(Ee)>=3&&v&&(B!==void 0&&(clearTimeout(B),B=void 0),re())}}),le;if(c){let V=!1;le=c.subscribe(fe=>{if(!V){V=!0;return}fe.length>0&&!K&&ne()})}let K=!1,ne=()=>{if(K)return;K=!0,B!==void 0&&(clearTimeout(B),B=void 0),v&&re(),$=!0,le?.(),Oe();let V=fe=>{try{fe.down([[ve]])}catch{}};V(R),V(k),V(w),V(x),N&&V(N),A&&V(A);try{l?.()}catch{}},pe={dispose:ne,sent:w,failed:k,inFlight:x,errors:R};return v&&(pe.buffered=N,pe.flush=async()=>{$||(await re(),await Promise.all(P))}),A&&(pe.paused=A),pe}Et();Re();function mt(t){return{describeKind:"producer",...t}}function Sa(t,e){let{parse:n,closeOnTeardown:r=!1,...o}=e??{};return H(s=>{let i=!0,a,u=()=>{let y=a;a=void 0,y?.()},c=y=>{i&&(i=!1,s.down([y]),u())},d=(y,b=y)=>{if(i)try{let v=y!==null&&typeof y=="object"&&"data"in y?y.data:y,T=n?n(v,b):v;s.emit(T)}catch(v){c([O,v])}},l=y=>{c([O,y])},p=()=>{c([C])};if(typeof t=="function"){try{if(a=t(d,l,p),typeof a!="function")throw new Error("fromWebSocket register contract violation: register must return cleanup callable")}catch(y){c([O,y])}return()=>{i=!1,u()}}let f=t,m=y=>d(y,y),g=y=>l(y),h=()=>p();return f.addEventListener("message",m),f.addEventListener("error",g),f.addEventListener("close",h),a=()=>{f.removeEventListener("message",m),f.removeEventListener("error",g),f.removeEventListener("close",h),r&&f.close()},()=>{i=!1,u()}},mt(o))}function Gd(t,e){return hn(t,e)}function Na(t,e){let{method:n="GET",headers:r,body:o,transform:s=v=>v.json(),timeoutNs:i=30*1e9,signal:a,completeAfterFetch:u=!1,refetchOnSubscribe:c=!1,...d}=e??{},l=E(0,{name:`${d.name??"http"}/fetchCount`}),p=E(0,{name:`${d.name??"http"}/lastUpdated`}),f=E(!1,{name:`${d.name??"http"}/fetched`}),m=0,g=o!==void 0?typeof o=="string"?o:JSON.stringify(o):void 0,h=v=>{let T=new AbortController,w=!0;if(a?.aborted)return w=!1,v.down([[O,a.reason??new Error("Aborted")]]),()=>{};a?.addEventListener("abort",()=>T.abort(a.reason),{once:!0});let k=setTimeout(()=>T.abort(new Error("Request timeout")),Math.ceil(i/1e6));return fetch(t,{method:n,headers:r,body:g,signal:T.signal}).then(async x=>{if(clearTimeout(k),!w)return;if(!x.ok)throw new Error(`HTTP ${x.status}: ${x.statusText}`);let R=await s(x);w&&(Z(()=>{m+=1,l.down([[S,m]]),p.down([[S,Te()]]),f.down([[S,!0]]),v.emit(R)}),u&&v.down([[C]]))}).catch(x=>{clearTimeout(k),w&&(x&&x.name==="AbortError"||v.down([[O,x]]))}),()=>{w=!1,T.abort()}},y=H(v=>h({emit:T=>v.emit(T),down:T=>v.down(T)}),{...mt(d),resubscribable:c});return{...Vt(y),fetchCount:l,lastUpdated:p,fetched:f}}function Fd(t,e,n){let{method:r="POST",headers:o={"Content-Type":"application/json"},serialize:s=m=>JSON.stringify(m),timeoutNs:i,batchFormat:a="json-array",batchSize:u,flushIntervalMs:c,retry:d,onTransportError:l}=n??{},p=async m=>{let g=i!==void 0?new AbortController:void 0,h;g&&i!==void 0&&(h=setTimeout(()=>g.abort(new Error("Request timeout")),Math.ceil(i/1e6)));try{let y=await fetch(e,{method:r,headers:o,body:m,signal:g?.signal}),b=async()=>{try{await y.arrayBuffer?.()}catch{}};if(!y.ok)throw await b(),new Error(`HTTP ${y.status}: ${y.statusText}`);await b()}finally{h!==void 0&&clearTimeout(h)}};return u!==void 0||c!==void 0?We(t,{onTransportError:l,retry:d,batchSize:u,flushIntervalMs:c,sendBatch:async m=>{let g;a==="ndjson"?g=m.map(h=>{let y=s(h);return typeof y=="string"?y:new TextDecoder().decode(y)}).join(`
16
- `):g=JSON.stringify(m),await p(g)}}):We(t,{onTransportError:l,retry:d,serialize:s,send:async m=>{await p(m)}})}function $d(t){return Symbol.keyFor(t)??t.description??"message"}function Zn(t,e){return typeof t=="string"?t:e(t)}function jd(t,e){let n=`event: ${t}
17
- `;if(e!==void 0){let r=e.split(/\r?\n/);for(let o of r)n+=`data: ${o}
9
+ `,n}function Kf(t){return JSON.parse(t)}function Hf(t,e){try{t.send(JSON.stringify(e))}catch{}}function Qi(t,e){try{t(e)}catch{}}Tr();var Jo="graphReflyActor";function Xi(t){return e=>{let r=e.switchToHttp().getRequest()?.user;if(r!=null)return t?t(r):r}}function Md(t="x-graphrefly-actor"){return e=>{let r=e.switchToHttp().getRequest()?.headers?.[t.toLowerCase()];if(!(typeof r!="string"||r.length===0))try{return JSON.parse(r)}catch{return}}}function Od(t){let e=t?.[Jo];return e!=null?St(e):bt}var Lr=class{constructor(e){this.extractor=e}canActivate(e){let n=St(this.extractor(e)),r=e.switchToHttp().getRequest();return r!=null&&(r[Jo]=n),!0}};function Cd(t){return new Lr(t??Xi())}var jr=require("@nestjs/common"),tc=require("@nestjs/core");Tr();Ce();Ne();nn();se();nn();_e();function _t(t,e){if(e!=null&&e.length>0)return new Set(e);switch(t){case"standard":return new Set(["type","status","value","deps","meta","v"]);case"full":return null;default:return new Set(["type","deps"])}}function qf(t){return t._describeKind!=null?t._describeKind:t._deps.length>0?"derived":t._fn!=null?"producer":"state"}function Wf(t){let e={};for(let[n,r]of Object.entries(t.meta))try{e[n]=r.cache}catch{}return e}function Ir(t,e){let n=e==null,r=!n&&e!=null?[...e].filter(d=>d.startsWith("meta.")).map(d=>d.slice(5)):null,s=n||e.has("meta")||r!=null&&r.length>0,o="state",i=[];t instanceof Ae&&(o=qf(t),i=t._deps.map(d=>d.node.name??""));let a={type:o,deps:i};(n||e.has("status"))&&(a.status=t.status);let u=t instanceof Ae?t._guard:void 0;if(s){let d={...Wf(t)};if(u!=null&&d.access===void 0&&(d.access=Nr(u)),r!=null&&r.length>0&&!e.has("meta")){let c={};for(let l of r)l in d&&(c[l]=d[l]);a.meta=c}else a.meta=d}if(t.name!=null&&(a.name=t.name),n||e.has("value")){t.status==="sentinel"&&(a.sentinel=!0);try{a.value=t.cache}catch{}}if((n||e.has("v"))&&t.v!=null){let d={id:t.v.id,version:t.v.version};"cid"in t.v&&(d.cid=t.v.cid,d.prev=t.v.prev),a.v=d}return(n||e.has("guard"))&&u!=null&&(a.guard=Nr(u)),(n||e.has("lastMutation"))&&t.lastMutation!=null&&(a.lastMutation=t.lastMutation),a}_e();Q();Te();vt();var ln=class{constructor(e){this.capacity=e;if(!Number.isInteger(e)||e<=0)throw new Error(`RingBuffer capacity must be a positive integer (got ${e})`);this.buf=new Array(e)}buf;head=0;_size=0;get size(){return this._size}get maxSize(){return this.capacity}push(e){let n=(this.head+this._size)%this.capacity;this.buf[n]=e,this._size<this.capacity?this._size++:this.head=(this.head+1)%this.capacity}shift(){if(this._size===0)return;let e=this.buf[this.head];return this.buf[this.head]=void 0,this.head=(this.head+1)%this.capacity,this._size--,e}at(e){if(this._size===0)return;let n=e<0?this._size+e:e;if(!(n<0||n>=this._size))return this.buf[(this.head+n)%this.capacity]}toArray(){let e=new Array(this._size);for(let n=0;n<this._size;n++)e[n]=this.buf[(this.head+n)%this.capacity];return e}clear(){for(let e=0;e<this._size;e++)this.buf[(this.head+e)%this.capacity]=void 0;this.head=0,this._size=0}};So();function Zi(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 Qn(t){let e=0;for(let n of t)e+=Zi(n.codePointAt(0));return e}function Ad(t,e){if(e<=0)return"";let n=0,r="";for(let s of t){let o=Zi(s.codePointAt(0));if(n+o>e){if(e<=1)return"\u2026";for(;n+1>e&&r.length>0;){let i=[...r].pop();r=r.slice(0,-i.length),n-=Zi(i.codePointAt(0))}return`${r}\u2026`}r+=s,n+=o}return r}var Uf={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"},zf={horizontal:"-",vertical:"|",cornerTL:"+",cornerTR:"+",cornerBL:"+",cornerBR:"+",tDown:"+",tUp:"+",tRight:"+",tLeft:"+",cross:"+",arrowRight:">",arrowDown:"v",arrowLeft:"<",arrowUp:"^",boxTL:"+",boxTR:"+",boxBL:"+",boxBR:"+",boxH:"-",boxV:"|"};function Pd(t,e){let n=e.charset==="ascii"?zf:Uf,r=t.width,s=t.height,o=Array.from({length:s},()=>Array.from({length:r},()=>" ")),i=Array.from({length:s},()=>Array.from({length:r},()=>"empty"));for(let a of t.edges)Yf(o,i,n,a);for(let a of t.boxes)Jf(o,i,n,a,e.labelOf(a.id));return o.map(a=>em(a.join(""))).join(`
10
+ `)}function Jf(t,e,n,r,s){let{x:o,y:i,w:a,h:u}=r;if(a<2||u<2){u>0&&Ld(t,e,o,i,a,s);return}Kt(t,e,o,i,n.boxTL);for(let c=o+1;c<o+a-1;c+=1)Kt(t,e,c,i,n.boxH);Kt(t,e,o+a-1,i,n.boxTR);for(let c=i+1;c<i+u-1;c+=1){Kt(t,e,o,c,n.boxV);for(let l=o+1;l<o+a-1;l+=1)Gd(t,e,l,c," ","empty");Kt(t,e,o+a-1,c,n.boxV)}Kt(t,e,o,i+u-1,n.boxBL);for(let c=o+1;c<o+a-1;c+=1)Kt(t,e,c,i+u-1,n.boxH);Kt(t,e,o+a-1,i+u-1,n.boxBR);let d=i+Math.floor(u/2);Ld(t,e,o+1,d,a-2,s)}function Kt(t,e,n,r,s){Gd(t,e,n,r,s,s===" "?"empty":s==="\u2500"||s==="-"?"boxH":s==="\u2502"||s==="|"?"boxV":"boxCorner")}function Gd(t,e,n,r,s,o){if(r<0||r>=t.length)return;let i=t[r];n<0||n>=i.length||(i[n]=s,e[r][n]=o)}function Ld(t,e,n,r,s,o){if(r<0||r>=t.length)return;let i=n,a=s;for(let u of o){let d=Qn(u);if(d!==0){if(a<d)break;i>=0&&i<t[r].length&&(t[r][i]=u,e[r][i]="label",d===2&&i+1<t[r].length&&(t[r][i+1]="",e[r][i+1]="label")),i+=d,a-=d}}for(;a>0;)i>=0&&i<t[r].length&&(t[r][i]=" ",e[r][i]="empty"),i+=1,a-=1}function Yf(t,e,n,r){let s=r.points;if(s.length<2)return;for(let u=0;u+1<s.length;u+=1)Qf(t,e,n,s[u],s[u+1]);for(let u=1;u+1<s.length;u+=1){let d=s[u-1],c=s[u],l=s[u+1],p=Xf(d,c,l,n);p&&Dd(t,e,c.x,c.y,p,"edgeCorner")}let o=s[s.length-1],i=s[s.length-2],a=Zf(i,o,n);a&&Dd(t,e,o.x,o.y,a,"arrow")}function Qf(t,e,n,r,s){if(!(r.x===s.x&&r.y===s.y)){if(r.y===s.y){let o=r.y,i=Math.min(r.x,s.x),a=Math.max(r.x,s.x);for(let u=i;u<=a;u+=1)Id(t,e,u,o,n,"h")}else if(r.x===s.x){let o=r.x,i=Math.min(r.y,s.y),a=Math.max(r.y,s.y);for(let u=i;u<=a;u+=1)Id(t,e,o,u,n,"v")}}}function Id(t,e,n,r,s,o){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]=o==="h"?s.horizontal:s.vertical,e[r][n]=o==="h"?"edgeH":"edgeV";return}if(a==="edgeH"&&o==="v"){i[n]=s.cross,e[r][n]="edgeCorner";return}if(a==="edgeV"&&o==="h"){i[n]=s.cross,e[r][n]="edgeCorner";return}}}function Dd(t,e,n,r,s,o){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]=s,e[r][n]=o)}function Xf(t,e,n,r){let s=t.y===e.y,o=e.y===n.y;if(s===o)return;if(s){let u=t.x<e.x,d=n.y>e.y;return u&&d?r.cornerTR:u&&!d?r.cornerBR:!u&&d?r.cornerTL:r.cornerBL}let i=t.y<e.y,a=n.x>e.x;return i&&a?r.cornerBL:i&&!a?r.cornerBR:!i&&a?r.cornerTL:r.cornerTR}function Zf(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 em(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===32;)e-=1;return t.slice(0,e)}function jd(t){let e=tm(t);nm(e),rm(e),om(e),sm(e,t);let n=um(e,t),{width:r,height:s}=cm(e),o=[];for(let i of e.layers)for(let a of i)a.isVirtual||o.push({id:a.id,layer:a.layer,order:a.order,x:a.x,y:a.y,w:a.w,h:a.h});return{boxes:o,edges:n,width:r,height:s}}function tm(t){let e=new Map;for(let s of t.nodes)e.set(s,{id:s,isVirtual:!1,layer:-1,order:0,x:0,y:0,w:t.widthCells(s),h:t.heightCells(s),in:[],out:[]});let n=[],r=0;for(let s of t.edges){if(s.from===s.to)continue;let o=e.get(s.from),i=e.get(s.to);if(!o||!i)continue;let a={chainId:r++,chainFrom:s.from,chainTo:s.to,fromId:s.from,toId:s.to,hopIndex:0,chainLen:1};o.out.push(a),i.in.push(a),n.push(a)}return{nodes:e,layers:[],hops:n}}function nm(t){let e=new Map;for(let o of t.nodes.values())e.set(o.id,o.in.length);let n=[];for(let o of t.nodes.values())(e.get(o.id)??0)===0&&(o.layer=0,n.push(o));let r=new Set,s=0;for(;s<n.length;){let o=n[s++];if(!r.has(o.id)){r.add(o.id);for(let i of o.out){let a=t.nodes.get(i.toId);a.layer=Math.max(a.layer,o.layer+1);let u=(e.get(a.id)??0)-1;e.set(a.id,u),u<=0&&n.push(a)}}}for(let o of t.nodes.values())o.layer<0&&(o.layer=0)}function rm(t){let e=Math.max(0,...Array.from(t.nodes.values(),o=>o.layer)),n=Array.from({length:e+1},()=>[]);for(let o of t.nodes.values())n[o.layer].push(o);let r=[],s=0;for(let o of t.hops){let i=t.nodes.get(o.fromId),a=t.nodes.get(o.toId),u=a.layer-i.layer;if(u<=0){i.out=i.out.filter(l=>l!==o),a.in=a.in.filter(l=>l!==o);continue}if(u===1){o.hopIndex=0,o.chainLen=1,r.push(o);continue}i.out=i.out.filter(l=>l!==o),a.in=a.in.filter(l=>l!==o);let d=i;for(let l=1;l<u;l+=1){let p=`__virt_${s++}__`,f={id:p,isVirtual:!0,layer:i.layer+l,order:0,x:0,y:0,w:0,h:1,in:[],out:[]};t.nodes.set(p,f),n[f.layer].push(f);let m={chainId:o.chainId,chainFrom:o.chainFrom,chainTo:o.chainTo,fromId:d.id,toId:p,hopIndex:l-1,chainLen:u};d.out.push(m),f.in.push(m),r.push(m),d=f}let c={chainId:o.chainId,chainFrom:o.chainFrom,chainTo:o.chainTo,fromId:d.id,toId:a.id,hopIndex:u-1,chainLen:u};d.out.push(c),a.in.push(c),r.push(c)}for(let o of n)for(let i=0;i<o.length;i+=1)o[i].order=i;t.layers=n,t.hops=r}function om(t){for(let n=0;n<4;n+=1){for(let r=1;r<t.layers.length;r+=1)Fd(t,t.layers[r],"in"),Yo(t.layers[r]);for(let r=t.layers.length-2;r>=0;r-=1)Fd(t,t.layers[r],"out"),Yo(t.layers[r])}for(let n=0;n<2;n+=1){let r=!1;for(let s=1;s<t.layers.length;s+=1){let o=t.layers[s];for(let i=0;i+1<o.length;i+=1){let a=$d(t,o[i],o[i+1],"in");[o[i],o[i+1]]=[o[i+1],o[i]],Yo(o),$d(t,o[i],o[i+1],"in")<a?r=!0:([o[i],o[i+1]]=[o[i+1],o[i]],Yo(o))}}if(!r)break}}function Fd(t,e,n){let r=new Map;for(let s of e){let o=n==="in"?s.in:s.out;if(o.length===0){r.set(s.id,s.order);continue}let i=0,a=0;for(let u of o){let d=t.nodes.get(n==="in"?u.fromId:u.toId);d&&(i+=d.order,a+=1)}r.set(s.id,a===0?s.order:i/a)}e.sort((s,o)=>{let i=r.get(s.id),a=r.get(o.id);return i!==a?i-a:s.order-o.order})}function Yo(t){for(let e=0;e<t.length;e+=1)t[e].order=e}function $d(t,e,n,r){let s=r==="in"?e.in:e.out,o=r==="in"?n.in:n.out,i=0;for(let a of s)for(let u of o){let d=t.nodes.get(r==="in"?a.fromId:a.toId)?.order??0,c=t.nodes.get(r==="in"?u.fromId:u.toId)?.order??0;(e.order<n.order&&d>c||e.order>n.order&&d<c)&&(i+=1)}return i}function sm(t,e){e.direction==="LR"?im(t,e):am(t,e)}function im(t,e){let n=[],r=0;for(let s=0;s<t.layers.length;s+=1){n.push(r);let o=0;for(let i of t.layers[s])o=Math.max(o,i.w);r+=o+e.layerGap}for(let s=0;s<t.layers.length;s+=1)for(let o of t.layers[s])o.x=n[s];for(let s of t.layers){let o=0;for(let i of s)i.y=o,o+=i.h+e.nodeGap}Bd(t,e,"y")}function am(t,e){let n=[],r=0;for(let s=0;s<t.layers.length;s+=1){n.push(r);let o=0;for(let i of t.layers[s])o=Math.max(o,i.h);r+=o+e.layerGap}for(let s=0;s<t.layers.length;s+=1)for(let o of t.layers[s])o.y=n[s];for(let s of t.layers){let o=0;for(let i of s)i.x=o,o+=i.w+e.nodeGap}Bd(t,e,"x")}function Bd(t,e,n){let r=o=>n==="y"?o.h:o.w,s=e.nodeGap;for(let o=0;o<2;o+=1){let i=o===0?t.layers.slice(1):t.layers.slice(0,-1).reverse();for(let a of i){let u=new Map;for(let c of a){let l=o===0?c.in:c.out;if(l.length===0)continue;let p=[];for(let m of l){let g=t.nodes.get(o===0?m.fromId:m.toId);if(!g)continue;let h=n==="y"?g.y:g.x;p.push(h+Math.floor(r(g)/2))}if(p.length===0)continue;p.sort((m,g)=>m-g);let f=p[Math.floor(p.length/2)];u.set(c.id,f-Math.floor(r(c)/2))}let d=0;for(let c of a){let l=u.get(c.id),p=n==="y"?c.y:c.x,m=Math.max(l??p,d);n==="y"?c.y=m:c.x=m,d=m+r(c)+s}}}}function um(t,e){let n=new Map;for(let d of t.hops){let c=n.get(d.chainId);c?c.push(d):n.set(d.chainId,[d])}for(let d of n.values())d.sort((c,l)=>c.hopIndex-l.hopIndex);let r=e.direction==="LR",s=d=>r?d.x:d.y,o=d=>r?d.w:d.h,i=d=>r?d.y+Math.floor(d.h/2):d.x+Math.floor(d.w/2),a=new Map;for(let d=0;d+1<t.layers.length;d+=1){let c=t.layers[d],l=t.layers[d+1],p=0;for(let S of c)p=Math.max(p,s(S)+o(S));let f=Number.POSITIVE_INFINITY;for(let S of l)f=Math.min(f,s(S));let m=Number.isFinite(f)?f-1:p,g=Math.max(1,m-p+1),h=[];for(let S of c)for(let E of S.out)h.push(E);h.sort((S,E)=>{let L=i(t.nodes.get(S.fromId)),C=i(t.nodes.get(E.fromId));if(L!==C)return L-C;let I=i(t.nodes.get(S.toId)),A=i(t.nodes.get(E.toId));return I-A});let y=[],b=new Map;for(let S of h){let E=i(t.nodes.get(S.fromId)),L=i(t.nodes.get(S.toId)),C=Math.min(E,L),I=Math.max(E,L),A=-1;for(let P=0;P<y.length;P+=1){let U=y[P],z=!0;for(let D of U)if(D.lo<=I&&C<=D.hi){z=!1;break}if(z){U.push({lo:C,hi:I}),A=P;break}}A<0&&(y.push([{lo:C,hi:I}]),A=y.length-1),b.set(S,A)}let v=y.length,T=g>=Math.max(3,v+2),w=T?p+1:p,k=T?m-1:m,x=Math.max(1,k-w+1);for(let S of h){let E=b.get(S),L;if(v<=1)L=w+Math.floor(x/2);else{let C=(x-1)/(v-1);L=w+Math.floor(E*C)}a.set(S,Math.max(p,Math.min(m,L)))}}let u=[];for(let[,d]of n){let c=[];for(let p=0;p<d.length;p+=1){let f=d[p],m=t.nodes.get(f.fromId),g=t.nodes.get(f.toId),h=a.get(f),y=m.isVirtual?s(m):s(m)+o(m),b=g.isVirtual?s(g):s(g)-1,v=i(m),T=i(g);p===0&&Qo(c,r,y,v),v!==T&&(Qo(c,r,h,v),Qo(c,r,h,T)),Qo(c,r,b,T)}let l=d[0];u.push({from:l.chainFrom,to:l.chainTo,points:dm(c)})}return u}function Qo(t,e,n,r){t.push(e?{x:n,y:r}:{x:r,y:n})}function dm(t){let e=[];for(let n of t){let r=e[e.length-1];(!r||r.x!==n.x||r.y!==n.y)&&e.push(n)}return e}function cm(t){let e=0,n=0;for(let r of t.layers)for(let s of r)e=Math.max(e,s.x+s.w),n=Math.max(n,s.y+s.h);return{width:e,height:n}}var lm=24,pm=4,fm=1,mm=3;function Vd(t,e){let n=hm(e.direction),r=Math.max(3,e.maxLabelWidth??lm),s=e.asciiCharset??"unicode",o=Object.keys(t.nodes).sort(),i=new Set(o),a=t.edges.filter(f=>i.has(f.from)&&i.has(f.to)),u=new Map,d=new Map;for(let f of o){let m=Ad(f,r);u.set(f,m),d.set(f,Qn(m)+4)}let c=jd({nodes:o,edges:a,widthCells:f=>d.get(f)??3,heightCells:()=>mm,layerGap:pm,nodeGap:fm,direction:n}),l=Pd(c,{charset:s,labelOf:f=>u.get(f)??f}),p=e.logger;return p&&p(l),l}function hm(t){if(t===void 0||t==="LR")return"LR";if(t==="TD")return"TD";throw new Error(`ascii describe supports direction "LR" or "TD" only; got ${String(t)}`)}function Dr(t,e,n,r={}){let s=e in t.nodes,o=n in t.nodes;if(!s)return Xo(e,n,"no-such-from");if(!o)return Xo(e,n,"no-such-to");let i=r.maxDepth;if(i!=null&&(!Number.isInteger(i)||i<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(e===n){if(r.findCycle===!0){let d=gm(t,e,r);if(d!=null)return d}let u=Zo(e,t.nodes[e],0,r);return es(e,n,[u])}if(i===0)return Xo(e,n,"no-path");let a=Kd(t,e,n,i);return a.found?es(e,n,Hd(t,a.pathOrder,r)):Xo(e,n,a.truncated?"max-depth-exceeded":"no-path")}function Kd(t,e,n,r){let s=new Map,o=[{path:n,depth:0}],i=new Set([n]),a=0,u=!1;for(;a<o.length;){let l=o[a++];if(l.path===e)break;if(r!=null&&l.depth>=r){let g=t.nodes[l.path];g?.deps&&g.deps.length>0&&(u=!0);continue}let p=t.nodes[l.path];if(p==null)continue;let f=p.deps??[],m=new Map;for(let g=0;g<f.length;g++){let h=f[g];if(!h)continue;let y=m.get(h);y==null&&(y=[],m.set(h,y)),y.push(g)}for(let[g,h]of m)i.has(g)||(i.add(g),s.set(g,{from:l.path,depIndices:h}),o.push({path:g,depth:l.depth+1}))}if(!s.has(e))return{found:!1,pathOrder:[],truncated:u};let d=[{path:e}],c=e;for(;c!==n;){let l=s.get(c);if(l==null)return{found:!1,pathOrder:[],truncated:!1};d[d.length-1].depIndices=l.depIndices,d.push({path:l.from}),c=l.from}return{found:!0,pathOrder:d,truncated:!1}}function gm(t,e,n){let r=t.nodes[e];if(r==null)return null;let s=r.deps??[],o=[];for(let a=0;a<s.length;a++)s[a]===e&&o.push(a);if(o.length>0){let a=Zo(e,r,0,n);a.dep_index=o[0];let u=Zo(e,r,1,n);return es(e,e,[a,u])}let i=null;for(let a=0;a<s.length;a++){let u=s[a];if(!u||u===e)continue;let d=Kd(t,u,e,n.maxDepth);d.found&&(i==null||d.pathOrder.length<i.pathOrder.length)&&(i=d,i={found:!0,pathOrder:[{path:e,depIndices:[a]},...d.pathOrder],truncated:!1})}return i==null?null:es(e,e,Hd(t,i.pathOrder,n))}function Hd(t,e,n){return e.map((r,s)=>{let o=t.nodes[r.path],i=Zo(r.path,o,s,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 Zo(t,e,n,r){let s={path:t,type:e.type,hop:n};e.status!==void 0&&(s.status=e.status),"value"in e&&(s.value=e.value),e.v!=null&&(s.v=e.v);let o=r.annotations?.get(t)??e.annotation;o!=null&&(s.annotation=o);let i=r.lastMutations?.get(t)??e.lastMutation;return i!=null&&(s.lastMutation=i),s}function es(t,e,n){return qd(t,e,!0,"ok",n)}function Xo(t,e,n){return qd(t,e,!1,n,[])}function qd(t,e,n,r,s){let o=ym(t,e,n,r,s);return{from:t,to:e,found:n,reason:r,steps:s,text:o,toJSON(){return{from:t,to:e,found:n,reason:r,steps:s}}}}function ym(t,e,n,r,s){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 o=[`Causal path: ${t} \u2192 ${e} (${s.length} step(s))`];for(let i of s){let u=` ${i.hop===0?"\xB7":"\u2193"} ${i.path} (${i.type}${i.status?`/${i.status}`:""})`;if(o.push(u),"value"in i&&o.push(` value: ${bm(i.value)}`),i.annotation!=null&&o.push(` annotation: ${i.annotation}`),i.lastMutation!=null){let d=i.lastMutation.actor;o.push(` actor: ${d.type}${d.id?`:${d.id}`:""}`)}}return o.join(`
11
+ `)}function bm(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)}}_e();var je={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},ts=Symbol.for("sizeof");function Pr(t){let e=new WeakSet,n=new WeakSet,r=[t],s=0;for(;r.length>0;){let o=r.pop();s+=vm(o,e,n,r)}return s}function vm(t,e,n,r){if(t==null)return 0;switch(typeof t){case"number":return je.number;case"boolean":return je.boolean;case"string":return je.string+t.length*2;case"bigint":return je.bigint+Tm(t);case"symbol":return je.symbol;case"function":return e.has(t)?0:(e.add(t),je.function);case"undefined":return 0}let o=t;if(e.has(o))return 0;e.add(o);let i=o[ts];if(typeof i=="function")try{let d=i.call(o);if(typeof d=="number"&&Number.isFinite(d))return d}catch{}if(o instanceof Date)return je.date;if(o instanceof RegExp)return je.regexp+o.source.length*2;if(o instanceof Error){let d=o.message?o.message.length*2:0,c=o.stack?o.stack.length*2:0;return je.error+d+c}if(typeof URL<"u"&&o instanceof URL)return je.url+o.href.length*2;if(typeof Promise<"u"&&o instanceof Promise)return je.promise;if(o instanceof WeakMap)return je.weakmap;if(o instanceof WeakSet)return je.weakset;if(o instanceof Map){let d=je.map;for(let[c,l]of o)d+=je.mapEntry,r.push(c),r.push(l);return d}if(o instanceof Set){let d=je.set;for(let c of o)d+=je.setEntry,r.push(c);return d}if(Array.isArray(o)){let d=je.array+o.length*8;for(let c of o)r.push(c);return d}if(o instanceof ArrayBuffer)return n.has(o)?0:(n.add(o),o.byteLength);if(ArrayBuffer.isView(o)){let d=o;return n.has(d.buffer)?48:(n.add(d.buffer),d.buffer.byteLength+48)}let a=je.object,u=Object.keys(o);for(let d of u){a+=je.string+d.length*2;try{r.push(o[d])}catch{}}return a}function Tm(t){let e=t<0n?-t:t;if(e===0n)return 0;let n=e.toString(2).length;return Math.ceil(n/32)*8}function pn(t,e){let n=e?.topN??10,r=t.describe({detail:"standard"}),s=[],o=t._collectObserveTargets;typeof o=="function"&&o.call(t,"",s);let i=new Map;for(let[p,f]of s)i.set(p,f);let a=[];for(let[p,f]of Object.entries(r.nodes)){let m=i.get(p),g=m instanceof Ae?m:null,h=g?Pr(g.cache):0,y=g?g._sinkCount:0,b=f.deps?.length??0,v=f.type==="effect"&&y===0,T=y===0?f.type==="effect"?"orphan-effect":f.type==="derived"?"idle-derived":f.type==="producer"?"idle-producer":null:null;a.push({path:p,type:f.type,status:f.status??"unknown",valueSizeBytes:h,subscriberCount:y,depCount:b,isOrphanEffect:v,orphanKind:T})}let u=a.reduce((p,f)=>p+f.valueSizeBytes,0),d=(p,f)=>[...a].sort(f??((m,g)=>g[p]-m[p])).slice(0,n),c=a.filter(p=>p.orphanKind!=null),l=a.filter(p=>p.isOrphanEffect);return{nodeCount:a.length,edgeCount:r.edges.length,subgraphCount:r.subgraphs.length,nodes:a,totalValueSizeBytes:u,hotspots:{byValueSize:d("valueSizeBytes"),bySubscriberCount:d("subscriberCount"),byDepCount:d("depCount")},orphans:c,orphanEffects:l}}var Pe="::",We="__meta__",pt=1;function Wd(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 s=t.values().next();if(s.done)return;let o=s.value;t.delete(o);try{o()}catch(i){console.error(`[Graph "${e}".destroy] disposer threw:`,i)}}}function wm(t){let e=[];for(let n of Object.keys(t).sort()){let r=t[n].v;r!=null&&e.push(`${n} ${r.id} ${r.version}`)}return e.join(`
12
+ `)}function Ud(t){if(t.version!==pt)throw new Error(`unsupported snapshot version ${String(t.version)} (expected ${pt})`);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 km(t,e){let n=new WeakMap,r=(s,o)=>{if(Object.is(s,o))return!0;if(s==null||o==null||typeof s!="object"||typeof o!="object")return!1;let i=n.get(s);if(i==null&&(i=new WeakSet,n.set(s,i)),i.has(o))return!0;i.add(o);let a=s.constructor,u=o.constructor;if(a!==u)return!1;if(s instanceof Date)return s.getTime()===o.getTime();if(s instanceof RegExp)return s.source===o.source&&s.flags===o.flags;if(Array.isArray(s)){let p=o;if(s.length!==p.length)return!1;for(let f=0;f<s.length;f++)if(!r(s[f],p[f]))return!1;return!0}if(s instanceof Map){let p=o;if(s.size!==p.size)return!1;for(let[f,m]of s)if(!p.has(f)||!r(m,p.get(f)))return!1;return!0}if(s instanceof Set){let p=o;if(s.size!==p.size)return!1;for(let f of s){let m=!1;for(let g of p)if(r(f,g)){m=!0;break}if(!m)return!1}return!0}if(ArrayBuffer.isView(s)){let p=s,f=o;if(p.length!==f.length)return!1;for(let m=0;m<p.length;m++)if(p[m]!==f[m])return!1;return!0}let d=Object.keys(s),c=Object.keys(o);if(d.length!==c.length)return!1;let l=new Set(c);for(let p of d)if(!l.has(p)||!r(s[p],o[p]))return!1;return!0};return r(t,e)}function ta(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(ta);let e=t,n=Object.keys(e).sort(),r={};for(let s of n)r[s]=ta(e[s]);return r}function xm(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Rm(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Sm(t){return t==="TD"?"down":t==="BT"?"up":t==="RL"?"left":"right"}function Jd(t){let e=new Set,n=[];function r(s,o){let i=`${s}\0${o}`;e.has(i)||(e.add(i),n.push([s,o]))}for(let[s,o]of Object.entries(t.nodes)){let i=o.deps;if(i)for(let a of i)r(a,s)}for(let s of t.edges)r(s.from,s.to);return n}function Yd(t){if(t===void 0)return"LR";if(t==="TD"||t==="LR"||t==="BT"||t==="RL")return t;throw new Error(`invalid diagram direction ${String(t)}; expected one of: TD, LR, BT, RL`)}function Nm(t,e){let n=e.includeEdges??!0,r=e.includeSubgraphs??!0,{expand:s,...o}=t,i={...o,edges:n?t.edges:[],subgraphs:r?t.subgraphs:[]},a=JSON.stringify(ta(i),null,e.indent??2);return e.logger?.(a),a}function Em(t,e){let n=e.includeEdges??!0,r=e.includeSubgraphs??!0,s=[];s.push(`Graph ${t.name}`),s.push("Nodes:");for(let i of Object.keys(t.nodes).sort()){let a=t.nodes[i];s.push(`- ${i} (${a.type}/${a.status}): ${rs(a.value)}`)}if(n){s.push("Edges:");for(let i of t.edges)s.push(`- ${i.from} -> ${i.to}`)}if(r){s.push("Subgraphs:");for(let i of t.subgraphs)s.push(`- ${i}`)}let o=s.join(`
13
+ `);return e.logger?.(o),o}function Qd(t,e){let n=Yd(e.direction),r=Object.keys(t.nodes).sort(),s=new Map;for(let i=0;i<r.length;i+=1)s.set(r[i],`n${i}`);let o=[`flowchart ${n}`];for(let i of r){let a=s.get(i);o.push(` ${a}["${xm(i)}"]`)}for(let[i,a]of Jd(t)){let u=s.get(i),d=s.get(a);!u||!d||o.push(` ${u} --> ${d}`)}return o.join(`
14
+ `)}function _m(t,e){let n=Qd(t,e);return os(n)}function os(t,e){let n=e?.theme??"default",r=e?.autoSync??!0,o=JSON.stringify({code:t,mermaid:{theme:n},autoSync:r}),i=new TextEncoder().encode(o),a="";for(let d=0;d<i.length;d++)a+=String.fromCharCode(i[d]);return`https://mermaid.live/edit#base64:${globalThis.btoa(a).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`}function Mm(t,e){let n=Yd(e.direction),r=Object.keys(t.nodes).sort(),s=new Map;for(let i=0;i<r.length;i+=1)s.set(r[i],`n${i}`);let o=[`direction: ${Sm(n)}`];for(let i of r){let a=s.get(i);o.push(`${a}: "${Rm(i)}"`)}for(let[i,a]of Jd(t)){let u=s.get(i),d=s.get(a);!u||!d||o.push(`${u} -> ${d}`)}return o.join(`
15
+ `)}function Om(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ns(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 s=t.indexOf("]",n+1);if(s<=n+1){e+="\\[";continue}let o=t.slice(n+1,s);o.startsWith("!")&&(o=`^${o.slice(1)}`),o=o.replace(/\\/g,"\\\\"),e+=`[${o}]`,n=s;continue}e+=Om(r)}return e+="$",new RegExp(e)}var Cm={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"},Am={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function rs(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 Lm(t){return t==="none"?Am:t==="ansi"||t==null?Cm:{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 zd(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 Im(t,e,n){for(let r=0;r<t.length;r++){let s=t.charCodeAt(r);if(s<32||s===127)throw new Error(`Graph "${e}": ${n} "${t}" must not contain control character (U+${s.toString(16).padStart(4,"0").toUpperCase()} at index ${r})`)}}function ea(t,e,n){if(t==="")throw new Error(`Graph "${e}": ${n} name must be non-empty`);if(t.includes(Pe))throw new Error(`Graph "${e}": ${n} "${t}" must not contain '${Pe}' (path separator)`);if(t===We)throw new Error(`Graph "${e}": ${n} name "${We}" is reserved for meta companion paths`);Im(t,e,n)}function Dm(t,e){if(t==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let n=t.split(Pe);for(let r of n)if(r==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return n}function Pm(t,e){let n=!1;for(let s of t)if(!e.isMetaPassthrough(s[0])){n=!0;break}return n?t.filter(s=>e.isMetaPassthrough(s[0])):t}function Xd(t){for(let e of t._mounts.values())Xd(e);for(let e of t._nodes.values())try{e.down([[de]],{internal:!0})}catch{}}var q=class t{name;opts;config;_nodes=new Map;_nodeToName=new WeakMap;_mounts=new Map;_parent=void 0;_storageDisposers=new Set;_disposers=new Set;_destroyed=!1;_topology;_topologyEmitters=new Set;constructor(e,n){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(Pe))throw new Error(`Graph name must not contain '${Pe}' (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??$e,this._traceRing=new ln(n?.traceCapacity??1e3),n?.versioning!=null&&this.setVersioning(n.versioning)}ancestors(e=!0){let n=[],r=e?this:this._parent;for(;r!=null;)n.push(r),r=r._parent;return n}get topology(){return this._topology==null&&(this._topology=$(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,s=n?.name??r;if(s==null||s==="")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 o=s,i=n?.annotation;if(ea(o,this.name,"add"),this._mounts.has(o))throw new Error(`Graph "${this.name}": name "${o}" is already a mount point`);if(this._nodes.has(o))throw new Error(`Graph "${this.name}": node "${o}" 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(o,e),this._nodeToName.set(e,o),this._emitTopology({kind:"added",name:o,nodeKind:"node"}),i!=null&&(this._annotations.set(o,i),this.config.inspectorEnabled&&this._traceRing.push({path:o,annotation:i,timestamp_ns:F()})),e}setVersioning(e){if(e!=null)for(let n of this._nodes.values())n instanceof Ae&&n._applyVersioning(e)}remove(e){ea(e,this.name,"remove");let n=this._mounts.get(e);if(n){let o={kind:"mount",nodes:[],mounts:[]},i=[];n._collectObserveTargets("",i);for(let[a,u]of i)a.includes(`${Pe}${We}${Pe}`)||o.nodes.push(a);return o.nodes.sort(),o.mounts.push(e),o.mounts.push(...n._collectSubgraphs(`${e}${Pe}`)),this._mounts.delete(e),n._parent=void 0,Xd(n),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:o}),o}let r=this._nodes.get(e);if(!r)throw new Error(`Graph "${this.name}": unknown node or mount "${e}"`);this._nodes.delete(e),this._nodeToName.delete(r),r.down([[de]],{internal:!0});let s={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:s}),s}removeAll(e){let n=typeof e=="function"?e:(()=>{let o=ns(e);return i=>o.test(i)})(),r={kind:"mount",nodes:[],mounts:[]},s=[...this._nodes.keys(),...this._mounts.keys()].filter(o=>n(o));for(let o of s){let i=this.remove(o);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 s=e[r++];return{value:[s,n.get(s)],done:!1}}}}node(e){if(e==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(e.includes(Pe))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 s=r?.internal===!0;this.node(e).down([[R,n]],{actor:r?.actor,internal:s,delivery:"write"})}setAll(e,n){let r=Symbol.iterator in e?e:Object.entries(e);Y(()=>{for(let[s,o]of r)this.set(s,o,n)})}invalidate(e,n){let r=n?.internal===!0;this.node(e).down([[Ye]],{actor:n?.actor,internal:r,delivery:"write"})}error(e,n,r){let s=r?.internal===!0;this.node(e).down([[M,n]],{actor:r?.actor,internal:s,delivery:"write"})}complete(e,n){let r=n?.internal===!0;this.node(e).down([[O]],{actor:n?.actor,internal:r,delivery:"write"})}edges(e){let n=e?.recursive===!0,r=new Map;if(!n){for(let[u,d]of this._nodes)r.set(d,u);let a=[];for(let[u,d]of this._nodes)if(d instanceof Ae)for(let c of d._deps){let l=r.get(c.node);l!=null&&a.push([l,u])}return a.sort((u,d)=>u[0]<d[0]?-1:u[0]>d[0]?1:u[1]<d[1]?-1:u[1]>d[1]?1:0),a}let s=[];this._collectObserveTargets("",s);let o=new Map;for(let[a,u]of s)o.set(u,a);let i=[];for(let[a,u]of s)if(u instanceof Ae)for(let d of u._deps){let c=o.get(d.node);c!=null&&i.push([c,a])}return i.sort((a,u)=>a[0]<u[0]?-1:a[0]>u[0]?1:a[1]<u[1]?-1:a[1]>u[1]?1:0),i}mount(e,n){if(ea(e,this.name,"mount"),this._nodes.has(e))throw new Error(`Graph "${this.name}": cannot mount at "${e}" \u2014 node with that name exists`);if(this._mounts.has(e))throw new Error(`Graph "${this.name}": mount "${e}" already exists`);if(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=Dm(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],s=n.slice(1);if(s.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 o=this._nodes.get(r);if(o&&s.length>0&&s[0]===We)return this._resolveMetaChainFromNode(o,s,n.join(Pe));let i=this._mounts.get(r);if(!i)throw this._nodes.has(r)?new Error(`Graph "${this.name}": "${r}" is a node; trailing path "${s.join(Pe)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${r}"`);return i.resolve(s.join(Pe))}_resolveMetaChainFromNode(e,n,r){let s=e,o=0,i=[...n];for(;o<i.length;){if(i[o]!==We)throw new Error(`Graph "${this.name}": expected ${We} segment in meta path "${r}"`);if(o+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${We} in "${r}"`);let a=i[o+1],u=s.meta[a];if(!u)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${r}"`);s=u,o+=2}return s}signal(e,n){if(n?.internal!==!0){for(let s of e)if(this.config.messageTier(s[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,s){for(let u of this._mounts.values())u._signalDeliver(e,n,r,s);let i=n.internal===!0?{internal:!0}:{actor:n.actor,delivery:"signal"},a=Pm(e,this.config);for(let u of[...this._nodes.keys()].sort()){let d=this._nodes.get(u);if(!r.has(d)){r.add(d);try{d.down(e,i)}catch(c){if(c instanceof rt)throw c;s.push(c)}a.length!==0&&this._signalMetaSubtree(d,a,r,i,s)}}}_signalMetaSubtree(e,n,r,s,o){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,s)}catch(u){if(u instanceof rt)throw u;o.push(u)}this._signalMetaSubtree(a,n,r,s,o)}}}describe(e){if(e?.reactive===!0)return this._describeReactive(e);let n=e?.actor,r=e?.filter,s=_t(e?.detail,e?.fields),o=e?.format==="spec",i=o?_t("minimal"):s,a=[];this._collectObserveTargets("",a);let u=new Map;for(let[k,x]of a)u.set(x,k);let d=[];{let k=a.map(([,E])=>E),x=new Set(u.values()),S=0;for(;k.length>0;){let E=k.shift();if(E instanceof Ae)for(let L of E._deps){let C=L.node;if(u.has(C))continue;let I=C.name??"",A=I;if(!A||x.has(A))if(I){let P=2;for(;x.has(`${I}#${P}`);)P++;A=`${I}#${P}`}else for(A=`__internal__/${S++}`;x.has(A);)A=`__internal__/${S++}`;u.set(C,A),x.add(A),d.push([A,C]),k.push(C)}}}let c=[...a,...d],l={};for(let[k,x]of c){if(n!=null&&!x.allowsObserve(n))continue;let S=Ir(x,i),E=x instanceof Ae?x._deps.map(A=>u.get(A.node)??A.node.name??""):[],{name:L,...C}=S,I={...C,deps:E};if(!o){let A=this._annotations.get(k);A!=null&&(I.annotation=A)}if(r!=null)if(typeof r=="function"){let A=r;if(!(A.length>=2?A(k,I):A(I)))continue}else{let A=!0;for(let[P,U]of Object.entries(r)){let z=P==="deps_includes"?"depsIncludes":P==="meta_has"?"metaHas":P;if(z==="depsIncludes"){if(!I.deps.includes(String(U))){A=!1;break}continue}if(z==="metaHas"){if(!Object.hasOwn(I.meta??{},String(U))){A=!1;break}continue}if(I[z]!==U){A=!1;break}}if(!A)continue}l[k]=I}let p=new Set(Object.keys(l)),f=[];for(let[k,x]of c)if(x instanceof Ae)for(let S of x._deps){let E=u.get(S.node);E!=null&&f.push([E,k])}f.sort((k,x)=>k[0]<x[0]?-1:k[0]>x[0]?1:k[1]<x[1]?-1:k[1]>x[1]?1:0);let m=f.map(([k,x])=>({from:k,to:x}));(n!=null||r!=null)&&(m=m.filter(k=>p.has(k.from)&&p.has(k.to)));let g=this._collectSubgraphs(""),h=n!=null||r!=null?g.filter(k=>{let x=`${k}${Pe}`;return[...p].some(S=>S===k||S.startsWith(x))}):g,y=this,b=e,v={name:this.name,nodes:l,edges:m,subgraphs:h,expand(k){let x={...b,format:void 0};return Array.isArray(k)?(x.fields=k,x.detail=void 0):(x.detail=k,x.fields=void 0),y.describe(x)}},T=e??{},w=T.format;return w==="json"?Nm(v,T):w==="pretty"?Em(v,T):w==="mermaid"?Qd(v,T):w==="mermaid-url"?_m(v,T):w==="d2"?Mm(v,T):w==="ascii"?Vd(v,T):v}_collectSubgraphs(e){let n=[];for(let r of[...this._mounts.keys()].sort()){let s=e===""?r:`${e}${r}`;n.push(s),n.push(...this._mounts.get(r)._collectSubgraphs(`${s}${Pe}`))}return n}resourceProfile(e){return pn(this,e)}reachable(e,n,r={}){return r.withDetail===!0?fn(this.describe(),e,n,{...r,withDetail:!0}):fn(this.describe(),e,n,r)}explain(e,n,r){return r?.reactive===!0?this._explainReactive(e,n,r):this._explainStatic(e,n,r)}_explainStatic(e,n,r){let s=this.describe({detail:"full"}),o=new Map(this._annotations),i=new Map;for(let[a,u]of Object.entries(s.nodes))u.lastMutation!=null&&i.set(a,u.lastMutation);return Dr(s,e,n,{...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{},annotations:o,lastMutations:i})}_describeReactive(e){let n={...e,reactive:!1},r=e.reactiveName??"describe",s=0,o=N(s,{name:`${r}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,u=!1,d=()=>{a||u||(a=!0,xr(()=>{a=!1,!u&&(s+=1,o.emit(s))}))},c=i.onEvent(h=>{let y=h.type;y!=="data"&&y!=="error"&&y!=="complete"&&y!=="teardown"||d()}),l=[],p=new WeakSet,f=h=>{if(p.has(h)||u)return;p.add(h);let y=h.topology.subscribe(b=>{for(let v of b){if(v[0]!==R)continue;let T=v[1];if(d(),T.kind==="added"&&T.nodeKind==="mount"){let w=h._mounts.get(T.name);w!=null&&f(w)}}});l.push(y);for(let b of h._mounts.keys()){let v=h._mounts.get(b);v!=null&&f(v)}};f(this);let m;try{m=_([o],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(h,y)=>h===y})}catch(h){c();for(let y of l)y();throw i.dispose(),h}let g=re(m);return{node:m,dispose(){u=!0,c();for(let h of l)h();l.length=0,i.dispose(),g()}}}_explainReactive(e,n,r){let s=0,o=N(s,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,u=!1,d=i.onEvent(f=>{let m=f.type;m!=="data"&&m!=="error"&&m!=="complete"&&m!=="teardown"||a||u||(a=!0,xr(()=>{a=!1,!u&&(s+=1,o.emit(s))}))}),c={...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{}},l;try{l=_([o],()=>this._explainStatic(e,n,c),{name:r?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:e,to:n},equals:(f,m)=>f.found===m.found&&f.reason===m.reason&&f.steps.length===m.steps.length&&Gm(f.steps,m.steps)})}catch(f){throw d(),i.dispose(),f}let p=re(l);return{node:l,dispose(){u=!0,d(),i.dispose(),p()}}}_pathsMatching(e){let n=ns(e),r=[];return this._collectObserveTargets("",r),r.map(([s])=>s).filter(s=>n.test(s))}_collectObserveTargets(e,n){for(let r of[...this._mounts.keys()].sort()){let s=e===""?r:`${e}${Pe}${r}`;this._mounts.get(r)._collectObserveTargets(s,n)}for(let r of[...this._nodes.keys()].sort()){let s=this._nodes.get(r),o=e===""?r:`${e}${Pe}${r}`;n.push([o,s]),this._appendMetaObserveTargets(o,s,n)}}_appendMetaObserveTargets(e,n,r){for(let s of Object.keys(n.meta).sort()){let o=n.meta[s],i=`${e}${Pe}${We}${Pe}${s}`;r.push([i,o]),this._appendMetaObserveTargets(i,o,r)}}observe(e,n){let r=typeof e=="string",o=zd(r?n:e),i=o.structured===!0||o.timeline===!0||o.causal===!0||o.derived===!0||o.detail==="minimal"||o.detail==="full"||o.format!=null,a=o.actor;if(r){let c=e,l=this.resolve(c);if(a!=null&&!l.allowsObserve(a))throw new rt({actor:a,action:"observe",nodeName:c});return i?this._buildStructuredObserver([[c,l]],o,"one"):{subscribe(p){return l.subscribe(p)},up(p){try{l.up?.(p)}catch(f){if(f instanceof rt)return;throw f}}}}let u=[];this._collectObserveTargets("",u),u.sort((c,l)=>c[0]<l[0]?-1:c[0]>l[0]?1:0);let d=a==null?u:u.filter(([,c])=>c.allowsObserve(a));return i?this._buildStructuredObserver(d,o,"all"):{subscribe:c=>{let l=d.map(([p,f])=>f.subscribe(m=>{c(p,m)}));return()=>{for(let p of l)p()}},up:(c,l)=>{try{this.resolve(c).up?.(l)}catch(p){if(p instanceof rt)return;throw p}}}}_buildStructuredObserver(e,n,r){let s=r==="one"?e[0]?.[0]:void 0,o=i=>{if(r==="one"&&s!=null){let c=this.resolve(s);return this._buildStructuredObserver([[s,c]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((c,l)=>c[0]<l[0]?-1:c[0]>l[0]?1:0);let u=i.actor,d=u==null?a:a.filter(([,c])=>c.allowsObserve(u));return this._buildStructuredObserver(d,i,"all")};return this._createObserveResult(e,n,o)}_createObserveResult(e,n,r){let s=n.timeline===!0,o=n.causal===!0,i=n.derived===!0,a=n.detail==="minimal",u=this.config.inspectorEnabled,d=(o||i)&&u,c=n.maxEvents,l=c!=null&&c>0?new ln(c):null,p=[],f=new Set,m={},g=new Set,h=0,y=0,b=0,v=0,T=0,w=0,k=!1,x=!1,S=0,E=new Map,L=new Map,C=new Map,I=j=>{l?l.push(j):p.push(j);for(let ne of f)ne(j)},A=()=>s?{timestamp_ns:F(),in_batch:Zt(),batch_id:S}:{},P=(j,ne)=>{if(!(!d||!(j instanceof Ae)))return j._setInspectorHook(Re=>{if(Re.kind==="dep_message")E.set(j,Re.depIndex);else if(Re.kind==="run"){let Me=Re.batchData.map((he,Ge)=>he!=null&&he.length>0?he.at(-1):Re.prevData[Ge]);L.set(j,Me);let Oe=Re.batchData.map(he=>he!=null?[...he]:void 0);C.set(j,Oe),i&&I({type:"derived",path:ne,dep_values:Me,dep_batches:Oe,...A()})}})},U=j=>{let ne=E.get(j),Re=L.get(j);if(!o||Re==null)return{};let Oe=(ne!=null&&ne>=0&&j instanceof Ae?j._deps[ne]:void 0)?.node,he=Oe?.v,Ge=C.get(j);return{trigger_dep_index:ne,trigger_dep_name:Oe?.name,...he!=null?{trigger_version:{id:he.id,version:he.version}}:{},dep_values:[...Re],...Ge!=null?{dep_batches:Ge}:{}}},z=[],D=[];for(let[j,ne]of e){let Re=P(ne,j);Re&&z.push(Re),D.push(ne.subscribe(Me=>{S++;for(let Oe of Me){let he=Oe[0],Ge=A();if(he===R){m[j]=Oe[1];let oe=ne instanceof Ae?ne.lastMutation?.actor??bt:bt;I({type:"data",path:j,data:Oe[1],actor:oe,...Ge,...U(ne)})}else if(a)he===X?h++:he===G?y++:he===Ye?b++:he===Be?v++:he===Ke?T++:he===de?w++:he===O&&!g.has(j)?k=!0:he===M&&(x=!0,g.add(j));else if(he===X)h++,I({type:"dirty",path:j,...Ge});else if(he===G)y++,I({type:"resolved",path:j,...Ge,...U(ne)});else if(he===Ye)b++,I({type:"invalidate",path:j,...Ge});else if(he===Be)v++,I({type:"pause",path:j,lockId:Oe[1],...Ge});else if(he===Ke)T++,I({type:"resume",path:j,lockId:Oe[1],...Ge});else if(he===O)g.has(j)||(k=!0),I({type:"complete",path:j,...Ge});else if(he===M){x=!0,g.add(j);let oe=ne instanceof Ae?ne.lastMutation?.actor??bt:bt;I({type:"error",path:j,data:Oe[1],actor:oe,...Ge})}else he===de&&(w++,I({type:"teardown",path:j,...Ge}))}}))}let Z=!1,te=()=>{if(!Z){Z=!0;for(let j of D)j();for(let j of z)j();for(let j of J)j({value:void 0,done:!0});J.length=0}},ke=[],J=[];f.add(j=>{let ne=J.shift();ne?ne({value:j,done:!1}):ke.push(j)});let K={get values(){return m},get dirtyCount(){return h},get resolvedCount(){return y},get invalidateCount(){return b},get pauseCount(){return v},get resumeCount(){return T},get teardownCount(){return w},get events(){return l?l.toArray():[...p]},get anyCompletedCleanly(){return k},get anyErrored(){return x},get completedWithoutErrors(){return k&&!x},onEvent(j){return f.add(j),()=>f.delete(j)},dispose:te,expand(j){te();let ne={...n};return typeof j=="string"?ne.detail=j:Object.assign(ne,j),r(zd(ne))},[Symbol.asyncIterator](){return{next(){return ke.length>0?Promise.resolve({value:ke.shift(),done:!1}):Z?Promise.resolve({value:void 0,done:!0}):new Promise(j=>J.push(j))},return(){return te(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger(K,n),K}_attachFormatLogger(e,n){let r=n.format;if(r==null)return;let s=n.logger??(m=>console.log(m)),o=n.includeTypes?new Set(n.includeTypes):null,i=n.excludeTypes?new Set(n.excludeTypes):null,a=o==null&&i==null?()=>!0:m=>(o==null||o.has(m))&&(i==null||!i.has(m)),u=Lm(n.theme),d=r==="stage-log"?F():0,c=m=>m==null?"":n.stageLabels?.[m]??m,l=(m,g)=>m.length>g?`${m.slice(0,g-1)}\u2026`:m,p=m=>m.type==="data"||m.type==="error"?l(rs(m.data),120):"",f=m=>{if(r==="stage-log"){let x=(F()-d)/1e9,S=c(m.path).padEnd(9);if(m.type==="data"){let E=p(m);return`[${x.toFixed(3)}s] ${S} \u2190${E?` ${E}`:""}`}if(m.type==="error"){let E=p(m);return`[${x.toFixed(3)}s] ${S} \u2717${E?` ${E}`:""}`}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 g=u[m.type]??"",h=m.path?`${u.path}${m.path}${u.reset} `:"",y=m.type==="data"||m.type==="error",b=m.type==="pause"||m.type==="resume",v=y?` ${rs(m.data)}`:b?` ${rs(m.lockId)}`:"",T=m.type==="data"||m.type==="resolved"||m.type==="derived"?m:void 0,w=T?.trigger_dep_name!=null?` <- ${T.trigger_dep_name}`:T?.trigger_dep_index!=null?` <- #${T.trigger_dep_index}`:"",k=m.in_batch?" [batch]":"";return`${h}${g}${m.type.toUpperCase()}${u.reset}${v}${w}${k}`};e.onEvent(m=>{a(m.type)&&s(f(m),m)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){Wd(this._disposers,this.name),this.signal([[de]],{internal:!0}),Wd(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"}),s={};for(let a of Object.keys(r.nodes).sort()){let{lastMutation:u,guard:d,...c}=r.nodes[a];s[a]=c}let o=[...r.subgraphs].sort(),i={...r,version:1,nodes:s,subgraphs:o};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 yr(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,n){let r=n?.config??$e,{codec:s,codecVersion:o,payload:i}=br(e,r);return s.decode(i,o)}restore(e,n){if(Ud(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(o=>ns(o)),s=n?.includeProducers===!0;for(let o of Object.keys(e.nodes).sort()){if(r!==null&&!r.some(a=>a.test(o)))continue;let i=e.nodes[o];if(i!==void 0){if(!("value"in i)||i.value===void 0){"value"in i&&i.value===void 0&&n?.onError?.(o,new Error(`restore: slice.value is undefined for "${o}" (undefined is the global SENTINEL; not valid DATA)`));continue}if(!(i.type==="derived"||i.type==="effect")&&!(i.type==="producer"&&!s)){if(i.v!=null){let u=this.tryResolve(o)?.v;if(u!=null&&u.id===i.v.id&&u.version===i.v.version)continue}try{this.set(o,i.value)}catch(a){n?.onError?.(o,a)}}}}}static fromSnapshot(e,n){Ud(e);let r=typeof n=="function"?n:n?.build,s=typeof n=="function"?void 0:n?.factories,o=new t(e.name);if(r)return r(o),o.restore(e),o;for(let f of[...e.subgraphs].sort((m,g)=>{let h=m.split(Pe).length,y=g.split(Pe).length;return h!==y?h-y:m<g?-1:m>g?1:0})){let m=f.split(Pe),g=o;for(let h of m)g._mounts.has(h)||g.mount(h,new t(h)),g=g._mounts.get(h)}let i=s?Object.entries(s).map(([f,m])=>({re:ns(f),factory:m})):[],a=f=>{for(let m of i)if(m.re.test(f))return m.factory},u=f=>{let m=f.split(Pe),g=m.pop();if(g==null||g.length===0)throw new Error(`invalid snapshot path "${f}"`);let h=o;for(let y of m){let b=h._mounts.get(y);if(!b)throw new Error(`unknown mount "${y}" in path "${f}"`);h=b}return[h,g]},d=Object.entries(e.nodes).filter(([f])=>!f.includes(`${Pe}${We}${Pe}`)).sort((f,m)=>f[0]<m[0]?-1:f[0]>m[0]?1:0),c=new Map(d),l=new Map,p=!0;for(;c.size>0&&p;){p=!1;for(let[f,m]of[...c.entries()]){let g=m?.deps??[];if(!g.every(w=>l.has(w)))continue;let[h,y]=u(f),b={...m?.meta??{}},v=a(f),T;if(m?.type==="state")T=N(m.value,{meta:b});else{if(v==null)continue;T=v(y,{path:f,type:m.type,value:m.value,meta:b,deps:g,resolvedDeps:g.map(w=>l.get(w))})}h.add(T,{name:y}),l.set(f,T),c.delete(f),p=!0}}if(c.size>0){let f=[...c.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${f}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return o.restore(e),o}toJSON(){return this.snapshot()}attachStorage(e,n={}){let r=e.map(d=>({tier:d,debounceMs:Math.max(0,d.debounceMs??0),compactEvery:Math.max(1,d.compactEvery??10),timer:void 0,seq:0,lastSnapshot:void 0,lastFingerprint:"",disposed:!1,savePending:void 0}));n.autoRestore===!0&&this._cascadeRestore(e,n.onError);let s=(d,c)=>{if(d.disposed)return;let l=wm(c.nodes);if(d.lastSnapshot!=null&&l!==""&&l===d.lastFingerprint)return;let p=d.seq+1,f=ce(),h=d.lastSnapshot==null||p%d.compactEvery===0?{mode:"full",snapshot:c,seq:p,timestamp_ns:f,format_version:pt}:{mode:"diff",diff:ss(d.lastSnapshot,c),seq:p,timestamp_ns:f,format_version:pt};if(d.tier.filter&&!d.tier.filter(this.name,h))return;let y;try{y=d.tier.save(this.name,h)}catch(b){n.onError?.(b,d.tier);return}if(y&&typeof y.then=="function"){let T=(d.savePending??Promise.resolve()).then(()=>y,()=>y).then(()=>{d.disposed||(d.seq=p,d.lastSnapshot=c,d.lastFingerprint=l)},w=>{n.onError?.(w,d.tier)});d.savePending=T.finally(()=>{d.savePending===T&&(d.savePending=void 0)})}else d.seq=p,d.lastSnapshot=c,d.lastFingerprint=l},o=(d,c)=>{try{s(d,c)}catch(l){n.onError?.(l,d.tier)}},i=(d,c)=>{if(!c.some(m=>{let g=this.config.messageTier(m[0]);return g>=3&&g<5}))return;if(n.filter){let m=this.tryResolve(d);if(m==null)return;let g=Ir(m,_t("standard"));if(!n.filter(d,g))return}let p,f=()=>(p==null&&(p=this.snapshot()),p);for(let m of r)m.disposed||(m.debounceMs===0?o(m,f()):(m.timer==null&&(m.timer=new Le),m.timer.start(m.debounceMs,()=>{m.disposed||o(m,this.snapshot())})))},a;if(n.paths!=null){let c=(typeof n.paths=="string"?this._pathsMatching(n.paths):n.paths).map(l=>{let p=this.tryResolve(l);return p==null?()=>{}:p.subscribe(f=>i(l,f))});a=()=>{for(let l of c)l()}}else a=this.observe().subscribe((d,c)=>i(d,c));let u=()=>{a();for(let d of r)d.disposed=!0,d.timer?.cancel();this._storageDisposers.delete(u)};return this._storageDisposers.add(u),{dispose:u}}async _cascadeRestore(e,n){for(let r of e){let s;try{s=await r.load(this.name)}catch(i){n?.(i,r);continue}if(s==null||typeof s!="object"||Array.isArray(s))continue;let o=s;try{if(o.mode==="full"&&o.snapshot!=null)return this.restore(o.snapshot),!0;if(o.version===pt&&o.nodes!=null)return this.restore(o),!0}catch(i){n?.(i,r)}}return!1}static async fromStorage(e,n,r){for(let s of n){let o;try{o=await s.load(e)}catch(u){r?.onError?.(u,s);continue}if(o==null||typeof o!="object"||Array.isArray(o))continue;let i=o,a=i.mode==="full"&&i.snapshot!=null?i.snapshot:i.version===pt&&i.nodes!=null?i:void 0;if(a!=null)try{return t.fromSnapshot(a,r)}catch(u){r?.onError?.(u,s)}}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 s={path:e,annotation:n,timestamp_ns:F(),...r?.actor!=null?{actor:r.actor}:{}};this._traceRing.push(s)}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(s=>!e(s)),r=this._traceRing.size-n.length;this._traceRing.clear();for(let s of n)this._traceRing.push(s);return r}static diff(e,n){let r=new Set(Object.keys(e.nodes)),s=new Set(Object.keys(n.nodes)),o=[...s].filter(b=>!r.has(b)).sort(),i=[...r].filter(b=>!s.has(b)).sort(),a=[],u=[];for(let b of r){if(!s.has(b))continue;let v=e.nodes[b],T=n.nodes[b],w=v.v,k=T.v;w!=null&&k!=null&&w.id===k.id&&w.version!==k.version&&u.push({path:b,id:w.id,from:w.version,to:k.version});let x=w!=null&&k!=null&&w.id===k.id&&w.version===k.version;for(let S of["type","status","sentinel"]){let E=v[S],L=T[S];E!==L&&a.push({path:b,field:S,from:E,to:L})}if(!x)for(let S of["value","meta"]){let E=v[S],L=T[S];km(E,L)||a.push({path:b,field:S,from:E,to:L})}}let d=b=>`${b.from} ${b.to}`,c=new Set(e.edges.map(d)),l=new Set(n.edges.map(d)),p=n.edges.filter(b=>!c.has(d(b))),f=e.edges.filter(b=>!l.has(d(b))),m=new Set(e.subgraphs),g=new Set(n.subgraphs),h=[...g].filter(b=>!m.has(b)).sort(),y=[...m].filter(b=>!g.has(b)).sort();return{nodesAdded:o,nodesRemoved:i,nodesChanged:a,versionChanges:u,edgesAdded:p,edgesRemoved:f,subgraphsAdded:h,subgraphsRemoved:y}}};function ss(t,e){let n=q.diff(t,e),r={};for(let s of n.nodesAdded){let o=e.nodes[s];o!=null&&(r[s]=o)}return{...n,nodesAddedFull:r}}function fn(t,e,n,r={}){let s={paths:[],depths:new Map,truncated:!1};if(!e)return r.withDetail?s:[];if(!r.both&&n!=="upstream"&&n!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let o=r.maxDepth;if(o!=null&&(!Number.isInteger(o)||o<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(o===0)return r.withDetail?s:[];let i=new Map,a=new Map,u=new Map,d=new Map,c=new Set;for(let[v,T]of Object.entries(t.nodes)){if(!v)continue;c.add(v);let w=T.deps??[];i.set(v,w);for(let k of w)k&&(c.add(k),a.has(k)||a.set(k,new Set),a.get(k).add(v))}for(let v of t.edges){if(v==null||typeof v!="object")continue;let T=typeof v.from=="string"?v.from:"",w=typeof v.to=="string"?v.to:"";!T||!w||(c.add(T),c.add(w),d.has(T)||d.set(T,new Set),d.get(T).add(w),u.has(w)||u.set(w,new Set),u.get(w).add(T))}if(!c.has(e))return r.withDetail?s:[];let l=r.both===!0,p=v=>{if(l){let x=i.get(v)??[],S=u.get(v),E=a.get(v),L=d.get(v),C=[...x];return S&&C.push(...S),E&&C.push(...E),L&&C.push(...L),C}if(n==="upstream"){let x=i.get(v)??[],S=u.get(v);return S?[...x,...S]:x}let T=a.get(v),w=d.get(v),k=T?[...T]:[];return w&&k.push(...w),k},f=new Set([e]),m=new Map,g=[{path:e,depth:0}],h=0,y=!1;for(;h<g.length;){let v=g[h++];if(o!=null&&v.depth>=o){p(v.path).length>0&&(y=!0);continue}for(let T of p(v.path))!T||f.has(T)||(f.add(T),m.set(T,v.depth+1),g.push({path:T,depth:v.depth+1}))}let b=[...m.keys()].sort((v,T)=>v<T?-1:v>T?1:0);return r.withDetail?{paths:b,depths:m,truncated:y}:b}function Gm(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],s=e[n];if(r.path!==s.path||r.type!==s.type||r.status!==s.status||r.hop!==s.hop||r.dep_index!==s.dep_index||r.annotation!==s.annotation||r.value!==s.value||r.lastMutation!==s.lastMutation)return!1;let o=r.v,i=s.v;if(o!==i&&(o==null||i==null||o.id!==i.id||o.version!==i.version))return!1}return!0}var us={};we(us,{CqrsGraph:()=>as,MemoryEventStore:()=>sa,cqrs:()=>ia});Ce();Ne();nn();var na={};we(na,{COMPLETE:()=>O,COMPLETE_MSG:()=>ko,COMPLETE_ONLY_BATCH:()=>gr,DATA:()=>R,DEFAULT_ACTOR:()=>bt,DIRTY:()=>X,DIRTY_MSG:()=>Rt,DIRTY_ONLY_BATCH:()=>On,ERROR:()=>M,GraphReFlyConfig:()=>en,GuardDenied:()=>rt,INVALIDATE:()=>Ye,INVALIDATE_MSG:()=>wo,INVALIDATE_ONLY_BATCH:()=>hr,NodeImpl:()=>Ae,PAUSE:()=>Be,RESOLVED:()=>G,RESOLVED_MSG:()=>_n,RESOLVED_ONLY_BATCH:()=>mr,RESUME:()=>Ke,START:()=>yt,START_MSG:()=>Mn,TEARDOWN:()=>de,TEARDOWN_MSG:()=>xo,TEARDOWN_ONLY_BATCH:()=>Cn,accessHintForGuard:()=>Nr,advanceVersion:()=>Er,autoTrackNode:()=>rn,batch:()=>Y,configure:()=>ji,createVersioning:()=>Dn,defaultConfig:()=>$e,defaultHash:()=>Gt,derived:()=>_,downWithBatch:()=>Nt,dynamicNode:()=>_r,effect:()=>le,isBatching:()=>Zt,isV1:()=>Gi,monotonicNs:()=>F,node:()=>V,normalizeActor:()=>St,pipe:()=>Bi,policy:()=>tn,policyFromRules:()=>Sr,producer:()=>$,registerBuiltins:()=>Rr,resolveDescribeFields:()=>_t,state:()=>N,wallClockNs:()=>ce});Tr();Ce();Ne();Di();nn();se();_e();Q();No();Ce();se();Q();var Gr=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),s=e.length-r;for(let o=0;o<r;o++)this._buf[o]=e[s+o];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),s=Math.min(e,this._size);if(s>=r)return[];let o=r-s;if(this._maxSize===void 0)return this._buf.slice(s,r);let i=new Array(o);for(let a=0;a<o;a++)i[a]=this._buf[(this._head+s+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 Zd(t){return t.subscribe(()=>{})}var Fm=64;function Ue(t,e={}){let{name:n,maxSize:r,versioning:s,backend:o}=e,i=o??new Gr(t,r),a=N(i.toArray(),{name:n,describeKind:"state",equals:(m,g)=>m===g,...s!=null?{versioning:s}:{}});function u(){let m=i.toArray();Y(()=>{a.down([[X]]),a.down([[R,m]])})}let d=new Map,c=new Map;function l(m,g){return`${m}:${g===void 0?"END":g}`}function p(m){if(m.size<Fm)return;let g=m.keys().next();if(g.done)return;let h=m.get(g.value);h!==void 0&&h.dispose(),m.delete(g.value)}function f(m){let g=i.version;try{return m()}finally{i.version!==g&&u()}}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 g=d.get(m);if(g!==void 0)return d.delete(m),d.set(m,g),g.node;p(d);let h=_([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=Zd(h);return d.set(m,{node:h,dispose:y}),h},slice(m,g){if(!Number.isInteger(m)||m<0)throw new RangeError(`slice: start must be a non-negative integer (got ${m})`);if(g!==void 0&&(!Number.isInteger(g)||g<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${g})`);let h=l(m,g),y=c.get(h);if(y!==void 0)return c.delete(h),c.set(h,y),y.node;p(c);let b=_([a],([T])=>{let w=T;return g===void 0?w.slice(m):w.slice(m,g)},{initial:i.slice(m,g),describeKind:"derived"}),v=Zd(b);return c.set(h,{node:b,dispose:v}),b},disposeTail(m){let g=d.get(m);return g===void 0?!1:(g.dispose(),d.delete(m),!0)},disposeSlice(m,g){let h=l(m,g),y=c.get(h);return y===void 0?!1:(y.dispose(),c.delete(h),!0)},disposeAllViews(){for(let m of d.values())m.dispose();d.clear();for(let m of c.values())m.dispose();c.clear()},dispose(){for(let m of d.values())m.dispose();d.clear();for(let m of c.values())m.dispose();c.clear()}}}var oa={};we(oa,{ENVELOPE_VERSION:()=>An,GRAPH_META_SEGMENT:()=>We,Graph:()=>q,JsonCodec:()=>Ro,SIZEOF_OVERHEAD:()=>je,SIZEOF_SYMBOL:()=>ts,SNAPSHOT_VERSION:()=>pt,createDagCborCodec:()=>Ai,createDagCborZstdCodec:()=>Li,decodeEnvelope:()=>br,diffForWAL:()=>ss,encodeEnvelope:()=>yr,explainPath:()=>Dr,graphProfile:()=>pn,mermaidLiveUrl:()=>os,reachable:()=>fn,registerBuiltinCodecs:()=>vr,replayWAL:()=>Ii,sizeof:()=>Pr,validateGraphObservability:()=>ra,watchTopologyTree:()=>Mt});So();se();function Mt(t,e){let n=new Map,r=(s,o)=>{if(n.has(s))return;let i={off:()=>{},prefix:o};n.set(s,i);let a=s.topology.subscribe(u=>{for(let d of u){if(d[0]!==R)continue;let c=d[1];if(e(c,s,o),c.kind==="added"&&c.nodeKind==="mount"){let l=s._mounts.get(c.name);if(l instanceof q){let p=`${o}${c.name}::`;r(l,p)}}else if(c.kind==="removed"&&c.nodeKind==="mount"){let l=`${o}${c.name}::`;for(let[p,f]of Array.from(n.entries()))p!==t&&f.prefix.startsWith(l)&&(f.off(),n.delete(p))}}});i.off=a;for(let[u,d]of s._mounts)if(d instanceof q){let c=`${o}${u}::`;r(d,c)}};return r(t,""),()=>{for(let s of n.values())s.off();n.clear()}}function ra(t,e={}){let n=[],r=e.requireFound??!0;if(e.skipDescribe!==!0)try{let d=t.describe(),c=new Set(Object.keys(d.nodes)),l=[];for(let[p,f]of Object.entries(d.nodes))for(let m of f.deps)m!==""&&!c.has(m)&&l.push(`${p} \u2192 ${m}`);for(let p of d.edges)c.has(p.from)||l.push(`edge.from: ${p.from}`),c.has(p.to)||l.push(`edge.to: ${p.to}`);l.length>0?n.push({kind:"describe",ok:!1,reason:`describe() has ${l.length} dangling pointer(s); nodes \u2289 deps`,danglingDeps:l}):n.push({kind:"describe",ok:!0,nodeCount:c.size,edgeCount:d.edges.length})}catch(d){n.push({kind:"describe",ok:!1,reason:`describe() threw: ${d instanceof Error?d.message:String(d)}`})}for(let d of e.formats??[])try{let c=t.describe({format:d});typeof c!="string"||c.length===0?n.push({kind:"describe-format",ok:!1,format:d,reason:`describe({ format: "${d}" }) returned empty or non-string output`}):n.push({kind:"describe-format",ok:!0,format:d,length:c.length})}catch(c){n.push({kind:"describe-format",ok:!1,format:d,reason:c instanceof Error?c.message:String(c)})}for(let d of e.paths??[])try{t.resolve(d),n.push({kind:"observe",ok:!0,path:d})}catch(c){n.push({kind:"observe",ok:!1,path:d,reason:c instanceof Error?c.message:String(c)})}for(let[d,c]of e.pairs??[])try{let l=t.explain(d,c);r&&l.found===!1?n.push({kind:"explain",ok:!1,from:d,to:c,reason:`explain(${d} \u2192 ${c}) found no path${l.reason?`: ${l.reason}`:""}`}):n.push({kind:"explain",ok:!0,from:d,to:c,found:l.found,steps:l.steps.length})}catch(l){n.push({kind:"explain",ok:!1,from:d,to:c,reason:l instanceof Error?l.message:String(l)})}let s=n.filter(d=>!d.ok),o=s.length===0,i=e.paths?.length??0,a=e.pairs?.length??0,u=e.formats?.length??0;return{ok:o,checks:n,failures:s,summary(){let d=[e.skipDescribe===!0?null:"describe",u>0?`${u} format${u===1?"":"s"}`:null,i>0?`${i} observe path${i===1?"":"s"}`:null,a>0?`${a} explain pair${a===1?"":"s"}`:null].filter(l=>l!=null),c=d.length>0?d.join(", "):"describe-only";return o?`validateGraphObservability: OK (${c})`:`validateGraphObservability: ${s.length} failure(s) across ${c}`}}}Ce();se();_e();Te();function ft(t,e){t!=null&&Nt(n=>t.down(n),[[R,e]],$e.tierOf)}function Fr(t,e){let n=t.cache??0;return n>=e?!1:(t.down([[X],[R,n+1]]),!0)}function ze(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}function $r(t){return t.relatedTo?.[0]??t.summary}var $m=tn((t,e)=>{t("write"),t("signal"),e("observe")}),jm=tn((t,e)=>{t("observe"),t("signal"),e("write")}),Bm=tn((t,e)=>{t("observe"),t("signal"),e("write")});function is(t,e){return ze("cqrs",t,e)}var sa=class{_store=new Map;persist(e){let n=this._store.get(e.type);n||(n=[],this._store.set(e.type,n)),n.push(e)}loadEvents(e,n){let r=this._store.get(e)??[],s=n?.timestampNs,o=n?.seq,i=s==null?[...r]:r.filter(u=>u.timestampNs>s||u.timestampNs===s&&u.seq>(o??-1)),a=i.length>0?i[i.length-1]:void 0;return{events:i,cursor:a?{timestampNs:a.timestampNs,seq:a.seq}:n}}clear(){this._store.clear()}},as=class extends q{_eventLogs=new Map;_commandHandlers=new Map;_projections=new Set;_sagas=new Set;_keepaliveDisposers=[];_eventStore;_seq=0;constructor(e,n={}){super(e,n.graph)}destroy(){for(let e of this._keepaliveDisposers)e();this._keepaliveDisposers.length=0,super.destroy()}event(e){let n=this._eventLogs.get(e);if(n)return n.node;let r=Ue([],{name:e,versioning:0}),s=r.entries,o=_([s],([i])=>i,{name:e,describeKind:"state",meta:is("event",{event_name:e}),guard:Bm,initial:s.cache});return this.add(o,{name:e}),this._keepaliveDisposers.push(re(o)),this._eventLogs.set(e,{log:r,node:o}),o}_appendEvent(e,n){let r=this._eventLogs.get(e);if(r||(this.event(e),r=this._eventLogs.get(e)),r.node.status==="completed"||r.node.status==="errored")throw new Error(`Cannot dispatch to terminated event stream "${e}" (status: ${r.node.status}).`);let s=r.log.entries.v,o={type:e,payload:n,timestampNs:ce(),seq:++this._seq,...s!=null?{v0:{id:s.id,version:s.version}}:{}};r.log.append(o),this._eventStore&&this._eventStore.persist(o)}command(e,n){let r=N(void 0,{name:e,describeKind:"state",meta:{...is("command",{command_name:e}),error:null},guard:$m});return this.add(r,{name:e}),this._commandHandlers.set(e,n),r}dispatch(e,n){let r=this._commandHandlers.get(e);if(!r)throw new Error(`Unknown command: "${e}". Register with .command() first.`);let s=this.resolve(e);Y(()=>{s.emit(n,{internal:!0});try{r(n,{emit:(o,i)=>this._appendEvent(o,i)}),s.meta.error.emit(null,{internal:!0})}catch(o){throw s.meta.error.emit(o,{internal:!0}),o}})}projection(e,n,r,s){let o=n.map(a=>(this._eventLogs.has(a)||this.event(a),this._eventLogs.get(a).node)),i=_(o,a=>{let u=[];for(let d of a){let c=d;u.push(...c)}return u.sort((d,c)=>d.timestampNs-c.timestampNs||d.seq-c.seq),r(s,u)},{name:e,describeKind:"derived",meta:is("projection",{projection_name:e,source_events:n}),guard:jm,initial:s});return this.add(i,{name:e}),this._keepaliveDisposers.push(re(i)),this._projections.add(e),i}saga(e,n,r){let s=n.map(u=>(this._eventLogs.has(u)||this.event(u),this._eventLogs.get(u).node)),o=new Map,i={},a=V(s,(u,d)=>{let c=i.n.meta.error;for(let l=0;l<u.length;l++){let p=u[l];if(p==null||p.length===0)continue;let f=p.at(-1);if(!f)continue;let m=n[l],g=o.get(m)??0;if(f.length>g){let h=f.slice(g);for(let y of h)try{r(y),c.emit(null,{internal:!0})}catch(b){c.emit(b,{internal:!0})}o.set(m,f.length)}}},{name:e,describeKind:"effect",meta:{...is("saga",{saga_name:e,source_events:n}),error:null}});return i.n=a,this.add(a,{name:e}),this._keepaliveDisposers.push(re(a)),this._sagas.add(e),a}useEventStore(e){this._eventStore=e}async rebuildProjection(e,n,r){if(!this._eventStore)throw new Error("No event store wired. Call useEventStore() first.");let s=[];for(let o of e){let i=await this._eventStore.loadEvents(o);s.push(...i.events)}return s.sort((o,i)=>o.timestampNs-i.timestampNs||o.seq-i.seq),n(r,s)}};function ia(t,e){return new as(t,e)}var ua=class{constructor(e){this.graph=e}onModuleDestroy(){this.graph.destroy()}},da=class{graph=new q("request");onModuleDestroy(){this.graph.destroy()}},ec,aa;ec=[(0,jr.Module)({})];var Ht=class Ht{static forRoot(e){let n=e??{},r=n.name??"root",s=[{provide:at,useFactory:()=>{let o=new q(r);return n.build&&n.build(o),n.snapshot&&o.restore(n.snapshot),o}},{provide:Symbol.for("graphrefly:root-lifecycle"),useFactory:o=>new ua(o),inject:[at]},{provide:cn,useFactory:(o,i)=>new cn(o,i),inject:[at,tc.ModuleRef]}];if(n.nodes)for(let o of n.nodes)s.push({provide:ct(o),useFactory:i=>i.resolve(o),inject:[at]});return n.requestScope&&s.push({provide:Symbol.for("graphrefly:request-lifecycle"),useFactory:()=>new da,scope:jr.Scope.REQUEST},{provide:on,useFactory:o=>o.graph,inject:[Symbol.for("graphrefly:request-lifecycle")],scope:jr.Scope.REQUEST}),{module:Ht,global:!0,providers:s,exports:[at,...(n.nodes??[]).map(ct),...n.requestScope?[on]:[]]}}static forFeature(e){let n=[{provide:ot(e.name),useFactory:r=>{let s=new q(e.name);return e.build&&e.build(s),e.snapshot&&s.restore(e.snapshot),r.mount(e.name,s),s},inject:[at]}];if(e.nodes)for(let r of e.nodes)n.push({provide:ct(`${e.name}::${r}`),useFactory:s=>s.resolve(r),inject:[ot(e.name)]});return{module:Ht,providers:n,exports:[ot(e.name),...(e.nodes??[]).map(r=>ct(`${e.name}::${r}`))]}}static forCqrs(e){let n=[{provide:ot(e.name),useFactory:r=>{let s=ia(e.name,e.cqrs);return e.eventStore&&s.useEventStore(e.eventStore),e.build&&e.build(s),r.mount(e.name,s),s},inject:[at]}];if(e.nodes)for(let r of e.nodes)n.push({provide:ct(`${e.name}::${r}`),useFactory:s=>s.resolve(r),inject:[ot(e.name)]});return{module:Ht,providers:n,exports:[ot(e.name),...(e.nodes??[]).map(r=>ct(`${e.name}::${r}`))]}}};aa=$u(null),Ht=Vu(aa,0,"GraphReflyModule",ec,Ht),Bu(aa,1,Ht);var ds=Ht;var ls={};we(ls,{useStore:()=>Vm,useSubscribe:()=>nc,useSubscribeRecord:()=>Km});var Ot=require("react");se();function nc(t){return(0,Ot.useSyncExternalStore)(e=>{let n=!1,r=t.subscribe(()=>{n||e()});return()=>{n=!0,r()}},()=>t.cache,()=>t.cache)}function Vm(t){let e=nc(t),n=(0,Ot.useCallback)(r=>{t.down([[X],[R,r]])},[t]);return[e,n]}function Km(t,e){let n=(0,Ot.useRef)(e);n.current=e;let r=(0,Ot.useMemo)(()=>{let s=()=>{let i={},a=t.cache??[];for(let u of a){let d=n.current(u),c={};for(let l of Object.keys(d))c[l]=d[l].cache;i[u]=c}return i},o=s();return{subscribe:i=>{let a=!1,u=[],d=()=>{for(let p of u)p();u=[]},c=p=>{d();for(let f of p){let m=n.current(f);for(let g of Object.keys(m)){let h=m[g].subscribe(()=>{o=s(),a||i()});u.push(h)}}o=s(),a||i()},l=t.subscribe(p=>{let f=p.some(m=>m[0]===R||m[0]===G);!a&&f&&c(t.cache??[])});return c(t.cache??[]),()=>{a=!0,l(),d()}},getSnapshot:()=>o}},[t]);return(0,Ot.useSyncExternalStore)(r.subscribe,r.getSnapshot,r.getSnapshot)}var fs={};we(fs,{Signal:()=>Hm});Ce();se();Q();var Xn=[];function ps(t){let e=t.cache;return t.subscribe(r=>{for(let[s,o]of r)s===R&&(e=o)})(),e}var ca=class{_node;_equals;constructor(e,n){this._equals=n?.equals??Object.is,this._node=N(e,{...n,resubscribable:!0,resetOnTeardown:!0})}get(){let e=Xn[Xn.length-1];return e?(this._node.status==="sentinel"&&ps(this._node),e(this._node)):this._node.status==="sentinel"?ps(this._node):this._node.cache}set(e){this._equals(this.get(),e)||Y(()=>{this._node.down([[X],[R,e]])})}},la=class{_node;constructor(e,n){this._node=rn(r=>{Xn.push(r);try{return e()}finally{Xn.pop()}},{...n,describeKind:"derived",resubscribable:!0,resetOnTeardown:!0})}get(){let e=Xn[Xn.length-1];return e?(this._node.status==="sentinel"&&ps(this._node),e(this._node)):this._node.status==="sentinel"?ps(this._node):this._node.cache}},Hm={State:ca,Computed:la,sub:(t,e)=>{let n=typeof e=="function"?{data:e,error:void 0,complete:void 0}:e,r=!0;return t._node.subscribe(s=>{for(let[o,i]of s){if(o===R){if(r){r=!1;continue}n.data?.(i)}o===M&&n.error?.(i),o===O&&n.complete?.()}})}};var ms={};we(ms,{useStore:()=>qm,useSubscribe:()=>rc,useSubscribeRecord:()=>Wm});var Ct=require("solid-js");se();function rc(t){let[e,n]=(0,Ct.createSignal)(t.cache,{equals:!1}),r=t.subscribe(()=>{n(()=>t.cache)});return(0,Ct.getOwner)()?(0,Ct.onCleanup)(()=>r()):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribe called outside a Solid reactive owner \u2014 subscription will not be auto-disposed."),e}function qm(t){return[rc(t),r=>{t.down([[X],[R,r]])}]}function Wm(t,e){let[n,r]=(0,Ct.createSignal)({},{equals:!1}),s=[],o=()=>{for(let d of s)d();s=[]},i=()=>{let d={};for(let c of t.cache??[]){let l=e(c),p={};for(let f of Object.keys(l))p[f]=l[f].cache;d[c]=p}return d},a=d=>{o();for(let c of d){let l=e(c);for(let p of Object.keys(l)){let f=l[p].subscribe(()=>{r(()=>i())});s.push(f)}}r(()=>i())},u=t.subscribe(d=>{d.some(c=>c[0]===R||c[0]===G)&&a(t.cache??[])});return a(t.cache??[]),(0,Ct.getOwner)()?(0,Ct.onCleanup)(()=>{u(),o()}):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribeRecord called outside a Solid reactive owner \u2014 subscription will not be auto-disposed."),n}var hs={};we(hs,{useStore:()=>zm,useSubscribe:()=>Um,useSubscribeRecord:()=>Jm});se();function Um(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n}}}function zm(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n},set(e){t.down([[X],[R,e]])},update(e){let n=e(t.cache);t.down([[X],[R,n]])}}}function Jm(t,e){return{subscribe(n){let r=[],s=()=>{for(let u of r)u();r=[]},o=()=>{let u={};for(let d of t.cache??[]){let c=e(d),l={};for(let p of Object.keys(c))l[p]=c[p].cache;u[d]=l}return u},i=u=>{s();for(let d of u){let c=e(d);for(let l of Object.keys(c)){let p=c[l].subscribe(()=>{n(o())});r.push(p)}}n(o())},a=t.subscribe(u=>{u.some(d=>d[0]===R||d[0]===G)&&i(t.cache??[])});return i(t.cache??[]),()=>{a(),s()}}}}var gs={};we(gs,{useStore:()=>Qm,useSubscribe:()=>Ym,useSubscribeRecord:()=>Xm});var Ve=require("vue");se();function Ym(t){let e=(0,Ve.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,Ve.getCurrentScope)()?(0,Ve.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribe called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Ve.readonly)(e)}function Qm(t){let e=(0,Ve.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,Ve.getCurrentScope)()?(0,Ve.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useStore called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Ve.computed)({get:()=>e.value,set:r=>{t.down([[X],[R,r]])}})}function Xm(t,e){let n=(0,Ve.shallowRef)({}),r=new Map;function s(){let a={};for(let[u,d]of r)a[u]={...d.values};n.value=a}function o(a){for(let d of r.values())for(let c of d.subs)c();r.clear();for(let d of a){let c=e(d),l=Object.keys(c),p={},f=[];for(let m of l){let g=c[m];p[m]=g.cache;let h=g.subscribe(()=>{p[m]=g.cache,s()});f.push(h)}r.set(d,{subs:f,values:p})}let u={};for(let[d,c]of r)u[d]={...c.values};n.value=u}return(0,Ve.watch)(()=>[...(typeof t=="function"?t():(0,Ve.isRef)(t)?t.value:t)??[]],a=>o(a??[]),{immediate:!0}),(0,Ve.getCurrentScope)()?(0,Ve.onScopeDispose)(()=>{for(let a of r.values())for(let u of a.subs)u();r.clear()}):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribeRecord called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Ve.readonly)(n)}var ys={};we(ys,{create:()=>eh});se();Q();var Zm=()=>!1;function eh(t){let e=new q("zustand"),n=N(void 0,{name:"state",equals:Zm});e.add(n,{name:"state"});let r=()=>n.cache,s=(a,u)=>{let d=n.cache,c=typeof a=="function"?a(d):a;n.emit(u?c:{...d,...c})},o={getState:r,setState:s,getInitialState:()=>i,subscribe:a=>{let u=!0,d=n.cache;return n.subscribe(c=>{for(let[l,p]of c)if(l===R){if(u){u=!1;continue}a(p,d),d=p}})},destroy:e.destroy.bind(e)},i=t(s,r,o);return n.emit(i),Object.assign(e,o)}var Ea={};we(Ea,{CircuitOpenError:()=>lt,ContentAddressedMissError:()=>zr,NS_PER_MS:()=>He,NS_PER_SEC:()=>it,NativeIndexBackend:()=>Qr,NativeListBackend:()=>Xr,NativeLogBackend:()=>Gr,NativeMapBackend:()=>Wr,NativePubSubBackend:()=>Yr,RateLimiterOverflowError:()=>an,ResettableTimer:()=>Le,TimeoutError:()=>un,audit:()=>Sc,awaitSettled:()=>Wo,buffer:()=>Nc,bufferCount:()=>Ec,bufferTime:()=>Mc,cached:()=>Rd,canonicalJson:()=>Jr,cascadingCache:()=>Gl,catchError:()=>$c,checkpointToRedis:()=>Ml,checkpointToS3:()=>_l,circuitBreaker:()=>Tt,combine:()=>ma,combineLatest:()=>Pc,concat:()=>bc,concatMap:()=>wc,constant:()=>Po,contentAddressedStorage:()=>xs,createTransport:()=>Wt,createWatermarkController:()=>Yn,csvRows:()=>cl,debounce:()=>ga,debounceTime:()=>Gc,decorrelatedJitter:()=>jo,delay:()=>xc,deserializeError:()=>yn,dictStorage:()=>zl,distill:()=>ws,distinctUntilChanged:()=>hc,elementAt:()=>pc,empty:()=>vd,escapeRegexChar:()=>Ui,exhaustMap:()=>Tc,exponential:()=>Fo,externalBundle:()=>bs,externalProducer:()=>mn,fallback:()=>Un,fibonacci:()=>$o,filter:()=>Xe,find:()=>lc,first:()=>vs,firstValueFrom:()=>Qe,firstWhere:()=>Vo,flatMap:()=>kc,forEach:()=>Vt,fromAny:()=>W,fromAsyncIter:()=>Ar,fromCSV:()=>dl,fromClickHouseWatch:()=>ml,fromCron:()=>Ko,fromDrizzle:()=>Il,fromEvent:()=>bd,fromHTTP:()=>wa,fromHTTPPoll:()=>Jc,fromHTTPStream:()=>zc,fromIter:()=>Ho,fromKafka:()=>sl,fromKysely:()=>Dl,fromMCP:()=>Xc,fromNATS:()=>yl,fromNDJSON:()=>fl,fromOTel:()=>Zc,fromPrisma:()=>Ll,fromPrometheus:()=>ol,fromPromise:()=>Jn,fromPulsar:()=>hl,fromRabbitMQ:()=>vl,fromRaf:()=>yd,fromRedisStream:()=>al,fromSSE:()=>Uc,fromSqlite:()=>Ol,fromSqliteCursor:()=>Cl,fromStatsD:()=>nl,fromSyslog:()=>el,fromTimer:()=>dt,fromWebSocket:()=>Ta,fromWebSocketReconnect:()=>Qc,fromWebhook:()=>jc,globToRegExp:()=>hd,interval:()=>Ac,keepalive:()=>re,last:()=>cc,linear:()=>Go,lru:()=>Ra,makeHttpError:()=>ht,map:()=>Br,matchesAnyPattern:()=>gd,matchesCron:()=>Do,memoryStorage:()=>eo,merge:()=>wt,mergeMap:()=>ha,nameToSignal:()=>hn,ndjsonRows:()=>ll,never:()=>Td,nodeSignal:()=>Uo,of:()=>zi,onFirstData:()=>Kr,pairwise:()=>gc,parseCron:()=>Io,parsePrometheusText:()=>ka,parseSSEStream:()=>Lt,parseStatsD:()=>rl,parseSyslog:()=>tl,pausable:()=>Ic,pubsub:()=>Vl,race:()=>vc,rateLimiter:()=>Wn,reactiveCounter:()=>Ji,reactiveIndex:()=>ql,reactiveList:()=>Rs,reactiveLog:()=>Ue,reactiveMap:()=>Ze,reactiveSink:()=>qe,reduce:()=>ac,repeat:()=>Lc,replay:()=>qo,rescue:()=>Hr,resolveBackoffPreset:()=>Ft,retry:()=>Hn,retrySource:()=>$t,sample:()=>Rc,scan:()=>ic,serializeError:()=>gn,share:()=>xd,shareReplay:()=>Sd,signalToName:()=>qt,singleFromAny:()=>Ss,singleNodeFromAny:()=>Wl,skip:()=>fa,sortJsonValue:()=>Zr,stableJsonString:()=>Ul,stratify:()=>to,switchMap:()=>be,take:()=>Vr,takeUntil:()=>dc,takeWhile:()=>uc,tap:()=>fc,tapFirst:()=>mc,throttle:()=>ya,throttleTime:()=>Fc,throwError:()=>wd,timeout:()=>zn,toArray:()=>kd,toCSV:()=>wl,toClickHouse:()=>kl,toFile:()=>xa,toHTTP:()=>Bc,toKafka:()=>il,toLoki:()=>Nl,toMongo:()=>Sl,toNATS:()=>bl,toObservable:()=>Lo,toPostgres:()=>Rl,toPulsar:()=>gl,toRabbitMQ:()=>Tl,toReadableStream:()=>Wc,toRedisStream:()=>ul,toS3:()=>xl,toSSE:()=>Hc,toSSEBytes:()=>qc,toSqlite:()=>Al,toTempo:()=>El,toWebSocket:()=>Yc,tokenBucket:()=>jt,valve:()=>Dc,verifiable:()=>jl,window:()=>Cc,windowCount:()=>_c,windowTime:()=>Oc,withBreaker:()=>qn,withLatestFrom:()=>At,withMaxAttempts:()=>qi,withStatus:()=>Bt,workerBridge:()=>Sa,workerSelf:()=>Na,zip:()=>yc});Ce();Ne();se();_e();Q();Ce();se();Q();function oc(t){return{describeKind:"producer",...t}}function mn(t,e){return $(n=>{let r=!0,s={emit(i){r&&n.emit(i)},error(i){r&&(r=!1,n.down([[M,i]]))},complete(){r&&(r=!1,n.down([[O]]))}},o;try{let i=t(s);o=typeof i=="function"?i:void 0}catch(i){return s.error(i),()=>{r=!1}}return()=>{r=!1;try{o?.()}catch{}}},oc(e))}function bs(t,e,n){let r=!0,s,o=0,i=0,a={},u=[],d=()=>{let f=s;s=void 0;try{f?.()}catch{}};for(let f of e){let m=n?.name?`${n.name}::${f}`:f,g=n?.channelOpts?.[f],h=$(y=>(o++,()=>{i++,o>0&&i>=o&&i>=e.length&&d()}),oc({...g,name:m}));a[f]=h,u.push(h)}let c={};for(let f of e)c[f]=m=>{r&&a[f].down([[R,m]])};c.error=f=>{r&&(r=!1,Y(()=>{for(let m of u)m.down([[M,f]])}),d())},c.complete=()=>{r&&(r=!1,Y(()=>{for(let f of u)f.down([[O]])}),d())};let l=t(c);return s=typeof l=="function"?l:void 0,Object.assign(a,{dispose:()=>{r&&(r=!1,Y(()=>{for(let f of u)try{f.down([[O]])}catch{}}),d())}})}Ne();se();_e();Q();Te();function ie(t){return{describeKind:"derived",...t}}function sc(t){return{describeKind:"derived",partial:!0,...t}}function Br(t,e,n){return V([t],(r,s)=>{let o=r[0];if(o==null||o.length===0){s.down([[G]]);return}for(let i of o)s.emit(e(i))},ie(n))}function Xe(t,e,n){return V([t],(r,s)=>{let o=r[0];if(o==null||o.length===0){s.down([[G]]);return}let i=!1;for(let a of o)e(a)&&(s.emit(a),i=!0);i||s.down([[G]])},ie(n))}function ic(t,e,n,r){return V([t],(s,o,i)=>{"acc"in i.store||(i.store.acc=n);let a=s[0];if(a==null||a.length===0){o.down([[G]]);return}for(let u of a)i.store.acc=e(i.store.acc,u),o.emit(i.store.acc)},{...ie(r),initial:n,resetOnTeardown:!0})}function ac(t,e,n,r){return V([t],(s,o,i)=>{if("acc"in i.store||(i.store.acc=n),i.terminalDeps[0]===!0){o.emit(i.store.acc),o.down([[O]]);return}let a=s[0];if(a==null||a.length===0){o.down([[G]]);return}for(let u of a)i.store.acc=e(i.store.acc,u)},{...ie(r),completeWhenDepsComplete:!1})}function Vr(t,e,n){return e<=0?V([t],(r,s,o)=>{o.store.completed||(o.store.completed=!0,s.down([[O]]))},{...ie(n),completeWhenDepsComplete:!1}):V([t],(r,s,o)=>{if("taken"in o.store||(o.store.taken=0),o.store.done){s.down([[G]]);return}if(o.terminalDeps[0]===!0){o.store.done=!0,s.down([[O]]);return}let i=r[0];if(i==null||i.length===0){s.down([[G]]);return}for(let a of i)if(o.store.taken++,s.emit(a),o.store.taken>=e){o.store.done=!0,s.down([[O]]);return}},{...ie(n),completeWhenDepsComplete:!1})}function fa(t,e,n){return V([t],(r,s,o)=>{"skipped"in o.store||(o.store.skipped=0);let i=r[0];if(i==null||i.length===0){s.down([[G]]);return}let a=!1;for(let u of i)o.store.skipped++,o.store.skipped<=e||(s.emit(u),a=!0);a||s.down([[G]])},ie(n))}function uc(t,e,n){return V([t],(r,s,o)=>{if(o.store.done){s.down([[G]]);return}let i=r[0];if(i==null||i.length===0){s.down([[G]]);return}for(let a of i){if(!e(a)){o.store.done=!0,s.down([[O]]);return}s.emit(a)}},{...ie(n),completeWhenDepsComplete:!1})}function dc(t,e,n){let r=n?.predicate??(i=>i[0]===R),{predicate:s,...o}=n??{};return $(i=>{let a=!1,u=t.subscribe(c=>{if(!a)for(let l of c){if(a)return;l[0]===R?i.emit(l[1]):(l[0]===O||l[0]===M)&&(a=!0,i.down([l]))}}),d=e.subscribe(c=>{if(!a)for(let l of c){if(a)return;if(r(l)){a=!0,i.down([[O]]);return}}});return()=>{u(),d()}},ie(o))}function vs(t,e){return Vr(t,1,e)}function cc(t,e){let{defaultValue:n,...r}=e??{},s=e!=null&&Object.hasOwn(e,"defaultValue");return V([t],(o,i,a)=>{if(a.terminalDeps[0]===!0){a.store.has?i.emit(a.store.latest):s&&i.emit(n),i.down([[O]]);return}let u=o[0];if(u==null||u.length===0){i.down([[G]]);return}a.store.latest=u.at(-1),a.store.has=!0},{...ie(r),completeWhenDepsComplete:!1})}function lc(t,e,n){return Vr(Xe(t,e,n),1,n)}function pc(t,e,n){return Vr(fa(t,e,n),1,n)}function fc(t,e,n){if(typeof e=="function")return V([t],(s,o)=>{let i=s[0];if(i==null||i.length===0){o.down([[G]]);return}for(let a of i)e(a),o.emit(a)},ie(n));let r=e;return V([t],(s,o,i)=>{if(i.terminalDeps[0]!==void 0){i.terminalDeps[0]===!0?(r.complete?.(),o.down([[O]])):(r.error?.(i.terminalDeps[0]),o.down([[M,i.terminalDeps[0]]]));return}let a=s[0];if(a==null||a.length===0){o.down([[G]]);return}for(let u of a)r.data?.(u),o.emit(u)},{...ie(n),completeWhenDepsComplete:!1})}function Kr(t,e,n){let r=n?.where??(o=>o!=null),s=!1;return V([t],(o,i)=>{let a=o[0];if(a==null||a.length===0){i.down([[G]]);return}for(let u of a)!s&&r(u)&&(s=!0,e(u)),i.emit(u)},ie(n))}var mc=Kr;function hc(t,e=Object.is,n){return V([t],(r,s,o)=>{let i=r[0];if(i==null||i.length===0){s.down([[G]]);return}let a=!1;for(let u of i)o.store.hasPrev&&e(o.store.prev,u)||(o.store.prev=u,o.store.hasPrev=!0,s.emit(u),a=!0);a||s.down([[G]])},ie(n))}function gc(t,e){return V([t],(n,r,s)=>{let o=n[0];if(o==null||o.length===0){r.down([[G]]);return}let i=!1;for(let a of o)if(!s.store.hasPrev)s.store.prev=a,s.store.hasPrev=!0;else{let u=[s.store.prev,a];s.store.prev=a,r.emit(u),i=!0}i||r.down([[G]])},ie(e))}function ma(...t){let e=[...t];return _(e,n=>n,{...ie(),equals:(n,r)=>{if(n.length!==r.length)return!1;for(let s=0;s<n.length;s++)if(!Object.is(n[s],r[s]))return!1;return!0}})}function At(t,e,n){return V([t,e],(r,s,o)=>{let i=r[0],a=r[1],u=a!=null&&a.length>0?a.at(-1):o.prevData[1];if(i!=null&&i.length>0){if(!(a!=null&&a.length>0)&&o.prevData[1]===void 0){s.down([[G]]);return}for(let d of i)s.emit([d,u])}else s.down([[G]])},sc(n))}function wt(...t){return t.length===0?$(e=>{e.down([[O]])},ie()):$(e=>{let n=t.length,r=0,s=[];for(let o of t){let i=o.subscribe(a=>{for(let u of a)u[0]===R?e.emit(u[1]):u[0]===O?(r+=1,r>=n&&e.down([[O]])):u[0]===M&&e.down([u])});s.push(i)}return()=>{for(let o of s)o()}},ie())}function yc(...t){let e=t.length;return e===0?$(n=>{n.emit([]),n.down([[O]])},ie()):$(n=>{let r=Array.from({length:e},()=>[]),s=e;function o(){for(;r.every(a=>a.length>0);){let a=r.map(u=>u.shift());n.emit(a)}}let i=[];for(let a=0;a<e;a++){let u=a,d=t[a].subscribe(c=>{for(let l of c)l[0]===R?(r[u].push(l[1]),o()):l[0]===O?(s-=1,(s===0||r[u].length===0)&&n.down([[O]])):l[0]===M&&n.down([l])});i.push(d)}return()=>{for(let a of i)a()}},ie())}function bc(t,e,n){return $(r=>{let s=0,o=[],i,a;return a=e.subscribe(u=>{for(let d of u)s===0?d[0]===R?o.push(d[1]):d[0]===M&&r.down([d]):d[0]===R?r.emit(d[1]):(d[0]===O||d[0]===M)&&r.down([d])}),i=t.subscribe(u=>{for(let d of u)if(s===0)if(d[0]===R)r.emit(d[1]);else if(d[0]===O){s=1;for(let c of o)r.emit(c);o.length=0}else d[0]===M&&r.down([d])}),()=>{i?.(),a?.()}},ie(n))}function vc(...t){return t.length===0?$(e=>{e.down([[O]])},ie()):t.length===1?V([t[0]],(e,n)=>{let r=e[0];if(r==null||r.length===0){n.down([[G]]);return}for(let s of r)n.emit(s)},ie()):$(e=>{let n=null,r=[];for(let s=0;s<t.length;s++){let o=s,i=t[s].subscribe(a=>{for(let u of a){if(n!==null&&o!==n)return;u[0]===R?(n===null&&(n=o),e.emit(u[1])):(u[0]===O||u[0]===M)&&(n===null||o===n)&&e.down([u])}});r.push(i)}return()=>{for(let s of r)s()}},ie())}function Ts(t,e,n){let r,s=!1,o=()=>{s||(s=!0,n())};return r=t.subscribe(i=>{let a=!1,u=!1;for(let d of i)d[0]!==yt&&(d[0]===R?e.emit(d[1]):d[0]===O?a=!0:d[0]===M?(u=!0,e.down([d])):(d[0]===X||d[0]===G)&&e.down([d]));u?(r?.(),r=void 0,o()):a&&o()}),()=>{r?.(),r=void 0}}function be(t,e,n){let r,s=!1;function o(){r?.(),r=void 0}return V([t],(i,a,u)=>{if(u.terminalDeps[0]!=null&&u.terminalDeps[0]!==!0){o();return}if(u.terminalDeps[0]===!0){s=!0,r||a.down([[O]]);return}let d=i[0];if(!(d==null||d.length===0))return o(),r=Ts(W(e(d[d.length-1])),a,()=>{o(),s&&a.down([[O]])}),{deactivate:()=>{o(),s=!1}}},{...ie(n),completeWhenDepsComplete:!1})}function Tc(t,e,n){let r,s=!1;function o(){r?.(),r=void 0}return V([t],(i,a,u)=>{if(u.terminalDeps[0]!=null&&u.terminalDeps[0]!==!0){o();return}if(u.terminalDeps[0]===!0){s=!0,r||a.down([[O]]);return}let d=i[0];if(!(d==null||d.length===0))return r===void 0?r=Ts(W(e(d[0])),a,()=>{o(),s&&a.down([[O]])}):a.down([[G]]),{deactivate:()=>{o(),s=!1}}},{...ie(n),completeWhenDepsComplete:!1})}function wc(t,e,n){let{maxBuffer:r,...s}=n??{},o=[],i,a=!1,u;function d(){i?.(),i=void 0}function c(){if(!u||i!==void 0)return;if(o.length===0){a&&u.down([[O]]);return}let p=o.shift();i=Ts(W(e(p)),u,()=>{d(),c()})}function l(p){r&&r>0&&o.length>=r&&o.shift(),o.push(p),c()}return V([t],(p,f,m)=>{if(u=f,m.terminalDeps[0]!=null&&m.terminalDeps[0]!==!0){d(),o.length=0;return}if(m.terminalDeps[0]===!0){a=!0,c();return}let g=p[0];if(!(g==null||g.length===0)){for(let h of g)l(h);return{deactivate:()=>{d(),o.length=0,a=!1}}}},{...ie(s),completeWhenDepsComplete:!1})}function ha(t,e,n){let{concurrent:r,...s}=n??{},o=r!=null&&r>0?r:Number.POSITIVE_INFINITY,i=0,a=!1,u=new Set,d=[],c;function l(){a&&i===0&&d.length===0&&c&&c.down([[O]])}function p(h){if(!c)return;i++;let y;y=Ts(W(e(h)),c,()=>{y&&u.delete(y),i--,f(),l()}),u.add(y)}function f(){for(;d.length>0&&i<o;)p(d.shift())}function m(h){i<o?p(h):d.push(h)}function g(){for(let h of u)h();u.clear(),i=0,d.length=0}return V([t],(h,y,b)=>{if(c=y,b.terminalDeps[0]!=null&&b.terminalDeps[0]!==!0){g();return}if(b.terminalDeps[0]===!0){a=!0,l();return}let v=h[0];if(!(v==null||v.length===0)){for(let T of v)m(T);return{deactivate:()=>{g(),a=!1}}}},{...ie(s),completeWhenDepsComplete:!1})}var kc=ha;function xc(t,e,n){return $(r=>{let s=new Set;function o(){for(let a of s)clearTimeout(a);s.clear()}let i=t.subscribe(a=>{for(let u of a)if(u[0]===R){let d=setTimeout(()=>{s.delete(d),r.emit(u[1])},e);s.add(d)}else if(u[0]===O){let d=setTimeout(()=>{s.delete(d),r.down([[O]])},e);s.add(d)}else u[0]===M&&(o(),r.down([u]))});return()=>{i(),o()}},ie(n))}function ga(t,e,n){return $(r=>{let s,o;function i(){s!==void 0&&(clearTimeout(s),s=void 0)}let a=t.subscribe(u=>{for(let d of u)d[0]===R?(i(),o=d[1],s=setTimeout(()=>{s=void 0,r.emit(o)},e)):d[0]===O?(s!==void 0&&(i(),r.emit(o)),r.down([[O]])):d[0]===M&&(i(),r.down([d]))});return()=>{a(),i()}},ie(n))}function ya(t,e,n){let{leading:r,trailing:s,...o}=n??{},i=r!==!1,a=s===!0,u=e*1e6;return $(d=>{let c,l=-1/0,p,f=!1;function m(){c!==void 0&&(clearTimeout(c),c=void 0)}let g=t.subscribe(h=>{for(let y of h)if(y[0]===R){let b=y[1],v=F();if(i&&v-l>=u)l=v,d.emit(b),m(),a&&(c=setTimeout(()=>{c=void 0,f&&(l=F(),d.emit(p),f=!1)},e));else if(a&&(p=b,f=!0,c===void 0)){let T=(v-l)/1e6;c=setTimeout(()=>{c=void 0,f&&(l=F(),d.emit(p),f=!1)},Math.max(0,e-T))}}else(y[0]===O||y[0]===M)&&(m(),d.down([y]))});return()=>{g(),m()}},ie(o))}function Rc(t,e,n){return $(r=>{let s,o=!1,i=!1,a=t.subscribe(d=>{if(!o)for(let c of d){if(o)return;c[0]===R?s={v:c[1]}:c[0]===M?(o=!0,r.down([c])):c[0]===O&&(i=!0,s=void 0)}}),u=e.subscribe(d=>{if(!o)for(let c of d){if(o)return;c[0]===R?s!==void 0&&!i&&r.emit(s.v):c[0]===M?(o=!0,r.down([c])):c[0]===O&&(o=!0,r.down([[O]]))}});return()=>{a(),u()}},ie(n))}function Sc(t,e,n){return $(r=>{let s,o,i=!1;function a(){s!==void 0&&(clearTimeout(s),s=void 0)}let u=t.subscribe(d=>{for(let c of d)c[0]===R?(o=c[1],i=!0,a(),s=setTimeout(()=>{s=void 0,i&&(i=!1,r.emit(o))},e)):(c[0]===O||c[0]===M)&&(a(),r.down([c]))});return()=>{u(),a()}},ie(n))}function Nc(t,e,n){return $(r=>{let s=[],o=t.subscribe(a=>{for(let u of a)u[0]===R?s.push(u[1]):u[0]===O?(s.length>0&&r.emit([...s]),s.length=0,r.down([[O]])):u[0]===M&&r.down([u])}),i=e.subscribe(a=>{for(let u of a)u[0]===R?s.length>0&&(r.emit([...s]),s.length=0):u[0]===O?r.down([[O]]):u[0]===M&&r.down([u])});return()=>{o(),i(),s.length=0}},ie(n))}function Ec(t,e,n){if(e<=0)throw new RangeError("bufferCount expects count > 0");return $(r=>{let s=[],o=t.subscribe(i=>{for(let a of i)a[0]===R?(s.push(a[1]),s.length>=e&&r.emit(s.splice(0,s.length))):a[0]===O?(s.length>0&&r.emit([...s]),s.length=0,r.down([[O]])):a[0]===M&&r.down([a])});return()=>{o(),s.length=0}},ie(n))}function _c(t,e,n){if(e<=0)throw new RangeError("windowCount expects count > 0");return $(r=>{let s,o=0;function i(){let u=$(d=>(s=d.down.bind(d),()=>{s=void 0}),ie());o=0,r.emit(u)}let a=t.subscribe(u=>{for(let d of u)d[0]===R?(s||i(),s?.([[R,d[1]]]),o+=1,o>=e&&(s?.([[O]]),s=void 0)):d[0]===O?(s?.([[O]]),s=void 0,r.down([[O]])):d[0]===M&&(s?.([d]),s=void 0,r.down([d]))});return()=>{a(),s?.([[O]]),s=void 0}},ie(n))}function Mc(t,e,n){return $(r=>{let s=[],o=setInterval(()=>{s.length>0&&(r.emit([...s]),s.length=0)},e),i=t.subscribe(a=>{for(let u of a)u[0]===R?s.push(u[1]):u[0]===O?(clearInterval(o),s.length>0&&r.emit([...s]),s.length=0,r.down([[O]])):u[0]===M&&(clearInterval(o),r.down([u]))});return()=>{i(),clearInterval(o),s.length=0}},ie(n))}function Oc(t,e,n){return $(r=>{let s;function o(){s?.([[O]]),s=void 0}function i(){let d=$(c=>(s=c.down.bind(c),()=>{s=void 0}),ie());r.emit(d)}i();let a=setInterval(()=>{o(),i()},e),u=t.subscribe(d=>{for(let c of d)c[0]===R?s?.([[R,c[1]]]):c[0]===O?(clearInterval(a),o(),r.down([[O]])):c[0]===M&&(clearInterval(a),s?.([c]),o(),r.down([c]))});return()=>{u(),clearInterval(a),o()}},ie(n))}function Cc(t,e,n){return $(r=>{let s;function o(){s?.([[O]]),s=void 0}function i(){let d=$(c=>(s=c.down.bind(c),()=>{s=void 0}),ie());r.emit(d)}let a=t.subscribe(d=>{for(let c of d)c[0]===R?(s||i(),s?.([[R,c[1]]])):c[0]===O?(o(),r.down([[O]])):c[0]===M&&(s?.([c]),s=void 0,r.down([c]))}),u=e.subscribe(d=>{for(let c of d)c[0]===R&&(o(),i())});return()=>{a(),u(),o()}},ie(n))}function Ac(t,e){return $((n,r)=>{"n"in r.store||(r.store.n=0);let s=setInterval(()=>{n.emit(r.store.n),r.store.n=r.store.n+1},t);return()=>clearInterval(s)},ie(e))}function Lc(t,e,n){if(e<=0)throw new RangeError("repeat expects count > 0");return $(r=>{let s=e,o,i=()=>{o?.(),o=t.subscribe(a=>{let u=!1,d=[];for(let c of a)c[0]===O?u=!0:d.push(c);d.length>0&&r.down(d),u&&(o?.(),o=void 0,s-=1,s>0?i():r.down([[O]]))})};return i(),()=>{o?.()}},ie(n))}function Ic(t,e){return V([t],(n,r)=>{let s=n[0];if(s==null||s.length===0){r.down([[G]]);return}for(let o of s)r.emit(o)},ie(e))}function Hr(t,e,n){return $(r=>{let s=t.subscribe(o=>{for(let i of o)if(i[0]===R)r.emit(i[1]);else if(i[0]===M)try{r.emit(e(i[1]))}catch(a){r.down([[M,a]])}else i[0]===O&&r.down([[O]])});return()=>{s()}},ie(n))}function Dc(t,e,n){return V([t,e],(r,s,o)=>{let i=r[1];if(!(i!=null&&i.length>0?i.at(-1):o.prevData[1])){s.down([[G]]);return}let u=r[0];if(u!=null&&u.length>0){for(let d of u)s.emit(d);return}if(i!=null&&i.length>0&&o.prevData[0]!==void 0){s.emit(o.prevData[0]);return}s.down([[G]])},sc(n))}var Pc=ma,Gc=ga,Fc=ya,$c=Hr;se();_e();Q();Kn();var ba=class{ring;arr;constructor(e){e===Number.POSITIVE_INFINITY||e<=0?(this.arr=[],this.ring=null):(this.ring=new ln(e),this.arr=null)}get length(){return this.ring!=null?this.ring.size:this.arr.length}push(e){this.ring!=null?this.ring.push(e):this.arr.push(e)}shift(){return this.ring!=null?this.ring.shift():this.arr.shift()}drain(){if(this.ring!=null){let n=this.ring.toArray();return this.ring.clear(),n}let e=this.arr;return this.arr=[],e}};function qr(t){return t instanceof Error?t:new Error(String(t))}function th(t){return t===void 0?null:typeof t=="string"?Ft(t):t}function qe(t,e){let{name:n,onTransportError:r,retry:s,backpressure:o,batchSize:i=Number.POSITIVE_INFINITY,flushIntervalMs:a=0,serialize:u,stopOn:d,onUpstreamMessage:c,onDispose:l,send:p,sendBatch:f,ctx:m}=e;if(!p&&!f)throw new Error("reactiveSink: `send` or `sendBatch` must be provided");let g=m,h=Math.max(1,s?.maxAttempts??1),y=th(s?.backoff??(h>1?"exponential":void 0)),b=s?.shouldRetry??(()=>!0),v=f!==void 0||i<Number.POSITIVE_INFINITY||a>0,T=B=>n?`${n}::${B}`:void 0,w=N(void 0,{equals:()=>!1,name:T("sent")}),k=N(null,{name:T("failed")}),x=N(0,{name:T("inFlight")}),S=N(null,{name:T("errors")}),E=v?N(0,{name:T("buffered")}):void 0,L=o?N(!1,{name:T("paused")}):void 0,C=0,I=B=>{C+=B,x.down([[R,C]])},A=B=>{try{r?.(B)}catch{}try{S.down([[R,B]])}catch{}},P=new Set,U=B=>{P.add(B);let ae=()=>P.delete(B);B.then(ae,ae)},z=(B,ae,xe)=>{let Se=y?y(ae-1,xe,null):0,ue=Se==null?0:typeof Se=="number"&&Se>0?Se:0,De=Math.max(1,Math.ceil(ue/1e6));return new Promise(fe=>{setTimeout(()=>fe(B()),De)})},D=B=>B!=null&&typeof B=="object"&&typeof B.then=="function",Z=B=>{let ae;try{ae=u?u(B):B}catch(fe){let me=qr(fe);return A({stage:"serialize",error:me,value:B}),k.down([[R,{value:B,error:me,attempts:0}]]),Promise.resolve()}let xe=0,Se=fe=>{I(-1);let me=qr(fe);if(A({stage:"send",error:me,value:B,attempt:xe}),!(xe<h&&b(me,xe))){k.down([[R,{value:B,error:me,attempts:xe}]]);return}return z(De,xe,me)},ue=()=>{I(-1),w.down([[R,B]])};function De(){xe+=1,I(1);let fe;try{fe=p(ae,g)}catch(me){return Se(me)??Promise.resolve()}return D(fe)?fe.then(ue,me=>Se(me)):(ue(),Promise.resolve())}return De()},te=o?.maxBuffer??Number.POSITIVE_INFINITY,ke=new ba(te),J,K=!1,j=()=>{E?.down([[R,ke.length]])},ne=B=>{L&&L.down([[R,B]])},Re=o?.strategy??"drop-oldest",Me=(B,ae)=>{let xe={value:B,payload:ae};if(ke.length<te)return ke.push(xe),j(),!0;if(Re==="drop-oldest"){let ue=ke.shift();return ke.push(xe),j(),ne(!0),k.down([[R,{value:ue.value,error:new Error("backpressure: buffer overflow \u2014 dropped oldest"),attempts:0}]]),!0}if(Re==="drop-newest")return ne(!0),k.down([[R,{value:B,error:new Error("backpressure: buffer overflow \u2014 dropped newest"),attempts:0}]]),!1;let Se=new Error("backpressure: buffer overflow");return A({stage:"send",error:Se,value:B}),k.down([[R,{value:B,error:Se,attempts:0}]]),ne(!0),!1},Oe=B=>{let ae=0,xe=B.map(fe=>fe.payload),Se=fe=>{I(-1);let me=qr(fe);if(A({stage:"send",error:me,value:B.map(Nn=>Nn.value),attempt:ae}),!(ae<h&&b(me,ae))){for(let{value:Nn}of B)k.down([[R,{value:Nn,error:me,attempts:ae}]]);return}return z(De,ae,me)},ue=()=>{I(-1);for(let{value:fe}of B)w.down([[R,fe]])};function De(){ae+=1,I(1);let fe;try{fe=f(xe,g)}catch(me){return Se(me)??Promise.resolve()}return D(fe)?fe.then(ue,me=>Se(me)):(ue(),Promise.resolve())}return De()},he=async B=>{for(let ae of B)await Ge(ae.value,ae.payload)},Ge=(B,ae)=>{let xe=0,Se=fe=>{I(-1);let me=qr(fe);if(A({stage:"send",error:me,value:B,attempt:xe}),!(xe<h&&b(me,xe))){k.down([[R,{value:B,error:me,attempts:xe}]]);return}return z(De,xe,me)},ue=()=>{I(-1),w.down([[R,B]])};function De(){xe+=1,I(1);let fe;try{fe=p(ae,g)}catch(me){return Se(me)??Promise.resolve()}return D(fe)?fe.then(ue,me=>Se(me)):(ue(),Promise.resolve())}return De()},oe=()=>{if(K||ke.length===0)return Promise.resolve();let B=ke.drain();if(j(),ne(!1),f!==void 0){let xe=Oe(B);return U(xe),xe}let ae=he(B);return U(ae),ae},ve=()=>{J!==void 0||K||a<=0||(J=setTimeout(()=>{J=void 0,oe()},a))},Fe=t.subscribe(B=>{for(let ae of B){let xe=ae[0];if(xe!==R)try{c?.(ae)}catch{}if(xe===R){let Se=ae[1];if(v){let ue;if(u)try{ue=u(Se)}catch(fe){let me=qr(fe);A({stage:"serialize",error:me,value:Se}),k.down([[R,{value:Se,error:me,attempts:0}]]);continue}else ue=Se;if(!Me(Se,ue))continue;ke.length>=i?oe():ve()}else{let ue=Z(Se);U(ue)}}else $e.messageTier(xe)>=3&&v&&(J!==void 0&&(clearTimeout(J),J=void 0),oe())}}),ge;if(d){let B=!1;ge=d.subscribe(ae=>{if(!B){B=!0;return}ae.length>0&&!H&&ee()})}let H=!1,ee=()=>{if(H)return;H=!0,J!==void 0&&(clearTimeout(J),J=void 0),v&&oe(),K=!0,ge?.(),Fe();let B=ae=>{try{ae.down([[de]])}catch{}};B(S),B(k),B(w),B(x),E&&B(E),L&&B(L);try{l?.()}catch{}},ye={dispose:ee,sent:w,failed:k,inFlight:x,errors:S};return v&&(ye.buffered=E,ye.flush=async()=>{K||(await oe(),await Promise.all(P))}),L&&(ye.paused=L),ye}Et();Te();function mt(t){return{describeKind:"producer",...t}}function Ta(t,e){let{parse:n,closeOnTeardown:r=!1,...s}=e??{};return $(o=>{let i=!0,a,u=()=>{let y=a;a=void 0,y?.()},d=y=>{i&&(i=!1,o.down([y]),u())},c=(y,b=y)=>{if(i)try{let v=y!==null&&typeof y=="object"&&"data"in y?y.data:y,T=n?n(v,b):v;o.emit(T)}catch(v){d([M,v])}},l=y=>{d([M,y])},p=()=>{d([O])};if(typeof t=="function"){try{if(a=t(c,l,p),typeof a!="function")throw new Error("fromWebSocket register contract violation: register must return cleanup callable")}catch(y){d([M,y])}return()=>{i=!1,u()}}let f=t,m=y=>c(y,y),g=y=>l(y),h=()=>p();return f.addEventListener("message",m),f.addEventListener("error",g),f.addEventListener("close",h),a=()=>{f.removeEventListener("message",m),f.removeEventListener("error",g),f.removeEventListener("close",h),r&&f.close()},()=>{i=!1,u()}},mt(s))}function jc(t,e){return mn(t,e)}function wa(t,e){let{method:n="GET",headers:r,body:s,transform:o=v=>v.json(),timeoutNs:i=30*1e9,signal:a,completeAfterFetch:u=!1,refetchOnSubscribe:d=!1,...c}=e??{},l=N(0,{name:`${c.name??"http"}/fetchCount`}),p=N(0,{name:`${c.name??"http"}/lastUpdated`}),f=N(!1,{name:`${c.name??"http"}/fetched`}),m=0,g=s!==void 0?typeof s=="string"?s:JSON.stringify(s):void 0,h=v=>{let T=new AbortController,w=!0;if(a?.aborted)return w=!1,v.down([[M,a.reason??new Error("Aborted")]]),()=>{};a?.addEventListener("abort",()=>T.abort(a.reason),{once:!0});let k=setTimeout(()=>T.abort(new Error("Request timeout")),Math.ceil(i/1e6));return fetch(t,{method:n,headers:r,body:g,signal:T.signal}).then(async x=>{if(clearTimeout(k),!w)return;if(!x.ok)throw new Error(`HTTP ${x.status}: ${x.statusText}`);let S=await o(x);w&&(Y(()=>{m+=1,l.down([[R,m]]),p.down([[R,ce()]]),f.down([[R,!0]]),v.emit(S)}),u&&v.down([[O]]))}).catch(x=>{clearTimeout(k),w&&(x&&x.name==="AbortError"||v.down([[M,x]]))}),()=>{w=!1,T.abort()}},y=$(v=>h({emit:T=>v.emit(T),down:T=>v.down(T)}),{...mt(c),resubscribable:d});return{...Bt(y),fetchCount:l,lastUpdated:p,fetched:f}}function Bc(t,e,n){let{method:r="POST",headers:s={"Content-Type":"application/json"},serialize:o=m=>JSON.stringify(m),timeoutNs:i,batchFormat:a="json-array",batchSize:u,flushIntervalMs:d,retry:c,onTransportError:l}=n??{},p=async m=>{let g=i!==void 0?new AbortController:void 0,h;g&&i!==void 0&&(h=setTimeout(()=>g.abort(new Error("Request timeout")),Math.ceil(i/1e6)));try{let y=await fetch(e,{method:r,headers:s,body:m,signal:g?.signal}),b=async()=>{try{await y.arrayBuffer?.()}catch{}};if(!y.ok)throw await b(),new Error(`HTTP ${y.status}: ${y.statusText}`);await b()}finally{h!==void 0&&clearTimeout(h)}};return u!==void 0||d!==void 0?qe(t,{onTransportError:l,retry:c,batchSize:u,flushIntervalMs:d,sendBatch:async m=>{let g;a==="ndjson"?g=m.map(h=>{let y=o(h);return typeof y=="string"?y:new TextDecoder().decode(y)}).join(`
16
+ `):g=JSON.stringify(m),await p(g)}}):qe(t,{onTransportError:l,retry:c,serialize:o,send:async m=>{await p(m)}})}function Vc(t){return Symbol.keyFor(t)??t.description??"message"}function Zn(t,e){return typeof t=="string"?t:e(t)}function Kc(t,e){let n=`event: ${t}
17
+ `;if(e!==void 0){let r=e.split(/\r?\n/);for(let s of r)n+=`data: ${s}
18
18
  `}return`${n}
19
- `}function Bd(t,e){let{serialize:n=f=>{if(f instanceof Error)return f.message;try{return JSON.stringify(f)}catch{return String(f)}},dataEvent:r="data",errorEvent:o="error",completeEvent:s="complete",includeResolved:i=!1,includeDirty:a=!1,keepAliveMs:u,signal:c,eventNameResolver:d=$d}=e??{},l=new TextEncoder,p;return new ReadableStream({start(f){let m=!1,g,h=()=>{},y=()=>{m||(m=!0,g!==void 0&&clearInterval(g),c?.removeEventListener("abort",v),h(),f.close())};p=y;let b=(T,w)=>{m||f.enqueue(l.encode(jd(T,w)))},v=()=>{m||y()};h=t.subscribe(T=>{for(let w of T){let k=w[0];if(!($e.isLocalOnly(k)&&!(k===te&&a))){if(k===S){b(r,Zn(w[1],n));continue}if(k===O){b(o,Zn(w[1],n)),y();return}if(k===C){b(s),y();return}!i&&k===F||b(d(k),w.length>1?Zn(w[1],n):void 0)}}}),u!==void 0&&u>0&&(g=setInterval(()=>{m||f.enqueue(l.encode(`: keepalive
19
+ `}function Hc(t,e){let{serialize:n=f=>{if(f instanceof Error)return f.message;try{return JSON.stringify(f)}catch{return String(f)}},dataEvent:r="data",errorEvent:s="error",completeEvent:o="complete",includeResolved:i=!1,includeDirty:a=!1,keepAliveMs:u,signal:d,eventNameResolver:c=Vc}=e??{},l=new TextEncoder,p;return new ReadableStream({start(f){let m=!1,g,h=()=>{},y=()=>{m||(m=!0,g!==void 0&&clearInterval(g),d?.removeEventListener("abort",v),h(),f.close())};p=y;let b=(T,w)=>{m||f.enqueue(l.encode(Kc(T,w)))},v=()=>{m||y()};h=t.subscribe(T=>{for(let w of T){let k=w[0];if(!($e.isLocalOnly(k)&&!(k===X&&a))){if(k===R){b(r,Zn(w[1],n));continue}if(k===M){b(s,Zn(w[1],n)),y();return}if(k===O){b(o),y();return}!i&&k===G||b(c(k),w.length>1?Zn(w[1],n):void 0)}}}),u!==void 0&&u>0&&(g=setInterval(()=>{m||f.enqueue(l.encode(`: keepalive
20
20
 
21
- `))},u)),c?.aborted?v():c?.addEventListener("abort",v,{once:!0})},cancel(){p?.()}})}function Vd(t,e){let{serialize:n=p=>{if(p instanceof Error)return p.message;try{return JSON.stringify(p)}catch{return String(p)}},dataEvent:r="data",errorEvent:o="error",completeEvent:s="complete",includeResolved:i=!1,includeDirty:a=!1,keepAliveMs:u,signal:c,eventNameResolver:d=$d}=e??{},l=new TextEncoder;return H(p=>{let f=!0,m,g=(b,v)=>{f&&p.emit(l.encode(jd(b,v)))},h=()=>{f&&(f=!1,p.down([[C]]))},y=t.subscribe(b=>{if(f)for(let v of b){let T=v[0];if(!($e.isLocalOnly(T)&&!(T===te&&a))){if(T===S){g(r,Zn(v[1],n));continue}if(T===O){g(o,Zn(v[1],n)),f=!1,p.down([[C]]);return}if(T===C){g(s),f=!1,p.down([[C]]);return}!i&&T===F||g(d(T),v.length>1?Zn(v[1],n):void 0)}}});return u!==void 0&&u>0&&(m=setInterval(()=>{f&&p.emit(l.encode(`: keepalive
21
+ `))},u)),d?.aborted?v():d?.addEventListener("abort",v,{once:!0})},cancel(){p?.()}})}function qc(t,e){let{serialize:n=p=>{if(p instanceof Error)return p.message;try{return JSON.stringify(p)}catch{return String(p)}},dataEvent:r="data",errorEvent:s="error",completeEvent:o="complete",includeResolved:i=!1,includeDirty:a=!1,keepAliveMs:u,signal:d,eventNameResolver:c=Vc}=e??{},l=new TextEncoder;return $(p=>{let f=!0,m,g=(b,v)=>{f&&p.emit(l.encode(Kc(b,v)))},h=()=>{f&&(f=!1,p.down([[O]]))},y=t.subscribe(b=>{if(f)for(let v of b){let T=v[0];if(!($e.isLocalOnly(T)&&!(T===X&&a))){if(T===R){g(r,Zn(v[1],n));continue}if(T===M){g(s,Zn(v[1],n)),f=!1,p.down([[O]]);return}if(T===O){g(o),f=!1,p.down([[O]]);return}!i&&T===G||g(c(T),v.length>1?Zn(v[1],n):void 0)}}});return u!==void 0&&u>0&&(m=setInterval(()=>{f&&p.emit(l.encode(`: keepalive
22
22
 
23
- `))},u)),c?.aborted?h():c?.addEventListener("abort",h,{once:!0}),()=>{f=!1,m!==void 0&&clearInterval(m),c?.removeEventListener("abort",h),y()}})}function Kd(t){let e,n=!1;return new ReadableStream({start(r){e=t.subscribe(o=>{for(let s of o){let i=s[0];if(n)return;if(i===S)try{r.enqueue(s[1])}catch{n=!0,e?.()}else if(i===O){n=!0;try{r.error(s[1])}catch{}return}else if(i===C){n=!0;try{r.close()}catch{}return}}})},cancel(){n=!0,e?.()}})}async function*Lt(t,e){let n=e?.parse??(w=>w),r=e?.signal,o=new TextDecoder,s="",i="message",a=[],u,c,d=[],l=()=>{if(a.length===0&&i==="message"&&u===void 0){a=[];return}let w=a.join(`
24
- `);d.push({event:i,data:n(w),id:u,retry:c}),i="message",a=[],u=void 0,c=void 0},p=w=>{if(w===""){l();return}if(w.startsWith(":"))return;let k=w.indexOf(":"),x=k<0?w:w.slice(0,k),R=k<0?"":w.slice(k+1);switch(R.startsWith(" ")&&(R=R.slice(1)),x){case"event":i=R;break;case"data":a.push(R);break;case"id":R.includes("\0")||(u=R);break;case"retry":{let N=Number(R);Number.isFinite(N)&&(c=N);break}}},f=(w,k)=>{s+=o.decode(w,{stream:!k});let x=s.split(/\r?\n/);s=x.pop()??"";for(let R of x)p(R)},m=t,g=t instanceof ReadableStream?t:m&&typeof m=="object"&&m.body instanceof ReadableStream?m.body:null,h,y,b=!1,v=()=>{b||(b=!0,h&&h.cancel().catch(()=>{}),y&&typeof y.return=="function"&&Promise.resolve(y.return()).catch(()=>{}))},T=()=>{v()};if(r){if(r.aborted)return;r.addEventListener("abort",T,{once:!0})}try{if(g){for(h=g.getReader();!r?.aborted;){let{value:w,done:k}=await h.read();if(k)break;for(f(w,!1);d.length>0;)yield d.shift()}f(new Uint8Array,!0)}else{for(y=t[Symbol.asyncIterator]();!r?.aborted;){let k=await y.next();if(k.done)break;for(f(k.value,!1);d.length>0;)yield d.shift()}f(new Uint8Array,!0)}if(s.trim()){for(let w of s.split(/\r?\n/))p(w);l()}for(;d.length>0;)yield d.shift()}finally{r&&r.removeEventListener("abort",T),v()}}function Hd(t,e){let{parse:n,...r}=e??{};return H(o=>{let s=!0,i=new AbortController;return(async()=>{try{for await(let u of Lt(t,{parse:n,signal:i.signal})){if(!s)return;o.emit(u)}s&&o.down([[C]])}catch(u){s&&o.down([[O,u]])}})(),()=>{s=!1,i.abort()}},mt(r))}function Wd(t,e){let{method:n="GET",headers:r,body:o,signal:s,...i}=e??{};return H(a=>{let u=!0,c=new AbortController;if(s?.aborted)return a.down([[O,s.reason??new Error("Aborted")]]),()=>{};s?.addEventListener("abort",()=>c.abort(s.reason),{once:!0});let d=o!==void 0?typeof o=="string"?o:JSON.stringify(o):void 0;return(async()=>{try{let p=await fetch(t,{method:n,headers:r,body:d,signal:c.signal});if(!u)return;if(!p.ok)throw new Error(`HTTP ${p.status}: ${p.statusText}`);if(!p.body)throw new Error("HTTP response has no body");let f=p.body.getReader();for(;u;){let{value:m,done:g}=await f.read();if(g)break;m&&a.emit(m)}u&&a.down([[C]])}catch(p){if(!u||p&&p.name==="AbortError")return;a.down([[O,p]])}})(),()=>{u=!1,c.abort()}},mt(i))}function qd(t,e){let{intervalMs:n=5e3,...r}=e??{};return Se(ct(n,{period:n}),()=>Na(t,{...r,completeAfterFetch:!0}).node)}function Ud(t,e,n){let{serialize:r=y=>{if(typeof y=="string"||y instanceof Blob||y instanceof ArrayBuffer||ArrayBuffer.isView(y))return y;try{return JSON.stringify(y)}catch{return String(y)}},closeOnComplete:o=!0,closeOnError:s=!0,closeCode:i,closeReason:a,onTransportError:u,retry:c,backpressure:d,stopOn:l}=n??{},p=!1,f=y=>{if(!p){p=!0;try{e.close(i,a)}catch(b){let v=b instanceof Error?b:new Error(String(b));try{u?.({stage:"close",error:v,value:void 0,message:y})}catch{}}}},m=null,h=We(t,{onTransportError:u,serialize:y=>{let b=r(y);if(b===void 0)throw new Error("serialize returned undefined");return b},retry:c,backpressure:d,stopOn:l,onDispose:()=>{if(m){try{e.removeEventListener("close",m)}catch{}m=null}},send:y=>{e.send(y)},onUpstreamMessage:y=>{(y[0]===C&&o||y[0]===O&&s)&&f(y)}});return m=()=>{p=!0,h.dispose()},e.addEventListener("close",m),h}function zd(t,e){let{parse:n,maxRetries:r,backoff:o="exponential",closeOnTeardown:s=!0,...i}=e??{};return jt(()=>Sa(t(),{parse:n,closeOnTeardown:s,...i}),{count:r,backoff:o})}function Jd(t,e){let{method:n="notifications/message",onDisconnect:r,...o}=e??{};return hn(({emit:s,error:i})=>(t.setNotificationHandler(n,a=>s(a)),r?.(a=>i(a??new Error("MCP client disconnected"))),()=>t.setNotificationHandler(n,()=>{})),o)}function Yd(t,e){return xs(({traces:r,metrics:o,logs:s,error:i})=>t({onTraces:a=>{Z(()=>{for(let u of a)r(u)})},onMetrics:a=>{Z(()=>{for(let u of a)o(u)})},onLogs:a=>{Z(()=>{for(let u of a)s(u)})},onError:i})??void 0,["traces","metrics","logs"],e?.name?{name:e.name}:void 0)}function Qd(t,e){return hn(t,e)}function Xd(t){let e=t.match(/^<(\d{1,3})>\d?\s*(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s*(.*)/s);if(!e){let r=Te();return{facility:1,severity:6,timestamp:new Date(Math.floor(r/1e6)).toISOString(),hostname:"-",appName:"-",procId:"-",msgId:"-",message:t.trim(),timestampNs:r}}let n=Number(e[1]);return{facility:n>>3,severity:n&7,timestamp:e[2],hostname:e[3],appName:e[4],procId:e[5],msgId:e[6],message:(e[7]??"").trim(),timestampNs:Te()}}function Zd(t,e){return hn(t,e)}var Qm={c:"counter",g:"gauge",ms:"timer",h:"histogram",s:"set",d:"distribution"};function el(t){let e=t.split("|"),[n,r]=(e[0]??"").split(":");if(!n||r===void 0)throw new Error(`Invalid StatsD line: ${t}`);let o=e[1]?.trim()??"c",s=Qm[o]??"counter",i=s==="set"?0:Number(r),a,u={};for(let c=2;c<e.length;c++){let d=e[c].trim();if(d.startsWith("@"))a=Number(d.slice(1));else if(d.startsWith("#"))for(let l of d.slice(1).split(",")){let[p,f]=l.split(":");p&&(u[p]=f??"")}}return{name:n.trim(),value:i,type:s,sampleRate:a,tags:u,timestampNs:Te()}}function tl(t,e){let{intervalNs:n=15*1e9,headers:r,timeoutNs:o=10*1e9,signal:s,maxConsecutiveErrors:i=1}=e??{},a=Math.ceil(n/1e6),u=0;return Se(ct(0,{period:a,signal:s}),()=>H(c=>{let d=!0,l=new AbortController,p=setTimeout(()=>l.abort(new Error("Scrape timeout")),Math.ceil(o/1e6));return(async()=>{try{let m=await fetch(t,{headers:{Accept:"text/plain",...r},signal:l.signal});if(clearTimeout(p),!d)return;if(!m.ok)throw new Error(`Prometheus scrape ${m.status}: ${m.statusText}`);let g=await m.text();if(!d)return;let h=Ea(g);for(let y of h)c.emit(y);u=0,c.down([[C]])}catch(m){if(clearTimeout(p),!d||m instanceof Error&&m.name==="AbortError")return;u+=1,u>=i&&c.down([[O,m]])}})(),()=>{d=!1,clearTimeout(p),l.abort()}}))}function Ea(t){let e=[],n=new Map,r=new Map;for(let o of t.split(`
25
- `)){let s=o.trim();if(!s)continue;if(s.startsWith("# TYPE ")){let p=s.slice(7),f=p.indexOf(" ");f>0&&n.set(p.slice(0,f),p.slice(f+1).trim());continue}if(s.startsWith("# HELP ")){let p=s.slice(7),f=p.indexOf(" ");f>0&&r.set(p.slice(0,f),p.slice(f+1).trim());continue}if(s.startsWith("#"))continue;let i,a={},u,c,d=s.indexOf("{");if(d>=0){i=s.slice(0,d);let p=s.indexOf("}",d);if(p<0)continue;let f=s.slice(d+1,p);a=Xm(f);let m=s.slice(p+1).trim().split(/\s+/);u=m[0]??"",c=m[1]}else{let p=s.split(/\s+/);i=p[0]??"",u=p[1]??"",c=p[2]}if(!i||!u)continue;let l=i.replace(/(_total|_count|_sum|_bucket|_created|_info)$/,"");e.push({name:i,labels:a,value:Number(u),timestampMs:c?Number(c):void 0,type:n.get(l)??n.get(i),help:r.get(l)??r.get(i),timestampNs:Te()})}return e}function Xm(t){let e={},n=/(\w+)="((?:[^"\\]|\\.)*)"/g,r=n.exec(t);for(;r!==null;)e[r[1]]=r[2].replace(/\\(.)/g,"$1"),r=n.exec(t);return e}function nl(t,e,n){let{fromBeginning:r=!1,deserialize:o=i=>{if(i===null)return null;try{return JSON.parse(i.toString())}catch{return i.toString()}},...s}=n??{};return H(i=>{let a=!0;return(async()=>{try{await t.subscribe({topic:e,fromBeginning:r}),await t.run({eachMessage:async({topic:c,partition:d,message:l})=>{if(!a)return;let p={};if(l.headers)for(let[f,m]of Object.entries(l.headers))m!==void 0&&(p[f]=typeof m=="string"?m:m.toString());i.emit({topic:c,partition:d,key:l.key?.toString()??null,value:o(l.value),headers:p,offset:l.offset,timestamp:l.timestamp,timestampNs:Te()})}})}catch(c){a&&i.down([[O,c]])}})(),()=>{a=!1}},mt(s))}function rl(t,e,n,r){let{serialize:o=a=>JSON.stringify(a),keyExtractor:s,onTransportError:i}=r??{};return We(t,{onTransportError:i,send:async a=>{let u=s?.(a)??null,c=o(a);await e.send({topic:n,messages:[{key:u,value:Buffer.from(c)}]})}})}function ol(t,e,n){let{blockMs:r=5e3,startId:o="$",parse:s=a=>{for(let c=0;c<a.length;c+=2)if(a[c]==="data")try{return JSON.parse(a[c+1])}catch{return a[c+1]}let u={};for(let c=0;c<a.length;c+=2)u[a[c]]=a[c+1];return u},...i}=n??{};return H(a=>{let u=!0,c=o;return(async()=>{for(;u;)try{let l=await t.xread("BLOCK",r,"STREAMS",e,c);if(!u)return;if(l)for(let[p,f]of l)for(let[m,g]of f)c=m,a.emit({id:m,key:e,data:s(g),timestampNs:Te()})}catch(l){if(!u)return;a.down([[O,l]]);return}})(),()=>{u=!1}},mt(i))}function sl(t,e,n,r){let{serialize:o=a=>["data",JSON.stringify(a)],maxLen:s,onTransportError:i}=r??{};return We(t,{onTransportError:i,send:async a=>{let u=o(a);await(s!==void 0?e.xadd(n,"MAXLEN","~",String(s),"*",...u):e.xadd(n,"*",...u))}})}function il(t,e){let{delimiter:n=",",hasHeader:r=!0,columns:o,parseLine:s,...i}=e??{},a=s??(u=>cl(u,n));return H(u=>{let c=!1;return(async()=>{try{let l=o,p="";for await(let f of t){if(c)return;p+=f;let m=p.split(/\r?\n/);p=m.pop()??"";for(let g of m){if(c)return;if(!g.trim())continue;let h=a(g);if(!l&&r){l=h;continue}l||(l=h.map((b,v)=>`col${v}`));let y={};for(let b=0;b<l.length;b++)y[l[b]]=h[b]??"";u.emit(y)}}if(!c&&p.trim()){let f=a(p);if(l){let m={};for(let g=0;g<l.length;g++)m[l[g]]=f[g]??"";u.emit(m)}}c||u.down([[C]])}catch(l){c||u.down([[O,l]])}})(),()=>{c=!0}},mt(i))}function al(t,e){let{delimiter:n=",",hasHeader:r=!0,columns:o,parseLine:s,...i}=e??{},a=s??(u=>cl(u,n));return U([t],(u,c,d)=>{let l=u[0];if(l==null||l.length===0)return;let p=d.store;typeof p.buffer!="string"&&(p.buffer=""),p.headers===void 0&&o&&(p.headers=o.slice());for(let f of l){p.buffer=p.buffer+f;let m=p.buffer.split(/\r?\n/);p.buffer=m.pop()??"";for(let g of m){if(!g.trim())continue;let h=a(g);if(!p.headers&&r){p.headers=h;continue}p.headers||(p.headers=h.map((b,v)=>`col${v}`));let y={};for(let b=0;b<p.headers.length;b++)y[p.headers[b]]=h[b]??"";c.emit(y)}}},{describeKind:"derived",...i})}function ul(t,e){return U([t],(n,r,o)=>{let s=n[0];if(s==null||s.length===0)return;let i=o.store;typeof i.buffer!="string"&&(i.buffer="");for(let a of s){i.buffer=i.buffer+a;let u=i.buffer.split(/\r?\n/);i.buffer=u.pop()??"";for(let c of u)if(c.trim())try{r.emit(JSON.parse(c))}catch(d){r.down([[O,d]]);return}}},{describeKind:"derived",...e??{}})}function cl(t,e){let n=[],r="",o=!1;for(let s=0;s<t.length;s++){let i=t[s];o?i==='"'?t[s+1]==='"'?(r+='"',s++):o=!1:r+=i:i==='"'?o=!0:i===e?(n.push(r),r=""):r+=i}return n.push(r),n}function dl(t,e){return H(n=>{let r=!1;return(async()=>{try{let s="";for await(let i of t){if(r)return;s+=i;let a=s.split(/\r?\n/);s=a.pop()??"";for(let u of a){if(r)return;let c=u.trim();c&&n.emit(JSON.parse(c))}}!r&&s.trim()&&n.emit(JSON.parse(s.trim())),r||n.down([[C]])}catch(s){r||n.down([[O,s]])}})(),()=>{r=!0}},mt(e))}function ll(t,e,n){let{intervalNs:r=5*1e9,format:o="JSONEachRow",signal:s,maxConsecutiveErrors:i=1}=n??{},a=Math.ceil(r/1e6),u=0;return Se(ct(0,{period:a,signal:s}),()=>H(c=>{let d=!0;return(async()=>{try{let p=await t.query({query:e,format:o});if(!d)return;let f=await p.json();if(!d)return;for(let m of f)c.emit(m);u=0,c.down([[C]])}catch(p){if(!d)return;u+=1,u>=i&&c.down([[O,p]])}})(),()=>{d=!1}}))}function pl(t,e){let{autoAck:n=!0,deserialize:r=a=>{try{return JSON.parse(a.toString())}catch{return a.toString()}},onAckError:o,...s}=e??{},i=a=>{if(o)try{o(a instanceof Error?a:new Error(String(a)))}catch{}};return H(a=>{let u=!0;return(async()=>{for(;u;)try{let d=await t.receive();if(!u)return;let l={topic:d.getTopicName(),messageId:d.getMessageId().toString(),key:d.getPartitionKey(),value:r(d.getData()),properties:d.getProperties(),publishTime:d.getPublishTimestamp(),eventTime:d.getEventTimestamp(),timestampNs:Te()};if(n)a.emit(l),t.acknowledge(d).catch(i);else{let p=!1,f={value:l,ack(){p||(p=!0,t.acknowledge(d).catch(i))},nack(m){if(p)return;p=!0;let g=t;try{let h=g.negativeAcknowledge?.(d);h&&typeof h.then=="function"&&h.catch(i)}catch(h){i(h)}}};a.emit(f)}}catch(d){u&&a.down([[O,d]]);return}})(),()=>{u=!1}},mt(s))}function fl(t,e,n){let{serialize:r=a=>Buffer.from(JSON.stringify(a)),keyExtractor:o,propertiesExtractor:s,onTransportError:i}=n??{};return We(t,{onTransportError:i,send:async a=>{await e.send({data:r(a),partitionKey:o?.(a),properties:s?.(a)})}})}function ml(t,e,n){let r=new TextDecoder,{queue:o,deserialize:s=a=>{let u=r.decode(a);try{return JSON.parse(u)}catch{return u}},...i}=n??{};return H(a=>{let u=!0,c=t.subscribe(e,o?{queue:o}:void 0);return(async()=>{try{for await(let l of c){if(!u)return;let p={};if(l.headers)for(let f of l.headers.keys())p[f]=l.headers.get(f);a.emit({subject:l.subject,data:s(l.data),headers:p,reply:l.reply,sid:l.sid,timestampNs:Te()})}u&&a.down([[C]])}catch(l){u&&a.down([[O,l]])}})(),()=>{u=!1}},mt(i))}function hl(t,e,n,r){let o=new TextEncoder,{serialize:s=a=>o.encode(JSON.stringify(a)),onTransportError:i}=r??{};return We(t,{onTransportError:i,send:a=>{e.publish(n,s(a))}})}function gl(t,e,n){let{autoAck:r=!0,deserialize:o=u=>{try{return JSON.parse(u.toString())}catch{return u.toString()}},onAckError:s,...i}=n??{},a=u=>{if(s)try{s(u instanceof Error?u:new Error(String(u)))}catch{}};return H(u=>{let c=!0,d;return(async()=>{try{d=(await t.consume(e,f=>{if(!c)return;if(f===null){c&&u.down([[O,new Error("Consumer cancelled by broker")]]);return}let m={queue:e,routingKey:f.fields.routingKey,exchange:f.fields.exchange,content:o(f.content),properties:f.properties,deliveryTag:f.fields.deliveryTag,redelivered:f.fields.redelivered,timestampNs:Te()};if(r){u.emit(m);try{t.ack(f)}catch(g){a(g)}}else{let g=!1,h=t,y={value:m,ack(){if(!g){g=!0;try{t.ack(f)}catch(b){a(b)}}},nack(b){if(g)return;g=!0;let v=b?.requeue;if(!h.nack){a(new Error("RabbitMQ channel does not expose `nack`; cannot negative-ack"));return}try{h.nack(f,!1,v)}catch(T){a(T)}}};u.emit(y)}},{noAck:!1})).consumerTag}catch(p){c&&u.down([[O,p]])}})(),()=>{c=!1,d!==void 0&&t.cancel(d)}},mt(i))}function yl(t,e,n,r){let{serialize:o=a=>Buffer.from(JSON.stringify(a)),routingKeyExtractor:s=()=>"",onTransportError:i}=r??{};return We(t,{onTransportError:i,send:a=>{let u=s(a),c=o(a);e.publish(n,u,c)}})}function _a(t,e,n){let{serialize:r=l=>`${JSON.stringify(l)}
26
- `,flushIntervalMs:o=0,batchSize:s=Number.POSITIVE_INFINITY,onTransportError:i,mode:a}=n??{},c=o>0||s<Number.POSITIVE_INFINITY?We(t,{onTransportError:i,batchSize:s,flushIntervalMs:o,serialize:r,sendBatch:l=>{e.write(l.join(""))}}):We(t,{onTransportError:i,serialize:r,send:l=>{e.write(l)}}),d=c.dispose;return c.dispose=()=>{d();try{e.end()}catch{}},c}function Ra(t,e){return t.includes(e)||t.includes('"')||t.includes(`
27
- `)?`"${t.replace(/"/g,'""')}"`:t}function bl(t,e,n){let{columns:r,delimiter:o=",",writeHeader:s=!0,cellExtractor:i=(f,m)=>String(f[m]??""),flushIntervalMs:a=0,batchSize:u=Number.POSITIVE_INFINITY,onTransportError:c,...d}=n,l=!1;return _a(t,e,{serialize:f=>{if(!l&&s){l=!0;let m=r.map(h=>Ra(h,o)).join(o),g=r.map(h=>Ra(i(f,h),o)).join(o);return`${m}
23
+ `))},u)),d?.aborted?h():d?.addEventListener("abort",h,{once:!0}),()=>{f=!1,m!==void 0&&clearInterval(m),d?.removeEventListener("abort",h),y()}})}function Wc(t){let e,n=!1;return new ReadableStream({start(r){e=t.subscribe(s=>{for(let o of s){let i=o[0];if(n)return;if(i===R)try{r.enqueue(o[1])}catch{n=!0,e?.()}else if(i===M){n=!0;try{r.error(o[1])}catch{}return}else if(i===O){n=!0;try{r.close()}catch{}return}}})},cancel(){n=!0,e?.()}})}async function*Lt(t,e){let n=e?.parse??(w=>w),r=e?.signal,s=new TextDecoder,o="",i="message",a=[],u,d,c=[],l=()=>{if(a.length===0&&i==="message"&&u===void 0){a=[];return}let w=a.join(`
24
+ `);c.push({event:i,data:n(w),id:u,retry:d}),i="message",a=[],u=void 0,d=void 0},p=w=>{if(w===""){l();return}if(w.startsWith(":"))return;let k=w.indexOf(":"),x=k<0?w:w.slice(0,k),S=k<0?"":w.slice(k+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")||(u=S);break;case"retry":{let E=Number(S);Number.isFinite(E)&&(d=E);break}}},f=(w,k)=>{o+=s.decode(w,{stream:!k});let x=o.split(/\r?\n/);o=x.pop()??"";for(let S of x)p(S)},m=t,g=t instanceof ReadableStream?t:m&&typeof m=="object"&&m.body instanceof ReadableStream?m.body:null,h,y,b=!1,v=()=>{b||(b=!0,h&&h.cancel().catch(()=>{}),y&&typeof y.return=="function"&&Promise.resolve(y.return()).catch(()=>{}))},T=()=>{v()};if(r){if(r.aborted)return;r.addEventListener("abort",T,{once:!0})}try{if(g){for(h=g.getReader();!r?.aborted;){let{value:w,done:k}=await h.read();if(k)break;for(f(w,!1);c.length>0;)yield c.shift()}f(new Uint8Array,!0)}else{for(y=t[Symbol.asyncIterator]();!r?.aborted;){let k=await y.next();if(k.done)break;for(f(k.value,!1);c.length>0;)yield c.shift()}f(new Uint8Array,!0)}if(o.trim()){for(let w of o.split(/\r?\n/))p(w);l()}for(;c.length>0;)yield c.shift()}finally{r&&r.removeEventListener("abort",T),v()}}function Uc(t,e){let{parse:n,...r}=e??{};return $(s=>{let o=!0,i=new AbortController;return(async()=>{try{for await(let u of Lt(t,{parse:n,signal:i.signal})){if(!o)return;s.emit(u)}o&&s.down([[O]])}catch(u){o&&s.down([[M,u]])}})(),()=>{o=!1,i.abort()}},mt(r))}function zc(t,e){let{method:n="GET",headers:r,body:s,signal:o,...i}=e??{};return $(a=>{let u=!0,d=new AbortController;if(o?.aborted)return a.down([[M,o.reason??new Error("Aborted")]]),()=>{};o?.addEventListener("abort",()=>d.abort(o.reason),{once:!0});let c=s!==void 0?typeof s=="string"?s:JSON.stringify(s):void 0;return(async()=>{try{let p=await fetch(t,{method:n,headers:r,body:c,signal:d.signal});if(!u)return;if(!p.ok)throw new Error(`HTTP ${p.status}: ${p.statusText}`);if(!p.body)throw new Error("HTTP response has no body");let f=p.body.getReader();for(;u;){let{value:m,done:g}=await f.read();if(g)break;m&&a.emit(m)}u&&a.down([[O]])}catch(p){if(!u||p&&p.name==="AbortError")return;a.down([[M,p]])}})(),()=>{u=!1,d.abort()}},mt(i))}function Jc(t,e){let{intervalMs:n=5e3,...r}=e??{};return be(dt(n,{period:n}),()=>wa(t,{...r,completeAfterFetch:!0}).node)}function Yc(t,e,n){let{serialize:r=y=>{if(typeof y=="string"||y instanceof Blob||y instanceof ArrayBuffer||ArrayBuffer.isView(y))return y;try{return JSON.stringify(y)}catch{return String(y)}},closeOnComplete:s=!0,closeOnError:o=!0,closeCode:i,closeReason:a,onTransportError:u,retry:d,backpressure:c,stopOn:l}=n??{},p=!1,f=y=>{if(!p){p=!0;try{e.close(i,a)}catch(b){let v=b instanceof Error?b:new Error(String(b));try{u?.({stage:"close",error:v,value:void 0,message:y})}catch{}}}},m=null,h=qe(t,{onTransportError:u,serialize:y=>{let b=r(y);if(b===void 0)throw new Error("serialize returned undefined");return b},retry:d,backpressure:c,stopOn:l,onDispose:()=>{if(m){try{e.removeEventListener("close",m)}catch{}m=null}},send:y=>{e.send(y)},onUpstreamMessage:y=>{(y[0]===O&&s||y[0]===M&&o)&&f(y)}});return m=()=>{p=!0,h.dispose()},e.addEventListener("close",m),h}function Qc(t,e){let{parse:n,maxRetries:r,backoff:s="exponential",closeOnTeardown:o=!0,...i}=e??{};return $t(()=>Ta(t(),{parse:n,closeOnTeardown:o,...i}),{count:r,backoff:s})}function Xc(t,e){let{method:n="notifications/message",onDisconnect:r,...s}=e??{};return mn(({emit:o,error:i})=>(t.setNotificationHandler(n,a=>o(a)),r?.(a=>i(a??new Error("MCP client disconnected"))),()=>t.setNotificationHandler(n,()=>{})),s)}function Zc(t,e){return bs(({traces:r,metrics:s,logs:o,error:i})=>t({onTraces:a=>{Y(()=>{for(let u of a)r(u)})},onMetrics:a=>{Y(()=>{for(let u of a)s(u)})},onLogs:a=>{Y(()=>{for(let u of a)o(u)})},onError:i})??void 0,["traces","metrics","logs"],e?.name?{name:e.name}:void 0)}function el(t,e){return mn(t,e)}function tl(t){let e=t.match(/^<(\d{1,3})>\d?\s*(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s*(.*)/s);if(!e){let r=ce();return{facility:1,severity:6,timestamp:new Date(Math.floor(r/1e6)).toISOString(),hostname:"-",appName:"-",procId:"-",msgId:"-",message:t.trim(),timestampNs:r}}let n=Number(e[1]);return{facility:n>>3,severity:n&7,timestamp:e[2],hostname:e[3],appName:e[4],procId:e[5],msgId:e[6],message:(e[7]??"").trim(),timestampNs:ce()}}function nl(t,e){return mn(t,e)}var nh={c:"counter",g:"gauge",ms:"timer",h:"histogram",s:"set",d:"distribution"};function rl(t){let e=t.split("|"),[n,r]=(e[0]??"").split(":");if(!n||r===void 0)throw new Error(`Invalid StatsD line: ${t}`);let s=e[1]?.trim()??"c",o=nh[s]??"counter",i=o==="set"?0:Number(r),a,u={};for(let d=2;d<e.length;d++){let c=e[d].trim();if(c.startsWith("@"))a=Number(c.slice(1));else if(c.startsWith("#"))for(let l of c.slice(1).split(",")){let[p,f]=l.split(":");p&&(u[p]=f??"")}}return{name:n.trim(),value:i,type:o,sampleRate:a,tags:u,timestampNs:ce()}}function ol(t,e){let{intervalNs:n=15*1e9,headers:r,timeoutNs:s=10*1e9,signal:o,maxConsecutiveErrors:i=1}=e??{},a=Math.ceil(n/1e6),u=0;return be(dt(0,{period:a,signal:o}),()=>$(d=>{let c=!0,l=new AbortController,p=setTimeout(()=>l.abort(new Error("Scrape timeout")),Math.ceil(s/1e6));return(async()=>{try{let m=await fetch(t,{headers:{Accept:"text/plain",...r},signal:l.signal});if(clearTimeout(p),!c)return;if(!m.ok)throw new Error(`Prometheus scrape ${m.status}: ${m.statusText}`);let g=await m.text();if(!c)return;let h=ka(g);for(let y of h)d.emit(y);u=0,d.down([[O]])}catch(m){if(clearTimeout(p),!c||m instanceof Error&&m.name==="AbortError")return;u+=1,u>=i&&d.down([[M,m]])}})(),()=>{c=!1,clearTimeout(p),l.abort()}}))}function ka(t){let e=[],n=new Map,r=new Map;for(let s of t.split(`
25
+ `)){let o=s.trim();if(!o)continue;if(o.startsWith("# TYPE ")){let p=o.slice(7),f=p.indexOf(" ");f>0&&n.set(p.slice(0,f),p.slice(f+1).trim());continue}if(o.startsWith("# HELP ")){let p=o.slice(7),f=p.indexOf(" ");f>0&&r.set(p.slice(0,f),p.slice(f+1).trim());continue}if(o.startsWith("#"))continue;let i,a={},u,d,c=o.indexOf("{");if(c>=0){i=o.slice(0,c);let p=o.indexOf("}",c);if(p<0)continue;let f=o.slice(c+1,p);a=rh(f);let m=o.slice(p+1).trim().split(/\s+/);u=m[0]??"",d=m[1]}else{let p=o.split(/\s+/);i=p[0]??"",u=p[1]??"",d=p[2]}if(!i||!u)continue;let l=i.replace(/(_total|_count|_sum|_bucket|_created|_info)$/,"");e.push({name:i,labels:a,value:Number(u),timestampMs:d?Number(d):void 0,type:n.get(l)??n.get(i),help:r.get(l)??r.get(i),timestampNs:ce()})}return e}function rh(t){let e={},n=/(\w+)="((?:[^"\\]|\\.)*)"/g,r=n.exec(t);for(;r!==null;)e[r[1]]=r[2].replace(/\\(.)/g,"$1"),r=n.exec(t);return e}function sl(t,e,n){let{fromBeginning:r=!1,deserialize:s=i=>{if(i===null)return null;try{return JSON.parse(i.toString())}catch{return i.toString()}},...o}=n??{};return $(i=>{let a=!0;return(async()=>{try{await t.subscribe({topic:e,fromBeginning:r}),await t.run({eachMessage:async({topic:d,partition:c,message:l})=>{if(!a)return;let p={};if(l.headers)for(let[f,m]of Object.entries(l.headers))m!==void 0&&(p[f]=typeof m=="string"?m:m.toString());i.emit({topic:d,partition:c,key:l.key?.toString()??null,value:s(l.value),headers:p,offset:l.offset,timestamp:l.timestamp,timestampNs:ce()})}})}catch(d){a&&i.down([[M,d]])}})(),()=>{a=!1}},mt(o))}function il(t,e,n,r){let{serialize:s=a=>JSON.stringify(a),keyExtractor:o,onTransportError:i}=r??{};return qe(t,{onTransportError:i,send:async a=>{let u=o?.(a)??null,d=s(a);await e.send({topic:n,messages:[{key:u,value:Buffer.from(d)}]})}})}function al(t,e,n){let{blockMs:r=5e3,startId:s="$",parse:o=a=>{for(let d=0;d<a.length;d+=2)if(a[d]==="data")try{return JSON.parse(a[d+1])}catch{return a[d+1]}let u={};for(let d=0;d<a.length;d+=2)u[a[d]]=a[d+1];return u},...i}=n??{};return $(a=>{let u=!0,d=s;return(async()=>{for(;u;)try{let l=await t.xread("BLOCK",r,"STREAMS",e,d);if(!u)return;if(l)for(let[p,f]of l)for(let[m,g]of f)d=m,a.emit({id:m,key:e,data:o(g),timestampNs:ce()})}catch(l){if(!u)return;a.down([[M,l]]);return}})(),()=>{u=!1}},mt(i))}function ul(t,e,n,r){let{serialize:s=a=>["data",JSON.stringify(a)],maxLen:o,onTransportError:i}=r??{};return qe(t,{onTransportError:i,send:async a=>{let u=s(a);await(o!==void 0?e.xadd(n,"MAXLEN","~",String(o),"*",...u):e.xadd(n,"*",...u))}})}function dl(t,e){let{delimiter:n=",",hasHeader:r=!0,columns:s,parseLine:o,...i}=e??{},a=o??(u=>pl(u,n));return $(u=>{let d=!1;return(async()=>{try{let l=s,p="";for await(let f of t){if(d)return;p+=f;let m=p.split(/\r?\n/);p=m.pop()??"";for(let g of m){if(d)return;if(!g.trim())continue;let h=a(g);if(!l&&r){l=h;continue}l||(l=h.map((b,v)=>`col${v}`));let y={};for(let b=0;b<l.length;b++)y[l[b]]=h[b]??"";u.emit(y)}}if(!d&&p.trim()){let f=a(p);if(l){let m={};for(let g=0;g<l.length;g++)m[l[g]]=f[g]??"";u.emit(m)}}d||u.down([[O]])}catch(l){d||u.down([[M,l]])}})(),()=>{d=!0}},mt(i))}function cl(t,e){let{delimiter:n=",",hasHeader:r=!0,columns:s,parseLine:o,...i}=e??{},a=o??(u=>pl(u,n));return V([t],(u,d,c)=>{let l=u[0];if(l==null||l.length===0)return;let p=c.store;typeof p.buffer!="string"&&(p.buffer=""),p.headers===void 0&&s&&(p.headers=s.slice());for(let f of l){p.buffer=p.buffer+f;let m=p.buffer.split(/\r?\n/);p.buffer=m.pop()??"";for(let g of m){if(!g.trim())continue;let h=a(g);if(!p.headers&&r){p.headers=h;continue}p.headers||(p.headers=h.map((b,v)=>`col${v}`));let y={};for(let b=0;b<p.headers.length;b++)y[p.headers[b]]=h[b]??"";d.emit(y)}}},{describeKind:"derived",...i})}function ll(t,e){return V([t],(n,r,s)=>{let o=n[0];if(o==null||o.length===0)return;let i=s.store;typeof i.buffer!="string"&&(i.buffer="");for(let a of o){i.buffer=i.buffer+a;let u=i.buffer.split(/\r?\n/);i.buffer=u.pop()??"";for(let d of u)if(d.trim())try{r.emit(JSON.parse(d))}catch(c){r.down([[M,c]]);return}}},{describeKind:"derived",...e??{}})}function pl(t,e){let n=[],r="",s=!1;for(let o=0;o<t.length;o++){let i=t[o];s?i==='"'?t[o+1]==='"'?(r+='"',o++):s=!1:r+=i:i==='"'?s=!0:i===e?(n.push(r),r=""):r+=i}return n.push(r),n}function fl(t,e){return $(n=>{let r=!1;return(async()=>{try{let o="";for await(let i of t){if(r)return;o+=i;let a=o.split(/\r?\n/);o=a.pop()??"";for(let u of a){if(r)return;let d=u.trim();d&&n.emit(JSON.parse(d))}}!r&&o.trim()&&n.emit(JSON.parse(o.trim())),r||n.down([[O]])}catch(o){r||n.down([[M,o]])}})(),()=>{r=!0}},mt(e))}function ml(t,e,n){let{intervalNs:r=5*1e9,format:s="JSONEachRow",signal:o,maxConsecutiveErrors:i=1}=n??{},a=Math.ceil(r/1e6),u=0;return be(dt(0,{period:a,signal:o}),()=>$(d=>{let c=!0;return(async()=>{try{let p=await t.query({query:e,format:s});if(!c)return;let f=await p.json();if(!c)return;for(let m of f)d.emit(m);u=0,d.down([[O]])}catch(p){if(!c)return;u+=1,u>=i&&d.down([[M,p]])}})(),()=>{c=!1}}))}function hl(t,e){let{autoAck:n=!0,deserialize:r=a=>{try{return JSON.parse(a.toString())}catch{return a.toString()}},onAckError:s,...o}=e??{},i=a=>{if(s)try{s(a instanceof Error?a:new Error(String(a)))}catch{}};return $(a=>{let u=!0;return(async()=>{for(;u;)try{let c=await t.receive();if(!u)return;let l={topic:c.getTopicName(),messageId:c.getMessageId().toString(),key:c.getPartitionKey(),value:r(c.getData()),properties:c.getProperties(),publishTime:c.getPublishTimestamp(),eventTime:c.getEventTimestamp(),timestampNs:ce()};if(n)a.emit(l),t.acknowledge(c).catch(i);else{let p=!1,f={value:l,ack(){p||(p=!0,t.acknowledge(c).catch(i))},nack(m){if(p)return;p=!0;let g=t;try{let h=g.negativeAcknowledge?.(c);h&&typeof h.then=="function"&&h.catch(i)}catch(h){i(h)}}};a.emit(f)}}catch(c){u&&a.down([[M,c]]);return}})(),()=>{u=!1}},mt(o))}function gl(t,e,n){let{serialize:r=a=>Buffer.from(JSON.stringify(a)),keyExtractor:s,propertiesExtractor:o,onTransportError:i}=n??{};return qe(t,{onTransportError:i,send:async a=>{await e.send({data:r(a),partitionKey:s?.(a),properties:o?.(a)})}})}function yl(t,e,n){let r=new TextDecoder,{queue:s,deserialize:o=a=>{let u=r.decode(a);try{return JSON.parse(u)}catch{return u}},...i}=n??{};return $(a=>{let u=!0,d=t.subscribe(e,s?{queue:s}:void 0);return(async()=>{try{for await(let l of d){if(!u)return;let p={};if(l.headers)for(let f of l.headers.keys())p[f]=l.headers.get(f);a.emit({subject:l.subject,data:o(l.data),headers:p,reply:l.reply,sid:l.sid,timestampNs:ce()})}u&&a.down([[O]])}catch(l){u&&a.down([[M,l]])}})(),()=>{u=!1}},mt(i))}function bl(t,e,n,r){let s=new TextEncoder,{serialize:o=a=>s.encode(JSON.stringify(a)),onTransportError:i}=r??{};return qe(t,{onTransportError:i,send:a=>{e.publish(n,o(a))}})}function vl(t,e,n){let{autoAck:r=!0,deserialize:s=u=>{try{return JSON.parse(u.toString())}catch{return u.toString()}},onAckError:o,...i}=n??{},a=u=>{if(o)try{o(u instanceof Error?u:new Error(String(u)))}catch{}};return $(u=>{let d=!0,c;return(async()=>{try{c=(await t.consume(e,f=>{if(!d)return;if(f===null){d&&u.down([[M,new Error("Consumer cancelled by broker")]]);return}let m={queue:e,routingKey:f.fields.routingKey,exchange:f.fields.exchange,content:s(f.content),properties:f.properties,deliveryTag:f.fields.deliveryTag,redelivered:f.fields.redelivered,timestampNs:ce()};if(r){u.emit(m);try{t.ack(f)}catch(g){a(g)}}else{let g=!1,h=t,y={value:m,ack(){if(!g){g=!0;try{t.ack(f)}catch(b){a(b)}}},nack(b){if(g)return;g=!0;let v=b?.requeue;if(!h.nack){a(new Error("RabbitMQ channel does not expose `nack`; cannot negative-ack"));return}try{h.nack(f,!1,v)}catch(T){a(T)}}};u.emit(y)}},{noAck:!1})).consumerTag}catch(p){d&&u.down([[M,p]])}})(),()=>{d=!1,c!==void 0&&t.cancel(c)}},mt(i))}function Tl(t,e,n,r){let{serialize:s=a=>Buffer.from(JSON.stringify(a)),routingKeyExtractor:o=()=>"",onTransportError:i}=r??{};return qe(t,{onTransportError:i,send:a=>{let u=o(a),d=s(a);e.publish(n,u,d)}})}function xa(t,e,n){let{serialize:r=l=>`${JSON.stringify(l)}
26
+ `,flushIntervalMs:s=0,batchSize:o=Number.POSITIVE_INFINITY,onTransportError:i,mode:a}=n??{},d=s>0||o<Number.POSITIVE_INFINITY?qe(t,{onTransportError:i,batchSize:o,flushIntervalMs:s,serialize:r,sendBatch:l=>{e.write(l.join(""))}}):qe(t,{onTransportError:i,serialize:r,send:l=>{e.write(l)}}),c=d.dispose;return d.dispose=()=>{c();try{e.end()}catch{}},d}function va(t,e){return t.includes(e)||t.includes('"')||t.includes(`
27
+ `)?`"${t.replace(/"/g,'""')}"`:t}function wl(t,e,n){let{columns:r,delimiter:s=",",writeHeader:o=!0,cellExtractor:i=(f,m)=>String(f[m]??""),flushIntervalMs:a=0,batchSize:u=Number.POSITIVE_INFINITY,onTransportError:d,...c}=n,l=!1;return xa(t,e,{serialize:f=>{if(!l&&o){l=!0;let m=r.map(h=>va(h,s)).join(s),g=r.map(h=>va(i(f,h),s)).join(s);return`${m}
28
28
  ${g}
29
- `}return`${r.map(m=>Ra(i(f,m),o)).join(o)}
30
- `},flushIntervalMs:a,batchSize:u,onTransportError:c,...d})}function vl(t,e,n,r){let{batchSize:o=1e3,flushIntervalMs:s=5e3,format:i="JSONEachRow",transform:a=c=>c,onTransportError:u}=r??{};return We(t,{onTransportError:u,batchSize:o,flushIntervalMs:s,serialize:a,sendBatch:async c=>{await e.insert({table:n,values:c,format:i})}})}function Tl(t,e,n,r){let{format:o="ndjson",keyGenerator:s=(p,f)=>{let m=Math.floor(f/1e6);return`data/${new Date(m).toISOString().replace(/[:.]/g,"-")}-${p}.${o==="ndjson"?"ndjson":"json"}`},batchSize:i=1e3,flushIntervalMs:a=1e4,transform:u=p=>p,onTransportError:c}=r??{},d=o==="ndjson"?"application/x-ndjson":"application/json",l=0;return We(t,{onTransportError:c,batchSize:i,flushIntervalMs:a,serialize:u,sendBatch:async p=>{l+=1;let f=o==="ndjson"?`${p.map(g=>JSON.stringify(g)).join(`
29
+ `}return`${r.map(m=>va(i(f,m),s)).join(s)}
30
+ `},flushIntervalMs:a,batchSize:u,onTransportError:d,...c})}function kl(t,e,n,r){let{batchSize:s=1e3,flushIntervalMs:o=5e3,format:i="JSONEachRow",transform:a=d=>d,onTransportError:u}=r??{};return qe(t,{onTransportError:u,batchSize:s,flushIntervalMs:o,serialize:a,sendBatch:async d=>{await e.insert({table:n,values:d,format:i})}})}function xl(t,e,n,r){let{format:s="ndjson",keyGenerator:o=(p,f)=>{let m=Math.floor(f/1e6);return`data/${new Date(m).toISOString().replace(/[:.]/g,"-")}-${p}.${s==="ndjson"?"ndjson":"json"}`},batchSize:i=1e3,flushIntervalMs:a=1e4,transform:u=p=>p,onTransportError:d}=r??{},c=s==="ndjson"?"application/x-ndjson":"application/json",l=0;return qe(t,{onTransportError:d,batchSize:i,flushIntervalMs:a,serialize:u,sendBatch:async p=>{l+=1;let f=s==="ndjson"?`${p.map(g=>JSON.stringify(g)).join(`
31
31
  `)}
32
- `:JSON.stringify(p),m=s(l,Te());await e.putObject({Bucket:n,Key:m,Body:f,ContentType:d})}})}function wl(t,e,n,r){let{toSQL:o=(i,a)=>({sql:`INSERT INTO "${a.replace(/"/g,'""')}" (data) VALUES ($1)`,params:[JSON.stringify(i)]}),onTransportError:s}=r??{};return We(t,{onTransportError:s,serialize:i=>o(i,n),send:async i=>{let a=i;await e.query(a.sql,a.params)}})}function kl(t,e,n){let{toDocument:r=s=>s,onTransportError:o}=n??{};return We(t,{onTransportError:o,serialize:r,send:async s=>{await e.insertOne(s)}})}function xl(t,e,n){let{labels:r={},toLine:o=a=>JSON.stringify(a),toLabels:s,onTransportError:i}=n??{};return We(t,{onTransportError:i,serialize:a=>({line:o(a),labels:s?{...r,...s(a)}:r}),send:async a=>{let{line:u,labels:c}=a,d=`${Te()}`;await e.push({streams:[{stream:c,values:[[d,u]]}]})}})}function Rl(t,e,n){let{toResourceSpans:r=s=>[s],onTransportError:o}=n??{};return We(t,{onTransportError:o,serialize:r,send:async s=>{await e.push({resourceSpans:s})}})}function Sl(t,e,n,r){let{prefix:o="checkpoints/",debounceMs:s=500,compactEvery:i=10,onError:a}=r??{},u={debounceMs:s,compactEvery:i,save(c,d){let l=Math.floor(Te()/1e6),p=`${o}${t.name}/checkpoint-${l}.json`,f;try{f=JSON.stringify(d)}catch(m){a?.(m);return}e.putObject({Bucket:n,Key:p,Body:f,ContentType:"application/json"}).catch(m=>a?.(m))},load(){return null}};return t.attachStorage([u],{onError:c=>a?.(c)})}function Nl(t,e,n){let{prefix:r="graphrefly:checkpoint:",debounceMs:o=500,compactEvery:s=10,onError:i}=n??{},a=`${r}${t.name}`,u={debounceMs:o,compactEvery:s,save(c,d){let l;try{l=JSON.stringify(d)}catch(p){i?.(p);return}e.set(a,l).catch(p=>i?.(p))},async load(){let c=await e.get(a);if(c==null)return null;try{return JSON.parse(c)}catch{return null}}};return t.attachStorage([u],{onError:c=>i?.(c)})}function El(t,e,n){let{mapRow:r=i=>i,params:o,...s}=n??{};return H(i=>{try{let u=t.query(e,o).map(r);i.emit(u),i.down([[C]])}catch(a){i.down([[O,a instanceof Error?a:new Error(String(a))]])}},{describeKind:"producer",completeWhenDepsComplete:!1,...s})}function _l(t,e,n){let{mapRow:r=i=>i,params:o,...s}=n??{};return H(i=>{try{let a=t.iterate(e,o);Z(()=>{for(let u of a)i.emit(r(u));i.down([[C]])})}catch(a){i.down([[O,a instanceof Error?a:new Error(String(a))]])}},{describeKind:"producer",completeWhenDepsComplete:!1,...s})}function Ml(t,e,n,r){if(n.includes("\0")||n.length===0)throw new Error(`toSqlite: invalid table name: ${JSON.stringify(n)}`);let{toSQL:o=(L,P)=>({sql:`INSERT INTO "${P.replace(/"/g,'""')}" (data) VALUES (?)`,params:[JSON.stringify(L)]}),onTransportError:s,batchInsert:i=!1,maxBatchSize:a=1e3,flushIntervalMs:u=0}=r??{},c=L=>o(L,n);if(!i)return We(t,{onTransportError:s,serialize:c,send:L=>{let P=L;e.query(P.sql,P.params)}});let d=E(null),l=E(void 0,{equals:()=>!1}),p=E(null),f=E(0),m=E(0),g=L=>{try{s?.(L)}catch{}try{d.down([[S,L]])}catch{}},h=[],y=!1,b,v=!1,T=()=>m.down([[S,h.length]]),w=L=>{v||l.down([[S,L]])},k=L=>{v||p.down([[S,L]])},x=L=>{v||f.down([[S,L]])},R=L=>{v||g(L)},N=()=>{if(h.length===0||y)return;y=!0,x(1);try{e.query("BEGIN",[])}catch(Q){y=!1,x(0),R({stage:"send",error:Q instanceof Error?Q:new Error(String(Q)),value:void 0});return}let L=h;h=[],T();let P,J=0;for(let Q of L)try{e.query(Q.query.sql,Q.query.params),J+=1}catch(D){P=D instanceof Error?D:new Error(String(D));break}if(P){try{e.query("ROLLBACK",[])}catch{}R({stage:"send",error:P,value:void 0});for(let Q of L)k({value:Q.value,error:P,attempts:1})}else try{e.query("COMMIT",[]);for(let Q of L)w(Q.value)}catch(Q){let D=Q instanceof Error?Q:new Error(String(Q));R({stage:"send",error:D,value:void 0});for(let z=0;z<J;z++)k({value:L[z].value,error:D,attempts:1})}y=!1,x(0)},A=()=>{u>0&&b===void 0&&!v&&(b=setTimeout(()=>{b=void 0,N()},u))},M=t.subscribe(L=>{for(let P of L){let J=P[0];if(J===S){let Q=P[1],D;try{D=c(Q)}catch(z){let W=z instanceof Error?z:new Error(String(z));g({stage:"serialize",error:W,value:Q}),p.down([[S,{value:Q,error:W,attempts:0}]]);continue}h.push({value:Q,query:D}),T(),h.length>=a?N():A()}else $e.messageTier(J)>=3&&N()}});return{dispose:()=>{if(!v){b!==void 0&&(clearTimeout(b),b=void 0),N(),v=!0,M();for(let L of[d,l,p,f,m])try{L.down([[ve]])}catch{}}},sent:l,failed:p,inFlight:f,errors:d,buffered:m,flush:async()=>{v||N()}}}function Ol(t,e){let{args:n,mapRow:r=s=>s,...o}=e??{};return H(s=>{let i=!0;return t.findMany(n).then(a=>{i&&(s.emit(a.map(r)),s.down([[C]]))}).catch(a=>{if(i)try{s.down([[O,a instanceof Error?a:new Error(String(a))]])}catch{}}),()=>{i=!1}},{...o,describeKind:"producer",completeWhenDepsComplete:!1})}function Cl(t,e){let{mapRow:n=o=>o,...r}=e??{};return H(o=>{let s=!0;return t.execute().then(i=>{s&&(o.emit(i.map(n)),o.down([[C]]))}).catch(i=>{if(s)try{o.down([[O,i instanceof Error?i:new Error(String(i))]])}catch{}}),()=>{s=!1}},{...r,describeKind:"producer",completeWhenDepsComplete:!1})}function Al(t,e){let{mapRow:n=o=>o,...r}=e??{};return H(o=>{let s=!0;return t.execute().then(i=>{s&&(o.emit(i.map(n)),o.down([[C]]))}).catch(i=>{if(s)try{o.down([[O,i instanceof Error?i:new Error(String(i))]])}catch{}}),()=>{s=!1}},{...r,describeKind:"producer",completeWhenDepsComplete:!1})}Kn();ae();ee();function Ma(){let t=new Map,e=null,n=null;function r(s){s.prev?s.prev.next=s.next:e=s.next,s.next?s.next.prev=s.prev:n=s.prev,s.prev=null,s.next=null}function o(s){s.next=e,s.prev=null,e&&(e.prev=s),e=s,n===null&&(n=s)}return{insert(s){if(t.has(s)){this.touch(s);return}let i={key:s,prev:null,next:null};t.set(s,i),o(i)},touch(s){let i=t.get(s);i&&(r(i),o(i))},delete(s){let i=t.get(s);i&&(r(i),t.delete(s))},evict(s){let i=[];for(let a=0;a<s&&n!==null;a++){let u=n;i.push(u.key),r(u),t.delete(u.key)}return i},size(){return t.size}}}function Ll(t){return t!=null&&typeof t.then=="function"}function er(t){Ll(t)&&t.catch(()=>{})}function Il(t,e){let n=new Map,r=e?.maxSize??0,o=r>0?e?.eviction??Ma():null,s=e?.writeThrough??!1;function i(c,d,l){for(let p=0;p<l;p++)try{er(t[p].save(c,d))}catch{}}function a(c,d,l=0){for(let p=l;p<t.length;p++){let f;try{f=t[p].load(c)}catch{continue}if(Ll(f)){let m=p;f.then(g=>{g!=null?(d.down([[S,g]]),i(c,g,m)):a(c,d,m+1)},()=>{a(c,d,m+1)});return}if(f!=null){d.down([[S,f]]),i(c,f,p);return}}}function u(){if(!(!o||r<=0))for(;o.size()>=r;){let c=o.evict(1);if(c.length===0)break;for(let d of c){let l=n.get(d);if(l){let p=l.cache;if(l.status!=="sentinel"&&t.length>0){let f=t.length-1;try{er(t[f].save(d,p))}catch{}for(let m=0;m<f;m++)try{let g=t[m].clear;g&&er(g.call(t[m],d))}catch{}}l.down([[ve]])}n.delete(d)}}}return{load(c){let d=n.get(c);if(d)return o?.touch(c),d;o&&r>0&&o.size()>=r&&u();let l=E(void 0);return n.set(c,l),o?.insert(c),a(c,l),l},save(c,d){if(s)for(let p of t)try{er(p.save(c,d))}catch{}else if(t[0])try{er(t[0].save(c,d))}catch{}let l=n.get(c);if(l)l.down([[S,d]]),o?.touch(c);else{o&&r>0&&o.size()>=r&&u();let p=E(d);n.set(c,p),o?.insert(c)}},invalidate(c){let d=n.get(c);d&&a(c,d)},delete(c){o?.delete(c);let d=n.get(c);d&&d.down([[ve]]),n.delete(c);for(let l of t)try{let p=l.clear;p&&er(p.call(l,c))}catch{}},has(c){return n.has(c)},get size(){return n.size}}}Ae();ae();ee();Ae();_e();ae();ee();var qr=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=j(),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=j(),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 j()+n*1e9}}_isExpired(e,n){return e.expiresAt===void 0?!1:(n??j())>=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 Xe(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 qr({maxSize:n,defaultTtl:r}),u=E(a.toMap(),{name:e,describeKind:"state",equals:(p,f)=>p===f,...o!=null?{versioning:o}:{}});function c(){let p=a.toMap();Z(()=>{u.down([[te]]),u.down([[S,p]])})}function d(){if(!i)return;let p=a.toMap(),f=i.archiveThreshold,m=i.maxSize,g=[];for(let[y,b]of p)g.push({key:y,value:b,score:i.score(y,b)});g.sort((y,b)=>y.score-b.score);let h=new Set;if(f!==void 0)for(let y of g)if(y.score<f)h.add(y.key);else break;if(m!==void 0&&g.length-h.size>m)for(let y of g){if(g.length-h.size<=m)break;h.has(y.key)||h.add(y.key)}if(h.size!==0)for(let y of g)h.has(y.key)&&(i.onArchive?.(y.key,y.value,y.score),a.delete(y.key))}function l(p,f="mutation"){let m=a.version;try{return p()}finally{a.version!==m&&(f==="mutation"&&d(),c())}}return{entries:u,has(p){return l(()=>a.has(p),"read")},get(p){return l(()=>a.get(p),"read")},set(p,f,m){l(()=>a.set(p,f,m?.ttl))},setMany(p,f){l(()=>a.setMany(p,f?.ttl))},delete(p){l(()=>a.delete(p))},deleteMany(p){l(()=>a.deleteMany(p))},clear(){l(()=>a.clear())},pruneExpired(){l(()=>a.pruneExpired())},get size(){return a.size},dispose(){}}}Re();function Zm(t){return typeof t=="object"&&t!==null&&"cache"in t&&typeof t.subscribe=="function"}function Gl(t,e,n){let r=X(t),o=r.v!=null,s=E(n?.initialVerified??null,{...o?{meta:{sourceVersion:null}}:{}}),i=n?.trigger!==void 0&&n.trigger!==null,a=null;if(i&&n?.autoVerify?a=wt(X(n.trigger),r):i?a=X(n.trigger):n?.autoVerify&&(a=r),a!==null){let u;if(a===r)u=Se(r,c=>e(c));else{let c=r.cache;r.subscribe(d=>{for(let l of d)l[0]===S&&(c=l[1])}),u=Se(a,()=>e(c))}Kt(u,c=>{Z(()=>{if(s.down([[S,c]]),o){let d=r.v;d!=null&&s.meta.sourceVersion.down([[S,{id:d.id,version:d.version}]])}})})}return{node:r,verified:s,trigger:a}}function Dl(t){t.subscribe(()=>{})}function Ur(t){return t instanceof Map?t:new Map}function Pl(t,e){if(!Array.isArray(e.upsert))throw new TypeError("distill extraction requires upsert: Array<{ key, value }>");Z(()=>{for(let{key:n,value:r}of e.upsert)t.set(n,r);for(let n of e.remove??[])t.delete(n)})}function Ns(t,e,n){let r=X(t),o=Xe(n.mapOptions??{}),s=n.budget??2e3,a=n.context!==void 0&&n.context!==null?X(n.context):E(null),u=Ur(o.entries.cache);o.entries.subscribe(f=>{for(let m of f)m[0]===S&&(u=Ur(m[1]))});let c=Se(r,f=>e(f,u));if(Kt(c,f=>{Pl(o,f)}),n.evict){let f=new Map,m=_([o.entries],([g])=>{let h=[],y=Ur(g);for(let b of f.keys())y.has(b)||(f.get(b)(),f.delete(b));for(let[b,v]of y){let T=n.evict(b,v);if(Zm(T)){if(!f.has(b)){let w=Kt(T,k=>{k===!0&&o.has(b)&&o.delete(b)});f.set(b,w)}continue}if(typeof T=="boolean"){T&&h.push(b);continue}throw new TypeError("distill evict() must return boolean or Node<boolean>")}return h});Kt(m,g=>{for(let h of g)o.delete(h)})}let d=n.consolidateTrigger!==void 0&&n.consolidateTrigger!==null;if(n.consolidate&&d){let f=X(n.consolidateTrigger),m=Se(f,()=>n.consolidate(u));Kt(m,g=>{Pl(o,g)})}let l=_([o.entries,a],([f,m])=>{let g=[...Ur(f).entries()].map(([b,v])=>({key:b,value:v,score:n.score(v,m),cost:n.cost(v)}));g.sort((b,v)=>v.score-b.score);let h=[],y=s;for(let b of g)b.cost<=y&&(h.push({key:b.key,value:b.value,score:b.score}),y-=b.cost);return h}),p=_([o.entries],([f])=>Ur(f).size);return Dl(l),Dl(p),{store:o,compact:l,size:p}}async function Es(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+=Fl[r[s]];return o}var Fl=new Array(256);for(let t=0;t<256;t++)Fl[t]=t.toString(16).padStart(2,"0");var zr=class extends Error{constructor(n,r){super(`content-addressed lookup miss in read-strict mode: ${n}`);this.key=n;this.context=r;this.name="ContentAddressedMissError"}};function Jr(t){let e=new Set,n=r=>{if(r===null||typeof r!="object")return r;let o=r;if(e.has(o))return{__cycle:!0};e.add(o);try{if(Array.isArray(r))return r.map(n);let s={};for(let i of Object.keys(r).sort())s[i]=n(r[i]);return s}finally{e.delete(o)}};return JSON.stringify(n(t))}function _s(t){let{storage:e,keyContext:n,keyPrefix:r,mode:o="read-write"}=t,s=n??(a=>a);async function i(a){let u=Jr(s(a)),c=await Es(u);return r?`${r}:${c}`:c}return{keyFor:i,async lookup(a){if(o==="write")return;let u=await i(a),c=await e.load(u);if(c==null){if(o==="read-strict")throw new zr(u,a);return}return c},async store(a,u){if(o==="read")return;let c=await i(a);await e.save(c,u)},async forget(a){if(o==="read"||o==="write"||!e.clear)return;let u=await i(a);await e.clear(u)}}}Ji();async function ht(t,e){let n;try{n=await t.text()}catch{n=""}let r=e??"HTTP",o=new Error(`${r} API ${t.status}: ${t.statusText}${n?` \u2014 ${n}`:""}`);return o.status=t.status,o.headers=t.headers,o}Ae();ae();Le();var Yr=class{_version=0;_topics=new Set;get version(){return this._version}get topicCount(){return this._topics.size}hasTopic(e){return this._topics.has(e)}topicNames(){return this._topics.values()}createTopic(e){return this._topics.has(e)?!1:(this._topics.add(e),this._version+=1,!0)}removeTopic(e){let n=this._topics.delete(e);return n&&(this._version+=1),n}};function $l(t={}){let{backend:e}=t,n=e??new Yr,r=new Map;function o(s){let i=r.get(s);return i===void 0&&(i=U({describeKind:"state"}),r.set(s,i),n.createTopic(s)),i}return{topic(s){return o(s)},publish(s,i){o(s).emit(i)},publishMany(s){Z(()=>{for(let[i,a]of s)o(i).emit(a)})},removeTopic(s){let i=r.get(s);return i===void 0?!1:(r.delete(s),n.removeTopic(s),i.down([[ve]]),!0)},has(s){return n.hasTopic(s)},get size(){return n.topicCount},topicNames(){return n.topicNames()}}}Ae();ae();ee();function jl(t,e){if(t===e)return 0;let n=typeof t;if(n===typeof e&&(n==="number"||n==="string"||n==="boolean"||n==="bigint")){let o=t,s=e;return o<s?-1:o>s?1:0}return String(t).localeCompare(String(e))}function eh(t,e){let n=jl(t[0],e[0]);return n!==0?n:jl(t[1],e[1])}function Bl(t){return[t.secondary,t.primary]}function tr(t,e){let n=Bl(e),r=0,o=t.length;for(;r<o;){let s=r+o>>1;eh(n,Bl(t[s]))>0?r=s+1:o=s}return r}var Qr=class{_version=0;_buf=[];_byPrimary=new Map;get version(){return this._version}get size(){return this._buf.length}has(e){return this._byPrimary.has(e)}get(e){return this._byPrimary.get(e)?.value}upsert(e,n,r,o){let s=this._byPrimary.get(e),i={primary:e,secondary:n,value:r};if(s!==void 0&&o?.equals?.(s,i))return!1;if(s!==void 0){let u=tr(this._buf,s);this._buf.splice(u,1)}let a=tr(this._buf,i);return this._buf.splice(a,0,i),this._byPrimary.set(e,i),this._version+=1,s===void 0}upsertMany(e,n){let r=0;try{for(let o of e){let s=this._byPrimary.get(o.primary),i={primary:o.primary,secondary:o.secondary,value:o.value};if(s!==void 0&&n?.equals?.(s,i))continue;if(s!==void 0){let u=tr(this._buf,s);this._buf.splice(u,1)}let a=tr(this._buf,i);this._buf.splice(a,0,i),this._byPrimary.set(o.primary,i),r+=1}}finally{r>0&&(this._version+=1)}return r}delete(e){let n=this._byPrimary.get(e);if(n===void 0)return!1;let r=tr(this._buf,n);return this._buf.splice(r,1),this._byPrimary.delete(e),this._version+=1,!0}deleteMany(e){let n=0;try{for(let r of e){let o=this._byPrimary.get(r);if(o===void 0)continue;let s=tr(this._buf,o);this._buf.splice(s,1),this._byPrimary.delete(r),n+=1}}finally{n>0&&(this._version+=1)}return n}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._byPrimary.clear(),this._version+=1,e)}toArray(){return[...this._buf]}toPrimaryMap(){let e=new Map;for(let n of this._buf)e.set(n.primary,n.value);return e}};function th(t){return t.subscribe(()=>{})}function Vl(t={}){let{name:e,versioning:n,equals:r,backend:o}=t,s=o??new Qr;function i(f){return f?.equals!==void 0||r===void 0?f:{...f,equals:r}}let a=E([],{name:e,describeKind:"state",equals:(f,m)=>f===m,...n!=null?{versioning:n}:{}}),u=_([a],([f])=>{let m=f,g=new Map;for(let h of m)g.set(h.primary,h.value);return g},{initial:s.toPrimaryMap(),describeKind:"derived"}),c=th(u),d=!1;function l(){let f=s.toArray();Z(()=>{a.down([[te]]),a.down([[S,f]])})}function p(f){let m=s.version;try{return f()}finally{s.version!==m&&l()}}return{ordered:a,byPrimary:u,has(f){return s.has(f)},get(f){return s.get(f)},get size(){return s.size},upsert(f,m,g,h){return p(()=>s.upsert(f,m,g,i(h)))},upsertMany(f,m){let g=[...f];g.length!==0&&p(()=>s.upsertMany(g,i(m)))},delete(f){p(()=>s.delete(f))},deleteMany(f){let m=[...f];m.length!==0&&p(()=>s.deleteMany(m))},clear(){p(()=>s.clear())},dispose(){d||(d=!0,c())}}}Ae();ae();ee();var Xr=class{_version=0;_buf;constructor(e){this._buf=e?[...e]:[]}get version(){return this._version}get size(){return this._buf.length}at(e){if(!Number.isInteger(e))return;let n=e>=0?e:this._buf.length+e;if(!(n<0||n>=this._buf.length))return this._buf[n]}append(e){this._buf.push(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._buf.length;this._buf.length=n+e.length;for(let r=0;r<e.length;r++)this._buf[n+r]=e[r];this._version+=1}insert(e,n){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insert: index ${e} out of range [0, ${this._buf.length}]`);this._buf.splice(e,0,n),this._version+=1}insertMany(e,n){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insertMany: index ${e} out of range [0, ${this._buf.length}]`);n.length!==0&&(this._buf.splice(e,0,...n),this._version+=1)}pop(e){if(this._buf.length===0)throw new RangeError("pop from empty list");if(!Number.isInteger(e))throw new RangeError(`pop: index ${e} must be an integer`);let n=e>=0?e:this._buf.length+e;if(n<0||n>=this._buf.length)throw new RangeError(`pop: index ${e} out of range`);let[r]=this._buf.splice(n,1);return this._version+=1,r}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._version+=1,e)}toArray(){return[...this._buf]}};function Ms(t,e={}){let{name:n,versioning:r,backend:o}=e,s=o??new Xr(t),i=E(s.toArray(),{name:n,describeKind:"state",equals:(c,d)=>c===d,...r!=null?{versioning:r}:{}});function a(){let c=s.toArray();Z(()=>{i.down([[te]]),i.down([[S,c]])})}function u(c){let d=s.version;try{return c()}finally{s.version!==d&&a()}}return{items:i,get size(){return s.size},at(c){return s.at(c)},append(c){u(()=>s.append(c))},appendMany(c){u(()=>s.appendMany(c))},insert(c,d){u(()=>s.insert(c,d))},insertMany(c,d){u(()=>s.insertMany(c,d))},pop(c=-1){return u(()=>s.pop(c))},clear(){u(()=>s.clear())},dispose(){}}}Et();ae();Re();function Os(t,e={}){let n=e.keyFn??(o=>String(o)),r=new Map;return o=>{let s=n(o),i=r.get(s);if(i)return i;let a=t(o),u;a!=null&&typeof a.then=="function"?u=Promise.resolve(a):a!=null&&typeof a=="object"&&"subscribe"in a&&"cache"in a?u=Qe(a):a!=null&&typeof a=="object"&&Symbol.asyncIterator in a?u=(async()=>{let l=a[Symbol.asyncIterator]();try{let{value:p,done:f}=await l.next();if(f)throw new Error("singleFromAny: factory returned empty async iterable");return p}finally{await l.return?.()}})():a!=null&&typeof a=="object"&&Symbol.iterator in a?u=(async()=>{let l=a[Symbol.iterator]();try{let{value:p,done:f}=l.next();if(f)throw new Error("singleFromAny: factory returned empty iterable");return p}finally{l.return?.()}})():u=Promise.resolve(a);let c,d=()=>{r.get(s)===c&&r.delete(s)};return c=u.then(l=>(d(),l),l=>{throw d(),l}),r.set(s,c),c}}function Kl(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=X(t(o));r.set(s,a);let u=a.subscribe(c=>{for(let d of c)if(d[0]===O||d[0]===C){r.get(s)===a&&r.delete(s),u();return}});return a}}Re();function Zr(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(Zr);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=Zr(e[o]);return r}function Hl(t){return JSON.stringify(Zr(t),void 0,0)}function eo(){let t=new Map;return{save(e,n){t.set(e,JSON.parse(JSON.stringify(n)))},load(e){let n=t.get(e);return n===void 0?null:JSON.parse(JSON.stringify(n))},clear(e){t.delete(e)},list(){return[...t.keys()].sort()}}}function Wl(t){return{save(e,n){t[e]=JSON.parse(JSON.stringify(n))},load(e){let n=t[e];return n===void 0?null:JSON.parse(JSON.stringify(n))},clear(e){delete t[e]},list(){return Object.keys(t).sort()}}}ae();Le();ee();function to(t,e,n,r){let o=new Y(t,r);o.add(e,{name:"source"});let s=E(n,{meta:{kind:"stratify_rules"}});o.add(s,{name:"rules"});for(let i of n)nh(o,e,s,i);return o}function nh(t,e,n,r){let o=`branch/${r.name}`,s=Symbol("noValue"),i=!1,a=!1,u=!1,c=s,d=!1,l=n.cache??[];function p(g){if(u){u=!1;let h=c;if(c=s,h!==s){let y=l.find(v=>v.name===r.name),b=!1;try{b=y?.classify(h)??!1}catch{b=!1}b?(d=!1,g.emit(h)):d&&(d=!1,g.down([[te],[F]]))}else d?(d=!1,g.down([[te],[F]])):g.down([[F]])}}let f=U([],(g,h)=>{let y=e.subscribe(v=>{for(let T of v)m(T,0,h)}),b=n.subscribe(v=>{for(let T of v)m(T,1,h)});return()=>{y(),b()}},{describeKind:"derived",meta:{kind:"stratify_branch",branch:r.name},completeWhenDepsComplete:!1});function m(g,h,y){let b=g[0];return b===te?(h===0?(i=!0,d=!0):a=!0,!0):b===S||b===F?(h===0?(i=!1,u=!0,c=b===S?g[1]:s):(b===S&&(l=g[1]),a=!1),i||a||p(y),!0):b===C||b===O||b===ve?(i=!1,a=!1,u=!1,c=s,d=!1,h===0&&y.down([g]),!0):h===1}if(t.add(f,{name:o}),r.ops){let g=r.ops(f),h=`branch/${r.name}/out`;t.add(g,{name:h})}}vt();Ae();ae();Le();ee();Re();ae();var rh=new Map([[Ye,"INVALIDATE"],[Be,"PAUSE"],[Ke,"RESUME"],[ve,"TEARDOWN"],[C,"COMPLETE"],[O,"ERROR"]]),oh=new Map([["INVALIDATE",Ye],["PAUSE",Be],["RESUME",Ke],["TEARDOWN",ve],["COMPLETE",C],["ERROR",O]]);function qt(t){let e=rh.get(t);return e||(Symbol.keyFor(t)??"UNKNOWN")}function gn(t){let e=oh.get(t);if(e)return e;if(t&&t!=="UNKNOWN")return Symbol.for(t)}function yn(t){return t instanceof Error?{message:t.message,name:t.name,stack:t.stack}:{message:String(t),name:"Error"}}function bn(t){let e=new Error(t.message);return e.name=t.name,t.stack&&(e.stack=t.stack),e}function Ut(t){if(typeof MessagePort<"u"&&t instanceof MessagePort)return{post(e,n){t.postMessage(e,n??[])},listen(e){let n=r=>e(r.data);return t.addEventListener("message",n),t.start(),()=>t.removeEventListener("message",n)},terminate(){t.close()}};if(typeof SharedWorker<"u"&&t instanceof SharedWorker)return Ut(t.port);if(typeof Worker<"u"&&t instanceof Worker)return{post(e,n){t.postMessage(e,n??[])},listen(e){let n=r=>e(r.data);return t.addEventListener("message",n),()=>t.removeEventListener("message",n)},terminate(){t.terminate()}};if(typeof BroadcastChannel<"u"&&t instanceof BroadcastChannel)return{post(e,n){n&&n.length>0&&console.warn("[graphrefly] WorkerTransport: BroadcastChannel does not support Transferable objects. The transfer argument is ignored and objects will be cloned instead."),t.postMessage(e)},listen(e){let n=r=>e(r.data);return t.addEventListener("message",n),()=>t.removeEventListener("message",n)},terminate(){t.close()}};if(typeof ServiceWorker<"u"&&t instanceof ServiceWorker)return{post(e,n){t.postMessage(e,n??[])},listen(e){let n=r=>{r.source===t&&e(r.data)};return navigator.serviceWorker.addEventListener("message",n),()=>navigator.serviceWorker.removeEventListener("message",n)}};throw new Error("createTransport: unsupported target type. Expected Worker, SharedWorker, ServiceWorker, BroadcastChannel, or MessagePort.")}function sh(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function Oa(t,e){let n=sh(t)?t:Ut(t),r=e.name??"workerBridge",o=Object.entries(e.expose??{}),s=e.import??[],i=e.transfer??{},a=E("connecting",{name:`${r}::meta::status`}),u=E(null,{name:`${r}::meta::error`}),c=new Map,d=new Map;for(let b of s){let v=E(void 0,{name:`${r}::${b}`});c.set(b,v)}let l;if(o.length>0){let b=o.map(([,w])=>w),v=U(b,(w,k)=>{let x={};for(let R=0;R<o.length;R++){let[N]=o[R],A=w[R];A!=null&&A.length>0&&(x[N]=A.at(-1))}Object.keys(x).length!==0&&k.emit(x)},{name:`${r}::aggregated`,partial:!0});l=de([v],w=>{let k=w[0];if(k==null||Object.keys(k).length===0)return;let x=[];for(let A of Object.keys(k)){let M=i[A];M&&x.push(...M(k[A]))}let R;for(let[A,M]of o)A in k&&M.v!=null&&(R==null&&(R={}),R[A]=M.v.version);let N={t:"b",u:k,...R?{v:R}:{}};try{n.post(N,x.length>0?x:void 0)}catch(A){u.down([[S,A instanceof Error?A:new Error(String(A))]])}}).subscribe(()=>{})}let p=!1,f=n.listen(b=>{if(p)return;let v=b;switch(v.t){case"r":{Z(()=>{for(let[w,k]of Object.entries(v.stores)){let x=c.get(w);x&&x.down([[S,k]])}}),a.down([[S,"connected"]]);let T={};for(let[w,k]of o)T[w]=k.cache;n.post({t:"i",stores:T});break}case"v":{let T=c.get(v.s);T&&T.down([[S,v.d]]);break}case"b":{Z(()=>{for(let[T,w]of Object.entries(v.u)){let k=v.v?.[T];if(k!=null){let R=d.get(T);if(R!=null&&k<=R)continue;d.set(T,k)}let x=c.get(T);x&&x.down([[S,w]])}});break}case"e":{let T=c.get(v.s);T&&T.down([[O,bn(v.err)]]);break}case"s":{let T=gn(v.sig);if(!T)break;let w=v.s==="*"?[...c.values()]:c.has(v.s)?[c.get(v.s)]:[];for(let k of w)k.down(v.d===void 0?[[T]]:[[T,v.d]]);break}}}),m=[];for(let[b,v]of o){let T=v.subscribe((w=>{if(!p)for(let k of w){let x=k[0];x!==S&&($e.isLocalOnly(x)||(x===O?n.post({t:"e",s:b,err:yn(k[1])}):n.post({t:"s",s:b,sig:qt(x),d:k.length>1?k[1]:void 0})))}}));m.push(T)}let g;if(e.timeoutMs!=null&&e.timeoutMs>0){let b=ct(e.timeoutMs),v=it(a,w=>w==="connected");g=Rs(wt(Br(b,()=>"timeout"),Br(v,()=>"ready"))).subscribe(w=>{for(let k of w)k[0]===S&&k[1]==="timeout"&&(u.down([[S,new Error("Worker bridge handshake timeout")]]),h())})}function h(){if(!p){p=!0,g?.(),n.post({t:"s",s:"*",sig:qt(ve)}),l&&l();for(let b of m)b();m.length=0,f(),a.down([[S,"closed"]]),d.clear(),c.clear()}}let y={meta:{status:a,error:u},destroy:h};for(let[b,v]of c)y[b]=v;return y}Ae();ae();Le();ee();function ih(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function Ca(t,e){let n=ih(t)?t:Ut(t),r=e.import??[],o=e.transfer??{},s=new Map,i=new Map,a={};for(let h of r){let y=E(void 0,{name:`worker::${h}`});s.set(h,y),a[h]=y}let u=e.expose(a),c=Object.entries(u),d,l=!1;if(c.length>0){let h=c.map(([,v])=>v),y=U(h,(v,T)=>{let w={};for(let k=0;k<c.length;k++){let[x]=c[k],R=v[k];R!=null&&R.length>0&&(w[x]=R.at(-1))}Object.keys(w).length!==0&&T.emit(w)},{name:"workerSelf::aggregated",partial:!0});d=de([y],v=>{if(l)return;let T=v[0];if(T==null||Object.keys(T).length===0)return;let w=[];for(let R of Object.keys(T)){let N=o[R];N&&w.push(...N(T[R]))}let k;for(let[R,N]of c)R in T&&N.v!=null&&(k==null&&(k={}),k[R]=N.v.version);let x={t:"b",u:T,...k?{v:k}:{}};try{n.post(x,w.length>0?w:void 0)}catch{}}).subscribe(()=>{})}let p=[];for(let[h,y]of c){let b=y.subscribe((v=>{if(!l)for(let T of v){let w=T[0];w!==S&&($e.isLocalOnly(w)||(w===O?n.post({t:"e",s:h,err:yn(T[1])}):n.post({t:"s",s:h,sig:qt(w),d:T.length>1?T[1]:void 0})))}}));p.push(b)}let f=n.listen(h=>{if(l)return;let y=h;switch(y.t){case"i":{Z(()=>{for(let[b,v]of Object.entries(y.stores)){let T=s.get(b);T&&T.down([[S,v]])}});break}case"v":{let b=s.get(y.s);b&&b.down([[S,y.d]]);break}case"b":{Z(()=>{for(let[b,v]of Object.entries(y.u)){let T=y.v?.[b];if(T!=null){let k=i.get(b);if(k!=null&&T<=k)continue;i.set(b,T)}let w=s.get(b);w&&w.down([[S,v]])}});break}case"e":{let b=s.get(y.s);b&&b.down([[O,bn(y.err)]]);break}case"s":{let b=gn(y.sig);if(!b)break;if(b===ve&&y.s==="*"){g();return}let v=y.s==="*"?[...s.values()]:s.has(y.s)?[s.get(y.s)]:[];for(let T of v)T.down(y.d===void 0?[[b]]:[[b,y.d]]);break}}}),m={};for(let[h,y]of c)m[h]=y.cache;n.post({t:"r",stores:m});function g(){if(!l){l=!0,d&&d();for(let h of p)h();p.length=0,f(),n.terminate?.(),i.clear(),s.clear()}}return{destroy:g}}var Ou={};Ne(Ou,{SNAPSHOT_WIRE_VERSION:()=>Ro,SurfaceError:()=>Ce,accountability:()=>ai,ai:()=>oi,asSurfaceError:()=>Ni,cqrs:()=>fs,createGraph:()=>dr,deleteSnapshot:()=>Li,demoShell:()=>ci,diffSnapshots:()=>Ci,domainTemplates:()=>di,graphspec:()=>ri,guarded:()=>pi,harness:()=>wi,jobQueue:()=>vi,layout:()=>Ri,lens:()=>xi,listSnapshots:()=>Ai,memory:()=>ei,messaging:()=>zs,orchestration:()=>Js,reduction:()=>ni,refine:()=>hi,resilientPipeline:()=>Si,restoreSnapshot:()=>Oi,runReduction:()=>Ei,saveSnapshot:()=>Mi,surface:()=>Ii});var oi={};Ne(oi,{AgentLoopGraph:()=>Xs,AllTiersExhaustedError:()=>oo,BudgetExhaustedError:()=>$s,ChatStreamGraph:()=>Ys,CircuitOpenError:()=>lt,DEFAULT_DECAY_RATE:()=>mo,FallbackMissError:()=>mh,LLMTimeoutError:()=>rr,ReplayCacheMissError:()=>wn,ToolRegistryGraph:()=>Qs,admissionFilter3D:()=>Eg,admissionScored:()=>hp,agentLoop:()=>Rg,agentMemory:()=>Og,anthropicAdapter:()=>La,canonicalJson:()=>Da,cascadingLlmAdapter:()=>za,chatStream:()=>Xa,composePricing:()=>Lh,computePrice:()=>Ba,contentGate:()=>Tg,costMeterExtractor:()=>mg,createAdapter:()=>_h,createCapabilitiesRegistry:()=>ah,createPricingRegistry:()=>Ch,dryRunAdapter:()=>vn,fallbackAdapter:()=>Pa,fromLLM:()=>Uh,frozenContext:()=>Qh,gatedStream:()=>lg,gaugesAsContext:()=>Pg,googleAdapter:()=>Ga,graphFromSpec:()=>Np,graphFromSpecReactive:()=>Ug,handoff:()=>Sg,keywordFlagExtractor:()=>gg,knobsAsTools:()=>Jg,llmConsolidator:()=>nu,llmExtractor:()=>tu,memoryRetrieval:()=>Dg,memoryWithKG:()=>Ag,memoryWithTiers:()=>Lg,memoryWithVectors:()=>Cg,observableAdapter:()=>Mh,openAICompatAdapter:()=>$a,parseRateLimitFromError:()=>Wa,pricingFor:()=>Ih,promptNode:()=>kn,redactor:()=>wg,registryPricing:()=>Ah,resilientAdapter:()=>qh,streamExtractor:()=>yg,streamingPromptNode:()=>dg,suggestStrategy:()=>Ep,suggestStrategyReactive:()=>Qg,systemPromptBuilder:()=>pg,tier:()=>Hh,toolCallExtractor:()=>vg,toolExecution:()=>Za,toolRegistry:()=>eu,toolSelector:()=>Ng,validateGraphDef:()=>Xg,withBreaker:()=>Va,withBudgetGate:()=>Ha,withDryRun:()=>Ph,withRateLimiter:()=>Ua,withReplayCache:()=>ro,withRetry:()=>Ja,withTimeout:()=>Ya,zeroPrice:()=>Fs});ee();function no(t,e){return`${t}::${e}`}function ah(t){let e=Xe({name:"capabilitiesRegistry"}),n=c=>{e.set(no(c.provider,c.id),c)};if(t)for(let c of t)n(c);let r=(c,d)=>{let l=e.get(no(c,d));if(l)return l;let p=e.entries.cache;if(!p)return;let f;for(let[,m]of p){if(m.provider!==c)continue;let g=m.id;d.startsWith(g)&&(!f||g.length>f.id.length)&&(f=m)}return f},o=128,s=new Map,i=new Map,a=(c,d,l,p)=>{for(c.has(d)&&c.delete(d),c.set(d,l);c.size>p;){let f=c.keys().next().value;if(f===void 0)break;c.delete(f)}},u=_([e.entries],([c])=>Array.from(c.values()),{name:"capabilitiesRegistry/entries",initial:[]});return{register:n,lookup:r,remove(c,d){let l=e.has(no(c,d));return l&&e.delete(no(c,d)),l},entries(){let c=e.entries.cache;return(function*(){if(c)for(let d of c.values())yield d})()},lookupNode(c,d){let l=no(c,d),p=s.get(l);if(p)return s.delete(l),s.set(l,p),p;let f=_([e.entries],()=>r(c,d),{name:`capabilitiesRegistry/lookup/${c}::${d}`,initial:void 0});return a(s,l,f,o),f},entriesNode:u,byProvider(c){let d=i.get(c);if(d)return i.delete(c),i.set(c,d),d;let l=_([u],([p])=>p.filter(f=>f.provider===c),{name:`capabilitiesRegistry/byProvider/${c}`,initial:[]});return a(i,c,l,o),l}}}_e();function La(t={}){return t.sdk?ph(t):lh(t)}function Cs(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}=uh(t,e?.systemPrompt),a={model:o,messages:i.map(ch),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(dh)),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 uh(t,e){let n=[];e&&n.push(e);let r=[];for(let o of t)o.role==="system"?n.push(o.content):r.push(o);return{system:n.length>0?n.join(`
32
+ `:JSON.stringify(p),m=o(l,ce());await e.putObject({Bucket:n,Key:m,Body:f,ContentType:c})}})}function Rl(t,e,n,r){let{toSQL:s=(i,a)=>({sql:`INSERT INTO "${a.replace(/"/g,'""')}" (data) VALUES ($1)`,params:[JSON.stringify(i)]}),onTransportError:o}=r??{};return qe(t,{onTransportError:o,serialize:i=>s(i,n),send:async i=>{let a=i;await e.query(a.sql,a.params)}})}function Sl(t,e,n){let{toDocument:r=o=>o,onTransportError:s}=n??{};return qe(t,{onTransportError:s,serialize:r,send:async o=>{await e.insertOne(o)}})}function Nl(t,e,n){let{labels:r={},toLine:s=a=>JSON.stringify(a),toLabels:o,onTransportError:i}=n??{};return qe(t,{onTransportError:i,serialize:a=>({line:s(a),labels:o?{...r,...o(a)}:r}),send:async a=>{let{line:u,labels:d}=a,c=`${ce()}`;await e.push({streams:[{stream:d,values:[[c,u]]}]})}})}function El(t,e,n){let{toResourceSpans:r=o=>[o],onTransportError:s}=n??{};return qe(t,{onTransportError:s,serialize:r,send:async o=>{await e.push({resourceSpans:o})}})}function _l(t,e,n,r){let{prefix:s="checkpoints/",debounceMs:o=500,compactEvery:i=10,onError:a}=r??{},u={debounceMs:o,compactEvery:i,save(d,c){let l=Math.floor(ce()/1e6),p=`${s}${t.name}/checkpoint-${l}.json`,f;try{f=JSON.stringify(c)}catch(m){a?.(m);return}e.putObject({Bucket:n,Key:p,Body:f,ContentType:"application/json"}).catch(m=>a?.(m))},load(){return null}};return t.attachStorage([u],{onError:d=>a?.(d)})}function Ml(t,e,n){let{prefix:r="graphrefly:checkpoint:",debounceMs:s=500,compactEvery:o=10,onError:i}=n??{},a=`${r}${t.name}`,u={debounceMs:s,compactEvery:o,save(d,c){let l;try{l=JSON.stringify(c)}catch(p){i?.(p);return}e.set(a,l).catch(p=>i?.(p))},async load(){let d=await e.get(a);if(d==null)return null;try{return JSON.parse(d)}catch{return null}}};return t.attachStorage([u],{onError:d=>i?.(d)})}function Ol(t,e,n){let{mapRow:r=i=>i,params:s,...o}=n??{};return $(i=>{try{let u=t.query(e,s).map(r);i.emit(u),i.down([[O]])}catch(a){i.down([[M,a instanceof Error?a:new Error(String(a))]])}},{describeKind:"producer",completeWhenDepsComplete:!1,...o})}function Cl(t,e,n){let{mapRow:r=i=>i,params:s,...o}=n??{};return $(i=>{try{let a=t.iterate(e,s);Y(()=>{for(let u of a)i.emit(r(u));i.down([[O]])})}catch(a){i.down([[M,a instanceof Error?a:new Error(String(a))]])}},{describeKind:"producer",completeWhenDepsComplete:!1,...o})}function Al(t,e,n,r){if(n.includes("\0")||n.length===0)throw new Error(`toSqlite: invalid table name: ${JSON.stringify(n)}`);let{toSQL:s=(A,P)=>({sql:`INSERT INTO "${P.replace(/"/g,'""')}" (data) VALUES (?)`,params:[JSON.stringify(A)]}),onTransportError:o,batchInsert:i=!1,maxBatchSize:a=1e3,flushIntervalMs:u=0}=r??{},d=A=>s(A,n);if(!i)return qe(t,{onTransportError:o,serialize:d,send:A=>{let P=A;e.query(P.sql,P.params)}});let c=N(null),l=N(void 0,{equals:()=>!1}),p=N(null),f=N(0),m=N(0),g=A=>{try{o?.(A)}catch{}try{c.down([[R,A]])}catch{}},h=[],y=!1,b,v=!1,T=()=>m.down([[R,h.length]]),w=A=>{v||l.down([[R,A]])},k=A=>{v||p.down([[R,A]])},x=A=>{v||f.down([[R,A]])},S=A=>{v||g(A)},E=()=>{if(h.length===0||y)return;y=!0,x(1);try{e.query("BEGIN",[])}catch(z){y=!1,x(0),S({stage:"send",error:z instanceof Error?z:new Error(String(z)),value:void 0});return}let A=h;h=[],T();let P,U=0;for(let z of A)try{e.query(z.query.sql,z.query.params),U+=1}catch(D){P=D instanceof Error?D:new Error(String(D));break}if(P){try{e.query("ROLLBACK",[])}catch{}S({stage:"send",error:P,value:void 0});for(let z of A)k({value:z.value,error:P,attempts:1})}else try{e.query("COMMIT",[]);for(let z of A)w(z.value)}catch(z){let D=z instanceof Error?z:new Error(String(z));S({stage:"send",error:D,value:void 0});for(let Z=0;Z<U;Z++)k({value:A[Z].value,error:D,attempts:1})}y=!1,x(0)},L=()=>{u>0&&b===void 0&&!v&&(b=setTimeout(()=>{b=void 0,E()},u))},C=t.subscribe(A=>{for(let P of A){let U=P[0];if(U===R){let z=P[1],D;try{D=d(z)}catch(Z){let te=Z instanceof Error?Z:new Error(String(Z));g({stage:"serialize",error:te,value:z}),p.down([[R,{value:z,error:te,attempts:0}]]);continue}h.push({value:z,query:D}),T(),h.length>=a?E():L()}else $e.messageTier(U)>=3&&E()}});return{dispose:()=>{if(!v){b!==void 0&&(clearTimeout(b),b=void 0),E(),v=!0,C();for(let A of[c,l,p,f,m])try{A.down([[de]])}catch{}}},sent:l,failed:p,inFlight:f,errors:c,buffered:m,flush:async()=>{v||E()}}}function Ll(t,e){let{args:n,mapRow:r=o=>o,...s}=e??{};return $(o=>{let i=!0;return t.findMany(n).then(a=>{i&&(o.emit(a.map(r)),o.down([[O]]))}).catch(a=>{if(i)try{o.down([[M,a instanceof Error?a:new Error(String(a))]])}catch{}}),()=>{i=!1}},{...s,describeKind:"producer",completeWhenDepsComplete:!1})}function Il(t,e){let{mapRow:n=s=>s,...r}=e??{};return $(s=>{let o=!0;return t.execute().then(i=>{o&&(s.emit(i.map(n)),s.down([[O]]))}).catch(i=>{if(o)try{s.down([[M,i instanceof Error?i:new Error(String(i))]])}catch{}}),()=>{o=!1}},{...r,describeKind:"producer",completeWhenDepsComplete:!1})}function Dl(t,e){let{mapRow:n=s=>s,...r}=e??{};return $(s=>{let o=!0;return t.execute().then(i=>{o&&(s.emit(i.map(n)),s.down([[O]]))}).catch(i=>{if(o)try{s.down([[M,i instanceof Error?i:new Error(String(i))]])}catch{}}),()=>{o=!1}},{...r,describeKind:"producer",completeWhenDepsComplete:!1})}Kn();se();Q();function Ra(){let t=new Map,e=null,n=null;function r(o){o.prev?o.prev.next=o.next:e=o.next,o.next?o.next.prev=o.prev:n=o.prev,o.prev=null,o.next=null}function s(o){o.next=e,o.prev=null,e&&(e.prev=o),e=o,n===null&&(n=o)}return{insert(o){if(t.has(o)){this.touch(o);return}let i={key:o,prev:null,next:null};t.set(o,i),s(i)},touch(o){let i=t.get(o);i&&(r(i),s(i))},delete(o){let i=t.get(o);i&&(r(i),t.delete(o))},evict(o){let i=[];for(let a=0;a<o&&n!==null;a++){let u=n;i.push(u.key),r(u),t.delete(u.key)}return i},size(){return t.size}}}function Pl(t){return t!=null&&typeof t.then=="function"}function er(t){Pl(t)&&t.catch(()=>{})}function Gl(t,e){let n=new Map,r=e?.maxSize??0,s=r>0?e?.eviction??Ra():null,o=e?.writeThrough??!1;function i(d,c,l){for(let p=0;p<l;p++)try{er(t[p].save(d,c))}catch{}}function a(d,c,l=0){for(let p=l;p<t.length;p++){let f;try{f=t[p].load(d)}catch{continue}if(Pl(f)){let m=p;f.then(g=>{g!=null?(c.down([[R,g]]),i(d,g,m)):a(d,c,m+1)},()=>{a(d,c,m+1)});return}if(f!=null){c.down([[R,f]]),i(d,f,p);return}}}function u(){if(!(!s||r<=0))for(;s.size()>=r;){let d=s.evict(1);if(d.length===0)break;for(let c of d){let l=n.get(c);if(l){let p=l.cache;if(l.status!=="sentinel"&&t.length>0){let f=t.length-1;try{er(t[f].save(c,p))}catch{}for(let m=0;m<f;m++)try{let g=t[m].clear;g&&er(g.call(t[m],c))}catch{}}l.down([[de]])}n.delete(c)}}}return{load(d){let c=n.get(d);if(c)return s?.touch(d),c;s&&r>0&&s.size()>=r&&u();let l=N(void 0);return n.set(d,l),s?.insert(d),a(d,l),l},save(d,c){if(o)for(let p of t)try{er(p.save(d,c))}catch{}else if(t[0])try{er(t[0].save(d,c))}catch{}let l=n.get(d);if(l)l.down([[R,c]]),s?.touch(d);else{s&&r>0&&s.size()>=r&&u();let p=N(c);n.set(d,p),s?.insert(d)}},invalidate(d){let c=n.get(d);c&&a(d,c)},delete(d){s?.delete(d);let c=n.get(d);c&&c.down([[de]]),n.delete(d);for(let l of t)try{let p=l.clear;p&&er(p.call(l,d))}catch{}},has(d){return n.has(d)},get size(){return n.size}}}Ce();se();Q();Ce();Ne();se();Q();var Wr=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 s=this._resolveExpiresAt(r);this._store.has(e)&&this._store.delete(e),this._store.set(e,{value:n,expiresAt:s}),this._evictLruWhileOver(),this._version+=1}setMany(e,n){let r=this._resolveExpiresAt(n),s=0;try{for(let[o,i]of e)this._store.has(o)&&this._store.delete(o),this._store.set(o,{value:i,expiresAt:r}),s+=1}finally{s>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,s]of this._store)this._isExpired(s,e)&&(this._store.delete(r),n+=1);return n>0&&(this._version+=1),n}toMap(){let e=F(),n=new Map;for(let[r,s]of this._store)this._isExpired(s,e)||n.set(r,s.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 Ze(t={}){let{name:e,maxSize:n,defaultTtl:r,versioning:s,backend:o,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=o??new Wr({maxSize:n,defaultTtl:r}),u=N(a.toMap(),{name:e,describeKind:"state",equals:(p,f)=>p===f,...s!=null?{versioning:s}:{}});function d(){let p=a.toMap();Y(()=>{u.down([[X]]),u.down([[R,p]])})}function c(){if(!i)return;let p=a.toMap(),f=i.archiveThreshold,m=i.maxSize,g=[];for(let[y,b]of p)g.push({key:y,value:b,score:i.score(y,b)});g.sort((y,b)=>y.score-b.score);let h=new Set;if(f!==void 0)for(let y of g)if(y.score<f)h.add(y.key);else break;if(m!==void 0&&g.length-h.size>m)for(let y of g){if(g.length-h.size<=m)break;h.has(y.key)||h.add(y.key)}if(h.size!==0)for(let y of g)h.has(y.key)&&(i.onArchive?.(y.key,y.value,y.score),a.delete(y.key))}function l(p,f="mutation"){let m=a.version;try{return p()}finally{a.version!==m&&(f==="mutation"&&c(),d())}}return{entries:u,has(p){return l(()=>a.has(p),"read")},get(p){return l(()=>a.get(p),"read")},set(p,f,m){l(()=>a.set(p,f,m?.ttl))},setMany(p,f){l(()=>a.setMany(p,f?.ttl))},delete(p){l(()=>a.delete(p))},deleteMany(p){l(()=>a.deleteMany(p))},clear(){l(()=>a.clear())},pruneExpired(){l(()=>a.pruneExpired())},get size(){return a.size},dispose(){}}}Te();function oh(t){return typeof t=="object"&&t!==null&&"cache"in t&&typeof t.subscribe=="function"}function jl(t,e,n){let r=W(t),s=r.v!=null,o=N(n?.initialVerified??null,{...s?{meta:{sourceVersion:null}}:{}}),i=n?.trigger!==void 0&&n.trigger!==null,a=null;if(i&&n?.autoVerify?a=wt(W(n.trigger),r):i?a=W(n.trigger):n?.autoVerify&&(a=r),a!==null){let u;if(a===r)u=be(r,d=>e(d));else{let d=r.cache;r.subscribe(c=>{for(let l of c)l[0]===R&&(d=l[1])}),u=be(a,()=>e(d))}Vt(u,d=>{Y(()=>{if(o.down([[R,d]]),s){let c=r.v;c!=null&&o.meta.sourceVersion.down([[R,{id:c.id,version:c.version}]])}})})}return{node:r,verified:o,trigger:a}}function Fl(t){t.subscribe(()=>{})}function Ur(t){return t instanceof Map?t:new Map}function $l(t,e){if(!Array.isArray(e.upsert))throw new TypeError("distill extraction requires upsert: Array<{ key, value }>");Y(()=>{for(let{key:n,value:r}of e.upsert)t.set(n,r);for(let n of e.remove??[])t.delete(n)})}function ws(t,e,n){let r=W(t),s=Ze(n.mapOptions??{}),o=n.budget??2e3,a=n.context!==void 0&&n.context!==null?W(n.context):N(null),u=Ur(s.entries.cache);s.entries.subscribe(f=>{for(let m of f)m[0]===R&&(u=Ur(m[1]))});let d=be(r,f=>e(f,u));if(Vt(d,f=>{$l(s,f)}),n.evict){let f=new Map,m=_([s.entries],([g])=>{let h=[],y=Ur(g);for(let b of f.keys())y.has(b)||(f.get(b)(),f.delete(b));for(let[b,v]of y){let T=n.evict(b,v);if(oh(T)){if(!f.has(b)){let w=Vt(T,k=>{k===!0&&s.has(b)&&s.delete(b)});f.set(b,w)}continue}if(typeof T=="boolean"){T&&h.push(b);continue}throw new TypeError("distill evict() must return boolean or Node<boolean>")}return h});Vt(m,g=>{for(let h of g)s.delete(h)})}let c=n.consolidateTrigger!==void 0&&n.consolidateTrigger!==null;if(n.consolidate&&c){let f=W(n.consolidateTrigger),m=be(f,()=>n.consolidate(u));Vt(m,g=>{$l(s,g)})}let l=_([s.entries,a],([f,m])=>{let g=[...Ur(f).entries()].map(([b,v])=>({key:b,value:v,score:n.score(v,m),cost:n.cost(v)}));g.sort((b,v)=>v.score-b.score);let h=[],y=o;for(let b of g)b.cost<=y&&(h.push({key:b.key,value:b.value,score:b.score}),y-=b.cost);return h}),p=_([s.entries],([f])=>Ur(f).size);return Fl(l),Fl(p),{store:s,compact:l,size:p}}async function ks(t){let e=typeof t=="string"?new TextEncoder().encode(t):t,n=await globalThis.crypto.subtle.digest("SHA-256",e),r=new Uint8Array(n),s="";for(let o=0;o<r.length;o++)s+=Bl[r[o]];return s}var Bl=new Array(256);for(let t=0;t<256;t++)Bl[t]=t.toString(16).padStart(2,"0");var zr=class extends Error{constructor(n,r){super(`content-addressed lookup miss in read-strict mode: ${n}`);this.key=n;this.context=r;this.name="ContentAddressedMissError"}};function Jr(t){let e=new Set,n=r=>{if(r===null||typeof r!="object")return r;let s=r;if(e.has(s))return{__cycle:!0};e.add(s);try{if(Array.isArray(r))return r.map(n);let o={};for(let i of Object.keys(r).sort())o[i]=n(r[i]);return o}finally{e.delete(s)}};return JSON.stringify(n(t))}function xs(t){let{storage:e,keyContext:n,keyPrefix:r,mode:s="read-write"}=t,o=n??(a=>a);async function i(a){let u=Jr(o(a)),d=await ks(u);return r?`${r}:${d}`:d}return{keyFor:i,async lookup(a){if(s==="write")return;let u=await i(a),d=await e.load(u);if(d==null){if(s==="read-strict")throw new zr(u,a);return}return d},async store(a,u){if(s==="read")return;let d=await i(a);await e.save(d,u)},async forget(a){if(s==="read"||s==="write"||!e.clear)return;let u=await i(a);await e.clear(u)}}}Hi();async function ht(t,e){let n;try{n=await t.text()}catch{n=""}let r=e??"HTTP",s=new Error(`${r} API ${t.status}: ${t.statusText}${n?` \u2014 ${n}`:""}`);return s.status=t.status,s.headers=t.headers,s}Ce();se();_e();var Yr=class{_version=0;_topics=new Set;get version(){return this._version}get topicCount(){return this._topics.size}hasTopic(e){return this._topics.has(e)}topicNames(){return this._topics.values()}createTopic(e){return this._topics.has(e)?!1:(this._topics.add(e),this._version+=1,!0)}removeTopic(e){let n=this._topics.delete(e);return n&&(this._version+=1),n}};function Vl(t={}){let{backend:e}=t,n=e??new Yr,r=new Map;function s(o){let i=r.get(o);return i===void 0&&(i=V({describeKind:"state"}),r.set(o,i),n.createTopic(o)),i}return{topic(o){return s(o)},publish(o,i){s(o).emit(i)},publishMany(o){Y(()=>{for(let[i,a]of o)s(i).emit(a)})},removeTopic(o){let i=r.get(o);return i===void 0?!1:(r.delete(o),n.removeTopic(o),i.down([[de]]),!0)},has(o){return n.hasTopic(o)},get size(){return n.topicCount},topicNames(){return n.topicNames()}}}Ce();se();Q();function Kl(t,e){if(t===e)return 0;let n=typeof t;if(n===typeof e&&(n==="number"||n==="string"||n==="boolean"||n==="bigint")){let s=t,o=e;return s<o?-1:s>o?1:0}return String(t).localeCompare(String(e))}function sh(t,e){let n=Kl(t[0],e[0]);return n!==0?n:Kl(t[1],e[1])}function Hl(t){return[t.secondary,t.primary]}function tr(t,e){let n=Hl(e),r=0,s=t.length;for(;r<s;){let o=r+s>>1;sh(n,Hl(t[o]))>0?r=o+1:s=o}return r}var Qr=class{_version=0;_buf=[];_byPrimary=new Map;get version(){return this._version}get size(){return this._buf.length}has(e){return this._byPrimary.has(e)}get(e){return this._byPrimary.get(e)?.value}upsert(e,n,r,s){let o=this._byPrimary.get(e),i={primary:e,secondary:n,value:r};if(o!==void 0&&s?.equals?.(o,i))return!1;if(o!==void 0){let u=tr(this._buf,o);this._buf.splice(u,1)}let a=tr(this._buf,i);return this._buf.splice(a,0,i),this._byPrimary.set(e,i),this._version+=1,o===void 0}upsertMany(e,n){let r=0;try{for(let s of e){let o=this._byPrimary.get(s.primary),i={primary:s.primary,secondary:s.secondary,value:s.value};if(o!==void 0&&n?.equals?.(o,i))continue;if(o!==void 0){let u=tr(this._buf,o);this._buf.splice(u,1)}let a=tr(this._buf,i);this._buf.splice(a,0,i),this._byPrimary.set(s.primary,i),r+=1}}finally{r>0&&(this._version+=1)}return r}delete(e){let n=this._byPrimary.get(e);if(n===void 0)return!1;let r=tr(this._buf,n);return this._buf.splice(r,1),this._byPrimary.delete(e),this._version+=1,!0}deleteMany(e){let n=0;try{for(let r of e){let s=this._byPrimary.get(r);if(s===void 0)continue;let o=tr(this._buf,s);this._buf.splice(o,1),this._byPrimary.delete(r),n+=1}}finally{n>0&&(this._version+=1)}return n}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._byPrimary.clear(),this._version+=1,e)}toArray(){return[...this._buf]}toPrimaryMap(){let e=new Map;for(let n of this._buf)e.set(n.primary,n.value);return e}};function ih(t){return t.subscribe(()=>{})}function ql(t={}){let{name:e,versioning:n,equals:r,backend:s}=t,o=s??new Qr;function i(f){return f?.equals!==void 0||r===void 0?f:{...f,equals:r}}let a=N([],{name:e,describeKind:"state",equals:(f,m)=>f===m,...n!=null?{versioning:n}:{}}),u=_([a],([f])=>{let m=f,g=new Map;for(let h of m)g.set(h.primary,h.value);return g},{initial:o.toPrimaryMap(),describeKind:"derived"}),d=ih(u),c=!1;function l(){let f=o.toArray();Y(()=>{a.down([[X]]),a.down([[R,f]])})}function p(f){let m=o.version;try{return f()}finally{o.version!==m&&l()}}return{ordered:a,byPrimary:u,has(f){return o.has(f)},get(f){return o.get(f)},get size(){return o.size},upsert(f,m,g,h){return p(()=>o.upsert(f,m,g,i(h)))},upsertMany(f,m){let g=[...f];g.length!==0&&p(()=>o.upsertMany(g,i(m)))},delete(f){p(()=>o.delete(f))},deleteMany(f){let m=[...f];m.length!==0&&p(()=>o.deleteMany(m))},clear(){p(()=>o.clear())},dispose(){c||(c=!0,d())}}}Ce();se();Q();var Xr=class{_version=0;_buf;constructor(e){this._buf=e?[...e]:[]}get version(){return this._version}get size(){return this._buf.length}at(e){if(!Number.isInteger(e))return;let n=e>=0?e:this._buf.length+e;if(!(n<0||n>=this._buf.length))return this._buf[n]}append(e){this._buf.push(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._buf.length;this._buf.length=n+e.length;for(let r=0;r<e.length;r++)this._buf[n+r]=e[r];this._version+=1}insert(e,n){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insert: index ${e} out of range [0, ${this._buf.length}]`);this._buf.splice(e,0,n),this._version+=1}insertMany(e,n){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insertMany: index ${e} out of range [0, ${this._buf.length}]`);n.length!==0&&(this._buf.splice(e,0,...n),this._version+=1)}pop(e){if(this._buf.length===0)throw new RangeError("pop from empty list");if(!Number.isInteger(e))throw new RangeError(`pop: index ${e} must be an integer`);let n=e>=0?e:this._buf.length+e;if(n<0||n>=this._buf.length)throw new RangeError(`pop: index ${e} out of range`);let[r]=this._buf.splice(n,1);return this._version+=1,r}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._version+=1,e)}toArray(){return[...this._buf]}};function Rs(t,e={}){let{name:n,versioning:r,backend:s}=e,o=s??new Xr(t),i=N(o.toArray(),{name:n,describeKind:"state",equals:(d,c)=>d===c,...r!=null?{versioning:r}:{}});function a(){let d=o.toArray();Y(()=>{i.down([[X]]),i.down([[R,d]])})}function u(d){let c=o.version;try{return d()}finally{o.version!==c&&a()}}return{items:i,get size(){return o.size},at(d){return o.at(d)},append(d){u(()=>o.append(d))},appendMany(d){u(()=>o.appendMany(d))},insert(d,c){u(()=>o.insert(d,c))},insertMany(d,c){u(()=>o.insertMany(d,c))},pop(d=-1){return u(()=>o.pop(d))},clear(){u(()=>o.clear())},dispose(){}}}Et();se();Te();function Ss(t,e={}){let n=e.keyFn??(s=>String(s)),r=new Map;return s=>{let o=n(s),i=r.get(o);if(i)return i;let a=t(s),u;a!=null&&typeof a.then=="function"?u=Promise.resolve(a):a!=null&&typeof a=="object"&&"subscribe"in a&&"cache"in a?u=Qe(a):a!=null&&typeof a=="object"&&Symbol.asyncIterator in a?u=(async()=>{let l=a[Symbol.asyncIterator]();try{let{value:p,done:f}=await l.next();if(f)throw new Error("singleFromAny: factory returned empty async iterable");return p}finally{await l.return?.()}})():a!=null&&typeof a=="object"&&Symbol.iterator in a?u=(async()=>{let l=a[Symbol.iterator]();try{let{value:p,done:f}=l.next();if(f)throw new Error("singleFromAny: factory returned empty iterable");return p}finally{l.return?.()}})():u=Promise.resolve(a);let d,c=()=>{r.get(o)===d&&r.delete(o)};return d=u.then(l=>(c(),l),l=>{throw c(),l}),r.set(o,d),d}}function Wl(t,e={}){let n=e.keyFn??(s=>String(s)),r=new Map;return s=>{let o=n(s),i=r.get(o);if(i)return i;let a=W(t(s));r.set(o,a);let u=a.subscribe(d=>{for(let c of d)if(c[0]===M||c[0]===O){r.get(o)===a&&r.delete(o),u();return}});return a}}Te();function Zr(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(Zr);let e=t,n=Object.keys(e).sort(),r={};for(let s of n)r[s]=Zr(e[s]);return r}function Ul(t){return JSON.stringify(Zr(t),void 0,0)}function eo(){let t=new Map;return{save(e,n){t.set(e,JSON.parse(JSON.stringify(n)))},load(e){let n=t.get(e);return n===void 0?null:JSON.parse(JSON.stringify(n))},clear(e){t.delete(e)},list(){return[...t.keys()].sort()}}}function zl(t){return{save(e,n){t[e]=JSON.parse(JSON.stringify(n))},load(e){let n=t[e];return n===void 0?null:JSON.parse(JSON.stringify(n))},clear(e){delete t[e]},list(){return Object.keys(t).sort()}}}se();_e();Q();function to(t,e,n,r){let s=new q(t,r);s.add(e,{name:"source"});let o=N(n,{meta:{kind:"stratify_rules"}});s.add(o,{name:"rules"});for(let i of n)ah(s,e,o,i);return s}function ah(t,e,n,r){let s=`branch/${r.name}`,o=Symbol("noValue"),i=!1,a=!1,u=!1,d=o,c=!1,l=n.cache??[];function p(g){if(u){u=!1;let h=d;if(d=o,h!==o){let y=l.find(v=>v.name===r.name),b=!1;try{b=y?.classify(h)??!1}catch{b=!1}b?(c=!1,g.emit(h)):c&&(c=!1,g.down([[X],[G]]))}else c?(c=!1,g.down([[X],[G]])):g.down([[G]])}}let f=V([],(g,h)=>{let y=e.subscribe(v=>{for(let T of v)m(T,0,h)}),b=n.subscribe(v=>{for(let T of v)m(T,1,h)});return()=>{y(),b()}},{describeKind:"derived",meta:{kind:"stratify_branch",branch:r.name},completeWhenDepsComplete:!1});function m(g,h,y){let b=g[0];return b===X?(h===0?(i=!0,c=!0):a=!0,!0):b===R||b===G?(h===0?(i=!1,u=!0,d=b===R?g[1]:o):(b===R&&(l=g[1]),a=!1),i||a||p(y),!0):b===O||b===M||b===de?(i=!1,a=!1,u=!1,d=o,c=!1,h===0&&y.down([g]),!0):h===1}if(t.add(f,{name:s}),r.ops){let g=r.ops(f),h=`branch/${r.name}/out`;t.add(g,{name:h})}}vt();Ce();se();_e();Q();Te();se();var uh=new Map([[Ye,"INVALIDATE"],[Be,"PAUSE"],[Ke,"RESUME"],[de,"TEARDOWN"],[O,"COMPLETE"],[M,"ERROR"]]),dh=new Map([["INVALIDATE",Ye],["PAUSE",Be],["RESUME",Ke],["TEARDOWN",de],["COMPLETE",O],["ERROR",M]]);function qt(t){let e=uh.get(t);return e||(Symbol.keyFor(t)??"UNKNOWN")}function hn(t){let e=dh.get(t);if(e)return e;if(t&&t!=="UNKNOWN")return Symbol.for(t)}function gn(t){return t instanceof Error?{message:t.message,name:t.name,stack:t.stack}:{message:String(t),name:"Error"}}function yn(t){let e=new Error(t.message);return e.name=t.name,t.stack&&(e.stack=t.stack),e}function Wt(t){if(typeof MessagePort<"u"&&t instanceof MessagePort)return{post(e,n){t.postMessage(e,n??[])},listen(e){let n=r=>e(r.data);return t.addEventListener("message",n),t.start(),()=>t.removeEventListener("message",n)},terminate(){t.close()}};if(typeof SharedWorker<"u"&&t instanceof SharedWorker)return Wt(t.port);if(typeof Worker<"u"&&t instanceof Worker)return{post(e,n){t.postMessage(e,n??[])},listen(e){let n=r=>e(r.data);return t.addEventListener("message",n),()=>t.removeEventListener("message",n)},terminate(){t.terminate()}};if(typeof BroadcastChannel<"u"&&t instanceof BroadcastChannel)return{post(e,n){n&&n.length>0&&console.warn("[graphrefly] WorkerTransport: BroadcastChannel does not support Transferable objects. The transfer argument is ignored and objects will be cloned instead."),t.postMessage(e)},listen(e){let n=r=>e(r.data);return t.addEventListener("message",n),()=>t.removeEventListener("message",n)},terminate(){t.close()}};if(typeof ServiceWorker<"u"&&t instanceof ServiceWorker)return{post(e,n){t.postMessage(e,n??[])},listen(e){let n=r=>{r.source===t&&e(r.data)};return navigator.serviceWorker.addEventListener("message",n),()=>navigator.serviceWorker.removeEventListener("message",n)}};throw new Error("createTransport: unsupported target type. Expected Worker, SharedWorker, ServiceWorker, BroadcastChannel, or MessagePort.")}function ch(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function Sa(t,e){let n=ch(t)?t:Wt(t),r=e.name??"workerBridge",s=Object.entries(e.expose??{}),o=e.import??[],i=e.transfer??{},a=N("connecting",{name:`${r}::meta::status`}),u=N(null,{name:`${r}::meta::error`}),d=new Map,c=new Map;for(let b of o){let v=N(void 0,{name:`${r}::${b}`});d.set(b,v)}let l;if(s.length>0){let b=s.map(([,w])=>w),v=V(b,(w,k)=>{let x={};for(let S=0;S<s.length;S++){let[E]=s[S],L=w[S];L!=null&&L.length>0&&(x[E]=L.at(-1))}Object.keys(x).length!==0&&k.emit(x)},{name:`${r}::aggregated`,partial:!0});l=le([v],w=>{let k=w[0];if(k==null||Object.keys(k).length===0)return;let x=[];for(let L of Object.keys(k)){let C=i[L];C&&x.push(...C(k[L]))}let S;for(let[L,C]of s)L in k&&C.v!=null&&(S==null&&(S={}),S[L]=C.v.version);let E={t:"b",u:k,...S?{v:S}:{}};try{n.post(E,x.length>0?x:void 0)}catch(L){u.down([[R,L instanceof Error?L:new Error(String(L))]])}}).subscribe(()=>{})}let p=!1,f=n.listen(b=>{if(p)return;let v=b;switch(v.t){case"r":{Y(()=>{for(let[w,k]of Object.entries(v.stores)){let x=d.get(w);x&&x.down([[R,k]])}}),a.down([[R,"connected"]]);let T={};for(let[w,k]of s)T[w]=k.cache;n.post({t:"i",stores:T});break}case"v":{let T=d.get(v.s);T&&T.down([[R,v.d]]);break}case"b":{Y(()=>{for(let[T,w]of Object.entries(v.u)){let k=v.v?.[T];if(k!=null){let S=c.get(T);if(S!=null&&k<=S)continue;c.set(T,k)}let x=d.get(T);x&&x.down([[R,w]])}});break}case"e":{let T=d.get(v.s);T&&T.down([[M,yn(v.err)]]);break}case"s":{let T=hn(v.sig);if(!T)break;let w=v.s==="*"?[...d.values()]:d.has(v.s)?[d.get(v.s)]:[];for(let k of w)k.down(v.d===void 0?[[T]]:[[T,v.d]]);break}}}),m=[];for(let[b,v]of s){let T=v.subscribe((w=>{if(!p)for(let k of w){let x=k[0];x!==R&&($e.isLocalOnly(x)||(x===M?n.post({t:"e",s:b,err:gn(k[1])}):n.post({t:"s",s:b,sig:qt(x),d:k.length>1?k[1]:void 0})))}}));m.push(T)}let g;if(e.timeoutMs!=null&&e.timeoutMs>0){let b=dt(e.timeoutMs),v=Xe(a,w=>w==="connected");g=vs(wt(Br(b,()=>"timeout"),Br(v,()=>"ready"))).subscribe(w=>{for(let k of w)k[0]===R&&k[1]==="timeout"&&(u.down([[R,new Error("Worker bridge handshake timeout")]]),h())})}function h(){if(!p){p=!0,g?.(),n.post({t:"s",s:"*",sig:qt(de)}),l&&l();for(let b of m)b();m.length=0,f(),a.down([[R,"closed"]]),c.clear(),d.clear()}}let y={meta:{status:a,error:u},destroy:h};for(let[b,v]of d)y[b]=v;return y}Ce();se();_e();Q();function lh(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function Na(t,e){let n=lh(t)?t:Wt(t),r=e.import??[],s=e.transfer??{},o=new Map,i=new Map,a={};for(let h of r){let y=N(void 0,{name:`worker::${h}`});o.set(h,y),a[h]=y}let u=e.expose(a),d=Object.entries(u),c,l=!1;if(d.length>0){let h=d.map(([,v])=>v),y=V(h,(v,T)=>{let w={};for(let k=0;k<d.length;k++){let[x]=d[k],S=v[k];S!=null&&S.length>0&&(w[x]=S.at(-1))}Object.keys(w).length!==0&&T.emit(w)},{name:"workerSelf::aggregated",partial:!0});c=le([y],v=>{if(l)return;let T=v[0];if(T==null||Object.keys(T).length===0)return;let w=[];for(let S of Object.keys(T)){let E=s[S];E&&w.push(...E(T[S]))}let k;for(let[S,E]of d)S in T&&E.v!=null&&(k==null&&(k={}),k[S]=E.v.version);let x={t:"b",u:T,...k?{v:k}:{}};try{n.post(x,w.length>0?w:void 0)}catch{}}).subscribe(()=>{})}let p=[];for(let[h,y]of d){let b=y.subscribe((v=>{if(!l)for(let T of v){let w=T[0];w!==R&&($e.isLocalOnly(w)||(w===M?n.post({t:"e",s:h,err:gn(T[1])}):n.post({t:"s",s:h,sig:qt(w),d:T.length>1?T[1]:void 0})))}}));p.push(b)}let f=n.listen(h=>{if(l)return;let y=h;switch(y.t){case"i":{Y(()=>{for(let[b,v]of Object.entries(y.stores)){let T=o.get(b);T&&T.down([[R,v]])}});break}case"v":{let b=o.get(y.s);b&&b.down([[R,y.d]]);break}case"b":{Y(()=>{for(let[b,v]of Object.entries(y.u)){let T=y.v?.[b];if(T!=null){let k=i.get(b);if(k!=null&&T<=k)continue;i.set(b,T)}let w=o.get(b);w&&w.down([[R,v]])}});break}case"e":{let b=o.get(y.s);b&&b.down([[M,yn(y.err)]]);break}case"s":{let b=hn(y.sig);if(!b)break;if(b===de&&y.s==="*"){g();return}let v=y.s==="*"?[...o.values()]:o.has(y.s)?[o.get(y.s)]:[];for(let T of v)T.down(y.d===void 0?[[b]]:[[b,y.d]]);break}}}),m={};for(let[h,y]of d)m[h]=y.cache;n.post({t:"r",stores:m});function g(){if(!l){l=!0,c&&c();for(let h of p)h();p.length=0,f(),n.terminate?.(),i.clear(),o.clear()}}return{destroy:g}}var Lu={};we(Lu,{SNAPSHOT_WIRE_VERSION:()=>vo,SurfaceError:()=>Ee,accountability:()=>ni,ai:()=>Zs,asSurfaceError:()=>wi,cqrs:()=>us,createGraph:()=>cr,deleteSnapshot:()=>_i,demoShell:()=>oi,diffSnapshots:()=>Ni,domainTemplates:()=>si,graphspec:()=>Xs,guarded:()=>ai,harness:()=>gi,jobQueue:()=>mi,layout:()=>vi,lens:()=>bi,listSnapshots:()=>Ei,memory:()=>Js,messaging:()=>Ks,orchestration:()=>Hs,reduction:()=>Qs,refine:()=>ci,resilientPipeline:()=>Ti,restoreSnapshot:()=>Si,runReduction:()=>ki,saveSnapshot:()=>Ri,surface:()=>Mi});var Zs={};we(Zs,{AgentLoopGraph:()=>Us,AllTiersExhaustedError:()=>oo,BudgetExhaustedError:()=>Is,ChatStreamGraph:()=>qs,CircuitOpenError:()=>lt,DEFAULT_DECAY_RATE:()=>tu,FallbackMissError:()=>vh,LLMTimeoutError:()=>rr,ReplayCacheMissError:()=>Tn,ToolRegistryGraph:()=>Ws,admissionFilter3D:()=>Cg,admissionScored:()=>Tp,agentLoop:()=>_g,agentMemory:()=>Dg,anthropicAdapter:()=>_a,canonicalJson:()=>Oa,cascadingLlmAdapter:()=>Ka,chatStream:()=>Ua,composePricing:()=>Fh,computePrice:()=>Pa,contentGate:()=>Rg,costMeterExtractor:()=>bg,createAdapter:()=>Lh,createCapabilitiesRegistry:()=>ph,createPricingRegistry:()=>Ph,dryRunAdapter:()=>bn,fallbackAdapter:()=>Ca,fromLLM:()=>Xh,frozenContext:()=>ng,gatedStream:()=>hg,gaugesAsContext:()=>Pg,googleAdapter:()=>Aa,graphFromSpec:()=>Cp,graphFromSpecReactive:()=>Ug,handoff:()=>Mg,keywordFlagExtractor:()=>Tg,knobsAsTools:()=>Jg,llmConsolidator:()=>Qa,llmExtractor:()=>Ya,memoryRetrieval:()=>su,memoryWithKG:()=>ru,memoryWithTiers:()=>ou,memoryWithVectors:()=>nu,observableAdapter:()=>Ih,openAICompatAdapter:()=>Ia,parseRateLimitFromError:()=>ja,pricingFor:()=>$h,promptNode:()=>wn,redactor:()=>Sg,registryPricing:()=>Gh,resilientAdapter:()=>Qh,streamExtractor:()=>wg,streamingPromptNode:()=>mg,suggestStrategy:()=>Ap,suggestStrategyReactive:()=>Qg,systemPromptBuilder:()=>gg,tier:()=>Jh,toolCallExtractor:()=>xg,toolExecution:()=>za,toolRegistry:()=>Ja,toolSelector:()=>Og,validateGraphDef:()=>Xg,withBreaker:()=>Ga,withBudgetGate:()=>$a,withDryRun:()=>Bh,withRateLimiter:()=>Va,withReplayCache:()=>ro,withRetry:()=>Ha,withTimeout:()=>qa,zeroPrice:()=>Ls});Q();function no(t,e){return`${t}::${e}`}function ph(t){let e=Ze({name:"capabilitiesRegistry"}),n=d=>{e.set(no(d.provider,d.id),d)};if(t)for(let d of t)n(d);let r=(d,c)=>{let l=e.get(no(d,c));if(l)return l;let p=e.entries.cache;if(!p)return;let f;for(let[,m]of p){if(m.provider!==d)continue;let g=m.id;c.startsWith(g)&&(!f||g.length>f.id.length)&&(f=m)}return f},s=128,o=new Map,i=new Map,a=(d,c,l,p)=>{for(d.has(c)&&d.delete(c),d.set(c,l);d.size>p;){let f=d.keys().next().value;if(f===void 0)break;d.delete(f)}},u=_([e.entries],([d])=>Array.from(d.values()),{name:"capabilitiesRegistry/entries",initial:[]});return{register:n,lookup:r,remove(d,c){let l=e.has(no(d,c));return l&&e.delete(no(d,c)),l},entries(){let d=e.entries.cache;return(function*(){if(d)for(let c of d.values())yield c})()},lookupNode(d,c){let l=no(d,c),p=o.get(l);if(p)return o.delete(l),o.set(l,p),p;let f=_([e.entries],()=>r(d,c),{name:`capabilitiesRegistry/lookup/${d}::${c}`,initial:void 0});return a(o,l,f,s),f},entriesNode:u,byProvider(d){let c=i.get(d);if(c)return i.delete(d),i.set(d,c),c;let l=_([u],([p])=>p.filter(f=>f.provider===d),{name:`capabilitiesRegistry/byProvider/${d}`,initial:[]});return a(i,d,l,s),l}}}Ne();function _a(t={}){return t.sdk?yh(t):gh(t)}function Ns(t,e,n,r){let s=e?.model??n;if(!s)throw new Error("anthropicAdapter: model must be set via options.model or invokeOpts.model");let{system:o,chat:i}=fh(t,e?.systemPrompt),a={model:s,messages:i.map(mh),max_tokens:e?.maxTokens??4096};return o&&(a.system=o),e?.temperature!=null&&(a.temperature=e.temperature),e?.tools&&e.tools.length>0&&(a.tools=e.tools.map(hh)),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 fh(t,e){let n=[];e&&n.push(e);let r=[];for(let s of t)s.role==="system"?n.push(s.content):r.push(s);return{system:n.length>0?n.join(`
33
33
 
34
- `):void 0,chat:r}}function ch(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 dh(t){return{name:t.name,description:t.description,input_schema:t.parameters}}function As(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 Ia(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 ql(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:Ia(t.usage),finishReason:t.stop_reason,latencyMs:e,model:t.model,provider:"anthropic"}}function lh(t){let e=t.apiKey??globalThis.process?.env?.ANTHROPIC_API_KEY,n=t.baseURL??"https://api.anthropic.com",r=t.anthropicVersion??"2023-06-01",o=t.fetchImpl??fetch,s=()=>{if(!e)throw new Error("anthropicAdapter: apiKey required for invoke/stream (or provide opts.sdk)");return{"x-api-key":e,"anthropic-version":r,"content-type":"application/json",...t.headers??{}}};return{provider:"anthropic",model:t.model,async invoke(i,a){let u=Cs(i,a,t.model,!1),c=j(),d=await o(`${n}/v1/messages`,{method:"POST",headers:s(),body:JSON.stringify(u),signal:a?.signal});if(!d.ok)throw await ht(d,"Anthropic");let l=await d.json(),p=Math.max(0,(j()-c)/1e6);return ql(l,p)},async*stream(i,a){let u=Cs(i,a,t.model,!0),c=await o(`${n}/v1/messages`,{method:"POST",headers:{...s(),accept:"text/event-stream"},body:JSON.stringify(u),signal:a?.signal});if(!c.ok)throw await ht(c,"Anthropic");if(!c.body)throw new Error("anthropicAdapter: streaming response has no body");let d,l,p=new Map;for await(let f of Lt(c.body,{signal:a?.signal})){let m=f.data;if(!m)continue;let g;try{g=JSON.parse(m)}catch{continue}switch(g.type){case"message_start":{d=As(d,g.message.usage);break}case"content_block_start":{let h=g,y=h.content_block;y.type==="tool_use"&&(p.set(h.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 h=g,y=h.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(h.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 h=g;h.delta.stop_reason&&(l=h.delta.stop_reason),h.delta.usage&&(d=As(d,h.delta.usage));break}case"message_stop":break}}d&&(yield{type:"usage",usage:Ia(d)}),yield{type:"finish",reason:l??"stop"}}}}function ph(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=Cs(n,r,t.model,!1),s=j(),i=await e.messages.create(o,{signal:r?.signal}),a=Math.max(0,(j()-s)/1e6);return ql(i,a)},async*stream(n,r){if(!e.messages.stream)throw new Error("sdkBackedAnthropic: SDK instance does not expose .messages.stream");let o=Cs(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=As(s,a.message.usage);break;case"content_block_delta":{let u=a.delta;u?.type==="text_delta"&&typeof u.text=="string"?yield{type:"token",delta:u.text}:u?.type==="input_json_delta"&&typeof u.partial_json=="string"?yield{type:"tool-call-delta",delta:{argumentsDelta:u.partial_json}}:u?.type==="thinking_delta"&&typeof u.thinking=="string"&&(yield{type:"thinking",delta:u.thinking});break}case"message_delta":{let u=a;u.delta.stop_reason&&(i=u.delta.stop_reason),u.delta.usage&&(s=As(s,u.delta.usage));break}}s&&(yield{type:"usage",usage:Ia(s)}),yield{type:"finish",reason:i??"stop"}}}}vt();function Ls(){let t=new Error("aborted");return t.name="AbortError",t}function Ul(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Ls()):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(Ls())},e.addEventListener("abort",s,{once:!0}))})}function vn(t={}){let e=t.provider??"dry-run",n=t.model??"dry-run-v1",r=t.latencyMs??0,o=Math.max(1,t.streamChunkSize??16),s=t.respond??(a=>{let u=[...a].reverse().find(c=>c.role==="user");return u?`echo: ${u.content}`:"dry-run: no user message"}),i=t.usage??((a,u)=>{let c=a.reduce((d,l)=>d+l.content.length,0);return{input:{regular:Math.ceil(c/4)},output:{regular:Math.ceil(u.length/4)}}});return{provider:e,model:n,async invoke(a,u){if(await Ul(r,u?.signal),u?.signal?.aborted)throw Ls();let c=s(a,u),d=i(a,c);return{content:c,usage:d,finishReason:"stop",model:u?.model??n,provider:e,tier:u?.tier,metadata:{dryRun:!0}}},async*stream(a,u){let c=s(a,u),d=i(a,c),l=Math.ceil(c.length/o)||1,p=r>0?r/l:0;for(let f=0;f<c.length;f+=o){if(u?.signal?.aborted)throw Ls();await Ul(p,u?.signal),yield{type:"token",delta:c.slice(f,f+o)}}yield{type:"usage",usage:d},yield{type:"finish",reason:"stop"}}}}_e();_e();Re();vt();function zl(t){let{storage:e,mode:n="read-write",keyFn:r,keyPrefix:o="llm-replay"}=t,i=_s({storage:e,keyPrefix:o,mode:n==="read-strict"?"read":n,keyContext:({messages:u,opts:c})=>{let{signal:d,keyContext:l,...p}=c??{};return{messages:u,opts:p}}});async function a(u,c){if(r){if(r.length<=1){let l={messages:u,opts:c,context:c?.keyContext},p=await r(l);return`${o}:${p}`}let d=await r(u,c);return`${o}:${d}`}return i.keyFor({messages:u,opts:c})}return{keyFor:a,async lookup(u,c){if(n!=="write"){if(r){let d=await a(u,c),l=await e.load(d);return l??void 0}return i.lookup({messages:u,opts:c})}},async store(u,c,d){if(n!=="read"){if(r){let l=await a(u,c);await e.save(l,d);return}await i.store({messages:u,opts:c},d)}},async forget(u,c){if(!(n==="read"||n==="write")&&e.clear){if(r){let d=await a(u,c);await e.clear(d);return}await i.forget({messages:u,opts:c})}}}}_e();ae();ee();Re();function Ze(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 Is(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=X(t);if(r){let c=!1;s.subscribe(d=>{for(let l of d){if(c)return;l[0]===O&&(c=!0,r(l[1]))}})}let i,a=!1,u=Kr(s,c=>{i=n(c),a=!0});return _([u],([c])=>c==null?null:a?i:n(c),{name:o??"adapt/invokeTap"})}function Tn(t){let e=t.endNs??j();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 kt(){return{input:{regular:0},output:{regular:0}}}var Jl=Symbol.for("graphrefly.adapter.middlewareLayers");function Je(t,e,n){let o=[...n?fh(n):[],e];return Object.defineProperty(t,Jl,{value:Object.freeze(o),enumerable:!1,writable:!1,configurable:!1}),t}function fh(t){let e=t[Jl];return Array.isArray(e)?e:[]}var wn=class extends Error{constructor(n,r){super(`withReplayCache: no cached response for ${r} (key=${n}, mode=read-strict)`);this.key=n;this.method=r}name="ReplayCacheMissError"};function ro(t,e){let n=e.mode??"read-write",r=e.cacheStreaming??!1,o=e.captureStreamCadence??!1,s=e.replaySpeed??1,i=e.keyPrefix??"llm-replay",a=n==="read"||n==="read-strict",u=zl({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=Os(async({messages:p,invokeOpts:f})=>await Qe(X(t.invoke(p,f))),{keyFn:({_precomputedKey:p})=>p}),l=Ze(t,{async invoke(p,f){let m=await u.keyFor(p,f),g=await u.lookup(p,f);if(g?.response){let y=g.response;return{...y,metadata:{...y.metadata??{},replayCache:"hit"}}}if(n==="read-strict")throw new wn(m,"invoke");let h=await d({messages:p,invokeOpts:f,_precomputedKey:m});return a||await u.store(p,f,{response:h,storedAtNs:Te()}),h},async*stream(p,f){if(!r){for await(let k of t.stream(p,f))yield k;return}let m=await u.keyFor(p,f),g=await u.lookup(p,f);if(g){let k=g.response;if(g.streamChunks&&g.streamCadenceMs)for(let x=0;x<g.streamChunks.length;x++){let R=g.streamCadenceMs[x]??0,N=s>0?R/s:0;N>0&&await c(N),yield{type:"token",delta:g.streamChunks[x]?.delta??""}}else k.content&&(yield{type:"token",delta:k.content});k.usage&&(yield{type:"usage",usage:k.usage}),yield{type:"finish",reason:k.finishReason??"stop"};return}if(n==="read-strict")throw new wn(m,"stream");let h="",y,b,v=[],T=[],w;for await(let k of t.stream(p,f)){if(k.type==="token"&&(h+=k.delta,o)){let x=j(),R=w===void 0?0:(x-w)/1e6;T.push(R),w=x,v.push({delta:k.delta})}k.type==="usage"&&(y=k.usage),k.type==="finish"&&(b=k.reason),yield k}if((h||y)&&!a){let x={response:{content:h,usage:y??{input:{regular:0},output:{regular:0}},finishReason:b,model:t.model??f?.model??"",provider:t.provider},storedAtNs:Te(),...o?{streamChunks:v,streamCadenceMs:T}:{}};await u.store(p,f,x)}}});return Je(l,"withReplayCache",t),l}var Da=Jr;var mh=wn;function Yl(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 Ql(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 hh(t,e){if("key"in t)return t.key;let n=Da({messages:t.messages,opts:t.invokeOpts??{}}),r=await Es(n);return`${e}:${r}`}function gh(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 yh(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=eo(),o=t.fixtures,s=(async()=>{for(let i of o){let a=await hh(i,e);await r.save(a,gh(i))}})();return s.catch(()=>{}),{tier:r,seedReady:s}}return t.fixturesStorage?{tier:t.fixturesStorage,seedReady:Promise.resolve()}:{tier:void 0,seedReady:Promise.resolve()}}function Pa(t={}){let e=t.provider??"fallback",n=t.model??"fallback",r=t.onMiss??"respond",o=t.keyPrefix??"fallback",s=t.record?t.record.adapter:r==="throw"?vn({provider:e,model:n,respond:()=>"[unreachable: read-strict mode throws on miss]"}):{provider:e,model:n,async invoke(d,l){let p=t.respond?t.respond(d,l):Yl(e,n);return Ql(p,e,n)},async*stream(d,l){let p=t.respond?t.respond(d,l):Yl(e,n),f=Ql(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=yh(t,o);i=d.tier??eo(),a=d.seedReady}let u=t.record?"read-write":r==="throw"?"read-strict":"read",c=ro(s,{storage:i,mode:u,keyPrefix:o,cacheStreaming:!0,captureStreamCadence:!0,replaySpeed:t.replaySpeed,...t.keyFn?{keyFn:t.keyFn}:{}});return{provider:e,model:n,capabilities:c.capabilities?.bind(c),async invoke(d,l){return await a,c.invoke(d,l)},async*stream(d,l){await a;for await(let p of c.stream(d,l))yield p}}}_e();function Ga(t={}){return t.sdk?wh(t):Th(t)}function Ds(t,e){let n=[],r=[];e?.systemPrompt&&n.push(e.systemPrompt);for(let i of t){if(i.role==="system"){n.push(i.content);continue}if(i.role==="tool"){r.push({role:"user",parts:[{functionResponse:{name:i.name??i.toolCallId??"tool",response:{result:i.content}}}]});continue}if(i.role==="assistant"&&i.toolCalls&&i.toolCalls.length>0){let a=[];i.content&&a.push({text:i.content});for(let u of i.toolCalls)a.push({functionCall:{name:u.name,args:u.arguments}});r.push({role:"model",parts:a});continue}r.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let o={contents:r};n.length>0&&(o.systemInstruction={role:"system",parts:[{text:n.join(`
34
+ `):void 0,chat:r}}function mh(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 hh(t){return{name:t.name,description:t.description,input_schema:t.parameters}}function Es(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 Ma(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 Jl(t,e){let n=[],r=[];for(let s of t.content)if(s.type==="text"&&typeof s.text=="string")n.push(s.text);else if(s.type==="tool_use"){let o=s;r.push({id:o.id,name:o.name,arguments:o.input??{}})}return{content:n.join(""),toolCalls:r.length>0?r:void 0,usage:Ma(t.usage),finishReason:t.stop_reason,latencyMs:e,model:t.model,provider:"anthropic"}}function gh(t){let e=t.apiKey??globalThis.process?.env?.ANTHROPIC_API_KEY,n=t.baseURL??"https://api.anthropic.com",r=t.anthropicVersion??"2023-06-01",s=t.fetchImpl??fetch,o=()=>{if(!e)throw new Error("anthropicAdapter: apiKey required for invoke/stream (or provide opts.sdk)");return{"x-api-key":e,"anthropic-version":r,"content-type":"application/json",...t.headers??{}}};return{provider:"anthropic",model:t.model,async invoke(i,a){let u=Ns(i,a,t.model,!1),d=F(),c=await s(`${n}/v1/messages`,{method:"POST",headers:o(),body:JSON.stringify(u),signal:a?.signal});if(!c.ok)throw await ht(c,"Anthropic");let l=await c.json(),p=Math.max(0,(F()-d)/1e6);return Jl(l,p)},async*stream(i,a){let u=Ns(i,a,t.model,!0),d=await s(`${n}/v1/messages`,{method:"POST",headers:{...o(),accept:"text/event-stream"},body:JSON.stringify(u),signal:a?.signal});if(!d.ok)throw await ht(d,"Anthropic");if(!d.body)throw new Error("anthropicAdapter: streaming response has no body");let c,l,p=new Map;for await(let f of Lt(d.body,{signal:a?.signal})){let m=f.data;if(!m)continue;let g;try{g=JSON.parse(m)}catch{continue}switch(g.type){case"message_start":{c=Es(c,g.message.usage);break}case"content_block_start":{let h=g,y=h.content_block;y.type==="tool_use"&&(p.set(h.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 h=g,y=h.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(h.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 h=g;h.delta.stop_reason&&(l=h.delta.stop_reason),h.delta.usage&&(c=Es(c,h.delta.usage));break}case"message_stop":break}}c&&(yield{type:"usage",usage:Ma(c)}),yield{type:"finish",reason:l??"stop"}}}}function yh(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 s=Ns(n,r,t.model,!1),o=F(),i=await e.messages.create(s,{signal:r?.signal}),a=Math.max(0,(F()-o)/1e6);return Jl(i,a)},async*stream(n,r){if(!e.messages.stream)throw new Error("sdkBackedAnthropic: SDK instance does not expose .messages.stream");let s=Ns(n,r,t.model,!0),o,i;for await(let a of e.messages.stream(s,{signal:r?.signal}))switch(a.type){case"message_start":o=Es(o,a.message.usage);break;case"content_block_delta":{let u=a.delta;u?.type==="text_delta"&&typeof u.text=="string"?yield{type:"token",delta:u.text}:u?.type==="input_json_delta"&&typeof u.partial_json=="string"?yield{type:"tool-call-delta",delta:{argumentsDelta:u.partial_json}}:u?.type==="thinking_delta"&&typeof u.thinking=="string"&&(yield{type:"thinking",delta:u.thinking});break}case"message_delta":{let u=a;u.delta.stop_reason&&(i=u.delta.stop_reason),u.delta.usage&&(o=Es(o,u.delta.usage));break}}o&&(yield{type:"usage",usage:Ma(o)}),yield{type:"finish",reason:i??"stop"}}}}vt();function _s(){let t=new Error("aborted");return t.name="AbortError",t}function Yl(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(_s()):new Promise((n,r)=>{let s=new Le,o,i=()=>{s.cancel(),e&&o&&e.removeEventListener("abort",o)};s.start(t,()=>{i(),n()}),e&&(o=()=>{i(),r(_s())},e.addEventListener("abort",o,{once:!0}))})}function bn(t={}){let e=t.provider??"dry-run",n=t.model??"dry-run-v1",r=t.latencyMs??0,s=Math.max(1,t.streamChunkSize??16),o=t.respond??(a=>{let u=[...a].reverse().find(d=>d.role==="user");return u?`echo: ${u.content}`:"dry-run: no user message"}),i=t.usage??((a,u)=>{let d=a.reduce((c,l)=>c+l.content.length,0);return{input:{regular:Math.ceil(d/4)},output:{regular:Math.ceil(u.length/4)}}});return{provider:e,model:n,async invoke(a,u){if(await Yl(r,u?.signal),u?.signal?.aborted)throw _s();let d=o(a,u),c=i(a,d);return{content:d,usage:c,finishReason:"stop",model:u?.model??n,provider:e,tier:u?.tier,metadata:{dryRun:!0}}},async*stream(a,u){let d=o(a,u),c=i(a,d),l=Math.ceil(d.length/s)||1,p=r>0?r/l:0;for(let f=0;f<d.length;f+=s){if(u?.signal?.aborted)throw _s();await Yl(p,u?.signal),yield{type:"token",delta:d.slice(f,f+s)}}yield{type:"usage",usage:c},yield{type:"finish",reason:"stop"}}}}Ne();Ne();Te();vt();function Ql(t){let{storage:e,mode:n="read-write",keyFn:r,keyPrefix:s="llm-replay"}=t,i=xs({storage:e,keyPrefix:s,mode:n==="read-strict"?"read":n,keyContext:({messages:u,opts:d})=>{let{signal:c,keyContext:l,...p}=d??{};return{messages:u,opts:p}}});async function a(u,d){if(r){if(r.length<=1){let l={messages:u,opts:d,context:d?.keyContext},p=await r(l);return`${s}:${p}`}let c=await r(u,d);return`${s}:${c}`}return i.keyFor({messages:u,opts:d})}return{keyFor:a,async lookup(u,d){if(n!=="write"){if(r){let c=await a(u,d),l=await e.load(c);return l??void 0}return i.lookup({messages:u,opts:d})}},async store(u,d,c){if(n!=="read"){if(r){let l=await a(u,d);await e.save(l,c);return}await i.store({messages:u,opts:d},c)}},async forget(u,d){if(!(n==="read"||n==="write")&&e.clear){if(r){let c=await a(u,d);await e.clear(c);return}await i.forget({messages:u,opts:d})}}}}Ne();se();Q();Te();function et(t,e,n){return{provider:n?.provider??t.provider,model:n?.model??t.model,capabilities:n?.capabilities??t.capabilities?.bind(t),invoke:e.invoke,stream:e.stream}}function Ms(t,e){let{onResp:n,onError:r,name:s}=e;if(t!=null&&typeof t.then=="function"){let d=t;return r?d.then(n).catch(c=>{throw r(c),c}):d.then(n)}if(t!=null&&typeof t=="object"&&"content"in t)return n(t);let o=W(t);if(r){let d=!1;o.subscribe(c=>{for(let l of c){if(d)return;l[0]===M&&(d=!0,r(l[1]))}})}let i,a=!1,u=Kr(o,d=>{i=n(d),a=!0});return _([u],([d])=>d==null?null:a?i:n(d),{name:s??"adapt/invokeTap"})}function vn(t){let e=t.endNs??F();return{timestamp:e,wallClock:t.startWallClockNs??ce(),provider:t.provider,model:t.model,tier:t.tier,usage:t.usage,latencyMs:Math.max(0,(e-t.startNs)/1e6),method:t.method,...t.error?{error:t.error}:{}}}function kt(){return{input:{regular:0},output:{regular:0}}}var Xl=Symbol.for("graphrefly.adapter.middlewareLayers");function Je(t,e,n){let s=[...n?bh(n):[],e];return Object.defineProperty(t,Xl,{value:Object.freeze(s),enumerable:!1,writable:!1,configurable:!1}),t}function bh(t){let e=t[Xl];return Array.isArray(e)?e:[]}var Tn=class extends Error{constructor(n,r){super(`withReplayCache: no cached response for ${r} (key=${n}, mode=read-strict)`);this.key=n;this.method=r}name="ReplayCacheMissError"};function ro(t,e){let n=e.mode??"read-write",r=e.cacheStreaming??!1,s=e.captureStreamCadence??!1,o=e.replaySpeed??1,i=e.keyPrefix??"llm-replay",a=n==="read"||n==="read-strict",u=Ql({storage:e.storage,mode:n==="write-only"?"write":n,keyFn:e.keyFn,keyPrefix:i}),d=p=>p<=0?Promise.resolve():new Promise(f=>{new Le().start(p,()=>f())}),c=Ss(async({messages:p,invokeOpts:f})=>await Qe(W(t.invoke(p,f))),{keyFn:({_precomputedKey:p})=>p}),l=et(t,{async invoke(p,f){let m=await u.keyFor(p,f),g=await u.lookup(p,f);if(g?.response){let y=g.response;return{...y,metadata:{...y.metadata??{},replayCache:"hit"}}}if(n==="read-strict")throw new Tn(m,"invoke");let h=await c({messages:p,invokeOpts:f,_precomputedKey:m});return a||await u.store(p,f,{response:h,storedAtNs:ce()}),h},async*stream(p,f){if(!r){for await(let k of t.stream(p,f))yield k;return}let m=await u.keyFor(p,f),g=await u.lookup(p,f);if(g){let k=g.response;if(g.streamChunks&&g.streamCadenceMs)for(let x=0;x<g.streamChunks.length;x++){let S=g.streamCadenceMs[x]??0,E=o>0?S/o:0;E>0&&await d(E),yield{type:"token",delta:g.streamChunks[x]?.delta??""}}else k.content&&(yield{type:"token",delta:k.content});k.usage&&(yield{type:"usage",usage:k.usage}),yield{type:"finish",reason:k.finishReason??"stop"};return}if(n==="read-strict")throw new Tn(m,"stream");let h="",y,b,v=[],T=[],w;for await(let k of t.stream(p,f)){if(k.type==="token"&&(h+=k.delta,s)){let x=F(),S=w===void 0?0:(x-w)/1e6;T.push(S),w=x,v.push({delta:k.delta})}k.type==="usage"&&(y=k.usage),k.type==="finish"&&(b=k.reason),yield k}if((h||y)&&!a){let x={response:{content:h,usage:y??{input:{regular:0},output:{regular:0}},finishReason:b,model:t.model??f?.model??"",provider:t.provider},storedAtNs:ce(),...s?{streamChunks:v,streamCadenceMs:T}:{}};await u.store(p,f,x)}}});return Je(l,"withReplayCache",t),l}var Oa=Jr;var vh=Tn;function Zl(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 ep(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 Th(t,e){if("key"in t)return t.key;let n=Oa({messages:t.messages,opts:t.invokeOpts??{}}),r=await ks(n);return`${e}:${r}`}function wh(t){let e={response:t.response,storedAtNs:ce()};if("key"in t&&t.stream){let n=t.stream.chunks.filter(r=>r.type==="token");return{...e,streamChunks:n.map(r=>({delta:r.delta})),streamCadenceMs:t.stream.delaysMs??n.map(()=>0)}}return e}function kh(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=eo(),s=t.fixtures,o=(async()=>{for(let i of s){let a=await Th(i,e);await r.save(a,wh(i))}})();return o.catch(()=>{}),{tier:r,seedReady:o}}return t.fixturesStorage?{tier:t.fixturesStorage,seedReady:Promise.resolve()}:{tier:void 0,seedReady:Promise.resolve()}}function Ca(t={}){let e=t.provider??"fallback",n=t.model??"fallback",r=t.onMiss??"respond",s=t.keyPrefix??"fallback",o=t.record?t.record.adapter:r==="throw"?bn({provider:e,model:n,respond:()=>"[unreachable: read-strict mode throws on miss]"}):{provider:e,model:n,async invoke(c,l){let p=t.respond?t.respond(c,l):Zl(e,n);return ep(p,e,n)},async*stream(c,l){let p=t.respond?t.respond(c,l):Zl(e,n),f=ep(p,e,n);yield{type:"token",delta:f.content},f.usage&&(yield{type:"usage",usage:f.usage}),yield{type:"finish",reason:f.finishReason??"stop"}}},i,a=Promise.resolve();if(t.record){if(!t.record.storage)throw new TypeError("fallbackAdapter: `record.storage` is required in record mode. For filesystem `record.dir` convenience, use the node subpath's `fallbackAdapter`.");i=t.record.storage}else{let c=kh(t,s);i=c.tier??eo(),a=c.seedReady}let u=t.record?"read-write":r==="throw"?"read-strict":"read",d=ro(o,{storage:i,mode:u,keyPrefix:s,cacheStreaming:!0,captureStreamCadence:!0,replaySpeed:t.replaySpeed,...t.keyFn?{keyFn:t.keyFn}:{}});return{provider:e,model:n,capabilities:d.capabilities?.bind(d),async invoke(c,l){return await a,d.invoke(c,l)},async*stream(c,l){await a;for await(let p of d.stream(c,l))yield p}}}Ne();function Aa(t={}){return t.sdk?Nh(t):Sh(t)}function Os(t,e){let n=[],r=[];e?.systemPrompt&&n.push(e.systemPrompt);for(let i of t){if(i.role==="system"){n.push(i.content);continue}if(i.role==="tool"){r.push({role:"user",parts:[{functionResponse:{name:i.name??i.toolCallId??"tool",response:{result:i.content}}}]});continue}if(i.role==="assistant"&&i.toolCalls&&i.toolCalls.length>0){let a=[];i.content&&a.push({text:i.content});for(let u of i.toolCalls)a.push({functionCall:{name:u.name,args:u.arguments}});r.push({role:"model",parts:a});continue}r.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let s={contents:r};n.length>0&&(s.systemInstruction={role:"system",parts:[{text:n.join(`
35
35
 
36
- `)}]});let s={};return e?.maxTokens!=null&&(s.maxOutputTokens=e.maxTokens),e?.temperature!=null&&(s.temperature=e.temperature),e?.maxReasoningTokens!=null&&(s.thinkingConfig={thinkingBudget:e.maxReasoningTokens}),Object.keys(s).length>0&&(o.generationConfig=s),e?.tools&&e.tools.length>0&&(o.tools=[{functionDeclarations:e.tools.map(bh)}]),e?.providerExtras&&Object.assign(o,e.providerExtras),o}function bh(t){return{name:t.name,description:t.description,parameters:t.parameters}}function Fa(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 Xl(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:Fa(t.usageMetadata),finishReason:n?.finishReason,latencyMs:e,model:t.modelVersion,provider:"google"}}function vh(t){if(t.apiKey)return t.apiKey;let e=globalThis.process?.env;return e?.GOOGLE_API_KEY??e?.GEMINI_API_KEY}function Th(t){let e=t.baseURL??"https://generativelanguage.googleapis.com/v1beta",n=t.fetchImpl??fetch,r=s=>{let i=s?.model??t.model;if(!i)throw new Error("googleAdapter: model must be set via options.model or invokeOpts.model");return i},o=()=>{let s=vh(t);if(!s)throw new Error("googleAdapter: apiKey required for invoke/stream");return`key=${encodeURIComponent(s)}`};return{provider:"google",model:t.model,async invoke(s,i){let a=r(i),u=Ds(s,i),c=j(),d=`${e}/models/${encodeURIComponent(a)}:generateContent?${o()}`,l=await n(d,{method:"POST",headers:{"content-type":"application/json",...t.headers??{}},body:JSON.stringify(u),signal:i?.signal});if(!l.ok)throw await ht(l,"Google");let p=await l.json(),f=Math.max(0,(j()-c)/1e6);return Xl(p,f)},async*stream(s,i){let a=r(i),u=Ds(s,i),c=`${e}/models/${encodeURIComponent(a)}:streamGenerateContent?alt=sse&${o()}`,d=await n(c,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",...t.headers??{}},body:JSON.stringify(u),signal:i?.signal});if(!d.ok)throw await ht(d,"Google");if(!d.body)throw new Error("googleAdapter: streaming response has no body");let l,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 g=m.candidates?.[0];for(let h of g?.content?.parts??[])typeof h.text=="string"&&(h.thought?yield{type:"thinking",delta:h.text}:yield{type:"token",delta:h.text}),h.functionCall&&(yield{type:"tool-call-delta",delta:{name:h.functionCall.name,argumentsDelta:JSON.stringify(h.functionCall.args??{})}});g?.finishReason&&(p=g.finishReason),m.usageMetadata&&(l=m.usageMetadata)}l&&(yield{type:"usage",usage:Fa(l)}),yield{type:"finish",reason:p??"stop"}}}}function wh(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=Ds(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=j(),a=await e.models.generateContent({...o,model:s},{signal:r?.signal}),u=Math.max(0,(j()-i)/1e6);return Xl(a,u)},async*stream(n,r){if(!e.models.generateContentStream)throw new Error("sdkBackedGoogle: SDK instance does not expose generateContentStream");let o=Ds(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i,a;for await(let u of e.models.generateContentStream({...o,model:s},{signal:r?.signal})){let c=u.candidates?.[0];for(let d of c?.content?.parts??[])typeof d.text=="string"&&(d.thought?yield{type:"thinking",delta:d.text}:yield{type:"token",delta:d.text}),d.functionCall&&(yield{type:"tool-call-delta",delta:{name:d.functionCall.name,argumentsDelta:JSON.stringify(d.functionCall.args??{})}});c?.finishReason&&(a=c.finishReason),u.usageMetadata&&(i=u.usageMetadata)}i&&(yield{type:"usage",usage:Fa(i)}),yield{type:"finish",reason:a??"stop"}}}}_e();var kh={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 $a(t={}){return t.sdk?Eh(t):Nh(t)}function Ps(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(xh);e?.systemPrompt&&!t.some(u=>u.role==="system")&&i.unshift({role:"system",content:e.systemPrompt});let a={model:s,messages:i};return e?.maxTokens!=null&&(a.max_tokens=e.maxTokens),e?.temperature!=null&&(a.temperature=e.temperature),e?.tools&&e.tools.length>0&&(a.tools=e.tools.map(Rh)),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 xh(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 Rh(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}}function ja(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 Zl(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:Sh(a.function.arguments)}));return{content:s,toolCalls:i.length>0?i:void 0,usage:ja(t.usage),finishReason:r?.finish_reason,latencyMs:e,model:t.model,provider:n}}function Sh(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!=null?e:{_raw:t}}catch{return{_raw:t}}}function ep(t){let e=t.preset??"openai",n=kh[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 Nh(t){let{provider:e,baseURL:n,apiKey:r}=ep(t),o=t.fetchImpl??fetch,s=e!=="ollama",i=()=>{let a={"content-type":"application/json",...t.headers??{}};if(s){if(!r)throw new Error(`openAICompatAdapter[${e}]: apiKey required for invoke/stream`);a.authorization=`Bearer ${r}`}return a};return{provider:e,model:t.model,async invoke(a,u){let c=Ps(a,u,t.model,!1,t.bodyExtras),d=j(),l=await o(`${n}/chat/completions`,{method:"POST",headers:i(),body:JSON.stringify(c),signal:u?.signal});if(!l.ok)throw await ht(l,e);let p=await l.json(),f=Math.max(0,(j()-d)/1e6);return Zl(p,f,e)},async*stream(a,u){let c=Ps(a,u,t.model,!0,t.bodyExtras),d=await o(`${n}/chat/completions`,{method:"POST",headers:{...i(),accept:"text/event-stream"},body:JSON.stringify(c),signal:u?.signal});if(!d.ok)throw await ht(d,e);if(!d.body)throw new Error(`openAICompatAdapter[${e}]: streaming response has no body`);let l,p;for await(let f of Lt(d.body,{signal:u?.signal})){if(!f.data||f.data==="[DONE]")continue;let m;try{m=JSON.parse(f.data)}catch{continue}let g=m.choices;if(g){let h=g[0];if(h?.delta?.content&&(yield{type:"token",delta:h.delta.content}),h?.delta?.reasoning_content&&(yield{type:"thinking",delta:h.delta.reasoning_content}),h?.delta?.tool_calls)for(let y of h.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:y.id,name:y.function?.name,argumentsDelta:y.function?.arguments}};h?.finish_reason&&(p=h.finish_reason)}m.usage&&(l=m.usage,yield{type:"usage",usage:ja(l)})}yield{type:"finish",reason:p??"stop"}}}}function Eh(t){let e=t.sdk;if(!e)throw new Error("sdkBackedOpenAI: sdk instance required");let{provider:n}=ep(t);return{provider:n,model:t.model,async invoke(r,o){let s=Ps(r,o,t.model,!1,t.bodyExtras),i=j(),a=await e.chat.completions.create(s,{signal:o?.signal}),u=Math.max(0,(j()-i)/1e6);return Zl(a,u,n)},async*stream(r,o){let s=Ps(r,o,t.model,!0,t.bodyExtras),i=await e.chat.completions.create(s,{signal:o?.signal}),a,u;for await(let c of i){let d=c.choices;if(d){let 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&&(u=p.finish_reason)}let l=c.usage;l&&(a=l,yield{type:"usage",usage:ja(l)})}yield{type:"finish",reason:u??"stop"}}}}function _h(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 La(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 Ga(e)}case"dry-run":{let e={model:t.model,...t.extras};return vn(e)}case"fallback":{let e={provider:t.provider,model:t.model,...t.extras};return Pa(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 $a(e)}default:{let e=t.provider;throw new Error(`createAdapter: unknown provider: ${String(e)}`)}}}_e();ee();Re();function gt(t){let e=t.input,n=e.regular+(e.cacheRead??0)+(e.cacheWrite5m??0)+(e.cacheWrite1h??0)+(e.cacheWriteOther??0)+(e.audio??0)+(e.image??0)+(e.video??0)+(e.toolUse??0);if(!e.extensions)return n;let r=0;for(let o of Object.values(e.extensions))r+=o;return n+r}function It(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 tp(){return{input:{regular:0},output:{regular:0}}}function Mh(t,e){let n=e?.logMax??1e3,r=Ue(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:n}),o=E(null,{name:"adapterStats/lastCall"}),s=_([r.entries],([g])=>g.length,{name:"adapterStats/totalCalls",initial:0}),i=_([r.entries],([g])=>g.reduce((h,y)=>h+gt(y.usage),0),{name:"adapterStats/totalInputTokens",initial:0}),a=_([r.entries],([g])=>g.reduce((h,y)=>h+It(y.usage),0),{name:"adapterStats/totalOutputTokens",initial:0}),u=[se(s),se(i),se(a)],c=g=>{r.append(g),o.emit(g)},d=()=>{r.clear(),o.emit(null)},l=Ze(t,{invoke(g,h){let y=j(),b=Te(),v=t.model??h?.model??"",T=k=>(c(Tn({provider:t.provider,model:t.model??h?.model??k.model??"",tier:h?.tier??k.tier,usage:k.usage??kt(),startNs:y,startWallClockNs:b,method:"invoke"})),k),w=k=>{let x=k;c(Tn({provider:t.provider,model:v,tier:h?.tier,usage:kt(),startNs:y,startWallClockNs:b,method:"invoke",error:{type:x?.name??"Error",message:x?.message??String(k)}}))};return Is(t.invoke(g,h),{onResp:T,onError:w,name:"adapterStats/invokeTap"})},async*stream(g,h){let y=j(),b=Te(),v=t.model??h?.model??"",T;try{for await(let w of t.stream(g,h))w.type==="usage"&&(T=w.usage),yield w;c(Tn({provider:t.provider,model:v,tier:h?.tier,usage:T??kt(),startNs:y,startWallClockNs:b,method:"stream"}))}catch(w){let k=w;throw c(Tn({provider:t.provider,model:v,tier:h?.tier,usage:T??kt(),startNs:y,startWallClockNs:b,method:"stream",error:{type:k?.name??"Error",message:k?.message??String(w)}})),w}}});Je(l,"observableAdapter",t);let p=!1;return{adapter:l,stats:{lastCall:o,allCalls:r,totalCalls:s,totalInputTokens:i,totalOutputTokens:a,reset:d,dispose:()=>{if(!p){p=!0;for(let g of u)g();u.length=0}}}}}function Oh(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function Fs(t="USD"){return{total:0,currency:t}}function Ba(t,e,n){let r=gt(t),o=e.currency??"USD",s=n?.withBreakdown===!0,i=s?{}:null,a=0,u=(h,y,b)=>{if(!y||b==null)return;let v=Oh(b,r),T=y*v/1e6;a+=T,s&&(i[h]=(i[h]??0)+T)},c=t.input,d=e.input;if(d&&(u("input.regular",c.regular,d.regular),u("input.cacheRead",c.cacheRead??0,d.cacheRead),u("input.cacheWrite5m",c.cacheWrite5m??0,d.cacheWrite5m),u("input.cacheWrite1h",c.cacheWrite1h??0,d.cacheWrite1h),u("input.cacheWriteOther",c.cacheWriteOther??0,d.cacheWriteOther),u("input.audio",c.audio??0,d.audio),u("input.image",c.image??0,d.image),u("input.video",c.video??0,d.video),u("input.toolUse",c.toolUse??0,d.toolUse),c.extensions&&d.extensions))for(let[h,y]of Object.entries(c.extensions))u(`input.ext.${h}`,y,d.extensions[h]);let l=t.output,p=e.output;if(p&&(u("output.regular",l.regular,p.regular),u("output.reasoning",l.reasoning??0,p.reasoning),u("output.audio",l.audio??0,p.audio),u("output.predictionAccepted",l.predictionAccepted??0,p.predictionAccepted),u("output.predictionRejected",l.predictionRejected??0,p.predictionRejected),l.extensions&&p.extensions))for(let[h,y]of Object.entries(l.extensions))u(`output.ext.${h}`,y,p.extensions[h]);let f=n?.tier;if(f&&e.tierMultipliers){let h=e.tierMultipliers[f];if(h!=null&&(a*=h,s))for(let y of Object.keys(i))i[y]*=h}let m=t.auxiliary,g=e.auxiliary;if(m&&g)for(let[h,y]of Object.entries(m)){let b=g[h];if(b==null||!y)continue;let v=y*b;a+=v,s&&(i[`auxiliary.${h}`]=v)}return s?{total:a,currency:o,breakdown:i}:{total:a,currency:o}}function Gs(t,e){return`${t}::${e}`}function Ch(t){let e=new Map,n=new Map,r=(o,s,i)=>{e.set(Gs(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(Gs(o,s));if(i)return i.pricing;let a=n.get(o);if(!a)return;let u;for(let c of a)if(s.startsWith(c)&&(!u||c.length>u.key.length)){let d=e.get(Gs(o,c));d&&(u={key:c,pricing:d.pricing})}return u?.pricing},remove(o,s){let i=e.delete(Gs(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 Ah(t,e="USD"){return(n,r)=>{let o=t.lookup(r.provider,r.model);return o?Ba(n,o,{tier:r.tier,withBreakdown:r.withBreakdown}):Fs(e)}}function Lh(...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):Fs()}}function Ih(t,e,n){return t?.pricing?Ba(e,t.pricing,n):Fs()}Et();Re();function Va(t,e={}){let n=e.breaker??Tt(e),r=Ze(t,{async invoke(o,s){if(!n.canExecute())throw new lt;try{let i=await Qe(X(t.invoke(o,s)));return n.recordSuccess(),i}catch(i){throw n.recordFailure(i),i}},async*stream(o,s){if(!n.canExecute())throw new lt;try{for await(let i of t.stream(o,s))yield i;n.recordSuccess()}catch(i){throw n.recordFailure(i),i}}});return Je(r,"withBreaker",t),{adapter:r,breaker:n}}_e();ae();ee();Re();var $s=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"},Ka=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),np=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function Ha(t,e){let n=Ue(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),r=E(np(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),o=_([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(se(o),e.onExhausted!=null){let c=e.onExhausted,d=!1,l=!0;o.subscribe(p=>{for(let f of p)if(f[0]===S){let m=f[1];if(d&&l&&m===!1){let g=rp(r.cache??Ka,e.caps);g&&c(g)}l=m,d=!0}})}let s=()=>{if(o.cache===!1){let c=r.cache??Ka,d=rp(c,e.caps);return new $s(d??"budget",e.caps[d??"calls"]??0,Dh(c,d??"calls"))}},i=(c,d)=>{let l=t.provider,p=Tn({provider:l,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??Ka,m=e.pricingFn?f.usd+e.pricingFn(c,{model:d.model,provider:l,tier:d.tier}).total:f.usd;r.emit({calls:f.calls+1,inputTokens:f.inputTokens+gt(c),outputTokens:f.outputTokens+It(c),usd:m})},a=()=>{n.clear(),r.emit(np())},u=Ze(t,{invoke(c,d){let l=s();if(l)return Promise.reject(l);let p=j(),f=t.model??d?.model??"",m=h=>(i(h.usage??kt(),{model:t.model??d?.model??h.model??"",tier:d?.tier??h.tier,startNs:p,method:"invoke"}),h),g=h=>{let y=h;i(kt(),{model:f,tier:d?.tier,startNs:p,method:"invoke",error:{type:y?.name??"Error",message:y?.message??String(h)}})};return Is(t.invoke(c,d),{onResp:m,onError:g,name:"budgetGate/invokeTap"})},async*stream(c,d){let l=s();if(l)throw l;let p=j(),f;try{for await(let m of t.stream(c,d))m.type==="usage"&&(f=m.usage),yield m;i(f??kt(),{model:t.model??d?.model??"",tier:d?.tier,startNs:p,method:"stream"})}catch(m){let g=m;throw i(f??kt(),{model:t.model??d?.model??"",tier:d?.tier,startNs:p,method:"stream",error:{type:g?.name??"Error",message:g?.message??String(m)}}),m}}});return Je(u,"withBudgetGate",t),{adapter:u,budget:{totals:r,isOpen:o,log:n,reset:a}}}function rp(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 Dh(t,e){switch(e){case"calls":return t.calls;case"inputTokens":return t.inputTokens;case"outputTokens":return t.outputTokens;case"usd":return t.usd}}Re();function Ph(t,e){let n=e.mock??vn({provider:t.provider,model:t.model}),r=typeof e.enabled=="boolean"?e.enabled:void 0,o=r===void 0?X(e.enabled):void 0,s;o&&(s=se(o));let i=()=>r!==void 0?r:!!o?.cache,a=Ze(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 Je(a,"withDryRun",t),{adapter:a,dispose:()=>{s&&(s(),s=void 0)}}}function Wa(t){if(t==null||typeof t!="object")return;let e=t,n=e.status,r=Gh(e.headers);if(n!==429&&n!==503&&!Kh(e.message))return;let o={},s=r("retry-after"),i=$h(s);i!=null&&(o.retryAfterMs=i);let a=r("anthropic-ratelimit-requests-reset");if(a){let f=op(a);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let u=r("anthropic-ratelimit-tokens-reset");if(u){let f=op(u);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let c=js(r,"x-ratelimit-limit-requests");c!=null&&(o.rpmCap=c);let d=js(r,"x-ratelimit-limit-tokens");d!=null&&(o.tpmCap=d);let l=js(r,"x-ratelimit-remaining-requests"),p=js(r,"x-ratelimit-remaining-tokens");if(l!=null&&c!=null&&c>0&&(o.usageHint??={},o.usageHint.rpm=1-l/c),p!=null&&d!=null&&d>0&&(o.usageHint??={},o.usageHint.tpm=1-p/d),o.retryAfterMs==null&&e.message){let f=Bh(e.message);f!=null&&(o.retryAfterMs=f)}return e.headers&&(o.metadata={headers:Fh(e.headers)}),o.retryAfterMs==null&&o.rpmCap==null&&o.tpmCap==null&&o.usageHint==null?o.metadata?o:void 0:o}function Gh(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 Fh(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 js(t,e){let n=t(e);if(n==null)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function $h(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 op(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var jh=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function Bh(t){let e=jh.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 Vh=/rate\s*limit|too\s*many\s*requests|quota|429/i;function Kh(t){return!!t&&Vh.test(t)}_e();ae();ee();Et();Re();vt();function qa(t){let e=new Error(t);return e.name="AbortError",e}function ip(t={}){let e=Math.max(1,t.burstMultiplier??1),n=t.clampCooldownMs??6e4,r=t.rpm!=null?X(t.rpm):E(Number.POSITIVE_INFINITY),o=t.tpm!=null?X(t.tpm):E(Number.POSITIVE_INFINITY),s=E(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),i=E(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),a=E({},{name:"adaptiveRateLimiter/lastSignal"}),u=_([r,s],([L,P])=>Math.min(Number(L??1/0),Number(P??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),c=_([o,i],([L,P])=>Math.min(Number(L??1/0),Number(P??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),d=nr(Number(r.cache??Number.POSITIVE_INFINITY),e),l=nr(Number(o.cache??Number.POSITIVE_INFINITY),e),p=!1,f=!1,m=u.subscribe(L=>{for(let P of L)if(P[0]===S){let J=Number(P[1]);Number.isFinite(J)&&J>0?(d=nr(J,e),p=!1):J===1/0?(d=nr(1/0,e),p=!1):J<=0&&(p=!0)}}),g=c.subscribe(L=>{for(let P of L)if(P[0]===S){let J=Number(P[1]);Number.isFinite(J)&&J>0?(l=nr(J,e),f=!1):J===1/0?(l=nr(1/0,e),f=!1):J<=0&&(f=!0)}}),h=0,y=new De,b=new De,v;t.adaptation!=null&&(v=X(t.adaptation).subscribe(P=>{for(let J of P)J[0]===S&&T(J[1])}));function T(L){if(a.emit(L),L.rpmCap!=null&&Number.isFinite(L.rpmCap)&&L.rpmCap>=0&&(s.emit(L.rpmCap),Number.isFinite(n)&&n>0&&y.start(n,()=>s.emit(Number.POSITIVE_INFINITY))),L.tpmCap!=null&&Number.isFinite(L.tpmCap)&&L.tpmCap>=0&&(i.emit(L.tpmCap),Number.isFinite(n)&&n>0&&b.start(n,()=>i.emit(Number.POSITIVE_INFINITY))),L.retryAfterMs!=null&&L.retryAfterMs>0){let P=j()+L.retryAfterMs*1e6;P>h&&(h=P)}}let w=E(0,{name:"adaptiveRateLimiter/pending"}),k=E(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),x=E(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),R=L=>{w.emit((w.cache??0)+L)},N=()=>{k.emit(d.available()),x.emit(l.available())};async function A(L={}){let P=L.requestCost??1,J=L.tokenCost??0,Q=L.signal;R(1);try{for(;;){if(Q?.aborted)throw qa("AdaptiveRateLimiter.acquire aborted");let D=j();if(h>D){let $=Math.ceil((h-D)/1e6);await Bs($,Q);continue}if(P>0&&p||J>0&&f){await Bs(250,Q);continue}let z=d,W=l;if(!z.tryConsume(P)){await Bs(sp(z,P),Q);continue}if(!(J>0?W.tryConsume(J):!0)){z.putBack(P),await Bs(sp(W,J),Q);continue}N();return}}finally{R(-1)}}function M(L){L>0?l.tryConsume(L):L<0&&l.putBack(-L),N()}function I(){m(),g(),v?.(),y.cancel(),b.cancel()}return{effectiveRpm:u,effectiveTpm:c,lastSignal:a,pending:w,rpmAvailable:k,tpmAvailable:x,acquire:A,recordUsage:M,recordSignal:T,dispose:I}}function nr(t,e){if(!Number.isFinite(t)||t===1/0)return Bt(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let n=Math.max(1,t*e),r=t/60;return Bt(n,r)}function sp(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 Bs(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(qa("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(qa("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",s,{once:!0}))})}Re();function Ua(t,e={}){let n=e.limiter??ip({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=Wa(i);a&&n.recordSignal(a)},s=Ze(t,{async invoke(i,a){let u=r(i,a);await n.acquire({requestCost:1,tokenCost:u,signal:a?.signal});try{let c=await Qe(X(t.invoke(i,a))),d=c.usage??tp(),p=gt(d)+It(d)-u;return p>0&&n.recordUsage(p),c}catch(c){throw o(c),c}},async*stream(i,a){let u=r(i,a);await n.acquire({requestCost:1,tokenCost:u,signal:a?.signal});try{let c=0;for await(let l of t.stream(i,a))l.type==="usage"&&(c=gt(l.usage)+It(l.usage)),yield l;let d=c-u;d>0&&n.recordUsage(d)}catch(c){throw o(c),c}}});return Je(s,"withRateLimiter",t),{adapter:s,limiter:n}}Et();Re();var oo=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 za(t,e={}){if(t.length===0)throw new RangeError("cascadingLlmAdapter: tiers must be non-empty");let n=t.map(s=>({name:s.name,adapter:s.adapter,filter:s.filter,breaker:s.breaker?"canExecute"in s.breaker?s.breaker:Tt(s.breaker):void 0})),r=e.streamRetryBeforeFirstChunk??!0,o={provider:"cascading",model:void 0,async invoke(s,i){let a=[],u=new Map;for(let d=0;d<n.length;d++){let l=n[d];if(l.filter&&!l.filter(s,i)){a.push({name:l.name,reason:"filter"});continue}if(l.breaker&&!l.breaker.canExecute()){a.push({name:l.name,reason:"breaker"});continue}try{let p=await Qe(X(l.adapter.invoke(s,i)));return l.breaker?.recordSuccess(),{...p,metadata:{...p.metadata??{},tier:l.name}}}catch(p){u.set(l.name,p),l.breaker?.recordFailure(p);let f=n[d+1];f&&e.onFallback?.(l.name,f.name,p)}}let c={skipped:a,failed:u};throw e.onExhausted?.(c),new oo(c)},async*stream(s,i){let a=[],u=new Map;for(let d=0;d<n.length;d++){let l=n[d];if(l.filter&&!l.filter(s,i)){a.push({name:l.name,reason:"filter"});continue}if(l.breaker&&!l.breaker.canExecute()){a.push({name:l.name,reason:"breaker"});continue}let p=!1;try{for await(let f of l.adapter.stream(s,i))p=!0,yield f;l.breaker?.recordSuccess();return}catch(f){if(u.set(l.name,f),l.breaker?.recordFailure(f),p||!r)throw f;let m=n[d+1];m&&e.onFallback?.(l.name,m.name,f)}}let c={skipped:a,failed:u};throw e.onExhausted?.(c),new oo(c)}};return Je(o,`cascade[${n.map(s=>s.name).join(",")}]`),o}function Hh(t,e,n){let r={name:t,adapter:e};return n?.breaker&&(r.breaker=n.breaker),n?.filter&&(r.filter=n.filter),r}Re();vt();function Vs(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function ap(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Vs()):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(Vs())},e.addEventListener("abort",s,{once:!0}))})}function Ja(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??Wh,u=e.retryStreaming??!0,c=(l,p)=>{if(s==="decorrelated"){let h=Math.min(o,Math.max(r,p*3));return r+Math.random()*(h-r)}let f=s==="exp"?r*2**(l-1):r*l,m=Math.min(o,f);if(!i)return m;let g=m*(.5+Math.random());return Math.min(o,g)},d=Ze(t,{async invoke(l,p){if(p?.signal?.aborted)throw Vs();let f,m=r;for(let g=1;g<=n;g++)try{return await Qe(X(t.invoke(l,p)))}catch(h){if(f=h,g>=n||!a(h,g))throw h;let y=c(g,m);m=y,await ap(y,p?.signal)}throw f},async*stream(l,p){if(p?.signal?.aborted)throw Vs();if(!u){for await(let g of t.stream(l,p))yield g;return}let f,m=r;for(let g=1;g<=n;g++){let h=!1;try{for await(let y of t.stream(l,p))h=!0,yield y;return}catch(y){if(f=y,h||g>=n||!a(y,g))throw y;let b=c(g,m);m=b,await ap(b,p?.signal)}}throw f}});return Je(d,"withRetry",t),d}function Wh(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}Re();vt();var rr=class extends Error{constructor(n){super(`LLM call timed out after ${n}ms`);this.ms=n}name="LLMTimeoutError"};function Ya(t,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let n=s=>{let i=new AbortController,a=!1,u,c=new De;return s&&(s.aborted?i.abort(s.reason):(u=()=>{c.cancel(),i.abort(s.reason)},s.addEventListener("abort",u,{once:!0}))),c.start(e,()=>{a=!0,i.abort(new rr(e))}),{signal:i.signal,cancel:()=>{c.cancel(),s&&u&&s.removeEventListener("abort",u)},timedOut:()=>a}},r=(s,i)=>{if(!i||s instanceof rr)throw s;let a=s;if(a?.name==="AbortError"||a?.name==="DOMException"&&Number(a.code)===20||s?.message==="aborted"){let c=new rr(e);throw c.cause=s,c}throw s},o=Ze(t,{async invoke(s,i){let{signal:a,cancel:u,timedOut:c}=n(i?.signal);try{return await Qe(X(t.invoke(s,{...i,signal:a})))}catch(d){return r(d,c())}finally{u()}},async*stream(s,i){let{signal:a,cancel:u,timedOut:c}=n(i?.signal);try{for await(let d of t.stream(s,{...i,signal:a}))yield d}catch(d){r(d,c())}finally{u()}}});return Je(o,"withTimeout",t),o}function qh(t,e={}){let n={adapter:t},r=t;if(e.rateLimit){let o=Ua(r,e.rateLimit);r=o.adapter,n.rateLimiter=o.limiter}if(e.budget){let o=Ha(r,e.budget);r=o.adapter,n.budget=o.budget}if(e.breaker){let o=Va(r,e.breaker);r=o.adapter,n.breaker=o.breaker}if(e.timeoutMs!=null&&(r=Ya(r,e.timeoutMs)),e.retry&&(r=Ja(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=za([{name:e.name??"primary",adapter:r},{name:"fallback",adapter:e.fallback}],o)}return e.cache&&(r=ro(r,e.cache)),n.adapter=r,n}ee();Re();function Uh(t,e,n){let r=X(e);return Se(r,s=>{if(!s||s.length===0)return E(null);let i=n?.tools;return t.invoke(s,{model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,tools:i,systemPrompt:n?.systemPrompt})})}Le();Re();ae();Re();vt();function ue(t,e){return ze("ai",t,e)}function zh(t){return t!=null&&typeof t.then=="function"}function Qa(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function Jh(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var Yh=3e4;function up(t,e){if(t.status==="settled"){let r=t.cache;if(r!==void 0)return Promise.resolve(r)}let n=e?.timeoutMs??Yh;return new Promise((r,o)=>{let s=new De,i=t.subscribe(a=>{for(let u of a){if(u[0]===S){s.cancel(),i(),r(u[1]);return}if(u[0]===O){s.cancel(),i(),o(u[1]);return}if(u[0]===C){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 so(t){return zh(t)?so(await t):Qa(t)?up(t):Jh(t)?up(X(t)):t}function or(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function Qh(t,e){let n=X(t),r=e?.refreshTrigger!=null?X(e.refreshTrigger):null;return r==null?U([n],(o,s,i)=>{if(i.store.emitted===!0)return;let u=o[0],c=u!=null&&u.length>0?u.at(-1):i.prevData[0];if(c!==void 0)return i.store.emitted=!0,s.emit(c),{invalidate:()=>{i.store.emitted=!1}}},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:ue("frozen_context")}):U([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:ue("frozen_context")})}ae();ee();Re();function cp(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function Xh(t,e=200){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function kn(t,e,n,r){let o=r?.format??"text",s=r?.name??"prompt_node",i=_(e,u=>{if(u.some(d=>d==null))return[];let c=typeof n=="string"?n:n(...u);return c?[{role:"user",content:c}]:[]},{name:`${s}::messages`,meta:ue("prompt_node")});return Se(i,u=>!u||u.length===0?E(null):H(c=>{let d=!1,l=!1,p,f={model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt};if(r?.abort){let y=Xo(r.abort);f.signal=y.signal,p=y.dispose}let m;try{m=t.invoke(u,f)}catch(y){return d=!0,c.down([[O,y]]),()=>{p?.()}}let h=X(m).subscribe(y=>{if(!(l||d))for(let b of y){if(d)return;if(b[0]===S){let v=b[1];try{let T=cp(v),w=o==="json"?JSON.parse(or(T)):T;c.emit(w)}catch(T){let w=cp(v),k=new Error(`promptNode: failed to parse LLM response as JSON: ${T.message}
37
- Raw content (first 200 chars): ${Xh(w)}`);d=!0,c.down([[O,k]]);return}}else if(b[0]===O){d=!0,c.down([[O,b[1]]]);return}else if(b[0]===C){d=!0,c.down([[C]]);return}else c.down([b])}});return()=>{l=!0,h(),p?.()}},{name:`${s}::call`,meta:ue("prompt_node::call")}),{name:`${s}::output`,meta:r?.meta?{...ue("prompt_node::output"),...r.meta}:ue("prompt_node::output")})}Ae();_e();ee();Re();var zs={};Ne(zs,{MessagingHubGraph:()=>Ws,SubscriptionGraph:()=>io,TopicBridgeGraph:()=>Hs,TopicGraph:()=>Rn,messagingHub:()=>ao,subscription:()=>dp,topic:()=>qs,topicBridge:()=>Us});Le();var Zh=2147483647;function Ks(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function xn(t,e){return ze("messaging",t,e)}var Rn=class extends Y{_log;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=Ue([],{name:"events",maxSize:n.retainedLimit}),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=_([this.events],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:xn("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(se(this.latest)),this.hasLatest=_([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:xn("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(se(this.hasLatest)),this.addDisposer(()=>{this.events.down([[C]])}),this.addDisposer(()=>this._log.disposeAllViews())}publish(e){this._log.append(e)}retained(){return this.events.cache}},io=class extends Y{source;cursor;available;topic;constructor(e,n,r={}){super(e,r.graph);let o=Ks(r.cursor??0,"subscription cursor");this.topic=n;let s=n.events;this.source=_([s],([i])=>i,{name:"source",describeKind:"derived",meta:xn("subscription_source"),initial:s.cache}),this.add(this.source,{name:"source"}),this.cursor=E(o,{name:"cursor",describeKind:"state",meta:xn("subscription_cursor")}),this.add(this.cursor,{name:"cursor"}),this.available=_([this.source,this.cursor],([i,a])=>{let u=i,c=Math.max(0,Math.trunc(a??0));return u.slice(c)},{name:"available",describeKind:"derived",meta:xn("subscription_available"),initial:[]}),this.add(this.available,{name:"available"}),this.addDisposer(se(this.source)),this.addDisposer(se(this.available))}ack(e){let n=this.available.cache,r=e===void 0?n.length:Ks(e,"subscription ack count"),o=Math.min(r,n.length);if(o<=0)return this.cursor.cache;let s=this.cursor.cache+o;return this.cursor.emit(s),s}pull(e,n={}){let r=this.available.cache,o=e===void 0?r.length:Ks(e,"subscription pull limit"),s=r.slice(0,o);return n.ack&&s.length>0&&this.ack(s.length),s}},Hs=class extends Y{_sourceSub;_target;bridgedCount;constructor(e,n,r,o={}){super(e,o.graph),this._sourceSub=dp(`${e}-subscription`,n,{cursor:o.cursor}),this._target=r,this.mount("subscription",this._sourceSub),this.bridgedCount=E(0,{name:"bridgedCount",describeKind:"state",meta:xn("topic_bridge_count")}),this.add(this.bridgedCount,{name:"bridgedCount"});let s=Math.max(1,Ks(o.maxPerPump??Zh,"topic bridge maxPerPump")),i=o.map??(u=>u),a=U([this._sourceSub.available],()=>{let u=this._sourceSub.pull(s,{ack:!0});if(u.length===0)return;let c=0;for(let d of u){let l=i(d);l!==void 0&&(this._target.publish(l),c+=1)}if(c>0){let d=this.bridgedCount.cache;this.bridgedCount.emit(d+c)}},{name:"pump",describeKind:"effect",meta:xn("topic_bridge_pump")});this.add(a,{name:"pump"}),this.addDisposer(se(a))}},Ws=class extends Y{_topics=new Map;_version=0;_defaultTopicOptions;constructor(e,n={}){super(e,n.graph),this._defaultTopicOptions={...n.defaultTopicOptions??{}}}get version(){return this._version}get size(){return this._topics.size}has(e){return this._topics.has(e)}topicNames(){return this._topics.keys()}topic(e,n){let r=this._topics.get(e);if(r===void 0){let o={...this._defaultTopicOptions,...n??{}};r=new Rn(e,o),this._topics.set(e,r),this.mount(e,r),this._version+=1}return r}publish(e,n){this.topic(e).publish(n)}publishMany(e){Z(()=>{for(let[n,r]of e)this.topic(n).publish(r)})}subscribe(e,n,r){let o=this.topic(n);return new io(e,o,r)}removeTopic(e){if(!this._topics.has(e))return!1;try{this.remove(e)}finally{this._topics.delete(e),this._version+=1}return!0}};function qs(t,e){return new Rn(t,e)}function ao(t,e){return new Ws(t,e)}function dp(t,e,n){return new io(t,e,n)}function Us(t,e,n,r){return new Hs(t,e,n,r)}var Js={};Ne(Js,{approval:()=>og,branch:()=>rg,gate:()=>uo,join:()=>sg,loop:()=>ig,onFailure:()=>cg,pipeline:()=>lp,sensor:()=>ug,subPipeline:()=>ag,task:()=>ng});Ae();ae();Le();ee();function Dt(t,e){if(typeof e=="string")return{node:t.resolve(e),path:e};let n=eg(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 eg(t,e){let n=t.describe(),r=`::${qe}::`;for(let o of Object.keys(n.nodes).sort())if(!o.includes(r))try{if(t.resolve(o)===e)return o}catch{}}function zt(t,e,n,r){t.add(n,{name:e})}function Jt(t,e){return ze("orchestration",t,e)}function tg(t){let e=r=>{let o=r.trim();return o.length===0?0:Number(o)},n;return typeof t=="string"?n=e(t):t===null?n=0:n=Number(t),Number.isFinite(n)?Math.max(0,Math.trunc(n)):1}function lp(t,e){return new Y(t,e)}function ng(t,e,n,r){let s=(r?.deps??[]).map(d=>Dt(t,d)),{deps:i,...a}=r??{},u=(d,l,p)=>{let f=d.map((m,g)=>m!=null&&m.length>0?m.at(-1):p.prevData[g]);l.emit(n(f,p))},c=U(s.map(d=>d.node),u,{...a,name:e,describeKind:"derived",meta:Jt("task",r?.meta)});return zt(t,e,c,s.flatMap(d=>d.path?[d.path]:[])),c}function rg(t,e,n,r,o){let s=Dt(t,n),i=_([s.node],([a])=>({branch:r(a)?"then":"else",value:a}),{...o,name:e,meta:Jt("branch",o?.meta)});return zt(t,e,i,s.path?[s.path]:[]),i}function og(t,e,n,r,o){let s=Dt(t,n),i=Dt(t,r),a=o?.isApproved??(c=>!!c),u=U([s.node,i.node],(c,d,l)=>{let p=c[0],f=c[1],m=f!=null&&f.length>0?f.at(-1):l.prevData[1];if(m===void 0||!a(m)){d.down([[F]]);return}if(p==null||p.length===0){f!=null&&f.length>0&&l.prevData[0]!==void 0?d.emit(l.prevData[0]):d.down([[F]]);return}for(let g of p)d.emit(g)},{...o,name:e,describeKind:"derived",meta:Jt("approval",o?.meta)});return zt(t,e,u,[s.path,i.path].filter(c=>typeof c=="string")),u}function uo(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=Dt(t,n),a=E([],{name:"pending",equals:()=>!1}),u=E(s,{name:"isOpen"}),c=_([a],([k])=>k.length,{name:"count"}),d=E(null,{name:"lastRejected",equals:()=>!1}),l=[],p=!1,f=s,m=u.subscribe(k=>{for(let x of k)x[0]===S&&(f=x[1])});function g(){a.emit([...l])}function h(k){l.push(k),l.length>o&&l.shift(),g()}function y(k){let x=l.splice(0,k);return g(),x}function b(k){if(p)throw new Error(`gate: ${k}() called after gate was torn down`)}let v=U([i.node],(k,x,R)=>{let N=R.terminalDeps[0];if(N!==void 0){p=!0,l=[],g(),x.down(N===!0?[[C]]:[[O,N]]);return}let A=k[0];if(A==null||A.length===0){x.down([[F]]);return}for(let M of A)f?x.emit(M):(h(M),x.down([[F]]))},{name:e,describeKind:"derived",meta:Jt("gate",r?.meta)}),T={node:v,pending:a,count:c,isOpen:u,lastRejected:d,approve(k=1){b("approve");let x=y(k);for(let R of x){if(p)break;v.emit(R)}},reject(k=1){b("reject");let x=[...l],R=Math.min(k,x.length);if(R===0){y(k);return}Z(()=>{for(let N=0;N<R;N++)d.emit(x[N]);y(k)})},modify(k,x=1){b("modify");let R=[...l],N=y(x);for(let A=0;A<N.length&&!p;A++)v.emit(k(N[A],A,R))},open(){b("open"),Z(()=>{u.emit(!0);let k=y(l.length);for(let x of k){if(p)break;v.emit(x)}})},close(){b("close"),u.emit(!1)}};t.addDisposer(c.subscribe(()=>{})),t.addDisposer(m),zt(t,e,v,i.path?[i.path]:[]);let w=new Y(`${e}_state`);return w.add(a,{name:"pending"}),w.add(u,{name:"isOpen"}),w.add(c,{name:"count"}),w.add(d,{name:"lastRejected"}),t.mount(`${e}_state`,w),t.addDisposer(d.subscribe(()=>{})),T}function sg(t,e,n,r){let o=n.map(i=>Dt(t,i)),s=_(o.map(i=>i.node),i=>i,{...r,name:e,meta:Jt("join",r?.meta)});return zt(t,e,s,o.flatMap(i=>i.path?[i.path]:[])),s}function ig(t,e,n,r,o){let s=Dt(t,n),i=o?.iterations,a=typeof i=="number"||i===void 0?void 0:Dt(t,i),u=typeof i=="number"?i:void 0,c=U(a?[s.node,a.node]:[s.node],(d,l,p)=>{let f=d[0],m=f!=null&&f.length>0?f.at(-1):p.prevData[0],g=a?d[1]:void 0,h=u??(a?g!=null&&g.length>0?g.at(-1):p.prevData[1]:1),y=tg(h);for(let b=0;b<y;b+=1)m=r(m,b,l);l.emit(m)},{...o,name:e,describeKind:"derived",meta:Jt("loop",o?.meta)});return zt(t,e,c,[s.path,a?.path].filter(d=>typeof d=="string")),c}function ag(t,e,n,r){let o=n instanceof Y?n:lp(e,r);return typeof n=="function"&&n(o),t.mount(e,o),o}function ug(t,e,n,r){let o=U([],()=>{},{...r,name:e,initial:n,describeKind:"producer",meta:Jt("sensor",r?.meta)});return zt(t,e,o,[]),{node:o,push(s){o.emit(s)},error(s){o.down([[O,s]])},complete(){o.down([[C]])}}}function cg(t,e,n,r,o){let s=Dt(t,n),i=!1,a=U([],(u,c)=>{let d=s.node.subscribe(l=>{for(let p of l){if(i)return;if(p[0]===O)try{c.emit(r(p[1],c))}catch(f){i=!0,c.down([[O,f]])}else c.down([p]),p[0]===C&&(i=!0)}});return()=>d()},{...o,name:e,describeKind:"derived",completeWhenDepsComplete:!1,errorWhenDepsError:!1,meta:Jt("onFailure",o?.meta)});return zt(t,e,a,s.path?[s.path]:[]),a}async function pp(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 fp(t,e){if(e==="json")try{return JSON.parse(or(t))}catch(n){let r=t.slice(0,160);throw new Error(`streamingPromptNode: format:"json" \u2014 failed to parse accumulated text as JSON: ${n.message}; content preview: ${r}`)}return t}function mp(t,e){return _([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:ue("accumulated_text"),initial:""})}function dg(t,e,n,r){let o=r?.name??"llm",s=r?.format??"text",i=qs(`${o}/stream`,{...r?.retainedLimit!=null?{retainedLimit:r.retainedLimit}:{}}),a=_(e,l=>{if(l.some(f=>f==null))return[];let p=typeof n=="string"?n:n(...l);return p?[{role:"user",content:p}]:[]},{name:`${o}::messages`,meta:ue("prompt_node::messages"),initial:[]}),u=Se(a,l=>{let p=l;if(!p||p.length===0)return E(null);let f=new AbortController;async function*m(){try{let g=await pp(t,p,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt,signal:f.signal},i);yield fp(g,s)}finally{f.abort()}}return X(m())}),c=mp(i,`${o}::accumulatedText`),d=se(u);return{output:u,deltaTopic:i,accumulatedText:c,dispose:()=>{d(),i.destroy()}}}function lg(t,e,n,r,o,s){let i=E(0,{name:`${e}/cancel`}),a=0,u=[...r,i],c=s?.name??e,d=s?.format??"text",l=qs(`${c}/stream`,{...s?.retainedLimit!=null?{retainedLimit:s.retainedLimit}:{}}),p=_(u,k=>{let x=k.slice(0,-1);if(x.some(N=>N==null))return[];let R=typeof o=="string"?o:o(...x);return R?[{role:"user",content:R}]:[]},{name:`${c}::messages`,meta:ue("prompt_node::messages"),initial:[]}),f=Se(p,k=>{let x=k;if(!x||x.length===0)return E(null);let R=new AbortController;async function*N(){try{let A=await pp(n,x,{model:s?.model,temperature:s?.temperature,maxTokens:s?.maxTokens,systemPrompt:s?.systemPrompt,signal:R.signal},l);yield fp(A,d)}finally{R.abort()}}return X(N())}),m=mp(l,`${c}::accumulatedText`),g=it(f,k=>k!=null);t.add(g,{name:`${e}/raw`});let h=uo(t,`${e}/gate`,`${e}/raw`,s?.gate),y=se(f),b=se(h.node),v=se(m);t.addDisposer(y),t.addDisposer(b),t.addDisposer(v);let T=h.reject.bind(h),w={...h,reject(k=1){Z(()=>{T(k),i.emit(++a)})}};return{output:h.node,deltaTopic:l,accumulatedText:m,gate:w,dispose:()=>{y(),b(),v(),l.destroy()}}}ee();Re();function pg(t,e){let n=e?.separator??`
36
+ `)}]});let o={};return e?.maxTokens!=null&&(o.maxOutputTokens=e.maxTokens),e?.temperature!=null&&(o.temperature=e.temperature),e?.maxReasoningTokens!=null&&(o.thinkingConfig={thinkingBudget:e.maxReasoningTokens}),Object.keys(o).length>0&&(s.generationConfig=o),e?.tools&&e.tools.length>0&&(s.tools=[{functionDeclarations:e.tools.map(xh)}]),e?.providerExtras&&Object.assign(s,e.providerExtras),s}function xh(t){return{name:t.name,description:t.description,parameters:t.parameters}}function tp(t,e,n){let r={},s=t.generationConfig;s&&(typeof s.maxOutputTokens=="number"&&(r.maxOutputTokens=s.maxOutputTokens),typeof s.temperature=="number"&&(r.temperature=s.temperature),s.thinkingConfig&&(r.thinkingConfig=s.thinkingConfig)),t.systemInstruction&&(r.systemInstruction=t.systemInstruction),t.tools&&(r.tools=t.tools);for(let[o,i]of Object.entries(t))o==="contents"||o==="generationConfig"||o==="systemInstruction"||o==="tools"||o==="abortSignal"||o==="model"||(r[o]=i);return n&&(r.abortSignal=n),{model:e,contents:t.contents,config:Object.keys(r).length>0?r:void 0}}function La(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 s of t.promptTokensDetails){let o=s.modality?.toLowerCase();o==="image"?e.input.image=(e.input.image??0)+s.tokenCount:o==="audio"?e.input.audio=(e.input.audio??0)+s.tokenCount:o==="video"&&(e.input.video=(e.input.video??0)+s.tokenCount)}return e.output.regular=t.candidatesTokenCount??0,t.thoughtsTokenCount&&(e.output.reasoning=t.thoughtsTokenCount),e}function np(t,e){let n=t.candidates?.[0],r=n?.content?.parts??[],s=[],o=[],i=0;for(let a of r)typeof a.text=="string"&&s.push(a.text),a.functionCall&&o.push({id:`${a.functionCall.name}-${i++}`,name:a.functionCall.name,arguments:a.functionCall.args??{}});return{content:s.join(""),toolCalls:o.length>0?o:void 0,usage:La(t.usageMetadata),finishReason:n?.finishReason,latencyMs:e,model:t.modelVersion,provider:"google"}}function Rh(t){if(t.apiKey)return t.apiKey;let e=globalThis.process?.env;return e?.GOOGLE_API_KEY??e?.GEMINI_API_KEY}function Sh(t){let e=t.baseURL??"https://generativelanguage.googleapis.com/v1beta",n=t.fetchImpl??fetch,r=o=>{let i=o?.model??t.model;if(!i)throw new Error("googleAdapter: model must be set via options.model or invokeOpts.model");return i},s=()=>{let o=Rh(t);if(!o)throw new Error("googleAdapter: apiKey required for invoke/stream");return`key=${encodeURIComponent(o)}`};return{provider:"google",model:t.model,async invoke(o,i){let a=r(i),u=Os(o,i),d=F(),c=`${e}/models/${encodeURIComponent(a)}:generateContent?${s()}`,l=await n(c,{method:"POST",headers:{"content-type":"application/json",...t.headers??{}},body:JSON.stringify(u),signal:i?.signal});if(!l.ok)throw await ht(l,"Google");let p=await l.json(),f=Math.max(0,(F()-d)/1e6);return np(p,f)},async*stream(o,i){let a=r(i),u=Os(o,i),d=`${e}/models/${encodeURIComponent(a)}:streamGenerateContent?alt=sse&${s()}`,c=await n(d,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",...t.headers??{}},body:JSON.stringify(u),signal:i?.signal});if(!c.ok)throw await ht(c,"Google");if(!c.body)throw new Error("googleAdapter: streaming response has no body");let l,p;for await(let f of Lt(c.body,{signal:i?.signal})){if(!f.data)continue;let m;try{m=JSON.parse(f.data)}catch{continue}let g=m.candidates?.[0];for(let h of g?.content?.parts??[])typeof h.text=="string"&&(h.thought?yield{type:"thinking",delta:h.text}:yield{type:"token",delta:h.text}),h.functionCall&&(yield{type:"tool-call-delta",delta:{name:h.functionCall.name,argumentsDelta:JSON.stringify(h.functionCall.args??{})}});g?.finishReason&&(p=g.finishReason),m.usageMetadata&&(l=m.usageMetadata)}l&&(yield{type:"usage",usage:La(l)}),yield{type:"finish",reason:p??"stop"}}}}function Nh(t){let e=t.sdk;if(!e)throw new Error("sdkBackedGoogle: sdk instance required");return{provider:"google",model:t.model,async invoke(n,r){let s=Os(n,r),o=r?.model??t.model;if(!o)throw new Error("googleAdapter: model required");let i=tp(s,o,r?.signal),a=F(),u=await e.models.generateContent(i),d=Math.max(0,(F()-a)/1e6);return np(u,d)},async*stream(n,r){if(!e.models.generateContentStream)throw new Error("sdkBackedGoogle: SDK instance does not expose generateContentStream");let s=Os(n,r),o=r?.model??t.model;if(!o)throw new Error("googleAdapter: model required");let i=tp(s,o,r?.signal),a,u,d=await e.models.generateContentStream(i);for await(let c of d){let l=c.candidates?.[0];for(let p of l?.content?.parts??[])typeof p.text=="string"&&(p.thought?yield{type:"thinking",delta:p.text}:yield{type:"token",delta:p.text}),p.functionCall&&(yield{type:"tool-call-delta",delta:{name:p.functionCall.name,argumentsDelta:JSON.stringify(p.functionCall.args??{})}});l?.finishReason&&(u=l.finishReason),c.usageMetadata&&(a=c.usageMetadata)}a&&(yield{type:"usage",usage:La(a)}),yield{type:"finish",reason:u??"stop"}}}}Ne();var Eh={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 Ia(t={}){return t.sdk?Ah(t):Ch(t)}function Cs(t,e,n,r,s){let o=e?.model??n;if(!o)throw new Error("openAICompatAdapter: model must be set via options.model or invokeOpts.model");let i=t.map(_h);e?.systemPrompt&&!t.some(u=>u.role==="system")&&i.unshift({role:"system",content:e.systemPrompt});let a={model:o,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(Mh)),e?.maxReasoningTokens!=null&&(a.reasoning={max_tokens:e.maxReasoningTokens}),r&&(a.stream=!0,a.stream_options={include_usage:!0}),s&&Object.assign(a,s),e?.providerExtras&&Object.assign(a,e.providerExtras),a}function _h(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 Mh(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}}function Da(t){let e={input:{regular:0},output:{regular:0},raw:t};if(!t)return e;let n=t.prompt_tokens??0,r=t.prompt_tokens_details?.cached_tokens??0;t.prompt_cache_hit_tokens!=null?(r=t.prompt_cache_hit_tokens,e.input.regular=t.prompt_cache_miss_tokens??Math.max(0,n-r)):e.input.regular=Math.max(0,n-r),r>0&&(e.input.cacheRead=r),t.prompt_tokens_details?.audio_tokens&&(e.input.audio=t.prompt_tokens_details.audio_tokens);let s=t.completion_tokens??0,o=t.completion_tokens_details?.reasoning_tokens??0;return e.output.regular=Math.max(0,s-o),o>0&&(e.output.reasoning=o),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 rp(t,e,n){let r=t.choices[0],s=r?.message,o=s?.content??"",i=(s?.tool_calls??[]).map(a=>({id:a.id,name:a.function.name,arguments:Oh(a.function.arguments)}));return{content:o,toolCalls:i.length>0?i:void 0,usage:Da(t.usage),finishReason:r?.finish_reason,latencyMs:e,model:t.model,provider:n}}function Oh(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!=null?e:{_raw:t}}catch{return{_raw:t}}}function op(t){let e=t.preset??"openai",n=Eh[e],r=t.baseURL??n.baseURL,s=t.provider??n.provider,o=n.apiKeyEnv,i=t.apiKey??(o?globalThis.process?.env?.[o]:void 0);return{provider:s,baseURL:r,apiKey:i}}function Ch(t){let{provider:e,baseURL:n,apiKey:r}=op(t),s=t.fetchImpl??fetch,o=e!=="ollama",i=()=>{let a={"content-type":"application/json",...t.headers??{}};if(o){if(!r)throw new Error(`openAICompatAdapter[${e}]: apiKey required for invoke/stream`);a.authorization=`Bearer ${r}`}return a};return{provider:e,model:t.model,async invoke(a,u){let d=Cs(a,u,t.model,!1,t.bodyExtras),c=F(),l=await s(`${n}/chat/completions`,{method:"POST",headers:i(),body:JSON.stringify(d),signal:u?.signal});if(!l.ok)throw await ht(l,e);let p=await l.json(),f=Math.max(0,(F()-c)/1e6);return rp(p,f,e)},async*stream(a,u){let d=Cs(a,u,t.model,!0,t.bodyExtras),c=await s(`${n}/chat/completions`,{method:"POST",headers:{...i(),accept:"text/event-stream"},body:JSON.stringify(d),signal:u?.signal});if(!c.ok)throw await ht(c,e);if(!c.body)throw new Error(`openAICompatAdapter[${e}]: streaming response has no body`);let l,p;for await(let f of Lt(c.body,{signal:u?.signal})){if(!f.data||f.data==="[DONE]")continue;let m;try{m=JSON.parse(f.data)}catch{continue}let g=m.choices;if(g){let h=g[0];if(h?.delta?.content&&(yield{type:"token",delta:h.delta.content}),h?.delta?.reasoning_content&&(yield{type:"thinking",delta:h.delta.reasoning_content}),h?.delta?.tool_calls)for(let y of h.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:y.id,name:y.function?.name,argumentsDelta:y.function?.arguments}};h?.finish_reason&&(p=h.finish_reason)}m.usage&&(l=m.usage,yield{type:"usage",usage:Da(l)})}yield{type:"finish",reason:p??"stop"}}}}function Ah(t){let e=t.sdk;if(!e)throw new Error("sdkBackedOpenAI: sdk instance required");let{provider:n}=op(t);return{provider:n,model:t.model,async invoke(r,s){let o=Cs(r,s,t.model,!1,t.bodyExtras),i=F(),a=await e.chat.completions.create(o,{signal:s?.signal}),u=Math.max(0,(F()-i)/1e6);return rp(a,u,n)},async*stream(r,s){let o=Cs(r,s,t.model,!0,t.bodyExtras),i=await e.chat.completions.create(o,{signal:s?.signal}),a,u;for await(let d of i){let c=d.choices;if(c){let p=c[0];if(p?.delta?.content&&(yield{type:"token",delta:p.delta.content}),p?.delta?.reasoning_content&&(yield{type:"thinking",delta:p.delta.reasoning_content}),p?.delta?.tool_calls)for(let f of p.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:f.id,name:f.function?.name,argumentsDelta:f.function?.arguments}};p?.finish_reason&&(u=p.finish_reason)}let l=d.usage;l&&(a=l,yield{type:"usage",usage:Da(l)})}yield{type:"finish",reason:u??"stop"}}}}function Lh(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 _a(e)}case"google":{let e={apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return Aa(e)}case"dry-run":{let e={model:t.model,...t.extras};return bn(e)}case"fallback":{let e={provider:t.provider,model:t.model,...t.extras};return Ca(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 Ia(e)}default:{let e=t.provider;throw new Error(`createAdapter: unknown provider: ${String(e)}`)}}}Ne();Q();Te();function gt(t){let e=t.input,n=e.regular+(e.cacheRead??0)+(e.cacheWrite5m??0)+(e.cacheWrite1h??0)+(e.cacheWriteOther??0)+(e.audio??0)+(e.image??0)+(e.video??0)+(e.toolUse??0);if(!e.extensions)return n;let r=0;for(let s of Object.values(e.extensions))r+=s;return n+r}function It(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 s of Object.values(e.extensions))r+=s;return n+r}function sp(){return{input:{regular:0},output:{regular:0}}}function Ih(t,e){let n=e?.logMax??1e3,r=Ue(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:n}),s=N(null,{name:"adapterStats/lastCall"}),o=_([r.entries],([g])=>g.length,{name:"adapterStats/totalCalls",initial:0}),i=_([r.entries],([g])=>g.reduce((h,y)=>h+gt(y.usage),0),{name:"adapterStats/totalInputTokens",initial:0}),a=_([r.entries],([g])=>g.reduce((h,y)=>h+It(y.usage),0),{name:"adapterStats/totalOutputTokens",initial:0}),u=[re(o),re(i),re(a)],d=g=>{r.append(g),s.emit(g)},c=()=>{r.clear(),s.emit(null)},l=et(t,{invoke(g,h){let y=F(),b=ce(),v=t.model??h?.model??"",T=k=>(d(vn({provider:t.provider,model:t.model??h?.model??k.model??"",tier:h?.tier??k.tier,usage:k.usage??kt(),startNs:y,startWallClockNs:b,method:"invoke"})),k),w=k=>{let x=k;d(vn({provider:t.provider,model:v,tier:h?.tier,usage:kt(),startNs:y,startWallClockNs:b,method:"invoke",error:{type:x?.name??"Error",message:x?.message??String(k)}}))};return Ms(t.invoke(g,h),{onResp:T,onError:w,name:"adapterStats/invokeTap"})},async*stream(g,h){let y=F(),b=ce(),v=t.model??h?.model??"",T;try{for await(let w of t.stream(g,h))w.type==="usage"&&(T=w.usage),yield w;d(vn({provider:t.provider,model:v,tier:h?.tier,usage:T??kt(),startNs:y,startWallClockNs:b,method:"stream"}))}catch(w){let k=w;throw d(vn({provider:t.provider,model:v,tier:h?.tier,usage:T??kt(),startNs:y,startWallClockNs:b,method:"stream",error:{type:k?.name??"Error",message:k?.message??String(w)}})),w}}});Je(l,"observableAdapter",t);let p=!1;return{adapter:l,stats:{lastCall:s,allCalls:r,totalCalls:o,totalInputTokens:i,totalOutputTokens:a,reset:c,dispose:()=>{if(!p){p=!0;for(let g of u)g();u.length=0}}}}}function Dh(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function Ls(t="USD"){return{total:0,currency:t}}function Pa(t,e,n){let r=gt(t),s=e.currency??"USD",o=n?.withBreakdown===!0,i=o?{}:null,a=0,u=(h,y,b)=>{if(!y||b==null)return;let v=Dh(b,r),T=y*v/1e6;a+=T,o&&(i[h]=(i[h]??0)+T)},d=t.input,c=e.input;if(c&&(u("input.regular",d.regular,c.regular),u("input.cacheRead",d.cacheRead??0,c.cacheRead),u("input.cacheWrite5m",d.cacheWrite5m??0,c.cacheWrite5m),u("input.cacheWrite1h",d.cacheWrite1h??0,c.cacheWrite1h),u("input.cacheWriteOther",d.cacheWriteOther??0,c.cacheWriteOther),u("input.audio",d.audio??0,c.audio),u("input.image",d.image??0,c.image),u("input.video",d.video??0,c.video),u("input.toolUse",d.toolUse??0,c.toolUse),d.extensions&&c.extensions))for(let[h,y]of Object.entries(d.extensions))u(`input.ext.${h}`,y,c.extensions[h]);let l=t.output,p=e.output;if(p&&(u("output.regular",l.regular,p.regular),u("output.reasoning",l.reasoning??0,p.reasoning),u("output.audio",l.audio??0,p.audio),u("output.predictionAccepted",l.predictionAccepted??0,p.predictionAccepted),u("output.predictionRejected",l.predictionRejected??0,p.predictionRejected),l.extensions&&p.extensions))for(let[h,y]of Object.entries(l.extensions))u(`output.ext.${h}`,y,p.extensions[h]);let f=n?.tier;if(f&&e.tierMultipliers){let h=e.tierMultipliers[f];if(h!=null&&(a*=h,o))for(let y of Object.keys(i))i[y]*=h}let m=t.auxiliary,g=e.auxiliary;if(m&&g)for(let[h,y]of Object.entries(m)){let b=g[h];if(b==null||!y)continue;let v=y*b;a+=v,o&&(i[`auxiliary.${h}`]=v)}return o?{total:a,currency:s,breakdown:i}:{total:a,currency:s}}function As(t,e){return`${t}::${e}`}function Ph(t){let e=new Map,n=new Map,r=(s,o,i)=>{e.set(As(s,o),{provider:s,model:o,pricing:i});let a=n.get(s);a||(a=new Set,n.set(s,a)),a.add(o)};if(t)for(let[s,o,i]of t)r(s,o,i);return{register:r,lookup(s,o){let i=e.get(As(s,o));if(i)return i.pricing;let a=n.get(s);if(!a)return;let u;for(let d of a)if(o.startsWith(d)&&(!u||d.length>u.key.length)){let c=e.get(As(s,d));c&&(u={key:d,pricing:c.pricing})}return u?.pricing},remove(s,o){let i=e.delete(As(s,o));if(i){let a=n.get(s);a?.delete(o),a&&a.size===0&&n.delete(s)}return i},entries(){let s=e.values();return(function*(){for(let{provider:o,model:i,pricing:a}of s)yield[o,i,a]})()}}}function Gh(t,e="USD"){return(n,r)=>{let s=t.lookup(r.provider,r.model);return s?Pa(n,s,{tier:r.tier,withBreakdown:r.withBreakdown}):Ls(e)}}function Fh(...t){return(e,n)=>{for(let r of t){let s=r(e,n);if(s.total!==0)return s}return t.length>0?t[0](e,n):Ls()}}function $h(t,e,n){return t?.pricing?Pa(e,t.pricing,n):Ls()}Et();Te();function Ga(t,e={}){let n=e.breaker??Tt(e),r=et(t,{async invoke(s,o){if(!n.canExecute())throw new lt;try{let i=await Qe(W(t.invoke(s,o)));return n.recordSuccess(),i}catch(i){throw n.recordFailure(i),i}},async*stream(s,o){if(!n.canExecute())throw new lt;try{for await(let i of t.stream(s,o))yield i;n.recordSuccess()}catch(i){throw n.recordFailure(i),i}}});return Je(r,"withBreaker",t),{adapter:r,breaker:n}}Ne();se();Q();Te();var Is=class extends Error{constructor(n,r,s){super(`Budget exhausted: ${n} (limit=${r}, observed=${s})`);this.which=n;this.limit=r;this.observed=s}name="BudgetExhaustedError"},Fa=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),ip=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function $a(t,e){let n=Ue(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),r=N(ip(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),s=_([r],([d])=>{let c=d;return!(e.caps.calls!=null&&c.calls>=e.caps.calls||e.caps.inputTokens!=null&&c.inputTokens>=e.caps.inputTokens||e.caps.outputTokens!=null&&c.outputTokens>=e.caps.outputTokens||e.caps.usd!=null&&c.usd>=e.caps.usd)},{name:e.name?`${e.name}/isOpen`:"budgetGate/isOpen",initial:!0});if(re(s),e.onExhausted!=null){let d=e.onExhausted,c=!1,l=!0;s.subscribe(p=>{for(let f of p)if(f[0]===R){let m=f[1];if(c&&l&&m===!1){let g=ap(r.cache??Fa,e.caps);g&&d(g)}l=m,c=!0}})}let o=()=>{if(s.cache===!1){let d=r.cache??Fa,c=ap(d,e.caps);return new Is(c??"budget",e.caps[c??"calls"]??0,jh(d,c??"calls"))}},i=(d,c)=>{let l=t.provider,p=vn({provider:l,model:c.model,tier:c.tier,usage:d,startNs:c.startNs,method:c.method,...c.error?{error:c.error}:{}});n.append(p);let f=r.cache??Fa,m=e.pricingFn?f.usd+e.pricingFn(d,{model:c.model,provider:l,tier:c.tier}).total:f.usd;r.emit({calls:f.calls+1,inputTokens:f.inputTokens+gt(d),outputTokens:f.outputTokens+It(d),usd:m})},a=()=>{n.clear(),r.emit(ip())},u=et(t,{invoke(d,c){let l=o();if(l)return Promise.reject(l);let p=F(),f=t.model??c?.model??"",m=h=>(i(h.usage??kt(),{model:t.model??c?.model??h.model??"",tier:c?.tier??h.tier,startNs:p,method:"invoke"}),h),g=h=>{let y=h;i(kt(),{model:f,tier:c?.tier,startNs:p,method:"invoke",error:{type:y?.name??"Error",message:y?.message??String(h)}})};return Ms(t.invoke(d,c),{onResp:m,onError:g,name:"budgetGate/invokeTap"})},async*stream(d,c){let l=o();if(l)throw l;let p=F(),f;try{for await(let m of t.stream(d,c))m.type==="usage"&&(f=m.usage),yield m;i(f??kt(),{model:t.model??c?.model??"",tier:c?.tier,startNs:p,method:"stream"})}catch(m){let g=m;throw i(f??kt(),{model:t.model??c?.model??"",tier:c?.tier,startNs:p,method:"stream",error:{type:g?.name??"Error",message:g?.message??String(m)}}),m}}});return Je(u,"withBudgetGate",t),{adapter:u,budget:{totals:r,isOpen:s,log:n,reset:a}}}function ap(t,e){if(e.calls!=null&&t.calls>=e.calls)return"calls";if(e.inputTokens!=null&&t.inputTokens>=e.inputTokens)return"inputTokens";if(e.outputTokens!=null&&t.outputTokens>=e.outputTokens)return"outputTokens";if(e.usd!=null&&t.usd>=e.usd)return"usd"}function jh(t,e){switch(e){case"calls":return t.calls;case"inputTokens":return t.inputTokens;case"outputTokens":return t.outputTokens;case"usd":return t.usd}}Te();function Bh(t,e){let n=e.mock??bn({provider:t.provider,model:t.model}),r=typeof e.enabled=="boolean"?e.enabled:void 0,s=r===void 0?W(e.enabled):void 0,o;s&&(o=re(s));let i=()=>r!==void 0?r:!!s?.cache,a=et(t,{invoke(d,c){return i()?n.invoke(d,c):t.invoke(d,c)},stream(d,c){return i()?n.stream(d,c):t.stream(d,c)}});return Je(a,"withDryRun",t),{adapter:a,dispose:()=>{o&&(o(),o=void 0)}}}function ja(t){if(t==null||typeof t!="object")return;let e=t,n=e.status,r=Vh(e.headers);if(n!==429&&n!==503&&!zh(e.message))return;let s={},o=r("retry-after"),i=Hh(o);i!=null&&(s.retryAfterMs=i);let a=r("anthropic-ratelimit-requests-reset");if(a){let f=up(a);f!=null&&(s.retryAfterMs=Math.max(s.retryAfterMs??0,f))}let u=r("anthropic-ratelimit-tokens-reset");if(u){let f=up(u);f!=null&&(s.retryAfterMs=Math.max(s.retryAfterMs??0,f))}let d=Ds(r,"x-ratelimit-limit-requests");d!=null&&(s.rpmCap=d);let c=Ds(r,"x-ratelimit-limit-tokens");c!=null&&(s.tpmCap=c);let l=Ds(r,"x-ratelimit-remaining-requests"),p=Ds(r,"x-ratelimit-remaining-tokens");if(l!=null&&d!=null&&d>0&&(s.usageHint??={},s.usageHint.rpm=1-l/d),p!=null&&c!=null&&c>0&&(s.usageHint??={},s.usageHint.tpm=1-p/c),s.retryAfterMs==null&&e.message){let f=Wh(e.message);f!=null&&(s.retryAfterMs=f)}return e.headers&&(s.metadata={headers:Kh(e.headers)}),s.retryAfterMs==null&&s.rpmCap==null&&s.tpmCap==null&&s.usageHint==null?s.metadata?s:void 0:s}function Vh(t){if(!t)return()=>{};if(typeof t.get=="function"){let r=t;return s=>r.get(s)??r.get(s.toLowerCase())??void 0}let e=t,n={};for(let[r,s]of Object.entries(e)){let o=Array.isArray(s)?s.join(", "):s;o!=null&&(n[r.toLowerCase()]=o)}return r=>n[r.toLowerCase()]}function Kh(t){let e={};if(typeof t.forEach=="function")return t.forEach((n,r)=>{e[r]=n}),e;for(let[n,r]of Object.entries(t))r!=null&&(e[n]=Array.isArray(r)?r.join(", "):r);return e}function Ds(t,e){let n=t(e);if(n==null)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function Hh(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 s=r-Date.now();if(s>0)return s}}function up(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var qh=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function Wh(t){let e=qh.exec(t);if(!e)return;let n=Number(e[1]);if(!Number.isFinite(n))return;let r=(e[2]??"s").toLowerCase();if(r==="ms")return n;if(r.startsWith("s"))return n*1e3;if(r.startsWith("m"))return n*6e4}var Uh=/rate\s*limit|too\s*many\s*requests|quota|429/i;function zh(t){return!!t&&Uh.test(t)}Ne();se();Q();Et();Te();vt();function Ba(t){let e=new Error(t);return e.name="AbortError",e}function cp(t={}){let e=Math.max(1,t.burstMultiplier??1),n=t.clampCooldownMs??6e4,r=t.rpm!=null?W(t.rpm):N(Number.POSITIVE_INFINITY),s=t.tpm!=null?W(t.tpm):N(Number.POSITIVE_INFINITY),o=N(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),i=N(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),a=N({},{name:"adaptiveRateLimiter/lastSignal"}),u=_([r,o],([A,P])=>Math.min(Number(A??1/0),Number(P??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),d=_([s,i],([A,P])=>Math.min(Number(A??1/0),Number(P??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),c=nr(Number(r.cache??Number.POSITIVE_INFINITY),e),l=nr(Number(s.cache??Number.POSITIVE_INFINITY),e),p=!1,f=!1,m=u.subscribe(A=>{for(let P of A)if(P[0]===R){let U=Number(P[1]);Number.isFinite(U)&&U>0?(c=nr(U,e),p=!1):U===1/0?(c=nr(1/0,e),p=!1):U<=0&&(p=!0)}}),g=d.subscribe(A=>{for(let P of A)if(P[0]===R){let U=Number(P[1]);Number.isFinite(U)&&U>0?(l=nr(U,e),f=!1):U===1/0?(l=nr(1/0,e),f=!1):U<=0&&(f=!0)}}),h=0,y=new Le,b=new Le,v;t.adaptation!=null&&(v=W(t.adaptation).subscribe(P=>{for(let U of P)U[0]===R&&T(U[1])}));function T(A){if(a.emit(A),A.rpmCap!=null&&Number.isFinite(A.rpmCap)&&A.rpmCap>=0&&(o.emit(A.rpmCap),Number.isFinite(n)&&n>0&&y.start(n,()=>o.emit(Number.POSITIVE_INFINITY))),A.tpmCap!=null&&Number.isFinite(A.tpmCap)&&A.tpmCap>=0&&(i.emit(A.tpmCap),Number.isFinite(n)&&n>0&&b.start(n,()=>i.emit(Number.POSITIVE_INFINITY))),A.retryAfterMs!=null&&A.retryAfterMs>0){let P=F()+A.retryAfterMs*1e6;P>h&&(h=P)}}let w=N(0,{name:"adaptiveRateLimiter/pending"}),k=N(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),x=N(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),S=A=>{w.emit((w.cache??0)+A)},E=()=>{k.emit(c.available()),x.emit(l.available())};async function L(A={}){let P=A.requestCost??1,U=A.tokenCost??0,z=A.signal;S(1);try{for(;;){if(z?.aborted)throw Ba("AdaptiveRateLimiter.acquire aborted");let D=F();if(h>D){let K=Math.ceil((h-D)/1e6);await Ps(K,z);continue}if(P>0&&p||U>0&&f){await Ps(250,z);continue}let Z=c,te=l;if(!Z.tryConsume(P)){await Ps(dp(Z,P),z);continue}if(!(U>0?te.tryConsume(U):!0)){Z.putBack(P),await Ps(dp(te,U),z);continue}E();return}}finally{S(-1)}}function C(A){A>0?l.tryConsume(A):A<0&&l.putBack(-A),E()}function I(){m(),g(),v?.(),y.cancel(),b.cancel()}return{effectiveRpm:u,effectiveTpm:d,lastSignal:a,pending:w,rpmAvailable:k,tpmAvailable:x,acquire:L,recordUsage:C,recordSignal:T,dispose:I}}function nr(t,e){if(!Number.isFinite(t)||t===1/0)return jt(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let n=Math.max(1,t*e),r=t/60;return jt(n,r)}function dp(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 Ps(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Ba("AdaptiveRateLimiter.acquire aborted")):new Promise((n,r)=>{let s=new Le,o,i=()=>{s.cancel(),e&&o&&e.removeEventListener("abort",o)};s.start(t,()=>{i(),n()}),e&&(o=()=>{i(),r(Ba("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",o,{once:!0}))})}Te();function Va(t,e={}){let n=e.limiter??cp({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,s=i=>{let a=ja(i);a&&n.recordSignal(a)},o=et(t,{async invoke(i,a){let u=r(i,a);await n.acquire({requestCost:1,tokenCost:u,signal:a?.signal});try{let d=await Qe(W(t.invoke(i,a))),c=d.usage??sp(),p=gt(c)+It(c)-u;return p>0&&n.recordUsage(p),d}catch(d){throw s(d),d}},async*stream(i,a){let u=r(i,a);await n.acquire({requestCost:1,tokenCost:u,signal:a?.signal});try{let d=0;for await(let l of t.stream(i,a))l.type==="usage"&&(d=gt(l.usage)+It(l.usage)),yield l;let c=d-u;c>0&&n.recordUsage(c)}catch(d){throw s(d),d}}});return Je(o,"withRateLimiter",t),{adapter:o,limiter:n}}Et();Te();var oo=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 Ka(t,e={}){if(t.length===0)throw new RangeError("cascadingLlmAdapter: tiers must be non-empty");let n=t.map(o=>({name:o.name,adapter:o.adapter,filter:o.filter,breaker:o.breaker?"canExecute"in o.breaker?o.breaker:Tt(o.breaker):void 0})),r=e.streamRetryBeforeFirstChunk??!0,s={provider:"cascading",model:void 0,async invoke(o,i){let a=[],u=new Map;for(let c=0;c<n.length;c++){let l=n[c];if(l.filter&&!l.filter(o,i)){a.push({name:l.name,reason:"filter"});continue}if(l.breaker&&!l.breaker.canExecute()){a.push({name:l.name,reason:"breaker"});continue}try{let p=await Qe(W(l.adapter.invoke(o,i)));return l.breaker?.recordSuccess(),{...p,metadata:{...p.metadata??{},tier:l.name}}}catch(p){u.set(l.name,p),l.breaker?.recordFailure(p);let f=n[c+1];f&&e.onFallback?.(l.name,f.name,p)}}let d={skipped:a,failed:u};throw e.onExhausted?.(d),new oo(d)},async*stream(o,i){let a=[],u=new Map;for(let c=0;c<n.length;c++){let l=n[c];if(l.filter&&!l.filter(o,i)){a.push({name:l.name,reason:"filter"});continue}if(l.breaker&&!l.breaker.canExecute()){a.push({name:l.name,reason:"breaker"});continue}let p=!1;try{for await(let f of l.adapter.stream(o,i))p=!0,yield f;l.breaker?.recordSuccess();return}catch(f){if(u.set(l.name,f),l.breaker?.recordFailure(f),p||!r)throw f;let m=n[c+1];m&&e.onFallback?.(l.name,m.name,f)}}let d={skipped:a,failed:u};throw e.onExhausted?.(d),new oo(d)}};return Je(s,`cascade[${n.map(o=>o.name).join(",")}]`),s}function Jh(t,e,n){let r={name:t,adapter:e};return n?.breaker&&(r.breaker=n.breaker),n?.filter&&(r.filter=n.filter),r}Te();vt();function Gs(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function lp(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Gs()):new Promise((n,r)=>{let s=new Le,o,i=()=>{s.cancel(),e&&o&&e.removeEventListener("abort",o)};s.start(t,()=>{i(),n()}),e&&(o=()=>{i(),r(Gs())},e.addEventListener("abort",o,{once:!0}))})}function Ha(t,e={}){let n=e.attempts??3,r=e.baseDelayMs??500,s=e.maxDelayMs??1e4,o=e.strategy??"decorrelated",i=e.jitter??!0,a=e.shouldRetry??Yh,u=e.retryStreaming??!0,d=(l,p)=>{if(o==="decorrelated"){let h=Math.min(s,Math.max(r,p*3));return r+Math.random()*(h-r)}let f=o==="exp"?r*2**(l-1):r*l,m=Math.min(s,f);if(!i)return m;let g=m*(.5+Math.random());return Math.min(s,g)},c=et(t,{async invoke(l,p){if(p?.signal?.aborted)throw Gs();let f,m=r;for(let g=1;g<=n;g++)try{return await Qe(W(t.invoke(l,p)))}catch(h){if(f=h,g>=n||!a(h,g))throw h;let y=d(g,m);m=y,await lp(y,p?.signal)}throw f},async*stream(l,p){if(p?.signal?.aborted)throw Gs();if(!u){for await(let g of t.stream(l,p))yield g;return}let f,m=r;for(let g=1;g<=n;g++){let h=!1;try{for await(let y of t.stream(l,p))h=!0,yield y;return}catch(y){if(f=y,h||g>=n||!a(y,g))throw y;let b=d(g,m);m=b,await lp(b,p?.signal)}}throw f}});return Je(c,"withRetry",t),c}function Yh(t,e){if(t==null)return!1;let n=t;return n.name==="LLMTimeoutError"?!0:n.name==="AbortError"||n.message==="aborted"||n.name==="DOMException"&&n.code!=null&&Number(n.code)===20||n.name==="BudgetExhaustedError"||n.name==="CircuitOpenError"?!1:n.status!=null?n.status===429||n.status>=500&&n.status<600:n.code&&typeof n.code=="string"&&/^E[A-Z]+$/.test(n.code)?!0:n.message?/network|timeout|socket|fetch|econn|eai_/i.test(n.message):!1}Te();vt();var rr=class extends Error{constructor(n){super(`LLM call timed out after ${n}ms`);this.ms=n}name="LLMTimeoutError"};function qa(t,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let n=o=>{let i=new AbortController,a=!1,u,d=new Le;return o&&(o.aborted?i.abort(o.reason):(u=()=>{d.cancel(),i.abort(o.reason)},o.addEventListener("abort",u,{once:!0}))),d.start(e,()=>{a=!0,i.abort(new rr(e))}),{signal:i.signal,cancel:()=>{d.cancel(),o&&u&&o.removeEventListener("abort",u)},timedOut:()=>a}},r=(o,i)=>{if(!i||o instanceof rr)throw o;let a=o;if(a?.name==="AbortError"||a?.name==="DOMException"&&Number(a.code)===20||o?.message==="aborted"){let d=new rr(e);throw d.cause=o,d}throw o},s=et(t,{async invoke(o,i){let{signal:a,cancel:u,timedOut:d}=n(i?.signal);try{return await Qe(W(t.invoke(o,{...i,signal:a})))}catch(c){return r(c,d())}finally{u()}},async*stream(o,i){let{signal:a,cancel:u,timedOut:d}=n(i?.signal);try{for await(let c of t.stream(o,{...i,signal:a}))yield c}catch(c){r(c,d())}finally{u()}}});return Je(s,"withTimeout",t),s}function Qh(t,e={}){let n={adapter:t},r=t;if(e.rateLimit){let s=Va(r,e.rateLimit);r=s.adapter,n.rateLimiter=s.limiter}if(e.budget){let s=$a(r,e.budget);r=s.adapter,n.budget=s.budget}if(e.breaker){let s=Ga(r,e.breaker);r=s.adapter,n.breaker=s.breaker}if(e.timeoutMs!=null&&(r=qa(r,e.timeoutMs)),e.retry&&(r=Ha(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 s={};e.onFallback&&(s.onFallback=e.onFallback),e.onExhausted&&(s.onExhausted=e.onExhausted),r=Ka([{name:e.name??"primary",adapter:r},{name:"fallback",adapter:e.fallback}],s)}return e.cache&&(r=ro(r,e.cache)),n.adapter=r,n}Q();Te();function Xh(t,e,n){let r=W(e);return be(r,o=>{if(!o||o.length===0)return N(null);let i=n?.tools;return t.invoke(o,{model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,tools:i,systemPrompt:n?.systemPrompt})})}_e();Te();se();Te();vt();function pe(t,e){return ze("ai",t,e)}function Zh(t){return t!=null&&typeof t.then=="function"}function Wa(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function eg(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var tg=3e4;function pp(t,e){if(t.status==="settled"){let r=t.cache;if(r!==void 0)return Promise.resolve(r)}let n=e?.timeoutMs??tg;return new Promise((r,s)=>{let o=new Le,i=t.subscribe(a=>{for(let u of a){if(u[0]===R){o.cancel(),i(),r(u[1]);return}if(u[0]===M){o.cancel(),i(),s(u[1]);return}if(u[0]===O){o.cancel(),i(),s(new Error("firstDataFromNode: completed without producing a value"));return}}});o.start(n,()=>{i(),s(new Error(`firstDataFromNode: timed out after ${n}ms`))})})}async function so(t){return Zh(t)?so(await t):Wa(t)?pp(t):eg(t)?pp(W(t)):t}function or(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function ng(t,e){let n=W(t),r=e?.refreshTrigger!=null?W(e.refreshTrigger):null;return r==null?V([n],(s,o,i)=>{if(i.store.emitted===!0)return;let u=s[0],d=u!=null&&u.length>0?u.at(-1):i.prevData[0];if(d!==void 0)return i.store.emitted=!0,o.emit(d),{invalidate:()=>{i.store.emitted=!1}}},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:pe("frozen_context")}):V([n,r],(s,o,i)=>{let a=s[1];if(!(a!=null&&a.length>0))return;let d=s[0],c=d!=null&&d.length>0?d.at(-1):i.prevData[0];o.emit(c)},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:pe("frozen_context")})}se();Q();Te();function fp(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function rg(t,e=200){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function wn(t,e,n,r){let s=r?.format??"text",o=r?.name??"prompt_node",i=_(e,u=>{if(u.some(c=>c==null))return[];let d=typeof n=="string"?n:n(...u);return d?[{role:"user",content:d}]:[]},{name:`${o}::messages`,meta:pe("prompt_node")});return be(i,u=>!u||u.length===0?N(null):$(d=>{let c=!1,l=!1,p,f={model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt};if(r?.abort){let y=Uo(r.abort);f.signal=y.signal,p=y.dispose}let m;try{m=t.invoke(u,f)}catch(y){return c=!0,d.down([[M,y]]),()=>{p?.()}}let h=W(m).subscribe(y=>{if(!(l||c))for(let b of y){if(c)return;if(b[0]===R){let v=b[1];try{let T=fp(v),w=s==="json"?JSON.parse(or(T)):T;d.emit(w)}catch(T){let w=fp(v),k=new Error(`promptNode: failed to parse LLM response as JSON: ${T.message}
37
+ Raw content (first 200 chars): ${rg(w)}`);c=!0,d.down([[M,k]]);return}}else if(b[0]===M){c=!0,d.down([[M,b[1]]]);return}else if(b[0]===O){c=!0,d.down([[O]]);return}else d.down([b])}});return()=>{l=!0,h(),p?.()}},{name:`${o}::call`,meta:pe("prompt_node::call")}),{name:`${o}::output`,meta:r?.meta?{...pe("prompt_node::output"),...r.meta}:pe("prompt_node::output")})}Ce();Ne();Q();Te();var Ks={};we(Ks,{MessagingHubGraph:()=>js,SubscriptionGraph:()=>io,TopicBridgeGraph:()=>$s,TopicGraph:()=>xn,messagingHub:()=>ao,subscription:()=>mp,topic:()=>Bs,topicBridge:()=>Vs});_e();var og=2147483647;function Fs(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function kn(t,e){return ze("messaging",t,e)}var xn=class extends q{_log;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=Ue([],{name:"events",maxSize:n.retainedLimit}),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=_([this.events],([r])=>{let s=r;return s.length===0?null:s[s.length-1]},{name:"latest",describeKind:"derived",meta:kn("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(re(this.latest)),this.hasLatest=_([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:kn("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(re(this.hasLatest)),this.addDisposer(()=>{this.events.down([[O]])}),this.addDisposer(()=>this._log.disposeAllViews())}publish(e){this._log.append(e)}retained(){return this.events.cache}},io=class extends q{source;cursor;available;topic;constructor(e,n,r={}){super(e,r.graph);let s=Fs(r.cursor??0,"subscription cursor");this.topic=n;let o=n.events;this.source=_([o],([i])=>i,{name:"source",describeKind:"derived",meta:kn("subscription_source"),initial:o.cache}),this.add(this.source,{name:"source"}),this.cursor=N(s,{name:"cursor",describeKind:"state",meta:kn("subscription_cursor")}),this.add(this.cursor,{name:"cursor"}),this.available=_([this.source,this.cursor],([i,a])=>{let u=i,d=Math.max(0,Math.trunc(a??0));return u.slice(d)},{name:"available",describeKind:"derived",meta:kn("subscription_available"),initial:[]}),this.add(this.available,{name:"available"}),this.addDisposer(re(this.source)),this.addDisposer(re(this.available))}ack(e){let n=this.available.cache,r=e===void 0?n.length:Fs(e,"subscription ack count"),s=Math.min(r,n.length);if(s<=0)return this.cursor.cache;let o=this.cursor.cache+s;return this.cursor.emit(o),o}pull(e,n={}){let r=this.available.cache,s=e===void 0?r.length:Fs(e,"subscription pull limit"),o=r.slice(0,s);return n.ack&&o.length>0&&this.ack(o.length),o}},$s=class extends q{_sourceSub;_target;bridgedCount;constructor(e,n,r,s={}){super(e,s.graph),this._sourceSub=mp(`${e}-subscription`,n,{cursor:s.cursor}),this._target=r,this.mount("subscription",this._sourceSub),this.bridgedCount=N(0,{name:"bridgedCount",describeKind:"state",meta:kn("topic_bridge_count")}),this.add(this.bridgedCount,{name:"bridgedCount"});let o=Math.max(1,Fs(s.maxPerPump??og,"topic bridge maxPerPump")),i=s.map??(u=>u),a=V([this._sourceSub.available],()=>{let u=this._sourceSub.pull(o,{ack:!0});if(u.length===0)return;let d=0;for(let c of u){let l=i(c);l!==void 0&&(this._target.publish(l),d+=1)}if(d>0){let c=this.bridgedCount.cache;this.bridgedCount.emit(c+d)}},{name:"pump",describeKind:"effect",meta:kn("topic_bridge_pump")});this.add(a,{name:"pump"}),this.addDisposer(re(a))}},js=class extends q{_topics=new Map;_version=0;_defaultTopicOptions;constructor(e,n={}){super(e,n.graph),this._defaultTopicOptions={...n.defaultTopicOptions??{}}}get version(){return this._version}get size(){return this._topics.size}has(e){return this._topics.has(e)}topicNames(){return this._topics.keys()}topic(e,n){let r=this._topics.get(e);if(r===void 0){let s={...this._defaultTopicOptions,...n??{}};r=new xn(e,s),this._topics.set(e,r),this.mount(e,r),this._version+=1}return r}publish(e,n){this.topic(e).publish(n)}publishMany(e){Y(()=>{for(let[n,r]of e)this.topic(n).publish(r)})}subscribe(e,n,r){let s=this.topic(n);return new io(e,s,r)}removeTopic(e){if(!this._topics.has(e))return!1;try{this.remove(e)}finally{this._topics.delete(e),this._version+=1}return!0}};function Bs(t,e){return new xn(t,e)}function ao(t,e){return new js(t,e)}function mp(t,e,n){return new io(t,e,n)}function Vs(t,e,n,r){return new $s(t,e,n,r)}var Hs={};we(Hs,{approval:()=>ug,branch:()=>ag,gate:()=>uo,join:()=>dg,loop:()=>cg,onFailure:()=>fg,pipeline:()=>gp,sensor:()=>pg,subPipeline:()=>lg,task:()=>ig});Ce();se();_e();Q();function Dt(t,e){if(typeof e=="string")return{node:t.resolve(e),path:e};let n=hp(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 hp(t,e){let n=t.describe(),r=`::${We}::`;for(let s of Object.keys(n.nodes).sort())if(!s.includes(r))try{if(t.resolve(s)===e)return s}catch{}}function Ut(t,e,n,r){t.add(n,{name:e})}function zt(t,e){return ze("orchestration",t,e)}function sg(t){let e=r=>{let s=r.trim();return s.length===0?0:Number(s)},n;return typeof t=="string"?n=e(t):t===null?n=0:n=Number(t),Number.isFinite(n)?Math.max(0,Math.trunc(n)):1}function gp(t,e){return new q(t,e)}function ig(t,e,n,r){let o=(r?.deps??[]).map(c=>Dt(t,c)),{deps:i,...a}=r??{},u=(c,l,p)=>{let f=c.map((m,g)=>m!=null&&m.length>0?m.at(-1):p.prevData[g]);l.emit(n(f,p))},d=V(o.map(c=>c.node),u,{...a,name:e,describeKind:"derived",meta:zt("task",r?.meta)});return Ut(t,e,d,o.flatMap(c=>c.path?[c.path]:[])),d}function ag(t,e,n,r,s){let o=Dt(t,n),i=_([o.node],([a])=>({branch:r(a)?"then":"else",value:a}),{...s,name:e,meta:zt("branch",s?.meta)});return Ut(t,e,i,o.path?[o.path]:[]),i}function ug(t,e,n,r,s){let o=Dt(t,n),i=Dt(t,r),a=s?.isApproved??(d=>!!d),u=V([o.node,i.node],(d,c,l)=>{let p=d[0],f=d[1],m=f!=null&&f.length>0?f.at(-1):l.prevData[1];if(m===void 0||!a(m)){c.down([[G]]);return}if(p==null||p.length===0){f!=null&&f.length>0&&l.prevData[0]!==void 0?c.emit(l.prevData[0]):c.down([[G]]);return}for(let g of p)c.emit(g)},{...s,name:e,describeKind:"derived",meta:zt("approval",s?.meta)});return Ut(t,e,u,[o.path,i.path].filter(d=>typeof d=="string")),u}function uo(t,e,n,r){let s=r?.maxPending??1/0;if(s<1&&s!==1/0)throw new RangeError("gate: maxPending must be >= 1");let o=r?.startOpen??!1;typeof n!="string"&&!hp(t,n)&&t.add(n,{name:`${e}/source`});let i=Dt(t,n),a=N([],{name:"pending",equals:()=>!1}),u=N(o,{name:"isOpen"}),d=_([a],([k])=>k.length,{name:"count"}),c=N(null,{name:"lastRejected",equals:()=>!1}),l=[],p=!1,f=o,m=u.subscribe(k=>{for(let x of k)x[0]===R&&(f=x[1])});function g(){a.emit([...l])}function h(k){l.push(k),l.length>s&&l.shift(),g()}function y(k){let x=l.splice(0,k);return g(),x}function b(k){if(p)throw new Error(`gate: ${k}() called after gate was torn down`)}let v=V([i.node],(k,x,S)=>{let E=S.terminalDeps[0];if(E!==void 0){p=!0,l=[],g(),x.down(E===!0?[[O]]:[[M,E]]);return}let L=k[0];if(L==null||L.length===0){x.down([[G]]);return}for(let C of L)f?x.emit(C):(h(C),x.down([[G]]))},{name:e,describeKind:"derived",meta:zt("gate",r?.meta)}),T={node:v,pending:a,count:d,isOpen:u,lastRejected:c,approve(k=1){b("approve");let x=y(k);for(let S of x){if(p)break;v.emit(S)}},reject(k=1){b("reject"),Y(()=>{let x=[...l],S=Math.min(k,x.length);for(let E=0;E<S;E++)c.emit(x[E]);y(k)})},modify(k,x=1){b("modify");let S=[...l],E=y(x);for(let L=0;L<E.length&&!p;L++)v.emit(k(E[L],L,S))},open(){b("open"),Y(()=>{u.emit(!0);let k=y(l.length);for(let x of k){if(p)break;v.emit(x)}})},close(){b("close"),u.emit(!1)}};t.addDisposer(d.subscribe(()=>{})),t.addDisposer(m),Ut(t,e,v,i.path?[i.path]:[]);let w=new q(`${e}_state`);return w.add(a,{name:"pending"}),w.add(u,{name:"isOpen"}),w.add(d,{name:"count"}),w.add(c,{name:"lastRejected"}),t.mount(`${e}_state`,w),t.addDisposer(c.subscribe(()=>{})),T}function dg(t,e,n,r){let s=n.map(i=>Dt(t,i)),o=_(s.map(i=>i.node),i=>i,{...r,name:e,meta:zt("join",r?.meta)});return Ut(t,e,o,s.flatMap(i=>i.path?[i.path]:[])),o}function cg(t,e,n,r,s){let o=Dt(t,n),i=s?.iterations,a=typeof i=="number"||i===void 0?void 0:Dt(t,i),u=typeof i=="number"?i:void 0,d=V(a?[o.node,a.node]:[o.node],(c,l,p)=>{let f=c[0],m=f!=null&&f.length>0?f.at(-1):p.prevData[0],g=a?c[1]:void 0,h=u??(a?g!=null&&g.length>0?g.at(-1):p.prevData[1]:1),y=sg(h);for(let b=0;b<y;b+=1)m=r(m,b,l);l.emit(m)},{...s,name:e,describeKind:"derived",meta:zt("loop",s?.meta)});return Ut(t,e,d,[o.path,a?.path].filter(c=>typeof c=="string")),d}function lg(t,e,n,r){let s=n instanceof q?n:gp(e,r);return typeof n=="function"&&n(s),t.mount(e,s),s}function pg(t,e,n,r){let s=V([],()=>{},{...r,name:e,initial:n,describeKind:"producer",meta:zt("sensor",r?.meta)});return Ut(t,e,s,[]),{node:s,push(o){s.emit(o)},error(o){s.down([[M,o]])},complete(){s.down([[O]])}}}function fg(t,e,n,r,s){let o=Dt(t,n),i=!1,a=V([],(u,d)=>{let c=o.node.subscribe(l=>{for(let p of l){if(i)return;if(p[0]===M)try{d.emit(r(p[1],d))}catch(f){i=!0,d.down([[M,f]])}else d.down([p]),p[0]===O&&(i=!0)}});return()=>c()},{...s,name:e,describeKind:"derived",completeWhenDepsComplete:!1,errorWhenDepsError:!1,meta:zt("onFailure",s?.meta)});return Ut(t,e,a,o.path?[o.path]:[]),a}async function yp(t,e,n,r){let s="",o=0;for await(let i of t.stream(e,n))r.publish({...i,seq:o++,ts:ce()}),i.type==="token"&&(s+=i.delta);return s}function bp(t,e){if(e==="json")try{return JSON.parse(or(t))}catch(n){let r=t.slice(0,160);throw new Error(`streamingPromptNode: format:"json" \u2014 failed to parse accumulated text as JSON: ${n.message}; content preview: ${r}`)}return t}function vp(t,e){return _([t.latest],([n],r)=>{let s=r.store;if(n==null)return s.acc??"";let o=n;return o.seq===0&&(s.acc=""),o.type==="token"&&(s.acc=(s.acc??"")+o.delta),s.acc??""},{name:e,meta:pe("accumulated_text"),initial:""})}function mg(t,e,n,r){let s=r?.name??"llm",o=r?.format??"text",i=Bs(`${s}/stream`,{...r?.retainedLimit!=null?{retainedLimit:r.retainedLimit}:{}}),a=_(e,l=>{if(l.some(f=>f==null))return[];let p=typeof n=="string"?n:n(...l);return p?[{role:"user",content:p}]:[]},{name:`${s}::messages`,meta:pe("prompt_node::messages"),initial:[]}),u=be(a,l=>{let p=l;if(!p||p.length===0)return N(null);let f=new AbortController;async function*m(){try{let g=await yp(t,p,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt,signal:f.signal},i);yield bp(g,o)}finally{f.abort()}}return W(m())}),d=vp(i,`${s}::accumulatedText`),c=re(u);return{output:u,deltaTopic:i,accumulatedText:d,dispose:()=>{c(),i.destroy()}}}function hg(t,e,n,r,s,o){let i=N(0,{name:`${e}/cancel`}),a=0,u=[...r,i],d=o?.name??e,c=o?.format??"text",l=Bs(`${d}/stream`,{...o?.retainedLimit!=null?{retainedLimit:o.retainedLimit}:{}}),p=_(u,k=>{let x=k.slice(0,-1);if(x.some(E=>E==null))return[];let S=typeof s=="string"?s:s(...x);return S?[{role:"user",content:S}]:[]},{name:`${d}::messages`,meta:pe("prompt_node::messages"),initial:[]}),f=be(p,k=>{let x=k;if(!x||x.length===0)return N(null);let S=new AbortController;async function*E(){try{let L=await yp(n,x,{model:o?.model,temperature:o?.temperature,maxTokens:o?.maxTokens,systemPrompt:o?.systemPrompt,signal:S.signal},l);yield bp(L,c)}finally{S.abort()}}return W(E())}),m=vp(l,`${d}::accumulatedText`),g=Xe(f,k=>k!=null);t.add(g,{name:`${e}/raw`});let h=uo(t,`${e}/gate`,`${e}/raw`,o?.gate),y=re(f),b=re(h.node),v=re(m);t.addDisposer(y),t.addDisposer(b),t.addDisposer(v);let T=h.reject.bind(h),w={...h,reject(k=1){Y(()=>{T(k),i.emit(++a)})}};return{output:h.node,deltaTopic:l,accumulatedText:m,gate:w,dispose:()=>{y(),b(),v(),l.destroy()}}}Q();Te();function gg(t,e){let n=e?.separator??`
38
38
 
39
- `,r=t.map(i=>typeof i=="string"?E(i):X(i)),o=_(r,i=>i.filter(a=>a!=null&&a!=="").join(n),{name:e?.name??"systemPrompt",describeKind:"derived",meta:ue("system_prompt"),initial:""}),s=se(o);return Object.assign(o,{dispose:s})}ee();var fg=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens&&t.estimated===e.estimated;function mg(t,e){let n=e?.charsPerToken??4,r={chunkCount:0,charCount:0,estimatedTokens:0,estimated:!0};return _([t.latest],([o],s)=>{if(o==null)return r;let i=o;"chunkCount"in s.store||(s.store.chunkCount=0,s.store.charCount=0,s.store.usageTokens=0,s.store.sawUsage=!1);let a=s.store;i.type==="token"?(a.chunkCount+=1,a.charCount+=i.delta.length):i.type==="usage"&&(a.sawUsage=!0,a.usageTokens=gt(i.usage)+It(i.usage));let u=a.sawUsage?a.usageTokens:Math.ceil(a.charCount/n);return{chunkCount:a.chunkCount,charCount:a.charCount,estimatedTokens:u,estimated:!a.sawUsage}},{name:e?.name??"cost-meter",describeKind:"derived",initial:r,meta:ue("cost_meter_extractor"),equals:fg})}ee();var hg=(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 gg(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 _([t],([o],s)=>{if(o==null)return[];let i=o;"flags"in s.store||(s.store.flags=[],s.store.scannedTo=0);let a=s.store.flags,u=s.store.scannedTo,c=Math.max(0,u-n),d=i.slice(c),l=!1;for(let{pattern:p,label:f,compiled:m}of r){m.lastIndex=0;for(let g of d.matchAll(m)){let h=c+(g.index??0);h+g[0].length<=u||(a.push({label:f,pattern:p,match:g[0],position:h}),l=!0)}}return s.store.scannedTo=i.length,l?[...a]:a.slice()},{name:e.name??"keyword-flag-extractor",describeKind:"derived",initial:[],meta:ue("keyword_flag_extractor"),equals:hg})}ee();function yg(t,e,n){return _([t],([r])=>r==null?null:e(r),{name:n?.name??"extractor",describeKind:"derived",initial:null,meta:ue("stream_extractor"),...n?.equals?{equals:n.equals}:{}})}ee();var bg=(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 vg(t,e){return _([t],([n],r)=>{if(n==null)return[];let o=n;"calls"in r.store||(r.store.calls=[],r.store.scanFrom=0);let s=r.store.calls,i=r.store.scanFrom,a=!1;for(;i<o.length;){let u=o.indexOf("{",i);if(u===-1){r.store.scanFrom=o.length;break}let c=0,d=-1,l=!1;for(let f=u;f<o.length;f++){let m=o[f];if(l)m==="\\"&&f+1<o.length?f++:m==='"'&&(l=!1);else if(m==='"')l=!0;else if(m==="{")c++;else if(m==="}"&&(c--,c===0)){d=f;break}}if(d===-1){r.store.scanFrom=u;break}let p=o.slice(u,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:u}),a=!0)}catch{}i=d+1,r.store.scanFrom=i}return a?[...s]:s.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:ue("tool_call_extractor"),equals:bg})}ee();function Tg(t,e,n,r){let o=n*(r?.hardMultiplier??1.5),s=typeof e!="function",i=[t];return s&&i.push(e),_(i,a=>{let u=a[0]??"";if(u.length===0)return"allow";let c=s?a[1]??0:e(u);return c>=o?"block":c>=n?"review":"allow"},{name:r?.name??"content-gate",initial:"allow"})}ee();function wg(t,e,n,r){let o=n??(()=>"[REDACTED]");function s(i){let a=i;for(let u of e){let c=u.global?u:new RegExp(u.source,`${u.flags}g`);a=a.replace(c,d=>o(d,u))}return a}return _([t],([i])=>s(i??""),{name:r?.name??"redactor",initial:""})}Ae();ae();Le();ee();Re();ee();var Ys=class extends Y{_log;messages;latest;messageCount;constructor(e,n={}){super(e,n.graph),this._log=Ue([],{name:"messages",maxSize:n.maxMessages}),this.messages=this._log.entries,this.add(this.messages,{name:"messages"}),this.latest=_([this.messages],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:ue("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(se(this.latest)),this.messageCount=_([this.messages],([r])=>r.length,{name:"messageCount",describeKind:"derived",meta:ue("chat_message_count"),initial:0}),this.add(this.messageCount,{name:"messageCount"}),this.addDisposer(se(this.messageCount))}append(e,n,r){this._log.append({role:e,content:n,...r})}appendToolResult(e,n){this._log.append({role:"tool",content:n,toolCallId:e})}clear(){this._log.clear()}allMessages(){return this.messages.cache}};function Xa(t,e){return new Ys(t,e)}ee();Et();function Za(t){let{toolCalls:e,tools:n}=t,r=t.retryCount??1,o=t.onError??"rescue",s=(i,a)=>{if(i===a)return!0;if(i.length!==a.length)return!1;for(let u=0;u<i.length;u++){let c=i[u],d=a[u];if(c?.id!==d?.id||c?.content!==d?.content)return!1}return!0};return Se(e,i=>{if(i==null||i.length===0)throw new Error("toolExecution: received an empty tool-call batch as DATA \u2014 callers must upstream-filter empty batches (emit RESOLVED) so switchMap is only dispatched for non-empty batches.");let a=i.map(u=>kg(u,n,r,o));return _(a,u=>u,{name:"toolExecution::batch",equals:s})})}function kg(t,e,n,r){let o=jt(()=>e.executeReactive(t.name,t.arguments),{count:n}),s=_([o],([i])=>({id:t.id,content:typeof i=="string"?i:JSON.stringify(i)}));return r==="propagate"?s:Hr(s,i=>({id:t.id,content:JSON.stringify({error:String(i)})}))}ae();ee();Re();var Qs=class extends Y{definitions;schemas;_bundle;constructor(e,n={}){super(e,n.graph),this._bundle=Xe({name:"definitions"}),this.definitions=this._bundle.entries,this.add(this.definitions,{name:"definitions"}),this.schemas=_([this.definitions],([r])=>[...(r??new Map).values()],{name:"schemas",describeKind:"derived",meta:ue("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(se(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 H(o=>{let s=new AbortController,i;try{let u=r.handler(n,{signal:s.signal});i=xg(u,s.signal)}catch(u){return o.down([[O,u]]),()=>{s.abort()}}let a=i.subscribe(u=>{o.down(u)});return()=>{s.abort(),a()}},{name:`executeReactive::${e}`,meta:ue("tool_execute_reactive")})}getDefinition(e){return this._bundle.entries.cache?.get(e)}};function eu(t,e){return new Qs(t,e)}function xg(t,e){return Qa(t)?t:t!=null&&typeof t.then=="function"?Jn(t,{signal:e}):t!=null&&typeof t=="object"&&Symbol.asyncIterator in t?Ar(t,{signal:e}):Jn(Promise.resolve(t),{signal:e})}var Xs=class extends Y{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;_terminalResult;_disposeRunWiring;_running=!1;_currentAbortController=null;constructor(e,n){if(super(e,n.graph),this.chat=Xa(`${e}-chat`,{maxMessages:n.maxMessages}),this.mount("chat",this.chat),this.tools=eu(`${e}-tools`),this.mount("tools",this.tools),n.tools)for(let B of n.tools)this.tools.register(B);this.status=E("idle",{name:"status",describeKind:"state",meta:ue("agent_status")}),this.add(this.status,{name:"status"}),this.turn=E(0,{name:"turn",describeKind:"state",meta:ue("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.aborted=E(!1,{name:"aborted",describeKind:"state",meta:ue("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let r=0,o=this.turn.subscribe(B=>{for(let $ of B)$[0]===S&&(r=$[1])}),s=!1,i=this.aborted.subscribe(B=>{for(let $ of B)$[0]===S&&(s=$[1])}),a=this.chat.messages.cache??[],u=this.chat.messages.subscribe(B=>{for(let $ of B)$[0]===S&&(a=$[1])}),c=this.tools.schemas.cache??[],d=this.tools.schemas.subscribe(B=>{for(let $ of B)$[0]===S&&(c=$[1])}),l=n.adapter,p=n.systemPrompt,f=n.model,m=n.temperature,g=n.maxTokens,h=n.maxTurns??10,y=n.stopWhen,b=this.chat,v=this.tools,T=this.status,w=this.turn,k=this.aborted,x=U([T],(B,$,G)=>{if(co(B,G.prevData,0,"idle")!=="thinking"||s||r>=h){$.down([[F]]);return}if(a.length===0){$.down([[F]]);return}$.emit({messages:a,tools:c})},{name:"promptInput",describeKind:"derived",meta:ue("agent_prompt_input")}),R=Se(x,B=>{let $=new AbortController;return this._currentAbortController=$,s&&$.abort(new Error("agentLoop: aborted")),X(l.invoke(B.messages,{tools:B.tools.length>0?B.tools:void 0,systemPrompt:p,model:f,temperature:m,maxTokens:g,signal:$.signal}),{signal:$.signal})},{equals:()=>!1}),N=E(null,{name:"lastResponse",describeKind:"state",meta:ue("agent_last_response")});this.lastResponse=N;let A=U([N,T],(B,$,G)=>{let q=co(B,G.prevData,0,null);if(co(B,G.prevData,1,"idle")!=="acting"){$.down([[F]]);return}let he=q?.toolCalls;if(he==null||he.length===0){$.down([[F]]);return}$.emit(he)},{name:"toolCallsRaw",describeKind:"derived",meta:ue("agent_tool_calls_raw")}),M=n.interceptToolCalls?n.interceptToolCalls(A):A;this.toolCalls=M;let I=Za({toolCalls:M,tools:v,retryCount:1});this.toolResults=I;let L=de([R],([B])=>{if(s)return;let $=B,G=r+1,q=$.toolCalls!=null&&$.toolCalls.length>0,ce=$.finishReason==="end_turn"&&(!$.toolCalls||$.toolCalls.length===0),he=y?.($)===!0,xe=G>=h,oe=he||ce||!q||xe?"done":"acting";Z(()=>{N.emit($),T.emit(oe),w.emit(G),b.append("assistant",$.content,{toolCalls:$.toolCalls})})}),P=de([I],([B])=>{if(s)return;let $=B;if($.length===0)return;let G=r>=h?"done":"thinking";Z(()=>{T.emit(G);for(let q of $)b.appendToolResult(q.id,q.content)})}),J=T.cache??"idle",Q=T.subscribe(B=>{for(let $ of B)$[0]===S&&(J=$[1])}),D=de([k],([B])=>{B===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),J!=="done"&&T.emit("done"))}),z=se(L),W=se(P),ie=se(D);this._terminalResult=U([T,N],(B,$,G)=>{let q=co(B,G.prevData,0,"idle"),ce=co(B,G.prevData,1,null);if(q==="done"){if(ce!=null){$.emit(ce);return}let he=new Error("agentLoop: aborted");he.name="AbortError",$.down([[O,he]]);return}if(q==="error"){$.down([[O,new Error("agentLoop: errored")]]);return}$.down([[F]])},{name:"terminalResult",describeKind:"derived",meta:ue("agent_terminal_result")}),this.add(x,{name:"promptInput"}),this.add(R,{name:"llmResponse"}),this.add(this.lastResponse,{name:"lastResponse"}),this.toolCalls===A?this.add(this.toolCalls,{name:"toolCalls"}):(this.add(A,{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(Q),this.addDisposer(u),this.addDisposer(d),this.addDisposer(z),this.addDisposer(W),this.addDisposer(ie),this._disposeRunWiring=()=>{}}async run(e,n){if(this._running)throw new RangeError(`agentLoop "${this.name}": run() called while a previous run() is still pending \u2014 await the previous run before starting another, or call abort() first`);this._running=!0;let r;try{Z(()=>{this.turn.emit(0),this.aborted.emit(!1),this.status.emit("idle"),this.lastResponse.emit(null)}),e!=null&&this.chat.append("user",e);let o=Qo(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 co(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 Rg(t,e){return new Xs(t,e)}ee();Re();function Sg(t,e,n){let r=X(t),o=n?.condition!=null?X(n.condition):null,s=E(null,{name:n?.name?`${n.name}::null`:"handoff::null"});if(o==null)return Se(r,a=>{if(a==null)return s;let u=E(a);return e(u)});let i=_([r,o],([a,u])=>({v:a,open:u===!0}),{name:n?.name?`${n.name}::router`:"handoff::router",describeKind:"derived"});return Se(i,({v:a,open:u})=>{if(a==null)return s;if(!u)return E(a);let c=E(a);return e(c)})}ee();Re();function Ng(t,e,n){let r=X(t),o=e.map(i=>X(i)),s=[r,...o];return _(s,i=>{let a=i[0]??[],u=i.slice(1);return a.filter(c=>{for(let d of u)if(d!=null&&!d(c))return!1;return!0})},{name:n?.name??"tool-selector",describeKind:"derived",meta:ue("tool_selector"),equals:(i,a)=>{let u=i,c=a;if(u.length!==c.length)return!1;for(let d=0;d<u.length;d++)if(u[d]!==c[d])return!1;return!0}})}function hp(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 Eg(t){let e={persistence:t.persistenceThreshold??.3,personalValue:t.personalValueThreshold??.3},n=hp({scoreFn:t.scoreFn,thresholds:e});return t.requireStructured?r=>{if(!n(r))return!1;let o=t.scoreFn(r).structure;return Number.isFinite(o)&&o>0}:n}Ae();_e();ee();Re();var ei={};Ne(ei,{collection:()=>Mg,decay:()=>Pt,knowledgeGraph:()=>fo,lightCollection:()=>lo,vectorIndex:()=>po});_e();ee();function Pt(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 gp(t){if(t!==void 0&&t<1)throw new RangeError("maxSize must be >= 1")}function xt(t){return new Map(t)}function tt(t){return t.cache??new Map}function Zs(t){return t.cache??[]}function _g(t,e){let n=Math.max(t.length,e.length),r=0,o=0,s=0;for(let i=0;i<n;i+=1){let a=t[i]??0,u=e[i]??0;r+=a*u,o+=a*a,s+=u*u}return o===0||s===0?0:r/Math.sqrt(o*s)}function lo(t={}){let e=t.maxSize,n=t.policy??"fifo";gp(e);let r=E(new Map,{name:t.name,describeKind:"state"});function o(i){if(e!==void 0)for(;i.size>e;){let a;for(let u of i.values()){if(!a){a=u;continue}let c=n==="lru"?u.lastAccessNs:u.createdAtNs,d=n==="lru"?a.lastAccessNs:a.createdAtNs;c<d&&(a=u)}if(!a)break;i.delete(a.id)}}function s(i){r.emit(i)}return{entries:r,upsert(i,a){let u=j(),c=tt(r),d=c.get(i),l=xt(c);l.set(i,{id:i,value:a,createdAtNs:d?.createdAtNs??u,lastAccessNs:u}),o(l),s(l)},remove(i){let a=xt(tt(r));a.delete(i)&&s(a)},clear(){tt(r).size!==0&&s(new Map)},get(i){let a=tt(r),u=a.get(i);if(u){if(n==="lru"){let c=j(),d=xt(a);d.set(i,{...u,lastAccessNs:c}),s(d)}return u.value}},has(i){return tt(r).has(i)}}}function Mg(t,e={}){let n=e.maxSize,r=e.policy??"lru",o=e.decayRate??0,s=e.minScore??0,i=e.score??(()=>1);gp(n);let a=new Y(t),u=E(new Map,{name:"items",describeKind:"state"}),c=_([u],([g])=>{let h=g??new Map,y=j(),b=[...h.values()].map(v=>{let T=(y-v.lastAccessNs)/1e9;return{...v,score:Pt(v.baseScore,T,o,s)}});return b.sort((v,T)=>T.score-v.score||T.lastAccessNs-v.lastAccessNs),b},{name:"ranked",describeKind:"derived"}),d=_([u],([g])=>(g??new Map).size,{name:"size",describeKind:"derived",initial:0});c.subscribe(()=>{}),d.subscribe(()=>{}),a.add(u,{name:"items"}),a.add(c,{name:"ranked"}),a.add(d,{name:"size"});function l(g,h){let y=(h-g.lastAccessNs)/1e9;return Pt(g.baseScore,y,o,s)}function p(g){if(n!==void 0)for(;g.size>n;){let h=j(),y,b=Number.POSITIVE_INFINITY;for(let v of g.values()){let T=l(v,h);if(T<b){y=v,b=T;continue}if(T===b&&y){let w=r==="lru"?v.lastAccessNs:v.createdAtNs,k=r==="lru"?y.lastAccessNs:y.createdAtNs;w<k&&(y=v)}}if(!y)break;g.delete(y.id)}}function f(g){u.emit(g)}return Object.assign(a,{upsert(g,h,y){let b=j(),v=tt(u),T=v.get(g),w=y?.score??i(h),k=xt(v);k.set(g,{id:g,value:h,baseScore:w,createdAtNs:T?.createdAtNs??b,lastAccessNs:b}),p(k),f(k)},remove(g){let h=xt(tt(u));h.delete(g)&&f(h)},clear(){tt(u).size!==0&&f(new Map)},getItem(g){let h=tt(u),y=h.get(g);if(y){if(r==="lru"){let b=xt(h);b.set(g,{...y,lastAccessNs:j()}),f(b)}return y}}})}function po(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=E(new Map,{describeKind:"state",name:"vector-index"});function s(a){if(n!==void 0&&a.length!==n)throw new RangeError(`vector dimension mismatch: expected ${n}, got ${a.length}`)}function i(a){o.emit(a)}return{backend:e,entries:o,upsert(a,u,c){s(u);let d=xt(tt(o));d.set(a,{id:a,vector:[...u],meta:c}),e==="hnsw"&&r.upsert(a,u,c),i(d)},remove(a){let u=xt(tt(o));u.delete(a)&&(e==="hnsw"&&r.remove(a),i(u))},clear(){tt(o).size!==0&&(e==="hnsw"&&r.clear(),i(new Map))},search(a,u=5){return s(a),u<=0?[]:e==="hnsw"?r.search(a,u):[...tt(o).values()].map(d=>({id:d.id,score:_g(a,d.vector),meta:d.meta})).sort((d,l)=>l.score-d.score).slice(0,u)}}}function fo(t){let e=new Y(t),n=E(new Map,{name:"entities",describeKind:"state"}),r=E([],{name:"edges",describeKind:"state"}),o=_([r],([u])=>{let c=u??[],d=new Map;for(let l of c){let p=d.get(l.from)??[];d.set(l.from,Object.freeze([...p,l]))}return d},{name:"adjacency",describeKind:"derived",initial:new Map});o.subscribe(()=>{}),e.add(n,{name:"entities"}),e.add(r,{name:"edges"}),e.add(o,{name:"adjacency"});function s(u){n.emit(u)}function i(u){r.emit(u)}return Object.assign(e,{upsertEntity(u,c){let d=xt(tt(n));d.set(u,c),s(d)},removeEntity(u){let c=xt(tt(n)),d=c.delete(u),l=Zs(r),p=l.filter(f=>f.from!==u&&f.to!==u);!d&&p.length===l.length||(s(c),i(p))},link(u,c,d,l=1){let p=`${u}\0${c}\0${d}`,f=Zs(r),m=new Set(f.map(h=>`${h.from}\0${h.to}\0${h.relation}`)),g=[...f];if(m.has(p))for(let h=0;h<g.length;h+=1){let y=g[h];if(y.from===u&&y.to===c&&y.relation===d){g[h]={...y,weight:l};break}}else g.push({from:u,to:c,relation:d,weight:l});i(g)},unlink(u,c,d){let l=Zs(r),p=l.filter(f=>d===void 0?!(f.from===u&&f.to===c):!(f.from===u&&f.to===c&&f.relation===d));p.length!==l.length&&i(p)},related(u,c){return Zs(r).filter(d=>(d.from===u||d.to===u)&&(c===void 0||d.relation===c))}})}ee();function yp(t,e,n,r){let o=n.name??r;return s=>{let i=E(s);return kn(n.adapter,[i],a=>e(a),{name:o,format:"json",systemPrompt:t,model:n.model,temperature:n.temperature??0,maxTokens:n.maxTokens})}}function tu(t,e){let n=e.maxExistingKeys??100,r=yp(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 nu(t,e){let n=yp(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 mo=Math.LN2/604800;function ho(t){return t instanceof Map?t:new Map}function Og(t,e,n){let r=new Y(t,n.graph),o=[],s;if(n.extractFn)s=n.extractFn;else if(n.adapter&&n.extractPrompt)s=tu(n.extractPrompt,{adapter:n.adapter});else throw new Error("agentMemory: provide either extractFn or adapter + extractPrompt");let i=(v,T)=>v==null?{upsert:[]}:s(v,T),a=e;if(n.admissionFilter){let v=X(e),T=n.admissionFilter;a=_([v],([w])=>{if(T(w))return w},{name:"admissionFilter",describeKind:"derived"})}let u;n.consolidateFn?u=n.consolidateFn:n.adapter&&n.consolidatePrompt&&(u=nu(n.consolidatePrompt,{adapter:n.adapter}));let c=n.consolidateTrigger;if(!c&&u&&n.reflection?.enabled!==!1){let v=n.reflection?.interval??3e5;c=ct(v,{period:v})}let d={score:n.score,cost:n.cost,budget:n.budget??2e3,context:n.context,consolidate:u,consolidateTrigger:c},l=Ns(a,i,d);r.add(l.store.entries,{name:"store"}),r.add(l.compact,{name:"compact"}),r.add(l.size,{name:"size"});let p=null;n.vectorDimensions&&n.vectorDimensions>0&&n.embedFn&&(p=po({dimension:n.vectorDimensions}),r.add(p.entries,{name:"vectorIndex"}));let f=null;n.enableKnowledgeGraph&&(f=fo(`${t}-kg`),r.mount("kg",f));let m=null;if(n.tiers){let v=n.tiers,T=v.decayRate??mo,w=v.maxActive??1e3,k=v.archiveThreshold??.1,x=v.permanentFilter??(()=>!1),R=lo({name:"permanent"});r.add(R.entries,{name:"permanent"});let N=new Set,A=D=>N.has(D)?"permanent":ho(l.store.entries.cache).has(D)?"active":"archived",M=(D,z)=>{N.add(D),R.upsert(D,z)},I=new Map,L=l.store.entries,P=n.context?X(n.context):E(null),J=de([L,P],([D,z])=>{let W=ho(D),ie=j(),B=[],$=[];for(let[q,ce]of W){if(I.has(q)||I.set(q,ie),x(q,ce)){$.push({key:q,value:ce});continue}let he=n.score(ce,z),xe=I.get(q)??ie,oe=Number(ie-xe)/1e9;Pt(he,oe,T)<k&&B.push(q)}for(let q of I.keys())W.has(q)||I.delete(q);for(let{key:q,value:ce}of $)N.has(q)||M(q,ce);let G=W.size-N.size;if(G>w){let q=[...W.entries()].filter(([he])=>!N.has(he)).map(([he,xe])=>({key:he,score:n.score(xe,z)})).sort((he,xe)=>he.score-xe.score),ce=G-w;for(let he=0;he<ce&&he<q.length;he++){let xe=q[he].key;B.includes(xe)||B.push(xe)}}B.length>0&&Z(()=>{for(let q of B)l.store.delete(q)})});o.push(J.subscribe(()=>{}));let Q=null;v.archiveTier&&(Q=r.attachStorage([v.archiveTier],v.archiveStorageOptions??{})),m={permanent:R,activeEntries:L,archiveHandle:Q,tierOf:A,markPermanent:M}}if(p||f){let v=n.embedFn,T=n.entityFn,w=l.store.entries,k=de([w],([x])=>{let R=ho(x);for(let[N,A]of R){if(p&&v){let M=v(A);M&&p.upsert(N,M,A)}if(f&&T){let M=T(N,A);if(M){for(let I of M.entities??[])f.upsertEntity(I.id,I.value);for(let I of M.relations??[])f.link(I.from,I.to,I.relation,I.weight)}}}});o.push(k.subscribe(()=>{}))}let g=null,h=null,y=null,b=null;if(p||f){let v=n.retrieval?.topK??20,T=n.retrieval?.graphDepth??1,w=n.budget??2e3,k=n.cost,x=n.score,R=n.contextOf,N=n.contextWeight??0,A=n.context?X(n.context):E(null),M=(D,z)=>{if(!D||!z)return 0;let W=Math.min(D.length,z.length),ie=0;for(;ie<W&&D[ie]===z[ie];)ie++;return ie},I=(D,z,W)=>{let ie=new Map,B=[];if(p&&W.vector){B=p.search(W.vector,v);for(let oe of B){let ye=D.get(oe.id);ye&&ie.set(oe.id,{value:ye,sources:new Set(["vector"])})}}let $=[];if(f){let oe=[...W.entityIds??[],...ie.keys()],ye=new Set,re=oe;for(let ge=0;ge<T;ge++){let Oe=[];for(let le of re){if(ye.has(le))continue;ye.add(le);let K=f.related(le);for(let ne of K){let pe=ne.to;if(!ye.has(pe)){Oe.push(pe);let V=D.get(pe);if(V){let fe=ie.get(pe);fe?fe.sources.add("graph"):ie.set(pe,{value:V,sources:new Set(["graph"])}),$.push(pe)}}}}re=Oe}}for(let[oe,ye]of D)ie.has(oe)||ie.set(oe,{value:ye,sources:new Set(["store"])});let G=W.context?.length??0,q=[];for(let[oe,{value:ye,sources:re}]of ie){let ge=R?R(ye):void 0,Oe=x(ye,z);if(N>0&&G>0){let K=M(W.context,ge);K>0&&(Oe=Oe*(1+N*K/G))}let le=ge?{key:oe,value:ye,score:Oe,sources:[...re],context:ge}:{key:oe,value:ye,score:Oe,sources:[...re]};q.push(le)}q.sort((oe,ye)=>ye.score-oe.score);let ce=[],he=0;for(let oe of q){let ye=k(oe.value);if(he+ye>w&&ce.length>0)break;ce.push(oe),he+=ye}return{packed:ce,trace:{vectorCandidates:B,graphExpanded:$,ranked:q,packed:ce}}},L=(D,z)=>{if(D===z)return!0;if(D.length!==z.length)return!1;for(let W=0;W<D.length;W++)if(D[W]!==z[W])return!1;return!0},P=E([],{name:"retrieval",describeKind:"state",meta:ue("retrieval_pipeline"),equals:L});r.add(P,{name:"retrieval"}),g=P;let J=E(null,{name:"retrievalTrace",describeKind:"state",meta:ue("retrieval_trace")});r.add(J,{name:"retrievalTrace"}),h=J,y=D=>{let z=ho(l.store.entries.cache),{packed:W,trace:ie}=I(z,A.cache,D);return Z(()=>{P.emit(W),J.emit(ie)}),W},b=D=>{let z=X(D),W=_([l.store.entries,A,z],([B,$,G])=>{if(G==null)return{packed:[],trace:null};let q=ho(B),{packed:ce,trace:he}=I(q,$,G);return{packed:ce,trace:he}},{name:"retrievalReactive::result",describeKind:"derived",meta:ue("retrieval_reactive_result"),initial:{packed:[],trace:null}}),ie=de([W],([B])=>{let $=B;Z(()=>{P.emit($.packed),$.trace&&J.emit($.trace)})});return o.push(ie.subscribe(()=>{})),_([W],([B])=>B.packed,{name:"retrievalReactive",describeKind:"derived",meta:ue("retrieval_reactive"),initial:[],equals:L})}}return r.addDisposer(()=>{for(let v of o)v();o.length=0}),Object.assign(r,{distillBundle:l,compact:l.compact,size:l.size,vectors:p,kg:f,memoryTiers:m,retrieval:g,retrievalTrace:h,retrieve:y,retrieveReactive:b})}Ae();_e();ee();Re();function sr(t){return t instanceof Map?t:new Map}function Cg(t,e,n){let r=po({dimension:n.dimension});t.add(r.entries,{name:"vectorIndex"});let s=de([e.store.entries],([i])=>{let a=sr(i);for(let[u,c]of a){let d=n.embedFn(c);d&&r.upsert(u,d,c)}}).subscribe(()=>{});return t.addDisposer(s),{vectors:r,dispose:()=>s()}}function Ag(t,e,n,r){let o=fo(`${n}-kg`);t.mount(n,o);let i=de([e.store.entries],([a])=>{let u=sr(a);for(let[c,d]of u){let l=r.entityFn(c,d);if(l){for(let p of l.entities??[])o.upsertEntity(p.id,p.value);for(let p of l.relations??[])o.link(p.from,p.to,p.relation,p.weight)}}}).subscribe(()=>{});return t.addDisposer(i),{kg:o,dispose:()=>i()}}function Lg(t,e,n){let r=n.decayRate??mo,o=n.maxActive??1e3,s=n.archiveThreshold??.1,i=n.permanentFilter??(()=>!1),a=lo({name:"permanent"});t.add(a.entries,{name:"permanent"});let u=new Set,c=b=>u.has(b)?"permanent":sr(e.store.entries.cache).has(b)?"active":"archived",d=(b,v)=>{u.add(b),a.upsert(b,v)},l=new Map,p=e.store.entries,f=n.context?X(n.context):E(null),g=de([p,f],([b,v])=>{let T=sr(b),w=j(),k=[],x=[];for(let[N,A]of T){if(l.has(N)||l.set(N,w),i(N,A)){x.push({key:N,value:A});continue}let M=n.score(A,v),I=l.get(N)??w,L=Number(w-I)/1e9;Pt(M,L,r)<s&&k.push(N)}for(let N of l.keys())T.has(N)||l.delete(N);for(let{key:N,value:A}of x)u.has(N)||d(N,A);let R=T.size-u.size;if(R>o){let N=[...T.entries()].filter(([M])=>!u.has(M)).map(([M,I])=>({key:M,score:n.score(I,v)})).sort((M,I)=>M.score-I.score),A=R-o;for(let M=0;M<A&&M<N.length;M++){let I=N[M].key;k.includes(I)||k.push(I)}}k.length>0&&Z(()=>{for(let N of k)e.store.delete(N)})}).subscribe(()=>{}),h=null;n.archiveTier&&(h=t.attachStorage([n.archiveTier],n.archiveStorageOptions??{}));let y=()=>{g(),h?.dispose()};return t.addDisposer(y),{tiers:{permanent:a,activeEntries:p,archiveHandle:h,tierOf:c,markPermanent:d},dispose:y}}function Ig(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 Dg(t,e,n,r,o){let s=o.topK??20,i=o.graphDepth??1,a=o.budget??2e3,u=o.contextWeight??0,c=o.context?X(o.context):E(null),d=(h,y,b)=>{let v=new Map,T=[];if(n&&b.vector){T=n.search(b.vector,s);for(let A of T){let M=h.get(A.id);M&&v.set(A.id,{value:M,sources:new Set(["vector"])})}}let w=[];if(r){let A=[...b.entityIds??[],...v.keys()],M=new Set,I=A;for(let L=0;L<i;L++){let P=[];for(let J of I)if(!M.has(J)){M.add(J);for(let Q of r.related(J)){let D=Q.to;if(!M.has(D)){P.push(D);let z=h.get(D);if(z){let W=v.get(D);W?W.sources.add("graph"):v.set(D,{value:z,sources:new Set(["graph"])}),w.push(D)}}}}I=P}}for(let[A,M]of h)v.has(A)||v.set(A,{value:M,sources:new Set(["store"])});let k=b.context?.length??0,x=[];for(let[A,{value:M,sources:I}]of v){let L=o.contextOf?o.contextOf(M):void 0,P=o.score(M,y);if(u>0&&k>0){let Q=Ig(b.context,L);Q>0&&(P=P*(1+u*Q/k))}let J=L?{key:A,value:M,score:P,sources:[...I],context:L}:{key:A,value:M,score:P,sources:[...I]};x.push(J)}x.sort((A,M)=>M.score-A.score);let R=[],N=0;for(let A of x){let M=o.cost(A.value);if(N+M>a&&R.length>0)break;R.push(A),N+=M}return{packed:R,trace:{vectorCandidates:T,graphExpanded:w,ranked:x,packed:R}}},l=(h,y)=>{if(h===y)return!0;if(h.length!==y.length)return!1;for(let b=0;b<h.length;b++)if(h[b]!==y[b])return!1;return!0},p=E([],{name:"retrieval",describeKind:"state",meta:ue("retrieval_pipeline"),equals:l});t.add(p,{name:"retrieval"});let f=E(null,{name:"retrievalTrace",describeKind:"state",meta:ue("retrieval_trace")});return t.add(f,{name:"retrievalTrace"}),{retrieval:p,retrievalTrace:f,retrieve:h=>{let y=sr(e.store.entries.cache),{packed:b,trace:v}=d(y,c.cache,h);return Z(()=>{p.emit(b),f.emit(v)}),b},retrieveReactive:h=>{let y=X(h),b=_([e.store.entries,c,y],([w,k,x])=>{if(x==null)return{packed:[],trace:null};let R=sr(w),{packed:N,trace:A}=d(R,k,x);return{packed:N,trace:A}},{name:"retrievalReactive::result",describeKind:"derived",meta:ue("retrieval_reactive_result"),initial:{packed:[],trace:null}}),T=de([b],([w])=>{let k=w;Z(()=>{p.emit(k.packed),k.trace&&f.emit(k.trace)})}).subscribe(()=>{});return t.addDisposer(T),_([b],([w])=>w.packed,{name:"retrievalReactive",describeKind:"derived",meta:ue("retrieval_reactive"),initial:[],equals:l})}}}function Pg(t,e,n){let r=t.describe({actor:e,detail:"full"}),o=n?.groupByTags??!0,s=n?.separator??`
40
- `,i=[],a=n?.sinceVersion;for(let[u,c]of Object.entries(r.nodes)){let d=c.meta??{},l=d.description,p=d.format;if(!l&&!p)continue;if(a!=null&&c.v!=null){let y=a.get(u);if(y!=null&&y.id===c.v.id&&c.v.version<=y.version)continue}let f=l??u,m=c.value,g=d.unit,h;p==="currency"&&typeof m=="number"?h=`$${m.toFixed(2)}`:p==="percentage"&&typeof m=="number"?h=`${(m*100).toFixed(1)}%`:m==null?h="(no value)":h=String(m),g&&p!=="currency"&&p!=="percentage"&&(h=`${h} ${g}`),i.push({path:u,description:f,formatted:h})}if(i.length===0)return"";if(o){let u=new Map,c=[];for(let l of i){let f=r.nodes[l.path].meta?.tags;if(f&&f.length>0){let m=f[0],g=u.get(m);g||(g=[],u.set(m,g)),g.push(l)}else c.push(l)}if(u.size===0)return i.map(l=>`- ${l.description}: ${l.formatted}`).join(s);let d=[];for(let[l,p]of[...u.entries()].sort((f,m)=>f[0].localeCompare(m[0])))d.push(`[${l}]${s}${p.map(f=>`- ${f.description}: ${f.formatted}`).join(s)}`);return c.length>0&&d.push(c.map(l=>`- ${l.description}: ${l.formatted}`).join(s)),d.join(s+s)}return i.map(u=>`- ${u.description}: ${u.formatted}`).join(s)}ae();ee();Re();var ri={};Ne(ri,{compileSpec:()=>vo,decompileGraph:()=>Hg,extractFnFactory:()=>vp,extractSourceFactory:()=>Tp,generateCatalogPrompt:()=>wp,isRichFnEntry:()=>yo,isRichSourceEntry:()=>su,llmCompose:()=>qg,llmRefine:()=>Rp,specDiff:()=>Wg,validateSpec:()=>ir,validateSpecAgainstCatalog:()=>bo});ee();var ni={};Ne(ni,{budgetGate:()=>ru,effectivenessTracker:()=>Fg,feedback:()=>Yt,funnel:()=>Gg,scorer:()=>go});Ae();ae();Le();ee();function ti(t,e){return ze("reduction",t,e)}function Gg(t,e,n,r){if(e.length===0)throw new RangeError("funnel requires at least one source");if(n.length===0)throw new RangeError("funnel requires at least one stage");let o=new Y(t,r),s=e.length===1?e[0]:wt(...e);o.add(s,{name:"merged"});let i="merged";for(let a=0;a<n.length;a++){let u=n[a],c=new Y(u.name);u.build(c);try{c.resolve("input")}catch{throw new Error(`funnel stage "${u.name}" must define an "input" node`)}try{c.resolve("output")}catch{throw new Error(`funnel stage "${u.name}" must define an "output" node`)}o.mount(u.name,c);let d=o.resolve(i),l=`${u.name}::input`,p=o.resolve(l),f=`__bridge_${i}\u2192${u.name}_input`,m=de([d],([g])=>{p.emit(g)},{name:f});o.add(m,{name:f}),o.addDisposer(se(m)),i=`${u.name}::output`}return o}function Yt(t,e,n,r){let o=r?.maxIterations??10,s=`__feedback_${e}`,i=E(0,{meta:ti("feedback_counter",{maxIterations:o,feedbackFrom:e,feedbackTo:n})});t.add(i,{name:s});let a=t.resolve(e),u=t.resolve(n),c=`__feedback_effect_${e}`,d=U([],(l,p)=>{let f=a.subscribe(m=>{for(let g of m){let h=g[0];if(h===S){let y=g[1];if(y==null)return;Z(()=>{Fr(i,o)&&u.emit(y)})}else if(h===C||h===O){let y=h===O&&g.length>1?[O,g[1]]:[h];i.down([y])}}});return()=>f()},{name:c,describeKind:"effect",meta:{...ti("feedback_effect",{feedbackFrom:e,feedbackTo:n}),_internal:!0}});return t.add(d,{name:c}),t.addDisposer(se(d)),t}function ru(t,e,n){if(e.length===0)throw new RangeError("budgetGate requires at least one constraint");let r=e.map(f=>f.node),o=[t,...r],s=[],i=!1,a=!1,u=Symbol("budget-gate"),c=new Array(e.length);function d(){return e.every((f,m)=>f.check(c[m]))}function l(f){for(;s.length>0&&d();){let m=s[0];s=s.slice(1),f.emit(m)}s.length===0&&a&&(a=!1,f.down([[F]]))}return U([],(f,m)=>{for(let h=0;h<e.length;h++)c[h]=e[h].node.cache;let g=[];for(let h=0;h<o.length;h++){let y=o[h];g.push(y.subscribe(b=>{for(let v of b)p(v,h,m)}))}return()=>{for(let h of g)h()}},{...n,describeKind:"derived",meta:ti("budget_gate",n?.meta)});function p(f,m,g){let h=f[0];if(m===0){if(h===S)return d()&&s.length===0?g.emit(f[1]):(s.push(f[1]),i||(i=!0,g.up([[Be,u]]))),!0;if(h===te)return g.down([[te]]),!0;if(h===F)return s.length===0?g.down([[F]]):a=!0,!0;if(h===C||h===O){for(let y of s)g.emit(y);return s=[],a=!1,i&&(i=!1,g.up([[Ke,u]])),g.down([f]),!0}return!1}return h===S&&(c[m-1]=f[1]),h===S||h===F?(d()&&s.length>0?(l(g),s.length===0&&i&&(i=!1,g.up([[Ke,u]]))):!d()&&!i&&s.length>0&&(i=!0,g.up([[Be,u]])),!0):h===te?!0:h===O?(g.down([f]),!0):h===C}}function go(t,e,n){if(t.length===0)throw new RangeError("scorer requires at least one source");if(t.length!==e.length)throw new RangeError("scorer requires the same number of sources and weights");let r=[...t,...e],o=t.length,s=n?.scoreFns;return _(r,i=>{let a=i.slice(0,o),u=i.slice(o),c=[],d=0;for(let l=0;l<o;l++){let p=a[l]??0,f=u[l]??0,g=(s?.[l]?s[l](p):p)*f;c.push(g),d+=g}return{value:a,score:d,breakdown:c}},{...n?{equals:n.equals,resubscribable:n.resubscribable,resetOnTeardown:n.resetOnTeardown}:{},describeKind:"derived",meta:ti("scorer",n?.meta)})}function Fg(t){let e=Xe({name:t?.name??"effectiveness-entries"}),n=_([e.entries],([i])=>new Map(i),{name:`${t?.name??"effectiveness"}-snapshot`,equals:(i,a)=>{let u=i,c=a;if(u.size!==c.size)return!1;for(let[d,l]of u){let p=c.get(d);if(!p||l.attempts!==p.attempts||l.successes!==p.successes)return!1}return!0}});function r(i,a){let u=e.get(i),c=(u?.attempts??0)+1,d=(u?.successes??0)+(a?1:0);e.set(i,{key:i,attempts:c,successes:d,successRate:d/c})}function o(i){return e.get(i)}let s=se(n);return{node:n,record:r,lookup:o,dispose:()=>s()}}function yo(t){return typeof t=="object"&&t!==null&&"factory"in t}function su(t){return typeof t=="object"&&t!==null&&"factory"in t}function vp(t){return yo(t)?t.factory:t}function Tp(t){return su(t)?t.factory:t}function wp(t){let e=[];if(t.fns){let n=new Map;for(let[r,o]of Object.entries(t.fns)){let s=yo(o)?o.tags?.[0]??"Other":"Other";n.has(s)||n.set(s,[]),n.get(s).push($g(r,o))}for(let[r,o]of n)e.push(`${r}:
41
- ${o.join(`
42
- `)}`)}if(t.sources){let n=[];for(let[r,o]of Object.entries(t.sources))n.push(jg(r,o));n.length>0&&e.push(`Sources:
39
+ `,r=t.map(i=>typeof i=="string"?N(i):W(i)),s=_(r,i=>i.filter(a=>a!=null&&a!=="").join(n),{name:e?.name??"systemPrompt",describeKind:"derived",meta:pe("system_prompt"),initial:""}),o=re(s);return Object.assign(s,{dispose:o})}Q();var yg=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens&&t.estimated===e.estimated;function bg(t,e){let n=e?.charsPerToken??4,r={chunkCount:0,charCount:0,estimatedTokens:0,estimated:!0};return _([t.latest],([s],o)=>{if(s==null)return r;let i=s;"chunkCount"in o.store||(o.store.chunkCount=0,o.store.charCount=0,o.store.usageTokens=0,o.store.sawUsage=!1);let a=o.store;i.type==="token"?(a.chunkCount+=1,a.charCount+=i.delta.length):i.type==="usage"&&(a.sawUsage=!0,a.usageTokens=gt(i.usage)+It(i.usage));let u=a.sawUsage?a.usageTokens:Math.ceil(a.charCount/n);return{chunkCount:a.chunkCount,charCount:a.charCount,estimatedTokens:u,estimated:!a.sawUsage}},{name:e?.name??"cost-meter",describeKind:"derived",initial:r,meta:pe("cost_meter_extractor"),equals:yg})}Q();var vg=(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],s=e[n];if(r.label!==s.label||r.pattern!==s.pattern||r.match!==s.match||r.position!==s.position)return!1}return!0};function Tg(t,e){let n=e.maxPatternLength??128;for(let s of e.patterns)if(s.pattern.source.length>n)throw new Error(`keywordFlagExtractor: pattern "${s.label}" literal exceeds maxPatternLength (${s.pattern.source.length} > ${n}); raise the option or shorten the pattern.`);let r=e.patterns.map(s=>({label:s.label,pattern:s.pattern,compiled:new RegExp(s.pattern.source,`${s.pattern.flags.replace("g","")}g`)}));return _([t],([s],o)=>{if(s==null)return[];let i=s;"flags"in o.store||(o.store.flags=[],o.store.scannedTo=0);let a=o.store.flags,u=o.store.scannedTo,d=Math.max(0,u-n),c=i.slice(d),l=!1;for(let{pattern:p,label:f,compiled:m}of r){m.lastIndex=0;for(let g of c.matchAll(m)){let h=d+(g.index??0);h+g[0].length<=u||(a.push({label:f,pattern:p,match:g[0],position:h}),l=!0)}}return o.store.scannedTo=i.length,l?[...a]:a.slice()},{name:e.name??"keyword-flag-extractor",describeKind:"derived",initial:[],meta:pe("keyword_flag_extractor"),equals:vg})}Q();function wg(t,e,n){return _([t],([r])=>r==null?null:e(r),{name:n?.name??"extractor",describeKind:"derived",initial:null,meta:pe("stream_extractor"),...n?.equals?{equals:n.equals}:{}})}Q();var kg=(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],s=e[n];if(r.startIndex!==s.startIndex||r.name!==s.name||r.raw!==s.raw)return!1}return!0};function xg(t,e){return _([t],([n],r)=>{if(n==null)return[];let s=n;"calls"in r.store||(r.store.calls=[],r.store.scanFrom=0);let o=r.store.calls,i=r.store.scanFrom,a=!1;for(;i<s.length;){let u=s.indexOf("{",i);if(u===-1){r.store.scanFrom=s.length;break}let d=0,c=-1,l=!1;for(let f=u;f<s.length;f++){let m=s[f];if(l)m==="\\"&&f+1<s.length?f++:m==='"'&&(l=!1);else if(m==='"')l=!0;else if(m==="{")d++;else if(m==="}"&&(d--,d===0)){c=f;break}}if(c===-1){r.store.scanFrom=u;break}let p=s.slice(u,c+1);try{let f=JSON.parse(p);typeof f.name=="string"&&f.arguments!=null&&typeof f.arguments=="object"&&(o.push({name:f.name,arguments:f.arguments,raw:p,startIndex:u}),a=!0)}catch{}i=c+1,r.store.scanFrom=i}return a?[...o]:o.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:pe("tool_call_extractor"),equals:kg})}Q();function Rg(t,e,n,r){let s=n*(r?.hardMultiplier??1.5),o=typeof e!="function",i=[t];return o&&i.push(e),_(i,a=>{let u=a[0]??"";if(u.length===0)return"allow";let d=o?a[1]??0:e(u);return d>=s?"block":d>=n?"review":"allow"},{name:r?.name??"content-gate",initial:"allow"})}Q();function Sg(t,e,n,r){let s=n??(()=>"[REDACTED]");function o(i){let a=i;for(let u of e){let d=u.global?u:new RegExp(u.source,`${u.flags}g`);a=a.replace(d,c=>s(c,u))}return a}return _([t],([i])=>o(i??""),{name:r?.name??"redactor",initial:""})}Ce();se();_e();Q();Te();Q();var qs=class extends q{_log;messages;latest;messageCount;constructor(e,n={}){super(e,n.graph),this._log=Ue([],{name:"messages",maxSize:n.maxMessages}),this.messages=this._log.entries,this.add(this.messages,{name:"messages"}),this.latest=_([this.messages],([r])=>{let s=r;return s.length===0?null:s[s.length-1]},{name:"latest",describeKind:"derived",meta:pe("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(re(this.latest)),this.messageCount=_([this.messages],([r])=>r.length,{name:"messageCount",describeKind:"derived",meta:pe("chat_message_count"),initial:0}),this.add(this.messageCount,{name:"messageCount"}),this.addDisposer(re(this.messageCount))}append(e,n,r){this._log.append({role:e,content:n,...r})}appendToolResult(e,n){this._log.append({role:"tool",content:n,toolCallId:e})}clear(){this._log.clear()}allMessages(){return this.messages.cache}};function Ua(t,e){return new qs(t,e)}Q();Et();function za(t){let{toolCalls:e,tools:n}=t,r=t.retryCount??1,s=t.onError??"rescue",o=(i,a)=>{if(i===a)return!0;if(i.length!==a.length)return!1;for(let u=0;u<i.length;u++){let d=i[u],c=a[u];if(d?.id!==c?.id||d?.content!==c?.content)return!1}return!0};return be(e,i=>{if(i==null||i.length===0)throw new Error("toolExecution: received an empty tool-call batch as DATA \u2014 callers must upstream-filter empty batches (emit RESOLVED) so switchMap is only dispatched for non-empty batches.");let a=i.map(u=>Ng(u,n,r,s));return _(a,u=>u,{name:"toolExecution::batch",equals:o})})}function Ng(t,e,n,r){let s=$t(()=>e.executeReactive(t.name,t.arguments),{count:n}),o=_([s],([i])=>({id:t.id,content:typeof i=="string"?i:JSON.stringify(i)}));return r==="propagate"?o:Hr(o,i=>({id:t.id,content:JSON.stringify({error:String(i)})}))}se();Q();Te();var Ws=class extends q{definitions;schemas;_bundle;constructor(e,n={}){super(e,n.graph),this._bundle=Ze({name:"definitions"}),this.definitions=this._bundle.entries,this.add(this.definitions,{name:"definitions"}),this.schemas=_([this.definitions],([r])=>[...(r??new Map).values()],{name:"schemas",describeKind:"derived",meta:pe("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(re(this.schemas))}register(e){this._bundle.set(e.name,e)}unregister(e){this._bundle.delete(e)}executeReactive(e,n){let r=this._bundle.get(e);if(!r)throw new Error(`toolRegistry: unknown tool "${e}"`);return $(s=>{let o=new AbortController,i;try{let u=r.handler(n,{signal:o.signal});i=Eg(u,o.signal)}catch(u){return s.down([[M,u]]),()=>{o.abort()}}let a=i.subscribe(u=>{s.down(u)});return()=>{o.abort(),a()}},{name:`executeReactive::${e}`,meta:pe("tool_execute_reactive")})}getDefinition(e){return this._bundle.entries.cache?.get(e)}};function Ja(t,e){return new Ws(t,e)}function Eg(t,e){return Wa(t)?t:t!=null&&typeof t.then=="function"?Jn(t,{signal:e}):t!=null&&typeof t=="object"&&Symbol.asyncIterator in t?Ar(t,{signal:e}):Jn(Promise.resolve(t),{signal:e})}var Us=class extends q{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;_terminalResult;_disposeRunWiring;_running=!1;_currentAbortController=null;constructor(e,n){if(super(e,n.graph),this.chat=Ua(`${e}-chat`,{maxMessages:n.maxMessages}),this.mount("chat",this.chat),this.tools=Ja(`${e}-tools`),this.mount("tools",this.tools),n.tools)for(let J of n.tools)this.tools.register(J);this.status=N("idle",{name:"status",describeKind:"state",meta:pe("agent_status")}),this.add(this.status,{name:"status"}),this.turn=N(0,{name:"turn",describeKind:"state",meta:pe("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.aborted=N(!1,{name:"aborted",describeKind:"state",meta:pe("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let r=0,s=this.turn.subscribe(J=>{for(let K of J)K[0]===R&&(r=K[1])}),o=!1,i=this.aborted.subscribe(J=>{for(let K of J)K[0]===R&&(o=K[1])}),a=this.chat.messages.cache??[],u=this.chat.messages.subscribe(J=>{for(let K of J)K[0]===R&&(a=K[1])}),d=this.tools.schemas.cache??[],c=this.tools.schemas.subscribe(J=>{for(let K of J)K[0]===R&&(d=K[1])}),l=n.adapter,p=n.systemPrompt,f=n.model,m=n.temperature,g=n.maxTokens,h=n.maxTurns??10,y=n.stopWhen,b=this.chat,v=this.tools,T=this.status,w=this.turn,k=this.aborted,x=V([T],(J,K,j)=>{if(co(J,j.prevData,0,"idle")!=="thinking"||o||r>=h){K.down([[G]]);return}if(a.length===0){K.down([[G]]);return}K.emit({messages:a,tools:d})},{name:"promptInput",describeKind:"derived",meta:pe("agent_prompt_input")}),S=be(x,J=>{let K=new AbortController;return this._currentAbortController=K,o&&K.abort(new Error("agentLoop: aborted")),W(l.invoke(J.messages,{tools:J.tools.length>0?J.tools:void 0,systemPrompt:p,model:f,temperature:m,maxTokens:g,signal:K.signal}),{signal:K.signal})},{equals:()=>!1}),E=N(null,{name:"lastResponse",describeKind:"state",meta:pe("agent_last_response")});this.lastResponse=E;let L=V([E,T],(J,K,j)=>{let ne=co(J,j.prevData,0,null);if(co(J,j.prevData,1,"idle")!=="acting"){K.down([[G]]);return}let Me=ne?.toolCalls;if(Me==null||Me.length===0){K.down([[G]]);return}K.emit(Me)},{name:"toolCallsRaw",describeKind:"derived",meta:pe("agent_tool_calls_raw")}),C=n.interceptToolCalls?n.interceptToolCalls(L):L;this.toolCalls=C;let I=za({toolCalls:C,tools:v,retryCount:1});this.toolResults=I;let A=le([S],([J])=>{if(o)return;let K=J,j=r+1,ne=K.toolCalls!=null&&K.toolCalls.length>0,Re=K.finishReason==="end_turn"&&(!K.toolCalls||K.toolCalls.length===0),Me=y?.(K)===!0,Oe=j>=h,he=Me||Re||!ne||Oe?"done":"acting";Y(()=>{E.emit(K),T.emit(he),w.emit(j),b.append("assistant",K.content,{toolCalls:K.toolCalls})})}),P=le([I],([J])=>{if(o)return;let K=J;if(K.length===0)return;let j=r>=h?"done":"thinking";Y(()=>{T.emit(j);for(let ne of K)b.appendToolResult(ne.id,ne.content)})}),U=T.cache??"idle",z=T.subscribe(J=>{for(let K of J)K[0]===R&&(U=K[1])}),D=le([k],([J])=>{J===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),U!=="done"&&T.emit("done"))}),Z=re(A),te=re(P),ke=re(D);this._terminalResult=V([T,E],(J,K,j)=>{let ne=co(J,j.prevData,0,"idle"),Re=co(J,j.prevData,1,null);if(ne==="done"){if(Re!=null){K.emit(Re);return}let Me=new Error("agentLoop: aborted");Me.name="AbortError",K.down([[M,Me]]);return}if(ne==="error"){K.down([[M,new Error("agentLoop: errored")]]);return}K.down([[G]])},{name:"terminalResult",describeKind:"derived",meta:pe("agent_terminal_result")}),this.add(x,{name:"promptInput"}),this.add(S,{name:"llmResponse"}),this.add(this.lastResponse,{name:"lastResponse"}),this.toolCalls===L?this.add(this.toolCalls,{name:"toolCalls"}):(this.add(L,{name:"toolCallsRaw"}),this.add(this.toolCalls,{name:"toolCalls"})),this.add(I,{name:"toolResults"}),this.add(this._terminalResult,{name:"terminalResult"}),this.addDisposer(s),this.addDisposer(i),this.addDisposer(z),this.addDisposer(u),this.addDisposer(c),this.addDisposer(Z),this.addDisposer(te),this.addDisposer(ke),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{Y(()=>{this.turn.emit(0),this.aborted.emit(!1),this.status.emit("idle"),this.lastResponse.emit(null)}),e!=null&&this.chat.append("user",e);let s=Wo(this._terminalResult,{skipCurrent:!0});if(n!=null)if(n.aborted)this.aborted.emit(!0);else{let o=()=>this.aborted.emit(!0);n.addEventListener("abort",o,{once:!0}),r=()=>n.removeEventListener("abort",o)}return n?.aborted!==!0&&this.status.emit("thinking"),await s}finally{r?.(),this._running=!1,this._currentAbortController=null}}abort(){this.aborted.emit(!0)}destroy(){try{this._disposeRunWiring()}catch{}super.destroy()}};function co(t,e,n,r){let s=t[n];if(s!=null&&s.length>0)return s[s.length-1];let o=e[n];return o!==void 0?o:r}function _g(t,e){return new Us(t,e)}Q();Te();function Mg(t,e,n){let r=W(t),s=n?.condition!=null?W(n.condition):null,o=N(null,{name:n?.name?`${n.name}::null`:"handoff::null"});if(s==null)return be(r,a=>{if(a==null)return o;let u=N(a);return e(u)});let i=_([r,s],([a,u])=>({v:a,open:u===!0}),{name:n?.name?`${n.name}::router`:"handoff::router",describeKind:"derived"});return be(i,({v:a,open:u})=>{if(a==null)return o;if(!u)return N(a);let d=N(a);return e(d)})}Q();Te();function Og(t,e,n){let r=W(t),s=e.map(i=>W(i)),o=[r,...s];return _(o,i=>{let a=i[0]??[],u=i.slice(1);return a.filter(d=>{for(let c of u)if(c!=null&&!c(d))return!1;return!0})},{name:n?.name??"tool-selector",describeKind:"derived",meta:pe("tool_selector"),equals:(i,a)=>{let u=i,d=a;if(u.length!==d.length)return!1;for(let c=0;c<u.length;c++)if(u[c]!==d[c])return!1;return!0}})}function Tp(t){let e=t.thresholds??{};return n=>{let r=t.scoreFn(n);for(let s of Object.keys(e)){let o=e[s];if(o===void 0)continue;let i=r[s];if((Number.isFinite(i)?i:Number.NEGATIVE_INFINITY)<o)return!1}return!0}}function Cg(t){let e={persistence:t.persistenceThreshold??.3,personalValue:t.personalValueThreshold??.3},n=Tp({scoreFn:t.scoreFn,thresholds:e});return t.requireStructured?r=>{if(!n(r))return!1;let s=t.scoreFn(r).structure;return Number.isFinite(s)&&s>0}:n}Q();Te();Q();function wp(t,e,n,r){let s=n.name??r;return o=>{let i=N(o);return wn(n.adapter,[i],a=>e(a),{name:s,format:"json",systemPrompt:t,model:n.model,temperature:n.temperature??0,maxTokens:n.maxTokens})}}function Ya(t,e){let n=e.maxExistingKeys??100,r=wp(t,s=>JSON.stringify({input:s.raw,existingKeys:s.existingKeys}),e,"llmExtractor");return(s,o)=>{let i=n===Number.POSITIVE_INFINITY?[...o.keys()]:[...o.keys()].slice(0,n);return r({raw:s,existingKeys:i})}}function Qa(t,e){let n=wp(t,r=>JSON.stringify({memories:r}),e,"llmConsolidator");return r=>{let s=[...r.entries()].map(([o,i])=>({key:o,value:i}));return n(s)}}Ce();Ne();Q();Te();var Js={};we(Js,{collection:()=>Lg,decay:()=>Rn,knowledgeGraph:()=>eu,lightCollection:()=>Xa,vectorIndex:()=>Za});Ne();Q();function Rn(t,e,n,r=0){if(!Number.isFinite(t))return r;if(!Number.isFinite(e)||e<=0||!Number.isFinite(n)||n<=0)return Math.max(r,t);let s=t*Math.exp(-n*e);return Math.max(r,s)}function kp(t){if(t!==void 0&&t<1)throw new RangeError("maxSize must be >= 1")}function xt(t){return new Map(t)}function nt(t){return t.cache??new Map}function zs(t){return t.cache??[]}function Ag(t,e){let n=Math.max(t.length,e.length),r=0,s=0,o=0;for(let i=0;i<n;i+=1){let a=t[i]??0,u=e[i]??0;r+=a*u,s+=a*a,o+=u*u}return s===0||o===0?0:r/Math.sqrt(s*o)}function Xa(t={}){let e=t.maxSize,n=t.policy??"fifo";kp(e);let r=N(new Map,{name:t.name,describeKind:"state"});function s(i){if(e!==void 0)for(;i.size>e;){let a;for(let u of i.values()){if(!a){a=u;continue}let d=n==="lru"?u.lastAccessNs:u.createdAtNs,c=n==="lru"?a.lastAccessNs:a.createdAtNs;d<c&&(a=u)}if(!a)break;i.delete(a.id)}}function o(i){r.emit(i)}return{entries:r,upsert(i,a){let u=F(),d=nt(r),c=d.get(i),l=xt(d);l.set(i,{id:i,value:a,createdAtNs:c?.createdAtNs??u,lastAccessNs:u}),s(l),o(l)},remove(i){let a=xt(nt(r));a.delete(i)&&o(a)},clear(){nt(r).size!==0&&o(new Map)},get(i){let a=nt(r),u=a.get(i);if(u){if(n==="lru"){let d=F(),c=xt(a);c.set(i,{...u,lastAccessNs:d}),o(c)}return u.value}},has(i){return nt(r).has(i)}}}function Lg(t,e={}){let n=e.maxSize,r=e.policy??"lru",s=e.decayRate??0,o=e.minScore??0,i=e.score??(()=>1);kp(n);let a=new q(t),u=N(new Map,{name:"items",describeKind:"state"}),d=_([u],([g])=>{let h=g??new Map,y=F(),b=[...h.values()].map(v=>{let T=(y-v.lastAccessNs)/1e9;return{...v,score:Rn(v.baseScore,T,s,o)}});return b.sort((v,T)=>T.score-v.score||T.lastAccessNs-v.lastAccessNs),b},{name:"ranked",describeKind:"derived"}),c=_([u],([g])=>(g??new Map).size,{name:"size",describeKind:"derived",initial:0});d.subscribe(()=>{}),c.subscribe(()=>{}),a.add(u,{name:"items"}),a.add(d,{name:"ranked"}),a.add(c,{name:"size"});function l(g,h){let y=(h-g.lastAccessNs)/1e9;return Rn(g.baseScore,y,s,o)}function p(g){if(n!==void 0)for(;g.size>n;){let h=F(),y,b=Number.POSITIVE_INFINITY;for(let v of g.values()){let T=l(v,h);if(T<b){y=v,b=T;continue}if(T===b&&y){let w=r==="lru"?v.lastAccessNs:v.createdAtNs,k=r==="lru"?y.lastAccessNs:y.createdAtNs;w<k&&(y=v)}}if(!y)break;g.delete(y.id)}}function f(g){u.emit(g)}return Object.assign(a,{upsert(g,h,y){let b=F(),v=nt(u),T=v.get(g),w=y?.score??i(h),k=xt(v);k.set(g,{id:g,value:h,baseScore:w,createdAtNs:T?.createdAtNs??b,lastAccessNs:b}),p(k),f(k)},remove(g){let h=xt(nt(u));h.delete(g)&&f(h)},clear(){nt(u).size!==0&&f(new Map)},getItem(g){let h=nt(u),y=h.get(g);if(y){if(r==="lru"){let b=xt(h);b.set(g,{...y,lastAccessNs:F()}),f(b)}return y}}})}function Za(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 s=N(new Map,{describeKind:"state",name:"vector-index"});function o(a){if(n!==void 0&&a.length!==n)throw new RangeError(`vector dimension mismatch: expected ${n}, got ${a.length}`)}function i(a){s.emit(a)}return{backend:e,entries:s,upsert(a,u,d){o(u);let c=xt(nt(s));c.set(a,{id:a,vector:[...u],meta:d}),e==="hnsw"&&r.upsert(a,u,d),i(c)},remove(a){let u=xt(nt(s));u.delete(a)&&(e==="hnsw"&&r.remove(a),i(u))},clear(){nt(s).size!==0&&(e==="hnsw"&&r.clear(),i(new Map))},search(a,u=5){return o(a),u<=0?[]:e==="hnsw"?r.search(a,u):[...nt(s).values()].map(c=>({id:c.id,score:Ag(a,c.vector),meta:c.meta})).sort((c,l)=>l.score-c.score).slice(0,u)}}}function eu(t){let e=new q(t),n=N(new Map,{name:"entities",describeKind:"state"}),r=N([],{name:"edges",describeKind:"state"}),s=_([r],([u])=>{let d=u??[],c=new Map;for(let l of d){let p=c.get(l.from)??[];c.set(l.from,Object.freeze([...p,l]))}return c},{name:"adjacency",describeKind:"derived",initial:new Map});s.subscribe(()=>{}),e.add(n,{name:"entities"}),e.add(r,{name:"edges"}),e.add(s,{name:"adjacency"});function o(u){n.emit(u)}function i(u){r.emit(u)}return Object.assign(e,{upsertEntity(u,d){let c=xt(nt(n));c.set(u,d),o(c)},removeEntity(u){let d=xt(nt(n)),c=d.delete(u),l=zs(r),p=l.filter(f=>f.from!==u&&f.to!==u);!c&&p.length===l.length||(o(d),i(p))},link(u,d,c,l=1){let p=`${u}\0${d}\0${c}`,f=zs(r),m=new Set(f.map(h=>`${h.from}\0${h.to}\0${h.relation}`)),g=[...f];if(m.has(p))for(let h=0;h<g.length;h+=1){let y=g[h];if(y.from===u&&y.to===d&&y.relation===c){g[h]={...y,weight:l};break}}else g.push({from:u,to:d,relation:c,weight:l});i(g)},unlink(u,d,c){let l=zs(r),p=l.filter(f=>c===void 0?!(f.from===u&&f.to===d):!(f.from===u&&f.to===d&&f.relation===c));p.length!==l.length&&i(p)},related(u,d){return zs(r).filter(c=>(c.from===u||c.to===u)&&(d===void 0||c.relation===d))}})}var tu=Math.LN2/604800;function sr(t){return t instanceof Map?t:new Map}function nu(t,e,n){let r=Za({dimension:n.dimension});t.add(r.entries,{name:"vectorIndex"});let o=le([e.store.entries],([i])=>{let a=sr(i);for(let[u,d]of a){let c=n.embedFn(d);c&&r.upsert(u,c,d)}}).subscribe(()=>{});return t.addDisposer(o),{vectors:r,dispose:()=>o()}}function ru(t,e,n,r){let s=r.mountPath??n,o=eu(`${n}-kg`);if(t.mount(s,o),!r.entityFn)return{kg:o,dispose:()=>{}};let i=r.entityFn,u=le([e.store.entries],([d])=>{let c=sr(d);for(let[l,p]of c){let f=i(l,p);if(f){for(let m of f.entities??[])o.upsertEntity(m.id,m.value);for(let m of f.relations??[])o.link(m.from,m.to,m.relation,m.weight)}}}).subscribe(()=>{});return t.addDisposer(u),{kg:o,dispose:()=>u()}}function ou(t,e,n){let r=n.decayRate??tu,s=n.maxActive??1e3,o=n.archiveThreshold??.1,i=n.permanentFilter??(()=>!1),a=Xa({name:"permanent"});t.add(a.entries,{name:"permanent"});let u=new Set,d=b=>u.has(b)?"permanent":sr(e.store.entries.cache).has(b)?"active":"archived",c=(b,v)=>{u.add(b),a.upsert(b,v)},l=new Map,p=e.store.entries,f=n.context?W(n.context):N(null),g=le([p,f],([b,v])=>{let T=sr(b),w=F(),k=[],x=[];for(let[E,L]of T){if(l.has(E)||l.set(E,w),i(E,L)){x.push({key:E,value:L});continue}let C=n.score(L,v),I=l.get(E)??w,A=Number(w-I)/1e9;Rn(C,A,r)<o&&k.push(E)}for(let E of l.keys())T.has(E)||l.delete(E);for(let{key:E,value:L}of x)u.has(E)||c(E,L);let S=T.size-u.size;if(S>s){let E=[...T.entries()].filter(([C])=>!u.has(C)).map(([C,I])=>({key:C,score:n.score(I,v)})).sort((C,I)=>C.score-I.score),L=S-s;for(let C=0;C<L&&C<E.length;C++){let I=E[C].key;k.includes(I)||k.push(I)}}k.length>0&&Y(()=>{for(let E of k)e.store.delete(E)})}).subscribe(()=>{}),h=null;n.archiveTier&&(h=t.attachStorage([n.archiveTier],n.archiveStorageOptions??{}));let y=()=>{g(),h?.dispose()};return t.addDisposer(y),{tiers:{permanent:a,activeEntries:p,archiveHandle:h,tierOf:d,markPermanent:c},dispose:y}}function Ig(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 su(t,e,n,r,s){let o=s.topK??20,i=s.graphDepth??1,a=s.budget??2e3,u=s.contextWeight??0,d=s.context?W(s.context):N(null),c=(h,y,b)=>{let v=new Map,T=[];if(n&&b.vector){T=n.search(b.vector,o);for(let L of T){let C=h.get(L.id);C&&v.set(L.id,{value:C,sources:new Set(["vector"])})}}let w=[];if(r){let L=[...b.entityIds??[],...v.keys()],C=new Set,I=L;for(let A=0;A<i;A++){let P=[];for(let U of I)if(!C.has(U)){C.add(U);for(let z of r.related(U)){let D=z.to;if(!C.has(D)){P.push(D);let Z=h.get(D);if(Z){let te=v.get(D);te?te.sources.add("graph"):v.set(D,{value:Z,sources:new Set(["graph"])}),w.push(D)}}}}I=P}}for(let[L,C]of h)v.has(L)||v.set(L,{value:C,sources:new Set(["store"])});let k=b.context?.length??0,x=[];for(let[L,{value:C,sources:I}]of v){let A=s.contextOf?s.contextOf(C):void 0,P=s.score(C,y);if(u>0&&k>0){let z=Ig(b.context,A);z>0&&(P=P*(1+u*z/k))}let U=A?{key:L,value:C,score:P,sources:[...I],context:A}:{key:L,value:C,score:P,sources:[...I]};x.push(U)}x.sort((L,C)=>C.score-L.score);let S=[],E=0;for(let L of x){let C=s.cost(L.value);if(E+C>a&&S.length>0)break;S.push(L),E+=C}return{packed:S,trace:{vectorCandidates:T,graphExpanded:w,ranked:x,packed:S}}},l=(h,y)=>{if(h===y)return!0;if(h.length!==y.length)return!1;for(let b=0;b<h.length;b++)if(h[b]!==y[b])return!1;return!0},p=N([],{name:"retrieval",describeKind:"state",meta:pe("retrieval_pipeline"),equals:l});t.add(p,{name:"retrieval"});let f=N(null,{name:"retrievalTrace",describeKind:"state",meta:pe("retrieval_trace")});return t.add(f,{name:"retrievalTrace"}),{retrieval:p,retrievalTrace:f,retrieve:h=>{let y=sr(e.store.entries.cache),{packed:b,trace:v}=c(y,d.cache,h);return Y(()=>{p.emit(b),f.emit(v)}),b},retrieveReactive:h=>{let y=W(h),b=_([e.store.entries,d,y],([w,k,x])=>{if(x==null)return{packed:[],trace:null};let S=sr(w),{packed:E,trace:L}=c(S,k,x);return{packed:E,trace:L}},{name:"retrievalReactive::result",describeKind:"derived",meta:pe("retrieval_reactive_result"),initial:{packed:[],trace:null}}),T=le([b],([w])=>{let k=w;Y(()=>{p.emit(k.packed),k.trace&&f.emit(k.trace)})}).subscribe(()=>{});return t.addDisposer(T),_([b],([w])=>w.packed,{name:"retrievalReactive",describeKind:"derived",meta:pe("retrieval_reactive"),initial:[],equals:l})}}}function Dg(t,e,n){let r=new q(t,n.graph),s;if(n.extractFn)s=n.extractFn;else if(n.adapter&&n.extractPrompt)s=Ya(n.extractPrompt,{adapter:n.adapter});else throw new Error("agentMemory: provide either extractFn or adapter + extractPrompt");let o=(b,v)=>b==null?{upsert:[]}:s(b,v),i=e;if(n.admissionFilter){let b=W(e),v=n.admissionFilter;i=_([b],([T])=>{if(v(T))return T},{name:"admissionFilter",describeKind:"derived"})}let a;n.consolidateFn?a=n.consolidateFn:n.adapter&&n.consolidatePrompt&&(a=Qa(n.consolidatePrompt,{adapter:n.adapter}));let u=n.consolidateTrigger;if(!u&&a&&n.reflection?.enabled!==!1){let b=n.reflection?.interval??3e5;u=dt(b,{period:b})}let d={score:n.score,cost:n.cost,budget:n.budget??2e3,context:n.context,consolidate:a,consolidateTrigger:u},c=ws(i,o,d);r.add(c.store.entries,{name:"store"}),r.add(c.compact,{name:"compact"}),r.add(c.size,{name:"size"});let l=null;n.vectorDimensions&&n.vectorDimensions>0&&n.embedFn&&(l=nu(r,c,{dimension:n.vectorDimensions,embedFn:n.embedFn}).vectors);let p=null;n.enableKnowledgeGraph&&(p=ru(r,c,t,{mountPath:"kg",entityFn:n.entityFn}).kg);let f=null;n.tiers&&(f=ou(r,c,{...n.tiers,score:n.score,context:n.context}).tiers);let m=null,g=null,h=null,y=null;if(l||p){let b=su(r,c,l,p,{score:n.score,cost:n.cost,budget:n.budget,topK:n.retrieval?.topK,graphDepth:n.retrieval?.graphDepth,contextOf:n.contextOf,contextWeight:n.contextWeight,context:n.context});m=b.retrieval,g=b.retrievalTrace,h=b.retrieve,y=b.retrieveReactive}return Object.assign(r,{distillBundle:c,compact:c.compact,size:c.size,vectors:l,kg:p,memoryTiers:f,retrieval:m,retrievalTrace:g,retrieve:h,retrieveReactive:y})}function Pg(t,e,n){let r=t.describe({actor:e,detail:"full"}),s=n?.groupByTags??!0,o=n?.separator??`
40
+ `,i=[],a=n?.sinceVersion;for(let[u,d]of Object.entries(r.nodes)){let c=d.meta??{},l=c.description,p=c.format;if(!l&&!p)continue;if(a!=null&&d.v!=null){let y=a.get(u);if(y!=null&&y.id===d.v.id&&d.v.version<=y.version)continue}let f=l??u,m=d.value,g=c.unit,h;p==="currency"&&typeof m=="number"?h=`$${m.toFixed(2)}`:p==="percentage"&&typeof m=="number"?h=`${(m*100).toFixed(1)}%`:m==null?h="(no value)":h=String(m),g&&p!=="currency"&&p!=="percentage"&&(h=`${h} ${g}`),i.push({path:u,description:f,formatted:h})}if(i.length===0)return"";if(s){let u=new Map,d=[];for(let l of i){let f=r.nodes[l.path].meta?.tags;if(f&&f.length>0){let m=f[0],g=u.get(m);g||(g=[],u.set(m,g)),g.push(l)}else d.push(l)}if(u.size===0)return i.map(l=>`- ${l.description}: ${l.formatted}`).join(o);let c=[];for(let[l,p]of[...u.entries()].sort((f,m)=>f[0].localeCompare(m[0])))c.push(`[${l}]${o}${p.map(f=>`- ${f.description}: ${f.formatted}`).join(o)}`);return d.length>0&&c.push(d.map(l=>`- ${l.description}: ${l.formatted}`).join(o)),c.join(o+o)}return i.map(u=>`- ${u.description}: ${u.formatted}`).join(o)}se();Q();Te();var Xs={};we(Xs,{compileSpec:()=>mo,decompileGraph:()=>Hg,extractFnFactory:()=>Rp,extractSourceFactory:()=>Sp,generateCatalogPrompt:()=>Np,isRichFnEntry:()=>po,isRichSourceEntry:()=>uu,llmCompose:()=>Wg,llmRefine:()=>Mp,specDiff:()=>qg,validateSpec:()=>ir,validateSpecAgainstCatalog:()=>fo});Q();var Qs={};we(Qs,{budgetGate:()=>iu,effectivenessTracker:()=>Fg,feedback:()=>Jt,funnel:()=>Gg,scorer:()=>lo});Ce();se();_e();Q();function Ys(t,e){return ze("reduction",t,e)}function Gg(t,e,n,r){if(e.length===0)throw new RangeError("funnel requires at least one source");if(n.length===0)throw new RangeError("funnel requires at least one stage");let s=new q(t,r),o=e.length===1?e[0]:wt(...e);s.add(o,{name:"merged"});let i="merged";for(let a=0;a<n.length;a++){let u=n[a],d=new q(u.name);u.build(d);try{d.resolve("input")}catch{throw new Error(`funnel stage "${u.name}" must define an "input" node`)}try{d.resolve("output")}catch{throw new Error(`funnel stage "${u.name}" must define an "output" node`)}s.mount(u.name,d);let c=s.resolve(i),l=`${u.name}::input`,p=s.resolve(l),f=`__bridge_${i}\u2192${u.name}_input`,m=le([c],([g])=>{p.emit(g)},{name:f});s.add(m,{name:f}),s.addDisposer(re(m)),i=`${u.name}::output`}return s}function Jt(t,e,n,r){let s=r?.maxIterations??10,o=`__feedback_${e}`,i=N(0,{meta:Ys("feedback_counter",{maxIterations:s,feedbackFrom:e,feedbackTo:n})});t.add(i,{name:o});let a=t.resolve(e),u=t.resolve(n),d=`__feedback_effect_${e}`,c=V([],(l,p)=>{let f=a.subscribe(m=>{for(let g of m){let h=g[0];if(h===R){let y=g[1];if(y==null)return;Y(()=>{Fr(i,s)&&u.emit(y)})}else if(h===O||h===M){let y=h===M&&g.length>1?[M,g[1]]:[h];i.down([y])}}});return()=>f()},{name:d,describeKind:"effect",meta:{...Ys("feedback_effect",{feedbackFrom:e,feedbackTo:n}),_internal:!0}});return t.add(c,{name:d}),t.addDisposer(re(c)),t}function iu(t,e,n){if(e.length===0)throw new RangeError("budgetGate requires at least one constraint");let r=e.map(f=>f.node),s=[t,...r],o=[],i=!1,a=!1,u=Symbol("budget-gate"),d=new Array(e.length);function c(){return e.every((f,m)=>f.check(d[m]))}function l(f){for(;o.length>0&&c();){let m=o[0];o=o.slice(1),f.emit(m)}o.length===0&&a&&(a=!1,f.down([[G]]))}return V([],(f,m)=>{for(let h=0;h<e.length;h++)d[h]=e[h].node.cache;let g=[];for(let h=0;h<s.length;h++){let y=s[h];g.push(y.subscribe(b=>{for(let v of b)p(v,h,m)}))}return()=>{for(let h of g)h()}},{...n,describeKind:"derived",meta:Ys("budget_gate",n?.meta)});function p(f,m,g){let h=f[0];if(m===0){if(h===R)return c()&&o.length===0?g.emit(f[1]):(o.push(f[1]),i||(i=!0,g.up([[Be,u]]))),!0;if(h===X)return g.down([[X]]),!0;if(h===G)return o.length===0?g.down([[G]]):a=!0,!0;if(h===O||h===M){for(let y of o)g.emit(y);return o=[],a=!1,i&&(i=!1,g.up([[Ke,u]])),g.down([f]),!0}return!1}return h===R&&(d[m-1]=f[1]),h===R||h===G?(c()&&o.length>0?(l(g),o.length===0&&i&&(i=!1,g.up([[Ke,u]]))):!c()&&!i&&o.length>0&&(i=!0,g.up([[Be,u]])),!0):h===X?!0:h===M?(g.down([f]),!0):h===O}}function lo(t,e,n){if(t.length===0)throw new RangeError("scorer requires at least one source");if(t.length!==e.length)throw new RangeError("scorer requires the same number of sources and weights");let r=[...t,...e],s=t.length,o=n?.scoreFns;return _(r,i=>{let a=i.slice(0,s),u=i.slice(s),d=[],c=0;for(let l=0;l<s;l++){let p=a[l]??0,f=u[l]??0,g=(o?.[l]?o[l](p):p)*f;d.push(g),c+=g}return{value:a,score:c,breakdown:d}},{...n?{equals:n.equals,resubscribable:n.resubscribable,resetOnTeardown:n.resetOnTeardown}:{},describeKind:"derived",meta:Ys("scorer",n?.meta)})}function Fg(t){let e=Ze({name:t?.name??"effectiveness-entries"}),n=_([e.entries],([i])=>new Map(i),{name:`${t?.name??"effectiveness"}-snapshot`,equals:(i,a)=>{let u=i,d=a;if(u.size!==d.size)return!1;for(let[c,l]of u){let p=d.get(c);if(!p||l.attempts!==p.attempts||l.successes!==p.successes)return!1}return!0}});function r(i,a){let u=e.get(i),d=(u?.attempts??0)+1,c=(u?.successes??0)+(a?1:0);e.set(i,{key:i,attempts:d,successes:c,successRate:c/d})}function s(i){return e.get(i)}let o=re(n);return{node:n,record:r,lookup:s,dispose:()=>o()}}function po(t){return typeof t=="object"&&t!==null&&"factory"in t}function uu(t){return typeof t=="object"&&t!==null&&"factory"in t}function Rp(t){return po(t)?t.factory:t}function Sp(t){return uu(t)?t.factory:t}function Np(t){let e=[];if(t.fns){let n=new Map;for(let[r,s]of Object.entries(t.fns)){let o=po(s)?s.tags?.[0]??"Other":"Other";n.has(o)||n.set(o,[]),n.get(o).push($g(r,s))}for(let[r,s]of n)e.push(`${r}:
41
+ ${s.join(`
42
+ `)}`)}if(t.sources){let n=[];for(let[r,s]of Object.entries(t.sources))n.push(jg(r,s));n.length>0&&e.push(`Sources:
43
43
  ${n.join(`
44
44
  `)}`)}return e.join(`
45
45
 
46
- `)}function $g(t,e){if(!yo(e))return`- ${t}`;let n=`- ${t}: ${e.description}`;if(e.configSchema){let r=Object.entries(e.configSchema).map(([o,s])=>{let i=`${o}: ${s.type}`;return s.enum&&(i+=` (${s.enum.join("|")})`),s.required===!1&&(i+="?"),i});n+=`. Config: { ${r.join(", ")} }`}return n}function jg(t,e){if(!su(e))return`- ${t}`;let n=`- ${t}: ${e.description}`;if(e.configSchema){let r=Object.entries(e.configSchema).map(([o,s])=>{let i=`${o}: ${s.type}`;return s.required===!1&&(i+="?"),i});n+=`. Config: { ${r.join(", ")} }`}return n}function bo(t,e){let n=[],r=new Set(Object.keys(e.fns??{})),o=new Set(Object.keys(e.sources??{}));for(let[s,i]of Object.entries(t.nodes)){if(i.type==="template")continue;let a=i;if(a.fn&&r.size>0&&!r.has(a.fn))if(o.has(a.fn))n.push(`Node "${s}": fn "${a.fn}" is a source, not a function. Use it as a producer source instead, or use a function from: ${[...r].join(", ")}`);else{let u=ou(a.fn,r);n.push(`Node "${s}": fn "${a.fn}" not found in catalog`+(u?`. Did you mean "${u}"?`:""))}if(a.source&&o.size>0&&!o.has(a.source))if(r.has(a.source))n.push(`Node "${s}": source "${a.source}" is a function, not a source. Use it as fn instead, or use a source from: ${[...o].join(", ")}`);else{let u=ou(a.source,o);n.push(`Node "${s}": source "${a.source}" not found in catalog`+(u?`. Did you mean "${u}"?`:""))}if(a.fn&&a.config&&e.fns?.[a.fn]){let u=e.fns[a.fn];if(yo(u)&&u.configSchema){for(let[c,d]of Object.entries(u.configSchema))if(d.required!==!1&&!(c in a.config)&&n.push(`Node "${s}": config missing required field "${c}"`),c in a.config&&d.enum){let l=a.config[c];d.enum.includes(l)||n.push(`Node "${s}": config.${c} = ${JSON.stringify(l)}, expected one of: ${d.enum.join(", ")}`)}}}}if(t.templates){for(let[s,i]of Object.entries(t.templates))for(let[a,u]of Object.entries(i.nodes))if(u.fn&&r.size>0&&!r.has(u.fn)){let c=ou(u.fn,r);n.push(`Template "${s}" node "${a}": fn "${u.fn}" not found in catalog`+(c?`. Did you mean "${c}"?`:""))}}return{valid:n.length===0,errors:n,warnings:[]}}function ou(t,e){let n=null,r=1/0,o=t.toLowerCase();for(let s of e){let i=Bg(o,s.toLowerCase());i<r&&i<=Math.max(3,Math.floor(t.length/2))&&(r=i,n=s)}return n}function Bg(t,e){let n=t.length,r=e.length,o=Array.from({length:n+1},(s,i)=>Array.from({length:r+1},(a,u)=>i===0?u:u===0?i:0));for(let s=1;s<=n;s++)for(let i=1;i<=r;i++)o[s][i]=t[s-1]===e[i-1]?o[s-1][i-1]:1+Math.min(o[s-1][i],o[s][i-1],o[s-1][i-1]);return o[n][r]}var bp=new Set(["state","producer","derived","effect","operator","template"]),Vg=new Set(["state","producer","derived","effect","operator"]);function ir(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,u]of Object.entries(r.templates))if(u!=null&&typeof u=="object"){let c=u;i.set(a,{params:Array.isArray(c.params)?c.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,u]of Object.entries(r.templates)){if(u==null||typeof u!="object"){e.push(`Template "${a}": must be an object`);continue}let c=u;if(Array.isArray(c.params)||e.push(`Template "${a}": missing 'params' array`),c.nodes==null||typeof c.nodes!="object"||Array.isArray(c.nodes))e.push(`Template "${a}": missing or invalid 'nodes' object`);else{let d=new Set(Array.isArray(c.params)?c.params:[]),l=new Set(Object.keys(c.nodes));for(let[p,f]of Object.entries(c.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"||!Vg.has(m.type))&&e.push(`Template "${a}" node "${p}": invalid type`),Array.isArray(m.deps))for(let g of m.deps)!l.has(g)&&!d.has(g)&&e.push(`Template "${a}" node "${p}": dep "${g}" is not an inner node or param`)}typeof c.output!="string"?e.push(`Template "${a}": missing 'output' string`):c.nodes[c.output]||e.push(`Template "${a}": output "${c.output}" is not a declared node`)}}for(let[a,u]of Object.entries(r.nodes)){if(u==null||typeof u!="object"){e.push(`Node "${a}": must be an object`);continue}let c=u;if(typeof c.type!="string"||!bp.has(c.type)){e.push(`Node "${a}": invalid type "${String(c.type)}" (expected: ${[...bp].join(", ")})`);continue}if(s.set(a,c.type),c.type==="template")if(typeof c.template!="string"||!i.has(c.template))e.push(`Node "${a}": template "${String(c.template)}" not found in templates`);else if(c.bind==null||typeof c.bind!="object"||Array.isArray(c.bind))e.push(`Node "${a}": template ref requires 'bind' object`);else{let d=i.get(c.template),l=c.bind;for(let p of d.params)p in l||e.push(`Node "${a}": template param "${p}" is not bound (template "${c.template}")`);for(let[,p]of Object.entries(l))typeof p=="string"&&!o.has(p)&&e.push(`Node "${a}": bind target "${p}" does not reference an existing node`)}else{if(Array.isArray(c.deps))for(let d of c.deps)d===a?e.push(`Node "${a}": self-referencing dep`):o.has(d)||e.push(`Node "${a}": dep "${d}" does not reference an existing node`);(c.type==="derived"||c.type==="effect"||c.type==="operator")&&!Array.isArray(c.deps)&&e.push(`Node "${a}": ${c.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 u=r.feedback[a];if(u==null||typeof u!="object"){e.push(`Feedback [${a}]: must be an object`);continue}let c=u;typeof c.from!="string"||!o.has(c.from)?e.push(`Feedback [${a}]: 'from' "${String(c.from)}" does not reference an existing node`):s.get(c.from)==="effect"&&n.push(`Feedback [${a}]: 'from' "${c.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 c.from=="string"&&c.from===c.to&&e.push(`Feedback [${a}]: 'from' and 'to' must be different nodes`),typeof c.to!="string"||!o.has(c.to)?e.push(`Feedback [${a}]: 'to' "${String(c.to)}" does not reference an existing node`):typeof c.to=="string"&&s.get(c.to)!=="state"&&e.push(`Feedback [${a}]: 'to' node "${c.to}" must be a state node (got "${s.get(c.to)??"unknown"}")`)}return{valid:e.length===0,errors:e,warnings:n}}function vo(t,e){let n=ir(t);if(!n.valid)throw new Error(`compileSpec: invalid GraphSpec:
46
+ `)}function $g(t,e){if(!po(e))return`- ${t}`;let n=`- ${t}: ${e.description}`;if(e.configSchema){let r=Object.entries(e.configSchema).map(([s,o])=>{let i=`${s}: ${o.type}`;return o.enum&&(i+=` (${o.enum.join("|")})`),o.required===!1&&(i+="?"),i});n+=`. Config: { ${r.join(", ")} }`}return n}function jg(t,e){if(!uu(e))return`- ${t}`;let n=`- ${t}: ${e.description}`;if(e.configSchema){let r=Object.entries(e.configSchema).map(([s,o])=>{let i=`${s}: ${o.type}`;return o.required===!1&&(i+="?"),i});n+=`. Config: { ${r.join(", ")} }`}return n}function fo(t,e){let n=[],r=new Set(Object.keys(e.fns??{})),s=new Set(Object.keys(e.sources??{}));for(let[o,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(s.has(a.fn))n.push(`Node "${o}": fn "${a.fn}" is a source, not a function. Use it as a producer source instead, or use a function from: ${[...r].join(", ")}`);else{let u=au(a.fn,r);n.push(`Node "${o}": fn "${a.fn}" not found in catalog`+(u?`. Did you mean "${u}"?`:""))}if(a.source&&s.size>0&&!s.has(a.source))if(r.has(a.source))n.push(`Node "${o}": source "${a.source}" is a function, not a source. Use it as fn instead, or use a source from: ${[...s].join(", ")}`);else{let u=au(a.source,s);n.push(`Node "${o}": source "${a.source}" not found in catalog`+(u?`. Did you mean "${u}"?`:""))}if(a.fn&&a.config&&e.fns?.[a.fn]){let u=e.fns[a.fn];if(po(u)&&u.configSchema){for(let[d,c]of Object.entries(u.configSchema))if(c.required!==!1&&!(d in a.config)&&n.push(`Node "${o}": config missing required field "${d}"`),d in a.config&&c.enum){let l=a.config[d];c.enum.includes(l)||n.push(`Node "${o}": config.${d} = ${JSON.stringify(l)}, expected one of: ${c.enum.join(", ")}`)}}}}if(t.templates){for(let[o,i]of Object.entries(t.templates))for(let[a,u]of Object.entries(i.nodes))if(u.fn&&r.size>0&&!r.has(u.fn)){let d=au(u.fn,r);n.push(`Template "${o}" node "${a}": fn "${u.fn}" not found in catalog`+(d?`. Did you mean "${d}"?`:""))}}return{valid:n.length===0,errors:n,warnings:[]}}function au(t,e){let n=null,r=1/0,s=t.toLowerCase();for(let o of e){let i=Bg(s,o.toLowerCase());i<r&&i<=Math.max(3,Math.floor(t.length/2))&&(r=i,n=o)}return n}function Bg(t,e){let n=t.length,r=e.length,s=Array.from({length:n+1},(o,i)=>Array.from({length:r+1},(a,u)=>i===0?u:u===0?i:0));for(let o=1;o<=n;o++)for(let i=1;i<=r;i++)s[o][i]=t[o-1]===e[i-1]?s[o-1][i-1]:1+Math.min(s[o-1][i],s[o][i-1],s[o-1][i-1]);return s[n][r]}var xp=new Set(["state","producer","derived","effect","operator","template"]),Vg=new Set(["state","producer","derived","effect","operator"]);function ir(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 s=new Set(Object.keys(r.nodes)),o=new Map,i=new Map;if(r.templates!=null&&typeof r.templates=="object"&&!Array.isArray(r.templates)){for(let[a,u]of Object.entries(r.templates))if(u!=null&&typeof u=="object"){let d=u;i.set(a,{params:Array.isArray(d.params)?d.params:[]})}}if(r.templates!=null)if(typeof r.templates!="object"||Array.isArray(r.templates))e.push("'templates' must be an object");else for(let[a,u]of Object.entries(r.templates)){if(u==null||typeof u!="object"){e.push(`Template "${a}": must be an object`);continue}let d=u;if(Array.isArray(d.params)||e.push(`Template "${a}": missing 'params' array`),d.nodes==null||typeof d.nodes!="object"||Array.isArray(d.nodes))e.push(`Template "${a}": missing or invalid 'nodes' object`);else{let c=new Set(Array.isArray(d.params)?d.params:[]),l=new Set(Object.keys(d.nodes));for(let[p,f]of Object.entries(d.nodes)){if(f==null||typeof f!="object"){e.push(`Template "${a}" node "${p}": must be an object`);continue}let m=f;if((typeof m.type!="string"||!Vg.has(m.type))&&e.push(`Template "${a}" node "${p}": invalid type`),Array.isArray(m.deps))for(let g of m.deps)!l.has(g)&&!c.has(g)&&e.push(`Template "${a}" node "${p}": dep "${g}" is not an inner node or param`)}typeof d.output!="string"?e.push(`Template "${a}": missing 'output' string`):d.nodes[d.output]||e.push(`Template "${a}": output "${d.output}" is not a declared node`)}}for(let[a,u]of Object.entries(r.nodes)){if(u==null||typeof u!="object"){e.push(`Node "${a}": must be an object`);continue}let d=u;if(typeof d.type!="string"||!xp.has(d.type)){e.push(`Node "${a}": invalid type "${String(d.type)}" (expected: ${[...xp].join(", ")})`);continue}if(o.set(a,d.type),d.type==="template")if(typeof d.template!="string"||!i.has(d.template))e.push(`Node "${a}": template "${String(d.template)}" not found in templates`);else if(d.bind==null||typeof d.bind!="object"||Array.isArray(d.bind))e.push(`Node "${a}": template ref requires 'bind' object`);else{let c=i.get(d.template),l=d.bind;for(let p of c.params)p in l||e.push(`Node "${a}": template param "${p}" is not bound (template "${d.template}")`);for(let[,p]of Object.entries(l))typeof p=="string"&&!s.has(p)&&e.push(`Node "${a}": bind target "${p}" does not reference an existing node`)}else{if(Array.isArray(d.deps))for(let c of d.deps)c===a?e.push(`Node "${a}": self-referencing dep`):s.has(c)||e.push(`Node "${a}": dep "${c}" does not reference an existing node`);(d.type==="derived"||d.type==="effect"||d.type==="operator")&&!Array.isArray(d.deps)&&e.push(`Node "${a}": ${d.type} node should have a 'deps' array`)}}if(r.feedback!=null)if(!Array.isArray(r.feedback))e.push("'feedback' must be an array");else for(let a=0;a<r.feedback.length;a++){let u=r.feedback[a];if(u==null||typeof u!="object"){e.push(`Feedback [${a}]: must be an object`);continue}let d=u;typeof d.from!="string"||!s.has(d.from)?e.push(`Feedback [${a}]: 'from' "${String(d.from)}" does not reference an existing node`):o.get(d.from)==="effect"&&n.push(`Feedback [${a}]: 'from' "${d.from}" is an effect node \u2014 effects emit no DATA, so the feedback edge will never fire. Did you mean a derived/state node upstream?`),typeof d.from=="string"&&d.from===d.to&&e.push(`Feedback [${a}]: 'from' and 'to' must be different nodes`),typeof d.to!="string"||!s.has(d.to)?e.push(`Feedback [${a}]: 'to' "${String(d.to)}" does not reference an existing node`):typeof d.to=="string"&&o.get(d.to)!=="state"&&e.push(`Feedback [${a}]: 'to' node "${d.to}" must be a state node (got "${o.get(d.to)??"unknown"}")`)}return{valid:e.length===0,errors:e,warnings:n}}function mo(t,e){let n=ir(t);if(!n.valid)throw new Error(`compileSpec: invalid GraphSpec:
47
47
  ${n.errors.join(`
48
- `)}`);let r=e?.catalog??{},o=e?.onMissing??"placeholder",s=new Y(t.name),i=t.templates??{},a=bo(t,r);if(!a.valid)throw new Error(`compileSpec: catalog validation errors:
48
+ `)}`);let r=e?.catalog??{},s=e?.onMissing??"placeholder",o=new q(t.name),i=t.templates??{},a=fo(t,r);if(!a.valid)throw new Error(`compileSpec: catalog validation errors:
49
49
  ${a.errors.join(`
50
- `)}`);let u=[],c=(h,y,b)=>{if(b){u.push({path:h,kind:"source",name:b});return}y&&u.push({path:h,kind:"fn",name:y})},d=h=>{let y=r.fns?.[h];return y?vp(y):void 0},l=h=>{let y=r.sources?.[h];return y?Tp(y):void 0},p=new Map,f=[];for(let[h,y]of Object.entries(t.nodes)){if(y.type==="template")continue;let b=y;if(b.type==="state"){let v=E(b.initial,{name:h,meta:b.meta?{...b.meta}:void 0});s.add(v,{name:h}),p.set(h,v)}else if(b.type==="producer"){let v=b.source?l(b.source):void 0,T=b.fn?d(b.fn):void 0;if(v){let w=v(b.config??{});s.add(w,{name:h}),p.set(h,w)}else if(T){let w=T([],b.config??{});s.add(w,{name:h}),p.set(h,w)}else{c(h,b.fn,b.source);let w=H(()=>{},{name:h,meta:{...b.meta,_specFn:b.fn,_specSource:b.source}});s.add(w,{name:h}),p.set(h,w)}}else f.push([h,b])}let m=!0,g=new Map(f);for(;g.size>0&&m;){m=!1;for(let[h,y]of[...g.entries()]){let b=y.deps??[];if(!b.every(k=>p.has(k)))continue;let v=b.map(k=>p.get(k)),T=y.fn?d(y.fn):void 0,w;T?w=T(v,y.config??{}):y.type==="effect"?(y.fn&&c(h,y.fn,void 0),w=de(v,()=>{})):(y.fn&&c(h,y.fn,void 0),w=_(v,k=>k[0])),s.add(w,{name:h}),p.set(h,w),g.delete(h),m=!0}}if(g.size>0){let h=[...g.keys()].sort().join(", ");throw new Error(`compileSpec: unresolvable deps for nodes: ${h}`)}for(let[h,y]of Object.entries(t.nodes)){if(y.type!=="template")continue;let b=y,v=i[b.template],T=new Y(h),w=new Map,k=[];for(let[A,M]of Object.entries(v.nodes)){let I=(M.deps??[]).map(P=>P.startsWith("$")&&b.bind[P]?b.bind[P]:P),L={...M,deps:I};if(M.type==="state"){let P=E(M.initial,{name:A,meta:M.meta?{...M.meta}:void 0});T.add(P,{name:A}),w.set(A,P)}else if(M.type==="producer"){let P=M.source?l(M.source):void 0,J=M.fn?d(M.fn):void 0;if(P){let Q=P(M.config??{});T.add(Q,{name:A}),w.set(A,Q)}else if(J){let Q=J([],M.config??{});T.add(Q,{name:A}),w.set(A,Q)}else{c(`${h}.${A}`,M.fn,M.source);let Q=H(()=>{},{name:A,meta:{...M.meta,_specFn:M.fn,_specSource:M.source}});T.add(Q,{name:A}),w.set(A,Q)}}else k.push([A,L])}let x=!0,R=new Map(k);for(;R.size>0&&x;){x=!1;for(let[A,M]of[...R.entries()]){let I=M.deps??[];if(!I.every(D=>w.has(D)||p.has(D)))continue;let P=I.map(D=>w.get(D)??p.get(D)),J=M.fn?d(M.fn):void 0,Q;J?Q=J(P,M.config??{}):M.type==="effect"?(M.fn&&c(`${h}.${A}`,M.fn,void 0),Q=de(P,()=>{})):(M.fn&&c(`${h}.${A}`,M.fn,void 0),Q=_(P,D=>D[0])),T.add(Q,{name:A}),w.set(A,Q),R.delete(A),x=!0}}if(R.size>0){let A=[...R.keys()].sort().join(", ");throw new Error(`compileSpec: template "${b.template}" has unresolvable deps: ${A}`)}s.mount(h,T);let N=`${h}::${v.output}`;p.set(h,s.resolve(N));try{let A=s.resolve(N);A.meta._templateName?.emit(b.template),A.meta._templateBind?.emit(b.bind)}catch{}}for(let h of t.feedback??[])Yt(s,h.from,h.to,{maxIterations:h.maxIterations});if(u.length>0){if(o==="error"){let h=u.map(y=>` - ${y.path}: missing ${y.kind} "${y.name}"`);throw new Error(`compileSpec: ${u.length} catalog entr${u.length===1?"y":"ies"} missing \u2014 pass them via opts.catalog or set opts.onMissing to "warn"/"placeholder":
50
+ `)}`);let u=[],d=(h,y,b)=>{if(b){u.push({path:h,kind:"source",name:b});return}y&&u.push({path:h,kind:"fn",name:y})},c=h=>{let y=r.fns?.[h];return y?Rp(y):void 0},l=h=>{let y=r.sources?.[h];return y?Sp(y):void 0},p=new Map,f=[];for(let[h,y]of Object.entries(t.nodes)){if(y.type==="template")continue;let b=y;if(b.type==="state"){let v=N(b.initial,{name:h,meta:b.meta?{...b.meta}:void 0});o.add(v,{name:h}),p.set(h,v)}else if(b.type==="producer"){let v=b.source?l(b.source):void 0,T=b.fn?c(b.fn):void 0;if(v){let w=v(b.config??{});o.add(w,{name:h}),p.set(h,w)}else if(T){let w=T([],b.config??{});o.add(w,{name:h}),p.set(h,w)}else{d(h,b.fn,b.source);let w=$(()=>{},{name:h,meta:{...b.meta,_specFn:b.fn,_specSource:b.source}});o.add(w,{name:h}),p.set(h,w)}}else f.push([h,b])}let m=!0,g=new Map(f);for(;g.size>0&&m;){m=!1;for(let[h,y]of[...g.entries()]){let b=y.deps??[];if(!b.every(k=>p.has(k)))continue;let v=b.map(k=>p.get(k)),T=y.fn?c(y.fn):void 0,w;T?w=T(v,y.config??{}):y.type==="effect"?(y.fn&&d(h,y.fn,void 0),w=le(v,()=>{})):(y.fn&&d(h,y.fn,void 0),w=_(v,k=>k[0])),o.add(w,{name:h}),p.set(h,w),g.delete(h),m=!0}}if(g.size>0){let h=[...g.keys()].sort().join(", ");throw new Error(`compileSpec: unresolvable deps for nodes: ${h}`)}for(let[h,y]of Object.entries(t.nodes)){if(y.type!=="template")continue;let b=y,v=i[b.template],T=new q(h),w=new Map,k=[];for(let[L,C]of Object.entries(v.nodes)){let I=(C.deps??[]).map(P=>P.startsWith("$")&&b.bind[P]?b.bind[P]:P),A={...C,deps:I};if(C.type==="state"){let P=N(C.initial,{name:L,meta:C.meta?{...C.meta}:void 0});T.add(P,{name:L}),w.set(L,P)}else if(C.type==="producer"){let P=C.source?l(C.source):void 0,U=C.fn?c(C.fn):void 0;if(P){let z=P(C.config??{});T.add(z,{name:L}),w.set(L,z)}else if(U){let z=U([],C.config??{});T.add(z,{name:L}),w.set(L,z)}else{d(`${h}.${L}`,C.fn,C.source);let z=$(()=>{},{name:L,meta:{...C.meta,_specFn:C.fn,_specSource:C.source}});T.add(z,{name:L}),w.set(L,z)}}else k.push([L,A])}let x=!0,S=new Map(k);for(;S.size>0&&x;){x=!1;for(let[L,C]of[...S.entries()]){let I=C.deps??[];if(!I.every(D=>w.has(D)||p.has(D)))continue;let P=I.map(D=>w.get(D)??p.get(D)),U=C.fn?c(C.fn):void 0,z;U?z=U(P,C.config??{}):C.type==="effect"?(C.fn&&d(`${h}.${L}`,C.fn,void 0),z=le(P,()=>{})):(C.fn&&d(`${h}.${L}`,C.fn,void 0),z=_(P,D=>D[0])),T.add(z,{name:L}),w.set(L,z),S.delete(L),x=!0}}if(S.size>0){let L=[...S.keys()].sort().join(", ");throw new Error(`compileSpec: template "${b.template}" has unresolvable deps: ${L}`)}o.mount(h,T);let E=`${h}::${v.output}`;p.set(h,o.resolve(E));try{let L=o.resolve(E);L.meta._templateName?.emit(b.template),L.meta._templateBind?.emit(b.bind)}catch{}}for(let h of t.feedback??[])Jt(o,h.from,h.to,{maxIterations:h.maxIterations});if(u.length>0){if(s==="error"){let h=u.map(y=>` - ${y.path}: missing ${y.kind} "${y.name}"`);throw new Error(`compileSpec: ${u.length} catalog entr${u.length===1?"y":"ies"} missing \u2014 pass them via opts.catalog or set opts.onMissing to "warn"/"placeholder":
51
51
  ${h.join(`
52
- `)}`)}if(o==="warn"){let h=e?.onWarn??(y=>console.warn(y));for(let y of u)h(`compileSpec: ${y.path} references missing ${y.kind} "${y.name}" \u2014 substituted placeholder`)}}return s}var Kg=new Set(["reduction","reduction_type","_specFn","_specSource","_templateName","_templateBind","feedbackFrom","feedbackTo","_internal"]);function Hg(t){let e=t.describe({detail:"standard"}),n={},r=[],o=`::${qe}::`,s=/^__feedback_(?!effect_)(.+)$/,i=new Set;for(let f of Object.keys(e.nodes)){if(f.includes(o))continue;let m=s.exec(f);if(m){i.add(m[1]);let g=e.nodes[f]?.meta;g?.feedbackFrom&&g?.feedbackTo&&r.push({from:g.feedbackFrom,to:g.feedbackTo,...g.maxIterations?{maxIterations:g.maxIterations}:{}})}}for(let[f,m]of Object.entries(e.nodes)){if(f.includes(o)||s.test(f)||m.meta?._internal||f.startsWith("__feedback_effect_")||f.startsWith("__bridge_")||f.includes("::"))continue;let g={type:m.type};if(m.deps.length>0&&(g.deps=m.deps.filter(h=>!h.includes("::"))),m.type==="state"&&m.value!==void 0&&(g.initial=m.value),m.meta&&Object.keys(m.meta).length>0){let h={};for(let[y,b]of Object.entries(m.meta))Kg.has(y)||(h[y]=b);Object.keys(h).length>0&&(g.meta=h)}n[f]=g}let a={},u={},c=new Set;for(let f of e.subgraphs){let m=`${f}::`;for(let[g,h]of Object.entries(e.nodes)){if(!g.startsWith(m)||g.includes(o))continue;let y=h.meta;if(y?._templateName&&y?._templateBind){let b=y._templateName,v=y._templateBind;if(!a[b]){let T={},w=new Set,k=`${f}::`;for(let[I,L]of Object.entries(e.nodes)){if(!I.startsWith(k)||I.includes(o))continue;let P=I.slice(k.length);P.includes("::")||(w.add(P),T[P]={type:L.type,...L.deps.length>0?{deps:L.deps.map(J=>J.startsWith(k)?J.slice(k.length):J)}:{}})}let x=[],R=new Map;for(let I of Object.values(T))for(let L of I.deps??[])if(!w.has(L)&&!R.has(L)){let P=`$${L}`;x.push(P),R.set(L,P)}for(let I of Object.values(T))I.deps&&(I.deps=I.deps.map(L=>R.get(L)??L));let N=new Set;for(let I of Object.values(T))for(let L of I.deps??[])w.has(L)&&N.add(L);let M=[...w].filter(I=>!N.has(I))[0]??[...w].pop();a[b]={params:x,nodes:T,output:M}}delete n[f],u[f]={type:"template",template:b,bind:v},c.add(f);break}}}let d=new Map;for(let f of e.subgraphs){if(c.has(f))continue;let m={},g=`${f}::`;for(let[y,b]of Object.entries(e.nodes)){if(y.includes(o)||!y.startsWith(g))continue;let v=y.slice(g.length);v.includes("::")||(m[v]={type:b.type,...b.deps.length>0?{deps:b.deps.map(T=>T.startsWith(g)?T.slice(g.length):T)}:{}})}let h=JSON.stringify(Object.fromEntries(Object.entries(m).sort(([y],[b])=>y.localeCompare(b)).map(([y,b])=>[y,{type:b.type,deps:b.deps??[]}])));d.has(h)||d.set(h,[]),d.get(h).push({name:f,nodes:m})}for(let[,f]of d){if(f.length<2)continue;let m=`${f[0].name}_template`,g=f[0].nodes,h=new Set(Object.keys(g)),y=[],b=new Map;for(let x of Object.values(g))for(let R of x.deps??[])if(!h.has(R)&&!b.has(R)){let N=`$${R}`;y.push(N),b.set(R,N)}let v=new Set;for(let x of Object.values(g))for(let R of x.deps??[])h.has(R)&&v.add(R);let w=[...h].filter(x=>!v.has(x))[0]??[...h].pop(),k={};for(let[x,R]of Object.entries(g))k[x]={...R,deps:R.deps?.map(N=>b.get(N)??N)};a[m]={params:y,nodes:k,output:w};for(let x of f){delete n[x.name];let R={},N=new Set(Object.keys(x.nodes));for(let A of Object.values(x.nodes))for(let M of A.deps??[])if(!N.has(M)){let I=b.get(M)??`$${M}`;R[I]=M}u[x.name]={type:"template",template:m,bind:R}}}let l={...n,...u},p={name:e.name,nodes:l};return Object.keys(a).length>0&&(p.templates=a),r.length>0&&(p.feedback=r),p}function Wg(t,e){let n=[];t.name!==e.name&&n.push({type:"changed",path:"name",detail:`"${t.name}" \u2192 "${e.name}"`});let r=new Set(Object.keys(t.nodes)),o=new Set(Object.keys(e.nodes));for(let b of o)if(!r.has(b)){let v=e.nodes[b];n.push({type:"added",path:`nodes.${b}`,detail:`type: ${v.type}`})}for(let b of r)o.has(b)||n.push({type:"removed",path:`nodes.${b}`});for(let b of r){if(!o.has(b))continue;let v=t.nodes[b],T=e.nodes[b];if(JSON.stringify(v)!==JSON.stringify(T)){let w=[];v.type!==T.type&&w.push(`type: ${v.type} \u2192 ${T.type}`),JSON.stringify(v.deps)!==JSON.stringify(T.deps)&&w.push("deps changed"),v.fn!==T.fn&&w.push(`fn: ${v.fn} \u2192 ${T.fn}`),JSON.stringify(v.config)!==JSON.stringify(T.config)&&w.push("config changed"),n.push({type:"changed",path:`nodes.${b}`,detail:w.join("; ")||"modified"})}}let s=t.templates??{},i=e.templates??{},a=new Set(Object.keys(s)),u=new Set(Object.keys(i));for(let b of u)a.has(b)||n.push({type:"added",path:`templates.${b}`});for(let b of a)u.has(b)||n.push({type:"removed",path:`templates.${b}`});for(let b of a)u.has(b)&&JSON.stringify(s[b])!==JSON.stringify(i[b])&&n.push({type:"changed",path:`templates.${b}`,detail:"template definition changed"});let c=t.feedback??[],d=e.feedback??[],l=new Set(c.map(b=>`${b.from}->${b.to}`)),p=new Set(d.map(b=>`${b.from}->${b.to}`));for(let b of d){let v=`${b.from}->${b.to}`;l.has(v)||n.push({type:"added",path:`feedback.${v}`,detail:`maxIterations: ${b.maxIterations??10}`})}for(let b of c){let v=`${b.from}->${b.to}`;p.has(v)||n.push({type:"removed",path:`feedback.${v}`})}for(let b of c){let v=`${b.from}->${b.to}`,T=d.find(w=>w.from===b.from&&w.to===b.to);T&&JSON.stringify(b)!==JSON.stringify(T)&&n.push({type:"changed",path:`feedback.${v}`,detail:`maxIterations: ${b.maxIterations??10} \u2192 ${T.maxIterations??10}`})}let f=n.filter(b=>b.type==="added").length,m=n.filter(b=>b.type==="removed").length,g=n.filter(b=>b.type==="changed").length,h=[];f&&h.push(`${f} added`),m&&h.push(`${m} removed`),g&&h.push(`${g} changed`);let y=h.length>0?h.join(", "):"no changes";return{entries:n,summary:y}}var kp=`You are a graph architect for GraphReFly, a reactive graph protocol.
52
+ `)}`)}if(s==="warn"){let h=e?.onWarn??(y=>console.warn(y));for(let y of u)h(`compileSpec: ${y.path} references missing ${y.kind} "${y.name}" \u2014 substituted placeholder`)}}return o}var Kg=new Set(["reduction","reduction_type","_specFn","_specSource","_templateName","_templateBind","feedbackFrom","feedbackTo","_internal"]);function Hg(t){let e=t.describe({detail:"standard"}),n={},r=[],s=`::${We}::`,o=/^__feedback_(?!effect_)(.+)$/,i=new Set;for(let f of Object.keys(e.nodes)){if(f.includes(s))continue;let m=o.exec(f);if(m){i.add(m[1]);let g=e.nodes[f]?.meta;g?.feedbackFrom&&g?.feedbackTo&&r.push({from:g.feedbackFrom,to:g.feedbackTo,...g.maxIterations?{maxIterations:g.maxIterations}:{}})}}for(let[f,m]of Object.entries(e.nodes)){if(f.includes(s)||o.test(f)||m.meta?._internal||f.startsWith("__feedback_effect_")||f.startsWith("__bridge_")||f.includes("::"))continue;let g={type:m.type};if(m.deps.length>0&&(g.deps=m.deps.filter(h=>!h.includes("::"))),m.type==="state"&&m.value!==void 0&&(g.initial=m.value),m.meta&&Object.keys(m.meta).length>0){let h={};for(let[y,b]of Object.entries(m.meta))Kg.has(y)||(h[y]=b);Object.keys(h).length>0&&(g.meta=h)}n[f]=g}let a={},u={},d=new Set;for(let f of e.subgraphs){let m=`${f}::`;for(let[g,h]of Object.entries(e.nodes)){if(!g.startsWith(m)||g.includes(s))continue;let y=h.meta;if(y?._templateName&&y?._templateBind){let b=y._templateName,v=y._templateBind;if(!a[b]){let T={},w=new Set,k=`${f}::`;for(let[I,A]of Object.entries(e.nodes)){if(!I.startsWith(k)||I.includes(s))continue;let P=I.slice(k.length);P.includes("::")||(w.add(P),T[P]={type:A.type,...A.deps.length>0?{deps:A.deps.map(U=>U.startsWith(k)?U.slice(k.length):U)}:{}})}let x=[],S=new Map;for(let I of Object.values(T))for(let A of I.deps??[])if(!w.has(A)&&!S.has(A)){let P=`$${A}`;x.push(P),S.set(A,P)}for(let I of Object.values(T))I.deps&&(I.deps=I.deps.map(A=>S.get(A)??A));let E=new Set;for(let I of Object.values(T))for(let A of I.deps??[])w.has(A)&&E.add(A);let C=[...w].filter(I=>!E.has(I))[0]??[...w].pop();a[b]={params:x,nodes:T,output:C}}delete n[f],u[f]={type:"template",template:b,bind:v},d.add(f);break}}}let c=new Map;for(let f of e.subgraphs){if(d.has(f))continue;let m={},g=`${f}::`;for(let[y,b]of Object.entries(e.nodes)){if(y.includes(s)||!y.startsWith(g))continue;let v=y.slice(g.length);v.includes("::")||(m[v]={type:b.type,...b.deps.length>0?{deps:b.deps.map(T=>T.startsWith(g)?T.slice(g.length):T)}:{}})}let h=JSON.stringify(Object.fromEntries(Object.entries(m).sort(([y],[b])=>y.localeCompare(b)).map(([y,b])=>[y,{type:b.type,deps:b.deps??[]}])));c.has(h)||c.set(h,[]),c.get(h).push({name:f,nodes:m})}for(let[,f]of c){if(f.length<2)continue;let m=`${f[0].name}_template`,g=f[0].nodes,h=new Set(Object.keys(g)),y=[],b=new Map;for(let x of Object.values(g))for(let S of x.deps??[])if(!h.has(S)&&!b.has(S)){let E=`$${S}`;y.push(E),b.set(S,E)}let v=new Set;for(let x of Object.values(g))for(let S of x.deps??[])h.has(S)&&v.add(S);let w=[...h].filter(x=>!v.has(x))[0]??[...h].pop(),k={};for(let[x,S]of Object.entries(g))k[x]={...S,deps:S.deps?.map(E=>b.get(E)??E)};a[m]={params:y,nodes:k,output:w};for(let x of f){delete n[x.name];let S={},E=new Set(Object.keys(x.nodes));for(let L of Object.values(x.nodes))for(let C of L.deps??[])if(!E.has(C)){let I=b.get(C)??`$${C}`;S[I]=C}u[x.name]={type:"template",template:m,bind:S}}}let l={...n,...u},p={name:e.name,nodes:l};return Object.keys(a).length>0&&(p.templates=a),r.length>0&&(p.feedback=r),p}function qg(t,e){let n=[];t.name!==e.name&&n.push({type:"changed",path:"name",detail:`"${t.name}" \u2192 "${e.name}"`});let r=new Set(Object.keys(t.nodes)),s=new Set(Object.keys(e.nodes));for(let b of s)if(!r.has(b)){let v=e.nodes[b];n.push({type:"added",path:`nodes.${b}`,detail:`type: ${v.type}`})}for(let b of r)s.has(b)||n.push({type:"removed",path:`nodes.${b}`});for(let b of r){if(!s.has(b))continue;let v=t.nodes[b],T=e.nodes[b];if(JSON.stringify(v)!==JSON.stringify(T)){let w=[];v.type!==T.type&&w.push(`type: ${v.type} \u2192 ${T.type}`),JSON.stringify(v.deps)!==JSON.stringify(T.deps)&&w.push("deps changed"),v.fn!==T.fn&&w.push(`fn: ${v.fn} \u2192 ${T.fn}`),JSON.stringify(v.config)!==JSON.stringify(T.config)&&w.push("config changed"),n.push({type:"changed",path:`nodes.${b}`,detail:w.join("; ")||"modified"})}}let o=t.templates??{},i=e.templates??{},a=new Set(Object.keys(o)),u=new Set(Object.keys(i));for(let b of u)a.has(b)||n.push({type:"added",path:`templates.${b}`});for(let b of a)u.has(b)||n.push({type:"removed",path:`templates.${b}`});for(let b of a)u.has(b)&&JSON.stringify(o[b])!==JSON.stringify(i[b])&&n.push({type:"changed",path:`templates.${b}`,detail:"template definition changed"});let d=t.feedback??[],c=e.feedback??[],l=new Set(d.map(b=>`${b.from}->${b.to}`)),p=new Set(c.map(b=>`${b.from}->${b.to}`));for(let b of c){let v=`${b.from}->${b.to}`;l.has(v)||n.push({type:"added",path:`feedback.${v}`,detail:`maxIterations: ${b.maxIterations??10}`})}for(let b of d){let v=`${b.from}->${b.to}`;p.has(v)||n.push({type:"removed",path:`feedback.${v}`})}for(let b of d){let v=`${b.from}->${b.to}`,T=c.find(w=>w.from===b.from&&w.to===b.to);T&&JSON.stringify(b)!==JSON.stringify(T)&&n.push({type:"changed",path:`feedback.${v}`,detail:`maxIterations: ${b.maxIterations??10} \u2192 ${T.maxIterations??10}`})}let f=n.filter(b=>b.type==="added").length,m=n.filter(b=>b.type==="removed").length,g=n.filter(b=>b.type==="changed").length,h=[];f&&h.push(`${f} added`),m&&h.push(`${m} removed`),g&&h.push(`${g} changed`);let y=h.length>0?h.join(", "):"no changes";return{entries:n,summary:y}}var Ep=`You are a graph architect for GraphReFly, a reactive graph protocol.
53
53
 
54
54
  Given a natural-language description, produce a JSON GraphSpec with this structure:
55
55
 
@@ -91,32 +91,32 @@ Rules:
91
91
  - Use "templates" when the same subgraph pattern repeats (e.g., per-source resilience).
92
92
  - Use "feedback" for bounded cycles where a derived value writes back to a state node.
93
93
  - meta.description is required for every node.
94
- - Return ONLY valid JSON, no markdown fences or commentary.`;function xp(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}async function qg(t,e,n){let r=kp,o=n?.catalogDescription??(n?.catalog?wp(n.catalog):void 0);o&&(r+=`
94
+ - Return ONLY valid JSON, no markdown fences or commentary.`;function _p(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}async function Wg(t,e,n){let r=Ep,s=n?.catalogDescription??(n?.catalog?Np(n.catalog):void 0);s&&(r+=`
95
95
 
96
96
  Available catalog (use ONLY these names):
97
- ${o}`),n?.systemPromptExtra&&(r+=`
97
+ ${s}`),n?.systemPromptExtra&&(r+=`
98
98
 
99
- ${n.systemPromptExtra}`);let s=[{role:"system",content:r},{role:"user",content:t}],u=(await e.invoke(s,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens})).content.trim();u.startsWith("```")&&(u=xp(u));let c;try{c=JSON.parse(u)}catch{throw new Error(`llmCompose: LLM response is not valid JSON: ${u.slice(0,200)}`)}let d=ir(c);if(!d.valid)throw new Error(`llmCompose: invalid GraphSpec:
100
- ${d.errors.join(`
101
- `)}`);let l=c;if(n?.catalog){let p=n.maxAutoRefine??0;for(let f=0;f<=p;f++){let m=bo(l,n.catalog);if(m.valid)break;if(f===p)throw new Error(`llmCompose: catalog validation failed after ${p} refine attempts:
99
+ ${n.systemPromptExtra}`);let o=[{role:"system",content:r},{role:"user",content:t}],u=(await e.invoke(o,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens})).content.trim();u.startsWith("```")&&(u=_p(u));let d;try{d=JSON.parse(u)}catch{throw new Error(`llmCompose: LLM response is not valid JSON: ${u.slice(0,200)}`)}let c=ir(d);if(!c.valid)throw new Error(`llmCompose: invalid GraphSpec:
100
+ ${c.errors.join(`
101
+ `)}`);let l=d;if(n?.catalog){let p=n.maxAutoRefine??0;for(let f=0;f<=p;f++){let m=fo(l,n.catalog);if(m.valid)break;if(f===p)throw new Error(`llmCompose: catalog validation failed after ${p} refine attempts:
102
102
  ${m.errors.join(`
103
- `)}`);l=await Rp(l,`Fix these catalog errors:
103
+ `)}`);l=await Mp(l,`Fix these catalog errors:
104
104
  ${m.errors.join(`
105
105
  `)}
106
106
 
107
- Use ONLY functions and sources from the catalog.`,e,{...n,catalogDescription:o})}}return l}async function Rp(t,e,n,r){let o=kp;r?.catalogDescription&&(o+=`
107
+ Use ONLY functions and sources from the catalog.`,e,{...n,catalogDescription:s})}}return l}async function Mp(t,e,n,r){let s=Ep;r?.catalogDescription&&(s+=`
108
108
 
109
109
  Available catalog:
110
- ${r.catalogDescription}`),r?.systemPromptExtra&&(o+=`
110
+ ${r.catalogDescription}`),r?.systemPromptExtra&&(s+=`
111
111
 
112
- ${r.systemPromptExtra}`);let s=[{role:"system",content:o},{role:"user",content:`Current GraphSpec:
112
+ ${r.systemPromptExtra}`);let o=[{role:"system",content:s},{role:"user",content:`Current GraphSpec:
113
113
  ${JSON.stringify(t,null,2)}
114
114
 
115
115
  Modification request: ${e}
116
116
 
117
- Return the complete modified GraphSpec as JSON.`}],u=(await n.invoke(s,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens})).content.trim();u.startsWith("```")&&(u=xp(u));let c;try{c=JSON.parse(u)}catch{throw new Error(`llmRefine: LLM response is not valid JSON: ${u.slice(0,200)}`)}let d=ir(c);if(!d.valid)throw new Error(`llmRefine: invalid GraphSpec:
118
- ${d.errors.join(`
119
- `)}`);return c}var Sp=`You are a graph architect for GraphReFly, a reactive graph protocol.
117
+ Return the complete modified GraphSpec as JSON.`}],u=(await n.invoke(o,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens})).content.trim();u.startsWith("```")&&(u=_p(u));let d;try{d=JSON.parse(u)}catch{throw new Error(`llmRefine: LLM response is not valid JSON: ${u.slice(0,200)}`)}let c=ir(d);if(!c.valid)throw new Error(`llmRefine: invalid GraphSpec:
118
+ ${c.errors.join(`
119
+ `)}`);return d}var Op=`You are a graph architect for GraphReFly, a reactive graph protocol.
120
120
 
121
121
  Given a natural-language description, produce a JSON graph specification with this structure:
122
122
 
@@ -149,9 +149,9 @@ Rules:
149
149
  - "operator" nodes are parameterized transformations with deps.
150
150
  - Use "deps" inside each node to declare dependencies \u2014 no separate "edges" array.
151
151
  - meta.description is required for every node.
152
- - Return ONLY valid JSON, no markdown fences or commentary.`;async function Np(t,e,n){let o=[{role:"system",content:n?.systemPromptExtra?`${Sp}
152
+ - Return ONLY valid JSON, no markdown fences or commentary.`;async function Cp(t,e,n){let s=[{role:"system",content:n?.systemPromptExtra?`${Op}
153
153
 
154
- ${n.systemPromptExtra}`:Sp},{role:"user",content:t}],s=e.invoke(o,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens,signal:n?.signal}),a=(await so(s)).content.trim();a.startsWith("```")&&(a=or(a));let u;try{u=JSON.parse(a)}catch{throw new Error(`graphFromSpec: LLM response is not valid JSON: ${a.slice(0,200)}`)}return vo(u,{catalog:n?.catalog})}function Ug(t,e,n){let r=X(t);return Se(r,o=>!o||typeof o!="string"||o.trim().length===0?E(null):H(s=>{let i=new AbortController,a=!1;return Np(o,e,{...n,signal:i.signal}).then(u=>{if(a){u.destroy();return}s.emit(u),s.down([[C]])}).catch(u=>{a||s.down([[O,u]])}),()=>{a=!0,i.abort()}},{name:"graphFromSpec::call"}))}function zg(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 Jg(t,e){let n=t.describe({actor:e,detail:"full"}),r=[],o=[],s=[];for(let[i,a]of Object.entries(n.nodes)){if(a.type!=="state"||i.includes("::__meta__::")||a.status==="completed"||a.status==="errored")continue;let u=a.meta??{},c=u.access;if(c==="human"||c==="system")continue;let d=u.description??`Set the value of ${i}`,l=zg(u),p={type:"object",required:["value"],properties:{value:l},additionalProperties:!1},f=i.replace(/::/g,"__");r.push({type:"function",function:{name:f,description:d,parameters:p}}),o.push({name:i,description:d,inputSchema:p});let m=t,g=e,h=a.v;s.push({name:i,description:d,parameters:p,handler(y){return m.set(i,y.value,g?{actor:g}:void 0),y.value},...h!=null?{version:{id:h.id,version:h.version}}:{}})}return{openai:r,mcp:o,definitions:s}}ae();ee();Re();var Yg=`You are a reactive graph optimizer for GraphReFly.
154
+ ${n.systemPromptExtra}`:Op},{role:"user",content:t}],o=e.invoke(s,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens,signal:n?.signal}),a=(await so(o)).content.trim();a.startsWith("```")&&(a=or(a));let u;try{u=JSON.parse(a)}catch{throw new Error(`graphFromSpec: LLM response is not valid JSON: ${a.slice(0,200)}`)}return mo(u,{catalog:n?.catalog})}function Ug(t,e,n){let r=W(t);return be(r,s=>!s||typeof s!="string"||s.trim().length===0?N(null):$(o=>{let i=new AbortController,a=!1;return Cp(s,e,{...n,signal:i.signal}).then(u=>{if(a){u.destroy();return}o.emit(u),o.down([[O]])}).catch(u=>{a||o.down([[M,u]])}),()=>{a=!0,i.abort()}},{name:"graphFromSpec::call"}))}function zg(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 Jg(t,e){let n=t.describe({actor:e,detail:"full"}),r=[],s=[],o=[];for(let[i,a]of Object.entries(n.nodes)){if(a.type!=="state"||i.includes("::__meta__::")||a.status==="completed"||a.status==="errored")continue;let u=a.meta??{},d=u.access;if(d==="human"||d==="system")continue;let c=u.description??`Set the value of ${i}`,l=zg(u),p={type:"object",required:["value"],properties:{value:l},additionalProperties:!1},f=i.replace(/::/g,"__");r.push({type:"function",function:{name:f,description:c,parameters:p}}),s.push({name:i,description:c,inputSchema:p});let m=t,g=e,h=a.v;o.push({name:i,description:c,parameters:p,handler(y){return m.set(i,y.value,g?{actor:g}:void 0),y.value},...h!=null?{version:{id:h.id,version:h.version}}:{}})}return{openai:r,mcp:s,definitions:o}}se();Q();Te();var Yg=`You are a reactive graph optimizer for GraphReFly.
155
155
 
156
156
  Given a graph's current structure (from describe()) and a problem statement, suggest topology and parameter changes to solve the problem.
157
157
 
@@ -172,8 +172,8 @@ Return ONLY valid JSON with this structure:
172
172
  Rules:
173
173
  - Only suggest operations that reference existing nodes (for remove/disconnect/set_value/update_meta) or new nodes you define (for add_node).
174
174
  - Keep changes minimal \u2014 prefer the smallest set of operations that solves the problem.
175
- - Return ONLY valid JSON, no markdown fences or commentary.`;async function Ep(t,e,n,r){let{expand:o,...s}=t.describe({actor:r?.actor,detail:"standard"}),i=[{role:"system",content:Yg},{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}),c=(await so(a)).content.trim();c.startsWith("```")&&(c=c.replace(/^```(?:json)?\s*/,"").replace(/\s*```$/,""));let d;try{d=JSON.parse(c)}catch{throw new Error(`suggestStrategy: LLM response is not valid JSON: ${c.slice(0,200)}`)}let l=d;if(typeof l.summary!="string")throw new Error("suggestStrategy: missing 'summary' in response");if(typeof l.reasoning!="string")throw new Error("suggestStrategy: missing 'reasoning' in response");if(!Array.isArray(l.operations))throw new Error("suggestStrategy: missing 'operations' array in response");return{summary:l.summary,reasoning:l.reasoning,operations:l.operations}}function Qg(t,e,n,r){let o=X(e),s=At(o,t);return Se(s,i=>{if(i==null)return E(null);let[a,u]=i;return!u||!a||typeof a!="string"||a.trim().length===0?E(null):u.destroyed?E(null):H(c=>{let d=new AbortController,l=!1;return Ep(u,a,n,{...r,signal:d.signal}).then(p=>{l||(c.emit(p),c.down([[C]]))}).catch(p=>{l||c.down([[O,p]])}),()=>{l=!0,d.abort()}},{name:"suggestStrategy::call"})})}var _p=new Set(["state","derived","producer","operator","effect"]);function Xg(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"||!_p.has(i.type))&&e.push(`Node "${o}": invalid type "${String(i.type)}" (expected: ${[..._p].join(", ")})`),Array.isArray(i.deps))for(let a of i.deps)typeof a=="string"&&!r.has(a)&&e.push(`Node "${o}": dep "${a}" does not reference an existing node`)}if(!Array.isArray(n.edges))n.edges!==void 0&&e.push("'edges' must be an array");else{let o=new Set;for(let s=0;s<n.edges.length;s++){let i=n.edges[s];if(i==null||typeof i!="object"){e.push(`Edge [${s}]: must be an object`);continue}let a=i;(typeof a.from!="string"||!r.has(a.from))&&e.push(`Edge [${s}]: 'from' "${String(a.from)}" does not reference an existing node`),(typeof a.to!="string"||!r.has(a.to))&&e.push(`Edge [${s}]: 'to' "${String(a.to)}" does not reference an existing node`);let u=`${a.from}->${a.to}`;o.has(u)&&e.push(`Edge [${s}]: duplicate edge ${u}`),o.add(u)}}return{valid:e.length===0,errors:e}}var ai={};Ne(ai,{AuditTrailGraph:()=>si,PolicyEnforcerGraph:()=>ii,auditTrail:()=>ey,complianceSnapshot:()=>ty,policyEnforcer:()=>au,reactiveExplainPath:()=>uu});_e();rn();ae();Le();ee();Co();function Op(t,e){return ze("audit",t,e)}var Zg=new Set(["data","error","complete","teardown"]),si=class extends Y{entries;count;_log;_target;constructor(e,n){super(n.name??`${e.name}_audit`,n.graph),this._target=e,this._log=Ue([],{name:"entries",...n.maxSize!=null?{maxSize:n.maxSize}:{}}),this.entries=this._log.entries,this.add(this.entries,{name:"entries"}),this.count=_([this.entries],([u])=>u.length,{name:"count",describeKind:"derived",meta:Op("count")}),this.add(this.count,{name:"count"}),this.addDisposer(se(this.count));let r=n.includeTypes!=null?new Set(n.includeTypes):Zg,o=n.filter,s=0,i=e.observe({timeline:!0,structured:!0}),a=i.onEvent(u=>{if(u.type==="derived")return;let c=u.type;if(!r.has(c))return;let d=u.path??"",l={seq:s++,timestamp_ns:u.timestamp_ns??j(),wall_clock_ns:Te(),path:d,type:c},f=(d?iu(e,d):void 0)?.lastMutation;f!=null&&(l.actor=f.actor),c==="data"&&(l.value=u.data),c==="error"&&(l.error=u.data);let m=d?ry(e,d):void 0;m!=null&&(l.annotation=m),!(o!=null&&!o(l))&&this._log.append(l)});this.addDisposer(()=>{a(),i.dispose()}),this.addDisposer(()=>this._log.disposeAllViews())}all(){return this.entries.cache??[]}byNode(e){return this.all().filter(n=>n.path===e)}byActor(e){return this.all().filter(n=>n.actor?.id===e)}byActorType(e){return this.all().filter(n=>n.actor?.type===e)}byTimeRange(e,n){return this.all().filter(r=>!(r.timestamp_ns<e||n!=null&&r.timestamp_ns>=n))}get target(){return this._target}};function ey(t,e={}){return new si(t,e)}var ii=class extends Y{policies;violations;violationCount;_target;_mode;_currentGuard;constructor(e,n,r){super(r.name??`${e.name}_policy`,r.graph),this._target=e,this._mode=r.mode??"audit";let o=ny(n)?n:E(n,{name:"policies"});this.policies=o,this.add(this.policies,{name:"policies"}),this.violations=new Rn("violations",{retainedLimit:r.violationsLimit??1e3}),this.mount("violations",this.violations),this.violationCount=_([this.violations.events],([c])=>c.length,{name:"violationCount",describeKind:"derived",meta:Op("policy_violation_count")}),this.add(this.violationCount,{name:"violationCount"}),this.addDisposer(se(this.violationCount));let i=o.cache??[];this._currentGuard=Sr(i);let a=o.subscribe(c=>{for(let d of c)d[0]===S&&(i=d[1]??[],this._currentGuard=Sr(i))});this.addDisposer(a);let u=r.paths!=null?[...r.paths]:Mp(e);if(this._mode==="enforce"){let c=new Map,d=l=>{if(c.has(l))return;let p=iu(e,l);if(!(p instanceof Ie))return;let f=(m,g)=>{let h=this._currentGuard(m,g);return h||this._publishViolation(m,g,l,"blocked"),h};c.set(l,p._pushGuard(f))};for(let l of u)d(l);if(r.paths==null){let l=Mt(e,(p,f,m)=>{if(p.kind==="added")if(p.nodeKind==="node")d(`${m}${p.name}`);else{let g=f._mounts.get(p.name);if(!(g instanceof Y))return;let h=`${m}${p.name}::`,y=Mp(g);for(let b of y)d(b===""?`${m}${p.name}`:`${h}${b}`)}else if(p.kind==="removed")if(p.nodeKind==="node"){let g=`${m}${p.name}`,h=c.get(g);h!=null&&(h(),c.delete(g))}else{let g=`${m}${p.name}`,h=`${g}::`;for(let[y,b]of c)(y===g||y.startsWith(h))&&(b(),c.delete(y))}});this.addDisposer(l)}else{let l=e.topology.subscribe(p=>{for(let f of p){if(f[0]!==S)continue;let m=f[1];if(m.kind!=="removed"||m.nodeKind!=="node")continue;let g=c.get(m.name);g!=null&&(g(),c.delete(m.name))}});this.addDisposer(l)}this.addDisposer(()=>{for(let l of c.values())l();c.clear()})}else{let c=e.observe({timeline:!0,structured:!0}),d=c.onEvent(l=>{if(l.type!=="data"&&l.type!=="error")return;let p=l.path??"";if(!p||r.paths!=null&&!r.paths.includes(p))return;let f=l.actor??iu(e,p)?.lastMutation?.actor;if(f==null)return;let m="write";this._currentGuard(f,m)||this._publishViolation(f,m,p,"observed")});this.addDisposer(()=>{d(),c.dispose()})}}_publishViolation(e,n,r,o){this.violations.publish({timestamp_ns:j(),wall_clock_ns:Te(),path:r,actor:e,action:n,mode:this._mode,result:o})}all(){return this.violations.retained()}get mode(){return this._mode}get target(){return this._target}};function au(t,e,n={}){return new ii(t,e,n)}function uu(t,e,n,r){return t.explain(e,n,{reactive:!0,...r})}function ty(t,e={}){let n={format_version:1,timestamp_ns:j(),wall_clock_ns:Te(),graph:t.snapshot()};if(e.actor!=null&&(n.actor=e.actor),e.audit!=null){let o=[...e.audit.all()];n.audit={count:o.length,entries:o}}if(e.policies!=null){let o=e.policies.policies.cache??[];n.policies={mode:e.policies.mode,rules:o,violations:[...e.policies.all()]}}let r=oy(n);return{...n,fingerprint:r}}function ny(t){return typeof t=="object"&&t!==null&&"subscribe"in t}function iu(t,e){try{return t.node(e)}catch{return}}function ry(t,e){try{return t.annotation(e)}catch{return}}function Mp(t){let e=t.describe({detail:"minimal"});return Object.keys(e.nodes)}function oy(t){return Ft(JSON.stringify(sy(t)))}function sy(t){let e=new Set,n=r=>{if(r===void 0)return{__undefined:!0};if(r===null)return null;let o=typeof r;if(o==="bigint")return{__bigint:r.toString()};if(o!=="object")return r;let s=r;if(e.has(s))return{__circular:!0};e.add(s);try{if(Array.isArray(s))return s.map(n);if(s instanceof Date)return{__date:s.toISOString()};if(s instanceof RegExp)return{__regexp:{source:s.source,flags:s.flags}};if(s instanceof Map)return{__map:[...s.entries()].map(([u,c])=>[n(u),n(c)])};if(s instanceof Set)return{__set:[...s].map(n)};if(ArrayBuffer.isView(s)){let a=s,u=new Array(a.length);for(let c=0;c<a.length;c++)u[c]=a[c]??0;return{__typed_array:{ctor:s.constructor.name,data:u}}}let i={};for(let a of Object.keys(s).sort())i[a]=n(s[a]);return i}finally{e.delete(s)}};return n(t)}var ci={};Ne(ci,{demoShell:()=>fy});Ae();ee();_e();Le();ee();function iy(t){for(let e of t){let n=e.codePointAt(0);if(n>=19968&&n<=40959||n>=13312&&n<=19903||n>=12288&&n<=12351||n>=12352&&n<=12447||n>=12448&&n<=12543||n>=44032&&n<=55215||n>=65280&&n<=65519)return!0}return!1}var Cp=new Set(["\uFF0C","\uFF0E","\uFF01","\uFF1A","\uFF1B","\uFF1F","\u3001","\u3002","\u30FB","\uFF09","\u3015","\u3009","\u300B","\u300D","\u300F","\u3011"]),ay=new Set([".",",","!","?",":",";",")","]","}","%",'"',"\u201D","\u2019","\xBB","\u203A","\u2026"]);function uy(t){return t.replace(/[\t\n\r\f ]+/g," ").replace(/^ | $/g,"")}function cy(t){let e=new Intl.Segmenter(void 0,{granularity:"word"}),n=[];for(let r of e.segment(t)){let o=r.segment,s=r.isWordLike??!1,i=[],a=[],u=[],c="",d=null;for(let l of o){let p;l===" "?p="space":l==="\u200B"?p="zero-width-break":l==="\xAD"?p="soft-hyphen":l===`
176
- `?p="hard-break":p="text",d!==null&&p===d?c+=l:(d!==null&&(i.push(c),a.push(d==="text"&&s),u.push(d)),c=l,d=p)}d!==null&&(i.push(c),a.push(d==="text"&&s),u.push(d)),n.push({texts:i,isWordLike:a,kinds:u})}return n}function Gt(t,e,n,r,o){let s=uy(t);if(s.length===0)return[];let i=cy(s),a=new Intl.Segmenter(void 0,{granularity:"grapheme"}),u=[],c=[],d=[];for(let y of i)for(let b=0;b<y.texts.length;b++)u.push(y.texts[b]),c.push(y.kinds[b]),d.push(y.isWordLike[b]);let l=[],p=[],f=[];for(let y=0;y<u.length;y++){let b=u[y],v=c[y],T=d[y];if(v==="text"&&!T&&l.length>0&&p[p.length-1]==="text"&&b.length===1&&(ay.has(b)||Cp.has(b))){l[l.length-1]+=b;continue}if(b==="-"&&l.length>0&&p[p.length-1]==="text"&&f[f.length-1]){l[l.length-1]+=b;continue}l.push(b),p.push(v),f.push(T)}let m=r.get(e);m||(m=new Map,r.set(e,m));function g(y){let b=m.get(y);if(b===void 0){o&&(o.misses+=1);let v=n.measureSegment(y,e).width;b=Number.isFinite(v)&&v>=0?v:0,m.set(y,b)}else o&&(o.hits+=1);return b}let h=[];for(let y=0;y<l.length;y++){let b=l[y],v=p[y];if(v!=="text"){h.push({text:b,width:v==="space"?g(" ")*b.length:0,kind:v,graphemeWidths:null});continue}if(iy(b)){let k="";for(let x of a.segment(b)){let R=x.segment;if(k.length>0&&Cp.has(R)){k+=R;continue}if(k.length>0){let N=g(k);h.push({text:k,width:N,kind:"text",graphemeWidths:null})}k=R}if(k.length>0){let x=g(k);h.push({text:k,width:x,kind:"text",graphemeWidths:null})}continue}let T=g(b),w=null;if(f[y]&&b.length>1){let k=[];for(let x of a.segment(b))k.push(g(x.segment));k.length>1&&(w=k)}h.push({text:b,width:T,kind:"text",graphemeWidths:w})}return h}function Sn(t,e,n,r,o){if(t.length===0)return{lines:[],lineCount:0};let s=[],i=0,a=!1,u=0,c=0,d=0,l=0,p=-1,f=0,m=o.get(r);m||(m=new Map,o.set(r,m));let g=m.get("-");g===void 0&&(g=n.measureSegment("-",r).width,m.set("-",g));function h(w=d,k=l,x=i){let R="";for(let N=u;N<w;N++){let A=t[N];if(!(A.kind==="soft-hyphen"||A.kind==="hard-break"))if(N===u&&c>0&&A.graphemeWidths){let I=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(A.text)].map(L=>L.segment);R+=I.slice(c).join("")}else R+=A.text}if(k>0&&w<t.length){let N=t[w],M=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(N.text)].map(L=>L.segment),I=u===w?c:0;R+=M.slice(I,k).join("")}w>0&&t[w-1]?.kind==="soft-hyphen"&&!(u===w&&c>0)&&(R+="-"),s.push({text:R,width:x,startSegment:u,startGrapheme:c,endSegment:w,endGrapheme:k}),i=0,a=!1,p=-1,f=0}function y(w){return w==="space"||w==="zero-width-break"||w==="soft-hyphen"}function b(w,k,x){a=!0,u=w,c=k,d=w+1,l=0,i=x}function v(w,k,x){a=!0,u=w,c=k,d=w,l=k+1,i=x}for(let w=0;w<t.length;w++){let k=t[w];if(k.kind==="hard-break"){a?h():s.push({text:"",width:0,startSegment:w,startGrapheme:0,endSegment:w,endGrapheme:0}),u=w+1,c=0;continue}let x=k.width;if(!a){x>e&&k.graphemeWidths?T(w,0,k.graphemeWidths):b(w,0,x),y(k.kind)&&(p=w+1,f=k.kind==="space"?i-x:i);continue}let R=i+x;if(R>e+.005){if(y(k.kind)){i+=x,d=w+1,l=0,h(w+1,0,k.kind==="space"?i-x:i);continue}if(p>=0){h(p,0,f),w--;continue}if(x>e&&k.graphemeWidths){h(),T(w,0,k.graphemeWidths);continue}h(),w--;continue}i=R,d=w+1,l=0,y(k.kind)&&(p=w+1,f=k.kind==="space"?i-x:i)}return a&&h(),{lines:s,lineCount:s.length};function T(w,k,x){for(let R=k;R<x.length;R++){let N=x[R];if(!a){v(w,R,N);continue}i+N>e+.005?(h(),v(w,R,N)):(i+=N,d=w,l=R+1)}a&&d===w&&l===x.length&&(d=w+1,l=0)}}function cu(t){return t==="space"||t==="zero-width-break"||t==="soft-hyphen"}var du=null;function dy(){return du===null&&(du=new Intl.Segmenter(void 0,{granularity:"grapheme"})),du}function Ap(t,e,n){if(e===0&&n<0)return t.text;let r=[...dy().segment(t.text)].map(s=>s.segment),o=n<0?r.length:n;return r.slice(e,o).join("")}function Qt(t,e,n,r,o,s){let i="";for(let a=e;a<r;a++){let u=t[a];u.kind==="soft-hyphen"||u.kind==="hard-break"||(a===e&&n>0?i+=Ap(u,n,-1):i+=u.text)}if(o>0&&r<t.length){let a=t[r];i+=Ap(a,e===r?n:0,o)}return s&&(i+="-"),i}function ly(t){if(!t?.adapter||!t.font)return 0;let e=t.cache;if(e){let n=e.get(t.font);n||(n=new Map,e.set(t.font,n));let r=n.get("-");return r===void 0&&(r=t.adapter.measureSegment("-",t.font).width,n.set("-",r)),r}return t.adapter.measureSegment("-",t.font).width}function lu(t,e,n,r){let o=e.segmentIndex,s=e.graphemeIndex;if(o>=t.length)return null;if(s===0){for(;o<t.length;){let w=t[o];if(w.kind==="hard-break")return{text:"",width:0,start:{segmentIndex:e.segmentIndex,graphemeIndex:0},end:{segmentIndex:o+1,graphemeIndex:0}};if(w.kind==="space"||w.kind==="zero-width-break"||w.kind==="soft-hyphen"){o+=1;continue}break}if(o>=t.length)return null}let i=ly(r),a=o,u=o===e.segmentIndex?s:0,c=0,d=a,l=0,p=!1,f=-1,m=0,g=0,h=!1,y=(w,k,x,R)=>{f=w,m=k,g=x,h=R==="soft-hyphen"},b=(w,k,x)=>{for(let R=k;R<x.length;R++){let N=x[R];if(!p){c=N,d=w,l=R+1,p=!0;continue}if(c+N>n+.005)return!0;c+=N,d=w,l=R+1}return d===w&&l===x.length&&(d=w+1,l=0),!1};if(u>0&&a<t.length){let w=t[a];if(w.graphemeWidths){if(b(a,u,w.graphemeWidths))return{text:Qt(t,a,u,d,l,!1),width:c,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}};o=d}}for(;o<t.length;){let w=t[o];if(w.kind==="hard-break"){if(p){let R=d>0&&t[d-1]?.kind==="soft-hyphen";return{text:Qt(t,a,u,d,l,R),width:c+(R?i:0),start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}}}return{text:"",width:0,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:o+1,graphemeIndex:0}}}let k=w.width;if(!p){if(k>n&&w.graphemeWidths){if(b(o,0,w.graphemeWidths))return{text:Qt(t,a,u,d,l,!1),width:c,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}};o=d;continue}c=k,d=o+1,l=0,p=!0,cu(w.kind)&&y(o+1,0,w.kind==="space"?c-k:c,w.kind),o+=1;continue}let x=c+k;if(x>n+.005){if(cu(w.kind)){d=o+1,l=0;let N=w.kind==="soft-hyphen",A=w.kind==="space"?c:c+(N?i:0);return{text:Qt(t,a,u,d,l,N),width:A,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}}}return f>=0?{text:Qt(t,a,u,f,m,h),width:g+(h?i:0),start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:f,graphemeIndex:m}}:k>n&&w.graphemeWidths?{text:Qt(t,a,u,d,l,!1),width:c,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}}:{text:Qt(t,a,u,d,l,!1),width:c,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}}}c=x,d=o+1,l=0,cu(w.kind)&&y(o+1,0,w.kind==="space"?c-k:c,w.kind),o+=1}if(!p)return null;let v=d>0&&t[d-1]?.kind==="soft-hyphen";return{text:Qt(t,a,u,d,l,v),width:c+(v?i:0),start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:d,graphemeIndex:l}}}function pu(t,e,n=0){let r=[t];for(let o=0;o<e.length;o++){let s=e[o],i=[];for(let a=0;a<r.length;a++){let u=r[a];if(s.right<=u.left||s.left>=u.right){i.push(u);continue}s.left>u.left&&i.push({left:u.left,right:s.left}),s.right<u.right&&i.push({left:s.right,right:u.right})}r=i}return n>0?r.filter(o=>o.right-o.left>=n):r}function ui(t,e,n){let r=[],o=new Intl.Segmenter(void 0,{granularity:"grapheme"});for(let s=0;s<t.lines.length;s++){let i=t.lines[s],a=s*n,u=0;for(let c=i.startSegment;c<e.length;c++){let d=e[c];if(d.kind==="soft-hyphen"||d.kind==="hard-break"){if(c>=i.endSegment&&i.endGrapheme===0)break;continue}let l=[...o.segment(d.text)].map(m=>m.segment);if(l.length===0)continue;let p=c===i.startSegment?i.startGrapheme:0,f;if(c<i.endSegment)f=l.length;else if(c===i.endSegment&&i.endGrapheme>0)f=i.endGrapheme;else break;for(let m=p;m<f;m++){let g=d.graphemeWidths?d.graphemeWidths[m]:d.width/l.length;r.push({x:u,y:a,width:g,height:n,line:s}),u+=g}}}return r}function py(t){let{adapter:e,name:n="reactive-layout"}=t,r=new Y(n),o=new Map,s=E(t.text??"",{name:"text"}),i=E(t.font??"16px sans-serif",{name:"font"}),a=E(t.lineHeight??20,{name:"line-height"}),u=E(Math.max(0,t.maxWidth??800),{name:"max-width"});function c(m,g){if(m===null||g===null)return m===g;if(m.length!==g.length)return!1;for(let h=0;h<m.length;h++)if(m[h]!==g[h])return!1;return!0}let d=U([s,i],(m,g,h)=>{let y=m[0],b=y!=null&&y.length>0?y.at(-1):h.prevData[0],v=m[1],T=v!=null&&v.length>0?v.at(-1):h.prevData[1],w=j(),k={hits:0,misses:0},x=Gt(b,T,e,o,k),R=j()-w,N=k.hits+k.misses,A=N===0?1:k.hits/N,M=d.meta;M&&(ft(M["cache-hit-rate"],A),ft(M["segment-count"],x.length),ft(M["layout-time-ns"],R)),g.emit(x);let I=()=>{o.clear(),e.clearCache?.()};return{deactivate:I,invalidate:I}},{name:"segments",describeKind:"derived",meta:{"cache-hit-rate":0,"segment-count":0,"layout-time-ns":0},equals:(m,g)=>{let h=m,y=g;if(h==null||y==null)return h===y;if(h.length!==y.length)return!1;for(let b=0;b<h.length;b++){let v=h[b],T=y[b];if(v.text!==T.text||v.width!==T.width||v.kind!==T.kind||!c(v.graphemeWidths??null,T.graphemeWidths??null))return!1}return!0}}),l=_([d,u,i],([m,g,h])=>Sn(m,g,e,h,o),{name:"line-breaks",equals:(m,g)=>{let h=m,y=g;if(h==null||y==null)return h===y;if(h.lineCount!==y.lineCount)return!1;for(let b=0;b<h.lines.length;b++){let v=h.lines[b],T=y.lines[b];if(v.text!==T.text||v.width!==T.width||v.startSegment!==T.startSegment||v.startGrapheme!==T.startGrapheme||v.endSegment!==T.endSegment||v.endGrapheme!==T.endGrapheme)return!1}return!0}}),p=_([l,a],([m,g])=>m.lineCount*g,{name:"height"}),f=_([l,d,a],([m,g,h])=>ui(m,g,h),{name:"char-positions",equals:(m,g)=>{let h=m,y=g;if(h==null||y==null)return h===y;if(h.length!==y.length)return!1;for(let b=0;b<h.length;b++)if(h[b].x!==y[b].x||h[b].y!==y[b].y||h[b].width!==y[b].width)return!1;return!0}});return r.add(s,{name:"text"}),r.add(i,{name:"font"}),r.add(a,{name:"line-height"}),r.add(u,{name:"max-width"}),r.add(d,{name:"segments"}),r.add(l,{name:"line-breaks"}),r.add(p,{name:"height"}),r.add(f,{name:"char-positions"}),{graph:r,setText:m=>r.set("text",m),setFont:m=>r.set("font",m),setLineHeight:m=>r.set("line-height",m),setMaxWidth:m=>r.set("max-width",Math.max(0,m)),segments:d,lineBreaks:l,height:p,charPositions:f}}function To(t){return Math.max(0,Math.min(1,t))}function fy(t){let e=To(t?.mainRatio??.65),n=To(t?.sideSplit??.5),r=Math.max(0,t?.viewportWidth??1280),o=t?.nodeRegistry??new Map,s=t?.adapter??null,i=t?.layoutFont??"14px monospace",a=t?.onHighlight,u=new Y("demo-shell"),c=E(e,{name:"pane/main-ratio"}),d=E(n,{name:"pane/side-split"}),l=E(null,{name:"pane/fullscreen"}),p=E(r,{name:"viewport/width"});u.add(c,{name:"pane/main-ratio"}),u.add(d,{name:"pane/side-split"}),u.add(l,{name:"pane/fullscreen"}),u.add(p,{name:"viewport/width"});let f=_([c,p,l],([D,z,W])=>{let ie=D,B=z,$=W;return $==="main"?B:$==="graph"||$==="code"?0:Math.round(B*ie)},{name:"pane/main-width"}),m=_([f,p,l],([D,z,W])=>{let ie=W,B=z;return ie==="main"?0:ie==="graph"||ie==="code"?B:B-D},{name:"pane/side-width"}),g=_([d,l],([D,z])=>{let W=z;return W==="graph"?1:W==="code"||W==="main"?0:To(D)},{name:"pane/graph-height-ratio"}),h=_([g,l],([D,z])=>{let W=z;return W==="code"?1:W==="graph"||W==="main"?0:1-D},{name:"pane/code-height-ratio"});u.add(f,{name:"pane/main-width"}),u.add(m,{name:"pane/side-width"}),u.add(g,{name:"pane/graph-height-ratio"}),u.add(h,{name:"pane/code-height-ratio"});let y=E(null,{name:"demo/graph-ref"}),b=E(0,{name:"demo/graph-tick"});u.add(y,{name:"demo/graph-ref"}),u.add(b,{name:"demo/graph-tick"});let v=_([y,b],([D,z])=>{let W=D;return W?W.describe({format:"mermaid"}):""},{name:"graph/mermaid"}),T=_([y,b],([D,z])=>{let W=D;if(!W)return null;let{expand:ie,...B}=W.describe({detail:"standard"});return B},{name:"graph/describe"});u.add(v,{name:"graph/mermaid"}),u.add(T,{name:"graph/describe"});let w=E(null,{name:"hover/target"});u.add(w,{name:"hover/target"});let k=_([w],([D])=>{let z=D;if(!z)return null;let W=o.get(z.id);return W?W.codeLine:null},{name:"highlight/code-scroll"}),x=_([w],([D])=>{let z=D;if(!z)return null;let W=o.get(z.id);return W?W.visualSelector:null},{name:"highlight/visual"}),R=_([w],([D])=>{let z=D;return z?z.id:null},{name:"highlight/graph"});if(u.add(k,{name:"highlight/code-scroll"}),u.add(x,{name:"highlight/visual"}),u.add(R,{name:"highlight/graph"}),a?.codeScroll){let D=a.codeScroll,z=de([k],([W])=>{D(W)});u.add(z,{name:"highlight/apply-code-scroll"})}if(a?.visual){let D=a.visual,z=de([x],([W])=>{D(W)});u.add(z,{name:"highlight/apply-visual"})}if(a?.graph){let D=a.graph,z=de([R],([W])=>{D(W)});u.add(z,{name:"highlight/apply-graph"})}let N=E(null,{name:"inspect/selected-node"});u.add(N,{name:"inspect/selected-node"});let A=_t("standard"),M=_([N,y,b],([D,z,W])=>{let ie=z,B=D;if(!ie||!B)return null;try{let $=ie.resolve(B),G=Ir($,A);return{path:B,...G,value:$.cache}}catch{return null}},{name:"inspect/node-detail"}),I=_([y,b],([D,z])=>{let W=D;return W?W.trace():[]},{name:"inspect/trace-log"});u.add(M,{name:"inspect/node-detail"}),u.add(I,{name:"inspect/trace-log"});let L=E(!1,{name:"meta/debug"});u.add(L,{name:"meta/debug"});let P=_([L,b],([D,z])=>D?u.describe({format:"mermaid"}):"",{name:"meta/shell-mermaid"});u.add(P,{name:"meta/shell-mermaid"});let J=E("",{name:"layout/code-text"});if(u.add(J,{name:"layout/code-text"}),s){let D=new Map,z=_([T],([B])=>{let $=B;if(!$)return new Map;let G=new Map;for(let[q]of Object.entries($.nodes)){let ce=Gt(q,i,s,D),he=Sn(ce,1/0,s,i,D),xe=he.lines.reduce((ye,re)=>Math.max(ye,re.width),0),oe=he.lineCount*20;G.set(q,{width:xe,height:oe})}return G},{name:"layout/graph-labels",equals:(B,$)=>{if(B===$)return!0;let G=B,q=$;if(G.size!==q.size)return!1;for(let[ce,he]of G){let xe=q.get(ce);if(!xe||xe.width!==he.width||xe.height!==he.height)return!1}return!0}}),W=_([J,m],([B,$])=>{let G=B;if(!G)return{lineCount:0,lines:[]};let q=Gt(G,i,s,D),ce=$-40;return Sn(q,Math.max(100,ce),s,i,D)},{name:"layout/code-lines"}),ie=_([z],([B])=>{let $=B;if($.size===0)return 200;let G=0;for(let{width:q}of $.values())q>G&&(G=q);return Math.max(200,Math.round(G+80))},{name:"layout/side-width-hint"});u.add(z,{name:"layout/graph-labels"}),u.add(W,{name:"layout/code-lines"}),u.add(ie,{name:"layout/side-width-hint"})}let Q=0;return{graph:u,setMainRatio(D){u.set("pane/main-ratio",To(D))},setSideSplit(D){u.set("pane/side-split",To(D))},setFullscreen(D){u.set("pane/fullscreen",D)},setViewportWidth(D){u.set("viewport/width",Math.max(0,D))},setHoverTarget(D){u.set("hover/target",D)},setDemoGraph(D){u.set("demo/graph-ref",D)},bumpGraphTick(){u.set("demo/graph-tick",++Q)},selectNode(D){u.set("inspect/selected-node",D)},setMetaDebug(D){u.set("meta/debug",D)},setCodeText(D){u.set("layout/code-text",D)},batch(D){Z(D)},destroy(){u.destroy()}}}var di={};Ne(di,{contentModerationGraph:()=>gy,dataQualityGraph:()=>yy,issueTrackerGraph:()=>hy,observabilityGraph:()=>my});Ae();ee();function Pe(t,e){return ze("domain_template",t,e)}function my(t,e){let n=new Y(t,e);n.add(e.source,{name:"source"});let r=[{name:"errors",classify:T=>fu(T,"error")},{name:"traces",classify:T=>fu(T,"trace")},{name:"metrics",classify:T=>fu(T,"metric")}],o=e.branches??r,s=o.map(T=>({name:T.name,classify:T.classify})),i=to("stratify",e.source,s);n.mount("stratify",i);let a=o.map(T=>{try{let w=n.resolve(`stratify::branch/${T.name}`);return _([w],([k])=>k,{initial:null})}catch{return E(null)}}),u=e.correlate??(T=>T),c=_(a,T=>u(T),{meta:Pe("observability",{stage:"correlate"})});n.add(c,{name:"correlate"});let d=e.sloCheck??(()=>({pass:!0})),l=_([c],T=>T[0],{meta:Pe("observability",{stage:"slo_value"})}),p=_([l],T=>d(T[0]),{meta:Pe("observability",{stage:"slo_verified"})});n.add(l,{name:"slo_value"}),n.add(p,{name:"slo_verified"});let f=e.weights??o.map(()=>1),m=a.map(T=>_([T],w=>w[0]!=null?1:0)),g=f.map(T=>E(T));for(let T=0;T<m.length;T++)n.add(m[T],{name:`__signal_${T}`}),n.add(g[T],{name:`__weight_${T}`});let h=go(m,g);n.add(h,{name:"alerts"});let y=_([h,p],T=>({scored:T[0],slo:T[1]}),{meta:Pe("observability",{stage:"output"})});n.add(y,{name:"output"});let b=E(null,{meta:Pe("observability",{stage:"feedback_reentry"})});n.add(b,{name:"feedback_reentry"});let v=_([p],T=>{let w=T[0];return w&&w.pass===!1?w:null},{meta:Pe("observability",{stage:"feedback_condition"})});return n.add(v,{name:"feedback_condition"}),Yt(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??5}),n}function hy(t,e){let n=new Y(t,e);n.add(e.source,{name:"source"});let r=0,o=T=>({id:`issue-${++r}`,title:String(T),severity:1,source:"unknown",raw:T}),s=e.extract??o,i=_([e.source],T=>s(T[0]),{meta:Pe("issue_tracker",{stage:"extract"})});n.add(i,{name:"extract"});let a=e.verify??(()=>({valid:!0})),u=_([i],T=>{let w=T[0];return{issue:w,verification:a(w)}},{meta:Pe("issue_tracker",{stage:"verify"})});n.add(u,{name:"verify"});let c=E([],{meta:Pe("issue_tracker",{stage:"known_patterns"})});n.add(c,{name:"known_patterns"});let d=e.detectRegression??(()=>({regression:!1})),l=_([i,c],T=>{let w=T[0],k=T[1];return{issue:w,regression:d(w,k)}},{meta:Pe("issue_tracker",{stage:"regression"})});n.add(l,{name:"regression"});let p=_([i],T=>T[0]?.severity??0),f=_([l],T=>T[0]?.regression?2:0);n.add(p,{name:"__severity_signal"}),n.add(f,{name:"__regression_signal"});let m=E(1),g=E(1.5);n.add(m,{name:"__severity_weight"}),n.add(g,{name:"__regression_weight"});let h=go([p,f],[m,g]);n.add(h,{name:"priority"});let y=_([u,l,h],T=>({verified:T[0],regression:T[1],priority:T[2]}),{meta:Pe("issue_tracker",{stage:"output"})});n.add(y,{name:"output"});let b=E(null,{meta:Pe("issue_tracker",{stage:"feedback_reentry"})});n.add(b,{name:"feedback_reentry"});let v=_([u],T=>{let w=T[0];if(w){let k=w.verification;if(k&&k.valid===!1)return w}return null},{meta:Pe("issue_tracker",{stage:"feedback_condition"})});return n.add(v,{name:"feedback_condition"}),Yt(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??3}),n}function gy(t,e){let n=new Y(t,e);n.add(e.source,{name:"source"});let r=v=>({label:"review",confidence:.5,original:v}),o=e.classify??r,s=_([e.source],v=>o(v[0]),{meta:Pe("content_moderation",{stage:"classify"})});n.add(s,{name:"classify"});let i=to("stratify",s,[{name:"safe",classify:v=>v.label==="safe"},{name:"review",classify:v=>v.label==="review"},{name:"block",classify:v=>v.label==="block"}]);n.mount("stratify",i);let a=Ue([],{name:"review_queue",maxSize:e.maxQueueSize});n.add(a.entries,{name:"review_queue"});let u;try{u=n.resolve("stratify::branch/review")}catch{u=E(null),n.add(u,{name:"__review_fallback"})}let c=de([u],v=>{let T=v[0];T&&a.append(T)});n.add(c,{name:"__review_accumulator"}),n.addDisposer(se(c));let d=E({},{meta:Pe("content_moderation",{stage:"policy",access:"both",description:"Moderation policy rules \u2014 updated via feedback"})});n.add(d,{name:"policy"});let l=e.weights??[.1,1,2],p=_([s],v=>v[0]?.confidence??0),f=_([s],v=>{let T=v[0];return T?T.label==="block"?l[2]:T.label==="review"?l[1]:l[0]:0});n.add(p,{name:"__confidence_signal"}),n.add(f,{name:"__severity_signal"});let m=E(1),g=E(1);n.add(m,{name:"__w_confidence"}),n.add(g,{name:"__w_severity"});let h=go([p,f],[m,g]);n.add(h,{name:"priority"});let y=_([s,h],v=>({classification:v[0],priority:v[1]}),{meta:Pe("content_moderation",{stage:"output"})});n.add(y,{name:"output"});let b=_([a.entries,d],v=>{let T=v[0];if(T&&T.length>0){let w=T[T.length-1];if(w&&w.falsePositive)return w}return null},{meta:Pe("content_moderation",{stage:"feedback_condition"})});return n.add(b,{name:"feedback_condition"}),Yt(n,"feedback_condition","policy",{maxIterations:e.maxFeedbackIterations??5}),n}function yy(t,e){let n=new Y(t,e);n.add(e.source,{name:"source"});let r=e.validate??(h=>({valid:!0,errors:[],record:h})),o=_([e.source],h=>h[0]!=null?r(h[0]):void 0,{meta:Pe("data_quality",{stage:"validate"})});n.add(o,{name:"validate"});let s=e.detectAnomaly??(h=>({anomaly:!1,score:0,record:h})),i=_([e.source],h=>h[0]!=null?s(h[0]):void 0,{meta:Pe("data_quality",{stage:"anomaly"})});n.add(i,{name:"anomaly"});let a=E(null,{meta:Pe("data_quality",{stage:"baseline",description:"Rolling baseline for drift detection"})});n.add(a,{name:"baseline"});let u=de([o],h=>{let y=h[0];y?.valid&&Z(()=>{a.emit(y.record)})});n.add(u,{name:"__baseline_updater"}),se(u);let c=e.detectDrift??(()=>({drift:!1})),d=_([e.source,a],h=>c(h[0],h[1]),{meta:Pe("data_quality",{stage:"drift"})});n.add(d,{name:"drift"});let l=e.suggest??(()=>null),p=_([o,i],h=>l({validation:h[0],anomaly:h[1]}),{meta:Pe("data_quality",{stage:"remediate"})});n.add(p,{name:"remediate"});let f=_([o,i,d,p],h=>({validation:h[0],anomaly:h[1],drift:h[2],remediation:h[3]}),{meta:Pe("data_quality",{stage:"output"})});n.add(f,{name:"output"});let m=E([],{meta:Pe("data_quality",{stage:"validation_rules"})});n.add(m,{name:"validation_rules"});let g=_([i],h=>{let y=h[0];return y?.anomaly?y:null},{meta:Pe("data_quality",{stage:"feedback_condition"})});return n.add(g,{name:"feedback_condition"}),Yt(n,"feedback_condition","validation_rules",{maxIterations:e.maxFeedbackIterations??3}),n}function fu(t,e){if(t==null||typeof t!="object")return!1;let n=t;return n.type===e||n.kind===e}var pi={};Ne(pi,{GuardedExecutionGraph:()=>li,guardedExecution:()=>by});var li=class extends Y{enforcer;violations;_target;_defaultActor;constructor(e,n){super(n.name??`${e.name}_guarded`,n.graph),this._target=e,this._defaultActor=n.actor;let r={mode:n.mode??"enforce",name:"enforcer"};n.violationsLimit!=null&&(r.violationsLimit=n.violationsLimit),this.enforcer=au(e,n.policies,r),this.violations=this.enforcer.violations,this.mount("enforcer",this.enforcer)}scopedDescribe(e){let n=e?.actor??this._defaultActor,r={...e,...n!=null?{actor:n}:{}};return this._target.describe(r)}get target(){return this._target}};function by(t,e){return new li(t,e)}var wi={};Ne(wi,{DEFAULT_DECAY_RATE:()=>ur,DEFAULT_EXECUTE_PROMPT:()=>hu,DEFAULT_QUEUE_CONFIGS:()=>fi,DEFAULT_SEVERITY_WEIGHTS:()=>ar,DEFAULT_TRIAGE_PROMPT:()=>mu,DEFAULT_VERIFY_PROMPT:()=>gu,HarnessGraph:()=>Ti,QUEUE_NAMES:()=>ot,affectedTaskFilter:()=>xy,beforeAfterCompare:()=>ky,codeChangeBridge:()=>Ry,createIntakeBridge:()=>vy,defaultErrorClassifier:()=>mi,defaultLlmExecutor:()=>jp,defaultLlmVerifier:()=>Bp,evalIntakeBridge:()=>Ty,evalSource:()=>wy,evalVerifier:()=>Ip,harnessEvalPair:()=>Py,harnessLoop:()=>By,harnessProfile:()=>Ky,harnessTrace:()=>Wy,notifyEffect:()=>Sy,priorityScore:()=>$y,refineExecutor:()=>vu,resolvePromptFn:()=>wo,strategyKey:()=>cr,strategyModel:()=>wu});ee();Re();function vy(t,e,n,r){return de([t],([o])=>{if(o==null)return;let s=n(o);for(let i of s)e.publish(i)},{name:r?.name??"intake-bridge"})}function Ty(t,e,n){let r=n?.defaultSeverity??"medium";return de([t],([o])=>{if(o==null)return;let s=Array.isArray(o)?o:[o];for(let i of s)for(let a of i.tasks)if(!(a.valid&&a.judge_scores?.every(u=>u.pass))){if(!a.valid&&(!a.judge_scores||a.judge_scores.length===0)){e.publish({source:"eval",summary:`Task ${a.task_id} invalid (model: ${i.model})`,evidence:`Run ${i.run_id}: task produced invalid output`,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:r});continue}if(a.judge_scores)for(let u of a.judge_scores)u.pass||e.publish({source:"eval",summary:`${a.task_id}: ${u.claim} (model: ${i.model})`,evidence:u.reasoning,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:r})}},{name:n?.name??"eval-intake-bridge"})}function wy(t,e){return Se(t,()=>X(e()))}function ky(t,e){return _([t,e],([n,r])=>{let o=n,s=r,i=new Map(o.tasks.map(p=>[p.task_id,p])),a=new Map(s.tasks.map(p=>[p.task_id,p])),u=new Set([...i.keys(),...a.keys()]),c=[],d=[],l=[];for(let p of u){let f=i.get(p),m=a.get(p),g=f?.valid??!1,h=m?.valid??!1,y=f?.judge_scores?f.judge_scores.filter(T=>T.pass).length:void 0,b=m?.judge_scores?m.judge_scores.filter(T=>T.pass).length:void 0,v=y!==void 0&&b!==void 0?b-y:void 0;c.push({taskId:p,before:g,after:h,scoreDiff:v}),g&&!h&&d.push(p),!g&&h&&l.push(p)}return{newFailures:d,resolved:l,taskDeltas:c,overallImproved:l.length>d.length}},{name:"eval-delta"})}function xy(t,e){let n=e==null?null:Array.isArray(e)?E(e):e,r=[t];return n&&r.push(n),_(r,o=>{let s=o[0],i=n?new Set(o[1]):null,a=new Set;for(let u of s)for(let c of u.affectsEvalTasks??[])(i==null||i.has(c))&&a.add(c);return[...a].sort()},{name:"affected-task-filter"})}function Ry(t,e,n,r){let o=r?.defaultSeverity??"high";function s(a){let u=[];for(let c of a.lintErrors??[])u.push({source:"code-change",summary:`Lint: ${c.rule} in ${c.file}:${c.line}`,evidence:c.message,affectsAreas:[c.file],severity:o});for(let c of a.testFailures??[])u.push({source:"test",summary:`Test failure: ${c.testId}`,evidence:c.message,affectsAreas:[c.file],affectsEvalTasks:[c.testId],severity:o});return u}let i=n??s;return de([t],([a])=>{if(a!=null)for(let u of i(a))e.publish(u)},{name:r?.name??"code-change-bridge"})}function Sy(t,e,n){return de([t.latest],([r])=>{r!=null&&e(r)},{name:n?.name??"notify-effect"})}var ot=["auto-fix","needs-decision","investigation","backlog"],fi={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1}},ar={critical:100,high:70,medium:40,low:10},ur=Math.LN2/(168*3600);function cr(t,e){return`${t}\u2192${e}`}var Ny=/\b(parse|json|config|validation|syntax)\b/i,mi=t=>Ny.test(t.detail)?"self-correctable":"structural",mu=`You are a triage classifier for a reactive collaboration harness.
175
+ - Return ONLY valid JSON, no markdown fences or commentary.`;async function Ap(t,e,n,r){let{expand:s,...o}=t.describe({actor:r?.actor,detail:"standard"}),i=[{role:"system",content:Yg},{role:"user",content:JSON.stringify({graph:o,problem:e})}],a=n.invoke(i,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens,signal:r?.signal}),d=(await so(a)).content.trim();d.startsWith("```")&&(d=d.replace(/^```(?:json)?\s*/,"").replace(/\s*```$/,""));let c;try{c=JSON.parse(d)}catch{throw new Error(`suggestStrategy: LLM response is not valid JSON: ${d.slice(0,200)}`)}let l=c;if(typeof l.summary!="string")throw new Error("suggestStrategy: missing 'summary' in response");if(typeof l.reasoning!="string")throw new Error("suggestStrategy: missing 'reasoning' in response");if(!Array.isArray(l.operations))throw new Error("suggestStrategy: missing 'operations' array in response");return{summary:l.summary,reasoning:l.reasoning,operations:l.operations}}function Qg(t,e,n,r){let s=W(e),o=At(s,t);return be(o,i=>{if(i==null)return N(null);let[a,u]=i;return!u||!a||typeof a!="string"||a.trim().length===0?N(null):u.destroyed?N(null):$(d=>{let c=new AbortController,l=!1;return Ap(u,a,n,{...r,signal:c.signal}).then(p=>{l||(d.emit(p),d.down([[O]]))}).catch(p=>{l||d.down([[M,p]])}),()=>{l=!0,c.abort()}},{name:"suggestStrategy::call"})})}var Lp=new Set(["state","derived","producer","operator","effect"]);function Xg(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[s,o]of Object.entries(n.nodes)){if(o==null||typeof o!="object"){e.push(`Node "${s}": must be an object`);continue}let i=o;if((typeof i.type!="string"||!Lp.has(i.type))&&e.push(`Node "${s}": invalid type "${String(i.type)}" (expected: ${[...Lp].join(", ")})`),Array.isArray(i.deps))for(let a of i.deps)typeof a=="string"&&!r.has(a)&&e.push(`Node "${s}": 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 s=new Set;for(let o=0;o<n.edges.length;o++){let i=n.edges[o];if(i==null||typeof i!="object"){e.push(`Edge [${o}]: must be an object`);continue}let a=i;(typeof a.from!="string"||!r.has(a.from))&&e.push(`Edge [${o}]: 'from' "${String(a.from)}" does not reference an existing node`),(typeof a.to!="string"||!r.has(a.to))&&e.push(`Edge [${o}]: 'to' "${String(a.to)}" does not reference an existing node`);let u=`${a.from}->${a.to}`;s.has(u)&&e.push(`Edge [${o}]: duplicate edge ${u}`),s.add(u)}}return{valid:e.length===0,errors:e}}var ni={};we(ni,{AuditTrailGraph:()=>ei,PolicyEnforcerGraph:()=>ti,auditTrail:()=>ey,complianceSnapshot:()=>ty,policyEnforcer:()=>cu,reactiveExplainPath:()=>lu});Ne();nn();se();_e();Q();No();function Dp(t,e){return ze("audit",t,e)}var Zg=new Set(["data","error","complete","teardown"]),ei=class extends q{entries;count;_log;_target;constructor(e,n){super(n.name??`${e.name}_audit`,n.graph),this._target=e,this._log=Ue([],{name:"entries",...n.maxSize!=null?{maxSize:n.maxSize}:{}}),this.entries=this._log.entries,this.add(this.entries,{name:"entries"}),this.count=_([this.entries],([u])=>u.length,{name:"count",describeKind:"derived",meta:Dp("count")}),this.add(this.count,{name:"count"}),this.addDisposer(re(this.count));let r=n.includeTypes!=null?new Set(n.includeTypes):Zg,s=n.filter,o=0,i=e.observe({timeline:!0,structured:!0}),a=i.onEvent(u=>{if(u.type==="derived")return;let d=u.type;if(!r.has(d))return;let c=u.path??"",l={seq:o++,timestamp_ns:u.timestamp_ns??F(),wall_clock_ns:ce(),path:c,type:d},f=(c?du(e,c):void 0)?.lastMutation;f!=null&&(l.actor=f.actor),d==="data"&&(l.value=u.data),d==="error"&&(l.error=u.data);let m=c?ry(e,c):void 0;m!=null&&(l.annotation=m),!(s!=null&&!s(l))&&this._log.append(l)});this.addDisposer(()=>{a(),i.dispose()}),this.addDisposer(()=>this._log.disposeAllViews())}all(){return this.entries.cache??[]}byNode(e){return this.all().filter(n=>n.path===e)}byActor(e){return this.all().filter(n=>n.actor?.id===e)}byActorType(e){return this.all().filter(n=>n.actor?.type===e)}byTimeRange(e,n){return this.all().filter(r=>!(r.timestamp_ns<e||n!=null&&r.timestamp_ns>=n))}get target(){return this._target}};function ey(t,e={}){return new ei(t,e)}var ti=class extends q{policies;violations;violationCount;_target;_mode;_currentGuard;constructor(e,n,r){super(r.name??`${e.name}_policy`,r.graph),this._target=e,this._mode=r.mode??"audit";let s=ny(n)?n:N(n,{name:"policies"});this.policies=s,this.add(this.policies,{name:"policies"}),this.violations=new xn("violations",{retainedLimit:r.violationsLimit??1e3}),this.mount("violations",this.violations),this.violationCount=_([this.violations.events],([d])=>d.length,{name:"violationCount",describeKind:"derived",meta:Dp("policy_violation_count")}),this.add(this.violationCount,{name:"violationCount"}),this.addDisposer(re(this.violationCount));let i=s.cache??[];this._currentGuard=Sr(i);let a=s.subscribe(d=>{for(let c of d)c[0]===R&&(i=c[1]??[],this._currentGuard=Sr(i))});this.addDisposer(a);let u=r.paths!=null?[...r.paths]:Ip(e);if(this._mode==="enforce"){let d=new Map,c=l=>{if(d.has(l))return;let p=du(e,l);if(!(p instanceof Ae))return;let f=(m,g)=>{let h=this._currentGuard(m,g);return h||this._publishViolation(m,g,l,"blocked"),h};d.set(l,p._pushGuard(f))};for(let l of u)c(l);if(r.paths==null){let l=Mt(e,(p,f,m)=>{if(p.kind==="added")if(p.nodeKind==="node")c(`${m}${p.name}`);else{let g=f._mounts.get(p.name);if(!(g instanceof q))return;let h=`${m}${p.name}::`,y=Ip(g);for(let b of y)c(b===""?`${m}${p.name}`:`${h}${b}`)}else if(p.kind==="removed")if(p.nodeKind==="node"){let g=`${m}${p.name}`,h=d.get(g);h!=null&&(h(),d.delete(g))}else{let g=`${m}${p.name}`,h=`${g}::`;for(let[y,b]of d)(y===g||y.startsWith(h))&&(b(),d.delete(y))}});this.addDisposer(l)}else{let l=e.topology.subscribe(p=>{for(let f of p){if(f[0]!==R)continue;let m=f[1];if(m.kind!=="removed"||m.nodeKind!=="node")continue;let g=d.get(m.name);g!=null&&(g(),d.delete(m.name))}});this.addDisposer(l)}this.addDisposer(()=>{for(let l of d.values())l();d.clear()})}else{let d=e.observe({timeline:!0,structured:!0}),c=d.onEvent(l=>{if(l.type!=="data"&&l.type!=="error")return;let p=l.path??"";if(!p||r.paths!=null&&!r.paths.includes(p))return;let f=l.actor??du(e,p)?.lastMutation?.actor;if(f==null)return;let m="write";this._currentGuard(f,m)||this._publishViolation(f,m,p,"observed")});this.addDisposer(()=>{c(),d.dispose()})}}_publishViolation(e,n,r,s){this.violations.publish({timestamp_ns:F(),wall_clock_ns:ce(),path:r,actor:e,action:n,mode:this._mode,result:s})}all(){return this.violations.retained()}get mode(){return this._mode}get target(){return this._target}};function cu(t,e,n={}){return new ti(t,e,n)}function lu(t,e,n,r){return t.explain(e,n,{reactive:!0,...r})}function ty(t,e={}){let n={format_version:1,timestamp_ns:F(),wall_clock_ns:ce(),graph:t.snapshot()};if(e.actor!=null&&(n.actor=e.actor),e.audit!=null){let s=[...e.audit.all()];n.audit={count:s.length,entries:s}}if(e.policies!=null){let s=e.policies.policies.cache??[];n.policies={mode:e.policies.mode,rules:s,violations:[...e.policies.all()]}}let r=oy(n);return{...n,fingerprint:r}}function ny(t){return typeof t=="object"&&t!==null&&"subscribe"in t}function du(t,e){try{return t.node(e)}catch{return}}function ry(t,e){try{return t.annotation(e)}catch{return}}function Ip(t){let e=t.describe({detail:"minimal"});return Object.keys(e.nodes)}function oy(t){return Gt(JSON.stringify(sy(t)))}function sy(t){let e=new Set,n=r=>{if(r===void 0)return{__undefined:!0};if(r===null)return null;let s=typeof r;if(s==="bigint")return{__bigint:r.toString()};if(s!=="object")return r;let o=r;if(e.has(o))return{__circular:!0};e.add(o);try{if(Array.isArray(o))return o.map(n);if(o instanceof Date)return{__date:o.toISOString()};if(o instanceof RegExp)return{__regexp:{source:o.source,flags:o.flags}};if(o instanceof Map)return{__map:[...o.entries()].map(([u,d])=>[n(u),n(d)])};if(o instanceof Set)return{__set:[...o].map(n)};if(ArrayBuffer.isView(o)){let a=o,u=new Array(a.length);for(let d=0;d<a.length;d++)u[d]=a[d]??0;return{__typed_array:{ctor:o.constructor.name,data:u}}}let i={};for(let a of Object.keys(o).sort())i[a]=n(o[a]);return i}finally{e.delete(o)}};return n(t)}var oi={};we(oi,{demoShell:()=>fy});Ce();Q();Ne();_e();Q();function iy(t){for(let e of t){let n=e.codePointAt(0);if(n>=19968&&n<=40959||n>=13312&&n<=19903||n>=12288&&n<=12351||n>=12352&&n<=12447||n>=12448&&n<=12543||n>=44032&&n<=55215||n>=65280&&n<=65519)return!0}return!1}var Pp=new Set(["\uFF0C","\uFF0E","\uFF01","\uFF1A","\uFF1B","\uFF1F","\u3001","\u3002","\u30FB","\uFF09","\u3015","\u3009","\u300B","\u300D","\u300F","\u3011"]),ay=new Set([".",",","!","?",":",";",")","]","}","%",'"',"\u201D","\u2019","\xBB","\u203A","\u2026"]);function uy(t){return t.replace(/[\t\n\r\f ]+/g," ").replace(/^ | $/g,"")}function dy(t){let e=new Intl.Segmenter(void 0,{granularity:"word"}),n=[];for(let r of e.segment(t)){let s=r.segment,o=r.isWordLike??!1,i=[],a=[],u=[],d="",c=null;for(let l of s){let p;l===" "?p="space":l==="\u200B"?p="zero-width-break":l==="\xAD"?p="soft-hyphen":l===`
176
+ `?p="hard-break":p="text",c!==null&&p===c?d+=l:(c!==null&&(i.push(d),a.push(c==="text"&&o),u.push(c)),d=l,c=p)}c!==null&&(i.push(d),a.push(c==="text"&&o),u.push(c)),n.push({texts:i,isWordLike:a,kinds:u})}return n}function Pt(t,e,n,r,s){let o=uy(t);if(o.length===0)return[];let i=dy(o),a=new Intl.Segmenter(void 0,{granularity:"grapheme"}),u=[],d=[],c=[];for(let y of i)for(let b=0;b<y.texts.length;b++)u.push(y.texts[b]),d.push(y.kinds[b]),c.push(y.isWordLike[b]);let l=[],p=[],f=[];for(let y=0;y<u.length;y++){let b=u[y],v=d[y],T=c[y];if(v==="text"&&!T&&l.length>0&&p[p.length-1]==="text"&&b.length===1&&(ay.has(b)||Pp.has(b))){l[l.length-1]+=b;continue}if(b==="-"&&l.length>0&&p[p.length-1]==="text"&&f[f.length-1]){l[l.length-1]+=b;continue}l.push(b),p.push(v),f.push(T)}let m=r.get(e);m||(m=new Map,r.set(e,m));function g(y){let b=m.get(y);if(b===void 0){s&&(s.misses+=1);let v=n.measureSegment(y,e).width;b=Number.isFinite(v)&&v>=0?v:0,m.set(y,b)}else s&&(s.hits+=1);return b}let h=[];for(let y=0;y<l.length;y++){let b=l[y],v=p[y];if(v!=="text"){h.push({text:b,width:v==="space"?g(" ")*b.length:0,kind:v,graphemeWidths:null});continue}if(iy(b)){let k="";for(let x of a.segment(b)){let S=x.segment;if(k.length>0&&Pp.has(S)){k+=S;continue}if(k.length>0){let E=g(k);h.push({text:k,width:E,kind:"text",graphemeWidths:null})}k=S}if(k.length>0){let x=g(k);h.push({text:k,width:x,kind:"text",graphemeWidths:null})}continue}let T=g(b),w=null;if(f[y]&&b.length>1){let k=[];for(let x of a.segment(b))k.push(g(x.segment));k.length>1&&(w=k)}h.push({text:b,width:T,kind:"text",graphemeWidths:w})}return h}function Sn(t,e,n,r,s){if(t.length===0)return{lines:[],lineCount:0};let o=[],i=0,a=!1,u=0,d=0,c=0,l=0,p=-1,f=0,m=s.get(r);m||(m=new Map,s.set(r,m));let g=m.get("-");g===void 0&&(g=n.measureSegment("-",r).width,m.set("-",g));function h(w=c,k=l,x=i){let S="";for(let E=u;E<w;E++){let L=t[E];if(!(L.kind==="soft-hyphen"||L.kind==="hard-break"))if(E===u&&d>0&&L.graphemeWidths){let I=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(L.text)].map(A=>A.segment);S+=I.slice(d).join("")}else S+=L.text}if(k>0&&w<t.length){let E=t[w],C=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(E.text)].map(A=>A.segment),I=u===w?d:0;S+=C.slice(I,k).join("")}w>0&&t[w-1]?.kind==="soft-hyphen"&&!(u===w&&d>0)&&(S+="-"),o.push({text:S,width:x,startSegment:u,startGrapheme:d,endSegment:w,endGrapheme:k}),i=0,a=!1,p=-1,f=0}function y(w){return w==="space"||w==="zero-width-break"||w==="soft-hyphen"}function b(w,k,x){a=!0,u=w,d=k,c=w+1,l=0,i=x}function v(w,k,x){a=!0,u=w,d=k,c=w,l=k+1,i=x}for(let w=0;w<t.length;w++){let k=t[w];if(k.kind==="hard-break"){a?h():o.push({text:"",width:0,startSegment:w,startGrapheme:0,endSegment:w,endGrapheme:0}),u=w+1,d=0;continue}let x=k.width;if(!a){x>e&&k.graphemeWidths?T(w,0,k.graphemeWidths):b(w,0,x),y(k.kind)&&(p=w+1,f=k.kind==="space"?i-x:i);continue}let S=i+x;if(S>e+.005){if(y(k.kind)){i+=x,c=w+1,l=0,h(w+1,0,k.kind==="space"?i-x:i);continue}if(p>=0){h(p,0,f),w--;continue}if(x>e&&k.graphemeWidths){h(),T(w,0,k.graphemeWidths);continue}h(),w--;continue}i=S,c=w+1,l=0,y(k.kind)&&(p=w+1,f=k.kind==="space"?i-x:i)}return a&&h(),{lines:o,lineCount:o.length};function T(w,k,x){for(let S=k;S<x.length;S++){let E=x[S];if(!a){v(w,S,E);continue}i+E>e+.005?(h(),v(w,S,E)):(i+=E,c=w,l=S+1)}a&&c===w&&l===x.length&&(c=w+1,l=0)}}function pu(t){return t==="space"||t==="zero-width-break"||t==="soft-hyphen"}var fu=null;function cy(){return fu===null&&(fu=new Intl.Segmenter(void 0,{granularity:"grapheme"})),fu}function Gp(t,e,n){if(e===0&&n<0)return t.text;let r=[...cy().segment(t.text)].map(o=>o.segment),s=n<0?r.length:n;return r.slice(e,s).join("")}function Yt(t,e,n,r,s,o){let i="";for(let a=e;a<r;a++){let u=t[a];u.kind==="soft-hyphen"||u.kind==="hard-break"||(a===e&&n>0?i+=Gp(u,n,-1):i+=u.text)}if(s>0&&r<t.length){let a=t[r];i+=Gp(a,e===r?n:0,s)}return o&&(i+="-"),i}function ly(t){if(!t?.adapter||!t.font)return 0;let e=t.cache;if(e){let n=e.get(t.font);n||(n=new Map,e.set(t.font,n));let r=n.get("-");return r===void 0&&(r=t.adapter.measureSegment("-",t.font).width,n.set("-",r)),r}return t.adapter.measureSegment("-",t.font).width}function mu(t,e,n,r){let s=e.segmentIndex,o=e.graphemeIndex;if(s>=t.length)return null;if(o===0){for(;s<t.length;){let w=t[s];if(w.kind==="hard-break")return{text:"",width:0,start:{segmentIndex:e.segmentIndex,graphemeIndex:0},end:{segmentIndex:s+1,graphemeIndex:0}};if(w.kind==="space"||w.kind==="zero-width-break"||w.kind==="soft-hyphen"){s+=1;continue}break}if(s>=t.length)return null}let i=ly(r),a=s,u=s===e.segmentIndex?o:0,d=0,c=a,l=0,p=!1,f=-1,m=0,g=0,h=!1,y=(w,k,x,S)=>{f=w,m=k,g=x,h=S==="soft-hyphen"},b=(w,k,x)=>{for(let S=k;S<x.length;S++){let E=x[S];if(!p){d=E,c=w,l=S+1,p=!0;continue}if(d+E>n+.005)return!0;d+=E,c=w,l=S+1}return c===w&&l===x.length&&(c=w+1,l=0),!1};if(u>0&&a<t.length){let w=t[a];if(w.graphemeWidths){if(b(a,u,w.graphemeWidths))return{text:Yt(t,a,u,c,l,!1),width:d,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:c,graphemeIndex:l}};s=c}}for(;s<t.length;){let w=t[s];if(w.kind==="hard-break"){if(p){let S=c>0&&t[c-1]?.kind==="soft-hyphen";return{text:Yt(t,a,u,c,l,S),width:d+(S?i:0),start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:c,graphemeIndex:l}}}return{text:"",width:0,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:s+1,graphemeIndex:0}}}let k=w.width;if(!p){if(k>n&&w.graphemeWidths){if(b(s,0,w.graphemeWidths))return{text:Yt(t,a,u,c,l,!1),width:d,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:c,graphemeIndex:l}};s=c;continue}d=k,c=s+1,l=0,p=!0,pu(w.kind)&&y(s+1,0,w.kind==="space"?d-k:d,w.kind),s+=1;continue}let x=d+k;if(x>n+.005){if(pu(w.kind)){c=s+1,l=0;let E=w.kind==="soft-hyphen",L=w.kind==="space"?d:d+(E?i:0);return{text:Yt(t,a,u,c,l,E),width:L,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:c,graphemeIndex:l}}}return f>=0?{text:Yt(t,a,u,f,m,h),width:g+(h?i:0),start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:f,graphemeIndex:m}}:k>n&&w.graphemeWidths?{text:Yt(t,a,u,c,l,!1),width:d,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:c,graphemeIndex:l}}:{text:Yt(t,a,u,c,l,!1),width:d,start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:c,graphemeIndex:l}}}d=x,c=s+1,l=0,pu(w.kind)&&y(s+1,0,w.kind==="space"?d-k:d,w.kind),s+=1}if(!p)return null;let v=c>0&&t[c-1]?.kind==="soft-hyphen";return{text:Yt(t,a,u,c,l,v),width:d+(v?i:0),start:{segmentIndex:a,graphemeIndex:u},end:{segmentIndex:c,graphemeIndex:l}}}function hu(t,e,n=0){let r=[t];for(let s=0;s<e.length;s++){let o=e[s],i=[];for(let a=0;a<r.length;a++){let u=r[a];if(o.right<=u.left||o.left>=u.right){i.push(u);continue}o.left>u.left&&i.push({left:u.left,right:o.left}),o.right<u.right&&i.push({left:o.right,right:u.right})}r=i}return n>0?r.filter(s=>s.right-s.left>=n):r}function ri(t,e,n){let r=[],s=new Intl.Segmenter(void 0,{granularity:"grapheme"});for(let o=0;o<t.lines.length;o++){let i=t.lines[o],a=o*n,u=0;for(let d=i.startSegment;d<e.length;d++){let c=e[d];if(c.kind==="soft-hyphen"||c.kind==="hard-break"){if(d>=i.endSegment&&i.endGrapheme===0)break;continue}let l=[...s.segment(c.text)].map(m=>m.segment);if(l.length===0)continue;let p=d===i.startSegment?i.startGrapheme:0,f;if(d<i.endSegment)f=l.length;else if(d===i.endSegment&&i.endGrapheme>0)f=i.endGrapheme;else break;for(let m=p;m<f;m++){let g=c.graphemeWidths?c.graphemeWidths[m]:c.width/l.length;r.push({x:u,y:a,width:g,height:n,line:o}),u+=g}}}return r}function py(t){let{adapter:e,name:n="reactive-layout"}=t,r=new q(n),s=new Map,o=N(t.text??"",{name:"text"}),i=N(t.font??"16px sans-serif",{name:"font"}),a=N(t.lineHeight??20,{name:"line-height"}),u=N(Math.max(0,t.maxWidth??800),{name:"max-width"});function d(m,g){if(m===null||g===null)return m===g;if(m.length!==g.length)return!1;for(let h=0;h<m.length;h++)if(m[h]!==g[h])return!1;return!0}let c=V([o,i],(m,g,h)=>{let y=m[0],b=y!=null&&y.length>0?y.at(-1):h.prevData[0],v=m[1],T=v!=null&&v.length>0?v.at(-1):h.prevData[1],w=F(),k={hits:0,misses:0},x=Pt(b,T,e,s,k),S=F()-w,E=k.hits+k.misses,L=E===0?1:k.hits/E,C=c.meta;C&&(ft(C["cache-hit-rate"],L),ft(C["segment-count"],x.length),ft(C["layout-time-ns"],S)),g.emit(x);let I=()=>{s.clear(),e.clearCache?.()};return{deactivate:I,invalidate:I}},{name:"segments",describeKind:"derived",meta:{"cache-hit-rate":0,"segment-count":0,"layout-time-ns":0},equals:(m,g)=>{let h=m,y=g;if(h==null||y==null)return h===y;if(h.length!==y.length)return!1;for(let b=0;b<h.length;b++){let v=h[b],T=y[b];if(v.text!==T.text||v.width!==T.width||v.kind!==T.kind||!d(v.graphemeWidths??null,T.graphemeWidths??null))return!1}return!0}}),l=_([c,u,i],([m,g,h])=>Sn(m,g,e,h,s),{name:"line-breaks",equals:(m,g)=>{let h=m,y=g;if(h==null||y==null)return h===y;if(h.lineCount!==y.lineCount)return!1;for(let b=0;b<h.lines.length;b++){let v=h.lines[b],T=y.lines[b];if(v.text!==T.text||v.width!==T.width||v.startSegment!==T.startSegment||v.startGrapheme!==T.startGrapheme||v.endSegment!==T.endSegment||v.endGrapheme!==T.endGrapheme)return!1}return!0}}),p=_([l,a],([m,g])=>m.lineCount*g,{name:"height"}),f=_([l,c,a],([m,g,h])=>ri(m,g,h),{name:"char-positions",equals:(m,g)=>{let h=m,y=g;if(h==null||y==null)return h===y;if(h.length!==y.length)return!1;for(let b=0;b<h.length;b++)if(h[b].x!==y[b].x||h[b].y!==y[b].y||h[b].width!==y[b].width)return!1;return!0}});return r.add(o,{name:"text"}),r.add(i,{name:"font"}),r.add(a,{name:"line-height"}),r.add(u,{name:"max-width"}),r.add(c,{name:"segments"}),r.add(l,{name:"line-breaks"}),r.add(p,{name:"height"}),r.add(f,{name:"char-positions"}),{graph:r,setText:m=>r.set("text",m),setFont:m=>r.set("font",m),setLineHeight:m=>r.set("line-height",m),setMaxWidth:m=>r.set("max-width",Math.max(0,m)),segments:c,lineBreaks:l,height:p,charPositions:f}}function ho(t){return Math.max(0,Math.min(1,t))}function fy(t){let e=ho(t?.mainRatio??.65),n=ho(t?.sideSplit??.5),r=Math.max(0,t?.viewportWidth??1280),s=t?.nodeRegistry??new Map,o=t?.adapter??null,i=t?.layoutFont??"14px monospace",a=t?.onHighlight,u=new q("demo-shell"),d=N(e,{name:"pane/main-ratio"}),c=N(n,{name:"pane/side-split"}),l=N(null,{name:"pane/fullscreen"}),p=N(r,{name:"viewport/width"});u.add(d,{name:"pane/main-ratio"}),u.add(c,{name:"pane/side-split"}),u.add(l,{name:"pane/fullscreen"}),u.add(p,{name:"viewport/width"});let f=_([d,p,l],([D,Z,te])=>{let ke=D,J=Z,K=te;return K==="main"?J:K==="graph"||K==="code"?0:Math.round(J*ke)},{name:"pane/main-width"}),m=_([f,p,l],([D,Z,te])=>{let ke=te,J=Z;return ke==="main"?0:ke==="graph"||ke==="code"?J:J-D},{name:"pane/side-width"}),g=_([c,l],([D,Z])=>{let te=Z;return te==="graph"?1:te==="code"||te==="main"?0:ho(D)},{name:"pane/graph-height-ratio"}),h=_([g,l],([D,Z])=>{let te=Z;return te==="code"?1:te==="graph"||te==="main"?0:1-D},{name:"pane/code-height-ratio"});u.add(f,{name:"pane/main-width"}),u.add(m,{name:"pane/side-width"}),u.add(g,{name:"pane/graph-height-ratio"}),u.add(h,{name:"pane/code-height-ratio"});let y=N(null,{name:"demo/graph-ref"}),b=N(0,{name:"demo/graph-tick"});u.add(y,{name:"demo/graph-ref"}),u.add(b,{name:"demo/graph-tick"});let v=_([y,b],([D,Z])=>{let te=D;return te?te.describe({format:"mermaid"}):""},{name:"graph/mermaid"}),T=_([y,b],([D,Z])=>{let te=D;if(!te)return null;let{expand:ke,...J}=te.describe({detail:"standard"});return J},{name:"graph/describe"});u.add(v,{name:"graph/mermaid"}),u.add(T,{name:"graph/describe"});let w=N(null,{name:"hover/target"});u.add(w,{name:"hover/target"});let k=_([w],([D])=>{let Z=D;if(!Z)return null;let te=s.get(Z.id);return te?te.codeLine:null},{name:"highlight/code-scroll"}),x=_([w],([D])=>{let Z=D;if(!Z)return null;let te=s.get(Z.id);return te?te.visualSelector:null},{name:"highlight/visual"}),S=_([w],([D])=>{let Z=D;return Z?Z.id:null},{name:"highlight/graph"});if(u.add(k,{name:"highlight/code-scroll"}),u.add(x,{name:"highlight/visual"}),u.add(S,{name:"highlight/graph"}),a?.codeScroll){let D=a.codeScroll,Z=le([k],([te])=>{D(te)});u.add(Z,{name:"highlight/apply-code-scroll"})}if(a?.visual){let D=a.visual,Z=le([x],([te])=>{D(te)});u.add(Z,{name:"highlight/apply-visual"})}if(a?.graph){let D=a.graph,Z=le([S],([te])=>{D(te)});u.add(Z,{name:"highlight/apply-graph"})}let E=N(null,{name:"inspect/selected-node"});u.add(E,{name:"inspect/selected-node"});let L=_t("standard"),C=_([E,y,b],([D,Z,te])=>{let ke=Z,J=D;if(!ke||!J)return null;try{let K=ke.resolve(J),j=Ir(K,L);return{path:J,...j,value:K.cache}}catch{return null}},{name:"inspect/node-detail"}),I=_([y,b],([D,Z])=>{let te=D;return te?te.trace():[]},{name:"inspect/trace-log"});u.add(C,{name:"inspect/node-detail"}),u.add(I,{name:"inspect/trace-log"});let A=N(!1,{name:"meta/debug"});u.add(A,{name:"meta/debug"});let P=_([A,b],([D,Z])=>D?u.describe({format:"mermaid"}):"",{name:"meta/shell-mermaid"});u.add(P,{name:"meta/shell-mermaid"});let U=N("",{name:"layout/code-text"});if(u.add(U,{name:"layout/code-text"}),o){let D=new Map,Z=_([T],([J])=>{let K=J;if(!K)return new Map;let j=new Map;for(let[ne]of Object.entries(K.nodes)){let Re=Pt(ne,i,o,D),Me=Sn(Re,1/0,o,i,D),Oe=Me.lines.reduce((Ge,oe)=>Math.max(Ge,oe.width),0),he=Me.lineCount*20;j.set(ne,{width:Oe,height:he})}return j},{name:"layout/graph-labels",equals:(J,K)=>{if(J===K)return!0;let j=J,ne=K;if(j.size!==ne.size)return!1;for(let[Re,Me]of j){let Oe=ne.get(Re);if(!Oe||Oe.width!==Me.width||Oe.height!==Me.height)return!1}return!0}}),te=_([U,m],([J,K])=>{let j=J;if(!j)return{lineCount:0,lines:[]};let ne=Pt(j,i,o,D),Re=K-40;return Sn(ne,Math.max(100,Re),o,i,D)},{name:"layout/code-lines"}),ke=_([Z],([J])=>{let K=J;if(K.size===0)return 200;let j=0;for(let{width:ne}of K.values())ne>j&&(j=ne);return Math.max(200,Math.round(j+80))},{name:"layout/side-width-hint"});u.add(Z,{name:"layout/graph-labels"}),u.add(te,{name:"layout/code-lines"}),u.add(ke,{name:"layout/side-width-hint"})}let z=0;return{graph:u,setMainRatio(D){u.set("pane/main-ratio",ho(D))},setSideSplit(D){u.set("pane/side-split",ho(D))},setFullscreen(D){u.set("pane/fullscreen",D)},setViewportWidth(D){u.set("viewport/width",Math.max(0,D))},setHoverTarget(D){u.set("hover/target",D)},setDemoGraph(D){u.set("demo/graph-ref",D)},bumpGraphTick(){u.set("demo/graph-tick",++z)},selectNode(D){u.set("inspect/selected-node",D)},setMetaDebug(D){u.set("meta/debug",D)},setCodeText(D){u.set("layout/code-text",D)},batch(D){Y(D)},destroy(){u.destroy()}}}var si={};we(si,{contentModerationGraph:()=>gy,dataQualityGraph:()=>yy,issueTrackerGraph:()=>hy,observabilityGraph:()=>my});Ce();Q();function Ie(t,e){return ze("domain_template",t,e)}function my(t,e){let n=new q(t,e);n.add(e.source,{name:"source"});let r=[{name:"errors",classify:T=>gu(T,"error")},{name:"traces",classify:T=>gu(T,"trace")},{name:"metrics",classify:T=>gu(T,"metric")}],s=e.branches??r,o=s.map(T=>({name:T.name,classify:T.classify})),i=to("stratify",e.source,o);n.mount("stratify",i);let a=s.map(T=>{try{let w=n.resolve(`stratify::branch/${T.name}`);return _([w],([k])=>k,{initial:null})}catch{return N(null)}}),u=e.correlate??(T=>T),d=_(a,T=>u(T),{meta:Ie("observability",{stage:"correlate"})});n.add(d,{name:"correlate"});let c=e.sloCheck??(()=>({pass:!0})),l=_([d],T=>T[0],{meta:Ie("observability",{stage:"slo_value"})}),p=_([l],T=>c(T[0]),{meta:Ie("observability",{stage:"slo_verified"})});n.add(l,{name:"slo_value"}),n.add(p,{name:"slo_verified"});let f=e.weights??s.map(()=>1),m=a.map(T=>_([T],w=>w[0]!=null?1:0)),g=f.map(T=>N(T));for(let T=0;T<m.length;T++)n.add(m[T],{name:`__signal_${T}`}),n.add(g[T],{name:`__weight_${T}`});let h=lo(m,g);n.add(h,{name:"alerts"});let y=_([h,p],T=>({scored:T[0],slo:T[1]}),{meta:Ie("observability",{stage:"output"})});n.add(y,{name:"output"});let b=N(null,{meta:Ie("observability",{stage:"feedback_reentry"})});n.add(b,{name:"feedback_reentry"});let v=_([p],T=>{let w=T[0];return w&&w.pass===!1?w:null},{meta:Ie("observability",{stage:"feedback_condition"})});return n.add(v,{name:"feedback_condition"}),Jt(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??5}),n}function hy(t,e){let n=new q(t,e);n.add(e.source,{name:"source"});let r=0,s=T=>({id:`issue-${++r}`,title:String(T),severity:1,source:"unknown",raw:T}),o=e.extract??s,i=_([e.source],T=>o(T[0]),{meta:Ie("issue_tracker",{stage:"extract"})});n.add(i,{name:"extract"});let a=e.verify??(()=>({valid:!0})),u=_([i],T=>{let w=T[0];return{issue:w,verification:a(w)}},{meta:Ie("issue_tracker",{stage:"verify"})});n.add(u,{name:"verify"});let d=N([],{meta:Ie("issue_tracker",{stage:"known_patterns"})});n.add(d,{name:"known_patterns"});let c=e.detectRegression??(()=>({regression:!1})),l=_([i,d],T=>{let w=T[0],k=T[1];return{issue:w,regression:c(w,k)}},{meta:Ie("issue_tracker",{stage:"regression"})});n.add(l,{name:"regression"});let p=_([i],T=>T[0]?.severity??0),f=_([l],T=>T[0]?.regression?2:0);n.add(p,{name:"__severity_signal"}),n.add(f,{name:"__regression_signal"});let m=N(1),g=N(1.5);n.add(m,{name:"__severity_weight"}),n.add(g,{name:"__regression_weight"});let h=lo([p,f],[m,g]);n.add(h,{name:"priority"});let y=_([u,l,h],T=>({verified:T[0],regression:T[1],priority:T[2]}),{meta:Ie("issue_tracker",{stage:"output"})});n.add(y,{name:"output"});let b=N(null,{meta:Ie("issue_tracker",{stage:"feedback_reentry"})});n.add(b,{name:"feedback_reentry"});let v=_([u],T=>{let w=T[0];if(w){let k=w.verification;if(k&&k.valid===!1)return w}return null},{meta:Ie("issue_tracker",{stage:"feedback_condition"})});return n.add(v,{name:"feedback_condition"}),Jt(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??3}),n}function gy(t,e){let n=new q(t,e);n.add(e.source,{name:"source"});let r=v=>({label:"review",confidence:.5,original:v}),s=e.classify??r,o=_([e.source],v=>s(v[0]),{meta:Ie("content_moderation",{stage:"classify"})});n.add(o,{name:"classify"});let i=to("stratify",o,[{name:"safe",classify:v=>v.label==="safe"},{name:"review",classify:v=>v.label==="review"},{name:"block",classify:v=>v.label==="block"}]);n.mount("stratify",i);let a=Ue([],{name:"review_queue",maxSize:e.maxQueueSize});n.add(a.entries,{name:"review_queue"});let u;try{u=n.resolve("stratify::branch/review")}catch{u=N(null),n.add(u,{name:"__review_fallback"})}let d=le([u],v=>{let T=v[0];T&&a.append(T)});n.add(d,{name:"__review_accumulator"}),n.addDisposer(re(d));let c=N({},{meta:Ie("content_moderation",{stage:"policy",access:"both",description:"Moderation policy rules \u2014 updated via feedback"})});n.add(c,{name:"policy"});let l=e.weights??[.1,1,2],p=_([o],v=>v[0]?.confidence??0),f=_([o],v=>{let T=v[0];return T?T.label==="block"?l[2]:T.label==="review"?l[1]:l[0]:0});n.add(p,{name:"__confidence_signal"}),n.add(f,{name:"__severity_signal"});let m=N(1),g=N(1);n.add(m,{name:"__w_confidence"}),n.add(g,{name:"__w_severity"});let h=lo([p,f],[m,g]);n.add(h,{name:"priority"});let y=_([o,h],v=>({classification:v[0],priority:v[1]}),{meta:Ie("content_moderation",{stage:"output"})});n.add(y,{name:"output"});let b=_([a.entries,c],v=>{let T=v[0];if(T&&T.length>0){let w=T[T.length-1];if(w&&w.falsePositive)return w}return null},{meta:Ie("content_moderation",{stage:"feedback_condition"})});return n.add(b,{name:"feedback_condition"}),Jt(n,"feedback_condition","policy",{maxIterations:e.maxFeedbackIterations??5}),n}function yy(t,e){let n=new q(t,e);n.add(e.source,{name:"source"});let r=e.validate??(h=>({valid:!0,errors:[],record:h})),s=_([e.source],h=>h[0]!=null?r(h[0]):void 0,{meta:Ie("data_quality",{stage:"validate"})});n.add(s,{name:"validate"});let o=e.detectAnomaly??(h=>({anomaly:!1,score:0,record:h})),i=_([e.source],h=>h[0]!=null?o(h[0]):void 0,{meta:Ie("data_quality",{stage:"anomaly"})});n.add(i,{name:"anomaly"});let a=N(null,{meta:Ie("data_quality",{stage:"baseline",description:"Rolling baseline for drift detection"})});n.add(a,{name:"baseline"});let u=le([s],h=>{let y=h[0];y?.valid&&Y(()=>{a.emit(y.record)})});n.add(u,{name:"__baseline_updater"}),re(u);let d=e.detectDrift??(()=>({drift:!1})),c=_([e.source,a],h=>d(h[0],h[1]),{meta:Ie("data_quality",{stage:"drift"})});n.add(c,{name:"drift"});let l=e.suggest??(()=>null),p=_([s,i],h=>l({validation:h[0],anomaly:h[1]}),{meta:Ie("data_quality",{stage:"remediate"})});n.add(p,{name:"remediate"});let f=_([s,i,c,p],h=>({validation:h[0],anomaly:h[1],drift:h[2],remediation:h[3]}),{meta:Ie("data_quality",{stage:"output"})});n.add(f,{name:"output"});let m=N([],{meta:Ie("data_quality",{stage:"validation_rules"})});n.add(m,{name:"validation_rules"});let g=_([i],h=>{let y=h[0];return y?.anomaly?y:null},{meta:Ie("data_quality",{stage:"feedback_condition"})});return n.add(g,{name:"feedback_condition"}),Jt(n,"feedback_condition","validation_rules",{maxIterations:e.maxFeedbackIterations??3}),n}function gu(t,e){if(t==null||typeof t!="object")return!1;let n=t;return n.type===e||n.kind===e}var ai={};we(ai,{GuardedExecutionGraph:()=>ii,guardedExecution:()=>by});var ii=class extends q{enforcer;violations;_target;_defaultActor;constructor(e,n){super(n.name??`${e.name}_guarded`,n.graph),this._target=e,this._defaultActor=n.actor;let r={mode:n.mode??"enforce",name:"enforcer"};n.violationsLimit!=null&&(r.violationsLimit=n.violationsLimit),this.enforcer=cu(e,n.policies,r),this.violations=this.enforcer.violations,this.mount("enforcer",this.enforcer)}scopedDescribe(e){let n=e?.actor??this._defaultActor,r={...e,...n!=null?{actor:n}:{}};return this._target.describe(r)}get target(){return this._target}};function by(t,e){return new ii(t,e)}var gi={};we(gi,{DEFAULT_DECAY_RATE:()=>ur,DEFAULT_EXECUTE_PROMPT:()=>bu,DEFAULT_QUEUE_CONFIGS:()=>ui,DEFAULT_SEVERITY_WEIGHTS:()=>ar,DEFAULT_TRIAGE_PROMPT:()=>yu,DEFAULT_VERIFY_PROMPT:()=>vu,HarnessGraph:()=>hi,QUEUE_NAMES:()=>st,actuatorExecutor:()=>xy,affectedTaskFilter:()=>My,autoSolidify:()=>Ry,beforeAfterCompare:()=>_y,codeChangeBridge:()=>Oy,createIntakeBridge:()=>Sy,defaultErrorClassifier:()=>di,defaultLlmExecutor:()=>qp,defaultLlmVerifier:()=>Wp,evalIntakeBridge:()=>Ny,evalSource:()=>Ey,evalVerifier:()=>$p,harnessEvalPair:()=>Vy,harnessLoop:()=>Uy,harnessProfile:()=>Jy,harnessTrace:()=>Qy,notifyEffect:()=>Cy,priorityScore:()=>qy,refineExecutor:()=>ku,resolvePromptFn:()=>go,strategyKey:()=>dr,strategyModel:()=>Ru});se();Q();Te();function vy(t,e){return{outcome:"success",detail:`actuator applied ${e.intervention} for ${ky(e.summary)}`,artifact:t}}function Ty(t,e){let n=t instanceof Error?t.message:String(t);return{outcome:"failure",detail:`actuator threw on ${e.intervention}: ${n}`}}function wy(t){return`actuator skipped ${t.intervention} (shouldApply returned false)`}function ky(t,e=80){return t.length<=e?t:`${t.slice(0,e-1)}\u2026`}function xy(t){let e=t.name??"actuator-executor",n=t.toOutput??vy,r=t.onError??Ty,s=t.skipDetail??wy;return o=>{let i=Xe(o,u=>u!=null,{name:`${e}/gate-in`}),a=be(i,u=>t.shouldApply&&!t.shouldApply(u)?$(d=>(d.down([[R,{outcome:"failure",detail:s(u)}],[O]]),()=>{}),{name:`${e}/skip`}):$(d=>{let c=new AbortController,l=!1,p=null,f=g=>{l||(l=!0,d.down([[R,g],[O]]),p?.(),p=null)},m;try{let g=t.apply(u,{signal:c.signal});m=W(g,{signal:c.signal})}catch(g){return f(r(g,u)),()=>{c.abort()}}return p=m.subscribe(g=>{for(let h of g){if(l)return;if(h[0]===R){f(n(h[1],u));return}if(h[0]===M){f(r(h[1],u));return}if(h[0]===O){f(r(new Error("actuator inner completed without emitting DATA"),u));return}}}),l&&p&&(p(),p=null),()=>{c.abort(),p?.(),p=null}},{name:`${e}/inner`}),{name:e});return Xe(a,u=>u!=null,{name:`${e}/gate-out`})}}se();Q();function Ry(t){let e=t.name??"auto-solidify",n=t.extract??(s=>s.execution.artifact??null),r=t.predicate??(()=>!0);return $(s=>{let o=null,i=!1,a=()=>{i||(i=!0,o?.(),o=null)},u=d=>{i||(s.down([[M,d]]),a())};return o=t.verifyResults.subscribe(d=>{if(!i)for(let c of d){if(i)return;if(c[0]!==R){if(c[0]===O){s.down([[O]]),a();return}continue}let l=c[1];if(l==null||!l.verified)continue;let p;try{p=r(l)}catch(m){u(m);return}if(!p)continue;let f;try{f=n(l)}catch(m){u(m);return}if(f!=null){try{t.write(f,l)}catch(m){u(m);return}s.down([[R,f]])}}}),i&&o&&(o(),o=null),()=>{a()}},{name:e})}Q();Te();function Sy(t,e,n,r){return le([t],([s])=>{if(s==null)return;let o=n(s);for(let i of o)e.publish(i)},{name:r?.name??"intake-bridge"})}function Ny(t,e,n){let r=n?.defaultSeverity??"medium";return le([t],([s])=>{if(s==null)return;let o=Array.isArray(s)?s:[s];for(let i of o)for(let a of i.tasks)if(!(a.valid&&a.judge_scores?.every(u=>u.pass))){if(!a.valid&&(!a.judge_scores||a.judge_scores.length===0)){e.publish({source:"eval",summary:`Task ${a.task_id} invalid (model: ${i.model})`,evidence:`Run ${i.run_id}: task produced invalid output`,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:r});continue}if(a.judge_scores)for(let u of a.judge_scores)u.pass||e.publish({source:"eval",summary:`${a.task_id}: ${u.claim} (model: ${i.model})`,evidence:u.reasoning,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:r})}},{name:n?.name??"eval-intake-bridge"})}function Ey(t,e){return be(t,()=>W(e()))}function _y(t,e){return _([t,e],([n,r])=>{let s=n,o=r,i=new Map(s.tasks.map(p=>[p.task_id,p])),a=new Map(o.tasks.map(p=>[p.task_id,p])),u=new Set([...i.keys(),...a.keys()]),d=[],c=[],l=[];for(let p of u){let f=i.get(p),m=a.get(p),g=f?.valid??!1,h=m?.valid??!1,y=f?.judge_scores?f.judge_scores.filter(T=>T.pass).length:void 0,b=m?.judge_scores?m.judge_scores.filter(T=>T.pass).length:void 0,v=y!==void 0&&b!==void 0?b-y:void 0;d.push({taskId:p,before:g,after:h,scoreDiff:v}),g&&!h&&c.push(p),!g&&h&&l.push(p)}return{newFailures:c,resolved:l,taskDeltas:d,overallImproved:l.length>c.length}},{name:"eval-delta"})}function My(t,e){let n=e==null?null:Array.isArray(e)?N(e):e,r=[t];return n&&r.push(n),_(r,s=>{let o=s[0],i=n?new Set(s[1]):null,a=new Set;for(let u of o)for(let d of u.affectsEvalTasks??[])(i==null||i.has(d))&&a.add(d);return[...a].sort()},{name:"affected-task-filter"})}function Oy(t,e,n,r){let s=r?.defaultSeverity??"high";function o(a){let u=[];for(let d of a.lintErrors??[])u.push({source:"code-change",summary:`Lint: ${d.rule} in ${d.file}:${d.line}`,evidence:d.message,affectsAreas:[d.file],severity:s});for(let d of a.testFailures??[])u.push({source:"test",summary:`Test failure: ${d.testId}`,evidence:d.message,affectsAreas:[d.file],affectsEvalTasks:[d.testId],severity:s});return u}let i=n??o;return le([t],([a])=>{if(a!=null)for(let u of i(a))e.publish(u)},{name:r?.name??"code-change-bridge"})}function Cy(t,e,n){return le([t.latest],([r])=>{r!=null&&e(r)},{name:n?.name??"notify-effect"})}var st=["auto-fix","needs-decision","investigation","backlog"],ui={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1}},ar={critical:100,high:70,medium:40,low:10},ur=Math.LN2/(168*3600);function dr(t,e){return`${t}\u2192${e}`}var Ay=/\b(parse|json|config|validation|syntax)\b/i,di=t=>Ay.test(t.detail)?"self-correctable":"structural",yu=`You are a triage classifier for a reactive collaboration harness.
177
177
 
178
178
  Given an intake item, classify it and output JSON:
179
179
  {
@@ -188,7 +188,7 @@ Strategy model (past effectiveness):
188
188
  {{strategy}}
189
189
 
190
190
  Intake item:
191
- {{item}}`,hu=`You are an implementation agent.
191
+ {{item}}`,bu=`You are an implementation agent.
192
192
 
193
193
  Given a triaged issue with root cause and intervention type, produce a fix.
194
194
 
@@ -199,7 +199,7 @@ Output JSON:
199
199
  {
200
200
  "outcome": "success" | "failure" | "partial",
201
201
  "detail": "<description of what was done or what failed>"
202
- }`,gu=`You are a QA reviewer.
202
+ }`,vu=`You are a QA reviewer.
203
203
 
204
204
  Given an execution result, verify whether the fix is correct.
205
205
 
@@ -214,11 +214,11 @@ Output JSON:
214
214
  "verified": true/false,
215
215
  "findings": ["<finding1>", ...],
216
216
  "errorClass": "self-correctable" | "structural" // only if verified=false
217
- }`;function wo(t,e,n){if(typeof t=="function")return t;let r=t??e;return o=>n(r,o)}ee();ee();var hi={};Ne(hi,{blindVariation:()=>_y,errorCritique:()=>Cy,refineLoop:()=>bu});Ae();_e();ae();Le();ee();function Ey(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.subscribe=="function"&&typeof e.down=="function"&&typeof e.emit=="function"}function Lp(t,e){if(t.length===0)return{best:null,bestScore:Number.NEGATIVE_INFINITY};if(t.length===1){let s=yu(e);return{best:t[0],bestScore:s}}if(e.some(s=>typeof s.candidateIndex=="number")){let s=new Array(t.length);for(let u=0;u<t.length;u++)s[u]={sum:0,count:0};for(let u of e){let c=u.candidateIndex;typeof c=="number"&&c>=0&&c<t.length&&(s[c].sum+=u.score,s[c].count+=1)}let i=t[0],a=s[0].count>0?s[0].sum/s[0].count:Number.NEGATIVE_INFINITY;for(let u=1;u<t.length;u++){let c=s[u].count>0?s[u].sum/s[u].count:Number.NEGATIVE_INFINITY;c>a&&(a=c,i=t[u])}return{best:i,bestScore:a}}let r=t[0],o=e[0]?.score??Number.NEGATIVE_INFINITY;for(let s=1;s<t.length;s++){let i=e[s]?.score??Number.NEGATIVE_INFINITY;i>o&&(o=i,r=t[s])}return{best:r,bestScore:o}}function yu(t){if(t.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let n of t)e+=n.score;return e/t.length}function bu(t,e,n,r){let o=r.name??"refine-loop",s=new Y(o,r.graph),i=Ey(r.dataset)?r.dataset:E(r.dataset,{name:"dataset"});s.add(i,{name:"dataset"});let a=E(0,{name:"iteration"});s.add(a,{name:"iteration"});let u=E(n,{name:"strategy",equals:()=>!1});s.add(u,{name:"strategy"});let c=E(null,{name:"lastFeedback"});s.add(c,{name:"lastFeedback"});let d=E([],{name:"prevCandidates"});s.add(d,{name:"prevCandidates"});let l=E(!1,{name:"paused"});s.add(l,{name:"paused"});let p=E("running",{name:"status"});s.add(p,{name:"status"});let f=E([],{name:"history",equals:()=>!1});s.add(f,{name:"history"});let m=E(null,{name:"best"});s.add(m,{name:"best"});let g=E(Number.NEGATIVE_INFINITY,{name:"score"});s.add(g,{name:"score"});let h=E(0,{name:"budget-used"});s.add(h,{name:"budget-used"});let y=ao("stages");s.mount("stages",y);let b=y.topic("generate"),v=y.topic("evaluate"),T=y.topic("analyze"),w=y.topic("decide"),k=n,x=null,R=[];s.addDisposer(u.subscribe(re=>{for(let ge of re)ge[0]===S&&(k=ge[1])})),s.addDisposer(c.subscribe(re=>{for(let ge of re)ge[0]===S&&(x=ge[1])})),s.addDisposer(d.subscribe(re=>{for(let ge of re)ge[0]===S&&(R=ge[1])}));let N=Se(a,re=>{let ge=k,Oe=re===0||x==null;return U([],(le,K)=>{let ne=!1;try{let pe=Oe?ge.seed(t):ge.generate(x,R);if(pe instanceof Promise)return pe.then(V=>{ne||K.emit(V)},V=>{ne||K.down([[O,V]])}),()=>{ne=!0};K.emit(pe)}catch(pe){ne=!0,K.down([[O,pe]])}},{describeKind:"producer"})},{name:"candidates"});s.add(N,{name:"candidates"});let A=de([N],(re,ge,Oe)=>{let le=Oe.terminalDeps[0];le!==void 0&&le!==!0&&p.emit("errored")},{name:"error-watcher",errorWhenDepsError:!1});s.add(A,{name:"error-watcher"}),s.addDisposer(A.subscribe(()=>{}));let M=_([N,a],([re,ge])=>({iteration:ge,candidates:re,timestamp_ns:j()}),{name:"generate-event"});s.add(M,{name:"generate-event"}),s.addDisposer(M.subscribe(()=>{}));let I=de([M],([re])=>{b.publish(re)},{name:"generate-publish"});s.add(I,{name:"generate-publish"}),s.addDisposer(I.subscribe(()=>{}));let L=de([N],([re])=>{d.emit(re)},{name:"generate-mirror"});s.add(L,{name:"generate-mirror"}),s.addDisposer(L.subscribe(()=>{}));let P=e(N,i);s.add(P,{name:"scores"});let J=_([P,N,a],([re,ge,Oe])=>({iteration:Oe,candidates:ge,scores:re,timestamp_ns:j()}),{name:"evaluate-event"});s.add(J,{name:"evaluate-event"}),s.addDisposer(J.subscribe(()=>{}));let Q=de([J],([re])=>{v.publish(re)},{name:"evaluate-publish"});s.add(Q,{name:"evaluate-publish"}),s.addDisposer(Q.subscribe(()=>{}));let D=_([P,N],([re,ge])=>k.analyze(re,ge),{name:"feedback"});s.add(D,{name:"feedback"});let z=_([D,N,a],([re,ge,Oe])=>({iteration:Oe,candidates:ge,feedback:re,timestamp_ns:j()}),{name:"analyze-event"});s.add(z,{name:"analyze-event"}),s.addDisposer(z.subscribe(()=>{}));let W=de([z],([re])=>{T.publish(re)},{name:"analyze-publish"});s.add(W,{name:"analyze-publish"}),s.addDisposer(W.subscribe(()=>{}));let ie=_([f],([re])=>{let ge=re;if(r.patience==null||ge.length<=r.patience)return!1;let Oe=ge.slice(-(r.patience+1)),le=Oe[0].bestScore;return Oe.slice(1).every(K=>K.bestScore<=le)},{name:"patience-check"});s.add(ie,{name:"patience-check"});let B=_([g],([re])=>r.minScore!=null&&re>=r.minScore,{name:"min-score-check"});s.add(B,{name:"min-score-check"});let $=_([f],([re])=>{let ge=re;if(r.minDelta==null||ge.length<2)return!1;let Oe=ge[ge.length-2].bestScore,le=ge[ge.length-1].bestScore;return Math.abs(le-Oe)<r.minDelta},{name:"min-delta-check"});s.add($,{name:"min-delta-check"});let G=_([h],([re])=>r.maxEvaluations!=null&&re>=r.maxEvaluations,{name:"max-evaluations-check"});s.add(G,{name:"max-evaluations-check"});let q=_([a],([re])=>r.maxIterations!=null&&re>=r.maxIterations,{name:"max-iterations-check"});s.add(q,{name:"max-iterations-check"});let ce=_([h],([re])=>r.budget!=null&&re>=r.budget,{name:"budget-exhausted-check"});s.add(ce,{name:"budget-exhausted-check"}),s.addDisposer(ie.subscribe(()=>{})),s.addDisposer(B.subscribe(()=>{})),s.addDisposer($.subscribe(()=>{})),s.addDisposer(G.subscribe(()=>{})),s.addDisposer(q.subscribe(()=>{})),s.addDisposer(ce.subscribe(()=>{}));let he=_([ie,B,$,G,q],([re,ge,Oe,le,K])=>re?{converged:!0,reason:"patience"}:ge?{converged:!0,reason:"min-score"}:Oe?{converged:!0,reason:"min-delta"}:le?{converged:!0,reason:"max-evaluations"}:K?{converged:!0,reason:"max-iterations"}:{converged:!1},{name:"converged"});s.add(he,{name:"converged"}),s.addDisposer(he.subscribe(()=>{}));let xe=-1,oe=de([D,P,N],([re,ge,Oe])=>{let le=a.cache,K=re,ne=Oe,pe=ge;if(le<=xe)return;xe=le;let{best:V,bestScore:fe}=Lp(ne,pe),Ee=f.cache,Me={n:le,candidates:ne,scores:pe,feedback:K,best:V,bestScore:fe,timestamp_ns:j()},be=[...Ee,Me],Ge=h.cache+ne.length,we="continue",ke,lr=r.budget!=null&&Ge>=r.budget,Nn=l.cache;if(lr)we="budget",ke="budget";else if(r.minScore!=null&&K.score>=r.minScore)we="converged",ke="min-score";else if(r.maxIterations!=null&&le>=r.maxIterations)we="converged",ke="max-iterations";else if(r.maxEvaluations!=null&&Ge>=r.maxEvaluations)we="converged",ke="max-evaluations";else if(r.minDelta!=null&&be.length>=2){let So=be[be.length-2].bestScore,Di=be[be.length-1].bestScore;Math.abs(Di-So)<r.minDelta&&(we="converged",ke="min-delta")}else if(r.patience!=null&&be.length>r.patience){let So=be.slice(-(r.patience+1)),Di=So[0].bestScore;So.slice(1).every(Xp=>Xp.bestScore<=Di)&&(we="converged",ke="patience")}we==="continue"&&Nn&&(we="paused"),Z(()=>{m.emit(V),g.emit(K.score),f.emit(be),h.emit(Ge),c.emit(K),w.publish({iteration:le,decision:we,reason:ke,timestamp_ns:j()}),we==="continue"?a.emit(le+1):p.emit(we==="converged"?"converged":we==="budget"?"budget":"paused")})},{name:"decide-bridge"});return s.add(oe,{name:"decide-bridge"}),s.addDisposer(oe.subscribe(()=>{})),Object.assign(s,{best:m,score:g,status:p,history:f,strategy:u,iteration:a,generate:b,evaluate:v,analyze:T,decide:w,setStrategy(re){u.emit(re)},pause(){l.emit(!0)},resume(){p.cache==="paused"&&Z(()=>{l.emit(!1),p.emit("running"),a.emit(a.cache+1)})}})}function _y(t){let e=t.width??4;return{name:t.name??"blindVariation",seed(r){return[r]},analyze(r,o){let s=yu(r),i=null;for(let a of r)(!i||a.score<i.score)&&(i=a);return{summary:`blindVariation iteration: mean=${s.toFixed(3)}, n=${r.length}`,score:s,weakTasks:i?[i.taskId]:[]}},async generate(r,o){if(o.length===0)throw new Error("blindVariation.generate: empty candidate batch \u2014 cannot derive prior for teacher");let s=o[o.length-1],i=0,u={prior:s,reportCost:c=>{i+=c}};try{if(t.parallel!==!1)return await Promise.all(Array.from({length:e},()=>t.teacher(u)));let c=[];for(let d=0;d<e;d++)c.push(await t.teacher(u));return c}finally{if(t.tokens!=null&&i>0){let c=t.tokens.cache??0;t.tokens.emit(c+i)}}}}}function My(t){return typeof t=="object"&&t!==null&&t.kind==="errorCritique"}function Oy(t,e){return t.length===0?`No task scored below the batch mean (${e.score.toFixed(3)}). Reinforce the current direction.`:`Failures below threshold:
218
- ${t.map(r=>{let o=r.error!=null?` | error: ${r.error}`:"";return`- ${r.taskId} (score=${r.score.toFixed(3)})${o}`}).join(`
219
- `)}`}function Cy(t){let e=t.width??4,n=t.name??"errorCritique",r=t.maxFailureSamples??5,o=t.formatCritique??Oy;return{name:n,seed(s){return[s]},analyze(s,i){let a=yu(s),u=typeof t.failureThreshold=="function"?t.failureThreshold(s):t.failureThreshold,c=u===void 0&&!Number.isFinite(a),d=u??a,l=c?[...s].sort((v,T)=>v.score-T.score):s.filter(v=>v.score<d).slice().sort((v,T)=>v.score-T.score),p=l.slice(0,r),{best:f,bestScore:m}=Lp(i,s),g={summary:"",score:a,weakTasks:p.map(v=>v.taskId)},h=o(p,g),y={kind:"errorCritique",best:f,failures:p,critiqueText:h},b=l.length>p.length?` (top ${p.length} retained)`:"";return{summary:`errorCritique iteration: mean=${a.toFixed(3)}, failures=${l.length}${b}/${s.length}, bestScore=${m.toFixed(3)}`,critique:y,weakTasks:p.map(v=>v.taskId),score:a}},async generate(s,i){if(i.length===0)throw new Error("errorCritique.generate: empty candidate batch \u2014 cannot derive prior for teacher");let a=My(s.critique)?s.critique:void 0,u=a!==void 0?a.best:i[i.length-1],c=a?.critiqueText??s.summary,d=a?.failures??[],l=0,f={prior:u,critique:c,failures:d,reportCost:m=>{l+=m}};try{if(t.parallel!==!1)return await Promise.all(Array.from({length:e},()=>t.teacher(f)));let m=[];for(let g=0;g<e;g++)m.push(await t.teacher(f));return m}finally{if(t.tokens!=null&&l>0){let m=t.tokens.cache??0;t.tokens.emit(m+l)}}}}}function Ay(t){let{best:e,score:n,status:r}=t,o=Number.isFinite(n)?n.toFixed(3):String(n),s=e??void 0;return r==="converged"?{outcome:"success",detail:`refineLoop converged at score ${o}`,artifact:s}:r==="budget"?{outcome:"partial",detail:`refineLoop hit budget at score ${o}`,artifact:s}:{outcome:"failure",detail:`refineLoop errored (status=${r})`,artifact:s}}function vu(t){let e=t.name??"refine-executor",n=t.toOutput??Ay;return r=>{let o=it(r,i=>i!=null,{name:`${e}/gate-in`}),s=Se(o,i=>{let a=bu(t.seedFrom(i),t.evaluator,t.strategy,{...t.refine,dataset:t.datasetFor(i),name:`${e}/inner`});return _([a.status,a.best,a.score],([u,c,d])=>{let l=u;return l!=="converged"&&l!=="budget"&&l!=="errored"?null:n({best:c,score:d,status:l})},{name:`${e}/output`})},{name:e});return it(s,i=>i!=null,{name:`${e}/gate-out`})}}function Ly(t){if(t.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let n of t)e+=n.score;return e/t.length}function Iy(t){let{passCount:e,total:n,meanScore:r,threshold:o,missingArtifact:s}=t,i=Number.isFinite(r)?r.toFixed(3):String(r),a=!s&&n>0&&r>=o,u=s?["EXECUTE stage did not emit an artifact; cannot verify reactively"]:a?[`${e}/${n} eval tasks passed; mean score ${i} \u2265 ${o}`]:n===0?["No eval tasks were selected for this item \u2014 cannot verify"]:[`${e}/${n} eval tasks passed; mean score ${i} < threshold ${o}`];return a?{verified:!0,findings:u}:{verified:!1,findings:u,errorClass:"structural"}}function Dy(t){return t.artifact??null}function Ip(t){let e=t.name??"eval-verifier",n=t.threshold??.5,r=t.toOutput??Iy,o=t.extractArtifact??Dy;return s=>{let i=it(s,u=>u!=null&&u[0]!=null&&u[1]!=null,{name:`${e}/gate-in`}),a=Se(i,u=>{let[c,d]=u,l=o(c,d);if(l==null)return E(r({scores:[],meanScore:Number.NEGATIVE_INFINITY,passCount:0,total:0,threshold:n,missingArtifact:!0}));let p=E([l],{name:`${e}/candidates`}),f=E(t.datasetFor(d),{name:`${e}/dataset`}),m=t.evaluator(p,f);return _([m],([g])=>{let h=g;if(h==null)return null;let y=Ly(h),b=h.filter(v=>v.score>=n).length;return r({scores:h,meanScore:y,passCount:b,total:h.length,threshold:n})},{name:`${e}/output`})},{name:e});return it(a,u=>u!=null,{name:`${e}/gate-out`})}}function Py(t){let e=t.name??"harness-pair",n=vu({name:`${e}-exec`,seedFrom:t.seedFrom,evaluator:t.evaluator,strategy:t.strategy,datasetFor:t.datasetFor,refine:t.refine}),r=Ip({name:`${e}-verify`,evaluator:t.evaluator,datasetFor:t.datasetFor,threshold:t.threshold});return{executor:n,verifier:r}}_e();Le();ee();var vi={};Ne(vi,{JobFlowGraph:()=>yi,JobQueueGraph:()=>gi,jobFlow:()=>Fy,jobQueue:()=>bi});Le();var Gy=2147483647;function Dp(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Tu(t,e){return ze("job_queue",t,e)}var gi=class extends Y{_pending;_jobs;_seq=0;pending;jobs;depth;constructor(e,n={}){super(e,n.graph),this._pending=Ms([],{name:"pending"}),this._jobs=Xe({name:"jobs"}),this.pending=this._pending.items,this.jobs=this._jobs.entries,this.add(this.pending,{name:"pending"}),this.add(this.jobs,{name:"jobs"}),this.depth=_([this.pending],([r])=>r.length,{name:"depth",describeKind:"derived",meta:Tu("queue_depth"),initial:0}),this.add(this.depth,{name:"depth"}),this.addDisposer(se(this.depth))}enqueue(e,n={}){let r=n.id??`${this.name}-${++this._seq}`;if(this._jobs.get(r)!==void 0)throw new Error(`jobQueue("${this.name}"): duplicate job id "${r}"`);let o={id:r,payload:e,attempts:0,metadata:Object.freeze({...n.metadata??{}}),state:"queued"};return this._jobs.set(r,o),this._pending.append(r),r}claim(e=1){let n=Dp(e,"job queue claim limit");if(n===0)return[];let r=[];for(;r.length<n&&this.pending.cache.length!==0;){let s=this._pending.pop(0),i=this._jobs.get(s);if(!i||i.state!=="queued")continue;let a={...i,state:"inflight",attempts:i.attempts+1};this._jobs.set(s,a),r.push(a)}return r}ack(e){let n=this._jobs.get(e);return!n||n.state!=="inflight"?!1:(this._jobs.delete(e),!0)}nack(e,n={}){let r=this._jobs.get(e);return!r||r.state!=="inflight"?!1:n.requeue??!0?(this._jobs.set(e,{...r,state:"queued"}),this._pending.append(e),!0):(this._jobs.delete(e),!0)}removeById(e){let n=this._jobs.get(e);if(!n)return!1;if(n.state==="queued"){let o=this.pending.cache.indexOf(e);o>=0&&this._pending.pop(o)}return this._jobs.delete(e),!0}},yi=class extends Y{_stageNames;_queues=new Map;_completed;completed;completedCount;constructor(e,n={}){super(e,n.graph);let r=(n.stages??["incoming","processing","done"]).map(i=>i.trim());if(r.length<2)throw new Error(`jobFlow("${e}"): requires at least 2 stages`);if(new Set(r).size!==r.length)throw new Error(`jobFlow("${e}"): stage names must be unique`);this._stageNames=Object.freeze([...r]);for(let i of this._stageNames){let a=bi(`${e}-${i}`);this._queues.set(i,a),this.mount(i,a)}this._completed=Ue([],{name:"completed"}),this.completed=this._completed.entries,this.add(this.completed,{name:"completed"}),this.completedCount=_([this.completed],([i])=>i.length,{name:"completedCount",describeKind:"derived",meta:Tu("job_flow_completed_count"),initial:0}),this.add(this.completedCount,{name:"completedCount"}),this.addDisposer(se(this.completedCount));let s=Math.max(1,Dp(n.maxPerPump??Gy,"job flow maxPerPump"));for(let i=0;i<this._stageNames.length;i+=1){let a=this._stageNames[i],u=this.queue(a),c=i+1<this._stageNames.length?this.queue(this._stageNames[i+1]):null,d=U([u.pending],()=>{let l=0;for(;l<s;){let p=u.claim(1);if(p.length===0)break;let f=p[0];if(!f)break;c?c.enqueue(f.payload,{metadata:{...f.metadata,job_flow_from:a}}):this._completed.append(f),u.ack(f.id),l+=1}},{name:`pump_${a}`,describeKind:"effect",meta:Tu("job_flow_pump")});this.add(d,{name:`pump_${a}`}),this.addDisposer(se(d))}}stages(){return this._stageNames}queue(e){let n=this._queues.get(e);if(!n)throw new Error(`jobFlow("${this.name}"): unknown stage "${e}"`);return n}enqueue(e,n={}){return this.queue(this._stageNames[0]).enqueue(e,n)}retainedCompleted(){return this.completed.cache}};function bi(t,e){return new gi(t,e)}function Fy(t,e){return new yi(t,e)}_e();ee();function wu(){let t=Xe({name:"strategy-entries"}),e=_([t.entries],([i])=>{let a=i;return new Map(a)},{name:"strategy-model",equals:(i,a)=>{let u=i,c=a;if(u.size!==c.size)return!1;for(let[d,l]of u){let p=c.get(d);if(!p||l.attempts!==p.attempts||l.successes!==p.successes)return!1}return!0}});function n(i,a,u){let c=cr(i,a),d=t.get(c),l=(d?.attempts??0)+1,p=(d?.successes??0)+(u?1:0);t.set(c,{rootCause:i,intervention:a,attempts:l,successes:p,successRate:p/l})}function r(i,a){return t.get(cr(i,a))}let o=e.subscribe(()=>{});function s(){o()}return{node:e,record:n,lookup:r,dispose:s}}function $y(t,e,n,r,o){let s={...ar,...o?.severityWeights},i=o?.decayRate??ur,a=o?.effectivenessThreshold??.7,u=o?.effectivenessBoost??15,c=[t,e,n];return r&&c.push(r),_(c,d=>{let l=d[0],p=d[1],f=d[2],m=r?d[3]:0,g=s[l.severity??"medium"],h=(j()-f)/1e9,y=Pt(g,h,i,0),b=cr(l.rootCause,l.intervention),v=p.get(b);return v&&v.successRate>=a&&(y+=u),y+=m*20,y},{name:"priority-score"})}var Pp="intake",jy="triage-output",Gp="retry",Fp="verify-results",$p="__unrouted";function jp(t,e){let n=wo(e,hu,(r,o)=>r.replace("{{item}}",JSON.stringify(o)));return r=>kn(t,[r],n,{name:"execute",format:"json"})}function Bp(t,e){let n=wo(e,gu,(r,o)=>{let[s,i]=o;return r.replace("{{execution}}",JSON.stringify(s)).replace("{{item}}",JSON.stringify(i))});return r=>kn(t,[r],o=>o==null?"":n(o),{name:"verify",format:"json"})}var Ti=class extends Y{queues;jobs;gates;strategy;totalRetries;totalReingestions;priorityScores;constructor(e,n,r,o,s,i,a,u){super(e),this.queues=n,this.jobs=r,this.gates=o,this.strategy=s,this.totalRetries=i,this.totalReingestions=a,this.priorityScores=u}get intake(){return this.queues.topic(Pp)}get verifyResults(){return this.queues.topic(Fp)}get retry(){return this.queues.topic(Gp)}get unrouted(){return this.queues.topic($p)}stageNodes(){let e=this.queues,n=i=>e.has(i)?`queues::${i}::latest`:null,r=i=>i==null?[]:[i],o=ot.flatMap(i=>r(n(i))),s=[];for(let[i]of this.gates)s.push(`gates::${i}/gate`);return[{label:"INTAKE",paths:r(n("intake"))},{label:"TRIAGE",paths:["triage"]},{label:"QUEUE",paths:o},{label:"GATE",paths:s},{label:"EXECUTE",paths:["execute"]},{label:"VERIFY",paths:r(n("verify-results"))},{label:"REFLECT",paths:["reflect"]},{label:"STRATEGY",paths:["strategy"]}]}};function By(t,e){let n=e.adapter,r=e.maxRetries??2,o=e.retainedLimit??1e3,s=e.errorClassifier??mi,i=new Map;for(let K of ot)i.set(K,{...fi[K],...e.queues?.[K]});let a=ao(`${t}/queues`,{defaultTopicOptions:{retainedLimit:o}}),u=a.topic(Pp),c=a.topic(jy),d=a.topic(Gp),l=a.topic(Fp),p=new Map;for(let K of ot)p.set(K,a.topic(K));let f=a.topic($p),m=wu(),g=At(u.latest,m.node),h=wo(e.triagePrompt,mu,(K,ne)=>{let[pe,V]=ne;return K.replace("{{strategy}}",JSON.stringify(Array.from(V.entries()))).replace("{{item}}",JSON.stringify(pe))}),y=kn(n,[g],K=>{let ne=K;return!ne||!ne[0]?"":h(ne)},{name:"triage",format:"json"}),b=At(y,g),T=de([b],([K])=>{if(K==null)return;let[ne,pe]=K;if(!ne?.route)return;let V=pe?.[0],fe={...ne,...V};c.publish(fe)}).subscribe(()=>{}),w=new Set(ot);for(let K of ot)Us(`bridge/${K}`,c,p.get(K),{map:ne=>ne.route===K?ne:void 0});Us("bridge/__unrouted",c,f,{map:K=>w.has(K.route)?void 0:K});let k=new Map,x=new Map;for(let K of ot)k.set(K,bi(`jobs/${K}`));let R=[];for(let K of ot){let ne=p.get(K),pe=k.get(K),V=new WeakSet,fe=de([ne.events],([Ee])=>{let Me=Ee??[];for(let be of Me){if(V.has(be))continue;V.add(be);let Ge=pe.enqueue(be);x.set($r(be),{route:K,id:Ge})}},{name:`jobs/${K}-mirror`});R.push(fe.subscribe(()=>{}))}function N(K){let ne=$r(K),pe=x.get(ne);pe&&(k.get(pe.route)?.removeById(pe.id),x.delete(ne))}let A=new Y("gates"),M=new Map;for(let K of ot){let ne=i.get(K);if(!ne.gated)continue;let pe=p.get(K);A.add(pe.latest,{name:`${K}/source`});let V=uo(A,`${K}/gate`,`${K}/source`,{maxPending:ne.maxPending,startOpen:ne.startOpen});M.set(K,V)}let I=[];for(let K of ot)i.get(K).gated&&M.has(K)?I.push(M.get(K).node):I.push(p.get(K).latest);I.push(d.latest);let L=wt(...I),J=(e.executor??jp(n,e.executePrompt))(L),Q=At(J,L),z=(e.verifier??Bp(n,e.verifyPrompt))(Q),W=At(z,Q),ie=e.maxReingestions??1,B=Math.min(e.maxTotalRetries??r*10,100),$=Math.min(e.maxTotalReingestions??ie*10,100),G=E(0),q=E(0);function ce(K,ne,pe){let V={item:pe,outcome:ne?.outcome??"failure",detail:ne?.detail??"unknown",artifact:ne?.artifact};return{item:pe,execution:V,verified:K.verified,findings:K.findings??[],errorClass:K.errorClass}}function he(K,ne){m.record(ne.rootCause,ne.intervention,!0),l.publish(K),N(ne)}function xe(K,ne){let pe=$r(ne),V=ne.$retries??0,fe={...ne,$retries:V+1,summary:`[RETRY ${V+1}/${r}] ${pe} \u2014 Previous attempt failed: ${K.findings.join("; ")}`,relatedTo:[pe]};d.publish(fe)}function oe(K,ne){m.record(ne.rootCause,ne.intervention,!1),l.publish(K),N(ne);let pe=$r(ne),V=ne.$reingestions??0;V<ie&&Fr(q,$)&&u.publish({source:ne.source,summary:`Verification failed for: ${pe}`,evidence:K.findings.join(`
220
- `),affectsAreas:ne.affectsAreas,affectsEvalTasks:ne.affectsEvalTasks,severity:ne.severity??"high",relatedTo:[pe],$reingestions:V+1})}let ye=U([W],(K,ne)=>{let pe=K[0];if(pe==null||pe.length===0)return;let V=pe[pe.length-1];if(V==null)return;let[fe,Ee]=V,[Me,be]=Ee??[null,null];if(!fe||!be)return;if(Me==null){oe({item:be,execution:{item:be,outcome:"failure",detail:"executor returned null"},verified:!1,findings:["executor returned null"],errorClass:"structural"},be);return}let Ge=ce(fe,Me,be);if(Ge.verified){he(Ge,be);return}let we=Ge.errorClass??s({item:be,outcome:Me.outcome,detail:Ge.findings.join("; ")}),ke=be.$retries??0;we==="self-correctable"&&ke<r&&Fr(G,B)?xe(Ge,be):oe(Ge,be)}),re=ye.subscribe(()=>{}),ge=_([ye],()=>null,{name:"reflect",equals:()=>!1}),Oe;e.priority&&(Oe=Vy(p,m,e));let le=new Ti(t,a,k,M,m,G,q,Oe);le.addDisposer(T),le.addDisposer(re),le.addDisposer(m.dispose);for(let K of R)le.addDisposer(K);if(le.add(y,{name:"triage"}),le.add(L,{name:"execute-input"}),le.add(J,{name:"execute"}),le.add(Q,{name:"execute-context"}),le.add(z,{name:"verify"}),le.add(W,{name:"verify-context"}),le.add(ye,{name:"verify-dispatch"}),le.add(ge,{name:"reflect"}),le.add(m.node,{name:"strategy"}),le.addDisposer(ge.subscribe(()=>{})),Oe)for(let[K,ne]of Oe)le.add(ne,{name:`priority/${K}`}),le.addDisposer(ne.subscribe(()=>{}));le.mount("queues",a),le.mount("gates",A);for(let[K,ne]of k)le.mount(`jobs/${K}`,ne);return le}function Vy(t,e,n){if(!n.lastInteractionNs)throw new Error("harnessLoop: `opts.priority` requires `opts.lastInteractionNs` \u2014 pass a Node<number> (e.g. `fromTimer(60_000)` or a `state(monotonicNs())` you bump on human interaction). Priority scores only decay when this node settles; an internal default would freeze age at construction time.");let r=n.lastInteractionNs,o=n.priority??{},s={...ar,...o.severityWeights},i=o.decayRate??ur,a=o.effectivenessThreshold??.7,u=o.effectivenessBoost??15,c=new Map;for(let[d,l]of t){let p=_([l.latest,e.node,r],f=>{let m=f[0];if(m==null)return 0;let g=s[m.severity??"medium"]??40,h=(j()-f[2])/1e9,y=g*Math.exp(-i*Math.max(0,h)),b=`${m.rootCause}\u2192${m.intervention}`,T=f[1]?.get(b);return T&&T.successRate>=a&&(y+=u),y},{name:`priority/${d}`});c.set(d,p)}return c}function Ky(t,e){let n=fn(t,e),r={};for(let o of ot){let s=t.queues.has(o)?t.queues.topic(o):null;r[o]=s?.retained().length??0}return{...n,queueDepths:r,strategyEntries:t.strategy.node.cache?.size??0,totalRetries:t.totalRetries.cache??0,totalReingestions:t.totalReingestions.cache??0}}_e();function Hy(t){let e={};for(let{label:n,paths:r}of t.stageNodes())for(let o of r)e[o]=n;return e}function Wy(t,e){let n=e?.logger===null?null:e?.logger??console.log,r=e?.detail??"summary",o=j(),s=[],i=[],a=Hy(t);function u(){return(j()-o)/1e9}function c(d,l,p){let f={elapsed:u(),stage:d,type:l};r!=="summary"&&(f.summary=qy(p)),r==="full"&&(f.data=p),i.push(f)}for(let[d,l]of Object.entries(a))try{let p=t.observe(d,{format:"stage-log",stageLabels:a,logger:n?f=>n(f):()=>{},includeTypes:["data","error","complete"]});p.onEvent(f=>{f.type==="data"?c(l,"data",f.data):f.type==="error"?c(l,"error",f.data):f.type==="complete"&&c(l,"complete",void 0)}),s.push(p)}catch(p){let f=p instanceof Error?p.message:String(p);c(l,"error",`observe-unavailable: ${d} \u2014 ${f}`),n&&n(`[${u().toFixed(3)}s] ${l.padEnd(9)} \u2717 observe-unavailable: ${f}`)}return{get events(){return i},dispose(){for(let d of s)d.dispose();s.length=0}}}function qy(t){if(t==null)return"null";if(typeof t=="string")return Vp(t,80);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return Vp(e,120)}catch{return String(t)}}function Vp(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}var xi={};Ne(xi,{LensGraph:()=>ki,graphLens:()=>Qy,watchTopologyTree:()=>Mt});_e();ee();function Kp(t){return ze("lens",t)}function Uy(t){let e=Object.keys(t.nodes),n=new Map,r=new Map;for(let g of e){let h=t.nodes[g]?.deps??[];n.set(g,h);for(let y of h)r.has(y)||r.set(y,new Set),r.get(y).add(g)}let o=[],s=[];for(let g of e)(n.get(g)??[]).length===0&&o.push(g),r.has(g)||s.push(g);o.sort(),s.sort();let i=t.edges.length,a=0,u=1,c=2,d=new Map;for(let g of e)d.set(g,a);let l=!1,p=new Map,f=g=>{let h=d.get(g)??a;if(h===u)return l=!0,0;if(h===c)return p.get(g)??0;d.set(g,u);let y=0,b=r.get(g);if(b!=null)for(let v of b){let T=f(v);T+1>y&&(y=T+1)}return d.set(g,c),p.set(g,y),y},m=0;for(let g of o){let h=f(g);h>m&&(m=h)}for(let g of e)d.get(g)===a&&f(g);return{nodeCount:e.length,edgeCount:i,subgraphCount:t.subgraphs.length,sources:o,sinks:s,depth:m,hasCycles:l}}function zy(t){let e=[];for(let[n,r]of Object.entries(t.nodes)){if(r.status!=="errored")continue;let o={path:n,status:"errored"},s=mn(t,n,"upstream",{});for(let i of s)if(i!==n&&t.nodes[i]?.status==="errored"){o.upstreamCause=i;break}e.push(o)}return e.sort((n,r)=>n.path<r.path?-1:n.path>r.path?1:0),{ok:e.length===0,problems:e}}function Jy(t,e){return t.nodeCount===e.nodeCount&&t.edgeCount===e.edgeCount&&t.subgraphCount===e.subgraphCount&&t.depth===e.depth&&t.hasCycles===e.hasCycles&&Hp(t.sources,e.sources)&&Hp(t.sinks,e.sinks)}function Yy(t,e){if(t.ok!==e.ok||t.problems.length!==e.problems.length)return!1;for(let n=0;n<t.problems.length;n++){let r=t.problems[n],o=e.problems[n];if(r.path!==o.path||r.status!==o.status||r.upstreamCause!==o.upstreamCause)return!1}return!0}function Hp(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}var ki=class extends Y{stats;health;flow;_target;constructor(e,n={}){super(n.name??`${e.name}_lens`,n.graph),this._target=e;let r=0,o=0,s=E(0,{name:"stats_tick"}),i=E(0,{name:"health_tick"});this.add(s,{name:"stats_tick"}),this.add(i,{name:"health_tick"});let a={name:"flow"};n.maxFlowPaths!=null&&(a.maxSize=n.maxFlowPaths),this.flow=Xe(a),this.add(this.flow.entries,{name:"flow"});let u=n.pathFilter,c=Mt(e,(p,f,m)=>{if(r+=1,s.emit(r),o+=1,i.emit(o),p.kind==="removed")if(p.nodeKind==="node"){let g=`${m}${p.name}`;this.flow.delete(g)}else{let g=`${m}${p.name}::`,h=[];for(let y of p.audit.nodes){let b=y===""?`${m}${p.name}`:`${g}${y}`;h.push(b)}h.length>0&&this.flow.deleteMany(h)}});this.addDisposer(c);let d=e.observe({timeline:!0,structured:!0}),l=d.onEvent(p=>{let f=p.type;if((f==="error"||f==="complete"||f==="data"||f==="teardown")&&(o+=1,i.emit(o)),f==="data"){let m=p.path??"";if(!m||u!=null&&!u(m))return;let g=this.flow.get(m),h=g!=null?g.count+1:1;this.flow.set(m,{path:m,count:h,lastUpdate_ns:j()})}});this.addDisposer(()=>{l(),d.dispose()}),this.stats=_([s],()=>Uy(e.describe({detail:"minimal"})),{name:"stats",describeKind:"derived",equals:Jy,meta:Kp("stats")}),this.add(this.stats,{name:"stats"}),this.addDisposer(se(this.stats)),this.health=_([i],()=>zy(e.describe({detail:"standard"})),{name:"health",describeKind:"derived",equals:Yy,meta:Kp("health")}),this.add(this.health,{name:"health"}),this.addDisposer(se(this.health))}why(e,n,r){let o=uu(this._target,e,n,r);return this.addDisposer(o.dispose),o}get target(){return this._target}};function Qy(t,e){return new ki(t,e)}var Ri={};Ne(Ri,{CanvasMeasureAdapter:()=>Su,CliMeasureAdapter:()=>ku,ImageSizeAdapter:()=>_u,NodeCanvasMeasureAdapter:()=>Nu,PrecomputedAdapter:()=>Ru,SvgBoundsAdapter:()=>Eu,analyzeAndMeasure:()=>Gt,carveTextLineSlots:()=>pu,circleIntervalForBand:()=>Jp,computeBlockFlow:()=>Up,computeCharPositions:()=>ui,computeFlowLines:()=>Qp,computeLineBreaks:()=>Sn,computeTotalHeight:()=>zp,layoutNextLine:()=>lu,measureBlock:()=>Wp,measureBlocks:()=>qp,reactiveBlockLayout:()=>Xy,reactiveFlowLayout:()=>eb,reactiveLayout:()=>py,rectIntervalForBand:()=>Yp});var ku=class{cellPx;constructor(e){this.cellPx=e?.cellPx??8}measureSegment(e,n){return{width:Qn(e)*this.cellPx}}},xu=class extends Error{name="KeyError"},Ru=class{metrics;fallback;constructor(e){this.metrics=e.metrics;let n=e.fallback??"per-char";if(n!=="per-char"&&n!=="error")throw new Error(`fallback must be 'per-char' or 'error', got ${JSON.stringify(e.fallback)}`);this.fallback=n}measureSegment(e,n){let r=this.metrics[n];if(r){let s=r[e];if(s!==void 0)return{width:s}}if(this.fallback==="error")throw new xu(`PrecomputedAdapter: no metrics for segment ${JSON.stringify(e)} in font ${JSON.stringify(n)}`);let o=0;if(r)for(let s of e){let i=r[s];i!==void 0&&(o+=i)}return{width:o}}},Su=class{ctx=null;currentFont="";emojiCorrection;constructor(e){this.emojiCorrection=e?.emojiCorrection??1}getContext(){if(!this.ctx){if(typeof OffscreenCanvas>"u")throw new Error("CanvasMeasureAdapter requires a browser environment with OffscreenCanvas support. Use CliMeasureAdapter or NodeCanvasMeasureAdapter for Node.js.");let n=new OffscreenCanvas(0,0).getContext("2d");if(!n)throw new Error("CanvasMeasureAdapter: failed to get 2d context");this.ctx=n}return this.ctx}measureSegment(e,n){let r=this.getContext();n!==this.currentFont&&(r.font=n,this.currentFont=n);let o=r.measureText(e).width;return this.emojiCorrection!==1&&new RegExp("\\p{Emoji_Presentation}","u").test(e)&&(o*=this.emojiCorrection),{width:o}}clearCache(){this.currentFont=""}},Nu=class{ctx=null;currentFont="";canvasModule;constructor(e){this.canvasModule=e}getContext(){if(!this.ctx){let n=this.canvasModule.createCanvas(0,0).getContext("2d");if(!n)throw new Error("NodeCanvasMeasureAdapter: failed to get 2d context");this.ctx=n}return this.ctx}measureSegment(e,n){let r=this.getContext();return n!==this.currentFont&&(r.font=n,this.currentFont=n),{width:r.measureText(e).width}}clearCache(){this.currentFont=""}},Eu=class{measureSvg(e){let n=e.match(/viewBox\s*=\s*["']([^"']+)["']/);if(n){let s=n[1].trim().split(/[\s,]+/);if(s.length>=4){let i=Number.parseFloat(s[2]),a=Number.parseFloat(s[3]);if(Number.isFinite(i)&&Number.isFinite(a)&&i>0&&a>0)return{width:i,height:a};throw new Error("SvgBoundsAdapter: viewBox width/height are missing, non-finite, or not positive")}}let r=e.match(/<svg[^>]*\bwidth\s*=\s*["']?([\d.]+)/),o=e.match(/<svg[^>]*\bheight\s*=\s*["']?([\d.]+)/);if(r&&o){let s=Number.parseFloat(r[1]),i=Number.parseFloat(o[1]);if(Number.isFinite(s)&&Number.isFinite(i)&&s>0&&i>0)return{width:s,height:i};throw new Error("SvgBoundsAdapter: svg width/height attributes are non-finite or not positive")}throw new Error("SvgBoundsAdapter: cannot determine dimensions \u2014 SVG has no viewBox or width/height attributes")}},_u=class{sizes;constructor(e){this.sizes=new Map(Object.entries(e))}measureImage(e){let n=this.sizes.get(e);if(!n)throw new Error(`ImageSizeAdapter: no dimensions registered for ${JSON.stringify(e)}`);return{width:n.width,height:n.height}}};_e();Le();ee();function Wp(t,e,n,r,o,s,i){switch(t.type){case"text":{let a=t.font??o,u=t.lineHeight??s,c=Gt(t.text,a,n.text,r),d=Sn(c,e,n.text,a,r),l=ui(d,c,u),p=d.lineCount*u,f=0;for(let m of d.lines)m.width>f&&(f=m.width);return{index:i,type:"text",width:Math.min(f,e),height:p,textSegments:c,textLineBreaks:d,textCharPositions:l}}case"image":{let a,u;if(t.naturalWidth!=null&&t.naturalHeight!=null)a=t.naturalWidth,u=t.naturalHeight;else if(n.image){let c=n.image.measureImage(t.src);a=c.width,u=c.height}else throw new Error(`Image block at index ${i} has no naturalWidth/naturalHeight and no ImageMeasurer adapter`);return a>e&&(u=u*e/a,a=e),{index:i,type:"image",width:a,height:u}}case"svg":{let a,u;if(t.viewBox)a=t.viewBox.width,u=t.viewBox.height;else if(n.svg){let c=n.svg.measureSvg(t.content);a=c.width,u=c.height}else throw new Error(`SVG block at index ${i} has no viewBox and no SvgMeasurer adapter`);return a>e&&(u=u*e/a,a=e),{index:i,type:"svg",width:a,height:u}}}}function qp(t,e,n,r,o,s){return t.map((i,a)=>Wp(i,e,n,r,o,s,a))}function Up(t,e){let n=[],r=0;for(let o=0;o<t.length;o++){let s=t[o];n.push({...s,x:0,y:r}),r+=s.height+(o<t.length-1?e:0)}return n}function zp(t){if(t.length===0)return 0;let e=t[t.length-1];return e.y+e.height}function Xy(t){let{adapters:e,name:n="reactive-block-layout",defaultFont:r="16px sans-serif",defaultLineHeight:o=20}=t,s=new Y(n),i=new Map,a=E(t.blocks??[],{name:"blocks"}),u=E(Math.max(0,t.maxWidth??800),{name:"max-width"}),c=E(t.gap??0,{name:"gap"}),d=U([a,u],(f,m,g)=>{let h=f[0]!=null&&f[0].length>0?f[0].at(-1):g.prevData[0],y=f[1]!=null&&f[1].length>0?f[1].at(-1):g.prevData[1],b=j(),v=qp(h,y,e,i,r,o),T=j()-b,w=d.meta;w&&(ft(w["block-count"],v.length),ft(w["layout-time-ns"],T)),m.emit(v);let k=()=>{i.clear(),e.text.clearCache?.()};return{deactivate:k,invalidate:k}},{name:"measured-blocks",describeKind:"derived",meta:{"block-count":0,"layout-time-ns":0},equals:(f,m)=>{let g=f,h=m;if(g==null||h==null)return g===h;if(g.length!==h.length)return!1;for(let y=0;y<g.length;y++){let b=g[y],v=h[y];if(b.type!==v.type||b.width!==v.width||b.height!==v.height||b.index!==v.index)return!1}return!0}}),l=_([d,c],([f,m])=>Up(f,m),{name:"block-flow",equals:(f,m)=>{let g=f,h=m;if(g==null||h==null)return g===h;if(g.length!==h.length)return!1;for(let y=0;y<g.length;y++){let b=g[y],v=h[y];if(b.x!==v.x||b.y!==v.y||b.width!==v.width||b.height!==v.height)return!1}return!0}}),p=_([l],([f])=>zp(f),{name:"total-height"});return s.add(a,{name:"blocks"}),s.add(u,{name:"max-width"}),s.add(c,{name:"gap"}),s.add(d,{name:"measured-blocks"}),s.add(l,{name:"block-flow"}),s.add(p,{name:"total-height"}),{graph:s,setBlocks:f=>s.set("blocks",f),setMaxWidth:f=>s.set("max-width",Math.max(0,f)),setGap:f=>s.set("gap",f),measuredBlocks:d,blockFlow:l,totalHeight:p}}_e();Le();ee();function Jp(t,e,n){let r=t.hPad??0,o=t.vPad??0,s=e-o,i=n+o;if(s>=t.cy+t.r||i<=t.cy-t.r)return null;let a=t.cy>=s&&t.cy<=i?0:t.cy<s?s-t.cy:t.cy-i;if(a>=t.r)return null;let u=Math.sqrt(t.r*t.r-a*a);return{left:t.cx-u-r,right:t.cx+u+r}}function Yp(t,e,n){let r=t.hPad??0,o=t.vPad??0;return n<=t.y-o||e>=t.y+t.h+o?null:{left:t.x-r,right:t.x+t.w+r}}function Zy(t,e,n){return t.kind==="circle"?Jp(t,e,n):Yp(t,e,n)}function Qp(t,e,n,r,o,s,i){let a=i?.paragraphSpacing??o,u=[],c={segmentIndex:0,graphemeIndex:0};if(t.length===0||n.count<=0||o<=0)return{lines:u,cursor:c};let d=e.paddingX??0,l=e.paddingY??0,p=Math.max(0,e.width-d*2),f=Math.max(0,e.height-l*2),m=n.gap*Math.max(0,n.count-1),g=Math.max(0,(p-m)/n.count);if(g<=0)return{lines:u,cursor:c};e:for(let h=0;h<n.count;h++){let y=d+h*(g+n.gap),b=y+g,v=l;for(;v+o<=l+f;){let T=v+o,w=[];for(let R=0;R<r.length;R++){let N=Zy(r[R],v,T);N!==null&&w.push(N)}let k=pu({left:y,right:b},w,s);if(k.length===0){v+=o;continue}let x=!1;for(let R=0;R<k.length;R++){let N=k[R],A=N.right-N.left,M=lu(t,c,A);if(M===null)return{lines:u,cursor:c};if(M.text.length===0&&M.width===0){c=M.end,x=!0;break}u.push({x:N.left,y:v,width:M.width,slotWidth:A,text:M.text,columnIndex:h,flushToRight:N.right<b-.5}),c=M.end}if(x){v+=a;continue}if(v+=o,c.segmentIndex>=t.length)break e}if(c.segmentIndex>=t.length)break}return{lines:u,cursor:c}}function eb(t){let{adapter:e,name:n="reactive-flow-layout",minSlotWidth:r=20}=t,o=new Y(n),s=new Map,i=E(t.text??"",{name:"text"}),a=E(t.font??"16px sans-serif",{name:"font"}),u=E(t.lineHeight??20,{name:"line-height"}),c=E(t.container??{width:800,height:600,paddingX:0,paddingY:0},{name:"container"}),d=E(t.columns??{count:1,gap:0},{name:"columns"}),l=E(t.obstacles??[],{name:"obstacles"}),p=E(t.paragraphSpacing??null,{name:"paragraph-spacing"}),f=U([i,a],(g,h,y)=>{let b=g[0],v=b!=null&&b.length>0?b.at(-1):y.prevData[0],T=g[1],w=T!=null&&T.length>0?T.at(-1):y.prevData[1],k=Gt(v,w,e,s);h.emit(k);let x=()=>{s.clear(),e.clearCache?.()};return{deactivate:x,invalidate:x}},{name:"segments",describeKind:"derived"}),m=_([f,c,d,l,u,p],([g,h,y,b,v,T])=>{let w=g,k=j(),x=T??v,{lines:R,cursor:N}=Qp(w,h,y,b,v,r,{paragraphSpacing:x}),A=j()-k,M=Math.max(0,w.length-N.segmentIndex),I=m.meta;return I&&(ft(I["line-count"],R.length),ft(I["layout-time-ns"],A),ft(I["overflow-segments"],M)),R},{name:"flow-lines",meta:{"line-count":0,"layout-time-ns":0,"overflow-segments":0},equals:(g,h)=>{let y=g,b=h;if(y.length!==b.length)return!1;for(let v=0;v<y.length;v++){let T=y[v],w=b[v];if(T.x!==w.x||T.y!==w.y||T.width!==w.width||T.slotWidth!==w.slotWidth||T.text!==w.text||T.columnIndex!==w.columnIndex||T.flushToRight!==w.flushToRight)return!1}return!0}});return o.add(i,{name:"text"}),o.add(a,{name:"font"}),o.add(u,{name:"line-height"}),o.add(c,{name:"container"}),o.add(d,{name:"columns"}),o.add(l,{name:"obstacles"}),o.add(p,{name:"paragraph-spacing"}),o.add(f,{name:"segments"}),o.add(m,{name:"flow-lines"}),{graph:o,setText:g=>o.set("text",g),setFont:g=>o.set("font",g),setLineHeight:g=>o.set("line-height",g),setContainer:g=>o.set("container",g),setColumns:g=>o.set("columns",g),setObstacles:g=>o.set("obstacles",g),setParagraphSpacing:g=>o.set("paragraph-spacing",g),segments:f,flowLines:m}}var Si={};Ne(Si,{NS_PER_MS:()=>He,NS_PER_SEC:()=>st,resilientPipeline:()=>tb});Kn();Et();function tb(t,e={}){let n=t;e.rateLimit!=null&&(n=qn(n,e.rateLimit)),e.budget!=null&&e.budget.length>0&&(n=ru(n,e.budget));let r;if(e.breaker!=null){let s=Tt(e.breaker),i=e.breakerOnOpen??"skip",a=Wn(s,{onOpen:i})(n);n=a.node,r=a.breakerState}if(e.timeoutMs!=null){if(e.timeoutMs<=0)throw new RangeError("timeoutMs must be > 0");if(e.timeoutMs>9e6)throw new RangeError("timeoutMs must be <= 9_000_000 (\u22482.5h) to stay within safe ns arithmetic");n=zn(n,e.timeoutMs*1e6)}e.retry!=null&&(n=Hn(n,e.retry)),e.fallback!==void 0&&(n=Un(n,e.fallback));let o=Vt(n,{initialStatus:e.initialStatus??"pending"});return{node:o.node,status:o.status,error:o.error,breakerState:r}}var Ii={};Ne(Ii,{SNAPSHOT_WIRE_VERSION:()=>Ro,SurfaceError:()=>Ce,asSurfaceError:()=>Ni,createGraph:()=>dr,deleteSnapshot:()=>Li,diffSnapshots:()=>Ci,listSnapshots:()=>Ai,restoreSnapshot:()=>Oi,runReduction:()=>Ei,saveSnapshot:()=>Mi});var Ce=class extends Error{code;details;constructor(e,n,r){super(n),this.name="SurfaceError",this.code=e,r!==void 0&&(this.details=r)}toJSON(){let e={code:this.code,message:this.message};if(this.details!==void 0){let n=nb(this.details);n!==void 0&&(e.details=n)}return e}};function nb(t){try{return JSON.parse(JSON.stringify(t))}catch{return}}function Ni(t,e="internal-error"){if(t instanceof Ce)return t;let n=t instanceof Error?t.message:String(t);return new Ce(e,n)}function dr(t,e){let n=ir(t);if(!n.valid)throw new Ce("invalid-spec",`GraphSpec validation failed:
217
+ }`;function go(t,e,n){if(typeof t=="function")return t;let r=t??e;return s=>n(r,s)}Q();Q();var ci={};we(ci,{blindVariation:()=>Iy,errorCritique:()=>Gy,refineLoop:()=>wu});Ce();Ne();se();_e();Q();function Ly(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.subscribe=="function"&&typeof e.down=="function"&&typeof e.emit=="function"}function Fp(t,e){if(t.length===0)return{best:null,bestScore:Number.NEGATIVE_INFINITY};if(t.length===1){let o=Tu(e);return{best:t[0],bestScore:o}}if(e.some(o=>typeof o.candidateIndex=="number")){let o=new Array(t.length);for(let u=0;u<t.length;u++)o[u]={sum:0,count:0};for(let u of e){let d=u.candidateIndex;typeof d=="number"&&d>=0&&d<t.length&&(o[d].sum+=u.score,o[d].count+=1)}let i=t[0],a=o[0].count>0?o[0].sum/o[0].count:Number.NEGATIVE_INFINITY;for(let u=1;u<t.length;u++){let d=o[u].count>0?o[u].sum/o[u].count:Number.NEGATIVE_INFINITY;d>a&&(a=d,i=t[u])}return{best:i,bestScore:a}}let r=t[0],s=e[0]?.score??Number.NEGATIVE_INFINITY;for(let o=1;o<t.length;o++){let i=e[o]?.score??Number.NEGATIVE_INFINITY;i>s&&(s=i,r=t[o])}return{best:r,bestScore:s}}function Tu(t){if(t.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let n of t)e+=n.score;return e/t.length}function wu(t,e,n,r){let s=r.name??"refine-loop",o=new q(s,r.graph),i=Ly(r.dataset)?r.dataset:N(r.dataset,{name:"dataset"});o.add(i,{name:"dataset"});let a=N(0,{name:"iteration"});o.add(a,{name:"iteration"});let u=N(n,{name:"strategy",equals:()=>!1});o.add(u,{name:"strategy"});let d=N(null,{name:"lastFeedback"});o.add(d,{name:"lastFeedback"});let c=N([],{name:"prevCandidates"});o.add(c,{name:"prevCandidates"});let l=N(!1,{name:"paused"});o.add(l,{name:"paused"});let p=N("running",{name:"status"});o.add(p,{name:"status"});let f=N([],{name:"history",equals:()=>!1});o.add(f,{name:"history"});let m=N(null,{name:"best"});o.add(m,{name:"best"});let g=N(Number.NEGATIVE_INFINITY,{name:"score"});o.add(g,{name:"score"});let h=N(0,{name:"budget-used"});o.add(h,{name:"budget-used"});let y=ao("stages");o.mount("stages",y);let b=y.topic("generate"),v=y.topic("evaluate"),T=y.topic("analyze"),w=y.topic("decide"),k=n,x=null,S=[];o.addDisposer(u.subscribe(oe=>{for(let ve of oe)ve[0]===R&&(k=ve[1])})),o.addDisposer(d.subscribe(oe=>{for(let ve of oe)ve[0]===R&&(x=ve[1])})),o.addDisposer(c.subscribe(oe=>{for(let ve of oe)ve[0]===R&&(S=ve[1])}));let E=be(a,oe=>{let ve=k,Fe=oe===0||x==null;return V([],(ge,H)=>{let ee=!1;try{let ye=Fe?ve.seed(t):ve.generate(x,S);if(ye instanceof Promise)return ye.then(B=>{ee||H.emit(B)},B=>{ee||H.down([[M,B]])}),()=>{ee=!0};H.emit(ye)}catch(ye){ee=!0,H.down([[M,ye]])}},{describeKind:"producer"})},{name:"candidates"});o.add(E,{name:"candidates"});let L=le([E],(oe,ve,Fe)=>{let ge=Fe.terminalDeps[0];ge!==void 0&&ge!==!0&&p.emit("errored")},{name:"error-watcher",errorWhenDepsError:!1});o.add(L,{name:"error-watcher"}),o.addDisposer(L.subscribe(()=>{}));let C=_([E,a],([oe,ve])=>({iteration:ve,candidates:oe,timestamp_ns:F()}),{name:"generate-event"});o.add(C,{name:"generate-event"}),o.addDisposer(C.subscribe(()=>{}));let I=le([C],([oe])=>{b.publish(oe)},{name:"generate-publish"});o.add(I,{name:"generate-publish"}),o.addDisposer(I.subscribe(()=>{}));let A=le([E],([oe])=>{c.emit(oe)},{name:"generate-mirror"});o.add(A,{name:"generate-mirror"}),o.addDisposer(A.subscribe(()=>{}));let P=e(E,i);o.add(P,{name:"scores"});let U=_([P,E,a],([oe,ve,Fe])=>({iteration:Fe,candidates:ve,scores:oe,timestamp_ns:F()}),{name:"evaluate-event"});o.add(U,{name:"evaluate-event"}),o.addDisposer(U.subscribe(()=>{}));let z=le([U],([oe])=>{v.publish(oe)},{name:"evaluate-publish"});o.add(z,{name:"evaluate-publish"}),o.addDisposer(z.subscribe(()=>{}));let D=_([P,E],([oe,ve])=>k.analyze(oe,ve),{name:"feedback"});o.add(D,{name:"feedback"});let Z=_([D,E,a],([oe,ve,Fe])=>({iteration:Fe,candidates:ve,feedback:oe,timestamp_ns:F()}),{name:"analyze-event"});o.add(Z,{name:"analyze-event"}),o.addDisposer(Z.subscribe(()=>{}));let te=le([Z],([oe])=>{T.publish(oe)},{name:"analyze-publish"});o.add(te,{name:"analyze-publish"}),o.addDisposer(te.subscribe(()=>{}));let ke=_([f],([oe])=>{let ve=oe;if(r.patience==null||ve.length<=r.patience)return!1;let Fe=ve.slice(-(r.patience+1)),ge=Fe[0].bestScore;return Fe.slice(1).every(H=>H.bestScore<=ge)},{name:"patience-check"});o.add(ke,{name:"patience-check"});let J=_([g],([oe])=>r.minScore!=null&&oe>=r.minScore,{name:"min-score-check"});o.add(J,{name:"min-score-check"});let K=_([f],([oe])=>{let ve=oe;if(r.minDelta==null||ve.length<2)return!1;let Fe=ve[ve.length-2].bestScore,ge=ve[ve.length-1].bestScore;return Math.abs(ge-Fe)<r.minDelta},{name:"min-delta-check"});o.add(K,{name:"min-delta-check"});let j=_([h],([oe])=>r.maxEvaluations!=null&&oe>=r.maxEvaluations,{name:"max-evaluations-check"});o.add(j,{name:"max-evaluations-check"});let ne=_([a],([oe])=>r.maxIterations!=null&&oe>=r.maxIterations,{name:"max-iterations-check"});o.add(ne,{name:"max-iterations-check"});let Re=_([h],([oe])=>r.budget!=null&&oe>=r.budget,{name:"budget-exhausted-check"});o.add(Re,{name:"budget-exhausted-check"}),o.addDisposer(ke.subscribe(()=>{})),o.addDisposer(J.subscribe(()=>{})),o.addDisposer(K.subscribe(()=>{})),o.addDisposer(j.subscribe(()=>{})),o.addDisposer(ne.subscribe(()=>{})),o.addDisposer(Re.subscribe(()=>{}));let Me=_([ke,J,K,j,ne],([oe,ve,Fe,ge,H])=>oe?{converged:!0,reason:"patience"}:ve?{converged:!0,reason:"min-score"}:Fe?{converged:!0,reason:"min-delta"}:ge?{converged:!0,reason:"max-evaluations"}:H?{converged:!0,reason:"max-iterations"}:{converged:!1},{name:"converged"});o.add(Me,{name:"converged"}),o.addDisposer(Me.subscribe(()=>{}));let Oe=-1,he=le([D,P,E],([oe,ve,Fe])=>{let ge=a.cache,H=oe,ee=Fe,ye=ve;if(ge<=Oe)return;Oe=ge;let{best:B,bestScore:ae}=Fp(ee,ye),xe=f.cache,Se={n:ge,candidates:ee,scores:ye,feedback:H,best:B,bestScore:ae,timestamp_ns:F()},ue=[...xe,Se],De=h.cache+ee.length,fe="continue",me,lr=r.budget!=null&&De>=r.budget,Nn=l.cache;if(lr)fe="budget",me="budget";else if(r.minScore!=null&&H.score>=r.minScore)fe="converged",me="min-score";else if(r.maxIterations!=null&&ge>=r.maxIterations)fe="converged",me="max-iterations";else if(r.maxEvaluations!=null&&De>=r.maxEvaluations)fe="converged",me="max-evaluations";else if(r.minDelta!=null&&ue.length>=2){let To=ue[ue.length-2].bestScore,Oi=ue[ue.length-1].bestScore;Math.abs(Oi-To)<r.minDelta&&(fe="converged",me="min-delta")}else if(r.patience!=null&&ue.length>r.patience){let To=ue.slice(-(r.patience+1)),Oi=To[0].bestScore;To.slice(1).every(rf=>rf.bestScore<=Oi)&&(fe="converged",me="patience")}fe==="continue"&&Nn&&(fe="paused"),Y(()=>{m.emit(B),g.emit(H.score),f.emit(ue),h.emit(De),d.emit(H),w.publish({iteration:ge,decision:fe,reason:me,timestamp_ns:F()}),fe==="continue"?a.emit(ge+1):p.emit(fe==="converged"?"converged":fe==="budget"?"budget":"paused")})},{name:"decide-bridge"});return o.add(he,{name:"decide-bridge"}),o.addDisposer(he.subscribe(()=>{})),Object.assign(o,{best:m,score:g,status:p,history:f,strategy:u,iteration:a,generate:b,evaluate:v,analyze:T,decide:w,setStrategy(oe){u.emit(oe)},pause(){l.emit(!0)},resume(){p.cache==="paused"&&Y(()=>{l.emit(!1),p.emit("running"),a.emit(a.cache+1)})}})}function Iy(t){let e=t.width??4;return{name:t.name??"blindVariation",seed(r){return[r]},analyze(r,s){let o=Tu(r),i=null;for(let a of r)(!i||a.score<i.score)&&(i=a);return{summary:`blindVariation iteration: mean=${o.toFixed(3)}, n=${r.length}`,score:o,weakTasks:i?[i.taskId]:[]}},async generate(r,s){if(s.length===0)throw new Error("blindVariation.generate: empty candidate batch \u2014 cannot derive prior for teacher");let o=s[s.length-1],i=0,u={prior:o,reportCost:d=>{i+=d}};try{if(t.parallel!==!1)return await Promise.all(Array.from({length:e},()=>t.teacher(u)));let d=[];for(let c=0;c<e;c++)d.push(await t.teacher(u));return d}finally{if(t.tokens!=null&&i>0){let d=t.tokens.cache??0;t.tokens.emit(d+i)}}}}}function Dy(t){return typeof t=="object"&&t!==null&&t.kind==="errorCritique"}function Py(t,e){return t.length===0?`No task scored below the batch mean (${e.score.toFixed(3)}). Reinforce the current direction.`:`Failures below threshold:
218
+ ${t.map(r=>{let s=r.error!=null?` | error: ${r.error}`:"";return`- ${r.taskId} (score=${r.score.toFixed(3)})${s}`}).join(`
219
+ `)}`}function Gy(t){let e=t.width??4,n=t.name??"errorCritique",r=t.maxFailureSamples??5,s=t.formatCritique??Py;return{name:n,seed(o){return[o]},analyze(o,i){let a=Tu(o),u=typeof t.failureThreshold=="function"?t.failureThreshold(o):t.failureThreshold,d=u===void 0&&!Number.isFinite(a),c=u??a,l=d?[...o].sort((v,T)=>v.score-T.score):o.filter(v=>v.score<c).slice().sort((v,T)=>v.score-T.score),p=l.slice(0,r),{best:f,bestScore:m}=Fp(i,o),g={summary:"",score:a,weakTasks:p.map(v=>v.taskId)},h=s(p,g),y={kind:"errorCritique",best:f,failures:p,critiqueText:h},b=l.length>p.length?` (top ${p.length} retained)`:"";return{summary:`errorCritique iteration: mean=${a.toFixed(3)}, failures=${l.length}${b}/${o.length}, bestScore=${m.toFixed(3)}`,critique:y,weakTasks:p.map(v=>v.taskId),score:a}},async generate(o,i){if(i.length===0)throw new Error("errorCritique.generate: empty candidate batch \u2014 cannot derive prior for teacher");let a=Dy(o.critique)?o.critique:void 0,u=a!==void 0?a.best:i[i.length-1],d=a?.critiqueText??o.summary,c=a?.failures??[],l=0,f={prior:u,critique:d,failures:c,reportCost:m=>{l+=m}};try{if(t.parallel!==!1)return await Promise.all(Array.from({length:e},()=>t.teacher(f)));let m=[];for(let g=0;g<e;g++)m.push(await t.teacher(f));return m}finally{if(t.tokens!=null&&l>0){let m=t.tokens.cache??0;t.tokens.emit(m+l)}}}}}function Fy(t){let{best:e,score:n,status:r}=t,s=Number.isFinite(n)?n.toFixed(3):String(n),o=e??void 0;return r==="converged"?{outcome:"success",detail:`refineLoop converged at score ${s}`,artifact:o}:r==="budget"?{outcome:"partial",detail:`refineLoop hit budget at score ${s}`,artifact:o}:{outcome:"failure",detail:`refineLoop errored (status=${r})`,artifact:o}}function ku(t){let e=t.name??"refine-executor",n=t.toOutput??Fy;return r=>{let s=Xe(r,i=>i!=null,{name:`${e}/gate-in`}),o=be(s,i=>{let a=wu(t.seedFrom(i),t.evaluator,t.strategy,{...t.refine,dataset:t.datasetFor(i),name:`${e}/inner`});return _([a.status,a.best,a.score],([u,d,c])=>{let l=u;return l!=="converged"&&l!=="budget"&&l!=="errored"?null:n({best:d,score:c,status:l})},{name:`${e}/output`})},{name:e});return Xe(o,i=>i!=null,{name:`${e}/gate-out`})}}function $y(t){if(t.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let n of t)e+=n.score;return e/t.length}function jy(t){let{passCount:e,total:n,meanScore:r,threshold:s,missingArtifact:o}=t,i=Number.isFinite(r)?r.toFixed(3):String(r),a=!o&&n>0&&r>=s,u=o?["EXECUTE stage did not emit an artifact; cannot verify reactively"]:a?[`${e}/${n} eval tasks passed; mean score ${i} \u2265 ${s}`]:n===0?["No eval tasks were selected for this item \u2014 cannot verify"]:[`${e}/${n} eval tasks passed; mean score ${i} < threshold ${s}`];return a?{verified:!0,findings:u}:{verified:!1,findings:u,errorClass:"structural"}}function By(t){return t.artifact??null}function $p(t){let e=t.name??"eval-verifier",n=t.threshold??.5,r=t.toOutput??jy,s=t.extractArtifact??By;return o=>{let i=Xe(o,u=>u!=null&&u[0]!=null&&u[1]!=null,{name:`${e}/gate-in`}),a=be(i,u=>{let[d,c]=u,l=s(d,c);if(l==null)return N(r({scores:[],meanScore:Number.NEGATIVE_INFINITY,passCount:0,total:0,threshold:n,missingArtifact:!0}));let p=N([l],{name:`${e}/candidates`}),f=N(t.datasetFor(c),{name:`${e}/dataset`}),m=t.evaluator(p,f);return _([m],([g])=>{let h=g;if(h==null)return null;let y=$y(h),b=h.filter(v=>v.score>=n).length;return r({scores:h,meanScore:y,passCount:b,total:h.length,threshold:n})},{name:`${e}/output`})},{name:e});return Xe(a,u=>u!=null,{name:`${e}/gate-out`})}}function Vy(t){let e=t.name??"harness-pair",n=ku({name:`${e}-exec`,seedFrom:t.seedFrom,evaluator:t.evaluator,strategy:t.strategy,datasetFor:t.datasetFor,refine:t.refine}),r=$p({name:`${e}-verify`,evaluator:t.evaluator,datasetFor:t.datasetFor,threshold:t.threshold});return{executor:n,verifier:r}}Ne();_e();Q();var mi={};we(mi,{JobFlowGraph:()=>pi,JobQueueGraph:()=>li,jobFlow:()=>Hy,jobQueue:()=>fi});_e();var Ky=2147483647;function jp(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function xu(t,e){return ze("job_queue",t,e)}var li=class extends q{_pending;_jobs;_seq=0;pending;jobs;depth;constructor(e,n={}){super(e,n.graph),this._pending=Rs([],{name:"pending"}),this._jobs=Ze({name:"jobs"}),this.pending=this._pending.items,this.jobs=this._jobs.entries,this.add(this.pending,{name:"pending"}),this.add(this.jobs,{name:"jobs"}),this.depth=_([this.pending],([r])=>r.length,{name:"depth",describeKind:"derived",meta:xu("queue_depth"),initial:0}),this.add(this.depth,{name:"depth"}),this.addDisposer(re(this.depth))}enqueue(e,n={}){let r=n.id??`${this.name}-${++this._seq}`;if(this._jobs.get(r)!==void 0)throw new Error(`jobQueue("${this.name}"): duplicate job id "${r}"`);let s={id:r,payload:e,attempts:0,metadata:Object.freeze({...n.metadata??{}}),state:"queued"};return this._jobs.set(r,s),this._pending.append(r),r}claim(e=1){let n=jp(e,"job queue claim limit");if(n===0)return[];let r=[];for(;r.length<n&&this.pending.cache.length!==0;){let o=this._pending.pop(0),i=this._jobs.get(o);if(!i||i.state!=="queued")continue;let a={...i,state:"inflight",attempts:i.attempts+1};this._jobs.set(o,a),r.push(a)}return r}ack(e){let n=this._jobs.get(e);return!n||n.state!=="inflight"?!1:(this._jobs.delete(e),!0)}nack(e,n={}){let r=this._jobs.get(e);return!r||r.state!=="inflight"?!1:n.requeue??!0?(this._jobs.set(e,{...r,state:"queued"}),this._pending.append(e),!0):(this._jobs.delete(e),!0)}removeById(e){let n=this._jobs.get(e);if(!n)return!1;if(n.state==="queued"){let s=this.pending.cache.indexOf(e);s>=0&&this._pending.pop(s)}return this._jobs.delete(e),!0}},pi=class extends q{_stageNames;_queues=new Map;_completed;completed;completedCount;constructor(e,n={}){super(e,n.graph);let r=(n.stages??["incoming","processing","done"]).map(i=>i.trim());if(r.length<2)throw new Error(`jobFlow("${e}"): requires at least 2 stages`);if(new Set(r).size!==r.length)throw new Error(`jobFlow("${e}"): stage names must be unique`);this._stageNames=Object.freeze([...r]);for(let i of this._stageNames){let a=fi(`${e}-${i}`);this._queues.set(i,a),this.mount(i,a)}this._completed=Ue([],{name:"completed"}),this.completed=this._completed.entries,this.add(this.completed,{name:"completed"}),this.completedCount=_([this.completed],([i])=>i.length,{name:"completedCount",describeKind:"derived",meta:xu("job_flow_completed_count"),initial:0}),this.add(this.completedCount,{name:"completedCount"}),this.addDisposer(re(this.completedCount));let o=Math.max(1,jp(n.maxPerPump??Ky,"job flow maxPerPump"));for(let i=0;i<this._stageNames.length;i+=1){let a=this._stageNames[i],u=this.queue(a),d=i+1<this._stageNames.length?this.queue(this._stageNames[i+1]):null,c=V([u.pending],()=>{let l=0;for(;l<o;){let p=u.claim(1);if(p.length===0)break;let f=p[0];if(!f)break;d?d.enqueue(f.payload,{metadata:{...f.metadata,job_flow_from:a}}):this._completed.append(f),u.ack(f.id),l+=1}},{name:`pump_${a}`,describeKind:"effect",meta:xu("job_flow_pump")});this.add(c,{name:`pump_${a}`}),this.addDisposer(re(c))}}stages(){return this._stageNames}queue(e){let n=this._queues.get(e);if(!n)throw new Error(`jobFlow("${this.name}"): unknown stage "${e}"`);return n}enqueue(e,n={}){return this.queue(this._stageNames[0]).enqueue(e,n)}retainedCompleted(){return this.completed.cache}};function fi(t,e){return new li(t,e)}function Hy(t,e){return new pi(t,e)}Ne();Q();function Ru(){let t=Ze({name:"strategy-entries"}),e=_([t.entries],([i])=>{let a=i;return new Map(a)},{name:"strategy-model",equals:(i,a)=>{let u=i,d=a;if(u.size!==d.size)return!1;for(let[c,l]of u){let p=d.get(c);if(!p||l.attempts!==p.attempts||l.successes!==p.successes)return!1}return!0}});function n(i,a,u){let d=dr(i,a),c=t.get(d),l=(c?.attempts??0)+1,p=(c?.successes??0)+(u?1:0);t.set(d,{rootCause:i,intervention:a,attempts:l,successes:p,successRate:p/l})}function r(i,a){return t.get(dr(i,a))}let s=e.subscribe(()=>{});function o(){s()}return{node:e,record:n,lookup:r,dispose:o}}function qy(t,e,n,r,s){let o={...ar,...s?.severityWeights},i=s?.decayRate??ur,a=s?.effectivenessThreshold??.7,u=s?.effectivenessBoost??15,d=[t,e,n];return r&&d.push(r),_(d,c=>{let l=c[0],p=c[1],f=c[2],m=r?c[3]:0,g=o[l.severity??"medium"],h=(F()-f)/1e9,y=Rn(g,h,i,0),b=dr(l.rootCause,l.intervention),v=p.get(b);return v&&v.successRate>=a&&(y+=u),y+=m*20,y},{name:"priority-score"})}var Bp="intake",Wy="triage-output",Vp="retry",Kp="verify-results",Hp="__unrouted";function qp(t,e){let n=go(e,bu,(r,s)=>r.replace("{{item}}",JSON.stringify(s)));return r=>wn(t,[r],n,{name:"execute",format:"json"})}function Wp(t,e){let n=go(e,vu,(r,s)=>{let[o,i]=s;return r.replace("{{execution}}",JSON.stringify(o)).replace("{{item}}",JSON.stringify(i))});return r=>wn(t,[r],s=>s==null?"":n(s),{name:"verify",format:"json"})}var hi=class extends q{queues;jobs;gates;queueTopics;strategy;totalRetries;totalReingestions;priorityScores;constructor(e,n,r,s,o,i,a,u,d){super(e),this.queues=n,this.queueTopics=r,this.jobs=s,this.gates=o,this.strategy=i,this.totalRetries=a,this.totalReingestions=u,this.priorityScores=d}get intake(){return this.queues.topic(Bp)}get verifyResults(){return this.queues.topic(Kp)}get retry(){return this.queues.topic(Vp)}get unrouted(){return this.queues.topic(Hp)}stageNodes(){let e=this.queues,n=i=>e.has(i)?`queues::${i}::latest`:null,r=i=>i==null?[]:[i],s=st.flatMap(i=>r(n(i))),o=[];for(let[i]of this.gates)o.push(`gates::${i}/gate`);return[{label:"INTAKE",paths:r(n("intake"))},{label:"TRIAGE",paths:["triage"]},{label:"QUEUE",paths:s},{label:"GATE",paths:o},{label:"EXECUTE",paths:["execute"]},{label:"VERIFY",paths:r(n("verify-results"))},{label:"REFLECT",paths:["reflect"]},{label:"STRATEGY",paths:["strategy"]}]}};function Uy(t,e){let n=e.adapter,r=e.maxRetries??2,s=e.retainedLimit??1e3,o=e.errorClassifier??di,i=new Map;for(let H of st)i.set(H,{...ui[H],...e.queues?.[H]});let a=ao(`${t}/queues`,{defaultTopicOptions:{retainedLimit:s}}),u=a.topic(Bp),d=a.topic(Wy),c=a.topic(Vp),l=a.topic(Kp),p=new Map;for(let H of st)p.set(H,a.topic(H));let f=a.topic(Hp),m=Ru(),g=At(u.latest,m.node),h=go(e.triagePrompt,yu,(H,ee)=>{let[ye,B]=ee;return H.replace("{{strategy}}",JSON.stringify(Array.from(B.entries()))).replace("{{item}}",JSON.stringify(ye))}),y=wn(n,[g],H=>{let ee=H;return!ee||!ee[0]?"":h(ee)},{name:"triage",format:"json"}),b=At(y,g),T=le([b],([H])=>{if(H==null)return;let[ee,ye]=H;if(!ee?.route)return;let B=ye?.[0],ae={...ee,...B};d.publish(ae)}).subscribe(()=>{}),w=new Set(st);for(let H of st)Vs(`bridge/${H}`,d,p.get(H),{map:ee=>ee.route===H?ee:void 0});Vs("bridge/__unrouted",d,f,{map:H=>w.has(H.route)?void 0:H});let k=new Map,x=new Map;for(let H of st)k.set(H,fi(`jobs/${H}`));let S=[];for(let H of st){let ee=p.get(H),ye=k.get(H),B=new WeakSet,ae=le([ee.events],([xe])=>{let Se=xe??[];for(let ue of Se){if(B.has(ue))continue;B.add(ue);let De=ye.enqueue(ue);x.set($r(ue),{route:H,id:De})}},{name:`jobs/${H}-mirror`});S.push(ae.subscribe(()=>{}))}function E(H){let ee=$r(H),ye=x.get(ee);ye&&(k.get(ye.route)?.removeById(ye.id),x.delete(ee))}let L=new q("gates"),C=new Map;for(let H of st){let ee=i.get(H);if(!ee.gated)continue;let ye=p.get(H),B=uo(L,`${H}/gate`,ye.latest,{maxPending:ee.maxPending,startOpen:ee.startOpen});C.set(H,B)}let I=[];for(let H of st)i.get(H).gated&&C.has(H)?I.push(C.get(H).node):I.push(p.get(H).latest);I.push(c.latest);let A=wt(...I),U=(e.executor??qp(n,e.executePrompt))(A),z=At(U,A),Z=(e.verifier??Wp(n,e.verifyPrompt))(z),te=At(Z,z),ke=e.maxReingestions??1,J=Math.min(e.maxTotalRetries??r*10,100),K=Math.min(e.maxTotalReingestions??ke*10,100),j=N(0),ne=N(0);function Re(H,ee,ye){let B={item:ye,outcome:ee?.outcome??"failure",detail:ee?.detail??"unknown",artifact:ee?.artifact};return{item:ye,execution:B,verified:H.verified,findings:H.findings??[],errorClass:H.errorClass}}function Me(H,ee){m.record(ee.rootCause,ee.intervention,!0),l.publish(H),E(ee)}function Oe(H,ee){let ye=$r(ee),B=ee.$retries??0,ae={...ee,$retries:B+1,summary:`[RETRY ${B+1}/${r}] ${ye} \u2014 Previous attempt failed: ${H.findings.join("; ")}`,relatedTo:[ye]};c.publish(ae)}function he(H,ee){m.record(ee.rootCause,ee.intervention,!1),l.publish(H),E(ee);let ye=$r(ee),B=ee.$reingestions??0;B<ke&&Fr(ne,K)&&u.publish({source:ee.source,summary:`Verification failed for: ${ye}`,evidence:H.findings.join(`
220
+ `),affectsAreas:ee.affectsAreas,affectsEvalTasks:ee.affectsEvalTasks,severity:ee.severity??"high",relatedTo:[ye],$reingestions:B+1})}let Ge=V([te],(H,ee)=>{let ye=H[0];if(ye==null||ye.length===0)return;let B=ye[ye.length-1];if(B==null)return;let[ae,xe]=B,[Se,ue]=xe??[null,null];if(!ae||!ue)return;if(Se==null){he({item:ue,execution:{item:ue,outcome:"failure",detail:"executor returned null"},verified:!1,findings:["executor returned null"],errorClass:"structural"},ue);return}let De=Re(ae,Se,ue);if(De.verified){Me(De,ue);return}let fe=De.errorClass??o({item:ue,outcome:Se.outcome,detail:De.findings.join("; ")}),me=ue.$retries??0;fe==="self-correctable"&&me<r&&Fr(j,J)?Oe(De,ue):he(De,ue)}),oe=Ge.subscribe(()=>{}),ve=_([Ge],()=>null,{name:"reflect",equals:()=>!1}),Fe;e.priority&&(Fe=zy(p,m,e));let ge=new hi(t,a,p,k,C,m,j,ne,Fe);ge.addDisposer(T),ge.addDisposer(oe),ge.addDisposer(m.dispose);for(let H of S)ge.addDisposer(H);if(ge.add(y,{name:"triage"}),ge.add(A,{name:"execute-input"}),ge.add(U,{name:"execute"}),ge.add(z,{name:"execute-context"}),ge.add(Z,{name:"verify"}),ge.add(te,{name:"verify-context"}),ge.add(Ge,{name:"verify-dispatch"}),ge.add(ve,{name:"reflect"}),ge.add(m.node,{name:"strategy"}),ge.addDisposer(ve.subscribe(()=>{})),Fe)for(let[H,ee]of Fe)ge.add(ee,{name:`priority/${H}`}),ge.addDisposer(ee.subscribe(()=>{}));ge.mount("queues",a),ge.mount("gates",L);for(let[H,ee]of k)ge.mount(`jobs/${H}`,ee);return ge}function zy(t,e,n){if(!n.lastInteractionNs)throw new Error("harnessLoop: `opts.priority` requires `opts.lastInteractionNs` \u2014 pass a Node<number> (e.g. `fromTimer(60_000)` or a `state(monotonicNs())` you bump on human interaction). Priority scores only decay when this node settles; an internal default would freeze age at construction time.");let r=n.lastInteractionNs,s=n.priority??{},o={...ar,...s.severityWeights},i=s.decayRate??ur,a=s.effectivenessThreshold??.7,u=s.effectivenessBoost??15,d=new Map;for(let[c,l]of t){let p=_([l.latest,e.node,r],f=>{let m=f[0];if(m==null)return 0;let g=o[m.severity??"medium"]??40,h=(F()-f[2])/1e9,y=g*Math.exp(-i*Math.max(0,h)),b=`${m.rootCause}\u2192${m.intervention}`,T=f[1]?.get(b);return T&&T.successRate>=a&&(y+=u),y},{name:`priority/${c}`});d.set(c,p)}return d}function Jy(t,e){let n=pn(t,e),r={};for(let s of st){let o=t.queues.has(s)?t.queues.topic(s):null;r[s]=o?.retained().length??0}return{...n,queueDepths:r,strategyEntries:t.strategy.node.cache?.size??0,totalRetries:t.totalRetries.cache??0,totalReingestions:t.totalReingestions.cache??0}}Ne();function Yy(t){let e={};for(let{label:n,paths:r}of t.stageNodes())for(let s of r)e[s]=n;return e}function Qy(t,e){let n=e?.logger===null?null:e?.logger??console.log,r=e?.detail??"summary",s=F(),o=[],i=[],a=Yy(t);function u(){return(F()-s)/1e9}function d(c,l,p){let f={elapsed:u(),stage:c,type:l};r!=="summary"&&(f.summary=Xy(p)),r==="full"&&(f.data=p),i.push(f)}for(let[c,l]of Object.entries(a))try{let p=t.observe(c,{format:"stage-log",stageLabels:a,logger:n?f=>n(f):()=>{},includeTypes:["data","error","complete"]});p.onEvent(f=>{f.type==="data"?d(l,"data",f.data):f.type==="error"?d(l,"error",f.data):f.type==="complete"&&d(l,"complete",void 0)}),o.push(p)}catch(p){let f=p instanceof Error?p.message:String(p);d(l,"error",`observe-unavailable: ${c} \u2014 ${f}`),n&&n(`[${u().toFixed(3)}s] ${l.padEnd(9)} \u2717 observe-unavailable: ${f}`)}return{get events(){return i},dispose(){for(let c of o)c.dispose();o.length=0}}}function Xy(t){if(t==null)return"null";if(typeof t=="string")return Up(t,80);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return Up(e,120)}catch{return String(t)}}function Up(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}var bi={};we(bi,{LensGraph:()=>yi,graphLens:()=>rb,watchTopologyTree:()=>Mt});Ne();Q();function zp(t){return ze("lens",t)}function Zy(t){let e=Object.keys(t.nodes),n=new Map,r=new Map;for(let g of e){let h=t.nodes[g]?.deps??[];n.set(g,h);for(let y of h)r.has(y)||r.set(y,new Set),r.get(y).add(g)}let s=[],o=[];for(let g of e)(n.get(g)??[]).length===0&&s.push(g),r.has(g)||o.push(g);s.sort(),o.sort();let i=t.edges.length,a=0,u=1,d=2,c=new Map;for(let g of e)c.set(g,a);let l=!1,p=new Map,f=g=>{let h=c.get(g)??a;if(h===u)return l=!0,0;if(h===d)return p.get(g)??0;c.set(g,u);let y=0,b=r.get(g);if(b!=null)for(let v of b){let T=f(v);T+1>y&&(y=T+1)}return c.set(g,d),p.set(g,y),y},m=0;for(let g of s){let h=f(g);h>m&&(m=h)}for(let g of e)c.get(g)===a&&f(g);return{nodeCount:e.length,edgeCount:i,subgraphCount:t.subgraphs.length,sources:s,sinks:o,depth:m,hasCycles:l}}function eb(t){let e=[];for(let[n,r]of Object.entries(t.nodes)){if(r.status!=="errored")continue;let s={path:n,status:"errored"},o=fn(t,n,"upstream",{});for(let i of o)if(i!==n&&t.nodes[i]?.status==="errored"){s.upstreamCause=i;break}e.push(s)}return e.sort((n,r)=>n.path<r.path?-1:n.path>r.path?1:0),{ok:e.length===0,problems:e}}function tb(t,e){return t.nodeCount===e.nodeCount&&t.edgeCount===e.edgeCount&&t.subgraphCount===e.subgraphCount&&t.depth===e.depth&&t.hasCycles===e.hasCycles&&Jp(t.sources,e.sources)&&Jp(t.sinks,e.sinks)}function nb(t,e){if(t.ok!==e.ok||t.problems.length!==e.problems.length)return!1;for(let n=0;n<t.problems.length;n++){let r=t.problems[n],s=e.problems[n];if(r.path!==s.path||r.status!==s.status||r.upstreamCause!==s.upstreamCause)return!1}return!0}function Jp(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}var yi=class extends q{stats;health;flow;_target;constructor(e,n={}){super(n.name??`${e.name}_lens`,n.graph),this._target=e;let r=0,s=0,o=N(0,{name:"stats_tick"}),i=N(0,{name:"health_tick"});this.add(o,{name:"stats_tick"}),this.add(i,{name:"health_tick"});let a={name:"flow"};n.maxFlowPaths!=null&&(a.maxSize=n.maxFlowPaths),this.flow=Ze(a),this.add(this.flow.entries,{name:"flow"});let u=n.pathFilter,d=Mt(e,(p,f,m)=>{if(r+=1,o.emit(r),s+=1,i.emit(s),p.kind==="removed")if(p.nodeKind==="node"){let g=`${m}${p.name}`;this.flow.delete(g)}else{let g=`${m}${p.name}::`,h=[];for(let y of p.audit.nodes){let b=y===""?`${m}${p.name}`:`${g}${y}`;h.push(b)}h.length>0&&this.flow.deleteMany(h)}});this.addDisposer(d);let c=e.observe({timeline:!0,structured:!0}),l=c.onEvent(p=>{let f=p.type;if((f==="error"||f==="complete"||f==="data"||f==="teardown")&&(s+=1,i.emit(s)),f==="data"){let m=p.path??"";if(!m||u!=null&&!u(m))return;let g=this.flow.get(m),h=g!=null?g.count+1:1;this.flow.set(m,{path:m,count:h,lastUpdate_ns:F()})}});this.addDisposer(()=>{l(),c.dispose()}),this.stats=_([o],()=>Zy(e.describe({detail:"minimal"})),{name:"stats",describeKind:"derived",equals:tb,meta:zp("stats")}),this.add(this.stats,{name:"stats"}),this.addDisposer(re(this.stats)),this.health=_([i],()=>eb(e.describe({detail:"standard"})),{name:"health",describeKind:"derived",equals:nb,meta:zp("health")}),this.add(this.health,{name:"health"}),this.addDisposer(re(this.health))}why(e,n,r){let s=lu(this._target,e,n,r);return this.addDisposer(s.dispose),s}get target(){return this._target}};function rb(t,e){return new yi(t,e)}var vi={};we(vi,{CanvasMeasureAdapter:()=>_u,CliMeasureAdapter:()=>Su,ImageSizeAdapter:()=>Cu,NodeCanvasMeasureAdapter:()=>Mu,PrecomputedAdapter:()=>Eu,SvgBoundsAdapter:()=>Ou,analyzeAndMeasure:()=>Pt,carveTextLineSlots:()=>hu,circleIntervalForBand:()=>ef,computeBlockFlow:()=>Xp,computeCharPositions:()=>ri,computeFlowLines:()=>nf,computeLineBreaks:()=>Sn,computeTotalHeight:()=>Zp,layoutNextLine:()=>mu,measureBlock:()=>Yp,measureBlocks:()=>Qp,reactiveBlockLayout:()=>ob,reactiveFlowLayout:()=>ib,reactiveLayout:()=>py,rectIntervalForBand:()=>tf});var Su=class{cellPx;constructor(e){this.cellPx=e?.cellPx??8}measureSegment(e,n){return{width:Qn(e)*this.cellPx}}},Nu=class extends Error{name="KeyError"},Eu=class{metrics;fallback;constructor(e){this.metrics=e.metrics;let n=e.fallback??"per-char";if(n!=="per-char"&&n!=="error")throw new Error(`fallback must be 'per-char' or 'error', got ${JSON.stringify(e.fallback)}`);this.fallback=n}measureSegment(e,n){let r=this.metrics[n];if(r){let o=r[e];if(o!==void 0)return{width:o}}if(this.fallback==="error")throw new Nu(`PrecomputedAdapter: no metrics for segment ${JSON.stringify(e)} in font ${JSON.stringify(n)}`);let s=0;if(r)for(let o of e){let i=r[o];i!==void 0&&(s+=i)}return{width:s}}},_u=class{ctx=null;currentFont="";emojiCorrection;constructor(e){this.emojiCorrection=e?.emojiCorrection??1}getContext(){if(!this.ctx){if(typeof OffscreenCanvas>"u")throw new Error("CanvasMeasureAdapter requires a browser environment with OffscreenCanvas support. Use CliMeasureAdapter or NodeCanvasMeasureAdapter for Node.js.");let n=new OffscreenCanvas(0,0).getContext("2d");if(!n)throw new Error("CanvasMeasureAdapter: failed to get 2d context");this.ctx=n}return this.ctx}measureSegment(e,n){let r=this.getContext();n!==this.currentFont&&(r.font=n,this.currentFont=n);let s=r.measureText(e).width;return this.emojiCorrection!==1&&new RegExp("\\p{Emoji_Presentation}","u").test(e)&&(s*=this.emojiCorrection),{width:s}}clearCache(){this.currentFont=""}},Mu=class{ctx=null;currentFont="";canvasModule;constructor(e){this.canvasModule=e}getContext(){if(!this.ctx){let n=this.canvasModule.createCanvas(0,0).getContext("2d");if(!n)throw new Error("NodeCanvasMeasureAdapter: failed to get 2d context");this.ctx=n}return this.ctx}measureSegment(e,n){let r=this.getContext();return n!==this.currentFont&&(r.font=n,this.currentFont=n),{width:r.measureText(e).width}}clearCache(){this.currentFont=""}},Ou=class{measureSvg(e){let n=e.match(/viewBox\s*=\s*["']([^"']+)["']/);if(n){let o=n[1].trim().split(/[\s,]+/);if(o.length>=4){let i=Number.parseFloat(o[2]),a=Number.parseFloat(o[3]);if(Number.isFinite(i)&&Number.isFinite(a)&&i>0&&a>0)return{width:i,height:a};throw new Error("SvgBoundsAdapter: viewBox width/height are missing, non-finite, or not positive")}}let r=e.match(/<svg[^>]*\bwidth\s*=\s*["']?([\d.]+)/),s=e.match(/<svg[^>]*\bheight\s*=\s*["']?([\d.]+)/);if(r&&s){let o=Number.parseFloat(r[1]),i=Number.parseFloat(s[1]);if(Number.isFinite(o)&&Number.isFinite(i)&&o>0&&i>0)return{width:o,height:i};throw new Error("SvgBoundsAdapter: svg width/height attributes are non-finite or not positive")}throw new Error("SvgBoundsAdapter: cannot determine dimensions \u2014 SVG has no viewBox or width/height attributes")}},Cu=class{sizes;constructor(e){this.sizes=new Map(Object.entries(e))}measureImage(e){let n=this.sizes.get(e);if(!n)throw new Error(`ImageSizeAdapter: no dimensions registered for ${JSON.stringify(e)}`);return{width:n.width,height:n.height}}};Ne();_e();Q();function Yp(t,e,n,r,s,o,i){switch(t.type){case"text":{let a=t.font??s,u=t.lineHeight??o,d=Pt(t.text,a,n.text,r),c=Sn(d,e,n.text,a,r),l=ri(c,d,u),p=c.lineCount*u,f=0;for(let m of c.lines)m.width>f&&(f=m.width);return{index:i,type:"text",width:Math.min(f,e),height:p,textSegments:d,textLineBreaks:c,textCharPositions:l}}case"image":{let a,u;if(t.naturalWidth!=null&&t.naturalHeight!=null)a=t.naturalWidth,u=t.naturalHeight;else if(n.image){let d=n.image.measureImage(t.src);a=d.width,u=d.height}else throw new Error(`Image block at index ${i} has no naturalWidth/naturalHeight and no ImageMeasurer adapter`);return a>e&&(u=u*e/a,a=e),{index:i,type:"image",width:a,height:u}}case"svg":{let a,u;if(t.viewBox)a=t.viewBox.width,u=t.viewBox.height;else if(n.svg){let d=n.svg.measureSvg(t.content);a=d.width,u=d.height}else throw new Error(`SVG block at index ${i} has no viewBox and no SvgMeasurer adapter`);return a>e&&(u=u*e/a,a=e),{index:i,type:"svg",width:a,height:u}}}}function Qp(t,e,n,r,s,o){return t.map((i,a)=>Yp(i,e,n,r,s,o,a))}function Xp(t,e){let n=[],r=0;for(let s=0;s<t.length;s++){let o=t[s];n.push({...o,x:0,y:r}),r+=o.height+(s<t.length-1?e:0)}return n}function Zp(t){if(t.length===0)return 0;let e=t[t.length-1];return e.y+e.height}function ob(t){let{adapters:e,name:n="reactive-block-layout",defaultFont:r="16px sans-serif",defaultLineHeight:s=20}=t,o=new q(n),i=new Map,a=N(t.blocks??[],{name:"blocks"}),u=N(Math.max(0,t.maxWidth??800),{name:"max-width"}),d=N(t.gap??0,{name:"gap"}),c=V([a,u],(f,m,g)=>{let h=f[0]!=null&&f[0].length>0?f[0].at(-1):g.prevData[0],y=f[1]!=null&&f[1].length>0?f[1].at(-1):g.prevData[1],b=F(),v=Qp(h,y,e,i,r,s),T=F()-b,w=c.meta;w&&(ft(w["block-count"],v.length),ft(w["layout-time-ns"],T)),m.emit(v);let k=()=>{i.clear(),e.text.clearCache?.()};return{deactivate:k,invalidate:k}},{name:"measured-blocks",describeKind:"derived",meta:{"block-count":0,"layout-time-ns":0},equals:(f,m)=>{let g=f,h=m;if(g==null||h==null)return g===h;if(g.length!==h.length)return!1;for(let y=0;y<g.length;y++){let b=g[y],v=h[y];if(b.type!==v.type||b.width!==v.width||b.height!==v.height||b.index!==v.index)return!1}return!0}}),l=_([c,d],([f,m])=>Xp(f,m),{name:"block-flow",equals:(f,m)=>{let g=f,h=m;if(g==null||h==null)return g===h;if(g.length!==h.length)return!1;for(let y=0;y<g.length;y++){let b=g[y],v=h[y];if(b.x!==v.x||b.y!==v.y||b.width!==v.width||b.height!==v.height)return!1}return!0}}),p=_([l],([f])=>Zp(f),{name:"total-height"});return o.add(a,{name:"blocks"}),o.add(u,{name:"max-width"}),o.add(d,{name:"gap"}),o.add(c,{name:"measured-blocks"}),o.add(l,{name:"block-flow"}),o.add(p,{name:"total-height"}),{graph:o,setBlocks:f=>o.set("blocks",f),setMaxWidth:f=>o.set("max-width",Math.max(0,f)),setGap:f=>o.set("gap",f),measuredBlocks:c,blockFlow:l,totalHeight:p}}Ne();_e();Q();function ef(t,e,n){let r=t.hPad??0,s=t.vPad??0,o=e-s,i=n+s;if(o>=t.cy+t.r||i<=t.cy-t.r)return null;let a=t.cy>=o&&t.cy<=i?0:t.cy<o?o-t.cy:t.cy-i;if(a>=t.r)return null;let u=Math.sqrt(t.r*t.r-a*a);return{left:t.cx-u-r,right:t.cx+u+r}}function tf(t,e,n){let r=t.hPad??0,s=t.vPad??0;return n<=t.y-s||e>=t.y+t.h+s?null:{left:t.x-r,right:t.x+t.w+r}}function sb(t,e,n){return t.kind==="circle"?ef(t,e,n):tf(t,e,n)}function nf(t,e,n,r,s,o,i){let a=i?.paragraphSpacing??s,u=[],d={segmentIndex:0,graphemeIndex:0};if(t.length===0||n.count<=0||s<=0)return{lines:u,cursor:d};let c=e.paddingX??0,l=e.paddingY??0,p=Math.max(0,e.width-c*2),f=Math.max(0,e.height-l*2),m=n.gap*Math.max(0,n.count-1),g=Math.max(0,(p-m)/n.count);if(g<=0)return{lines:u,cursor:d};e:for(let h=0;h<n.count;h++){let y=c+h*(g+n.gap),b=y+g,v=l;for(;v+s<=l+f;){let T=v+s,w=[];for(let S=0;S<r.length;S++){let E=sb(r[S],v,T);E!==null&&w.push(E)}let k=hu({left:y,right:b},w,o);if(k.length===0){v+=s;continue}let x=!1;for(let S=0;S<k.length;S++){let E=k[S],L=E.right-E.left,C=mu(t,d,L);if(C===null)return{lines:u,cursor:d};if(C.text.length===0&&C.width===0){d=C.end,x=!0;break}u.push({x:E.left,y:v,width:C.width,slotWidth:L,text:C.text,columnIndex:h,flushToRight:E.right<b-.5}),d=C.end}if(x){v+=a;continue}if(v+=s,d.segmentIndex>=t.length)break e}if(d.segmentIndex>=t.length)break}return{lines:u,cursor:d}}function ib(t){let{adapter:e,name:n="reactive-flow-layout",minSlotWidth:r=20}=t,s=new q(n),o=new Map,i=N(t.text??"",{name:"text"}),a=N(t.font??"16px sans-serif",{name:"font"}),u=N(t.lineHeight??20,{name:"line-height"}),d=N(t.container??{width:800,height:600,paddingX:0,paddingY:0},{name:"container"}),c=N(t.columns??{count:1,gap:0},{name:"columns"}),l=N(t.obstacles??[],{name:"obstacles"}),p=N(t.paragraphSpacing??null,{name:"paragraph-spacing"}),f=V([i,a],(g,h,y)=>{let b=g[0],v=b!=null&&b.length>0?b.at(-1):y.prevData[0],T=g[1],w=T!=null&&T.length>0?T.at(-1):y.prevData[1],k=Pt(v,w,e,o);h.emit(k);let x=()=>{o.clear(),e.clearCache?.()};return{deactivate:x,invalidate:x}},{name:"segments",describeKind:"derived"}),m=_([f,d,c,l,u,p],([g,h,y,b,v,T])=>{let w=g,k=F(),x=T??v,{lines:S,cursor:E}=nf(w,h,y,b,v,r,{paragraphSpacing:x}),L=F()-k,C=Math.max(0,w.length-E.segmentIndex),I=m.meta;return I&&(ft(I["line-count"],S.length),ft(I["layout-time-ns"],L),ft(I["overflow-segments"],C)),S},{name:"flow-lines",meta:{"line-count":0,"layout-time-ns":0,"overflow-segments":0},equals:(g,h)=>{let y=g,b=h;if(y.length!==b.length)return!1;for(let v=0;v<y.length;v++){let T=y[v],w=b[v];if(T.x!==w.x||T.y!==w.y||T.width!==w.width||T.slotWidth!==w.slotWidth||T.text!==w.text||T.columnIndex!==w.columnIndex||T.flushToRight!==w.flushToRight)return!1}return!0}});return s.add(i,{name:"text"}),s.add(a,{name:"font"}),s.add(u,{name:"line-height"}),s.add(d,{name:"container"}),s.add(c,{name:"columns"}),s.add(l,{name:"obstacles"}),s.add(p,{name:"paragraph-spacing"}),s.add(f,{name:"segments"}),s.add(m,{name:"flow-lines"}),{graph:s,setText:g=>s.set("text",g),setFont:g=>s.set("font",g),setLineHeight:g=>s.set("line-height",g),setContainer:g=>s.set("container",g),setColumns:g=>s.set("columns",g),setObstacles:g=>s.set("obstacles",g),setParagraphSpacing:g=>s.set("paragraph-spacing",g),segments:f,flowLines:m}}var Ti={};we(Ti,{NS_PER_MS:()=>He,NS_PER_SEC:()=>it,resilientPipeline:()=>ab});Kn();Et();function ab(t,e={}){let n=t;e.rateLimit!=null&&(n=Wn(n,e.rateLimit)),e.budget!=null&&e.budget.length>0&&(n=iu(n,e.budget));let r;if(e.breaker!=null){let o=Tt(e.breaker),i=e.breakerOnOpen??"skip",a=qn(o,{onOpen:i})(n);n=a.node,r=a.breakerState}if(e.timeoutMs!=null){if(e.timeoutMs<=0)throw new RangeError("timeoutMs must be > 0");if(e.timeoutMs>9e6)throw new RangeError("timeoutMs must be <= 9_000_000 (\u22482.5h) to stay within safe ns arithmetic");n=zn(n,e.timeoutMs*1e6)}e.retry!=null&&(n=Hn(n,e.retry)),e.fallback!==void 0&&(n=Un(n,e.fallback));let s=Bt(n,{initialStatus:e.initialStatus??"pending"});return{node:s.node,status:s.status,error:s.error,breakerState:r}}var Mi={};we(Mi,{SNAPSHOT_WIRE_VERSION:()=>vo,SurfaceError:()=>Ee,asSurfaceError:()=>wi,createGraph:()=>cr,deleteSnapshot:()=>_i,diffSnapshots:()=>Ni,listSnapshots:()=>Ei,restoreSnapshot:()=>Si,runReduction:()=>ki,saveSnapshot:()=>Ri});var Ee=class extends Error{code;details;constructor(e,n,r){super(n),this.name="SurfaceError",this.code=e,r!==void 0&&(this.details=r)}toJSON(){let e={code:this.code,message:this.message};if(this.details!==void 0){let n=ub(this.details);n!==void 0&&(e.details=n)}return e}};function ub(t){try{return JSON.parse(JSON.stringify(t))}catch{return}}function wi(t,e="internal-error"){if(t instanceof Ee)return t;let n=t instanceof Error?t.message:String(t);return new Ee(e,n)}function cr(t,e){let n=ir(t);if(!n.valid)throw new Ee("invalid-spec",`GraphSpec validation failed:
221
221
  ${n.errors.join(`
222
- `)}`,{errors:n.errors});let r=e?.catalog??{},o=bo(t,r);if(!o.valid)throw new Ce("catalog-error",`Catalog validation failed:
223
- ${o.errors.join(`
224
- `)}`,{errors:o.errors});try{return vo(t,e)}catch(s){let i=s instanceof Error?s.message:String(s);throw new Ce("catalog-error",i)}}ae();var rb=3e4;async function Ei(t,e,n){let r=n?.inputPath??"input",o=n?.outputPath??"output",s=n?.timeoutMs??rb,i=dr(t,{catalog:n?.catalog}),a;try{a=i.resolve(o)}catch{throw i.destroy(),new Ce("node-not-found",`reduce: output path "${o}" is not registered`,{path:o})}try{i.resolve(r)}catch{throw i.destroy(),new Ce("node-not-found",`reduce: input path "${r}" is not registered`,{path:r})}try{return await new Promise((u,c)=>{let d=!1,l=!1,p,f,m=!1,g=h=>{l||(l=!0,p!==void 0&&clearTimeout(p),f!==void 0?(f(),f=void 0):m=!0,h())};f=a.subscribe(h=>{for(let y of h){if(l)return;if(d){if(y[0]===S){g(()=>u(y[1]));return}if(y[0]===F){let b=a.cache;g(()=>u(b));return}if(y[0]===O){let b=y[1],v=b instanceof Error?b.message:String(b),T=b instanceof Error?b:void 0;g(()=>c(new Ce("internal-error",`reduce: output emitted ERROR: ${v}`,T!=null?{cause:T}:void 0)));return}if(y[0]===C){g(()=>c(new Ce("internal-error","reduce: output COMPLETEd without a post-push DATA")));return}}}}),m&&(f?.(),f=void 0),d=!0;try{i.set(r,e)}catch(h){let y=h instanceof Error?h.message:String(h),b=h instanceof Error?h:void 0;g(()=>c(new Ce("internal-error",`reduce: failed to set input on "${r}": ${y}`,b!=null?{path:r,cause:b}:{path:r})));return}!l&&Number.isFinite(s)&&s>0&&(p=setTimeout(()=>{g(()=>c(new Ce("reduce-timeout",`reduce: no output emitted within ${s}ms`,{timeoutMs:s,outputPath:o})))},s),p.unref?.())})}finally{i.destroy()}}_e();var Ro=pt,ko="snapshot:";function xo(t){if(t.startsWith(ko))throw new Ce("snapshot-failed",`snapshot id must not start with "${ko}" (reserved); got "${t}"`,{snapshotId:t})}function _i(t){return`${ko}${t}`}function ob(t){return t.startsWith(ko)?t.slice(ko.length):void 0}function Mu(t,e){if(t==null||typeof t!="object")throw new Ce("snapshot-not-found",`snapshot "${e}" not found in tier`,{snapshotId:e});let n=t;if("mode"in n){if(n.mode==="full"&&"snapshot"in n)return n.snapshot;throw n.mode==="diff"?new Ce("restore-failed",`snapshot "${e}" is a diff record; restore the baseline and replay WAL instead`,{snapshotId:e,mode:"diff"}):new Ce("restore-failed",`snapshot "${e}" has unknown mode "${String(n.mode)}"`,{snapshotId:e,mode:String(n.mode)})}if("nodes"in n&&"edges"in n&&"subgraphs"in n&&"name"in n)return n;throw new Ce("restore-failed",`snapshot "${e}" payload is not a GraphCheckpointRecord or GraphPersistSnapshot`,{snapshotId:e})}async function Mi(t,e,n){xo(e);let r;try{r=t.snapshot()}catch(s){let i=s instanceof Error?s.message:String(s);throw new Ce("snapshot-failed",`snapshot "${e}" serialization failed: ${i}`,{snapshotId:e})}let o={mode:"full",seq:0,timestamp_ns:Te(),format_version:Ro,snapshot:r};try{await n.save(_i(e),o)}catch(s){let i=s instanceof Error?s.message:String(s);throw new Ce("snapshot-failed",`snapshot "${e}" save failed: ${i}`,{snapshotId:e})}return{snapshotId:e,timestamp_ns:o.timestamp_ns}}async function Oi(t,e,n){xo(t);let r=_i(t),o=await e.load(r);o==null&&(o=await e.load(t));let s=Mu(o,t);try{return Y.fromSnapshot(s,n?.factories?{factories:n.factories}:void 0)}catch(i){let a=i instanceof Error?i.message:String(i);throw new Ce("restore-failed",`snapshot "${t}" restore failed: ${a}`,{snapshotId:t})}}async function Ci(t,e,n){xo(t),xo(e);let r=async u=>{let c=_i(u),d=await n.load(c);return d==null&&(d=await n.load(u)),d},[o,s]=await Promise.all([r(t),r(e)]),i=Mu(o,t),a=Mu(s,e);return Y.diff(i,a)}async function Ai(t,e){if(typeof t.list!="function")throw new Ce("tier-no-list","StorageTier does not implement list(); wrap the tier with an enumerator or use a different backend");let n=await t.list(),r=[],o=e?.includeUnprefixed===!0;for(let s of n){let i=ob(s);i!==void 0?r.push(i):o&&r.push(s)}return r}async function Li(t,e){if(xo(t),typeof e.clear!="function")throw new Ce("snapshot-failed",`StorageTier is append-only (no clear()); cannot delete "${t}"`,{snapshotId:t});try{await e.clear(_i(t))}catch(n){let r=n instanceof Error?n.message:String(n);throw new Ce("snapshot-failed",`snapshot "${t}" delete failed: ${r}`,{snapshotId:t})}}var sb="0.0.0";0&&(module.exports={COMPLETE,COMPLETE_MSG,COMPLETE_ONLY_BATCH,CircuitOpenError,ContentAddressedMissError,DATA,DEFAULT_ACTOR,DIRTY,DIRTY_MSG,DIRTY_ONLY_BATCH,ENVELOPE_VERSION,ERROR,GRAPH_META_SEGMENT,Graph,GraphReFlyConfig,GuardDenied,INVALIDATE,INVALIDATE_MSG,INVALIDATE_ONLY_BATCH,JsonCodec,NS_PER_MS,NS_PER_SEC,NativeIndexBackend,NativeListBackend,NativeLogBackend,NativeMapBackend,NativePubSubBackend,NodeImpl,PAUSE,RESOLVED,RESOLVED_MSG,RESOLVED_ONLY_BATCH,RESUME,RateLimiterOverflowError,ResettableTimer,SIZEOF_OVERHEAD,SIZEOF_SYMBOL,SNAPSHOT_VERSION,SNAPSHOT_WIRE_VERSION,START,START_MSG,SurfaceError,TEARDOWN,TEARDOWN_MSG,TEARDOWN_ONLY_BATCH,TimeoutError,accessHintForGuard,accountability,advanceVersion,ai,asSurfaceError,audit,autoTrackNode,awaitSettled,batch,buffer,bufferCount,bufferTime,cached,canonicalJson,cascadingCache,catchError,checkpointToRedis,checkpointToS3,circuitBreaker,combine,combineLatest,compat,concat,concatMap,configure,constant,contentAddressedStorage,core,cqrs,createDagCborCodec,createDagCborZstdCodec,createGraph,createTransport,createVersioning,createWatermarkController,csvRows,debounce,debounceTime,decodeEnvelope,decorrelatedJitter,defaultConfig,defaultHash,delay,deleteSnapshot,demoShell,derived,deserializeError,dictStorage,diffForWAL,diffSnapshots,distill,distinctUntilChanged,domainTemplates,downWithBatch,dynamicNode,effect,elementAt,empty,encodeEnvelope,escapeRegexChar,exhaustMap,explainPath,exponential,externalBundle,externalProducer,extra,fallback,fibonacci,filter,find,first,firstValueFrom,firstWhere,flatMap,forEach,fromAny,fromAsyncIter,fromCSV,fromClickHouseWatch,fromCron,fromDrizzle,fromEvent,fromHTTP,fromHTTPPoll,fromHTTPStream,fromIter,fromKafka,fromKysely,fromMCP,fromNATS,fromNDJSON,fromOTel,fromPrisma,fromPrometheus,fromPromise,fromPulsar,fromRabbitMQ,fromRaf,fromRedisStream,fromSSE,fromSqlite,fromSqliteCursor,fromStatsD,fromSyslog,fromTimer,fromWebSocket,fromWebSocketReconnect,fromWebhook,globToRegExp,graph,graphProfile,graphspec,guarded,harness,interval,isBatching,isV1,jobQueue,jotai,keepalive,last,layout,lens,linear,listSnapshots,lru,makeHttpError,map,matchesAnyPattern,matchesCron,memory,memoryStorage,merge,mergeMap,mermaidLiveUrl,messaging,monotonicNs,nameToSignal,nanostores,ndjsonRows,nestjs,never,node,nodeSignal,normalizeActor,of,onFirstData,orchestration,pairwise,parseCron,parsePrometheusText,parseSSEStream,parseStatsD,parseSyslog,patterns,pausable,pipe,policy,policyFromRules,producer,pubsub,race,rateLimiter,reachable,react,reactiveCounter,reactiveIndex,reactiveList,reactiveLog,reactiveMap,reactiveSink,reduce,reduction,refine,registerBuiltinCodecs,registerBuiltins,repeat,replay,replayWAL,rescue,resilientPipeline,resolveBackoffPreset,resolveDescribeFields,restoreSnapshot,retry,retrySource,runReduction,sample,saveSnapshot,scan,serializeError,share,shareReplay,signalToName,signals,singleFromAny,singleNodeFromAny,sizeof,skip,solid,sortJsonValue,stableJsonString,state,stratify,surface,svelte,switchMap,take,takeUntil,takeWhile,tap,tapFirst,throttle,throttleTime,throwError,timeout,toArray,toCSV,toClickHouse,toFile,toHTTP,toKafka,toLoki,toMongo,toNATS,toObservable,toPostgres,toPulsar,toRabbitMQ,toReadableStream,toRedisStream,toS3,toSSE,toSSEBytes,toSqlite,toTempo,toWebSocket,tokenBucket,validateGraphObservability,valve,verifiable,version,vue,wallClockNs,watchTopologyTree,window,windowCount,windowTime,withBreaker,withLatestFrom,withMaxAttempts,withStatus,workerBridge,workerSelf,zip,zustand});
222
+ `)}`,{errors:n.errors});let r=e?.catalog??{},s=fo(t,r);if(!s.valid)throw new Ee("catalog-error",`Catalog validation failed:
223
+ ${s.errors.join(`
224
+ `)}`,{errors:s.errors});try{return mo(t,e)}catch(o){let i=o instanceof Error?o.message:String(o);throw new Ee("catalog-error",i)}}se();var db=3e4;async function ki(t,e,n){let r=n?.inputPath??"input",s=n?.outputPath??"output",o=n?.timeoutMs??db,i=cr(t,{catalog:n?.catalog}),a;try{a=i.resolve(s)}catch{throw i.destroy(),new Ee("node-not-found",`reduce: output path "${s}" is not registered`,{path:s})}try{i.resolve(r)}catch{throw i.destroy(),new Ee("node-not-found",`reduce: input path "${r}" is not registered`,{path:r})}try{return await new Promise((u,d)=>{let c=!1,l=!1,p,f,m=!1,g=h=>{l||(l=!0,p!==void 0&&clearTimeout(p),f!==void 0?(f(),f=void 0):m=!0,h())};f=a.subscribe(h=>{for(let y of h){if(l)return;if(c){if(y[0]===R){g(()=>u(y[1]));return}if(y[0]===G){let b=a.cache;g(()=>u(b));return}if(y[0]===M){let b=y[1],v=b instanceof Error?b.message:String(b),T=b instanceof Error?b:void 0;g(()=>d(new Ee("internal-error",`reduce: output emitted ERROR: ${v}`,T!=null?{cause:T}:void 0)));return}if(y[0]===O){g(()=>d(new Ee("internal-error","reduce: output COMPLETEd without a post-push DATA")));return}}}}),m&&(f?.(),f=void 0),c=!0;try{i.set(r,e)}catch(h){let y=h instanceof Error?h.message:String(h),b=h instanceof Error?h:void 0;g(()=>d(new Ee("internal-error",`reduce: failed to set input on "${r}": ${y}`,b!=null?{path:r,cause:b}:{path:r})));return}!l&&Number.isFinite(o)&&o>0&&(p=setTimeout(()=>{g(()=>d(new Ee("reduce-timeout",`reduce: no output emitted within ${o}ms`,{timeoutMs:o,outputPath:s})))},o),p.unref?.())})}finally{i.destroy()}}Ne();var vo=pt,yo="snapshot:";function bo(t){if(t.startsWith(yo))throw new Ee("snapshot-failed",`snapshot id must not start with "${yo}" (reserved); got "${t}"`,{snapshotId:t})}function xi(t){return`${yo}${t}`}function cb(t){return t.startsWith(yo)?t.slice(yo.length):void 0}function Au(t,e){if(t==null||typeof t!="object")throw new Ee("snapshot-not-found",`snapshot "${e}" not found in tier`,{snapshotId:e});let n=t;if("mode"in n){if(n.mode==="full"&&"snapshot"in n)return n.snapshot;throw n.mode==="diff"?new Ee("restore-failed",`snapshot "${e}" is a diff record; restore the baseline and replay WAL instead`,{snapshotId:e,mode:"diff"}):new Ee("restore-failed",`snapshot "${e}" has unknown mode "${String(n.mode)}"`,{snapshotId:e,mode:String(n.mode)})}if("nodes"in n&&"edges"in n&&"subgraphs"in n&&"name"in n)return n;throw new Ee("restore-failed",`snapshot "${e}" payload is not a GraphCheckpointRecord or GraphPersistSnapshot`,{snapshotId:e})}async function Ri(t,e,n){bo(e);let r;try{r=t.snapshot()}catch(o){let i=o instanceof Error?o.message:String(o);throw new Ee("snapshot-failed",`snapshot "${e}" serialization failed: ${i}`,{snapshotId:e})}let s={mode:"full",seq:0,timestamp_ns:ce(),format_version:vo,snapshot:r};try{await n.save(xi(e),s)}catch(o){let i=o instanceof Error?o.message:String(o);throw new Ee("snapshot-failed",`snapshot "${e}" save failed: ${i}`,{snapshotId:e})}return{snapshotId:e,timestamp_ns:s.timestamp_ns}}async function Si(t,e,n){bo(t);let r=xi(t),s=await e.load(r);s==null&&(s=await e.load(t));let o=Au(s,t);try{return q.fromSnapshot(o,n?.factories?{factories:n.factories}:void 0)}catch(i){let a=i instanceof Error?i.message:String(i);throw new Ee("restore-failed",`snapshot "${t}" restore failed: ${a}`,{snapshotId:t})}}async function Ni(t,e,n){bo(t),bo(e);let r=async u=>{let d=xi(u),c=await n.load(d);return c==null&&(c=await n.load(u)),c},[s,o]=await Promise.all([r(t),r(e)]),i=Au(s,t),a=Au(o,e);return q.diff(i,a)}async function Ei(t,e){if(typeof t.list!="function")throw new Ee("tier-no-list","StorageTier does not implement list(); wrap the tier with an enumerator or use a different backend");let n=await t.list(),r=[],s=e?.includeUnprefixed===!0;for(let o of n){let i=cb(o);i!==void 0?r.push(i):s&&r.push(o)}return r}async function _i(t,e){if(bo(t),typeof e.clear!="function")throw new Ee("snapshot-failed",`StorageTier is append-only (no clear()); cannot delete "${t}"`,{snapshotId:t});try{await e.clear(xi(t))}catch(n){let r=n instanceof Error?n.message:String(n);throw new Ee("snapshot-failed",`snapshot "${t}" delete failed: ${r}`,{snapshotId:t})}}var lb="0.0.0";0&&(module.exports={COMPLETE,COMPLETE_MSG,COMPLETE_ONLY_BATCH,CircuitOpenError,ContentAddressedMissError,DATA,DEFAULT_ACTOR,DIRTY,DIRTY_MSG,DIRTY_ONLY_BATCH,ENVELOPE_VERSION,ERROR,GRAPH_META_SEGMENT,Graph,GraphReFlyConfig,GuardDenied,INVALIDATE,INVALIDATE_MSG,INVALIDATE_ONLY_BATCH,JsonCodec,NS_PER_MS,NS_PER_SEC,NativeIndexBackend,NativeListBackend,NativeLogBackend,NativeMapBackend,NativePubSubBackend,NodeImpl,PAUSE,RESOLVED,RESOLVED_MSG,RESOLVED_ONLY_BATCH,RESUME,RateLimiterOverflowError,ResettableTimer,SIZEOF_OVERHEAD,SIZEOF_SYMBOL,SNAPSHOT_VERSION,SNAPSHOT_WIRE_VERSION,START,START_MSG,SurfaceError,TEARDOWN,TEARDOWN_MSG,TEARDOWN_ONLY_BATCH,TimeoutError,accessHintForGuard,accountability,advanceVersion,ai,asSurfaceError,audit,autoTrackNode,awaitSettled,batch,buffer,bufferCount,bufferTime,cached,canonicalJson,cascadingCache,catchError,checkpointToRedis,checkpointToS3,circuitBreaker,combine,combineLatest,compat,concat,concatMap,configure,constant,contentAddressedStorage,core,cqrs,createDagCborCodec,createDagCborZstdCodec,createGraph,createTransport,createVersioning,createWatermarkController,csvRows,debounce,debounceTime,decodeEnvelope,decorrelatedJitter,defaultConfig,defaultHash,delay,deleteSnapshot,demoShell,derived,deserializeError,dictStorage,diffForWAL,diffSnapshots,distill,distinctUntilChanged,domainTemplates,downWithBatch,dynamicNode,effect,elementAt,empty,encodeEnvelope,escapeRegexChar,exhaustMap,explainPath,exponential,externalBundle,externalProducer,extra,fallback,fibonacci,filter,find,first,firstValueFrom,firstWhere,flatMap,forEach,fromAny,fromAsyncIter,fromCSV,fromClickHouseWatch,fromCron,fromDrizzle,fromEvent,fromHTTP,fromHTTPPoll,fromHTTPStream,fromIter,fromKafka,fromKysely,fromMCP,fromNATS,fromNDJSON,fromOTel,fromPrisma,fromPrometheus,fromPromise,fromPulsar,fromRabbitMQ,fromRaf,fromRedisStream,fromSSE,fromSqlite,fromSqliteCursor,fromStatsD,fromSyslog,fromTimer,fromWebSocket,fromWebSocketReconnect,fromWebhook,globToRegExp,graph,graphProfile,graphspec,guarded,harness,interval,isBatching,isV1,jobQueue,jotai,keepalive,last,layout,lens,linear,listSnapshots,lru,makeHttpError,map,matchesAnyPattern,matchesCron,memory,memoryStorage,merge,mergeMap,mermaidLiveUrl,messaging,monotonicNs,nameToSignal,nanostores,ndjsonRows,nestjs,never,node,nodeSignal,normalizeActor,of,onFirstData,orchestration,pairwise,parseCron,parsePrometheusText,parseSSEStream,parseStatsD,parseSyslog,patterns,pausable,pipe,policy,policyFromRules,producer,pubsub,race,rateLimiter,reachable,react,reactiveCounter,reactiveIndex,reactiveList,reactiveLog,reactiveMap,reactiveSink,reduce,reduction,refine,registerBuiltinCodecs,registerBuiltins,repeat,replay,replayWAL,rescue,resilientPipeline,resolveBackoffPreset,resolveDescribeFields,restoreSnapshot,retry,retrySource,runReduction,sample,saveSnapshot,scan,serializeError,share,shareReplay,signalToName,signals,singleFromAny,singleNodeFromAny,sizeof,skip,solid,sortJsonValue,stableJsonString,state,stratify,surface,svelte,switchMap,take,takeUntil,takeWhile,tap,tapFirst,throttle,throttleTime,throwError,timeout,toArray,toCSV,toClickHouse,toFile,toHTTP,toKafka,toLoki,toMongo,toNATS,toObservable,toPostgres,toPulsar,toRabbitMQ,toReadableStream,toRedisStream,toS3,toSSE,toSSEBytes,toSqlite,toTempo,toWebSocket,tokenBucket,validateGraphObservability,valve,verifiable,version,vue,wallClockNs,watchTopologyTree,window,windowCount,windowTime,withBreaker,withLatestFrom,withMaxAttempts,withStatus,workerBridge,workerSelf,zip,zustand});