@easbot/memory 0.1.11 → 0.1.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,7 +1,4 @@
1
- 'use strict';var types=require('@easbot/types'),ie=require('jieba-wasm'),utils=require('@easbot/utils'),Ee=require('path'),se=require('fs/promises'),ma=require('fs'),Qa=require('zod'),url=require('url'),events=require('events'),fn=require('stream'),string_decoder=require('string_decoder'),oh=require('better-sqlite3'),crypto=require('crypto'),ai$1=require('ai');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var ie__namespace=/*#__PURE__*/_interopNamespace(ie);var Ee__default=/*#__PURE__*/_interopDefault(Ee);var se__default=/*#__PURE__*/_interopDefault(se);var ma__namespace=/*#__PURE__*/_interopNamespace(ma);var Qa__default=/*#__PURE__*/_interopDefault(Qa);var fn__default=/*#__PURE__*/_interopDefault(fn);var oh__default=/*#__PURE__*/_interopDefault(oh);var Jn=Object.defineProperty;var sr=i=>{throw TypeError(i)};var Kn=(i,t,e)=>t in i?Jn(i,t,{enumerable:true,configurable:true,writable:true,value:e}):i[t]=e;var p=(i,t,e)=>Kn(i,typeof t!="symbol"?t+"":t,e),vs=(i,t,e)=>t.has(i)||sr("Cannot "+e);var n=(i,t,e)=>(vs(i,t,"read from private field"),e?e.call(i):t.get(i)),w=(i,t,e)=>t.has(i)?sr("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(i):t.set(i,e),m=(i,t,e,s)=>(vs(i,t,"write to private field"),t.set(i,e),e),y=(i,t,e)=>(vs(i,t,"access private method"),e);var Hi=(i,t,e,s)=>({set _(r){m(i,t,r);},get _(){return n(i,t,s)}});var Qn=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,ct=Qn();var Ts=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","other"],Yt=class extends Error{constructor(e,s,r){super(e,{cause:r});this.code=s;this.cause=r;this.name="MemoryError";}},pt=class extends Yt{constructor(t,e){super(t,"MEMORY_VALIDATION_ERROR",e),this.name="MemoryValidationError";}},ei=class extends Yt{constructor(t){super(`Memory not found: ${t}`,"MEMORY_NOT_FOUND"),this.name="MemoryNotFoundError";}},ii=class extends Yt{constructor(t){super(t,"MEMORY_PERMISSION_ERROR"),this.name="MemoryPermissionError";}},Q=class extends Yt{constructor(t,e){super(t,"MEMORY_DATABASE_ERROR",e),this.name="MemoryDatabaseError";}},Mt=class extends Yt{constructor(t,e){super(t,"MEMORY_FILE_ERROR",e),this.name="MemoryFileError";}},si=class extends Yt{constructor(t,e){super(t,"MEMORY_SEARCH_ERROR",e),this.name="MemorySearchError";}},ri=class extends Yt{constructor(t,e){super(t,"MEMORY_EMBEDDING_ERROR",e),this.name="MemoryEmbeddingError";}},Zn=(l=>(l.VALIDATION_ERROR="MEMORY_VALIDATION_ERROR",l.NOT_FOUND="MEMORY_NOT_FOUND",l.PERMISSION_ERROR="MEMORY_PERMISSION_ERROR",l.DATABASE_ERROR="MEMORY_DATABASE_ERROR",l.FILE_ERROR="MEMORY_FILE_ERROR",l.SEARCH_ERROR="MEMORY_SEARCH_ERROR",l.EMBEDDING_ERROR="MEMORY_EMBEDDING_ERROR",l))(Zn||{});var Jr=(i,t,e)=>{let s=i instanceof RegExp?rr(i,e):i,r=t instanceof RegExp?rr(t,e):t,o=s!==null&&r!=null&&to(s,r,e);return o&&{start:o[0],end:o[1],pre:e.slice(0,o[0]),body:e.slice(o[0]+s.length,o[1]),post:e.slice(o[1]+r.length)}},rr=(i,t)=>{let e=t.match(i);return e?e[0]:null},to=(i,t,e)=>{let s,r,o,a,l,h=e.indexOf(i),c=e.indexOf(t,h+1),u=h;if(h>=0&&c>0){if(i===t)return [h,c];for(s=[],o=e.length;u>=0&&!l;){if(u===h)s.push(u),h=e.indexOf(i,u+1);else if(s.length===1){let d=s.pop();d!==void 0&&(l=[d,c]);}else r=s.pop(),r!==void 0&&r<o&&(o=r,a=c),c=e.indexOf(t,u+1);u=h<c&&h>=0?h:c;}s.length&&a!==void 0&&(l=[o,a]);}return l},Kr="\0SLASH"+Math.random()+"\0",Qr="\0OPEN"+Math.random()+"\0",qs="\0CLOSE"+Math.random()+"\0",Zr="\0COMMA"+Math.random()+"\0",tn="\0PERIOD"+Math.random()+"\0",eo=new RegExp(Kr,"g"),io=new RegExp(Qr,"g"),so=new RegExp(qs,"g"),ro=new RegExp(Zr,"g"),no=new RegExp(tn,"g"),oo=/\\\\/g,ao=/\\{/g,ho=/\\}/g,lo=/\\,/g,co=/\\./g,uo=1e5;function As(i){return isNaN(i)?i.charCodeAt(0):parseInt(i,10)}function po(i){return i.replace(oo,Kr).replace(ao,Qr).replace(ho,qs).replace(lo,Zr).replace(co,tn)}function mo(i){return i.replace(eo,"\\").replace(io,"{").replace(so,"}").replace(ro,",").replace(no,".")}function en(i){if(!i)return [""];let t=[],e=Jr("{","}",i);if(!e)return i.split(",");let{pre:s,body:r,post:o}=e,a=s.split(",");a[a.length-1]+="{"+r+"}";let l=en(o);return o.length&&(a[a.length-1]+=l.shift(),a.push.apply(a,l)),t.push.apply(t,a),t}function fo(i,t={}){if(!i)return [];let{max:e=uo}=t;return i.slice(0,2)==="{}"&&(i="\\{\\}"+i.slice(2)),di(po(i),e,true).map(mo)}function go(i){return "{"+i+"}"}function yo(i){return /^-?0\d/.test(i)}function wo(i,t){return i<=t}function bo(i,t){return i>=t}function di(i,t,e){let s=[],r=Jr("{","}",i);if(!r)return [i];let o=r.pre,a=r.post.length?di(r.post,t,false):[""];if(/\$$/.test(r.pre))for(let l=0;l<a.length&&l<t;l++){let h=o+"{"+r.body+"}"+a[l];s.push(h);}else {let l=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(r.body),h=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(r.body),c=l||h,u=r.body.indexOf(",")>=0;if(!c&&!u)return r.post.match(/,(?!,).*\}/)?(i=r.pre+"{"+r.body+qs+r.post,di(i,t,true)):[i];let d;if(c)d=r.body.split(/\.\./);else if(d=en(r.body),d.length===1&&d[0]!==void 0&&(d=di(d[0],t,false).map(go),d.length===1))return a.map(g=>r.pre+d[0]+g);let f;if(c&&d[0]!==void 0&&d[1]!==void 0){let g=As(d[0]),b=As(d[1]),E=Math.max(d[0].length,d[1].length),T=d.length===3&&d[2]!==void 0?Math.abs(As(d[2])):1,S=wo;b<g&&(T*=-1,S=bo);let x=d.some(yo);f=[];for(let R=g;S(R,b);R+=T){let A;if(h)A=String.fromCharCode(R),A==="\\"&&(A="");else if(A=String(R),x){let _=E-A.length;if(_>0){let N=new Array(_+1).join("0");R<0?A="-"+N+A.slice(1):A=N+A;}}f.push(A);}}else {f=[];for(let g=0;g<d.length;g++)f.push.apply(f,di(d[g],t,false));}for(let g=0;g<f.length;g++)for(let b=0;b<a.length&&s.length<t;b++){let E=o+f[g]+a[b];(!e||c||E)&&s.push(E);}}return s}var cs=i=>{if(typeof i!="string")throw new TypeError("invalid pattern");if(i.length>65536)throw new TypeError("pattern is too long")},Eo={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",true],"[:alpha:]":["\\p{L}\\p{Nl}",true],"[:ascii:]":["\\x00-\\x7f",false],"[:blank:]":["\\p{Zs}\\t",true],"[:cntrl:]":["\\p{Cc}",true],"[:digit:]":["\\p{Nd}",true],"[:graph:]":["\\p{Z}\\p{C}",true,true],"[:lower:]":["\\p{Ll}",true],"[:print:]":["\\p{C}",true],"[:punct:]":["\\p{P}",true],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",true],"[:upper:]":["\\p{Lu}",true],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",true],"[:xdigit:]":["A-Fa-f0-9",false]},ni=i=>i.replace(/[[\]\\-]/g,"\\$&"),So=i=>i.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),nr=i=>i.join(""),vo=(i,t)=>{let e=t;if(i.charAt(e)!=="[")throw new Error("not in a brace expression");let s=[],r=[],o=e+1,a=false,l=false,h=false,c=false,u=e,d="";t:for(;o<i.length;){let b=i.charAt(o);if((b==="!"||b==="^")&&o===e+1){c=true,o++;continue}if(b==="]"&&a&&!h){u=o+1;break}if(a=true,b==="\\"&&!h){h=true,o++;continue}if(b==="["&&!h){for(let[E,[T,S,x]]of Object.entries(Eo))if(i.startsWith(E,o)){if(d)return ["$.",false,i.length-e,true];o+=E.length,x?r.push(T):s.push(T),l=l||S;continue t}}if(h=false,d){b>d?s.push(ni(d)+"-"+ni(b)):b===d&&s.push(ni(b)),d="",o++;continue}if(i.startsWith("-]",o+1)){s.push(ni(b+"-")),o+=2;continue}if(i.startsWith("-",o+1)){d=b,o+=2;continue}s.push(ni(b)),o++;}if(u<o)return ["",false,0,false];if(!s.length&&!r.length)return ["$.",false,i.length-e,true];if(r.length===0&&s.length===1&&/^\\?.$/.test(s[0])&&!c){let b=s[0].length===2?s[0].slice(-1):s[0];return [So(b),false,u-e,false]}let f="["+(c?"^":"")+nr(s)+"]",g="["+(c?"":"^")+nr(r)+"]";return [s.length&&r.length?"("+f+"|"+g+")":s.length?f:g,l,u-e,true]},$e=(i,{windowsPathsNoEscape:t=false,magicalBraces:e=true}={})=>e?t?i.replace(/\[([^\/\\])\]/g,"$1"):i.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):t?i.replace(/\[([^\/\\{}])\]/g,"$1"):i.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1"),To=new Set(["!","?","+","*","@"]),or=i=>To.has(i),Ro="(?!(?:^|/)\\.\\.?(?:$|/))",qi="(?!\\.)",_o=new Set(["[","."]),Ao=new Set(["..","."]),Mo=new Set("().*{}+?[]^$\\!"),xo=i=>i.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Vs="[^/]",ar=Vs+"*?",hr=Vs+"+?",j,q,Vt,L,W,ce,Ae,de,$t,Me,wi,Ce,rn,ye,K,is,Ls,nn,sn=(K=class{constructor(t,e,s={}){w(this,Ce);p(this,"type");w(this,j);w(this,q);w(this,Vt,false);w(this,L,[]);w(this,W);w(this,ce);w(this,Ae);w(this,de,false);w(this,$t);w(this,Me);w(this,wi,false);this.type=t,t&&m(this,q,true),m(this,W,e),m(this,j,n(this,W)?n(n(this,W),j):this),m(this,$t,n(this,j)===this?s:n(n(this,j),$t)),m(this,Ae,n(this,j)===this?[]:n(n(this,j),Ae)),t==="!"&&!n(n(this,j),de)&&n(this,Ae).push(this),m(this,ce,n(this,W)?n(n(this,W),L).length:0);}get hasMagic(){if(n(this,q)!==void 0)return n(this,q);for(let t of n(this,L))if(typeof t!="string"&&(t.type||t.hasMagic))return m(this,q,true);return n(this,q)}toString(){return n(this,Me)!==void 0?n(this,Me):this.type?m(this,Me,this.type+"("+n(this,L).map(t=>String(t)).join("|")+")"):m(this,Me,n(this,L).map(t=>String(t)).join(""))}push(...t){for(let e of t)if(e!==""){if(typeof e!="string"&&!(e instanceof K&&n(e,W)===this))throw new Error("invalid part: "+e);n(this,L).push(e);}}toJSON(){let t=this.type===null?n(this,L).slice().map(e=>typeof e=="string"?e:e.toJSON()):[this.type,...n(this,L).map(e=>e.toJSON())];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===n(this,j)||n(n(this,j),de)&&n(this,W)?.type==="!")&&t.push({}),t}isStart(){if(n(this,j)===this)return true;if(!n(this,W)?.isStart())return false;if(n(this,ce)===0)return true;let t=n(this,W);for(let e=0;e<n(this,ce);e++){let s=n(t,L)[e];if(!(s instanceof K&&s.type==="!"))return false}return true}isEnd(){if(n(this,j)===this||n(this,W)?.type==="!")return true;if(!n(this,W)?.isEnd())return false;if(!this.type)return n(this,W)?.isEnd();let t=n(this,W)?n(n(this,W),L).length:0;return n(this,ce)===t-1}copyIn(t){typeof t=="string"?this.push(t):this.push(t.clone(this));}clone(t){let e=new K(this.type,t);for(let s of n(this,L))e.copyIn(s);return e}static fromGlob(t,e={}){var r;let s=new K(null,void 0,e);return y(r=K,ye,is).call(r,t,s,0,e),s}toMMPattern(){if(this!==n(this,j))return n(this,j).toMMPattern();let t=this.toString(),[e,s,r,o]=this.toRegExpSource();if(!(r||n(this,q)||n(this,$t).nocase&&!n(this,$t).nocaseMagicOnly&&t.toUpperCase()!==t.toLowerCase()))return s;let a=(n(this,$t).nocase?"i":"")+(o?"u":"");return Object.assign(new RegExp(`^${e}$`,a),{_src:e,_glob:t})}get options(){return n(this,$t)}toRegExpSource(t){let e=t??!!n(this,$t).dot;if(n(this,j)===this&&y(this,Ce,rn).call(this),!this.type){let h=this.isStart()&&this.isEnd()&&!n(this,L).some(f=>typeof f!="string"),c=n(this,L).map(f=>{var S;let[g,b,E,T]=typeof f=="string"?y(S=K,ye,nn).call(S,f,n(this,q),h):f.toRegExpSource(t);return m(this,q,n(this,q)||E),m(this,Vt,n(this,Vt)||T),g}).join(""),u="";if(this.isStart()&&typeof n(this,L)[0]=="string"&&!(n(this,L).length===1&&Ao.has(n(this,L)[0]))){let f=_o,g=e&&f.has(c.charAt(0))||c.startsWith("\\.")&&f.has(c.charAt(2))||c.startsWith("\\.\\.")&&f.has(c.charAt(4)),b=!e&&!t&&f.has(c.charAt(0));u=g?Ro:b?qi:"";}let d="";return this.isEnd()&&n(n(this,j),de)&&n(this,W)?.type==="!"&&(d="(?:$|\\/)"),[u+c+d,$e(c),m(this,q,!!n(this,q)),n(this,Vt)]}let s=this.type==="*"||this.type==="+",r=this.type==="!"?"(?:(?!(?:":"(?:",o=y(this,Ce,Ls).call(this,e);if(this.isStart()&&this.isEnd()&&!o&&this.type!=="!"){let h=this.toString();return m(this,L,[h]),this.type=null,m(this,q,void 0),[h,$e(this.toString()),false,false]}let a=!s||t||e||!qi?"":y(this,Ce,Ls).call(this,true);a===o&&(a=""),a&&(o=`(?:${o})(?:${a})*?`);let l="";if(this.type==="!"&&n(this,wi))l=(this.isStart()&&!e?qi:"")+hr;else {let h=this.type==="!"?"))"+(this.isStart()&&!e&&!t?qi:"")+ar+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&a?")":this.type==="*"&&a?")?":`)${this.type}`;l=r+o+h;}return [l,$e(o),m(this,q,!!n(this,q)),n(this,Vt)]}},j=new WeakMap,q=new WeakMap,Vt=new WeakMap,L=new WeakMap,W=new WeakMap,ce=new WeakMap,Ae=new WeakMap,de=new WeakMap,$t=new WeakMap,Me=new WeakMap,wi=new WeakMap,Ce=new WeakSet,rn=function(){if(this!==n(this,j))throw new Error("should only call on root");if(n(this,de))return this;this.toString(),m(this,de,true);let t;for(;t=n(this,Ae).pop();){if(t.type!=="!")continue;let e=t,s=n(e,W);for(;s;){for(let r=n(e,ce)+1;!s.type&&r<n(s,L).length;r++)for(let o of n(t,L)){if(typeof o=="string")throw new Error("string part in extglob AST??");o.copyIn(n(s,L)[r]);}e=s,s=n(e,W);}}return this},ye=new WeakSet,is=function(t,e,s,r){var g,b;let o=false,a=false,l=-1,h=false;if(e.type===null){let E=s,T="";for(;E<t.length;){let S=t.charAt(E++);if(o||S==="\\"){o=!o,T+=S;continue}if(a){E===l+1?(S==="^"||S==="!")&&(h=true):S==="]"&&!(E===l+2&&h)&&(a=false),T+=S;continue}else if(S==="["){a=true,l=E,h=false,T+=S;continue}if(!r.noext&&or(S)&&t.charAt(E)==="("){e.push(T),T="";let x=new K(S,e);E=y(g=K,ye,is).call(g,t,x,E,r),e.push(x);continue}T+=S;}return e.push(T),E}let c=s+1,u=new K(null,e),d=[],f="";for(;c<t.length;){let E=t.charAt(c++);if(o||E==="\\"){o=!o,f+=E;continue}if(a){c===l+1?(E==="^"||E==="!")&&(h=true):E==="]"&&!(c===l+2&&h)&&(a=false),f+=E;continue}else if(E==="["){a=true,l=c,h=false,f+=E;continue}if(or(E)&&t.charAt(c)==="("){u.push(f),f="";let T=new K(E,u);u.push(T),c=y(b=K,ye,is).call(b,t,T,c,r);continue}if(E==="|"){u.push(f),f="",d.push(u),u=new K(null,e);continue}if(E===")")return f===""&&n(e,L).length===0&&m(e,wi,true),u.push(f),f="",e.push(...d,u),c;f+=E;}return e.type=null,m(e,q,void 0),m(e,L,[t.substring(s-1)]),c},Ls=function(t){return n(this,L).map(e=>{if(typeof e=="string")throw new Error("string type in extglob ast??");let[s,r,o,a]=e.toRegExpSource(t);return m(this,Vt,n(this,Vt)||a),s}).filter(e=>!(this.isStart()&&this.isEnd())||!!e).join("|")},nn=function(t,e,s=false){let r=false,o="",a=false,l=false;for(let h=0;h<t.length;h++){let c=t.charAt(h);if(r){r=false,o+=(Mo.has(c)?"\\":"")+c;continue}if(c==="*"){if(l)continue;l=true,o+=s&&/^[*]+$/.test(t)?hr:ar,e=true;continue}else l=false;if(c==="\\"){h===t.length-1?o+="\\\\":r=true;continue}if(c==="["){let[u,d,f,g]=vo(t,h);if(f){o+=u,a=a||d,h+=f-1,e=e||g;continue}}if(c==="?"){o+=Vs,e=true;continue}o+=xo(c);}return [o,$e(t),!!e,a]},w(K,ye),K),on=(i,{windowsPathsNoEscape:t=false,magicalBraces:e=false}={})=>e?t?i.replace(/[?*()[\]{}]/g,"[$&]"):i.replace(/[?*()[\]\\{}]/g,"\\$&"):t?i.replace(/[?*()[\]]/g,"[$&]"):i.replace(/[?*()[\]\\]/g,"\\$&"),ht=(i,t,e={})=>(cs(t),!e.nocomment&&t.charAt(0)==="#"?false:new we(t,e).match(i)),Oo=/^\*+([^+@!?\*\[\(]*)$/,Io=i=>t=>!t.startsWith(".")&&t.endsWith(i),No=i=>t=>t.endsWith(i),Fo=i=>(i=i.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(i)),ko=i=>(i=i.toLowerCase(),t=>t.toLowerCase().endsWith(i)),Lo=/^\*+\.\*+$/,Do=i=>!i.startsWith(".")&&i.includes("."),Co=i=>i!=="."&&i!==".."&&i.includes("."),Po=/^\.\*+$/,Wo=i=>i!=="."&&i!==".."&&i.startsWith("."),zo=/^\*+$/,jo=i=>i.length!==0&&!i.startsWith("."),$o=i=>i.length!==0&&i!=="."&&i!=="..",Uo=/^\?+([^+@!?\*\[\(]*)?$/,Bo=([i,t=""])=>{let e=an([i]);return t?(t=t.toLowerCase(),s=>e(s)&&s.toLowerCase().endsWith(t)):e},Go=([i,t=""])=>{let e=hn([i]);return t?(t=t.toLowerCase(),s=>e(s)&&s.toLowerCase().endsWith(t)):e},Xo=([i,t=""])=>{let e=hn([i]);return t?s=>e(s)&&s.endsWith(t):e},Yo=([i,t=""])=>{let e=an([i]);return t?s=>e(s)&&s.endsWith(t):e},an=([i])=>{let t=i.length;return e=>e.length===t&&!e.startsWith(".")},hn=([i])=>{let t=i.length;return e=>e.length===t&&e!=="."&&e!==".."},ln=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",lr={win32:{sep:"\\"},posix:{sep:"/"}},Ho=ln==="win32"?lr.win32.sep:lr.posix.sep;ht.sep=Ho;var at=Symbol("globstar **");ht.GLOBSTAR=at;var qo="[^/]",Vo=qo+"*?",Jo="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",Ko="(?:(?!(?:\\/|^)\\.).)*?",Qo=(i,t={})=>e=>ht(e,i,t);ht.filter=Qo;var Et=(i,t={})=>Object.assign({},i,t),Zo=i=>{if(!i||typeof i!="object"||!Object.keys(i).length)return ht;let t=ht;return Object.assign((e,s,r={})=>t(e,s,Et(i,r)),{Minimatch:class extends t.Minimatch{constructor(e,s={}){super(e,Et(i,s));}static defaults(e){return t.defaults(Et(i,e)).Minimatch}},AST:class extends t.AST{constructor(e,s,r={}){super(e,s,Et(i,r));}static fromGlob(e,s={}){return t.AST.fromGlob(e,Et(i,s))}},unescape:(e,s={})=>t.unescape(e,Et(i,s)),escape:(e,s={})=>t.escape(e,Et(i,s)),filter:(e,s={})=>t.filter(e,Et(i,s)),defaults:e=>t.defaults(Et(i,e)),makeRe:(e,s={})=>t.makeRe(e,Et(i,s)),braceExpand:(e,s={})=>t.braceExpand(e,Et(i,s)),match:(e,s,r={})=>t.match(e,s,Et(i,r)),sep:t.sep,GLOBSTAR:at})};ht.defaults=Zo;var cn=(i,t={})=>(cs(i),t.nobrace||!/\{(?:(?!\{).)*\}/.test(i)?[i]:fo(i,{max:t.braceExpandMax}));ht.braceExpand=cn;var ta=(i,t={})=>new we(i,t).makeRe();ht.makeRe=ta;var ea=(i,t,e={})=>{let s=new we(t,e);return i=i.filter(r=>s.match(r)),s.options.nonull&&!i.length&&i.push(t),i};ht.match=ea;var cr=/[?*]|[+@!]\(.*?\)|\[|\]/,ia=i=>i.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),we=class{constructor(i,t={}){p(this,"options");p(this,"set");p(this,"pattern");p(this,"windowsPathsNoEscape");p(this,"nonegate");p(this,"negate");p(this,"comment");p(this,"empty");p(this,"preserveMultipleSlashes");p(this,"partial");p(this,"globSet");p(this,"globParts");p(this,"nocase");p(this,"isWindows");p(this,"platform");p(this,"windowsNoMagicRoot");p(this,"regexp");cs(i),t=t||{},this.options=t,this.pattern=i,this.platform=t.platform||ln,this.isWindows=this.platform==="win32";let e="allowWindowsEscape";this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t[e]===false,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=false,this.nonegate=!!t.nonegate,this.comment=false,this.empty=false,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot!==void 0?t.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make();}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return true;for(let i of this.set)for(let t of i)if(typeof t!="string")return true;return false}debug(...i){}make(){let i=this.pattern,t=this.options;if(!t.nocomment&&i.charAt(0)==="#"){this.comment=true;return}if(!i){this.empty=true;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...r)=>console.error(...r)),this.debug(this.pattern,this.globSet);let e=this.globSet.map(r=>this.slashSplit(r));this.globParts=this.preprocess(e),this.debug(this.pattern,this.globParts);let s=this.globParts.map((r,o,a)=>{if(this.isWindows&&this.windowsNoMagicRoot){let l=r[0]===""&&r[1]===""&&(r[2]==="?"||!cr.test(r[2]))&&!cr.test(r[3]),h=/^[a-z]:/i.test(r[0]);if(l)return [...r.slice(0,4),...r.slice(4).map(c=>this.parse(c))];if(h)return [r[0],...r.slice(1).map(c=>this.parse(c))]}return r.map(l=>this.parse(l))});if(this.debug(this.pattern,s),this.set=s.filter(r=>r.indexOf(false)===-1),this.isWindows)for(let r=0;r<this.set.length;r++){let o=this.set[r];o[0]===""&&o[1]===""&&this.globParts[r][2]==="?"&&typeof o[3]=="string"&&/^[a-z]:$/i.test(o[3])&&(o[2]="?");}this.debug(this.pattern,this.set);}preprocess(i){if(this.options.noglobstar)for(let e=0;e<i.length;e++)for(let s=0;s<i[e].length;s++)i[e][s]==="**"&&(i[e][s]="*");let{optimizationLevel:t=1}=this.options;return t>=2?(i=this.firstPhasePreProcess(i),i=this.secondPhasePreProcess(i)):t>=1?i=this.levelOneOptimize(i):i=this.adjascentGlobstarOptimize(i),i}adjascentGlobstarOptimize(i){return i.map(t=>{let e=-1;for(;(e=t.indexOf("**",e+1))!==-1;){let s=e;for(;t[s+1]==="**";)s++;s!==e&&t.splice(e,s-e);}return t})}levelOneOptimize(i){return i.map(t=>(t=t.reduce((e,s)=>{let r=e[e.length-1];return s==="**"&&r==="**"?e:s===".."&&r&&r!==".."&&r!=="."&&r!=="**"?(e.pop(),e):(e.push(s),e)},[]),t.length===0?[""]:t))}levelTwoFileOptimize(i){Array.isArray(i)||(i=this.slashSplit(i));let t=false;do{if(t=false,!this.preserveMultipleSlashes){for(let s=1;s<i.length-1;s++){let r=i[s];s===1&&r===""&&i[0]===""||(r==="."||r==="")&&(t=true,i.splice(s,1),s--);}i[0]==="."&&i.length===2&&(i[1]==="."||i[1]==="")&&(t=true,i.pop());}let e=0;for(;(e=i.indexOf("..",e+1))!==-1;){let s=i[e-1];s&&s!=="."&&s!==".."&&s!=="**"&&(t=true,i.splice(e-1,2),e-=2);}}while(t);return i.length===0?[""]:i}firstPhasePreProcess(i){let t=false;do{t=false;for(let e of i){let s=-1;for(;(s=e.indexOf("**",s+1))!==-1;){let o=s;for(;e[o+1]==="**";)o++;o>s&&e.splice(s+1,o-s);let a=e[s+1],l=e[s+2],h=e[s+3];if(a!==".."||!l||l==="."||l===".."||!h||h==="."||h==="..")continue;t=true,e.splice(s,1);let c=e.slice(0);c[s]="**",i.push(c),s--;}if(!this.preserveMultipleSlashes){for(let o=1;o<e.length-1;o++){let a=e[o];o===1&&a===""&&e[0]===""||(a==="."||a==="")&&(t=true,e.splice(o,1),o--);}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(t=true,e.pop());}let r=0;for(;(r=e.indexOf("..",r+1))!==-1;){let o=e[r-1];if(o&&o!=="."&&o!==".."&&o!=="**"){t=true;let a=r===1&&e[r+1]==="**"?["."]:[];e.splice(r-1,2,...a),e.length===0&&e.push(""),r-=2;}}}}while(t);return i}secondPhasePreProcess(i){for(let t=0;t<i.length-1;t++)for(let e=t+1;e<i.length;e++){let s=this.partsMatch(i[t],i[e],!this.preserveMultipleSlashes);if(s){i[t]=[],i[e]=s;break}}return i.filter(t=>t.length)}partsMatch(i,t,e=false){let s=0,r=0,o=[],a="";for(;s<i.length&&r<t.length;)if(i[s]===t[r])o.push(a==="b"?t[r]:i[s]),s++,r++;else if(e&&i[s]==="**"&&t[r]===i[s+1])o.push(i[s]),s++;else if(e&&t[r]==="**"&&i[s]===t[r+1])o.push(t[r]),r++;else if(i[s]==="*"&&t[r]&&(this.options.dot||!t[r].startsWith("."))&&t[r]!=="**"){if(a==="b")return false;a="a",o.push(i[s]),s++,r++;}else if(t[r]==="*"&&i[s]&&(this.options.dot||!i[s].startsWith("."))&&i[s]!=="**"){if(a==="a")return false;a="b",o.push(t[r]),s++,r++;}else return false;return i.length===t.length&&o}parseNegate(){if(this.nonegate)return;let i=this.pattern,t=false,e=0;for(let s=0;s<i.length&&i.charAt(s)==="!";s++)t=!t,e++;e&&(this.pattern=i.slice(e)),this.negate=t;}matchOne(i,t,e=false){let s=this.options;if(this.isWindows){let b=typeof i[0]=="string"&&/^[a-z]:$/i.test(i[0]),E=!b&&i[0]===""&&i[1]===""&&i[2]==="?"&&/^[a-z]:$/i.test(i[3]),T=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),S=!T&&t[0]===""&&t[1]===""&&t[2]==="?"&&typeof t[3]=="string"&&/^[a-z]:$/i.test(t[3]),x=E?3:b?0:void 0,R=S?3:T?0:void 0;if(typeof x=="number"&&typeof R=="number"){let[A,_]=[i[x],t[R]];A.toLowerCase()===_.toLowerCase()&&(t[R]=A,R>x?t=t.slice(R):x>R&&(i=i.slice(x)));}}let{optimizationLevel:r=1}=this.options;r>=2&&(i=this.levelTwoFileOptimize(i)),this.debug("matchOne",this,{file:i,pattern:t}),this.debug("matchOne",i.length,t.length);for(var o=0,a=0,l=i.length,h=t.length;o<l&&a<h;o++,a++){this.debug("matchOne loop");var c=t[a],u=i[o];if(this.debug(t,c,u),c===false)return false;if(c===at){this.debug("GLOBSTAR",[t,c,u]);var d=o,f=a+1;if(f===h){for(this.debug("** at the end");o<l;o++)if(i[o]==="."||i[o]===".."||!s.dot&&i[o].charAt(0)===".")return false;return true}for(;d<l;){var g=i[d];if(this.debug(`
2
- globstar while`,i,d,t,f,g),this.matchOne(i.slice(d),t.slice(f),e))return this.debug("globstar found match!",d,l,g),true;if(g==="."||g===".."||!s.dot&&g.charAt(0)==="."){this.debug("dot detected!",i,d,t,f);break}this.debug("globstar swallow a segment, and continue"),d++;}return !!(e&&(this.debug(`
3
- >>> no match, partial?`,i,d,t,f),d===l))}let b;if(typeof c=="string"?(b=u===c,this.debug("string match",c,u,b)):(b=c.test(u),this.debug("pattern match",c,u,b)),!b)return false}if(o===l&&a===h)return true;if(o===l)return e;if(a===h)return o===l-1&&i[o]==="";throw new Error("wtf?")}braceExpand(){return cn(this.pattern,this.options)}parse(i){cs(i);let t=this.options;if(i==="**")return at;if(i==="")return "";let e,s=null;(e=i.match(zo))?s=t.dot?$o:jo:(e=i.match(Oo))?s=(t.nocase?t.dot?ko:Fo:t.dot?No:Io)(e[1]):(e=i.match(Uo))?s=(t.nocase?t.dot?Go:Bo:t.dot?Xo:Yo)(e):(e=i.match(Lo))?s=t.dot?Co:Do:(e=i.match(Po))&&(s=Wo);let r=sn.fromGlob(i,this.options).toMMPattern();return s&&typeof r=="object"&&Reflect.defineProperty(r,"test",{value:s}),r}makeRe(){if(this.regexp||this.regexp===false)return this.regexp;let i=this.set;if(!i.length)return this.regexp=false,this.regexp;let t=this.options,e=t.noglobstar?Vo:t.dot?Jo:Ko,s=new Set(t.nocase?["i"]:[]),r=i.map(l=>{let h=l.map(u=>{if(u instanceof RegExp)for(let d of u.flags.split(""))s.add(d);return typeof u=="string"?ia(u):u===at?at:u._src});h.forEach((u,d)=>{let f=h[d+1],g=h[d-1];u!==at||g===at||(g===void 0?f!==void 0&&f!==at?h[d+1]="(?:\\/|"+e+"\\/)?"+f:h[d]=e:f===void 0?h[d-1]=g+"(?:\\/|\\/"+e+")?":f!==at&&(h[d-1]=g+"(?:\\/|\\/"+e+"\\/)"+f,h[d+1]=at));});let c=h.filter(u=>u!==at);if(this.partial&&c.length>=1){let u=[];for(let d=1;d<=c.length;d++)u.push(c.slice(0,d).join("/"));return "(?:"+u.join("|")+")"}return c.join("/")}).join("|"),[o,a]=i.length>1?["(?:",")"]:["",""];r="^"+o+r+a+"$",this.partial&&(r="^(?:\\/|"+o+r.slice(1,-1)+a+")$"),this.negate&&(r="^(?!"+r+").+$");try{this.regexp=new RegExp(r,[...s].join(""));}catch{this.regexp=false;}return this.regexp}slashSplit(i){return this.preserveMultipleSlashes?i.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(i)?["",...i.split(/\/+/)]:i.split(/\/+/)}match(i,t=this.partial){if(this.debug("match",i,this.pattern),this.comment)return false;if(this.empty)return i==="";if(i==="/"&&t)return true;let e=this.options;this.isWindows&&(i=i.split("\\").join("/"));let s=this.slashSplit(i);this.debug(this.pattern,"split",s);let r=this.set;this.debug(this.pattern,"set",r);let o=s[s.length-1];if(!o)for(let a=s.length-2;!o&&a>=0;a--)o=s[a];for(let a=0;a<r.length;a++){let l=r[a],h=s;if(e.matchBase&&l.length===1&&(h=[o]),this.matchOne(h,l,t))return e.flipNegate?true:!this.negate}return e.flipNegate?false:this.negate}static defaults(i){return ht.defaults(i).Minimatch}};ht.AST=sn;ht.Minimatch=we;ht.escape=on;ht.unescape=$e;var ra=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,dn=new Set,Ds=typeof process=="object"&&process?process:{},un=(i,t,e,s)=>{typeof Ds.emitWarning=="function"?Ds.emitWarning(i,t,e,s):console.error(`[${e}] ${t}: ${i}`);},ds=globalThis.AbortController,dr=globalThis.AbortSignal;if(typeof ds>"u"){dr=class{constructor(){p(this,"onabort");p(this,"_onabort",[]);p(this,"reason");p(this,"aborted",false);}addEventListener(e,s){this._onabort.push(s);}},ds=class{constructor(){p(this,"signal",new dr);t();}abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=true;for(let s of this.signal._onabort)s(e);this.signal.onabort?.(e);}}};let i=Ds.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{i&&(i=false,un("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t));};}var na=i=>!dn.has(i),oe=i=>i&&i===Math.floor(i)&&i>0&&isFinite(i),pn=i=>oe(i)?i<=Math.pow(2,8)?Uint8Array:i<=Math.pow(2,16)?Uint16Array:i<=Math.pow(2,32)?Uint32Array:i<=Number.MAX_SAFE_INTEGER?ss:null:null,ss=class extends Array{constructor(i){super(i),this.fill(0);}},Gt,Ue,oa=(Gt=class{constructor(t,e){p(this,"heap");p(this,"length");if(!n(Gt,Ue))throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new e(t),this.length=0;}static create(t){let e=pn(t);if(!e)return [];m(Gt,Ue,true);let s=new Gt(t,e);return m(Gt,Ue,false),s}push(t){this.heap[this.length++]=t;}pop(){return this.heap[--this.length]}},Ue=new WeakMap,w(Gt,Ue,false),Gt),Ar,Mr,vt,ft,It,xe,Nt,Be,Ge,Ft,$,kt,z,D,I,rt,gt,it,V,Lt,J,Dt,Ct,yt,wt,Pt,ue,nt,Xe,v,Cs,Oe,Jt,bi,bt,mn,Ie,Ye,Ei,ae,he,Ps,rs,ns,k,Ws,ui,le,zs,He,ms=(He=class{constructor(t){w(this,v);w(this,vt);w(this,ft);w(this,It);w(this,xe);w(this,Nt);w(this,Be);w(this,Ge);w(this,Ft);p(this,"ttl");p(this,"ttlResolution");p(this,"ttlAutopurge");p(this,"updateAgeOnGet");p(this,"updateAgeOnHas");p(this,"allowStale");p(this,"noDisposeOnSet");p(this,"noUpdateTTL");p(this,"maxEntrySize");p(this,"sizeCalculation");p(this,"noDeleteOnFetchRejection");p(this,"noDeleteOnStaleGet");p(this,"allowStaleOnFetchAbort");p(this,"allowStaleOnFetchRejection");p(this,"ignoreFetchAbort");w(this,$);w(this,kt);w(this,z);w(this,D);w(this,I);w(this,rt);w(this,gt);w(this,it);w(this,V);w(this,Lt);w(this,J);w(this,Dt);w(this,Ct);w(this,yt);w(this,wt);w(this,Pt);w(this,ue);w(this,nt);w(this,Xe);w(this,Oe,()=>{});w(this,Jt,()=>{});w(this,bi,()=>{});w(this,bt,()=>false);w(this,Ie,t=>{});w(this,Ye,(t,e,s)=>{});w(this,Ei,(t,e,s,r)=>{if(s||r)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0});p(this,Ar,"LRUCache");let{max:e=0,ttl:s,ttlResolution:r=1,ttlAutopurge:o,updateAgeOnGet:a,updateAgeOnHas:l,allowStale:h,dispose:c,onInsert:u,disposeAfter:d,noDisposeOnSet:f,noUpdateTTL:g,maxSize:b=0,maxEntrySize:E=0,sizeCalculation:T,fetchMethod:S,memoMethod:x,noDeleteOnFetchRejection:R,noDeleteOnStaleGet:A,allowStaleOnFetchRejection:_,allowStaleOnFetchAbort:N,ignoreFetchAbort:F,perf:tt}=t;if(tt!==void 0&&typeof tt?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(m(this,Ft,tt??ra),e!==0&&!oe(e))throw new TypeError("max option must be a nonnegative integer");let C=e?pn(e):Array;if(!C)throw new Error("invalid max value: "+e);if(m(this,vt,e),m(this,ft,b),this.maxEntrySize=E||n(this,ft),this.sizeCalculation=T,this.sizeCalculation){if(!n(this,ft)&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(x!==void 0&&typeof x!="function")throw new TypeError("memoMethod must be a function if defined");if(m(this,Ge,x),S!==void 0&&typeof S!="function")throw new TypeError("fetchMethod must be a function if specified");if(m(this,Be,S),m(this,ue,!!S),m(this,z,new Map),m(this,D,new Array(e).fill(void 0)),m(this,I,new Array(e).fill(void 0)),m(this,rt,new C(e)),m(this,gt,new C(e)),m(this,it,0),m(this,V,0),m(this,Lt,oa.create(e)),m(this,$,0),m(this,kt,0),typeof c=="function"&&m(this,It,c),typeof u=="function"&&m(this,xe,u),typeof d=="function"?(m(this,Nt,d),m(this,J,[])):(m(this,Nt,void 0),m(this,J,void 0)),m(this,Pt,!!n(this,It)),m(this,Xe,!!n(this,xe)),m(this,nt,!!n(this,Nt)),this.noDisposeOnSet=!!f,this.noUpdateTTL=!!g,this.noDeleteOnFetchRejection=!!R,this.allowStaleOnFetchRejection=!!_,this.allowStaleOnFetchAbort=!!N,this.ignoreFetchAbort=!!F,this.maxEntrySize!==0){if(n(this,ft)!==0&&!oe(n(this,ft)))throw new TypeError("maxSize must be a positive integer if specified");if(!oe(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");y(this,v,mn).call(this);}if(this.allowStale=!!h,this.noDeleteOnStaleGet=!!A,this.updateAgeOnGet=!!a,this.updateAgeOnHas=!!l,this.ttlResolution=oe(r)||r===0?r:1,this.ttlAutopurge=!!o,this.ttl=s||0,this.ttl){if(!oe(this.ttl))throw new TypeError("ttl must be a positive integer if specified");y(this,v,Cs).call(this);}if(n(this,vt)===0&&this.ttl===0&&n(this,ft)===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!n(this,vt)&&!n(this,ft)){let G="LRU_CACHE_UNBOUNDED";na(G)&&(dn.add(G),un("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",G,He));}}get perf(){return n(this,Ft)}static unsafeExposeInternals(t){return {starts:n(t,Ct),ttls:n(t,yt),autopurgeTimers:n(t,wt),sizes:n(t,Dt),keyMap:n(t,z),keyList:n(t,D),valList:n(t,I),next:n(t,rt),prev:n(t,gt),get head(){return n(t,it)},get tail(){return n(t,V)},free:n(t,Lt),isBackgroundFetch:e=>{var s;return y(s=t,v,k).call(s,e)},backgroundFetch:(e,s,r,o)=>{var a;return y(a=t,v,ns).call(a,e,s,r,o)},moveToTail:e=>{var s;return y(s=t,v,ui).call(s,e)},indexes:e=>{var s;return y(s=t,v,ae).call(s,e)},rindexes:e=>{var s;return y(s=t,v,he).call(s,e)},isStale:e=>{var s;return n(s=t,bt).call(s,e)}}}get max(){return n(this,vt)}get maxSize(){return n(this,ft)}get calculatedSize(){return n(this,kt)}get size(){return n(this,$)}get fetchMethod(){return n(this,Be)}get memoMethod(){return n(this,Ge)}get dispose(){return n(this,It)}get onInsert(){return n(this,xe)}get disposeAfter(){return n(this,Nt)}getRemainingTTL(t){return n(this,z).has(t)?1/0:0}*entries(){for(let t of y(this,v,ae).call(this))n(this,I)[t]!==void 0&&n(this,D)[t]!==void 0&&!y(this,v,k).call(this,n(this,I)[t])&&(yield [n(this,D)[t],n(this,I)[t]]);}*rentries(){for(let t of y(this,v,he).call(this))n(this,I)[t]!==void 0&&n(this,D)[t]!==void 0&&!y(this,v,k).call(this,n(this,I)[t])&&(yield [n(this,D)[t],n(this,I)[t]]);}*keys(){for(let t of y(this,v,ae).call(this)){let e=n(this,D)[t];e!==void 0&&!y(this,v,k).call(this,n(this,I)[t])&&(yield e);}}*rkeys(){for(let t of y(this,v,he).call(this)){let e=n(this,D)[t];e!==void 0&&!y(this,v,k).call(this,n(this,I)[t])&&(yield e);}}*values(){for(let t of y(this,v,ae).call(this))n(this,I)[t]!==void 0&&!y(this,v,k).call(this,n(this,I)[t])&&(yield n(this,I)[t]);}*rvalues(){for(let t of y(this,v,he).call(this))n(this,I)[t]!==void 0&&!y(this,v,k).call(this,n(this,I)[t])&&(yield n(this,I)[t]);}[(Mr=Symbol.iterator,Ar=Symbol.toStringTag,Mr)](){return this.entries()}find(t,e={}){for(let s of y(this,v,ae).call(this)){let r=n(this,I)[s],o=y(this,v,k).call(this,r)?r.__staleWhileFetching:r;if(o!==void 0&&t(o,n(this,D)[s],this))return this.get(n(this,D)[s],e)}}forEach(t,e=this){for(let s of y(this,v,ae).call(this)){let r=n(this,I)[s],o=y(this,v,k).call(this,r)?r.__staleWhileFetching:r;o!==void 0&&t.call(e,o,n(this,D)[s],this);}}rforEach(t,e=this){for(let s of y(this,v,he).call(this)){let r=n(this,I)[s],o=y(this,v,k).call(this,r)?r.__staleWhileFetching:r;o!==void 0&&t.call(e,o,n(this,D)[s],this);}}purgeStale(){let t=false;for(let e of y(this,v,he).call(this,{allowStale:true}))n(this,bt).call(this,e)&&(y(this,v,le).call(this,n(this,D)[e],"expire"),t=true);return t}info(t){let e=n(this,z).get(t);if(e===void 0)return;let s=n(this,I)[e],r=y(this,v,k).call(this,s)?s.__staleWhileFetching:s;if(r===void 0)return;let o={value:r};if(n(this,yt)&&n(this,Ct)){let a=n(this,yt)[e],l=n(this,Ct)[e];if(a&&l){let h=a-(n(this,Ft).now()-l);o.ttl=h,o.start=Date.now();}}return n(this,Dt)&&(o.size=n(this,Dt)[e]),o}dump(){let t=[];for(let e of y(this,v,ae).call(this,{allowStale:true})){let s=n(this,D)[e],r=n(this,I)[e],o=y(this,v,k).call(this,r)?r.__staleWhileFetching:r;if(o===void 0||s===void 0)continue;let a={value:o};if(n(this,yt)&&n(this,Ct)){a.ttl=n(this,yt)[e];let l=n(this,Ft).now()-n(this,Ct)[e];a.start=Math.floor(Date.now()-l);}n(this,Dt)&&(a.size=n(this,Dt)[e]),t.unshift([s,a]);}return t}load(t){this.clear();for(let[e,s]of t){if(s.start){let r=Date.now()-s.start;s.start=n(this,Ft).now()-r;}this.set(e,s.value,s);}}set(t,e,s={}){var f,g,b,E;if(e===void 0)return this.delete(t),this;let{ttl:r=this.ttl,start:o,noDisposeOnSet:a=this.noDisposeOnSet,sizeCalculation:l=this.sizeCalculation,status:h}=s,{noUpdateTTL:c=this.noUpdateTTL}=s,u=n(this,Ei).call(this,t,e,s.size||0,l);if(this.maxEntrySize&&u>this.maxEntrySize)return h&&(h.set="miss",h.maxEntrySizeExceeded=true),y(this,v,le).call(this,t,"set"),this;let d=n(this,$)===0?void 0:n(this,z).get(t);if(d===void 0)d=n(this,$)===0?n(this,V):n(this,Lt).length!==0?n(this,Lt).pop():n(this,$)===n(this,vt)?y(this,v,rs).call(this,false):n(this,$),n(this,D)[d]=t,n(this,I)[d]=e,n(this,z).set(t,d),n(this,rt)[n(this,V)]=d,n(this,gt)[d]=n(this,V),m(this,V,d),Hi(this,$)._++,n(this,Ye).call(this,d,u,h),h&&(h.set="add"),c=false,n(this,Xe)&&((f=n(this,xe))==null||f.call(this,e,t,"add"));else {y(this,v,ui).call(this,d);let T=n(this,I)[d];if(e!==T){if(n(this,ue)&&y(this,v,k).call(this,T)){T.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:S}=T;S!==void 0&&!a&&(n(this,Pt)&&((g=n(this,It))==null||g.call(this,S,t,"set")),n(this,nt)&&n(this,J)?.push([S,t,"set"]));}else a||(n(this,Pt)&&((b=n(this,It))==null||b.call(this,T,t,"set")),n(this,nt)&&n(this,J)?.push([T,t,"set"]));if(n(this,Ie).call(this,d),n(this,Ye).call(this,d,u,h),n(this,I)[d]=e,h){h.set="replace";let S=T&&y(this,v,k).call(this,T)?T.__staleWhileFetching:T;S!==void 0&&(h.oldValue=S);}}else h&&(h.set="update");n(this,Xe)&&this.onInsert?.(e,t,e===T?"update":"replace");}if(r!==0&&!n(this,yt)&&y(this,v,Cs).call(this),n(this,yt)&&(c||n(this,bi).call(this,d,r,o),h&&n(this,Jt).call(this,h,d)),!a&&n(this,nt)&&n(this,J)){let T=n(this,J),S;for(;S=T?.shift();)(E=n(this,Nt))==null||E.call(this,...S);}return this}pop(){var t;try{for(;n(this,$);){let e=n(this,I)[n(this,it)];if(y(this,v,rs).call(this,!0),y(this,v,k).call(this,e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(n(this,nt)&&n(this,J)){let e=n(this,J),s;for(;s=e?.shift();)(t=n(this,Nt))==null||t.call(this,...s);}}}has(t,e={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:r}=e,o=n(this,z).get(t);if(o!==void 0){let a=n(this,I)[o];if(y(this,v,k).call(this,a)&&a.__staleWhileFetching===void 0)return false;if(n(this,bt).call(this,o))r&&(r.has="stale",n(this,Jt).call(this,r,o));else return s&&n(this,Oe).call(this,o),r&&(r.has="hit",n(this,Jt).call(this,r,o)),true}else r&&(r.has="miss");return false}peek(t,e={}){let{allowStale:s=this.allowStale}=e,r=n(this,z).get(t);if(r===void 0||!s&&n(this,bt).call(this,r))return;let o=n(this,I)[r];return y(this,v,k).call(this,o)?o.__staleWhileFetching:o}async fetch(t,e={}){let{allowStale:s=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:a=this.ttl,noDisposeOnSet:l=this.noDisposeOnSet,size:h=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:f=this.allowStaleOnFetchRejection,ignoreFetchAbort:g=this.ignoreFetchAbort,allowStaleOnFetchAbort:b=this.allowStaleOnFetchAbort,context:E,forceRefresh:T=false,status:S,signal:x}=e;if(!n(this,ue))return S&&(S.fetch="get"),this.get(t,{allowStale:s,updateAgeOnGet:r,noDeleteOnStaleGet:o,status:S});let R={allowStale:s,updateAgeOnGet:r,noDeleteOnStaleGet:o,ttl:a,noDisposeOnSet:l,size:h,sizeCalculation:c,noUpdateTTL:u,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:f,allowStaleOnFetchAbort:b,ignoreFetchAbort:g,status:S,signal:x},A=n(this,z).get(t);if(A===void 0){S&&(S.fetch="miss");let _=y(this,v,ns).call(this,t,A,R,E);return _.__returned=_}else {let _=n(this,I)[A];if(y(this,v,k).call(this,_)){let C=s&&_.__staleWhileFetching!==void 0;return S&&(S.fetch="inflight",C&&(S.returnedStale=true)),C?_.__staleWhileFetching:_.__returned=_}let N=n(this,bt).call(this,A);if(!T&&!N)return S&&(S.fetch="hit"),y(this,v,ui).call(this,A),r&&n(this,Oe).call(this,A),S&&n(this,Jt).call(this,S,A),_;let F=y(this,v,ns).call(this,t,A,R,E),tt=F.__staleWhileFetching!==void 0&&s;return S&&(S.fetch=N?"stale":"refresh",tt&&N&&(S.returnedStale=true)),tt?F.__staleWhileFetching:F.__returned=F}}async forceFetch(t,e={}){let s=await this.fetch(t,e);if(s===void 0)throw new Error("fetch() returned undefined");return s}memo(t,e={}){let s=n(this,Ge);if(!s)throw new Error("no memoMethod provided to constructor");let{context:r,forceRefresh:o,...a}=e,l=this.get(t,a);if(!o&&l!==void 0)return l;let h=s(t,l,{options:a,context:r});return this.set(t,h,a),h}get(t,e={}){let{allowStale:s=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:a}=e,l=n(this,z).get(t);if(l!==void 0){let h=n(this,I)[l],c=y(this,v,k).call(this,h);return a&&n(this,Jt).call(this,a,l),n(this,bt).call(this,l)?(a&&(a.get="stale"),c?(a&&s&&h.__staleWhileFetching!==void 0&&(a.returnedStale=true),s?h.__staleWhileFetching:void 0):(o||y(this,v,le).call(this,t,"expire"),a&&s&&(a.returnedStale=true),s?h:void 0)):(a&&(a.get="hit"),c?h.__staleWhileFetching:(y(this,v,ui).call(this,l),r&&n(this,Oe).call(this,l),h))}else a&&(a.get="miss");}delete(t){return y(this,v,le).call(this,t,"delete")}clear(){return y(this,v,zs).call(this,"delete")}},vt=new WeakMap,ft=new WeakMap,It=new WeakMap,xe=new WeakMap,Nt=new WeakMap,Be=new WeakMap,Ge=new WeakMap,Ft=new WeakMap,$=new WeakMap,kt=new WeakMap,z=new WeakMap,D=new WeakMap,I=new WeakMap,rt=new WeakMap,gt=new WeakMap,it=new WeakMap,V=new WeakMap,Lt=new WeakMap,J=new WeakMap,Dt=new WeakMap,Ct=new WeakMap,yt=new WeakMap,wt=new WeakMap,Pt=new WeakMap,ue=new WeakMap,nt=new WeakMap,Xe=new WeakMap,v=new WeakSet,Cs=function(){let t=new ss(n(this,vt)),e=new ss(n(this,vt));m(this,yt,t),m(this,Ct,e);let s=this.ttlAutopurge?new Array(n(this,vt)):void 0;m(this,wt,s),m(this,bi,(a,l,h=n(this,Ft).now())=>{if(e[a]=l!==0?h:0,t[a]=l,s?.[a]&&(clearTimeout(s[a]),s[a]=void 0),l!==0&&s){let c=setTimeout(()=>{n(this,bt).call(this,a)&&y(this,v,le).call(this,n(this,D)[a],"expire");},l+1);c.unref&&c.unref(),s[a]=c;}}),m(this,Oe,a=>{e[a]=t[a]!==0?n(this,Ft).now():0;}),m(this,Jt,(a,l)=>{if(t[l]){let h=t[l],c=e[l];if(!h||!c)return;a.ttl=h,a.start=c,a.now=r||o();let u=a.now-c;a.remainingTTL=h-u;}});let r=0,o=()=>{let a=n(this,Ft).now();if(this.ttlResolution>0){r=a;let l=setTimeout(()=>r=0,this.ttlResolution);l.unref&&l.unref();}return a};this.getRemainingTTL=a=>{let l=n(this,z).get(a);if(l===void 0)return 0;let h=t[l],c=e[l];if(!h||!c)return 1/0;let u=(r||o())-c;return h-u},m(this,bt,a=>{let l=e[a],h=t[a];return !!h&&!!l&&(r||o())-l>h});},Oe=new WeakMap,Jt=new WeakMap,bi=new WeakMap,bt=new WeakMap,mn=function(){let t=new ss(n(this,vt));m(this,kt,0),m(this,Dt,t),m(this,Ie,e=>{m(this,kt,n(this,kt)-t[e]),t[e]=0;}),m(this,Ei,(e,s,r,o)=>{if(y(this,v,k).call(this,s))return 0;if(!oe(r))if(o){if(typeof o!="function")throw new TypeError("sizeCalculation must be a function");if(r=o(s,e),!oe(r))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return r}),m(this,Ye,(e,s,r)=>{if(t[e]=s,n(this,ft)){let o=n(this,ft)-t[e];for(;n(this,kt)>o;)y(this,v,rs).call(this,true);}m(this,kt,n(this,kt)+t[e]),r&&(r.entrySize=s,r.totalCalculatedSize=n(this,kt));});},Ie=new WeakMap,Ye=new WeakMap,Ei=new WeakMap,ae=function*({allowStale:t=this.allowStale}={}){if(n(this,$))for(let e=n(this,V);!(!y(this,v,Ps).call(this,e)||((t||!n(this,bt).call(this,e))&&(yield e),e===n(this,it)));)e=n(this,gt)[e];},he=function*({allowStale:t=this.allowStale}={}){if(n(this,$))for(let e=n(this,it);!(!y(this,v,Ps).call(this,e)||((t||!n(this,bt).call(this,e))&&(yield e),e===n(this,V)));)e=n(this,rt)[e];},Ps=function(t){return t!==void 0&&n(this,z).get(n(this,D)[t])===t},rs=function(t){var o;let e=n(this,it),s=n(this,D)[e],r=n(this,I)[e];return n(this,ue)&&y(this,v,k).call(this,r)?r.__abortController.abort(new Error("evicted")):(n(this,Pt)||n(this,nt))&&(n(this,Pt)&&((o=n(this,It))==null||o.call(this,r,s,"evict")),n(this,nt)&&n(this,J)?.push([r,s,"evict"])),n(this,Ie).call(this,e),n(this,wt)?.[e]&&(clearTimeout(n(this,wt)[e]),n(this,wt)[e]=void 0),t&&(n(this,D)[e]=void 0,n(this,I)[e]=void 0,n(this,Lt).push(e)),n(this,$)===1?(m(this,it,m(this,V,0)),n(this,Lt).length=0):m(this,it,n(this,rt)[e]),n(this,z).delete(s),Hi(this,$)._--,e},ns=function(t,e,s,r){let o=e===void 0?void 0:n(this,I)[e];if(y(this,v,k).call(this,o))return o;let a=new ds,{signal:l}=s;l?.addEventListener("abort",()=>a.abort(l.reason),{signal:a.signal});let h={signal:a.signal,options:s,context:r},c=(E,T=false)=>{let{aborted:S}=a.signal,x=s.ignoreFetchAbort&&E!==void 0,R=s.ignoreFetchAbort||!!(s.allowStaleOnFetchAbort&&E!==void 0);if(s.status&&(S&&!T?(s.status.fetchAborted=true,s.status.fetchError=a.signal.reason,x&&(s.status.fetchAbortIgnored=true)):s.status.fetchResolved=true),S&&!x&&!T)return d(a.signal.reason,R);let A=g,_=n(this,I)[e];return (_===g||x&&T&&_===void 0)&&(E===void 0?A.__staleWhileFetching!==void 0?n(this,I)[e]=A.__staleWhileFetching:y(this,v,le).call(this,t,"fetch"):(s.status&&(s.status.fetchUpdated=true),this.set(t,E,h.options))),E},u=E=>(s.status&&(s.status.fetchRejected=true,s.status.fetchError=E),d(E,false)),d=(E,T)=>{let{aborted:S}=a.signal,x=S&&s.allowStaleOnFetchAbort,R=x||s.allowStaleOnFetchRejection,A=R||s.noDeleteOnFetchRejection,_=g;if(n(this,I)[e]===g&&(!A||!T&&_.__staleWhileFetching===void 0?y(this,v,le).call(this,t,"fetch"):x||(n(this,I)[e]=_.__staleWhileFetching)),R)return s.status&&_.__staleWhileFetching!==void 0&&(s.status.returnedStale=true),_.__staleWhileFetching;if(_.__returned===_)throw E},f=(E,T)=>{var x;let S=(x=n(this,Be))==null?void 0:x.call(this,t,o,h);S&&S instanceof Promise&&S.then(R=>E(R===void 0?void 0:R),T),a.signal.addEventListener("abort",()=>{(!s.ignoreFetchAbort||s.allowStaleOnFetchAbort)&&(E(void 0),s.allowStaleOnFetchAbort&&(E=R=>c(R,true)));});};s.status&&(s.status.fetchDispatched=true);let g=new Promise(f).then(c,u),b=Object.assign(g,{__abortController:a,__staleWhileFetching:o,__returned:void 0});return e===void 0?(this.set(t,b,{...h.options,status:void 0}),e=n(this,z).get(t)):n(this,I)[e]=b,b},k=function(t){if(!n(this,ue))return false;let e=t;return !!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof ds},Ws=function(t,e){n(this,gt)[e]=t,n(this,rt)[t]=e;},ui=function(t){t!==n(this,V)&&(t===n(this,it)?m(this,it,n(this,rt)[t]):y(this,v,Ws).call(this,n(this,gt)[t],n(this,rt)[t]),y(this,v,Ws).call(this,n(this,V),t),m(this,V,t));},le=function(t,e){var r,o;let s=false;if(n(this,$)!==0){let a=n(this,z).get(t);if(a!==void 0)if(n(this,wt)?.[a]&&(clearTimeout(n(this,wt)?.[a]),n(this,wt)[a]=void 0),s=true,n(this,$)===1)y(this,v,zs).call(this,e);else {n(this,Ie).call(this,a);let l=n(this,I)[a];if(y(this,v,k).call(this,l)?l.__abortController.abort(new Error("deleted")):(n(this,Pt)||n(this,nt))&&(n(this,Pt)&&((r=n(this,It))==null||r.call(this,l,t,e)),n(this,nt)&&n(this,J)?.push([l,t,e])),n(this,z).delete(t),n(this,D)[a]=void 0,n(this,I)[a]=void 0,a===n(this,V))m(this,V,n(this,gt)[a]);else if(a===n(this,it))m(this,it,n(this,rt)[a]);else {let h=n(this,gt)[a];n(this,rt)[h]=n(this,rt)[a];let c=n(this,rt)[a];n(this,gt)[c]=n(this,gt)[a];}Hi(this,$)._--,n(this,Lt).push(a);}}if(n(this,nt)&&n(this,J)?.length){let a=n(this,J),l;for(;l=a?.shift();)(o=n(this,Nt))==null||o.call(this,...l);}return s},zs=function(t){var e,s;for(let r of y(this,v,he).call(this,{allowStale:true})){let o=n(this,I)[r];if(y(this,v,k).call(this,o))o.__abortController.abort(new Error("deleted"));else {let a=n(this,D)[r];n(this,Pt)&&((e=n(this,It))==null||e.call(this,o,a,t)),n(this,nt)&&n(this,J)?.push([o,a,t]);}}if(n(this,z).clear(),n(this,I).fill(void 0),n(this,D).fill(void 0),n(this,yt)&&n(this,Ct)){n(this,yt).fill(0),n(this,Ct).fill(0);for(let r of n(this,wt)??[])r!==void 0&&clearTimeout(r);n(this,wt)?.fill(void 0);}if(n(this,Dt)&&n(this,Dt).fill(0),m(this,it,0),m(this,V,0),n(this,Lt).length=0,m(this,kt,0),m(this,$,0),n(this,nt)&&n(this,J)){let r=n(this,J),o;for(;o=r?.shift();)(s=n(this,Nt))==null||s.call(this,...o);}},He),ur=typeof process=="object"&&process?process:{stdout:null,stderr:null},Ea=i=>!!i&&typeof i=="object"&&(i instanceof us||i instanceof fn__default.default||Sa(i)||va(i)),Sa=i=>!!i&&typeof i=="object"&&i instanceof events.EventEmitter&&typeof i.pipe=="function"&&i.pipe!==fn__default.default.Writable.prototype.pipe,va=i=>!!i&&typeof i=="object"&&i instanceof events.EventEmitter&&typeof i.write=="function"&&typeof i.end=="function",Ht=Symbol("EOF"),qt=Symbol("maybeEmitEnd"),ne=Symbol("emittedEnd"),Vi=Symbol("emittingEnd"),oi=Symbol("emittedError"),Ji=Symbol("closed"),pr=Symbol("read"),Ki=Symbol("flush"),mr=Symbol("flushChunk"),xt=Symbol("encoding"),ze=Symbol("decoder"),X=Symbol("flowing"),ai=Symbol("paused"),je=Symbol("resume"),Y=Symbol("buffer"),st=Symbol("pipes"),H=Symbol("bufferLength"),Ms=Symbol("bufferPush"),Qi=Symbol("bufferShift"),et=Symbol("objectMode"),P=Symbol("destroyed"),xs=Symbol("error"),Os=Symbol("emitData"),fr=Symbol("emitEnd"),Is=Symbol("emitEnd2"),zt=Symbol("async"),Ns=Symbol("abort"),Zi=Symbol("aborted"),hi=Symbol("signal"),Te=Symbol("dataListeners"),mt=Symbol("discarded"),li=i=>Promise.resolve().then(i),Ta=i=>i(),Ra=i=>i==="end"||i==="finish"||i==="prefinish",_a=i=>i instanceof ArrayBuffer||!!i&&typeof i=="object"&&i.constructor&&i.constructor.name==="ArrayBuffer"&&i.byteLength>=0,Aa=i=>!Buffer.isBuffer(i)&&ArrayBuffer.isView(i),gn=class{constructor(i,t,e){p(this,"src");p(this,"dest");p(this,"opts");p(this,"ondrain");this.src=i,this.dest=t,this.opts=e,this.ondrain=()=>i[je](),this.dest.on("drain",this.ondrain);}unpipe(){this.dest.removeListener("drain",this.ondrain);}proxyErrors(i){}end(){this.unpipe(),this.opts.end&&this.dest.end();}},Ma=class extends gn{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe();}constructor(i,t,e){super(i,t,e),this.proxyErrors=s=>this.dest.emit("error",s),i.on("error",this.proxyErrors);}},xa=i=>!!i.objectMode,Oa=i=>!i.objectMode&&!!i.encoding&&i.encoding!=="buffer",xr,Or,Ir,Nr,Fr,kr,Lr,Dr,Cr,Pr,Wr,zr,jr,$r,Ur,Br,Gr,Xr,Yr,us=class extends events.EventEmitter{constructor(...t){let e=t[0]||{};super();p(this,Yr,false);p(this,Xr,false);p(this,Gr,[]);p(this,Br,[]);p(this,Ur);p(this,$r);p(this,jr);p(this,zr);p(this,Wr,false);p(this,Pr,false);p(this,Cr,false);p(this,Dr,false);p(this,Lr,null);p(this,kr,0);p(this,Fr,false);p(this,Nr);p(this,Ir,false);p(this,Or,0);p(this,xr,false);p(this,"writable",true);p(this,"readable",true);if(e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");xa(e)?(this[et]=true,this[xt]=null):Oa(e)?(this[xt]=e.encoding,this[et]=false):(this[et]=false,this[xt]=null),this[zt]=!!e.async,this[ze]=this[xt]?new string_decoder.StringDecoder(this[xt]):null,e&&e.debugExposeBuffer===true&&Object.defineProperty(this,"buffer",{get:()=>this[Y]}),e&&e.debugExposePipes===true&&Object.defineProperty(this,"pipes",{get:()=>this[st]});let{signal:s}=e;s&&(this[hi]=s,s.aborted?this[Ns]():s.addEventListener("abort",()=>this[Ns]()));}get bufferLength(){return this[H]}get encoding(){return this[xt]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[et]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[zt]}set async(t){this[zt]=this[zt]||!!t;}[(Yr=X,Xr=ai,Gr=st,Br=Y,Ur=et,$r=xt,jr=zt,zr=ze,Wr=Ht,Pr=ne,Cr=Vi,Dr=Ji,Lr=oi,kr=H,Fr=P,Nr=hi,Ir=Zi,Or=Te,xr=mt,Ns)](){this[Zi]=true,this.emit("abort",this[hi]?.reason),this.destroy(this[hi]?.reason);}get aborted(){return this[Zi]}set aborted(t){}write(t,e,s){if(this[Zi])return false;if(this[Ht])throw new Error("write after end");if(this[P])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),true;typeof e=="function"&&(s=e,e="utf8"),e||(e="utf8");let r=this[zt]?li:Ta;if(!this[et]&&!Buffer.isBuffer(t)){if(Aa(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(_a(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[et]?(this[X]&&this[H]!==0&&this[Ki](true),this[X]?this.emit("data",t):this[Ms](t),this[H]!==0&&this.emit("readable"),s&&r(s),this[X]):t.length?(typeof t=="string"&&!(e===this[xt]&&!this[ze]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[xt]&&(t=this[ze].write(t)),this[X]&&this[H]!==0&&this[Ki](true),this[X]?this.emit("data",t):this[Ms](t),this[H]!==0&&this.emit("readable"),s&&r(s),this[X]):(this[H]!==0&&this.emit("readable"),s&&r(s),this[X])}read(t){if(this[P])return null;if(this[mt]=false,this[H]===0||t===0||t&&t>this[H])return this[qt](),null;this[et]&&(t=null),this[Y].length>1&&!this[et]&&(this[Y]=[this[xt]?this[Y].join(""):Buffer.concat(this[Y],this[H])]);let e=this[pr](t||null,this[Y][0]);return this[qt](),e}[pr](t,e){if(this[et])this[Qi]();else {let s=e;t===s.length||t===null?this[Qi]():typeof s=="string"?(this[Y][0]=s.slice(t),e=s.slice(0,t),this[H]-=t):(this[Y][0]=s.subarray(t),e=s.subarray(0,t),this[H]-=t);}return this.emit("data",e),!this[Y].length&&!this[Ht]&&this.emit("drain"),e}end(t,e,s){return typeof t=="function"&&(s=t,t=void 0),typeof e=="function"&&(s=e,e="utf8"),t!==void 0&&this.write(t,e),s&&this.once("end",s),this[Ht]=true,this.writable=false,(this[X]||!this[ai])&&this[qt](),this}[je](){this[P]||(!this[Te]&&!this[st].length&&(this[mt]=true),this[ai]=false,this[X]=true,this.emit("resume"),this[Y].length?this[Ki]():this[Ht]?this[qt]():this.emit("drain"));}resume(){return this[je]()}pause(){this[X]=false,this[ai]=true,this[mt]=false;}get destroyed(){return this[P]}get flowing(){return this[X]}get paused(){return this[ai]}[Ms](t){this[et]?this[H]+=1:this[H]+=t.length,this[Y].push(t);}[Qi](){return this[et]?this[H]-=1:this[H]-=this[Y][0].length,this[Y].shift()}[Ki](t=false){do;while(this[mr](this[Qi]())&&this[Y].length);!t&&!this[Y].length&&!this[Ht]&&this.emit("drain");}[mr](t){return this.emit("data",t),this[X]}pipe(t,e){if(this[P])return t;this[mt]=false;let s=this[ne];return e=e||{},t===ur.stdout||t===ur.stderr?e.end=false:e.end=e.end!==false,e.proxyErrors=!!e.proxyErrors,s?e.end&&t.end():(this[st].push(e.proxyErrors?new Ma(this,t,e):new gn(this,t,e)),this[zt]?li(()=>this[je]()):this[je]()),t}unpipe(t){let e=this[st].find(s=>s.dest===t);e&&(this[st].length===1?(this[X]&&this[Te]===0&&(this[X]=false),this[st]=[]):this[st].splice(this[st].indexOf(e),1),e.unpipe());}addListener(t,e){return this.on(t,e)}on(t,e){let s=super.on(t,e);if(t==="data")this[mt]=false,this[Te]++,!this[st].length&&!this[X]&&this[je]();else if(t==="readable"&&this[H]!==0)super.emit("readable");else if(Ra(t)&&this[ne])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[oi]){let r=e;this[zt]?li(()=>r.call(this,this[oi])):r.call(this,this[oi]);}return s}removeListener(t,e){return this.off(t,e)}off(t,e){let s=super.off(t,e);return t==="data"&&(this[Te]=this.listeners("data").length,this[Te]===0&&!this[mt]&&!this[st].length&&(this[X]=false)),s}removeAllListeners(t){let e=super.removeAllListeners(t);return (t==="data"||t===void 0)&&(this[Te]=0,!this[mt]&&!this[st].length&&(this[X]=false)),e}get emittedEnd(){return this[ne]}[qt](){!this[Vi]&&!this[ne]&&!this[P]&&this[Y].length===0&&this[Ht]&&(this[Vi]=true,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ji]&&this.emit("close"),this[Vi]=false);}emit(t,...e){let s=e[0];if(t!=="error"&&t!=="close"&&t!==P&&this[P])return false;if(t==="data")return !this[et]&&!s?false:this[zt]?(li(()=>this[Os](s)),true):this[Os](s);if(t==="end")return this[fr]();if(t==="close"){if(this[Ji]=true,!this[ne]&&!this[P])return false;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[oi]=s,super.emit(xs,s);let o=!this[hi]||this.listeners("error").length?super.emit("error",s):false;return this[qt](),o}else if(t==="resume"){let o=super.emit("resume");return this[qt](),o}else if(t==="finish"||t==="prefinish"){let o=super.emit(t);return this.removeAllListeners(t),o}let r=super.emit(t,...e);return this[qt](),r}[Os](t){for(let s of this[st])s.dest.write(t)===false&&this.pause();let e=this[mt]?false:super.emit("data",t);return this[qt](),e}[fr](){return this[ne]?false:(this[ne]=true,this.readable=false,this[zt]?(li(()=>this[Is]()),true):this[Is]())}[Is](){if(this[ze]){let e=this[ze].end();if(e){for(let s of this[st])s.dest.write(e);this[mt]||super.emit("data",e);}}for(let e of this[st])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[et]||(t.dataLength=0);let e=this.promise();return this.on("data",s=>{t.push(s),this[et]||(t.dataLength+=s.length);}),await e,t}async concat(){if(this[et])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[xt]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(P,()=>e(new Error("stream destroyed"))),this.on("error",s=>e(s)),this.on("end",()=>t());})}[Symbol.asyncIterator](){this[mt]=false;let t=false,e=async()=>(this.pause(),t=true,{value:void 0,done:true});return {next:()=>{if(t)return e();let s=this.read();if(s!==null)return Promise.resolve({done:false,value:s});if(this[Ht])return e();let r,o,a=u=>{this.off("data",l),this.off("end",h),this.off(P,c),e(),o(u);},l=u=>{this.off("error",a),this.off("end",h),this.off(P,c),this.pause(),r({value:u,done:!!this[Ht]});},h=()=>{this.off("error",a),this.off("data",l),this.off(P,c),e(),r({done:true,value:void 0});},c=()=>a(new Error("stream destroyed"));return new Promise((u,d)=>{o=d,r=u,this.once(P,c),this.once("error",a),this.once("end",h),this.once("data",l);})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[mt]=false;let t=false,e=()=>(this.pause(),this.off(xs,e),this.off(P,e),this.off("end",e),t=true,{done:true,value:void 0}),s=()=>{if(t)return e();let r=this.read();return r===null?e():{done:false,value:r}};return this.once("end",e),this.once(xs,e),this.once(P,e),{next:s,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[P])return t?this.emit("error",t):this.emit(P),this;this[P]=true,this[mt]=true,this[Y].length=0,this[H]=0;let e=this;return typeof e.close=="function"&&!this[Ji]&&e.close(),t?this.emit("error",t):this.emit(P),this}static get isStream(){return Ea}},Ia=ma.realpathSync.native,pi={lstatSync:ma.lstatSync,readdir:ma.readdir,readdirSync:ma.readdirSync,readlinkSync:ma.readlinkSync,realpathSync:Ia,promises:{lstat:se.lstat,readdir:se.readdir,readlink:se.readlink,realpath:se.realpath}},yn=i=>!i||i===pi||i===ma__namespace?pi:{...pi,...i,promises:{...pi.promises,...i.promises||{}}},wn=/^\\\\\?\\([a-z]:)\\?$/i,Na=i=>i.replace(/\//g,"\\").replace(wn,"$1\\"),Fa=/[\\\/]/,Tt=0,bn=1,En=2,jt=4,Sn=6,vn=8,Re=10,Tn=12,St=15,ci=~St,Fs=16,gr=32,mi=64,Ot=128,ts=256,os=512,yr=mi|Ot|os,ka=1023,ks=i=>i.isFile()?vn:i.isDirectory()?jt:i.isSymbolicLink()?Re:i.isCharacterDevice()?En:i.isBlockDevice()?Sn:i.isSocket()?Tn:i.isFIFO()?bn:Tt,wr=new ms({max:2**12}),fi=i=>{let t=wr.get(i);if(t)return t;let e=i.normalize("NFKD");return wr.set(i,e),e},br=new ms({max:2**12}),es=i=>{let t=br.get(i);if(t)return t;let e=fi(i.toLowerCase());return br.set(i,e),e},Er=class extends ms{constructor(){super({max:256});}},La=class extends ms{constructor(i=16*1024){super({maxSize:i,sizeCalculation:t=>t.length+1});}},Rn=Symbol("PathScurry setAsCwd"),ot,Si,vi,Ti,Ri,_i,Ai,Mi,xi,Oi,Ii,Ni,Fi,ki,Li,Di,Ci,Pi,Wi,pe,Ne,Ut,Kt,Qt,Zt,O,Fe,te,Bt,M,$s,as,gi,Us,Bs,yi,hs,Gs,Xs,ls,_n,An,Mn,Ys,qe,Ve,xn,ke,Hr,dt=(Hr=class{constructor(i,t=Tt,e,s,r,o,a){w(this,M);p(this,"name");p(this,"root");p(this,"roots");p(this,"parent");p(this,"nocase");p(this,"isCWD",false);w(this,ot);w(this,Si);w(this,vi);w(this,Ti);w(this,Ri);w(this,_i);w(this,Ai);w(this,Mi);w(this,xi);w(this,Oi);w(this,Ii);w(this,Ni);w(this,Fi);w(this,ki);w(this,Li);w(this,Di);w(this,Ci);w(this,Pi);w(this,Wi);w(this,pe);w(this,Ne);w(this,Ut);w(this,Kt);w(this,Qt);w(this,Zt);w(this,O);w(this,Fe);w(this,te);w(this,Bt);w(this,qe,[]);w(this,Ve,false);w(this,ke);this.name=i,m(this,pe,r?es(i):fi(i)),m(this,O,t&ka),this.nocase=r,this.roots=s,this.root=e||this,m(this,Fe,o),m(this,Ut,a.fullpath),m(this,Qt,a.relative),m(this,Zt,a.relativePosix),this.parent=a.parent,this.parent?m(this,ot,n(this.parent,ot)):m(this,ot,yn(a.fs));}get dev(){return n(this,Si)}get mode(){return n(this,vi)}get nlink(){return n(this,Ti)}get uid(){return n(this,Ri)}get gid(){return n(this,_i)}get rdev(){return n(this,Ai)}get blksize(){return n(this,Mi)}get ino(){return n(this,xi)}get size(){return n(this,Oi)}get blocks(){return n(this,Ii)}get atimeMs(){return n(this,Ni)}get mtimeMs(){return n(this,Fi)}get ctimeMs(){return n(this,ki)}get birthtimeMs(){return n(this,Li)}get atime(){return n(this,Di)}get mtime(){return n(this,Ci)}get ctime(){return n(this,Pi)}get birthtime(){return n(this,Wi)}get parentPath(){return (this.parent||this).fullpath()}get path(){return this.parentPath}depth(){return n(this,Ne)!==void 0?n(this,Ne):this.parent?m(this,Ne,this.parent.depth()+1):m(this,Ne,0)}childrenCache(){return n(this,Fe)}resolve(i){var s;if(!i)return this;let t=this.getRootString(i),e=i.substring(t.length).split(this.splitSep);return t?y(s=this.getRoot(t),M,$s).call(s,e):y(this,M,$s).call(this,e)}children(){let i=n(this,Fe).get(this);if(i)return i;let t=Object.assign([],{provisional:0});return n(this,Fe).set(this,t),m(this,O,n(this,O)&~Fs),t}child(i,t){if(i===""||i===".")return this;if(i==="..")return this.parent||this;let e=this.children(),s=this.nocase?es(i):fi(i);for(let l of e)if(n(l,pe)===s)return l;let r=this.parent?this.sep:"",o=n(this,Ut)?n(this,Ut)+r+i:void 0,a=this.newChild(i,Tt,{...t,parent:this,fullpath:o});return this.canReaddir()||m(a,O,n(a,O)|Ot),e.push(a),a}relative(){if(this.isCWD)return "";if(n(this,Qt)!==void 0)return n(this,Qt);let i=this.name,t=this.parent;if(!t)return m(this,Qt,this.name);let e=t.relative();return e+(!e||!t.parent?"":this.sep)+i}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return "";if(n(this,Zt)!==void 0)return n(this,Zt);let i=this.name,t=this.parent;if(!t)return m(this,Zt,this.fullpathPosix());let e=t.relativePosix();return e+(!e||!t.parent?"":"/")+i}fullpath(){if(n(this,Ut)!==void 0)return n(this,Ut);let i=this.name,t=this.parent;if(!t)return m(this,Ut,this.name);let e=t.fullpath()+(t.parent?this.sep:"")+i;return m(this,Ut,e)}fullpathPosix(){if(n(this,Kt)!==void 0)return n(this,Kt);if(this.sep==="/")return m(this,Kt,this.fullpath());if(!this.parent){let s=this.fullpath().replace(/\\/g,"/");return /^[a-z]:\//i.test(s)?m(this,Kt,`//?/${s}`):m(this,Kt,s)}let i=this.parent,t=i.fullpathPosix(),e=t+(!t||!i.parent?"":"/")+this.name;return m(this,Kt,e)}isUnknown(){return (n(this,O)&St)===Tt}isType(i){return this[`is${i}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return (n(this,O)&St)===vn}isDirectory(){return (n(this,O)&St)===jt}isCharacterDevice(){return (n(this,O)&St)===En}isBlockDevice(){return (n(this,O)&St)===Sn}isFIFO(){return (n(this,O)&St)===bn}isSocket(){return (n(this,O)&St)===Tn}isSymbolicLink(){return (n(this,O)&Re)===Re}lstatCached(){return n(this,O)&gr?this:void 0}readlinkCached(){return n(this,te)}realpathCached(){return n(this,Bt)}readdirCached(){let i=this.children();return i.slice(0,i.provisional)}canReadlink(){if(n(this,te))return true;if(!this.parent)return false;let i=n(this,O)&St;return !(i!==Tt&&i!==Re||n(this,O)&ts||n(this,O)&Ot)}calledReaddir(){return !!(n(this,O)&Fs)}isENOENT(){return !!(n(this,O)&Ot)}isNamed(i){return this.nocase?n(this,pe)===es(i):n(this,pe)===fi(i)}async readlink(){let i=n(this,te);if(i)return i;if(this.canReadlink()&&this.parent)try{let t=await n(this,ot).promises.readlink(this.fullpath()),e=(await this.parent.realpath())?.resolve(t);if(e)return m(this,te,e)}catch(t){y(this,M,Xs).call(this,t.code);return}}readlinkSync(){let i=n(this,te);if(i)return i;if(this.canReadlink()&&this.parent)try{let t=n(this,ot).readlinkSync(this.fullpath()),e=this.parent.realpathSync()?.resolve(t);if(e)return m(this,te,e)}catch(t){y(this,M,Xs).call(this,t.code);return}}async lstat(){if((n(this,O)&Ot)===0)try{return y(this,M,Ys).call(this,await n(this,ot).promises.lstat(this.fullpath())),this}catch(i){y(this,M,Gs).call(this,i.code);}}lstatSync(){if((n(this,O)&Ot)===0)try{return y(this,M,Ys).call(this,n(this,ot).lstatSync(this.fullpath())),this}catch(i){y(this,M,Gs).call(this,i.code);}}readdirCB(i,t=false){if(!this.canReaddir()){t?i(null,[]):queueMicrotask(()=>i(null,[]));return}let e=this.children();if(this.calledReaddir()){let r=e.slice(0,e.provisional);t?i(null,r):queueMicrotask(()=>i(null,r));return}if(n(this,qe).push(i),n(this,Ve))return;m(this,Ve,true);let s=this.fullpath();n(this,ot).readdir(s,{withFileTypes:true},(r,o)=>{if(r)y(this,M,hs).call(this,r.code),e.provisional=0;else {for(let a of o)y(this,M,ls).call(this,a,e);y(this,M,as).call(this,e);}y(this,M,xn).call(this,e.slice(0,e.provisional));});}async readdir(){if(!this.canReaddir())return [];let i=this.children();if(this.calledReaddir())return i.slice(0,i.provisional);let t=this.fullpath();if(n(this,ke))await n(this,ke);else {let e=()=>{};m(this,ke,new Promise(s=>e=s));try{for(let s of await n(this,ot).promises.readdir(t,{withFileTypes:!0}))y(this,M,ls).call(this,s,i);y(this,M,as).call(this,i);}catch(s){y(this,M,hs).call(this,s.code),i.provisional=0;}m(this,ke,void 0),e();}return i.slice(0,i.provisional)}readdirSync(){if(!this.canReaddir())return [];let i=this.children();if(this.calledReaddir())return i.slice(0,i.provisional);let t=this.fullpath();try{for(let e of n(this,ot).readdirSync(t,{withFileTypes:!0}))y(this,M,ls).call(this,e,i);y(this,M,as).call(this,i);}catch(e){y(this,M,hs).call(this,e.code),i.provisional=0;}return i.slice(0,i.provisional)}canReaddir(){if(n(this,O)&yr)return false;let i=St&n(this,O);return i===Tt||i===jt||i===Re}shouldWalk(i,t){return (n(this,O)&jt)===jt&&!(n(this,O)&yr)&&!i.has(this)&&(!t||t(this))}async realpath(){if(n(this,Bt))return n(this,Bt);if(!((os|ts|Ot)&n(this,O)))try{let i=await n(this,ot).promises.realpath(this.fullpath());return m(this,Bt,this.resolve(i))}catch{y(this,M,Bs).call(this);}}realpathSync(){if(n(this,Bt))return n(this,Bt);if(!((os|ts|Ot)&n(this,O)))try{let i=n(this,ot).realpathSync(this.fullpath());return m(this,Bt,this.resolve(i))}catch{y(this,M,Bs).call(this);}}[Rn](i){if(i===this)return;i.isCWD=false,this.isCWD=true;let t=new Set([]),e=[],s=this;for(;s&&s.parent;)t.add(s),m(s,Qt,e.join(this.sep)),m(s,Zt,e.join("/")),s=s.parent,e.push("..");for(s=i;s&&s.parent&&!t.has(s);)m(s,Qt,void 0),m(s,Zt,void 0),s=s.parent;}},ot=new WeakMap,Si=new WeakMap,vi=new WeakMap,Ti=new WeakMap,Ri=new WeakMap,_i=new WeakMap,Ai=new WeakMap,Mi=new WeakMap,xi=new WeakMap,Oi=new WeakMap,Ii=new WeakMap,Ni=new WeakMap,Fi=new WeakMap,ki=new WeakMap,Li=new WeakMap,Di=new WeakMap,Ci=new WeakMap,Pi=new WeakMap,Wi=new WeakMap,pe=new WeakMap,Ne=new WeakMap,Ut=new WeakMap,Kt=new WeakMap,Qt=new WeakMap,Zt=new WeakMap,O=new WeakMap,Fe=new WeakMap,te=new WeakMap,Bt=new WeakMap,M=new WeakSet,$s=function(i){let t=this;for(let e of i)t=t.child(e);return t},as=function(i){var t;m(this,O,n(this,O)|Fs);for(let e=i.provisional;e<i.length;e++){let s=i[e];s&&y(t=s,M,gi).call(t);}},gi=function(){n(this,O)&Ot||(m(this,O,(n(this,O)|Ot)&ci),y(this,M,Us).call(this));},Us=function(){var t;let i=this.children();i.provisional=0;for(let e of i)y(t=e,M,gi).call(t);},Bs=function(){m(this,O,n(this,O)|os),y(this,M,yi).call(this);},yi=function(){if(n(this,O)&mi)return;let i=n(this,O);(i&St)===jt&&(i&=ci),m(this,O,i|mi),y(this,M,Us).call(this);},hs=function(i=""){i==="ENOTDIR"||i==="EPERM"?y(this,M,yi).call(this):i==="ENOENT"?y(this,M,gi).call(this):this.children().provisional=0;},Gs=function(i=""){var t;i==="ENOTDIR"?y(t=this.parent,M,yi).call(t):i==="ENOENT"&&y(this,M,gi).call(this);},Xs=function(i=""){var e;let t=n(this,O);t|=ts,i==="ENOENT"&&(t|=Ot),(i==="EINVAL"||i==="UNKNOWN")&&(t&=ci),m(this,O,t),i==="ENOTDIR"&&this.parent&&y(e=this.parent,M,yi).call(e);},ls=function(i,t){return y(this,M,An).call(this,i,t)||y(this,M,_n).call(this,i,t)},_n=function(i,t){let e=ks(i),s=this.newChild(i.name,e,{parent:this}),r=n(s,O)&St;return r!==jt&&r!==Re&&r!==Tt&&m(s,O,n(s,O)|mi),t.unshift(s),t.provisional++,s},An=function(i,t){for(let e=t.provisional;e<t.length;e++){let s=t[e];if((this.nocase?es(i.name):fi(i.name))===n(s,pe))return y(this,M,Mn).call(this,i,s,e,t)}},Mn=function(i,t,e,s){let r=t.name;return m(t,O,n(t,O)&ci|ks(i)),r!==i.name&&(t.name=i.name),e!==s.provisional&&(e===s.length-1?s.pop():s.splice(e,1),s.unshift(t)),s.provisional++,t},Ys=function(i){let{atime:t,atimeMs:e,birthtime:s,birthtimeMs:r,blksize:o,blocks:a,ctime:l,ctimeMs:h,dev:c,gid:u,ino:d,mode:f,mtime:g,mtimeMs:b,nlink:E,rdev:T,size:S,uid:x}=i;m(this,Di,t),m(this,Ni,e),m(this,Wi,s),m(this,Li,r),m(this,Mi,o),m(this,Ii,a),m(this,Pi,l),m(this,ki,h),m(this,Si,c),m(this,_i,u),m(this,xi,d),m(this,vi,f),m(this,Ci,g),m(this,Fi,b),m(this,Ti,E),m(this,Ai,T),m(this,Oi,S),m(this,Ri,x);let R=ks(i);m(this,O,n(this,O)&ci|R|gr),R!==Tt&&R!==jt&&R!==Re&&m(this,O,n(this,O)|mi);},qe=new WeakMap,Ve=new WeakMap,xn=function(i){m(this,Ve,false);let t=n(this,qe).slice();n(this,qe).length=0,t.forEach(e=>e(null,i));},ke=new WeakMap,Hr),On=class In extends dt{constructor(e,s=Tt,r,o,a,l,h){super(e,s,r,o,a,l,h);p(this,"sep","\\");p(this,"splitSep",Fa);}newChild(e,s=Tt,r={}){return new In(e,s,this.root,this.roots,this.nocase,this.childrenCache(),r)}getRootString(e){return Ee.win32.parse(e).root}getRoot(e){if(e=Na(e.toUpperCase()),e===this.root.name)return this.root;for(let[s,r]of Object.entries(this.roots))if(this.sameRoot(e,s))return this.roots[e]=r;return this.roots[e]=new Ks(e,this).root}sameRoot(e,s=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(wn,"$1\\"),e===s}},Nn=class Fn extends dt{constructor(e,s=Tt,r,o,a,l,h){super(e,s,r,o,a,l,h);p(this,"splitSep","/");p(this,"sep","/");}getRootString(e){return e.startsWith("/")?"/":""}getRoot(e){return this.root}newChild(e,s=Tt,r={}){return new Fn(e,s,this.root,this.roots,this.nocase,this.childrenCache(),r)}},Je,Ke,zi,ji,qr,kn=(qr=class{constructor(i=process.cwd(),t,e,{nocase:s,childrenCacheSize:r=16*1024,fs:o=pi}={}){p(this,"root");p(this,"rootPath");p(this,"roots");p(this,"cwd");w(this,Je);w(this,Ke);w(this,zi);p(this,"nocase");w(this,ji);m(this,ji,yn(o)),(i instanceof URL||i.startsWith("file://"))&&(i=url.fileURLToPath(i));let a=t.resolve(i);this.roots=Object.create(null),this.rootPath=this.parseRootPath(a),m(this,Je,new Er),m(this,Ke,new Er),m(this,zi,new La(r));let l=a.substring(this.rootPath.length).split(e);if(l.length===1&&!l[0]&&l.pop(),s===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=s,this.root=this.newRoot(n(this,ji)),this.roots[this.rootPath]=this.root;let h=this.root,c=l.length-1,u=t.sep,d=this.rootPath,f=false;for(let g of l){let b=c--;h=h.child(g,{relative:new Array(b).fill("..").join(u),relativePosix:new Array(b).fill("..").join("/"),fullpath:d+=(f?"":u)+g}),f=true;}this.cwd=h;}depth(i=this.cwd){return typeof i=="string"&&(i=this.cwd.resolve(i)),i.depth()}childrenCache(){return n(this,zi)}resolve(...i){let t="";for(let r=i.length-1;r>=0;r--){let o=i[r];if(!(!o||o===".")&&(t=t?`${o}/${t}`:o,this.isAbsolute(o)))break}let e=n(this,Je).get(t);if(e!==void 0)return e;let s=this.cwd.resolve(t).fullpath();return n(this,Je).set(t,s),s}resolvePosix(...i){let t="";for(let r=i.length-1;r>=0;r--){let o=i[r];if(!(!o||o===".")&&(t=t?`${o}/${t}`:o,this.isAbsolute(o)))break}let e=n(this,Ke).get(t);if(e!==void 0)return e;let s=this.cwd.resolve(t).fullpathPosix();return n(this,Ke).set(t,s),s}relative(i=this.cwd){return typeof i=="string"&&(i=this.cwd.resolve(i)),i.relative()}relativePosix(i=this.cwd){return typeof i=="string"&&(i=this.cwd.resolve(i)),i.relativePosix()}basename(i=this.cwd){return typeof i=="string"&&(i=this.cwd.resolve(i)),i.name}dirname(i=this.cwd){return typeof i=="string"&&(i=this.cwd.resolve(i)),(i.parent||i).fullpath()}async readdir(i=this.cwd,t={withFileTypes:true}){typeof i=="string"?i=this.cwd.resolve(i):i instanceof dt||(t=i,i=this.cwd);let{withFileTypes:e}=t;if(i.canReaddir()){let s=await i.readdir();return e?s:s.map(r=>r.name)}else return []}readdirSync(i=this.cwd,t={withFileTypes:true}){typeof i=="string"?i=this.cwd.resolve(i):i instanceof dt||(t=i,i=this.cwd);let{withFileTypes:e=true}=t;return i.canReaddir()?e?i.readdirSync():i.readdirSync().map(s=>s.name):[]}async lstat(i=this.cwd){return typeof i=="string"&&(i=this.cwd.resolve(i)),i.lstat()}lstatSync(i=this.cwd){return typeof i=="string"&&(i=this.cwd.resolve(i)),i.lstatSync()}async readlink(i=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof i=="string"?i=this.cwd.resolve(i):i instanceof dt||(t=i.withFileTypes,i=this.cwd);let e=await i.readlink();return t?e:e?.fullpath()}readlinkSync(i=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof i=="string"?i=this.cwd.resolve(i):i instanceof dt||(t=i.withFileTypes,i=this.cwd);let e=i.readlinkSync();return t?e:e?.fullpath()}async realpath(i=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof i=="string"?i=this.cwd.resolve(i):i instanceof dt||(t=i.withFileTypes,i=this.cwd);let e=await i.realpath();return t?e:e?.fullpath()}realpathSync(i=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof i=="string"?i=this.cwd.resolve(i):i instanceof dt||(t=i.withFileTypes,i=this.cwd);let e=i.realpathSync();return t?e:e?.fullpath()}async walk(i=this.cwd,t={}){typeof i=="string"?i=this.cwd.resolve(i):i instanceof dt||(t=i,i=this.cwd);let{withFileTypes:e=true,follow:s=false,filter:r,walkFilter:o}=t,a=[];(!r||r(i))&&a.push(e?i:i.fullpath());let l=new Set,h=(u,d)=>{l.add(u),u.readdirCB((f,g)=>{if(f)return d(f);let b=g.length;if(!b)return d();let E=()=>{--b===0&&d();};for(let T of g)(!r||r(T))&&a.push(e?T:T.fullpath()),s&&T.isSymbolicLink()?T.realpath().then(S=>S?.isUnknown()?S.lstat():S).then(S=>S?.shouldWalk(l,o)?h(S,E):E()):T.shouldWalk(l,o)?h(T,E):E();},true);},c=i;return new Promise((u,d)=>{h(c,f=>{if(f)return d(f);u(a);});})}walkSync(i=this.cwd,t={}){typeof i=="string"?i=this.cwd.resolve(i):i instanceof dt||(t=i,i=this.cwd);let{withFileTypes:e=true,follow:s=false,filter:r,walkFilter:o}=t,a=[];(!r||r(i))&&a.push(e?i:i.fullpath());let l=new Set([i]);for(let h of l){let c=h.readdirSync();for(let u of c){(!r||r(u))&&a.push(e?u:u.fullpath());let d=u;if(u.isSymbolicLink()){if(!(s&&(d=u.realpathSync())))continue;d.isUnknown()&&d.lstatSync();}d.shouldWalk(l,o)&&l.add(d);}}return a}[Symbol.asyncIterator](){return this.iterate()}iterate(i=this.cwd,t={}){return typeof i=="string"?i=this.cwd.resolve(i):i instanceof dt||(t=i,i=this.cwd),this.stream(i,t)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(i=this.cwd,t={}){typeof i=="string"?i=this.cwd.resolve(i):i instanceof dt||(t=i,i=this.cwd);let{withFileTypes:e=true,follow:s=false,filter:r,walkFilter:o}=t;(!r||r(i))&&(yield e?i:i.fullpath());let a=new Set([i]);for(let l of a){let h=l.readdirSync();for(let c of h){(!r||r(c))&&(yield e?c:c.fullpath());let u=c;if(c.isSymbolicLink()){if(!(s&&(u=c.realpathSync())))continue;u.isUnknown()&&u.lstatSync();}u.shouldWalk(a,o)&&a.add(u);}}}stream(i=this.cwd,t={}){typeof i=="string"?i=this.cwd.resolve(i):i instanceof dt||(t=i,i=this.cwd);let{withFileTypes:e=true,follow:s=false,filter:r,walkFilter:o}=t,a=new us({objectMode:true});(!r||r(i))&&a.write(e?i:i.fullpath());let l=new Set,h=[i],c=0,u=()=>{let d=false;for(;!d;){let f=h.shift();if(!f){c===0&&a.end();return}c++,l.add(f);let g=(E,T,S=false)=>{if(E)return a.emit("error",E);if(s&&!S){let x=[];for(let R of T)R.isSymbolicLink()&&x.push(R.realpath().then(A=>A?.isUnknown()?A.lstat():A));if(x.length){Promise.all(x).then(()=>g(null,T,true));return}}for(let x of T)x&&(!r||r(x))&&(a.write(e?x:x.fullpath())||(d=true));c--;for(let x of T){let R=x.realpathCached()||x;R.shouldWalk(l,o)&&h.push(R);}d&&!a.flowing?a.once("drain",u):b||u();},b=true;f.readdirCB(g,true),b=false;}};return u(),a}streamSync(i=this.cwd,t={}){typeof i=="string"?i=this.cwd.resolve(i):i instanceof dt||(t=i,i=this.cwd);let{withFileTypes:e=true,follow:s=false,filter:r,walkFilter:o}=t,a=new us({objectMode:true}),l=new Set;(!r||r(i))&&a.write(e?i:i.fullpath());let h=[i],c=0,u=()=>{let d=false;for(;!d;){let f=h.shift();if(!f){c===0&&a.end();return}c++,l.add(f);let g=f.readdirSync();for(let b of g)(!r||r(b))&&(a.write(e?b:b.fullpath())||(d=true));c--;for(let b of g){let E=b;if(b.isSymbolicLink()){if(!(s&&(E=b.realpathSync())))continue;E.isUnknown()&&E.lstatSync();}E.shouldWalk(l,o)&&h.push(E);}}d&&!a.flowing&&a.once("drain",u);};return u(),a}chdir(i=this.cwd){let t=this.cwd;this.cwd=typeof i=="string"?this.cwd.resolve(i):i,this.cwd[Rn](t);}},Je=new WeakMap,Ke=new WeakMap,zi=new WeakMap,ji=new WeakMap,qr),Ks=class extends kn{constructor(t=process.cwd(),e={}){let{nocase:s=true}=e;super(t,Ee.win32,"\\",{...e,nocase:s});p(this,"sep","\\");this.nocase=s;for(let r=this.cwd;r;r=r.parent)r.nocase=this.nocase;}parseRootPath(t){return Ee.win32.parse(t).root.toUpperCase()}newRoot(t){return new On(this.rootPath,jt,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")||t.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(t)}},Qs=class extends kn{constructor(t=process.cwd(),e={}){let{nocase:s=false}=e;super(t,Ee.posix,"/",{...e,nocase:s});p(this,"sep","/");this.nocase=s;}parseRootPath(t){return "/"}newRoot(t){return new Nn(this.rootPath,jt,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")}},Ln=class extends Qs{constructor(i=process.cwd(),t={}){let{nocase:e=true}=t;super(i,{...t,nocase:e});}};process.platform==="win32"?On:Nn;var Da=process.platform==="win32"?Ks:process.platform==="darwin"?Ln:Qs,Ca=i=>i.length>=1,Pa=i=>i.length>=1,Wa=Symbol.for("nodejs.util.inspect.custom"),U,ut,B,Le,Wt,$i,me,fe,ge,Qe,Ze,Dn=(Ze=class{constructor(t,e,s,r){w(this,U);w(this,ut);w(this,B);p(this,"length");w(this,Le);w(this,Wt);w(this,$i);w(this,me);w(this,fe);w(this,ge);w(this,Qe,true);if(!Ca(t))throw new TypeError("empty pattern list");if(!Pa(e))throw new TypeError("empty glob list");if(e.length!==t.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=t.length,s<0||s>=this.length)throw new TypeError("index out of range");if(m(this,U,t),m(this,ut,e),m(this,B,s),m(this,Le,r),n(this,B)===0){if(this.isUNC()){let[o,a,l,h,...c]=n(this,U),[u,d,f,g,...b]=n(this,ut);c[0]===""&&(c.shift(),b.shift());let E=[o,a,l,h,""].join("/"),T=[u,d,f,g,""].join("/");m(this,U,[E,...c]),m(this,ut,[T,...b]),this.length=n(this,U).length;}else if(this.isDrive()||this.isAbsolute()){let[o,...a]=n(this,U),[l,...h]=n(this,ut);a[0]===""&&(a.shift(),h.shift());let c=o+"/",u=l+"/";m(this,U,[c,...a]),m(this,ut,[u,...h]),this.length=n(this,U).length;}}}[Wa](){return "Pattern <"+n(this,ut).slice(n(this,B)).join("/")+">"}pattern(){return n(this,U)[n(this,B)]}isString(){return typeof n(this,U)[n(this,B)]=="string"}isGlobstar(){return n(this,U)[n(this,B)]===at}isRegExp(){return n(this,U)[n(this,B)]instanceof RegExp}globString(){return m(this,$i,n(this,$i)||(n(this,B)===0?this.isAbsolute()?n(this,ut)[0]+n(this,ut).slice(1).join("/"):n(this,ut).join("/"):n(this,ut).slice(n(this,B)).join("/")))}hasMore(){return this.length>n(this,B)+1}rest(){return n(this,Wt)!==void 0?n(this,Wt):this.hasMore()?(m(this,Wt,new Ze(n(this,U),n(this,ut),n(this,B)+1,n(this,Le))),m(n(this,Wt),ge,n(this,ge)),m(n(this,Wt),fe,n(this,fe)),m(n(this,Wt),me,n(this,me)),n(this,Wt)):m(this,Wt,null)}isUNC(){let t=n(this,U);return n(this,fe)!==void 0?n(this,fe):m(this,fe,n(this,Le)==="win32"&&n(this,B)===0&&t[0]===""&&t[1]===""&&typeof t[2]=="string"&&!!t[2]&&typeof t[3]=="string"&&!!t[3])}isDrive(){let t=n(this,U);return n(this,me)!==void 0?n(this,me):m(this,me,n(this,Le)==="win32"&&n(this,B)===0&&this.length>1&&typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]))}isAbsolute(){let t=n(this,U);return n(this,ge)!==void 0?n(this,ge):m(this,ge,t[0]===""&&t.length>1||this.isDrive()||this.isUNC())}root(){let t=n(this,U)[0];return typeof t=="string"&&this.isAbsolute()&&n(this,B)===0?t:""}checkFollowGlobstar(){return !(n(this,B)===0||!this.isGlobstar()||!n(this,Qe))}markFollowGlobstar(){return n(this,B)===0||!this.isGlobstar()||!n(this,Qe)?false:(m(this,Qe,false),true)}},U=new WeakMap,ut=new WeakMap,B=new WeakMap,Le=new WeakMap,Wt=new WeakMap,$i=new WeakMap,me=new WeakMap,fe=new WeakMap,ge=new WeakMap,Qe=new WeakMap,Ze),za=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Sr=class{constructor(i,{nobrace:t,nocase:e,noext:s,noglobstar:r,platform:o=za}){p(this,"relative");p(this,"relativeChildren");p(this,"absolute");p(this,"absoluteChildren");p(this,"platform");p(this,"mmopts");this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=o,this.mmopts={dot:true,nobrace:t,nocase:e,noext:s,noglobstar:r,optimizationLevel:2,platform:o,nocomment:true,nonegate:true};for(let a of i)this.add(a);}add(i){let t=new we(i,this.mmopts);for(let e=0;e<t.set.length;e++){let s=t.set[e],r=t.globParts[e];if(!s||!r)throw new Error("invalid pattern object");for(;s[0]==="."&&r[0]===".";)s.shift(),r.shift();let o=new Dn(s,r,0,this.platform),a=new we(o.globString(),this.mmopts),l=r[r.length-1]==="**",h=o.isAbsolute();h?this.absolute.push(a):this.relative.push(a),l&&(h?this.absoluteChildren.push(a):this.relativeChildren.push(a));}}ignored(i){let t=i.fullpath(),e=`${t}/`,s=i.relative()||".",r=`${s}/`;for(let o of this.relative)if(o.match(s)||o.match(r))return true;for(let o of this.absolute)if(o.match(t)||o.match(e))return true;return false}childrenIgnored(i){let t=i.fullpath()+"/",e=(i.relative()||".")+"/";for(let s of this.relativeChildren)if(s.match(e))return true;for(let s of this.absoluteChildren)if(s.match(t))return true;return false}},ja=class Cn{constructor(t=new Map){p(this,"store");this.store=t;}copy(){return new Cn(new Map(this.store))}hasWalked(t,e){return this.store.get(t.fullpath())?.has(e.globString())}storeWalked(t,e){let s=t.fullpath(),r=this.store.get(s);r?r.add(e.globString()):this.store.set(s,new Set([e.globString()]));}},$a=class{constructor(){p(this,"store",new Map);}add(i,t,e){let s=(t?2:0)|(e?1:0),r=this.store.get(i);this.store.set(i,r===void 0?s:s&r);}entries(){return [...this.store.entries()].map(([i,t])=>[i,!!(t&2),!!(t&1)])}},Ua=class{constructor(){p(this,"store",new Map);}add(i,t){if(!i.canReaddir())return;let e=this.store.get(i);e?e.find(s=>s.globString()===t.globString())||e.push(t):this.store.set(i,[t]);}get(i){let t=this.store.get(i);if(!t)throw new Error("attempting to walk unknown path");return t}entries(){return this.keys().map(i=>[i,this.store.get(i)])}keys(){return [...this.store.keys()].filter(i=>i.canReaddir())}},vr=class Pn{constructor(t,e){p(this,"hasWalkedCache");p(this,"matches",new $a);p(this,"subwalks",new Ua);p(this,"patterns");p(this,"follow");p(this,"dot");p(this,"opts");this.opts=t,this.follow=!!t.follow,this.dot=!!t.dot,this.hasWalkedCache=e?e.copy():new ja;}processPatterns(t,e){this.patterns=e;let s=e.map(r=>[t,r]);for(let[r,o]of s){this.hasWalkedCache.storeWalked(r,o);let a=o.root(),l=o.isAbsolute()&&this.opts.absolute!==false;if(a){r=r.resolve(a==="/"&&this.opts.root!==void 0?this.opts.root:a);let d=o.rest();if(d)o=d;else {this.matches.add(r,true,false);continue}}if(r.isENOENT())continue;let h,c,u=false;for(;typeof(h=o.pattern())=="string"&&(c=o.rest());)r=r.resolve(h),o=c,u=true;if(h=o.pattern(),c=o.rest(),u){if(this.hasWalkedCache.hasWalked(r,o))continue;this.hasWalkedCache.storeWalked(r,o);}if(typeof h=="string"){let d=h===".."||h===""||h===".";this.matches.add(r.resolve(h),l,d);continue}else if(h===at){(!r.isSymbolicLink()||this.follow||o.checkFollowGlobstar())&&this.subwalks.add(r,o);let d=c?.pattern(),f=c?.rest();if(!c||(d===""||d===".")&&!f)this.matches.add(r,l,d===""||d===".");else if(d===".."){let g=r.parent||r;f?this.hasWalkedCache.hasWalked(g,f)||this.subwalks.add(g,f):this.matches.add(g,l,true);}}else h instanceof RegExp&&this.subwalks.add(r,o);}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new Pn(this.opts,this.hasWalkedCache)}filterEntries(t,e){let s=this.subwalks.get(t),r=this.child();for(let o of e)for(let a of s){let l=a.isAbsolute(),h=a.pattern(),c=a.rest();h===at?r.testGlobstar(o,a,c,l):h instanceof RegExp?r.testRegExp(o,h,c,l):r.testString(o,h,c,l);}return r}testGlobstar(t,e,s,r){if((this.dot||!t.name.startsWith("."))&&(e.hasMore()||this.matches.add(t,r,false),t.canReaddir()&&(this.follow||!t.isSymbolicLink()?this.subwalks.add(t,e):t.isSymbolicLink()&&(s&&e.checkFollowGlobstar()?this.subwalks.add(t,s):e.markFollowGlobstar()&&this.subwalks.add(t,e)))),s){let o=s.pattern();if(typeof o=="string"&&o!==".."&&o!==""&&o!==".")this.testString(t,o,s.rest(),r);else if(o===".."){let a=t.parent||t;this.subwalks.add(a,s);}else o instanceof RegExp&&this.testRegExp(t,o,s.rest(),r);}}testRegExp(t,e,s,r){e.test(t.name)&&(s?this.subwalks.add(t,s):this.matches.add(t,r,false));}testString(t,e,s,r){t.isNamed(e)&&(s?this.subwalks.add(t,s):this.matches.add(t,r,false));}},Ba=(i,t)=>typeof i=="string"?new Sr([i],t):Array.isArray(i)?new Sr(i,t):i,ti,ee,De,Rt,_e,Hs,Vr,Wn=(Vr=class{constructor(i,t,e){w(this,Rt);p(this,"path");p(this,"patterns");p(this,"opts");p(this,"seen",new Set);p(this,"paused",false);p(this,"aborted",false);w(this,ti,[]);w(this,ee);w(this,De);p(this,"signal");p(this,"maxDepth");p(this,"includeChildMatches");if(this.patterns=i,this.path=t,this.opts=e,m(this,De,!e.posix&&e.platform==="win32"?"\\":"/"),this.includeChildMatches=e.includeChildMatches!==false,(e.ignore||!this.includeChildMatches)&&(m(this,ee,Ba(e.ignore??[],e)),!this.includeChildMatches&&typeof n(this,ee).add!="function")){let s="cannot ignore child matches, ignore lacks add() method.";throw new Error(s)}this.maxDepth=e.maxDepth||1/0,e.signal&&(this.signal=e.signal,this.signal.addEventListener("abort",()=>{n(this,ti).length=0;}));}pause(){this.paused=true;}resume(){if(this.signal?.aborted)return;this.paused=false;let i;for(;!this.paused&&(i=n(this,ti).shift());)i();}onResume(i){this.signal?.aborted||(this.paused?n(this,ti).push(i):i());}async matchCheck(i,t){if(t&&this.opts.nodir)return;let e;if(this.opts.realpath){if(e=i.realpathCached()||await i.realpath(),!e)return;i=e;}let s=i.isUnknown()||this.opts.stat?await i.lstat():i;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let r=await s.realpath();r&&(r.isUnknown()||this.opts.stat)&&await r.lstat();}return this.matchCheckTest(s,t)}matchCheckTest(i,t){return i&&(this.maxDepth===1/0||i.depth()<=this.maxDepth)&&(!t||i.canReaddir())&&(!this.opts.nodir||!i.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!i.isSymbolicLink()||!i.realpathCached()?.isDirectory())&&!y(this,Rt,_e).call(this,i)?i:void 0}matchCheckSync(i,t){if(t&&this.opts.nodir)return;let e;if(this.opts.realpath){if(e=i.realpathCached()||i.realpathSync(),!e)return;i=e;}let s=i.isUnknown()||this.opts.stat?i.lstatSync():i;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let r=s.realpathSync();r&&(r?.isUnknown()||this.opts.stat)&&r.lstatSync();}return this.matchCheckTest(s,t)}matchFinish(i,t){if(y(this,Rt,_e).call(this,i))return;if(!this.includeChildMatches&&n(this,ee)?.add){let r=`${i.relativePosix()}/**`;n(this,ee).add(r);}let e=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(i);let s=this.opts.mark&&i.isDirectory()?n(this,De):"";if(this.opts.withFileTypes)this.matchEmit(i);else if(e){let r=this.opts.posix?i.fullpathPosix():i.fullpath();this.matchEmit(r+s);}else {let r=this.opts.posix?i.relativePosix():i.relative(),o=this.opts.dotRelative&&!r.startsWith(".."+n(this,De))?"."+n(this,De):"";this.matchEmit(r?o+r+s:"."+s);}}async match(i,t,e){let s=await this.matchCheck(i,e);s&&this.matchFinish(s,t);}matchSync(i,t,e){let s=this.matchCheckSync(i,e);s&&this.matchFinish(s,t);}walkCB(i,t,e){this.signal?.aborted&&e(),this.walkCB2(i,t,new vr(this.opts),e);}walkCB2(i,t,e,s){if(y(this,Rt,Hs).call(this,i))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2(i,t,e,s));return}e.processPatterns(i,t);let r=1,o=()=>{--r===0&&s();};for(let[a,l,h]of e.matches.entries())y(this,Rt,_e).call(this,a)||(r++,this.match(a,l,h).then(()=>o()));for(let a of e.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;r++;let l=a.readdirCached();a.calledReaddir()?this.walkCB3(a,l,e,o):a.readdirCB((h,c)=>this.walkCB3(a,c,e,o),true);}o();}walkCB3(i,t,e,s){e=e.filterEntries(i,t);let r=1,o=()=>{--r===0&&s();};for(let[a,l,h]of e.matches.entries())y(this,Rt,_e).call(this,a)||(r++,this.match(a,l,h).then(()=>o()));for(let[a,l]of e.subwalks.entries())r++,this.walkCB2(a,l,e.child(),o);o();}walkCBSync(i,t,e){this.signal?.aborted&&e(),this.walkCB2Sync(i,t,new vr(this.opts),e);}walkCB2Sync(i,t,e,s){if(y(this,Rt,Hs).call(this,i))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2Sync(i,t,e,s));return}e.processPatterns(i,t);let r=1,o=()=>{--r===0&&s();};for(let[a,l,h]of e.matches.entries())y(this,Rt,_e).call(this,a)||this.matchSync(a,l,h);for(let a of e.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;r++;let l=a.readdirSync();this.walkCB3Sync(a,l,e,o);}o();}walkCB3Sync(i,t,e,s){e=e.filterEntries(i,t);let r=1,o=()=>{--r===0&&s();};for(let[a,l,h]of e.matches.entries())y(this,Rt,_e).call(this,a)||this.matchSync(a,l,h);for(let[a,l]of e.subwalks.entries())r++,this.walkCB2Sync(a,l,e.child(),o);o();}},ti=new WeakMap,ee=new WeakMap,De=new WeakMap,Rt=new WeakSet,_e=function(i){return this.seen.has(i)||!!n(this,ee)?.ignored?.(i)},Hs=function(i){return !!n(this,ee)?.childrenIgnored?.(i)},Vr),Tr=class extends Wn{constructor(t,e,s){super(t,e,s);p(this,"matches",new Set);}matchEmit(t){this.matches.add(t);}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((t,e)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?e(this.signal.reason):t(this.matches);});}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},Rr=class extends Wn{constructor(t,e,s){super(t,e,s);p(this,"results");this.results=new us({signal:this.signal,objectMode:true}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume());}matchEmit(t){this.results.write(t),this.results.flowing||this.pause();}stream(){let t=this.path;return t.isUnknown()?t.lstat().then(()=>{this.walkCB(t,this.patterns,()=>this.results.end());}):this.walkCB(t,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}},Ga=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Pe=class{constructor(i,t){p(this,"absolute");p(this,"cwd");p(this,"root");p(this,"dot");p(this,"dotRelative");p(this,"follow");p(this,"ignore");p(this,"magicalBraces");p(this,"mark");p(this,"matchBase");p(this,"maxDepth");p(this,"nobrace");p(this,"nocase");p(this,"nodir");p(this,"noext");p(this,"noglobstar");p(this,"pattern");p(this,"platform");p(this,"realpath");p(this,"scurry");p(this,"stat");p(this,"signal");p(this,"windowsPathsNoEscape");p(this,"withFileTypes");p(this,"includeChildMatches");p(this,"opts");p(this,"patterns");if(!t)throw new TypeError("glob options required");if(this.withFileTypes=!!t.withFileTypes,this.signal=t.signal,this.follow=!!t.follow,this.dot=!!t.dot,this.dotRelative=!!t.dotRelative,this.nodir=!!t.nodir,this.mark=!!t.mark,t.cwd?(t.cwd instanceof URL||t.cwd.startsWith("file://"))&&(t.cwd=url.fileURLToPath(t.cwd)):this.cwd="",this.cwd=t.cwd||"",this.root=t.root,this.magicalBraces=!!t.magicalBraces,this.nobrace=!!t.nobrace,this.noext=!!t.noext,this.realpath=!!t.realpath,this.absolute=t.absolute,this.includeChildMatches=t.includeChildMatches!==false,this.noglobstar=!!t.noglobstar,this.matchBase=!!t.matchBase,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:1/0,this.stat=!!t.stat,this.ignore=t.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof i=="string"&&(i=[i]),this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===false,this.windowsPathsNoEscape&&(i=i.map(l=>l.replace(/\\/g,"/"))),this.matchBase){if(t.noglobstar)throw new TypeError("base matching requires globstar");i=i.map(l=>l.includes("/")?l:`./**/${l}`);}if(this.pattern=i,this.platform=t.platform||Ga,this.opts={...t,platform:this.platform},t.scurry){if(this.scurry=t.scurry,t.nocase!==void 0&&t.nocase!==t.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else {let l=t.platform==="win32"?Ks:t.platform==="darwin"?Ln:t.platform?Qs:Da;this.scurry=new l(this.cwd,{nocase:t.nocase,fs:t.fs});}this.nocase=this.scurry.nocase;let e=this.platform==="darwin"||this.platform==="win32",s={braceExpandMax:1e4,...t,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:e,nocomment:true,noext:this.noext,nonegate:true,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},r=this.pattern.map(l=>new we(l,s)),[o,a]=r.reduce((l,h)=>(l[0].push(...h.set),l[1].push(...h.globParts),l),[[],[]]);this.patterns=o.map((l,h)=>{let c=a[h];if(!c)throw new Error("invalid pattern object");return new Dn(l,c,0,this.platform)});}async walk(){return [...await new Tr(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return [...new Tr(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new Rr(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new Rr(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}},Xa=(i,t={})=>{Array.isArray(i)||(i=[i]);for(let e of i)if(new we(e,t).hasMagic())return true;return false};function fs(i,t={}){return new Pe(i,t).streamSync()}function zn(i,t={}){return new Pe(i,t).stream()}function jn(i,t={}){return new Pe(i,t).walkSync()}async function _r(i,t={}){return new Pe(i,t).walk()}function gs(i,t={}){return new Pe(i,t).iterateSync()}function $n(i,t={}){return new Pe(i,t).iterate()}var Ya=fs,Ha=Object.assign(zn,{sync:fs}),qa=gs,Va=Object.assign($n,{sync:gs}),Ja=Object.assign(jn,{stream:fs,iterate:gs}),ps=Object.assign(_r,{glob:_r,globSync:jn,sync:Ja,globStream:zn,stream:Ha,globStreamSync:fs,streamSync:Ya,globIterate:$n,iterate:Va,globIterateSync:gs,iterateSync:qa,Glob:Pe,hasMagic:Xa,escape:on,unescape:$e});ps.glob=ps;var be;(A=>{A.Level=Qa__default.default.enum(["DEBUG","INFO","WARN","ERROR"]).meta({ref:"LogLevel",description:"Log level"});let t={DEBUG:0,INFO:1,WARN:2,ERROR:3},e="INFO";function s(_){return t[_]>=t[e]}function r(){return e}A.getLevel=r;let o=new Map;A.Default=R({service:"default"});let l="";function h(){return l}A.file=h;let c,u,d=false,f=()=>{},g=false;async function b(_){if(d)return;if(_.print){d=true;return}_.level&&(e=_.level);let N=_.logDir||Ee__default.default.join(process.env.EASBOT_LOG_PATH??process.cwd(),"logs");_.logFile?l=Ee__default.default.join(N,_.logFile??"memory.log"):l=Ee__default.default.join(N,"memory.log");try{await se__default.default.mkdir(N,{recursive:!0}),c=await se__default.default.open(l,"a"),u=ma.createWriteStream("",{fd:c.fd,autoClose:!1}),f=F=>{if(!(g||!u||u.destroyed))try{if(!u.writable)return;u.write(F,tt=>{tt&&!g&&(g=!0,setTimeout(()=>{g=!1;},1e3));});}catch{g||(g=!0,setTimeout(()=>{g=!1;},1e3));}},d=!0;}catch{f=F=>{try{process.stderr.write(F);}catch{}},d=true;}}A.init=b;async function E(){d&&(u&&!u.destroyed&&(await new Promise((_,N)=>{u.end(F=>{F?N(F):_();});}).catch(()=>{}),u=void 0),c&&(await c.close().catch(()=>{}),c=void 0),f=_=>{try{process.stderr.write(_);}catch{}},d=false);}A.close=E;function S(_,N=0){let F=_.message;return _.cause instanceof Error&&N<10?F+" Caused by: "+S(_.cause,N+1):F}let x=Date.now();function R(_){_=_||{};let N=_.service;if(N&&typeof N=="string"){let C=o.get(N);if(C)return C}function F(C,G){let Es=Object.entries({..._,...G}).filter(([ir,re])=>re!=null).map(([ir,re])=>{let Ss=`${ir}=`;return re instanceof Error?Ss+S(re):typeof re=="object"?Ss+JSON.stringify(re):Ss+re}).join(" "),We=new Date,Vn=We.getTime()-x;return x=We.getTime(),[utils.formatLogTime(We),"+"+Vn+"ms",Es,C].filter(Boolean).join(" ")+`
4
- `}let tt={debug(C,G){s("DEBUG")&&f("DEBUG "+F(C,G));},info(C,G){s("INFO")&&f("INFO "+F(C,G));},error(C,G){s("ERROR")&&f("ERROR "+F(C,G));},warn(C,G){s("WARN")&&f("WARN "+F(C,G));},tag(C,G){return _&&(_[C]=G),tt},clone(){return A.create({..._})},time(C,G){let Es=Date.now();tt.info(C,{status:"started",...G});function We(){tt.info(C,{status:"completed",duration:Date.now()-Es,...G});}return {stop:We,[Symbol.dispose](){We();}}}};return N&&typeof N=="string"&&o.set(N,tt),tt}A.create=R;})(be||(be={}));var lt=be.create({service:"memory.tokenizer"}),Xt=false,ih=utils.loadTextFile("./assets/jieba_dict.txt",ct);async function Un(i){if(!Xt)try{lt.debug("Initializing jieba tokenizer");let t=ih();if(ie__namespace.with_dict(t),lt.debug("Built-in dictionary loaded"),i?.dictPath&&i.dictPath.length>0)for(let e of i.dictPath)await sh(e);Xt=!0,lt.debug("Jieba tokenizer initialized successfully");}catch(t){lt.error("Failed to initialize jieba tokenizer",{error:String(t)}),lt.warn("Using fallback tokenization (space-based)");}}async function sh(i){if(!Xt)throw new Error("Tokenizer not initialized");try{let t=await utils.Filesystem.readText(i);lt.debug("Loading custom dictionary",{dictPath:i}),ie__namespace.with_dict(t),lt.debug("Custom dictionary loaded successfully",{dictPath:i});}catch(t){lt.warn("Failed to load custom dictionary",{dictPath:i,error:String(t)});}}function rh(i){if(!Xt)return i.split(/\s+/).filter(Boolean);try{return ie__namespace.cut(i)}catch(t){return lt.warn("Tokenization failed, using fallback",{error:String(t)}),i.split(/\s+/).filter(Boolean)}}function nh(i){if(!Xt)return i.split(/\s+/).filter(Boolean);try{return ie__namespace.cut_for_search(i)}catch(t){return lt.warn("Tokenization for search failed, using fallback",{error:String(t)}),i.split(/\s+/).filter(Boolean)}}function El(i,t,e){if(Xt)try{ie__namespace.add_word(i,t,e),lt.debug("Word added to dictionary",{word:i,freq:t,tag:e});}catch(s){lt.warn("Failed to add word",{word:i,error:String(s)});}}function Sl(){return Xt}async function vl(){Xt=false,lt.debug("Tokenizer closed");}function er(i){if(!Xt)return i.split(/\s+/).filter(Boolean).join(" ");try{return rh(i).join(" ")}catch(t){return lt.warn("Tokenization failed, using fallback",{error:String(t)}),i.split(/\s+/).filter(Boolean).join(" ")}}function Bn(i){if(!Xt)return i.split(/\s+/).filter(Boolean).join(" ");try{return nh(i).join(" ")}catch(t){return lt.warn("Tokenization for search failed, using fallback",{error:String(t)}),i.split(/\s+/).filter(Boolean).join(" ")}}var Ui=class{constructor(t){p(this,"db",null);p(this,"storagePath");p(this,"initialized",false);p(this,"initPromise",null);this.storagePath=utils.Filesystem.toUnixPath(t);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize(),await this.initPromise,this.initialized=true;}}async doInitialize(){try{this.db=await this.openDatabaseAsync(),this.createTables(),this.db.pragma("foreign_keys = ON");}catch(t){throw new Q(`Database initialization failed: ${t.message}`,t)}}async openDatabaseAsync(){return new Promise((t,e)=>{setImmediate(()=>{try{let s=new oh__default.default(this.storagePath);s.pragma("journal_mode = WAL"),s.pragma("synchronous = NORMAL"),s.pragma("cache_size = -64000"),s.pragma("temp_store = MEMORY"),t(s);}catch(s){e(s);}});})}createTables(){if(!this.db)throw new Q("Database not initialized");let t=this.db;t.exec(`
1
+ 'use strict';var chunk5SBYP5H4_cjs=require('./chunks/chunk-5SBYP5H4.cjs'),types=require('@easbot/types'),x=require('jieba-wasm'),utils=require('@easbot/utils'),Ae=require('better-sqlite3'),crypto=require('crypto'),N=require('fs/promises'),_=require('path'),fs=require('fs'),ai=require('ai');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var x__namespace=/*#__PURE__*/_interopNamespace(x);var Ae__default=/*#__PURE__*/_interopDefault(Ae);var N__default=/*#__PURE__*/_interopDefault(N);var ___default=/*#__PURE__*/_interopDefault(_);var te=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"],F=class extends Error{constructor(t,n,r){super(t,{cause:r});this.code=n;this.cause=r;this.name="MemoryError";}},M=class extends F{constructor(e,t){super(e,"MEMORY_VALIDATION_ERROR",t),this.name="MemoryValidationError";}},W=class extends F{constructor(e){super(`Memory not found: ${e}`,"MEMORY_NOT_FOUND"),this.name="MemoryNotFoundError";}},X=class extends F{constructor(e){super(e,"MEMORY_PERMISSION_ERROR"),this.name="MemoryPermissionError";}},T=class extends F{constructor(e,t){super(e,"MEMORY_DATABASE_ERROR",t),this.name="MemoryDatabaseError";}},L=class extends F{constructor(e,t){super(e,"MEMORY_FILE_ERROR",t),this.name="MemoryFileError";}},J=class extends F{constructor(e,t){super(e,"MEMORY_SEARCH_ERROR",t),this.name="MemorySearchError";}},B=class extends F{constructor(e,t){super(e,"MEMORY_EMBEDDING_ERROR",t),this.name="MemoryEmbeddingError";}},Te=(d=>(d.VALIDATION_ERROR="MEMORY_VALIDATION_ERROR",d.NOT_FOUND="MEMORY_NOT_FOUND",d.PERMISSION_ERROR="MEMORY_PERMISSION_ERROR",d.DATABASE_ERROR="MEMORY_DATABASE_ERROR",d.FILE_ERROR="MEMORY_FILE_ERROR",d.SEARCH_ERROR="MEMORY_SEARCH_ERROR",d.EMBEDDING_ERROR="MEMORY_EMBEDDING_ERROR",d))(Te||{});var I=chunk5SBYP5H4_cjs.c.create({service:"memory.tokenizer"}),v=false,Ie=utils.loadTextFile("./assets/jieba_dict.txt",chunk5SBYP5H4_cjs.b);async function de(g){if(!v)try{I.debug("Initializing jieba tokenizer");let e=Ie();if(x__namespace.with_dict(e),I.debug("Built-in dictionary loaded"),g?.dictPath&&g.dictPath.length>0)for(let t of g.dictPath)await Me(t);v=!0,I.debug("Jieba tokenizer initialized successfully");}catch(e){I.error("Failed to initialize jieba tokenizer",{error:String(e)}),I.warn("Using fallback tokenization (space-based)");}}async function Me(g){if(!v)throw new Error("Tokenizer not initialized");try{let e=await utils.Filesystem.readText(g);I.debug("Loading custom dictionary",{dictPath:g}),x__namespace.with_dict(e),I.debug("Custom dictionary loaded successfully",{dictPath:g});}catch(e){I.warn("Failed to load custom dictionary",{dictPath:g,error:String(e)});}}function Se(g){if(!v)return g.split(/\s+/).filter(Boolean);try{return x__namespace.cut(g)}catch(e){return I.warn("Tokenization failed, using fallback",{error:String(e)}),g.split(/\s+/).filter(Boolean)}}function Ne(g){if(!v)return g.split(/\s+/).filter(Boolean);try{return x__namespace.cut_for_search(g)}catch(e){return I.warn("Tokenization for search failed, using fallback",{error:String(e)}),g.split(/\s+/).filter(Boolean)}}function Ve(g,e,t){if(v)try{x__namespace.add_word(g,e,t),I.debug("Word added to dictionary",{word:g,freq:e,tag:t});}catch(n){I.warn("Failed to add word",{word:g,error:String(n)});}}function Je(){return v}async function Ge(){v=false,I.debug("Tokenizer closed");}function ie(g){if(!v)return g.split(/\s+/).filter(Boolean).join(" ");try{return Se(g).join(" ")}catch(e){return I.warn("Tokenization failed, using fallback",{error:String(e)}),g.split(/\s+/).filter(Boolean).join(" ")}}function ce(g){if(!v)return g.split(/\s+/).filter(Boolean).join(" ");try{return Ne(g).join(" ")}catch(e){return I.warn("Tokenization for search failed, using fallback",{error:String(e)}),g.split(/\s+/).filter(Boolean).join(" ")}}var j=class{constructor(e){chunk5SBYP5H4_cjs.a(this,"db",null);chunk5SBYP5H4_cjs.a(this,"storagePath");chunk5SBYP5H4_cjs.a(this,"initialized",false);chunk5SBYP5H4_cjs.a(this,"initPromise",null);this.storagePath=utils.Filesystem.toUnixPath(e);}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doInitialize(),await this.initPromise,this.initialized=true;}}async doInitialize(){try{this.db=await this.openDatabaseAsync(),this.createTables(),this.db.pragma("foreign_keys = ON");}catch(e){throw new T(`Database initialization failed: ${e.message}`,e)}}async openDatabaseAsync(){return new Promise((e,t)=>{setImmediate(()=>{try{let n=new Ae__default.default(this.storagePath);n.pragma("journal_mode = WAL"),n.pragma("synchronous = NORMAL"),n.pragma("cache_size = -64000"),n.pragma("temp_store = MEMORY"),e(n);}catch(n){t(n);}});})}createTables(){if(!this.db)throw new T("Database not initialized");let e=this.db;e.exec(`
5
2
  CREATE TABLE IF NOT EXISTS memory_facts (
6
3
  id TEXT PRIMARY KEY,
7
4
  agent_id TEXT NOT NULL,
@@ -15,23 +12,23 @@ globstar while`,i,d,t,f,g),this.matchOne(i.slice(d),t.slice(f),e))return this.de
15
12
  tags TEXT,
16
13
  node_ids TEXT,
17
14
  file_path TEXT,
18
- created_at INTEGER NOT NULL,
19
- updated_at INTEGER NOT NULL,
15
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
16
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
20
17
  UNIQUE(session_id, msg_id)
21
18
  )
22
- `),t.exec("CREATE INDEX IF NOT EXISTS idx_memory_facts_agent_id ON memory_facts(agent_id)"),t.exec("CREATE INDEX IF NOT EXISTS idx_memory_facts_agent_category ON memory_facts(agent_id, category)"),t.exec("CREATE INDEX IF NOT EXISTS idx_memory_facts_agent_importance ON memory_facts(agent_id, importance DESC)"),t.exec("CREATE INDEX IF NOT EXISTS idx_memory_facts_created_at ON memory_facts(created_at)"),t.exec(`
19
+ `),e.exec("CREATE INDEX IF NOT EXISTS idx_memory_facts_agent_id ON memory_facts(agent_id)"),e.exec("CREATE INDEX IF NOT EXISTS idx_memory_facts_agent_category ON memory_facts(agent_id, category)"),e.exec("CREATE INDEX IF NOT EXISTS idx_memory_facts_agent_importance ON memory_facts(agent_id, importance DESC)"),e.exec("CREATE INDEX IF NOT EXISTS idx_memory_facts_created_at ON memory_facts(created_at)"),e.exec(`
23
20
  CREATE TABLE IF NOT EXISTS memory_vectors (
24
21
  fact_id TEXT PRIMARY KEY,
25
22
  embedding BLOB NOT NULL,
26
23
  FOREIGN KEY (fact_id) REFERENCES memory_facts(id) ON DELETE CASCADE
27
24
  )
28
- `),t.exec(`
25
+ `),e.exec(`
29
26
  CREATE TABLE IF NOT EXISTS embedding_cache (
30
27
  content_hash TEXT PRIMARY KEY,
31
28
  embedding BLOB NOT NULL,
32
- created_at INTEGER DEFAULT (unixepoch())
29
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
33
30
  )
34
- `),t.exec(`
31
+ `),e.exec(`
35
32
  CREATE VIRTUAL TABLE IF NOT EXISTS memory_facts_fts USING fts5(
36
33
  fact_id UNINDEXED,
37
34
  agent_id UNINDEXED,
@@ -39,7 +36,7 @@ globstar while`,i,d,t,f,g),this.matchOne(i.slice(d),t.slice(f),e))return this.de
39
36
  tags,
40
37
  tokenize='porter unicode61'
41
38
  )
42
- `),t.exec(`
39
+ `),e.exec(`
43
40
  CREATE TABLE IF NOT EXISTS short_term_sessions (
44
41
  id TEXT PRIMARY KEY,
45
42
  agent_id TEXT NOT NULL,
@@ -50,64 +47,58 @@ globstar while`,i,d,t,f,g),this.matchOne(i.slice(d),t.slice(f),e))return this.de
50
47
  content TEXT NOT NULL,
51
48
  model_id TEXT,
52
49
  provider_id TEXT,
53
- created_at INTEGER NOT NULL
50
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
54
51
  )
55
- `),t.exec("CREATE INDEX IF NOT EXISTS idx_short_term_agent_session ON short_term_sessions(agent_id, session_id)"),t.exec("CREATE INDEX IF NOT EXISTS idx_short_term_message_id ON short_term_sessions(message_id)"),t.exec("CREATE INDEX IF NOT EXISTS idx_short_term_created_at ON short_term_sessions(created_at)"),t.exec(`
52
+ `),e.exec("CREATE INDEX IF NOT EXISTS idx_short_term_agent_session ON short_term_sessions(agent_id, session_id)"),e.exec("CREATE INDEX IF NOT EXISTS idx_short_term_message_id ON short_term_sessions(message_id)"),e.exec("CREATE INDEX IF NOT EXISTS idx_short_term_created_at ON short_term_sessions(created_at)"),e.exec(`
56
53
  CREATE TABLE IF NOT EXISTS nodes (
57
54
  id INTEGER PRIMARY KEY AUTOINCREMENT,
58
55
  name TEXT NOT NULL,
59
56
  type TEXT NOT NULL,
60
57
  properties TEXT,
61
- createdAt INTEGER DEFAULT (unixepoch()),
62
- updatedAt INTEGER DEFAULT (unixepoch())
58
+ createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
59
+ updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP
63
60
  )
64
- `),t.exec("CREATE INDEX IF NOT EXISTS idx_nodes_name ON nodes(name)"),t.exec("CREATE INDEX IF NOT EXISTS idx_nodes_type ON nodes(type)"),t.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_nodes_name_type ON nodes(name, type)"),t.exec(`
61
+ `),e.exec("CREATE INDEX IF NOT EXISTS idx_nodes_name ON nodes(name)"),e.exec("CREATE INDEX IF NOT EXISTS idx_nodes_type ON nodes(type)"),e.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_nodes_name_type ON nodes(name, type)"),e.exec(`
65
62
  CREATE TABLE IF NOT EXISTS edges (
66
63
  id INTEGER PRIMARY KEY AUTOINCREMENT,
67
64
  source INTEGER NOT NULL,
68
65
  target INTEGER NOT NULL,
69
66
  relation TEXT NOT NULL,
70
67
  properties TEXT,
71
- createdAt INTEGER DEFAULT (unixepoch()),
68
+ createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
72
69
  FOREIGN KEY (source) REFERENCES nodes(id) ON DELETE CASCADE,
73
70
  FOREIGN KEY (target) REFERENCES nodes(id) ON DELETE CASCADE
74
71
  )
75
- `),t.exec("CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source)"),t.exec("CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target)"),t.exec("CREATE INDEX IF NOT EXISTS idx_edges_relation ON edges(relation)"),t.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_edges_unique ON edges(source, target, relation)"),t.exec(`
72
+ `),e.exec("CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source)"),e.exec("CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target)"),e.exec("CREATE INDEX IF NOT EXISTS idx_edges_relation ON edges(relation)"),e.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_edges_unique ON edges(source, target, relation)"),e.exec(`
76
73
  CREATE TABLE IF NOT EXISTS meta (
77
74
  key TEXT PRIMARY KEY,
78
75
  value TEXT
79
76
  )
80
- `);}query(t,e){if(!this.db)throw new Q("Database not initialized. Call initialize() first.");try{let s=this.db.prepare(t);return e?s.all(...e):s.all()}catch(s){throw new Q(`Query failed: ${s.message}`,s)}}run(t,e){if(!this.db)throw new Q("Database not initialized. Call initialize() first.");try{let s=this.db.prepare(t),r=e?s.run(...e):s.run();return {lastID:Number(r.lastInsertRowid),changes:r.changes}}catch(s){throw new Q(`Write failed: ${s.message}`,s)}}transaction(t){if(!this.db)throw new Q("Database not initialized. Call initialize() first.");return this.db.transaction(t)()}prepare(t){if(!this.db)throw new Q("Database not initialized. Call initialize() first.");return this.db.prepare(t)}exec(t){if(!this.db)throw new Q("Database not initialized. Call initialize() first.");this.db.exec(t);}getDb(){if(!this.db)throw new Q("Database not initialized. Call initialize() first.");return this.db}getPath(){return this.storagePath}close(){this.db&&(this.db.close(),this.db=null,this.initialized=false);}healthCheck(){try{return this.db?(this.db.prepare("SELECT 1").get(),!0):!1}catch{return false}}};var lh=["id","agentId","category","importance"],Bi="---",_t=class i{static generateId(){let t=Date.now(),e=crypto.randomBytes(3).toString("hex");return `mem_${t}_${e}`}static serialize(t){let e={id:t.id,agentId:t.agentId,category:t.category,importance:t.importance,createdAt:utils.formatLocalISO(t.createdAt),updatedAt:utils.formatLocalISO(t.updatedAt),source:t.source};t.sessionId&&(e.sessionId=t.sessionId),t.msgId&&(e.msgId=t.msgId),t.parentMsgId&&(e.parentMsgId=t.parentMsgId),t.tags&&t.tags.length>0&&(e.tags=t.tags),t.nodeIds&&t.nodeIds.length>0&&(e.nodeIds=t.nodeIds),t.filePath&&(e.filePath=t.filePath);let s=Object.entries(e).map(([r,o])=>Array.isArray(o)?`${r}: [${o.join(", ")}]`:`${r}: ${o}`);return [Bi,...s,Bi,"",t.content.trim(),""].join(`
81
- `)}static serializeFile(t){return t.map(e=>i.serialize(e)).join(`
82
- `)}static parse(t){let e=[],s=t.split(`
83
- `),r=0;for(;r<s.length;){if(s[r]?.trim()!==Bi){r++;continue}let o=r+1,a=-1;for(let g=o;g<s.length;g++)if(s[g]?.trim()===Bi){a=g;break}if(a===-1){r++;continue}let l=s.slice(o,a),h=i.parseFrontmatter(l);i.validateFrontmatter(h);let c=a+1,u=s.length;for(let g=c;g<s.length;g++)if(s[g]?.trim()===Bi){u=g;break}let d=s.slice(c,u).join(`
84
- `).trim(),f={id:String(h.id),agentId:String(h.agentId),category:h.category,importance:Number(h.importance),source:h.source??"session_self_write",content:d,createdAt:h.createdAt?new Date(String(h.createdAt)).getTime():Date.now(),updatedAt:h.updatedAt?new Date(String(h.updatedAt)).getTime():Date.now()};h.sessionId&&(f.sessionId=String(h.sessionId)),h.msgId&&(f.msgId=String(h.msgId)),h.parentMsgId&&(f.parentMsgId=String(h.parentMsgId)),h.filePath&&(f.filePath=String(h.filePath)),h.tags&&(f.tags=i.parseArrayField(h.tags)),h.nodeIds&&(f.nodeIds=i.parseArrayField(h.nodeIds).map(Number).filter(g=>!Number.isNaN(g))),e.push(f),r=u;}return e}static parseFrontmatter(t){let e={};for(let s of t){let r=s.indexOf(":");if(r===-1)continue;let o=s.slice(0,r).trim(),a=s.slice(r+1).trim();if(o)if(a.startsWith("[")&&a.endsWith("]")){let l=a.slice(1,-1).trim();e[o]=l?l.split(",").map(h=>h.trim()).filter(Boolean):[];}else e[o]=a;}return e}static validateFrontmatter(t){for(let r of lh)if(t[r]===void 0||t[r]==="")throw new pt(`Missing required field in memory frontmatter: ${r}`);let e=t.category;if(!Ts.includes(e))throw new pt(`Invalid category: "${e}". Valid values: ${Ts.join(", ")}`);let s=Number(t.importance);if(Number.isNaN(s)||s<1||s>10)throw new pt(`Invalid importance: "${t.importance}". Must be an integer between 1 and 10.`)}static parseArrayField(t){if(Array.isArray(t))return t.map(String);if(typeof t=="string"){let e=t.trim();if(e.startsWith("[")&&e.endsWith("]")){let s=e.slice(1,-1).trim();return s?s.split(",").map(r=>r.trim()).filter(Boolean):[]}return e?[e]:[]}return []}};var Xn="MEMORY.md",Yn="active",dh="archive",At=class i{static getMemoryMdPath(t){return Ee__default.default.join(t,Xn)}static getActiveFilePath(t,e,s){let o=(s??new Date).toISOString().slice(0,10);return Ee__default.default.join(t,Yn,e,`${o}.md`)}static getArchiveFilePath(t,e,s,r){let o=new Date(s),a=`${o.getFullYear()}-${String(o.getMonth()+1).padStart(2,"0")}`;return Ee__default.default.join(t,dh,a,e,r)}static async readMemoryMd(t){let e=i.getMemoryMdPath(t);try{return await se__default.default.readFile(e,"utf-8")}catch(s){if(s.code==="ENOENT")return null;throw new Mt(`Failed to read MEMORY.md: ${s.message}`,s)}}static async write(t,e){let s=i.getActiveFilePath(t,e.category),r=utils.Filesystem.toUnixPath(Ee__default.default.relative(t,s));if(Ee__default.default.basename(s)===Xn)throw new ii("Writing to MEMORY.md is not allowed. MEMORY.md is read-only.");try{await se__default.default.mkdir(Ee__default.default.dirname(s),{recursive:!0});let o=_t.serialize(e),a="";try{a=await se__default.default.readFile(s,"utf-8");}catch{}let l=a.length>0&&!a.endsWith(`
77
+ `);}query(e,t){if(!this.db)throw new T("Database not initialized. Call initialize() first.");try{let n=this.db.prepare(e);return t?n.all(...t):n.all()}catch(n){throw new T(`Query failed: ${n.message}`,n)}}run(e,t){if(!this.db)throw new T("Database not initialized. Call initialize() first.");try{let n=this.db.prepare(e),r=t?n.run(...t):n.run();return {lastID:Number(r.lastInsertRowid),changes:r.changes}}catch(n){throw new T(`Write failed: ${n.message}`,n)}}transaction(e){if(!this.db)throw new T("Database not initialized. Call initialize() first.");return this.db.transaction(e)()}prepare(e){if(!this.db)throw new T("Database not initialized. Call initialize() first.");return this.db.prepare(e)}exec(e){if(!this.db)throw new T("Database not initialized. Call initialize() first.");this.db.exec(e);}getDb(){if(!this.db)throw new T("Database not initialized. Call initialize() first.");return this.db}getPath(){return this.storagePath}close(){this.db&&(this.db.close(),this.db=null,this.initialized=false);}healthCheck(){try{return this.db?(this.db.prepare("SELECT 1").get(),!0):!1}catch{return false}}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,t){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,t);}};var Le=["id","agentId","category","importance"],Y="---",S=class g{static generateId(){let e=Date.now(),t=crypto.randomBytes(3).toString("hex");return `mem_${e}_${t}`}static serialize(e){let t=new Date(e.createdAt),n=e.updatedAt?new Date(e.updatedAt):new Date,r={id:e.id,agentId:e.agentId,category:e.category,importance:e.importance,createdAt:utils.formatLocalISO(t),updatedAt:utils.formatLocalISO(n),source:e.source};e.sessionId&&(r.sessionId=e.sessionId),e.msgId&&(r.msgId=e.msgId),e.parentMsgId&&(r.parentMsgId=e.parentMsgId),e.tags&&e.tags.length>0&&(r.tags=e.tags),e.nodeIds&&e.nodeIds.length>0&&(r.nodeIds=e.nodeIds),e.filePath&&(r.filePath=e.filePath);let i=Object.entries(r).map(([s,d])=>Array.isArray(d)?`${s}: [${d.join(", ")}]`:`${s}: ${d}`);return [Y,...i,Y,"",e.content.trim(),""].join(`
78
+ `)}static serializeFile(e){return e.map(t=>g.serialize(t)).join(`
79
+ `)}static parse(e){let t=[],n=e.split(`
80
+ `),r=0;for(;r<n.length;){if(n[r]?.trim()!==Y){r++;continue}let i=r+1,s=-1;for(let u=i;u<n.length;u++)if(n[u]?.trim()===Y){s=u;break}if(s===-1){r++;continue}let d=n.slice(i,s),o=g.parseFrontmatter(d);g.validateFrontmatter(o);let m=s+1,a=n.length;for(let u=m;u<n.length;u++)if(n[u]?.trim()===Y){a=u;break}let c=n.slice(m,a).join(`
81
+ `).trim(),l={id:String(o.id),agentId:String(o.agentId),category:o.category,importance:Number(o.importance),source:o.source??"session_self_write",content:c,createdAt:o.createdAt?new Date(String(o.createdAt)).toISOString():new Date().toISOString(),updatedAt:o.updatedAt?new Date(String(o.updatedAt)).toISOString():new Date().toISOString()};o.sessionId&&(l.sessionId=String(o.sessionId)),o.msgId&&(l.msgId=String(o.msgId)),o.parentMsgId&&(l.parentMsgId=String(o.parentMsgId)),o.filePath&&(l.filePath=String(o.filePath)),o.tags&&(l.tags=g.parseArrayField(o.tags)),o.nodeIds&&(l.nodeIds=g.parseArrayField(o.nodeIds).map(Number).filter(u=>!Number.isNaN(u))),t.push(l),r=a;}return t}static parseFrontmatter(e){let t={};for(let n of e){let r=n.indexOf(":");if(r===-1)continue;let i=n.slice(0,r).trim(),s=n.slice(r+1).trim();if(i)if(s.startsWith("[")&&s.endsWith("]")){let d=s.slice(1,-1).trim();t[i]=d?d.split(",").map(o=>o.trim()).filter(Boolean):[];}else t[i]=s;}return t}static validateFrontmatter(e){for(let r of Le)if(e[r]===void 0||e[r]==="")throw new M(`Missing required field in memory frontmatter: ${r}`);let t=e.category;if(!te.includes(t))throw new M(`Invalid category: "${t}". Valid values: ${te.join(", ")}`);let n=Number(e.importance);if(Number.isNaN(n)||n<1||n>10)throw new M(`Invalid importance: "${e.importance}". Must be an integer between 1 and 10.`)}static parseArrayField(e){if(Array.isArray(e))return e.map(String);if(typeof e=="string"){let t=e.trim();if(t.startsWith("[")&&t.endsWith("]")){let n=t.slice(1,-1).trim();return n?n.split(",").map(r=>r.trim()).filter(Boolean):[]}return t?[t]:[]}return []}};var le="MEMORY.md",ue="active",De="archive",O=class g{static getMemoryMdPath(e){return ___default.default.join(e,le)}static getActiveFilePath(e,t,n){let r=n??new Date,i=r.getFullYear(),s=String(r.getMonth()+1).padStart(2,"0"),d=String(r.getDate()).padStart(2,"0"),o=`${i}-${s}-${d}`;return ___default.default.join(e,ue,t,`${o}.md`)}static getArchiveFilePath(e,t,n,r){let i=new Date(n),s=`${i.getFullYear()}-${String(i.getMonth()+1).padStart(2,"0")}`;return ___default.default.join(e,De,s,t,r)}static async readMemoryMd(e){let t=g.getMemoryMdPath(e);try{return await N__default.default.readFile(t,"utf-8")}catch(n){if(n.code==="ENOENT")return null;throw new L(`Failed to read MEMORY.md: ${n.message}`,n)}}static async write(e,t){let n=g.getActiveFilePath(e,t.category);utils.Filesystem.toUnixPath(___default.default.relative(e,n));if(___default.default.basename(n)===le)throw new X("Writing to MEMORY.md is not allowed. MEMORY.md is read-only.");try{await N__default.default.mkdir(___default.default.dirname(n),{recursive:!0});let i=S.serialize(t),s="";try{s=await N__default.default.readFile(n,"utf-8");}catch{}let d=s.length>0&&!s.endsWith(`
85
82
  `)?`
86
- `:"";return await se__default.default.writeFile(s,`${a}${l}${o}`,"utf-8"),r}catch(o){throw o instanceof ii?o:new Mt(`Failed to write memory to ${r}: ${o.message}`,o)}}static async read(t){try{let e=await se__default.default.readFile(t,"utf-8");return _t.parse(e)}catch(e){if(e.code==="ENOENT")return [];throw new Mt(`Failed to read memory file ${t}: ${e.message}`,e)}}static async delete(t,e){try{let s=await i.read(t),r=s.filter(o=>o.id!==e);if(r.length===s.length)return;r.length===0?await se__default.default.unlink(t).catch(()=>{}):await se__default.default.writeFile(t,_t.serializeFile(r),"utf-8");}catch(s){throw s instanceof Mt?s:new Mt(`Failed to delete memory ${e} from ${t}: ${s.message}`,s)}}static async update(t,e,s){try{let r=await i.read(t),o=r.findIndex(l=>l.id===e);if(o===-1)return;let a={...r[o],...s,updatedAt:Date.now()};r[o]=a,await se__default.default.writeFile(t,_t.serializeFile(r),"utf-8");}catch(r){throw r instanceof Mt?r:new Mt(`Failed to update memory ${e} in ${t}: ${r.message}`,r)}}static async listActiveFiles(t){let e=Ee__default.default.join(t,Yn),s=[];try{await i.scanDir(e,s);}catch(r){if(r.code==="ENOENT")return [];throw new Mt(`Failed to list active memory files: ${r.message}`,r)}return s}static async scanDir(t,e){let s=await se__default.default.readdir(t,{withFileTypes:true});for(let r of s){let o=Ee__default.default.join(t,r.name);r.isDirectory()?await i.scanDir(o,e):r.isFile()&&r.name.endsWith(".md")&&e.push(o);}}};var Gi=class{constructor(t,e){p(this,"db");p(this,"config");this.db=t,this.config=e;}async archive(){let e=(this.config.archiveDays??30)*864e5,s=Date.now(),r=[],o=await At.listActiveFiles(this.config.workspaceDir);for(let a of o){let l=await At.read(a);if(l.length===0)continue;let h=l[0]?.createdAt??s;if(s-h<=e)continue;let c=l[0]?.category;if(!c)continue;let u=Ee__default.default.basename(a),d=At.getArchiveFilePath(this.config.workspaceDir,c,h,u);await ma.promises.mkdir(Ee__default.default.dirname(d),{recursive:true}),await ma.promises.rename(a,d);let f=utils.Filesystem.toUnixPath(Ee__default.default.relative(this.config.workspaceDir,d)),g=utils.Filesystem.toUnixPath(Ee__default.default.relative(this.config.workspaceDir,a));this.db.prepare("UPDATE memory_facts SET file_path = ? WHERE file_path = ?").run(f,g),r.push({source:a,target:d,timestamp:s});}return {archivedCount:r.length,records:r}}};var Xi=class{constructor(t){p(this,"db");this.db=t;}async upsertNode(t,e,s){let r=Date.now(),o=this.db.prepare("SELECT id FROM nodes WHERE name = ? AND type = ?").get(t,e);if(o)return this.db.prepare("UPDATE nodes SET properties = ?, updatedAt = ? WHERE id = ?").run(JSON.stringify(s??{}),r,o.id),o.id;let a=this.db.prepare("INSERT INTO nodes (name, type, properties, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?)").run(t,e,JSON.stringify(s??{}),r,r);return Number(a.lastInsertRowid)}async deleteNode(t){this.db.prepare("DELETE FROM nodes WHERE id = ?").run(t);}async upsertEdge(t,e,s,r){let o=this.db.prepare("INSERT INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)").run(t,e,s,JSON.stringify(r??{}),Date.now());return Number(o.lastInsertRowid)}async queryNodes(t={}){let e="SELECT id, name, type, properties, createdAt, updatedAt FROM nodes",s=[],r=[];return t.ids&&t.ids.length>0&&(r.push(`id IN (${t.ids.map(()=>"?").join(",")})`),s.push(...t.ids)),t.name&&(r.push("name LIKE ?"),s.push(`%${t.name}%`)),t.type&&(r.push("type = ?"),s.push(t.type)),r.length>0&&(e+=` WHERE ${r.join(" AND ")}`),e+=" ORDER BY id",t.limit&&(e+=" LIMIT ?",s.push(t.limit)),this.db.prepare(e).all(...s).map(a=>({id:a.id,name:a.name,type:a.type,properties:a.properties?JSON.parse(a.properties):void 0,createdAt:a.createdAt,updatedAt:a.updatedAt}))}async queryEdges(t={}){let e="SELECT id, source, target, relation, properties, createdAt FROM edges",s=[],r=[];return t.ids&&t.ids.length>0&&(r.push(`id IN (${t.ids.map(()=>"?").join(",")})`),s.push(...t.ids)),t.source!==void 0&&(r.push("source = ?"),s.push(t.source)),t.target!==void 0&&(r.push("target = ?"),s.push(t.target)),t.sourceOrTarget&&t.sourceOrTarget.length>0&&(r.push(`(source IN (${t.sourceOrTarget.map(()=>"?").join(",")}) OR target IN (${t.sourceOrTarget.map(()=>"?").join(",")}))`),s.push(...t.sourceOrTarget,...t.sourceOrTarget)),t.relation&&(r.push("relation = ?"),s.push(t.relation)),r.length>0&&(e+=` WHERE ${r.join(" AND ")}`),e+=" ORDER BY id",t.limit&&(e+=" LIMIT ?",s.push(t.limit)),this.db.prepare(e).all(...s).map(a=>({id:a.id,source:a.source,target:a.target,relation:a.relation,properties:a.properties?JSON.parse(a.properties):void 0,createdAt:a.createdAt}))}async queryNeighbors(t,e=1){let s=new Set,r=[{id:t,level:0}],o=[];for(;r.length>0;){let a=r.shift();if(!a)break;if(s.has(a.id)||a.level>e)continue;s.add(a.id);let l=(await this.queryNodes({ids:[a.id],limit:1}))[0];if(!l)continue;let c=(await this.queryEdges({})).filter(u=>u.source===a.id||u.target===a.id);if(o.push({...l,edges:c}),a.level<e)for(let u of c){let d=u.source===a.id?u.target:u.source;s.has(d)||r.push({id:d,level:a.level+1});}}return o}};var Se;(u=>{let i=null;function t(d){e()||(i={models:d.models,options:d.options??{}});}u.init=t;function e(){return i!==null}u.isInitialized=e;function s(){return i?{embedding:!!i.models.embeddingLlm,graph:!!i.models.graphLlm}:{embedding:false,graph:false}}u.capabilities=s;async function r(d){let g=l().models.embeddingLlm;if(!g)throw new Error("embeddingLlm model is not configured.");try{let b=await ai$1.embed({model:g,value:d});return new Float32Array(b.embedding)}catch(b){let E=g.doEmbed;if(typeof E!="function")throw new Error("embeddingLlm model does not support embedding generation.",{cause:b});let S=(await E({values:[d]}))?.embeddings?.[0];if(!S||!Array.isArray(S))throw new Error("embeddingLlm model returned invalid embedding result.",{cause:b});return new Float32Array(S)}}u.embedText=r;async function o(d){let g=l().models.embeddingLlm;if(!g)throw new Error("embeddingLlm model is not configured.");try{return (await ai$1.embedMany({model:g,values:d})).embeddings.map(E=>new Float32Array(E))}catch{return ((await g.doEmbed?.({values:d}))?.embeddings??[]).map(E=>new Float32Array(E))}}u.embedTexts=o;async function a(d,f){let g=l(),b=g.models.graphLlm;if(!b)throw new Error("llm model is not configured.");try{return ai$1.streamText({model:b,prompt:d,maxOutputTokens:f?.maxOutputTokens??g.options.graph?.maxOutputTokens,temperature:f?.temperature??g.options.graph?.temperature}).text}catch{return (await b.doGenerate?.({prompt:[{role:"user",content:[{type:"text",text:d}]}],maxOutputTokens:f?.maxOutputTokens??g.options.graph?.maxOutputTokens}))?.content?.find(T=>T.type==="text")?.text??""}}u.generate=a;let l=()=>{if(!i)throw new Error("Llm is not initialized. Please call Llm.init() first.");return i};u.embed=r,u.embedMany=o;})(Se||(Se={}));var ws=class{constructor(t,e){p(this,"db");p(this,"config");p(this,"embeddingModel");this.db=t,this.config=e,this.embeddingModel=e.embeddingLlm,this.embeddingModel&&Se.init({models:{embeddingLlm:this.embeddingModel,graphLlm:e.graphLlm}});}async search(t,e){let s=e?.maxResults??this.config.search.maxResults,r=e?.minScore??this.config.search.minScore,o=e?.vectorWeight??this.config.search.hybrid.vectorWeight,a=e?.textWeight??this.config.search.hybrid.textWeight,l=await this.hybridSearch(t,s*2,r,o,a,e);return l.length===0?[]:l.slice(0,s)}async hybridSearch(t,e,s,r,o,a){let h=!!this.embeddingModel?await this.embed(t):null,c=["mf.agent_id = ?"],u=[a?.agentId];a?.category&&(c.push("mf.category = ?"),u.push(a.category)),a?.minImportance!==void 0&&(c.push("mf.importance >= ?"),u.push(a.minImportance)),a?.source&&(c.push("mf.source = ?"),u.push(a.source)),a?.fromTime!==void 0&&(c.push("mf.created_at >= ?"),u.push(a.fromTime)),a?.toTime!==void 0&&(c.push("mf.created_at <= ?"),u.push(a.toTime));let d=c.join(" AND "),[f,g]=await Promise.all([h?this.vectorSearch(h,d,u,e,s,a?.candidateFactIds):Promise.resolve([]),this.ftsSearch(t,d,u,e,s)]),b=h?r:0,E=h?o:1;return this.mergeResults(f,g,b,E,d,u)}async vectorSearch(t,e,s,r,o,a){if(!this.embeddingModel)return [];try{let l;if(a&&a.length>0){let c=a.map(()=>"?").join(",");l=this.db.prepare(`
83
+ `:"";return await N__default.default.writeFile(n,`${s}${d}${i}`,"utf-8"),utils.Filesystem.normalize(n)}catch(i){throw i instanceof X?i:new L(`Failed to write memory to ${n}: ${i.message}`,i)}}static async read(e){try{let t=await N__default.default.readFile(e,"utf-8");return S.parse(t)}catch(t){if(t.code==="ENOENT")return [];throw new L(`Failed to read memory file ${e}: ${t.message}`,t)}}static async delete(e,t){try{let n=await g.read(e),r=n.filter(i=>i.id!==t);if(r.length===n.length)return;r.length===0?await N__default.default.unlink(e).catch(()=>{}):await N__default.default.writeFile(e,S.serializeFile(r),"utf-8");}catch(n){throw n instanceof L?n:new L(`Failed to delete memory ${t} from ${e}: ${n.message}`,n)}}static async update(e,t,n){try{let r=await g.read(e),i=r.findIndex(d=>d.id===t);if(i===-1)return;let s={...r[i],...n,updatedAt:new Date().toISOString()};r[i]=s,await N__default.default.writeFile(e,S.serializeFile(r),"utf-8");}catch(r){throw r instanceof L?r:new L(`Failed to update memory ${t} in ${e}: ${r.message}`,r)}}static async listActiveFiles(e){let t=___default.default.join(e,ue),n=[];try{await g.scanDir(t,n);}catch(r){if(r.code==="ENOENT")return [];throw new L(`Failed to list active memory files: ${r.message}`,r)}return n}static async scanDir(e,t){let n=await N__default.default.readdir(e,{withFileTypes:true});for(let r of n){let i=___default.default.join(e,r.name);r.isDirectory()?await g.scanDir(i,t):r.isFile()&&r.name.endsWith(".md")&&t.push(i);}}};var q=class{constructor(e,t){chunk5SBYP5H4_cjs.a(this,"db");chunk5SBYP5H4_cjs.a(this,"config");this.db=e,this.config=t;}async archive(){let t=(this.config.archiveDays??30)*864e5,n=Date.now(),r=[],i=await O.listActiveFiles(this.config.workspaceDir);for(let s of i){let d=await O.read(s);if(d.length===0)continue;let o=d[0]?.createdAt,m=o?new Date(o).getTime():n;if(n-m<=t)continue;let a=d[0]?.category;if(!a)continue;let c=___default.default.basename(s),l=O.getArchiveFilePath(this.config.workspaceDir,a,m,c);await fs.promises.mkdir(___default.default.dirname(l),{recursive:true}),await fs.promises.rename(s,l);let u=utils.Filesystem.toUnixPath(___default.default.relative(this.config.workspaceDir,l)),p=utils.Filesystem.toUnixPath(___default.default.relative(this.config.workspaceDir,s));this.db.prepare("UPDATE memory_facts SET file_path = ? WHERE file_path = ?").run(u,p),r.push({source:s,target:l,timestamp:n});}return {archivedCount:r.length,records:r}}};var K=chunk5SBYP5H4_cjs.c.create({service:"memory.graph-store"}),H=class{constructor(e){chunk5SBYP5H4_cjs.a(this,"db");this.db=e;}async upsertNode(e,t,n){let r=Date.now(),i=this.db.prepare("SELECT id FROM nodes WHERE name = ? AND type = ?").get(e,t);if(i)return this.db.prepare("UPDATE nodes SET properties = ?, updatedAt = ? WHERE id = ?").run(JSON.stringify(n??{}),r,i.id),i.id;let s=this.db.prepare("INSERT INTO nodes (name, type, properties, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?)").run(e,t,JSON.stringify(n??{}),r,r);return Number(s.lastInsertRowid)}async deleteNode(e){this.db.prepare("DELETE FROM nodes WHERE id = ?").run(e);}async upsertEdge(e,t,n,r){let i=this.db.prepare("INSERT INTO edges (source, target, relation, properties, createdAt) VALUES (?, ?, ?, ?, ?)").run(e,t,n,JSON.stringify(r??{}),Date.now());return Number(i.lastInsertRowid)}async queryNodes(e={}){let t="SELECT id, name, type, properties, createdAt, updatedAt FROM nodes",n=[],r=[];if(e.ids&&e.ids.length>0){let s=e.ids.map(d=>typeof d=="string"?parseInt(d,10):d).filter(d=>!Number.isNaN(d));r.push(`id IN (${s.map(()=>"?").join(", ")})`),n.push(...s);}e.name&&(r.push("name LIKE ?"),n.push(`%${e.name}%`)),e.type&&(r.push("type = ?"),n.push(e.type)),r.length>0&&(t+=` WHERE ${r.join(" AND ")}`),t+=" ORDER BY id",e.limit&&(t+=" LIMIT ?",n.push(e.limit)),K.debug("queryNodes",{sql:t,params:n,filter:e});let i=this.db.prepare(t).all(...n);return K.debug("queryNodes result",{count:i.length}),i.map(s=>({id:s.id,name:s.name,type:s.type,properties:s.properties?JSON.parse(s.properties):void 0,createdAt:s.createdAt,updatedAt:s.updatedAt}))}async queryEdges(e={}){let t="SELECT id, source, target, relation, properties, createdAt FROM edges",n=[],r=[];if(e.ids&&e.ids.length>0&&(r.push(`id IN (${e.ids.map(()=>"?").join(", ")})`),n.push(...e.ids)),e.source!==void 0&&(r.push("source = ?"),n.push(e.source)),e.target!==void 0&&(r.push("target = ?"),n.push(e.target)),e.sourceOrTarget&&e.sourceOrTarget.length>0){let m=e.sourceOrTarget.map(a=>typeof a=="string"?parseInt(a,10):a).filter(a=>!Number.isNaN(a));r.push(`(source IN (${m.map(()=>"?").join(", ")}) OR target IN (${m.map(()=>"?").join(", ")}))`),n.push(...m,...m);}e.relation&&(r.push("relation = ?"),n.push(e.relation)),r.length>0&&(t+=` WHERE ${r.join(" AND ")}`),t+=" ORDER BY id",e.limit&&(t+=" LIMIT ?",n.push(e.limit)),K.debug("queryEdges",{sql:t,params:n,filter:e});let i=this.db.prepare(t).all(...n);K.debug("queryEdges result",{count:i.length});let s=[...new Set(i.map(m=>m.target))],d=s.length>0?await this.queryNodes({ids:s,limit:s.length}):[],o=new Map(d.map(m=>[m.id,m]));return i.map(m=>{let a={id:m.id,source:m.source,target:m.target,relation:m.relation,properties:m.properties?JSON.parse(m.properties):void 0,createdAt:m.createdAt},c=o.get(m.target);return c&&(a.targetNode=c),a})}async queryNeighbors(e,t=1,n){let r=new Set,i=[{id:e,level:0}],s=[],d=n?.maxEdgesPerNode??50;for(;i.length>0;){let o=i.shift();if(!o)break;if(r.has(o.id)||o.level>t)continue;r.add(o.id);let a=(await this.queryNodes({ids:[o.id],limit:1}))[0];if(!a)continue;let c=await this.queryEdges({sourceOrTarget:[o.id],limit:d});if(s.push({...a,edges:c}),o.level<t)for(let l of c){let u=l.source===o.id?l.target:l.source;r.has(u)||i.push({id:u,level:o.level+1});}}return s}};var U;(a=>{let g=null;function e(c){t()||(g={models:c.models,options:c.options??{}});}a.init=e;function t(){return g!==null}a.isInitialized=t;function n(){return g?{embedding:!!g.models.embeddingLlm,graph:!!g.models.graphLlm}:{embedding:false,graph:false}}a.capabilities=n;async function r(c){let u=d().models.embeddingLlm;if(!u)throw new Error("embeddingLlm model is not configured.");try{let p=await ai.embed({model:u,value:c});return new Float32Array(p.embedding)}catch(p){let E=u.doEmbed;if(typeof E!="function")throw new Error("embeddingLlm model does not support embedding generation.",{cause:p});let A=(await E({values:[c]}))?.embeddings?.[0];if(!A||!Array.isArray(A))throw new Error("embeddingLlm model returned invalid embedding result.",{cause:p});return new Float32Array(A)}}a.embedText=r;async function i(c){let u=d().models.embeddingLlm;if(!u)throw new Error("embeddingLlm model is not configured.");try{return (await ai.embedMany({model:u,values:c})).embeddings.map(E=>new Float32Array(E))}catch{return ((await u.doEmbed?.({values:c}))?.embeddings??[]).map(E=>new Float32Array(E))}}a.embedTexts=i;async function s(c,l){let u=d(),p=u.models.graphLlm;if(!p)throw new Error("llm model is not configured.");try{return (await ai.streamText({model:p,prompt:c,maxOutputTokens:l?.maxOutputTokens??u.options.graph?.maxOutputTokens,temperature:l?.temperature??u.options.graph?.temperature})).text}catch{return (await p.doGenerate?.({prompt:[{role:"user",content:[{type:"text",text:c}]}],maxOutputTokens:l?.maxOutputTokens??u.options.graph?.maxOutputTokens}))?.content?.find(D=>D.type==="text")?.text??""}}a.generate=s;let d=()=>{if(!g)throw new Error("Llm is not initialized. Please call Llm.init() first.");return g};a.embed=r,a.embedMany=i;})(U||(U={}));var Q=class{constructor(e,t){chunk5SBYP5H4_cjs.a(this,"db");chunk5SBYP5H4_cjs.a(this,"config");chunk5SBYP5H4_cjs.a(this,"embeddingModel");this.db=e,this.config=t,this.embeddingModel=t.embeddingLlm,this.embeddingModel&&U.init({models:{embeddingLlm:this.embeddingModel,graphLlm:t.graphLlm}});}async search(e,t){if(!e.trim())return [];if(!t?.agentId)return [];let n=t.maxResults??this.config.search.maxResults,r=await this.hybridSearch(e,{...t,maxResults:n*2});return r.length===0?[]:r.slice(0,n)}async hybridSearch(e,t){let{maxResults:n=this.config.search.maxResults,minScore:r=this.config.search.minScore,vectorWeight:i=this.config.search.hybrid.vectorWeight,textWeight:s=this.config.search.hybrid.textWeight,enableEmbedding:d=true}=t??{},m=d&&!!this.embeddingModel?await this.embed(e):null,a=["mf.agent_id = ?"],c=[t?.agentId];t?.category&&(a.push("mf.category = ?"),c.push(t.category)),t?.minImportance!==void 0&&(a.push("mf.importance >= ?"),c.push(t.minImportance)),t?.source&&(a.push("mf.source = ?"),c.push(t.source)),t?.fromTime!==void 0&&(a.push("mf.created_at >= ?"),c.push(t.fromTime)),t?.toTime!==void 0&&(a.push("mf.created_at <= ?"),c.push(t.toTime));let l=a.join(" AND "),[u,p]=await Promise.all([m?this.vectorSearch(m,l,c,n,r,t?.candidateFactIds):Promise.resolve([]),this.ftsSearch(e,l,c,n,r)]),E=m?i:0,D=m?s:1;return this.mergeResults(u,p,E,D,l,c,r)}async vectorSearch(e,t,n,r,i,s){if(!this.embeddingModel)return [];try{let d;if(s&&s.length>0){let m=s.map(()=>"?").join(",");d=this.db.prepare(`
87
84
  SELECT mf.id, mv.embedding
88
85
  FROM memory_facts mf
89
86
  JOIN memory_vectors mv ON mf.id = mv.fact_id
90
- WHERE ${e} AND mf.id IN (${c})
91
- `).all(...s,...a);}else l=this.db.prepare(`
87
+ WHERE ${t} AND mf.id IN (${m})
88
+ `).all(...n,...s);}else d=this.db.prepare(`
92
89
  SELECT mf.id, mv.embedding
93
90
  FROM memory_facts mf
94
91
  JOIN memory_vectors mv ON mf.id = mv.fact_id
95
- WHERE ${e}
92
+ WHERE ${t}
96
93
  LIMIT ?
97
- `).all(...s,Math.max(r*100,1e3));let h=[];for(let c of l){let u=new Float32Array(c.embedding.buffer,c.embedding.byteOffset,c.embedding.length/4),d=this.cosineSimilarity(t,u);d>=o&&h.push({id:c.id,score:d});}return h.sort((c,u)=>u.score-c.score).slice(0,r)}catch(l){throw new si(`\u5411\u91CF\u641C\u7D22\u5931\u8D25: ${l instanceof Error?l.message:String(l)}`,l instanceof Error?l:void 0)}}async ftsSearch(t,e,s,r,o){let a=()=>this.db.prepare(`
98
- SELECT mf.id, 0.5 as score
99
- FROM memory_facts mf
100
- WHERE ${e} AND mf.content LIKE ?
101
- ORDER BY mf.importance DESC, mf.created_at DESC
102
- LIMIT ?
103
- `).all(...s,`%${t}%`,r);try{let h=(Bn(t).trim()||t.trim()).split(/\s+/).filter(d=>d.length>0).map(d=>`"${d.replace(/"/g,'""')}"`).join(" "),c=this.db.prepare(`
94
+ `).all(...n,Math.max(r*100,1e3));let o=[];for(let m of d){let a=new Float32Array(m.embedding.buffer,m.embedding.byteOffset,m.embedding.length/4),c=this.cosineSimilarity(e,a);o.push({id:m.id,score:c});}return o.sort((m,a)=>a.score-m.score).slice(0,r)}catch(d){throw new J(`\u5411\u91CF\u641C\u7D22\u5931\u8D25: ${d instanceof Error?d.message:String(d)}`,d instanceof Error?d:void 0)}}async ftsSearch(e,t,n,r,i){let s=()=>[];try{let o=(ce(e).trim()||e.trim()).split(/\s+/).filter(c=>c.length>0).map(c=>`"${c.replace(/"/g,'""')}"`).join(" "),m=this.db.prepare(`
104
95
  SELECT mf.id, bm25(memory_facts_fts) as score
