@callbag-recharge/callbag-recharge 0.18.0 → 0.19.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/README.md CHANGED
@@ -171,7 +171,7 @@ const log = reactiveLog<string>({ maxSize: 1000 })
171
171
  log.append('event happened')
172
172
  const recent = log.slice(-10) // Store<string[]> — reactive
173
173
 
174
- // Reactive Index — dual-key lookup, 1.01x native Map.get speed on reads
174
+ // Reactive Index — dual-key lookup, ~1.2x native Map.get speed on reads
175
175
  const index = reactiveIndex<string, string, Item>()
176
176
  index.set('pk', 'sk', item)
177
177
  const found = index.select('pk', 'sk') // Store<Item | undefined>
@@ -211,7 +211,7 @@ forEach(events, (signal, event) => process(event))
211
211
 
212
212
  ## Agent memory
213
213
 
214
- Reactive memory primitives for agentic workflows — push-based dirty tracking, decay-scored eviction, tag-based retrieval.
214
+ Reactive memory primitives for agentic workflows — decay-scored eviction, O(1) tag retrieval, push-based score tracking.
215
215
 
216
216
  ```ts
217
217
  import { collection, memoryNode } from 'callbag-recharge/memory'
@@ -219,10 +219,14 @@ import { collection, memoryNode } from 'callbag-recharge/memory'
219
219
  const memory = collection<string>({ maxSize: 100 })
220
220
  memory.add('User prefers TypeScript', { id: 'pref-1', tags: ['preference'] })
221
221
 
222
- // Tag-based retrieval via reactive index
222
+ // O(1) tag-based retrieval via reactive index
223
223
  memory.tagIndex.select('preference').get() // Set{'pref-1'}
224
224
 
225
- // Decay-scored eviction — oldest/least important items evicted first
225
+ // O(log n) eviction — live min-heap, scores update reactively as nodes are
226
+ // touched/tagged. No O(n) scan at eviction time.
227
+ memory.add('Older fact', { tags: ['context'] })
228
+ memory.add('Recent fact', { tags: ['context'] }) // touches bump score
229
+ // When maxSize exceeded, lowest-scoring node evicted automatically
226
230
  ```
227
231
 
228
232
  ---
@@ -0,0 +1 @@
1
+ import{a as D}from"./chunk-JCENQEPP.js";import{a as A}from"./chunk-ZJCF5NYF.js";import{a as N}from"./chunk-PV347CGV.js";import{a as w}from"./chunk-GMLWTZFM.js";import{a as h}from"./chunk-EAK2HKAD.js";import{B as S,v as b}from"./chunk-TUPD47IE.js";function O(d){let a=d?.halfLife??864e5,m=d?.recency??1,u=d?.importance??1,t=d?.frequency??.5,i=Math.LN2/a;return(o,f)=>{let y=(f??Date.now())-o.accessedAt,g=Math.exp(-i*y),s=1-1/(1+o.accessCount);return m*g+u*o.importance+t*s}}function T(d,a,m){let u=a?.halfLife??864e5,t=a?.recency??1,i=a?.importance??1,o=a?.frequency??.5,f=(m??Date.now())-d.accessedAt,y=Math.exp(-Math.LN2/u*f),g=1-1/(1+d.accessCount);return t*y+i*d.importance+o*g}var F=0;function W(){return`mem-${++F}`}function L(d,a){let m=a?.id??W(),u=Date.now(),t={id:m,createdAt:u,updatedAt:u,accessedAt:u,accessCount:0,importance:a?.importance??.5,tags:new Set(a?.tags)},i=h(d,{name:`mem:${m}:content`}),o=h(t,{name:`mem:${m}:meta`,equals:()=>!1}),f={},y=N([o],()=>T(o.get(),f),{name:`mem:${m}:score`});return{id:m,content:i,meta:o,scoreStore:y,touch(){let s=Date.now();o.update(c=>({...c,accessedAt:s,accessCount:c.accessCount+1}))},tag(...s){o.update(c=>{let p=new Set(c.tags);for(let I of s)p.add(I);return{...c,tags:p,updatedAt:Date.now()}})},untag(...s){o.update(c=>{let p=new Set(c.tags);for(let I of s)p.delete(I);return{...c,tags:p,updatedAt:Date.now()}})},setImportance(s){o.update(c=>({...c,importance:Math.max(0,Math.min(1,s)),updatedAt:Date.now()}))},update(s){b(()=>{i.set(s),o.update(c=>({...c,updatedAt:Date.now()}))})},score(s){return T(o.get(),s??f)},destroy(){S(i),S(o)}}}var z=0;function X(d){let a=++z,m=d?.maxSize??1/0,u=d?.weights??{},t=new Map,i=A(),o=new Map,f=m<1/0?D(e=>t.get(e).meta,e=>T(e,u)):null,y=h(0,{name:`collection-${a}:ver`}),g=N([y],()=>Array.from(t.values()),{name:`collection-${a}:nodes`}),s=N([y],()=>t.size,{name:`collection-${a}:size`}),c=!1;function p(){y.update(e=>e+1)}function I(e){let r=Array.from(e.meta.get().tags);i.update(e.id,r);let n=w(e.meta,v=>{let l=Array.from(v.tags);i.update(e.id,l)});o.set(e.id,()=>n.unsubscribe())}function _(e){let r=o.get(e);r&&(r(),o.delete(e)),i.remove(e)}function x(){if(!f||t.size<=m)return;let e=f.evict(t.size-m);for(let r of e){let n=t.get(r);n&&(_(r),n.destroy(),t.delete(r))}}return{add(e,r){if(c)throw new Error("Collection is destroyed");let n=L(e,r);return t.set(n.id,n),I(n),f?.insert(n.id),x(),p(),n},remove(e){let r=typeof e=="string"?e:e.id,n=t.get(r);return n?(_(r),f?.delete(r),n.destroy(),t.delete(r),p(),!0):!1},get(e){return t.get(e)},has(e){return t.has(e)},nodes:g,size:s,tagIndex:i,query(e){let r=[];for(let n of t.values())e(n)&&r.push(n);return r},byTag(e){let r=i.get(e),n=[];for(let v of r){let l=t.get(v);l&&n.push(l)}return n},topK(e,r){let n=r??u,v=Date.now(),l=Array.from(t.values()).map(M=>({node:M,score:T(M.meta.get(),n,v)}));return l.sort((M,C)=>C.score-M.score),l.slice(0,e).map(M=>M.node)},destroy(){if(!c){c=!0,f?.clear();for(let e of o.values())e();o.clear(),i.destroy(),S(y),b(()=>{for(let e of t.values())e.destroy();t.clear()})}}}}export{O as a,T as b,L as c,X as d};
@@ -0,0 +1 @@
1
+ import{a as m}from"./chunk-GMLWTZFM.js";function g(h,f=o=>o){let o=[],s=new Map,c=new Map;function p(e,n){let t=o[e],r=o[n];o[e]=r,o[n]=t,t.index=n,r.index=e}function l(e){for(;e>0;){let n=e-1>>>1;if(o[n].score<=o[e].score)break;p(e,n),e=n}}function d(e){let n=o.length;for(;;){let t=e,r=2*e+1,u=r+1;if(r<n&&o[r].score<o[t].score&&(t=r),u<n&&o[u].score<o[t].score&&(t=u),t===e)break;p(e,t),e=t}}function a(e){let n=o.length-1;if(e===n){o.pop();return}p(e,n),o.pop(),l(e),d(e)}return{touch(){},insert(e){if(s.has(e))return;let n=h(e),t={key:e,score:f(n.get()),index:o.length};o.push(t),s.set(e,t),l(t.index);let r=m(n,u=>{let i=s.get(e);if(!i)return;let b=i.score;i.score=f(u),i.score<b?l(i.index):i.score>b&&d(i.index)});c.set(e,()=>r.unsubscribe())},delete(e){let n=s.get(e);if(!n)return;let t=c.get(e);t&&(t(),c.delete(e)),a(n.index),s.delete(e)},evict(e=1){let n=[];for(;n.length<e&&o.length>0;){let{key:t}=o[0];n.push(t);let r=c.get(t);r&&(r(),c.delete(t)),a(0),s.delete(t)}return n},size:()=>s.size,clear(){for(let e of c.values())e();c.clear(),s.clear(),o.length=0}}}export{g as a};
@@ -1,4 +1,4 @@
1
- "use strict";var Ie=Object.defineProperty;var Ve=Object.getOwnPropertyDescriptor;var We=Object.getOwnPropertyNames;var je=Object.prototype.hasOwnProperty;var Ue=(i,e)=>{for(var s in e)Ie(i,s,{get:e[s],enumerable:!0})},ze=(i,e,s,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of We(e))!je.call(i,n)&&n!==s&&Ie(i,n,{get:()=>e[n],enumerable:!(t=Ve(e,n))||t.enumerable});return i};var Ke=i=>ze(Ie({},"__esModule",{value:!0}),i);var nt={};Ue(nt,{collection:()=>Fe,computeScore:()=>q,decay:()=>Pe,memoryNode:()=>we});module.exports=Ke(nt);var J=class{_v;_w;constructor(e){this._v=0,this._w=e>32?new Uint32Array((e-1>>>5)+1):null}set(e){let s=this._w;if(s===null)this._v|=1<<e;else{let t=e>>>5,n=1<<(e&31);s[t]&n||(s[t]|=n,this._v++)}}clear(e){let s=this._w;if(s===null)this._v&=~(1<<e);else{let t=e>>>5,n=1<<(e&31);s[t]&n&&(s[t]&=~n,this._v--)}}test(e){let s=this._w;return s===null?(this._v&1<<e)!==0:(s[e>>>5]&1<<(e&31))!==0}empty(){return this._v===0}reset(){this._v=0,this._w?.fill(0)}};var T=Symbol("DIRTY"),D=Symbol("RESOLVED"),H=Symbol("SINGLE_DEP"),U=Symbol("RESET"),Ye=Symbol("PAUSE"),qe=Symbol("RESUME"),F=Symbol("TEARDOWN");function Z(i){return i===U||i===Ye||i===qe||i===F}var ue=0,fe=1,de=2,pe=3,he=4,ge=5,k=7,ne=7<<k,He=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function _e(i){return He[(i&ne)>>>k]}var y=0,v=1,S=2,m=3,oe=0,ae=[],Re=!1;function V(i){oe++;try{return i()}finally{if(oe--,oe===0&&!Re){Re=!0;for(let e=0;e<ae.length;e++)ae[e]();ae.length=0,Re=!1}}}function B(){return oe>0}function me(i){ae.push(i)}var le=0,ce=[];function Se(){le++}function ye(){if(le--,le===0){for(let i=0;i<ce.length;i++)ce[i]();ce.length=0}}function Ae(i){le>0?ce.push(i):i()}function W(i){let e=i;typeof e.complete=="function"?e.complete():typeof e._handleEnd=="function"&&e._handleEnd(void 0)}var M=class i{static _names=new WeakMap;static _kinds=new WeakMap;static _keys=new WeakMap;static _stores=new Set;static _edges=new Map;static _nextId=0;static _usedKeys=new Set;static _explicitEnabled=null;static _cachedDefault=null;static _annotations=new WeakMap;static _traceLog=[];static _traceHead=0;static _traceFull=!1;static maxTraceEntries=1e3;static get enabled(){if(i._explicitEnabled!==null)return i._explicitEnabled;if(i._cachedDefault!==null)return i._cachedDefault;try{i._cachedDefault=globalThis.process?.env?.NODE_ENV!=="production"}catch{i._cachedDefault=!0}return i._cachedDefault}static set enabled(e){i._explicitEnabled=e}static _depSuffix(e){if(!e?.length)return;let t=e.map(n=>i._names.get(n)??"?").join(",");return t.length>40?`${t.slice(0,37)}...`:t}static _resolveKey(e){let s=i._keys.get(e)??i._names.get(e);if(s)return s;let t=`anonymous_${i._nextId++}`;return i._keys.set(e,t),t}static register(e,s){if(!i.enabled)return;s?.name&&i._names.set(e,s.name),s?.kind&&i._kinds.set(e,s.kind);let t=i._nextId++,n=s?.name;if(!(n&&!i._usedKeys.has(n)))if(n){let o=i._depSuffix(s?.deps);n=o?`${n}(${o})`:`${n}_${t}`,i._usedKeys.has(n)&&(n=`${n}_${t}`)}else{let o=s?.kind??"store",a=i._depSuffix(s?.deps);n=a?`${o}(${a})`:`${o}_${t}`,i._usedKeys.has(n)&&(n=`${n}_${t}`)}i._usedKeys.add(n),i._keys.set(e,n),i._stores.add(new WeakRef(e))}static registerEdge(e,s){if(!i.enabled)return;let t=i._resolveKey(e),n=i._resolveKey(s),o=i._edges.get(t);o?o.includes(n)||o.push(n):i._edges.set(t,[n])}static getEdges(){return new Map(i._edges)}static getName(e){if(i.enabled)return i._names.get(e)}static getKind(e){return i._kinds.get(e)}static inspect(e){return{name:i._names.get(e),kind:i._kinds.get(e)??"unknown",value:typeof e.get=="function"?e.get():void 0,status:e._status}}static graph(){let e=new Map,s=new Set;for(let t of i._stores){let n=t.deref();if(!n){i._stores.delete(t);continue}let o=i._resolveKey(n);s.add(o),e.set(o,i.inspect(n))}for(let[t,n]of i._edges){if(!s.has(t)){i._edges.delete(t),i._usedKeys.delete(t);continue}let o=n.filter(a=>s.has(a));o.length===0?i._edges.delete(t):o.length!==n.length&&i._edges.set(t,o)}return e}static trace(e,s){let t=null,n=e.get();return e.source(y,(o,a)=>{if(o===y&&(t=a),o===S){t=null;return}if(o===1){let u=a;if(!Object.is(u,n)){let d=n;n=u,s(u,d)}}}),()=>t?.(S)}static dumpGraph(){let e=i.graph(),s=i.getEdges(),t=new Map;for(let[a,u]of s)for(let d of u){let f=t.get(d);f?f.includes(a)||f.push(a):t.set(d,[a])}let n=[];for(let[a,u]of e){let d=t.get(a),f=s.get(a),r=d?.length?` \u2190 [${d.join(", ")}]`:"",c=f?.length?` \u2192 [${f.join(", ")}]`:"";n.push(` ${a} (${u.kind}) = ${JSON.stringify(u.value)} [${u.status??"?"}]${r}${c}`)}return[`Store Graph (${e.size} nodes):`,...n].join(`
2
- `)}static _signalLabel(e){return e===T?"DIRTY":e===D?"RESOLVED":typeof e=="symbol"?e.description??String(e):String(e)}static _observe(e,s,t){let n=null,o=!1,a=s??i.getName(e),u=[],d={values:[],signals:[],events:[],ended:!1,endError:void 0,get completedCleanly(){return d.ended&&!o},get errored(){return d.ended&&o},dirtyCount:0,resolvedCount:0,name:a,get eventLog(){return u},dispose:()=>n?.(S),reconnect:()=>(n?.(S),i._observe(e,s,t))};return e.source(y,(f,r)=>{if(f===y){n=r;return}let c=B();f===v?(d.values.push(r),d.events.push({type:"data",data:r,inBatch:c}),u.push(r),t&&t(`[${a}] DATA:`,r)):f===m?(d.signals.push(r),d.events.push({type:"signal",data:r,inBatch:c}),u.push(i._signalLabel(r)),r===T?d.dirtyCount++:r===D&&d.resolvedCount++,t&&t(`[${a}] STATE:`,r)):f===S&&(d.ended=!0,d.endError=r,o=r!==void 0,d.events.push({type:"end",data:r,inBatch:c}),u.push(o?["END",r]:"END"),t&&t(`[${a}] END`,r!==void 0?r:""),n=null)}),d}static observe(e){return i._observe(e)}static activate(e){let s=null;return e.source(y,(t,n)=>{t===y&&(s=n),t===S&&(s=null)}),()=>s?.(S)}static tap(e,s){let t=s??`tap(${i.getName(e)??"anon"})`,n={get:()=>e.get(),source:e.source};return i.register(n,{name:t,kind:"tap"}),i.registerEdge(e,n),n}static spy(e,s){let t=s?.name??i.getName(e)??"spy",n=s?.log??console.log;return i._observe(e,t,n)}static snapshot(){let e=i.graph(),s=i.getEdges(),t=new Map;for(let a of i._stores){let u=a.deref();if(!u)continue;let d=i._annotations.get(u);d!==void 0&&t.set(i._resolveKey(u),d)}let n=[];for(let[a,u]of e){let d={name:a,kind:u.kind,value:u.value,status:u.status},f=t.get(a);f!==void 0&&(d.annotation=f),n.push(d)}let o=[];for(let[a,u]of s)for(let d of u)o.push({from:a,to:d});return{nodes:n,edges:o,trace:i.traceLog()}}static toMermaid(e){let s=e?.direction??"TD",t=i.snapshot(),n=[`graph ${s}`],o={SETTLED:":::settled",DIRTY:":::dirty",ERRORED:":::errored",COMPLETED:":::completed"},a=new Map;function u(r){let c=r.replace(/[^a-zA-Z0-9_]/g,"_"),h=a.get(c);return h===void 0?(a.set(c,1),c):(a.set(c,h+1),`${c}__${h}`)}let d=new Map;function f(r){let c=JSON.stringify(r);return c&&c.length>30?`${c.slice(0,27)}...`:c??"undefined"}for(let r of t.nodes){let c=u(r.name);d.set(r.name,c);let h=`${r.name} (${r.kind}) = ${f(r.value)}`,_=o[r.status??""]??"";n.push(` ${c}["${h}"]${_}`)}for(let r of t.edges){let c=d.get(r.from)??u(r.from),h=d.get(r.to)??u(r.to);n.push(` ${c} --> ${h}`)}return n.push(""),n.push(" classDef settled fill:#d4edda,stroke:#28a745"),n.push(" classDef dirty fill:#fff3cd,stroke:#ffc107"),n.push(" classDef errored fill:#f8d7da,stroke:#dc3545"),n.push(" classDef completed fill:#cce5ff,stroke:#007bff"),n.join(`
3
- `)}static toD2(e){let s=e?.direction??"down",t=i.snapshot(),n=[`direction: ${s}`,""],o={state:"rectangle",derived:"hexagon",effect:"oval",producer:"rectangle",operator:"parallelogram","pipeline-step":"rectangle","pipeline-status":"diamond",checkpoint:"cylinder"},a=new Map;function u(r){let c=r.replace(/[^a-zA-Z0-9_]/g,"_"),h=a.get(c);return h===void 0?(a.set(c,1),c):(a.set(c,h+1),`${c}__${h}`)}let d=new Map;function f(r){let c=JSON.stringify(r);return c&&c.length>30?`${c.slice(0,27)}...`:c??"undefined"}for(let r of t.nodes){let c=u(r.name);d.set(r.name,c);let h=o[r.kind]??"rectangle",_=`${r.name} (${r.kind}) = ${f(r.value)}`,I=r.status?` [${r.status}]`:"";n.push(`${c}: "${_}${I}" { shape: ${h} }`)}t.edges.length>0&&n.push("");for(let r of t.edges){let c=d.get(r.from)??u(r.from),h=d.get(r.to)??u(r.to);n.push(`${c} -> ${h}`)}return n.join(`
4
- `)}static annotate(e,s){if(!i.enabled)return;i._annotations.set(e,s);let t={node:i._resolveKey(e),reason:s,timestamp:Date.now()},n=i.maxTraceEntries;n<=0||(i._traceLog.length<n?i._traceLog.push(t):(i._traceLog[i._traceHead]=t,i._traceFull=!0),i._traceHead=(i._traceHead+1)%n)}static getAnnotation(e){return i._annotations.get(e)}static traceLog(){return i._traceFull?[...i._traceLog.slice(i._traceHead),...i._traceLog.slice(0,i._traceHead)]:i._traceLog.slice(0,i._traceHead||i._traceLog.length)}static clearTrace(){i._traceLog=[],i._traceHead=0,i._traceFull=!1}static timeline(e){let s=null,t=[];return e.source(y,(n,o)=>{if(n===y){s=o;return}let a={timestamp:Date.now(),type:n===v?"data":n===m?"signal":"end",data:o,inBatch:B()};t.push(a),n===S&&(s=null)}),{entries:t,dispose:()=>s?.(S)}}static observeDerived(e){let s=[],t=e,n=t._fn;if(typeof n!="function"||!Array.isArray(t._deps))return{...i.observe(e),evaluations:s};t._fn=()=>{let d=t._deps.map(r=>r.get()),f=n();return s.push({result:f,depValues:d,timestamp:Date.now()}),f};let o=i._observe(e),a=o.dispose;return{...o,evaluations:s,dispose:()=>{t._fn=n,a()},reconnect:()=>(t._fn=n,a(),i.observeDerived(e))}}static observeTaskState(e){let s=e.status.get(),t=[],n=null;return e.status.source(y,(o,a)=>{if(o===y){n=a;return}if(o===v){let u=a;if(u!==s){let d={from:s,to:u,timestamp:Date.now()};u==="error"&&(d.error=e.error.get()),t.push(d),s=u}}o===S&&(n=null)}),{transitions:t,get currentStatus(){return e.status.get()},dispose:()=>{n?.(S)}}}static causalityTrace(e){let s=[],t=e,n=t._fn;if(typeof n!="function"||!Array.isArray(t._deps))return{...i.observe(e),causality:s};let o=t._deps,a=o.map(r=>r.get());t._fn=()=>{let r=o.map(_=>_.get()),c=n(),h=-1;for(let _=0;_<o.length;_++)if(!Object.is(r[_],a[_])){h=_;break}return s.push({result:c,triggerDepIndex:h,triggerDepName:h>=0?i.getName(o[h]):void 0,depValues:r,timestamp:Date.now()}),a=r,c};let u=i._observe(e),d=u.dispose;return{...u,causality:s,dispose:()=>{t._fn=n,d()},reconnect:()=>(t._fn=n,d(),i.causalityTrace(e))}}static _reset(){i._names=new WeakMap,i._kinds=new WeakMap,i._keys=new WeakMap,i._stores=new Set,i._edges=new Map,i._usedKeys=new Set,i._nextId=0,i._explicitEnabled=null,i._cachedDefault=null,i._annotations=new WeakMap,i._traceLog=[],i._traceHead=0,i._traceFull=!1,i.maxTraceEntries=1e3}};var G=1,Q=2,X=4,L=8,z=32,Oe=64,Be=ue<<k,ee=fe<<k,Me=de<<k,ie=pe<<k,Ge=he<<k,Te=ge<<k,b=ne,ve=class{_output=null;_upstreamTalkbacks=[];_cachedValue;_flags;_dirtyDeps;_eqFn;_deps;_fn;get _status(){return _e(this._flags)}constructor(e,s,t,n){this._deps=e,this._fn=s,this._eqFn=t?.equals,this._flags=n?Oe:0,this._dirtyDeps=new J(e.length),this.source=this.source.bind(this),M.register(this,{kind:"derived",...t,deps:e});for(let o of e)M.registerEdge(o,this)}_dispatch(e,s){let t=this._output;if(t)if(this._flags&z)for(let n of t)n(e,s);else t(e,s)}_recompute(){let e;try{e=this._fn()}catch(s){this._handleEnd(s);return}if(this._eqFn&&this._flags&G&&this._eqFn(this._cachedValue,e)){this._flags=this._flags&~b|ie,this._dispatch(m,D);return}this._cachedValue=e,this._flags=(this._flags|G)&~b|Me,this._dispatch(v,this._cachedValue)}_recomputeIdentity(e){if(!(this._flags&L)){if(this._eqFn&&this._flags&G&&this._eqFn(this._cachedValue,e)){this._flags=this._flags&~b|ie,this._dispatch(m,D);return}this._cachedValue=e,this._flags=(this._flags|G)&~b|Me,this._dispatch(v,e)}}_lazyConnect(){if(!(this._flags&(Q|L))){try{this._cachedValue=this._fn()}catch(e){this._handleEnd(e);return}this._flags=(this._flags|G)&~b|Me,Se(),this._connectUpstream(),this._flags&L||(this._flags|=Q),ye()}}_connectUpstream(){this._upstreamTalkbacks.length=0,this._deps.length===1?this._flags&Oe?this._connectSingleDepIdentity():this._connectSingleDep():this._connectMultiDep()}_connectSingleDep(){let e=!1;this._deps[0].source(y,(s,t)=>{if(s===y){this._upstreamTalkbacks.push(t),t(m,H);return}if(!(this._flags&L))if(s===m)if(t===T){if(e)return;e=!0,this._flags=this._flags&~b|ee,this._dispatch(m,T)}else t===D?e&&(e=!1,this._flags=this._flags&~b|ie,this._dispatch(m,D)):this._dispatch(m,t);else s===v?e?(e=!1,this._recompute()):(this._flags=this._flags&~b|ee,this._dispatch(m,T),this._recompute()):s===S&&this._handleEnd(t)})}_connectSingleDepIdentity(){let e=!1;this._deps[0].source(y,(s,t)=>{if(s===y){this._upstreamTalkbacks.push(t),t(m,H);return}this._flags&L||(s===m?t===T?(e=!0,this._flags=this._flags&~b|ee,this._dispatch(m,T)):t===D?e&&(e=!1,this._flags=this._flags&~b|ie,this._dispatch(m,D)):this._dispatch(m,t):s===v?e?(e=!1,this._recomputeIdentity(t)):(this._flags=this._flags&~b|ee,this._dispatch(m,T),this._recomputeIdentity(t)):s===S&&this._handleEnd(t))})}_connectMultiDep(){for(let e=0;e<this._deps.length&&!(this._flags&L);e++){let s=e;this._deps[s].source(y,(t,n)=>{if(t===y){this._upstreamTalkbacks.push(n);return}if(!(this._flags&L))if(t===m)if(n===T){let o=this._dirtyDeps.empty();this._dirtyDeps.set(s),o&&(this._flags&=~X,this._flags=this._flags&~b|ee,this._dispatch(m,T))}else n===D?this._dirtyDeps.test(s)&&(this._dirtyDeps.clear(s),this._dirtyDeps.empty()&&(this._flags&X?this._recompute():(this._flags=this._flags&~b|ie,this._dispatch(m,D)))):this._dispatch(m,n);else t===v?this._dirtyDeps.test(s)?(this._dirtyDeps.clear(s),this._flags|=X,this._dirtyDeps.empty()&&this._recompute()):this._dirtyDeps.empty()?(this._flags=this._flags&~b|ee,this._dispatch(m,T),this._recompute()):this._flags|=X:t===S&&this._handleEnd(n)})}}_handleEnd(e){this._flags|=L,this._flags=this._flags&~b|(e!==void 0?Te:Ge),e!==void 0&&(this._cachedValue=e);for(let n of this._upstreamTalkbacks)n(S);this._upstreamTalkbacks=[],this._flags&=~Q,this._dirtyDeps.reset();let s=this._output,t=this._flags&z;if(this._output=null,this._flags&=~z,s)if(t)for(let n of s)try{e!==void 0?n(S,e):n(S)}catch{}else e!==void 0?s(S,e):s(S)}_disconnectUpstream(){for(let e of this._upstreamTalkbacks)e(S);this._upstreamTalkbacks.length=0,this._flags&=~(Q|X),this._flags=this._flags&~b|Be,this._dirtyDeps.reset()}_handleLifecycleSignal(e){if(!(this._flags&L)){if(e===F){for(let s of this._upstreamTalkbacks)s(m,F);this._handleEnd(void 0);return}e===U&&(this._flags&=~(G|X),this._dirtyDeps.reset());for(let s of this._upstreamTalkbacks)s(m,e)}}get(){if(this._flags&Q)return this._cachedValue;if(this._flags&L){if((this._flags&b)===Te)throw this._cachedValue;return this._cachedValue}let e=this._fn();return this._cachedValue=e,this._flags|=G,e}source(e,s){if(e===y){let t=s;if(this._flags&L){let n=(this._flags&b)===Te;t(y,o=>{}),n?t(S,this._cachedValue):t(S);return}if(!(this._flags&Q)&&(this._lazyConnect(),this._flags&L)){let n=(this._flags&b)===Te;t(y,o=>{}),n?t(S,this._cachedValue):t(S);return}if(this._output===null)this._output=t;else if(this._flags&z)this._output.add(t);else{let n=new Set;n.add(this._output),n.add(t),this._output=n,this._flags|=z}t(y,(n,o)=>{if(n===v&&t(v,this._cachedValue),n===m&&Z(o)){this._handleLifecycleSignal(o);return}if(n===S){if(this._output===null)return;if(this._flags&z){let a=this._output;a.delete(t),a.size===1?(this._output=a.values().next().value,this._flags&=~z):a.size===0&&(this._output=null,this._flags&=~z,this._disconnectUpstream())}else this._output===t&&(this._output=null,this._disconnectUpstream())}})}}};function N(i,e,s){return new ve(i,e,s)}(e=>{function i(s,t){return new ve([s],()=>s.get(),t,!0)}e.from=i})(N||={});function be(i,e,s){let t,n=[],o=!1,a=new J(i.length),u=!1;function d(){o||(t&&t(),t=e())}let f=0;function r(h){if(!o){if(h===F){for(let _ of n)_(m,F);n.length=0,o=!0,t&&t(),t=void 0;return}h===U&&(f++,a.reset(),u=!1,d());for(let _ of n)_(m,h)}}Se(),d();for(let h=0;h<i.length&&!o;h++){let _=h,I=f;i[_].source(y,(P,j)=>{if(P===y){n.push(j),i.length===1&&j(m,H);return}if(!o){if(P===m){if(Z(j)){r(j),I=f;return}if(I!==f)return;j===T?(a.empty()&&(u=!1),a.set(_)):j===D&&a.test(_)&&(a.clear(_),a.empty()&&u&&d())}if(P===v){if(I!==f)return;a.test(_)?(a.clear(_),u=!0,a.empty()&&d()):a.empty()?d():u=!0}if(P===S){o=!0,t&&t(),t=void 0;for(let l of n)l(S);n.length=0}}})}ye();let c=()=>{if(!o){o=!0,t&&t(),t=void 0;for(let h of n)h(S);n.length=0}};c.signal=h=>r(h),M.register(c,{kind:"effect",...s,deps:i});for(let h of i)M.registerEdge(h,c);return c}var Ee=1,C=64,A=2,te=4,Ne=8,Ce=16,K=32,$=1024,E=ne,se=fe<<k,re=de<<k,De=ue<<k,Je=he<<k,Ze=ge<<k,Qe=pe<<k,ke=class{_value;_output=null;_flags;get _status(){return _e(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;_onLifecycleSignal;constructor(e,s){this._value=s?.initial,this._fn=e,this._eqFn=s?.equals,this._getterFn=s?.getter,this._initial=s?.initial;let t=0;s?.autoDirty!==!1&&(t|=te),s?.resetOnTeardown&&(t|=Ne),s?.resubscribable&&(t|=Ce),this._flags=t,this.source=this.source.bind(this),this.emit=this.emit.bind(this),s?._skipInspect||M.register(this,{kind:"producer",...s})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(e,s){let t=this._output;if(t)if(this._flags&C)for(let n of t)n(e,s);else t(e,s)}emit(e){this._flags&A||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(B()?this._flags&K||(this._flags|=K,this._flags&te&&(this._flags=this._flags&~E|se,this._dispatch(m,T)),me(()=>{this._flags&=~K,this._flags=this._flags&~E|re,this._dispatch(v,this._value)})):(this._flags&te&&!(this._flags&$)&&(this._flags=this._flags&~E|se,this._dispatch(m,T)),this._flags=this._flags&~E|re,this._dispatch(v,this._value))))}signal(e){this._flags&A||!this._output||(e===T?this._flags=this._flags&~E|se:e===D&&(this._flags=this._flags&~E|Qe),this._dispatch(m,e))}complete(){if(this._flags&A)return;this._flags=(this._flags|A)&~E|Je;let e=this._output,s=this._flags&C;if(this._output=null,this._flags&=~(C|$),this._singleDepCount=0,this._stop(),e)if(s)for(let t of e)t(S);else e(S)}error(e){if(this._flags&A)return;this._flags=(this._flags|A)&~E|Ze;let s=this._output,t=this._flags&C;if(this._output=null,this._flags&=~(C|$),this._singleDepCount=0,this._stop(),s)if(t)for(let n of s)n(S,e);else s(S,e)}_start(){if(this._flags&Ee||!this._fn)return;this._flags|=Ee,this._onLifecycleSignal=void 0;let e=this._fn({emit:this.emit,signal:s=>this.signal(s),complete:()=>this.complete(),error:s=>this.error(s),onSignal:s=>{this._onLifecycleSignal=s}});this._cleanup=typeof e=="function"?e:void 0}_stop(){this._flags&Ee&&(this._flags&=~Ee,this._onLifecycleSignal=void 0,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&Ne&&(this._value=this._initial),this._flags&A||(this._flags=this._flags&~E|De))}_handleLifecycleSignal(e){if(!(this._flags&A)){if(e===F){this._onLifecycleSignal?.(e),this.complete();return}e===U&&(this._value=this._initial,this._flags&=~K),this._onLifecycleSignal?.(e),e===U&&this.emit(this._initial)}}source(e,s){if(e===y){let t=s;if(this._flags&A)if(this._flags&Ce&&this._output===null)this._flags=this._flags&~(A|E)|De;else{t(y,o=>{}),t(S);return}if(this._output===null)this._output=t;else if(this._flags&C)this._output.add(t);else{let o=new Set;o.add(this._output),o.add(t),this._output=o,this._flags=(this._flags|C)&~$}let n=!1;t(y,(o,a)=>{if(o===v&&t(v,this._value),o===m){a===H&&!n?(n=!0,this._singleDepCount++,this._flags&C||(this._flags|=$)):Z(a)&&this._handleLifecycleSignal(a);return}if(o===S){if(n&&(n=!1,this._singleDepCount--),this._output===null)return;if(this._flags&C){let u=this._output;u.delete(t),u.size===1?(this._output=u.values().next().value,this._flags&=~C,this._singleDepCount>0&&(this._flags|=$)):u.size===0&&(this._output=null,this._flags&=~(C|$),this._singleDepCount=0,this._flags=this._flags&~E|De,this._stop())}else this._output===t&&(this._output=null,this._flags&=~$,this._singleDepCount=0,this._flags=this._flags&~E|De,this._stop())}}),Ae(()=>this._start())}}};var Le=class extends ke{constructor(e,s){super(void 0,{initial:e,autoDirty:!0,equals:s?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),M.register(this,{kind:"state",...s})}get(){return this._value}set(e){this._flags&A||this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(B()?this._flags&K||(this._flags|=K,this._flags&te&&(this._flags=this._flags&~E|se,this._dispatch(m,T)),me(()=>{this._flags&=~K,this._flags=this._flags&~E|re,this._dispatch(v,this._value)})):(this._flags&te&&!(this._flags&$)&&(this._flags=this._flags&~E|se,this._dispatch(m,T)),this._flags=this._flags&~E|re,this._dispatch(v,this._value))))}update(e){this.set(e(this._value))}};function Y(i,e){return new Le(i,e)}var Xe=0;xe.from=function(e){let s=xe({id:e.id});for(let[t,n]of Object.entries(e.index))for(let o of n)s.add(o,[t]);return s};function xe(i){let e=++Xe,s=i?.id??`ridx-${e}`,t=new Map,n=new Map,o=new Map,a=new Map,u=Y(0,{name:`${s}:ver`}),d=N([u],()=>Array.from(t.keys()),{name:`${s}:keys`}),f=N([u],()=>t.size,{name:`${s}:size`}),r=!1,c=Object.freeze(new Set);function h(l){let p=o.get(l);return p||(p=Y(t.get(l)??new Set,{name:`${s}:${l}`,equals:()=>!1}),o.set(l,p)),p}function _(l){let p=o.get(l);if(p){let g=t.get(l);p.set(g?new Set(g):new Set)}}function I(l,p){let g=t.get(p),x=!g;return g||(g=new Set,t.set(p,g)),g.add(l),x}function P(l,p){let g=t.get(p);return g?(g.delete(l),g.size===0?(t.delete(p),!0):!1):!1}return{get id(){return s},get version(){return u.get()},get(l){let p=t.get(l);return p?Object.freeze(new Set(p)):c},has(l){let p=t.get(l);return p!==void 0&&p.size>0},keys(){return Array.from(t.keys())},get size(){return t.size},select(l){let p=a.get(l);if(p)return p;let g=h(l);return p=N([g],()=>g.get(),{name:`${s}:${l}:select`}),a.set(l,p),p},keysStore:d,sizeStore:f,add(l,p){if(r||p.length===0)return;let g=n.get(l);g||(g=new Set,n.set(l,g)),V(()=>{let x=!1;for(let w of p)g.add(w),I(l,w)&&(x=!0),_(w);x&&u.update(w=>w+1)})},remove(l){if(r)return;let p=n.get(l);p&&V(()=>{let g=!1;for(let x of p)P(l,x)&&(g=!0),_(x);n.delete(l),g&&u.update(x=>x+1)})},update(l,p){if(r)return;let g=n.get(l),x=new Set(p);V(()=>{let w=!1;if(g)for(let O of g)x.has(O)||(P(l,O)&&(w=!0),_(O));let R=n.get(l);R||(R=new Set,n.set(l,R)),R.clear();for(let O of p)R.add(O),I(l,O)&&(w=!0),_(O);w&&u.update(O=>O+1)})},clear(){t.size!==0&&V(()=>{t.clear(),n.clear();for(let l of o.values())l.set(new Set);u.update(l=>l+1)})},snapshot(){let l={};for(let[p,g]of t)l[p]=Array.from(g);return{type:"reactiveIndex",id:s,version:u.get(),index:l}},destroy(){if(!r){r=!0,t.clear(),n.clear();for(let l of o.values())W(l);o.clear();for(let l of a.values())W(l);a.clear(),W(u)}}}}function $e(i,e=s=>s){let s=[],t=new Map,n=new Map;function o(f,r){let c=s[f],h=s[r];s[f]=h,s[r]=c,c.index=r,h.index=f}function a(f){for(;f>0;){let r=f-1>>>1;if(s[r].score<=s[f].score)break;o(f,r),f=r}}function u(f){let r=s.length;for(;;){let c=f,h=2*f+1,_=h+1;if(h<r&&s[h].score<s[c].score&&(c=h),_<r&&s[_].score<s[c].score&&(c=_),c===f)break;o(f,c),f=c}}function d(f){let r=s.length-1;if(f===r){s.pop();return}o(f,r),s.pop(),a(f),u(f)}return{touch(){},insert(f){if(t.has(f))return;let r=i(f),c={key:f,score:e(r.get()),index:s.length};s.push(c),t.set(f,c),a(c.index);let h=be([r],()=>{let _=t.get(f);if(!_)return;let I=_.score;_.score=e(r.get()),_.score<I?a(_.index):_.score>I&&u(_.index)});n.set(f,h)},delete(f){let r=t.get(f);if(!r)return;let c=n.get(f);c&&(c(),n.delete(f)),d(r.index),t.delete(f)},evict(f=1){let r=[];for(;r.length<f&&s.length>0;){let{key:c}=s[0];r.push(c);let h=n.get(c);h&&(h(),n.delete(c)),d(0),t.delete(c)}return r},size:()=>t.size,clear(){for(let f of n.values())f();n.clear(),t.clear(),s.length=0}}}function Pe(i){let e=i?.halfLife??864e5,s=i?.recency??1,t=i?.importance??1,n=i?.frequency??.5,o=Math.LN2/e;return(a,u)=>{let d=(u??Date.now())-a.accessedAt,f=Math.exp(-o*d),r=1-1/(1+a.accessCount);return s*f+t*a.importance+n*r}}function q(i,e,s){let t=e?.halfLife??864e5,n=e?.recency??1,o=e?.importance??1,a=e?.frequency??.5,u=(s??Date.now())-i.accessedAt,d=Math.exp(-Math.LN2/t*u),f=1-1/(1+i.accessCount);return n*d+o*i.importance+a*f}var et=0;function tt(){return`mem-${++et}`}function we(i,e){let s=e?.id??tt(),t=Date.now(),n={id:s,createdAt:t,updatedAt:t,accessedAt:t,accessCount:0,importance:e?.importance??.5,tags:new Set(e?.tags)},o=Y(i,{name:`mem:${s}:content`}),a=Y(n,{name:`mem:${s}:meta`,equals:()=>!1}),u={},d=N([a],()=>q(a.get(),u),{name:`mem:${s}:score`});return{id:s,content:o,meta:a,scoreStore:d,touch(){let r=Date.now();a.update(c=>({...c,accessedAt:r,accessCount:c.accessCount+1}))},tag(...r){a.update(c=>{let h=new Set(c.tags);for(let _ of r)h.add(_);return{...c,tags:h,updatedAt:Date.now()}})},untag(...r){a.update(c=>{let h=new Set(c.tags);for(let _ of r)h.delete(_);return{...c,tags:h,updatedAt:Date.now()}})},setImportance(r){a.update(c=>({...c,importance:Math.max(0,Math.min(1,r)),updatedAt:Date.now()}))},update(r){V(()=>{o.set(r),a.update(c=>({...c,updatedAt:Date.now()}))})},score(r){return q(a.get(),r??u)},destroy(){W(o),W(a)}}}var st=0;function Fe(i){let e=++st,s=i?.maxSize??1/0,t=i?.weights??{},n=new Map,o=xe(),a=new Map,u=s<1/0?$e(l=>n.get(l).meta,l=>q(l,t)):null,d=Y(0,{name:`collection-${e}:ver`}),f=N([d],()=>Array.from(n.values()),{name:`collection-${e}:nodes`}),r=N([d],()=>n.size,{name:`collection-${e}:size`}),c=!1;function h(){d.update(l=>l+1)}function _(l){let p=be([l.meta],()=>{let g=Array.from(l.meta.get().tags);o.update(l.id,g)});a.set(l.id,p)}function I(l){let p=a.get(l);p&&(p(),a.delete(l)),o.remove(l)}function P(){if(!u||n.size<=s)return;let l=u.evict(n.size-s);for(let p of l){let g=n.get(p);g&&(I(p),g.destroy(),n.delete(p))}}return{add(l,p){if(c)throw new Error("Collection is destroyed");let g=we(l,p);return n.set(g.id,g),_(g),u?.insert(g.id),P(),h(),g},remove(l){let p=typeof l=="string"?l:l.id,g=n.get(p);return g?(I(p),u?.delete(p),g.destroy(),n.delete(p),h(),!0):!1},get(l){return n.get(l)},has(l){return n.has(l)},nodes:f,size:r,tagIndex:o,query(l){let p=[];for(let g of n.values())l(g)&&p.push(g);return p},byTag(l){let p=o.get(l),g=[];for(let x of p){let w=n.get(x);w&&g.push(w)}return g},topK(l,p){let g=p??t,x=Date.now(),w=Array.from(n.values()).map(R=>({node:R,score:q(R.meta.get(),g,x)}));return w.sort((R,O)=>O.score-R.score),w.slice(0,l).map(R=>R.node)},destroy(){if(!c){c=!0,u?.clear();for(let l of a.values())l();a.clear(),o.destroy(),W(d),V(()=>{for(let l of n.values())l.destroy();n.clear()})}}}}0&&(module.exports={collection,computeScore,decay,memoryNode});
1
+ "use strict";var we=Object.defineProperty;var Ve=Object.getOwnPropertyDescriptor;var We=Object.getOwnPropertyNames;var je=Object.prototype.hasOwnProperty;var Ue=(i,e)=>{for(var s in e)we(i,s,{get:e[s],enumerable:!0})},ze=(i,e,s,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of We(e))!je.call(i,n)&&n!==s&&we(i,n,{get:()=>e[n],enumerable:!(t=Ve(e,n))||t.enumerable});return i};var Ke=i=>ze(we({},"__esModule",{value:!0}),i);var nt={};Ue(nt,{collection:()=>Pe,computeScore:()=>U,decay:()=>$e,memoryNode:()=>ke});module.exports=Ke(nt);var ne=class{_v;_w;constructor(e){this._v=0,this._w=e>32?new Uint32Array((e-1>>>5)+1):null}set(e){let s=this._w;if(s===null)this._v|=1<<e;else{let t=e>>>5,n=1<<(e&31);s[t]&n||(s[t]|=n,this._v++)}}clear(e){let s=this._w;if(s===null)this._v&=~(1<<e);else{let t=e>>>5,n=1<<(e&31);s[t]&n&&(s[t]&=~n,this._v--)}}test(e){let s=this._w;return s===null?(this._v&1<<e)!==0:(s[e>>>5]&1<<(e&31))!==0}empty(){return this._v===0}reset(){this._v=0,this._w?.fill(0)}};var y=Symbol("DIRTY"),I=Symbol("RESOLVED"),X=Symbol("SINGLE_DEP"),q=Symbol("RESET"),Ye=Symbol("PAUSE"),qe=Symbol("RESUME"),H=Symbol("TEARDOWN");function ce(i){return i===q||i===Ye||i===qe||i===H}var le=0,ue=1,fe=2,de=3,pe=4,he=5,k=7,ee=7<<k,He=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function ge(i){return He[(i&ee)>>>k]}var S=0,v=1,_=2,m=3,ie=0,re=[],Ie=!1;function $(i){ie++;try{return i()}finally{if(ie--,ie===0&&!Ie){Ie=!0;for(let e=0;e<re.length;e++)re[e]();re.length=0,Ie=!1}}}function K(){return ie>0}function _e(i){re.push(i)}var ae=0,oe=[];function me(){ae++}function Se(){if(ae--,ae===0){for(let i=0;i<oe.length;i++)oe[i]();oe.length=0}}function Le(i){ae>0?oe.push(i):i()}function P(i){let e=i;typeof e.complete=="function"?e.complete():typeof e._handleEnd=="function"&&e._handleEnd(void 0)}var F=class i{static _names=new WeakMap;static _kinds=new WeakMap;static _keys=new WeakMap;static _stores=new Set;static _edges=new Map;static _nextId=0;static _usedKeys=new Set;static _explicitEnabled=null;static _cachedDefault=null;static _annotations=new WeakMap;static _traceLog=[];static _traceHead=0;static _traceFull=!1;static maxTraceEntries=1e3;static get enabled(){if(i._explicitEnabled!==null)return i._explicitEnabled;if(i._cachedDefault!==null)return i._cachedDefault;try{i._cachedDefault=globalThis.process?.env?.NODE_ENV!=="production"}catch{i._cachedDefault=!0}return i._cachedDefault}static set enabled(e){i._explicitEnabled=e}static _depSuffix(e){if(!e?.length)return;let t=e.map(n=>i._names.get(n)??"?").join(",");return t.length>40?`${t.slice(0,37)}...`:t}static _resolveKey(e){let s=i._keys.get(e)??i._names.get(e);if(s)return s;let t=`anonymous_${i._nextId++}`;return i._keys.set(e,t),t}static register(e,s){if(!i.enabled)return;s?.name&&i._names.set(e,s.name),s?.kind&&i._kinds.set(e,s.kind);let t=i._nextId++,n=s?.name;if(!(n&&!i._usedKeys.has(n)))if(n){let o=i._depSuffix(s?.deps);n=o?`${n}(${o})`:`${n}_${t}`,i._usedKeys.has(n)&&(n=`${n}_${t}`)}else{let o=s?.kind??"store",a=i._depSuffix(s?.deps);n=a?`${o}(${a})`:`${o}_${t}`,i._usedKeys.has(n)&&(n=`${n}_${t}`)}i._usedKeys.add(n),i._keys.set(e,n),i._stores.add(new WeakRef(e))}static registerEdge(e,s){if(!i.enabled)return;let t=i._resolveKey(e),n=i._resolveKey(s),o=i._edges.get(t);o?o.includes(n)||o.push(n):i._edges.set(t,[n])}static getEdges(){return new Map(i._edges)}static getName(e){if(i.enabled)return i._names.get(e)}static getKind(e){return i._kinds.get(e)}static inspect(e){return{name:i._names.get(e),kind:i._kinds.get(e)??"unknown",value:typeof e.get=="function"?e.get():void 0,status:e._status}}static graph(){let e=new Map,s=new Set;for(let t of i._stores){let n=t.deref();if(!n){i._stores.delete(t);continue}let o=i._resolveKey(n);s.add(o),e.set(o,i.inspect(n))}for(let[t,n]of i._edges){if(!s.has(t)){i._edges.delete(t),i._usedKeys.delete(t);continue}let o=n.filter(a=>s.has(a));o.length===0?i._edges.delete(t):o.length!==n.length&&i._edges.set(t,o)}return e}static trace(e,s){let t=null,n=e.get();return e.source(S,(o,a)=>{if(o===S&&(t=a),o===_){t=null;return}if(o===1){let u=a;if(!Object.is(u,n)){let d=n;n=u,s(u,d)}}}),()=>t?.(_)}static dumpGraph(){let e=i.graph(),s=i.getEdges(),t=new Map;for(let[a,u]of s)for(let d of u){let f=t.get(d);f?f.includes(a)||f.push(a):t.set(d,[a])}let n=[];for(let[a,u]of e){let d=t.get(a),f=s.get(a),r=d?.length?` \u2190 [${d.join(", ")}]`:"",l=f?.length?` \u2192 [${f.join(", ")}]`:"";n.push(` ${a} (${u.kind}) = ${JSON.stringify(u.value)} [${u.status??"?"}]${r}${l}`)}return[`Store Graph (${e.size} nodes):`,...n].join(`
2
+ `)}static _signalLabel(e){return e===y?"DIRTY":e===I?"RESOLVED":typeof e=="symbol"?e.description??String(e):String(e)}static _observe(e,s,t){let n=null,o=!1,a=s??i.getName(e),u=[],d={values:[],signals:[],events:[],ended:!1,endError:void 0,get completedCleanly(){return d.ended&&!o},get errored(){return d.ended&&o},dirtyCount:0,resolvedCount:0,name:a,get eventLog(){return u},dispose:()=>n?.(_),reconnect:()=>(n?.(_),i._observe(e,s,t))};return e.source(S,(f,r)=>{if(f===S){n=r;return}let l=K();f===v?(d.values.push(r),d.events.push({type:"data",data:r,inBatch:l}),u.push(r),t&&t(`[${a}] DATA:`,r)):f===m?(d.signals.push(r),d.events.push({type:"signal",data:r,inBatch:l}),u.push(i._signalLabel(r)),r===y?d.dirtyCount++:r===I&&d.resolvedCount++,t&&t(`[${a}] STATE:`,r)):f===_&&(d.ended=!0,d.endError=r,o=r!==void 0,d.events.push({type:"end",data:r,inBatch:l}),u.push(o?["END",r]:"END"),t&&t(`[${a}] END`,r!==void 0?r:""),n=null)}),d}static observe(e){return i._observe(e)}static activate(e){let s=null;return e.source(S,(t,n)=>{t===S&&(s=n),t===_&&(s=null)}),()=>s?.(_)}static tap(e,s){let t=s??`tap(${i.getName(e)??"anon"})`,n={get:()=>e.get(),source:e.source};return i.register(n,{name:t,kind:"tap"}),i.registerEdge(e,n),n}static spy(e,s){let t=s?.name??i.getName(e)??"spy",n=s?.log??console.log;return i._observe(e,t,n)}static snapshot(){let e=i.graph(),s=i.getEdges(),t=new Map;for(let a of i._stores){let u=a.deref();if(!u)continue;let d=i._annotations.get(u);d!==void 0&&t.set(i._resolveKey(u),d)}let n=[];for(let[a,u]of e){let d={name:a,kind:u.kind,value:u.value,status:u.status},f=t.get(a);f!==void 0&&(d.annotation=f),n.push(d)}let o=[];for(let[a,u]of s)for(let d of u)o.push({from:a,to:d});return{nodes:n,edges:o,trace:i.traceLog()}}static toMermaid(e){let s=e?.direction??"TD",t=i.snapshot(),n=[`graph ${s}`],o={SETTLED:":::settled",DIRTY:":::dirty",ERRORED:":::errored",COMPLETED:":::completed"},a=new Map;function u(r){let l=r.replace(/[^a-zA-Z0-9_]/g,"_"),g=a.get(l);return g===void 0?(a.set(l,1),l):(a.set(l,g+1),`${l}__${g}`)}let d=new Map;function f(r){let l=JSON.stringify(r);return l&&l.length>30?`${l.slice(0,27)}...`:l??"undefined"}for(let r of t.nodes){let l=u(r.name);d.set(r.name,l);let g=`${r.name} (${r.kind}) = ${f(r.value)}`,T=o[r.status??""]??"";n.push(` ${l}["${g}"]${T}`)}for(let r of t.edges){let l=d.get(r.from)??u(r.from),g=d.get(r.to)??u(r.to);n.push(` ${l} --> ${g}`)}return n.push(""),n.push(" classDef settled fill:#d4edda,stroke:#28a745"),n.push(" classDef dirty fill:#fff3cd,stroke:#ffc107"),n.push(" classDef errored fill:#f8d7da,stroke:#dc3545"),n.push(" classDef completed fill:#cce5ff,stroke:#007bff"),n.join(`
3
+ `)}static toD2(e){let s=e?.direction??"down",t=i.snapshot(),n=[`direction: ${s}`,""],o={state:"rectangle",derived:"hexagon",effect:"oval",producer:"rectangle",operator:"parallelogram","pipeline-step":"rectangle","pipeline-status":"diamond",checkpoint:"cylinder"},a=new Map;function u(r){let l=r.replace(/[^a-zA-Z0-9_]/g,"_"),g=a.get(l);return g===void 0?(a.set(l,1),l):(a.set(l,g+1),`${l}__${g}`)}let d=new Map;function f(r){let l=JSON.stringify(r);return l&&l.length>30?`${l.slice(0,27)}...`:l??"undefined"}for(let r of t.nodes){let l=u(r.name);d.set(r.name,l);let g=o[r.kind]??"rectangle",T=`${r.name} (${r.kind}) = ${f(r.value)}`,w=r.status?` [${r.status}]`:"";n.push(`${l}: "${T}${w}" { shape: ${g} }`)}t.edges.length>0&&n.push("");for(let r of t.edges){let l=d.get(r.from)??u(r.from),g=d.get(r.to)??u(r.to);n.push(`${l} -> ${g}`)}return n.join(`
4
+ `)}static annotate(e,s){if(!i.enabled)return;i._annotations.set(e,s);let t={node:i._resolveKey(e),reason:s,timestamp:Date.now()},n=i.maxTraceEntries;n<=0||(i._traceLog.length<n?i._traceLog.push(t):(i._traceLog[i._traceHead]=t,i._traceFull=!0),i._traceHead=(i._traceHead+1)%n)}static getAnnotation(e){return i._annotations.get(e)}static traceLog(){return i._traceFull?[...i._traceLog.slice(i._traceHead),...i._traceLog.slice(0,i._traceHead)]:i._traceLog.slice(0,i._traceHead||i._traceLog.length)}static clearTrace(){i._traceLog=[],i._traceHead=0,i._traceFull=!1}static timeline(e){let s=null,t=[];return e.source(S,(n,o)=>{if(n===S){s=o;return}let a={timestamp:Date.now(),type:n===v?"data":n===m?"signal":"end",data:o,inBatch:K()};t.push(a),n===_&&(s=null)}),{entries:t,dispose:()=>s?.(_)}}static observeDerived(e){let s=[],t=e,n=t._fn;if(typeof n!="function"||!Array.isArray(t._deps))return{...i.observe(e),evaluations:s};t._fn=()=>{let d=t._deps.map(r=>r.get()),f=n();return s.push({result:f,depValues:d,timestamp:Date.now()}),f};let o=i._observe(e),a=o.dispose;return{...o,evaluations:s,dispose:()=>{t._fn=n,a()},reconnect:()=>(t._fn=n,a(),i.observeDerived(e))}}static observeTaskState(e){let s=e.status.get(),t=[],n=null;return e.status.source(S,(o,a)=>{if(o===S){n=a;return}if(o===v){let u=a;if(u!==s){let d={from:s,to:u,timestamp:Date.now()};u==="error"&&(d.error=e.error.get()),t.push(d),s=u}}o===_&&(n=null)}),{transitions:t,get currentStatus(){return e.status.get()},dispose:()=>{n?.(_)}}}static causalityTrace(e){let s=[],t=e,n=t._fn;if(typeof n!="function"||!Array.isArray(t._deps))return{...i.observe(e),causality:s};let o=t._deps,a=o.map(r=>r.get());t._fn=()=>{let r=o.map(T=>T.get()),l=n(),g=-1;for(let T=0;T<o.length;T++)if(!Object.is(r[T],a[T])){g=T;break}return s.push({result:l,triggerDepIndex:g,triggerDepName:g>=0?i.getName(o[g]):void 0,depValues:r,timestamp:Date.now()}),a=r,l};let u=i._observe(e),d=u.dispose;return{...u,causality:s,dispose:()=>{t._fn=n,d()},reconnect:()=>(t._fn=n,d(),i.causalityTrace(e))}}static _reset(){i._names=new WeakMap,i._kinds=new WeakMap,i._keys=new WeakMap,i._stores=new Set,i._edges=new Map,i._usedKeys=new Set,i._nextId=0,i._explicitEnabled=null,i._cachedDefault=null,i._annotations=new WeakMap,i._traceLog=[],i._traceHead=0,i._traceFull=!1,i.maxTraceEntries=1e3}};var Y=1,B=2,G=4,M=8,V=32,Oe=64,Be=le<<k,J=ue<<k,Re=fe<<k,te=de<<k,Ge=pe<<k,Te=he<<k,b=ee,ye=class{_output=null;_upstreamTalkbacks=[];_cachedValue;_flags;_dirtyDeps;_eqFn;_deps;_fn;get _status(){return ge(this._flags)}constructor(e,s,t,n){this._deps=e,this._fn=s,this._eqFn=t?.equals,this._flags=n?Oe:0,this._dirtyDeps=new ne(e.length),this.source=this.source.bind(this),F.register(this,{kind:"derived",...t,deps:e});for(let o of e)F.registerEdge(o,this)}_dispatch(e,s){let t=this._output;if(t)if(this._flags&V)for(let n of t)n(e,s);else t(e,s)}_recompute(){let e;try{e=this._fn()}catch(s){this._handleEnd(s);return}if(this._eqFn&&this._flags&Y&&this._eqFn(this._cachedValue,e)){this._flags=this._flags&~b|te,this._dispatch(m,I);return}this._cachedValue=e,this._flags=(this._flags|Y)&~b|Re,this._dispatch(v,this._cachedValue)}_recomputeIdentity(e){if(!(this._flags&M)){if(this._eqFn&&this._flags&Y&&this._eqFn(this._cachedValue,e)){this._flags=this._flags&~b|te,this._dispatch(m,I);return}this._cachedValue=e,this._flags=(this._flags|Y)&~b|Re,this._dispatch(v,e)}}_lazyConnect(){if(!(this._flags&(B|M))){try{this._cachedValue=this._fn()}catch(e){this._handleEnd(e);return}this._flags=(this._flags|Y)&~b|Re,me(),this._connectUpstream(),this._flags&M||(this._flags|=B),Se()}}_connectUpstream(){this._upstreamTalkbacks.length=0,this._deps.length===1?this._flags&Oe?this._connectSingleDepIdentity():this._connectSingleDep():this._connectMultiDep()}_connectSingleDep(){let e=!1;this._deps[0].source(S,(s,t)=>{if(s===S){this._upstreamTalkbacks.push(t),t(m,X);return}if(!(this._flags&M))if(s===m)if(t===y){if(e)return;e=!0,this._flags=this._flags&~b|J,this._dispatch(m,y)}else t===I?e&&(e=!1,this._flags=this._flags&~b|te,this._dispatch(m,I)):this._dispatch(m,t);else s===v?e?(e=!1,this._recompute()):(this._flags=this._flags&~b|J,this._dispatch(m,y),this._recompute()):s===_&&this._handleEnd(t)})}_connectSingleDepIdentity(){let e=!1;this._deps[0].source(S,(s,t)=>{if(s===S){this._upstreamTalkbacks.push(t),t(m,X);return}this._flags&M||(s===m?t===y?(e=!0,this._flags=this._flags&~b|J,this._dispatch(m,y)):t===I?e&&(e=!1,this._flags=this._flags&~b|te,this._dispatch(m,I)):this._dispatch(m,t):s===v?e?(e=!1,this._recomputeIdentity(t)):(this._flags=this._flags&~b|J,this._dispatch(m,y),this._recomputeIdentity(t)):s===_&&this._handleEnd(t))})}_connectMultiDep(){for(let e=0;e<this._deps.length&&!(this._flags&M);e++){let s=e;this._deps[s].source(S,(t,n)=>{if(t===S){this._upstreamTalkbacks.push(n);return}if(!(this._flags&M))if(t===m)if(n===y){let o=this._dirtyDeps.empty();this._dirtyDeps.set(s),o&&(this._flags&=~G,this._flags=this._flags&~b|J,this._dispatch(m,y))}else n===I?this._dirtyDeps.test(s)&&(this._dirtyDeps.clear(s),this._dirtyDeps.empty()&&(this._flags&G?this._recompute():(this._flags=this._flags&~b|te,this._dispatch(m,I)))):this._dispatch(m,n);else t===v?this._dirtyDeps.test(s)?(this._dirtyDeps.clear(s),this._flags|=G,this._dirtyDeps.empty()&&this._recompute()):this._dirtyDeps.empty()?(this._flags=this._flags&~b|J,this._dispatch(m,y),this._recompute()):this._flags|=G:t===_&&this._handleEnd(n)})}}_handleEnd(e){this._flags|=M,this._flags=this._flags&~b|(e!==void 0?Te:Ge),e!==void 0&&(this._cachedValue=e);for(let n of this._upstreamTalkbacks)n(_);this._upstreamTalkbacks=[],this._flags&=~B,this._dirtyDeps.reset();let s=this._output,t=this._flags&V;if(this._output=null,this._flags&=~V,s)if(t)for(let n of s)try{e!==void 0?n(_,e):n(_)}catch{}else e!==void 0?s(_,e):s(_)}_disconnectUpstream(){for(let e of this._upstreamTalkbacks)e(_);this._upstreamTalkbacks.length=0,this._flags&=~(B|G),this._flags=this._flags&~b|Be,this._dirtyDeps.reset()}_handleLifecycleSignal(e){if(!(this._flags&M)){if(e===H){for(let s of this._upstreamTalkbacks)s(m,H);this._handleEnd(void 0);return}e===q&&(this._flags&=~(Y|G),this._dirtyDeps.reset());for(let s of this._upstreamTalkbacks)s(m,e)}}get(){if(this._flags&B)return this._cachedValue;if(this._flags&M){if((this._flags&b)===Te)throw this._cachedValue;return this._cachedValue}let e=this._fn();return this._cachedValue=e,this._flags|=Y,e}source(e,s){if(e===S){let t=s;if(this._flags&M){let n=(this._flags&b)===Te;t(S,o=>{}),n?t(_,this._cachedValue):t(_);return}if(!(this._flags&B)&&(this._lazyConnect(),this._flags&M)){let n=(this._flags&b)===Te;t(S,o=>{}),n?t(_,this._cachedValue):t(_);return}if(this._output===null)this._output=t;else if(this._flags&V)this._output.add(t);else{let n=new Set;n.add(this._output),n.add(t),this._output=n,this._flags|=V}t(S,(n,o)=>{if(n===v&&t(v,this._cachedValue),n===m&&ce(o)){this._handleLifecycleSignal(o);return}if(n===_){if(this._output===null)return;if(this._flags&V){let a=this._output;a.delete(t),a.size===1?(this._output=a.values().next().value,this._flags&=~V):a.size===0&&(this._output=null,this._flags&=~V,this._disconnectUpstream())}else this._output===t&&(this._output=null,this._disconnectUpstream())}})}}};function A(i,e,s){return new ye(i,e,s)}(e=>{function i(s,t){return new ye([s],()=>s.get(),t,!0)}e.from=i})(A||={});var ve=1,N=64,L=2,Z=4,Ae=8,Ne=16,W=32,C=1024,x=ee,Q=ue<<k,se=fe<<k,be=le<<k,Je=pe<<k,Ze=he<<k,Qe=de<<k,Ee=class{_value;_output=null;_flags;get _status(){return ge(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;_onLifecycleSignal;constructor(e,s){this._value=s?.initial,this._fn=e,this._eqFn=s?.equals,this._getterFn=s?.getter,this._initial=s?.initial;let t=0;s?.autoDirty!==!1&&(t|=Z),s?.resetOnTeardown&&(t|=Ae),s?.resubscribable&&(t|=Ne),this._flags=t,this.source=this.source.bind(this),this.emit=this.emit.bind(this),s?._skipInspect||F.register(this,{kind:"producer",...s})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(e,s){let t=this._output;if(t)if(this._flags&N)for(let n of t)n(e,s);else t(e,s)}emit(e){this._flags&L||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(K()?this._flags&W||(this._flags|=W,this._flags&Z&&(this._flags=this._flags&~x|Q,this._dispatch(m,y)),_e(()=>{this._flags&=~W,this._flags=this._flags&~x|se,this._dispatch(v,this._value)})):(this._flags&Z&&!(this._flags&C)&&(this._flags=this._flags&~x|Q,this._dispatch(m,y)),this._flags=this._flags&~x|se,this._dispatch(v,this._value))))}signal(e){this._flags&L||!this._output||(e===y?this._flags=this._flags&~x|Q:e===I&&(this._flags=this._flags&~x|Qe),this._dispatch(m,e))}complete(){if(this._flags&L)return;this._flags=(this._flags|L)&~x|Je;let e=this._output,s=this._flags&N;if(this._output=null,this._flags&=~(N|C),this._singleDepCount=0,this._stop(),e)if(s)for(let t of e)t(_);else e(_)}error(e){if(this._flags&L)return;this._flags=(this._flags|L)&~x|Ze;let s=this._output,t=this._flags&N;if(this._output=null,this._flags&=~(N|C),this._singleDepCount=0,this._stop(),s)if(t)for(let n of s)n(_,e);else s(_,e)}_start(){if(this._flags&ve||!this._fn)return;this._flags|=ve,this._onLifecycleSignal=void 0;let e=this._fn({emit:this.emit,signal:s=>this.signal(s),complete:()=>this.complete(),error:s=>this.error(s),onSignal:s=>{this._onLifecycleSignal=s}});this._cleanup=typeof e=="function"?e:void 0}_stop(){this._flags&ve&&(this._flags&=~ve,this._onLifecycleSignal=void 0,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&Ae&&(this._value=this._initial),this._flags&L||(this._flags=this._flags&~x|be))}_handleLifecycleSignal(e){if(!(this._flags&L)){if(e===H){this._onLifecycleSignal?.(e),this.complete();return}e===q&&(this._value=this._initial,this._flags&=~W),this._onLifecycleSignal?.(e),e===q&&this.emit(this._initial)}}source(e,s){if(e===S){let t=s;if(this._flags&L)if(this._flags&Ne&&this._output===null)this._flags=this._flags&~(L|x)|be;else{t(S,o=>{}),t(_);return}if(this._output===null)this._output=t;else if(this._flags&N)this._output.add(t);else{let o=new Set;o.add(this._output),o.add(t),this._output=o,this._flags=(this._flags|N)&~C}let n=!1;t(S,(o,a)=>{if(o===v&&t(v,this._value),o===m){a===X&&!n?(n=!0,this._singleDepCount++,this._flags&N||(this._flags|=C)):ce(a)&&this._handleLifecycleSignal(a);return}if(o===_){if(n&&(n=!1,this._singleDepCount--),this._output===null)return;if(this._flags&N){let u=this._output;u.delete(t),u.size===1?(this._output=u.values().next().value,this._flags&=~N,this._singleDepCount>0&&(this._flags|=C)):u.size===0&&(this._output=null,this._flags&=~(N|C),this._singleDepCount=0,this._flags=this._flags&~x|be,this._stop())}else this._output===t&&(this._output=null,this._flags&=~C,this._singleDepCount=0,this._flags=this._flags&~x|be,this._stop())}}),Le(()=>this._start())}}};var Me=class extends Ee{constructor(e,s){super(void 0,{initial:e,autoDirty:!0,equals:s?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),F.register(this,{kind:"state",...s})}get(){return this._value}set(e){this._flags&L||this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(K()?this._flags&W||(this._flags|=W,this._flags&Z&&(this._flags=this._flags&~x|Q,this._dispatch(m,y)),_e(()=>{this._flags&=~W,this._flags=this._flags&~x|se,this._dispatch(v,this._value)})):(this._flags&Z&&!(this._flags&C)&&(this._flags=this._flags&~x|Q,this._dispatch(m,y)),this._flags=this._flags&~x|se,this._dispatch(v,this._value))))}update(e){this.set(e(this._value))}};function j(i,e){return new Me(i,e)}function De(i,e,s){let t=null;me(),i.source(S,(o,a)=>{if(o===S&&(t=a),o===_){t=null,s?.onEnd?.(a);return}if(o===1){let u=a,d=n;n=u,e(u,d)}});let n;try{n=i.get()}catch{}return Se(),{unsubscribe(){t?.(_),t=null},signal(o){t?.(m,o)}}}var Xe=0;xe.from=function(e){let s=xe({id:e.id});for(let[t,n]of Object.entries(e.index))for(let o of n)s.add(o,[t]);return s};function xe(i){let e=++Xe,s=i?.id??`ridx-${e}`,t=new Map,n=new Map,o=new Map,a=new Map,u=j(0,{name:`${s}:ver`}),d=A([u],()=>Array.from(t.keys()),{name:`${s}:keys`}),f=A([u],()=>t.size,{name:`${s}:size`}),r=!1,l=Object.freeze(new Set);function g(c){let p=o.get(c);return p||(p=j(t.get(c)??new Set,{name:`${s}:${c}`,equals:()=>!1}),o.set(c,p)),p}function T(c){let p=o.get(c);if(p){let h=t.get(c);p.set(h?new Set(h):new Set)}}function w(c,p){let h=t.get(p),E=!h;return h||(h=new Set,t.set(p,h)),h.add(c),E}function z(c,p){let h=t.get(p);return h?(h.delete(c),h.size===0?(t.delete(p),!0):!1):!1}return{get id(){return s},get version(){return u.get()},get(c){let p=t.get(c);return p?Object.freeze(new Set(p)):l},has(c){let p=t.get(c);return p!==void 0&&p.size>0},keys(){return Array.from(t.keys())},get size(){return t.size},select(c){let p=a.get(c);if(p)return p;let h=g(c);return p=A([h],()=>h.get(),{name:`${s}:${c}:select`}),a.set(c,p),p},keysStore:d,sizeStore:f,add(c,p){if(r||p.length===0)return;let h=n.get(c);h||(h=new Set,n.set(c,h)),$(()=>{let E=!1;for(let D of p)h.add(D),w(c,D)&&(E=!0),T(D);E&&u.update(D=>D+1)})},remove(c){if(r)return;let p=n.get(c);p&&$(()=>{let h=!1;for(let E of p)z(c,E)&&(h=!0),T(E);n.delete(c),h&&u.update(E=>E+1)})},update(c,p){if(r)return;let h=n.get(c),E=new Set(p);$(()=>{let D=!1;if(h)for(let O of h)E.has(O)||(z(c,O)&&(D=!0),T(O));let R=n.get(c);R||(R=new Set,n.set(c,R)),R.clear();for(let O of p)R.add(O),w(c,O)&&(D=!0),T(O);D&&u.update(O=>O+1)})},clear(){t.size!==0&&$(()=>{t.clear(),n.clear();for(let c of o.values())c.set(new Set);u.update(c=>c+1)})},snapshot(){let c={};for(let[p,h]of t)c[p]=Array.from(h);return{type:"reactiveIndex",id:s,version:u.get(),index:c}},destroy(){if(!r){r=!0,t.clear(),n.clear();for(let c of o.values())P(c);o.clear();for(let c of a.values())P(c);a.clear(),P(u)}}}}function Ce(i,e=s=>s){let s=[],t=new Map,n=new Map;function o(f,r){let l=s[f],g=s[r];s[f]=g,s[r]=l,l.index=r,g.index=f}function a(f){for(;f>0;){let r=f-1>>>1;if(s[r].score<=s[f].score)break;o(f,r),f=r}}function u(f){let r=s.length;for(;;){let l=f,g=2*f+1,T=g+1;if(g<r&&s[g].score<s[l].score&&(l=g),T<r&&s[T].score<s[l].score&&(l=T),l===f)break;o(f,l),f=l}}function d(f){let r=s.length-1;if(f===r){s.pop();return}o(f,r),s.pop(),a(f),u(f)}return{touch(){},insert(f){if(t.has(f))return;let r=i(f),l={key:f,score:e(r.get()),index:s.length};s.push(l),t.set(f,l),a(l.index);let g=De(r,T=>{let w=t.get(f);if(!w)return;let z=w.score;w.score=e(T),w.score<z?a(w.index):w.score>z&&u(w.index)});n.set(f,()=>g.unsubscribe())},delete(f){let r=t.get(f);if(!r)return;let l=n.get(f);l&&(l(),n.delete(f)),d(r.index),t.delete(f)},evict(f=1){let r=[];for(;r.length<f&&s.length>0;){let{key:l}=s[0];r.push(l);let g=n.get(l);g&&(g(),n.delete(l)),d(0),t.delete(l)}return r},size:()=>t.size,clear(){for(let f of n.values())f();n.clear(),t.clear(),s.length=0}}}function $e(i){let e=i?.halfLife??864e5,s=i?.recency??1,t=i?.importance??1,n=i?.frequency??.5,o=Math.LN2/e;return(a,u)=>{let d=(u??Date.now())-a.accessedAt,f=Math.exp(-o*d),r=1-1/(1+a.accessCount);return s*f+t*a.importance+n*r}}function U(i,e,s){let t=e?.halfLife??864e5,n=e?.recency??1,o=e?.importance??1,a=e?.frequency??.5,u=(s??Date.now())-i.accessedAt,d=Math.exp(-Math.LN2/t*u),f=1-1/(1+i.accessCount);return n*d+o*i.importance+a*f}var et=0;function tt(){return`mem-${++et}`}function ke(i,e){let s=e?.id??tt(),t=Date.now(),n={id:s,createdAt:t,updatedAt:t,accessedAt:t,accessCount:0,importance:e?.importance??.5,tags:new Set(e?.tags)},o=j(i,{name:`mem:${s}:content`}),a=j(n,{name:`mem:${s}:meta`,equals:()=>!1}),u={},d=A([a],()=>U(a.get(),u),{name:`mem:${s}:score`});return{id:s,content:o,meta:a,scoreStore:d,touch(){let r=Date.now();a.update(l=>({...l,accessedAt:r,accessCount:l.accessCount+1}))},tag(...r){a.update(l=>{let g=new Set(l.tags);for(let T of r)g.add(T);return{...l,tags:g,updatedAt:Date.now()}})},untag(...r){a.update(l=>{let g=new Set(l.tags);for(let T of r)g.delete(T);return{...l,tags:g,updatedAt:Date.now()}})},setImportance(r){a.update(l=>({...l,importance:Math.max(0,Math.min(1,r)),updatedAt:Date.now()}))},update(r){$(()=>{o.set(r),a.update(l=>({...l,updatedAt:Date.now()}))})},score(r){return U(a.get(),r??u)},destroy(){P(o),P(a)}}}var st=0;function Pe(i){let e=++st,s=i?.maxSize??1/0,t=i?.weights??{},n=new Map,o=xe(),a=new Map,u=s<1/0?Ce(c=>n.get(c).meta,c=>U(c,t)):null,d=j(0,{name:`collection-${e}:ver`}),f=A([d],()=>Array.from(n.values()),{name:`collection-${e}:nodes`}),r=A([d],()=>n.size,{name:`collection-${e}:size`}),l=!1;function g(){d.update(c=>c+1)}function T(c){let p=Array.from(c.meta.get().tags);o.update(c.id,p);let h=De(c.meta,E=>{let D=Array.from(E.tags);o.update(c.id,D)});a.set(c.id,()=>h.unsubscribe())}function w(c){let p=a.get(c);p&&(p(),a.delete(c)),o.remove(c)}function z(){if(!u||n.size<=s)return;let c=u.evict(n.size-s);for(let p of c){let h=n.get(p);h&&(w(p),h.destroy(),n.delete(p))}}return{add(c,p){if(l)throw new Error("Collection is destroyed");let h=ke(c,p);return n.set(h.id,h),T(h),u?.insert(h.id),z(),g(),h},remove(c){let p=typeof c=="string"?c:c.id,h=n.get(p);return h?(w(p),u?.delete(p),h.destroy(),n.delete(p),g(),!0):!1},get(c){return n.get(c)},has(c){return n.has(c)},nodes:f,size:r,tagIndex:o,query(c){let p=[];for(let h of n.values())c(h)&&p.push(h);return p},byTag(c){let p=o.get(c),h=[];for(let E of p){let D=n.get(E);D&&h.push(D)}return h},topK(c,p){let h=p??t,E=Date.now(),D=Array.from(n.values()).map(R=>({node:R,score:U(R.meta.get(),h,E)}));return D.sort((R,O)=>O.score-R.score),D.slice(0,c).map(R=>R.node)},destroy(){if(!l){l=!0,u?.clear();for(let c of a.values())c();a.clear(),o.destroy(),P(d),$(()=>{for(let c of n.values())c.destroy();n.clear()})}}}}0&&(module.exports={collection,computeScore,decay,memoryNode});
@@ -1 +1 @@
1
- import{a as o,b as e,c as t,d as r}from"../chunk-3ETD2EFQ.js";import"../chunk-6HKVNUGH.js";import"../chunk-ZJCF5NYF.js";import"../chunk-2ZFSL4MA.js";import"../chunk-PV347CGV.js";import"../chunk-HK7DRUNM.js";import"../chunk-EAK2HKAD.js";import"../chunk-2F6QWERG.js";import"../chunk-2L6223KN.js";import"../chunk-TUPD47IE.js";import"../chunk-I7AUKTXE.js";export{r as collection,e as computeScore,o as decay,t as memoryNode};
1
+ import{a as o,b as e,c as t,d as r}from"../chunk-G65KU7M5.js";import"../chunk-JCENQEPP.js";import"../chunk-ZJCF5NYF.js";import"../chunk-PV347CGV.js";import"../chunk-HK7DRUNM.js";import"../chunk-GMLWTZFM.js";import"../chunk-EAK2HKAD.js";import"../chunk-2F6QWERG.js";import"../chunk-2L6223KN.js";import"../chunk-TUPD47IE.js";import"../chunk-I7AUKTXE.js";export{r as collection,e as computeScore,o as decay,t as memoryNode};
@@ -1,4 +1,4 @@
1
- "use strict";var Ie=Object.defineProperty;var ze=Object.getOwnPropertyDescriptor;var We=Object.getOwnPropertyNames;var je=Object.prototype.hasOwnProperty;var Ue=(i,e)=>{for(var s in e)Ie(i,s,{get:e[s],enumerable:!0})},Ke=(i,e,s,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of We(e))!je.call(i,n)&&n!==s&&Ie(i,n,{get:()=>e[n],enumerable:!(t=ze(e,n))||t.enumerable});return i};var qe=i=>Ke(Ie({},"__esModule",{value:!0}),i);var rt={};Ue(rt,{memoryStore:()=>it});module.exports=qe(rt);var J=class{_v;_w;constructor(e){this._v=0,this._w=e>32?new Uint32Array((e-1>>>5)+1):null}set(e){let s=this._w;if(s===null)this._v|=1<<e;else{let t=e>>>5,n=1<<(e&31);s[t]&n||(s[t]|=n,this._v++)}}clear(e){let s=this._w;if(s===null)this._v&=~(1<<e);else{let t=e>>>5,n=1<<(e&31);s[t]&n&&(s[t]&=~n,this._v--)}}test(e){let s=this._w;return s===null?(this._v&1<<e)!==0:(s[e>>>5]&1<<(e&31))!==0}empty(){return this._v===0}reset(){this._v=0,this._w?.fill(0)}};var b=Symbol("DIRTY"),I=Symbol("RESOLVED"),Y=Symbol("SINGLE_DEP"),U=Symbol("RESET"),Ye=Symbol("PAUSE"),He=Symbol("RESUME"),W=Symbol("TEARDOWN");function Z(i){return i===U||i===Ye||i===He||i===W}var de=0,ge=1,pe=2,he=3,_e=4,me=5,R=7,ie=7<<R,Be=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function ye(i){return Be[(i&ie)>>>R]}var T=0,E=1,y=2,m=3,ce=0,le=[],Re=!1;function j(i){ce++;try{return i()}finally{if(ce--,ce===0&&!Re){Re=!0;for(let e=0;e<le.length;e++)le[e]();le.length=0,Re=!1}}}function H(){return ce>0}function Te(i){le.push(i)}var fe=0,ue=[];function Se(){fe++}function ve(){if(fe--,fe===0){for(let i=0;i<ue.length;i++)ue[i]();ue.length=0}}function Le(i){fe>0?ue.push(i):i()}function $(i){let e=i;typeof e.complete=="function"?e.complete():typeof e._handleEnd=="function"&&e._handleEnd(void 0)}var O=class i{static _names=new WeakMap;static _kinds=new WeakMap;static _keys=new WeakMap;static _stores=new Set;static _edges=new Map;static _nextId=0;static _usedKeys=new Set;static _explicitEnabled=null;static _cachedDefault=null;static _annotations=new WeakMap;static _traceLog=[];static _traceHead=0;static _traceFull=!1;static maxTraceEntries=1e3;static get enabled(){if(i._explicitEnabled!==null)return i._explicitEnabled;if(i._cachedDefault!==null)return i._cachedDefault;try{i._cachedDefault=globalThis.process?.env?.NODE_ENV!=="production"}catch{i._cachedDefault=!0}return i._cachedDefault}static set enabled(e){i._explicitEnabled=e}static _depSuffix(e){if(!e?.length)return;let t=e.map(n=>i._names.get(n)??"?").join(",");return t.length>40?`${t.slice(0,37)}...`:t}static _resolveKey(e){let s=i._keys.get(e)??i._names.get(e);if(s)return s;let t=`anonymous_${i._nextId++}`;return i._keys.set(e,t),t}static register(e,s){if(!i.enabled)return;s?.name&&i._names.set(e,s.name),s?.kind&&i._kinds.set(e,s.kind);let t=i._nextId++,n=s?.name;if(!(n&&!i._usedKeys.has(n)))if(n){let r=i._depSuffix(s?.deps);n=r?`${n}(${r})`:`${n}_${t}`,i._usedKeys.has(n)&&(n=`${n}_${t}`)}else{let r=s?.kind??"store",a=i._depSuffix(s?.deps);n=a?`${r}(${a})`:`${r}_${t}`,i._usedKeys.has(n)&&(n=`${n}_${t}`)}i._usedKeys.add(n),i._keys.set(e,n),i._stores.add(new WeakRef(e))}static registerEdge(e,s){if(!i.enabled)return;let t=i._resolveKey(e),n=i._resolveKey(s),r=i._edges.get(t);r?r.includes(n)||r.push(n):i._edges.set(t,[n])}static getEdges(){return new Map(i._edges)}static getName(e){if(i.enabled)return i._names.get(e)}static getKind(e){return i._kinds.get(e)}static inspect(e){return{name:i._names.get(e),kind:i._kinds.get(e)??"unknown",value:typeof e.get=="function"?e.get():void 0,status:e._status}}static graph(){let e=new Map,s=new Set;for(let t of i._stores){let n=t.deref();if(!n){i._stores.delete(t);continue}let r=i._resolveKey(n);s.add(r),e.set(r,i.inspect(n))}for(let[t,n]of i._edges){if(!s.has(t)){i._edges.delete(t),i._usedKeys.delete(t);continue}let r=n.filter(a=>s.has(a));r.length===0?i._edges.delete(t):r.length!==n.length&&i._edges.set(t,r)}return e}static trace(e,s){let t=null,n=e.get();return e.source(T,(r,a)=>{if(r===T&&(t=a),r===y){t=null;return}if(r===1){let u=a;if(!Object.is(u,n)){let g=n;n=u,s(u,g)}}}),()=>t?.(y)}static dumpGraph(){let e=i.graph(),s=i.getEdges(),t=new Map;for(let[a,u]of s)for(let g of u){let d=t.get(g);d?d.includes(a)||d.push(a):t.set(g,[a])}let n=[];for(let[a,u]of e){let g=t.get(a),d=s.get(a),o=g?.length?` \u2190 [${g.join(", ")}]`:"",c=d?.length?` \u2192 [${d.join(", ")}]`:"";n.push(` ${a} (${u.kind}) = ${JSON.stringify(u.value)} [${u.status??"?"}]${o}${c}`)}return[`Store Graph (${e.size} nodes):`,...n].join(`
2
- `)}static _signalLabel(e){return e===b?"DIRTY":e===I?"RESOLVED":typeof e=="symbol"?e.description??String(e):String(e)}static _observe(e,s,t){let n=null,r=!1,a=s??i.getName(e),u=[],g={values:[],signals:[],events:[],ended:!1,endError:void 0,get completedCleanly(){return g.ended&&!r},get errored(){return g.ended&&r},dirtyCount:0,resolvedCount:0,name:a,get eventLog(){return u},dispose:()=>n?.(y),reconnect:()=>(n?.(y),i._observe(e,s,t))};return e.source(T,(d,o)=>{if(d===T){n=o;return}let c=H();d===E?(g.values.push(o),g.events.push({type:"data",data:o,inBatch:c}),u.push(o),t&&t(`[${a}] DATA:`,o)):d===m?(g.signals.push(o),g.events.push({type:"signal",data:o,inBatch:c}),u.push(i._signalLabel(o)),o===b?g.dirtyCount++:o===I&&g.resolvedCount++,t&&t(`[${a}] STATE:`,o)):d===y&&(g.ended=!0,g.endError=o,r=o!==void 0,g.events.push({type:"end",data:o,inBatch:c}),u.push(r?["END",o]:"END"),t&&t(`[${a}] END`,o!==void 0?o:""),n=null)}),g}static observe(e){return i._observe(e)}static activate(e){let s=null;return e.source(T,(t,n)=>{t===T&&(s=n),t===y&&(s=null)}),()=>s?.(y)}static tap(e,s){let t=s??`tap(${i.getName(e)??"anon"})`,n={get:()=>e.get(),source:e.source};return i.register(n,{name:t,kind:"tap"}),i.registerEdge(e,n),n}static spy(e,s){let t=s?.name??i.getName(e)??"spy",n=s?.log??console.log;return i._observe(e,t,n)}static snapshot(){let e=i.graph(),s=i.getEdges(),t=new Map;for(let a of i._stores){let u=a.deref();if(!u)continue;let g=i._annotations.get(u);g!==void 0&&t.set(i._resolveKey(u),g)}let n=[];for(let[a,u]of e){let g={name:a,kind:u.kind,value:u.value,status:u.status},d=t.get(a);d!==void 0&&(g.annotation=d),n.push(g)}let r=[];for(let[a,u]of s)for(let g of u)r.push({from:a,to:g});return{nodes:n,edges:r,trace:i.traceLog()}}static toMermaid(e){let s=e?.direction??"TD",t=i.snapshot(),n=[`graph ${s}`],r={SETTLED:":::settled",DIRTY:":::dirty",ERRORED:":::errored",COMPLETED:":::completed"},a=new Map;function u(o){let c=o.replace(/[^a-zA-Z0-9_]/g,"_"),h=a.get(c);return h===void 0?(a.set(c,1),c):(a.set(c,h+1),`${c}__${h}`)}let g=new Map;function d(o){let c=JSON.stringify(o);return c&&c.length>30?`${c.slice(0,27)}...`:c??"undefined"}for(let o of t.nodes){let c=u(o.name);g.set(o.name,c);let h=`${o.name} (${o.kind}) = ${d(o.value)}`,_=r[o.status??""]??"";n.push(` ${c}["${h}"]${_}`)}for(let o of t.edges){let c=g.get(o.from)??u(o.from),h=g.get(o.to)??u(o.to);n.push(` ${c} --> ${h}`)}return n.push(""),n.push(" classDef settled fill:#d4edda,stroke:#28a745"),n.push(" classDef dirty fill:#fff3cd,stroke:#ffc107"),n.push(" classDef errored fill:#f8d7da,stroke:#dc3545"),n.push(" classDef completed fill:#cce5ff,stroke:#007bff"),n.join(`
3
- `)}static toD2(e){let s=e?.direction??"down",t=i.snapshot(),n=[`direction: ${s}`,""],r={state:"rectangle",derived:"hexagon",effect:"oval",producer:"rectangle",operator:"parallelogram","pipeline-step":"rectangle","pipeline-status":"diamond",checkpoint:"cylinder"},a=new Map;function u(o){let c=o.replace(/[^a-zA-Z0-9_]/g,"_"),h=a.get(c);return h===void 0?(a.set(c,1),c):(a.set(c,h+1),`${c}__${h}`)}let g=new Map;function d(o){let c=JSON.stringify(o);return c&&c.length>30?`${c.slice(0,27)}...`:c??"undefined"}for(let o of t.nodes){let c=u(o.name);g.set(o.name,c);let h=r[o.kind]??"rectangle",_=`${o.name} (${o.kind}) = ${d(o.value)}`,w=o.status?` [${o.status}]`:"";n.push(`${c}: "${_}${w}" { shape: ${h} }`)}t.edges.length>0&&n.push("");for(let o of t.edges){let c=g.get(o.from)??u(o.from),h=g.get(o.to)??u(o.to);n.push(`${c} -> ${h}`)}return n.join(`
4
- `)}static annotate(e,s){if(!i.enabled)return;i._annotations.set(e,s);let t={node:i._resolveKey(e),reason:s,timestamp:Date.now()},n=i.maxTraceEntries;n<=0||(i._traceLog.length<n?i._traceLog.push(t):(i._traceLog[i._traceHead]=t,i._traceFull=!0),i._traceHead=(i._traceHead+1)%n)}static getAnnotation(e){return i._annotations.get(e)}static traceLog(){return i._traceFull?[...i._traceLog.slice(i._traceHead),...i._traceLog.slice(0,i._traceHead)]:i._traceLog.slice(0,i._traceHead||i._traceLog.length)}static clearTrace(){i._traceLog=[],i._traceHead=0,i._traceFull=!1}static timeline(e){let s=null,t=[];return e.source(T,(n,r)=>{if(n===T){s=r;return}let a={timestamp:Date.now(),type:n===E?"data":n===m?"signal":"end",data:r,inBatch:H()};t.push(a),n===y&&(s=null)}),{entries:t,dispose:()=>s?.(y)}}static observeDerived(e){let s=[],t=e,n=t._fn;if(typeof n!="function"||!Array.isArray(t._deps))return{...i.observe(e),evaluations:s};t._fn=()=>{let g=t._deps.map(o=>o.get()),d=n();return s.push({result:d,depValues:g,timestamp:Date.now()}),d};let r=i._observe(e),a=r.dispose;return{...r,evaluations:s,dispose:()=>{t._fn=n,a()},reconnect:()=>(t._fn=n,a(),i.observeDerived(e))}}static observeTaskState(e){let s=e.status.get(),t=[],n=null;return e.status.source(T,(r,a)=>{if(r===T){n=a;return}if(r===E){let u=a;if(u!==s){let g={from:s,to:u,timestamp:Date.now()};u==="error"&&(g.error=e.error.get()),t.push(g),s=u}}r===y&&(n=null)}),{transitions:t,get currentStatus(){return e.status.get()},dispose:()=>{n?.(y)}}}static causalityTrace(e){let s=[],t=e,n=t._fn;if(typeof n!="function"||!Array.isArray(t._deps))return{...i.observe(e),causality:s};let r=t._deps,a=r.map(o=>o.get());t._fn=()=>{let o=r.map(_=>_.get()),c=n(),h=-1;for(let _=0;_<r.length;_++)if(!Object.is(o[_],a[_])){h=_;break}return s.push({result:c,triggerDepIndex:h,triggerDepName:h>=0?i.getName(r[h]):void 0,depValues:o,timestamp:Date.now()}),a=o,c};let u=i._observe(e),g=u.dispose;return{...u,causality:s,dispose:()=>{t._fn=n,g()},reconnect:()=>(t._fn=n,g(),i.causalityTrace(e))}}static _reset(){i._names=new WeakMap,i._kinds=new WeakMap,i._keys=new WeakMap,i._stores=new Set,i._edges=new Map,i._usedKeys=new Set,i._nextId=0,i._explicitEnabled=null,i._cachedDefault=null,i._annotations=new WeakMap,i._traceLog=[],i._traceHead=0,i._traceFull=!1,i.maxTraceEntries=1e3}};var B=1,Q=2,X=4,L=8,K=32,Ae=64,Ge=de<<R,ee=ge<<R,Ne=pe<<R,re=he<<R,Je=_e<<R,be=me<<R,k=ie,Ee=class{_output=null;_upstreamTalkbacks=[];_cachedValue;_flags;_dirtyDeps;_eqFn;_deps;_fn;get _status(){return ye(this._flags)}constructor(e,s,t,n){this._deps=e,this._fn=s,this._eqFn=t?.equals,this._flags=n?Ae:0,this._dirtyDeps=new J(e.length),this.source=this.source.bind(this),O.register(this,{kind:"derived",...t,deps:e});for(let r of e)O.registerEdge(r,this)}_dispatch(e,s){let t=this._output;if(t)if(this._flags&K)for(let n of t)n(e,s);else t(e,s)}_recompute(){let e;try{e=this._fn()}catch(s){this._handleEnd(s);return}if(this._eqFn&&this._flags&B&&this._eqFn(this._cachedValue,e)){this._flags=this._flags&~k|re,this._dispatch(m,I);return}this._cachedValue=e,this._flags=(this._flags|B)&~k|Ne,this._dispatch(E,this._cachedValue)}_recomputeIdentity(e){if(!(this._flags&L)){if(this._eqFn&&this._flags&B&&this._eqFn(this._cachedValue,e)){this._flags=this._flags&~k|re,this._dispatch(m,I);return}this._cachedValue=e,this._flags=(this._flags|B)&~k|Ne,this._dispatch(E,e)}}_lazyConnect(){if(!(this._flags&(Q|L))){try{this._cachedValue=this._fn()}catch(e){this._handleEnd(e);return}this._flags=(this._flags|B)&~k|Ne,Se(),this._connectUpstream(),this._flags&L||(this._flags|=Q),ve()}}_connectUpstream(){this._upstreamTalkbacks.length=0,this._deps.length===1?this._flags&Ae?this._connectSingleDepIdentity():this._connectSingleDep():this._connectMultiDep()}_connectSingleDep(){let e=!1;this._deps[0].source(T,(s,t)=>{if(s===T){this._upstreamTalkbacks.push(t),t(m,Y);return}if(!(this._flags&L))if(s===m)if(t===b){if(e)return;e=!0,this._flags=this._flags&~k|ee,this._dispatch(m,b)}else t===I?e&&(e=!1,this._flags=this._flags&~k|re,this._dispatch(m,I)):this._dispatch(m,t);else s===E?e?(e=!1,this._recompute()):(this._flags=this._flags&~k|ee,this._dispatch(m,b),this._recompute()):s===y&&this._handleEnd(t)})}_connectSingleDepIdentity(){let e=!1;this._deps[0].source(T,(s,t)=>{if(s===T){this._upstreamTalkbacks.push(t),t(m,Y);return}this._flags&L||(s===m?t===b?(e=!0,this._flags=this._flags&~k|ee,this._dispatch(m,b)):t===I?e&&(e=!1,this._flags=this._flags&~k|re,this._dispatch(m,I)):this._dispatch(m,t):s===E?e?(e=!1,this._recomputeIdentity(t)):(this._flags=this._flags&~k|ee,this._dispatch(m,b),this._recomputeIdentity(t)):s===y&&this._handleEnd(t))})}_connectMultiDep(){for(let e=0;e<this._deps.length&&!(this._flags&L);e++){let s=e;this._deps[s].source(T,(t,n)=>{if(t===T){this._upstreamTalkbacks.push(n);return}if(!(this._flags&L))if(t===m)if(n===b){let r=this._dirtyDeps.empty();this._dirtyDeps.set(s),r&&(this._flags&=~X,this._flags=this._flags&~k|ee,this._dispatch(m,b))}else n===I?this._dirtyDeps.test(s)&&(this._dirtyDeps.clear(s),this._dirtyDeps.empty()&&(this._flags&X?this._recompute():(this._flags=this._flags&~k|re,this._dispatch(m,I)))):this._dispatch(m,n);else t===E?this._dirtyDeps.test(s)?(this._dirtyDeps.clear(s),this._flags|=X,this._dirtyDeps.empty()&&this._recompute()):this._dirtyDeps.empty()?(this._flags=this._flags&~k|ee,this._dispatch(m,b),this._recompute()):this._flags|=X:t===y&&this._handleEnd(n)})}}_handleEnd(e){this._flags|=L,this._flags=this._flags&~k|(e!==void 0?be:Je),e!==void 0&&(this._cachedValue=e);for(let n of this._upstreamTalkbacks)n(y);this._upstreamTalkbacks=[],this._flags&=~Q,this._dirtyDeps.reset();let s=this._output,t=this._flags&K;if(this._output=null,this._flags&=~K,s)if(t)for(let n of s)try{e!==void 0?n(y,e):n(y)}catch{}else e!==void 0?s(y,e):s(y)}_disconnectUpstream(){for(let e of this._upstreamTalkbacks)e(y);this._upstreamTalkbacks.length=0,this._flags&=~(Q|X),this._flags=this._flags&~k|Ge,this._dirtyDeps.reset()}_handleLifecycleSignal(e){if(!(this._flags&L)){if(e===W){for(let s of this._upstreamTalkbacks)s(m,W);this._handleEnd(void 0);return}e===U&&(this._flags&=~(B|X),this._dirtyDeps.reset());for(let s of this._upstreamTalkbacks)s(m,e)}}get(){if(this._flags&Q)return this._cachedValue;if(this._flags&L){if((this._flags&k)===be)throw this._cachedValue;return this._cachedValue}let e=this._fn();return this._cachedValue=e,this._flags|=B,e}source(e,s){if(e===T){let t=s;if(this._flags&L){let n=(this._flags&k)===be;t(T,r=>{}),n?t(y,this._cachedValue):t(y);return}if(!(this._flags&Q)&&(this._lazyConnect(),this._flags&L)){let n=(this._flags&k)===be;t(T,r=>{}),n?t(y,this._cachedValue):t(y);return}if(this._output===null)this._output=t;else if(this._flags&K)this._output.add(t);else{let n=new Set;n.add(this._output),n.add(t),this._output=n,this._flags|=K}t(T,(n,r)=>{if(n===E&&t(E,this._cachedValue),n===m&&Z(r)){this._handleLifecycleSignal(r);return}if(n===y){if(this._output===null)return;if(this._flags&K){let a=this._output;a.delete(t),a.size===1?(this._output=a.values().next().value,this._flags&=~K):a.size===0&&(this._output=null,this._flags&=~K,this._disconnectUpstream())}else this._output===t&&(this._output=null,this._disconnectUpstream())}})}}};function N(i,e,s){return new Ee(i,e,s)}(e=>{function i(s,t){return new Ee([s],()=>s.get(),t,!0)}e.from=i})(N||={});var De=1,P=64,A=2,te=4,Ce=8,$e=16,q=32,V=1024,x=ie,ne=ge<<R,oe=pe<<R,ke=de<<R,Ze=_e<<R,Qe=me<<R,Xe=he<<R,xe=class{_value;_output=null;_flags;get _status(){return ye(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;_onLifecycleSignal;constructor(e,s){this._value=s?.initial,this._fn=e,this._eqFn=s?.equals,this._getterFn=s?.getter,this._initial=s?.initial;let t=0;s?.autoDirty!==!1&&(t|=te),s?.resetOnTeardown&&(t|=Ce),s?.resubscribable&&(t|=$e),this._flags=t,this.source=this.source.bind(this),this.emit=this.emit.bind(this),s?._skipInspect||O.register(this,{kind:"producer",...s})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(e,s){let t=this._output;if(t)if(this._flags&P)for(let n of t)n(e,s);else t(e,s)}emit(e){this._flags&A||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(H()?this._flags&q||(this._flags|=q,this._flags&te&&(this._flags=this._flags&~x|ne,this._dispatch(m,b)),Te(()=>{this._flags&=~q,this._flags=this._flags&~x|oe,this._dispatch(E,this._value)})):(this._flags&te&&!(this._flags&V)&&(this._flags=this._flags&~x|ne,this._dispatch(m,b)),this._flags=this._flags&~x|oe,this._dispatch(E,this._value))))}signal(e){this._flags&A||!this._output||(e===b?this._flags=this._flags&~x|ne:e===I&&(this._flags=this._flags&~x|Xe),this._dispatch(m,e))}complete(){if(this._flags&A)return;this._flags=(this._flags|A)&~x|Ze;let e=this._output,s=this._flags&P;if(this._output=null,this._flags&=~(P|V),this._singleDepCount=0,this._stop(),e)if(s)for(let t of e)t(y);else e(y)}error(e){if(this._flags&A)return;this._flags=(this._flags|A)&~x|Qe;let s=this._output,t=this._flags&P;if(this._output=null,this._flags&=~(P|V),this._singleDepCount=0,this._stop(),s)if(t)for(let n of s)n(y,e);else s(y,e)}_start(){if(this._flags&De||!this._fn)return;this._flags|=De,this._onLifecycleSignal=void 0;let e=this._fn({emit:this.emit,signal:s=>this.signal(s),complete:()=>this.complete(),error:s=>this.error(s),onSignal:s=>{this._onLifecycleSignal=s}});this._cleanup=typeof e=="function"?e:void 0}_stop(){this._flags&De&&(this._flags&=~De,this._onLifecycleSignal=void 0,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&Ce&&(this._value=this._initial),this._flags&A||(this._flags=this._flags&~x|ke))}_handleLifecycleSignal(e){if(!(this._flags&A)){if(e===W){this._onLifecycleSignal?.(e),this.complete();return}e===U&&(this._value=this._initial,this._flags&=~q),this._onLifecycleSignal?.(e),e===U&&this.emit(this._initial)}}source(e,s){if(e===T){let t=s;if(this._flags&A)if(this._flags&$e&&this._output===null)this._flags=this._flags&~(A|x)|ke;else{t(T,r=>{}),t(y);return}if(this._output===null)this._output=t;else if(this._flags&P)this._output.add(t);else{let r=new Set;r.add(this._output),r.add(t),this._output=r,this._flags=(this._flags|P)&~V}let n=!1;t(T,(r,a)=>{if(r===E&&t(E,this._value),r===m){a===Y&&!n?(n=!0,this._singleDepCount++,this._flags&P||(this._flags|=V)):Z(a)&&this._handleLifecycleSignal(a);return}if(r===y){if(n&&(n=!1,this._singleDepCount--),this._output===null)return;if(this._flags&P){let u=this._output;u.delete(t),u.size===1?(this._output=u.values().next().value,this._flags&=~P,this._singleDepCount>0&&(this._flags|=V)):u.size===0&&(this._output=null,this._flags&=~(P|V),this._singleDepCount=0,this._flags=this._flags&~x|ke,this._stop())}else this._output===t&&(this._output=null,this._flags&=~V,this._singleDepCount=0,this._flags=this._flags&~x|ke,this._stop())}}),Le(()=>this._start())}}};var Oe=class extends xe{constructor(e,s){super(void 0,{initial:e,autoDirty:!0,equals:s?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),O.register(this,{kind:"state",...s})}get(){return this._value}set(e){this._flags&A||this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(H()?this._flags&q||(this._flags|=q,this._flags&te&&(this._flags=this._flags&~x|ne,this._dispatch(m,b)),Te(()=>{this._flags&=~q,this._flags=this._flags&~x|oe,this._dispatch(E,this._value)})):(this._flags&te&&!(this._flags&V)&&(this._flags=this._flags&~x|ne,this._dispatch(m,b)),this._flags=this._flags&~x|oe,this._dispatch(E,this._value))))}update(e){this.set(e(this._value))}};function z(i,e){return new Oe(i,e)}function we(i,e,s){let t,n=[],r=!1,a=new J(i.length),u=!1;function g(){r||(t&&t(),t=e())}let d=0;function o(h){if(!r){if(h===W){for(let _ of n)_(m,W);n.length=0,r=!0,t&&t(),t=void 0;return}h===U&&(d++,a.reset(),u=!1,g());for(let _ of n)_(m,h)}}Se(),g();for(let h=0;h<i.length&&!r;h++){let _=h,w=d;i[_].source(T,(C,F)=>{if(C===T){n.push(F),i.length===1&&F(m,Y);return}if(!r){if(C===m){if(Z(F)){o(F),w=d;return}if(w!==d)return;F===b?(a.empty()&&(u=!1),a.set(_)):F===I&&a.test(_)&&(a.clear(_),a.empty()&&u&&g())}if(C===E){if(w!==d)return;a.test(_)?(a.clear(_),u=!0,a.empty()&&g()):a.empty()?g():u=!0}if(C===y){r=!0,t&&t(),t=void 0;for(let l of n)l(y);n.length=0}}})}ve();let c=()=>{if(!r){r=!0,t&&t(),t=void 0;for(let h of n)h(y);n.length=0}};c.signal=h=>o(h),O.register(c,{kind:"effect",...s,deps:i});for(let h of i)O.registerEdge(h,c);return c}var et=0;Me.from=function(e){let s=Me({id:e.id});for(let[t,n]of Object.entries(e.index))for(let r of n)s.add(r,[t]);return s};function Me(i){let e=++et,s=i?.id??`ridx-${e}`,t=new Map,n=new Map,r=new Map,a=new Map,u=z(0,{name:`${s}:ver`}),g=N([u],()=>Array.from(t.keys()),{name:`${s}:keys`}),d=N([u],()=>t.size,{name:`${s}:size`}),o=!1,c=Object.freeze(new Set);function h(l){let p=r.get(l);return p||(p=z(t.get(l)??new Set,{name:`${s}:${l}`,equals:()=>!1}),r.set(l,p)),p}function _(l){let p=r.get(l);if(p){let f=t.get(l);p.set(f?new Set(f):new Set)}}function w(l,p){let f=t.get(p),S=!f;return f||(f=new Set,t.set(p,f)),f.add(l),S}function C(l,p){let f=t.get(p);return f?(f.delete(l),f.size===0?(t.delete(p),!0):!1):!1}return{get id(){return s},get version(){return u.get()},get(l){let p=t.get(l);return p?Object.freeze(new Set(p)):c},has(l){let p=t.get(l);return p!==void 0&&p.size>0},keys(){return Array.from(t.keys())},get size(){return t.size},select(l){let p=a.get(l);if(p)return p;let f=h(l);return p=N([f],()=>f.get(),{name:`${s}:${l}:select`}),a.set(l,p),p},keysStore:g,sizeStore:d,add(l,p){if(o||p.length===0)return;let f=n.get(l);f||(f=new Set,n.set(l,f)),j(()=>{let S=!1;for(let v of p)f.add(v),w(l,v)&&(S=!0),_(v);S&&u.update(v=>v+1)})},remove(l){if(o)return;let p=n.get(l);p&&j(()=>{let f=!1;for(let S of p)C(l,S)&&(f=!0),_(S);n.delete(l),f&&u.update(S=>S+1)})},update(l,p){if(o)return;let f=n.get(l),S=new Set(p);j(()=>{let v=!1;if(f)for(let M of f)S.has(M)||(C(l,M)&&(v=!0),_(M));let D=n.get(l);D||(D=new Set,n.set(l,D)),D.clear();for(let M of p)D.add(M),w(l,M)&&(v=!0),_(M);v&&u.update(M=>M+1)})},clear(){t.size!==0&&j(()=>{t.clear(),n.clear();for(let l of r.values())l.set(new Set);u.update(l=>l+1)})},snapshot(){let l={};for(let[p,f]of t)l[p]=Array.from(f);return{type:"reactiveIndex",id:s,version:u.get(),index:l}},destroy(){if(!o){o=!0,t.clear(),n.clear();for(let l of r.values())$(l);r.clear();for(let l of a.values())$(l);a.clear(),$(u)}}}}function Pe(i,e=s=>s){let s=[],t=new Map,n=new Map;function r(d,o){let c=s[d],h=s[o];s[d]=h,s[o]=c,c.index=o,h.index=d}function a(d){for(;d>0;){let o=d-1>>>1;if(s[o].score<=s[d].score)break;r(d,o),d=o}}function u(d){let o=s.length;for(;;){let c=d,h=2*d+1,_=h+1;if(h<o&&s[h].score<s[c].score&&(c=h),_<o&&s[_].score<s[c].score&&(c=_),c===d)break;r(d,c),d=c}}function g(d){let o=s.length-1;if(d===o){s.pop();return}r(d,o),s.pop(),a(d),u(d)}return{touch(){},insert(d){if(t.has(d))return;let o=i(d),c={key:d,score:e(o.get()),index:s.length};s.push(c),t.set(d,c),a(c.index);let h=we([o],()=>{let _=t.get(d);if(!_)return;let w=_.score;_.score=e(o.get()),_.score<w?a(_.index):_.score>w&&u(_.index)});n.set(d,h)},delete(d){let o=t.get(d);if(!o)return;let c=n.get(d);c&&(c(),n.delete(d)),g(o.index),t.delete(d)},evict(d=1){let o=[];for(;o.length<d&&s.length>0;){let{key:c}=s[0];o.push(c);let h=n.get(c);h&&(h(),n.delete(c)),g(0),t.delete(c)}return o},size:()=>t.size,clear(){for(let d of n.values())d();n.clear(),t.clear(),s.length=0}}}function se(i,e,s){let t=e?.halfLife??864e5,n=e?.recency??1,r=e?.importance??1,a=e?.frequency??.5,u=(s??Date.now())-i.accessedAt,g=Math.exp(-Math.LN2/t*u),d=1-1/(1+i.accessCount);return n*g+r*i.importance+a*d}var tt=0;function nt(){return`mem-${++tt}`}function Fe(i,e){let s=e?.id??nt(),t=Date.now(),n={id:s,createdAt:t,updatedAt:t,accessedAt:t,accessCount:0,importance:e?.importance??.5,tags:new Set(e?.tags)},r=z(i,{name:`mem:${s}:content`}),a=z(n,{name:`mem:${s}:meta`,equals:()=>!1}),u={},g=N([a],()=>se(a.get(),u),{name:`mem:${s}:score`});return{id:s,content:r,meta:a,scoreStore:g,touch(){let o=Date.now();a.update(c=>({...c,accessedAt:o,accessCount:c.accessCount+1}))},tag(...o){a.update(c=>{let h=new Set(c.tags);for(let _ of o)h.add(_);return{...c,tags:h,updatedAt:Date.now()}})},untag(...o){a.update(c=>{let h=new Set(c.tags);for(let _ of o)h.delete(_);return{...c,tags:h,updatedAt:Date.now()}})},setImportance(o){a.update(c=>({...c,importance:Math.max(0,Math.min(1,o)),updatedAt:Date.now()}))},update(o){j(()=>{r.set(o),a.update(c=>({...c,updatedAt:Date.now()}))})},score(o){return se(a.get(),o??u)},destroy(){$(r),$(a)}}}var st=0;function ae(i){let e=++st,s=i?.maxSize??1/0,t=i?.weights??{},n=new Map,r=Me(),a=new Map,u=s<1/0?Pe(l=>n.get(l).meta,l=>se(l,t)):null,g=z(0,{name:`collection-${e}:ver`}),d=N([g],()=>Array.from(n.values()),{name:`collection-${e}:nodes`}),o=N([g],()=>n.size,{name:`collection-${e}:size`}),c=!1;function h(){g.update(l=>l+1)}function _(l){let p=we([l.meta],()=>{let f=Array.from(l.meta.get().tags);r.update(l.id,f)});a.set(l.id,p)}function w(l){let p=a.get(l);p&&(p(),a.delete(l)),r.remove(l)}function C(){if(!u||n.size<=s)return;let l=u.evict(n.size-s);for(let p of l){let f=n.get(p);f&&(w(p),f.destroy(),n.delete(p))}}return{add(l,p){if(c)throw new Error("Collection is destroyed");let f=Fe(l,p);return n.set(f.id,f),_(f),u?.insert(f.id),C(),h(),f},remove(l){let p=typeof l=="string"?l:l.id,f=n.get(p);return f?(w(p),u?.delete(p),f.destroy(),n.delete(p),h(),!0):!1},get(l){return n.get(l)},has(l){return n.has(l)},nodes:d,size:o,tagIndex:r,query(l){let p=[];for(let f of n.values())l(f)&&p.push(f);return p},byTag(l){let p=r.get(l),f=[];for(let S of p){let v=n.get(S);v&&f.push(v)}return f},topK(l,p){let f=p??t,S=Date.now(),v=Array.from(n.values()).map(D=>({node:D,score:se(D.meta.get(),f,S)}));return v.sort((D,M)=>M.score-D.score),v.slice(0,l).map(D=>D.node)},destroy(){if(!c){c=!0,u?.clear();for(let l of a.values())l();a.clear(),r.destroy(),$(g),j(()=>{for(let l of n.values())l.destroy();n.clear()})}}}}function it(i){let e=i?.workingCapacity??20,s=i?.longTermCapacity??1e3,t=i?.weights??{},n=ae(),r=ae({maxSize:e}),a=ae({maxSize:s,weights:t}),u=z(0),g=N([u,r.size,a.size],()=>(u.get(),n.size.get()+r.size.get()+a.size.get()));function d(f,S){return n.add(f,S)}function o(f,S){return r.add(f,S)}function c(f,S){return a.add(f,S)}function h(f){let S=null,v=n.get(f);if(v?S=n:(v=r.get(f),v&&(S=r)),!v||!S)return!1;let D=v.meta.get(),M=a.add(v.content.get(),{id:D.id,importance:D.importance,tags:Array.from(D.tags)});for(let G=0;G<D.accessCount;G++)M.touch();return S.remove(f),!0}function _(f,S){let v=S??t,D=[...n.topK(f,v),...r.topK(f,v),...a.topK(f,v)];D.sort((G,Ve)=>Ve.score(v)-G.score(v));let M=D.slice(0,f);for(let G of M)G.touch();return M}function w(f){return[...n.byTag(f),...r.byTag(f),...a.byTag(f)]}function C(f){return[...n.query(f),...r.query(f),...a.query(f)]}function F(){n.destroy(),n=ae(),u.update(f=>f+1)}function l(){n.destroy(),r.destroy(),a.destroy(),$(u)}let p=N([u],()=>(u.get(),n.nodes.get()));return{remember:d,session:p,focus:o,working:r.nodes,store:c,longTerm:a.nodes,promote:h,recall:_,recallByTag:w,search:C,resetSession:F,destroy:l,totalSize:g}}0&&(module.exports={memoryStore});
1
+ "use strict";var Ie=Object.defineProperty;var Ve=Object.getOwnPropertyDescriptor;var We=Object.getOwnPropertyNames;var je=Object.prototype.hasOwnProperty;var Ue=(i,e)=>{for(var s in e)Ie(i,s,{get:e[s],enumerable:!0})},Ke=(i,e,s,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of We(e))!je.call(i,n)&&n!==s&&Ie(i,n,{get:()=>e[n],enumerable:!(t=Ve(e,n))||t.enumerable});return i};var qe=i=>Ke(Ie({},"__esModule",{value:!0}),i);var rt={};Ue(rt,{memoryStore:()=>it});module.exports=qe(rt);var re=class{_v;_w;constructor(e){this._v=0,this._w=e>32?new Uint32Array((e-1>>>5)+1):null}set(e){let s=this._w;if(s===null)this._v|=1<<e;else{let t=e>>>5,n=1<<(e&31);s[t]&n||(s[t]|=n,this._v++)}}clear(e){let s=this._w;if(s===null)this._v&=~(1<<e);else{let t=e>>>5,n=1<<(e&31);s[t]&n&&(s[t]&=~n,this._v--)}}test(e){let s=this._w;return s===null?(this._v&1<<e)!==0:(s[e>>>5]&1<<(e&31))!==0}empty(){return this._v===0}reset(){this._v=0,this._w?.fill(0)}};var E=Symbol("DIRTY"),R=Symbol("RESOLVED"),ee=Symbol("SINGLE_DEP"),Y=Symbol("RESET"),Ye=Symbol("PAUSE"),He=Symbol("RESUME"),H=Symbol("TEARDOWN");function ue(i){return i===Y||i===Ye||i===He||i===H}var fe=0,de=1,pe=2,ge=3,he=4,_e=5,I=7,te=7<<I,Be=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function me(i){return Be[(i&te)>>>I]}var v=0,D=1,_=2,m=3,oe=0,ae=[],Re=!1;function z(i){oe++;try{return i()}finally{if(oe--,oe===0&&!Re){Re=!0;for(let e=0;e<ae.length;e++)ae[e]();ae.length=0,Re=!1}}}function U(){return oe>0}function Te(i){ae.push(i)}var le=0,ce=[];function ye(){le++}function Se(){if(le--,le===0){for(let i=0;i<ce.length;i++)ce[i]();ce.length=0}}function Ae(i){le>0?ce.push(i):i()}function L(i){let e=i;typeof e.complete=="function"?e.complete():typeof e._handleEnd=="function"&&e._handleEnd(void 0)}var V=class i{static _names=new WeakMap;static _kinds=new WeakMap;static _keys=new WeakMap;static _stores=new Set;static _edges=new Map;static _nextId=0;static _usedKeys=new Set;static _explicitEnabled=null;static _cachedDefault=null;static _annotations=new WeakMap;static _traceLog=[];static _traceHead=0;static _traceFull=!1;static maxTraceEntries=1e3;static get enabled(){if(i._explicitEnabled!==null)return i._explicitEnabled;if(i._cachedDefault!==null)return i._cachedDefault;try{i._cachedDefault=globalThis.process?.env?.NODE_ENV!=="production"}catch{i._cachedDefault=!0}return i._cachedDefault}static set enabled(e){i._explicitEnabled=e}static _depSuffix(e){if(!e?.length)return;let t=e.map(n=>i._names.get(n)??"?").join(",");return t.length>40?`${t.slice(0,37)}...`:t}static _resolveKey(e){let s=i._keys.get(e)??i._names.get(e);if(s)return s;let t=`anonymous_${i._nextId++}`;return i._keys.set(e,t),t}static register(e,s){if(!i.enabled)return;s?.name&&i._names.set(e,s.name),s?.kind&&i._kinds.set(e,s.kind);let t=i._nextId++,n=s?.name;if(!(n&&!i._usedKeys.has(n)))if(n){let r=i._depSuffix(s?.deps);n=r?`${n}(${r})`:`${n}_${t}`,i._usedKeys.has(n)&&(n=`${n}_${t}`)}else{let r=s?.kind??"store",a=i._depSuffix(s?.deps);n=a?`${r}(${a})`:`${r}_${t}`,i._usedKeys.has(n)&&(n=`${n}_${t}`)}i._usedKeys.add(n),i._keys.set(e,n),i._stores.add(new WeakRef(e))}static registerEdge(e,s){if(!i.enabled)return;let t=i._resolveKey(e),n=i._resolveKey(s),r=i._edges.get(t);r?r.includes(n)||r.push(n):i._edges.set(t,[n])}static getEdges(){return new Map(i._edges)}static getName(e){if(i.enabled)return i._names.get(e)}static getKind(e){return i._kinds.get(e)}static inspect(e){return{name:i._names.get(e),kind:i._kinds.get(e)??"unknown",value:typeof e.get=="function"?e.get():void 0,status:e._status}}static graph(){let e=new Map,s=new Set;for(let t of i._stores){let n=t.deref();if(!n){i._stores.delete(t);continue}let r=i._resolveKey(n);s.add(r),e.set(r,i.inspect(n))}for(let[t,n]of i._edges){if(!s.has(t)){i._edges.delete(t),i._usedKeys.delete(t);continue}let r=n.filter(a=>s.has(a));r.length===0?i._edges.delete(t):r.length!==n.length&&i._edges.set(t,r)}return e}static trace(e,s){let t=null,n=e.get();return e.source(v,(r,a)=>{if(r===v&&(t=a),r===_){t=null;return}if(r===1){let u=a;if(!Object.is(u,n)){let p=n;n=u,s(u,p)}}}),()=>t?.(_)}static dumpGraph(){let e=i.graph(),s=i.getEdges(),t=new Map;for(let[a,u]of s)for(let p of u){let d=t.get(p);d?d.includes(a)||d.push(a):t.set(p,[a])}let n=[];for(let[a,u]of e){let p=t.get(a),d=s.get(a),o=p?.length?` \u2190 [${p.join(", ")}]`:"",l=d?.length?` \u2192 [${d.join(", ")}]`:"";n.push(` ${a} (${u.kind}) = ${JSON.stringify(u.value)} [${u.status??"?"}]${o}${l}`)}return[`Store Graph (${e.size} nodes):`,...n].join(`
2
+ `)}static _signalLabel(e){return e===E?"DIRTY":e===R?"RESOLVED":typeof e=="symbol"?e.description??String(e):String(e)}static _observe(e,s,t){let n=null,r=!1,a=s??i.getName(e),u=[],p={values:[],signals:[],events:[],ended:!1,endError:void 0,get completedCleanly(){return p.ended&&!r},get errored(){return p.ended&&r},dirtyCount:0,resolvedCount:0,name:a,get eventLog(){return u},dispose:()=>n?.(_),reconnect:()=>(n?.(_),i._observe(e,s,t))};return e.source(v,(d,o)=>{if(d===v){n=o;return}let l=U();d===D?(p.values.push(o),p.events.push({type:"data",data:o,inBatch:l}),u.push(o),t&&t(`[${a}] DATA:`,o)):d===m?(p.signals.push(o),p.events.push({type:"signal",data:o,inBatch:l}),u.push(i._signalLabel(o)),o===E?p.dirtyCount++:o===R&&p.resolvedCount++,t&&t(`[${a}] STATE:`,o)):d===_&&(p.ended=!0,p.endError=o,r=o!==void 0,p.events.push({type:"end",data:o,inBatch:l}),u.push(r?["END",o]:"END"),t&&t(`[${a}] END`,o!==void 0?o:""),n=null)}),p}static observe(e){return i._observe(e)}static activate(e){let s=null;return e.source(v,(t,n)=>{t===v&&(s=n),t===_&&(s=null)}),()=>s?.(_)}static tap(e,s){let t=s??`tap(${i.getName(e)??"anon"})`,n={get:()=>e.get(),source:e.source};return i.register(n,{name:t,kind:"tap"}),i.registerEdge(e,n),n}static spy(e,s){let t=s?.name??i.getName(e)??"spy",n=s?.log??console.log;return i._observe(e,t,n)}static snapshot(){let e=i.graph(),s=i.getEdges(),t=new Map;for(let a of i._stores){let u=a.deref();if(!u)continue;let p=i._annotations.get(u);p!==void 0&&t.set(i._resolveKey(u),p)}let n=[];for(let[a,u]of e){let p={name:a,kind:u.kind,value:u.value,status:u.status},d=t.get(a);d!==void 0&&(p.annotation=d),n.push(p)}let r=[];for(let[a,u]of s)for(let p of u)r.push({from:a,to:p});return{nodes:n,edges:r,trace:i.traceLog()}}static toMermaid(e){let s=e?.direction??"TD",t=i.snapshot(),n=[`graph ${s}`],r={SETTLED:":::settled",DIRTY:":::dirty",ERRORED:":::errored",COMPLETED:":::completed"},a=new Map;function u(o){let l=o.replace(/[^a-zA-Z0-9_]/g,"_"),h=a.get(l);return h===void 0?(a.set(l,1),l):(a.set(l,h+1),`${l}__${h}`)}let p=new Map;function d(o){let l=JSON.stringify(o);return l&&l.length>30?`${l.slice(0,27)}...`:l??"undefined"}for(let o of t.nodes){let l=u(o.name);p.set(o.name,l);let h=`${o.name} (${o.kind}) = ${d(o.value)}`,T=r[o.status??""]??"";n.push(` ${l}["${h}"]${T}`)}for(let o of t.edges){let l=p.get(o.from)??u(o.from),h=p.get(o.to)??u(o.to);n.push(` ${l} --> ${h}`)}return n.push(""),n.push(" classDef settled fill:#d4edda,stroke:#28a745"),n.push(" classDef dirty fill:#fff3cd,stroke:#ffc107"),n.push(" classDef errored fill:#f8d7da,stroke:#dc3545"),n.push(" classDef completed fill:#cce5ff,stroke:#007bff"),n.join(`
3
+ `)}static toD2(e){let s=e?.direction??"down",t=i.snapshot(),n=[`direction: ${s}`,""],r={state:"rectangle",derived:"hexagon",effect:"oval",producer:"rectangle",operator:"parallelogram","pipeline-step":"rectangle","pipeline-status":"diamond",checkpoint:"cylinder"},a=new Map;function u(o){let l=o.replace(/[^a-zA-Z0-9_]/g,"_"),h=a.get(l);return h===void 0?(a.set(l,1),l):(a.set(l,h+1),`${l}__${h}`)}let p=new Map;function d(o){let l=JSON.stringify(o);return l&&l.length>30?`${l.slice(0,27)}...`:l??"undefined"}for(let o of t.nodes){let l=u(o.name);p.set(o.name,l);let h=r[o.kind]??"rectangle",T=`${o.name} (${o.kind}) = ${d(o.value)}`,x=o.status?` [${o.status}]`:"";n.push(`${l}: "${T}${x}" { shape: ${h} }`)}t.edges.length>0&&n.push("");for(let o of t.edges){let l=p.get(o.from)??u(o.from),h=p.get(o.to)??u(o.to);n.push(`${l} -> ${h}`)}return n.join(`
4
+ `)}static annotate(e,s){if(!i.enabled)return;i._annotations.set(e,s);let t={node:i._resolveKey(e),reason:s,timestamp:Date.now()},n=i.maxTraceEntries;n<=0||(i._traceLog.length<n?i._traceLog.push(t):(i._traceLog[i._traceHead]=t,i._traceFull=!0),i._traceHead=(i._traceHead+1)%n)}static getAnnotation(e){return i._annotations.get(e)}static traceLog(){return i._traceFull?[...i._traceLog.slice(i._traceHead),...i._traceLog.slice(0,i._traceHead)]:i._traceLog.slice(0,i._traceHead||i._traceLog.length)}static clearTrace(){i._traceLog=[],i._traceHead=0,i._traceFull=!1}static timeline(e){let s=null,t=[];return e.source(v,(n,r)=>{if(n===v){s=r;return}let a={timestamp:Date.now(),type:n===D?"data":n===m?"signal":"end",data:r,inBatch:U()};t.push(a),n===_&&(s=null)}),{entries:t,dispose:()=>s?.(_)}}static observeDerived(e){let s=[],t=e,n=t._fn;if(typeof n!="function"||!Array.isArray(t._deps))return{...i.observe(e),evaluations:s};t._fn=()=>{let p=t._deps.map(o=>o.get()),d=n();return s.push({result:d,depValues:p,timestamp:Date.now()}),d};let r=i._observe(e),a=r.dispose;return{...r,evaluations:s,dispose:()=>{t._fn=n,a()},reconnect:()=>(t._fn=n,a(),i.observeDerived(e))}}static observeTaskState(e){let s=e.status.get(),t=[],n=null;return e.status.source(v,(r,a)=>{if(r===v){n=a;return}if(r===D){let u=a;if(u!==s){let p={from:s,to:u,timestamp:Date.now()};u==="error"&&(p.error=e.error.get()),t.push(p),s=u}}r===_&&(n=null)}),{transitions:t,get currentStatus(){return e.status.get()},dispose:()=>{n?.(_)}}}static causalityTrace(e){let s=[],t=e,n=t._fn;if(typeof n!="function"||!Array.isArray(t._deps))return{...i.observe(e),causality:s};let r=t._deps,a=r.map(o=>o.get());t._fn=()=>{let o=r.map(T=>T.get()),l=n(),h=-1;for(let T=0;T<r.length;T++)if(!Object.is(o[T],a[T])){h=T;break}return s.push({result:l,triggerDepIndex:h,triggerDepName:h>=0?i.getName(r[h]):void 0,depValues:o,timestamp:Date.now()}),a=o,l};let u=i._observe(e),p=u.dispose;return{...u,causality:s,dispose:()=>{t._fn=n,p()},reconnect:()=>(t._fn=n,p(),i.causalityTrace(e))}}static _reset(){i._names=new WeakMap,i._kinds=new WeakMap,i._keys=new WeakMap,i._stores=new Set,i._edges=new Map,i._usedKeys=new Set,i._nextId=0,i._explicitEnabled=null,i._cachedDefault=null,i._annotations=new WeakMap,i._traceLog=[],i._traceHead=0,i._traceFull=!1,i.maxTraceEntries=1e3}};var K=1,B=2,G=4,O=8,W=32,Le=64,Ge=fe<<I,J=de<<I,Ne=pe<<I,se=ge<<I,Je=he<<I,ve=_e<<I,k=te,be=class{_output=null;_upstreamTalkbacks=[];_cachedValue;_flags;_dirtyDeps;_eqFn;_deps;_fn;get _status(){return me(this._flags)}constructor(e,s,t,n){this._deps=e,this._fn=s,this._eqFn=t?.equals,this._flags=n?Le:0,this._dirtyDeps=new re(e.length),this.source=this.source.bind(this),V.register(this,{kind:"derived",...t,deps:e});for(let r of e)V.registerEdge(r,this)}_dispatch(e,s){let t=this._output;if(t)if(this._flags&W)for(let n of t)n(e,s);else t(e,s)}_recompute(){let e;try{e=this._fn()}catch(s){this._handleEnd(s);return}if(this._eqFn&&this._flags&K&&this._eqFn(this._cachedValue,e)){this._flags=this._flags&~k|se,this._dispatch(m,R);return}this._cachedValue=e,this._flags=(this._flags|K)&~k|Ne,this._dispatch(D,this._cachedValue)}_recomputeIdentity(e){if(!(this._flags&O)){if(this._eqFn&&this._flags&K&&this._eqFn(this._cachedValue,e)){this._flags=this._flags&~k|se,this._dispatch(m,R);return}this._cachedValue=e,this._flags=(this._flags|K)&~k|Ne,this._dispatch(D,e)}}_lazyConnect(){if(!(this._flags&(B|O))){try{this._cachedValue=this._fn()}catch(e){this._handleEnd(e);return}this._flags=(this._flags|K)&~k|Ne,ye(),this._connectUpstream(),this._flags&O||(this._flags|=B),Se()}}_connectUpstream(){this._upstreamTalkbacks.length=0,this._deps.length===1?this._flags&Le?this._connectSingleDepIdentity():this._connectSingleDep():this._connectMultiDep()}_connectSingleDep(){let e=!1;this._deps[0].source(v,(s,t)=>{if(s===v){this._upstreamTalkbacks.push(t),t(m,ee);return}if(!(this._flags&O))if(s===m)if(t===E){if(e)return;e=!0,this._flags=this._flags&~k|J,this._dispatch(m,E)}else t===R?e&&(e=!1,this._flags=this._flags&~k|se,this._dispatch(m,R)):this._dispatch(m,t);else s===D?e?(e=!1,this._recompute()):(this._flags=this._flags&~k|J,this._dispatch(m,E),this._recompute()):s===_&&this._handleEnd(t)})}_connectSingleDepIdentity(){let e=!1;this._deps[0].source(v,(s,t)=>{if(s===v){this._upstreamTalkbacks.push(t),t(m,ee);return}this._flags&O||(s===m?t===E?(e=!0,this._flags=this._flags&~k|J,this._dispatch(m,E)):t===R?e&&(e=!1,this._flags=this._flags&~k|se,this._dispatch(m,R)):this._dispatch(m,t):s===D?e?(e=!1,this._recomputeIdentity(t)):(this._flags=this._flags&~k|J,this._dispatch(m,E),this._recomputeIdentity(t)):s===_&&this._handleEnd(t))})}_connectMultiDep(){for(let e=0;e<this._deps.length&&!(this._flags&O);e++){let s=e;this._deps[s].source(v,(t,n)=>{if(t===v){this._upstreamTalkbacks.push(n);return}if(!(this._flags&O))if(t===m)if(n===E){let r=this._dirtyDeps.empty();this._dirtyDeps.set(s),r&&(this._flags&=~G,this._flags=this._flags&~k|J,this._dispatch(m,E))}else n===R?this._dirtyDeps.test(s)&&(this._dirtyDeps.clear(s),this._dirtyDeps.empty()&&(this._flags&G?this._recompute():(this._flags=this._flags&~k|se,this._dispatch(m,R)))):this._dispatch(m,n);else t===D?this._dirtyDeps.test(s)?(this._dirtyDeps.clear(s),this._flags|=G,this._dirtyDeps.empty()&&this._recompute()):this._dirtyDeps.empty()?(this._flags=this._flags&~k|J,this._dispatch(m,E),this._recompute()):this._flags|=G:t===_&&this._handleEnd(n)})}}_handleEnd(e){this._flags|=O,this._flags=this._flags&~k|(e!==void 0?ve:Je),e!==void 0&&(this._cachedValue=e);for(let n of this._upstreamTalkbacks)n(_);this._upstreamTalkbacks=[],this._flags&=~B,this._dirtyDeps.reset();let s=this._output,t=this._flags&W;if(this._output=null,this._flags&=~W,s)if(t)for(let n of s)try{e!==void 0?n(_,e):n(_)}catch{}else e!==void 0?s(_,e):s(_)}_disconnectUpstream(){for(let e of this._upstreamTalkbacks)e(_);this._upstreamTalkbacks.length=0,this._flags&=~(B|G),this._flags=this._flags&~k|Ge,this._dirtyDeps.reset()}_handleLifecycleSignal(e){if(!(this._flags&O)){if(e===H){for(let s of this._upstreamTalkbacks)s(m,H);this._handleEnd(void 0);return}e===Y&&(this._flags&=~(K|G),this._dirtyDeps.reset());for(let s of this._upstreamTalkbacks)s(m,e)}}get(){if(this._flags&B)return this._cachedValue;if(this._flags&O){if((this._flags&k)===ve)throw this._cachedValue;return this._cachedValue}let e=this._fn();return this._cachedValue=e,this._flags|=K,e}source(e,s){if(e===v){let t=s;if(this._flags&O){let n=(this._flags&k)===ve;t(v,r=>{}),n?t(_,this._cachedValue):t(_);return}if(!(this._flags&B)&&(this._lazyConnect(),this._flags&O)){let n=(this._flags&k)===ve;t(v,r=>{}),n?t(_,this._cachedValue):t(_);return}if(this._output===null)this._output=t;else if(this._flags&W)this._output.add(t);else{let n=new Set;n.add(this._output),n.add(t),this._output=n,this._flags|=W}t(v,(n,r)=>{if(n===D&&t(D,this._cachedValue),n===m&&ue(r)){this._handleLifecycleSignal(r);return}if(n===_){if(this._output===null)return;if(this._flags&W){let a=this._output;a.delete(t),a.size===1?(this._output=a.values().next().value,this._flags&=~W):a.size===0&&(this._output=null,this._flags&=~W,this._disconnectUpstream())}else this._output===t&&(this._output=null,this._disconnectUpstream())}})}}};function N(i,e,s){return new be(i,e,s)}(e=>{function i(s,t){return new be([s],()=>s.get(),t,!0)}e.from=i})(N||={});var Ee=1,C=64,A=2,Z=4,Ce=8,$e=16,j=32,$=1024,w=te,Q=de<<I,ne=pe<<I,De=fe<<I,Ze=he<<I,Qe=_e<<I,Xe=ge<<I,ke=class{_value;_output=null;_flags;get _status(){return me(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;_onLifecycleSignal;constructor(e,s){this._value=s?.initial,this._fn=e,this._eqFn=s?.equals,this._getterFn=s?.getter,this._initial=s?.initial;let t=0;s?.autoDirty!==!1&&(t|=Z),s?.resetOnTeardown&&(t|=Ce),s?.resubscribable&&(t|=$e),this._flags=t,this.source=this.source.bind(this),this.emit=this.emit.bind(this),s?._skipInspect||V.register(this,{kind:"producer",...s})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(e,s){let t=this._output;if(t)if(this._flags&C)for(let n of t)n(e,s);else t(e,s)}emit(e){this._flags&A||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(U()?this._flags&j||(this._flags|=j,this._flags&Z&&(this._flags=this._flags&~w|Q,this._dispatch(m,E)),Te(()=>{this._flags&=~j,this._flags=this._flags&~w|ne,this._dispatch(D,this._value)})):(this._flags&Z&&!(this._flags&$)&&(this._flags=this._flags&~w|Q,this._dispatch(m,E)),this._flags=this._flags&~w|ne,this._dispatch(D,this._value))))}signal(e){this._flags&A||!this._output||(e===E?this._flags=this._flags&~w|Q:e===R&&(this._flags=this._flags&~w|Xe),this._dispatch(m,e))}complete(){if(this._flags&A)return;this._flags=(this._flags|A)&~w|Ze;let e=this._output,s=this._flags&C;if(this._output=null,this._flags&=~(C|$),this._singleDepCount=0,this._stop(),e)if(s)for(let t of e)t(_);else e(_)}error(e){if(this._flags&A)return;this._flags=(this._flags|A)&~w|Qe;let s=this._output,t=this._flags&C;if(this._output=null,this._flags&=~(C|$),this._singleDepCount=0,this._stop(),s)if(t)for(let n of s)n(_,e);else s(_,e)}_start(){if(this._flags&Ee||!this._fn)return;this._flags|=Ee,this._onLifecycleSignal=void 0;let e=this._fn({emit:this.emit,signal:s=>this.signal(s),complete:()=>this.complete(),error:s=>this.error(s),onSignal:s=>{this._onLifecycleSignal=s}});this._cleanup=typeof e=="function"?e:void 0}_stop(){this._flags&Ee&&(this._flags&=~Ee,this._onLifecycleSignal=void 0,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&Ce&&(this._value=this._initial),this._flags&A||(this._flags=this._flags&~w|De))}_handleLifecycleSignal(e){if(!(this._flags&A)){if(e===H){this._onLifecycleSignal?.(e),this.complete();return}e===Y&&(this._value=this._initial,this._flags&=~j),this._onLifecycleSignal?.(e),e===Y&&this.emit(this._initial)}}source(e,s){if(e===v){let t=s;if(this._flags&A)if(this._flags&$e&&this._output===null)this._flags=this._flags&~(A|w)|De;else{t(v,r=>{}),t(_);return}if(this._output===null)this._output=t;else if(this._flags&C)this._output.add(t);else{let r=new Set;r.add(this._output),r.add(t),this._output=r,this._flags=(this._flags|C)&~$}let n=!1;t(v,(r,a)=>{if(r===D&&t(D,this._value),r===m){a===ee&&!n?(n=!0,this._singleDepCount++,this._flags&C||(this._flags|=$)):ue(a)&&this._handleLifecycleSignal(a);return}if(r===_){if(n&&(n=!1,this._singleDepCount--),this._output===null)return;if(this._flags&C){let u=this._output;u.delete(t),u.size===1?(this._output=u.values().next().value,this._flags&=~C,this._singleDepCount>0&&(this._flags|=$)):u.size===0&&(this._output=null,this._flags&=~(C|$),this._singleDepCount=0,this._flags=this._flags&~w|De,this._stop())}else this._output===t&&(this._output=null,this._flags&=~$,this._singleDepCount=0,this._flags=this._flags&~w|De,this._stop())}}),Ae(()=>this._start())}}};var Oe=class extends ke{constructor(e,s){super(void 0,{initial:e,autoDirty:!0,equals:s?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),V.register(this,{kind:"state",...s})}get(){return this._value}set(e){this._flags&A||this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(U()?this._flags&j||(this._flags|=j,this._flags&Z&&(this._flags=this._flags&~w|Q,this._dispatch(m,E)),Te(()=>{this._flags&=~j,this._flags=this._flags&~w|ne,this._dispatch(D,this._value)})):(this._flags&Z&&!(this._flags&$)&&(this._flags=this._flags&~w|Q,this._dispatch(m,E)),this._flags=this._flags&~w|ne,this._dispatch(D,this._value))))}update(e){this.set(e(this._value))}};function P(i,e){return new Oe(i,e)}function xe(i,e,s){let t=null;ye(),i.source(v,(r,a)=>{if(r===v&&(t=a),r===_){t=null,s?.onEnd?.(a);return}if(r===1){let u=a,p=n;n=u,e(u,p)}});let n;try{n=i.get()}catch{}return Se(),{unsubscribe(){t?.(_),t=null},signal(r){t?.(m,r)}}}var et=0;we.from=function(e){let s=we({id:e.id});for(let[t,n]of Object.entries(e.index))for(let r of n)s.add(r,[t]);return s};function we(i){let e=++et,s=i?.id??`ridx-${e}`,t=new Map,n=new Map,r=new Map,a=new Map,u=P(0,{name:`${s}:ver`}),p=N([u],()=>Array.from(t.keys()),{name:`${s}:keys`}),d=N([u],()=>t.size,{name:`${s}:size`}),o=!1,l=Object.freeze(new Set);function h(c){let g=r.get(c);return g||(g=P(t.get(c)??new Set,{name:`${s}:${c}`,equals:()=>!1}),r.set(c,g)),g}function T(c){let g=r.get(c);if(g){let f=t.get(c);g.set(f?new Set(f):new Set)}}function x(c,g){let f=t.get(g),y=!f;return f||(f=new Set,t.set(g,f)),f.add(c),y}function F(c,g){let f=t.get(g);return f?(f.delete(c),f.size===0?(t.delete(g),!0):!1):!1}return{get id(){return s},get version(){return u.get()},get(c){let g=t.get(c);return g?Object.freeze(new Set(g)):l},has(c){let g=t.get(c);return g!==void 0&&g.size>0},keys(){return Array.from(t.keys())},get size(){return t.size},select(c){let g=a.get(c);if(g)return g;let f=h(c);return g=N([f],()=>f.get(),{name:`${s}:${c}:select`}),a.set(c,g),g},keysStore:p,sizeStore:d,add(c,g){if(o||g.length===0)return;let f=n.get(c);f||(f=new Set,n.set(c,f)),z(()=>{let y=!1;for(let S of g)f.add(S),x(c,S)&&(y=!0),T(S);y&&u.update(S=>S+1)})},remove(c){if(o)return;let g=n.get(c);g&&z(()=>{let f=!1;for(let y of g)F(c,y)&&(f=!0),T(y);n.delete(c),f&&u.update(y=>y+1)})},update(c,g){if(o)return;let f=n.get(c),y=new Set(g);z(()=>{let S=!1;if(f)for(let M of f)y.has(M)||(F(c,M)&&(S=!0),T(M));let b=n.get(c);b||(b=new Set,n.set(c,b)),b.clear();for(let M of g)b.add(M),x(c,M)&&(S=!0),T(M);S&&u.update(M=>M+1)})},clear(){t.size!==0&&z(()=>{t.clear(),n.clear();for(let c of r.values())c.set(new Set);u.update(c=>c+1)})},snapshot(){let c={};for(let[g,f]of t)c[g]=Array.from(f);return{type:"reactiveIndex",id:s,version:u.get(),index:c}},destroy(){if(!o){o=!0,t.clear(),n.clear();for(let c of r.values())L(c);r.clear();for(let c of a.values())L(c);a.clear(),L(u)}}}}function Pe(i,e=s=>s){let s=[],t=new Map,n=new Map;function r(d,o){let l=s[d],h=s[o];s[d]=h,s[o]=l,l.index=o,h.index=d}function a(d){for(;d>0;){let o=d-1>>>1;if(s[o].score<=s[d].score)break;r(d,o),d=o}}function u(d){let o=s.length;for(;;){let l=d,h=2*d+1,T=h+1;if(h<o&&s[h].score<s[l].score&&(l=h),T<o&&s[T].score<s[l].score&&(l=T),l===d)break;r(d,l),d=l}}function p(d){let o=s.length-1;if(d===o){s.pop();return}r(d,o),s.pop(),a(d),u(d)}return{touch(){},insert(d){if(t.has(d))return;let o=i(d),l={key:d,score:e(o.get()),index:s.length};s.push(l),t.set(d,l),a(l.index);let h=xe(o,T=>{let x=t.get(d);if(!x)return;let F=x.score;x.score=e(T),x.score<F?a(x.index):x.score>F&&u(x.index)});n.set(d,()=>h.unsubscribe())},delete(d){let o=t.get(d);if(!o)return;let l=n.get(d);l&&(l(),n.delete(d)),p(o.index),t.delete(d)},evict(d=1){let o=[];for(;o.length<d&&s.length>0;){let{key:l}=s[0];o.push(l);let h=n.get(l);h&&(h(),n.delete(l)),p(0),t.delete(l)}return o},size:()=>t.size,clear(){for(let d of n.values())d();n.clear(),t.clear(),s.length=0}}}function X(i,e,s){let t=e?.halfLife??864e5,n=e?.recency??1,r=e?.importance??1,a=e?.frequency??.5,u=(s??Date.now())-i.accessedAt,p=Math.exp(-Math.LN2/t*u),d=1-1/(1+i.accessCount);return n*p+r*i.importance+a*d}var tt=0;function st(){return`mem-${++tt}`}function Fe(i,e){let s=e?.id??st(),t=Date.now(),n={id:s,createdAt:t,updatedAt:t,accessedAt:t,accessCount:0,importance:e?.importance??.5,tags:new Set(e?.tags)},r=P(i,{name:`mem:${s}:content`}),a=P(n,{name:`mem:${s}:meta`,equals:()=>!1}),u={},p=N([a],()=>X(a.get(),u),{name:`mem:${s}:score`});return{id:s,content:r,meta:a,scoreStore:p,touch(){let o=Date.now();a.update(l=>({...l,accessedAt:o,accessCount:l.accessCount+1}))},tag(...o){a.update(l=>{let h=new Set(l.tags);for(let T of o)h.add(T);return{...l,tags:h,updatedAt:Date.now()}})},untag(...o){a.update(l=>{let h=new Set(l.tags);for(let T of o)h.delete(T);return{...l,tags:h,updatedAt:Date.now()}})},setImportance(o){a.update(l=>({...l,importance:Math.max(0,Math.min(1,o)),updatedAt:Date.now()}))},update(o){z(()=>{r.set(o),a.update(l=>({...l,updatedAt:Date.now()}))})},score(o){return X(a.get(),o??u)},destroy(){L(r),L(a)}}}var nt=0;function ie(i){let e=++nt,s=i?.maxSize??1/0,t=i?.weights??{},n=new Map,r=we(),a=new Map,u=s<1/0?Pe(c=>n.get(c).meta,c=>X(c,t)):null,p=P(0,{name:`collection-${e}:ver`}),d=N([p],()=>Array.from(n.values()),{name:`collection-${e}:nodes`}),o=N([p],()=>n.size,{name:`collection-${e}:size`}),l=!1;function h(){p.update(c=>c+1)}function T(c){let g=Array.from(c.meta.get().tags);r.update(c.id,g);let f=xe(c.meta,y=>{let S=Array.from(y.tags);r.update(c.id,S)});a.set(c.id,()=>f.unsubscribe())}function x(c){let g=a.get(c);g&&(g(),a.delete(c)),r.remove(c)}function F(){if(!u||n.size<=s)return;let c=u.evict(n.size-s);for(let g of c){let f=n.get(g);f&&(x(g),f.destroy(),n.delete(g))}}return{add(c,g){if(l)throw new Error("Collection is destroyed");let f=Fe(c,g);return n.set(f.id,f),T(f),u?.insert(f.id),F(),h(),f},remove(c){let g=typeof c=="string"?c:c.id,f=n.get(g);return f?(x(g),u?.delete(g),f.destroy(),n.delete(g),h(),!0):!1},get(c){return n.get(c)},has(c){return n.has(c)},nodes:d,size:o,tagIndex:r,query(c){let g=[];for(let f of n.values())c(f)&&g.push(f);return g},byTag(c){let g=r.get(c),f=[];for(let y of g){let S=n.get(y);S&&f.push(S)}return f},topK(c,g){let f=g??t,y=Date.now(),S=Array.from(n.values()).map(b=>({node:b,score:X(b.meta.get(),f,y)}));return S.sort((b,M)=>M.score-b.score),S.slice(0,c).map(b=>b.node)},destroy(){if(!l){l=!0,u?.clear();for(let c of a.values())c();a.clear(),r.destroy(),L(p),z(()=>{for(let c of n.values())c.destroy();n.clear()})}}}}function it(i){let e=i?.workingCapacity??20,s=i?.longTermCapacity??1e3,t=i?.weights??{},n=ie(),r=ie({maxSize:e}),a=ie({maxSize:s,weights:t}),u=P(0),p=N([u,r.size,a.size],()=>(u.get(),n.size.get()+r.size.get()+a.size.get()));function d(f,y){return n.add(f,y)}function o(f,y){return r.add(f,y)}function l(f,y){return a.add(f,y)}function h(f){let y=null,S=n.get(f);if(S?y=n:(S=r.get(f),S&&(y=r)),!S||!y)return!1;let b=S.meta.get(),M=a.add(S.content.get(),{id:b.id,importance:b.importance,tags:Array.from(b.tags)});for(let q=0;q<b.accessCount;q++)M.touch();return y.remove(f),!0}function T(f,y){let S=y??t,b=[...n.topK(f,S),...r.topK(f,S),...a.topK(f,S)];b.sort((q,ze)=>ze.score(S)-q.score(S));let M=b.slice(0,f);for(let q of M)q.touch();return M}function x(f){return[...n.byTag(f),...r.byTag(f),...a.byTag(f)]}function F(f){return[...n.query(f),...r.query(f),...a.query(f)]}function Me(){n.destroy(),n=ie(),u.update(f=>f+1)}function c(){n.destroy(),r.destroy(),a.destroy(),L(u)}let g=N([u],()=>(u.get(),n.nodes.get()));return{remember:d,session:g,focus:o,working:r.nodes,store:l,longTerm:a.nodes,promote:h,recall:T,recallByTag:x,search:F,resetSession:Me,destroy:c,totalSize:p}}0&&(module.exports={memoryStore});
@@ -1 +1 @@
1
- import{d}from"../../chunk-3ETD2EFQ.js";import"../../chunk-6HKVNUGH.js";import"../../chunk-ZJCF5NYF.js";import"../../chunk-2ZFSL4MA.js";import{a as u}from"../../chunk-PV347CGV.js";import"../../chunk-HK7DRUNM.js";import{a as l}from"../../chunk-EAK2HKAD.js";import"../../chunk-2F6QWERG.js";import"../../chunk-2L6223KN.js";import{B as g}from"../../chunk-TUPD47IE.js";import"../../chunk-I7AUKTXE.js";function B(a){let p=a?.workingCapacity??20,M=a?.longTermCapacity??1e3,T=a?.weights??{},t=d(),n=d({maxSize:p}),s=d({maxSize:M,weights:T}),m=l(0),f=u([m,n.size,s.size],()=>(m.get(),t.size.get()+n.size.get()+s.size.get()));function N(e,o){return t.add(e,o)}function S(e,o){return n.add(e,o)}function b(e,o){return s.add(e,o)}function h(e){let o=null,r=t.get(e);if(r?o=t:(r=n.get(e),r&&(o=n)),!r||!o)return!1;let i=r.meta.get(),y=s.add(r.content.get(),{id:i.id,importance:i.importance,tags:Array.from(i.tags)});for(let c=0;c<i.accessCount;c++)y.touch();return o.remove(e),!0}function w(e,o){let r=o??T,i=[...t.topK(e,r),...n.topK(e,r),...s.topK(e,r)];i.sort((c,W)=>W.score(r)-c.score(r));let y=i.slice(0,e);for(let c of y)c.touch();return y}function z(e){return[...t.byTag(e),...n.byTag(e),...s.byTag(e)]}function C(e){return[...t.query(e),...n.query(e),...s.query(e)]}function O(){t.destroy(),t=d(),m.update(e=>e+1)}function v(){t.destroy(),n.destroy(),s.destroy(),g(m)}let x=u([m],()=>(m.get(),t.nodes.get()));return{remember:N,session:x,focus:S,working:n.nodes,store:b,longTerm:s.nodes,promote:h,recall:w,recallByTag:z,search:C,resetSession:O,destroy:v,totalSize:f}}export{B as memoryStore};
1
+ import{d}from"../../chunk-G65KU7M5.js";import"../../chunk-JCENQEPP.js";import"../../chunk-ZJCF5NYF.js";import{a as u}from"../../chunk-PV347CGV.js";import"../../chunk-HK7DRUNM.js";import"../../chunk-GMLWTZFM.js";import{a as l}from"../../chunk-EAK2HKAD.js";import"../../chunk-2F6QWERG.js";import"../../chunk-2L6223KN.js";import{B as g}from"../../chunk-TUPD47IE.js";import"../../chunk-I7AUKTXE.js";function B(a){let p=a?.workingCapacity??20,M=a?.longTermCapacity??1e3,T=a?.weights??{},t=d(),n=d({maxSize:p}),s=d({maxSize:M,weights:T}),m=l(0),f=u([m,n.size,s.size],()=>(m.get(),t.size.get()+n.size.get()+s.size.get()));function N(e,o){return t.add(e,o)}function S(e,o){return n.add(e,o)}function b(e,o){return s.add(e,o)}function h(e){let o=null,r=t.get(e);if(r?o=t:(r=n.get(e),r&&(o=n)),!r||!o)return!1;let i=r.meta.get(),y=s.add(r.content.get(),{id:i.id,importance:i.importance,tags:Array.from(i.tags)});for(let c=0;c<i.accessCount;c++)y.touch();return o.remove(e),!0}function w(e,o){let r=o??T,i=[...t.topK(e,r),...n.topK(e,r),...s.topK(e,r)];i.sort((c,W)=>W.score(r)-c.score(r));let y=i.slice(0,e);for(let c of y)c.touch();return y}function z(e){return[...t.byTag(e),...n.byTag(e),...s.byTag(e)]}function C(e){return[...t.query(e),...n.query(e),...s.query(e)]}function O(){t.destroy(),t=d(),m.update(e=>e+1)}function v(){t.destroy(),n.destroy(),s.destroy(),g(m)}let x=u([m],()=>(m.get(),t.nodes.get()));return{remember:N,session:x,focus:S,working:n.nodes,store:b,longTerm:s.nodes,promote:h,recall:w,recallByTag:z,search:C,resetSession:O,destroy:v,totalSize:f}}export{B as memoryStore};
@@ -1,6 +1,6 @@
1
- "use strict";var Ht=Object.create;var Te=Object.defineProperty;var Yt=Object.getOwnPropertyDescriptor;var Qt=Object.getOwnPropertyNames;var Gt=Object.getPrototypeOf,Jt=Object.prototype.hasOwnProperty;var Zt=(t,e)=>{for(var n in e)Te(t,n,{get:e[n],enumerable:!0})},Ye=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Qt(e))!Jt.call(t,o)&&o!==n&&Te(t,o,{get:()=>e[o],enumerable:!(r=Yt(e,o))||r.enumerable});return t};var Fe=(t,e,n)=>(n=t!=null?Ht(Gt(t)):{},Ye(e||!t||!t.__esModule?Te(n,"default",{value:t,enumerable:!0}):n,t)),Xt=t=>Ye(Te({},"__esModule",{value:!0}),t);var dn={};Zt(dn,{CircuitOpenError:()=>Se,asyncQueue:()=>et,batchWriter:()=>at,cancellableAction:()=>ct,cancellableStream:()=>ut,cascadingCache:()=>$e,checkpoint:()=>mt,circuitBreaker:()=>bt,connectionHealth:()=>vt,constant:()=>tt,countdown:()=>It,dag:()=>_t,decorrelatedJitter:()=>it,dirtyTracker:()=>xt,exponential:()=>rt,fibonacci:()=>ot,fifo:()=>lt,fileAdapter:()=>gt,fromAbortable:()=>Ue,indexedDBAdapter:()=>Tt,keyedAsync:()=>kt,lfu:()=>ft,linear:()=>nt,lru:()=>Ie,memoryAdapter:()=>ht,random:()=>pt,reactiveScored:()=>Ct,retry:()=>Rt,scored:()=>dt,slidingWindow:()=>Dt,sqliteAdapter:()=>St,stateMachine:()=>Mt,stopwatch:()=>$t,tieredStorage:()=>Lt,tokenBucket:()=>wt,tokenTracker:()=>Bt,track:()=>Kt,validationPipeline:()=>Ft,withBreaker:()=>Wt,withConnectionStatus:()=>zt,withMaxAttempts:()=>st,withMeta:()=>jt,withStatus:()=>Ut});module.exports=Xt(dn);var R=Symbol("DIRTY"),I=Symbol("RESOLVED"),J=Symbol("SINGLE_DEP"),z=Symbol("RESET"),xe=Symbol("PAUSE"),ke=Symbol("RESUME"),q=Symbol("TEARDOWN");function ne(t){return t===z||t===xe||t===ke||t===q}var Ee=0,we=1,De=2,Ae=3,Ce=4,Re=5,$=7,pe=7<<$,en=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function Oe(t){return en[(t&pe)>>>$]}var k=0,A=1,y=2,_=3,be=0,ye=[],We=!1;function Z(t){be++;try{return t()}finally{if(be--,be===0&&!We){We=!0;for(let e=0;e<ye.length;e++)ye[e]();ye.length=0,We=!1}}}function X(){return be>0}function Me(t){ye.push(t)}var _e=0,ve=[];function re(){_e++}function oe(){if(_e--,_e===0){for(let t=0;t<ve.length;t++)ve[t]();ve.length=0}}function Qe(t){_e>0?ve.push(t):t()}function ie(t){let e=t;typeof e.complete=="function"?e.complete():typeof e._handleEnd=="function"&&e._handleEnd(void 0)}var w=class t{static _names=new WeakMap;static _kinds=new WeakMap;static _keys=new WeakMap;static _stores=new Set;static _edges=new Map;static _nextId=0;static _usedKeys=new Set;static _explicitEnabled=null;static _cachedDefault=null;static _annotations=new WeakMap;static _traceLog=[];static _traceHead=0;static _traceFull=!1;static maxTraceEntries=1e3;static get enabled(){if(t._explicitEnabled!==null)return t._explicitEnabled;if(t._cachedDefault!==null)return t._cachedDefault;try{t._cachedDefault=globalThis.process?.env?.NODE_ENV!=="production"}catch{t._cachedDefault=!0}return t._cachedDefault}static set enabled(e){t._explicitEnabled=e}static _depSuffix(e){if(!e?.length)return;let r=e.map(o=>t._names.get(o)??"?").join(",");return r.length>40?`${r.slice(0,37)}...`:r}static _resolveKey(e){let n=t._keys.get(e)??t._names.get(e);if(n)return n;let r=`anonymous_${t._nextId++}`;return t._keys.set(e,r),r}static register(e,n){if(!t.enabled)return;n?.name&&t._names.set(e,n.name),n?.kind&&t._kinds.set(e,n.kind);let r=t._nextId++,o=n?.name;if(!(o&&!t._usedKeys.has(o)))if(o){let s=t._depSuffix(n?.deps);o=s?`${o}(${s})`:`${o}_${r}`,t._usedKeys.has(o)&&(o=`${o}_${r}`)}else{let s=n?.kind??"store",i=t._depSuffix(n?.deps);o=i?`${s}(${i})`:`${s}_${r}`,t._usedKeys.has(o)&&(o=`${o}_${r}`)}t._usedKeys.add(o),t._keys.set(e,o),t._stores.add(new WeakRef(e))}static registerEdge(e,n){if(!t.enabled)return;let r=t._resolveKey(e),o=t._resolveKey(n),s=t._edges.get(r);s?s.includes(o)||s.push(o):t._edges.set(r,[o])}static getEdges(){return new Map(t._edges)}static getName(e){if(t.enabled)return t._names.get(e)}static getKind(e){return t._kinds.get(e)}static inspect(e){return{name:t._names.get(e),kind:t._kinds.get(e)??"unknown",value:typeof e.get=="function"?e.get():void 0,status:e._status}}static graph(){let e=new Map,n=new Set;for(let r of t._stores){let o=r.deref();if(!o){t._stores.delete(r);continue}let s=t._resolveKey(o);n.add(s),e.set(s,t.inspect(o))}for(let[r,o]of t._edges){if(!n.has(r)){t._edges.delete(r),t._usedKeys.delete(r);continue}let s=o.filter(i=>n.has(i));s.length===0?t._edges.delete(r):s.length!==o.length&&t._edges.set(r,s)}return e}static trace(e,n){let r=null,o=e.get();return e.source(k,(s,i)=>{if(s===k&&(r=i),s===y){r=null;return}if(s===1){let a=i;if(!Object.is(a,o)){let c=o;o=a,n(a,c)}}}),()=>r?.(y)}static dumpGraph(){let e=t.graph(),n=t.getEdges(),r=new Map;for(let[i,a]of n)for(let c of a){let l=r.get(c);l?l.includes(i)||l.push(i):r.set(c,[i])}let o=[];for(let[i,a]of e){let c=r.get(i),l=n.get(i),u=c?.length?` \u2190 [${c.join(", ")}]`:"",f=l?.length?` \u2192 [${l.join(", ")}]`:"";o.push(` ${i} (${a.kind}) = ${JSON.stringify(a.value)} [${a.status??"?"}]${u}${f}`)}return[`Store Graph (${e.size} nodes):`,...o].join(`
1
+ "use strict";var Ht=Object.create;var Te=Object.defineProperty;var Yt=Object.getOwnPropertyDescriptor;var Qt=Object.getOwnPropertyNames;var Gt=Object.getPrototypeOf,Jt=Object.prototype.hasOwnProperty;var Zt=(t,e)=>{for(var n in e)Te(t,n,{get:e[n],enumerable:!0})},He=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Qt(e))!Jt.call(t,o)&&o!==n&&Te(t,o,{get:()=>e[o],enumerable:!(r=Yt(e,o))||r.enumerable});return t};var Ke=(t,e,n)=>(n=t!=null?Ht(Gt(t)):{},He(e||!t||!t.__esModule?Te(n,"default",{value:t,enumerable:!0}):n,t)),Xt=t=>He(Te({},"__esModule",{value:!0}),t);var dn={};Zt(dn,{CircuitOpenError:()=>Se,asyncQueue:()=>Xe,batchWriter:()=>st,cancellableAction:()=>at,cancellableStream:()=>ct,cascadingCache:()=>$e,checkpoint:()=>pt,circuitBreaker:()=>Tt,connectionHealth:()=>yt,constant:()=>et,countdown:()=>Pt,dag:()=>vt,decorrelatedJitter:()=>ot,dirtyTracker:()=>_t,exponential:()=>nt,fibonacci:()=>rt,fifo:()=>ut,fileAdapter:()=>ht,fromAbortable:()=>je,indexedDBAdapter:()=>St,keyedAsync:()=>xt,lfu:()=>lt,linear:()=>tt,lru:()=>Ie,memoryAdapter:()=>mt,random:()=>dt,reactiveScored:()=>At,retry:()=>Ct,scored:()=>ft,slidingWindow:()=>wt,sqliteAdapter:()=>gt,stateMachine:()=>Ot,stopwatch:()=>It,tieredStorage:()=>Mt,tokenBucket:()=>Et,tokenTracker:()=>Nt,track:()=>Vt,validationPipeline:()=>Ft,withBreaker:()=>Wt,withConnectionStatus:()=>zt,withMaxAttempts:()=>it,withMeta:()=>jt,withStatus:()=>Ut});module.exports=Xt(dn);var R=Symbol("DIRTY"),I=Symbol("RESOLVED"),J=Symbol("SINGLE_DEP"),z=Symbol("RESET"),xe=Symbol("PAUSE"),ke=Symbol("RESUME"),q=Symbol("TEARDOWN");function ne(t){return t===z||t===xe||t===ke||t===q}var Ee=0,we=1,De=2,Ae=3,Ce=4,Re=5,$=7,pe=7<<$,en=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function Oe(t){return en[(t&pe)>>>$]}var k=0,A=1,y=2,_=3,be=0,ye=[],Fe=!1;function Z(t){be++;try{return t()}finally{if(be--,be===0&&!Fe){Fe=!0;for(let e=0;e<ye.length;e++)ye[e]();ye.length=0,Fe=!1}}}function X(){return be>0}function Me(t){ye.push(t)}var _e=0,ve=[];function re(){_e++}function oe(){if(_e--,_e===0){for(let t=0;t<ve.length;t++)ve[t]();ve.length=0}}function Ye(t){_e>0?ve.push(t):t()}function ie(t){let e=t;typeof e.complete=="function"?e.complete():typeof e._handleEnd=="function"&&e._handleEnd(void 0)}var w=class t{static _names=new WeakMap;static _kinds=new WeakMap;static _keys=new WeakMap;static _stores=new Set;static _edges=new Map;static _nextId=0;static _usedKeys=new Set;static _explicitEnabled=null;static _cachedDefault=null;static _annotations=new WeakMap;static _traceLog=[];static _traceHead=0;static _traceFull=!1;static maxTraceEntries=1e3;static get enabled(){if(t._explicitEnabled!==null)return t._explicitEnabled;if(t._cachedDefault!==null)return t._cachedDefault;try{t._cachedDefault=globalThis.process?.env?.NODE_ENV!=="production"}catch{t._cachedDefault=!0}return t._cachedDefault}static set enabled(e){t._explicitEnabled=e}static _depSuffix(e){if(!e?.length)return;let r=e.map(o=>t._names.get(o)??"?").join(",");return r.length>40?`${r.slice(0,37)}...`:r}static _resolveKey(e){let n=t._keys.get(e)??t._names.get(e);if(n)return n;let r=`anonymous_${t._nextId++}`;return t._keys.set(e,r),r}static register(e,n){if(!t.enabled)return;n?.name&&t._names.set(e,n.name),n?.kind&&t._kinds.set(e,n.kind);let r=t._nextId++,o=n?.name;if(!(o&&!t._usedKeys.has(o)))if(o){let s=t._depSuffix(n?.deps);o=s?`${o}(${s})`:`${o}_${r}`,t._usedKeys.has(o)&&(o=`${o}_${r}`)}else{let s=n?.kind??"store",i=t._depSuffix(n?.deps);o=i?`${s}(${i})`:`${s}_${r}`,t._usedKeys.has(o)&&(o=`${o}_${r}`)}t._usedKeys.add(o),t._keys.set(e,o),t._stores.add(new WeakRef(e))}static registerEdge(e,n){if(!t.enabled)return;let r=t._resolveKey(e),o=t._resolveKey(n),s=t._edges.get(r);s?s.includes(o)||s.push(o):t._edges.set(r,[o])}static getEdges(){return new Map(t._edges)}static getName(e){if(t.enabled)return t._names.get(e)}static getKind(e){return t._kinds.get(e)}static inspect(e){return{name:t._names.get(e),kind:t._kinds.get(e)??"unknown",value:typeof e.get=="function"?e.get():void 0,status:e._status}}static graph(){let e=new Map,n=new Set;for(let r of t._stores){let o=r.deref();if(!o){t._stores.delete(r);continue}let s=t._resolveKey(o);n.add(s),e.set(s,t.inspect(o))}for(let[r,o]of t._edges){if(!n.has(r)){t._edges.delete(r),t._usedKeys.delete(r);continue}let s=o.filter(i=>n.has(i));s.length===0?t._edges.delete(r):s.length!==o.length&&t._edges.set(r,s)}return e}static trace(e,n){let r=null,o=e.get();return e.source(k,(s,i)=>{if(s===k&&(r=i),s===y){r=null;return}if(s===1){let a=i;if(!Object.is(a,o)){let c=o;o=a,n(a,c)}}}),()=>r?.(y)}static dumpGraph(){let e=t.graph(),n=t.getEdges(),r=new Map;for(let[i,a]of n)for(let c of a){let l=r.get(c);l?l.includes(i)||l.push(i):r.set(c,[i])}let o=[];for(let[i,a]of e){let c=r.get(i),l=n.get(i),u=c?.length?` \u2190 [${c.join(", ")}]`:"",f=l?.length?` \u2192 [${l.join(", ")}]`:"";o.push(` ${i} (${a.kind}) = ${JSON.stringify(a.value)} [${a.status??"?"}]${u}${f}`)}return[`Store Graph (${e.size} nodes):`,...o].join(`
2
2
  `)}static _signalLabel(e){return e===R?"DIRTY":e===I?"RESOLVED":typeof e=="symbol"?e.description??String(e):String(e)}static _observe(e,n,r){let o=null,s=!1,i=n??t.getName(e),a=[],c={values:[],signals:[],events:[],ended:!1,endError:void 0,get completedCleanly(){return c.ended&&!s},get errored(){return c.ended&&s},dirtyCount:0,resolvedCount:0,name:i,get eventLog(){return a},dispose:()=>o?.(y),reconnect:()=>(o?.(y),t._observe(e,n,r))};return e.source(k,(l,u)=>{if(l===k){o=u;return}let f=X();l===A?(c.values.push(u),c.events.push({type:"data",data:u,inBatch:f}),a.push(u),r&&r(`[${i}] DATA:`,u)):l===_?(c.signals.push(u),c.events.push({type:"signal",data:u,inBatch:f}),a.push(t._signalLabel(u)),u===R?c.dirtyCount++:u===I&&c.resolvedCount++,r&&r(`[${i}] STATE:`,u)):l===y&&(c.ended=!0,c.endError=u,s=u!==void 0,c.events.push({type:"end",data:u,inBatch:f}),a.push(s?["END",u]:"END"),r&&r(`[${i}] END`,u!==void 0?u:""),o=null)}),c}static observe(e){return t._observe(e)}static activate(e){let n=null;return e.source(k,(r,o)=>{r===k&&(n=o),r===y&&(n=null)}),()=>n?.(y)}static tap(e,n){let r=n??`tap(${t.getName(e)??"anon"})`,o={get:()=>e.get(),source:e.source};return t.register(o,{name:r,kind:"tap"}),t.registerEdge(e,o),o}static spy(e,n){let r=n?.name??t.getName(e)??"spy",o=n?.log??console.log;return t._observe(e,r,o)}static snapshot(){let e=t.graph(),n=t.getEdges(),r=new Map;for(let i of t._stores){let a=i.deref();if(!a)continue;let c=t._annotations.get(a);c!==void 0&&r.set(t._resolveKey(a),c)}let o=[];for(let[i,a]of e){let c={name:i,kind:a.kind,value:a.value,status:a.status},l=r.get(i);l!==void 0&&(c.annotation=l),o.push(c)}let s=[];for(let[i,a]of n)for(let c of a)s.push({from:i,to:c});return{nodes:o,edges:s,trace:t.traceLog()}}static toMermaid(e){let n=e?.direction??"TD",r=t.snapshot(),o=[`graph ${n}`],s={SETTLED:":::settled",DIRTY:":::dirty",ERRORED:":::errored",COMPLETED:":::completed"},i=new Map;function a(u){let f=u.replace(/[^a-zA-Z0-9_]/g,"_"),d=i.get(f);return d===void 0?(i.set(f,1),f):(i.set(f,d+1),`${f}__${d}`)}let c=new Map;function l(u){let f=JSON.stringify(u);return f&&f.length>30?`${f.slice(0,27)}...`:f??"undefined"}for(let u of r.nodes){let f=a(u.name);c.set(u.name,f);let d=`${u.name} (${u.kind}) = ${l(u.value)}`,p=s[u.status??""]??"";o.push(` ${f}["${d}"]${p}`)}for(let u of r.edges){let f=c.get(u.from)??a(u.from),d=c.get(u.to)??a(u.to);o.push(` ${f} --> ${d}`)}return o.push(""),o.push(" classDef settled fill:#d4edda,stroke:#28a745"),o.push(" classDef dirty fill:#fff3cd,stroke:#ffc107"),o.push(" classDef errored fill:#f8d7da,stroke:#dc3545"),o.push(" classDef completed fill:#cce5ff,stroke:#007bff"),o.join(`
3
3
  `)}static toD2(e){let n=e?.direction??"down",r=t.snapshot(),o=[`direction: ${n}`,""],s={state:"rectangle",derived:"hexagon",effect:"oval",producer:"rectangle",operator:"parallelogram","pipeline-step":"rectangle","pipeline-status":"diamond",checkpoint:"cylinder"},i=new Map;function a(u){let f=u.replace(/[^a-zA-Z0-9_]/g,"_"),d=i.get(f);return d===void 0?(i.set(f,1),f):(i.set(f,d+1),`${f}__${d}`)}let c=new Map;function l(u){let f=JSON.stringify(u);return f&&f.length>30?`${f.slice(0,27)}...`:f??"undefined"}for(let u of r.nodes){let f=a(u.name);c.set(u.name,f);let d=s[u.kind]??"rectangle",p=`${u.name} (${u.kind}) = ${l(u.value)}`,m=u.status?` [${u.status}]`:"";o.push(`${f}: "${p}${m}" { shape: ${d} }`)}r.edges.length>0&&o.push("");for(let u of r.edges){let f=c.get(u.from)??a(u.from),d=c.get(u.to)??a(u.to);o.push(`${f} -> ${d}`)}return o.join(`
4
- `)}static annotate(e,n){if(!t.enabled)return;t._annotations.set(e,n);let r={node:t._resolveKey(e),reason:n,timestamp:Date.now()},o=t.maxTraceEntries;o<=0||(t._traceLog.length<o?t._traceLog.push(r):(t._traceLog[t._traceHead]=r,t._traceFull=!0),t._traceHead=(t._traceHead+1)%o)}static getAnnotation(e){return t._annotations.get(e)}static traceLog(){return t._traceFull?[...t._traceLog.slice(t._traceHead),...t._traceLog.slice(0,t._traceHead)]:t._traceLog.slice(0,t._traceHead||t._traceLog.length)}static clearTrace(){t._traceLog=[],t._traceHead=0,t._traceFull=!1}static timeline(e){let n=null,r=[];return e.source(k,(o,s)=>{if(o===k){n=s;return}let i={timestamp:Date.now(),type:o===A?"data":o===_?"signal":"end",data:s,inBatch:X()};r.push(i),o===y&&(n=null)}),{entries:r,dispose:()=>n?.(y)}}static observeDerived(e){let n=[],r=e,o=r._fn;if(typeof o!="function"||!Array.isArray(r._deps))return{...t.observe(e),evaluations:n};r._fn=()=>{let c=r._deps.map(u=>u.get()),l=o();return n.push({result:l,depValues:c,timestamp:Date.now()}),l};let s=t._observe(e),i=s.dispose;return{...s,evaluations:n,dispose:()=>{r._fn=o,i()},reconnect:()=>(r._fn=o,i(),t.observeDerived(e))}}static observeTaskState(e){let n=e.status.get(),r=[],o=null;return e.status.source(k,(s,i)=>{if(s===k){o=i;return}if(s===A){let a=i;if(a!==n){let c={from:n,to:a,timestamp:Date.now()};a==="error"&&(c.error=e.error.get()),r.push(c),n=a}}s===y&&(o=null)}),{transitions:r,get currentStatus(){return e.status.get()},dispose:()=>{o?.(y)}}}static causalityTrace(e){let n=[],r=e,o=r._fn;if(typeof o!="function"||!Array.isArray(r._deps))return{...t.observe(e),causality:n};let s=r._deps,i=s.map(u=>u.get());r._fn=()=>{let u=s.map(p=>p.get()),f=o(),d=-1;for(let p=0;p<s.length;p++)if(!Object.is(u[p],i[p])){d=p;break}return n.push({result:f,triggerDepIndex:d,triggerDepName:d>=0?t.getName(s[d]):void 0,depValues:u,timestamp:Date.now()}),i=u,f};let a=t._observe(e),c=a.dispose;return{...a,causality:n,dispose:()=>{r._fn=o,c()},reconnect:()=>(r._fn=o,c(),t.causalityTrace(e))}}static _reset(){t._names=new WeakMap,t._kinds=new WeakMap,t._keys=new WeakMap,t._stores=new Set,t._edges=new Map,t._usedKeys=new Set,t._nextId=0,t._explicitEnabled=null,t._cachedDefault=null,t._annotations=new WeakMap,t._traceLog=[],t._traceHead=0,t._traceFull=!1,t.maxTraceEntries=1e3}};var Le=1,j=64,K=2,se=4,Ge=8,Je=16,H=32,U=1024,L=pe,ae=we<<$,me=De<<$,Pe=Ee<<$,tn=Ce<<$,nn=Re<<$,rn=Ae<<$,he=class{_value;_output=null;_flags;get _status(){return Oe(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;_onLifecycleSignal;constructor(e,n){this._value=n?.initial,this._fn=e,this._eqFn=n?.equals,this._getterFn=n?.getter,this._initial=n?.initial;let r=0;n?.autoDirty!==!1&&(r|=se),n?.resetOnTeardown&&(r|=Ge),n?.resubscribable&&(r|=Je),this._flags=r,this.source=this.source.bind(this),this.emit=this.emit.bind(this),n?._skipInspect||w.register(this,{kind:"producer",...n})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(e,n){let r=this._output;if(r)if(this._flags&j)for(let o of r)o(e,n);else r(e,n)}emit(e){this._flags&K||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(X()?this._flags&H||(this._flags|=H,this._flags&se&&(this._flags=this._flags&~L|ae,this._dispatch(_,R)),Me(()=>{this._flags&=~H,this._flags=this._flags&~L|me,this._dispatch(A,this._value)})):(this._flags&se&&!(this._flags&U)&&(this._flags=this._flags&~L|ae,this._dispatch(_,R)),this._flags=this._flags&~L|me,this._dispatch(A,this._value))))}signal(e){this._flags&K||!this._output||(e===R?this._flags=this._flags&~L|ae:e===I&&(this._flags=this._flags&~L|rn),this._dispatch(_,e))}complete(){if(this._flags&K)return;this._flags=(this._flags|K)&~L|tn;let e=this._output,n=this._flags&j;if(this._output=null,this._flags&=~(j|U),this._singleDepCount=0,this._stop(),e)if(n)for(let r of e)r(y);else e(y)}error(e){if(this._flags&K)return;this._flags=(this._flags|K)&~L|nn;let n=this._output,r=this._flags&j;if(this._output=null,this._flags&=~(j|U),this._singleDepCount=0,this._stop(),n)if(r)for(let o of n)o(y,e);else n(y,e)}_start(){if(this._flags&Le||!this._fn)return;this._flags|=Le,this._onLifecycleSignal=void 0;let e=this._fn({emit:this.emit,signal:n=>this.signal(n),complete:()=>this.complete(),error:n=>this.error(n),onSignal:n=>{this._onLifecycleSignal=n}});this._cleanup=typeof e=="function"?e:void 0}_stop(){this._flags&Le&&(this._flags&=~Le,this._onLifecycleSignal=void 0,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&Ge&&(this._value=this._initial),this._flags&K||(this._flags=this._flags&~L|Pe))}_handleLifecycleSignal(e){if(!(this._flags&K)){if(e===q){this._onLifecycleSignal?.(e),this.complete();return}e===z&&(this._value=this._initial,this._flags&=~H),this._onLifecycleSignal?.(e),e===z&&this.emit(this._initial)}}source(e,n){if(e===k){let r=n;if(this._flags&K)if(this._flags&Je&&this._output===null)this._flags=this._flags&~(K|L)|Pe;else{r(k,s=>{}),r(y);return}if(this._output===null)this._output=r;else if(this._flags&j)this._output.add(r);else{let s=new Set;s.add(this._output),s.add(r),this._output=s,this._flags=(this._flags|j)&~U}let o=!1;r(k,(s,i)=>{if(s===A&&r(A,this._value),s===_){i===J&&!o?(o=!0,this._singleDepCount++,this._flags&j||(this._flags|=U)):ne(i)&&this._handleLifecycleSignal(i);return}if(s===y){if(o&&(o=!1,this._singleDepCount--),this._output===null)return;if(this._flags&j){let a=this._output;a.delete(r),a.size===1?(this._output=a.values().next().value,this._flags&=~j,this._singleDepCount>0&&(this._flags|=U)):a.size===0&&(this._output=null,this._flags&=~(j|U),this._singleDepCount=0,this._flags=this._flags&~L|Pe,this._stop())}else this._output===r&&(this._output=null,this._flags&=~U,this._singleDepCount=0,this._flags=this._flags&~L|Pe,this._stop())}}),Qe(()=>this._start())}}};function O(t,e){return new he(t,e)}var ze=class extends he{constructor(e,n){super(void 0,{initial:e,autoDirty:!0,equals:n?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),w.register(this,{kind:"state",...n})}get(){return this._value}set(e){this._flags&K||this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(X()?this._flags&H||(this._flags|=H,this._flags&se&&(this._flags=this._flags&~L|ae,this._dispatch(_,R)),Me(()=>{this._flags&=~H,this._flags=this._flags&~L|me,this._dispatch(A,this._value)})):(this._flags&se&&!(this._flags&U)&&(this._flags=this._flags&~L|ae,this._dispatch(_,R)),this._flags=this._flags&~L|me,this._dispatch(A,this._value))))}update(e){this.set(e(this._value))}};function T(t,e){return new ze(t,e)}function Ze(t,e,n){let r=null;return t(0,(o,s)=>{if(o===0){r=s;return}if(o===2){r=null,n?.onEnd?.(s);return}o===1&&e(s)}),{unsubscribe(){r?.(2),r=null}}}function Y(t,e){return new Promise((n,r)=>{let o=Ze(t,s=>{(!e||e(s))&&(o.unsubscribe(),n(s))},{onEnd:s=>{r(s??new Error("source completed without matching value"))}})})}function Xe(t,e){try{let n=t.get();if(!e||e(n))return Promise.resolve(n)}catch{}return Y(t.source,e)}function et(t,e){let n=Math.max(1,e?.concurrency??1),r=e?.strategy??"fifo",o=e?.name??"asyncQueue",s=T(0,{name:`${o}.size`}),i=T(0,{name:`${o}.running`}),a=T(0,{name:`${o}.completed`}),c=T(0,{name:`${o}.failed`}),l=T(!1,{name:`${o}.paused`}),u=[],f=0,d=!1;function p(x,C){d||(f--,i.set(f),a.update(E=>E+1),x.done$.set({ok:!0,result:C}),h())}function m(x,C){d||(f--,i.set(f),c.update(E=>E+1),x.done$.set({ok:!1,error:C}),h())}function h(){if(!(d||l.get()))for(;f<n&&u.length>0;){let x=r==="lifo"?u.pop():u.shift();s.set(u.length),f++,i.set(f);try{t(x.task).then(C=>p(x,C),C=>m(x,C))}catch(C){m(x,C)}}}function g(x){if(d)return Promise.reject(new Error("Queue is disposed"));let C=T(null,{name:`${o}.task`});return u.push({task:x,done$:C}),s.set(u.length),h(),Xe(C,E=>E!==null).then(E=>{if(ie(C),E.ok)return E.result;throw E.error},E=>{throw ie(C),E})}function b(){l.set(!0)}function S(){l.set(!1),h()}function v(){let x=u.splice(0,u.length);s.set(0);for(let C of x)C.done$.set({ok:!1,error:new Error("Queue cleared")})}function D(){d||(d=!0,v())}return{enqueue:g,size:s,running:i,completed:a,failed:c,pause:b,resume:S,paused:l,clear:v,dispose:D}}function tt(t){return()=>t}function nt(t,e=t){return n=>t+e*n}function rt(t){let e=t?.base??100,n=t?.factor??2,r=t?.maxDelay??3e4,o=t?.jitter??"none";return s=>{let i=Math.min(e*n**s,r);return on(i,o)}}function ot(t=100,e=3e4){return n=>{let r=1,o=1;for(let s=0;s<n;s++){let i=r+o;r=o,o=i}return Math.min(r*t,e)}}function it(t=100,e=3e4){return(n,r,o)=>{let i=Math.min(e,(o??t)*3);return je(t,i)}}function st(t,e){return(n,r,o)=>n>=e?null:t(n,r,o)}function on(t,e){switch(e){case"none":return t;case"full":return je(0,t);case"equal":return t/2+je(0,t/2)}}function je(t,e){return t+Math.random()*(e-t)}function at(t){let{maxSize:e,onFlush:n}=t,r=t.maxWaitMs??null,o=t.name??"batchWriter",s=T(0,{name:`${o}.size`}),i=T(0,{name:`${o}.totalFlushed`}),a=T(!1,{name:`${o}.flushing`}),c=[],l=null,u=!1,f=!1,d=0;function p(){l!==null&&(clearTimeout(l),l=null)}function m(){if(c.length===0||f)return;f=!0;let S=c;c=[],p(),s.set(0);try{let v=n(S);v&&typeof v.then=="function"?(d++,a.set(!0),v.then(()=>{i.update(D=>D+S.length),d--,d===0&&a.set(!1)},()=>{i.update(D=>D+S.length),d--,d===0&&a.set(!1)})):i.update(D=>D+S.length)}catch{i.update(v=>v+S.length)}finally{f=!1}}function h(S){u||(c.push(S),s.set(c.length),r!==null&&c.length===1&&(l=setTimeout(()=>{l=null,m()},r)),c.length>=e&&m())}function g(){m()}function b(){u=!0,p(),m()}return{add:h,flush:g,size:s,totalFlushed:i,flushing:a,stop:b}}function ct(t,e){let n=e?.name??"cancellableAction",r=e?.keepPreviousData??!1,o=T(e?.initial,{name:`${n}.data`}),s=T(!1,{name:`${n}.loading`}),i=T(void 0,{name:`${n}.error`}),a=T(0,{name:`${n}.runCount`}),c=null,l=0;function u(){c&&(c.abort(),c=null,s.set(!1))}async function f(d){u();let p=++l;c=new AbortController;let m=c.signal;s.set(!0),i.set(void 0),r||o.set(void 0);try{if(e?.rateLimiter&&(await e.rateLimiter.acquire(),m.aborted||p!==l))return;let h=await t(d,m);return p!==l?void 0:(o.set(h),s.set(!1),a.update(g=>g+1),c=null,h)}catch(h){if(p!==l)return;if(m.aborted){s.set(!1);return}i.set(h),s.set(!1),c=null;return}}return{execute:f,cancel:u,data:o,loading:s,error:i,runCount:a}}function F(t,e,n){let r=null;re(),t.source(k,(s,i)=>{if(s===k&&(r=i),s===y){r=null,n?.onEnd?.(i);return}if(s===1){let a=i,c=o;o=a,e(a,c)}});let o;try{o=t.get()}catch{}return oe(),{unsubscribe(){r?.(y),r=null},signal(s){r?.(_,s)}}}function ut(t){let e=t?.name??"cancellableStream",n=O(void 0,{initial:t?.initial,name:e,resubscribable:!0}),r=O(void 0,{initial:!1,name:`${e}.active`,_skipInspect:!0}),o=null,s=!1;function i(){s=!0,o&&(o.unsubscribe(),o=null),r.emit(!1)}function a(c){i(),s=!1,r.emit(!0);let l=Ue(c,{name:e,initial:t?.initial});o=F(l,u=>n.emit(u),{onEnd:u=>{if(o=null,!s)if(r.emit(!1),u!==void 0){try{t?.onError?.(u)}catch{}n.error(u)}else t?.onComplete?.()}})}return w.register(n,{kind:"cancellableStream"}),{store:n,start:a,cancel:i,active:r}}function Ue(t,e){let n=O(({emit:r,complete:o,error:s})=>{let i=new AbortController,a=!1;return(async()=>{try{for await(let c of t(i.signal)){if(i.signal.aborted)return;r(c)}if(!i.signal.aborted){a=!0;try{e?.onComplete?.()}catch{}o()}}catch(c){if(!i.signal.aborted){a=!0;try{e?.onError?.(c)}catch{}s(c)}}})(),()=>{if(!a){i.abort();try{e?.onAbort?.()}catch{}}}},{initial:e?.initial,name:e?.name??"fromAbortable",resubscribable:!0});return w.register(n,{kind:"fromAbortable"}),n}function lt(){let t=[],e=new Set,n=0;return{touch(){},insert(r){e.has(r)||(t.push(r),e.add(r))},delete(r){e.delete(r)},evict(r=1){let o=[];for(;o.length<r&&n<t.length;){let s=t[n++];e.delete(s)&&o.push(s)}return n>1e3&&n>t.length/2&&(t.splice(0,n),n=0),o},size:()=>e.size,clear(){t.length=0,e.clear(),n=0}}}function Ie(){let t=new Map,e={key:null,prev:null,next:null},n={key:null,prev:null,next:null};e.next=n,n.prev=e;function r(i){i.prev.next=i.next,i.next.prev=i.prev}function o(i){i.next=e.next,i.prev=e,e.next.prev=i,e.next=i}function s(i){r(i),o(i)}return{touch(i){let a=t.get(i);a&&s(a)},insert(i){let a=t.get(i);if(a){s(a);return}a={key:i,prev:null,next:null},t.set(i,a),o(a)},delete(i){let a=t.get(i);a&&(r(a),t.delete(i))},evict(i=1){let a=[];for(;a.length<i&&n.prev!==e;){let c=n.prev;a.push(c.key),r(c),t.delete(c.key)}return a},size:()=>t.size,clear(){t.clear(),e.next=n,n.prev=e}}}function ft(){let t=new Map,e={},n={};e.next=n,n.prev=e;function r(i,a){a.prev=i,a.next=i.next,i.next.prev=a,i.next=a}function o(i){i.prev.next=i.next,i.next.prev=i.prev}function s(i,a){if(i.next!==n&&i.next.freq===a)return i.next;let c={freq:a,keys:new Set};return r(i,c),c}return{touch(i){let a=t.get(i);if(!a)return;let c=s(a,a.freq+1);a.keys.delete(i),c.keys.add(i),t.set(i,c),a.keys.size===0&&o(a)},insert(i){if(t.has(i)){this.touch(i);return}let a=s(e,1);a.keys.add(i),t.set(i,a)},delete(i){let a=t.get(i);a&&(a.keys.delete(i),t.delete(i),a.keys.size===0&&o(a))},evict(i=1){let a=[];for(;a.length<i&&e.next!==n;){let c=e.next,l=c.keys.values().next().value;a.push(l),c.keys.delete(l),t.delete(l),c.keys.size===0&&o(c)}return a},size:()=>t.size,clear(){t.clear(),e.next=n,n.prev=e}}}function dt(t){let e=new Set;function n(r){try{return t(r)}catch{return-1/0}}return{touch(){},insert(r){e.add(r)},delete(r){e.delete(r)},evict(r=1){if(e.size===0)return[];if(r===1){let i,a=1/0;for(let c of e){let l=n(c);l<a&&(a=l,i=c)}return i!==void 0?(e.delete(i),[i]):[]}let o=Array.from(e).map(i=>({key:i,score:n(i)}));o.sort((i,a)=>i.score-a.score);let s=o.slice(0,r).map(i=>i.key);for(let i of s)e.delete(i);return s},size:()=>e.size,clear(){e.clear()}}}function pt(){let t=[],e=new Map;return{touch(){},insert(n){e.has(n)||(e.set(n,t.length),t.push(n))},delete(n){let r=e.get(n);if(r===void 0)return;let o=t[t.length-1];t[r]=o,e.set(o,r),t.pop(),e.delete(n)},evict(n=1){let r=[];for(;r.length<n&&t.length>0;){let o=Math.floor(Math.random()*t.length),s=t[o];r.push(s);let i=t[t.length-1];t[o]=i,e.set(i,o),t.pop(),e.delete(s)}return r},size:()=>t.length,clear(){t.length=0,e.clear()}}}function ce(t){t instanceof Promise&&t.catch(()=>{})}function $e(t,e){let n=new Map,r=e?.maxSize??0,o=r>0?e?.eviction??Ie():null,s=e?.writeThrough??!1,i=new Map;function a(p){return i.get(p)??0}function c(p){let m=a(p)+1;return i.set(p,m),m}function l(p,m,h){for(let g=0;g<h;g++){let b=t[g];b.save&&ce(b.save(p,m))}}function u(){if(!(!o||r<=0))for(;o.size()>r;){let p=o.evict(1);if(p.length===0)break;for(let m of p){let h=n.get(m);if(h){let g=h.get();if(g!==void 0){let b=-1;for(let S=t.length-1;S>=0;S--)if(t[S].save){ce(t[S].save(m,g)),b=S;break}for(let S=0;S<b;S++)t[S].clear&&ce(t[S].clear(m))}ie(h)}n.delete(m),i.delete(m)}}}function f(p,m){let h=c(p);d(p,m,0,h)}function d(p,m,h,g){if(h>=t.length)return;let b;try{b=t[h].load(p)}catch{d(p,m,h+1,g);return}b instanceof Promise?b.then(S=>{a(p)===g&&(S!==void 0?(m.set(S),l(p,S,h)):d(p,m,h+1,g))},()=>{a(p)===g&&d(p,m,h+1,g)}):b!==void 0?(m.set(b),l(p,b,h)):d(p,m,h+1,g)}return{load(p){let m=n.get(p);if(m)return o?.touch(p),m;let h=T(void 0);return n.set(p,h),o&&(o.insert(p),u()),f(p,h),h},save(p,m){if(c(p),s)for(let g of t)g.save&&ce(g.save(p,m));else t[0]?.save&&ce(t[0].save(p,m));let h=n.get(p);if(h)h.set(m),o?.touch(p);else{let g=T(m);n.set(p,g),o&&(o.insert(p),u())}},invalidate(p){let m=n.get(p);m&&f(p,m)},delete(p){o?.delete(p);let m=n.get(p);m&&ie(m),n.delete(p),i.delete(p);for(let h of t)h.clear&&ce(h.clear(p))},has(p){return n.has(p)},get size(){return n.size}}}function qe(t){t instanceof Promise&&t.catch(()=>{})}function mt(t,e,n){return r=>{let o=n?.name??`checkpoint:${t}`,s=T({recovered:!1,persistCount:0,id:t},{name:`${o}:meta`,equals:()=>!1}),i=O(({emit:c,error:l,complete:u})=>{let f=0,d=!0,p=!1,m=[],h=null,g=F(r,v=>{if(!p){m.push(v);return}f++,s.set({recovered:s.get().recovered,persistCount:f,id:t}),qe(e.save(t,v)),c(v)},{onEnd:v=>{if(!p){h={err:v};return}v!==void 0?l(v):u()}});function b(v){if(d){p=!0,s.set({recovered:v,persistCount:f,id:t});for(let D of m){if(!d)break;f++,s.set({recovered:v,persistCount:f,id:t}),qe(e.save(t,D)),c(D)}m.length=0,h&&(h.err!==void 0?l(h.err):u())}}let S=e.load(t);return S instanceof Promise?S.then(v=>{d&&(v!==void 0?(c(v),b(!0)):b(!1))},()=>{d&&b(!1)}):S!==void 0?(c(S),b(!0)):b(!1),()=>{d=!1,m.length=0,g.unsubscribe()}},{name:o,kind:"checkpoint"});w.register(i,{kind:"checkpoint"});let a=i;return Object.defineProperties(a,{meta:{value:s,enumerable:!0},clear:{value(){qe(e.clear(t))},enumerable:!0}}),a}}function ht(){let t=new Map;return{save(e,n){t.set(e,n)},load(e){return t.has(e)?t.get(e):void 0},clear(e){t.delete(e)}}}function Ne(t){return(e,n)=>{if(e!==0)return;let r=!1;n(0,o=>{o===2&&(r=!0)}),t.onsuccess=()=>{r||(r=!0,n(1,t.result),n(2))},t.onerror=()=>{r||(r=!0,n(2,t.error))}}}function gt(t){let{dir:e}=t;function n(r){let o=r.replace(/[^a-zA-Z0-9_-]/g,"_");return`${e}/${o}.json`}return{async save(r,o){let s=await import("fs/promises");await s.mkdir(e,{recursive:!0}),await s.writeFile(n(r),JSON.stringify(o),"utf-8")},async load(r){let o=await import("fs/promises");try{let s=await o.readFile(n(r),"utf-8");return JSON.parse(s)}catch(s){if(s?.code==="ENOENT")return;throw s}},async clear(r){let o=await import("fs/promises");try{await o.unlink(n(r))}catch(s){if(s?.code==="ENOENT")return;throw s}}}}var sn=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function St(t){let{db:e}=t,n=t.table??"checkpoints";if(!sn.test(n))throw new Error(`sqliteAdapter: invalid table name "${n}". Must match /^[a-zA-Z_][a-zA-Z0-9_]*$/.`);e.exec(`CREATE TABLE IF NOT EXISTS ${n} (id TEXT PRIMARY KEY, value TEXT NOT NULL)`);let r=e.prepare(`INSERT OR REPLACE INTO ${n} (id, value) VALUES (?, ?)`),o=e.prepare(`SELECT value FROM ${n} WHERE id = ?`),s=e.prepare(`DELETE FROM ${n} WHERE id = ?`);return{save(i,a){r.run(i,JSON.stringify(a))},load(i){let a=o.get(i);return a?JSON.parse(a.value):void 0},clear(i){s.run(i)}}}function Tt(t){let e=t?.dbName??"callbag-checkpoints",n=t?.storeName??"checkpoints",r=null,o=null;function s(){if(r)return Promise.resolve(r);if(o)return o;let c=indexedDB.open(e,1);return c.onupgradeneeded=()=>{let l=c.result;l.objectStoreNames.contains(n)||l.createObjectStore(n)},o=Y(Ne(c)).then(l=>(r=l,r.onversionchange=()=>{r?.close(),r=null,o=null},r)),o.catch(()=>{o=null}),o}function i(c){return s().then(l=>{let u=l.transaction(n,c);return{store:u.objectStore(n),tx:u}})}async function a(c,l){try{let{store:u}=await i(c);return await Y(Ne(l(u)))}catch(u){if(u?.name==="InvalidStateError"||r===null){r=null,o=null;let{store:f}=await i(c);return Y(Ne(l(f)))}throw u}}return{async save(c,l){await a("readwrite",u=>u.put(l,c))},async load(c){return await a("readonly",u=>u.get(c))??void 0},async clear(c){await a("readwrite",l=>l.delete(c))}}}function bt(t){let e=t?.failureThreshold??5,n=t?.cooldownMs??3e4,r=t?.cooldown??null,o=t?.halfOpenMax??1,s=t?.now??Date.now,i="closed",a=0,c=0,l=0,u=n,f=0;function d(){if(!r)return n;let h=r(c);return h!==null?h:n}function p(){i="open",u=d(),l=s(),f=0}return{canExecute(){return i==="closed"?!0:i==="open"?s()-l>=u?(i="half-open",f=1,!0):!1:f<o?(f++,!0):!1},recordSuccess(){i==="half-open"?(i="closed",a=0,c=0):i==="closed"&&(a=0)},recordFailure(h){if(i==="half-open"){c++,p();return}i==="closed"&&(a++,a>=e&&p())},get state(){return i},get failureCount(){return a},reset(){i="closed",a=0,c=0,f=0}}}var ue=class{_v;_w;constructor(e){this._v=0,this._w=e>32?new Uint32Array((e-1>>>5)+1):null}set(e){let n=this._w;if(n===null)this._v|=1<<e;else{let r=e>>>5,o=1<<(e&31);n[r]&o||(n[r]|=o,this._v++)}}clear(e){let n=this._w;if(n===null)this._v&=~(1<<e);else{let r=e>>>5,o=1<<(e&31);n[r]&o&&(n[r]&=~o,this._v--)}}test(e){let n=this._w;return n===null?(this._v&1<<e)!==0:(n[e>>>5]&1<<(e&31))!==0}empty(){return this._v===0}reset(){this._v=0,this._w?.fill(0)}};var ee=1,le=2,fe=4,W=8,Q=32,yt=64,an=Ee<<$,de=we<<$,He=De<<$,ge=Ae<<$,cn=Ce<<$,Be=Re<<$,M=pe,Ve=class{_output=null;_upstreamTalkbacks=[];_cachedValue;_flags;_dirtyDeps;_eqFn;_deps;_fn;get _status(){return Oe(this._flags)}constructor(e,n,r,o){this._deps=e,this._fn=n,this._eqFn=r?.equals,this._flags=o?yt:0,this._dirtyDeps=new ue(e.length),this.source=this.source.bind(this),w.register(this,{kind:"derived",...r,deps:e});for(let s of e)w.registerEdge(s,this)}_dispatch(e,n){let r=this._output;if(r)if(this._flags&Q)for(let o of r)o(e,n);else r(e,n)}_recompute(){let e;try{e=this._fn()}catch(n){this._handleEnd(n);return}if(this._eqFn&&this._flags&ee&&this._eqFn(this._cachedValue,e)){this._flags=this._flags&~M|ge,this._dispatch(_,I);return}this._cachedValue=e,this._flags=(this._flags|ee)&~M|He,this._dispatch(A,this._cachedValue)}_recomputeIdentity(e){if(!(this._flags&W)){if(this._eqFn&&this._flags&ee&&this._eqFn(this._cachedValue,e)){this._flags=this._flags&~M|ge,this._dispatch(_,I);return}this._cachedValue=e,this._flags=(this._flags|ee)&~M|He,this._dispatch(A,e)}}_lazyConnect(){if(!(this._flags&(le|W))){try{this._cachedValue=this._fn()}catch(e){this._handleEnd(e);return}this._flags=(this._flags|ee)&~M|He,re(),this._connectUpstream(),this._flags&W||(this._flags|=le),oe()}}_connectUpstream(){this._upstreamTalkbacks.length=0,this._deps.length===1?this._flags&yt?this._connectSingleDepIdentity():this._connectSingleDep():this._connectMultiDep()}_connectSingleDep(){let e=!1;this._deps[0].source(k,(n,r)=>{if(n===k){this._upstreamTalkbacks.push(r),r(_,J);return}if(!(this._flags&W))if(n===_)if(r===R){if(e)return;e=!0,this._flags=this._flags&~M|de,this._dispatch(_,R)}else r===I?e&&(e=!1,this._flags=this._flags&~M|ge,this._dispatch(_,I)):this._dispatch(_,r);else n===A?e?(e=!1,this._recompute()):(this._flags=this._flags&~M|de,this._dispatch(_,R),this._recompute()):n===y&&this._handleEnd(r)})}_connectSingleDepIdentity(){let e=!1;this._deps[0].source(k,(n,r)=>{if(n===k){this._upstreamTalkbacks.push(r),r(_,J);return}this._flags&W||(n===_?r===R?(e=!0,this._flags=this._flags&~M|de,this._dispatch(_,R)):r===I?e&&(e=!1,this._flags=this._flags&~M|ge,this._dispatch(_,I)):this._dispatch(_,r):n===A?e?(e=!1,this._recomputeIdentity(r)):(this._flags=this._flags&~M|de,this._dispatch(_,R),this._recomputeIdentity(r)):n===y&&this._handleEnd(r))})}_connectMultiDep(){for(let e=0;e<this._deps.length&&!(this._flags&W);e++){let n=e;this._deps[n].source(k,(r,o)=>{if(r===k){this._upstreamTalkbacks.push(o);return}if(!(this._flags&W))if(r===_)if(o===R){let s=this._dirtyDeps.empty();this._dirtyDeps.set(n),s&&(this._flags&=~fe,this._flags=this._flags&~M|de,this._dispatch(_,R))}else o===I?this._dirtyDeps.test(n)&&(this._dirtyDeps.clear(n),this._dirtyDeps.empty()&&(this._flags&fe?this._recompute():(this._flags=this._flags&~M|ge,this._dispatch(_,I)))):this._dispatch(_,o);else r===A?this._dirtyDeps.test(n)?(this._dirtyDeps.clear(n),this._flags|=fe,this._dirtyDeps.empty()&&this._recompute()):this._dirtyDeps.empty()?(this._flags=this._flags&~M|de,this._dispatch(_,R),this._recompute()):this._flags|=fe:r===y&&this._handleEnd(o)})}}_handleEnd(e){this._flags|=W,this._flags=this._flags&~M|(e!==void 0?Be:cn),e!==void 0&&(this._cachedValue=e);for(let o of this._upstreamTalkbacks)o(y);this._upstreamTalkbacks=[],this._flags&=~le,this._dirtyDeps.reset();let n=this._output,r=this._flags&Q;if(this._output=null,this._flags&=~Q,n)if(r)for(let o of n)try{e!==void 0?o(y,e):o(y)}catch{}else e!==void 0?n(y,e):n(y)}_disconnectUpstream(){for(let e of this._upstreamTalkbacks)e(y);this._upstreamTalkbacks.length=0,this._flags&=~(le|fe),this._flags=this._flags&~M|an,this._dirtyDeps.reset()}_handleLifecycleSignal(e){if(!(this._flags&W)){if(e===q){for(let n of this._upstreamTalkbacks)n(_,q);this._handleEnd(void 0);return}e===z&&(this._flags&=~(ee|fe),this._dirtyDeps.reset());for(let n of this._upstreamTalkbacks)n(_,e)}}get(){if(this._flags&le)return this._cachedValue;if(this._flags&W){if((this._flags&M)===Be)throw this._cachedValue;return this._cachedValue}let e=this._fn();return this._cachedValue=e,this._flags|=ee,e}source(e,n){if(e===k){let r=n;if(this._flags&W){let o=(this._flags&M)===Be;r(k,s=>{}),o?r(y,this._cachedValue):r(y);return}if(!(this._flags&le)&&(this._lazyConnect(),this._flags&W)){let o=(this._flags&M)===Be;r(k,s=>{}),o?r(y,this._cachedValue):r(y);return}if(this._output===null)this._output=r;else if(this._flags&Q)this._output.add(r);else{let o=new Set;o.add(this._output),o.add(r),this._output=o,this._flags|=Q}r(k,(o,s)=>{if(o===A&&r(A,this._cachedValue),o===_&&ne(s)){this._handleLifecycleSignal(s);return}if(o===y){if(this._output===null)return;if(this._flags&Q){let i=this._output;i.delete(r),i.size===1?(this._output=i.values().next().value,this._flags&=~Q):i.size===0&&(this._output=null,this._flags&=~Q,this._disconnectUpstream())}else this._output===r&&(this._output=null,this._disconnectUpstream())}})}}};function P(t,e,n){return new Ve(t,e,n)}(e=>{function t(n,r){return new Ve([n],()=>n.get(),r,!0)}e.from=t})(P||={});function vt(t){let e=t?.heartbeatMs??3e4,n=t?.timeoutMs??5e3,r=t?.backoff??null,o=t?.maxReconnects??Number.POSITIVE_INFINITY,s=t?.name??"connectionHealth",i=T("disconnected",{name:`${s}.status`}),a=T(0,{name:`${s}.reconnectCount`}),c=P([i],()=>i.get()==="connected",{name:`${s}.healthy`}),l=null,u=null,f=null,d=null,p=!1,m=!1,h=null,g;function b(){l!==null&&(clearTimeout(l),l=null),u!==null&&(clearTimeout(u),u=null),f!==null&&(clearTimeout(f),f=null),d&&(d.abort(),d=null),p=!1}function S(){m||!h||(l=setTimeout(()=>{l=null,!(m||!h)&&D()},e))}function v(){l!==null&&clearTimeout(l),S()}async function D(){if(!h||m||p)return;p=!0;let V=new AbortController;u=setTimeout(()=>{u=null,V.abort()},n);try{await h.heartbeat(V.signal),u!==null&&(clearTimeout(u),u=null),p=!1,S()}catch{if(u!==null&&(clearTimeout(u),u=null),p=!1,m)return;i.set("disconnected"),h.disconnect(),x()}}function x(){if(m||!h)return;let V=a.get();if(V>=o){i.set("failed");return}let B;if(r){let G=r(V,void 0,g);B=G!==null?G:1e3,g=B}else B=1e3;f=setTimeout(()=>{f=null,!m&&(a.update(G=>G+1),C())},B)}async function C(){if(!(m||!h)){i.set("connecting"),d=new AbortController;try{if(await h.connect(d.signal),m)return;d=null,i.set("connected"),a.set(0),g=void 0,v()}catch{if(m)return;d=null,i.set("disconnected"),x()}}}function E(V){h&&(b(),h.disconnect()),m=!1,h=V,a.set(0),g=void 0,C()}function N(){m=!0,b(),h&&h.disconnect(),h=null,i.set("disconnected")}return{status:i,healthy:c,reconnectCount:a,start:E,stop:N}}function _t(t){let e=new Map;for(let i=0;i<t.length;i++){if(e.has(t[i].store))throw new Error(`Duplicate store in DAG: ${t[i].name??`node[${i}]`}`);e.set(t[i].store,i)}let n=new Array(t.length).fill(0),r=t.map(()=>[]);for(let i=0;i<t.length;i++){let a=t[i].deps;if(a)for(let c of a){let l=e.get(c);if(l===void 0)throw new Error(`Dependency not found in DAG for ${t[i].name??`node[${i}]`}. All deps must be declared as DAG nodes.`);r[l].push(i),n[i]++}}let o=[];for(let i=0;i<t.length;i++)n[i]===0&&o.push(i);let s=[];for(;o.length>0;){let i=o.shift();s.push(i);for(let a of r[i])n[a]--,n[a]===0&&o.push(a)}if(s.length!==t.length){let i=t.filter((a,c)=>!s.includes(c)).map((a,c)=>a.name??`node[${c}]`);throw new Error(`Cycle detected in DAG involving: ${i.join(", ")}`)}for(let i of t)if(i.name&&w.register(i.store,{name:i.name,kind:"dag-node"}),i.deps)for(let a of i.deps)w.registerEdge(a,i.store);return{order:s.map(i=>t[i].store),size:t.length}}function xt(t,e,n){let r=n?.equals??Object.is,o=n?.name??"dirtyTracker",s=T(e,{name:`${o}.baseline`}),i=P([t,s],()=>!r(t.get(),s.get()),{name:`${o}.dirty`}),a=!1;function c(...u){a||s.set(u.length>0?u[0]:t.get())}function l(){a||(a=!0)}return{dirty:i,baseline:s,resetBaseline:c,dispose:l}}function kt(t){let e=new Map;return n=>{let r=e.get(n);if(r)return r;let o=t(n).finally(()=>e.delete(n));return e.set(n,o),o}}function Et(t,e){return(n,r)=>{if(n!==0)return;let o=!1;function s(){o||(o=!0,clearTimeout(a),e?.removeEventListener("abort",i),r(1,void 0),r(2))}function i(){s()}if(r(0,c=>{c===2&&!o&&(o=!0,clearTimeout(a),e?.removeEventListener("abort",i))}),e?.aborted){s();return}let a=setTimeout(s,t);e?.addEventListener("abort",i,{once:!0})}}function wt(t){let e=t.rate,n=t.burst??e,r=t.now??Date.now,o=n,s=r();function i(){let a=r(),c=(a-s)/1e3;o=Math.min(n,o+c*e),s=a}return{tryAcquire(a=1){return i(),o>=a?(o-=a,!0):!1},async acquire(a=1,c){if(a>n)throw new RangeError(`Cannot acquire ${a} tokens (burst capacity is ${n})`);if(c?.throwIfAborted(),i(),o>=a)return o-=a,0;let l=0;for(;o<a;){let f=(a-o)/e*1e3;l+=f,await At(f,c),i()}return o-=a,l},available(){return i(),Math.floor(o)},reset(){o=n,s=r()}}}function Dt(t){let e=t.max,n=t.windowMs,r=t.now??Date.now,o=[];function s(){let i=r()-n;for(;o.length>0&&o[0]<=i;)o.shift()}return{tryAcquire(i=1){if(s(),o.length+i<=e){let a=r();for(let c=0;c<i;c++)o.push(a);return!0}return!1},async acquire(i=1,a){if(i>e)throw new RangeError(`Cannot acquire ${i} slots (max capacity is ${e})`);if(a?.throwIfAborted(),s(),o.length+i<=e){let u=r();for(let f=0;f<i;f++)o.push(u);return 0}let c=0;for(;o.length+i>e;){let u=o.length+i-e,f=o[u-1],d=f!==void 0?f+n-r():n;d>0&&(c+=d,await At(d,a)),s()}let l=r();for(let u=0;u<i;u++)o.push(l);return c},available(){return s(),e-o.length},reset(){o.length=0}}}function At(t,e){return e?.aborted?Promise.reject(e.reason):Y(Et(Math.ceil(t),e)).then(()=>{if(e?.aborted)throw e.reason})}function Ke(t,e,n){let r,o=[],s=!1,i=new ue(t.length),a=!1;function c(){s||(r&&r(),r=e())}let l=0;function u(d){if(!s){if(d===q){for(let p of o)p(_,q);o.length=0,s=!0,r&&r(),r=void 0;return}d===z&&(l++,i.reset(),a=!1,c());for(let p of o)p(_,d)}}re(),c();for(let d=0;d<t.length&&!s;d++){let p=d,m=l;t[p].source(k,(h,g)=>{if(h===k){o.push(g),t.length===1&&g(_,J);return}if(!s){if(h===_){if(ne(g)){u(g),m=l;return}if(m!==l)return;g===R?(i.empty()&&(a=!1),i.set(p)):g===I&&i.test(p)&&(i.clear(p),i.empty()&&a&&c())}if(h===A){if(m!==l)return;i.test(p)?(i.clear(p),a=!0,i.empty()&&c()):i.empty()?c():a=!0}if(h===y){s=!0,r&&r(),r=void 0;for(let b of o)b(y);o.length=0}}})}oe();let f=()=>{if(!s){s=!0,r&&r(),r=void 0;for(let d of o)d(y);o.length=0}};f.signal=d=>u(d),w.register(f,{kind:"effect",...n,deps:t});for(let d of t)w.registerEdge(d,f);return f}function Ct(t,e=n=>n){let n=[],r=new Map,o=new Map;function s(l,u){let f=n[l],d=n[u];n[l]=d,n[u]=f,f.index=u,d.index=l}function i(l){for(;l>0;){let u=l-1>>>1;if(n[u].score<=n[l].score)break;s(l,u),l=u}}function a(l){let u=n.length;for(;;){let f=l,d=2*l+1,p=d+1;if(d<u&&n[d].score<n[f].score&&(f=d),p<u&&n[p].score<n[f].score&&(f=p),f===l)break;s(l,f),l=f}}function c(l){let u=n.length-1;if(l===u){n.pop();return}s(l,u),n.pop(),i(l),a(l)}return{touch(){},insert(l){if(r.has(l))return;let u=t(l),f={key:l,score:e(u.get()),index:n.length};n.push(f),r.set(l,f),i(f.index);let d=Ke([u],()=>{let p=r.get(l);if(!p)return;let m=p.score;p.score=e(u.get()),p.score<m?i(p.index):p.score>m&&a(p.index)});o.set(l,d)},delete(l){let u=r.get(l);if(!u)return;let f=o.get(l);f&&(f(),o.delete(l)),c(u.index),r.delete(l)},evict(l=1){let u=[];for(;u.length<l&&n.length>0;){let{key:f}=n[0];u.push(f);let d=o.get(f);d&&(d(),o.delete(f)),c(0),r.delete(f)}return u},size:()=>r.size,clear(){for(let l of o.values())l();o.clear(),r.clear(),n.length=0}}}function Rt(t){let e=typeof t=="number"?{count:t}:t,n=e.count??(e.delay?1/0:0),r=e.delay??null,o=e.while??null;return s=>{let i=T({attempt:0,pending:!1},{name:"retry:meta",equals:()=>!1});function a(l){i.set({attempt:l.attempt,lastError:l.lastError,pending:l.pending??!1})}let c=O(({emit:l,complete:u,error:f})=>{let d=0,p,m=null,h=!1,g=null,b=!1;function S(){if(b)return;m&&(m(y),m=null);let v=s.get();h&&v!==void 0&&l(v),h=!0,!b&&s.source(k,(D,x)=>{if(!b&&(D===k&&(m=x),D===1&&l(x),D===y))if(m=null,x!==void 0)if(d<n&&(o===null||o(x)))if(!r)d++,a({attempt:d,lastError:x}),S();else{let E=r(d,x,p);E!==null&&(p=E),E===null?(a({attempt:d,lastError:x}),f(x)):E<=0?(d++,a({attempt:d,lastError:x}),S()):(d++,a({attempt:d,lastError:x,pending:!0}),g=setTimeout(()=>{g=null,a({attempt:d,lastError:x,pending:!1}),S()},E))}else a({attempt:d,lastError:x}),f(x);else u()})}return S(),()=>{b=!0,g!==null&&(clearTimeout(g),g=null),m&&m(y)}},{initial:s.get()});return w.register(c,{kind:"retry"}),c.retryMeta=i,c}}function Ot(t){return typeof t=="string"?[{to:t}]:Array.isArray(t)?t:[t]}function un(t,e,n,r){let o=r,s=t.states[e];if(s?.onExit){let a=s.onExit(o);a!==void 0&&(o=a)}let i=t.states[n];if(i?.onEnter){let a=i.onEnter(o);a!==void 0&&(o=a)}return o}function ln(t){let e=[];for(let[n,r]of Object.entries(t.states))if(r.on){for(let[o,s]of Object.entries(r.on))if(s!==void 0)for(let i of Ot(s))e.push({from:n,event:o,to:i.to,guarded:!!i.guard})}return e}function te(t){return t.replace(/[^a-zA-Z0-9_]/g,"_")}function Mt(t,e){let n=T(e.initial),r=t,o=e.states[e.initial];if(o?.onEnter){let d=o.onEnter(r);d!==void 0&&(r=d)}let s=T(r),i=Object.freeze(ln(e));function a(d,p){let m=n.get(),h=e.states[m];if(!h?.on)return!1;let g=h.on[d];if(g===void 0)return!1;let b=Ot(g),S=s.get();for(let v of b){if(v.guard&&!v.guard(S,p))continue;let D=S;if(v.action){let x=v.action(S,p);x!==void 0&&(D=x)}return D=un(e,m,v.to,D),n.set(v.to),s.set(D),!0}return!1}function c(d){return n.get()===d}function l(){let d=n.get(),p=s.get(),m=e.states[d];m?.onExit&&m.onExit(p),n.set(e.initial);let h=e.states[e.initial];if(h?.onEnter){let g=h.onEnter(t);s.set(g!==void 0?g:t)}else s.set(t)}function u(d){let m=["stateDiagram-v2",` direction ${d?.direction??"LR"}`],h=Object.keys(e.states);for(let g of h){let b=te(g);m.push(` ${b} : ${g}`)}m.push(` [*] --> ${te(e.initial)}`);for(let g of i){let b=te(g.from),S=te(g.to),v=g.guarded?`${g.event} [guarded]`:g.event;m.push(` ${b} --> ${S} : ${v}`)}return m.join(`
4
+ `)}static annotate(e,n){if(!t.enabled)return;t._annotations.set(e,n);let r={node:t._resolveKey(e),reason:n,timestamp:Date.now()},o=t.maxTraceEntries;o<=0||(t._traceLog.length<o?t._traceLog.push(r):(t._traceLog[t._traceHead]=r,t._traceFull=!0),t._traceHead=(t._traceHead+1)%o)}static getAnnotation(e){return t._annotations.get(e)}static traceLog(){return t._traceFull?[...t._traceLog.slice(t._traceHead),...t._traceLog.slice(0,t._traceHead)]:t._traceLog.slice(0,t._traceHead||t._traceLog.length)}static clearTrace(){t._traceLog=[],t._traceHead=0,t._traceFull=!1}static timeline(e){let n=null,r=[];return e.source(k,(o,s)=>{if(o===k){n=s;return}let i={timestamp:Date.now(),type:o===A?"data":o===_?"signal":"end",data:s,inBatch:X()};r.push(i),o===y&&(n=null)}),{entries:r,dispose:()=>n?.(y)}}static observeDerived(e){let n=[],r=e,o=r._fn;if(typeof o!="function"||!Array.isArray(r._deps))return{...t.observe(e),evaluations:n};r._fn=()=>{let c=r._deps.map(u=>u.get()),l=o();return n.push({result:l,depValues:c,timestamp:Date.now()}),l};let s=t._observe(e),i=s.dispose;return{...s,evaluations:n,dispose:()=>{r._fn=o,i()},reconnect:()=>(r._fn=o,i(),t.observeDerived(e))}}static observeTaskState(e){let n=e.status.get(),r=[],o=null;return e.status.source(k,(s,i)=>{if(s===k){o=i;return}if(s===A){let a=i;if(a!==n){let c={from:n,to:a,timestamp:Date.now()};a==="error"&&(c.error=e.error.get()),r.push(c),n=a}}s===y&&(o=null)}),{transitions:r,get currentStatus(){return e.status.get()},dispose:()=>{o?.(y)}}}static causalityTrace(e){let n=[],r=e,o=r._fn;if(typeof o!="function"||!Array.isArray(r._deps))return{...t.observe(e),causality:n};let s=r._deps,i=s.map(u=>u.get());r._fn=()=>{let u=s.map(p=>p.get()),f=o(),d=-1;for(let p=0;p<s.length;p++)if(!Object.is(u[p],i[p])){d=p;break}return n.push({result:f,triggerDepIndex:d,triggerDepName:d>=0?t.getName(s[d]):void 0,depValues:u,timestamp:Date.now()}),i=u,f};let a=t._observe(e),c=a.dispose;return{...a,causality:n,dispose:()=>{r._fn=o,c()},reconnect:()=>(r._fn=o,c(),t.causalityTrace(e))}}static _reset(){t._names=new WeakMap,t._kinds=new WeakMap,t._keys=new WeakMap,t._stores=new Set,t._edges=new Map,t._usedKeys=new Set,t._nextId=0,t._explicitEnabled=null,t._cachedDefault=null,t._annotations=new WeakMap,t._traceLog=[],t._traceHead=0,t._traceFull=!1,t.maxTraceEntries=1e3}};var Le=1,j=64,F=2,se=4,Qe=8,Ge=16,H=32,U=1024,L=pe,ae=we<<$,me=De<<$,Pe=Ee<<$,tn=Ce<<$,nn=Re<<$,rn=Ae<<$,he=class{_value;_output=null;_flags;get _status(){return Oe(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;_onLifecycleSignal;constructor(e,n){this._value=n?.initial,this._fn=e,this._eqFn=n?.equals,this._getterFn=n?.getter,this._initial=n?.initial;let r=0;n?.autoDirty!==!1&&(r|=se),n?.resetOnTeardown&&(r|=Qe),n?.resubscribable&&(r|=Ge),this._flags=r,this.source=this.source.bind(this),this.emit=this.emit.bind(this),n?._skipInspect||w.register(this,{kind:"producer",...n})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(e,n){let r=this._output;if(r)if(this._flags&j)for(let o of r)o(e,n);else r(e,n)}emit(e){this._flags&F||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(X()?this._flags&H||(this._flags|=H,this._flags&se&&(this._flags=this._flags&~L|ae,this._dispatch(_,R)),Me(()=>{this._flags&=~H,this._flags=this._flags&~L|me,this._dispatch(A,this._value)})):(this._flags&se&&!(this._flags&U)&&(this._flags=this._flags&~L|ae,this._dispatch(_,R)),this._flags=this._flags&~L|me,this._dispatch(A,this._value))))}signal(e){this._flags&F||!this._output||(e===R?this._flags=this._flags&~L|ae:e===I&&(this._flags=this._flags&~L|rn),this._dispatch(_,e))}complete(){if(this._flags&F)return;this._flags=(this._flags|F)&~L|tn;let e=this._output,n=this._flags&j;if(this._output=null,this._flags&=~(j|U),this._singleDepCount=0,this._stop(),e)if(n)for(let r of e)r(y);else e(y)}error(e){if(this._flags&F)return;this._flags=(this._flags|F)&~L|nn;let n=this._output,r=this._flags&j;if(this._output=null,this._flags&=~(j|U),this._singleDepCount=0,this._stop(),n)if(r)for(let o of n)o(y,e);else n(y,e)}_start(){if(this._flags&Le||!this._fn)return;this._flags|=Le,this._onLifecycleSignal=void 0;let e=this._fn({emit:this.emit,signal:n=>this.signal(n),complete:()=>this.complete(),error:n=>this.error(n),onSignal:n=>{this._onLifecycleSignal=n}});this._cleanup=typeof e=="function"?e:void 0}_stop(){this._flags&Le&&(this._flags&=~Le,this._onLifecycleSignal=void 0,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&Qe&&(this._value=this._initial),this._flags&F||(this._flags=this._flags&~L|Pe))}_handleLifecycleSignal(e){if(!(this._flags&F)){if(e===q){this._onLifecycleSignal?.(e),this.complete();return}e===z&&(this._value=this._initial,this._flags&=~H),this._onLifecycleSignal?.(e),e===z&&this.emit(this._initial)}}source(e,n){if(e===k){let r=n;if(this._flags&F)if(this._flags&Ge&&this._output===null)this._flags=this._flags&~(F|L)|Pe;else{r(k,s=>{}),r(y);return}if(this._output===null)this._output=r;else if(this._flags&j)this._output.add(r);else{let s=new Set;s.add(this._output),s.add(r),this._output=s,this._flags=(this._flags|j)&~U}let o=!1;r(k,(s,i)=>{if(s===A&&r(A,this._value),s===_){i===J&&!o?(o=!0,this._singleDepCount++,this._flags&j||(this._flags|=U)):ne(i)&&this._handleLifecycleSignal(i);return}if(s===y){if(o&&(o=!1,this._singleDepCount--),this._output===null)return;if(this._flags&j){let a=this._output;a.delete(r),a.size===1?(this._output=a.values().next().value,this._flags&=~j,this._singleDepCount>0&&(this._flags|=U)):a.size===0&&(this._output=null,this._flags&=~(j|U),this._singleDepCount=0,this._flags=this._flags&~L|Pe,this._stop())}else this._output===r&&(this._output=null,this._flags&=~U,this._singleDepCount=0,this._flags=this._flags&~L|Pe,this._stop())}}),Ye(()=>this._start())}}};function O(t,e){return new he(t,e)}var We=class extends he{constructor(e,n){super(void 0,{initial:e,autoDirty:!0,equals:n?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),w.register(this,{kind:"state",...n})}get(){return this._value}set(e){this._flags&F||this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(X()?this._flags&H||(this._flags|=H,this._flags&se&&(this._flags=this._flags&~L|ae,this._dispatch(_,R)),Me(()=>{this._flags&=~H,this._flags=this._flags&~L|me,this._dispatch(A,this._value)})):(this._flags&se&&!(this._flags&U)&&(this._flags=this._flags&~L|ae,this._dispatch(_,R)),this._flags=this._flags&~L|me,this._dispatch(A,this._value))))}update(e){this.set(e(this._value))}};function T(t,e){return new We(t,e)}function Je(t,e,n){let r=null;return t(0,(o,s)=>{if(o===0){r=s;return}if(o===2){r=null,n?.onEnd?.(s);return}o===1&&e(s)}),{unsubscribe(){r?.(2),r=null}}}function Y(t,e){return new Promise((n,r)=>{let o=Je(t,s=>{(!e||e(s))&&(o.unsubscribe(),n(s))},{onEnd:s=>{r(s??new Error("source completed without matching value"))}})})}function Ze(t,e){try{let n=t.get();if(!e||e(n))return Promise.resolve(n)}catch{}return Y(t.source,e)}function Xe(t,e){let n=Math.max(1,e?.concurrency??1),r=e?.strategy??"fifo",o=e?.name??"asyncQueue",s=T(0,{name:`${o}.size`}),i=T(0,{name:`${o}.running`}),a=T(0,{name:`${o}.completed`}),c=T(0,{name:`${o}.failed`}),l=T(!1,{name:`${o}.paused`}),u=[],f=0,d=!1;function p(x,C){d||(f--,i.set(f),a.update(E=>E+1),x.done$.set({ok:!0,result:C}),h())}function m(x,C){d||(f--,i.set(f),c.update(E=>E+1),x.done$.set({ok:!1,error:C}),h())}function h(){if(!(d||l.get()))for(;f<n&&u.length>0;){let x=r==="lifo"?u.pop():u.shift();s.set(u.length),f++,i.set(f);try{t(x.task).then(C=>p(x,C),C=>m(x,C))}catch(C){m(x,C)}}}function g(x){if(d)return Promise.reject(new Error("Queue is disposed"));let C=T(null,{name:`${o}.task`});return u.push({task:x,done$:C}),s.set(u.length),h(),Ze(C,E=>E!==null).then(E=>{if(ie(C),E.ok)return E.result;throw E.error},E=>{throw ie(C),E})}function b(){l.set(!0)}function S(){l.set(!1),h()}function v(){let x=u.splice(0,u.length);s.set(0);for(let C of x)C.done$.set({ok:!1,error:new Error("Queue cleared")})}function D(){d||(d=!0,v())}return{enqueue:g,size:s,running:i,completed:a,failed:c,pause:b,resume:S,paused:l,clear:v,dispose:D}}function et(t){return()=>t}function tt(t,e=t){return n=>t+e*n}function nt(t){let e=t?.base??100,n=t?.factor??2,r=t?.maxDelay??3e4,o=t?.jitter??"none";return s=>{let i=Math.min(e*n**s,r);return on(i,o)}}function rt(t=100,e=3e4){return n=>{let r=1,o=1;for(let s=0;s<n;s++){let i=r+o;r=o,o=i}return Math.min(r*t,e)}}function ot(t=100,e=3e4){return(n,r,o)=>{let i=Math.min(e,(o??t)*3);return ze(t,i)}}function it(t,e){return(n,r,o)=>n>=e?null:t(n,r,o)}function on(t,e){switch(e){case"none":return t;case"full":return ze(0,t);case"equal":return t/2+ze(0,t/2)}}function ze(t,e){return t+Math.random()*(e-t)}function st(t){let{maxSize:e,onFlush:n}=t,r=t.maxWaitMs??null,o=t.name??"batchWriter",s=T(0,{name:`${o}.size`}),i=T(0,{name:`${o}.totalFlushed`}),a=T(!1,{name:`${o}.flushing`}),c=[],l=null,u=!1,f=!1,d=0;function p(){l!==null&&(clearTimeout(l),l=null)}function m(){if(c.length===0||f)return;f=!0;let S=c;c=[],p(),s.set(0);try{let v=n(S);v&&typeof v.then=="function"?(d++,a.set(!0),v.then(()=>{i.update(D=>D+S.length),d--,d===0&&a.set(!1)},()=>{i.update(D=>D+S.length),d--,d===0&&a.set(!1)})):i.update(D=>D+S.length)}catch{i.update(v=>v+S.length)}finally{f=!1}}function h(S){u||(c.push(S),s.set(c.length),r!==null&&c.length===1&&(l=setTimeout(()=>{l=null,m()},r)),c.length>=e&&m())}function g(){m()}function b(){u=!0,p(),m()}return{add:h,flush:g,size:s,totalFlushed:i,flushing:a,stop:b}}function at(t,e){let n=e?.name??"cancellableAction",r=e?.keepPreviousData??!1,o=T(e?.initial,{name:`${n}.data`}),s=T(!1,{name:`${n}.loading`}),i=T(void 0,{name:`${n}.error`}),a=T(0,{name:`${n}.runCount`}),c=null,l=0;function u(){c&&(c.abort(),c=null,s.set(!1))}async function f(d){u();let p=++l;c=new AbortController;let m=c.signal;s.set(!0),i.set(void 0),r||o.set(void 0);try{if(e?.rateLimiter&&(await e.rateLimiter.acquire(),m.aborted||p!==l))return;let h=await t(d,m);return p!==l?void 0:(o.set(h),s.set(!1),a.update(g=>g+1),c=null,h)}catch(h){if(p!==l)return;if(m.aborted){s.set(!1);return}i.set(h),s.set(!1),c=null;return}}return{execute:f,cancel:u,data:o,loading:s,error:i,runCount:a}}function V(t,e,n){let r=null;re(),t.source(k,(s,i)=>{if(s===k&&(r=i),s===y){r=null,n?.onEnd?.(i);return}if(s===1){let a=i,c=o;o=a,e(a,c)}});let o;try{o=t.get()}catch{}return oe(),{unsubscribe(){r?.(y),r=null},signal(s){r?.(_,s)}}}function ct(t){let e=t?.name??"cancellableStream",n=O(void 0,{initial:t?.initial,name:e,resubscribable:!0}),r=O(void 0,{initial:!1,name:`${e}.active`,_skipInspect:!0}),o=null,s=!1;function i(){s=!0,o&&(o.unsubscribe(),o=null),r.emit(!1)}function a(c){i(),s=!1,r.emit(!0);let l=je(c,{name:e,initial:t?.initial});o=V(l,u=>n.emit(u),{onEnd:u=>{if(o=null,!s)if(r.emit(!1),u!==void 0){try{t?.onError?.(u)}catch{}n.error(u)}else t?.onComplete?.()}})}return w.register(n,{kind:"cancellableStream"}),{store:n,start:a,cancel:i,active:r}}function je(t,e){let n=O(({emit:r,complete:o,error:s})=>{let i=new AbortController,a=!1;return(async()=>{try{for await(let c of t(i.signal)){if(i.signal.aborted)return;r(c)}if(!i.signal.aborted){a=!0;try{e?.onComplete?.()}catch{}o()}}catch(c){if(!i.signal.aborted){a=!0;try{e?.onError?.(c)}catch{}s(c)}}})(),()=>{if(!a){i.abort();try{e?.onAbort?.()}catch{}}}},{initial:e?.initial,name:e?.name??"fromAbortable",resubscribable:!0});return w.register(n,{kind:"fromAbortable"}),n}function ut(){let t=[],e=new Set,n=0;return{touch(){},insert(r){e.has(r)||(t.push(r),e.add(r))},delete(r){e.delete(r)},evict(r=1){let o=[];for(;o.length<r&&n<t.length;){let s=t[n++];e.delete(s)&&o.push(s)}return n>1e3&&n>t.length/2&&(t.splice(0,n),n=0),o},size:()=>e.size,clear(){t.length=0,e.clear(),n=0}}}function Ie(){let t=new Map,e={key:null,prev:null,next:null},n={key:null,prev:null,next:null};e.next=n,n.prev=e;function r(i){i.prev.next=i.next,i.next.prev=i.prev}function o(i){i.next=e.next,i.prev=e,e.next.prev=i,e.next=i}function s(i){r(i),o(i)}return{touch(i){let a=t.get(i);a&&s(a)},insert(i){let a=t.get(i);if(a){s(a);return}a={key:i,prev:null,next:null},t.set(i,a),o(a)},delete(i){let a=t.get(i);a&&(r(a),t.delete(i))},evict(i=1){let a=[];for(;a.length<i&&n.prev!==e;){let c=n.prev;a.push(c.key),r(c),t.delete(c.key)}return a},size:()=>t.size,clear(){t.clear(),e.next=n,n.prev=e}}}function lt(){let t=new Map,e={},n={};e.next=n,n.prev=e;function r(i,a){a.prev=i,a.next=i.next,i.next.prev=a,i.next=a}function o(i){i.prev.next=i.next,i.next.prev=i.prev}function s(i,a){if(i.next!==n&&i.next.freq===a)return i.next;let c={freq:a,keys:new Set};return r(i,c),c}return{touch(i){let a=t.get(i);if(!a)return;let c=s(a,a.freq+1);a.keys.delete(i),c.keys.add(i),t.set(i,c),a.keys.size===0&&o(a)},insert(i){if(t.has(i)){this.touch(i);return}let a=s(e,1);a.keys.add(i),t.set(i,a)},delete(i){let a=t.get(i);a&&(a.keys.delete(i),t.delete(i),a.keys.size===0&&o(a))},evict(i=1){let a=[];for(;a.length<i&&e.next!==n;){let c=e.next,l=c.keys.values().next().value;a.push(l),c.keys.delete(l),t.delete(l),c.keys.size===0&&o(c)}return a},size:()=>t.size,clear(){t.clear(),e.next=n,n.prev=e}}}function ft(t){let e=new Set;function n(r){try{return t(r)}catch{return-1/0}}return{touch(){},insert(r){e.add(r)},delete(r){e.delete(r)},evict(r=1){if(e.size===0)return[];if(r===1){let i,a=1/0;for(let c of e){let l=n(c);l<a&&(a=l,i=c)}return i!==void 0?(e.delete(i),[i]):[]}let o=Array.from(e).map(i=>({key:i,score:n(i)}));o.sort((i,a)=>i.score-a.score);let s=o.slice(0,r).map(i=>i.key);for(let i of s)e.delete(i);return s},size:()=>e.size,clear(){e.clear()}}}function dt(){let t=[],e=new Map;return{touch(){},insert(n){e.has(n)||(e.set(n,t.length),t.push(n))},delete(n){let r=e.get(n);if(r===void 0)return;let o=t[t.length-1];t[r]=o,e.set(o,r),t.pop(),e.delete(n)},evict(n=1){let r=[];for(;r.length<n&&t.length>0;){let o=Math.floor(Math.random()*t.length),s=t[o];r.push(s);let i=t[t.length-1];t[o]=i,e.set(i,o),t.pop(),e.delete(s)}return r},size:()=>t.length,clear(){t.length=0,e.clear()}}}function ce(t){t instanceof Promise&&t.catch(()=>{})}function $e(t,e){let n=new Map,r=e?.maxSize??0,o=r>0?e?.eviction??Ie():null,s=e?.writeThrough??!1,i=new Map;function a(p){return i.get(p)??0}function c(p){let m=a(p)+1;return i.set(p,m),m}function l(p,m,h){for(let g=0;g<h;g++){let b=t[g];b.save&&ce(b.save(p,m))}}function u(){if(!(!o||r<=0))for(;o.size()>r;){let p=o.evict(1);if(p.length===0)break;for(let m of p){let h=n.get(m);if(h){let g=h.get();if(g!==void 0){let b=-1;for(let S=t.length-1;S>=0;S--)if(t[S].save){ce(t[S].save(m,g)),b=S;break}for(let S=0;S<b;S++)t[S].clear&&ce(t[S].clear(m))}ie(h)}n.delete(m),i.delete(m)}}}function f(p,m){let h=c(p);d(p,m,0,h)}function d(p,m,h,g){if(h>=t.length)return;let b;try{b=t[h].load(p)}catch{d(p,m,h+1,g);return}b instanceof Promise?b.then(S=>{a(p)===g&&(S!==void 0?(m.set(S),l(p,S,h)):d(p,m,h+1,g))},()=>{a(p)===g&&d(p,m,h+1,g)}):b!==void 0?(m.set(b),l(p,b,h)):d(p,m,h+1,g)}return{load(p){let m=n.get(p);if(m)return o?.touch(p),m;let h=T(void 0);return n.set(p,h),o&&(o.insert(p),u()),f(p,h),h},save(p,m){if(c(p),s)for(let g of t)g.save&&ce(g.save(p,m));else t[0]?.save&&ce(t[0].save(p,m));let h=n.get(p);if(h)h.set(m),o?.touch(p);else{let g=T(m);n.set(p,g),o&&(o.insert(p),u())}},invalidate(p){let m=n.get(p);m&&f(p,m)},delete(p){o?.delete(p);let m=n.get(p);m&&ie(m),n.delete(p),i.delete(p);for(let h of t)h.clear&&ce(h.clear(p))},has(p){return n.has(p)},get size(){return n.size}}}function Ue(t){t instanceof Promise&&t.catch(()=>{})}function pt(t,e,n){return r=>{let o=n?.name??`checkpoint:${t}`,s=T({recovered:!1,persistCount:0,id:t},{name:`${o}:meta`,equals:()=>!1}),i=O(({emit:c,error:l,complete:u})=>{let f=0,d=!0,p=!1,m=[],h=null,g=V(r,v=>{if(!p){m.push(v);return}f++,s.set({recovered:s.get().recovered,persistCount:f,id:t}),Ue(e.save(t,v)),c(v)},{onEnd:v=>{if(!p){h={err:v};return}v!==void 0?l(v):u()}});function b(v){if(d){p=!0,s.set({recovered:v,persistCount:f,id:t});for(let D of m){if(!d)break;f++,s.set({recovered:v,persistCount:f,id:t}),Ue(e.save(t,D)),c(D)}m.length=0,h&&(h.err!==void 0?l(h.err):u())}}let S=e.load(t);return S instanceof Promise?S.then(v=>{d&&(v!==void 0?(c(v),b(!0)):b(!1))},()=>{d&&b(!1)}):S!==void 0?(c(S),b(!0)):b(!1),()=>{d=!1,m.length=0,g.unsubscribe()}},{name:o,kind:"checkpoint"});w.register(i,{kind:"checkpoint"});let a=i;return Object.defineProperties(a,{meta:{value:s,enumerable:!0},clear:{value(){Ue(e.clear(t))},enumerable:!0}}),a}}function mt(){let t=new Map;return{save(e,n){t.set(e,n)},load(e){return t.has(e)?t.get(e):void 0},clear(e){t.delete(e)}}}function Ne(t){return(e,n)=>{if(e!==0)return;let r=!1;n(0,o=>{o===2&&(r=!0)}),t.onsuccess=()=>{r||(r=!0,n(1,t.result),n(2))},t.onerror=()=>{r||(r=!0,n(2,t.error))}}}function ht(t){let{dir:e}=t;function n(r){let o=r.replace(/[^a-zA-Z0-9_-]/g,"_");return`${e}/${o}.json`}return{async save(r,o){let s=await import("fs/promises");await s.mkdir(e,{recursive:!0}),await s.writeFile(n(r),JSON.stringify(o),"utf-8")},async load(r){let o=await import("fs/promises");try{let s=await o.readFile(n(r),"utf-8");return JSON.parse(s)}catch(s){if(s?.code==="ENOENT")return;throw s}},async clear(r){let o=await import("fs/promises");try{await o.unlink(n(r))}catch(s){if(s?.code==="ENOENT")return;throw s}}}}var sn=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function gt(t){let{db:e}=t,n=t.table??"checkpoints";if(!sn.test(n))throw new Error(`sqliteAdapter: invalid table name "${n}". Must match /^[a-zA-Z_][a-zA-Z0-9_]*$/.`);e.exec(`CREATE TABLE IF NOT EXISTS ${n} (id TEXT PRIMARY KEY, value TEXT NOT NULL)`);let r=e.prepare(`INSERT OR REPLACE INTO ${n} (id, value) VALUES (?, ?)`),o=e.prepare(`SELECT value FROM ${n} WHERE id = ?`),s=e.prepare(`DELETE FROM ${n} WHERE id = ?`);return{save(i,a){r.run(i,JSON.stringify(a))},load(i){let a=o.get(i);return a?JSON.parse(a.value):void 0},clear(i){s.run(i)}}}function St(t){let e=t?.dbName??"callbag-checkpoints",n=t?.storeName??"checkpoints",r=null,o=null;function s(){if(r)return Promise.resolve(r);if(o)return o;let c=indexedDB.open(e,1);return c.onupgradeneeded=()=>{let l=c.result;l.objectStoreNames.contains(n)||l.createObjectStore(n)},o=Y(Ne(c)).then(l=>(r=l,r.onversionchange=()=>{r?.close(),r=null,o=null},r)),o.catch(()=>{o=null}),o}function i(c){return s().then(l=>{let u=l.transaction(n,c);return{store:u.objectStore(n),tx:u}})}async function a(c,l){try{let{store:u}=await i(c);return await Y(Ne(l(u)))}catch(u){if(u?.name==="InvalidStateError"||r===null){r=null,o=null;let{store:f}=await i(c);return Y(Ne(l(f)))}throw u}}return{async save(c,l){await a("readwrite",u=>u.put(l,c))},async load(c){return await a("readonly",u=>u.get(c))??void 0},async clear(c){await a("readwrite",l=>l.delete(c))}}}function Tt(t){let e=t?.failureThreshold??5,n=t?.cooldownMs??3e4,r=t?.cooldown??null,o=t?.halfOpenMax??1,s=t?.now??Date.now,i="closed",a=0,c=0,l=0,u=n,f=0;function d(){if(!r)return n;let h=r(c);return h!==null?h:n}function p(){i="open",u=d(),l=s(),f=0}return{canExecute(){return i==="closed"?!0:i==="open"?s()-l>=u?(i="half-open",f=1,!0):!1:f<o?(f++,!0):!1},recordSuccess(){i==="half-open"?(i="closed",a=0,c=0):i==="closed"&&(a=0)},recordFailure(h){if(i==="half-open"){c++,p();return}i==="closed"&&(a++,a>=e&&p())},get state(){return i},get failureCount(){return a},reset(){i="closed",a=0,c=0,f=0}}}var ue=class{_v;_w;constructor(e){this._v=0,this._w=e>32?new Uint32Array((e-1>>>5)+1):null}set(e){let n=this._w;if(n===null)this._v|=1<<e;else{let r=e>>>5,o=1<<(e&31);n[r]&o||(n[r]|=o,this._v++)}}clear(e){let n=this._w;if(n===null)this._v&=~(1<<e);else{let r=e>>>5,o=1<<(e&31);n[r]&o&&(n[r]&=~o,this._v--)}}test(e){let n=this._w;return n===null?(this._v&1<<e)!==0:(n[e>>>5]&1<<(e&31))!==0}empty(){return this._v===0}reset(){this._v=0,this._w?.fill(0)}};var ee=1,le=2,fe=4,W=8,Q=32,bt=64,an=Ee<<$,de=we<<$,qe=De<<$,ge=Ae<<$,cn=Ce<<$,Be=Re<<$,M=pe,Ve=class{_output=null;_upstreamTalkbacks=[];_cachedValue;_flags;_dirtyDeps;_eqFn;_deps;_fn;get _status(){return Oe(this._flags)}constructor(e,n,r,o){this._deps=e,this._fn=n,this._eqFn=r?.equals,this._flags=o?bt:0,this._dirtyDeps=new ue(e.length),this.source=this.source.bind(this),w.register(this,{kind:"derived",...r,deps:e});for(let s of e)w.registerEdge(s,this)}_dispatch(e,n){let r=this._output;if(r)if(this._flags&Q)for(let o of r)o(e,n);else r(e,n)}_recompute(){let e;try{e=this._fn()}catch(n){this._handleEnd(n);return}if(this._eqFn&&this._flags&ee&&this._eqFn(this._cachedValue,e)){this._flags=this._flags&~M|ge,this._dispatch(_,I);return}this._cachedValue=e,this._flags=(this._flags|ee)&~M|qe,this._dispatch(A,this._cachedValue)}_recomputeIdentity(e){if(!(this._flags&W)){if(this._eqFn&&this._flags&ee&&this._eqFn(this._cachedValue,e)){this._flags=this._flags&~M|ge,this._dispatch(_,I);return}this._cachedValue=e,this._flags=(this._flags|ee)&~M|qe,this._dispatch(A,e)}}_lazyConnect(){if(!(this._flags&(le|W))){try{this._cachedValue=this._fn()}catch(e){this._handleEnd(e);return}this._flags=(this._flags|ee)&~M|qe,re(),this._connectUpstream(),this._flags&W||(this._flags|=le),oe()}}_connectUpstream(){this._upstreamTalkbacks.length=0,this._deps.length===1?this._flags&bt?this._connectSingleDepIdentity():this._connectSingleDep():this._connectMultiDep()}_connectSingleDep(){let e=!1;this._deps[0].source(k,(n,r)=>{if(n===k){this._upstreamTalkbacks.push(r),r(_,J);return}if(!(this._flags&W))if(n===_)if(r===R){if(e)return;e=!0,this._flags=this._flags&~M|de,this._dispatch(_,R)}else r===I?e&&(e=!1,this._flags=this._flags&~M|ge,this._dispatch(_,I)):this._dispatch(_,r);else n===A?e?(e=!1,this._recompute()):(this._flags=this._flags&~M|de,this._dispatch(_,R),this._recompute()):n===y&&this._handleEnd(r)})}_connectSingleDepIdentity(){let e=!1;this._deps[0].source(k,(n,r)=>{if(n===k){this._upstreamTalkbacks.push(r),r(_,J);return}this._flags&W||(n===_?r===R?(e=!0,this._flags=this._flags&~M|de,this._dispatch(_,R)):r===I?e&&(e=!1,this._flags=this._flags&~M|ge,this._dispatch(_,I)):this._dispatch(_,r):n===A?e?(e=!1,this._recomputeIdentity(r)):(this._flags=this._flags&~M|de,this._dispatch(_,R),this._recomputeIdentity(r)):n===y&&this._handleEnd(r))})}_connectMultiDep(){for(let e=0;e<this._deps.length&&!(this._flags&W);e++){let n=e;this._deps[n].source(k,(r,o)=>{if(r===k){this._upstreamTalkbacks.push(o);return}if(!(this._flags&W))if(r===_)if(o===R){let s=this._dirtyDeps.empty();this._dirtyDeps.set(n),s&&(this._flags&=~fe,this._flags=this._flags&~M|de,this._dispatch(_,R))}else o===I?this._dirtyDeps.test(n)&&(this._dirtyDeps.clear(n),this._dirtyDeps.empty()&&(this._flags&fe?this._recompute():(this._flags=this._flags&~M|ge,this._dispatch(_,I)))):this._dispatch(_,o);else r===A?this._dirtyDeps.test(n)?(this._dirtyDeps.clear(n),this._flags|=fe,this._dirtyDeps.empty()&&this._recompute()):this._dirtyDeps.empty()?(this._flags=this._flags&~M|de,this._dispatch(_,R),this._recompute()):this._flags|=fe:r===y&&this._handleEnd(o)})}}_handleEnd(e){this._flags|=W,this._flags=this._flags&~M|(e!==void 0?Be:cn),e!==void 0&&(this._cachedValue=e);for(let o of this._upstreamTalkbacks)o(y);this._upstreamTalkbacks=[],this._flags&=~le,this._dirtyDeps.reset();let n=this._output,r=this._flags&Q;if(this._output=null,this._flags&=~Q,n)if(r)for(let o of n)try{e!==void 0?o(y,e):o(y)}catch{}else e!==void 0?n(y,e):n(y)}_disconnectUpstream(){for(let e of this._upstreamTalkbacks)e(y);this._upstreamTalkbacks.length=0,this._flags&=~(le|fe),this._flags=this._flags&~M|an,this._dirtyDeps.reset()}_handleLifecycleSignal(e){if(!(this._flags&W)){if(e===q){for(let n of this._upstreamTalkbacks)n(_,q);this._handleEnd(void 0);return}e===z&&(this._flags&=~(ee|fe),this._dirtyDeps.reset());for(let n of this._upstreamTalkbacks)n(_,e)}}get(){if(this._flags&le)return this._cachedValue;if(this._flags&W){if((this._flags&M)===Be)throw this._cachedValue;return this._cachedValue}let e=this._fn();return this._cachedValue=e,this._flags|=ee,e}source(e,n){if(e===k){let r=n;if(this._flags&W){let o=(this._flags&M)===Be;r(k,s=>{}),o?r(y,this._cachedValue):r(y);return}if(!(this._flags&le)&&(this._lazyConnect(),this._flags&W)){let o=(this._flags&M)===Be;r(k,s=>{}),o?r(y,this._cachedValue):r(y);return}if(this._output===null)this._output=r;else if(this._flags&Q)this._output.add(r);else{let o=new Set;o.add(this._output),o.add(r),this._output=o,this._flags|=Q}r(k,(o,s)=>{if(o===A&&r(A,this._cachedValue),o===_&&ne(s)){this._handleLifecycleSignal(s);return}if(o===y){if(this._output===null)return;if(this._flags&Q){let i=this._output;i.delete(r),i.size===1?(this._output=i.values().next().value,this._flags&=~Q):i.size===0&&(this._output=null,this._flags&=~Q,this._disconnectUpstream())}else this._output===r&&(this._output=null,this._disconnectUpstream())}})}}};function P(t,e,n){return new Ve(t,e,n)}(e=>{function t(n,r){return new Ve([n],()=>n.get(),r,!0)}e.from=t})(P||={});function yt(t){let e=t?.heartbeatMs??3e4,n=t?.timeoutMs??5e3,r=t?.backoff??null,o=t?.maxReconnects??Number.POSITIVE_INFINITY,s=t?.name??"connectionHealth",i=T("disconnected",{name:`${s}.status`}),a=T(0,{name:`${s}.reconnectCount`}),c=P([i],()=>i.get()==="connected",{name:`${s}.healthy`}),l=null,u=null,f=null,d=null,p=!1,m=!1,h=null,g;function b(){l!==null&&(clearTimeout(l),l=null),u!==null&&(clearTimeout(u),u=null),f!==null&&(clearTimeout(f),f=null),d&&(d.abort(),d=null),p=!1}function S(){m||!h||(l=setTimeout(()=>{l=null,!(m||!h)&&D()},e))}function v(){l!==null&&clearTimeout(l),S()}async function D(){if(!h||m||p)return;p=!0;let K=new AbortController;u=setTimeout(()=>{u=null,K.abort()},n);try{await h.heartbeat(K.signal),u!==null&&(clearTimeout(u),u=null),p=!1,S()}catch{if(u!==null&&(clearTimeout(u),u=null),p=!1,m)return;i.set("disconnected"),h.disconnect(),x()}}function x(){if(m||!h)return;let K=a.get();if(K>=o){i.set("failed");return}let B;if(r){let G=r(K,void 0,g);B=G!==null?G:1e3,g=B}else B=1e3;f=setTimeout(()=>{f=null,!m&&(a.update(G=>G+1),C())},B)}async function C(){if(!(m||!h)){i.set("connecting"),d=new AbortController;try{if(await h.connect(d.signal),m)return;d=null,i.set("connected"),a.set(0),g=void 0,v()}catch{if(m)return;d=null,i.set("disconnected"),x()}}}function E(K){h&&(b(),h.disconnect()),m=!1,h=K,a.set(0),g=void 0,C()}function N(){m=!0,b(),h&&h.disconnect(),h=null,i.set("disconnected")}return{status:i,healthy:c,reconnectCount:a,start:E,stop:N}}function vt(t){let e=new Map;for(let i=0;i<t.length;i++){if(e.has(t[i].store))throw new Error(`Duplicate store in DAG: ${t[i].name??`node[${i}]`}`);e.set(t[i].store,i)}let n=new Array(t.length).fill(0),r=t.map(()=>[]);for(let i=0;i<t.length;i++){let a=t[i].deps;if(a)for(let c of a){let l=e.get(c);if(l===void 0)throw new Error(`Dependency not found in DAG for ${t[i].name??`node[${i}]`}. All deps must be declared as DAG nodes.`);r[l].push(i),n[i]++}}let o=[];for(let i=0;i<t.length;i++)n[i]===0&&o.push(i);let s=[];for(;o.length>0;){let i=o.shift();s.push(i);for(let a of r[i])n[a]--,n[a]===0&&o.push(a)}if(s.length!==t.length){let i=t.filter((a,c)=>!s.includes(c)).map((a,c)=>a.name??`node[${c}]`);throw new Error(`Cycle detected in DAG involving: ${i.join(", ")}`)}for(let i of t)if(i.name&&w.register(i.store,{name:i.name,kind:"dag-node"}),i.deps)for(let a of i.deps)w.registerEdge(a,i.store);return{order:s.map(i=>t[i].store),size:t.length}}function _t(t,e,n){let r=n?.equals??Object.is,o=n?.name??"dirtyTracker",s=T(e,{name:`${o}.baseline`}),i=P([t,s],()=>!r(t.get(),s.get()),{name:`${o}.dirty`}),a=!1;function c(...u){a||s.set(u.length>0?u[0]:t.get())}function l(){a||(a=!0)}return{dirty:i,baseline:s,resetBaseline:c,dispose:l}}function xt(t){let e=new Map;return n=>{let r=e.get(n);if(r)return r;let o=t(n).finally(()=>e.delete(n));return e.set(n,o),o}}function kt(t,e){return(n,r)=>{if(n!==0)return;let o=!1;function s(){o||(o=!0,clearTimeout(a),e?.removeEventListener("abort",i),r(1,void 0),r(2))}function i(){s()}if(r(0,c=>{c===2&&!o&&(o=!0,clearTimeout(a),e?.removeEventListener("abort",i))}),e?.aborted){s();return}let a=setTimeout(s,t);e?.addEventListener("abort",i,{once:!0})}}function Et(t){let e=t.rate,n=t.burst??e,r=t.now??Date.now,o=n,s=r();function i(){let a=r(),c=(a-s)/1e3;o=Math.min(n,o+c*e),s=a}return{tryAcquire(a=1){return i(),o>=a?(o-=a,!0):!1},async acquire(a=1,c){if(a>n)throw new RangeError(`Cannot acquire ${a} tokens (burst capacity is ${n})`);if(c?.throwIfAborted(),i(),o>=a)return o-=a,0;let l=0;for(;o<a;){let f=(a-o)/e*1e3;l+=f,await Dt(f,c),i()}return o-=a,l},available(){return i(),Math.floor(o)},reset(){o=n,s=r()}}}function wt(t){let e=t.max,n=t.windowMs,r=t.now??Date.now,o=[];function s(){let i=r()-n;for(;o.length>0&&o[0]<=i;)o.shift()}return{tryAcquire(i=1){if(s(),o.length+i<=e){let a=r();for(let c=0;c<i;c++)o.push(a);return!0}return!1},async acquire(i=1,a){if(i>e)throw new RangeError(`Cannot acquire ${i} slots (max capacity is ${e})`);if(a?.throwIfAborted(),s(),o.length+i<=e){let u=r();for(let f=0;f<i;f++)o.push(u);return 0}let c=0;for(;o.length+i>e;){let u=o.length+i-e,f=o[u-1],d=f!==void 0?f+n-r():n;d>0&&(c+=d,await Dt(d,a)),s()}let l=r();for(let u=0;u<i;u++)o.push(l);return c},available(){return s(),e-o.length},reset(){o.length=0}}}function Dt(t,e){return e?.aborted?Promise.reject(e.reason):Y(kt(Math.ceil(t),e)).then(()=>{if(e?.aborted)throw e.reason})}function At(t,e=n=>n){let n=[],r=new Map,o=new Map;function s(l,u){let f=n[l],d=n[u];n[l]=d,n[u]=f,f.index=u,d.index=l}function i(l){for(;l>0;){let u=l-1>>>1;if(n[u].score<=n[l].score)break;s(l,u),l=u}}function a(l){let u=n.length;for(;;){let f=l,d=2*l+1,p=d+1;if(d<u&&n[d].score<n[f].score&&(f=d),p<u&&n[p].score<n[f].score&&(f=p),f===l)break;s(l,f),l=f}}function c(l){let u=n.length-1;if(l===u){n.pop();return}s(l,u),n.pop(),i(l),a(l)}return{touch(){},insert(l){if(r.has(l))return;let u=t(l),f={key:l,score:e(u.get()),index:n.length};n.push(f),r.set(l,f),i(f.index);let d=V(u,p=>{let m=r.get(l);if(!m)return;let h=m.score;m.score=e(p),m.score<h?i(m.index):m.score>h&&a(m.index)});o.set(l,()=>d.unsubscribe())},delete(l){let u=r.get(l);if(!u)return;let f=o.get(l);f&&(f(),o.delete(l)),c(u.index),r.delete(l)},evict(l=1){let u=[];for(;u.length<l&&n.length>0;){let{key:f}=n[0];u.push(f);let d=o.get(f);d&&(d(),o.delete(f)),c(0),r.delete(f)}return u},size:()=>r.size,clear(){for(let l of o.values())l();o.clear(),r.clear(),n.length=0}}}function Ct(t){let e=typeof t=="number"?{count:t}:t,n=e.count??(e.delay?1/0:0),r=e.delay??null,o=e.while??null;return s=>{let i=T({attempt:0,pending:!1},{name:"retry:meta",equals:()=>!1});function a(l){i.set({attempt:l.attempt,lastError:l.lastError,pending:l.pending??!1})}let c=O(({emit:l,complete:u,error:f})=>{let d=0,p,m=null,h=!1,g=null,b=!1;function S(){if(b)return;m&&(m(y),m=null);let v=s.get();h&&v!==void 0&&l(v),h=!0,!b&&s.source(k,(D,x)=>{if(!b&&(D===k&&(m=x),D===1&&l(x),D===y))if(m=null,x!==void 0)if(d<n&&(o===null||o(x)))if(!r)d++,a({attempt:d,lastError:x}),S();else{let E=r(d,x,p);E!==null&&(p=E),E===null?(a({attempt:d,lastError:x}),f(x)):E<=0?(d++,a({attempt:d,lastError:x}),S()):(d++,a({attempt:d,lastError:x,pending:!0}),g=setTimeout(()=>{g=null,a({attempt:d,lastError:x,pending:!1}),S()},E))}else a({attempt:d,lastError:x}),f(x);else u()})}return S(),()=>{b=!0,g!==null&&(clearTimeout(g),g=null),m&&m(y)}},{initial:s.get()});return w.register(c,{kind:"retry"}),c.retryMeta=i,c}}function Rt(t){return typeof t=="string"?[{to:t}]:Array.isArray(t)?t:[t]}function un(t,e,n,r){let o=r,s=t.states[e];if(s?.onExit){let a=s.onExit(o);a!==void 0&&(o=a)}let i=t.states[n];if(i?.onEnter){let a=i.onEnter(o);a!==void 0&&(o=a)}return o}function ln(t){let e=[];for(let[n,r]of Object.entries(t.states))if(r.on){for(let[o,s]of Object.entries(r.on))if(s!==void 0)for(let i of Rt(s))e.push({from:n,event:o,to:i.to,guarded:!!i.guard})}return e}function te(t){return t.replace(/[^a-zA-Z0-9_]/g,"_")}function Ot(t,e){let n=T(e.initial),r=t,o=e.states[e.initial];if(o?.onEnter){let d=o.onEnter(r);d!==void 0&&(r=d)}let s=T(r),i=Object.freeze(ln(e));function a(d,p){let m=n.get(),h=e.states[m];if(!h?.on)return!1;let g=h.on[d];if(g===void 0)return!1;let b=Rt(g),S=s.get();for(let v of b){if(v.guard&&!v.guard(S,p))continue;let D=S;if(v.action){let x=v.action(S,p);x!==void 0&&(D=x)}return D=un(e,m,v.to,D),n.set(v.to),s.set(D),!0}return!1}function c(d){return n.get()===d}function l(){let d=n.get(),p=s.get(),m=e.states[d];m?.onExit&&m.onExit(p),n.set(e.initial);let h=e.states[e.initial];if(h?.onEnter){let g=h.onEnter(t);s.set(g!==void 0?g:t)}else s.set(t)}function u(d){let m=["stateDiagram-v2",` direction ${d?.direction??"LR"}`],h=Object.keys(e.states);for(let g of h){let b=te(g);m.push(` ${b} : ${g}`)}m.push(` [*] --> ${te(e.initial)}`);for(let g of i){let b=te(g.from),S=te(g.to),v=g.guarded?`${g.event} [guarded]`:g.event;m.push(` ${b} --> ${S} : ${v}`)}return m.join(`
5
5
  `)}function f(d){let m=[`direction: ${d?.direction??"right"}`,""],h=Object.keys(e.states);for(let g of h){let b=te(g),v=g===e.initial?`${g} (initial)`:g;m.push(`${b}: "${v}"`)}if(i.length>0){m.push("");for(let g of i){let b=te(g.from),S=te(g.to),v=g.guarded?`${g.event} [guarded]`:g.event;m.push(`${b} -> ${S}: ${v}`)}}return m.join(`
6
- `)}return{current:n,context:s,send:a,matches:c,reset:l,transitions:i,toMermaid:u,toD2:f}}function fn(t){return{load:e=>t.load(e),save:(e,n)=>t.save(e,n),clear:e=>t.clear(e)}}function Lt(t,e){let n=$e(t.map(fn),{maxSize:e?.maxSize,eviction:e?.eviction});return{load:r=>n.load(r),save:(r,o)=>n.save(r,o),invalidate:r=>n.invalidate(r),delete:r=>n.delete(r),has:r=>n.has(r),get size(){return n.size},cache:n}}function Pt(t,e){let n=null,r=0,o=!1,s=!1;function i(){n!=null&&(clearInterval(n),n=null)}function a(){let c=Date.now(),l=c-r;r=c,e(l)}return{start(){o||(i(),r=Date.now(),s=!0,n=setInterval(a,t))},pause(){if(o||!s)return 0;let l=Date.now()-r;return s=!1,i(),l},resume(){o||s||(r=Date.now(),s=!0,n=setInterval(a,t))},stop(){o||(s=!1,i())},get active(){return s},get disposed(){return o},dispose(){o||(o=!0,s=!1,i())}}}function It(t,e){let n=Math.max(1,e?.tickMs??100),r=e?.name??"countdown",s=O(({emit:i,onSignal:a})=>{let c=t,l=!0,u=Pt(n,d=>{c-=d,c<=0&&(c=0,l=!1,u.stop()),i({remaining:c,active:l,expired:c<=0})});function f(){i({remaining:c,active:l,expired:c<=0})}return a(d=>{if(d===xe){if(!u.active)return;let p=u.pause();p>0&&(c=Math.max(0,c-p)),l=!1,f()}else if(d===ke){if(u.active||c<=0)return;u.resume(),l=!0,f()}else d===z&&(u.stop(),c=t,l=!1,f())}),f(),u.start(),()=>u.dispose()},{initial:{remaining:t,active:!1,expired:!1},name:r,kind:"countdown"});return{remaining:P([s],()=>s.get()?.remaining??t,{name:`${r}.remaining`}),active:P([s],()=>s.get()?.active??!1,{name:`${r}.active`,equals:Object.is}),expired:P([s],()=>s.get()?.expired??!1,{name:`${r}.expired`,equals:Object.is})}}function $t(t){let e=Math.max(1,t?.tickMs??100),n=t?.name??"stopwatch",o=O(({emit:s,onSignal:i})=>{let a=0,c=!0,l=[],u=Pt(e,d=>{a+=d,s({elapsed:a,active:c,laps:l})});function f(){s({elapsed:a,active:c,laps:l})}return i(d=>{if(d===xe){if(!u.active)return;let p=u.pause();p>0&&(a+=p),c=!1,f()}else if(d===ke){if(u.active)return;u.resume(),c=!0,f()}else d===z&&(u.stop(),a=0,c=!1,l=[],f())}),f(),u.start(),()=>u.dispose()},{initial:{elapsed:0,active:!1,laps:[]},name:n,kind:"stopwatch"});return{elapsed:P([o],()=>o.get()?.elapsed??0,{name:`${n}.elapsed`}),active:P([o],()=>o.get()?.active??!1,{name:`${n}.active`,equals:Object.is}),laps:P([o],()=>o.get()?.laps??[],{name:`${n}.laps`})}}var Nt=Object.freeze({promptTokens:0,completionTokens:0,totalTokens:0,cost:0,count:0});function Bt(t,e){return n=>{let r=e?.name??"tokenTracker",o=a=>a==null||!Number.isFinite(a)?0:a,s=T({...Nt},{name:`${r}:tokens`,equals:()=>!1}),i=O(({emit:a,error:c,complete:l})=>{let u=0,f=0,d=0,p=0,m=0;s.set({...Nt});let h=F(n,g=>{try{let b=t(g),S=o(b.promptTokens),v=o(b.completionTokens),D=o(b.totalTokens)||S+v,x=o(b.cost);u+=S,f+=v,d+=D,p+=x,m++,s.set({promptTokens:u,completionTokens:f,totalTokens:d,cost:p,count:m})}catch{m++,s.set({promptTokens:u,completionTokens:f,totalTokens:d,cost:p,count:m})}a(g)},{onEnd:g=>{g!==void 0?c(g):l()}});return()=>{h.unsubscribe()}},{initial:n.get()});return w.register(i,{kind:"tokenTracker",name:r}),i.tokens=s,i}}var Vt=Object.freeze({status:"idle",count:0});function Kt(t){return e=>{let n=T({...Vt},{name:t?.name?`${t.name}:meta`:"track:meta",equals:()=>!1}),r=O(({emit:o,error:s,complete:i})=>{let a=0,c;n.set({...Vt});let l=F(e,u=>{a++,a===1&&(c=Date.now()),n.set({status:"active",count:a,startedAt:c}),o(u)},{onEnd:u=>{let f=c!==void 0?Date.now()-c:void 0;u!==void 0?(n.set({status:"errored",count:a,error:u,startedAt:c,duration:f}),s(u)):(n.set({status:"completed",count:a,startedAt:c,duration:f}),i())}});return()=>{l.unsubscribe()}},{initial:e.get()});return w.register(r,{kind:"track"}),r.meta=n,r}}function Ft(t,e){let n=e?.sync??[],r=e?.async??[],o=e?.debounceMs??300,s=e?.name??"validation",i=[],a=T(i,{name:`${s}.syncErrors`}),c=T(i,{name:`${s}.asyncErrors`}),l=T(!1,{name:`${s}.validating`}),u=P([a,c],()=>{let E=a.get(),N=c.get();return E.length>0&&N.length>0?[...E,...N]:E.length>0?E:N.length>0?N:i},{name:`${s}.errors`}),f=P([u],()=>{let E=u.get();return E.length>0?E[0]:""},{name:`${s}.error`}),d=P([u,l],()=>u.get().length===0&&!l.get(),{name:`${s}.valid`}),p=null,m=null;function h(){p&&(p.abort(),p=null),m!==null&&(clearTimeout(m),m=null),l.set(!1)}function g(E){if(n.length===0)return i;let N=[];for(let V of n){let B=V(E);B!==!0&&B!==void 0&&N.push(B)}return N.length===0?i:N}function b(E){if(h(),r.length===0){l.set(!1),c.set(i);return}if(a.get().length>0){l.set(!1),c.set(i);return}l.set(!0);function N(){p=new AbortController;let V=p.signal;Promise.all(r.map(B=>B(E,V))).then(B=>{if(V.aborted||x)return;let G=B.filter(qt=>qt!==void 0);c.set(G.length===0?i:G),l.set(!1),p=null}).catch(B=>{V.aborted||x||(c.set([String(B)]),l.set(!1),p=null)})}o===0?N():m=setTimeout(()=>{m=null,N()},o)}function S(){let E=t.get(),N=g(E);a.set(N),b(E)}let v=Ke([t],()=>(S(),()=>h()));function D(){S()}let x=!1;function C(){x||(x=!0,h(),v())}return{error:f,errors:u,valid:d,validating:l,validate:D,dispose:C}}var Se=class extends Error{constructor(){super("Circuit breaker is open"),this.name="CircuitOpenError"}};function Wt(t,e){let n=e?.onOpen??"skip";return r=>{let o=T(t.state,{name:"breaker:state",equals:Object.is}),s=O(({emit:a,error:c,complete:l})=>{let u=F(r,f=>{t.canExecute()?(t.recordSuccess(),o.set(t.state),a(f)):(o.set(t.state),n==="error"&&(u.unsubscribe(),c(new Se)))},{onEnd:f=>{f!==void 0?(t.recordFailure(f),o.set(t.state),c(f)):l()}});return()=>{u.unsubscribe()}},{initial:r.get()}),i={get:()=>s.get(),source:(a,c)=>s.source(a,c),get _status(){return s._status},breakerState:o};return w.register(i,{kind:"withBreaker"}),i}}function zt(t,e){let n=e?.initialStatus??"connecting",r=T(n,{name:e?.name?`${e.name}:status`:"connectionStatus",equals:Object.is}),o=T(void 0,{name:e?.name?`${e.name}:error`:"connectionError",equals:Object.is}),s={get:()=>t.get(),source:(i,a)=>t.source(i,a),get _status(){return t._status},status:r,error:o,setConnected(){Z(()=>{o.set(void 0),r.set("connected")})},setError(i){Z(()=>{o.set(i),r.set("failed")})},setClosed(){Z(()=>{o.set(void 0),r.set("disconnected")})}};return w.register(s,{kind:"withConnectionStatus"}),s}function jt(t,e){let n=e?.name??"meta",r=T(0,{name:`${n}.count`}),o=T(void 0,{name:`${n}.lastValue`}),s=T(!1,{name:`${n}.ended`}),i=T(void 0,{name:`${n}.error`}),a=null;return t.source(k,(c,l)=>{if(c===k){a=l;return}c===A?(r.update(u=>u+1),o.set(l)):c===y&&(s.set(!0),l!==void 0&&i.set(l),a=null)}),{count:r,lastValue:o,ended:s,error:i,dispose:()=>a?.(y)}}function Ut(t,e){let n=e?.initialStatus??"pending",r=T(n,{name:"withStatus:status",equals:Object.is}),o=T(void 0,{name:"withStatus:error",equals:Object.is}),s=O(({emit:a,complete:c,error:l})=>{r.set(n),o.set(void 0);let u=F(t,f=>{r.get()==="errored"?Z(()=>{o.set(void 0),r.set("active")}):r.set("active"),a(f)},{onEnd:f=>{if(f!==void 0){let d=f instanceof Error?f:new Error(String(f));Z(()=>{o.set(d),r.set("errored")}),l(f)}else r.set("completed"),c()}});return()=>{u.unsubscribe()}},{initial:t.get(),resubscribable:!0}),i={get:()=>t.get(),source:(a,c)=>s.source(a,c),get _status(){return s._status},status:r,error:o};return w.register(i,{kind:"withStatus"}),i}0&&(module.exports={CircuitOpenError,asyncQueue,batchWriter,cancellableAction,cancellableStream,cascadingCache,checkpoint,circuitBreaker,connectionHealth,constant,countdown,dag,decorrelatedJitter,dirtyTracker,exponential,fibonacci,fifo,fileAdapter,fromAbortable,indexedDBAdapter,keyedAsync,lfu,linear,lru,memoryAdapter,random,reactiveScored,retry,scored,slidingWindow,sqliteAdapter,stateMachine,stopwatch,tieredStorage,tokenBucket,tokenTracker,track,validationPipeline,withBreaker,withConnectionStatus,withMaxAttempts,withMeta,withStatus});
6
+ `)}return{current:n,context:s,send:a,matches:c,reset:l,transitions:i,toMermaid:u,toD2:f}}function fn(t){return{load:e=>t.load(e),save:(e,n)=>t.save(e,n),clear:e=>t.clear(e)}}function Mt(t,e){let n=$e(t.map(fn),{maxSize:e?.maxSize,eviction:e?.eviction});return{load:r=>n.load(r),save:(r,o)=>n.save(r,o),invalidate:r=>n.invalidate(r),delete:r=>n.delete(r),has:r=>n.has(r),get size(){return n.size},cache:n}}function Lt(t,e){let n=null,r=0,o=!1,s=!1;function i(){n!=null&&(clearInterval(n),n=null)}function a(){let c=Date.now(),l=c-r;r=c,e(l)}return{start(){o||(i(),r=Date.now(),s=!0,n=setInterval(a,t))},pause(){if(o||!s)return 0;let l=Date.now()-r;return s=!1,i(),l},resume(){o||s||(r=Date.now(),s=!0,n=setInterval(a,t))},stop(){o||(s=!1,i())},get active(){return s},get disposed(){return o},dispose(){o||(o=!0,s=!1,i())}}}function Pt(t,e){let n=Math.max(1,e?.tickMs??100),r=e?.name??"countdown",s=O(({emit:i,onSignal:a})=>{let c=t,l=!0,u=Lt(n,d=>{c-=d,c<=0&&(c=0,l=!1,u.stop()),i({remaining:c,active:l,expired:c<=0})});function f(){i({remaining:c,active:l,expired:c<=0})}return a(d=>{if(d===xe){if(!u.active)return;let p=u.pause();p>0&&(c=Math.max(0,c-p)),l=!1,f()}else if(d===ke){if(u.active||c<=0)return;u.resume(),l=!0,f()}else d===z&&(u.stop(),c=t,l=!1,f())}),f(),u.start(),()=>u.dispose()},{initial:{remaining:t,active:!1,expired:!1},name:r,kind:"countdown"});return{remaining:P([s],()=>s.get()?.remaining??t,{name:`${r}.remaining`}),active:P([s],()=>s.get()?.active??!1,{name:`${r}.active`,equals:Object.is}),expired:P([s],()=>s.get()?.expired??!1,{name:`${r}.expired`,equals:Object.is})}}function It(t){let e=Math.max(1,t?.tickMs??100),n=t?.name??"stopwatch",o=O(({emit:s,onSignal:i})=>{let a=0,c=!0,l=[],u=Lt(e,d=>{a+=d,s({elapsed:a,active:c,laps:l})});function f(){s({elapsed:a,active:c,laps:l})}return i(d=>{if(d===xe){if(!u.active)return;let p=u.pause();p>0&&(a+=p),c=!1,f()}else if(d===ke){if(u.active)return;u.resume(),c=!0,f()}else d===z&&(u.stop(),a=0,c=!1,l=[],f())}),f(),u.start(),()=>u.dispose()},{initial:{elapsed:0,active:!1,laps:[]},name:n,kind:"stopwatch"});return{elapsed:P([o],()=>o.get()?.elapsed??0,{name:`${n}.elapsed`}),active:P([o],()=>o.get()?.active??!1,{name:`${n}.active`,equals:Object.is}),laps:P([o],()=>o.get()?.laps??[],{name:`${n}.laps`})}}var $t=Object.freeze({promptTokens:0,completionTokens:0,totalTokens:0,cost:0,count:0});function Nt(t,e){return n=>{let r=e?.name??"tokenTracker",o=a=>a==null||!Number.isFinite(a)?0:a,s=T({...$t},{name:`${r}:tokens`,equals:()=>!1}),i=O(({emit:a,error:c,complete:l})=>{let u=0,f=0,d=0,p=0,m=0;s.set({...$t});let h=V(n,g=>{try{let b=t(g),S=o(b.promptTokens),v=o(b.completionTokens),D=o(b.totalTokens)||S+v,x=o(b.cost);u+=S,f+=v,d+=D,p+=x,m++,s.set({promptTokens:u,completionTokens:f,totalTokens:d,cost:p,count:m})}catch{m++,s.set({promptTokens:u,completionTokens:f,totalTokens:d,cost:p,count:m})}a(g)},{onEnd:g=>{g!==void 0?c(g):l()}});return()=>{h.unsubscribe()}},{initial:n.get()});return w.register(i,{kind:"tokenTracker",name:r}),i.tokens=s,i}}var Bt=Object.freeze({status:"idle",count:0});function Vt(t){return e=>{let n=T({...Bt},{name:t?.name?`${t.name}:meta`:"track:meta",equals:()=>!1}),r=O(({emit:o,error:s,complete:i})=>{let a=0,c;n.set({...Bt});let l=V(e,u=>{a++,a===1&&(c=Date.now()),n.set({status:"active",count:a,startedAt:c}),o(u)},{onEnd:u=>{let f=c!==void 0?Date.now()-c:void 0;u!==void 0?(n.set({status:"errored",count:a,error:u,startedAt:c,duration:f}),s(u)):(n.set({status:"completed",count:a,startedAt:c,duration:f}),i())}});return()=>{l.unsubscribe()}},{initial:e.get()});return w.register(r,{kind:"track"}),r.meta=n,r}}function Kt(t,e,n){let r,o=[],s=!1,i=new ue(t.length),a=!1;function c(){s||(r&&r(),r=e())}let l=0;function u(d){if(!s){if(d===q){for(let p of o)p(_,q);o.length=0,s=!0,r&&r(),r=void 0;return}d===z&&(l++,i.reset(),a=!1,c());for(let p of o)p(_,d)}}re(),c();for(let d=0;d<t.length&&!s;d++){let p=d,m=l;t[p].source(k,(h,g)=>{if(h===k){o.push(g),t.length===1&&g(_,J);return}if(!s){if(h===_){if(ne(g)){u(g),m=l;return}if(m!==l)return;g===R?(i.empty()&&(a=!1),i.set(p)):g===I&&i.test(p)&&(i.clear(p),i.empty()&&a&&c())}if(h===A){if(m!==l)return;i.test(p)?(i.clear(p),a=!0,i.empty()&&c()):i.empty()?c():a=!0}if(h===y){s=!0,r&&r(),r=void 0;for(let b of o)b(y);o.length=0}}})}oe();let f=()=>{if(!s){s=!0,r&&r(),r=void 0;for(let d of o)d(y);o.length=0}};f.signal=d=>u(d),w.register(f,{kind:"effect",...n,deps:t});for(let d of t)w.registerEdge(d,f);return f}function Ft(t,e){let n=e?.sync??[],r=e?.async??[],o=e?.debounceMs??300,s=e?.name??"validation",i=[],a=T(i,{name:`${s}.syncErrors`}),c=T(i,{name:`${s}.asyncErrors`}),l=T(!1,{name:`${s}.validating`}),u=P([a,c],()=>{let E=a.get(),N=c.get();return E.length>0&&N.length>0?[...E,...N]:E.length>0?E:N.length>0?N:i},{name:`${s}.errors`}),f=P([u],()=>{let E=u.get();return E.length>0?E[0]:""},{name:`${s}.error`}),d=P([u,l],()=>u.get().length===0&&!l.get(),{name:`${s}.valid`}),p=null,m=null;function h(){p&&(p.abort(),p=null),m!==null&&(clearTimeout(m),m=null),l.set(!1)}function g(E){if(n.length===0)return i;let N=[];for(let K of n){let B=K(E);B!==!0&&B!==void 0&&N.push(B)}return N.length===0?i:N}function b(E){if(h(),r.length===0){l.set(!1),c.set(i);return}if(a.get().length>0){l.set(!1),c.set(i);return}l.set(!0);function N(){p=new AbortController;let K=p.signal;Promise.all(r.map(B=>B(E,K))).then(B=>{if(K.aborted||x)return;let G=B.filter(qt=>qt!==void 0);c.set(G.length===0?i:G),l.set(!1),p=null}).catch(B=>{K.aborted||x||(c.set([String(B)]),l.set(!1),p=null)})}o===0?N():m=setTimeout(()=>{m=null,N()},o)}function S(){let E=t.get(),N=g(E);a.set(N),b(E)}let v=Kt([t],()=>(S(),()=>h()));function D(){S()}let x=!1;function C(){x||(x=!0,h(),v())}return{error:f,errors:u,valid:d,validating:l,validate:D,dispose:C}}var Se=class extends Error{constructor(){super("Circuit breaker is open"),this.name="CircuitOpenError"}};function Wt(t,e){let n=e?.onOpen??"skip";return r=>{let o=T(t.state,{name:"breaker:state",equals:Object.is}),s=O(({emit:a,error:c,complete:l})=>{let u=V(r,f=>{t.canExecute()?(t.recordSuccess(),o.set(t.state),a(f)):(o.set(t.state),n==="error"&&(u.unsubscribe(),c(new Se)))},{onEnd:f=>{f!==void 0?(t.recordFailure(f),o.set(t.state),c(f)):l()}});return()=>{u.unsubscribe()}},{initial:r.get()}),i={get:()=>s.get(),source:(a,c)=>s.source(a,c),get _status(){return s._status},breakerState:o};return w.register(i,{kind:"withBreaker"}),i}}function zt(t,e){let n=e?.initialStatus??"connecting",r=T(n,{name:e?.name?`${e.name}:status`:"connectionStatus",equals:Object.is}),o=T(void 0,{name:e?.name?`${e.name}:error`:"connectionError",equals:Object.is}),s={get:()=>t.get(),source:(i,a)=>t.source(i,a),get _status(){return t._status},status:r,error:o,setConnected(){Z(()=>{o.set(void 0),r.set("connected")})},setError(i){Z(()=>{o.set(i),r.set("failed")})},setClosed(){Z(()=>{o.set(void 0),r.set("disconnected")})}};return w.register(s,{kind:"withConnectionStatus"}),s}function jt(t,e){let n=e?.name??"meta",r=T(0,{name:`${n}.count`}),o=T(void 0,{name:`${n}.lastValue`}),s=T(!1,{name:`${n}.ended`}),i=T(void 0,{name:`${n}.error`}),a=null;return t.source(k,(c,l)=>{if(c===k){a=l;return}c===A?(r.update(u=>u+1),o.set(l)):c===y&&(s.set(!0),l!==void 0&&i.set(l),a=null)}),{count:r,lastValue:o,ended:s,error:i,dispose:()=>a?.(y)}}function Ut(t,e){let n=e?.initialStatus??"pending",r=T(n,{name:"withStatus:status",equals:Object.is}),o=T(void 0,{name:"withStatus:error",equals:Object.is}),s=O(({emit:a,complete:c,error:l})=>{r.set(n),o.set(void 0);let u=V(t,f=>{r.get()==="errored"?Z(()=>{o.set(void 0),r.set("active")}):r.set("active"),a(f)},{onEnd:f=>{if(f!==void 0){let d=f instanceof Error?f:new Error(String(f));Z(()=>{o.set(d),r.set("errored")}),l(f)}else r.set("completed"),c()}});return()=>{u.unsubscribe()}},{initial:t.get(),resubscribable:!0}),i={get:()=>t.get(),source:(a,c)=>s.source(a,c),get _status(){return s._status},status:r,error:o};return w.register(i,{kind:"withStatus"}),i}0&&(module.exports={CircuitOpenError,asyncQueue,batchWriter,cancellableAction,cancellableStream,cascadingCache,checkpoint,circuitBreaker,connectionHealth,constant,countdown,dag,decorrelatedJitter,dirtyTracker,exponential,fibonacci,fifo,fileAdapter,fromAbortable,indexedDBAdapter,keyedAsync,lfu,linear,lru,memoryAdapter,random,reactiveScored,retry,scored,slidingWindow,sqliteAdapter,stateMachine,stopwatch,tieredStorage,tokenBucket,tokenTracker,track,validationPipeline,withBreaker,withConnectionStatus,withMaxAttempts,withMeta,withStatus});
@@ -1,3 +1,3 @@
1
- import{a as be}from"../chunk-F5EXEEZL.js";import{a as he}from"../chunk-ZCAW32S7.js";import{a as Se}from"../chunk-NT5AUV6U.js";import{a as se}from"../chunk-6HKVNUGH.js";import{a as me,b as N}from"../chunk-BKJEZSZY.js";import{a as G,b as ce,c as ue,d as le,e as de,f as fe,g as pe}from"../chunk-4AGPQIMR.js";import"../chunk-QSFTSBDR.js";import{a as re,b as j,c as oe,d as ie,e as ae}from"../chunk-JXOY2IAO.js";import"../chunk-2ZFSL4MA.js";import{a as A}from"../chunk-PV347CGV.js";import"../chunk-HK7DRUNM.js";import{a as B}from"../chunk-LLARZ7J7.js";import{a as ne}from"../chunk-5LLYKN4X.js";import{a as w}from"../chunk-GMLWTZFM.js";import{a as x}from"../chunk-EAK2HKAD.js";import{i as C}from"../chunk-2F6QWERG.js";import{a as k}from"../chunk-2L6223KN.js";import{B as L,d as _,e as z,f as q,r as D,s as U,t as M,v as I}from"../chunk-TUPD47IE.js";import"../chunk-I7AUKTXE.js";function ge(e){let{maxSize:r,onFlush:o}=e,a=e.maxWaitMs??null,n=e.name??"batchWriter",c=x(0,{name:`${n}.size`}),t=x(0,{name:`${n}.totalFlushed`}),i=x(!1,{name:`${n}.flushing`}),s=[],f=null,u=!1,S=!1,p=0;function d(){f!==null&&(clearTimeout(f),f=null)}function l(){if(s.length===0||S)return;S=!0;let h=s;s=[],d(),c.set(0);try{let T=o(h);T&&typeof T.then=="function"?(p++,i.set(!0),T.then(()=>{t.update(v=>v+h.length),p--,p===0&&i.set(!1)},()=>{t.update(v=>v+h.length),p--,p===0&&i.set(!1)})):t.update(v=>v+h.length)}catch{t.update(T=>T+h.length)}finally{S=!1}}function m(h){u||(s.push(h),c.set(s.length),a!==null&&s.length===1&&(f=setTimeout(()=>{f=null,l()},a)),s.length>=r&&l())}function b(){l()}function g(){u=!0,d(),l()}return{add:m,flush:b,size:c,totalFlushed:t,flushing:i,stop:g}}function Te(e){let r=e?.name??"cancellableStream",o=C(void 0,{initial:e?.initial,name:r,resubscribable:!0}),a=C(void 0,{initial:!1,name:`${r}.active`,_skipInspect:!0}),n=null,c=!1;function t(){c=!0,n&&(n.unsubscribe(),n=null),a.emit(!1)}function i(s){t(),c=!1,a.emit(!0);let f=J(s,{name:r,initial:e?.initial});n=w(f,u=>o.emit(u),{onEnd:u=>{if(n=null,!c)if(a.emit(!1),u!==void 0){try{e?.onError?.(u)}catch{}o.error(u)}else e?.onComplete?.()}})}return k.register(o,{kind:"cancellableStream"}),{store:o,start:i,cancel:t,active:a}}function J(e,r){let o=C(({emit:a,complete:n,error:c})=>{let t=new AbortController,i=!1;return(async()=>{try{for await(let s of e(t.signal)){if(t.signal.aborted)return;a(s)}if(!t.signal.aborted){i=!0;try{r?.onComplete?.()}catch{}n()}}catch(s){if(!t.signal.aborted){i=!0;try{r?.onError?.(s)}catch{}c(s)}}})(),()=>{if(!i){t.abort();try{r?.onAbort?.()}catch{}}}},{initial:r?.initial,name:r?.name??"fromAbortable",resubscribable:!0});return k.register(o,{kind:"fromAbortable"}),o}function P(e){e instanceof Promise&&e.catch(()=>{})}function H(e,r){let o=new Map,a=r?.maxSize??0,n=a>0?r?.eviction??j():null,c=r?.writeThrough??!1,t=new Map;function i(d){return t.get(d)??0}function s(d){let l=i(d)+1;return t.set(d,l),l}function f(d,l,m){for(let b=0;b<m;b++){let g=e[b];g.save&&P(g.save(d,l))}}function u(){if(!(!n||a<=0))for(;n.size()>a;){let d=n.evict(1);if(d.length===0)break;for(let l of d){let m=o.get(l);if(m){let b=m.get();if(b!==void 0){let g=-1;for(let h=e.length-1;h>=0;h--)if(e[h].save){P(e[h].save(l,b)),g=h;break}for(let h=0;h<g;h++)e[h].clear&&P(e[h].clear(l))}L(m)}o.delete(l),t.delete(l)}}}function S(d,l){let m=s(d);p(d,l,0,m)}function p(d,l,m,b){if(m>=e.length)return;let g;try{g=e[m].load(d)}catch{p(d,l,m+1,b);return}g instanceof Promise?g.then(h=>{i(d)===b&&(h!==void 0?(l.set(h),f(d,h,m)):p(d,l,m+1,b))},()=>{i(d)===b&&p(d,l,m+1,b)}):g!==void 0?(l.set(g),f(d,g,m)):p(d,l,m+1,b)}return{load(d){let l=o.get(d);if(l)return n?.touch(d),l;let m=x(void 0);return o.set(d,m),n&&(n.insert(d),u()),S(d,m),m},save(d,l){if(s(d),c)for(let b of e)b.save&&P(b.save(d,l));else e[0]?.save&&P(e[0].save(d,l));let m=o.get(d);if(m)m.set(l),n?.touch(d);else{let b=x(l);o.set(d,b),n&&(n.insert(d),u())}},invalidate(d){let l=o.get(d);l&&S(d,l)},delete(d){n?.delete(d);let l=o.get(d);l&&L(l),o.delete(d),t.delete(d);for(let m of e)m.clear&&P(m.clear(d))},has(d){return o.has(d)},get size(){return o.size}}}function Q(e){e instanceof Promise&&e.catch(()=>{})}function xe(e,r,o){return a=>{let n=o?.name??`checkpoint:${e}`,c=x({recovered:!1,persistCount:0,id:e},{name:`${n}:meta`,equals:()=>!1}),t=C(({emit:s,error:f,complete:u})=>{let S=0,p=!0,d=!1,l=[],m=null,b=w(a,T=>{if(!d){l.push(T);return}S++,c.set({recovered:c.get().recovered,persistCount:S,id:e}),Q(r.save(e,T)),s(T)},{onEnd:T=>{if(!d){m={err:T};return}T!==void 0?f(T):u()}});function g(T){if(p){d=!0,c.set({recovered:T,persistCount:S,id:e});for(let v of l){if(!p)break;S++,c.set({recovered:T,persistCount:S,id:e}),Q(r.save(e,v)),s(v)}l.length=0,m&&(m.err!==void 0?f(m.err):u())}}let h=r.load(e);return h instanceof Promise?h.then(T=>{p&&(T!==void 0?(s(T),g(!0)):g(!1))},()=>{p&&g(!1)}):h!==void 0?(s(h),g(!0)):g(!1),()=>{p=!1,l.length=0,b.unsubscribe()}},{name:n,kind:"checkpoint"});k.register(t,{kind:"checkpoint"});let i=t;return Object.defineProperties(i,{meta:{value:c,enumerable:!0},clear:{value(){Q(r.clear(e))},enumerable:!0}}),i}}function ve(){let e=new Map;return{save(r,o){e.set(r,o)},load(r){return e.has(r)?e.get(r):void 0},clear(r){e.delete(r)}}}function ye(e){let{dir:r}=e;function o(a){let n=a.replace(/[^a-zA-Z0-9_-]/g,"_");return`${r}/${n}.json`}return{async save(a,n){let c=await import("fs/promises");await c.mkdir(r,{recursive:!0}),await c.writeFile(o(a),JSON.stringify(n),"utf-8")},async load(a){let n=await import("fs/promises");try{let c=await n.readFile(o(a),"utf-8");return JSON.parse(c)}catch(c){if(c?.code==="ENOENT")return;throw c}},async clear(a){let n=await import("fs/promises");try{await n.unlink(o(a))}catch(c){if(c?.code==="ENOENT")return;throw c}}}}var ke=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function Ce(e){let{db:r}=e,o=e.table??"checkpoints";if(!ke.test(o))throw new Error(`sqliteAdapter: invalid table name "${o}". Must match /^[a-zA-Z_][a-zA-Z0-9_]*$/.`);r.exec(`CREATE TABLE IF NOT EXISTS ${o} (id TEXT PRIMARY KEY, value TEXT NOT NULL)`);let a=r.prepare(`INSERT OR REPLACE INTO ${o} (id, value) VALUES (?, ?)`),n=r.prepare(`SELECT value FROM ${o} WHERE id = ?`),c=r.prepare(`DELETE FROM ${o} WHERE id = ?`);return{save(t,i){a.run(t,JSON.stringify(i))},load(t){let i=n.get(t);return i?JSON.parse(i.value):void 0},clear(t){c.run(t)}}}function we(e){let r=e?.dbName??"callbag-checkpoints",o=e?.storeName??"checkpoints",a=null,n=null;function c(){if(a)return Promise.resolve(a);if(n)return n;let s=indexedDB.open(r,1);return s.onupgradeneeded=()=>{let f=s.result;f.objectStoreNames.contains(o)||f.createObjectStore(o)},n=B(N(s)).then(f=>(a=f,a.onversionchange=()=>{a?.close(),a=null,n=null},a)),n.catch(()=>{n=null}),n}function t(s){return c().then(f=>{let u=f.transaction(o,s);return{store:u.objectStore(o),tx:u}})}async function i(s,f){try{let{store:u}=await t(s);return await B(N(f(u)))}catch(u){if(u?.name==="InvalidStateError"||a===null){a=null,n=null;let{store:S}=await t(s);return B(N(f(S)))}throw u}}return{async save(s,f){await i("readwrite",u=>u.put(f,s))},async load(s){return await i("readonly",u=>u.get(s))??void 0},async clear(s){await i("readwrite",f=>f.delete(s))}}}function Ae(e){let r=e?.failureThreshold??5,o=e?.cooldownMs??3e4,a=e?.cooldown??null,n=e?.halfOpenMax??1,c=e?.now??Date.now,t="closed",i=0,s=0,f=0,u=o,S=0;function p(){if(!a)return o;let m=a(s);return m!==null?m:o}function d(){t="open",u=p(),f=c(),S=0}return{canExecute(){return t==="closed"?!0:t==="open"?c()-f>=u?(t="half-open",S=1,!0):!1:S<n?(S++,!0):!1},recordSuccess(){t==="half-open"?(t="closed",i=0,s=0):t==="closed"&&(i=0)},recordFailure(m){if(t==="half-open"){s++,d();return}t==="closed"&&(i++,i>=r&&d())},get state(){return t},get failureCount(){return i},reset(){t="closed",i=0,s=0,S=0}}}function Ee(e){let r=e?.heartbeatMs??3e4,o=e?.timeoutMs??5e3,a=e?.backoff??null,n=e?.maxReconnects??Number.POSITIVE_INFINITY,c=e?.name??"connectionHealth",t=x("disconnected",{name:`${c}.status`}),i=x(0,{name:`${c}.reconnectCount`}),s=A([t],()=>t.get()==="connected",{name:`${c}.healthy`}),f=null,u=null,S=null,p=null,d=!1,l=!1,m=null,b;function g(){f!==null&&(clearTimeout(f),f=null),u!==null&&(clearTimeout(u),u=null),S!==null&&(clearTimeout(S),S=null),p&&(p.abort(),p=null),d=!1}function h(){l||!m||(f=setTimeout(()=>{f=null,!(l||!m)&&v()},r))}function T(){f!==null&&clearTimeout(f),h()}async function v(){if(!m||l||d)return;d=!0;let O=new AbortController;u=setTimeout(()=>{u=null,O.abort()},o);try{await m.heartbeat(O.signal),u!==null&&(clearTimeout(u),u=null),d=!1,h()}catch{if(u!==null&&(clearTimeout(u),u=null),d=!1,l)return;t.set("disconnected"),m.disconnect(),y()}}function y(){if(l||!m)return;let O=i.get();if(O>=n){t.set("failed");return}let $;if(a){let W=a(O,void 0,b);$=W!==null?W:1e3,b=$}else $=1e3;S=setTimeout(()=>{S=null,!l&&(i.update(W=>W+1),F())},$)}async function F(){if(!(l||!m)){t.set("connecting"),p=new AbortController;try{if(await m.connect(p.signal),l)return;p=null,t.set("connected"),i.set(0),b=void 0,T()}catch{if(l)return;p=null,t.set("disconnected"),y()}}}function E(O){m&&(g(),m.disconnect()),l=!1,m=O,i.set(0),b=void 0,F()}function te(){l=!0,g(),m&&m.disconnect(),m=null,t.set("disconnected")}return{status:t,healthy:s,reconnectCount:i,start:E,stop:te}}function Oe(e){let r=new Map;for(let t=0;t<e.length;t++){if(r.has(e[t].store))throw new Error(`Duplicate store in DAG: ${e[t].name??`node[${t}]`}`);r.set(e[t].store,t)}let o=new Array(e.length).fill(0),a=e.map(()=>[]);for(let t=0;t<e.length;t++){let i=e[t].deps;if(i)for(let s of i){let f=r.get(s);if(f===void 0)throw new Error(`Dependency not found in DAG for ${e[t].name??`node[${t}]`}. All deps must be declared as DAG nodes.`);a[f].push(t),o[t]++}}let n=[];for(let t=0;t<e.length;t++)o[t]===0&&n.push(t);let c=[];for(;n.length>0;){let t=n.shift();c.push(t);for(let i of a[t])o[i]--,o[i]===0&&n.push(i)}if(c.length!==e.length){let t=e.filter((i,s)=>!c.includes(s)).map((i,s)=>i.name??`node[${s}]`);throw new Error(`Cycle detected in DAG involving: ${t.join(", ")}`)}for(let t of e)if(t.name&&k.register(t.store,{name:t.name,kind:"dag-node"}),t.deps)for(let i of t.deps)k.registerEdge(i,t.store);return{order:c.map(t=>e[t].store),size:e.length}}function Me(e){let r=new Map;return o=>{let a=r.get(o);if(a)return a;let n=e(o).finally(()=>r.delete(o));return r.set(o,n),n}}function Re(e){let r=e.rate,o=e.burst??r,a=e.now??Date.now,n=o,c=a();function t(){let i=a(),s=(i-c)/1e3;n=Math.min(o,n+s*r),c=i}return{tryAcquire(i=1){return t(),n>=i?(n-=i,!0):!1},async acquire(i=1,s){if(i>o)throw new RangeError(`Cannot acquire ${i} tokens (burst capacity is ${o})`);if(s?.throwIfAborted(),t(),n>=i)return n-=i,0;let f=0;for(;n<i;){let S=(i-n)/r*1e3;f+=S,await K(S,s),t()}return n-=i,f},available(){return t(),Math.floor(n)},reset(){n=o,c=a()}}}function De(e){let r=e.max,o=e.windowMs,a=e.now??Date.now,n=[];function c(){let t=a()-o;for(;n.length>0&&n[0]<=t;)n.shift()}return{tryAcquire(t=1){if(c(),n.length+t<=r){let i=a();for(let s=0;s<t;s++)n.push(i);return!0}return!1},async acquire(t=1,i){if(t>r)throw new RangeError(`Cannot acquire ${t} slots (max capacity is ${r})`);if(i?.throwIfAborted(),c(),n.length+t<=r){let u=a();for(let S=0;S<t;S++)n.push(u);return 0}let s=0;for(;n.length+t>r;){let u=n.length+t-r,S=n[u-1],p=S!==void 0?S+o-a():o;p>0&&(s+=p,await K(p,i)),c()}let f=a();for(let u=0;u<t;u++)n.push(f);return s},available(){return c(),r-n.length},reset(){n.length=0}}}function K(e,r){return r?.aborted?Promise.reject(r.reason):B(G(Math.ceil(e),r)).then(()=>{if(r?.aborted)throw r.reason})}function Be(e){let r=typeof e=="number"?{count:e}:e,o=r.count??(r.delay?1/0:0),a=r.delay??null,n=r.while??null;return c=>{let t=x({attempt:0,pending:!1},{name:"retry:meta",equals:()=>!1});function i(f){t.set({attempt:f.attempt,lastError:f.lastError,pending:f.pending??!1})}let s=C(({emit:f,complete:u,error:S})=>{let p=0,d,l=null,m=!1,b=null,g=!1;function h(){if(g)return;l&&(l(M),l=null);let T=c.get();m&&T!==void 0&&f(T),m=!0,!g&&c.source(D,(v,y)=>{if(!g&&(v===D&&(l=y),v===1&&f(y),v===M))if(l=null,y!==void 0)if(p<o&&(n===null||n(y)))if(!a)p++,i({attempt:p,lastError:y}),h();else{let E=a(p,y,d);E!==null&&(d=E),E===null?(i({attempt:p,lastError:y}),S(y)):E<=0?(p++,i({attempt:p,lastError:y}),h()):(p++,i({attempt:p,lastError:y,pending:!0}),b=setTimeout(()=>{b=null,i({attempt:p,lastError:y,pending:!1}),h()},E))}else i({attempt:p,lastError:y}),S(y);else u()})}return h(),()=>{g=!0,b!==null&&(clearTimeout(b),b=null),l&&l(M)}},{initial:c.get()});return k.register(s,{kind:"retry"}),s.retryMeta=t,s}}function Z(e){return typeof e=="string"?[{to:e}]:Array.isArray(e)?e:[e]}function Pe(e,r,o,a){let n=a,c=e.states[r];if(c?.onExit){let i=c.onExit(n);i!==void 0&&(n=i)}let t=e.states[o];if(t?.onEnter){let i=t.onEnter(n);i!==void 0&&(n=i)}return n}function $e(e){let r=[];for(let[o,a]of Object.entries(e.states))if(a.on){for(let[n,c]of Object.entries(a.on))if(c!==void 0)for(let t of Z(c))r.push({from:o,event:n,to:t.to,guarded:!!t.guard})}return r}function R(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}function We(e,r){let o=x(r.initial),a=e,n=r.states[r.initial];if(n?.onEnter){let p=n.onEnter(a);p!==void 0&&(a=p)}let c=x(a),t=Object.freeze($e(r));function i(p,d){let l=o.get(),m=r.states[l];if(!m?.on)return!1;let b=m.on[p];if(b===void 0)return!1;let g=Z(b),h=c.get();for(let T of g){if(T.guard&&!T.guard(h,d))continue;let v=h;if(T.action){let y=T.action(h,d);y!==void 0&&(v=y)}return v=Pe(r,l,T.to,v),o.set(T.to),c.set(v),!0}return!1}function s(p){return o.get()===p}function f(){let p=o.get(),d=c.get(),l=r.states[p];l?.onExit&&l.onExit(d),o.set(r.initial);let m=r.states[r.initial];if(m?.onEnter){let b=m.onEnter(e);c.set(b!==void 0?b:e)}else c.set(e)}function u(p){let l=["stateDiagram-v2",` direction ${p?.direction??"LR"}`],m=Object.keys(r.states);for(let b of m){let g=R(b);l.push(` ${g} : ${b}`)}l.push(` [*] --> ${R(r.initial)}`);for(let b of t){let g=R(b.from),h=R(b.to),T=b.guarded?`${b.event} [guarded]`:b.event;l.push(` ${g} --> ${h} : ${T}`)}return l.join(`
1
+ import{a as be}from"../chunk-F5EXEEZL.js";import{a as he}from"../chunk-ZCAW32S7.js";import{a as Se}from"../chunk-NT5AUV6U.js";import{a as se}from"../chunk-JCENQEPP.js";import{a as me,b as N}from"../chunk-BKJEZSZY.js";import{a as G,b as ce,c as ue,d as le,e as de,f as fe,g as pe}from"../chunk-4AGPQIMR.js";import"../chunk-QSFTSBDR.js";import{a as re,b as j,c as oe,d as ie,e as ae}from"../chunk-JXOY2IAO.js";import"../chunk-2ZFSL4MA.js";import{a as A}from"../chunk-PV347CGV.js";import"../chunk-HK7DRUNM.js";import{a as B}from"../chunk-LLARZ7J7.js";import{a as ne}from"../chunk-5LLYKN4X.js";import{a as w}from"../chunk-GMLWTZFM.js";import{a as x}from"../chunk-EAK2HKAD.js";import{i as C}from"../chunk-2F6QWERG.js";import{a as k}from"../chunk-2L6223KN.js";import{B as L,d as _,e as z,f as q,r as D,s as U,t as M,v as I}from"../chunk-TUPD47IE.js";import"../chunk-I7AUKTXE.js";function ge(e){let{maxSize:r,onFlush:o}=e,a=e.maxWaitMs??null,n=e.name??"batchWriter",c=x(0,{name:`${n}.size`}),t=x(0,{name:`${n}.totalFlushed`}),i=x(!1,{name:`${n}.flushing`}),s=[],f=null,u=!1,S=!1,p=0;function d(){f!==null&&(clearTimeout(f),f=null)}function l(){if(s.length===0||S)return;S=!0;let h=s;s=[],d(),c.set(0);try{let T=o(h);T&&typeof T.then=="function"?(p++,i.set(!0),T.then(()=>{t.update(v=>v+h.length),p--,p===0&&i.set(!1)},()=>{t.update(v=>v+h.length),p--,p===0&&i.set(!1)})):t.update(v=>v+h.length)}catch{t.update(T=>T+h.length)}finally{S=!1}}function m(h){u||(s.push(h),c.set(s.length),a!==null&&s.length===1&&(f=setTimeout(()=>{f=null,l()},a)),s.length>=r&&l())}function b(){l()}function g(){u=!0,d(),l()}return{add:m,flush:b,size:c,totalFlushed:t,flushing:i,stop:g}}function Te(e){let r=e?.name??"cancellableStream",o=C(void 0,{initial:e?.initial,name:r,resubscribable:!0}),a=C(void 0,{initial:!1,name:`${r}.active`,_skipInspect:!0}),n=null,c=!1;function t(){c=!0,n&&(n.unsubscribe(),n=null),a.emit(!1)}function i(s){t(),c=!1,a.emit(!0);let f=J(s,{name:r,initial:e?.initial});n=w(f,u=>o.emit(u),{onEnd:u=>{if(n=null,!c)if(a.emit(!1),u!==void 0){try{e?.onError?.(u)}catch{}o.error(u)}else e?.onComplete?.()}})}return k.register(o,{kind:"cancellableStream"}),{store:o,start:i,cancel:t,active:a}}function J(e,r){let o=C(({emit:a,complete:n,error:c})=>{let t=new AbortController,i=!1;return(async()=>{try{for await(let s of e(t.signal)){if(t.signal.aborted)return;a(s)}if(!t.signal.aborted){i=!0;try{r?.onComplete?.()}catch{}n()}}catch(s){if(!t.signal.aborted){i=!0;try{r?.onError?.(s)}catch{}c(s)}}})(),()=>{if(!i){t.abort();try{r?.onAbort?.()}catch{}}}},{initial:r?.initial,name:r?.name??"fromAbortable",resubscribable:!0});return k.register(o,{kind:"fromAbortable"}),o}function P(e){e instanceof Promise&&e.catch(()=>{})}function H(e,r){let o=new Map,a=r?.maxSize??0,n=a>0?r?.eviction??j():null,c=r?.writeThrough??!1,t=new Map;function i(d){return t.get(d)??0}function s(d){let l=i(d)+1;return t.set(d,l),l}function f(d,l,m){for(let b=0;b<m;b++){let g=e[b];g.save&&P(g.save(d,l))}}function u(){if(!(!n||a<=0))for(;n.size()>a;){let d=n.evict(1);if(d.length===0)break;for(let l of d){let m=o.get(l);if(m){let b=m.get();if(b!==void 0){let g=-1;for(let h=e.length-1;h>=0;h--)if(e[h].save){P(e[h].save(l,b)),g=h;break}for(let h=0;h<g;h++)e[h].clear&&P(e[h].clear(l))}L(m)}o.delete(l),t.delete(l)}}}function S(d,l){let m=s(d);p(d,l,0,m)}function p(d,l,m,b){if(m>=e.length)return;let g;try{g=e[m].load(d)}catch{p(d,l,m+1,b);return}g instanceof Promise?g.then(h=>{i(d)===b&&(h!==void 0?(l.set(h),f(d,h,m)):p(d,l,m+1,b))},()=>{i(d)===b&&p(d,l,m+1,b)}):g!==void 0?(l.set(g),f(d,g,m)):p(d,l,m+1,b)}return{load(d){let l=o.get(d);if(l)return n?.touch(d),l;let m=x(void 0);return o.set(d,m),n&&(n.insert(d),u()),S(d,m),m},save(d,l){if(s(d),c)for(let b of e)b.save&&P(b.save(d,l));else e[0]?.save&&P(e[0].save(d,l));let m=o.get(d);if(m)m.set(l),n?.touch(d);else{let b=x(l);o.set(d,b),n&&(n.insert(d),u())}},invalidate(d){let l=o.get(d);l&&S(d,l)},delete(d){n?.delete(d);let l=o.get(d);l&&L(l),o.delete(d),t.delete(d);for(let m of e)m.clear&&P(m.clear(d))},has(d){return o.has(d)},get size(){return o.size}}}function Q(e){e instanceof Promise&&e.catch(()=>{})}function xe(e,r,o){return a=>{let n=o?.name??`checkpoint:${e}`,c=x({recovered:!1,persistCount:0,id:e},{name:`${n}:meta`,equals:()=>!1}),t=C(({emit:s,error:f,complete:u})=>{let S=0,p=!0,d=!1,l=[],m=null,b=w(a,T=>{if(!d){l.push(T);return}S++,c.set({recovered:c.get().recovered,persistCount:S,id:e}),Q(r.save(e,T)),s(T)},{onEnd:T=>{if(!d){m={err:T};return}T!==void 0?f(T):u()}});function g(T){if(p){d=!0,c.set({recovered:T,persistCount:S,id:e});for(let v of l){if(!p)break;S++,c.set({recovered:T,persistCount:S,id:e}),Q(r.save(e,v)),s(v)}l.length=0,m&&(m.err!==void 0?f(m.err):u())}}let h=r.load(e);return h instanceof Promise?h.then(T=>{p&&(T!==void 0?(s(T),g(!0)):g(!1))},()=>{p&&g(!1)}):h!==void 0?(s(h),g(!0)):g(!1),()=>{p=!1,l.length=0,b.unsubscribe()}},{name:n,kind:"checkpoint"});k.register(t,{kind:"checkpoint"});let i=t;return Object.defineProperties(i,{meta:{value:c,enumerable:!0},clear:{value(){Q(r.clear(e))},enumerable:!0}}),i}}function ve(){let e=new Map;return{save(r,o){e.set(r,o)},load(r){return e.has(r)?e.get(r):void 0},clear(r){e.delete(r)}}}function ye(e){let{dir:r}=e;function o(a){let n=a.replace(/[^a-zA-Z0-9_-]/g,"_");return`${r}/${n}.json`}return{async save(a,n){let c=await import("fs/promises");await c.mkdir(r,{recursive:!0}),await c.writeFile(o(a),JSON.stringify(n),"utf-8")},async load(a){let n=await import("fs/promises");try{let c=await n.readFile(o(a),"utf-8");return JSON.parse(c)}catch(c){if(c?.code==="ENOENT")return;throw c}},async clear(a){let n=await import("fs/promises");try{await n.unlink(o(a))}catch(c){if(c?.code==="ENOENT")return;throw c}}}}var ke=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function Ce(e){let{db:r}=e,o=e.table??"checkpoints";if(!ke.test(o))throw new Error(`sqliteAdapter: invalid table name "${o}". Must match /^[a-zA-Z_][a-zA-Z0-9_]*$/.`);r.exec(`CREATE TABLE IF NOT EXISTS ${o} (id TEXT PRIMARY KEY, value TEXT NOT NULL)`);let a=r.prepare(`INSERT OR REPLACE INTO ${o} (id, value) VALUES (?, ?)`),n=r.prepare(`SELECT value FROM ${o} WHERE id = ?`),c=r.prepare(`DELETE FROM ${o} WHERE id = ?`);return{save(t,i){a.run(t,JSON.stringify(i))},load(t){let i=n.get(t);return i?JSON.parse(i.value):void 0},clear(t){c.run(t)}}}function we(e){let r=e?.dbName??"callbag-checkpoints",o=e?.storeName??"checkpoints",a=null,n=null;function c(){if(a)return Promise.resolve(a);if(n)return n;let s=indexedDB.open(r,1);return s.onupgradeneeded=()=>{let f=s.result;f.objectStoreNames.contains(o)||f.createObjectStore(o)},n=B(N(s)).then(f=>(a=f,a.onversionchange=()=>{a?.close(),a=null,n=null},a)),n.catch(()=>{n=null}),n}function t(s){return c().then(f=>{let u=f.transaction(o,s);return{store:u.objectStore(o),tx:u}})}async function i(s,f){try{let{store:u}=await t(s);return await B(N(f(u)))}catch(u){if(u?.name==="InvalidStateError"||a===null){a=null,n=null;let{store:S}=await t(s);return B(N(f(S)))}throw u}}return{async save(s,f){await i("readwrite",u=>u.put(f,s))},async load(s){return await i("readonly",u=>u.get(s))??void 0},async clear(s){await i("readwrite",f=>f.delete(s))}}}function Ae(e){let r=e?.failureThreshold??5,o=e?.cooldownMs??3e4,a=e?.cooldown??null,n=e?.halfOpenMax??1,c=e?.now??Date.now,t="closed",i=0,s=0,f=0,u=o,S=0;function p(){if(!a)return o;let m=a(s);return m!==null?m:o}function d(){t="open",u=p(),f=c(),S=0}return{canExecute(){return t==="closed"?!0:t==="open"?c()-f>=u?(t="half-open",S=1,!0):!1:S<n?(S++,!0):!1},recordSuccess(){t==="half-open"?(t="closed",i=0,s=0):t==="closed"&&(i=0)},recordFailure(m){if(t==="half-open"){s++,d();return}t==="closed"&&(i++,i>=r&&d())},get state(){return t},get failureCount(){return i},reset(){t="closed",i=0,s=0,S=0}}}function Ee(e){let r=e?.heartbeatMs??3e4,o=e?.timeoutMs??5e3,a=e?.backoff??null,n=e?.maxReconnects??Number.POSITIVE_INFINITY,c=e?.name??"connectionHealth",t=x("disconnected",{name:`${c}.status`}),i=x(0,{name:`${c}.reconnectCount`}),s=A([t],()=>t.get()==="connected",{name:`${c}.healthy`}),f=null,u=null,S=null,p=null,d=!1,l=!1,m=null,b;function g(){f!==null&&(clearTimeout(f),f=null),u!==null&&(clearTimeout(u),u=null),S!==null&&(clearTimeout(S),S=null),p&&(p.abort(),p=null),d=!1}function h(){l||!m||(f=setTimeout(()=>{f=null,!(l||!m)&&v()},r))}function T(){f!==null&&clearTimeout(f),h()}async function v(){if(!m||l||d)return;d=!0;let O=new AbortController;u=setTimeout(()=>{u=null,O.abort()},o);try{await m.heartbeat(O.signal),u!==null&&(clearTimeout(u),u=null),d=!1,h()}catch{if(u!==null&&(clearTimeout(u),u=null),d=!1,l)return;t.set("disconnected"),m.disconnect(),y()}}function y(){if(l||!m)return;let O=i.get();if(O>=n){t.set("failed");return}let $;if(a){let W=a(O,void 0,b);$=W!==null?W:1e3,b=$}else $=1e3;S=setTimeout(()=>{S=null,!l&&(i.update(W=>W+1),F())},$)}async function F(){if(!(l||!m)){t.set("connecting"),p=new AbortController;try{if(await m.connect(p.signal),l)return;p=null,t.set("connected"),i.set(0),b=void 0,T()}catch{if(l)return;p=null,t.set("disconnected"),y()}}}function E(O){m&&(g(),m.disconnect()),l=!1,m=O,i.set(0),b=void 0,F()}function te(){l=!0,g(),m&&m.disconnect(),m=null,t.set("disconnected")}return{status:t,healthy:s,reconnectCount:i,start:E,stop:te}}function Oe(e){let r=new Map;for(let t=0;t<e.length;t++){if(r.has(e[t].store))throw new Error(`Duplicate store in DAG: ${e[t].name??`node[${t}]`}`);r.set(e[t].store,t)}let o=new Array(e.length).fill(0),a=e.map(()=>[]);for(let t=0;t<e.length;t++){let i=e[t].deps;if(i)for(let s of i){let f=r.get(s);if(f===void 0)throw new Error(`Dependency not found in DAG for ${e[t].name??`node[${t}]`}. All deps must be declared as DAG nodes.`);a[f].push(t),o[t]++}}let n=[];for(let t=0;t<e.length;t++)o[t]===0&&n.push(t);let c=[];for(;n.length>0;){let t=n.shift();c.push(t);for(let i of a[t])o[i]--,o[i]===0&&n.push(i)}if(c.length!==e.length){let t=e.filter((i,s)=>!c.includes(s)).map((i,s)=>i.name??`node[${s}]`);throw new Error(`Cycle detected in DAG involving: ${t.join(", ")}`)}for(let t of e)if(t.name&&k.register(t.store,{name:t.name,kind:"dag-node"}),t.deps)for(let i of t.deps)k.registerEdge(i,t.store);return{order:c.map(t=>e[t].store),size:e.length}}function Me(e){let r=new Map;return o=>{let a=r.get(o);if(a)return a;let n=e(o).finally(()=>r.delete(o));return r.set(o,n),n}}function Re(e){let r=e.rate,o=e.burst??r,a=e.now??Date.now,n=o,c=a();function t(){let i=a(),s=(i-c)/1e3;n=Math.min(o,n+s*r),c=i}return{tryAcquire(i=1){return t(),n>=i?(n-=i,!0):!1},async acquire(i=1,s){if(i>o)throw new RangeError(`Cannot acquire ${i} tokens (burst capacity is ${o})`);if(s?.throwIfAborted(),t(),n>=i)return n-=i,0;let f=0;for(;n<i;){let S=(i-n)/r*1e3;f+=S,await K(S,s),t()}return n-=i,f},available(){return t(),Math.floor(n)},reset(){n=o,c=a()}}}function De(e){let r=e.max,o=e.windowMs,a=e.now??Date.now,n=[];function c(){let t=a()-o;for(;n.length>0&&n[0]<=t;)n.shift()}return{tryAcquire(t=1){if(c(),n.length+t<=r){let i=a();for(let s=0;s<t;s++)n.push(i);return!0}return!1},async acquire(t=1,i){if(t>r)throw new RangeError(`Cannot acquire ${t} slots (max capacity is ${r})`);if(i?.throwIfAborted(),c(),n.length+t<=r){let u=a();for(let S=0;S<t;S++)n.push(u);return 0}let s=0;for(;n.length+t>r;){let u=n.length+t-r,S=n[u-1],p=S!==void 0?S+o-a():o;p>0&&(s+=p,await K(p,i)),c()}let f=a();for(let u=0;u<t;u++)n.push(f);return s},available(){return c(),r-n.length},reset(){n.length=0}}}function K(e,r){return r?.aborted?Promise.reject(r.reason):B(G(Math.ceil(e),r)).then(()=>{if(r?.aborted)throw r.reason})}function Be(e){let r=typeof e=="number"?{count:e}:e,o=r.count??(r.delay?1/0:0),a=r.delay??null,n=r.while??null;return c=>{let t=x({attempt:0,pending:!1},{name:"retry:meta",equals:()=>!1});function i(f){t.set({attempt:f.attempt,lastError:f.lastError,pending:f.pending??!1})}let s=C(({emit:f,complete:u,error:S})=>{let p=0,d,l=null,m=!1,b=null,g=!1;function h(){if(g)return;l&&(l(M),l=null);let T=c.get();m&&T!==void 0&&f(T),m=!0,!g&&c.source(D,(v,y)=>{if(!g&&(v===D&&(l=y),v===1&&f(y),v===M))if(l=null,y!==void 0)if(p<o&&(n===null||n(y)))if(!a)p++,i({attempt:p,lastError:y}),h();else{let E=a(p,y,d);E!==null&&(d=E),E===null?(i({attempt:p,lastError:y}),S(y)):E<=0?(p++,i({attempt:p,lastError:y}),h()):(p++,i({attempt:p,lastError:y,pending:!0}),b=setTimeout(()=>{b=null,i({attempt:p,lastError:y,pending:!1}),h()},E))}else i({attempt:p,lastError:y}),S(y);else u()})}return h(),()=>{g=!0,b!==null&&(clearTimeout(b),b=null),l&&l(M)}},{initial:c.get()});return k.register(s,{kind:"retry"}),s.retryMeta=t,s}}function Z(e){return typeof e=="string"?[{to:e}]:Array.isArray(e)?e:[e]}function Pe(e,r,o,a){let n=a,c=e.states[r];if(c?.onExit){let i=c.onExit(n);i!==void 0&&(n=i)}let t=e.states[o];if(t?.onEnter){let i=t.onEnter(n);i!==void 0&&(n=i)}return n}function $e(e){let r=[];for(let[o,a]of Object.entries(e.states))if(a.on){for(let[n,c]of Object.entries(a.on))if(c!==void 0)for(let t of Z(c))r.push({from:o,event:n,to:t.to,guarded:!!t.guard})}return r}function R(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}function We(e,r){let o=x(r.initial),a=e,n=r.states[r.initial];if(n?.onEnter){let p=n.onEnter(a);p!==void 0&&(a=p)}let c=x(a),t=Object.freeze($e(r));function i(p,d){let l=o.get(),m=r.states[l];if(!m?.on)return!1;let b=m.on[p];if(b===void 0)return!1;let g=Z(b),h=c.get();for(let T of g){if(T.guard&&!T.guard(h,d))continue;let v=h;if(T.action){let y=T.action(h,d);y!==void 0&&(v=y)}return v=Pe(r,l,T.to,v),o.set(T.to),c.set(v),!0}return!1}function s(p){return o.get()===p}function f(){let p=o.get(),d=c.get(),l=r.states[p];l?.onExit&&l.onExit(d),o.set(r.initial);let m=r.states[r.initial];if(m?.onEnter){let b=m.onEnter(e);c.set(b!==void 0?b:e)}else c.set(e)}function u(p){let l=["stateDiagram-v2",` direction ${p?.direction??"LR"}`],m=Object.keys(r.states);for(let b of m){let g=R(b);l.push(` ${g} : ${b}`)}l.push(` [*] --> ${R(r.initial)}`);for(let b of t){let g=R(b.from),h=R(b.to),T=b.guarded?`${b.event} [guarded]`:b.event;l.push(` ${g} --> ${h} : ${T}`)}return l.join(`
2
2
  `)}function S(p){let l=[`direction: ${p?.direction??"right"}`,""],m=Object.keys(r.states);for(let b of m){let g=R(b),T=b===r.initial?`${b} (initial)`:b;l.push(`${g}: "${T}"`)}if(t.length>0){l.push("");for(let b of t){let g=R(b.from),h=R(b.to),T=b.guarded?`${b.event} [guarded]`:b.event;l.push(`${g} -> ${h}: ${T}`)}}return l.join(`
3
3
  `)}return{current:o,context:c,send:i,matches:s,reset:f,transitions:t,toMermaid:u,toD2:S}}function Ie(e){return{load:r=>e.load(r),save:(r,o)=>e.save(r,o),clear:r=>e.clear(r)}}function Ne(e,r){let o=H(e.map(Ie),{maxSize:r?.maxSize,eviction:r?.eviction});return{load:a=>o.load(a),save:(a,n)=>o.save(a,n),invalidate:a=>o.invalidate(a),delete:a=>o.delete(a),has:a=>o.has(a),get size(){return o.size},cache:o}}function Y(e,r){let o=null,a=0,n=!1,c=!1;function t(){o!=null&&(clearInterval(o),o=null)}function i(){let s=Date.now(),f=s-a;a=s,r(f)}return{start(){n||(t(),a=Date.now(),c=!0,o=setInterval(i,e))},pause(){if(n||!c)return 0;let f=Date.now()-a;return c=!1,t(),f},resume(){n||c||(a=Date.now(),c=!0,o=setInterval(i,e))},stop(){n||(c=!1,t())},get active(){return c},get disposed(){return n},dispose(){n||(n=!0,c=!1,t())}}}function Ve(e,r){let o=Math.max(1,r?.tickMs??100),a=r?.name??"countdown",c=C(({emit:t,onSignal:i})=>{let s=e,f=!0,u=Y(o,p=>{s-=p,s<=0&&(s=0,f=!1,u.stop()),t({remaining:s,active:f,expired:s<=0})});function S(){t({remaining:s,active:f,expired:s<=0})}return i(p=>{if(p===z){if(!u.active)return;let d=u.pause();d>0&&(s=Math.max(0,s-d)),f=!1,S()}else if(p===q){if(u.active||s<=0)return;u.resume(),f=!0,S()}else p===_&&(u.stop(),s=e,f=!1,S())}),S(),u.start(),()=>u.dispose()},{initial:{remaining:e,active:!1,expired:!1},name:a,kind:"countdown"});return{remaining:A([c],()=>c.get()?.remaining??e,{name:`${a}.remaining`}),active:A([c],()=>c.get()?.active??!1,{name:`${a}.active`,equals:Object.is}),expired:A([c],()=>c.get()?.expired??!1,{name:`${a}.expired`,equals:Object.is})}}function Fe(e){let r=Math.max(1,e?.tickMs??100),o=e?.name??"stopwatch",n=C(({emit:c,onSignal:t})=>{let i=0,s=!0,f=[],u=Y(r,p=>{i+=p,c({elapsed:i,active:s,laps:f})});function S(){c({elapsed:i,active:s,laps:f})}return t(p=>{if(p===z){if(!u.active)return;let d=u.pause();d>0&&(i+=d),s=!1,S()}else if(p===q){if(u.active)return;u.resume(),s=!0,S()}else p===_&&(u.stop(),i=0,s=!1,f=[],S())}),S(),u.start(),()=>u.dispose()},{initial:{elapsed:0,active:!1,laps:[]},name:o,kind:"stopwatch"});return{elapsed:A([n],()=>n.get()?.elapsed??0,{name:`${o}.elapsed`}),active:A([n],()=>n.get()?.active??!1,{name:`${o}.active`,equals:Object.is}),laps:A([n],()=>n.get()?.laps??[],{name:`${o}.laps`})}}var X=Object.freeze({promptTokens:0,completionTokens:0,totalTokens:0,cost:0,count:0});function _e(e,r){return o=>{let a=r?.name??"tokenTracker",n=i=>i==null||!Number.isFinite(i)?0:i,c=x({...X},{name:`${a}:tokens`,equals:()=>!1}),t=C(({emit:i,error:s,complete:f})=>{let u=0,S=0,p=0,d=0,l=0;c.set({...X});let m=w(o,b=>{try{let g=e(b),h=n(g.promptTokens),T=n(g.completionTokens),v=n(g.totalTokens)||h+T,y=n(g.cost);u+=h,S+=T,p+=v,d+=y,l++,c.set({promptTokens:u,completionTokens:S,totalTokens:p,cost:d,count:l})}catch{l++,c.set({promptTokens:u,completionTokens:S,totalTokens:p,cost:d,count:l})}i(b)},{onEnd:b=>{b!==void 0?s(b):f()}});return()=>{m.unsubscribe()}},{initial:o.get()});return k.register(t,{kind:"tokenTracker",name:a}),t.tokens=c,t}}var ee=Object.freeze({status:"idle",count:0});function ze(e){return r=>{let o=x({...ee},{name:e?.name?`${e.name}:meta`:"track:meta",equals:()=>!1}),a=C(({emit:n,error:c,complete:t})=>{let i=0,s;o.set({...ee});let f=w(r,u=>{i++,i===1&&(s=Date.now()),o.set({status:"active",count:i,startedAt:s}),n(u)},{onEnd:u=>{let S=s!==void 0?Date.now()-s:void 0;u!==void 0?(o.set({status:"errored",count:i,error:u,startedAt:s,duration:S}),c(u)):(o.set({status:"completed",count:i,startedAt:s,duration:S}),t())}});return()=>{f.unsubscribe()}},{initial:r.get()});return k.register(a,{kind:"track"}),a.meta=o,a}}var V=class extends Error{constructor(){super("Circuit breaker is open"),this.name="CircuitOpenError"}};function qe(e,r){let o=r?.onOpen??"skip";return a=>{let n=x(e.state,{name:"breaker:state",equals:Object.is}),c=C(({emit:i,error:s,complete:f})=>{let u=w(a,S=>{e.canExecute()?(e.recordSuccess(),n.set(e.state),i(S)):(n.set(e.state),o==="error"&&(u.unsubscribe(),s(new V)))},{onEnd:S=>{S!==void 0?(e.recordFailure(S),n.set(e.state),s(S)):f()}});return()=>{u.unsubscribe()}},{initial:a.get()}),t={get:()=>c.get(),source:(i,s)=>c.source(i,s),get _status(){return c._status},breakerState:n};return k.register(t,{kind:"withBreaker"}),t}}function Le(e,r){let o=r?.initialStatus??"connecting",a=x(o,{name:r?.name?`${r.name}:status`:"connectionStatus",equals:Object.is}),n=x(void 0,{name:r?.name?`${r.name}:error`:"connectionError",equals:Object.is}),c={get:()=>e.get(),source:(t,i)=>e.source(t,i),get _status(){return e._status},status:a,error:n,setConnected(){I(()=>{n.set(void 0),a.set("connected")})},setError(t){I(()=>{n.set(t),a.set("failed")})},setClosed(){I(()=>{n.set(void 0),a.set("disconnected")})}};return k.register(c,{kind:"withConnectionStatus"}),c}function je(e,r){let o=r?.name??"meta",a=x(0,{name:`${o}.count`}),n=x(void 0,{name:`${o}.lastValue`}),c=x(!1,{name:`${o}.ended`}),t=x(void 0,{name:`${o}.error`}),i=null;return e.source(D,(s,f)=>{if(s===D){i=f;return}s===U?(a.update(u=>u+1),n.set(f)):s===M&&(c.set(!0),f!==void 0&&t.set(f),i=null)}),{count:a,lastValue:n,ended:c,error:t,dispose:()=>i?.(M)}}export{V as CircuitOpenError,me as asyncQueue,ge as batchWriter,be as cancellableAction,Te as cancellableStream,H as cascadingCache,xe as checkpoint,Ae as circuitBreaker,Ee as connectionHealth,ce as constant,Ve as countdown,Oe as dag,fe as decorrelatedJitter,Se as dirtyTracker,le as exponential,de as fibonacci,re as fifo,ye as fileAdapter,J as fromAbortable,we as indexedDBAdapter,Me as keyedAsync,oe as lfu,ue as linear,j as lru,ve as memoryAdapter,ae as random,se as reactiveScored,Be as retry,ie as scored,De as slidingWindow,Ce as sqliteAdapter,We as stateMachine,Fe as stopwatch,Ne as tieredStorage,Re as tokenBucket,_e as tokenTracker,ze as track,he as validationPipeline,qe as withBreaker,Le as withConnectionStatus,pe as withMaxAttempts,je as withMeta,ne as withStatus};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@callbag-recharge/callbag-recharge",
3
- "version": "0.18.0",
3
+ "version": "0.19.0",
4
4
  "packageManager": "pnpm@10.32.1+sha512.a706938f0e89ac1456b6563eab4edf1d1faf3368d1191fc5c59790e96dc918e4456ab2e67d613de1043d2e8c81f87303e6b40d4ffeca9df15ef1ad567348f2be",
5
5
  "description": "Reactive state management with streaming operators, glitch-free diamond resolution, and an inspectable graph. 6 primitives, 60+ operators, framework-agnostic. Supports LLM token streaming, edge AI orchestration, durable workflows, and agentic memory.",
6
6
  "type": "module",
@@ -339,8 +339,7 @@
339
339
  "test": "vitest run",
340
340
  "test:watch": "vitest",
341
341
  "bench": "vitest bench",
342
- "bench:core": "vitest bench src/__bench__/core.bench.ts",
343
- "bench:compare": "vitest bench src/__bench__/compare.bench.ts",
342
+ "bench:core": "vitest bench src/__bench__/compare.bench.ts",
344
343
  "bench:data": "vitest bench src/__bench__/data-algorithms.bench.ts",
345
344
  "lint": "biome check .",
346
345
  "lint:fix": "biome check --write .",
@@ -1 +0,0 @@
1
- import{a as D}from"./chunk-6HKVNUGH.js";import{a as A}from"./chunk-ZJCF5NYF.js";import{a as b}from"./chunk-2ZFSL4MA.js";import{a as S}from"./chunk-PV347CGV.js";import{a as N}from"./chunk-EAK2HKAD.js";import{B as v,v as h}from"./chunk-TUPD47IE.js";function O(i){let a=i?.halfLife??864e5,d=i?.recency??1,u=i?.importance??1,t=i?.frequency??.5,m=Math.LN2/a;return(o,f)=>{let y=(f??Date.now())-o.accessedAt,l=Math.exp(-m*y),s=1-1/(1+o.accessCount);return d*l+u*o.importance+t*s}}function M(i,a,d){let u=a?.halfLife??864e5,t=a?.recency??1,m=a?.importance??1,o=a?.frequency??.5,f=(d??Date.now())-i.accessedAt,y=Math.exp(-Math.LN2/u*f),l=1-1/(1+i.accessCount);return t*y+m*i.importance+o*l}var F=0;function W(){return`mem-${++F}`}function L(i,a){let d=a?.id??W(),u=Date.now(),t={id:d,createdAt:u,updatedAt:u,accessedAt:u,accessCount:0,importance:a?.importance??.5,tags:new Set(a?.tags)},m=N(i,{name:`mem:${d}:content`}),o=N(t,{name:`mem:${d}:meta`,equals:()=>!1}),f={},y=S([o],()=>M(o.get(),f),{name:`mem:${d}:score`});return{id:d,content:m,meta:o,scoreStore:y,touch(){let s=Date.now();o.update(c=>({...c,accessedAt:s,accessCount:c.accessCount+1}))},tag(...s){o.update(c=>{let p=new Set(c.tags);for(let T of s)p.add(T);return{...c,tags:p,updatedAt:Date.now()}})},untag(...s){o.update(c=>{let p=new Set(c.tags);for(let T of s)p.delete(T);return{...c,tags:p,updatedAt:Date.now()}})},setImportance(s){o.update(c=>({...c,importance:Math.max(0,Math.min(1,s)),updatedAt:Date.now()}))},update(s){h(()=>{m.set(s),o.update(c=>({...c,updatedAt:Date.now()}))})},score(s){return M(o.get(),s??f)},destroy(){v(m),v(o)}}}var z=0;function X(i){let a=++z,d=i?.maxSize??1/0,u=i?.weights??{},t=new Map,m=A(),o=new Map,f=d<1/0?D(e=>t.get(e).meta,e=>M(e,u)):null,y=N(0,{name:`collection-${a}:ver`}),l=S([y],()=>Array.from(t.values()),{name:`collection-${a}:nodes`}),s=S([y],()=>t.size,{name:`collection-${a}:size`}),c=!1;function p(){y.update(e=>e+1)}function T(e){let r=b([e.meta],()=>{let n=Array.from(e.meta.get().tags);m.update(e.id,n)});o.set(e.id,r)}function w(e){let r=o.get(e);r&&(r(),o.delete(e)),m.remove(e)}function x(){if(!f||t.size<=d)return;let e=f.evict(t.size-d);for(let r of e){let n=t.get(r);n&&(w(r),n.destroy(),t.delete(r))}}return{add(e,r){if(c)throw new Error("Collection is destroyed");let n=L(e,r);return t.set(n.id,n),T(n),f?.insert(n.id),x(),p(),n},remove(e){let r=typeof e=="string"?e:e.id,n=t.get(r);return n?(w(r),f?.delete(r),n.destroy(),t.delete(r),p(),!0):!1},get(e){return t.get(e)},has(e){return t.has(e)},nodes:l,size:s,tagIndex:m,query(e){let r=[];for(let n of t.values())e(n)&&r.push(n);return r},byTag(e){let r=m.get(e),n=[];for(let _ of r){let I=t.get(_);I&&n.push(I)}return n},topK(e,r){let n=r??u,_=Date.now(),I=Array.from(t.values()).map(g=>({node:g,score:M(g.meta.get(),n,_)}));return I.sort((g,C)=>C.score-g.score),I.slice(0,e).map(g=>g.node)},destroy(){if(!c){c=!0,f?.clear();for(let e of o.values())e();o.clear(),m.destroy(),v(y),h(()=>{for(let e of t.values())e.destroy();t.clear()})}}}}export{O as a,M as b,L as c,X as d};
@@ -1 +0,0 @@
1
- import{a as m}from"./chunk-2ZFSL4MA.js";function b(h,d=o=>o){let o=[],c=new Map,i=new Map;function u(e,n){let t=o[e],r=o[n];o[e]=r,o[n]=t,t.index=n,r.index=e}function p(e){for(;e>0;){let n=e-1>>>1;if(o[n].score<=o[e].score)break;u(e,n),e=n}}function f(e){let n=o.length;for(;;){let t=e,r=2*e+1,s=r+1;if(r<n&&o[r].score<o[t].score&&(t=r),s<n&&o[s].score<o[t].score&&(t=s),t===e)break;u(e,t),e=t}}function l(e){let n=o.length-1;if(e===n){o.pop();return}u(e,n),o.pop(),p(e),f(e)}return{touch(){},insert(e){if(c.has(e))return;let n=h(e),t={key:e,score:d(n.get()),index:o.length};o.push(t),c.set(e,t),p(t.index);let r=m([n],()=>{let s=c.get(e);if(!s)return;let a=s.score;s.score=d(n.get()),s.score<a?p(s.index):s.score>a&&f(s.index)});i.set(e,r)},delete(e){let n=c.get(e);if(!n)return;let t=i.get(e);t&&(t(),i.delete(e)),l(n.index),c.delete(e)},evict(e=1){let n=[];for(;n.length<e&&o.length>0;){let{key:t}=o[0];n.push(t);let r=i.get(t);r&&(r(),i.delete(t)),l(0),c.delete(t)}return n},size:()=>c.size,clear(){for(let e of i.values())e();i.clear(),c.clear(),o.length=0}}}export{b as a};