@easbot/memory 0.1.13 → 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/README.en.md +79 -0
- package/README.md +20 -104
- package/dist/chunks/chunk-5SBYP5H4.cjs +4 -0
- package/dist/chunks/chunk-MS352GPQ.mjs +4 -0
- package/dist/chunks/log-FDVK2LXU.cjs +1 -0
- package/dist/chunks/log-WWZ27AYI.mjs +1 -0
- package/dist/index.cjs +47 -53
- package/dist/index.d.cts +92 -23
- package/dist/index.d.ts +92 -23
- package/dist/index.mjs +47 -53
- package/package.json +8 -5
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,4 @@
|
|
|
1
|
-
import {GRAPH_ENTITY_TYPE_DEFINITIONS,GRAPH_RELATION_TYPE_DEFINITIONS}from'@easbot/types';export{GRAPH_ENTITY_TYPE_DEFINITIONS,GRAPH_RELATION_TYPE_DEFINITIONS}from'@easbot/types';import*as se from'jieba-wasm';import {loadTextFile,formatLogTime,Filesystem,formatLocalISO}from'@easbot/utils';import Se,{win32,posix}from'path';import re,{realpath,readlink,readdir,lstat}from'fs/promises';import*as ma from'fs';import {realpathSync,createWriteStream,readlinkSync,readdirSync,readdir as readdir$1,lstatSync,promises}from'fs';import Qa from'zod';import {fileURLToPath}from'url';import {EventEmitter}from'events';import gn from'stream';import {StringDecoder}from'string_decoder';import oh from'better-sqlite3';import {randomBytes,createHash}from'crypto';import {embed,embedMany,streamText}from'ai';var Kn=Object.defineProperty;var rr=i=>{throw TypeError(i)};var Qn=(i,t,e)=>t in i?Kn(i,t,{enumerable:true,configurable:true,writable:true,value:e}):i[t]=e;var p=(i,t,e)=>Qn(i,typeof t!="symbol"?t+"":t,e),Ts=(i,t,e)=>t.has(i)||rr("Cannot "+e);var n=(i,t,e)=>(Ts(i,t,"read from private field"),e?e.call(i):t.get(i)),w=(i,t,e)=>t.has(i)?rr("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(i):t.set(i,e),m=(i,t,e,s)=>(Ts(i,t,"write to private field"),t.set(i,e),e),y=(i,t,e)=>(Ts(i,t,"access private method"),e);var qi=(i,t,e,s)=>({set _(r){m(i,t,r);},get _(){return n(i,t,s)}});var Rs=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","other"],Ht=class extends Error{constructor(e,s,r){super(e,{cause:r});this.code=s;this.cause=r;this.name="MemoryError";}},ut=class extends Ht{constructor(t,e){super(t,"MEMORY_VALIDATION_ERROR",e),this.name="MemoryValidationError";}},ii=class extends Ht{constructor(t){super(`Memory not found: ${t}`,"MEMORY_NOT_FOUND"),this.name="MemoryNotFoundError";}},si=class extends Ht{constructor(t){super(t,"MEMORY_PERMISSION_ERROR"),this.name="MemoryPermissionError";}},Q=class extends Ht{constructor(t,e){super(t,"MEMORY_DATABASE_ERROR",e),this.name="MemoryDatabaseError";}},xt=class extends Ht{constructor(t,e){super(t,"MEMORY_FILE_ERROR",e),this.name="MemoryFileError";}},ri=class extends Ht{constructor(t,e){super(t,"MEMORY_SEARCH_ERROR",e),this.name="MemorySearchError";}},ni=class extends Ht{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 Kr=(i,t,e)=>{let s=i instanceof RegExp?nr(i,e):i,r=t instanceof RegExp?nr(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)}},nr=(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},Qr="\0SLASH"+Math.random()+"\0",Zr="\0OPEN"+Math.random()+"\0",Vs="\0CLOSE"+Math.random()+"\0",tn="\0COMMA"+Math.random()+"\0",en="\0PERIOD"+Math.random()+"\0",eo=new RegExp(Qr,"g"),io=new RegExp(Zr,"g"),so=new RegExp(Vs,"g"),ro=new RegExp(tn,"g"),no=new RegExp(en,"g"),oo=/\\\\/g,ao=/\\{/g,ho=/\\}/g,lo=/\\,/g,co=/\\./g,uo=1e5;function Ms(i){return isNaN(i)?i.charCodeAt(0):parseInt(i,10)}function po(i){return i.replace(oo,Qr).replace(ao,Zr).replace(ho,Vs).replace(lo,tn).replace(co,en)}function mo(i){return i.replace(eo,"\\").replace(io,"{").replace(so,"}").replace(ro,",").replace(no,".")}function sn(i){if(!i)return [""];let t=[],e=Kr("{","}",i);if(!e)return i.split(",");let{pre:s,body:r,post:o}=e,a=s.split(",");a[a.length-1]+="{"+r+"}";let l=sn(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)),ui(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 ui(i,t,e){let s=[],r=Kr("{","}",i);if(!r)return [i];let o=r.pre,a=r.post.length?ui(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+Vs+r.post,ui(i,t,true)):[i];let d;if(c)d=r.body.split(/\.\./);else if(d=sn(r.body),d.length===1&&d[0]!==void 0&&(d=ui(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=Ms(d[0]),b=Ms(d[1]),E=Math.max(d[0].length,d[1].length),T=d.length===3&&d[2]!==void 0?Math.abs(Ms(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,ui(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 ds=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]},oi=i=>i.replace(/[[\]\\-]/g,"\\$&"),So=i=>i.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),or=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(oi(d)+"-"+oi(b)):b===d&&s.push(oi(b)),d="",o++;continue}if(i.startsWith("-]",o+1)){s.push(oi(b+"-")),o+=2;continue}if(i.startsWith("-",o+1)){d=b,o+=2;continue}s.push(oi(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?"^":"")+or(s)+"]",g="["+(c?"":"^")+or(r)+"]";return [s.length&&r.length?"("+f+"|"+g+")":s.length?f:g,l,u-e,true]},Ue=(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(["!","?","+","*","@"]),ar=i=>To.has(i),Ro="(?!(?:^|/)\\.\\.?(?:$|/))",Vi="(?!\\.)",_o=new Set(["[","."]),Ao=new Set(["..","."]),Mo=new Set("().*{}+?[]^$\\!"),xo=i=>i.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Js="[^/]",hr=Js+"*?",lr=Js+"+?",j,q,Jt,L,W,de,Me,ue,Ut,xe,bi,Pe,nn,we,K,ss,Ds,on,rn=(K=class{constructor(t,e,s={}){w(this,Pe);p(this,"type");w(this,j);w(this,q);w(this,Jt,false);w(this,L,[]);w(this,W);w(this,de);w(this,Me);w(this,ue,false);w(this,Ut);w(this,xe);w(this,bi,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,Ut,n(this,j)===this?s:n(n(this,j),Ut)),m(this,Me,n(this,j)===this?[]:n(n(this,j),Me)),t==="!"&&!n(n(this,j),ue)&&n(this,Me).push(this),m(this,de,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,xe)!==void 0?n(this,xe):this.type?m(this,xe,this.type+"("+n(this,L).map(t=>String(t)).join("|")+")"):m(this,xe,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),ue)&&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,de)===0)return true;let t=n(this,W);for(let e=0;e<n(this,de);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,de)===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,we,ss).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,Ut).nocase&&!n(this,Ut).nocaseMagicOnly&&t.toUpperCase()!==t.toLowerCase()))return s;let a=(n(this,Ut).nocase?"i":"")+(o?"u":"");return Object.assign(new RegExp(`^${e}$`,a),{_src:e,_glob:t})}get options(){return n(this,Ut)}toRegExpSource(t){let e=t??!!n(this,Ut).dot;if(n(this,j)===this&&y(this,Pe,nn).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,we,on).call(S,f,n(this,q),h):f.toRegExpSource(t);return m(this,q,n(this,q)||E),m(this,Jt,n(this,Jt)||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?Vi:"";}let d="";return this.isEnd()&&n(n(this,j),ue)&&n(this,W)?.type==="!"&&(d="(?:$|\\/)"),[u+c+d,Ue(c),m(this,q,!!n(this,q)),n(this,Jt)]}let s=this.type==="*"||this.type==="+",r=this.type==="!"?"(?:(?!(?:":"(?:",o=y(this,Pe,Ds).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,Ue(this.toString()),false,false]}let a=!s||t||e||!Vi?"":y(this,Pe,Ds).call(this,true);a===o&&(a=""),a&&(o=`(?:${o})(?:${a})*?`);let l="";if(this.type==="!"&&n(this,bi))l=(this.isStart()&&!e?Vi:"")+lr;else {let h=this.type==="!"?"))"+(this.isStart()&&!e&&!t?Vi:"")+hr+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&a?")":this.type==="*"&&a?")?":`)${this.type}`;l=r+o+h;}return [l,Ue(o),m(this,q,!!n(this,q)),n(this,Jt)]}},j=new WeakMap,q=new WeakMap,Jt=new WeakMap,L=new WeakMap,W=new WeakMap,de=new WeakMap,Me=new WeakMap,ue=new WeakMap,Ut=new WeakMap,xe=new WeakMap,bi=new WeakMap,Pe=new WeakSet,nn=function(){if(this!==n(this,j))throw new Error("should only call on root");if(n(this,ue))return this;this.toString(),m(this,ue,true);let t;for(;t=n(this,Me).pop();){if(t.type!=="!")continue;let e=t,s=n(e,W);for(;s;){for(let r=n(e,de)+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},we=new WeakSet,ss=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&&ar(S)&&t.charAt(E)==="("){e.push(T),T="";let x=new K(S,e);E=y(g=K,we,ss).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(ar(E)&&t.charAt(c)==="("){u.push(f),f="";let T=new K(E,u);u.push(T),c=y(b=K,we,ss).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,bi,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},Ds=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,Jt,n(this,Jt)||a),s}).filter(e=>!(this.isStart()&&this.isEnd())||!!e).join("|")},on=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)?lr:hr,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+=Js,e=true;continue}o+=xo(c);}return [o,Ue(t),!!e,a]},w(K,we),K),an=(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={})=>(ds(t),!e.nocomment&&t.charAt(0)==="#"?false:new be(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=hn([i]);return t?(t=t.toLowerCase(),s=>e(s)&&s.toLowerCase().endsWith(t)):e},Go=([i,t=""])=>{let e=ln([i]);return t?(t=t.toLowerCase(),s=>e(s)&&s.toLowerCase().endsWith(t)):e},Xo=([i,t=""])=>{let e=ln([i]);return t?s=>e(s)&&s.endsWith(t):e},Yo=([i,t=""])=>{let e=hn([i]);return t?s=>e(s)&&s.endsWith(t):e},hn=([i])=>{let t=i.length;return e=>e.length===t&&!e.startsWith(".")},ln=([i])=>{let t=i.length;return e=>e.length===t&&e!=="."&&e!==".."},cn=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",cr={win32:{sep:"\\"},posix:{sep:"/"}},Ho=cn==="win32"?cr.win32.sep:cr.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 St=(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,St(i,r)),{Minimatch:class extends t.Minimatch{constructor(e,s={}){super(e,St(i,s));}static defaults(e){return t.defaults(St(i,e)).Minimatch}},AST:class extends t.AST{constructor(e,s,r={}){super(e,s,St(i,r));}static fromGlob(e,s={}){return t.AST.fromGlob(e,St(i,s))}},unescape:(e,s={})=>t.unescape(e,St(i,s)),escape:(e,s={})=>t.escape(e,St(i,s)),filter:(e,s={})=>t.filter(e,St(i,s)),defaults:e=>t.defaults(St(i,e)),makeRe:(e,s={})=>t.makeRe(e,St(i,s)),braceExpand:(e,s={})=>t.braceExpand(e,St(i,s)),match:(e,s,r={})=>t.match(e,s,St(i,r)),sep:t.sep,GLOBSTAR:at})};ht.defaults=Zo;var dn=(i,t={})=>(ds(i),t.nobrace||!/\{(?:(?!\{).)*\}/.test(i)?[i]:fo(i,{max:t.braceExpandMax}));ht.braceExpand=dn;var ta=(i,t={})=>new be(i,t).makeRe();ht.makeRe=ta;var ea=(i,t,e={})=>{let s=new be(t,e);return i=i.filter(r=>s.match(r)),s.options.nonull&&!i.length&&i.push(t),i};ht.match=ea;var dr=/[?*]|[+@!]\(.*?\)|\[|\]/,ia=i=>i.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),be=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");ds(i),t=t||{},this.options=t,this.pattern=i,this.platform=t.platform||cn,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]==="?"||!dr.test(r[2]))&&!dr.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 dn(this.pattern,this.options)}parse(i){ds(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=rn.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=rn;ht.Minimatch=be;ht.escape=an;ht.unescape=Ue;var ra=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,un=new Set,Cs=typeof process=="object"&&process?process:{},pn=(i,t,e,s)=>{typeof Cs.emitWarning=="function"?Cs.emitWarning(i,t,e,s):console.error(`[${e}] ${t}: ${i}`);},us=globalThis.AbortController,ur=globalThis.AbortSignal;if(typeof us>"u"){ur=class{constructor(){p(this,"onabort");p(this,"_onabort",[]);p(this,"reason");p(this,"aborted",false);}addEventListener(e,s){this._onabort.push(s);}},us=class{constructor(){p(this,"signal",new ur);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=Cs.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{i&&(i=false,pn("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=>!un.has(i),ae=i=>i&&i===Math.floor(i)&&i>0&&isFinite(i),mn=i=>ae(i)?i<=Math.pow(2,8)?Uint8Array:i<=Math.pow(2,16)?Uint16Array:i<=Math.pow(2,32)?Uint32Array:i<=Number.MAX_SAFE_INTEGER?rs:null:null,rs=class extends Array{constructor(i){super(i),this.fill(0);}},Xt,Be,oa=(Xt=class{constructor(t,e){p(this,"heap");p(this,"length");if(!n(Xt,Be))throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new e(t),this.length=0;}static create(t){let e=mn(t);if(!e)return [];m(Xt,Be,true);let s=new Xt(t,e);return m(Xt,Be,false),s}push(t){this.heap[this.length++]=t;}pop(){return this.heap[--this.length]}},Be=new WeakMap,w(Xt,Be,false),Xt),Mr,xr,Tt,mt,Nt,Oe,Ft,Ge,Xe,kt,$,Lt,z,D,I,rt,ft,it,V,Dt,J,Ct,Pt,gt,yt,Wt,pe,nt,Ye,v,Ps,Ie,Kt,Ei,wt,fn,Ne,He,Si,he,le,Ws,ns,os,k,zs,pi,ce,js,qe,fs=(qe=class{constructor(t){w(this,v);w(this,Tt);w(this,mt);w(this,Nt);w(this,Oe);w(this,Ft);w(this,Ge);w(this,Xe);w(this,kt);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,Lt);w(this,z);w(this,D);w(this,I);w(this,rt);w(this,ft);w(this,it);w(this,V);w(this,Dt);w(this,J);w(this,Ct);w(this,Pt);w(this,gt);w(this,yt);w(this,Wt);w(this,pe);w(this,nt);w(this,Ye);w(this,Ie,()=>{});w(this,Kt,()=>{});w(this,Ei,()=>{});w(this,wt,()=>false);w(this,Ne,t=>{});w(this,He,(t,e,s)=>{});w(this,Si,(t,e,s,r)=>{if(s||r)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0});p(this,Mr,"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,kt,tt??ra),e!==0&&!ae(e))throw new TypeError("max option must be a nonnegative integer");let C=e?mn(e):Array;if(!C)throw new Error("invalid max value: "+e);if(m(this,Tt,e),m(this,mt,b),this.maxEntrySize=E||n(this,mt),this.sizeCalculation=T,this.sizeCalculation){if(!n(this,mt)&&!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,Xe,x),S!==void 0&&typeof S!="function")throw new TypeError("fetchMethod must be a function if specified");if(m(this,Ge,S),m(this,pe,!!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,ft,new C(e)),m(this,it,0),m(this,V,0),m(this,Dt,oa.create(e)),m(this,$,0),m(this,Lt,0),typeof c=="function"&&m(this,Nt,c),typeof u=="function"&&m(this,Oe,u),typeof d=="function"?(m(this,Ft,d),m(this,J,[])):(m(this,Ft,void 0),m(this,J,void 0)),m(this,Wt,!!n(this,Nt)),m(this,Ye,!!n(this,Oe)),m(this,nt,!!n(this,Ft)),this.noDisposeOnSet=!!f,this.noUpdateTTL=!!g,this.noDeleteOnFetchRejection=!!R,this.allowStaleOnFetchRejection=!!_,this.allowStaleOnFetchAbort=!!N,this.ignoreFetchAbort=!!F,this.maxEntrySize!==0){if(n(this,mt)!==0&&!ae(n(this,mt)))throw new TypeError("maxSize must be a positive integer if specified");if(!ae(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");y(this,v,fn).call(this);}if(this.allowStale=!!h,this.noDeleteOnStaleGet=!!A,this.updateAgeOnGet=!!a,this.updateAgeOnHas=!!l,this.ttlResolution=ae(r)||r===0?r:1,this.ttlAutopurge=!!o,this.ttl=s||0,this.ttl){if(!ae(this.ttl))throw new TypeError("ttl must be a positive integer if specified");y(this,v,Ps).call(this);}if(n(this,Tt)===0&&this.ttl===0&&n(this,mt)===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!n(this,Tt)&&!n(this,mt)){let G="LRU_CACHE_UNBOUNDED";na(G)&&(un.add(G),pn("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",G,qe));}}get perf(){return n(this,kt)}static unsafeExposeInternals(t){return {starts:n(t,Pt),ttls:n(t,gt),autopurgeTimers:n(t,yt),sizes:n(t,Ct),keyMap:n(t,z),keyList:n(t,D),valList:n(t,I),next:n(t,rt),prev:n(t,ft),get head(){return n(t,it)},get tail(){return n(t,V)},free:n(t,Dt),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,os).call(a,e,s,r,o)},moveToTail:e=>{var s;return y(s=t,v,pi).call(s,e)},indexes:e=>{var s;return y(s=t,v,he).call(s,e)},rindexes:e=>{var s;return y(s=t,v,le).call(s,e)},isStale:e=>{var s;return n(s=t,wt).call(s,e)}}}get max(){return n(this,Tt)}get maxSize(){return n(this,mt)}get calculatedSize(){return n(this,Lt)}get size(){return n(this,$)}get fetchMethod(){return n(this,Ge)}get memoMethod(){return n(this,Xe)}get dispose(){return n(this,Nt)}get onInsert(){return n(this,Oe)}get disposeAfter(){return n(this,Ft)}getRemainingTTL(t){return n(this,z).has(t)?1/0:0}*entries(){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]]);}*rentries(){for(let t of y(this,v,le).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,he).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,le).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,he).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,le).call(this))n(this,I)[t]!==void 0&&!y(this,v,k).call(this,n(this,I)[t])&&(yield n(this,I)[t]);}[(xr=Symbol.iterator,Mr=Symbol.toStringTag,xr)](){return this.entries()}find(t,e={}){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;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,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);}}rforEach(t,e=this){for(let s of y(this,v,le).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,le).call(this,{allowStale:true}))n(this,wt).call(this,e)&&(y(this,v,ce).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,gt)&&n(this,Pt)){let a=n(this,gt)[e],l=n(this,Pt)[e];if(a&&l){let h=a-(n(this,kt).now()-l);o.ttl=h,o.start=Date.now();}}return n(this,Ct)&&(o.size=n(this,Ct)[e]),o}dump(){let t=[];for(let e of y(this,v,he).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,gt)&&n(this,Pt)){a.ttl=n(this,gt)[e];let l=n(this,kt).now()-n(this,Pt)[e];a.start=Math.floor(Date.now()-l);}n(this,Ct)&&(a.size=n(this,Ct)[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,kt).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,Si).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,ce).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,Dt).length!==0?n(this,Dt).pop():n(this,$)===n(this,Tt)?y(this,v,ns).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,ft)[d]=n(this,V),m(this,V,d),qi(this,$)._++,n(this,He).call(this,d,u,h),h&&(h.set="add"),c=false,n(this,Ye)&&((f=n(this,Oe))==null||f.call(this,e,t,"add"));else {y(this,v,pi).call(this,d);let T=n(this,I)[d];if(e!==T){if(n(this,pe)&&y(this,v,k).call(this,T)){T.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:S}=T;S!==void 0&&!a&&(n(this,Wt)&&((g=n(this,Nt))==null||g.call(this,S,t,"set")),n(this,nt)&&n(this,J)?.push([S,t,"set"]));}else a||(n(this,Wt)&&((b=n(this,Nt))==null||b.call(this,T,t,"set")),n(this,nt)&&n(this,J)?.push([T,t,"set"]));if(n(this,Ne).call(this,d),n(this,He).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,Ye)&&this.onInsert?.(e,t,e===T?"update":"replace");}if(r!==0&&!n(this,gt)&&y(this,v,Ps).call(this),n(this,gt)&&(c||n(this,Ei).call(this,d,r,o),h&&n(this,Kt).call(this,h,d)),!a&&n(this,nt)&&n(this,J)){let T=n(this,J),S;for(;S=T?.shift();)(E=n(this,Ft))==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,ns).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,Ft))==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,wt).call(this,o))r&&(r.has="stale",n(this,Kt).call(this,r,o));else return s&&n(this,Ie).call(this,o),r&&(r.has="hit",n(this,Kt).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,wt).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,pe))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,os).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,wt).call(this,A);if(!T&&!N)return S&&(S.fetch="hit"),y(this,v,pi).call(this,A),r&&n(this,Ie).call(this,A),S&&n(this,Kt).call(this,S,A),_;let F=y(this,v,os).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,Xe);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,Kt).call(this,a,l),n(this,wt).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,ce).call(this,t,"expire"),a&&s&&(a.returnedStale=true),s?h:void 0)):(a&&(a.get="hit"),c?h.__staleWhileFetching:(y(this,v,pi).call(this,l),r&&n(this,Ie).call(this,l),h))}else a&&(a.get="miss");}delete(t){return y(this,v,ce).call(this,t,"delete")}clear(){return y(this,v,js).call(this,"delete")}},Tt=new WeakMap,mt=new WeakMap,Nt=new WeakMap,Oe=new WeakMap,Ft=new WeakMap,Ge=new WeakMap,Xe=new WeakMap,kt=new WeakMap,$=new WeakMap,Lt=new WeakMap,z=new WeakMap,D=new WeakMap,I=new WeakMap,rt=new WeakMap,ft=new WeakMap,it=new WeakMap,V=new WeakMap,Dt=new WeakMap,J=new WeakMap,Ct=new WeakMap,Pt=new WeakMap,gt=new WeakMap,yt=new WeakMap,Wt=new WeakMap,pe=new WeakMap,nt=new WeakMap,Ye=new WeakMap,v=new WeakSet,Ps=function(){let t=new rs(n(this,Tt)),e=new rs(n(this,Tt));m(this,gt,t),m(this,Pt,e);let s=this.ttlAutopurge?new Array(n(this,Tt)):void 0;m(this,yt,s),m(this,Ei,(a,l,h=n(this,kt).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,wt).call(this,a)&&y(this,v,ce).call(this,n(this,D)[a],"expire");},l+1);c.unref&&c.unref(),s[a]=c;}}),m(this,Ie,a=>{e[a]=t[a]!==0?n(this,kt).now():0;}),m(this,Kt,(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,kt).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,wt,a=>{let l=e[a],h=t[a];return !!h&&!!l&&(r||o())-l>h});},Ie=new WeakMap,Kt=new WeakMap,Ei=new WeakMap,wt=new WeakMap,fn=function(){let t=new rs(n(this,Tt));m(this,Lt,0),m(this,Ct,t),m(this,Ne,e=>{m(this,Lt,n(this,Lt)-t[e]),t[e]=0;}),m(this,Si,(e,s,r,o)=>{if(y(this,v,k).call(this,s))return 0;if(!ae(r))if(o){if(typeof o!="function")throw new TypeError("sizeCalculation must be a function");if(r=o(s,e),!ae(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,He,(e,s,r)=>{if(t[e]=s,n(this,mt)){let o=n(this,mt)-t[e];for(;n(this,Lt)>o;)y(this,v,ns).call(this,true);}m(this,Lt,n(this,Lt)+t[e]),r&&(r.entrySize=s,r.totalCalculatedSize=n(this,Lt));});},Ne=new WeakMap,He=new WeakMap,Si=new WeakMap,he=function*({allowStale:t=this.allowStale}={}){if(n(this,$))for(let e=n(this,V);!(!y(this,v,Ws).call(this,e)||((t||!n(this,wt).call(this,e))&&(yield e),e===n(this,it)));)e=n(this,ft)[e];},le=function*({allowStale:t=this.allowStale}={}){if(n(this,$))for(let e=n(this,it);!(!y(this,v,Ws).call(this,e)||((t||!n(this,wt).call(this,e))&&(yield e),e===n(this,V)));)e=n(this,rt)[e];},Ws=function(t){return t!==void 0&&n(this,z).get(n(this,D)[t])===t},ns=function(t){var o;let e=n(this,it),s=n(this,D)[e],r=n(this,I)[e];return n(this,pe)&&y(this,v,k).call(this,r)?r.__abortController.abort(new Error("evicted")):(n(this,Wt)||n(this,nt))&&(n(this,Wt)&&((o=n(this,Nt))==null||o.call(this,r,s,"evict")),n(this,nt)&&n(this,J)?.push([r,s,"evict"])),n(this,Ne).call(this,e),n(this,yt)?.[e]&&(clearTimeout(n(this,yt)[e]),n(this,yt)[e]=void 0),t&&(n(this,D)[e]=void 0,n(this,I)[e]=void 0,n(this,Dt).push(e)),n(this,$)===1?(m(this,it,m(this,V,0)),n(this,Dt).length=0):m(this,it,n(this,rt)[e]),n(this,z).delete(s),qi(this,$)._--,e},os=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 us,{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,ce).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,ce).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,Ge))==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,pe))return false;let e=t;return !!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof us},zs=function(t,e){n(this,ft)[e]=t,n(this,rt)[t]=e;},pi=function(t){t!==n(this,V)&&(t===n(this,it)?m(this,it,n(this,rt)[t]):y(this,v,zs).call(this,n(this,ft)[t],n(this,rt)[t]),y(this,v,zs).call(this,n(this,V),t),m(this,V,t));},ce=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,yt)?.[a]&&(clearTimeout(n(this,yt)?.[a]),n(this,yt)[a]=void 0),s=true,n(this,$)===1)y(this,v,js).call(this,e);else {n(this,Ne).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,Wt)||n(this,nt))&&(n(this,Wt)&&((r=n(this,Nt))==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,ft)[a]);else if(a===n(this,it))m(this,it,n(this,rt)[a]);else {let h=n(this,ft)[a];n(this,rt)[h]=n(this,rt)[a];let c=n(this,rt)[a];n(this,ft)[c]=n(this,ft)[a];}qi(this,$)._--,n(this,Dt).push(a);}}if(n(this,nt)&&n(this,J)?.length){let a=n(this,J),l;for(;l=a?.shift();)(o=n(this,Ft))==null||o.call(this,...l);}return s},js=function(t){var e,s;for(let r of y(this,v,le).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,Wt)&&((e=n(this,Nt))==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,gt)&&n(this,Pt)){n(this,gt).fill(0),n(this,Pt).fill(0);for(let r of n(this,yt)??[])r!==void 0&&clearTimeout(r);n(this,yt)?.fill(void 0);}if(n(this,Ct)&&n(this,Ct).fill(0),m(this,it,0),m(this,V,0),n(this,Dt).length=0,m(this,Lt,0),m(this,$,0),n(this,nt)&&n(this,J)){let r=n(this,J),o;for(;o=r?.shift();)(s=n(this,Ft))==null||s.call(this,...o);}},qe),pr=typeof process=="object"&&process?process:{stdout:null,stderr:null},Ea=i=>!!i&&typeof i=="object"&&(i instanceof ps||i instanceof gn||Sa(i)||va(i)),Sa=i=>!!i&&typeof i=="object"&&i instanceof EventEmitter&&typeof i.pipe=="function"&&i.pipe!==gn.Writable.prototype.pipe,va=i=>!!i&&typeof i=="object"&&i instanceof EventEmitter&&typeof i.write=="function"&&typeof i.end=="function",qt=Symbol("EOF"),Vt=Symbol("maybeEmitEnd"),oe=Symbol("emittedEnd"),Ji=Symbol("emittingEnd"),ai=Symbol("emittedError"),Ki=Symbol("closed"),mr=Symbol("read"),Qi=Symbol("flush"),fr=Symbol("flushChunk"),Ot=Symbol("encoding"),je=Symbol("decoder"),X=Symbol("flowing"),hi=Symbol("paused"),$e=Symbol("resume"),Y=Symbol("buffer"),st=Symbol("pipes"),H=Symbol("bufferLength"),xs=Symbol("bufferPush"),Zi=Symbol("bufferShift"),et=Symbol("objectMode"),P=Symbol("destroyed"),Os=Symbol("error"),Is=Symbol("emitData"),gr=Symbol("emitEnd"),Ns=Symbol("emitEnd2"),jt=Symbol("async"),Fs=Symbol("abort"),ts=Symbol("aborted"),li=Symbol("signal"),Re=Symbol("dataListeners"),pt=Symbol("discarded"),ci=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),yn=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[$e](),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 yn{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",Or,Ir,Nr,Fr,kr,Lr,Dr,Cr,Pr,Wr,zr,jr,$r,Ur,Br,Gr,Xr,Yr,Hr,ps=class extends EventEmitter{constructor(...t){let e=t[0]||{};super();p(this,Hr,false);p(this,Yr,false);p(this,Xr,[]);p(this,Gr,[]);p(this,Br);p(this,Ur);p(this,$r);p(this,jr);p(this,zr,false);p(this,Wr,false);p(this,Pr,false);p(this,Cr,false);p(this,Dr,null);p(this,Lr,0);p(this,kr,false);p(this,Fr);p(this,Nr,false);p(this,Ir,0);p(this,Or,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[Ot]=null):Oa(e)?(this[Ot]=e.encoding,this[et]=false):(this[et]=false,this[Ot]=null),this[jt]=!!e.async,this[je]=this[Ot]?new StringDecoder(this[Ot]):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[li]=s,s.aborted?this[Fs]():s.addEventListener("abort",()=>this[Fs]()));}get bufferLength(){return this[H]}get encoding(){return this[Ot]}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[jt]}set async(t){this[jt]=this[jt]||!!t;}[(Hr=X,Yr=hi,Xr=st,Gr=Y,Br=et,Ur=Ot,$r=jt,jr=je,zr=qt,Wr=oe,Pr=Ji,Cr=Ki,Dr=ai,Lr=H,kr=P,Fr=li,Nr=ts,Ir=Re,Or=pt,Fs)](){this[ts]=true,this.emit("abort",this[li]?.reason),this.destroy(this[li]?.reason);}get aborted(){return this[ts]}set aborted(t){}write(t,e,s){if(this[ts])return false;if(this[qt])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[jt]?ci: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[Qi](true),this[X]?this.emit("data",t):this[xs](t),this[H]!==0&&this.emit("readable"),s&&r(s),this[X]):t.length?(typeof t=="string"&&!(e===this[Ot]&&!this[je]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[Ot]&&(t=this[je].write(t)),this[X]&&this[H]!==0&&this[Qi](true),this[X]?this.emit("data",t):this[xs](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[pt]=false,this[H]===0||t===0||t&&t>this[H])return this[Vt](),null;this[et]&&(t=null),this[Y].length>1&&!this[et]&&(this[Y]=[this[Ot]?this[Y].join(""):Buffer.concat(this[Y],this[H])]);let e=this[mr](t||null,this[Y][0]);return this[Vt](),e}[mr](t,e){if(this[et])this[Zi]();else {let s=e;t===s.length||t===null?this[Zi]():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[qt]&&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[qt]=true,this.writable=false,(this[X]||!this[hi])&&this[Vt](),this}[$e](){this[P]||(!this[Re]&&!this[st].length&&(this[pt]=true),this[hi]=false,this[X]=true,this.emit("resume"),this[Y].length?this[Qi]():this[qt]?this[Vt]():this.emit("drain"));}resume(){return this[$e]()}pause(){this[X]=false,this[hi]=true,this[pt]=false;}get destroyed(){return this[P]}get flowing(){return this[X]}get paused(){return this[hi]}[xs](t){this[et]?this[H]+=1:this[H]+=t.length,this[Y].push(t);}[Zi](){return this[et]?this[H]-=1:this[H]-=this[Y][0].length,this[Y].shift()}[Qi](t=false){do;while(this[fr](this[Zi]())&&this[Y].length);!t&&!this[Y].length&&!this[qt]&&this.emit("drain");}[fr](t){return this.emit("data",t),this[X]}pipe(t,e){if(this[P])return t;this[pt]=false;let s=this[oe];return e=e||{},t===pr.stdout||t===pr.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 yn(this,t,e)),this[jt]?ci(()=>this[$e]()):this[$e]()),t}unpipe(t){let e=this[st].find(s=>s.dest===t);e&&(this[st].length===1?(this[X]&&this[Re]===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[pt]=false,this[Re]++,!this[st].length&&!this[X]&&this[$e]();else if(t==="readable"&&this[H]!==0)super.emit("readable");else if(Ra(t)&&this[oe])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[ai]){let r=e;this[jt]?ci(()=>r.call(this,this[ai])):r.call(this,this[ai]);}return s}removeListener(t,e){return this.off(t,e)}off(t,e){let s=super.off(t,e);return t==="data"&&(this[Re]=this.listeners("data").length,this[Re]===0&&!this[pt]&&!this[st].length&&(this[X]=false)),s}removeAllListeners(t){let e=super.removeAllListeners(t);return (t==="data"||t===void 0)&&(this[Re]=0,!this[pt]&&!this[st].length&&(this[X]=false)),e}get emittedEnd(){return this[oe]}[Vt](){!this[Ji]&&!this[oe]&&!this[P]&&this[Y].length===0&&this[qt]&&(this[Ji]=true,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ki]&&this.emit("close"),this[Ji]=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[jt]?(ci(()=>this[Is](s)),true):this[Is](s);if(t==="end")return this[gr]();if(t==="close"){if(this[Ki]=true,!this[oe]&&!this[P])return false;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[ai]=s,super.emit(Os,s);let o=!this[li]||this.listeners("error").length?super.emit("error",s):false;return this[Vt](),o}else if(t==="resume"){let o=super.emit("resume");return this[Vt](),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[Vt](),r}[Is](t){for(let s of this[st])s.dest.write(t)===false&&this.pause();let e=this[pt]?false:super.emit("data",t);return this[Vt](),e}[gr](){return this[oe]?false:(this[oe]=true,this.readable=false,this[jt]?(ci(()=>this[Ns]()),true):this[Ns]())}[Ns](){if(this[je]){let e=this[je].end();if(e){for(let s of this[st])s.dest.write(e);this[pt]||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[Ot]?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[pt]=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[qt])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[qt]});},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[pt]=false;let t=false,e=()=>(this.pause(),this.off(Os,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(Os,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[pt]=true,this[Y].length=0,this[H]=0;let e=this;return typeof e.close=="function"&&!this[Ki]&&e.close(),t?this.emit("error",t):this.emit(P),this}static get isStream(){return Ea}},Ia=realpathSync.native,mi={lstatSync:lstatSync,readdir:readdir$1,readdirSync:readdirSync,readlinkSync:readlinkSync,realpathSync:Ia,promises:{lstat:lstat,readdir:readdir,readlink:readlink,realpath:realpath}},wn=i=>!i||i===mi||i===ma?mi:{...mi,...i,promises:{...mi.promises,...i.promises||{}}},bn=/^\\\\\?\\([a-z]:)\\?$/i,Na=i=>i.replace(/\//g,"\\").replace(bn,"$1\\"),Fa=/[\\\/]/,Rt=0,En=1,Sn=2,$t=4,vn=6,Tn=8,_e=10,Rn=12,vt=15,di=~vt,ks=16,yr=32,fi=64,It=128,es=256,as=512,wr=fi|It|as,ka=1023,Ls=i=>i.isFile()?Tn:i.isDirectory()?$t:i.isSymbolicLink()?_e:i.isCharacterDevice()?Sn:i.isBlockDevice()?vn:i.isSocket()?Rn:i.isFIFO()?En:Rt,br=new fs({max:2**12}),gi=i=>{let t=br.get(i);if(t)return t;let e=i.normalize("NFKD");return br.set(i,e),e},Er=new fs({max:2**12}),is=i=>{let t=Er.get(i);if(t)return t;let e=gi(i.toLowerCase());return Er.set(i,e),e},Sr=class extends fs{constructor(){super({max:256});}},La=class extends fs{constructor(i=16*1024){super({maxSize:i,sizeCalculation:t=>t.length+1});}},_n=Symbol("PathScurry setAsCwd"),ot,vi,Ti,Ri,_i,Ai,Mi,xi,Oi,Ii,Ni,Fi,ki,Li,Di,Ci,Pi,Wi,zi,me,Fe,Bt,Qt,Zt,te,O,ke,ee,Gt,M,Us,hs,yi,Bs,Gs,wi,ls,Xs,Ys,cs,An,Mn,xn,Hs,Ve,Je,On,Le,qr,ct=(qr=class{constructor(i,t=Rt,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,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,zi);w(this,me);w(this,Fe);w(this,Bt);w(this,Qt);w(this,Zt);w(this,te);w(this,O);w(this,ke);w(this,ee);w(this,Gt);w(this,Ve,[]);w(this,Je,false);w(this,Le);this.name=i,m(this,me,r?is(i):gi(i)),m(this,O,t&ka),this.nocase=r,this.roots=s,this.root=e||this,m(this,ke,o),m(this,Bt,a.fullpath),m(this,Zt,a.relative),m(this,te,a.relativePosix),this.parent=a.parent,this.parent?m(this,ot,n(this.parent,ot)):m(this,ot,wn(a.fs));}get dev(){return n(this,vi)}get mode(){return n(this,Ti)}get nlink(){return n(this,Ri)}get uid(){return n(this,_i)}get gid(){return n(this,Ai)}get rdev(){return n(this,Mi)}get blksize(){return n(this,xi)}get ino(){return n(this,Oi)}get size(){return n(this,Ii)}get blocks(){return n(this,Ni)}get atimeMs(){return n(this,Fi)}get mtimeMs(){return n(this,ki)}get ctimeMs(){return n(this,Li)}get birthtimeMs(){return n(this,Di)}get atime(){return n(this,Ci)}get mtime(){return n(this,Pi)}get ctime(){return n(this,Wi)}get birthtime(){return n(this,zi)}get parentPath(){return (this.parent||this).fullpath()}get path(){return this.parentPath}depth(){return n(this,Fe)!==void 0?n(this,Fe):this.parent?m(this,Fe,this.parent.depth()+1):m(this,Fe,0)}childrenCache(){return n(this,ke)}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,Us).call(s,e):y(this,M,Us).call(this,e)}children(){let i=n(this,ke).get(this);if(i)return i;let t=Object.assign([],{provisional:0});return n(this,ke).set(this,t),m(this,O,n(this,O)&~ks),t}child(i,t){if(i===""||i===".")return this;if(i==="..")return this.parent||this;let e=this.children(),s=this.nocase?is(i):gi(i);for(let l of e)if(n(l,me)===s)return l;let r=this.parent?this.sep:"",o=n(this,Bt)?n(this,Bt)+r+i:void 0,a=this.newChild(i,Rt,{...t,parent:this,fullpath:o});return this.canReaddir()||m(a,O,n(a,O)|It),e.push(a),a}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.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,te)!==void 0)return n(this,te);let i=this.name,t=this.parent;if(!t)return m(this,te,this.fullpathPosix());let e=t.relativePosix();return e+(!e||!t.parent?"":"/")+i}fullpath(){if(n(this,Bt)!==void 0)return n(this,Bt);let i=this.name,t=this.parent;if(!t)return m(this,Bt,this.name);let e=t.fullpath()+(t.parent?this.sep:"")+i;return m(this,Bt,e)}fullpathPosix(){if(n(this,Qt)!==void 0)return n(this,Qt);if(this.sep==="/")return m(this,Qt,this.fullpath());if(!this.parent){let s=this.fullpath().replace(/\\/g,"/");return /^[a-z]:\//i.test(s)?m(this,Qt,`//?/${s}`):m(this,Qt,s)}let i=this.parent,t=i.fullpathPosix(),e=t+(!t||!i.parent?"":"/")+this.name;return m(this,Qt,e)}isUnknown(){return (n(this,O)&vt)===Rt}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)&vt)===Tn}isDirectory(){return (n(this,O)&vt)===$t}isCharacterDevice(){return (n(this,O)&vt)===Sn}isBlockDevice(){return (n(this,O)&vt)===vn}isFIFO(){return (n(this,O)&vt)===En}isSocket(){return (n(this,O)&vt)===Rn}isSymbolicLink(){return (n(this,O)&_e)===_e}lstatCached(){return n(this,O)&yr?this:void 0}readlinkCached(){return n(this,ee)}realpathCached(){return n(this,Gt)}readdirCached(){let i=this.children();return i.slice(0,i.provisional)}canReadlink(){if(n(this,ee))return true;if(!this.parent)return false;let i=n(this,O)&vt;return !(i!==Rt&&i!==_e||n(this,O)&es||n(this,O)&It)}calledReaddir(){return !!(n(this,O)&ks)}isENOENT(){return !!(n(this,O)&It)}isNamed(i){return this.nocase?n(this,me)===is(i):n(this,me)===gi(i)}async readlink(){let i=n(this,ee);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,ee,e)}catch(t){y(this,M,Ys).call(this,t.code);return}}readlinkSync(){let i=n(this,ee);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,ee,e)}catch(t){y(this,M,Ys).call(this,t.code);return}}async lstat(){if((n(this,O)&It)===0)try{return y(this,M,Hs).call(this,await n(this,ot).promises.lstat(this.fullpath())),this}catch(i){y(this,M,Xs).call(this,i.code);}}lstatSync(){if((n(this,O)&It)===0)try{return y(this,M,Hs).call(this,n(this,ot).lstatSync(this.fullpath())),this}catch(i){y(this,M,Xs).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,Ve).push(i),n(this,Je))return;m(this,Je,true);let s=this.fullpath();n(this,ot).readdir(s,{withFileTypes:true},(r,o)=>{if(r)y(this,M,ls).call(this,r.code),e.provisional=0;else {for(let a of o)y(this,M,cs).call(this,a,e);y(this,M,hs).call(this,e);}y(this,M,On).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,Le))await n(this,Le);else {let e=()=>{};m(this,Le,new Promise(s=>e=s));try{for(let s of await n(this,ot).promises.readdir(t,{withFileTypes:!0}))y(this,M,cs).call(this,s,i);y(this,M,hs).call(this,i);}catch(s){y(this,M,ls).call(this,s.code),i.provisional=0;}m(this,Le,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,cs).call(this,e,i);y(this,M,hs).call(this,i);}catch(e){y(this,M,ls).call(this,e.code),i.provisional=0;}return i.slice(0,i.provisional)}canReaddir(){if(n(this,O)&wr)return false;let i=vt&n(this,O);return i===Rt||i===$t||i===_e}shouldWalk(i,t){return (n(this,O)&$t)===$t&&!(n(this,O)&wr)&&!i.has(this)&&(!t||t(this))}async realpath(){if(n(this,Gt))return n(this,Gt);if(!((as|es|It)&n(this,O)))try{let i=await n(this,ot).promises.realpath(this.fullpath());return m(this,Gt,this.resolve(i))}catch{y(this,M,Gs).call(this);}}realpathSync(){if(n(this,Gt))return n(this,Gt);if(!((as|es|It)&n(this,O)))try{let i=n(this,ot).realpathSync(this.fullpath());return m(this,Gt,this.resolve(i))}catch{y(this,M,Gs).call(this);}}[_n](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,Zt,e.join(this.sep)),m(s,te,e.join("/")),s=s.parent,e.push("..");for(s=i;s&&s.parent&&!t.has(s);)m(s,Zt,void 0),m(s,te,void 0),s=s.parent;}},ot=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,zi=new WeakMap,me=new WeakMap,Fe=new WeakMap,Bt=new WeakMap,Qt=new WeakMap,Zt=new WeakMap,te=new WeakMap,O=new WeakMap,ke=new WeakMap,ee=new WeakMap,Gt=new WeakMap,M=new WeakSet,Us=function(i){let t=this;for(let e of i)t=t.child(e);return t},hs=function(i){var t;m(this,O,n(this,O)|ks);for(let e=i.provisional;e<i.length;e++){let s=i[e];s&&y(t=s,M,yi).call(t);}},yi=function(){n(this,O)&It||(m(this,O,(n(this,O)|It)&di),y(this,M,Bs).call(this));},Bs=function(){var t;let i=this.children();i.provisional=0;for(let e of i)y(t=e,M,yi).call(t);},Gs=function(){m(this,O,n(this,O)|as),y(this,M,wi).call(this);},wi=function(){if(n(this,O)&fi)return;let i=n(this,O);(i&vt)===$t&&(i&=di),m(this,O,i|fi),y(this,M,Bs).call(this);},ls=function(i=""){i==="ENOTDIR"||i==="EPERM"?y(this,M,wi).call(this):i==="ENOENT"?y(this,M,yi).call(this):this.children().provisional=0;},Xs=function(i=""){var t;i==="ENOTDIR"?y(t=this.parent,M,wi).call(t):i==="ENOENT"&&y(this,M,yi).call(this);},Ys=function(i=""){var e;let t=n(this,O);t|=es,i==="ENOENT"&&(t|=It),(i==="EINVAL"||i==="UNKNOWN")&&(t&=di),m(this,O,t),i==="ENOTDIR"&&this.parent&&y(e=this.parent,M,wi).call(e);},cs=function(i,t){return y(this,M,Mn).call(this,i,t)||y(this,M,An).call(this,i,t)},An=function(i,t){let e=Ls(i),s=this.newChild(i.name,e,{parent:this}),r=n(s,O)&vt;return r!==$t&&r!==_e&&r!==Rt&&m(s,O,n(s,O)|fi),t.unshift(s),t.provisional++,s},Mn=function(i,t){for(let e=t.provisional;e<t.length;e++){let s=t[e];if((this.nocase?is(i.name):gi(i.name))===n(s,me))return y(this,M,xn).call(this,i,s,e,t)}},xn=function(i,t,e,s){let r=t.name;return m(t,O,n(t,O)&di|Ls(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},Hs=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,Ci,t),m(this,Fi,e),m(this,zi,s),m(this,Di,r),m(this,xi,o),m(this,Ni,a),m(this,Wi,l),m(this,Li,h),m(this,vi,c),m(this,Ai,u),m(this,Oi,d),m(this,Ti,f),m(this,Pi,g),m(this,ki,b),m(this,Ri,E),m(this,Mi,T),m(this,Ii,S),m(this,_i,x);let R=Ls(i);m(this,O,n(this,O)&di|R|yr),R!==Rt&&R!==$t&&R!==_e&&m(this,O,n(this,O)|fi);},Ve=new WeakMap,Je=new WeakMap,On=function(i){m(this,Je,false);let t=n(this,Ve).slice();n(this,Ve).length=0,t.forEach(e=>e(null,i));},Le=new WeakMap,qr),In=class Nn extends ct{constructor(e,s=Rt,r,o,a,l,h){super(e,s,r,o,a,l,h);p(this,"sep","\\");p(this,"splitSep",Fa);}newChild(e,s=Rt,r={}){return new Nn(e,s,this.root,this.roots,this.nocase,this.childrenCache(),r)}getRootString(e){return 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 Qs(e,this).root}sameRoot(e,s=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(bn,"$1\\"),e===s}},Fn=class kn extends ct{constructor(e,s=Rt,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=Rt,r={}){return new kn(e,s,this.root,this.roots,this.nocase,this.childrenCache(),r)}},Ke,Qe,ji,$i,Vr,Ln=(Vr=class{constructor(i=process.cwd(),t,e,{nocase:s,childrenCacheSize:r=16*1024,fs:o=mi}={}){p(this,"root");p(this,"rootPath");p(this,"roots");p(this,"cwd");w(this,Ke);w(this,Qe);w(this,ji);p(this,"nocase");w(this,$i);m(this,$i,wn(o)),(i instanceof URL||i.startsWith("file://"))&&(i=fileURLToPath(i));let a=t.resolve(i);this.roots=Object.create(null),this.rootPath=this.parseRootPath(a),m(this,Ke,new Sr),m(this,Qe,new Sr),m(this,ji,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,$i)),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,ji)}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,Ke).get(t);if(e!==void 0)return e;let s=this.cwd.resolve(t).fullpath();return n(this,Ke).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,Qe).get(t);if(e!==void 0)return e;let s=this.cwd.resolve(t).fullpathPosix();return n(this,Qe).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 ct||(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 ct||(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 ct||(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 ct||(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 ct||(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 ct||(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 ct||(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 ct||(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 ct||(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 ct||(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 ct||(t=i,i=this.cwd);let{withFileTypes:e=true,follow:s=false,filter:r,walkFilter:o}=t,a=new ps({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 ct||(t=i,i=this.cwd);let{withFileTypes:e=true,follow:s=false,filter:r,walkFilter:o}=t,a=new ps({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[_n](t);}},Ke=new WeakMap,Qe=new WeakMap,ji=new WeakMap,$i=new WeakMap,Vr),Qs=class extends Ln{constructor(t=process.cwd(),e={}){let{nocase:s=true}=e;super(t,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 win32.parse(t).root.toUpperCase()}newRoot(t){return new In(this.rootPath,$t,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")||t.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(t)}},Zs=class extends Ln{constructor(t=process.cwd(),e={}){let{nocase:s=false}=e;super(t,posix,"/",{...e,nocase:s});p(this,"sep","/");this.nocase=s;}parseRootPath(t){return "/"}newRoot(t){return new Fn(this.rootPath,$t,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")}},Dn=class extends Zs{constructor(i=process.cwd(),t={}){let{nocase:e=true}=t;super(i,{...t,nocase:e});}};process.platform==="win32"?In:Fn;var Da=process.platform==="win32"?Qs:process.platform==="darwin"?Dn:Zs,Ca=i=>i.length>=1,Pa=i=>i.length>=1,Wa=Symbol.for("nodejs.util.inspect.custom"),U,dt,B,De,zt,Ui,fe,ge,ye,Ze,ti,Cn=(ti=class{constructor(t,e,s,r){w(this,U);w(this,dt);w(this,B);p(this,"length");w(this,De);w(this,zt);w(this,Ui);w(this,fe);w(this,ge);w(this,ye);w(this,Ze,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,dt,e),m(this,B,s),m(this,De,r),n(this,B)===0){if(this.isUNC()){let[o,a,l,h,...c]=n(this,U),[u,d,f,g,...b]=n(this,dt);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,dt,[T,...b]),this.length=n(this,U).length;}else if(this.isDrive()||this.isAbsolute()){let[o,...a]=n(this,U),[l,...h]=n(this,dt);a[0]===""&&(a.shift(),h.shift());let c=o+"/",u=l+"/";m(this,U,[c,...a]),m(this,dt,[u,...h]),this.length=n(this,U).length;}}}[Wa](){return "Pattern <"+n(this,dt).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,Ui,n(this,Ui)||(n(this,B)===0?this.isAbsolute()?n(this,dt)[0]+n(this,dt).slice(1).join("/"):n(this,dt).join("/"):n(this,dt).slice(n(this,B)).join("/")))}hasMore(){return this.length>n(this,B)+1}rest(){return n(this,zt)!==void 0?n(this,zt):this.hasMore()?(m(this,zt,new ti(n(this,U),n(this,dt),n(this,B)+1,n(this,De))),m(n(this,zt),ye,n(this,ye)),m(n(this,zt),ge,n(this,ge)),m(n(this,zt),fe,n(this,fe)),n(this,zt)):m(this,zt,null)}isUNC(){let t=n(this,U);return n(this,ge)!==void 0?n(this,ge):m(this,ge,n(this,De)==="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,fe)!==void 0?n(this,fe):m(this,fe,n(this,De)==="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,ye)!==void 0?n(this,ye):m(this,ye,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,Ze))}markFollowGlobstar(){return n(this,B)===0||!this.isGlobstar()||!n(this,Ze)?false:(m(this,Ze,false),true)}},U=new WeakMap,dt=new WeakMap,B=new WeakMap,De=new WeakMap,zt=new WeakMap,Ui=new WeakMap,fe=new WeakMap,ge=new WeakMap,ye=new WeakMap,Ze=new WeakMap,ti),za=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",vr=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 be(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 Cn(s,r,0,this.platform),a=new be(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 Pn{constructor(t=new Map){p(this,"store");this.store=t;}copy(){return new Pn(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())}},Tr=class Wn{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 Wn(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 vr([i],t):Array.isArray(i)?new vr(i,t):i,ei,ie,Ce,_t,Ae,qs,Jr,zn=(Jr=class{constructor(i,t,e){w(this,_t);p(this,"path");p(this,"patterns");p(this,"opts");p(this,"seen",new Set);p(this,"paused",false);p(this,"aborted",false);w(this,ei,[]);w(this,ie);w(this,Ce);p(this,"signal");p(this,"maxDepth");p(this,"includeChildMatches");if(this.patterns=i,this.path=t,this.opts=e,m(this,Ce,!e.posix&&e.platform==="win32"?"\\":"/"),this.includeChildMatches=e.includeChildMatches!==false,(e.ignore||!this.includeChildMatches)&&(m(this,ie,Ba(e.ignore??[],e)),!this.includeChildMatches&&typeof n(this,ie).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,ei).length=0;}));}pause(){this.paused=true;}resume(){if(this.signal?.aborted)return;this.paused=false;let i;for(;!this.paused&&(i=n(this,ei).shift());)i();}onResume(i){this.signal?.aborted||(this.paused?n(this,ei).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,_t,Ae).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,_t,Ae).call(this,i))return;if(!this.includeChildMatches&&n(this,ie)?.add){let r=`${i.relativePosix()}/**`;n(this,ie).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,Ce):"";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,Ce))?"."+n(this,Ce):"";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 Tr(this.opts),e);}walkCB2(i,t,e,s){if(y(this,_t,qs).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,_t,Ae).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,_t,Ae).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 Tr(this.opts),e);}walkCB2Sync(i,t,e,s){if(y(this,_t,qs).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,_t,Ae).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,_t,Ae).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();}},ei=new WeakMap,ie=new WeakMap,Ce=new WeakMap,_t=new WeakSet,Ae=function(i){return this.seen.has(i)||!!n(this,ie)?.ignored?.(i)},qs=function(i){return !!n(this,ie)?.childrenIgnored?.(i)},Jr),Rr=class extends zn{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}},_r=class extends zn{constructor(t,e,s){super(t,e,s);p(this,"results");this.results=new ps({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",We=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=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"?Qs:t.platform==="darwin"?Dn:t.platform?Zs: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 be(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 Cn(l,c,0,this.platform)});}async walk(){return [...await 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}).walk()]}walkSync(){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}).walkSync()]}stream(){return new _r(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 _r(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 be(e,t).hasMagic())return true;return false};function gs(i,t={}){return new We(i,t).streamSync()}function jn(i,t={}){return new We(i,t).stream()}function $n(i,t={}){return new We(i,t).walkSync()}async function Ar(i,t={}){return new We(i,t).walk()}function ys(i,t={}){return new We(i,t).iterateSync()}function Un(i,t={}){return new We(i,t).iterate()}var Ya=gs,Ha=Object.assign(jn,{sync:gs}),qa=ys,Va=Object.assign(Un,{sync:ys}),Ja=Object.assign($n,{stream:gs,iterate:ys}),ms=Object.assign(Ar,{glob:Ar,globSync:$n,sync:Ja,globStream:jn,stream:Ha,globStreamSync:gs,streamSync:Ya,globIterate:Un,iterate:Va,globIterateSync:ys,iterateSync:qa,Glob:We,hasMagic:Xa,escape:an,unescape:Ue});ms.glob=ms;var Ee;(A=>{A.Level=Qa.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||Se.join(process.env.EASBOT_LOG_PATH??process.cwd(),"logs");_.logFile?l=Se.join(N,_.logFile??"memory.log"):l=Se.join(N,"memory.log");try{await re.mkdir(N,{recursive:!0}),c=await re.open(l,"a"),u=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 Ss=Object.entries({..._,...G}).filter(([sr,ne])=>ne!=null).map(([sr,ne])=>{let vs=`${sr}=`;return ne instanceof Error?vs+S(ne):typeof ne=="object"?vs+JSON.stringify(ne):vs+ne}).join(" "),ze=new Date,Jn=ze.getTime()-x;return x=ze.getTime(),[formatLogTime(ze),"+"+Jn+"ms",Ss,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 Ss=Date.now();tt.info(C,{status:"started",...G});function ze(){tt.info(C,{status:"completed",duration:Date.now()-Ss,...G});}return {stop:ze,[Symbol.dispose](){ze();}}}};return N&&typeof N=="string"&&o.set(N,tt),tt}A.create=R;})(Ee||(Ee={}));var lt=Ee.create({service:"memory.tokenizer"}),Yt=false,ih=loadTextFile("./assets/jieba_dict.txt",import.meta.url);async function Bn(i){if(!Yt)try{lt.debug("Initializing jieba tokenizer");let t=ih();if(se.with_dict(t),lt.debug("Built-in dictionary loaded"),i?.dictPath&&i.dictPath.length>0)for(let e of i.dictPath)await sh(e);Yt=!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(!Yt)throw new Error("Tokenizer not initialized");try{let t=await Filesystem.readText(i);lt.debug("Loading custom dictionary",{dictPath:i}),se.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(!Yt)return i.split(/\s+/).filter(Boolean);try{return se.cut(i)}catch(t){return lt.warn("Tokenization failed, using fallback",{error:String(t)}),i.split(/\s+/).filter(Boolean)}}function nh(i){if(!Yt)return i.split(/\s+/).filter(Boolean);try{return se.cut_for_search(i)}catch(t){return lt.warn("Tokenization for search failed, using fallback",{error:String(t)}),i.split(/\s+/).filter(Boolean)}}function bl(i,t,e){if(Yt)try{se.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 El(){return Yt}async function Sl(){Yt=false,lt.debug("Tokenizer closed");}function ir(i){if(!Yt)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 Gn(i){if(!Yt)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 Bi=class{constructor(t){p(this,"db",null);p(this,"storagePath");p(this,"initialized",false);p(this,"initPromise",null);this.storagePath=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(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
|
+
import {b,a}from'./chunks/chunk-MS352GPQ.mjs';import {GRAPH_ENTITY_TYPE_DEFINITIONS,GRAPH_RELATION_TYPE_DEFINITIONS}from'@easbot/types';export{GRAPH_ENTITY_TYPE_DEFINITIONS,GRAPH_RELATION_TYPE_DEFINITIONS}from'@easbot/types';import*as P from'jieba-wasm';import {loadTextFile,Filesystem,formatLocalISO}from'@easbot/utils';import we from'better-sqlite3';import {randomBytes,createHash}from'crypto';import N from'fs/promises';import _ from'path';import {promises}from'fs';import {embed,embedMany,streamText}from'ai';var re=["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"],x=class extends Error{constructor(t,n,r){super(t,{cause:r});this.code=n;this.cause=r;this.name="MemoryError";}},M=class extends x{constructor(e,t){super(e,"MEMORY_VALIDATION_ERROR",t),this.name="MemoryValidationError";}},X=class extends x{constructor(e){super(`Memory not found: ${e}`,"MEMORY_NOT_FOUND"),this.name="MemoryNotFoundError";}},B=class extends x{constructor(e){super(e,"MEMORY_PERMISSION_ERROR"),this.name="MemoryPermissionError";}},T=class extends x{constructor(e,t){super(e,"MEMORY_DATABASE_ERROR",t),this.name="MemoryDatabaseError";}},O=class extends x{constructor(e,t){super(e,"MEMORY_FILE_ERROR",t),this.name="MemoryFileError";}},G=class extends x{constructor(e,t){super(e,"MEMORY_SEARCH_ERROR",t),this.name="MemorySearchError";}},j=class extends x{constructor(e,t){super(e,"MEMORY_EMBEDDING_ERROR",t),this.name="MemoryEmbeddingError";}},_e=(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))(_e||{});var I=b.create({service:"memory.tokenizer"}),F=false,Me=loadTextFile("./assets/jieba_dict.txt",import.meta.url);async function ce(g){if(!F)try{I.debug("Initializing jieba tokenizer");let e=Me();if(P.with_dict(e),I.debug("Built-in dictionary loaded"),g?.dictPath&&g.dictPath.length>0)for(let t of g.dictPath)await Se(t);F=!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 Se(g){if(!F)throw new Error("Tokenizer not initialized");try{let e=await Filesystem.readText(g);I.debug("Loading custom dictionary",{dictPath:g}),P.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 Ne(g){if(!F)return g.split(/\s+/).filter(Boolean);try{return P.cut(g)}catch(e){return I.warn("Tokenization failed, using fallback",{error:String(e)}),g.split(/\s+/).filter(Boolean)}}function Ae(g){if(!F)return g.split(/\s+/).filter(Boolean);try{return P.cut_for_search(g)}catch(e){return I.warn("Tokenization for search failed, using fallback",{error:String(e)}),g.split(/\s+/).filter(Boolean)}}function Je(g,e,t){if(F)try{P.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 Ge(){return F}async function Ke(){F=false,I.debug("Tokenizer closed");}function se(g){if(!F)return g.split(/\s+/).filter(Boolean).join(" ");try{return Ne(g).join(" ")}catch(e){return I.warn("Tokenization failed, using fallback",{error:String(e)}),g.split(/\s+/).filter(Boolean).join(" ")}}function me(g){if(!F)return g.split(/\s+/).filter(Boolean).join(" ");try{return Ae(g).join(" ")}catch(e){return I.warn("Tokenization for search failed, using fallback",{error:String(e)}),g.split(/\s+/).filter(Boolean).join(" ")}}var Y=class{constructor(e){a(this,"db",null);a(this,"storagePath");a(this,"initialized",false);a(this,"initPromise",null);this.storagePath=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 we(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
|
|
19
|
-
updated_at
|
|
15
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
16
|
+
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
20
17
|
UNIQUE(session_id, msg_id)
|
|
21
18
|
)
|
|
22
|
-
`),
|
|
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
|
-
`),
|
|
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
|
|
29
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
33
30
|
)
|
|
34
|
-
`),
|
|
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
|
-
`),
|
|
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
|
|
50
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
54
51
|
)
|
|
55
|
-
`),
|
|
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
|
|
62
|
-
updatedAt
|
|
58
|
+
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
59
|
+
updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
63
60
|
)
|
|
64
|
-
`),
|
|
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
|
|
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
|
-
`),
|
|
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
|
|
81
|
-
`)}static serializeFile(
|
|
82
|
-
`)}static parse(
|
|
83
|
-
`),r=0;for(;r<
|
|
84
|
-
`).trim(),
|
|
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 De=["id","agentId","category","importance"],q="---",S=class g{static generateId(){let e=Date.now(),t=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:formatLocalISO(t),updatedAt: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 [q,...i,q,"",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()!==q){r++;continue}let i=r+1,s=-1;for(let u=i;u<n.length;u++)if(n[u]?.trim()===q){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()===q){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 De)if(e[r]===void 0||e[r]==="")throw new M(`Missing required field in memory frontmatter: ${r}`);let t=e.category;if(!re.includes(t))throw new M(`Invalid category: "${t}". Valid values: ${re.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 ue="MEMORY.md",pe="active",ve="archive",w=class g{static getMemoryMdPath(e){return _.join(e,ue)}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 _.join(e,pe,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 _.join(e,ve,s,t,r)}static async readMemoryMd(e){let t=g.getMemoryMdPath(e);try{return await N.readFile(t,"utf-8")}catch(n){if(n.code==="ENOENT")return null;throw new O(`Failed to read MEMORY.md: ${n.message}`,n)}}static async write(e,t){let n=g.getActiveFilePath(e,t.category);Filesystem.toUnixPath(_.relative(e,n));if(_.basename(n)===ue)throw new B("Writing to MEMORY.md is not allowed. MEMORY.md is read-only.");try{await N.mkdir(_.dirname(n),{recursive:!0});let i=S.serialize(t),s="";try{s=await N.readFile(n,"utf-8");}catch{}let d=s.length>0&&!s.endsWith(`
|
|
85
82
|
`)?`
|
|
86
|
-
`:"";return await
|
|
83
|
+
`:"";return await N.writeFile(n,`${s}${d}${i}`,"utf-8"),Filesystem.normalize(n)}catch(i){throw i instanceof B?i:new O(`Failed to write memory to ${n}: ${i.message}`,i)}}static async read(e){try{let t=await N.readFile(e,"utf-8");return S.parse(t)}catch(t){if(t.code==="ENOENT")return [];throw new O(`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.unlink(e).catch(()=>{}):await N.writeFile(e,S.serializeFile(r),"utf-8");}catch(n){throw n instanceof O?n:new O(`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.writeFile(e,S.serializeFile(r),"utf-8");}catch(r){throw r instanceof O?r:new O(`Failed to update memory ${t} in ${e}: ${r.message}`,r)}}static async listActiveFiles(e){let t=_.join(e,pe),n=[];try{await g.scanDir(t,n);}catch(r){if(r.code==="ENOENT")return [];throw new O(`Failed to list active memory files: ${r.message}`,r)}return n}static async scanDir(e,t){let n=await N.readdir(e,{withFileTypes:true});for(let r of n){let i=_.join(e,r.name);r.isDirectory()?await g.scanDir(i,t):r.isFile()&&r.name.endsWith(".md")&&t.push(i);}}};var H=class{constructor(e,t){a(this,"db");a(this,"config");this.db=e,this.config=t;}async archive(){let t=(this.config.archiveDays??30)*864e5,n=Date.now(),r=[],i=await w.listActiveFiles(this.config.workspaceDir);for(let s of i){let d=await w.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=_.basename(s),l=w.getArchiveFilePath(this.config.workspaceDir,a,m,c);await promises.mkdir(_.dirname(l),{recursive:true}),await promises.rename(s,l);let u=Filesystem.toUnixPath(_.relative(this.config.workspaceDir,l)),p=Filesystem.toUnixPath(_.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 Q=b.create({service:"memory.graph-store"}),V=class{constructor(e){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)),Q.debug("queryNodes",{sql:t,params:n,filter:e});let i=this.db.prepare(t).all(...n);return Q.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)),Q.debug("queryEdges",{sql:t,params:n,filter:e});let i=this.db.prepare(t).all(...n);Q.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 z;(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 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 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 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(L=>L.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;})(z||(z={}));var Z=class{constructor(e,t){a(this,"db");a(this,"config");a(this,"embeddingModel");this.db=e,this.config=t,this.embeddingModel=t.embeddingLlm,this.embeddingModel&&z.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,L=m?s:1;return this.mergeResults(u,p,E,L,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 ${
|
|
91
|
-
`).all(...s
|
|
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 ${
|
|
92
|
+
WHERE ${t}
|
|
96
93
|
LIMIT ?
|
|
97
|
-
`).all(...
|
|
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=(Gn(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 G(`\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=(me(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 ${
|
|
98
|
+
WHERE ${t} AND memory_facts_fts.content MATCH ?
|
|
108
99
|
ORDER BY score DESC
|
|
109
100
|
LIMIT ?
|
|
110
|
-
`).all(...
|
|
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 (${
|
|
123
|
-
`).all(...
|
|
113
|
+
WHERE mf.id IN (${u})
|
|
114
|
+
`).all(...l),E=[],L=new Map;for(let h of p)if(h.node_ids)try{let R=JSON.parse(h.node_ids);L.set(h.memoryId,R),E.push(...R);}catch{}let A=Array.from(new Set(E)),oe=new Map,W=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)oe.set(f.id,f);let J=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 (${
|
|
126
|
-
|
|
127
|
-
source,
|
|
128
|
-
|
|
129
|
-
|
|
116
|
+
WHERE e.source IN (${h})`).all(...A);for(let f of J){let $=W.get(f.source)??[];$.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}}),W.set(f.source,$);}let te=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 te){let $=W.get(f.target)??[];$.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}}),W.set(f.target,$);}}return p.map(h=>{let R=L.get(h.memoryId)??[],J=R.length>0?R.flatMap(ae=>{let de=oe.get(ae);return de?[{...de,edges:W.get(ae)}]:[]}):void 0,te=c.get(h.memoryId)??0,f=new Date(h.createdAt),$=(Date.now()-f.getTime())/864e5,Ee=Math.exp(-0.05*$),be=(h.importance-1)/9,Te=.4*te+.3*Ee+.3*be;return {memoryId:h.memoryId,category:h.category,importance:h.importance,agentId:h.agentId,snippet:h.snippet,score:Te,createdAt:h.createdAt,source:h.source,filePath:h.filePath,nodes:(J?.length??0)>0?J:void 0}}).filter(h=>h.score>=d).sort((h,R)=>R.score-h.score)}async embed(e){if(!this.embeddingModel)throw new j("Embedding \u6A21\u578B\u672A\u914D\u7F6E\uFF0C\u65E0\u6CD5\u751F\u6210\u5411\u91CF");try{return await z.embedText(e)}catch(t){throw new j(`\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=b.create({service:"memory.system"}),ke=.7,Ue=.3,ze=10;var $e=new Set(GRAPH_ENTITY_TYPE_DEFINITIONS.map(g=>g.type)),We=new Set(GRAPH_RELATION_TYPE_DEFINITIONS.map(g=>g.type)),ee=class{constructor(e){a(this,"config");a(this,"db");a(this,"archiver",null);a(this,"searchEngine",null);a(this,"graphStore",null);a(this,"embeddingModel");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??ze,minScore:e.search?.minScore??.3,hybrid:{enabled:e.search?.hybrid?.enabled??true,vectorWeight:e.search?.hybrid?.vectorWeight??ke,textWeight:e.search?.hybrid?.textWeight??Ue}},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 Y(e.database.path),this.embeddingModel&&z.init({models:{embeddingLlm:this.embeddingModel,graphLlm:this.config.graphLlm}});}async initialize(){await b.init({logDir:this.config.logDir??_.join(this.config.workspaceDir,"logs"),print:process.argv.includes("--print-logs"),dev:false,level:"INFO"}),await N.mkdir(_.dirname(this.config.database.path),{recursive:true}),await N.mkdir(_.join(this.config.workspaceDir,"active"),{recursive:true}),await N.mkdir(_.join(this.config.workspaceDir,"archive"),{recursive:true}),await this.db.initialize(),this.archiver=new H(this.db.getDb(),this.config),this.graphStore=new V(this.db.getDb()),this.searchEngine=new Z(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 ce({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 w.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?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 X(t);let r=n[0]?.file_path,i=n[0]?.node_ids?JSON.parse(n[0].node_ids):[],s=n[0]?.content,d=s?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=_.isAbsolute(r)?r:_.join(this.config.workspaceDir,r);await w.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 X(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=_.isAbsolute(i.file_path)?i.file_path:_.join(this.config.workspaceDir,i.file_path);await w.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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[
|
|
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
|
|
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
|
-
)`,[
|
|
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,
|
|
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
|
|
146
|
-
`),s=
|
|
147
|
-
`),
|
|
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 w.listActiveFiles(this.config.workspaceDir);for(let t of e)await N.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 b.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=_.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=_.dirname(s);await N.mkdir(o,{recursive:!0});let m=d.map(c=>{let l=this.rowToFact(c);return S.serialize(l)}).join(`
|
|
139
|
+
`);if(await N.access(s).then(()=>!0).catch(()=>!1)){if((await N.readFile(s,"utf-8")).trim()===m.trim()){e.synced++;continue}e.updated++;}else e.created++;await N.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=[_.join(this.config.workspaceDir,"active"),_.join(this.config.workspaceDir,"archive")];for(let t of e)try{let n=await N.readdir(t,{withFileTypes:!0});for(let r of n){let i=_.join(t,r.name);if(r.isDirectory()){if((await N.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=[_.join(this.config.workspaceDir,"active"),_.join(this.config.workspaceDir,"archive")];for(let t of e)try{let n=await N.readdir(t,{withFileTypes:!0});for(let r of n){let i=_.join(t,r.name);r.isDirectory()?await N.rm(i,{recursive:!0,force:!0}):r.name.endsWith(".md")&&await N.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 z.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=GRAPH_ENTITY_TYPE_DEFINITIONS.map(i=>`- ${i.type}: ${i.rule}`).join(`
|
|
140
|
+
`),n=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
|
-
${
|
|
146
|
+
${t}
|
|
153
147
|
|
|
154
148
|
Relation type taxonomy:
|
|
155
|
-
${
|
|
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
|
|
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=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=se(n),s=r?se(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=$e.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():"",L=We.has(E)?E:"related_to",A=`${u.toLowerCase()}|${p.toLowerCase()}|${L}`;m.has(A)||(m.add(A),o.push({source:u,target:p,relation:L}));}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 Xe(g){let e=new ee(g);return await e.initialize(),e}async function tr(g){let{Log:e}=await import('./chunks/log-WWZ27AYI.mjs'),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")});}export{V as GraphStore,re as MEMORY_CATEGORIES,H as MemoryArchiver,T as MemoryDatabaseError,Y as MemoryDatabaseManager,j as MemoryEmbeddingError,x as MemoryError,_e as MemoryErrorCode,O as MemoryFileError,w as MemoryFileManager,S as MemoryFormatter,X as MemoryNotFoundError,B as MemoryPermissionError,G as MemorySearchError,ee as MemorySystem,M as MemoryValidationError,Je as addWord,Ke as closeTokenizer,Xe as createMemorySystem,tr as initLog,ce as initTokenizer,Ge as isInitialized,Se as loadCustomDict,se as toFtsTokens,me as toFtsTokensForSearch,Ne as tokenize,Ae as tokenizeForSearch};
|