105
96
  FROM memory_facts mf
106
97
  JOIN memory_facts_fts ON mf.id = memory_facts_fts.fact_id
107
- WHERE ${e} AND memory_facts_fts.content MATCH ?
98
+ WHERE ${t} AND memory_facts_fts.content MATCH ?
108
99
  ORDER BY score DESC
109
100
  LIMIT ?
110
- `).all(...s,h,r);if(c.length===0)return a();let u=Math.max(...c.map(d=>Math.abs(d.score)),1);return c.map(d=>({id:d.id,score:1-Math.abs(d.score)/u})).filter(d=>d.score>=o)}catch(l){if(l instanceof Error)return a();throw new si(`FTS \u641C\u7D22\u5931\u8D25: ${String(l)}`)}}async mergeResults(t,e,s,r,o,a){let l=s+r,h=s/l,c=r/l,u=new Map;for(let R of t)u.set(R.id,R.score*h);for(let R of e){let A=u.get(R.id)||0;u.set(R.id,A+R.score*c);}let d=Array.from(u.entries()).map(([R,A])=>({id:R,score:A})).sort((R,A)=>A.score-R.score).map(R=>R.id);if(d.length===0)return [];let f=d.map(()=>"?").join(","),g=this.db.prepare(`
101
+ `).all(...n,o,r);if(m.length===0)return s();let a=Math.max(...m.map(c=>Math.abs(c.score)),1);return m.map(c=>({id:c.id,score:1-Math.abs(c.score)/a})).filter(c=>c.score>=0)}catch{return s()}}async mergeResults(e,t,n,r,i,s,d){let o=n+r,m=n/o,a=r/o,c=new Map;for(let h of e)c.set(h.id,h.score*m);for(let h of t){let R=c.get(h.id)||0;c.set(h.id,R+h.score*a);}let l=Array.from(c.entries()).map(([h,R])=>({id:h,score:R})).sort((h,R)=>R.score-h.score).map(h=>h.id);if(l.length===0)return [];let u=l.map(()=>"?").join(","),p=this.db.prepare(`
111
102
  SELECT
