@callbag-recharge/callbag-recharge 0.22.0 → 0.23.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.
@@ -1 +1 @@
1
- import{a as z}from"./chunk-JCENQEPP.js";import{a as W}from"./chunk-ZJCF5NYF.js";import{a as b}from"./chunk-PV347CGV.js";import{a as E}from"./chunk-GMLWTZFM.js";import{a as A}from"./chunk-EAK2HKAD.js";import{B as S,v as w}from"./chunk-TUPD47IE.js";function k(i){let a=i?.halfLife??864e5,m=i?.recency??1,p=i?.importance??1,T=i?.frequency??.5,y=Math.LN2/a;return(t,f)=>{let l=(f??Date.now())-t.accessedAt,u=Math.exp(-y*l),s=1-1/(1+t.accessCount);return m*u+p*t.importance+T*s}}function v(i,a,m){let p=a?.halfLife??864e5,T=a?.recency??1,y=a?.importance??1,t=a?.frequency??.5,f=(m??Date.now())-i.accessedAt,l=Math.exp(-Math.LN2/p*f),u=1-1/(1+i.accessCount);return T*l+y*i.importance+t*u}var O=0;function q(){return`mem-${++O}`}function L(i,a){let m=a?.id??q(),p=Date.now(),T={id:m,createdAt:p,updatedAt:p,accessedAt:p,accessCount:0,importance:a?.importance??.5,tags:new Set(a?.tags)},y=A(i,{name:`mem:${m}:content`}),t=A(T,{name:`mem:${m}:meta`,equals:()=>!1}),f={},l=b([t],()=>v(t.get(),f),{name:`mem:${m}:score`});return{id:m,content:y,meta:t,scoreStore:l,touch(){let s=Date.now();t.update(d=>({...d,accessedAt:s,accessCount:d.accessCount+1}))},tag(...s){t.update(d=>{let h=new Set(d.tags);for(let M of s)h.add(M);return{...d,tags:h,updatedAt:Date.now()}})},untag(...s){t.update(d=>{let h=new Set(d.tags);for(let M of s)h.delete(M);return{...d,tags:h,updatedAt:Date.now()}})},setImportance(s){t.update(d=>({...d,importance:Math.max(0,Math.min(1,s)),updatedAt:Date.now()}))},update(s){w(()=>{y.set(s),t.update(d=>({...d,updatedAt:Date.now()}))})},score(s){return v(t.get(),s??f)},destroy(){S(y),S(t)}}}var P=0;function oe(i){let a=++P,m=i?.maxSize??1/0,p=i?.weights??{},T=i?.admissionPolicy,y=i?.forgetPolicy,t=new Map,f=W(),l=new Map,u=m<1/0?z(e=>t.get(e).meta,e=>v(e,p)):null,s=A(0,{name:`collection-${a}:ver`}),d=b([s],()=>Array.from(t.values()),{name:`collection-${a}:nodes`}),h=b([s],()=>t.size,{name:`collection-${a}:size`}),M=!1;function _(){s.update(e=>e+1)}function x(e){let o=Array.from(e.meta.get().tags);f.update(e.id,o);let r=E(e.meta,I=>{let n=Array.from(I.tags);f.update(e.id,n)});l.set(e.id,()=>r.unsubscribe())}function D(e){let o=l.get(e);o&&(o(),l.delete(e)),f.remove(e)}function $(){if(!u||t.size<=m)return;let e=u.evict(t.size-m);for(let o of e){let r=t.get(o);r&&(D(o),r.destroy(),t.delete(o))}}function C(){if(!y)return 0;let e=[];for(let o of t.values())y(o)&&e.push(o.id);for(let o of e){let r=t.get(o);r&&(D(o),u?.delete(o),r.destroy(),t.delete(o))}return e.length}return{add(e,o){if(M)throw new Error("Collection is destroyed");if(T){let I=Array.from(t.values()),n=T(e,I);switch(n.action){case"reject":return;case"update":{let c=t.get(n.targetId);if(!c)throw new Error(`Admission update target "${n.targetId}" not found`);return c.update(n.content),c}case"merge":{let c=t.get(n.targetId);if(!c)throw new Error(`Admission merge target "${n.targetId}" not found`);let g=n.reducer(c.content.get(),e);return c.update(g),c}default:break}}y&&C();let r=L(e,o);return t.set(r.id,r),x(r),u?.insert(r.id),$(),_(),r},remove(e){let o=typeof e=="string"?e:e.id,r=t.get(o);return r?(D(o),u?.delete(o),r.destroy(),t.delete(o),_(),!0):!1},get(e){return t.get(e)},has(e){return t.has(e)},nodes:d,size:h,tagIndex:f,query(e){let o=[];for(let r of t.values())e(r)&&o.push(r);return o},byTag(e){let o=f.get(e),r=[];for(let I of o){let n=t.get(I);n&&r.push(n)}return r},topK(e,o){let r=o??p,I=Date.now(),n=Array.from(t.values()).map(c=>({node:c,score:v(c.meta.get(),r,I)}));return n.sort((c,g)=>g.score-c.score),n.slice(0,e).map(c=>c.node)},summarize(e,o,r){if(M)throw new Error("Collection is destroyed");let I=Array.from(new Set(e)),n=[];for(let N of I){let F=t.get(N);F&&n.push(F)}if(n.length===0)throw new Error("No valid nodes to summarize");let c=o(n),g;return w(()=>{for(let N of n)D(N.id),u?.delete(N.id),N.destroy(),t.delete(N.id);y&&C(),g=L(c,r),t.set(g.id,g),x(g),u?.insert(g.id),_()}),g},gc(){if(M)throw new Error("Collection is destroyed");let e=C();return e>0&&_(),e},destroy(){if(!M){M=!0,u?.clear();for(let e of l.values())e();l.clear(),f.destroy(),w(()=>{for(let e of t.values())e.destroy();t.clear()}),S(s)}}}}export{k as a,v as b,L as c,oe as d};
1
+ import{a as $}from"./chunk-JCENQEPP.js";import{a as z}from"./chunk-ZJCF5NYF.js";import{a as b}from"./chunk-PV347CGV.js";import{a as W}from"./chunk-GMLWTZFM.js";import{a as A}from"./chunk-EAK2HKAD.js";import{B as S,v as w}from"./chunk-TUPD47IE.js";function k(i){let a=i?.halfLife??864e5,m=i?.recency??1,p=i?.importance??1,T=i?.frequency??.5,y=Math.LN2/a;return(t,f)=>{let l=(f??Date.now())-t.accessedAt,u=Math.exp(-y*l),s=1-1/(1+t.accessCount);return m*u+p*t.importance+T*s}}function v(i,a,m){let p=a?.halfLife??864e5,T=a?.recency??1,y=a?.importance??1,t=a?.frequency??.5,f=(m??Date.now())-i.accessedAt,l=Math.exp(-Math.LN2/p*f),u=1-1/(1+i.accessCount);return T*l+y*i.importance+t*u}var O=0;function q(){return`mem-${++O}`}function L(i,a){let m=a?.id??q(),p=Date.now(),T={id:m,createdAt:p,updatedAt:p,accessedAt:p,accessCount:0,importance:a?.importance??.5,tags:new Set(a?.tags)},y=A(i,{name:`mem:${m}:content`}),t=A(T,{name:`mem:${m}:meta`,equals:()=>!1}),f={},l=b([t],()=>v(t.get(),f),{name:`mem:${m}:score`});return{id:m,content:y,meta:t,scoreStore:l,touch(){let s=Date.now();t.update(d=>({...d,accessedAt:s,accessCount:d.accessCount+1}))},tag(...s){t.update(d=>{let h=new Set(d.tags);for(let M of s)h.add(M);return{...d,tags:h,updatedAt:Date.now()}})},untag(...s){t.update(d=>{let h=new Set(d.tags);for(let M of s)h.delete(M);return{...d,tags:h,updatedAt:Date.now()}})},setImportance(s){t.update(d=>({...d,importance:Math.max(0,Math.min(1,s)),updatedAt:Date.now()}))},update(s){w(()=>{y.set(s),t.update(d=>({...d,updatedAt:Date.now()}))})},score(s){return v(t.get(),s??f)},destroy(){S(y),S(t)}}}var P=0;function oe(i){let a=++P,m=i?.maxSize??1/0,p=i?.weights??{},T=i?.admissionPolicy,y=i?.forgetPolicy,t=new Map,f=z(),l=new Map,u=m<1/0?$(e=>t.get(e).meta,e=>v(e,p)):null,s=A(0,{name:`collection-${a}:ver`}),d=b([s],()=>Array.from(t.values()),{name:`collection-${a}:nodes`}),h=b([s],()=>t.size,{name:`collection-${a}:size`}),M=!1;function _(){s.update(e=>e+1)}function x(e){let o=Array.from(e.meta.get().tags);f.update(e.id,o);let r=W(e.meta,I=>{let n=Array.from(I.tags);f.update(e.id,n)});l.set(e.id,()=>r.unsubscribe())}function D(e){let o=l.get(e);o&&(o(),l.delete(e)),f.remove(e)}function F(){if(!u||t.size<=m)return;let e=u.evict(t.size-m);for(let o of e){let r=t.get(o);r&&(D(o),r.destroy(),t.delete(o))}}function C(){if(!y)return 0;let e=[];for(let o of t.values())y(o)&&e.push(o.id);for(let o of e){let r=t.get(o);r&&(D(o),u?.delete(o),r.destroy(),t.delete(o))}return e.length}return{add(e,o){if(M)throw new Error("Collection is destroyed");if(T){let I=Array.from(t.values()),n=T(e,I);switch(n.action){case"reject":return;case"update":{let c=t.get(n.targetId);if(!c)throw new Error(`Admission update target "${n.targetId}" not found`);return c.update(n.content),c}case"merge":{let c=t.get(n.targetId);if(!c)throw new Error(`Admission merge target "${n.targetId}" not found`);let g=n.reducer(c.content.get(),e);return c.update(g),c}default:break}}y&&C();let r=L(e,o);return t.set(r.id,r),x(r),u?.insert(r.id),F(),_(),r},remove(e){let o=typeof e=="string"?e:e.id,r=t.get(o);return r?(D(o),u?.delete(o),r.destroy(),t.delete(o),_(),!0):!1},get(e){return t.get(e)},has(e){return t.has(e)},nodes:d,size:h,tagIndex:f,query(e){let o=[];for(let r of t.values())e(r)&&o.push(r);return o},byTag(e){let o=f.get(e),r=[];for(let I of o){let n=t.get(I);n&&r.push(n)}return r},topK(e,o){let r=o??p,I=Date.now(),n=Array.from(t.values()).map(c=>({node:c,score:v(c.meta.get(),r,I)}));return n.sort((c,g)=>g.score-c.score),n.slice(0,e).map(c=>c.node)},summarize(e,o,r){if(M)throw new Error("Collection is destroyed");let I=Array.from(new Set(e)),n=[];for(let N of I){let E=t.get(N);E&&n.push(E)}if(n.length===0)throw new Error("No valid nodes to summarize");let c=o(n),g;return w(()=>{for(let N of n)D(N.id),u?.delete(N.id),N.destroy(),t.delete(N.id);y&&C(),g=L(c,r),t.set(g.id,g),x(g),u?.insert(g.id),F(),_()}),g},gc(){if(M)throw new Error("Collection is destroyed");let e=C();return e>0&&_(),e},destroy(){if(!M){M=!0,u?.clear();for(let e of l.values())e();l.clear(),f.destroy(),w(()=>{for(let e of t.values())e.destroy();t.clear()}),S(s)}}}}export{k as a,v as b,L as c,oe as d};
@@ -1,4 +1,4 @@
1
- "use strict";var qe=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var ct=Object.getOwnPropertyNames;var lt=Object.prototype.hasOwnProperty;var ut=(s,e)=>{for(var n in e)qe(s,n,{get:e[n],enumerable:!0})},ft=(s,e,n,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ct(e))!lt.call(s,r)&&r!==n&&qe(s,r,{get:()=>e[r],enumerable:!(t=at(e,r))||t.enumerable});return s};var dt=s=>ft(qe({},"__esModule",{value:!0}),s);var Rt={};ut(Rt,{collection:()=>rt,computeScore:()=>ie,decay:()=>st,memoryNode:()=>be,vectorIndex:()=>ot});module.exports=dt(Rt);var ve=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 t=e>>>5,r=1<<(e&31);n[t]&r||(n[t]|=r,this._v++)}}clear(e){let n=this._w;if(n===null)this._v&=~(1<<e);else{let t=e>>>5,r=1<<(e&31);n[t]&r&&(n[t]&=~r,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 O=Symbol("DIRTY"),U=Symbol("RESOLVED"),me=Symbol("SINGLE_DEP"),le=Symbol("RESET"),gt=Symbol("PAUSE"),ht=Symbol("RESUME"),ue=Symbol("TEARDOWN");function ke(s){return s===le||s===gt||s===ht||s===ue}var Ie=0,Me=1,Ae=2,Re=3,Ne=4,Le=5,H=7,ye=7<<H,pt=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function Oe(s){return pt[(s&ye)>>>H]}var M=0,C=1,v=2,D=3,Ee=0,De=[],Ye=!1;function X(s){Ee++;try{return s()}finally{if(Ee--,Ee===0&&!Ye){Ye=!0;for(let e=0;e<De.length;e++)De[e]();De.length=0,Ye=!1}}}function ae(){return Ee>0}function Ce(s){De.push(s)}var we=0,xe=[];function Fe(){we++}function $e(){if(we--,we===0){for(let s=0;s<xe.length;s++)xe[s]();xe.length=0}}function Xe(s){we>0?xe.push(s):s()}function G(s){let e=s;typeof e.complete=="function"?e.complete():typeof e._handleEnd=="function"&&e._handleEnd(void 0)}var ne=class s{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(s._explicitEnabled!==null)return s._explicitEnabled;if(s._cachedDefault!==null)return s._cachedDefault;try{s._cachedDefault=globalThis.process?.env?.NODE_ENV!=="production"}catch{s._cachedDefault=!0}return s._cachedDefault}static set enabled(e){s._explicitEnabled=e}static _depSuffix(e){if(!e?.length)return;let t=e.map(r=>s._names.get(r)??"?").join(",");return t.length>40?`${t.slice(0,37)}...`:t}static _resolveKey(e){let n=s._keys.get(e)??s._names.get(e);if(n)return n;let t=`anonymous_${s._nextId++}`;return s._keys.set(e,t),t}static register(e,n){if(!s.enabled)return;n?.name&&s._names.set(e,n.name),n?.kind&&s._kinds.set(e,n.kind);let t=s._nextId++,r=n?.name;if(!(r&&!s._usedKeys.has(r)))if(r){let a=s._depSuffix(n?.deps);r=a?`${r}(${a})`:`${r}_${t}`,s._usedKeys.has(r)&&(r=`${r}_${t}`)}else{let a=n?.kind??"store",i=s._depSuffix(n?.deps);r=i?`${a}(${i})`:`${a}_${t}`,s._usedKeys.has(r)&&(r=`${r}_${t}`)}s._usedKeys.add(r),s._keys.set(e,r),s._stores.add(new WeakRef(e))}static registerEdge(e,n){if(!s.enabled)return;let t=s._resolveKey(e),r=s._resolveKey(n),a=s._edges.get(t);a?a.includes(r)||a.push(r):s._edges.set(t,[r])}static getEdges(){return new Map(s._edges)}static getName(e){if(s.enabled)return s._names.get(e)}static getKind(e){return s._kinds.get(e)}static inspect(e){return{name:s._names.get(e),kind:s._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 t of s._stores){let r=t.deref();if(!r){s._stores.delete(t);continue}let a=s._resolveKey(r);n.add(a),e.set(a,s.inspect(r))}for(let[t,r]of s._edges){if(!n.has(t)){s._edges.delete(t),s._usedKeys.delete(t);continue}let a=r.filter(i=>n.has(i));a.length===0?s._edges.delete(t):a.length!==r.length&&s._edges.set(t,a)}return e}static trace(e,n){let t=null,r=e.get();return e.source(M,(a,i)=>{if(a===M&&(t=i),a===v){t=null;return}if(a===1){let f=i;if(!Object.is(f,r)){let c=r;r=f,n(f,c)}}}),()=>t?.(v)}static dumpGraph(){let e=s.graph(),n=s.getEdges(),t=new Map;for(let[i,f]of n)for(let c of f){let u=t.get(c);u?u.includes(i)||u.push(i):t.set(c,[i])}let r=[];for(let[i,f]of e){let c=t.get(i),u=n.get(i),o=c?.length?` \u2190 [${c.join(", ")}]`:"",l=u?.length?` \u2192 [${u.join(", ")}]`:"";r.push(` ${i} (${f.kind}) = ${JSON.stringify(f.value)} [${f.status??"?"}]${o}${l}`)}return[`Store Graph (${e.size} nodes):`,...r].join(`
2
- `)}static _signalLabel(e){return e===O?"DIRTY":e===U?"RESOLVED":typeof e=="symbol"?e.description??String(e):String(e)}static _observe(e,n,t){let r=null,a=!1,i=n??s.getName(e),f=[],c={values:[],signals:[],events:[],ended:!1,endError:void 0,get completedCleanly(){return c.ended&&!a},get errored(){return c.ended&&a},dirtyCount:0,resolvedCount:0,name:i,get eventLog(){return f},dispose:()=>r?.(v),reconnect:()=>(r?.(v),s._observe(e,n,t))};return e.source(M,(u,o)=>{if(u===M){r=o;return}let l=ae();u===C?(c.values.push(o),c.events.push({type:"data",data:o,inBatch:l}),f.push(o),t&&t(`[${i}] DATA:`,o)):u===D?(c.signals.push(o),c.events.push({type:"signal",data:o,inBatch:l}),f.push(s._signalLabel(o)),o===O?c.dirtyCount++:o===U&&c.resolvedCount++,t&&t(`[${i}] STATE:`,o)):u===v&&(c.ended=!0,c.endError=o,a=o!==void 0,c.events.push({type:"end",data:o,inBatch:l}),f.push(a?["END",o]:"END"),t&&t(`[${i}] END`,o!==void 0?o:""),r=null)}),c}static observe(e){return s._observe(e)}static activate(e){let n=null;return e.source(M,(t,r)=>{t===M&&(n=r),t===v&&(n=null)}),()=>n?.(v)}static tap(e,n){let t=n??`tap(${s.getName(e)??"anon"})`,r={get:()=>e.get(),source:e.source};return s.register(r,{name:t,kind:"tap"}),s.registerEdge(e,r),r}static spy(e,n){let t=n?.name??s.getName(e)??"spy",r=n?.log??console.log;return s._observe(e,t,r)}static snapshot(){let e=s.graph(),n=s.getEdges(),t=new Map;for(let i of s._stores){let f=i.deref();if(!f)continue;let c=s._annotations.get(f);c!==void 0&&t.set(s._resolveKey(f),c)}let r=[];for(let[i,f]of e){let c={name:i,kind:f.kind,value:f.value,status:f.status},u=t.get(i);u!==void 0&&(c.annotation=u),r.push(c)}let a=[];for(let[i,f]of n)for(let c of f)a.push({from:i,to:c});return{nodes:r,edges:a,trace:s.traceLog()}}static toMermaid(e){let n=e?.direction??"TD",t=s.snapshot(),r=[`graph ${n}`],a={SETTLED:":::settled",DIRTY:":::dirty",ERRORED:":::errored",COMPLETED:":::completed"},i=new Map;function f(o){let l=o.replace(/[^a-zA-Z0-9_]/g,"_"),g=i.get(l);return g===void 0?(i.set(l,1),l):(i.set(l,g+1),`${l}__${g}`)}let c=new Map;function u(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=f(o.name);c.set(o.name,l);let g=`${o.name} (${o.kind}) = ${u(o.value)}`,S=a[o.status??""]??"";r.push(` ${l}["${g}"]${S}`)}for(let o of t.edges){let l=c.get(o.from)??f(o.from),g=c.get(o.to)??f(o.to);r.push(` ${l} --> ${g}`)}return r.push(""),r.push(" classDef settled fill:#d4edda,stroke:#28a745"),r.push(" classDef dirty fill:#fff3cd,stroke:#ffc107"),r.push(" classDef errored fill:#f8d7da,stroke:#dc3545"),r.push(" classDef completed fill:#cce5ff,stroke:#007bff"),r.join(`
3
- `)}static toD2(e){let n=e?.direction??"down",t=s.snapshot(),r=[`direction: ${n}`,""],a={state:"rectangle",derived:"hexagon",effect:"oval",producer:"rectangle",operator:"parallelogram","pipeline-step":"rectangle","pipeline-status":"diamond",checkpoint:"cylinder"},i=new Map;function f(o){let l=o.replace(/[^a-zA-Z0-9_]/g,"_"),g=i.get(l);return g===void 0?(i.set(l,1),l):(i.set(l,g+1),`${l}__${g}`)}let c=new Map;function u(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=f(o.name);c.set(o.name,l);let g=a[o.kind]??"rectangle",S=`${o.name} (${o.kind}) = ${u(o.value)}`,F=o.status?` [${o.status}]`:"";r.push(`${l}: "${S}${F}" { shape: ${g} }`)}t.edges.length>0&&r.push("");for(let o of t.edges){let l=c.get(o.from)??f(o.from),g=c.get(o.to)??f(o.to);r.push(`${l} -> ${g}`)}return r.join(`
4
- `)}static annotate(e,n){if(!s.enabled)return;s._annotations.set(e,n);let t={node:s._resolveKey(e),reason:n,timestamp:Date.now()},r=s.maxTraceEntries;r<=0||(s._traceLog.length<r?s._traceLog.push(t):(s._traceLog[s._traceHead]=t,s._traceFull=!0),s._traceHead=(s._traceHead+1)%r)}static getAnnotation(e){return s._annotations.get(e)}static traceLog(){return s._traceFull?[...s._traceLog.slice(s._traceHead),...s._traceLog.slice(0,s._traceHead)]:s._traceLog.slice(0,s._traceHead||s._traceLog.length)}static clearTrace(){s._traceLog=[],s._traceHead=0,s._traceFull=!1}static timeline(e){let n=null,t=[];return e.source(M,(r,a)=>{if(r===M){n=a;return}let i={timestamp:Date.now(),type:r===C?"data":r===D?"signal":"end",data:a,inBatch:ae()};t.push(i),r===v&&(n=null)}),{entries:t,dispose:()=>n?.(v)}}static observeDerived(e){let n=[],t=e,r=t._fn;if(typeof r!="function"||!Array.isArray(t._deps))return{...s.observe(e),evaluations:n};t._fn=()=>{let c=t._deps.map(o=>o.get()),u=r();return n.push({result:u,depValues:c,timestamp:Date.now()}),u};let a=s._observe(e),i=a.dispose;return{...a,evaluations:n,dispose:()=>{t._fn=r,i()},reconnect:()=>(t._fn=r,i(),s.observeDerived(e))}}static observeTaskState(e){let n=e.status.get(),t=[],r=null;return e.status.source(M,(a,i)=>{if(a===M){r=i;return}if(a===C){let f=i;if(f!==n){let c={from:n,to:f,timestamp:Date.now()};f==="error"&&(c.error=e.error.get()),t.push(c),n=f}}a===v&&(r=null)}),{transitions:t,get currentStatus(){return e.status.get()},dispose:()=>{r?.(v)}}}static causalityTrace(e){let n=[],t=e,r=t._fn;if(typeof r!="function"||!Array.isArray(t._deps))return{...s.observe(e),causality:n};let a=t._deps,i=a.map(o=>o.get());t._fn=()=>{let o=a.map(S=>S.get()),l=r(),g=-1;for(let S=0;S<a.length;S++)if(!Object.is(o[S],i[S])){g=S;break}return n.push({result:l,triggerDepIndex:g,triggerDepName:g>=0?s.getName(a[g]):void 0,depValues:o,timestamp:Date.now()}),i=o,l};let f=s._observe(e),c=f.dispose;return{...f,causality:n,dispose:()=>{t._fn=r,c()},reconnect:()=>(t._fn=r,c(),s.causalityTrace(e))}}static _reset(){s._names=new WeakMap,s._kinds=new WeakMap,s._keys=new WeakMap,s._stores=new Set,s._edges=new Map,s._usedKeys=new Set,s._nextId=0,s._explicitEnabled=null,s._cachedDefault=null,s._annotations=new WeakMap,s._traceLog=[],s._traceHead=0,s._traceFull=!1,s.maxTraceEntries=1e3}};var ce=1,fe=2,de=4,Y=8,se=32,Qe=64,_t=Ie<<H,ge=Me<<H,Be=Ae<<H,Se=Re<<H,mt=Ne<<H,Pe=Le<<H,P=ye,Ve=class{_output=null;_upstreamTalkbacks=[];_cachedValue;_flags;_dirtyDeps;_eqFn;_deps;_fn;get _status(){return Oe(this._flags)}constructor(e,n,t,r){this._deps=e,this._fn=n,this._eqFn=t?.equals,this._flags=r?Qe:0,this._dirtyDeps=new ve(e.length),this.source=this.source.bind(this),ne.register(this,{kind:"derived",...t,deps:e});for(let a of e)ne.registerEdge(a,this)}_dispatch(e,n){let t=this._output;if(t)if(this._flags&se)for(let r of t)r(e,n);else t(e,n)}_recompute(){let e;try{e=this._fn()}catch(n){this._handleEnd(n);return}if(this._eqFn&&this._flags&ce&&this._eqFn(this._cachedValue,e)){this._flags=this._flags&~P|Se,this._dispatch(D,U);return}this._cachedValue=e,this._flags=(this._flags|ce)&~P|Be,this._dispatch(C,this._cachedValue)}_recomputeIdentity(e){if(!(this._flags&Y)){if(this._eqFn&&this._flags&ce&&this._eqFn(this._cachedValue,e)){this._flags=this._flags&~P|Se,this._dispatch(D,U);return}this._cachedValue=e,this._flags=(this._flags|ce)&~P|Be,this._dispatch(C,e)}}_lazyConnect(){if(!(this._flags&(fe|Y))){try{this._cachedValue=this._fn()}catch(e){this._handleEnd(e);return}this._flags=(this._flags|ce)&~P|Be,Fe(),this._connectUpstream(),this._flags&Y||(this._flags|=fe),$e()}}_connectUpstream(){this._upstreamTalkbacks.length=0,this._deps.length===1?this._flags&Qe?this._connectSingleDepIdentity():this._connectSingleDep():this._connectMultiDep()}_connectSingleDep(){let e=!1;this._deps[0].source(M,(n,t)=>{if(n===M){this._upstreamTalkbacks.push(t),t(D,me);return}if(!(this._flags&Y))if(n===D)if(t===O){if(e)return;e=!0,this._flags=this._flags&~P|ge,this._dispatch(D,O)}else t===U?e&&(e=!1,this._flags=this._flags&~P|Se,this._dispatch(D,U)):this._dispatch(D,t);else n===C?e?(e=!1,this._recompute()):(this._flags=this._flags&~P|ge,this._dispatch(D,O),this._recompute()):n===v&&this._handleEnd(t)})}_connectSingleDepIdentity(){let e=!1;this._deps[0].source(M,(n,t)=>{if(n===M){this._upstreamTalkbacks.push(t),t(D,me);return}this._flags&Y||(n===D?t===O?(e=!0,this._flags=this._flags&~P|ge,this._dispatch(D,O)):t===U?e&&(e=!1,this._flags=this._flags&~P|Se,this._dispatch(D,U)):this._dispatch(D,t):n===C?e?(e=!1,this._recomputeIdentity(t)):(this._flags=this._flags&~P|ge,this._dispatch(D,O),this._recomputeIdentity(t)):n===v&&this._handleEnd(t))})}_connectMultiDep(){for(let e=0;e<this._deps.length&&!(this._flags&Y);e++){let n=e;this._deps[n].source(M,(t,r)=>{if(t===M){this._upstreamTalkbacks.push(r);return}if(!(this._flags&Y))if(t===D)if(r===O){let a=this._dirtyDeps.empty();this._dirtyDeps.set(n),a&&(this._flags&=~de,this._flags=this._flags&~P|ge,this._dispatch(D,O))}else r===U?this._dirtyDeps.test(n)&&(this._dirtyDeps.clear(n),this._dirtyDeps.empty()&&(this._flags&de?this._recompute():(this._flags=this._flags&~P|Se,this._dispatch(D,U)))):this._dispatch(D,r);else t===C?this._dirtyDeps.test(n)?(this._dirtyDeps.clear(n),this._flags|=de,this._dirtyDeps.empty()&&this._recompute()):this._dirtyDeps.empty()?(this._flags=this._flags&~P|ge,this._dispatch(D,O),this._recompute()):this._flags|=de:t===v&&this._handleEnd(r)})}}_handleEnd(e){this._flags|=Y,this._flags=this._flags&~P|(e!==void 0?Pe:mt),e!==void 0&&(this._cachedValue=e);for(let r of this._upstreamTalkbacks)r(v);this._upstreamTalkbacks=[],this._flags&=~fe,this._dirtyDeps.reset();let n=this._output,t=this._flags&se;if(this._output=null,this._flags&=~se,n)if(t)for(let r of n)try{e!==void 0?r(v,e):r(v)}catch{}else e!==void 0?n(v,e):n(v)}_disconnectUpstream(){for(let e of this._upstreamTalkbacks)e(v);this._upstreamTalkbacks.length=0,this._flags&=~(fe|de),this._flags=this._flags&~P|_t,this._dirtyDeps.reset()}_handleLifecycleSignal(e){if(!(this._flags&Y)){if(e===ue){for(let n of this._upstreamTalkbacks)n(D,ue);this._handleEnd(void 0);return}e===le&&(this._flags&=~(ce|de),this._dirtyDeps.reset());for(let n of this._upstreamTalkbacks)n(D,e)}}get(){if(this._flags&fe)return this._cachedValue;if(this._flags&Y){if((this._flags&P)===Pe)throw this._cachedValue;return this._cachedValue}let e=this._fn();return this._cachedValue=e,this._flags|=ce,e}source(e,n){if(e===M){let t=n;if(this._flags&Y){let r=(this._flags&P)===Pe;t(M,a=>{}),r?t(v,this._cachedValue):t(v);return}if(!(this._flags&fe)&&(this._lazyConnect(),this._flags&Y)){let r=(this._flags&P)===Pe;t(M,a=>{}),r?t(v,this._cachedValue):t(v);return}if(this._output===null)this._output=t;else if(this._flags&se)this._output.add(t);else{let r=new Set;r.add(this._output),r.add(t),this._output=r,this._flags|=se}t(M,(r,a)=>{if(r===C&&t(C,this._cachedValue),r===D&&ke(a)){this._handleLifecycleSignal(a);return}if(r===v){if(this._output===null)return;if(this._flags&se){let i=this._output;i.delete(t),i.size===1?(this._output=i.values().next().value,this._flags&=~se):i.size===0&&(this._output=null,this._flags&=~se,this._disconnectUpstream())}else this._output===t&&(this._output=null,this._disconnectUpstream())}})}}};function J(s,e,n){return new Ve(s,e,n)}(e=>{function s(n,t){return new Ve([n],()=>n.get(),t,!0)}e.from=s})(J||={});var ze=1,Z=64,B=2,he=4,et=8,tt=16,re=32,Q=1024,z=ye,pe=Me<<H,Te=Ae<<H,He=Ie<<H,yt=Ne<<H,St=Le<<H,Tt=Re<<H,We=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 t=0;n?.autoDirty!==!1&&(t|=he),n?.resetOnTeardown&&(t|=et),n?.resubscribable&&(t|=tt),this._flags=t,this.source=this.source.bind(this),this.emit=this.emit.bind(this),n?._skipInspect||ne.register(this,{kind:"producer",...n})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(e,n){let t=this._output;if(t)if(this._flags&Z)for(let r of t)r(e,n);else t(e,n)}emit(e){this._flags&B||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(ae()?this._flags&re||(this._flags|=re,this._flags&he&&(this._flags=this._flags&~z|pe,this._dispatch(D,O)),Ce(()=>{this._flags&=~re,this._flags=this._flags&~z|Te,this._dispatch(C,this._value)})):(this._flags&he&&!(this._flags&Q)&&(this._flags=this._flags&~z|pe,this._dispatch(D,O)),this._flags=this._flags&~z|Te,this._dispatch(C,this._value))))}signal(e){this._flags&B||!this._output||(e===O?this._flags=this._flags&~z|pe:e===U&&(this._flags=this._flags&~z|Tt),this._dispatch(D,e))}complete(){if(this._flags&B)return;this._flags=(this._flags|B)&~z|yt;let e=this._output,n=this._flags&Z;if(this._output=null,this._flags&=~(Z|Q),this._singleDepCount=0,this._stop(),e)if(n)for(let t of e)t(v);else e(v)}error(e){if(this._flags&B)return;this._flags=(this._flags|B)&~z|St;let n=this._output,t=this._flags&Z;if(this._output=null,this._flags&=~(Z|Q),this._singleDepCount=0,this._stop(),n)if(t)for(let r of n)r(v,e);else n(v,e)}_start(){if(this._flags&ze||!this._fn)return;this._flags|=ze,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&ze&&(this._flags&=~ze,this._onLifecycleSignal=void 0,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&et&&(this._value=this._initial),this._flags&B||(this._flags=this._flags&~z|He))}_handleLifecycleSignal(e){if(!(this._flags&B)){if(e===ue){this._onLifecycleSignal?.(e),this.complete();return}e===le&&(this._value=this._initial,this._flags&=~re),this._onLifecycleSignal?.(e),e===le&&this.emit(this._initial)}}source(e,n){if(e===M){let t=n;if(this._flags&B)if(this._flags&tt&&this._output===null)this._flags=this._flags&~(B|z)|He;else{t(M,a=>{}),t(v);return}if(this._output===null)this._output=t;else if(this._flags&Z)this._output.add(t);else{let a=new Set;a.add(this._output),a.add(t),this._output=a,this._flags=(this._flags|Z)&~Q}let r=!1;t(M,(a,i)=>{if(a===C&&t(C,this._value),a===D){i===me&&!r?(r=!0,this._singleDepCount++,this._flags&Z||(this._flags|=Q)):ke(i)&&this._handleLifecycleSignal(i);return}if(a===v){if(r&&(r=!1,this._singleDepCount--),this._output===null)return;if(this._flags&Z){let f=this._output;f.delete(t),f.size===1?(this._output=f.values().next().value,this._flags&=~Z,this._singleDepCount>0&&(this._flags|=Q)):f.size===0&&(this._output=null,this._flags&=~(Z|Q),this._singleDepCount=0,this._flags=this._flags&~z|He,this._stop())}else this._output===t&&(this._output=null,this._flags&=~Q,this._singleDepCount=0,this._flags=this._flags&~z|He,this._stop())}}),Xe(()=>this._start())}}};var Ge=class extends We{constructor(e,n){super(void 0,{initial:e,autoDirty:!0,equals:n?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),ne.register(this,{kind:"state",...n})}get(){return this._value}set(e){this._flags&B||this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(ae()?this._flags&re||(this._flags|=re,this._flags&he&&(this._flags=this._flags&~z|pe,this._dispatch(D,O)),Ce(()=>{this._flags&=~re,this._flags=this._flags&~z|Te,this._dispatch(C,this._value)})):(this._flags&he&&!(this._flags&Q)&&(this._flags=this._flags&~z|pe,this._dispatch(D,O)),this._flags=this._flags&~z|Te,this._dispatch(C,this._value))))}update(e){this.set(e(this._value))}};function ee(s,e){return new Ge(s,e)}function je(s,e,n){let t=null;Fe(),s.source(M,(a,i)=>{if(a===M&&(t=i),a===v){t=null,n?.onEnd?.(i);return}if(a===1){let f=i,c=r;r=f,e(f,c)}});let r;try{r=s.get()}catch{}return $e(),{unsubscribe(){t?.(v),t=null},signal(a){t?.(D,a)}}}var bt=0;Ue.from=function(e){let n=Ue({id:e.id});for(let[t,r]of Object.entries(e.index))for(let a of r)n.add(a,[t]);return n};function Ue(s){let e=++bt,n=s?.id??`ridx-${e}`,t=new Map,r=new Map,a=new Map,i=new Map,f=ee(0,{name:`${n}:ver`}),c=J([f],()=>Array.from(t.keys()),{name:`${n}:keys`}),u=J([f],()=>t.size,{name:`${n}:size`}),o=!1,l=Object.freeze(new Set);function g(h){let m=a.get(h);return m||(m=ee(t.get(h)??new Set,{name:`${n}:${h}`,equals:()=>!1}),a.set(h,m)),m}function S(h){let m=a.get(h);if(m){let w=t.get(h);m.set(w?new Set(w):new Set)}}function F(h,m){let w=t.get(m),d=!w;return w||(w=new Set,t.set(m,w)),w.add(h),d}function K(h,m){let w=t.get(m);return w?(w.delete(h),w.size===0?(t.delete(m),!0):!1):!1}return{get id(){return n},get version(){return f.get()},get(h){let m=t.get(h);return m?Object.freeze(new Set(m)):l},has(h){let m=t.get(h);return m!==void 0&&m.size>0},keys(){return Array.from(t.keys())},get size(){return t.size},select(h){let m=i.get(h);if(m)return m;let w=g(h);return m=J([w],()=>w.get(),{name:`${n}:${h}:select`}),i.set(h,m),m},keysStore:c,sizeStore:u,add(h,m){if(o||m.length===0)return;let w=r.get(h);w||(w=new Set,r.set(h,w)),X(()=>{let d=!1;for(let _ of m)w.add(_),F(h,_)&&(d=!0),S(_);d&&f.update(_=>_+1)})},remove(h){if(o)return;let m=r.get(h);m&&X(()=>{let w=!1;for(let d of m)K(h,d)&&(w=!0),S(d);r.delete(h),w&&f.update(d=>d+1)})},update(h,m){if(o)return;let w=r.get(h),d=new Set(m);X(()=>{let _=!1;if(w)for(let L of w)d.has(L)||(K(h,L)&&(_=!0),S(L));let x=r.get(h);x||(x=new Set,r.set(h,x)),x.clear();for(let L of m)x.add(L),F(h,L)&&(_=!0),S(L);_&&f.update(L=>L+1)})},clear(){t.size!==0&&X(()=>{t.clear(),r.clear();for(let h of a.values())h.set(new Set);f.update(h=>h+1)})},snapshot(){let h={};for(let[m,w]of t)h[m]=Array.from(w);return{type:"reactiveIndex",id:n,version:f.get(),index:h}},destroy(){if(!o){o=!0,t.clear(),r.clear();for(let h of a.values())G(h);a.clear();for(let h of i.values())G(h);i.clear(),G(f)}}}}function nt(s,e=n=>n){let n=[],t=new Map,r=new Map;function a(u,o){let l=n[u],g=n[o];n[u]=g,n[o]=l,l.index=o,g.index=u}function i(u){for(;u>0;){let o=u-1>>>1;if(n[o].score<=n[u].score)break;a(u,o),u=o}}function f(u){let o=n.length;for(;;){let l=u,g=2*u+1,S=g+1;if(g<o&&n[g].score<n[l].score&&(l=g),S<o&&n[S].score<n[l].score&&(l=S),l===u)break;a(u,l),u=l}}function c(u){let o=n.length-1;if(u===o){n.pop();return}a(u,o),n.pop(),i(u),f(u)}return{touch(){},insert(u){if(t.has(u))return;let o=s(u),l={key:u,score:e(o.get()),index:n.length};n.push(l),t.set(u,l),i(l.index);let g=je(o,S=>{let F=t.get(u);if(!F)return;let K=F.score;F.score=e(S),F.score<K?i(F.index):F.score>K&&f(F.index)});r.set(u,()=>g.unsubscribe())},delete(u){let o=t.get(u);if(!o)return;let l=r.get(u);l&&(l(),r.delete(u)),c(o.index),t.delete(u)},evict(u=1){let o=[];for(;o.length<u&&n.length>0;){let{key:l}=n[0];o.push(l);let g=r.get(l);g&&(g(),r.delete(l)),c(0),t.delete(l)}return o},size:()=>t.size,clear(){for(let u of r.values())u();r.clear(),t.clear(),n.length=0}}}function st(s){let e=s?.halfLife??864e5,n=s?.recency??1,t=s?.importance??1,r=s?.frequency??.5,a=Math.LN2/e;return(i,f)=>{let c=(f??Date.now())-i.accessedAt,u=Math.exp(-a*c),o=1-1/(1+i.accessCount);return n*u+t*i.importance+r*o}}function ie(s,e,n){let t=e?.halfLife??864e5,r=e?.recency??1,a=e?.importance??1,i=e?.frequency??.5,f=(n??Date.now())-s.accessedAt,c=Math.exp(-Math.LN2/t*f),u=1-1/(1+s.accessCount);return r*c+a*s.importance+i*u}var vt=0;function Et(){return`mem-${++vt}`}function be(s,e){let n=e?.id??Et(),t=Date.now(),r={id:n,createdAt:t,updatedAt:t,accessedAt:t,accessCount:0,importance:e?.importance??.5,tags:new Set(e?.tags)},a=ee(s,{name:`mem:${n}:content`}),i=ee(r,{name:`mem:${n}:meta`,equals:()=>!1}),f={},c=J([i],()=>ie(i.get(),f),{name:`mem:${n}:score`});return{id:n,content:a,meta:i,scoreStore:c,touch(){let o=Date.now();i.update(l=>({...l,accessedAt:o,accessCount:l.accessCount+1}))},tag(...o){i.update(l=>{let g=new Set(l.tags);for(let S of o)g.add(S);return{...l,tags:g,updatedAt:Date.now()}})},untag(...o){i.update(l=>{let g=new Set(l.tags);for(let S of o)g.delete(S);return{...l,tags:g,updatedAt:Date.now()}})},setImportance(o){i.update(l=>({...l,importance:Math.max(0,Math.min(1,o)),updatedAt:Date.now()}))},update(o){X(()=>{a.set(o),i.update(l=>({...l,updatedAt:Date.now()}))})},score(o){return ie(i.get(),o??f)},destroy(){G(a),G(i)}}}var Dt=0;function rt(s){let e=++Dt,n=s?.maxSize??1/0,t=s?.weights??{},r=s?.admissionPolicy,a=s?.forgetPolicy,i=new Map,f=Ue(),c=new Map,u=n<1/0?nt(d=>i.get(d).meta,d=>ie(d,t)):null,o=ee(0,{name:`collection-${e}:ver`}),l=J([o],()=>Array.from(i.values()),{name:`collection-${e}:nodes`}),g=J([o],()=>i.size,{name:`collection-${e}:size`}),S=!1;function F(){o.update(d=>d+1)}function K(d){let _=Array.from(d.meta.get().tags);f.update(d.id,_);let x=je(d.meta,L=>{let N=Array.from(L.tags);f.update(d.id,N)});c.set(d.id,()=>x.unsubscribe())}function te(d){let _=c.get(d);_&&(_(),c.delete(d)),f.remove(d)}function h(){if(!u||i.size<=n)return;let d=u.evict(i.size-n);for(let _ of d){let x=i.get(_);x&&(te(_),x.destroy(),i.delete(_))}}function m(){if(!a)return 0;let d=[];for(let _ of i.values())a(_)&&d.push(_.id);for(let _ of d){let x=i.get(_);x&&(te(_),u?.delete(_),x.destroy(),i.delete(_))}return d.length}return{add(d,_){if(S)throw new Error("Collection is destroyed");if(r){let L=Array.from(i.values()),N=r(d,L);switch(N.action){case"reject":return;case"update":{let $=i.get(N.targetId);if(!$)throw new Error(`Admission update target "${N.targetId}" not found`);return $.update(N.content),$}case"merge":{let $=i.get(N.targetId);if(!$)throw new Error(`Admission merge target "${N.targetId}" not found`);let p=N.reducer($.content.get(),d);return $.update(p),$}default:break}}a&&m();let x=be(d,_);return i.set(x.id,x),K(x),u?.insert(x.id),h(),F(),x},remove(d){let _=typeof d=="string"?d:d.id,x=i.get(_);return x?(te(_),u?.delete(_),x.destroy(),i.delete(_),F(),!0):!1},get(d){return i.get(d)},has(d){return i.has(d)},nodes:l,size:g,tagIndex:f,query(d){let _=[];for(let x of i.values())d(x)&&_.push(x);return _},byTag(d){let _=f.get(d),x=[];for(let L of _){let N=i.get(L);N&&x.push(N)}return x},topK(d,_){let x=_??t,L=Date.now(),N=Array.from(i.values()).map($=>({node:$,score:ie($.meta.get(),x,L)}));return N.sort(($,p)=>p.score-$.score),N.slice(0,d).map($=>$.node)},summarize(d,_,x){if(S)throw new Error("Collection is destroyed");let L=Array.from(new Set(d)),N=[];for(let T of L){let b=i.get(T);b&&N.push(b)}if(N.length===0)throw new Error("No valid nodes to summarize");let $=_(N),p;return X(()=>{for(let T of N)te(T.id),u?.delete(T.id),T.destroy(),i.delete(T.id);a&&m(),p=be($,x),i.set(p.id,p),K(p),u?.insert(p.id),F()}),p},gc(){if(S)throw new Error("Collection is destroyed");let d=m();return d>0&&F(),d},destroy(){if(!S){S=!0,u?.clear();for(let d of c.values())d();c.clear(),f.destroy(),X(()=>{for(let d of i.values())d.destroy();i.clear()}),G(o)}}}}function xt(s,e){let n=0,t=0,r=0;for(let i=0;i<s.length;i++)n+=s[i]*e[i],t+=s[i]*s[i],r+=e[i]*e[i];let a=Math.sqrt(t)*Math.sqrt(r);return a===0?1:1-n/a}function wt(s,e){let n=0;for(let t=0;t<s.length;t++){let r=s[t]-e[t];n+=r*r}return Math.sqrt(n)}function kt(s,e){let n=0;for(let t=0;t<s.length;t++)n+=s[t]*e[t];return-n}var It={cosine:xt,euclidean:wt,dotProduct:kt};function Je(s,e){s.push(e);let n=s.length-1;for(;n>0;){let t=n-1>>1;if(s[t].dist<=s[n].dist)break;let r=s[t];s[t]=s[n],s[n]=r,n=t}}function Mt(s){let e=s[0],n=s.pop();if(s.length>0){s[0]=n;let t=0;for(;;){let r=t,a=2*t+1,i=2*t+2;if(a<s.length&&s[a].dist<s[r].dist&&(r=a),i<s.length&&s[i].dist<s[r].dist&&(r=i),r===t)break;let f=s[r];s[r]=s[t],s[t]=f,t=r}}return e}function it(s,e){if(s.length!==e)throw new Error(`Expected ${e} dimensions, got ${s.length}`);return new Float32Array(s)}function At(s){for(let e=0;e<s.length;e++)if(!Number.isFinite(s[e]))throw new Error("Vector contains non-finite values")}function ot(s){let e=s.dimensions;if(!e||e<=0)throw new Error("dimensions must be a positive integer");let n=s.m??16,t=n*2,r=s.efConstruction??200,a=s.efSearch??50,i=It[s.distance??"cosine"];if(!i)throw new Error(`Unknown distance metric: ${s.distance}`);let f=1/Math.log(n),c=[],u=new Map,o=-1,l=-1,g=0,S=ee(0);function F(){let p=Math.random();return p===0&&(p=Number.EPSILON),Math.floor(-Math.log(p)*f)}function K(p,T,b,y){let A=new Set;A.add(T);let V=i(p,c[T].vector),I=[];Je(I,{idx:T,dist:V});let k=[{idx:T,dist:V}];for(;I.length>0;){let E=Mt(I);if(k.length>=b){let j=-1/0;for(let q=0;q<k.length;q++)k[q].dist>j&&(j=k[q].dist);if(E.dist>j)break}let W=c[E.idx].neighbors[y];if(W)for(let j of W){if(A.has(j))continue;A.add(j);let q=c[j];if(q.deleted)continue;let oe=i(p,q.vector);if(k.length<b)Je(I,{idx:j,dist:oe}),k.push({idx:j,dist:oe});else{let Ze=0,Ke=k[0].dist;for(let _e=1;_e<k.length;_e++)k[_e].dist>Ke&&(Ke=k[_e].dist,Ze=_e);oe<Ke&&(Je(I,{idx:j,dist:oe}),k[Ze]={idx:j,dist:oe})}}}return k}function te(p,T,b){let y=T,A=i(p,c[y].vector),V=!0;for(;V;){V=!1;let I=c[y].neighbors[b];if(!I)break;for(let k of I){let E=c[k];if(E.deleted)continue;let R=i(p,E.vector);R<A&&(y=k,A=R,V=!0)}}return y}function h(p,T){p.sort((y,A)=>y.dist-A.dist);let b=[];for(let y=0;y<Math.min(p.length,T);y++)b.push(p[y].idx);return b}function m(p,T,b){let y=b===0?t:n;c[p].neighbors[b].add(T),c[T].neighbors[b].add(p),c[p].neighbors[b].size>y&&w(p,b,y),c[T].neighbors[b].size>y&&w(T,b,y)}function w(p,T,b){let y=c[p],A=[];for(let I of y.neighbors[T])c[I].deleted||A.push({idx:I,dist:i(y.vector,c[I].vector)});let V=h(A,b);y.neighbors[T]=new Set(V)}function d(p,T){let b=it(T,e);if(At(b),u.has(p)){let E=u.get(p),R=c[E];if(R.deleted){if(R.deleted=!1,R.vector=b,g++,o===-1)o=E,l=R.layer;else{for(let W=R.layer;W>=0;W--)R.neighbors[W]=new Set,_(E,W);R.layer>l&&(o=E,l=R.layer)}S.set(g)}else{R.vector=b;for(let W=R.layer;W>=0;W--){for(let j of R.neighbors[W])c[j].neighbors[W].delete(E);R.neighbors[W]=new Set,_(E,W)}}return}let y=F(),A=c.length,V=[];for(let E=0;E<=y;E++)V.push(new Set);let I={id:p,vector:b,layer:y,neighbors:V,deleted:!1};if(c.push(I),u.set(p,A),g++,o===-1){o=A,l=y,S.set(g);return}let k=o;for(let E=l;E>y;E--)k=te(b,k,E);for(let E=Math.min(y,l);E>=0;E--){let R=K(b,k,r,E),j=h(R,E===0?t:n);for(let q of j)q!==A&&m(A,q,E);R.length>0&&(R.sort((q,oe)=>q.dist-oe.dist),k=R[0].idx)}y>l&&(o=A,l=y),S.set(g)}function _(p,T){let b=o;if(b===p){let I=-1;for(let k=0;k<c.length;k++)if(k!==p&&!c[k].deleted&&c[k].layer>=T){I=k;break}if(I===-1)return;b=I}for(let I=Math.min(l,c[b].layer);I>T;I--)b=te(c[p].vector,b,I);let y=K(c[p].vector,b,r,T),V=h(y,T===0?t:n);for(let I of V)I!==p&&m(p,I,T)}function x(p){let T=u.get(p);if(T===void 0)return!1;let b=c[T];if(b.deleted)return!1;if(b.deleted=!0,g--,S.set(g),T===o){let y=-1;for(let A=0;A<c.length;A++)c[A].deleted||(y===-1||c[A].layer>c[y].layer)&&(y=A);o=y,l=y===-1?-1:c[y].layer}return!0}function L(p,T=10){if(g===0)return[];let b=it(p,e),y=Math.min(T,g),A=Math.max(a,y),V=o;for(let E=l;E>0;E--)V=te(b,V,E);let I=K(b,V,A,0);I.sort((E,R)=>E.dist-R.dist);let k=[];for(let E=0;E<I.length&&k.length<y;E++){let R=c[I[E].idx];R.deleted||k.push({id:R.id,distance:I[E].dist})}return k}function N(p){let T=u.get(p);return T===void 0?!1:!c[T].deleted}function $(){c.length=0,u.clear(),o=-1,l=-1,g=0,S.set(0),G(S)}return{add:d,remove:x,search:L,has:N,size:S,destroy:$}}0&&(module.exports={collection,computeScore,decay,memoryNode,vectorIndex});
1
+ "use strict";var qe=Object.defineProperty;var pt=Object.getOwnPropertyDescriptor;var mt=Object.getOwnPropertyNames;var _t=Object.prototype.hasOwnProperty;var yt=(s,e)=>{for(var n in e)qe(s,n,{get:e[n],enumerable:!0})},St=(s,e,n,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of mt(e))!_t.call(s,o)&&o!==n&&qe(s,o,{get:()=>e[o],enumerable:!(t=pt(e,o))||t.enumerable});return s};var Tt=s=>St(qe({},"__esModule",{value:!0}),s);var Wt={};yt(Wt,{collection:()=>je,computeScore:()=>se,decay:()=>rt,httpTransport:()=>it,knowledgeGraph:()=>at,lightCollection:()=>ut,memoryNode:()=>ce,sessionSync:()=>dt,vectorIndex:()=>gt,wsTransport:()=>ht});module.exports=Tt(Wt);var we=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 t=e>>>5,o=1<<(e&31);n[t]&o||(n[t]|=o,this._v++)}}clear(e){let n=this._w;if(n===null)this._v&=~(1<<e);else{let t=e>>>5,o=1<<(e&31);n[t]&o&&(n[t]&=~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 z=Symbol("DIRTY"),J=Symbol("RESOLVED"),Te=Symbol("SINGLE_DEP"),fe=Symbol("RESET"),vt=Symbol("PAUSE"),bt=Symbol("RESUME"),ge=Symbol("TEARDOWN");function Ie(s){return s===fe||s===vt||s===bt||s===ge}var Ne=0,Re=1,Ae=2,Oe=3,Le=4,Ce=5,q=7,ve=7<<q,Et=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function Ke(s){return Et[(s&ve)>>>q]}var F=0,U=1,A=2,O=3,xe=0,De=[],Ge=!1;function H(s){xe++;try{return s()}finally{if(xe--,xe===0&&!Ge){Ge=!0;for(let e=0;e<De.length;e++)De[e]();De.length=0,Ge=!1}}}function ue(){return xe>0}function Fe(s){De.push(s)}var Me=0,ke=[];function $e(){Me++}function Pe(){if(Me--,Me===0){for(let s=0;s<ke.length;s++)ke[s]();ke.length=0}}function et(s){Me>0?ke.push(s):s()}function V(s){let e=s;typeof e.complete=="function"?e.complete():typeof e._handleEnd=="function"&&e._handleEnd(void 0)}var oe=class s{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(s._explicitEnabled!==null)return s._explicitEnabled;if(s._cachedDefault!==null)return s._cachedDefault;try{s._cachedDefault=globalThis.process?.env?.NODE_ENV!=="production"}catch{s._cachedDefault=!0}return s._cachedDefault}static set enabled(e){s._explicitEnabled=e}static _depSuffix(e){if(!e?.length)return;let t=e.map(o=>s._names.get(o)??"?").join(",");return t.length>40?`${t.slice(0,37)}...`:t}static _resolveKey(e){let n=s._keys.get(e)??s._names.get(e);if(n)return n;let t=`anonymous_${s._nextId++}`;return s._keys.set(e,t),t}static register(e,n){if(!s.enabled)return;n?.name&&s._names.set(e,n.name),n?.kind&&s._kinds.set(e,n.kind);let t=s._nextId++,o=n?.name;if(!(o&&!s._usedKeys.has(o)))if(o){let a=s._depSuffix(n?.deps);o=a?`${o}(${a})`:`${o}_${t}`,s._usedKeys.has(o)&&(o=`${o}_${t}`)}else{let a=n?.kind??"store",r=s._depSuffix(n?.deps);o=r?`${a}(${r})`:`${a}_${t}`,s._usedKeys.has(o)&&(o=`${o}_${t}`)}s._usedKeys.add(o),s._keys.set(e,o),s._stores.add(new WeakRef(e))}static registerEdge(e,n){if(!s.enabled)return;let t=s._resolveKey(e),o=s._resolveKey(n),a=s._edges.get(t);a?a.includes(o)||a.push(o):s._edges.set(t,[o])}static getEdges(){return new Map(s._edges)}static getName(e){if(s.enabled)return s._names.get(e)}static getKind(e){return s._kinds.get(e)}static inspect(e){return{name:s._names.get(e),kind:s._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 t of s._stores){let o=t.deref();if(!o){s._stores.delete(t);continue}let a=s._resolveKey(o);n.add(a),e.set(a,s.inspect(o))}for(let[t,o]of s._edges){if(!n.has(t)){s._edges.delete(t),s._usedKeys.delete(t);continue}let a=o.filter(r=>n.has(r));a.length===0?s._edges.delete(t):a.length!==o.length&&s._edges.set(t,a)}return e}static trace(e,n){let t=null,o=e.get();return e.source(F,(a,r)=>{if(a===F&&(t=r),a===A){t=null;return}if(a===1){let c=r;if(!Object.is(c,o)){let f=o;o=c,n(c,f)}}}),()=>t?.(A)}static dumpGraph(){let e=s.graph(),n=s.getEdges(),t=new Map;for(let[r,c]of n)for(let f of c){let p=t.get(f);p?p.includes(r)||p.push(r):t.set(f,[r])}let o=[];for(let[r,c]of e){let f=t.get(r),p=n.get(r),i=f?.length?` \u2190 [${f.join(", ")}]`:"",l=p?.length?` \u2192 [${p.join(", ")}]`:"";o.push(` ${r} (${c.kind}) = ${JSON.stringify(c.value)} [${c.status??"?"}]${i}${l}`)}return[`Store Graph (${e.size} nodes):`,...o].join(`
2
+ `)}static _signalLabel(e){return e===z?"DIRTY":e===J?"RESOLVED":typeof e=="symbol"?e.description??String(e):String(e)}static _observe(e,n,t){let o=null,a=!1,r=n??s.getName(e),c=[],f={values:[],signals:[],events:[],ended:!1,endError:void 0,get completedCleanly(){return f.ended&&!a},get errored(){return f.ended&&a},dirtyCount:0,resolvedCount:0,name:r,get eventLog(){return c},dispose:()=>o?.(A),reconnect:()=>(o?.(A),s._observe(e,n,t))};return e.source(F,(p,i)=>{if(p===F){o=i;return}let l=ue();p===U?(f.values.push(i),f.events.push({type:"data",data:i,inBatch:l}),c.push(i),t&&t(`[${r}] DATA:`,i)):p===O?(f.signals.push(i),f.events.push({type:"signal",data:i,inBatch:l}),c.push(s._signalLabel(i)),i===z?f.dirtyCount++:i===J&&f.resolvedCount++,t&&t(`[${r}] STATE:`,i)):p===A&&(f.ended=!0,f.endError=i,a=i!==void 0,f.events.push({type:"end",data:i,inBatch:l}),c.push(a?["END",i]:"END"),t&&t(`[${r}] END`,i!==void 0?i:""),o=null)}),f}static observe(e){return s._observe(e)}static activate(e){let n=null;return e.source(F,(t,o)=>{t===F&&(n=o),t===A&&(n=null)}),()=>n?.(A)}static tap(e,n){let t=n??`tap(${s.getName(e)??"anon"})`,o={get:()=>e.get(),source:e.source};return s.register(o,{name:t,kind:"tap"}),s.registerEdge(e,o),o}static spy(e,n){let t=n?.name??s.getName(e)??"spy",o=n?.log??console.log;return s._observe(e,t,o)}static snapshot(){let e=s.graph(),n=s.getEdges(),t=new Map;for(let r of s._stores){let c=r.deref();if(!c)continue;let f=s._annotations.get(c);f!==void 0&&t.set(s._resolveKey(c),f)}let o=[];for(let[r,c]of e){let f={name:r,kind:c.kind,value:c.value,status:c.status},p=t.get(r);p!==void 0&&(f.annotation=p),o.push(f)}let a=[];for(let[r,c]of n)for(let f of c)a.push({from:r,to:f});return{nodes:o,edges:a,trace:s.traceLog()}}static toMermaid(e){let n=e?.direction??"TD",t=s.snapshot(),o=[`graph ${n}`],a={SETTLED:":::settled",DIRTY:":::dirty",ERRORED:":::errored",COMPLETED:":::completed"},r=new Map;function c(i){let l=i.replace(/[^a-zA-Z0-9_]/g,"_"),T=r.get(l);return T===void 0?(r.set(l,1),l):(r.set(l,T+1),`${l}__${T}`)}let f=new Map;function p(i){let l=JSON.stringify(i);return l&&l.length>30?`${l.slice(0,27)}...`:l??"undefined"}for(let i of t.nodes){let l=c(i.name);f.set(i.name,l);let T=`${i.name} (${i.kind}) = ${p(i.value)}`,D=a[i.status??""]??"";o.push(` ${l}["${T}"]${D}`)}for(let i of t.edges){let l=f.get(i.from)??c(i.from),T=f.get(i.to)??c(i.to);o.push(` ${l} --> ${T}`)}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
+ `)}static toD2(e){let n=e?.direction??"down",t=s.snapshot(),o=[`direction: ${n}`,""],a={state:"rectangle",derived:"hexagon",effect:"oval",producer:"rectangle",operator:"parallelogram","pipeline-step":"rectangle","pipeline-status":"diamond",checkpoint:"cylinder"},r=new Map;function c(i){let l=i.replace(/[^a-zA-Z0-9_]/g,"_"),T=r.get(l);return T===void 0?(r.set(l,1),l):(r.set(l,T+1),`${l}__${T}`)}let f=new Map;function p(i){let l=JSON.stringify(i);return l&&l.length>30?`${l.slice(0,27)}...`:l??"undefined"}for(let i of t.nodes){let l=c(i.name);f.set(i.name,l);let T=a[i.kind]??"rectangle",D=`${i.name} (${i.kind}) = ${p(i.value)}`,C=i.status?` [${i.status}]`:"";o.push(`${l}: "${D}${C}" { shape: ${T} }`)}t.edges.length>0&&o.push("");for(let i of t.edges){let l=f.get(i.from)??c(i.from),T=f.get(i.to)??c(i.to);o.push(`${l} -> ${T}`)}return o.join(`
4
+ `)}static annotate(e,n){if(!s.enabled)return;s._annotations.set(e,n);let t={node:s._resolveKey(e),reason:n,timestamp:Date.now()},o=s.maxTraceEntries;o<=0||(s._traceLog.length<o?s._traceLog.push(t):(s._traceLog[s._traceHead]=t,s._traceFull=!0),s._traceHead=(s._traceHead+1)%o)}static getAnnotation(e){return s._annotations.get(e)}static traceLog(){return s._traceFull?[...s._traceLog.slice(s._traceHead),...s._traceLog.slice(0,s._traceHead)]:s._traceLog.slice(0,s._traceHead||s._traceLog.length)}static clearTrace(){s._traceLog=[],s._traceHead=0,s._traceFull=!1}static timeline(e){let n=null,t=[];return e.source(F,(o,a)=>{if(o===F){n=a;return}let r={timestamp:Date.now(),type:o===U?"data":o===O?"signal":"end",data:a,inBatch:ue()};t.push(r),o===A&&(n=null)}),{entries:t,dispose:()=>n?.(A)}}static observeDerived(e){let n=[],t=e,o=t._fn;if(typeof o!="function"||!Array.isArray(t._deps))return{...s.observe(e),evaluations:n};t._fn=()=>{let f=t._deps.map(i=>i.get()),p=o();return n.push({result:p,depValues:f,timestamp:Date.now()}),p};let a=s._observe(e),r=a.dispose;return{...a,evaluations:n,dispose:()=>{t._fn=o,r()},reconnect:()=>(t._fn=o,r(),s.observeDerived(e))}}static observeTaskState(e){let n=e.status.get(),t=[],o=null;return e.status.source(F,(a,r)=>{if(a===F){o=r;return}if(a===U){let c=r;if(c!==n){let f={from:n,to:c,timestamp:Date.now()};c==="error"&&(f.error=e.error.get()),t.push(f),n=c}}a===A&&(o=null)}),{transitions:t,get currentStatus(){return e.status.get()},dispose:()=>{o?.(A)}}}static causalityTrace(e){let n=[],t=e,o=t._fn;if(typeof o!="function"||!Array.isArray(t._deps))return{...s.observe(e),causality:n};let a=t._deps,r=a.map(i=>i.get());t._fn=()=>{let i=a.map(D=>D.get()),l=o(),T=-1;for(let D=0;D<a.length;D++)if(!Object.is(i[D],r[D])){T=D;break}return n.push({result:l,triggerDepIndex:T,triggerDepName:T>=0?s.getName(a[T]):void 0,depValues:i,timestamp:Date.now()}),r=i,l};let c=s._observe(e),f=c.dispose;return{...c,causality:n,dispose:()=>{t._fn=o,f()},reconnect:()=>(t._fn=o,f(),s.causalityTrace(e))}}static _reset(){s._names=new WeakMap,s._kinds=new WeakMap,s._keys=new WeakMap,s._stores=new Set,s._edges=new Map,s._usedKeys=new Set,s._nextId=0,s._explicitEnabled=null,s._cachedDefault=null,s._annotations=new WeakMap,s._traceLog=[],s._traceHead=0,s._traceFull=!1,s.maxTraceEntries=1e3}};var de=1,he=2,pe=4,X=8,re=32,tt=64,wt=Ne<<q,me=Re<<q,Ye=Ae<<q,be=Oe<<q,xt=Le<<q,ze=Ce<<q,W=ve,Ue=class{_output=null;_upstreamTalkbacks=[];_cachedValue;_flags;_dirtyDeps;_eqFn;_deps;_fn;get _status(){return Ke(this._flags)}constructor(e,n,t,o){this._deps=e,this._fn=n,this._eqFn=t?.equals,this._flags=o?tt:0,this._dirtyDeps=new we(e.length),this.source=this.source.bind(this),oe.register(this,{kind:"derived",...t,deps:e});for(let a of e)oe.registerEdge(a,this)}_dispatch(e,n){let t=this._output;if(t)if(this._flags&re)for(let o of t)o(e,n);else t(e,n)}_recompute(){let e;try{e=this._fn()}catch(n){this._handleEnd(n);return}if(this._eqFn&&this._flags&de&&this._eqFn(this._cachedValue,e)){this._flags=this._flags&~W|be,this._dispatch(O,J);return}this._cachedValue=e,this._flags=(this._flags|de)&~W|Ye,this._dispatch(U,this._cachedValue)}_recomputeIdentity(e){if(!(this._flags&X)){if(this._eqFn&&this._flags&de&&this._eqFn(this._cachedValue,e)){this._flags=this._flags&~W|be,this._dispatch(O,J);return}this._cachedValue=e,this._flags=(this._flags|de)&~W|Ye,this._dispatch(U,e)}}_lazyConnect(){if(!(this._flags&(he|X))){try{this._cachedValue=this._fn()}catch(e){this._handleEnd(e);return}this._flags=(this._flags|de)&~W|Ye,$e(),this._connectUpstream(),this._flags&X||(this._flags|=he),Pe()}}_connectUpstream(){this._upstreamTalkbacks.length=0,this._deps.length===1?this._flags&tt?this._connectSingleDepIdentity():this._connectSingleDep():this._connectMultiDep()}_connectSingleDep(){let e=!1;this._deps[0].source(F,(n,t)=>{if(n===F){this._upstreamTalkbacks.push(t),t(O,Te);return}if(!(this._flags&X))if(n===O)if(t===z){if(e)return;e=!0,this._flags=this._flags&~W|me,this._dispatch(O,z)}else t===J?e&&(e=!1,this._flags=this._flags&~W|be,this._dispatch(O,J)):this._dispatch(O,t);else n===U?e?(e=!1,this._recompute()):(this._flags=this._flags&~W|me,this._dispatch(O,z),this._recompute()):n===A&&this._handleEnd(t)})}_connectSingleDepIdentity(){let e=!1;this._deps[0].source(F,(n,t)=>{if(n===F){this._upstreamTalkbacks.push(t),t(O,Te);return}this._flags&X||(n===O?t===z?(e=!0,this._flags=this._flags&~W|me,this._dispatch(O,z)):t===J?e&&(e=!1,this._flags=this._flags&~W|be,this._dispatch(O,J)):this._dispatch(O,t):n===U?e?(e=!1,this._recomputeIdentity(t)):(this._flags=this._flags&~W|me,this._dispatch(O,z),this._recomputeIdentity(t)):n===A&&this._handleEnd(t))})}_connectMultiDep(){for(let e=0;e<this._deps.length&&!(this._flags&X);e++){let n=e;this._deps[n].source(F,(t,o)=>{if(t===F){this._upstreamTalkbacks.push(o);return}if(!(this._flags&X))if(t===O)if(o===z){let a=this._dirtyDeps.empty();this._dirtyDeps.set(n),a&&(this._flags&=~pe,this._flags=this._flags&~W|me,this._dispatch(O,z))}else o===J?this._dirtyDeps.test(n)&&(this._dirtyDeps.clear(n),this._dirtyDeps.empty()&&(this._flags&pe?this._recompute():(this._flags=this._flags&~W|be,this._dispatch(O,J)))):this._dispatch(O,o);else t===U?this._dirtyDeps.test(n)?(this._dirtyDeps.clear(n),this._flags|=pe,this._dirtyDeps.empty()&&this._recompute()):this._dirtyDeps.empty()?(this._flags=this._flags&~W|me,this._dispatch(O,z),this._recompute()):this._flags|=pe:t===A&&this._handleEnd(o)})}}_handleEnd(e){this._flags|=X,this._flags=this._flags&~W|(e!==void 0?ze:xt),e!==void 0&&(this._cachedValue=e);for(let o of this._upstreamTalkbacks)o(A);this._upstreamTalkbacks=[],this._flags&=~he,this._dirtyDeps.reset();let n=this._output,t=this._flags&re;if(this._output=null,this._flags&=~re,n)if(t)for(let o of n)try{e!==void 0?o(A,e):o(A)}catch{}else e!==void 0?n(A,e):n(A)}_disconnectUpstream(){for(let e of this._upstreamTalkbacks)e(A);this._upstreamTalkbacks.length=0,this._flags&=~(he|pe),this._flags=this._flags&~W|wt,this._dirtyDeps.reset()}_handleLifecycleSignal(e){if(!(this._flags&X)){if(e===ge){for(let n of this._upstreamTalkbacks)n(O,ge);this._handleEnd(void 0);return}e===fe&&(this._flags&=~(de|pe),this._dirtyDeps.reset());for(let n of this._upstreamTalkbacks)n(O,e)}}get(){if(this._flags&he)return this._cachedValue;if(this._flags&X){if((this._flags&W)===ze)throw this._cachedValue;return this._cachedValue}let e=this._fn();return this._cachedValue=e,this._flags|=de,e}source(e,n){if(e===F){let t=n;if(this._flags&X){let o=(this._flags&W)===ze;t(F,a=>{}),o?t(A,this._cachedValue):t(A);return}if(!(this._flags&he)&&(this._lazyConnect(),this._flags&X)){let o=(this._flags&W)===ze;t(F,a=>{}),o?t(A,this._cachedValue):t(A);return}if(this._output===null)this._output=t;else if(this._flags&re)this._output.add(t);else{let o=new Set;o.add(this._output),o.add(t),this._output=o,this._flags|=re}t(F,(o,a)=>{if(o===U&&t(U,this._cachedValue),o===O&&Ie(a)){this._handleLifecycleSignal(a);return}if(o===A){if(this._output===null)return;if(this._flags&re){let r=this._output;r.delete(t),r.size===1?(this._output=r.values().next().value,this._flags&=~re):r.size===0&&(this._output=null,this._flags&=~re,this._disconnectUpstream())}else this._output===t&&(this._output=null,this._disconnectUpstream())}})}}};function j(s,e,n){return new Ue(s,e,n)}(e=>{function s(n,t){return new Ue([n],()=>n.get(),t,!0)}e.from=s})(j||={});var Ve=1,ee=64,Q=2,_e=4,nt=8,st=16,ie=32,ne=1024,B=ve,ye=Re<<q,Ee=Ae<<q,We=Ne<<q,Dt=Le<<q,kt=Ce<<q,Mt=Oe<<q,He=class{_value;_output=null;_flags;get _status(){return Ke(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 t=0;n?.autoDirty!==!1&&(t|=_e),n?.resetOnTeardown&&(t|=nt),n?.resubscribable&&(t|=st),this._flags=t,this.source=this.source.bind(this),this.emit=this.emit.bind(this),n?._skipInspect||oe.register(this,{kind:"producer",...n})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(e,n){let t=this._output;if(t)if(this._flags&ee)for(let o of t)o(e,n);else t(e,n)}emit(e){this._flags&Q||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(ue()?this._flags&ie||(this._flags|=ie,this._flags&_e&&(this._flags=this._flags&~B|ye,this._dispatch(O,z)),Fe(()=>{this._flags&=~ie,this._flags=this._flags&~B|Ee,this._dispatch(U,this._value)})):(this._flags&_e&&!(this._flags&ne)&&(this._flags=this._flags&~B|ye,this._dispatch(O,z)),this._flags=this._flags&~B|Ee,this._dispatch(U,this._value))))}signal(e){this._flags&Q||!this._output||(e===z?this._flags=this._flags&~B|ye:e===J&&(this._flags=this._flags&~B|Mt),this._dispatch(O,e))}complete(){if(this._flags&Q)return;this._flags=(this._flags|Q)&~B|Dt;let e=this._output,n=this._flags&ee;if(this._output=null,this._flags&=~(ee|ne),this._singleDepCount=0,this._stop(),e)if(n)for(let t of e)t(A);else e(A)}error(e){if(this._flags&Q)return;this._flags=(this._flags|Q)&~B|kt;let n=this._output,t=this._flags&ee;if(this._output=null,this._flags&=~(ee|ne),this._singleDepCount=0,this._stop(),n)if(t)for(let o of n)o(A,e);else n(A,e)}_start(){if(this._flags&Ve||!this._fn)return;this._flags|=Ve,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&Ve&&(this._flags&=~Ve,this._onLifecycleSignal=void 0,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&nt&&(this._value=this._initial),this._flags&Q||(this._flags=this._flags&~B|We))}_handleLifecycleSignal(e){if(!(this._flags&Q)){if(e===ge){this._onLifecycleSignal?.(e),this.complete();return}e===fe&&(this._value=this._initial,this._flags&=~ie),this._onLifecycleSignal?.(e),e===fe&&this.emit(this._initial)}}source(e,n){if(e===F){let t=n;if(this._flags&Q)if(this._flags&st&&this._output===null)this._flags=this._flags&~(Q|B)|We;else{t(F,a=>{}),t(A);return}if(this._output===null)this._output=t;else if(this._flags&ee)this._output.add(t);else{let a=new Set;a.add(this._output),a.add(t),this._output=a,this._flags=(this._flags|ee)&~ne}let o=!1;t(F,(a,r)=>{if(a===U&&t(U,this._value),a===O){r===Te&&!o?(o=!0,this._singleDepCount++,this._flags&ee||(this._flags|=ne)):Ie(r)&&this._handleLifecycleSignal(r);return}if(a===A){if(o&&(o=!1,this._singleDepCount--),this._output===null)return;if(this._flags&ee){let c=this._output;c.delete(t),c.size===1?(this._output=c.values().next().value,this._flags&=~ee,this._singleDepCount>0&&(this._flags|=ne)):c.size===0&&(this._output=null,this._flags&=~(ee|ne),this._singleDepCount=0,this._flags=this._flags&~B|We,this._stop())}else this._output===t&&(this._output=null,this._flags&=~ne,this._singleDepCount=0,this._flags=this._flags&~B|We,this._stop())}}),et(()=>this._start())}}};var Je=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),oe.register(this,{kind:"state",...n})}get(){return this._value}set(e){this._flags&Q||this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(ue()?this._flags&ie||(this._flags|=ie,this._flags&_e&&(this._flags=this._flags&~B|ye,this._dispatch(O,z)),Fe(()=>{this._flags&=~ie,this._flags=this._flags&~B|Ee,this._dispatch(U,this._value)})):(this._flags&_e&&!(this._flags&ne)&&(this._flags=this._flags&~B|ye,this._dispatch(O,z)),this._flags=this._flags&~B|Ee,this._dispatch(U,this._value))))}update(e){this.set(e(this._value))}};function Z(s,e){return new Je(s,e)}function te(s,e,n){let t=null;$e(),s.source(F,(a,r)=>{if(a===F&&(t=r),a===A){t=null,n?.onEnd?.(r);return}if(a===1){let c=r,f=o;o=c,e(c,f)}});let o;try{o=s.get()}catch{}return Pe(),{unsubscribe(){t?.(A),t=null},signal(a){t?.(O,a)}}}var It=0;ae.from=function(e){let n=ae({id:e.id});for(let[t,o]of Object.entries(e.index))for(let a of o)n.add(a,[t]);return n};function ae(s){let e=++It,n=s?.id??`ridx-${e}`,t=new Map,o=new Map,a=new Map,r=new Map,c=Z(0,{name:`${n}:ver`}),f=j([c],()=>Array.from(t.keys()),{name:`${n}:keys`}),p=j([c],()=>t.size,{name:`${n}:size`}),i=!1,l=Object.freeze(new Set);function T(b){let w=a.get(b);return w||(w=Z(t.get(b)??new Set,{name:`${n}:${b}`,equals:()=>!1}),a.set(b,w)),w}function D(b){let w=a.get(b);if(w){let M=t.get(b);w.set(M?new Set(M):new Set)}}function C(b,w){let M=t.get(w),v=!M;return M||(M=new Set,t.set(w,M)),M.add(b),v}function K(b,w){let M=t.get(w);return M?(M.delete(b),M.size===0?(t.delete(w),!0):!1):!1}return{get id(){return n},get version(){return c.get()},get(b){let w=t.get(b);return w?Object.freeze(new Set(w)):l},has(b){let w=t.get(b);return w!==void 0&&w.size>0},keys(){return Array.from(t.keys())},get size(){return t.size},select(b){let w=r.get(b);if(w)return w;let M=T(b);return w=j([M],()=>M.get(),{name:`${n}:${b}:select`}),r.set(b,w),w},keysStore:f,sizeStore:p,add(b,w){if(i||w.length===0)return;let M=o.get(b);M||(M=new Set,o.set(b,M)),H(()=>{let v=!1;for(let m of w)M.add(m),C(b,m)&&(v=!0),D(m);v&&c.update(m=>m+1)})},remove(b){if(i)return;let w=o.get(b);w&&H(()=>{let M=!1;for(let v of w)K(b,v)&&(M=!0),D(v);o.delete(b),M&&c.update(v=>v+1)})},update(b,w){if(i)return;let M=o.get(b),v=new Set(w);H(()=>{let m=!1;if(M)for(let x of M)v.has(x)||(K(b,x)&&(m=!0),D(x));let S=o.get(b);S||(S=new Set,o.set(b,S)),S.clear();for(let x of w)S.add(x),C(b,x)&&(m=!0),D(x);m&&c.update(x=>x+1)})},clear(){t.size!==0&&H(()=>{t.clear(),o.clear();for(let b of a.values())b.set(new Set);c.update(b=>b+1)})},snapshot(){let b={};for(let[w,M]of t)b[w]=Array.from(M);return{type:"reactiveIndex",id:n,version:c.get(),index:b}},destroy(){if(!i){i=!0,t.clear(),o.clear();for(let b of a.values())V(b);a.clear();for(let b of r.values())V(b);r.clear(),V(c)}}}}function ot(s,e=n=>n){let n=[],t=new Map,o=new Map;function a(p,i){let l=n[p],T=n[i];n[p]=T,n[i]=l,l.index=i,T.index=p}function r(p){for(;p>0;){let i=p-1>>>1;if(n[i].score<=n[p].score)break;a(p,i),p=i}}function c(p){let i=n.length;for(;;){let l=p,T=2*p+1,D=T+1;if(T<i&&n[T].score<n[l].score&&(l=T),D<i&&n[D].score<n[l].score&&(l=D),l===p)break;a(p,l),p=l}}function f(p){let i=n.length-1;if(p===i){n.pop();return}a(p,i),n.pop(),r(p),c(p)}return{touch(){},insert(p){if(t.has(p))return;let i=s(p),l={key:p,score:e(i.get()),index:n.length};n.push(l),t.set(p,l),r(l.index);let T=te(i,D=>{let C=t.get(p);if(!C)return;let K=C.score;C.score=e(D),C.score<K?r(C.index):C.score>K&&c(C.index)});o.set(p,()=>T.unsubscribe())},delete(p){let i=t.get(p);if(!i)return;let l=o.get(p);l&&(l(),o.delete(p)),f(i.index),t.delete(p)},evict(p=1){let i=[];for(;i.length<p&&n.length>0;){let{key:l}=n[0];i.push(l);let T=o.get(l);T&&(T(),o.delete(l)),f(0),t.delete(l)}return i},size:()=>t.size,clear(){for(let p of o.values())p();o.clear(),t.clear(),n.length=0}}}function rt(s){let e=s?.halfLife??864e5,n=s?.recency??1,t=s?.importance??1,o=s?.frequency??.5,a=Math.LN2/e;return(r,c)=>{let f=(c??Date.now())-r.accessedAt,p=Math.exp(-a*f),i=1-1/(1+r.accessCount);return n*p+t*r.importance+o*i}}function se(s,e,n){let t=e?.halfLife??864e5,o=e?.recency??1,a=e?.importance??1,r=e?.frequency??.5,c=(n??Date.now())-s.accessedAt,f=Math.exp(-Math.LN2/t*c),p=1-1/(1+s.accessCount);return o*f+a*s.importance+r*p}var Nt=0;function Rt(){return`mem-${++Nt}`}function ce(s,e){let n=e?.id??Rt(),t=Date.now(),o={id:n,createdAt:t,updatedAt:t,accessedAt:t,accessCount:0,importance:e?.importance??.5,tags:new Set(e?.tags)},a=Z(s,{name:`mem:${n}:content`}),r=Z(o,{name:`mem:${n}:meta`,equals:()=>!1}),c={},f=j([r],()=>se(r.get(),c),{name:`mem:${n}:score`});return{id:n,content:a,meta:r,scoreStore:f,touch(){let i=Date.now();r.update(l=>({...l,accessedAt:i,accessCount:l.accessCount+1}))},tag(...i){r.update(l=>{let T=new Set(l.tags);for(let D of i)T.add(D);return{...l,tags:T,updatedAt:Date.now()}})},untag(...i){r.update(l=>{let T=new Set(l.tags);for(let D of i)T.delete(D);return{...l,tags:T,updatedAt:Date.now()}})},setImportance(i){r.update(l=>({...l,importance:Math.max(0,Math.min(1,i)),updatedAt:Date.now()}))},update(i){H(()=>{a.set(i),r.update(l=>({...l,updatedAt:Date.now()}))})},score(i){return se(r.get(),i??c)},destroy(){V(a),V(r)}}}var At=0;function je(s){let e=++At,n=s?.maxSize??1/0,t=s?.weights??{},o=s?.admissionPolicy,a=s?.forgetPolicy,r=new Map,c=ae(),f=new Map,p=n<1/0?ot(v=>r.get(v).meta,v=>se(v,t)):null,i=Z(0,{name:`collection-${e}:ver`}),l=j([i],()=>Array.from(r.values()),{name:`collection-${e}:nodes`}),T=j([i],()=>r.size,{name:`collection-${e}:size`}),D=!1;function C(){i.update(v=>v+1)}function K(v){let m=Array.from(v.meta.get().tags);c.update(v.id,m);let S=te(v.meta,x=>{let g=Array.from(x.tags);c.update(v.id,g)});f.set(v.id,()=>S.unsubscribe())}function Y(v){let m=f.get(v);m&&(m(),f.delete(v)),c.remove(v)}function b(){if(!p||r.size<=n)return;let v=p.evict(r.size-n);for(let m of v){let S=r.get(m);S&&(Y(m),S.destroy(),r.delete(m))}}function w(){if(!a)return 0;let v=[];for(let m of r.values())a(m)&&v.push(m.id);for(let m of v){let S=r.get(m);S&&(Y(m),p?.delete(m),S.destroy(),r.delete(m))}return v.length}return{add(v,m){if(D)throw new Error("Collection is destroyed");if(o){let x=Array.from(r.values()),g=o(v,x);switch(g.action){case"reject":return;case"update":{let d=r.get(g.targetId);if(!d)throw new Error(`Admission update target "${g.targetId}" not found`);return d.update(g.content),d}case"merge":{let d=r.get(g.targetId);if(!d)throw new Error(`Admission merge target "${g.targetId}" not found`);let u=g.reducer(d.content.get(),v);return d.update(u),d}default:break}}a&&w();let S=ce(v,m);return r.set(S.id,S),K(S),p?.insert(S.id),b(),C(),S},remove(v){let m=typeof v=="string"?v:v.id,S=r.get(m);return S?(Y(m),p?.delete(m),S.destroy(),r.delete(m),C(),!0):!1},get(v){return r.get(v)},has(v){return r.has(v)},nodes:l,size:T,tagIndex:c,query(v){let m=[];for(let S of r.values())v(S)&&m.push(S);return m},byTag(v){let m=c.get(v),S=[];for(let x of m){let g=r.get(x);g&&S.push(g)}return S},topK(v,m){let S=m??t,x=Date.now(),g=Array.from(r.values()).map(d=>({node:d,score:se(d.meta.get(),S,x)}));return g.sort((d,u)=>u.score-d.score),g.slice(0,v).map(d=>d.node)},summarize(v,m,S){if(D)throw new Error("Collection is destroyed");let x=Array.from(new Set(v)),g=[];for(let h of x){let _=r.get(h);_&&g.push(_)}if(g.length===0)throw new Error("No valid nodes to summarize");let d=m(g),u;return H(()=>{for(let h of g)Y(h.id),p?.delete(h.id),h.destroy(),r.delete(h.id);a&&w(),u=ce(d,S),r.set(u.id,u),K(u),p?.insert(u.id),b(),C()}),u},gc(){if(D)throw new Error("Collection is destroyed");let v=w();return v>0&&C(),v},destroy(){if(!D){D=!0,p?.clear();for(let v of f.values())v();f.clear(),c.destroy(),H(()=>{for(let v of r.values())v.destroy();r.clear()}),V(i)}}}}function it(s,e){let n=e?.method??"POST",t={"Content-Type":"application/json",...e?.headers},o=e?.batchMs??0,a=e?.serialize??(i=>JSON.stringify(i)),r=!1,c=[],f=null;function p(){if(c.length===0)return;let i=c;c=[],f=null;let l=a(i);fetch(s,{method:n,headers:t,body:l}).catch(()=>{})}return{send(i){if(!r){if(o<=0){let l=a([i]);fetch(s,{method:n,headers:t,body:l}).catch(()=>{});return}c.push(i),f||(f=setTimeout(p,o))}},close(){r=!0,f&&(clearTimeout(f),f=null),p()}}}var Ot=0,Lt=0;function Ct(){return`rel-${++Lt}`}function at(s){let e=++Ot,n=je(s),t=new Map,o=new Map,a=new Map,r=ae({id:`kg-${e}:types`}),c=Z(0,{name:`kg-${e}:relVer`}),f=j([c],()=>t.size,{name:`kg-${e}:relCount`}),p=new Map,i=new Map,l=!1;function T(){c.update(g=>g+1)}function D(g){let d=o.get(g);return d||(d=new Set,o.set(g,d)),d}function C(g){let d=a.get(g);return d||(d=new Set,a.set(g,d)),d}function K(g){let d=t.get(g);if(!d)return!1;t.delete(g);let u=o.get(d.sourceId);u&&(u.delete(g),u.size===0&&o.delete(d.sourceId));let h=a.get(d.targetId);return h&&(h.delete(g),h.size===0&&a.delete(d.targetId)),r.remove(g),!0}function Y(g){let d=[],u=o.get(g);if(u)for(let _ of u)d.push(_);let h=a.get(g);if(h)for(let _ of h)d.push(_);d.length!==0&&H(()=>{for(let _ of d)K(_);T()})}function b(g,d,u){let h=[];if(d==="out"||d==="both"){let _=o.get(g);if(_)for(let y of _){let E=t.get(y);(!u||E.type===u)&&h.push(E)}}if(d==="in"||d==="both"){let _=a.get(g);if(_)for(let y of _){let E=t.get(y);(!u||E.type===u)&&h.push(E)}}return h}function w(g,d,u){let h=new Set,_=b(g,d,u);for(let y of _){let E=y.sourceId===g?y.targetId:y.sourceId;E!==g&&h.add(E)}return h}let M=new Set;for(let g of n.nodes.get())M.add(g.id);function v(g){for(let d of["out","in","both"]){let u=S(g,d),h=p.get(u);h&&(V(h),p.delete(u));let _=i.get(u);_&&(V(_),i.delete(u))}}let m=te(n.nodes,g=>{let d=new Set;for(let u of g)d.add(u.id);for(let u of M)d.has(u)||(Y(u),v(u));M=d});function S(g,d){return`${g}:${d}`}return{addEntity(g,d){if(l)throw new Error("KnowledgeGraph is destroyed");return n.add(g,d)},removeEntity(g){if(l)throw new Error("KnowledgeGraph is destroyed");return n.remove(g)},getEntity(g){return n.get(g)},hasEntity(g){return n.has(g)},entities:n.nodes,entityCount:n.size,addRelation(g,d,u,h){if(l)throw new Error("KnowledgeGraph is destroyed");if(!n.has(g))throw new Error(`Source entity "${g}" not found`);if(!n.has(d))throw new Error(`Target entity "${d}" not found`);let _=h?.id??Ct();if(t.has(_))throw new Error(`Relation ID "${_}" already exists`);let y=Date.now(),E=h?.weight??1,N={id:_,sourceId:g,targetId:d,type:u,weight:Math.max(0,Math.min(1,E)),metadata:h?.metadata,createdAt:y,updatedAt:y};return H(()=>{t.set(_,N),D(g).add(_),C(d).add(_),r.add(_,[u]),T()}),N},removeRelation(g){if(l)throw new Error("KnowledgeGraph is destroyed");let d=!1;return H(()=>{d=K(g),d&&T()}),d},removeRelationsBetween(g,d,u){if(l)throw new Error("KnowledgeGraph is destroyed");let h=o.get(g);if(!h)return 0;let _=[];for(let y of h){let E=t.get(y);E.targetId===d&&(!u||E.type===u)&&_.push(y)}return _.length===0?0:(H(()=>{for(let y of _)K(y);T()}),_.length)},getRelation(g){return t.get(g)},hasRelation(g){return t.has(g)},updateRelation(g,d){if(l)throw new Error("KnowledgeGraph is destroyed");let u=t.get(g);if(!u)return!1;let h={...u,weight:d.weight!==void 0?Math.max(0,Math.min(1,d.weight)):u.weight,metadata:d.metadata!==void 0?d.metadata:u.metadata,updatedAt:Date.now()};return t.set(g,h),T(),!0},relationCount:f,outgoing(g,d){return b(g,"out",d)},incoming(g,d){return b(g,"in",d)},neighbors(g,d){let u=d?.direction??"out",h=w(g,u,d?.type),_=[];for(let y of h){let E=n.get(y);E&&_.push(E)}return _},traverse(g,d){let u=d?.direction??"out",h=d?.type,_=d?.maxDepth??1/0,y=d?.maxNodes??1/0;if(!n.has(g))return[];let E=new Set([g]),N=[],I=[g],R=0;for(;I.length>0&&R<_&&N.length<y;){R++;let k=[];for(let L of I){let P=w(L,u,h);for(let $ of P){if(E.has($))continue;E.add($);let G=n.get($);if(G&&(N.push(G),N.length>=y))break;k.push($)}if(N.length>=y)break}I=k}return N},shortestPath(g,d,u){if(g===d)return[g];if(!n.has(g)||!n.has(d))return;let h=u?.direction??"both",_=u?.type,y=new Set([g]),E=new Map,N=[g];for(;N.length>0;){let I=[];for(let R of N){let k=w(R,h,_);for(let L of k)if(!y.has(L)){if(y.add(L),E.set(L,R),L===d){let P=[d],$=d;for(;$!==g;)$=E.get($),P.unshift($);return P}I.push(L)}}N=I}},subgraph(g){let d=new Set(g),u=[];for(let y of d){let E=n.get(y);E&&u.push(E)}let h=[],_=new Set;for(let y of d){let E=o.get(y);if(E)for(let N of E){if(_.has(N))continue;let I=t.get(N);d.has(I.targetId)&&(h.push(I),_.add(N))}}return{entities:u,relations:h}},relationsOf(g,d="both"){let u=S(g,d),h=p.get(u);return h||(h=j([c],()=>b(g,d),{name:`kg-${e}:relsOf:${u}`}),p.set(u,h),h)},neighborsOf(g,d="both"){let u=S(g,d),h=i.get(u);return h||(h=j([c],()=>{let _=w(g,d),y=[];for(let E of _){let N=n.get(E);N&&y.push(N)}return y},{name:`kg-${e}:neighborsOf:${u}`}),i.set(u,h),h)},relationsInRange(g,d){let u=[];for(let h of t.values())(h.createdAt>=g&&h.createdAt<=d||h.updatedAt>=g&&h.updatedAt<=d)&&u.push(h);return u},typeIndex:r,collection:n,destroy(){if(!l){l=!0,m.unsubscribe();for(let g of p.values())V(g);p.clear();for(let g of i.values())V(g);i.clear(),t.clear(),o.clear(),a.clear(),r.destroy(),V(f),V(c),n.destroy()}}}}function ct(){let s=[],e=new Set,n=0;return{touch(){},insert(t){e.has(t)||(s.push(t),e.add(t))},delete(t){e.delete(t)},evict(t=1){let o=[];for(;o.length<t&&n<s.length;){let a=s[n++];e.delete(a)&&o.push(a)}return n>1e3&&n>s.length/2&&(s.splice(0,n),n=0),o},size:()=>e.size,clear(){s.length=0,e.clear(),n=0}}}function lt(){let s=new Map,e={key:null,prev:null,next:null},n={key:null,prev:null,next:null};e.next=n,n.prev=e;function t(r){r.prev.next=r.next,r.next.prev=r.prev}function o(r){r.next=e.next,r.prev=e,e.next.prev=r,e.next=r}function a(r){t(r),o(r)}return{touch(r){let c=s.get(r);c&&a(c)},insert(r){let c=s.get(r);if(c){a(c);return}c={key:r,prev:null,next:null},s.set(r,c),o(c)},delete(r){let c=s.get(r);c&&(t(c),s.delete(r))},evict(r=1){let c=[];for(;c.length<r&&n.prev!==e;){let f=n.prev;c.push(f.key),t(f),s.delete(f.key)}return c},size:()=>s.size,clear(){s.clear(),e.next=n,n.prev=e}}}var Kt=0;function ut(s){let e=++Kt,n=s?.maxSize??1/0,t=s?.eviction??"fifo",o=s?.weights??{},a=s?.admissionPolicy,r=s?.forgetPolicy,c=new Map,f=ae(),p=new Map,i=n<1/0?t==="lru"?lt():ct():null,l=Z(0,{name:`lightCollection-${e}:ver`}),T=j([l],()=>Array.from(c.values()),{name:`lightCollection-${e}:nodes`}),D=j([l],()=>c.size,{name:`lightCollection-${e}:size`}),C=!1;function K(){l.update(m=>m+1)}function Y(m){let S=Array.from(m.meta.get().tags);f.update(m.id,S);let x=te(m.meta,g=>{let d=Array.from(g.tags);f.update(m.id,d)});p.set(m.id,()=>x.unsubscribe())}function b(m){let S=p.get(m);S&&(S(),p.delete(m)),f.remove(m)}function w(){if(!i||c.size<=n)return;let m=i.evict(c.size-n);for(let S of m){let x=c.get(S);x&&(b(S),x.destroy(),c.delete(S))}}function M(){if(!r)return 0;let m=[];for(let S of c.values())r(S)&&m.push(S.id);for(let S of m){let x=c.get(S);x&&(b(S),i?.delete(S),x.destroy(),c.delete(S))}return m.length}return{add(m,S){if(C)throw new Error("Collection is destroyed");if(a){let g=Array.from(c.values()),d=a(m,g);switch(d.action){case"reject":return;case"update":{let u=c.get(d.targetId);if(!u)throw new Error(`Admission update target "${d.targetId}" not found`);return u.update(d.content),i?.touch(u.id),u}case"merge":{let u=c.get(d.targetId);if(!u)throw new Error(`Admission merge target "${d.targetId}" not found`);let h=d.reducer(u.content.get(),m);return u.update(h),i?.touch(u.id),u}default:break}}r&&M();let x=ce(m,S);return c.set(x.id,x),Y(x),i?.insert(x.id),w(),K(),x},remove(m){let S=typeof m=="string"?m:m.id,x=c.get(S);return x?(b(S),i?.delete(S),x.destroy(),c.delete(S),K(),!0):!1},get(m){let S=c.get(m);return S&&i?.touch(m),S},has(m){return c.has(m)},nodes:T,size:D,tagIndex:f,query(m){let S=[];for(let x of c.values())m(x)&&S.push(x);return S},byTag(m){let S=f.get(m),x=[];for(let g of S){let d=c.get(g);d&&x.push(d)}return x},topK(m,S){let x=S??o,g=Date.now(),d=Array.from(c.values()).map(u=>({node:u,score:se(u.meta.get(),x,g)}));return d.sort((u,h)=>h.score-u.score),d.slice(0,m).map(u=>u.node)},summarize(m,S,x){if(C)throw new Error("Collection is destroyed");let g=Array.from(new Set(m)),d=[];for(let _ of g){let y=c.get(_);y&&d.push(y)}if(d.length===0)throw new Error("No valid nodes to summarize");let u=S(d),h;return H(()=>{for(let _ of d)b(_.id),i?.delete(_.id),_.destroy(),c.delete(_.id);r&&M(),h=ce(u,x),c.set(h.id,h),Y(h),i?.insert(h.id),w(),K()}),h},gc(){if(C)throw new Error("Collection is destroyed");let m=M();return m>0&&K(),m},destroy(){if(!C){C=!0,i?.clear();for(let m of p.values())m();p.clear(),f.destroy(),H(()=>{for(let m of c.values())m.destroy();c.clear()}),V(l)}}}}function Ze(s){let e=s.meta.get();return{id:s.id,content:s.content.get(),meta:{id:e.id,createdAt:e.createdAt,updatedAt:e.updatedAt,accessedAt:e.accessedAt,accessCount:e.accessCount,importance:e.importance,tags:Array.from(e.tags)}}}function dt(s,e,n){let t=n?.initialSnapshot!==!1,o=!1,a=new Map;function r(l){if(a.has(l.id))return;let T=te(l.meta,()=>{o||!s.has(l.id)||e.send({type:"update",nodes:[Ze(l)]})});a.set(l.id,T)}function c(l){let T=a.get(l);T&&(T.unsubscribe(),a.delete(l))}let f=new Set,p=s.nodes.get();f=new Set(p.map(l=>l.id)),t&&e.send({type:"snapshot",nodes:p.map(Ze)});for(let l of p)r(l);let i=te(s.nodes,l=>{if(o)return;let T=new Set(l.map(K=>K.id)),D=[];for(let K of l)f.has(K.id)||(D.push(K),r(K));let C=[];for(let K of f)T.has(K)||(C.push(K),c(K));D.length>0&&e.send({type:"add",nodes:D.map(Ze)}),C.length>0&&e.send({type:"remove",nodeIds:C}),f=T});return{dispose(){if(!o){o=!0,i.unsubscribe();for(let l of a.values())l.unsubscribe();a.clear()}}}}function Ft(s,e){let n=0,t=0,o=0;for(let r=0;r<s.length;r++)n+=s[r]*e[r],t+=s[r]*s[r],o+=e[r]*e[r];let a=Math.sqrt(t)*Math.sqrt(o);return a===0?1:1-n/a}function $t(s,e){let n=0;for(let t=0;t<s.length;t++){let o=s[t]-e[t];n+=o*o}return Math.sqrt(n)}function Pt(s,e){let n=0;for(let t=0;t<s.length;t++)n+=s[t]*e[t];return-n}var zt={cosine:Ft,euclidean:$t,dotProduct:Pt};function Xe(s,e){s.push(e);let n=s.length-1;for(;n>0;){let t=n-1>>1;if(s[t].dist<=s[n].dist)break;let o=s[t];s[t]=s[n],s[n]=o,n=t}}function Ut(s){let e=s[0],n=s.pop();if(s.length>0){s[0]=n;let t=0;for(;;){let o=t,a=2*t+1,r=2*t+2;if(a<s.length&&s[a].dist<s[o].dist&&(o=a),r<s.length&&s[r].dist<s[o].dist&&(o=r),o===t)break;let c=s[o];s[o]=s[t],s[t]=c,t=o}}return e}function ft(s,e){if(s.length!==e)throw new Error(`Expected ${e} dimensions, got ${s.length}`);return new Float32Array(s)}function Vt(s){for(let e=0;e<s.length;e++)if(!Number.isFinite(s[e]))throw new Error("Vector contains non-finite values")}function gt(s){let e=s.dimensions;if(!e||e<=0)throw new Error("dimensions must be a positive integer");let n=s.m??16,t=n*2,o=s.efConstruction??200,a=s.efSearch??50,r=zt[s.distance??"cosine"];if(!r)throw new Error(`Unknown distance metric: ${s.distance}`);let c=1/Math.log(n),f=[],p=new Map,i=-1,l=-1,T=0,D=Z(0);function C(){let u=Math.random();return u===0&&(u=Number.EPSILON),Math.floor(-Math.log(u)*c)}function K(u,h,_,y){let E=new Set;E.add(h);let N=r(u,f[h].vector),I=[];Xe(I,{idx:h,dist:N});let R=[{idx:h,dist:N}];for(;I.length>0;){let k=Ut(I);if(R.length>=_){let $=-1/0;for(let G=0;G<R.length;G++)R[G].dist>$&&($=R[G].dist);if(k.dist>$)break}let P=f[k.idx].neighbors[y];if(P)for(let $ of P){if(E.has($))continue;E.add($);let G=f[$];if(G.deleted)continue;let le=r(u,G.vector);if(R.length<_)Xe(I,{idx:$,dist:le}),R.push({idx:$,dist:le});else{let Qe=0,Be=R[0].dist;for(let Se=1;Se<R.length;Se++)R[Se].dist>Be&&(Be=R[Se].dist,Qe=Se);le<Be&&(Xe(I,{idx:$,dist:le}),R[Qe]={idx:$,dist:le})}}}return R}function Y(u,h,_){let y=h,E=r(u,f[y].vector),N=!0;for(;N;){N=!1;let I=f[y].neighbors[_];if(!I)break;for(let R of I){let k=f[R];if(k.deleted)continue;let L=r(u,k.vector);L<E&&(y=R,E=L,N=!0)}}return y}function b(u,h){u.sort((y,E)=>y.dist-E.dist);let _=[];for(let y=0;y<Math.min(u.length,h);y++)_.push(u[y].idx);return _}function w(u,h,_){let y=_===0?t:n;f[u].neighbors[_].add(h),f[h].neighbors[_].add(u),f[u].neighbors[_].size>y&&M(u,_,y),f[h].neighbors[_].size>y&&M(h,_,y)}function M(u,h,_){let y=f[u],E=[];for(let I of y.neighbors[h])f[I].deleted||E.push({idx:I,dist:r(y.vector,f[I].vector)});let N=b(E,_);y.neighbors[h]=new Set(N)}function v(u,h){let _=ft(h,e);if(Vt(_),p.has(u)){let k=p.get(u),L=f[k];if(L.deleted){if(L.deleted=!1,L.vector=_,T++,i===-1)i=k,l=L.layer;else{for(let P=L.layer;P>=0;P--)L.neighbors[P]=new Set,m(k,P);L.layer>l&&(i=k,l=L.layer)}D.set(T)}else{L.vector=_;for(let P=L.layer;P>=0;P--){for(let $ of L.neighbors[P])f[$].neighbors[P].delete(k);L.neighbors[P]=new Set,m(k,P)}}return}let y=C(),E=f.length,N=[];for(let k=0;k<=y;k++)N.push(new Set);let I={id:u,vector:_,layer:y,neighbors:N,deleted:!1};if(f.push(I),p.set(u,E),T++,i===-1){i=E,l=y,D.set(T);return}let R=i;for(let k=l;k>y;k--)R=Y(_,R,k);for(let k=Math.min(y,l);k>=0;k--){let L=K(_,R,o,k),$=b(L,k===0?t:n);for(let G of $)G!==E&&w(E,G,k);L.length>0&&(L.sort((G,le)=>G.dist-le.dist),R=L[0].idx)}y>l&&(i=E,l=y),D.set(T)}function m(u,h){let _=i;if(_===u){let I=-1;for(let R=0;R<f.length;R++)if(R!==u&&!f[R].deleted&&f[R].layer>=h){I=R;break}if(I===-1)return;_=I}for(let I=Math.min(l,f[_].layer);I>h;I--)_=Y(f[u].vector,_,I);let y=K(f[u].vector,_,o,h),N=b(y,h===0?t:n);for(let I of N)I!==u&&w(u,I,h)}function S(u){let h=p.get(u);if(h===void 0)return!1;let _=f[h];if(_.deleted)return!1;if(_.deleted=!0,T--,D.set(T),h===i){let y=-1;for(let E=0;E<f.length;E++)f[E].deleted||(y===-1||f[E].layer>f[y].layer)&&(y=E);i=y,l=y===-1?-1:f[y].layer}return!0}function x(u,h=10){if(T===0)return[];let _=ft(u,e),y=Math.min(h,T),E=Math.max(a,y),N=i;for(let k=l;k>0;k--)N=Y(_,N,k);let I=K(_,N,E,0);I.sort((k,L)=>k.dist-L.dist);let R=[];for(let k=0;k<I.length&&R.length<y;k++){let L=f[I[k].idx];L.deleted||R.push({id:L.id,distance:I[k].dist})}return R}function g(u){let h=p.get(u);return h===void 0?!1:!f[h].deleted}function d(){f.length=0,p.clear(),i=-1,l=-1,T=0,D.set(0),V(D)}return{add:v,remove:S,search:x,has:g,size:D,destroy:d}}function ht(s,e){let n=e?.serialize??(t=>JSON.stringify(t));return{send(t){try{s.send(n(t))}catch{}},close(){try{s.close()}catch{}}}}0&&(module.exports={collection,computeScore,decay,httpTransport,knowledgeGraph,lightCollection,memoryNode,sessionSync,vectorIndex,wsTransport});
@@ -1,5 +1,5 @@
1
- import { C as CollectionOptions, b as Collection, c as MemoryMeta, S as ScoreWeights, D as DecayOptions, d as DecayFn, M as MemoryNodeOptions, a as MemoryNode, V as VectorIndexOptions, e as VectorIndex } from '../types-FP6jV-p5.cjs';
2
- export { A as AdmissionDecision, f as AdmissionPolicyFn, g as DistanceMetric, F as ForgetPolicyFn, h as VectorSearchResult } from '../types-FP6jV-p5.cjs';
1
+ import { C as CollectionOptions, b as Collection, c as MemoryMeta, S as ScoreWeights, D as DecayOptions, d as DecayFn, H as HttpTransportOptions, e as SessionTransport, K as KnowledgeGraphOptions, f as KnowledgeGraph, L as LightCollectionOptions, M as MemoryNodeOptions, a as MemoryNode, g as SessionSyncOptions, V as VectorIndexOptions, h as VectorIndex, W as WsTransportOptions } from '../types-BwBbIZux.cjs';
2
+ export { A as AddRelationOptions, i as AdmissionDecision, j as AdmissionPolicyFn, k as DistanceMetric, F as ForgetPolicyFn, R as Relation, l as SerializedMeta, m as SerializedNode, n as SessionEvent, T as TraverseOptions, o as VectorSearchResult } from '../types-BwBbIZux.cjs';
3
3
  import '../types-BohB8jJr.cjs';
4
4
  import '../protocol-fwiQ1TAS.cjs';
5
5
  import '../types-BRnNQbJn.cjs';
@@ -69,7 +69,7 @@ import '../eviction-DGPP1vHP.cjs';
69
69
  * // Stale nodes pruned before each add(); call mem.gc() for on-demand cleanup.
70
70
  * ```
71
71
  *
72
- * @seeAlso [memoryNode](./node) — individual memory node, [decay](./decay) — scoring functions, [vectorIndex](./vectorIndex) — HNSW semantic search
72
+ * @seeAlso [memoryNode](./memoryNode) — individual memory node, [vectorIndex](./vectorIndex) — HNSW semantic search
73
73
  */
74
74
  declare function collection<T>(opts?: CollectionOptions<T>): Collection<T>;
75
75
 
@@ -84,9 +84,162 @@ declare function decay(opts?: DecayOptions): DecayFn;
84
84
  */
85
85
  declare function computeScore(meta: MemoryMeta, weights?: ScoreWeights, now?: number): number;
86
86
 
87
+ /**
88
+ * Creates a `SessionTransport` that sends session events via HTTP.
89
+ *
90
+ * When `batchMs > 0`, events are collected and sent together in a single
91
+ * request after the batch window elapses. Timer usage here is at a true
92
+ * system boundary (network I/O batching), per architecture §1.18.
93
+ *
94
+ * @param url - The HTTP endpoint to POST events to.
95
+ * @param opts - Optional configuration.
96
+ *
97
+ * @returns `SessionTransport` — pass to `sessionSync()`.
98
+ *
99
+ * @example
100
+ * ```ts
101
+ * import { httpTransport, sessionSync, collection } from 'callbag-recharge/memory';
102
+ *
103
+ * const transport = httpTransport('https://api.example.com/sessions', {
104
+ * headers: { Authorization: 'Bearer token' },
105
+ * batchMs: 500,
106
+ * });
107
+ * const { dispose } = sessionSync(collection(), transport);
108
+ * ```
109
+ *
110
+ * @category memory
111
+ */
112
+ declare function httpTransport<T = unknown>(url: string, opts?: HttpTransportOptions<T>): SessionTransport<T>;
113
+
114
+ /**
115
+ * Creates a reactive knowledge graph with entity relationships, temporal
116
+ * tracking, and graph-based retrieval.
117
+ *
118
+ * @param opts - Optional configuration (all `CollectionOptions` pass through to the internal entity collection).
119
+ *
120
+ * @returns `KnowledgeGraph<T>` — entity CRUD, relation management, graph queries, reactive stores.
121
+ *
122
+ * @remarks **Entities** are stored in an internal `Collection<T>`, exposed via `.collection`. All collection features (topK, byTag, gc, summarize, admission/forget policies, eviction) are available.
123
+ * @remarks **Relations** are directed, typed edges with temporal metadata (createdAt, updatedAt, weight). Indexed by type via `typeIndex`.
124
+ * @remarks **Cascade deletion** — removing an entity automatically removes all its relations via `subscribe` on collection.nodes (§1.19).
125
+ * @remarks **Graph traversal** — BFS via `traverse()`, shortest path via `shortestPath()`, subgraph extraction via `subgraph()`.
126
+ * @remarks **Reactive queries** — `relationsOf()` and `neighborsOf()` return cached reactive stores that update when relations change.
127
+ *
128
+ * @example
129
+ * ```ts
130
+ * import { knowledgeGraph } from 'callbag-recharge/memory';
131
+ *
132
+ * const kg = knowledgeGraph<string>();
133
+ * kg.addEntity("Alice", { id: "alice" });
134
+ * kg.addEntity("Bob", { id: "bob" });
135
+ * kg.addRelation("alice", "bob", "knows", { weight: 0.9 });
136
+ *
137
+ * kg.neighbors("alice"); // [MemoryNode<"Bob">]
138
+ * kg.outgoing("alice", "knows"); // [Relation]
139
+ * ```
140
+ *
141
+ * @seeAlso [collection](./collection) — entity storage, [vectorIndex](./vectorIndex) — semantic search
142
+ * @category memory
143
+ */
144
+ declare function knowledgeGraph<T>(opts?: KnowledgeGraphOptions<T>): KnowledgeGraph<T>;
145
+
146
+ /**
147
+ * Creates a lightweight reactive collection that uses FIFO or LRU eviction
148
+ * instead of decay-scored reactive eviction. Same `Collection<T>` interface
149
+ * as `collection()` — drop-in replacement for high-throughput paths.
150
+ *
151
+ * @param opts - Optional configuration.
152
+ *
153
+ * @returns `Collection<T>` — identical interface to `collection()`.
154
+ *
155
+ * @optionsType LightCollectionOptions
156
+ * @option maxSize | number | Infinity | Maximum nodes. Evicted by FIFO or LRU on overflow.
157
+ * @option eviction | "fifo" \| "lru" | "fifo" | Eviction strategy.
158
+ * @option weights | ScoreWeights | {} | Default weights for topK scoring (eviction does NOT use scores).
159
+ * @option admissionPolicy | AdmissionPolicyFn<T> | undefined | Gate every add().
160
+ * @option forgetPolicy | ForgetPolicyFn<T> | undefined | Predicate run before each add() and during gc().
161
+ *
162
+ * @remarks **FIFO** evicts the oldest-inserted node regardless of access. **LRU** evicts the least-recently-accessed node — `get()` counts as an access.
163
+ * @remarks **No per-node subscriptions.** Unlike `collection()` which subscribes to every node's `.meta` for reactive score updates, `lightCollection` has zero per-node overhead beyond tag tracking.
164
+ *
165
+ * @example
166
+ * ```ts
167
+ * import { lightCollection } from 'callbag-recharge/memory';
168
+ *
169
+ * // FIFO buffer — oldest out
170
+ * const buf = lightCollection<string>({ maxSize: 1000 });
171
+ *
172
+ * // LRU cache — least-recently-used out
173
+ * const cache = lightCollection<string>({ maxSize: 100, eviction: "lru" });
174
+ * ```
175
+ *
176
+ * @seeAlso [collection](./collection) — decay-scored eviction, [memoryNode](./memoryNode) — individual memory node
177
+ */
178
+ declare function lightCollection<T>(opts?: LightCollectionOptions<T>): Collection<T>;
179
+
87
180
  declare function memoryNode<T>(initialContent: T, opts?: MemoryNodeOptions): MemoryNode<T>;
88
181
 
182
+ /**
183
+ * Syncs a `Collection` to a remote via a pluggable `SessionTransport`.
184
+ *
185
+ * Subscribes to `collection.nodes` for structural changes (add/remove) and
186
+ * to each node's `meta` store for content/metadata updates. All metadata
187
+ * changes — including `touch()`, `tag()`, `setImportance()` — propagate as
188
+ * `"update"` events. Sends structured diff events through the transport.
189
+ * Uses lightweight `subscribe()` throughout (single dep per subscription,
190
+ * no DIRTY/RESOLVED overhead per §1.19).
191
+ *
192
+ * `dispose()` stops syncing but does **not** close the transport — the
193
+ * caller manages transport lifecycle separately.
194
+ *
195
+ * @param col - The collection to sync.
196
+ * @param transport - Transport backend (wsTransport, httpTransport, or custom).
197
+ * @param opts - Optional configuration.
198
+ *
199
+ * @returns `{ dispose() }` — call to stop syncing.
200
+ *
201
+ * @example
202
+ * ```ts
203
+ * import { collection } from 'callbag-recharge/memory';
204
+ * import { sessionSync, wsTransport } from 'callbag-recharge/memory';
205
+ *
206
+ * const mem = collection<string>({ maxSize: 100 });
207
+ * const transport = wsTransport(new WebSocket('ws://localhost:8080'));
208
+ * const { dispose } = sessionSync(mem, transport);
209
+ *
210
+ * mem.add("hello"); // → transport receives { type: "add", nodes: [...] }
211
+ * dispose();
212
+ * transport.close(); // caller manages transport lifecycle
213
+ * ```
214
+ *
215
+ * @category memory
216
+ */
217
+ declare function sessionSync<T>(col: Collection<T>, transport: SessionTransport<T>, opts?: SessionSyncOptions): {
218
+ dispose(): void;
219
+ };
220
+
89
221
  /** Create an in-process HNSW vector index. */
90
222
  declare function vectorIndex(opts: VectorIndexOptions): VectorIndex;
91
223
 
92
- export { Collection, CollectionOptions, DecayFn, DecayOptions, MemoryMeta, MemoryNode, MemoryNodeOptions, ScoreWeights, VectorIndex, VectorIndexOptions, collection, computeScore, decay, memoryNode, vectorIndex };
224
+ /**
225
+ * Creates a `SessionTransport` that sends session events over a WebSocket.
226
+ *
227
+ * @param ws - A WebSocket instance (browser-native or compatible).
228
+ * @param opts - Optional configuration.
229
+ *
230
+ * @returns `SessionTransport` — pass to `sessionSync()`.
231
+ *
232
+ * @example
233
+ * ```ts
234
+ * import { wsTransport, sessionSync, collection } from 'callbag-recharge/memory';
235
+ *
236
+ * const ws = new WebSocket('ws://localhost:8080/sessions');
237
+ * const transport = wsTransport(ws);
238
+ * const { dispose } = sessionSync(collection(), transport);
239
+ * ```
240
+ *
241
+ * @category memory
242
+ */
243
+ declare function wsTransport<T = unknown>(ws: WebSocket, opts?: WsTransportOptions<T>): SessionTransport<T>;
244
+
245
+ export { Collection, CollectionOptions, DecayFn, DecayOptions, HttpTransportOptions, KnowledgeGraph, KnowledgeGraphOptions, LightCollectionOptions, MemoryMeta, MemoryNode, MemoryNodeOptions, ScoreWeights, SessionSyncOptions, SessionTransport, VectorIndex, VectorIndexOptions, WsTransportOptions, collection, computeScore, decay, httpTransport, knowledgeGraph, lightCollection, memoryNode, sessionSync, vectorIndex, wsTransport };
@@ -1,5 +1,5 @@
1
- import { C as CollectionOptions, b as Collection, c as MemoryMeta, S as ScoreWeights, D as DecayOptions, d as DecayFn, M as MemoryNodeOptions, a as MemoryNode, V as VectorIndexOptions, e as VectorIndex } from '../types-9JbU1qd1.js';
2
- export { A as AdmissionDecision, f as AdmissionPolicyFn, g as DistanceMetric, F as ForgetPolicyFn, h as VectorSearchResult } from '../types-9JbU1qd1.js';
1
+ import { C as CollectionOptions, b as Collection, c as MemoryMeta, S as ScoreWeights, D as DecayOptions, d as DecayFn, H as HttpTransportOptions, e as SessionTransport, K as KnowledgeGraphOptions, f as KnowledgeGraph, L as LightCollectionOptions, M as MemoryNodeOptions, a as MemoryNode, g as SessionSyncOptions, V as VectorIndexOptions, h as VectorIndex, W as WsTransportOptions } from '../types-DtkjWIED.js';
2
+ export { A as AddRelationOptions, i as AdmissionDecision, j as AdmissionPolicyFn, k as DistanceMetric, F as ForgetPolicyFn, R as Relation, l as SerializedMeta, m as SerializedNode, n as SessionEvent, T as TraverseOptions, o as VectorSearchResult } from '../types-DtkjWIED.js';
3
3
  import '../types-CB1htCM8.js';
4
4
  import '../protocol-fwiQ1TAS.js';
5
5
  import '../types-n54oEEx_.js';
@@ -69,7 +69,7 @@ import '../eviction-DGPP1vHP.js';
69
69
  * // Stale nodes pruned before each add(); call mem.gc() for on-demand cleanup.
70
70
  * ```
71
71
  *
72
- * @seeAlso [memoryNode](./node) — individual memory node, [decay](./decay) — scoring functions, [vectorIndex](./vectorIndex) — HNSW semantic search
72
+ * @seeAlso [memoryNode](./memoryNode) — individual memory node, [vectorIndex](./vectorIndex) — HNSW semantic search
73
73
  */
74
74
  declare function collection<T>(opts?: CollectionOptions<T>): Collection<T>;
75
75
 
@@ -84,9 +84,162 @@ declare function decay(opts?: DecayOptions): DecayFn;
84
84
  */
85
85
  declare function computeScore(meta: MemoryMeta, weights?: ScoreWeights, now?: number): number;
86
86
 
87
+ /**
88
+ * Creates a `SessionTransport` that sends session events via HTTP.
89
+ *
90
+ * When `batchMs > 0`, events are collected and sent together in a single
91
+ * request after the batch window elapses. Timer usage here is at a true
92
+ * system boundary (network I/O batching), per architecture §1.18.
93
+ *
94
+ * @param url - The HTTP endpoint to POST events to.
95
+ * @param opts - Optional configuration.
96
+ *
97
+ * @returns `SessionTransport` — pass to `sessionSync()`.
98
+ *
99
+ * @example
100
+ * ```ts
101
+ * import { httpTransport, sessionSync, collection } from 'callbag-recharge/memory';
102
+ *
103
+ * const transport = httpTransport('https://api.example.com/sessions', {
104
+ * headers: { Authorization: 'Bearer token' },
105
+ * batchMs: 500,
106
+ * });
107
+ * const { dispose } = sessionSync(collection(), transport);
108
+ * ```
109
+ *
110
+ * @category memory
111
+ */
112
+ declare function httpTransport<T = unknown>(url: string, opts?: HttpTransportOptions<T>): SessionTransport<T>;
113
+
114
+ /**
115
+ * Creates a reactive knowledge graph with entity relationships, temporal
116
+ * tracking, and graph-based retrieval.
117
+ *
118
+ * @param opts - Optional configuration (all `CollectionOptions` pass through to the internal entity collection).
119
+ *
120
+ * @returns `KnowledgeGraph<T>` — entity CRUD, relation management, graph queries, reactive stores.
121
+ *
122
+ * @remarks **Entities** are stored in an internal `Collection<T>`, exposed via `.collection`. All collection features (topK, byTag, gc, summarize, admission/forget policies, eviction) are available.
123
+ * @remarks **Relations** are directed, typed edges with temporal metadata (createdAt, updatedAt, weight). Indexed by type via `typeIndex`.
124
+ * @remarks **Cascade deletion** — removing an entity automatically removes all its relations via `subscribe` on collection.nodes (§1.19).
125
+ * @remarks **Graph traversal** — BFS via `traverse()`, shortest path via `shortestPath()`, subgraph extraction via `subgraph()`.
126
+ * @remarks **Reactive queries** — `relationsOf()` and `neighborsOf()` return cached reactive stores that update when relations change.
127
+ *
128
+ * @example
129
+ * ```ts
130
+ * import { knowledgeGraph } from 'callbag-recharge/memory';
131
+ *
132
+ * const kg = knowledgeGraph<string>();
133
+ * kg.addEntity("Alice", { id: "alice" });
134
+ * kg.addEntity("Bob", { id: "bob" });
135
+ * kg.addRelation("alice", "bob", "knows", { weight: 0.9 });
136
+ *
137
+ * kg.neighbors("alice"); // [MemoryNode<"Bob">]
138
+ * kg.outgoing("alice", "knows"); // [Relation]
139
+ * ```
140
+ *
141
+ * @seeAlso [collection](./collection) — entity storage, [vectorIndex](./vectorIndex) — semantic search
142
+ * @category memory
143
+ */
144
+ declare function knowledgeGraph<T>(opts?: KnowledgeGraphOptions<T>): KnowledgeGraph<T>;
145
+
146
+ /**
147
+ * Creates a lightweight reactive collection that uses FIFO or LRU eviction
148
+ * instead of decay-scored reactive eviction. Same `Collection<T>` interface
149
+ * as `collection()` — drop-in replacement for high-throughput paths.
150
+ *
151
+ * @param opts - Optional configuration.
152
+ *
153
+ * @returns `Collection<T>` — identical interface to `collection()`.
154
+ *
155
+ * @optionsType LightCollectionOptions
156
+ * @option maxSize | number | Infinity | Maximum nodes. Evicted by FIFO or LRU on overflow.
157
+ * @option eviction | "fifo" \| "lru" | "fifo" | Eviction strategy.
158
+ * @option weights | ScoreWeights | {} | Default weights for topK scoring (eviction does NOT use scores).
159
+ * @option admissionPolicy | AdmissionPolicyFn<T> | undefined | Gate every add().
160
+ * @option forgetPolicy | ForgetPolicyFn<T> | undefined | Predicate run before each add() and during gc().
161
+ *
162
+ * @remarks **FIFO** evicts the oldest-inserted node regardless of access. **LRU** evicts the least-recently-accessed node — `get()` counts as an access.
163
+ * @remarks **No per-node subscriptions.** Unlike `collection()` which subscribes to every node's `.meta` for reactive score updates, `lightCollection` has zero per-node overhead beyond tag tracking.
164
+ *
165
+ * @example
166
+ * ```ts
167
+ * import { lightCollection } from 'callbag-recharge/memory';
168
+ *
169
+ * // FIFO buffer — oldest out
170
+ * const buf = lightCollection<string>({ maxSize: 1000 });
171
+ *
172
+ * // LRU cache — least-recently-used out
173
+ * const cache = lightCollection<string>({ maxSize: 100, eviction: "lru" });
174
+ * ```
175
+ *
176
+ * @seeAlso [collection](./collection) — decay-scored eviction, [memoryNode](./memoryNode) — individual memory node
177
+ */
178
+ declare function lightCollection<T>(opts?: LightCollectionOptions<T>): Collection<T>;
179
+
87
180
  declare function memoryNode<T>(initialContent: T, opts?: MemoryNodeOptions): MemoryNode<T>;
88
181
 
182
+ /**
183
+ * Syncs a `Collection` to a remote via a pluggable `SessionTransport`.
184
+ *
185
+ * Subscribes to `collection.nodes` for structural changes (add/remove) and
186
+ * to each node's `meta` store for content/metadata updates. All metadata
187
+ * changes — including `touch()`, `tag()`, `setImportance()` — propagate as
188
+ * `"update"` events. Sends structured diff events through the transport.
189
+ * Uses lightweight `subscribe()` throughout (single dep per subscription,
190
+ * no DIRTY/RESOLVED overhead per §1.19).
191
+ *
192
+ * `dispose()` stops syncing but does **not** close the transport — the
193
+ * caller manages transport lifecycle separately.
194
+ *
195
+ * @param col - The collection to sync.
196
+ * @param transport - Transport backend (wsTransport, httpTransport, or custom).
197
+ * @param opts - Optional configuration.
198
+ *
199
+ * @returns `{ dispose() }` — call to stop syncing.
200
+ *
201
+ * @example
202
+ * ```ts
203
+ * import { collection } from 'callbag-recharge/memory';
204
+ * import { sessionSync, wsTransport } from 'callbag-recharge/memory';
205
+ *
206
+ * const mem = collection<string>({ maxSize: 100 });
207
+ * const transport = wsTransport(new WebSocket('ws://localhost:8080'));
208
+ * const { dispose } = sessionSync(mem, transport);
209
+ *
210
+ * mem.add("hello"); // → transport receives { type: "add", nodes: [...] }
211
+ * dispose();
212
+ * transport.close(); // caller manages transport lifecycle
213
+ * ```
214
+ *
215
+ * @category memory
216
+ */
217
+ declare function sessionSync<T>(col: Collection<T>, transport: SessionTransport<T>, opts?: SessionSyncOptions): {
218
+ dispose(): void;
219
+ };
220
+
89
221
  /** Create an in-process HNSW vector index. */
90
222
  declare function vectorIndex(opts: VectorIndexOptions): VectorIndex;
91
223
 
92
- export { Collection, CollectionOptions, DecayFn, DecayOptions, MemoryMeta, MemoryNode, MemoryNodeOptions, ScoreWeights, VectorIndex, VectorIndexOptions, collection, computeScore, decay, memoryNode, vectorIndex };
224
+ /**
225
+ * Creates a `SessionTransport` that sends session events over a WebSocket.
226
+ *
227
+ * @param ws - A WebSocket instance (browser-native or compatible).
228
+ * @param opts - Optional configuration.
229
+ *
230
+ * @returns `SessionTransport` — pass to `sessionSync()`.
231
+ *
232
+ * @example
233
+ * ```ts
234
+ * import { wsTransport, sessionSync, collection } from 'callbag-recharge/memory';
235
+ *
236
+ * const ws = new WebSocket('ws://localhost:8080/sessions');
237
+ * const transport = wsTransport(ws);
238
+ * const { dispose } = sessionSync(collection(), transport);
239
+ * ```
240
+ *
241
+ * @category memory
242
+ */
243
+ declare function wsTransport<T = unknown>(ws: WebSocket, opts?: WsTransportOptions<T>): SessionTransport<T>;
244
+
245
+ export { Collection, CollectionOptions, DecayFn, DecayOptions, HttpTransportOptions, KnowledgeGraph, KnowledgeGraphOptions, LightCollectionOptions, MemoryMeta, MemoryNode, MemoryNodeOptions, ScoreWeights, SessionSyncOptions, SessionTransport, VectorIndex, VectorIndexOptions, WsTransportOptions, collection, computeScore, decay, httpTransport, knowledgeGraph, lightCollection, memoryNode, sessionSync, vectorIndex, wsTransport };