112
103
  mf.id as memoryId,
113
104
  mf.category,
@@ -119,40 +110,43 @@ globstar while`,i,d,t,f,g),this.matchOne(i.slice(d),t.slice(f),e))return this.de
119
110
  mf.file_path as filePath,
120
111
  mf.node_ids
121
112
  FROM memory_facts mf
122
- WHERE mf.id IN (${f})
123
- `).all(...d),b=[],E=new Map;for(let R of g)if(R.node_ids)try{let A=JSON.parse(R.node_ids);E.set(R.memoryId,A),b.push(...A);}catch{}let T=Array.from(new Set(b)),S=new Map,x=new Map;if(T.length>0){let R=T.map(()=>"?").join(","),A=this.db.prepare(`SELECT id, name, type FROM nodes WHERE id IN (${R})`).all(...T);for(let N of A)S.set(N.id,N);let _=this.db.prepare(`SELECT e.source, e.target, e.relation, n.name as targetName, n.type as targetType
113
+ WHERE mf.id IN (${u})
114
+ `).all(...l),E=[],D=new Map;for(let h of p)if(h.node_ids)try{let R=JSON.parse(h.node_ids);D.set(h.memoryId,R),E.push(...R);}catch{}let A=Array.from(new Set(E)),se=new Map,$=new Map;if(A.length>0){let h=A.map(()=>"?").join(", "),R=this.db.prepare(`SELECT id, name, type FROM nodes WHERE id IN (${h})`).all(...A);for(let f of R)se.set(f.id,f);let V=this.db.prepare(`SELECT e.id, e.source, e.target, e.relation, e.properties, e.createdAt, n.name as targetName, n.type as targetType
124
115
  FROM edges e JOIN nodes n ON n.id = e.target
125
- WHERE e.source IN (${R})`).all(...T);for(let N of _){let F=x.get(N.source)??[];F.push({relation:N.relation,targetId:N.target,targetName:N.targetName,targetType:N.targetType}),x.set(N.source,F);}}return g.map(R=>{let A=E.get(R.memoryId)??[],_=A.length>0?A.flatMap(N=>{let F=S.get(N);return F?[{...F,edges:x.get(N)}]:[]}):void 0;return {memoryId:R.memoryId,category:R.category,importance:R.importance,agentId:R.agentId,snippet:R.snippet,score:u.get(R.memoryId)??0,createdAt:R.createdAt,source:R.source,filePath:R.filePath,nodes:(_?.length??0)>0?_:void 0}})}async embed(t){if(!this.embeddingModel)throw new ri("Embedding \u6A21\u578B\u672A\u914D\u7F6E\uFF0C\u65E0\u6CD5\u751F\u6210\u5411\u91CF");try{return await Se.embedText(t)}catch(e){throw new ri(`\u751F\u6210\u5411\u91CF\u5931\u8D25: ${e instanceof Error?e.message:String(e)}`,e instanceof Error?e:void 0)}}cosineSimilarity(t,e){if(t.length!==e.length||t.length===0)return 0;let s=0,r=0,o=0;for(let a=0;a<t.length;a++){let l=t[a],h=e[a];s+=l*h,r+=l*l,o+=h*h;}return s/(Math.sqrt(r)*Math.sqrt(o))}};var Z=be.create({service:"memory.system"}),yh=.7,wh=.3,bh=10;var Eh=new Set(types.GRAPH_ENTITY_TYPE_DEFINITIONS.map(i=>i.type)),Sh=new Set(types.GRAPH_RELATION_TYPE_DEFINITIONS.map(i=>i.type)),bs=class{constructor(t){p(this,"config");p(this,"db");p(this,"archiver",null);p(this,"searchEngine",null);p(this,"graphStore",null);p(this,"embeddingModel");p(this,"vectorDims");t.search?.hybrid;this.config={workspaceDir:t.workspaceDir,sessionsDir:t.sessionsDir??"",database:t.database,archiveDays:t.archiveDays??30,shortTermMaxRounds:t.shortTermMaxRounds??20,search:{maxResults:t.search?.maxResults??bh,minScore:t.search?.minScore??.1,hybrid:{enabled:t.search?.hybrid?.enabled??true,vectorWeight:t.search?.hybrid?.vectorWeight??yh,textWeight:t.search?.hybrid?.textWeight??wh}},embedding:t.embedding??{},tokenizer:t.tokenizer??{},indexer:t.indexer??{batchSize:50,ignorePatterns:[],incremental:false},logDir:t.logDir??"",graphLlm:t.graphLlm,embeddingLlm:t.graphLlm},this.embeddingModel=t.embeddingLlm,this.db=new Ui(t.database.path),this.embeddingModel&&Se.init({models:{embeddingLlm:this.embeddingModel,graphLlm:this.config.graphLlm}});}async initialize(){let t=this.config.logDir||Ee__default.default.join(this.config.workspaceDir,"logs");await se__default.default.mkdir(t,{recursive:true}),await be.init({logDir:t,print:process.argv.includes("--print-logs"),dev:false,level:"INFO"}),await se__default.default.mkdir(Ee__default.default.dirname(this.config.database.path),{recursive:true}),await se__default.default.mkdir(Ee__default.default.join(this.config.workspaceDir,"active"),{recursive:true}),await se__default.default.mkdir(Ee__default.default.join(this.config.workspaceDir,"archive"),{recursive:true}),await this.db.initialize(),this.archiver=new Gi(this.db.getDb(),this.config),this.graphStore=new Xi(this.db.getDb()),this.searchEngine=new ws(this.db.getDb(),this.config);let e=this.db.query("SELECT value FROM meta WHERE key = ?",["vectorDims"]);e[0]&&(this.vectorDims=parseInt(e[0].value,10)),await Un({dictPath:this.config.tokenizer.dictPath}).catch(s=>{Z.warn("Tokenizer initialization failed, using fallback",{error:String(s)});}),Z.info("Memory system initialized",{workspaceDir:this.config.workspaceDir,dbPath:this.config.database.path});}async remember(t){if(!t.agentId?.trim())throw new pt("agentId is required for remember operation");let e=Date.now(),s=_t.generateId(),r={...t,id:s,source:"session_self_write",createdAt:e,updatedAt:e},o=await At.write(this.config.workspaceDir,r);r.filePath=o;let a=[];if(this.config.llm)try{let h=await this.extractEntitiesWithLlm(r.content);a=this.storeEntitiesAndRelations(h.entities,h.relations).nodeIds;}catch(h){Z.warn("Graph extraction failed, continuing without nodes",{error:String(h)});}else {let h=this.extractEntities(r.content);a=this.storeEntitiesAndRelations(h.entities,h.relations).nodeIds;}return r.nodeIds=a,this.db.run(`INSERT OR IGNORE INTO memory_facts
126
- (id, agent_id, session_id, msg_id, parent_msg_id, content, category, importance,
127
- source, tags, node_ids, file_path, created_at, updated_at)
128
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[r.id,r.agentId,r.sessionId??null,r.msgId??null,r.parentMsgId??null,r.content,r.category,r.importance,r.source,r.tags?JSON.stringify(r.tags):null,r.nodeIds?JSON.stringify(r.nodeIds):null,r.filePath?utils.Filesystem.toUnixPath(r.filePath):null,r.createdAt,r.updatedAt]),await this.embedAndStore(r.id,r.content),this.writeFts(r.id,r.agentId,r.content,r.tags),Z.info("Memory stored",{id:r.id,category:r.category,agentId:r.agentId,nodeCount:a.length}),r}async query(t,e){if(!e?.agentId?.trim())throw new pt("agentId is required for query operation");return this.getSearchEngine().search(t,e)}async forget(t,e){if(!t?.trim())throw new pt("agentId is required for forget operation");let s=this.db.query("SELECT file_path FROM memory_facts WHERE id = ? AND agent_id = ?",[e,t]);if(s.length===0)throw new ei(e);let r=s[0]?.file_path;if(this.db.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[e,t]),r){let o=Ee__default.default.isAbsolute(r)?r:Ee__default.default.join(this.config.workspaceDir,r);await At.delete(o,e).catch(a=>{Z.warn("Failed to delete memory from file",{memoryId:e,filePath:r,error:String(a)});});}Z.info("Memory deleted",{memoryId:e,agentId:t});}async update(t,e,s){if(!t?.trim())throw new pt("agentId is required for update operation");let r=this.db.query("SELECT * FROM memory_facts WHERE id = ? AND agent_id = ?",[e,t]);if(r.length===0)throw new ei(e);let o=r[0],a=Date.now(),l=s.content??o.content,h=s.importance??o.importance,c=s.tags??(o.tags?JSON.parse(o.tags):void 0);if(this.db.run(`UPDATE memory_facts SET content = ?, importance = ?, tags = ?, updated_at = ?
129
- WHERE id = ? AND agent_id = ?`,[l,h,c?JSON.stringify(c):null,a,e,t]),s.content&&(await this.embedAndStore(e,l),this.writeFts(e,t,l,c)),o.file_path){let d=Ee__default.default.isAbsolute(o.file_path)?o.file_path:Ee__default.default.join(this.config.workspaceDir,o.file_path);await At.update(d,e,s).catch(f=>{Z.warn("Failed to update memory in file",{memoryId:e,error:String(f)});});}let u={id:o.id,agentId:o.agent_id,sessionId:o.session_id??void 0,msgId:o.msg_id??void 0,parentMsgId:o.parent_msg_id??void 0,content:l,category:o.category,importance:h,source:o.source,tags:c,nodeIds:o.node_ids?JSON.parse(o.node_ids):void 0,filePath:o.file_path??void 0,createdAt:o.created_at,updatedAt:a};return Z.info("Memory updated",{memoryId:e,agentId:t}),u}async extractFromSession(t,e,s){if(!t?.trim())throw new pt("agentId is required for extractFromSession operation");let r=Date.now(),o=[];this.db.transaction(()=>{for(let a of s){if(!a.content?.trim())continue;let l=_t.generateId();this.db.run(`INSERT OR IGNORE INTO memory_facts
116
+ WHERE e.source IN (${h})`).all(...A);for(let f of V){let z=$.get(f.source)??[];z.push({id:f.id,source:f.source,target:f.target,relation:f.relation,properties:f.properties?JSON.parse(f.properties):void 0,createdAt:f.createdAt,targetNode:{id:f.target,name:f.targetName,type:f.targetType,createdAt:f.createdAt,updatedAt:f.createdAt}}),$.set(f.source,z);}let ee=this.db.prepare(`SELECT e.id, e.source, e.target, e.relation, e.properties, e.createdAt, n.name as sourceName, n.type as sourceType
117
+ FROM edges e JOIN nodes n ON n.id = e.source
118
+ WHERE e.target IN (${h})`).all(...A);for(let f of ee){let z=$.get(f.target)??[];z.push({id:f.id,source:f.source,target:f.target,relation:f.relation,properties:f.properties?JSON.parse(f.properties):void 0,createdAt:f.createdAt,targetNode:{id:f.source,name:f.sourceName,type:f.sourceType,createdAt:f.createdAt,updatedAt:f.createdAt}}),$.set(f.target,z);}}return p.map(h=>{let R=D.get(h.memoryId)??[],V=R.length>0?R.flatMap(oe=>{let ae=se.get(oe);return ae?[{...ae,edges:$.get(oe)}]:[]}):void 0,ee=c.get(h.memoryId)??0,f=new Date(h.createdAt),z=(Date.now()-f.getTime())/864e5,ye=Math.exp(-0.05*z),Ee=(h.importance-1)/9,be=.4*ee+.3*ye+.3*Ee;return {memoryId:h.memoryId,category:h.category,importance:h.importance,agentId:h.agentId,snippet:h.snippet,score:be,createdAt:h.createdAt,source:h.source,filePath:h.filePath,nodes:(V?.length??0)>0?V:void 0}}).filter(h=>h.score>=d).sort((h,R)=>R.score-h.score)}async embed(e){if(!this.embeddingModel)throw new B("Embedding \u6A21\u578B\u672A\u914D\u7F6E\uFF0C\u65E0\u6CD5\u751F\u6210\u5411\u91CF");try{return await U.embedText(e)}catch(t){throw new B(`\u751F\u6210\u5411\u91CF\u5931\u8D25: ${t instanceof Error?t.message:String(t)}`,t instanceof Error?t:void 0)}}cosineSimilarity(e,t){if(e.length!==t.length||e.length===0)return 0;let n=0,r=0,i=0;for(let s=0;s<e.length;s++){let d=e[s],o=t[s];n+=d*o,r+=d*d,i+=o*o;}return n/(Math.sqrt(r)*Math.sqrt(i))}};var y=chunk5SBYP5H4_cjs.c.create({service:"memory.system"}),Ce=.7,ke=.3,Ue=10;var ze=new Set(types.GRAPH_ENTITY_TYPE_DEFINITIONS.map(g=>g.type)),$e=new Set(types.GRAPH_RELATION_TYPE_DEFINITIONS.map(g=>g.type)),Z=class{constructor(e){chunk5SBYP5H4_cjs.a(this,"config");chunk5SBYP5H4_cjs.a(this,"db");chunk5SBYP5H4_cjs.a(this,"archiver",null);chunk5SBYP5H4_cjs.a(this,"searchEngine",null);chunk5SBYP5H4_cjs.a(this,"graphStore",null);chunk5SBYP5H4_cjs.a(this,"embeddingModel");chunk5SBYP5H4_cjs.a(this,"vectorDims");e.search?.hybrid;this.config={workspaceDir:e.workspaceDir,sessionsDir:e.sessionsDir??"",database:e.database,archiveDays:e.archiveDays??30,shortTermMaxRounds:e.shortTermMaxRounds??20,search:{maxResults:e.search?.maxResults??Ue,minScore:e.search?.minScore??.3,hybrid:{enabled:e.search?.hybrid?.enabled??true,vectorWeight:e.search?.hybrid?.vectorWeight??Ce,textWeight:e.search?.hybrid?.textWeight??ke}},embedding:e.embedding??{},tokenizer:e.tokenizer??{},indexer:e.indexer??{batchSize:50,ignorePatterns:[],incremental:false},logDir:e.logDir??"",graphLlm:e.graphLlm,embeddingLlm:e.embeddingLlm},this.embeddingModel=e.embeddingLlm,this.db=new j(e.database.path),this.embeddingModel&&U.init({models:{embeddingLlm:this.embeddingModel,graphLlm:this.config.graphLlm}});}async initialize(){await chunk5SBYP5H4_cjs.c.init({logDir:this.config.logDir??___default.default.join(this.config.workspaceDir,"logs"),print:process.argv.includes("--print-logs"),dev:false,level:"INFO"}),await N__default.default.mkdir(___default.default.dirname(this.config.database.path),{recursive:true}),await N__default.default.mkdir(___default.default.join(this.config.workspaceDir,"active"),{recursive:true}),await N__default.default.mkdir(___default.default.join(this.config.workspaceDir,"archive"),{recursive:true}),await this.db.initialize(),this.archiver=new q(this.db.getDb(),this.config),this.graphStore=new H(this.db.getDb()),this.searchEngine=new Q(this.db.getDb(),this.config);let e=this.db.query("SELECT value FROM meta WHERE key = ?",["vectorDims"]);e[0]&&(this.vectorDims=parseInt(e[0].value,10));let t=[["version","1.0.0"],["createdAt",new Date().toISOString()]];for(let[n,r]of t)this.db.run("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)",[n,r]);await de({dictPath:this.config.tokenizer.dictPath}).catch(n=>{y.warn("Tokenizer initialization failed, using fallback",{error:String(n)});}),y.info("Memory system initialized",{workspaceDir:this.config.workspaceDir,dbPath:this.config.database.path});}async remember(e){if(!e.agentId?.trim())throw new M("agentId is required for remember operation");let t=new Date().toISOString(),n=S.generateId(),r={...e,id:n,source:"session_self_write",createdAt:t,updatedAt:t},i=await O.write(this.config.workspaceDir,r);r.filePath=i;let s=[],d=this.config,o=this.extractEntities(r.content);if(s=this.storeEntitiesAndRelations(o.entities,o.relations).nodeIds,d.graphLlm){let l=r.content,u=r.agentId,p=r.id;y.debug("Scheduling background LLM extraction",{id:p,contentLength:l.length}),this.extractEntitiesWithLlm(l).then(E=>{y.debug("Background LLM extraction completed",{id:p,entities:E.entities.length,relations:E.relations.length}),this.mergeEntitiesAndRelations(p,u,E.entities,E.relations);}).catch(E=>{y.warn("Background graph extraction failed",{id:p,error:String(E)});});}r.nodeIds=s;let a=await this.embed(r.content),c=a?Buffer.from(a.buffer,a.byteOffset,a.byteLength):null;return this.db.transaction(()=>{this.db.run(`INSERT OR REPLACE INTO memory_facts
119
+ (id, agent_id, session_id, msg_id, parent_msg_id, content, category, importance,
120
+ source, tags, node_ids, file_path, created_at, updated_at)
121
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[r.id,r.agentId,r.sessionId??null,r.msgId??null,r.parentMsgId??null,r.content,r.category,r.importance,r.source,r.tags?JSON.stringify(r.tags):null,r.nodeIds?JSON.stringify(r.nodeIds):null,r.filePath?utils.Filesystem.toUnixPath(r.filePath):null,r.createdAt,r.updatedAt]),c&&this.db.run("INSERT OR REPLACE INTO memory_vectors (fact_id, embedding) VALUES (?, ?)",[r.id,c]),this.writeFts(r.id,r.agentId,r.content,r.tags);}),y.info("Memory stored",{id:r.id,category:r.category,agentId:r.agentId,nodeCount:s.length}),r}async query(e,t){if(!t?.agentId?.trim())throw new M("agentId is required for query operation");return this.getSearchEngine().search(e,t)}async queryEdgesByNodeId(e,t){if(!this.graphStore)return {nodes:[],edges:[]};let n=Math.min(Math.max(t?.maxDepth??2,1),3),r=await this.graphStore.queryNeighbors(e,n,{maxEdgesPerNode:t?.maxEdgesPerNode??20}),i=r.find(s=>s.id===e);return {node:i?{id:i.id,name:i.name,type:i.type}:void 0,nodes:r.map(s=>s),edges:r.flatMap(s=>s.edges??[])}}async forget(e,t){if(!e?.trim())throw new M("agentId is required for forget operation");let n=this.db.query("SELECT file_path, node_ids, content FROM memory_facts WHERE id = ? AND agent_id = ?",[t,e]);if(n.length===0)throw new W(t);let r=n[0]?.file_path,i=n[0]?.node_ids?JSON.parse(n[0].node_ids):[],s=n[0]?.content,d=s?crypto.createHash("sha256").update(s).digest("hex"):null,o=new Set;if(i.length>0){i.map(()=>"?").join(",");let c=this.db.query("SELECT node_ids FROM memory_facts WHERE id != ? AND agent_id = ? AND node_ids IS NOT NULL",[t,e]);for(let l of c)if(l.node_ids){let u=JSON.parse(l.node_ids);for(let p of u)o.add(p);}}let m=i.filter(a=>!o.has(a));if(this.db.transaction(()=>{if(this.db.run("DELETE FROM memory_facts WHERE id = ? AND agent_id = ?",[t,e]),this.db.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[t]),m.length>0){let a=m.map(()=>"?").join(",");this.db.run(`DELETE FROM nodes WHERE id IN (${a})`,m);}d&&this.db.run("DELETE FROM embedding_cache WHERE content_hash = ?",[d]);}),r){let a=___default.default.isAbsolute(r)?r:___default.default.join(this.config.workspaceDir,r);await O.delete(a,t).catch(c=>{y.warn("Failed to delete memory from file",{memoryId:t,filePath:r,error:String(c)});});}y.info("Memory deleted",{memoryId:t,agentId:e,orphanNodes:m.length});}async update(e,t,n){if(!e?.trim())throw new M("agentId is required for update operation");let r=this.db.query("SELECT * FROM memory_facts WHERE id = ? AND agent_id = ?",[t,e]);if(r.length===0)throw new W(t);let i=r[0],s=new Date().toISOString(),d=n.content??i.content,o=n.importance??i.importance,m=n.tags??(i.tags?JSON.parse(i.tags):void 0),a=n.content?await this.embed(d).then(l=>l?Buffer.from(l.buffer,l.byteOffset,l.byteLength):null):null;if(this.db.transaction(()=>{this.db.run(`UPDATE memory_facts SET content = ?, importance = ?, tags = ?, updated_at = ?
122
+ WHERE id = ? AND agent_id = ?`,[d,o,m?JSON.stringify(m):null,s,t,e]),a&&this.db.run("INSERT OR REPLACE INTO memory_vectors (fact_id, embedding) VALUES (?, ?)",[t,a]),this.writeFts(t,e,d,m);}),i.file_path){let l=___default.default.isAbsolute(i.file_path)?i.file_path:___default.default.join(this.config.workspaceDir,i.file_path);await O.update(l,t,n).catch(u=>{y.warn("Failed to update memory in file",{memoryId:t,error:String(u)});});}let c={id:i.id,agentId:i.agent_id,sessionId:i.session_id??void 0,msgId:i.msg_id??void 0,parentMsgId:i.parent_msg_id??void 0,content:d,category:i.category,importance:o,source:i.source,tags:m,nodeIds:i.node_ids?JSON.parse(i.node_ids):void 0,filePath:i.file_path??void 0,createdAt:String(i.created_at),updatedAt:s};return y.info("Memory updated",{memoryId:t,agentId:e}),c}async extractFromSession(e,t,n){if(!e?.trim())throw new M("agentId is required for extractFromSession operation");let r=Date.now(),i=[];for(let s of n){if(!s.content?.trim())continue;let d=S.generateId(),o=await this.embed(s.content),m=o?Buffer.from(o.buffer,o.byteOffset,o.byteLength):null;i.push({id:d,content:s.content,buffer:m});}this.db.transaction(()=>{for(let s of i)this.db.run(`INSERT OR IGNORE INTO memory_facts
130
123
  (id, agent_id, session_id, msg_id, parent_msg_id, content, category, importance,
131
124
  source, created_at, updated_at)
132
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[l,t,e,a.id,a.parentId??null,a.content,"task_context",5,"historical",a.createdAt??r,r]).changes>0&&(o.push({id:l,content:a.content}),this.writeFts(l,t,a.content,void 0));}});for(let a of o)await this.embedAndStore(a.id,a.content);Z.info("Session extracted to long-term memory",{agentId:t,sessionId:e,inserted:o.length});}async appendShortTerm(t){if(!t.agentId?.trim())throw new pt("agentId is required for appendShortTerm operation");let e=_t.generateId(),s=Date.now();this.db.run(`INSERT OR IGNORE INTO short_term_sessions
125
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[s.id,e,t,void 0,null,s.content,"task_context",5,"historical",r,r]),s.buffer&&this.db.run("INSERT OR REPLACE INTO memory_vectors (fact_id, embedding) VALUES (?, ?)",[s.id,s.buffer]),this.writeFts(s.id,e,s.content,void 0);}),y.info("Session extracted to long-term memory",{agentId:e,sessionId:t,inserted:i.length});}async appendShortTerm(e){if(!e.agentId?.trim())throw new M("agentId is required for appendShortTerm operation");let t=S.generateId(),n=new Date().toISOString();this.db.run(`INSERT OR IGNORE INTO short_term_sessions
133
126
  (id, agent_id, session_id, message_id, parent_id, role, content, model_id, provider_id, created_at)
134
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[e,t.agentId,t.sessionId,t.messageId,t.parentId??null,t.role,t.content,t.modelId??null,t.providerId??null,s]);let r=this.db.query("SELECT COUNT(*) as cnt FROM short_term_sessions WHERE agent_id = ? AND session_id = ?",[t.agentId,t.sessionId])[0]?.cnt??0;r>this.config.shortTermMaxRounds*2&&this.db.run(`DELETE FROM short_term_sessions WHERE id IN (
127
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t,e.agentId,e.sessionId,e.messageId,e.parentId??null,e.role,e.content,e.modelId??null,e.providerId??null,n]);let r=this.db.query("SELECT COUNT(*) as cnt FROM short_term_sessions WHERE agent_id = ? AND session_id = ?",[e.agentId,e.sessionId])[0]?.cnt??0;r>this.config.shortTermMaxRounds*2&&this.db.run(`DELETE FROM short_term_sessions WHERE id IN (
135
128
  SELECT id FROM short_term_sessions
136
129
  WHERE agent_id = ? AND session_id = ?
137
130
  ORDER BY created_at ASC
138
131
  LIMIT ?
139
- )`,[t.agentId,t.sessionId,r-this.config.shortTermMaxRounds*2]);}async getShortTerm(t,e,s=20){return this.db.query(`SELECT * FROM short_term_sessions
132
+ )`,[e.agentId,e.sessionId,r-this.config.shortTermMaxRounds*2]);}async getShortTerm(e,t,n=20){return this.db.query(`SELECT * FROM short_term_sessions
140
133
  WHERE agent_id = ? AND session_id = ?
141
134
  ORDER BY created_at DESC
142
- LIMIT ?`,[t,e,s]).map(o=>({id:o.id,agentId:o.agent_id,sessionId:o.session_id,messageId:o.message_id,parentId:o.parent_id??void 0,role:o.role,content:o.content,modelId:o.model_id??void 0,providerId:o.provider_id??void 0,createdAt:o.created_at}))}async listAgentIds(){return this.db.query("SELECT DISTINCT agent_id FROM memory_facts ORDER BY agent_id").map(e=>e.agent_id)}async queryForSummary(t,e=10){return t?.trim()?this.db.query(`SELECT * FROM memory_facts
135
+ LIMIT ?`,[e,t,n]).map(i=>({id:i.id,agentId:i.agent_id,sessionId:i.session_id,messageId:i.message_id,parentId:i.parent_id??void 0,role:i.role,content:i.content,modelId:i.model_id??void 0,providerId:i.provider_id??void 0,createdAt:i.created_at}))}async listAgentIds(){return this.db.query("SELECT DISTINCT agent_id FROM memory_facts ORDER BY agent_id").map(t=>t.agent_id)}async queryForSummary(e,t=10){return e?.trim()?this.db.query(`SELECT * FROM memory_facts
143
136
  WHERE agent_id = ? AND source IN ('historical', 'session_self_write')
144
137
  ORDER BY importance DESC, created_at DESC
145
- LIMIT ?`,[t,e]).map(r=>({id:r.id,agentId:r.agent_id,sessionId:r.session_id??void 0,msgId:r.msg_id??void 0,parentMsgId:r.parent_msg_id??void 0,content:r.content,category:r.category,importance:r.importance,source:r.source,tags:r.tags?JSON.parse(r.tags):void 0,nodeIds:r.node_ids?JSON.parse(r.node_ids):void 0,filePath:r.file_path??void 0,createdAt:r.created_at,updatedAt:r.updated_at})):[]}async archive(){await this.getArchiver().archive();}async cleanupOrphanRecords(){let t=this.db.transaction(()=>{let e=this.db.run("DELETE FROM memory_facts_fts WHERE fact_id NOT IN (SELECT id FROM memory_facts)"),s=this.db.run("DELETE FROM memory_vectors WHERE fact_id NOT IN (SELECT id FROM memory_facts)"),r=this.db.run("DELETE FROM embedding_cache WHERE content_hash NOT IN (SELECT content_hash FROM memory_facts)");return {orphanFts:e.changes,orphanVectors:s.changes,orphanCache:r.changes}});(t.orphanFts>0||t.orphanVectors>0||t.orphanCache>0)&&Z.info("Cleaned orphan records",t);}async clear(){this.db.transaction(()=>{this.db.run("DELETE FROM memory_facts"),this.db.run("DELETE FROM memory_vectors"),this.db.run("DELETE FROM embedding_cache"),this.db.run("DELETE FROM memory_facts_fts"),this.db.run("DELETE FROM short_term_sessions"),this.db.run("DELETE FROM nodes"),this.db.run("DELETE FROM edges");});try{let t=await At.listActiveFiles(this.config.workspaceDir);for(let e of t)await se__default.default.rm(e,{force:!0}).catch(()=>{});}catch(t){Z.warn("Failed to clean memory files",{error:String(t)});}Z.info("Memory system cleared");}async close(){this.db.close(),await be.close(),Z.info("Memory system closed");}extractEntities(t){let e=[],s=[],r=new Set,o=new Set,a=/([A-Za-z][\w.-]{1,80})\s+(is_a|part_of|has_attribute|located_in|occurs_in|causes|influences|owned_by|member_of|uses|depends_on|related_to)\s+([A-Za-z][\w.-]{1,80})/g;for(let h of t.matchAll(a)){let c=this.sanitizeEntityToken(h[1]??""),u=(h[2]??"related_to").trim(),d=this.sanitizeEntityToken(h[3]??"");if(!c||!d||c===d)continue;let f=c.toLowerCase();r.has(f)||(r.add(f),e.push({name:c,type:this.inferEntityType(c),properties:{source:"rule_extracted"}}));let g=d.toLowerCase();r.has(g)||(r.add(g),e.push({name:d,type:this.inferEntityType(d),properties:{source:"rule_extracted"}}));let b=`${f}|${g}|${u}`;o.has(b)||(o.add(b),s.push({source:c,target:d,relation:u}));}let l=t.match(/[A-Za-z][A-Za-z0-9_.-]{2,80}/g)??[];for(let h of l){let c=this.sanitizeEntityToken(h);if(!c)continue;let u=c.toLowerCase();r.has(u)||(r.add(u),e.push({name:c,type:this.inferEntityType(c),properties:{source:"keyword_extracted"}}));}return {entities:e,relations:s}}async extractEntitiesWithLlm(t){if(!this.config.llm)return this.extractEntities(t);try{let s=this.buildEntityExtractionPrompt(t),r=await Se.generate(s,{maxOutputTokens:2e3});return this.parseEntityExtractionResult(r)}catch(s){return Z.warn("LLM entity extraction failed, falling back to simple extraction",{error:String(s)}),this.extractEntities(t)}}buildEntityExtractionPrompt(t){let e=types.GRAPH_ENTITY_TYPE_DEFINITIONS.map(o=>`- ${o.type}: ${o.rule}`).join(`
146
- `),s=types.GRAPH_RELATION_TYPE_DEFINITIONS.map(o=>`- ${o.type}: ${o.rule}`).join(`
147
- `),r=t.slice(0,1e3);return `You are an information extraction engine for a general-purpose memory graph.
138
+ LIMIT ?`,[e,t]).map(r=>({id:r.id,agentId:r.agent_id,sessionId:r.session_id??void 0,msgId:r.msg_id??void 0,parentMsgId:r.parent_msg_id??void 0,content:r.content,category:r.category,importance:r.importance,source:r.source,tags:r.tags?JSON.parse(r.tags):void 0,nodeIds:r.node_ids?JSON.parse(r.node_ids):void 0,filePath:r.file_path??void 0,createdAt:String(r.created_at),updatedAt:String(r.updated_at)})):[]}async archive(){await this.getArchiver().archive();}async cleanupOrphanRecords(){let e=this.db.transaction(()=>{let t=this.db.run("DELETE FROM memory_facts_fts WHERE fact_id NOT IN (SELECT id FROM memory_facts)"),n=this.db.run("DELETE FROM memory_vectors WHERE fact_id NOT IN (SELECT id FROM memory_facts)"),r=this.db.run("DELETE FROM embedding_cache WHERE content_hash NOT IN (SELECT content_hash FROM memory_facts)");return {orphanFts:t.changes,orphanVectors:n.changes,orphanCache:r.changes}});(e.orphanFts>0||e.orphanVectors>0||e.orphanCache>0)&&y.info("Cleaned orphan records",e);}async clear(){this.db.transaction(()=>{this.db.run("DELETE FROM memory_facts"),this.db.run("DELETE FROM memory_vectors"),this.db.run("DELETE FROM embedding_cache"),this.db.run("DELETE FROM memory_facts_fts"),this.db.run("DELETE FROM short_term_sessions"),this.db.run("DELETE FROM nodes"),this.db.run("DELETE FROM edges");});try{let e=await O.listActiveFiles(this.config.workspaceDir);for(let t of e)await N__default.default.rm(t,{force:!0}).catch(()=>{});}catch(e){y.warn("Failed to clean memory files",{error:String(e)});}y.info("Memory system cleared");}async close(){this.db.close(),await chunk5SBYP5H4_cjs.c.close(),y.info("Memory system closed");}async getStatus(){try{let e=this.db.query("SELECT COUNT(*) as c FROM memory_facts"),t=this.db.query("SELECT COUNT(*) as c FROM graph_nodes"),n=this.db.query("SELECT COUNT(*) as c FROM graph_edges"),r=this.db.query("SELECT COUNT(*) as c FROM short_term_sessions"),i=this.db.query("SELECT key, value FROM meta"),s={};for(let d of i)s[d.key]=d.value;return {dbPath:this.config.database.path,workspaceDir:this.config.workspaceDir,factsCount:e[0]?.c??0,nodesCount:t[0]?.c??0,edgesCount:n[0]?.c??0,shortTermCount:r[0]?.c??0,embeddingLlmAvailable:!!this.config.embeddingLlm,graphLlmAvailable:!!this.config.graphLlm,healthy:!0,meta:s}}catch{return {dbPath:this.config.database.path,workspaceDir:this.config.workspaceDir,factsCount:0,nodesCount:0,edgesCount:0,shortTermCount:0,embeddingLlmAvailable:false,graphLlmAvailable:false,healthy:false,meta:{}}}}async sync(){let e={synced:0,created:0,updated:0,errors:[]};await this.hasMemoryFiles()||await this.clearFiles();let n=this.db.query("SELECT * FROM memory_facts ORDER BY category, created_at ASC",[]),r=new Map;for(let i of n){let s=i.category,d=new Date(i.created_at),m=`${`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,"0")}-${String(d.getDate()).padStart(2,"0")}`}.md`,a=`${s}/${m}`;if(!r.has(a)){let c=___default.default.join(this.config.workspaceDir,"active",s,m);r.set(a,{path:c,facts:[]});}r.get(a).facts.push(i);}for(let[i,{path:s,facts:d}]of r)try{let o=___default.default.dirname(s);await N__default.default.mkdir(o,{recursive:!0});let m=d.map(c=>{let l=this.rowToFact(c);return S.serialize(l)}).join(`
139
+ `);if(await N__default.default.access(s).then(()=>!0).catch(()=>!1)){if((await N__default.default.readFile(s,"utf-8")).trim()===m.trim()){e.synced++;continue}e.updated++;}else e.created++;await N__default.default.writeFile(s,m,"utf-8"),e.synced++;}catch(o){let m=o instanceof Error?o.message:String(o);e.errors.push(`Failed to sync ${i}: ${m}`),y.warn("Memory file sync failed",{key:i,error:m});}return y.info("Memory sync completed",{synced:e.synced,created:e.created,updated:e.updated,errors:e.errors.length}),this.db.setMeta("lastSync",new Date().toISOString()),e}async hasMemoryFiles(){let e=[___default.default.join(this.config.workspaceDir,"active"),___default.default.join(this.config.workspaceDir,"archive")];for(let t of e)try{let n=await N__default.default.readdir(t,{withFileTypes:!0});for(let r of n){let i=___default.default.join(t,r.name);if(r.isDirectory()){if((await N__default.default.readdir(i,{withFileTypes:!0})).length>0)return !0}else if(r.name.endsWith(".md"))return !0}}catch(n){if(n.code==="ENOENT")continue;throw n}return false}async clearFiles(){let e=[___default.default.join(this.config.workspaceDir,"active"),___default.default.join(this.config.workspaceDir,"archive")];for(let t of e)try{let n=await N__default.default.readdir(t,{withFileTypes:!0});for(let r of n){let i=___default.default.join(t,r.name);r.isDirectory()?await N__default.default.rm(i,{recursive:!0,force:!0}):r.name.endsWith(".md")&&await N__default.default.unlink(i);}}catch(n){if(n.code!=="ENOENT")throw n}y.info("Memory files cleared");}rowToFact(e){return {id:e.id,agentId:e.agent_id,sessionId:e.session_id??void 0,msgId:e.msg_id??void 0,parentMsgId:e.parent_msg_id??void 0,content:e.content,category:e.category,importance:e.importance,source:e.source,tags:e.tags?JSON.parse(e.tags):void 0,nodeIds:e.node_ids?JSON.parse(e.node_ids):void 0,filePath:e.file_path??void 0,createdAt:new Date(e.created_at).toISOString(),updatedAt:new Date(e.updated_at).toISOString()}}extractEntities(e){let t=[],n=[],r=new Set,i=new Set,s=/([A-Za-z][\w.-]{1,80})\s+(is_a|part_of|has_attribute|located_in|occurs_in|causes|influences|owned_by|member_of|uses|depends_on|related_to)\s+([A-Za-z][\w.-]{1,80})/g;for(let o of e.matchAll(s)){let m=this.sanitizeEntityToken(o[1]??""),a=(o[2]??"related_to").trim(),c=this.sanitizeEntityToken(o[3]??"");if(!m||!c||m===c)continue;let l=m.toLowerCase();r.has(l)||(r.add(l),t.push({name:m,type:this.inferEntityType(m),properties:{source:"rule_extracted"}}));let u=c.toLowerCase();r.has(u)||(r.add(u),t.push({name:c,type:this.inferEntityType(c),properties:{source:"rule_extracted"}}));let p=`${l}|${u}|${a}`;i.has(p)||(i.add(p),n.push({source:m,target:c,relation:a}));}let d=e.match(/[\p{L}\p{N}][\p{L}\p{N}_.-]{1,80}/gu)??[];for(let o of d){let m=this.sanitizeEntityToken(o);if(!m)continue;let a=m.toLowerCase();r.has(a)||(r.add(a),t.push({name:m,type:this.inferEntityType(m),properties:{source:"keyword_extracted"}}));}return {entities:t,relations:n}}async extractEntitiesWithLlm(e){if(!this.config.graphLlm)return this.extractEntities(e);try{let n=this.buildEntityExtractionPrompt(e);y.debug("LLM extracting entities...",{contentLength:e.length});let r=await U.generate(n,{maxOutputTokens:2e3});y.debug("LLM extraction result",{resultLength:r.length,result:r.slice(0,200)});let i=this.parseEntityExtractionResult(r);return y.debug("Parsed entities",{entityCount:i.entities.length,relationCount:i.relations.length}),i}catch(n){return y.warn("LLM entity extraction failed, falling back to simple extraction",{error:String(n)}),this.extractEntities(e)}}buildEntityExtractionPrompt(e){let t=types.GRAPH_ENTITY_TYPE_DEFINITIONS.map(i=>`- ${i.type}: ${i.rule}`).join(`
140
+ `),n=types.GRAPH_RELATION_TYPE_DEFINITIONS.map(i=>`- ${i.type}: ${i.rule}`).join(`
141
+ `),r=e.slice(0,1e3);return `You are an information extraction engine for a general-purpose memory graph.
148
142
 
149
143
  Extract entities and directed relations from the text.
150
144
 
151
145
  Entity type taxonomy:
152
- ${e}
146
+ ${t}
153
147
 
154
148
  Relation type taxonomy:
155
- ${s}
149
+ ${n}
156
150
 
157
151
  Extraction rules:
158
152
  - Output valid JSON only. Do not include markdown, prose, or code fences.
@@ -174,4 +168,4 @@ Return this exact JSON shape:
174
168
  }
175
169
 
176
170
  Input text:
177
- ${r}`}storeEntitiesAndRelations(t,e){if(t.length===0)return {nodeIds:[]};let s=new Map,r=Date.now(),o=t.map(()=>"?").join(","),a=this.db.query(`SELECT id, name, type FROM nodes WHERE name IN (${o})`,t.map(h=>h.name)),l=new Map(a.map(h=>[`${h.name}::${h.type}`,h.id]));return this.db.transaction(()=>{for(let h of t){let c=`${h.name}::${h.type}`,u=l.get(c);if(u!==void 0)this.db.run("UPDATE nodes SET properties = ?, updatedAt = ? WHERE id = ?",[JSON.stringify(h.properties),r,u]),s.set(h.name,u);else {let d=this.db.run("INSERT OR IGNORE INTO nodes (name, type, properties) VALUES (?, ?, ?)",[h.name,h.type,JSON.stringify(h.properties)]);d.lastID>0&&s.set(h.name,d.lastID);}}for(let h of e){let c=s.get(h.source),u=s.get(h.target);c&&u&&this.db.run("INSERT OR IGNORE INTO edges (source, target, relation) VALUES (?, ?, ?)",[c,u,h.relation]);}}),{nodeIds:Array.from(s.values())}}async embed(t){if(!this.embeddingModel)return null;let e=crypto.createHash("sha256").update(t).digest("hex"),s=this.db.query("SELECT embedding FROM embedding_cache WHERE content_hash = ?",[e])[0];if(s)return new Float32Array(s.embedding.buffer,s.embedding.byteOffset,s.embedding.byteLength/4);try{let o=(await this.embeddingModel.doEmbed({values:[t]})).embeddings[0];if(!o||o.length===0)return null;let a=new Float32Array(o),l=Buffer.from(a.buffer,a.byteOffset,a.byteLength);return this.db.run("INSERT OR REPLACE INTO embedding_cache (content_hash, embedding) VALUES (?, ?)",[e,l]),this.vectorDims===void 0&&(this.vectorDims=o.length,this.db.run("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",["vectorDims",String(o.length)])),a}catch(r){return Z.warn("Embedding failed",{error:String(r)}),null}}async embedAndStore(t,e){let s=await this.embed(e);if(!s)return;let r=Buffer.from(s.buffer,s.byteOffset,s.byteLength);this.db.run("INSERT OR REPLACE INTO memory_vectors (fact_id, embedding) VALUES (?, ?)",[t,r]);}writeFts(t,e,s,r){try{let o=er(s),a=r?er(r.join(" ")):"";this.db.transaction(()=>{this.db.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[t]),this.db.run("INSERT INTO memory_facts_fts (fact_id, agent_id, content, tags) VALUES (?, ?, ?, ?)",[t,e,o,a]);});}catch(o){Z.warn("FTS index write failed",{factId:t,error:String(o)});}}parseEntityExtractionResult(t){try{let e=t.match(/\{[\s\S]*\}/);if(e){let s=JSON.parse(e[0]);return this.normalizeExtractionResult(s)}}catch(e){Z.debug("Failed to parse entity extraction result",{error:String(e)});}return {entities:[],relations:[]}}normalizeExtractionResult(t){let e=t,s=Array.isArray(e.entities)?e.entities:[],r=Array.isArray(e.relations)?e.relations:[],o=[],a=new Set,l=new Map;for(let u of s){let d=typeof u?.name=="string"?u.name.trim():"";if(!d)continue;let f=d.toLowerCase();if(a.has(f))continue;a.add(f),l.set(f,d);let g=typeof u?.type=="string"?u.type.trim():"",b=Eh.has(g)?g:"keyword",E=u?.properties&&typeof u.properties=="object"&&!Array.isArray(u.properties)?u.properties:{};o.push({name:d,type:b,properties:E});}let h=[],c=new Set;for(let u of r){let d=typeof u?.source=="string"?u.source.trim():"",f=typeof u?.target=="string"?u.target.trim():"";if(!d||!f)continue;let g=l.get(d.toLowerCase()),b=l.get(f.toLowerCase());if(!g||!b||g===b)continue;let E=typeof u?.relation=="string"?u.relation.trim():"",T=Sh.has(E)?E:"related_to",S=`${g.toLowerCase()}|${b.toLowerCase()}|${T}`;c.has(S)||(c.add(S),h.push({source:g,target:b,relation:T}));}return {entities:o,relations:h}}sanitizeEntityToken(t){return t.trim().replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu,"").replace(/\s+/g," ").slice(0,120)}inferEntityType(t){let e=t.toLowerCase();return /(\.md|\.ts|\.json|readme|doc|spec|guideline)/i.test(t)?"document":/(api|service|system|engine|pipeline|server|db|database|memorysystem|contextengine)/i.test(t)?"process":/(team|group|org|company|inc|ltd|corp)/i.test(t)?"organization":/(deadline|date|day|week|month|year|q[1-4]|sprint)/i.test(t)?"time":/(score|rate|ratio|latency|accuracy|recall|precision|throughput|kpi)/i.test(t)?"metric":/(task|issue|ticket|todo|action)/i.test(t)?"task":/(event|incident|release|meeting|migration|launch)/i.test(t)?"event":/(process|workflow|procedure|flow|lifecycle)/i.test(t)?"process":/(file|model|dataset|artifact|resource|tool|sdk|ollama|sqlite|embedding|vector|fts)/i.test(t)?"object":/(concept|principle|policy|method|pattern|strategy)/i.test(t)?"concept":/[A-Z]/.test(t)&&e!==t?"object":"keyword"}getSearchEngine(){if(!this.searchEngine)throw new Q("Memory system not initialized. Call initialize() first.");return this.searchEngine}getGraphStore(){if(!this.graphStore)throw new Q("Memory system not initialized. Call initialize() first.");return this.graphStore}getArchiver(){if(!this.archiver)throw new Q("Memory system not initialized. Call initialize() first.");return this.archiver}};async function vh(i){let t=new bs(i);return await t.initialize(),t}Object.defineProperty(exports,"GRAPH_ENTITY_TYPE_DEFINITIONS",{enumerable:true,get:function(){return types.GRAPH_ENTITY_TYPE_DEFINITIONS}});Object.defineProperty(exports,"GRAPH_RELATION_TYPE_DEFINITIONS",{enumerable:true,get:function(){return types.GRAPH_RELATION_TYPE_DEFINITIONS}});exports.GraphStore=Xi;exports.MEMORY_CATEGORIES=Ts;exports.MemoryArchiver=Gi;exports.MemoryDatabaseError=Q;exports.MemoryDatabaseManager=Ui;exports.MemoryEmbeddingError=ri;exports.MemoryError=Yt;exports.MemoryErrorCode=Zn;exports.MemoryFileError=Mt;exports.MemoryFileManager=At;exports.MemoryFormatter=_t;exports.MemoryNotFoundError=ei;exports.MemoryPermissionError=ii;exports.MemorySearchError=si;exports.MemorySystem=bs;exports.MemoryValidationError=pt;exports.addWord=El;exports.closeTokenizer=vl;exports.createMemorySystem=vh;exports.initTokenizer=Un;exports.isInitialized=Sl;exports.loadCustomDict=sh;exports.toFtsTokens=er;exports.toFtsTokensForSearch=Bn;exports.tokenize=rh;exports.tokenizeForSearch=nh;
171
+ ${r}`}storeEntitiesAndRelations(e,t){if(e.length===0)return {nodeIds:[]};let n=new Map,r=new Date().toISOString(),i=e.map(()=>"?").join(","),s=this.db.query(`SELECT id, name, type FROM nodes WHERE name IN (${i})`,e.map(o=>o.name)),d=new Map(s.map(o=>[`${o.name}::${o.type}`,o.id]));return this.db.transaction(()=>{for(let o of e){let m=`${o.name}::${o.type}`,a=d.get(m);if(a!==void 0)this.db.run("UPDATE nodes SET properties = ?, updatedAt = ? WHERE id = ?",[JSON.stringify(o.properties),r,a]),n.set(o.name,a);else {let c=this.db.run("INSERT INTO nodes (name, type, properties, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?)",[o.name,o.type,JSON.stringify(o.properties),r,r]);c.lastID>0&&n.set(o.name,c.lastID);}}for(let o of t){let m=n.get(o.source),a=n.get(o.target);m&&a&&this.db.run("INSERT INTO edges (source, target, relation, createdAt) VALUES (?, ?, ?, ?)",[m,a,o.relation,r]);}}),{nodeIds:Array.from(n.values())}}mergeEntitiesAndRelations(e,t,n,r){if(n.length===0&&r.length===0)return;let i=new Map,s=new Date().toISOString(),d=n.map(()=>"?").join(","),o=this.db.query(`SELECT id, name, type FROM nodes WHERE name IN (${d})`,n.map(a=>a.name)),m=new Map(o.map(a=>[`${a.name}::${a.type}`,a.id]));this.db.transaction(()=>{for(let c of n){let l=`${c.name}::${c.type}`,u=m.get(l);if(u!==void 0)i.set(c.name,u);else {let p=this.db.run("INSERT INTO nodes (name, type, properties, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?)",[c.name,c.type,JSON.stringify(c.properties),s,s]);p.lastID>0&&i.set(c.name,p.lastID);}}for(let c of r){let l=i.get(c.source),u=i.get(c.target);l&&u&&this.db.run("INSERT INTO edges (source, target, relation, createdAt) VALUES (?, ?, ?, ?)",[l,u,c.relation,s]);}let a=Array.from(i.values());a.length>0&&this.db.run("UPDATE memory_facts SET node_ids = ? WHERE id = ?",[JSON.stringify(a),e]);});}async embed(e){if(!this.embeddingModel)return null;let t=crypto.createHash("sha256").update(e).digest("hex"),n=this.db.query("SELECT embedding FROM embedding_cache WHERE content_hash = ?",[t])[0];if(n)return new Float32Array(n.embedding.buffer,n.embedding.byteOffset,n.embedding.byteLength/4);try{let i=(await this.embeddingModel.doEmbed({values:[e]})).embeddings[0];if(!i||i.length===0)return null;let s=new Float32Array(i),d=Buffer.from(s.buffer,s.byteOffset,s.byteLength);return this.db.run("INSERT OR REPLACE INTO embedding_cache (content_hash, embedding) VALUES (?, ?)",[t,d]),this.vectorDims===void 0&&(this.vectorDims=i.length,this.db.run("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",["vectorDims",String(i.length)])),s}catch(r){return y.warn("Embedding failed",{error:String(r)}),null}}async embedAndStore(e,t){let n=await this.embed(t);if(!n)return;let r=Buffer.from(n.buffer,n.byteOffset,n.byteLength);try{this.db.run("INSERT OR REPLACE INTO memory_vectors (fact_id, embedding) VALUES (?, ?)",[e,r]);}catch(i){y.warn("Vector store failed (fact may not exist yet)",{factId:e,error:String(i)});}}writeVector(e,t){try{this.db.run("INSERT OR REPLACE INTO memory_vectors (fact_id, embedding) VALUES (?, ?)",[e,t]);}catch(n){y.warn("Vector write failed",{factId:e,error:String(n)});}}writeFts(e,t,n,r){try{let i=ie(n),s=r?ie(r.join(" ")):"";this.db.run("DELETE FROM memory_facts_fts WHERE fact_id = ?",[e]),this.db.run("INSERT INTO memory_facts_fts (fact_id, agent_id, content, tags) VALUES (?, ?, ?, ?)",[e,t,i,s]);}catch(i){y.warn("FTS index write failed",{factId:e,error:String(i)});}}parseEntityExtractionResult(e){try{let t=e.match(/\{[\s\S]*\}/);if(t){let n=JSON.parse(t[0]);return this.normalizeExtractionResult(n)}}catch(t){y.debug("Failed to parse entity extraction result",{error:String(t)});}return {entities:[],relations:[]}}normalizeExtractionResult(e){let t=e,n=Array.isArray(t.entities)?t.entities:[],r=Array.isArray(t.relations)?t.relations:[],i=[],s=new Set,d=new Map;for(let a of n){let c=typeof a?.name=="string"?a.name.trim():"";if(!c)continue;let l=c.toLowerCase();if(s.has(l))continue;s.add(l),d.set(l,c);let u=typeof a?.type=="string"?a.type.trim():"",p=ze.has(u)?u:"keyword",E=a?.properties&&typeof a.properties=="object"&&!Array.isArray(a.properties)?a.properties:{};i.push({name:c,type:p,properties:E});}let o=[],m=new Set;for(let a of r){let c=typeof a?.source=="string"?a.source.trim():"",l=typeof a?.target=="string"?a.target.trim():"";if(!c||!l)continue;let u=d.get(c.toLowerCase()),p=d.get(l.toLowerCase());if(!u||!p||u===p)continue;let E=typeof a?.relation=="string"?a.relation.trim():"",D=$e.has(E)?E:"related_to",A=`${u.toLowerCase()}|${p.toLowerCase()}|${D}`;m.has(A)||(m.add(A),o.push({source:u,target:p,relation:D}));}return {entities:i,relations:o}}sanitizeEntityToken(e){return e.trim().replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu,"").replace(/\s+/g," ").slice(0,120)}inferEntityType(e){let t=e.toLowerCase();return /(\.md|\.ts|\.json|readme|doc|spec|guideline)/i.test(e)?"document":/(api|service|system|engine|pipeline|server|db|database|memorysystem|contextengine)/i.test(e)?"process":/(team|group|org|company|inc|ltd|corp)/i.test(e)?"organization":/(deadline|date|day|week|month|year|q[1-4]|sprint)/i.test(e)?"time":/(score|rate|ratio|latency|accuracy|recall|precision|throughput|kpi)/i.test(e)?"metric":/(task|issue|ticket|todo|action)/i.test(e)?"task":/(event|incident|release|meeting|migration|launch)/i.test(e)?"event":/(process|workflow|procedure|flow|lifecycle)/i.test(e)?"process":/(file|model|dataset|artifact|resource|tool|sdk|ollama|sqlite|embedding|vector|fts)/i.test(e)?"object":/(concept|principle|policy|method|pattern|strategy)/i.test(e)?"concept":/[A-Z]/.test(e)&&t!==e?"object":"keyword"}getSearchEngine(){if(!this.searchEngine)throw new T("Memory system not initialized. Call initialize() first.");return this.searchEngine}getGraphStore(){if(!this.graphStore)throw new T("Memory system not initialized. Call initialize() first.");return this.graphStore}getArchiver(){if(!this.archiver)throw new T("Memory system not initialized. Call initialize() first.");return this.archiver}};async function We(g){let e=new Z(g);return await e.initialize(),e}async function er(g){let{Log:e}=await import('./chunks/log-FDVK2LXU.cjs'),t=false;await e.init({logDir:g.logDir??process.env.EASBOT_LOG_PATH??process.cwd(),print:g.print??false,dev:g.dev??t,level:g.level??("INFO")});}Object.defineProperty(exports,"GRAPH_ENTITY_TYPE_DEFINITIONS",{enumerable:true,get:function(){return types.GRAPH_ENTITY_TYPE_DEFINITIONS}});Object.defineProperty(exports,"GRAPH_RELATION_TYPE_DEFINITIONS",{enumerable:true,get:function(){return types.GRAPH_RELATION_TYPE_DEFINITIONS}});exports.GraphStore=H;exports.MEMORY_CATEGORIES=te;exports.MemoryArchiver=q;exports.MemoryDatabaseError=T;exports.MemoryDatabaseManager=j;exports.MemoryEmbeddingError=B;exports.MemoryError=F;exports.MemoryErrorCode=Te;exports.MemoryFileError=L;exports.MemoryFileManager=O;exports.MemoryFormatter=S;exports.MemoryNotFoundError=W;exports.MemoryPermissionError=X;exports.MemorySearchError=J;exports.MemorySystem=Z;exports.MemoryValidationError=M;exports.addWord=Ve;exports.closeTokenizer=Ge;exports.createMemorySystem=We;exports.initLog=er;exports.initTokenizer=de;exports.isInitialized=Je;exports.loadCustomDict=Me;exports.toFtsTokens=ie;exports.toFtsTokensForSearch=ce;exports.tokenize=Se;exports.tokenizeForSearch=Ne;