claude-mem 13.6.1 → 13.6.2
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/.codex-plugin/plugin.json +1 -1
- package/dist/npx-cli/index.js +1 -1
- package/openclaw/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/.codex-plugin/plugin.json +1 -1
- package/plugin/package.json +1 -1
- package/plugin/scripts/mcp-server.cjs +1 -1
- package/plugin/scripts/server-beta-service.cjs +1 -1
- package/plugin/scripts/transcript-watcher.cjs +1 -1
- package/plugin/scripts/worker-service.cjs +229 -229
|
@@ -12,7 +12,7 @@ ${n.stack}`:` ${n.message}`;else if(this.getLevel()===0&&typeof n=="object")try{
|
|
|
12
12
|
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),u=c?`${c[1].split("/").pop()}:${c[2]}`:"unknown",h={...s,location:u};return this.warn(e,`[HAPPY-PATH] ${r}`,h,i),n}},d=new nr;var Bn={};function Ln(){return typeof __dirname<"u"?__dirname:(0,_.dirname)((0,Jr.fileURLToPath)(Bn.url))}var ql=Ln();function Oe(){if(process.env.CLAUDE_MEM_DATA_DIR)return process.env.CLAUDE_MEM_DATA_DIR;let t=(0,_.join)((0,or.homedir)(),".claude-mem"),e=(0,_.join)(t,"settings.json");try{if((0,$e.existsSync)(e)){let r=JSON.parse((0,$e.readFileSync)(e,"utf-8")),s=r.env??r;if(s.CLAUDE_MEM_DATA_DIR)return s.CLAUDE_MEM_DATA_DIR}}catch{}return t}var v=Oe(),lt=process.env.CLAUDE_CONFIG_DIR||(0,_.join)((0,or.homedir)(),".claude"),ct=(0,_.join)(lt,"plugins","marketplaces","thedotmack"),Nn=(0,_.join)(v,"archives"),Un=(0,_.join)(v,"logs"),Fn=(0,_.join)(v,"trash"),Wn=(0,_.join)(v,"backups"),$n=(0,_.join)(v,"modes"),ut=(0,_.join)(v,"settings.json"),Vl=(0,_.join)(v,"claude-mem.db"),Hn=(0,_.join)(v,"vector-db"),ht=(0,_.join)(v,"observer-sessions"),jn=(0,_.basename)(ht),Ql=(0,_.join)(lt,"settings.json"),Zl=(0,_.join)(lt,"commands"),ec=(0,_.join)(lt,"CLAUDE.md");var R={dataDir:()=>v,workerPid:()=>(0,_.join)(v,"worker.pid"),serverBetaPid:()=>(0,_.join)(v,".server-beta.pid"),serverBetaPort:()=>(0,_.join)(v,".server-beta.port"),serverBetaRuntime:()=>(0,_.join)(v,".server-beta.runtime.json"),settings:()=>(0,_.join)(v,"settings.json"),database:()=>(0,_.join)(v,"claude-mem.db"),chroma:()=>(0,_.join)(v,"chroma"),combinedCerts:()=>(0,_.join)(v,"combined_certs.pem"),transcriptsConfig:()=>(0,_.join)(v,"transcript-watch.json"),transcriptsState:()=>(0,_.join)(v,"transcript-watch-state.json"),corpora:()=>(0,_.join)(v,"corpora"),supervisorRegistry:()=>(0,_.join)(v,"supervisor.json"),envFile:()=>(0,_.join)(v,".env"),logsDir:()=>Un,archives:()=>Nn,trash:()=>Fn,backups:()=>Wn,modes:()=>$n,vectorDb:()=>Hn,observerSessions:()=>ht};var Ie=R.transcriptsConfig(),dt=R.transcriptsState();var Gn={version:1,schemas:{},watches:[],stateFile:dt};function Kn(t){let e=typeof t.schema=="string"?t.schema:t.schema?.name;if(!(t.name==="codex"||e==="codex")||!t.path)return!1;let s=N(t.path).replace(/\\/g,"/"),i=(0,He.join)((0,ar.homedir)(),".codex","sessions").replace(/\\/g,"/");return s===`${i}/**/*.jsonl`}function Xr(t){let e=typeof t.schema=="string"?t.schema:t.schema?.name,r=t.name==="codex"&&(!e||e==="codex");return t.context?.mode==="agents"&&r&&Kn(t)}function N(t){return t&&(t.startsWith("~")?(0,He.join)((0,ar.homedir)(),t.slice(1)):t)}function je(t=Ie){let e=N(t);if(!(0,ne.existsSync)(e))throw new Error(`Transcript watch config not found: ${e}`);let r=(0,ne.readFileSync)(e,"utf-8"),s=JSON.parse(r);if(!s.version||!s.watches)throw new Error(`Invalid transcript watch config: ${e}`);return s.stateFile||(s.stateFile=dt),s}function pt(t=Ie){let e=N(t),r=(0,He.dirname)(e);(0,ne.existsSync)(r)||(0,ne.mkdirSync)(r,{recursive:!0}),(0,ne.writeFileSync)(e,JSON.stringify(Gn,null,2))}var x=require("fs"),J=require("path");var Is=require("node:url"),Le=require("node:path"),Ns=require("node:url"),Q=require("fs"),Qo=X(require("node:fs"),1),Se=require("node:fs/promises"),kt=require("node:events"),wr=X(require("node:stream"),1),Us=require("node:string_decoder"),ws=(t,e,r)=>{let s=t instanceof RegExp?qr(t,r):t,i=e instanceof RegExp?qr(e,r):e,n=s!==null&&i!=null&&Yn(s,i,r);return n&&{start:n[0],end:n[1],pre:r.slice(0,n[0]),body:r.slice(n[0]+s.length,n[1]),post:r.slice(n[1]+i.length)}},qr=(t,e)=>{let r=e.match(t);return r?r[0]:null},Yn=(t,e,r)=>{let s,i,n,o,a,l=r.indexOf(t),c=r.indexOf(e,l+1),u=l;if(l>=0&&c>0){if(t===e)return[l,c];for(s=[],n=r.length;u>=0&&!a;){if(u===l)s.push(u),l=r.indexOf(t,u+1);else if(s.length===1){let h=s.pop();h!==void 0&&(a=[h,c])}else i=s.pop(),i!==void 0&&i<n&&(n=i,o=c),c=r.indexOf(e,u+1);u=l<c&&l>=0?l:c}s.length&&o!==void 0&&(a=[n,o])}return a},ys="\0SLASH"+Math.random()+"\0",_s="\0OPEN"+Math.random()+"\0",Sr="\0CLOSE"+Math.random()+"\0",bs="\0COMMA"+Math.random()+"\0",vs="\0PERIOD"+Math.random()+"\0",zn=new RegExp(ys,"g"),Jn=new RegExp(_s,"g"),Xn=new RegExp(Sr,"g"),qn=new RegExp(bs,"g"),Vn=new RegExp(vs,"g"),Qn=/\\\\/g,Zn=/\\{/g,eo=/\\}/g,to=/\\,/g,ro=/\\./g,so=1e5;function lr(t){return isNaN(t)?t.charCodeAt(0):parseInt(t,10)}function io(t){return t.replace(Qn,ys).replace(Zn,_s).replace(eo,Sr).replace(to,bs).replace(ro,vs)}function no(t){return t.replace(zn,"\\").replace(Jn,"{").replace(Xn,"}").replace(qn,",").replace(Vn,".")}function Ts(t){if(!t)return[""];let e=[],r=ws("{","}",t);if(!r)return t.split(",");let{pre:s,body:i,post:n}=r,o=s.split(",");o[o.length-1]+="{"+i+"}";let a=Ts(n);return n.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),e.push.apply(e,o),e}function oo(t,e={}){if(!t)return[];let{max:r=so}=e;return t.slice(0,2)==="{}"&&(t="\\{\\}"+t.slice(2)),Xe(io(t),r,!0).map(no)}function ao(t){return"{"+t+"}"}function lo(t){return/^-?0\d/.test(t)}function co(t,e){return t<=e}function uo(t,e){return t>=e}function Xe(t,e,r){let s=[],i=ws("{","}",t);if(!i)return[t];let n=i.pre,o=i.post.length?Xe(i.post,e,!1):[""];if(/\$$/.test(i.pre))for(let a=0;a<o.length&&a<e;a++){let l=n+"{"+i.body+"}"+o[a];s.push(l)}else{let a=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(i.body),l=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(i.body),c=a||l,u=i.body.indexOf(",")>=0;if(!c&&!u)return i.post.match(/,(?!,).*\}/)?(t=i.pre+"{"+i.body+Sr+i.post,Xe(t,e,!0)):[t];let h;if(c)h=i.body.split(/\.\./);else if(h=Ts(i.body),h.length===1&&h[0]!==void 0&&(h=Xe(h[0],e,!1).map(ao),h.length===1))return o.map(f=>i.pre+h[0]+f);let p;if(c&&h[0]!==void 0&&h[1]!==void 0){let f=lr(h[0]),m=lr(h[1]),g=Math.max(h[0].length,h[1].length),w=h.length===3&&h[2]!==void 0?Math.abs(lr(h[2])):1,S=co;m<f&&(w*=-1,S=uo);let E=h.some(lo);p=[];for(let y=f;S(y,m);y+=w){let b;if(l)b=String.fromCharCode(y),b==="\\"&&(b="");else if(b=String(y),E){let T=g-b.length;if(T>0){let pe=new Array(T+1).join("0");y<0?b="-"+pe+b.slice(1):b=pe+b}}p.push(b)}}else{p=[];for(let f=0;f<h.length;f++)p.push.apply(p,Xe(h[f],e,!1))}for(let f=0;f<p.length;f++)for(let m=0;m<o.length&&s.length<e;m++){let g=n+p[f]+o[m];(!r||c||g)&&s.push(g)}}return s}var Tt=t=>{if(typeof t!="string")throw new TypeError("invalid pattern");if(t.length>65536)throw new TypeError("pattern is too long")},ho={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},Be=t=>t.replace(/[[\]\\-]/g,"\\$&"),po=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Vr=t=>t.join(""),fo=(t,e)=>{let r=e;if(t.charAt(r)!=="[")throw new Error("not in a brace expression");let s=[],i=[],n=r+1,o=!1,a=!1,l=!1,c=!1,u=r,h="";e:for(;n<t.length;){let m=t.charAt(n);if((m==="!"||m==="^")&&n===r+1){c=!0,n++;continue}if(m==="]"&&o&&!l){u=n+1;break}if(o=!0,m==="\\"&&!l){l=!0,n++;continue}if(m==="["&&!l){for(let[g,[w,S,E]]of Object.entries(ho))if(t.startsWith(g,n)){if(h)return["$.",!1,t.length-r,!0];n+=g.length,E?i.push(w):s.push(w),a=a||S;continue e}}if(l=!1,h){m>h?s.push(Be(h)+"-"+Be(m)):m===h&&s.push(Be(m)),h="",n++;continue}if(t.startsWith("-]",n+1)){s.push(Be(m+"-")),n+=2;continue}if(t.startsWith("-",n+1)){h=m,n+=2;continue}s.push(Be(m)),n++}if(u<n)return["",!1,0,!1];if(!s.length&&!i.length)return["$.",!1,t.length-r,!0];if(i.length===0&&s.length===1&&/^\\?.$/.test(s[0])&&!c){let m=s[0].length===2?s[0].slice(-1):s[0];return[po(m),!1,u-r,!1]}let p="["+(c?"^":"")+Vr(s)+"]",f="["+(c?"":"^")+Vr(i)+"]";return[s.length&&i.length?"("+p+"|"+f+")":s.length?p:f,a,u-r,!0]},xe=(t,{windowsPathsNoEscape:e=!1,magicalBraces:r=!0}={})=>r?e?t.replace(/\[([^\/\\])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):e?t.replace(/\[([^\/\\{}])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1"),mo=new Set(["!","?","+","*","@"]),Qr=t=>mo.has(t),go="(?!(?:^|/)\\.\\.?(?:$|/))",ft="(?!\\.)",So=new Set(["[","."]),Eo=new Set(["..","."]),wo=new Set("().*{}+?[]^$\\!"),yo=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Er="[^/]",Zr=Er+"*?",es=Er+"+?",Ms=class F{type;#e;#r;#n=!1;#i=[];#o;#y;#S;#u=!1;#a;#d;#h=!1;constructor(e,r,s={}){this.type=e,e&&(this.#r=!0),this.#o=r,this.#e=this.#o?this.#o.#e:this,this.#a=this.#e===this?s:this.#e.#a,this.#S=this.#e===this?[]:this.#e.#S,e==="!"&&!this.#e.#u&&this.#S.push(this),this.#y=this.#o?this.#o.#i.length:0}get hasMagic(){if(this.#r!==void 0)return this.#r;for(let e of this.#i)if(typeof e!="string"&&(e.type||e.hasMagic))return this.#r=!0;return this.#r}toString(){return this.#d!==void 0?this.#d:this.type?this.#d=this.type+"("+this.#i.map(e=>String(e)).join("|")+")":this.#d=this.#i.map(e=>String(e)).join("")}#l(){if(this!==this.#e)throw new Error("should only call on root");if(this.#u)return this;this.toString(),this.#u=!0;let e;for(;e=this.#S.pop();){if(e.type!=="!")continue;let r=e,s=r.#o;for(;s;){for(let i=r.#y+1;!s.type&&i<s.#i.length;i++)for(let n of e.#i){if(typeof n=="string")throw new Error("string part in extglob AST??");n.copyIn(s.#i[i])}r=s,s=r.#o}}return this}push(...e){for(let r of e)if(r!==""){if(typeof r!="string"&&!(r instanceof F&&r.#o===this))throw new Error("invalid part: "+r);this.#i.push(r)}}toJSON(){let e=this.type===null?this.#i.slice().map(r=>typeof r=="string"?r:r.toJSON()):[this.type,...this.#i.map(r=>r.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#u&&this.#o?.type==="!")&&e.push({}),e}isStart(){if(this.#e===this)return!0;if(!this.#o?.isStart())return!1;if(this.#y===0)return!0;let e=this.#o;for(let r=0;r<this.#y;r++){let s=e.#i[r];if(!(s instanceof F&&s.type==="!"))return!1}return!0}isEnd(){if(this.#e===this||this.#o?.type==="!")return!0;if(!this.#o?.isEnd())return!1;if(!this.type)return this.#o?.isEnd();let e=this.#o?this.#o.#i.length:0;return this.#y===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this))}clone(e){let r=new F(this.type,e);for(let s of this.#i)r.copyIn(s);return r}static#s(e,r,s,i){let n=!1,o=!1,a=-1,l=!1;if(r.type===null){let f=s,m="";for(;f<e.length;){let g=e.charAt(f++);if(n||g==="\\"){n=!n,m+=g;continue}if(o){f===a+1?(g==="^"||g==="!")&&(l=!0):g==="]"&&!(f===a+2&&l)&&(o=!1),m+=g;continue}else if(g==="["){o=!0,a=f,l=!1,m+=g;continue}if(!i.noext&&Qr(g)&&e.charAt(f)==="("){r.push(m),m="";let w=new F(g,r);f=F.#s(e,w,f,i),r.push(w);continue}m+=g}return r.push(m),f}let c=s+1,u=new F(null,r),h=[],p="";for(;c<e.length;){let f=e.charAt(c++);if(n||f==="\\"){n=!n,p+=f;continue}if(o){c===a+1?(f==="^"||f==="!")&&(l=!0):f==="]"&&!(c===a+2&&l)&&(o=!1),p+=f;continue}else if(f==="["){o=!0,a=c,l=!1,p+=f;continue}if(Qr(f)&&e.charAt(c)==="("){u.push(p),p="";let m=new F(f,u);u.push(m),c=F.#s(e,m,c,i);continue}if(f==="|"){u.push(p),p="",h.push(u),u=new F(null,r);continue}if(f===")")return p===""&&r.#i.length===0&&(r.#h=!0),u.push(p),p="",r.push(...h,u),c;p+=f}return r.type=null,r.#r=void 0,r.#i=[e.substring(s-1)],c}static fromGlob(e,r={}){let s=new F(null,void 0,r);return F.#s(e,s,0,r),s}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let e=this.toString(),[r,s,i,n]=this.toRegExpSource();if(!(i||this.#r||this.#a.nocase&&!this.#a.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return s;let o=(this.#a.nocase?"i":"")+(n?"u":"");return Object.assign(new RegExp(`^${r}$`,o),{_src:r,_glob:e})}get options(){return this.#a}toRegExpSource(e){let r=e??!!this.#a.dot;if(this.#e===this&&this.#l(),!this.type){let l=this.isStart()&&this.isEnd()&&!this.#i.some(p=>typeof p!="string"),c=this.#i.map(p=>{let[f,m,g,w]=typeof p=="string"?F.#_(p,this.#r,l):p.toRegExpSource(e);return this.#r=this.#r||g,this.#n=this.#n||w,f}).join(""),u="";if(this.isStart()&&typeof this.#i[0]=="string"&&!(this.#i.length===1&&Eo.has(this.#i[0]))){let p=So,f=r&&p.has(c.charAt(0))||c.startsWith("\\.")&&p.has(c.charAt(2))||c.startsWith("\\.\\.")&&p.has(c.charAt(4)),m=!r&&!e&&p.has(c.charAt(0));u=f?go:m?ft:""}let h="";return this.isEnd()&&this.#e.#u&&this.#o?.type==="!"&&(h="(?:$|\\/)"),[u+c+h,xe(c),this.#r=!!this.#r,this.#n]}let s=this.type==="*"||this.type==="+",i=this.type==="!"?"(?:(?!(?:":"(?:",n=this.#p(r);if(this.isStart()&&this.isEnd()&&!n&&this.type!=="!"){let l=this.toString();return this.#i=[l],this.type=null,this.#r=void 0,[l,xe(this.toString()),!1,!1]}let o=!s||e||r||!ft?"":this.#p(!0);o===n&&(o=""),o&&(n=`(?:${n})(?:${o})*?`);let a="";if(this.type==="!"&&this.#h)a=(this.isStart()&&!r?ft:"")+es;else{let l=this.type==="!"?"))"+(this.isStart()&&!r&&!e?ft:"")+Zr+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;a=i+n+l}return[a,xe(n),this.#r=!!this.#r,this.#n]}#p(e){return this.#i.map(r=>{if(typeof r=="string")throw new Error("string type in extglob ast??");let[s,i,n,o]=r.toRegExpSource(e);return this.#n=this.#n||o,s}).filter(r=>!(this.isStart()&&this.isEnd())||!!r).join("|")}static#_(e,r,s=!1){let i=!1,n="",o=!1,a=!1;for(let l=0;l<e.length;l++){let c=e.charAt(l);if(i){i=!1,n+=(wo.has(c)?"\\":"")+c;continue}if(c==="*"){if(a)continue;a=!0,n+=s&&/^[*]+$/.test(e)?es:Zr,r=!0;continue}else a=!1;if(c==="\\"){l===e.length-1?n+="\\\\":i=!0;continue}if(c==="["){let[u,h,p,f]=fo(e,l);if(p){n+=u,o=o||h,l+=p-1,r=r||f;continue}}if(c==="?"){n+=Er,r=!0;continue}n+=yo(c)}return[n,xe(e),!!r,o]}},Cs=(t,{windowsPathsNoEscape:e=!1,magicalBraces:r=!1}={})=>r?e?t.replace(/[?*()[\]{}]/g,"[$&]"):t.replace(/[?*()[\]\\{}]/g,"\\$&"):e?t.replace(/[?*()[\]]/g,"[$&]"):t.replace(/[?*()[\]\\]/g,"\\$&"),P=(t,e,r={})=>(Tt(e),!r.nocomment&&e.charAt(0)==="#"?!1:new ge(e,r).match(t)),_o=/^\*+([^+@!?\*\[\(]*)$/,bo=t=>e=>!e.startsWith(".")&&e.endsWith(t),vo=t=>e=>e.endsWith(t),To=t=>(t=t.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(t)),Mo=t=>(t=t.toLowerCase(),e=>e.toLowerCase().endsWith(t)),Co=/^\*+\.\*+$/,Ao=t=>!t.startsWith(".")&&t.includes("."),ko=t=>t!=="."&&t!==".."&&t.includes("."),Ro=/^\.\*+$/,Oo=t=>t!=="."&&t!==".."&&t.startsWith("."),Io=/^\*+$/,Do=t=>t.length!==0&&!t.startsWith("."),Po=t=>t.length!==0&&t!=="."&&t!=="..",xo=/^\?+([^+@!?\*\[\(]*)?$/,Lo=([t,e=""])=>{let r=As([t]);return e?(e=e.toLowerCase(),s=>r(s)&&s.toLowerCase().endsWith(e)):r},No=([t,e=""])=>{let r=ks([t]);return e?(e=e.toLowerCase(),s=>r(s)&&s.toLowerCase().endsWith(e)):r},Uo=([t,e=""])=>{let r=ks([t]);return e?s=>r(s)&&s.endsWith(e):r},Fo=([t,e=""])=>{let r=As([t]);return e?s=>r(s)&&s.endsWith(e):r},As=([t])=>{let e=t.length;return r=>r.length===e&&!r.startsWith(".")},ks=([t])=>{let e=t.length;return r=>r.length===e&&r!=="."&&r!==".."},Rs=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",ts={win32:{sep:"\\"},posix:{sep:"/"}},Wo=Rs==="win32"?ts.win32.sep:ts.posix.sep;P.sep=Wo;var D=Symbol("globstar **");P.GLOBSTAR=D;var $o="[^/]",Ho=$o+"*?",jo="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",Bo="(?:(?!(?:\\/|^)\\.).)*?",Go=(t,e={})=>r=>P(r,t,e);P.filter=Go;var $=(t,e={})=>Object.assign({},t,e),Ko=t=>{if(!t||typeof t!="object"||!Object.keys(t).length)return P;let e=P;return Object.assign((r,s,i={})=>e(r,s,$(t,i)),{Minimatch:class extends e.Minimatch{constructor(r,s={}){super(r,$(t,s))}static defaults(r){return e.defaults($(t,r)).Minimatch}},AST:class extends e.AST{constructor(r,s,i={}){super(r,s,$(t,i))}static fromGlob(r,s={}){return e.AST.fromGlob(r,$(t,s))}},unescape:(r,s={})=>e.unescape(r,$(t,s)),escape:(r,s={})=>e.escape(r,$(t,s)),filter:(r,s={})=>e.filter(r,$(t,s)),defaults:r=>e.defaults($(t,r)),makeRe:(r,s={})=>e.makeRe(r,$(t,s)),braceExpand:(r,s={})=>e.braceExpand(r,$(t,s)),match:(r,s,i={})=>e.match(r,s,$(t,i)),sep:e.sep,GLOBSTAR:D})};P.defaults=Ko;var Os=(t,e={})=>(Tt(t),e.nobrace||!/\{(?:(?!\{).)*\}/.test(t)?[t]:oo(t,{max:e.braceExpandMax}));P.braceExpand=Os;var Yo=(t,e={})=>new ge(t,e).makeRe();P.makeRe=Yo;var zo=(t,e,r={})=>{let s=new ge(e,r);return t=t.filter(i=>s.match(i)),s.options.nonull&&!t.length&&t.push(e),t};P.match=zo;var rs=/[?*]|[+@!]\(.*?\)|\[|\]/,Jo=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),ge=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(t,e={}){Tt(t),e=e||{},this.options=e,this.pattern=t,this.platform=e.platform||Rs,this.isWindows=this.platform==="win32";let r="allowWindowsEscape";this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e[r]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!e.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!e.nonegate,this.comment=!1,this.empty=!1,this.partial=!!e.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=e.windowsNoMagicRoot!==void 0?e.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let t of this.set)for(let e of t)if(typeof e!="string")return!0;return!1}debug(...t){}make(){let t=this.pattern,e=this.options;if(!e.nocomment&&t.charAt(0)==="#"){this.comment=!0;return}if(!t){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],e.debug&&(this.debug=(...i)=>console.error(...i)),this.debug(this.pattern,this.globSet);let r=this.globSet.map(i=>this.slashSplit(i));this.globParts=this.preprocess(r),this.debug(this.pattern,this.globParts);let s=this.globParts.map((i,n,o)=>{if(this.isWindows&&this.windowsNoMagicRoot){let a=i[0]===""&&i[1]===""&&(i[2]==="?"||!rs.test(i[2]))&&!rs.test(i[3]),l=/^[a-z]:/i.test(i[0]);if(a)return[...i.slice(0,4),...i.slice(4).map(c=>this.parse(c))];if(l)return[i[0],...i.slice(1).map(c=>this.parse(c))]}return i.map(a=>this.parse(a))});if(this.debug(this.pattern,s),this.set=s.filter(i=>i.indexOf(!1)===-1),this.isWindows)for(let i=0;i<this.set.length;i++){let n=this.set[i];n[0]===""&&n[1]===""&&this.globParts[i][2]==="?"&&typeof n[3]=="string"&&/^[a-z]:$/i.test(n[3])&&(n[2]="?")}this.debug(this.pattern,this.set)}preprocess(t){if(this.options.noglobstar)for(let r=0;r<t.length;r++)for(let s=0;s<t[r].length;s++)t[r][s]==="**"&&(t[r][s]="*");let{optimizationLevel:e=1}=this.options;return e>=2?(t=this.firstPhasePreProcess(t),t=this.secondPhasePreProcess(t)):e>=1?t=this.levelOneOptimize(t):t=this.adjascentGlobstarOptimize(t),t}adjascentGlobstarOptimize(t){return t.map(e=>{let r=-1;for(;(r=e.indexOf("**",r+1))!==-1;){let s=r;for(;e[s+1]==="**";)s++;s!==r&&e.splice(r,s-r)}return e})}levelOneOptimize(t){return t.map(e=>(e=e.reduce((r,s)=>{let i=r[r.length-1];return s==="**"&&i==="**"?r:s===".."&&i&&i!==".."&&i!=="."&&i!=="**"?(r.pop(),r):(r.push(s),r)},[]),e.length===0?[""]:e))}levelTwoFileOptimize(t){Array.isArray(t)||(t=this.slashSplit(t));let e=!1;do{if(e=!1,!this.preserveMultipleSlashes){for(let s=1;s<t.length-1;s++){let i=t[s];s===1&&i===""&&t[0]===""||(i==="."||i==="")&&(e=!0,t.splice(s,1),s--)}t[0]==="."&&t.length===2&&(t[1]==="."||t[1]==="")&&(e=!0,t.pop())}let r=0;for(;(r=t.indexOf("..",r+1))!==-1;){let s=t[r-1];s&&s!=="."&&s!==".."&&s!=="**"&&(e=!0,t.splice(r-1,2),r-=2)}}while(e);return t.length===0?[""]:t}firstPhasePreProcess(t){let e=!1;do{e=!1;for(let r of t){let s=-1;for(;(s=r.indexOf("**",s+1))!==-1;){let n=s;for(;r[n+1]==="**";)n++;n>s&&r.splice(s+1,n-s);let o=r[s+1],a=r[s+2],l=r[s+3];if(o!==".."||!a||a==="."||a===".."||!l||l==="."||l==="..")continue;e=!0,r.splice(s,1);let c=r.slice(0);c[s]="**",t.push(c),s--}if(!this.preserveMultipleSlashes){for(let n=1;n<r.length-1;n++){let o=r[n];n===1&&o===""&&r[0]===""||(o==="."||o==="")&&(e=!0,r.splice(n,1),n--)}r[0]==="."&&r.length===2&&(r[1]==="."||r[1]==="")&&(e=!0,r.pop())}let i=0;for(;(i=r.indexOf("..",i+1))!==-1;){let n=r[i-1];if(n&&n!=="."&&n!==".."&&n!=="**"){e=!0;let o=i===1&&r[i+1]==="**"?["."]:[];r.splice(i-1,2,...o),r.length===0&&r.push(""),i-=2}}}}while(e);return t}secondPhasePreProcess(t){for(let e=0;e<t.length-1;e++)for(let r=e+1;r<t.length;r++){let s=this.partsMatch(t[e],t[r],!this.preserveMultipleSlashes);if(s){t[e]=[],t[r]=s;break}}return t.filter(e=>e.length)}partsMatch(t,e,r=!1){let s=0,i=0,n=[],o="";for(;s<t.length&&i<e.length;)if(t[s]===e[i])n.push(o==="b"?e[i]:t[s]),s++,i++;else if(r&&t[s]==="**"&&e[i]===t[s+1])n.push(t[s]),s++;else if(r&&e[i]==="**"&&t[s]===e[i+1])n.push(e[i]),i++;else if(t[s]==="*"&&e[i]&&(this.options.dot||!e[i].startsWith("."))&&e[i]!=="**"){if(o==="b")return!1;o="a",n.push(t[s]),s++,i++}else if(e[i]==="*"&&t[s]&&(this.options.dot||!t[s].startsWith("."))&&t[s]!=="**"){if(o==="a")return!1;o="b",n.push(e[i]),s++,i++}else return!1;return t.length===e.length&&n}parseNegate(){if(this.nonegate)return;let t=this.pattern,e=!1,r=0;for(let s=0;s<t.length&&t.charAt(s)==="!";s++)e=!e,r++;r&&(this.pattern=t.slice(r)),this.negate=e}matchOne(t,e,r=!1){let s=this.options;if(this.isWindows){let m=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),g=!m&&t[0]===""&&t[1]===""&&t[2]==="?"&&/^[a-z]:$/i.test(t[3]),w=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),S=!w&&e[0]===""&&e[1]===""&&e[2]==="?"&&typeof e[3]=="string"&&/^[a-z]:$/i.test(e[3]),E=g?3:m?0:void 0,y=S?3:w?0:void 0;if(typeof E=="number"&&typeof y=="number"){let[b,T]=[t[E],e[y]];b.toLowerCase()===T.toLowerCase()&&(e[y]=b,y>E?e=e.slice(y):E>y&&(t=t.slice(E)))}}let{optimizationLevel:i=1}=this.options;i>=2&&(t=this.levelTwoFileOptimize(t)),this.debug("matchOne",this,{file:t,pattern:e}),this.debug("matchOne",t.length,e.length);for(var n=0,o=0,a=t.length,l=e.length;n<a&&o<l;n++,o++){this.debug("matchOne loop");var c=e[o],u=t[n];if(this.debug(e,c,u),c===!1)return!1;if(c===D){this.debug("GLOBSTAR",[e,c,u]);var h=n,p=o+1;if(p===l){for(this.debug("** at the end");n<a;n++)if(t[n]==="."||t[n]===".."||!s.dot&&t[n].charAt(0)===".")return!1;return!0}for(;h<a;){var f=t[h];if(this.debug(`
|
|
13
13
|
globstar while`,t,h,e,p,f),this.matchOne(t.slice(h),e.slice(p),r))return this.debug("globstar found match!",h,a,f),!0;if(f==="."||f===".."||!s.dot&&f.charAt(0)==="."){this.debug("dot detected!",t,h,e,p);break}this.debug("globstar swallow a segment, and continue"),h++}return!!(r&&(this.debug(`
|
|
14
14
|
>>> no match, partial?`,t,h,e,p),h===a))}let m;if(typeof c=="string"?(m=u===c,this.debug("string match",c,u,m)):(m=c.test(u),this.debug("pattern match",c,u,m)),!m)return!1}if(n===a&&o===l)return!0;if(n===a)return r;if(o===l)return n===a-1&&t[n]==="";throw new Error("wtf?")}braceExpand(){return Os(this.pattern,this.options)}parse(t){Tt(t);let e=this.options;if(t==="**")return D;if(t==="")return"";let r,s=null;(r=t.match(Io))?s=e.dot?Po:Do:(r=t.match(_o))?s=(e.nocase?e.dot?Mo:To:e.dot?vo:bo)(r[1]):(r=t.match(xo))?s=(e.nocase?e.dot?No:Lo:e.dot?Uo:Fo)(r):(r=t.match(Co))?s=e.dot?ko:Ao:(r=t.match(Ro))&&(s=Oo);let i=Ms.fromGlob(t,this.options).toMMPattern();return s&&typeof i=="object"&&Reflect.defineProperty(i,"test",{value:s}),i}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let t=this.set;if(!t.length)return this.regexp=!1,this.regexp;let e=this.options,r=e.noglobstar?Ho:e.dot?jo:Bo,s=new Set(e.nocase?["i"]:[]),i=t.map(a=>{let l=a.map(u=>{if(u instanceof RegExp)for(let h of u.flags.split(""))s.add(h);return typeof u=="string"?Jo(u):u===D?D:u._src});l.forEach((u,h)=>{let p=l[h+1],f=l[h-1];u!==D||f===D||(f===void 0?p!==void 0&&p!==D?l[h+1]="(?:\\/|"+r+"\\/)?"+p:l[h]=r:p===void 0?l[h-1]=f+"(?:\\/|\\/"+r+")?":p!==D&&(l[h-1]=f+"(?:\\/|\\/"+r+"\\/)"+p,l[h+1]=D))});let c=l.filter(u=>u!==D);if(this.partial&&c.length>=1){let u=[];for(let h=1;h<=c.length;h++)u.push(c.slice(0,h).join("/"));return"(?:"+u.join("|")+")"}return c.join("/")}).join("|"),[n,o]=t.length>1?["(?:",")"]:["",""];i="^"+n+i+o+"$",this.partial&&(i="^(?:\\/|"+n+i.slice(1,-1)+o+")$"),this.negate&&(i="^(?!"+i+").+$");try{this.regexp=new RegExp(i,[...s].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(t){return this.preserveMultipleSlashes?t.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(t)?["",...t.split(/\/+/)]:t.split(/\/+/)}match(t,e=this.partial){if(this.debug("match",t,this.pattern),this.comment)return!1;if(this.empty)return t==="";if(t==="/"&&e)return!0;let r=this.options;this.isWindows&&(t=t.split("\\").join("/"));let s=this.slashSplit(t);this.debug(this.pattern,"split",s);let i=this.set;this.debug(this.pattern,"set",i);let n=s[s.length-1];if(!n)for(let o=s.length-2;!n&&o>=0;o--)n=s[o];for(let o=0;o<i.length;o++){let a=i[o],l=s;if(r.matchBase&&a.length===1&&(l=[n]),this.matchOne(l,a,e))return r.flipNegate?!0:!this.negate}return r.flipNegate?!1:this.negate}static defaults(t){return P.defaults(t).Minimatch}};P.AST=Ms;P.Minimatch=ge;P.escape=Cs;P.unescape=xe;var Xo=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Ds=new Set,gr=typeof process=="object"&&process?process:{},Ps=(t,e,r,s)=>{typeof gr.emitWarning=="function"?gr.emitWarning(t,e,r,s):console.error(`[${r}] ${e}: ${t}`)},Mt=globalThis.AbortController,ss=globalThis.AbortSignal;if(typeof Mt>"u"){ss=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,s){this._onabort.push(s)}},Mt=class{constructor(){e()}signal=new ss;abort(r){if(!this.signal.aborted){this.signal.reason=r,this.signal.aborted=!0;for(let s of this.signal._onabort)s(r);this.signal.onabort?.(r)}}};let t=gr.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,Ps("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",e))}}var qo=t=>!Ds.has(t),me=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),xs=t=>me(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?bt:null:null,bt=class extends Array{constructor(t){super(t),this.fill(0)}},Vo=class qe{heap;length;static#e=!1;static create(e){let r=xs(e);if(!r)return[];qe.#e=!0;let s=new qe(e,r);return qe.#e=!1,s}constructor(e,r){if(!qe.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new r(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},At=class Ls{#e;#r;#n;#i;#o;#y;#S;#u;get perf(){return this.#u}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#a;#d;#h;#l;#s;#p;#_;#w;#f;#k;#m;#T;#M;#g;#E;#b;#C;#t;#x;static unsafeExposeInternals(e){return{starts:e.#M,ttls:e.#g,autopurgeTimers:e.#E,sizes:e.#T,keyMap:e.#h,keyList:e.#l,valList:e.#s,next:e.#p,prev:e.#_,get head(){return e.#w},get tail(){return e.#f},free:e.#k,isBackgroundFetch:r=>e.#c(r),backgroundFetch:(r,s,i,n)=>e.#j(r,s,i,n),moveToTail:r=>e.#N(r),indexes:r=>e.#O(r),rindexes:r=>e.#I(r),isStale:r=>e.#v(r)}}get max(){return this.#e}get maxSize(){return this.#r}get calculatedSize(){return this.#d}get size(){return this.#a}get fetchMethod(){return this.#y}get memoMethod(){return this.#S}get dispose(){return this.#n}get onInsert(){return this.#i}get disposeAfter(){return this.#o}constructor(e){let{max:r=0,ttl:s,ttlResolution:i=1,ttlAutopurge:n,updateAgeOnGet:o,updateAgeOnHas:a,allowStale:l,dispose:c,onInsert:u,disposeAfter:h,noDisposeOnSet:p,noUpdateTTL:f,maxSize:m=0,maxEntrySize:g=0,sizeCalculation:w,fetchMethod:S,memoMethod:E,noDeleteOnFetchRejection:y,noDeleteOnStaleGet:b,allowStaleOnFetchRejection:T,allowStaleOnFetchAbort:pe,ignoreFetchAbort:Ae,perf:ke}=e;if(ke!==void 0&&typeof ke?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#u=ke??Xo,r!==0&&!me(r))throw new TypeError("max option must be a nonnegative integer");let Re=r?xs(r):Array;if(!Re)throw new Error("invalid max value: "+r);if(this.#e=r,this.#r=m,this.maxEntrySize=g||this.#r,this.sizeCalculation=w,this.sizeCalculation){if(!this.#r&&!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(E!==void 0&&typeof E!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#S=E,S!==void 0&&typeof S!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#y=S,this.#C=!!S,this.#h=new Map,this.#l=new Array(r).fill(void 0),this.#s=new Array(r).fill(void 0),this.#p=new Re(r),this.#_=new Re(r),this.#w=0,this.#f=0,this.#k=Vo.create(r),this.#a=0,this.#d=0,typeof c=="function"&&(this.#n=c),typeof u=="function"&&(this.#i=u),typeof h=="function"?(this.#o=h,this.#m=[]):(this.#o=void 0,this.#m=void 0),this.#b=!!this.#n,this.#x=!!this.#i,this.#t=!!this.#o,this.noDisposeOnSet=!!p,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!y,this.allowStaleOnFetchRejection=!!T,this.allowStaleOnFetchAbort=!!pe,this.ignoreFetchAbort=!!Ae,this.maxEntrySize!==0){if(this.#r!==0&&!me(this.#r))throw new TypeError("maxSize must be a positive integer if specified");if(!me(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#G()}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!b,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!a,this.ttlResolution=me(i)||i===0?i:1,this.ttlAutopurge=!!n,this.ttl=s||0,this.ttl){if(!me(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#D()}if(this.#e===0&&this.ttl===0&&this.#r===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#e&&!this.#r){let tr="LRU_CACHE_UNBOUNDED";qo(tr)&&(Ds.add(tr),Ps("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",tr,Ls))}}getRemainingTTL(e){return this.#h.has(e)?1/0:0}#D(){let e=new bt(this.#e),r=new bt(this.#e);this.#g=e,this.#M=r;let s=this.ttlAutopurge?new Array(this.#e):void 0;this.#E=s,this.#F=(o,a,l=this.#u.now())=>{if(r[o]=a!==0?l:0,e[o]=a,s?.[o]&&(clearTimeout(s[o]),s[o]=void 0),a!==0&&s){let c=setTimeout(()=>{this.#v(o)&&this.#R(this.#l[o],"expire")},a+1);c.unref&&c.unref(),s[o]=c}},this.#A=o=>{r[o]=e[o]!==0?this.#u.now():0},this.#P=(o,a)=>{if(e[a]){let l=e[a],c=r[a];if(!l||!c)return;o.ttl=l,o.start=c,o.now=i||n();let u=o.now-c;o.remainingTTL=l-u}};let i=0,n=()=>{let o=this.#u.now();if(this.ttlResolution>0){i=o;let a=setTimeout(()=>i=0,this.ttlResolution);a.unref&&a.unref()}return o};this.getRemainingTTL=o=>{let a=this.#h.get(o);if(a===void 0)return 0;let l=e[a],c=r[a];if(!l||!c)return 1/0;let u=(i||n())-c;return l-u},this.#v=o=>{let a=r[o],l=e[o];return!!l&&!!a&&(i||n())-a>l}}#A=()=>{};#P=()=>{};#F=()=>{};#v=()=>!1;#G(){let e=new bt(this.#e);this.#d=0,this.#T=e,this.#U=r=>{this.#d-=e[r],e[r]=0},this.#W=(r,s,i,n)=>{if(this.#c(s))return 0;if(!me(i))if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(i=n(s,r),!me(i))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 i},this.#L=(r,s,i)=>{if(e[r]=s,this.#r){let n=this.#r-e[r];for(;this.#d>n;)this.#H(!0)}this.#d+=e[r],i&&(i.entrySize=s,i.totalCalculatedSize=this.#d)}}#U=e=>{};#L=(e,r,s)=>{};#W=(e,r,s,i)=>{if(s||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#O({allowStale:e=this.allowStale}={}){if(this.#a)for(let r=this.#f;!(!this.#$(r)||((e||!this.#v(r))&&(yield r),r===this.#w));)r=this.#_[r]}*#I({allowStale:e=this.allowStale}={}){if(this.#a)for(let r=this.#w;!(!this.#$(r)||((e||!this.#v(r))&&(yield r),r===this.#f));)r=this.#p[r]}#$(e){return e!==void 0&&this.#h.get(this.#l[e])===e}*entries(){for(let e of this.#O())this.#s[e]!==void 0&&this.#l[e]!==void 0&&!this.#c(this.#s[e])&&(yield[this.#l[e],this.#s[e]])}*rentries(){for(let e of this.#I())this.#s[e]!==void 0&&this.#l[e]!==void 0&&!this.#c(this.#s[e])&&(yield[this.#l[e],this.#s[e]])}*keys(){for(let e of this.#O()){let r=this.#l[e];r!==void 0&&!this.#c(this.#s[e])&&(yield r)}}*rkeys(){for(let e of this.#I()){let r=this.#l[e];r!==void 0&&!this.#c(this.#s[e])&&(yield r)}}*values(){for(let e of this.#O())this.#s[e]!==void 0&&!this.#c(this.#s[e])&&(yield this.#s[e])}*rvalues(){for(let e of this.#I())this.#s[e]!==void 0&&!this.#c(this.#s[e])&&(yield this.#s[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,r={}){for(let s of this.#O()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;if(n!==void 0&&e(n,this.#l[s],this))return this.get(this.#l[s],r)}}forEach(e,r=this){for(let s of this.#O()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;n!==void 0&&e.call(r,n,this.#l[s],this)}}rforEach(e,r=this){for(let s of this.#I()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;n!==void 0&&e.call(r,n,this.#l[s],this)}}purgeStale(){let e=!1;for(let r of this.#I({allowStale:!0}))this.#v(r)&&(this.#R(this.#l[r],"expire"),e=!0);return e}info(e){let r=this.#h.get(e);if(r===void 0)return;let s=this.#s[r],i=this.#c(s)?s.__staleWhileFetching:s;if(i===void 0)return;let n={value:i};if(this.#g&&this.#M){let o=this.#g[r],a=this.#M[r];if(o&&a){let l=o-(this.#u.now()-a);n.ttl=l,n.start=Date.now()}}return this.#T&&(n.size=this.#T[r]),n}dump(){let e=[];for(let r of this.#O({allowStale:!0})){let s=this.#l[r],i=this.#s[r],n=this.#c(i)?i.__staleWhileFetching:i;if(n===void 0||s===void 0)continue;let o={value:n};if(this.#g&&this.#M){o.ttl=this.#g[r];let a=this.#u.now()-this.#M[r];o.start=Math.floor(Date.now()-a)}this.#T&&(o.size=this.#T[r]),e.unshift([s,o])}return e}load(e){this.clear();for(let[r,s]of e){if(s.start){let i=Date.now()-s.start;s.start=this.#u.now()-i}this.set(r,s.value,s)}}set(e,r,s={}){if(r===void 0)return this.delete(e),this;let{ttl:i=this.ttl,start:n,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=s,{noUpdateTTL:c=this.noUpdateTTL}=s,u=this.#W(e,r,s.size||0,a);if(this.maxEntrySize&&u>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=!0),this.#R(e,"set"),this;let h=this.#a===0?void 0:this.#h.get(e);if(h===void 0)h=this.#a===0?this.#f:this.#k.length!==0?this.#k.pop():this.#a===this.#e?this.#H(!1):this.#a,this.#l[h]=e,this.#s[h]=r,this.#h.set(e,h),this.#p[this.#f]=h,this.#_[h]=this.#f,this.#f=h,this.#a++,this.#L(h,u,l),l&&(l.set="add"),c=!1,this.#x&&this.#i?.(r,e,"add");else{this.#N(h);let p=this.#s[h];if(r!==p){if(this.#C&&this.#c(p)){p.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:f}=p;f!==void 0&&!o&&(this.#b&&this.#n?.(f,e,"set"),this.#t&&this.#m?.push([f,e,"set"]))}else o||(this.#b&&this.#n?.(p,e,"set"),this.#t&&this.#m?.push([p,e,"set"]));if(this.#U(h),this.#L(h,u,l),this.#s[h]=r,l){l.set="replace";let f=p&&this.#c(p)?p.__staleWhileFetching:p;f!==void 0&&(l.oldValue=f)}}else l&&(l.set="update");this.#x&&this.onInsert?.(r,e,r===p?"update":"replace")}if(i!==0&&!this.#g&&this.#D(),this.#g&&(c||this.#F(h,i,n),l&&this.#P(l,h)),!o&&this.#t&&this.#m){let p=this.#m,f;for(;f=p?.shift();)this.#o?.(...f)}return this}pop(){try{for(;this.#a;){let e=this.#s[this.#w];if(this.#H(!0),this.#c(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#t&&this.#m){let e=this.#m,r;for(;r=e?.shift();)this.#o?.(...r)}}}#H(e){let r=this.#w,s=this.#l[r],i=this.#s[r];return this.#C&&this.#c(i)?i.__abortController.abort(new Error("evicted")):(this.#b||this.#t)&&(this.#b&&this.#n?.(i,s,"evict"),this.#t&&this.#m?.push([i,s,"evict"])),this.#U(r),this.#E?.[r]&&(clearTimeout(this.#E[r]),this.#E[r]=void 0),e&&(this.#l[r]=void 0,this.#s[r]=void 0,this.#k.push(r)),this.#a===1?(this.#w=this.#f=0,this.#k.length=0):this.#w=this.#p[r],this.#h.delete(s),this.#a--,r}has(e,r={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:i}=r,n=this.#h.get(e);if(n!==void 0){let o=this.#s[n];if(this.#c(o)&&o.__staleWhileFetching===void 0)return!1;if(this.#v(n))i&&(i.has="stale",this.#P(i,n));else return s&&this.#A(n),i&&(i.has="hit",this.#P(i,n)),!0}else i&&(i.has="miss");return!1}peek(e,r={}){let{allowStale:s=this.allowStale}=r,i=this.#h.get(e);if(i===void 0||!s&&this.#v(i))return;let n=this.#s[i];return this.#c(n)?n.__staleWhileFetching:n}#j(e,r,s,i){let n=r===void 0?void 0:this.#s[r];if(this.#c(n))return n;let o=new Mt,{signal:a}=s;a?.addEventListener("abort",()=>o.abort(a.reason),{signal:o.signal});let l={signal:o.signal,options:s,context:i},c=(g,w=!1)=>{let{aborted:S}=o.signal,E=s.ignoreFetchAbort&&g!==void 0,y=s.ignoreFetchAbort||!!(s.allowStaleOnFetchAbort&&g!==void 0);if(s.status&&(S&&!w?(s.status.fetchAborted=!0,s.status.fetchError=o.signal.reason,E&&(s.status.fetchAbortIgnored=!0)):s.status.fetchResolved=!0),S&&!E&&!w)return h(o.signal.reason,y);let b=f,T=this.#s[r];return(T===f||E&&w&&T===void 0)&&(g===void 0?b.__staleWhileFetching!==void 0?this.#s[r]=b.__staleWhileFetching:this.#R(e,"fetch"):(s.status&&(s.status.fetchUpdated=!0),this.set(e,g,l.options))),g},u=g=>(s.status&&(s.status.fetchRejected=!0,s.status.fetchError=g),h(g,!1)),h=(g,w)=>{let{aborted:S}=o.signal,E=S&&s.allowStaleOnFetchAbort,y=E||s.allowStaleOnFetchRejection,b=y||s.noDeleteOnFetchRejection,T=f;if(this.#s[r]===f&&(!b||!w&&T.__staleWhileFetching===void 0?this.#R(e,"fetch"):E||(this.#s[r]=T.__staleWhileFetching)),y)return s.status&&T.__staleWhileFetching!==void 0&&(s.status.returnedStale=!0),T.__staleWhileFetching;if(T.__returned===T)throw g},p=(g,w)=>{let S=this.#y?.(e,n,l);S&&S instanceof Promise&&S.then(E=>g(E===void 0?void 0:E),w),o.signal.addEventListener("abort",()=>{(!s.ignoreFetchAbort||s.allowStaleOnFetchAbort)&&(g(void 0),s.allowStaleOnFetchAbort&&(g=E=>c(E,!0)))})};s.status&&(s.status.fetchDispatched=!0);let f=new Promise(p).then(c,u),m=Object.assign(f,{__abortController:o,__staleWhileFetching:n,__returned:void 0});return r===void 0?(this.set(e,m,{...l.options,status:void 0}),r=this.#h.get(e)):this.#s[r]=m,m}#c(e){if(!this.#C)return!1;let r=e;return!!r&&r instanceof Promise&&r.hasOwnProperty("__staleWhileFetching")&&r.__abortController instanceof Mt}async fetch(e,r={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:l=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:h=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:p=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:m=this.allowStaleOnFetchAbort,context:g,forceRefresh:w=!1,status:S,signal:E}=r;if(!this.#C)return S&&(S.fetch="get"),this.get(e,{allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:n,status:S});let y={allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:n,ttl:o,noDisposeOnSet:a,size:l,sizeCalculation:c,noUpdateTTL:u,noDeleteOnFetchRejection:h,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:m,ignoreFetchAbort:f,status:S,signal:E},b=this.#h.get(e);if(b===void 0){S&&(S.fetch="miss");let T=this.#j(e,b,y,g);return T.__returned=T}else{let T=this.#s[b];if(this.#c(T)){let Re=s&&T.__staleWhileFetching!==void 0;return S&&(S.fetch="inflight",Re&&(S.returnedStale=!0)),Re?T.__staleWhileFetching:T.__returned=T}let pe=this.#v(b);if(!w&&!pe)return S&&(S.fetch="hit"),this.#N(b),i&&this.#A(b),S&&this.#P(S,b),T;let Ae=this.#j(e,b,y,g),ke=Ae.__staleWhileFetching!==void 0&&s;return S&&(S.fetch=pe?"stale":"refresh",ke&&pe&&(S.returnedStale=!0)),ke?Ae.__staleWhileFetching:Ae.__returned=Ae}}async forceFetch(e,r={}){let s=await this.fetch(e,r);if(s===void 0)throw new Error("fetch() returned undefined");return s}memo(e,r={}){let s=this.#S;if(!s)throw new Error("no memoMethod provided to constructor");let{context:i,forceRefresh:n,...o}=r,a=this.get(e,o);if(!n&&a!==void 0)return a;let l=s(e,a,{options:o,context:i});return this.set(e,l,o),l}get(e,r={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:o}=r,a=this.#h.get(e);if(a!==void 0){let l=this.#s[a],c=this.#c(l);return o&&this.#P(o,a),this.#v(a)?(o&&(o.get="stale"),c?(o&&s&&l.__staleWhileFetching!==void 0&&(o.returnedStale=!0),s?l.__staleWhileFetching:void 0):(n||this.#R(e,"expire"),o&&s&&(o.returnedStale=!0),s?l:void 0)):(o&&(o.get="hit"),c?l.__staleWhileFetching:(this.#N(a),i&&this.#A(a),l))}else o&&(o.get="miss")}#B(e,r){this.#_[r]=e,this.#p[e]=r}#N(e){e!==this.#f&&(e===this.#w?this.#w=this.#p[e]:this.#B(this.#_[e],this.#p[e]),this.#B(this.#f,e),this.#f=e)}delete(e){return this.#R(e,"delete")}#R(e,r){let s=!1;if(this.#a!==0){let i=this.#h.get(e);if(i!==void 0)if(this.#E?.[i]&&(clearTimeout(this.#E?.[i]),this.#E[i]=void 0),s=!0,this.#a===1)this.#K(r);else{this.#U(i);let n=this.#s[i];if(this.#c(n)?n.__abortController.abort(new Error("deleted")):(this.#b||this.#t)&&(this.#b&&this.#n?.(n,e,r),this.#t&&this.#m?.push([n,e,r])),this.#h.delete(e),this.#l[i]=void 0,this.#s[i]=void 0,i===this.#f)this.#f=this.#_[i];else if(i===this.#w)this.#w=this.#p[i];else{let o=this.#_[i];this.#p[o]=this.#p[i];let a=this.#p[i];this.#_[a]=this.#_[i]}this.#a--,this.#k.push(i)}}if(this.#t&&this.#m?.length){let i=this.#m,n;for(;n=i?.shift();)this.#o?.(...n)}return s}clear(){return this.#K("delete")}#K(e){for(let r of this.#I({allowStale:!0})){let s=this.#s[r];if(this.#c(s))s.__abortController.abort(new Error("deleted"));else{let i=this.#l[r];this.#b&&this.#n?.(s,i,e),this.#t&&this.#m?.push([s,i,e])}}if(this.#h.clear(),this.#s.fill(void 0),this.#l.fill(void 0),this.#g&&this.#M){this.#g.fill(0),this.#M.fill(0);for(let r of this.#E??[])r!==void 0&&clearTimeout(r);this.#E?.fill(void 0)}if(this.#T&&this.#T.fill(0),this.#w=0,this.#f=0,this.#k.length=0,this.#d=0,this.#a=0,this.#t&&this.#m){let r=this.#m,s;for(;s=r?.shift();)this.#o?.(...s)}}},is=typeof process=="object"&&process?process:{stdout:null,stderr:null},Zo=t=>!!t&&typeof t=="object"&&(t instanceof Ct||t instanceof wr.default||ea(t)||ta(t)),ea=t=>!!t&&typeof t=="object"&&t instanceof kt.EventEmitter&&typeof t.pipe=="function"&&t.pipe!==wr.default.Writable.prototype.pipe,ta=t=>!!t&&typeof t=="object"&&t instanceof kt.EventEmitter&&typeof t.write=="function"&&typeof t.end=="function",oe=Symbol("EOF"),ae=Symbol("maybeEmitEnd"),fe=Symbol("emittedEnd"),mt=Symbol("emittingEnd"),Ge=Symbol("emittedError"),gt=Symbol("closed"),ns=Symbol("read"),St=Symbol("flush"),os=Symbol("flushChunk"),G=Symbol("encoding"),De=Symbol("decoder"),C=Symbol("flowing"),Ke=Symbol("paused"),Pe=Symbol("resume"),A=Symbol("buffer"),I=Symbol("pipes"),k=Symbol("bufferLength"),cr=Symbol("bufferPush"),Et=Symbol("bufferShift"),O=Symbol("objectMode"),M=Symbol("destroyed"),ur=Symbol("error"),hr=Symbol("emitData"),as=Symbol("emitEnd"),dr=Symbol("emitEnd2"),q=Symbol("async"),pr=Symbol("abort"),wt=Symbol("aborted"),Ye=Symbol("signal"),ye=Symbol("dataListeners"),U=Symbol("discarded"),ze=t=>Promise.resolve().then(t),ra=t=>t(),sa=t=>t==="end"||t==="finish"||t==="prefinish",ia=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,na=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Fs=class{src;dest;opts;ondrain;constructor(t,e,r){this.src=t,this.dest=e,this.opts=r,this.ondrain=()=>t[Pe](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},oa=class extends Fs{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,r){super(t,e,r),this.proxyErrors=s=>this.dest.emit("error",s),t.on("error",this.proxyErrors)}},aa=t=>!!t.objectMode,la=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Ct=class extends kt.EventEmitter{[C]=!1;[Ke]=!1;[I]=[];[A]=[];[O];[G];[q];[De];[oe]=!1;[fe]=!1;[mt]=!1;[gt]=!1;[Ge]=null;[k]=0;[M]=!1;[Ye];[wt]=!1;[ye]=0;[U]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");aa(e)?(this[O]=!0,this[G]=null):la(e)?(this[G]=e.encoding,this[O]=!1):(this[O]=!1,this[G]=null),this[q]=!!e.async,this[De]=this[G]?new Us.StringDecoder(this[G]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[A]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[I]});let{signal:r}=e;r&&(this[Ye]=r,r.aborted?this[pr]():r.addEventListener("abort",()=>this[pr]()))}get bufferLength(){return this[k]}get encoding(){return this[G]}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[O]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[q]}set async(t){this[q]=this[q]||!!t}[pr](){this[wt]=!0,this.emit("abort",this[Ye]?.reason),this.destroy(this[Ye]?.reason)}get aborted(){return this[wt]}set aborted(t){}write(t,e,r){if(this[wt])return!1;if(this[oe])throw new Error("write after end");if(this[M])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(r=e,e="utf8"),e||(e="utf8");let s=this[q]?ze:ra;if(!this[O]&&!Buffer.isBuffer(t)){if(na(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(ia(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[O]?(this[C]&&this[k]!==0&&this[St](!0),this[C]?this.emit("data",t):this[cr](t),this[k]!==0&&this.emit("readable"),r&&s(r),this[C]):t.length?(typeof t=="string"&&!(e===this[G]&&!this[De]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[G]&&(t=this[De].write(t)),this[C]&&this[k]!==0&&this[St](!0),this[C]?this.emit("data",t):this[cr](t),this[k]!==0&&this.emit("readable"),r&&s(r),this[C]):(this[k]!==0&&this.emit("readable"),r&&s(r),this[C])}read(t){if(this[M])return null;if(this[U]=!1,this[k]===0||t===0||t&&t>this[k])return this[ae](),null;this[O]&&(t=null),this[A].length>1&&!this[O]&&(this[A]=[this[G]?this[A].join(""):Buffer.concat(this[A],this[k])]);let e=this[ns](t||null,this[A][0]);return this[ae](),e}[ns](t,e){if(this[O])this[Et]();else{let r=e;t===r.length||t===null?this[Et]():typeof r=="string"?(this[A][0]=r.slice(t),e=r.slice(0,t),this[k]-=t):(this[A][0]=r.subarray(t),e=r.subarray(0,t),this[k]-=t)}return this.emit("data",e),!this[A].length&&!this[oe]&&this.emit("drain"),e}end(t,e,r){return typeof t=="function"&&(r=t,t=void 0),typeof e=="function"&&(r=e,e="utf8"),t!==void 0&&this.write(t,e),r&&this.once("end",r),this[oe]=!0,this.writable=!1,(this[C]||!this[Ke])&&this[ae](),this}[Pe](){this[M]||(!this[ye]&&!this[I].length&&(this[U]=!0),this[Ke]=!1,this[C]=!0,this.emit("resume"),this[A].length?this[St]():this[oe]?this[ae]():this.emit("drain"))}resume(){return this[Pe]()}pause(){this[C]=!1,this[Ke]=!0,this[U]=!1}get destroyed(){return this[M]}get flowing(){return this[C]}get paused(){return this[Ke]}[cr](t){this[O]?this[k]+=1:this[k]+=t.length,this[A].push(t)}[Et](){return this[O]?this[k]-=1:this[k]-=this[A][0].length,this[A].shift()}[St](t=!1){do;while(this[os](this[Et]())&&this[A].length);!t&&!this[A].length&&!this[oe]&&this.emit("drain")}[os](t){return this.emit("data",t),this[C]}pipe(t,e){if(this[M])return t;this[U]=!1;let r=this[fe];return e=e||{},t===is.stdout||t===is.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[I].push(e.proxyErrors?new oa(this,t,e):new Fs(this,t,e)),this[q]?ze(()=>this[Pe]()):this[Pe]()),t}unpipe(t){let e=this[I].find(r=>r.dest===t);e&&(this[I].length===1?(this[C]&&this[ye]===0&&(this[C]=!1),this[I]=[]):this[I].splice(this[I].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let r=super.on(t,e);if(t==="data")this[U]=!1,this[ye]++,!this[I].length&&!this[C]&&this[Pe]();else if(t==="readable"&&this[k]!==0)super.emit("readable");else if(sa(t)&&this[fe])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[Ge]){let s=e;this[q]?ze(()=>s.call(this,this[Ge])):s.call(this,this[Ge])}return r}removeListener(t,e){return this.off(t,e)}off(t,e){let r=super.off(t,e);return t==="data"&&(this[ye]=this.listeners("data").length,this[ye]===0&&!this[U]&&!this[I].length&&(this[C]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[ye]=0,!this[U]&&!this[I].length&&(this[C]=!1)),e}get emittedEnd(){return this[fe]}[ae](){!this[mt]&&!this[fe]&&!this[M]&&this[A].length===0&&this[oe]&&(this[mt]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[gt]&&this.emit("close"),this[mt]=!1)}emit(t,...e){let r=e[0];if(t!=="error"&&t!=="close"&&t!==M&&this[M])return!1;if(t==="data")return!this[O]&&!r?!1:this[q]?(ze(()=>this[hr](r)),!0):this[hr](r);if(t==="end")return this[as]();if(t==="close"){if(this[gt]=!0,!this[fe]&&!this[M])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(t==="error"){this[Ge]=r,super.emit(ur,r);let i=!this[Ye]||this.listeners("error").length?super.emit("error",r):!1;return this[ae](),i}else if(t==="resume"){let i=super.emit("resume");return this[ae](),i}else if(t==="finish"||t==="prefinish"){let i=super.emit(t);return this.removeAllListeners(t),i}let s=super.emit(t,...e);return this[ae](),s}[hr](t){for(let r of this[I])r.dest.write(t)===!1&&this.pause();let e=this[U]?!1:super.emit("data",t);return this[ae](),e}[as](){return this[fe]?!1:(this[fe]=!0,this.readable=!1,this[q]?(ze(()=>this[dr]()),!0):this[dr]())}[dr](){if(this[De]){let e=this[De].end();if(e){for(let r of this[I])r.dest.write(e);this[U]||super.emit("data",e)}}for(let e of this[I])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[O]||(t.dataLength=0);let e=this.promise();return this.on("data",r=>{t.push(r),this[O]||(t.dataLength+=r.length)}),await e,t}async concat(){if(this[O])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[G]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(M,()=>e(new Error("stream destroyed"))),this.on("error",r=>e(r)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[U]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let r=this.read();if(r!==null)return Promise.resolve({done:!1,value:r});if(this[oe])return e();let s,i,n=c=>{this.off("data",o),this.off("end",a),this.off(M,l),e(),i(c)},o=c=>{this.off("error",n),this.off("end",a),this.off(M,l),this.pause(),s({value:c,done:!!this[oe]})},a=()=>{this.off("error",n),this.off("data",o),this.off(M,l),e(),s({done:!0,value:void 0})},l=()=>n(new Error("stream destroyed"));return new Promise((c,u)=>{i=u,s=c,this.once(M,l),this.once("error",n),this.once("end",a),this.once("data",o)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[U]=!1;let t=!1,e=()=>(this.pause(),this.off(ur,e),this.off(M,e),this.off("end",e),t=!0,{done:!0,value:void 0}),r=()=>{if(t)return e();let s=this.read();return s===null?e():{done:!1,value:s}};return this.once("end",e),this.once(ur,e),this.once(M,e),{next:r,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[M])return t?this.emit("error",t):this.emit(M),this;this[M]=!0,this[U]=!0,this[A].length=0,this[k]=0;let e=this;return typeof e.close=="function"&&!this[gt]&&e.close(),t?this.emit("error",t):this.emit(M),this}static get isStream(){return Zo}},ca=Q.realpathSync.native,Ve={lstatSync:Q.lstatSync,readdir:Q.readdir,readdirSync:Q.readdirSync,readlinkSync:Q.readlinkSync,realpathSync:ca,promises:{lstat:Se.lstat,readdir:Se.readdir,readlink:Se.readlink,realpath:Se.realpath}},Ws=t=>!t||t===Ve||t===Qo?Ve:{...Ve,...t,promises:{...Ve.promises,...t.promises||{}}},$s=/^\\\\\?\\([a-z]:)\\?$/i,ua=t=>t.replace(/\//g,"\\").replace($s,"$1\\"),ha=/[\\\/]/,j=0,Hs=1,js=2,V=4,Bs=6,Gs=8,_e=10,Ks=12,H=15,Je=~H,fr=16,ls=32,Qe=64,K=128,yt=256,vt=512,cs=Qe|K|vt,da=1023,mr=t=>t.isFile()?Gs:t.isDirectory()?V:t.isSymbolicLink()?_e:t.isCharacterDevice()?js:t.isBlockDevice()?Bs:t.isSocket()?Ks:t.isFIFO()?Hs:j,us=new At({max:2**12}),Ze=t=>{let e=us.get(t);if(e)return e;let r=t.normalize("NFKD");return us.set(t,r),r},hs=new At({max:2**12}),_t=t=>{let e=hs.get(t);if(e)return e;let r=Ze(t.toLowerCase());return hs.set(t,r),r},ds=class extends At{constructor(){super({max:256})}},pa=class extends At{constructor(t=16*1024){super({maxSize:t,sizeCalculation:e=>e.length+1})}},Ys=Symbol("PathScurry setAsCwd"),L=class{name;root;roots;parent;nocase;isCWD=!1;#e;#r;get dev(){return this.#r}#n;get mode(){return this.#n}#i;get nlink(){return this.#i}#o;get uid(){return this.#o}#y;get gid(){return this.#y}#S;get rdev(){return this.#S}#u;get blksize(){return this.#u}#a;get ino(){return this.#a}#d;get size(){return this.#d}#h;get blocks(){return this.#h}#l;get atimeMs(){return this.#l}#s;get mtimeMs(){return this.#s}#p;get ctimeMs(){return this.#p}#_;get birthtimeMs(){return this.#_}#w;get atime(){return this.#w}#f;get mtime(){return this.#f}#k;get ctime(){return this.#k}#m;get birthtime(){return this.#m}#T;#M;#g;#E;#b;#C;#t;#x;#D;#A;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(t,e=j,r,s,i,n,o){this.name=t,this.#T=i?_t(t):Ze(t),this.#t=e&da,this.nocase=i,this.roots=s,this.root=r||this,this.#x=n,this.#g=o.fullpath,this.#b=o.relative,this.#C=o.relativePosix,this.parent=o.parent,this.parent?this.#e=this.parent.#e:this.#e=Ws(o.fs)}depth(){return this.#M!==void 0?this.#M:this.parent?this.#M=this.parent.depth()+1:this.#M=0}childrenCache(){return this.#x}resolve(t){if(!t)return this;let e=this.getRootString(t),r=t.substring(e.length).split(this.splitSep);return e?this.getRoot(e).#P(r):this.#P(r)}#P(t){let e=this;for(let r of t)e=e.child(r);return e}children(){let t=this.#x.get(this);if(t)return t;let e=Object.assign([],{provisional:0});return this.#x.set(this,e),this.#t&=~fr,e}child(t,e){if(t===""||t===".")return this;if(t==="..")return this.parent||this;let r=this.children(),s=this.nocase?_t(t):Ze(t);for(let a of r)if(a.#T===s)return a;let i=this.parent?this.sep:"",n=this.#g?this.#g+i+t:void 0,o=this.newChild(t,j,{...e,parent:this,fullpath:n});return this.canReaddir()||(o.#t|=K),r.push(o),o}relative(){if(this.isCWD)return"";if(this.#b!==void 0)return this.#b;let t=this.name,e=this.parent;if(!e)return this.#b=this.name;let r=e.relative();return r+(!r||!e.parent?"":this.sep)+t}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#C!==void 0)return this.#C;let t=this.name,e=this.parent;if(!e)return this.#C=this.fullpathPosix();let r=e.relativePosix();return r+(!r||!e.parent?"":"/")+t}fullpath(){if(this.#g!==void 0)return this.#g;let t=this.name,e=this.parent;if(!e)return this.#g=this.name;let r=e.fullpath()+(e.parent?this.sep:"")+t;return this.#g=r}fullpathPosix(){if(this.#E!==void 0)return this.#E;if(this.sep==="/")return this.#E=this.fullpath();if(!this.parent){let s=this.fullpath().replace(/\\/g,"/");return/^[a-z]:\//i.test(s)?this.#E=`//?/${s}`:this.#E=s}let t=this.parent,e=t.fullpathPosix(),r=e+(!e||!t.parent?"":"/")+this.name;return this.#E=r}isUnknown(){return(this.#t&H)===j}isType(t){return this[`is${t}`]()}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(this.#t&H)===Gs}isDirectory(){return(this.#t&H)===V}isCharacterDevice(){return(this.#t&H)===js}isBlockDevice(){return(this.#t&H)===Bs}isFIFO(){return(this.#t&H)===Hs}isSocket(){return(this.#t&H)===Ks}isSymbolicLink(){return(this.#t&_e)===_e}lstatCached(){return this.#t&ls?this:void 0}readlinkCached(){return this.#D}realpathCached(){return this.#A}readdirCached(){let t=this.children();return t.slice(0,t.provisional)}canReadlink(){if(this.#D)return!0;if(!this.parent)return!1;let t=this.#t&H;return!(t!==j&&t!==_e||this.#t&yt||this.#t&K)}calledReaddir(){return!!(this.#t&fr)}isENOENT(){return!!(this.#t&K)}isNamed(t){return this.nocase?this.#T===_t(t):this.#T===Ze(t)}async readlink(){let t=this.#D;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=await this.#e.promises.readlink(this.fullpath()),r=(await this.parent.realpath())?.resolve(e);if(r)return this.#D=r}catch(e){this.#I(e.code);return}}readlinkSync(){let t=this.#D;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=this.#e.readlinkSync(this.fullpath()),r=this.parent.realpathSync()?.resolve(e);if(r)return this.#D=r}catch(e){this.#I(e.code);return}}#F(t){this.#t|=fr;for(let e=t.provisional;e<t.length;e++){let r=t[e];r&&r.#v()}}#v(){this.#t&K||(this.#t=(this.#t|K)&Je,this.#G())}#G(){let t=this.children();t.provisional=0;for(let e of t)e.#v()}#U(){this.#t|=vt,this.#L()}#L(){if(this.#t&Qe)return;let t=this.#t;(t&H)===V&&(t&=Je),this.#t=t|Qe,this.#G()}#W(t=""){t==="ENOTDIR"||t==="EPERM"?this.#L():t==="ENOENT"?this.#v():this.children().provisional=0}#O(t=""){t==="ENOTDIR"?this.parent.#L():t==="ENOENT"&&this.#v()}#I(t=""){let e=this.#t;e|=yt,t==="ENOENT"&&(e|=K),(t==="EINVAL"||t==="UNKNOWN")&&(e&=Je),this.#t=e,t==="ENOTDIR"&&this.parent&&this.parent.#L()}#$(t,e){return this.#j(t,e)||this.#H(t,e)}#H(t,e){let r=mr(t),s=this.newChild(t.name,r,{parent:this}),i=s.#t&H;return i!==V&&i!==_e&&i!==j&&(s.#t|=Qe),e.unshift(s),e.provisional++,s}#j(t,e){for(let r=e.provisional;r<e.length;r++){let s=e[r];if((this.nocase?_t(t.name):Ze(t.name))===s.#T)return this.#c(t,s,r,e)}}#c(t,e,r,s){let i=e.name;return e.#t=e.#t&Je|mr(t),i!==t.name&&(e.name=t.name),r!==s.provisional&&(r===s.length-1?s.pop():s.splice(r,1),s.unshift(e)),s.provisional++,e}async lstat(){if((this.#t&K)===0)try{return this.#B(await this.#e.promises.lstat(this.fullpath())),this}catch(t){this.#O(t.code)}}lstatSync(){if((this.#t&K)===0)try{return this.#B(this.#e.lstatSync(this.fullpath())),this}catch(t){this.#O(t.code)}}#B(t){let{atime:e,atimeMs:r,birthtime:s,birthtimeMs:i,blksize:n,blocks:o,ctime:a,ctimeMs:l,dev:c,gid:u,ino:h,mode:p,mtime:f,mtimeMs:m,nlink:g,rdev:w,size:S,uid:E}=t;this.#w=e,this.#l=r,this.#m=s,this.#_=i,this.#u=n,this.#h=o,this.#k=a,this.#p=l,this.#r=c,this.#y=u,this.#a=h,this.#n=p,this.#f=f,this.#s=m,this.#i=g,this.#S=w,this.#d=S,this.#o=E;let y=mr(t);this.#t=this.#t&Je|y|ls,y!==j&&y!==V&&y!==_e&&(this.#t|=Qe)}#N=[];#R=!1;#K(t){this.#R=!1;let e=this.#N.slice();this.#N.length=0,e.forEach(r=>r(null,t))}readdirCB(t,e=!1){if(!this.canReaddir()){e?t(null,[]):queueMicrotask(()=>t(null,[]));return}let r=this.children();if(this.calledReaddir()){let i=r.slice(0,r.provisional);e?t(null,i):queueMicrotask(()=>t(null,i));return}if(this.#N.push(t),this.#R)return;this.#R=!0;let s=this.fullpath();this.#e.readdir(s,{withFileTypes:!0},(i,n)=>{if(i)this.#W(i.code),r.provisional=0;else{for(let o of n)this.#$(o,r);this.#F(r)}this.#K(r.slice(0,r.provisional))})}#Y;async readdir(){if(!this.canReaddir())return[];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();if(this.#Y)await this.#Y;else{let r=()=>{};this.#Y=new Promise(s=>r=s);try{for(let s of await this.#e.promises.readdir(e,{withFileTypes:!0}))this.#$(s,t);this.#F(t)}catch(s){this.#W(s.code),t.provisional=0}this.#Y=void 0,r()}return t.slice(0,t.provisional)}readdirSync(){if(!this.canReaddir())return[];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();try{for(let r of this.#e.readdirSync(e,{withFileTypes:!0}))this.#$(r,t);this.#F(t)}catch(r){this.#W(r.code),t.provisional=0}return t.slice(0,t.provisional)}canReaddir(){if(this.#t&cs)return!1;let t=H&this.#t;return t===j||t===V||t===_e}shouldWalk(t,e){return(this.#t&V)===V&&!(this.#t&cs)&&!t.has(this)&&(!e||e(this))}async realpath(){if(this.#A)return this.#A;if(!((vt|yt|K)&this.#t))try{let t=await this.#e.promises.realpath(this.fullpath());return this.#A=this.resolve(t)}catch{this.#U()}}realpathSync(){if(this.#A)return this.#A;if(!((vt|yt|K)&this.#t))try{let t=this.#e.realpathSync(this.fullpath());return this.#A=this.resolve(t)}catch{this.#U()}}[Ys](t){if(t===this)return;t.isCWD=!1,this.isCWD=!0;let e=new Set([]),r=[],s=this;for(;s&&s.parent;)e.add(s),s.#b=r.join(this.sep),s.#C=r.join("/"),s=s.parent,r.push("..");for(s=t;s&&s.parent&&!e.has(s);)s.#b=void 0,s.#C=void 0,s=s.parent}},zs=class Js extends L{sep="\\";splitSep=ha;constructor(e,r=j,s,i,n,o,a){super(e,r,s,i,n,o,a)}newChild(e,r=j,s={}){return new Js(e,r,this.root,this.roots,this.nocase,this.childrenCache(),s)}getRootString(e){return Le.win32.parse(e).root}getRoot(e){if(e=ua(e.toUpperCase()),e===this.root.name)return this.root;for(let[r,s]of Object.entries(this.roots))if(this.sameRoot(e,r))return this.roots[e]=s;return this.roots[e]=new yr(e,this).root}sameRoot(e,r=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace($s,"$1\\"),e===r}},Xs=class qs extends L{splitSep="/";sep="/";constructor(e,r=j,s,i,n,o,a){super(e,r,s,i,n,o,a)}getRootString(e){return e.startsWith("/")?"/":""}getRoot(e){return this.root}newChild(e,r=j,s={}){return new qs(e,r,this.root,this.roots,this.nocase,this.childrenCache(),s)}},Vs=class{root;rootPath;roots;cwd;#e;#r;#n;nocase;#i;constructor(t=process.cwd(),e,r,{nocase:s,childrenCacheSize:i=16*1024,fs:n=Ve}={}){this.#i=Ws(n),(t instanceof URL||t.startsWith("file://"))&&(t=(0,Ns.fileURLToPath)(t));let o=e.resolve(t);this.roots=Object.create(null),this.rootPath=this.parseRootPath(o),this.#e=new ds,this.#r=new ds,this.#n=new pa(i);let a=o.substring(this.rootPath.length).split(r);if(a.length===1&&!a[0]&&a.pop(),s===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=s,this.root=this.newRoot(this.#i),this.roots[this.rootPath]=this.root;let l=this.root,c=a.length-1,u=e.sep,h=this.rootPath,p=!1;for(let f of a){let m=c--;l=l.child(f,{relative:new Array(m).fill("..").join(u),relativePosix:new Array(m).fill("..").join("/"),fullpath:h+=(p?"":u)+f}),p=!0}this.cwd=l}depth(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.depth()}childrenCache(){return this.#n}resolve(...t){let e="";for(let i=t.length-1;i>=0;i--){let n=t[i];if(!(!n||n===".")&&(e=e?`${n}/${e}`:n,this.isAbsolute(n)))break}let r=this.#e.get(e);if(r!==void 0)return r;let s=this.cwd.resolve(e).fullpath();return this.#e.set(e,s),s}resolvePosix(...t){let e="";for(let i=t.length-1;i>=0;i--){let n=t[i];if(!(!n||n===".")&&(e=e?`${n}/${e}`:n,this.isAbsolute(n)))break}let r=this.#r.get(e);if(r!==void 0)return r;let s=this.cwd.resolve(e).fullpathPosix();return this.#r.set(e,s),s}relative(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relative()}relativePosix(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relativePosix()}basename(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.name}dirname(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),(t.parent||t).fullpath()}async readdir(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r}=e;if(t.canReaddir()){let s=await t.readdir();return r?s:s.map(i=>i.name)}else return[]}readdirSync(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0}=e;return t.canReaddir()?r?t.readdirSync():t.readdirSync().map(s=>s.name):[]}async lstat(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstat()}lstatSync(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstatSync()}async readlink(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t.withFileTypes,t=this.cwd);let r=await t.readlink();return e?r:r?.fullpath()}readlinkSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t.withFileTypes,t=this.cwd);let r=t.readlinkSync();return e?r:r?.fullpath()}async realpath(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t.withFileTypes,t=this.cwd);let r=await t.realpath();return e?r:r?.fullpath()}realpathSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t.withFileTypes,t=this.cwd);let r=t.realpathSync();return e?r:r?.fullpath()}async walk(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=e,o=[];(!i||i(t))&&o.push(r?t:t.fullpath());let a=new Set,l=(u,h)=>{a.add(u),u.readdirCB((p,f)=>{if(p)return h(p);let m=f.length;if(!m)return h();let g=()=>{--m===0&&h()};for(let w of f)(!i||i(w))&&o.push(r?w:w.fullpath()),s&&w.isSymbolicLink()?w.realpath().then(S=>S?.isUnknown()?S.lstat():S).then(S=>S?.shouldWalk(a,n)?l(S,g):g()):w.shouldWalk(a,n)?l(w,g):g()},!0)},c=t;return new Promise((u,h)=>{l(c,p=>{if(p)return h(p);u(o)})})}walkSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=e,o=[];(!i||i(t))&&o.push(r?t:t.fullpath());let a=new Set([t]);for(let l of a){let c=l.readdirSync();for(let u of c){(!i||i(u))&&o.push(r?u:u.fullpath());let h=u;if(u.isSymbolicLink()){if(!(s&&(h=u.realpathSync())))continue;h.isUnknown()&&h.lstatSync()}h.shouldWalk(a,n)&&a.add(h)}}return o}[Symbol.asyncIterator](){return this.iterate()}iterate(t=this.cwd,e={}){return typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd),this.stream(t,e)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=e;(!i||i(t))&&(yield r?t:t.fullpath());let o=new Set([t]);for(let a of o){let l=a.readdirSync();for(let c of l){(!i||i(c))&&(yield r?c:c.fullpath());let u=c;if(c.isSymbolicLink()){if(!(s&&(u=c.realpathSync())))continue;u.isUnknown()&&u.lstatSync()}u.shouldWalk(o,n)&&o.add(u)}}}stream(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=e,o=new Ct({objectMode:!0});(!i||i(t))&&o.write(r?t:t.fullpath());let a=new Set,l=[t],c=0,u=()=>{let h=!1;for(;!h;){let p=l.shift();if(!p){c===0&&o.end();return}c++,a.add(p);let f=(g,w,S=!1)=>{if(g)return o.emit("error",g);if(s&&!S){let E=[];for(let y of w)y.isSymbolicLink()&&E.push(y.realpath().then(b=>b?.isUnknown()?b.lstat():b));if(E.length){Promise.all(E).then(()=>f(null,w,!0));return}}for(let E of w)E&&(!i||i(E))&&(o.write(r?E:E.fullpath())||(h=!0));c--;for(let E of w){let y=E.realpathCached()||E;y.shouldWalk(a,n)&&l.push(y)}h&&!o.flowing?o.once("drain",u):m||u()},m=!0;p.readdirCB(f,!0),m=!1}};return u(),o}streamSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=e,o=new Ct({objectMode:!0}),a=new Set;(!i||i(t))&&o.write(r?t:t.fullpath());let l=[t],c=0,u=()=>{let h=!1;for(;!h;){let p=l.shift();if(!p){c===0&&o.end();return}c++,a.add(p);let f=p.readdirSync();for(let m of f)(!i||i(m))&&(o.write(r?m:m.fullpath())||(h=!0));c--;for(let m of f){let g=m;if(m.isSymbolicLink()){if(!(s&&(g=m.realpathSync())))continue;g.isUnknown()&&g.lstatSync()}g.shouldWalk(a,n)&&l.push(g)}}h&&!o.flowing&&o.once("drain",u)};return u(),o}chdir(t=this.cwd){let e=this.cwd;this.cwd=typeof t=="string"?this.cwd.resolve(t):t,this.cwd[Ys](e)}},yr=class extends Vs{sep="\\";constructor(t=process.cwd(),e={}){let{nocase:r=!0}=e;super(t,Le.win32,"\\",{...e,nocase:r}),this.nocase=r;for(let s=this.cwd;s;s=s.parent)s.nocase=this.nocase}parseRootPath(t){return Le.win32.parse(t).root.toUpperCase()}newRoot(t){return new zs(this.rootPath,V,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")||t.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(t)}},_r=class extends Vs{sep="/";constructor(t=process.cwd(),e={}){let{nocase:r=!1}=e;super(t,Le.posix,"/",{...e,nocase:r}),this.nocase=r}parseRootPath(t){return"/"}newRoot(t){return new Xs(this.rootPath,V,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")}},Qs=class extends _r{constructor(t=process.cwd(),e={}){let{nocase:r=!0}=e;super(t,{...e,nocase:r})}},ic=process.platform==="win32"?zs:Xs,fa=process.platform==="win32"?yr:process.platform==="darwin"?Qs:_r,ma=t=>t.length>=1,ga=t=>t.length>=1,Sa=Symbol.for("nodejs.util.inspect.custom"),Zs=class ei{#e;#r;#n;length;#i;#o;#y;#S;#u;#a;#d=!0;constructor(e,r,s,i){if(!ma(e))throw new TypeError("empty pattern list");if(!ga(r))throw new TypeError("empty glob list");if(r.length!==e.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=e.length,s<0||s>=this.length)throw new TypeError("index out of range");if(this.#e=e,this.#r=r,this.#n=s,this.#i=i,this.#n===0){if(this.isUNC()){let[n,o,a,l,...c]=this.#e,[u,h,p,f,...m]=this.#r;c[0]===""&&(c.shift(),m.shift());let g=[n,o,a,l,""].join("/"),w=[u,h,p,f,""].join("/");this.#e=[g,...c],this.#r=[w,...m],this.length=this.#e.length}else if(this.isDrive()||this.isAbsolute()){let[n,...o]=this.#e,[a,...l]=this.#r;o[0]===""&&(o.shift(),l.shift());let c=n+"/",u=a+"/";this.#e=[c,...o],this.#r=[u,...l],this.length=this.#e.length}}}[Sa](){return"Pattern <"+this.#r.slice(this.#n).join("/")+">"}pattern(){return this.#e[this.#n]}isString(){return typeof this.#e[this.#n]=="string"}isGlobstar(){return this.#e[this.#n]===D}isRegExp(){return this.#e[this.#n]instanceof RegExp}globString(){return this.#y=this.#y||(this.#n===0?this.isAbsolute()?this.#r[0]+this.#r.slice(1).join("/"):this.#r.join("/"):this.#r.slice(this.#n).join("/"))}hasMore(){return this.length>this.#n+1}rest(){return this.#o!==void 0?this.#o:this.hasMore()?(this.#o=new ei(this.#e,this.#r,this.#n+1,this.#i),this.#o.#a=this.#a,this.#o.#u=this.#u,this.#o.#S=this.#S,this.#o):this.#o=null}isUNC(){let e=this.#e;return this.#u!==void 0?this.#u:this.#u=this.#i==="win32"&&this.#n===0&&e[0]===""&&e[1]===""&&typeof e[2]=="string"&&!!e[2]&&typeof e[3]=="string"&&!!e[3]}isDrive(){let e=this.#e;return this.#S!==void 0?this.#S:this.#S=this.#i==="win32"&&this.#n===0&&this.length>1&&typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0])}isAbsolute(){let e=this.#e;return this.#a!==void 0?this.#a:this.#a=e[0]===""&&e.length>1||this.isDrive()||this.isUNC()}root(){let e=this.#e[0];return typeof e=="string"&&this.isAbsolute()&&this.#n===0?e:""}checkFollowGlobstar(){return!(this.#n===0||!this.isGlobstar()||!this.#d)}markFollowGlobstar(){return this.#n===0||!this.isGlobstar()||!this.#d?!1:(this.#d=!1,!0)}},Ea=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",ps=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(t,{nobrace:e,nocase:r,noext:s,noglobstar:i,platform:n=Ea}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=n,this.mmopts={dot:!0,nobrace:e,nocase:r,noext:s,noglobstar:i,optimizationLevel:2,platform:n,nocomment:!0,nonegate:!0};for(let o of t)this.add(o)}add(t){let e=new ge(t,this.mmopts);for(let r=0;r<e.set.length;r++){let s=e.set[r],i=e.globParts[r];if(!s||!i)throw new Error("invalid pattern object");for(;s[0]==="."&&i[0]===".";)s.shift(),i.shift();let n=new Zs(s,i,0,this.platform),o=new ge(n.globString(),this.mmopts),a=i[i.length-1]==="**",l=n.isAbsolute();l?this.absolute.push(o):this.relative.push(o),a&&(l?this.absoluteChildren.push(o):this.relativeChildren.push(o))}}ignored(t){let e=t.fullpath(),r=`${e}/`,s=t.relative()||".",i=`${s}/`;for(let n of this.relative)if(n.match(s)||n.match(i))return!0;for(let n of this.absolute)if(n.match(e)||n.match(r))return!0;return!1}childrenIgnored(t){let e=t.fullpath()+"/",r=(t.relative()||".")+"/";for(let s of this.relativeChildren)if(s.match(r))return!0;for(let s of this.absoluteChildren)if(s.match(e))return!0;return!1}},wa=class ti{store;constructor(e=new Map){this.store=e}copy(){return new ti(new Map(this.store))}hasWalked(e,r){return this.store.get(e.fullpath())?.has(r.globString())}storeWalked(e,r){let s=e.fullpath(),i=this.store.get(s);i?i.add(r.globString()):this.store.set(s,new Set([r.globString()]))}},ya=class{store=new Map;add(t,e,r){let s=(e?2:0)|(r?1:0),i=this.store.get(t);this.store.set(t,i===void 0?s:s&i)}entries(){return[...this.store.entries()].map(([t,e])=>[t,!!(e&2),!!(e&1)])}},_a=class{store=new Map;add(t,e){if(!t.canReaddir())return;let r=this.store.get(t);r?r.find(s=>s.globString()===e.globString())||r.push(e):this.store.set(t,[e])}get(t){let e=this.store.get(t);if(!e)throw new Error("attempting to walk unknown path");return e}entries(){return this.keys().map(t=>[t,this.store.get(t)])}keys(){return[...this.store.keys()].filter(t=>t.canReaddir())}},fs=class ri{hasWalkedCache;matches=new ya;subwalks=new _a;patterns;follow;dot;opts;constructor(e,r){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=r?r.copy():new wa}processPatterns(e,r){this.patterns=r;let s=r.map(i=>[e,i]);for(let[i,n]of s){this.hasWalkedCache.storeWalked(i,n);let o=n.root(),a=n.isAbsolute()&&this.opts.absolute!==!1;if(o){i=i.resolve(o==="/"&&this.opts.root!==void 0?this.opts.root:o);let h=n.rest();if(h)n=h;else{this.matches.add(i,!0,!1);continue}}if(i.isENOENT())continue;let l,c,u=!1;for(;typeof(l=n.pattern())=="string"&&(c=n.rest());)i=i.resolve(l),n=c,u=!0;if(l=n.pattern(),c=n.rest(),u){if(this.hasWalkedCache.hasWalked(i,n))continue;this.hasWalkedCache.storeWalked(i,n)}if(typeof l=="string"){let h=l===".."||l===""||l===".";this.matches.add(i.resolve(l),a,h);continue}else if(l===D){(!i.isSymbolicLink()||this.follow||n.checkFollowGlobstar())&&this.subwalks.add(i,n);let h=c?.pattern(),p=c?.rest();if(!c||(h===""||h===".")&&!p)this.matches.add(i,a,h===""||h===".");else if(h===".."){let f=i.parent||i;p?this.hasWalkedCache.hasWalked(f,p)||this.subwalks.add(f,p):this.matches.add(f,a,!0)}}else l instanceof RegExp&&this.subwalks.add(i,n)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new ri(this.opts,this.hasWalkedCache)}filterEntries(e,r){let s=this.subwalks.get(e),i=this.child();for(let n of r)for(let o of s){let a=o.isAbsolute(),l=o.pattern(),c=o.rest();l===D?i.testGlobstar(n,o,c,a):l instanceof RegExp?i.testRegExp(n,l,c,a):i.testString(n,l,c,a)}return i}testGlobstar(e,r,s,i){if((this.dot||!e.name.startsWith("."))&&(r.hasMore()||this.matches.add(e,i,!1),e.canReaddir()&&(this.follow||!e.isSymbolicLink()?this.subwalks.add(e,r):e.isSymbolicLink()&&(s&&r.checkFollowGlobstar()?this.subwalks.add(e,s):r.markFollowGlobstar()&&this.subwalks.add(e,r)))),s){let n=s.pattern();if(typeof n=="string"&&n!==".."&&n!==""&&n!==".")this.testString(e,n,s.rest(),i);else if(n===".."){let o=e.parent||e;this.subwalks.add(o,s)}else n instanceof RegExp&&this.testRegExp(e,n,s.rest(),i)}}testRegExp(e,r,s,i){r.test(e.name)&&(s?this.subwalks.add(e,s):this.matches.add(e,i,!1))}testString(e,r,s,i){e.isNamed(r)&&(s?this.subwalks.add(e,s):this.matches.add(e,i,!1))}},ba=(t,e)=>typeof t=="string"?new ps([t],e):Array.isArray(t)?new ps(t,e):t,si=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#e=[];#r;#n;signal;maxDepth;includeChildMatches;constructor(t,e,r){if(this.patterns=t,this.path=e,this.opts=r,this.#n=!r.posix&&r.platform==="win32"?"\\":"/",this.includeChildMatches=r.includeChildMatches!==!1,(r.ignore||!this.includeChildMatches)&&(this.#r=ba(r.ignore??[],r),!this.includeChildMatches&&typeof this.#r.add!="function")){let s="cannot ignore child matches, ignore lacks add() method.";throw new Error(s)}this.maxDepth=r.maxDepth||1/0,r.signal&&(this.signal=r.signal,this.signal.addEventListener("abort",()=>{this.#e.length=0}))}#i(t){return this.seen.has(t)||!!this.#r?.ignored?.(t)}#o(t){return!!this.#r?.childrenIgnored?.(t)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let t;for(;!this.paused&&(t=this.#e.shift());)t()}onResume(t){this.signal?.aborted||(this.paused?this.#e.push(t):t())}async matchCheck(t,e){if(e&&this.opts.nodir)return;let r;if(this.opts.realpath){if(r=t.realpathCached()||await t.realpath(),!r)return;t=r}let s=t.isUnknown()||this.opts.stat?await t.lstat():t;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let i=await s.realpath();i&&(i.isUnknown()||this.opts.stat)&&await i.lstat()}return this.matchCheckTest(s,e)}matchCheckTest(t,e){return t&&(this.maxDepth===1/0||t.depth()<=this.maxDepth)&&(!e||t.canReaddir())&&(!this.opts.nodir||!t.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!t.isSymbolicLink()||!t.realpathCached()?.isDirectory())&&!this.#i(t)?t:void 0}matchCheckSync(t,e){if(e&&this.opts.nodir)return;let r;if(this.opts.realpath){if(r=t.realpathCached()||t.realpathSync(),!r)return;t=r}let s=t.isUnknown()||this.opts.stat?t.lstatSync():t;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let i=s.realpathSync();i&&(i?.isUnknown()||this.opts.stat)&&i.lstatSync()}return this.matchCheckTest(s,e)}matchFinish(t,e){if(this.#i(t))return;if(!this.includeChildMatches&&this.#r?.add){let i=`${t.relativePosix()}/**`;this.#r.add(i)}let r=this.opts.absolute===void 0?e:this.opts.absolute;this.seen.add(t);let s=this.opts.mark&&t.isDirectory()?this.#n:"";if(this.opts.withFileTypes)this.matchEmit(t);else if(r){let i=this.opts.posix?t.fullpathPosix():t.fullpath();this.matchEmit(i+s)}else{let i=this.opts.posix?t.relativePosix():t.relative(),n=this.opts.dotRelative&&!i.startsWith(".."+this.#n)?"."+this.#n:"";this.matchEmit(i?n+i+s:"."+s)}}async match(t,e,r){let s=await this.matchCheck(t,r);s&&this.matchFinish(s,e)}matchSync(t,e,r){let s=this.matchCheckSync(t,r);s&&this.matchFinish(s,e)}walkCB(t,e,r){this.signal?.aborted&&r(),this.walkCB2(t,e,new fs(this.opts),r)}walkCB2(t,e,r,s){if(this.#o(t))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2(t,e,r,s));return}r.processPatterns(t,e);let i=1,n=()=>{--i===0&&s()};for(let[o,a,l]of r.matches.entries())this.#i(o)||(i++,this.match(o,a,l).then(()=>n()));for(let o of r.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;i++;let a=o.readdirCached();o.calledReaddir()?this.walkCB3(o,a,r,n):o.readdirCB((l,c)=>this.walkCB3(o,c,r,n),!0)}n()}walkCB3(t,e,r,s){r=r.filterEntries(t,e);let i=1,n=()=>{--i===0&&s()};for(let[o,a,l]of r.matches.entries())this.#i(o)||(i++,this.match(o,a,l).then(()=>n()));for(let[o,a]of r.subwalks.entries())i++,this.walkCB2(o,a,r.child(),n);n()}walkCBSync(t,e,r){this.signal?.aborted&&r(),this.walkCB2Sync(t,e,new fs(this.opts),r)}walkCB2Sync(t,e,r,s){if(this.#o(t))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2Sync(t,e,r,s));return}r.processPatterns(t,e);let i=1,n=()=>{--i===0&&s()};for(let[o,a,l]of r.matches.entries())this.#i(o)||this.matchSync(o,a,l);for(let o of r.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;i++;let a=o.readdirSync();this.walkCB3Sync(o,a,r,n)}n()}walkCB3Sync(t,e,r,s){r=r.filterEntries(t,e);let i=1,n=()=>{--i===0&&s()};for(let[o,a,l]of r.matches.entries())this.#i(o)||this.matchSync(o,a,l);for(let[o,a]of r.subwalks.entries())i++,this.walkCB2Sync(o,a,r.child(),n);n()}},ms=class extends si{matches=new Set;constructor(t,e,r){super(t,e,r)}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}},gs=class extends si{results;constructor(t,e,r){super(t,e,r),this.results=new Ct({signal:this.signal,objectMode:!0}),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}},va=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",be=class{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(t,e){if(!e)throw new TypeError("glob options required");if(this.withFileTypes=!!e.withFileTypes,this.signal=e.signal,this.follow=!!e.follow,this.dot=!!e.dot,this.dotRelative=!!e.dotRelative,this.nodir=!!e.nodir,this.mark=!!e.mark,e.cwd?(e.cwd instanceof URL||e.cwd.startsWith("file://"))&&(e.cwd=(0,Is.fileURLToPath)(e.cwd)):this.cwd="",this.cwd=e.cwd||"",this.root=e.root,this.magicalBraces=!!e.magicalBraces,this.nobrace=!!e.nobrace,this.noext=!!e.noext,this.realpath=!!e.realpath,this.absolute=e.absolute,this.includeChildMatches=e.includeChildMatches!==!1,this.noglobstar=!!e.noglobstar,this.matchBase=!!e.matchBase,this.maxDepth=typeof e.maxDepth=="number"?e.maxDepth:1/0,this.stat=!!e.stat,this.ignore=e.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof t=="string"&&(t=[t]),this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(t=t.map(a=>a.replace(/\\/g,"/"))),this.matchBase){if(e.noglobstar)throw new TypeError("base matching requires globstar");t=t.map(a=>a.includes("/")?a:`./**/${a}`)}if(this.pattern=t,this.platform=e.platform||va,this.opts={...e,platform:this.platform},e.scurry){if(this.scurry=e.scurry,e.nocase!==void 0&&e.nocase!==e.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let a=e.platform==="win32"?yr:e.platform==="darwin"?Qs:e.platform?_r:fa;this.scurry=new a(this.cwd,{nocase:e.nocase,fs:e.fs})}this.nocase=this.scurry.nocase;let r=this.platform==="darwin"||this.platform==="win32",s={braceExpandMax:1e4,...e,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:r,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},i=this.pattern.map(a=>new ge(a,s)),[n,o]=i.reduce((a,l)=>(a[0].push(...l.set),a[1].push(...l.globParts),a),[[],[]]);this.patterns=n.map((a,l)=>{let c=o[l];if(!c)throw new Error("invalid pattern object");return new Zs(a,c,0,this.platform)})}async walk(){return[...await new ms(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 ms(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 gs(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 gs(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()}},Ta=(t,e={})=>{Array.isArray(t)||(t=[t]);for(let r of t)if(new ge(r,e).hasMagic())return!0;return!1};function Rt(t,e={}){return new be(t,e).streamSync()}function ii(t,e={}){return new be(t,e).stream()}function et(t,e={}){return new be(t,e).walkSync()}async function Ss(t,e={}){return new be(t,e).walk()}function Ot(t,e={}){return new be(t,e).iterateSync()}function ni(t,e={}){return new be(t,e).iterate()}var Ma=Rt,Ca=Object.assign(ii,{sync:Rt}),Aa=Ot,ka=Object.assign(ni,{sync:Ot}),Ra=Object.assign(et,{stream:Rt,iterate:Ot}),Es=Object.assign(Ss,{glob:Ss,globSync:et,sync:Ra,globStream:ii,stream:Ca,globStreamSync:Rt,streamSync:Ma,globIterate:ni,iterate:ka,globIterateSync:Ot,iterateSync:Aa,Glob:be,hasMagic:Ta,escape:Cs,unescape:xe});Es.glob=Es;var le=require("fs"),oi=require("path");function ai(t){try{if(!(0,le.existsSync)(t))return{offsets:{}};let e=(0,le.readFileSync)(t,"utf-8"),r=JSON.parse(e);return r.offsets?r:{offsets:{}}}catch(e){return d.warn("TRANSCRIPT","Failed to load watch state, starting fresh",{statePath:t,error:e instanceof Error?e.message:String(e)}),{offsets:{}}}}function li(t,e){try{let r=(0,oi.dirname)(t);(0,le.existsSync)(r)||(0,le.mkdirSync)(r,{recursive:!0}),(0,le.writeFileSync)(t,JSON.stringify(e,null,2))}catch(r){d.warn("TRANSCRIPT","Failed to save watch state",{statePath:t,error:r instanceof Error?r.message:String(r)})}}var ot=X(require("path"),1);var Fe=X(require("path"),1),Y=require("fs");var ci=require("node:child_process");function It(t,e,r){return(0,ci.spawn)(t,e??[],{windowsHide:!0,...r})}var W={DEFAULT:3e5,HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,WORKER_STARTUP_WAIT:1e3,PRE_RESTART_SETTLE_DELAY:2e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5},Ee={SUCCESS:0,FAILURE:1,BLOCKING_ERROR:2,USER_MESSAGE_ONLY:3};function ce(t){return process.platform==="win32"?Math.round(t*W.WINDOWS_MULTIPLIER):t}var Z=require("fs"),tt=require("path"),br=require("os");var ee=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_API_TIMEOUT_MS:String(ce(W.API_REQUEST)),CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_GEMINI_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_GEMINI_MAX_TOKENS:"100000",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_OPENROUTER_MAX_TOKENS:"100000",CLAUDE_MEM_DATA_DIR:(0,tt.join)((0,br.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,tt.join)((0,br.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let r=this.get(e);return parseInt(r,10)}static getBool(e){let r=this.get(e);return r==="true"||r===!0}static applyEnvOverrides(e){let r={...e};for(let s of Object.keys(this.DEFAULTS))process.env[s]!==void 0&&(r[s]=process.env[s]);return r}static loadFromFile(e,r=!0){try{if(!(0,Z.existsSync)(e)){let a=this.getAllDefaults();try{let l=(0,tt.dirname)(e);(0,Z.existsSync)(l)||(0,Z.mkdirSync)(l,{recursive:!0}),(0,Z.writeFileSync)(e,JSON.stringify(a,null,2),"utf-8"),console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(l){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,l instanceof Error?l.message:String(l))}return r?this.applyEnvOverrides(a):a}let s=(0,Z.readFileSync)(e,"utf-8"),i=JSON.parse(s.replace(/^\uFEFF/,"")),n=i;if(i.env&&typeof i.env=="object"){n=i.env;try{(0,Z.writeFileSync)(e,JSON.stringify(n,null,2),"utf-8"),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(a){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,a instanceof Error?a.message:String(a))}}let o={...this.DEFAULTS};for(let a of Object.keys(this.DEFAULTS))n[a]!==void 0&&(o[a]=n[a]);return r?this.applyEnvOverrides(o):o}catch(s){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,s instanceof Error?s.message:String(s));let i=this.getAllDefaults();return r?this.applyEnvOverrides(i):i}}};var Dt=null;function ue(){return Dt!==null||(Dt=ee.loadFromFile(ut)),Dt}var ve=require("fs");var Ar=require("child_process");var re=require("fs"),Mr=X(require("path"),1);var Oa=["CLAUDECODE_","CLAUDE_CODE_"],Ia=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),Da=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy"]),Pa=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS"]);function Pt(t=process.env){let e={};for(let[r,s]of Object.entries(t))if(s!==void 0){if(Pa.has(r)){e[r]=s;continue}Ia.has(r)||Da.has(r)||Oa.some(i=>r.startsWith(i))||(e[r]=s)}return e}var xa=5e3,La=1e3,Na=R.supervisorRegistry();function te(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;return r==="EPERM"?!0:(d.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return d.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}var Ua=5e3,ui=new Map;function Fa(t){let e=ui.get(t);if(e&&Date.now()-e.capturedAtMs<Ua)return e.token;let r=null;try{let s=(0,Ar.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Pt(process.env),LC_ALL:"C",LANG:"C"}});if(s.status===0){let i=s.stdout.trim();r=i.length>0?i:null}}catch(s){d.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:s instanceof Error?s.message:String(s)}),r=null}return ui.set(t,{token:r,capturedAtMs:Date.now()}),r}function hi(t){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux")try{let e=(0,re.readFileSync)(`/proc/${t}/stat`,"utf-8"),r=e.lastIndexOf(") ");if(r<0)return null;let i=e.slice(r+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(e){return d.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return Fa(t);try{let e=(0,Ar.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Pt(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let r=e.stdout.trim();return r.length>0?r:null}catch(e){return d.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}}function kr(t){if(!t||!te(t.pid))return!1;if(!t.startToken)return!0;let e=hi(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||d.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}var Cr=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=Na){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,re.mkdirSync)(Mr.default.dirname(this.registryPath),{recursive:!0}),!(0,re.existsSync)(this.registryPath)){this.persist();return}try{let s=JSON.parse((0,re.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[i,n]of Object.entries(s))this.entries.set(i,n)}catch(r){r instanceof Error?d.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):d.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&d.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,r,s){this.initialize(),this.entries.set(e,r),s&&this.runtimeProcesses.set(e,s),this.persist()}unregister(e){this.initialize();let r=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),r?.type==="sdk"&&Tr()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let s=Date.parse(e.startedAt),i=Date.parse(r.startedAt);return(Number.isNaN(s)?0:s)-(Number.isNaN(i)?0:i)})}getBySession(e){let r=String(e);return this.getAll().filter(s=>s.sessionId!==void 0&&String(s.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}getByPid(e){return this.getAll().filter(r=>r.pid===e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[s,i]of this.entries)te(i.pid)||(this.entries.delete(s),this.runtimeProcesses.delete(s),e+=1,i.type==="sdk"&&(r+=1));e>0&&this.persist();for(let s=0;s<r;s+=1)Tr();return e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let s=typeof e=="number"?e:Number(e)||void 0;d.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:s,pids:r.map(a=>a.pid)});let i=r.filter(a=>te(a.pid));for(let a of i)try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(l){l instanceof Error?l.code!=="ESRCH"&&d.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},l):d.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(l)})}let n=Date.now()+xa;for(;Date.now()<n&&i.filter(l=>te(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100));let o=i.filter(a=>te(a.pid));for(let a of o){d.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:s});try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(l){l instanceof Error?l.code!=="ESRCH"&&d.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},l):d.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(l)})}}if(o.length>0){let a=Date.now()+La;for(;Date.now()<a&&o.filter(c=>te(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100))}for(let a of r)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of r)a.type==="sdk"&&Tr();return d.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:s,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,re.mkdirSync)(Mr.default.dirname(this.registryPath),{recursive:!0}),(0,re.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},vr=null;function xt(){return vr||(vr=new Cr),vr}var Wa=[];function Tr(){let t=Wa.shift();t&&t()}var fi=require("child_process"),Ne=require("fs"),mi=require("util");var $a=(0,mi.promisify)(fi.execFile),Ha=R.workerPid();async function gi(t){let e=t.currentPid??process.pid,r=t.pidFilePath??Ha,s=t.registry.getAll(),i=[...s].filter(o=>o.pid!==e).sort((o,a)=>Date.parse(a.startedAt)-Date.parse(o.startedAt));for(let o of i){if(!te(o.pid)){t.registry.unregister(o.id);continue}try{await pi(o,"SIGTERM")}catch(a){a instanceof Error?d.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:o.pid,pgid:o.pgid,type:o.type},a):d.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:o.pid,pgid:o.pgid,type:o.type,error:String(a)})}}await di(i,5e3);let n=i.filter(o=>te(o.pid));for(let o of n)try{await pi(o,"SIGKILL")}catch(a){a instanceof Error?d.debug("SYSTEM","Failed to force kill child process",{pid:o.pid,pgid:o.pgid,type:o.type},a):d.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:o.pid,pgid:o.pgid,type:o.type,error:String(a)})}await di(n,1e3);for(let o of i)t.registry.unregister(o.id);for(let o of s.filter(a=>a.pid===e))t.registry.unregister(o.id);ja(r,e),t.registry.pruneDeadEntries()}function ja(t,e){if(!(0,Ne.existsSync)(t))return;let r=null;try{let s=JSON.parse((0,Ne.readFileSync)(t,"utf-8"));r=typeof s.pid=="number"?s.pid:null}catch(s){d.debug("SYSTEM","PID file unreadable during shutdown \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:s instanceof Error?s.message:String(s)});return}if(r!==e){d.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:r,currentPid:e});return}try{(0,Ne.rmSync)(t,{force:!0})}catch(s){s instanceof Error?d.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:t},s):d.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:t,error:String(s)})}}async function di(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.filter(i=>te(i.pid)).length===0)return;await new Promise(i=>setTimeout(i,100))}}async function pi(t,e){let{pid:r,pgid:s}=t;if(process.platform!=="win32"){if(typeof s=="number")try{process.kill(-s,e);return}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}try{process.kill(r,e)}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}return}if(e==="SIGTERM"){try{process.kill(r,e)}catch(o){if(o instanceof Error&&o.code==="ESRCH")return;throw o}return}let i=await Ba();if(i){await new Promise((o,a)=>{i(r,e,l=>{if(!l){o();return}if(l.code==="ESRCH"){o();return}a(l)})});return}let n=["/PID",String(r),"/T"];e==="SIGKILL"&&n.push("/F"),await $a("taskkill",n,{timeout:W.POWERSHELL_COMMAND,windowsHide:!0})}async function Ba(){let t="tree-kill";try{let e=await import(t);return e.default??e}catch(e){return d.debug("SYSTEM","tree-kill module not available, using fallback",{},e instanceof Error?e:void 0),null}}var Si=3e4,Ue=null;function Ga(){let e=xt().pruneDeadEntries();e>0&&d.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function Ei(){Ue===null&&(Ue=setInterval(Ga,Si),Ue.unref(),d.debug("SYSTEM","Health checker started",{intervalMs:Si}))}function wi(){Ue!==null&&(clearInterval(Ue),Ue=null,d.debug("SYSTEM","Health checker stopped"))}var Ka=R.workerPid(),Rr=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),Lt({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,Ei()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async s=>{if(this.shutdownInitiated){d.warn("SYSTEM",`Received ${s} but shutdown already in progress`);return}this.shutdownInitiated=!0,d.info("SYSTEM",`Received ${s}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){i instanceof Error?d.error("SYSTEM","Error during shutdown",{},i):d.error("SYSTEM","Error during shutdown (non-Error)",{error:String(i)});try{await this.stop()}catch(n){n instanceof Error?d.debug("SYSTEM","Supervisor shutdown fallback failed",{},n):d.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(n)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{d.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}wi(),this.stopPromise=gi({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,s){this.registry.register(e,r,s)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},iu=new Rr(xt());function Lt(t={}){let e=t.pidFilePath??Ka;if(!(0,ve.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,ve.readFileSync)(e,"utf-8"))}catch(i){return i instanceof Error?d.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},i):d.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(i)}),(0,ve.rmSync)(e,{force:!0}),"invalid"}return kr(r)&&r?((t.logAlive??!0)&&d.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(d.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,ve.rmSync)(e,{force:!0}),"stale")}var Or=require("path"),Ut=require("fs"),_i=require("crypto");var Nt=require("fs");function yi(t,e){if(!(0,Nt.existsSync)(t))return e;try{return JSON.parse((0,Nt.readFileSync)(t,"utf-8"))}catch(r){throw new Error(`Corrupt JSON file, refusing to overwrite: ${t}: ${r instanceof Error?r.message:String(r)}`)}}var bi="telemetry.json";function Ya(t){let e=t.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function za(t,e){if(Ya(t))return{enabled:!1,source:"DO_NOT_TRACK"};let r=t.CLAUDE_MEM_TELEMETRY?.toLowerCase();return r==="0"||r==="false"||r==="off"?{enabled:!1,source:"env"}:r==="1"||r==="true"||r==="on"?{enabled:!0,source:"env"}:e?.enabled===!0?{enabled:!0,source:"config"}:e?.enabled===!1?{enabled:!1,source:"config"}:{enabled:!0,source:"default"}}function vi(t,e){return za(t,e).enabled}function Ja(){return(0,Or.join)(Oe(),bi)}function Ir(){try{let t=yi(Ja(),null);return!t||typeof t!="object"||typeof t.installId!="string"||t.enabled!==void 0&&typeof t.enabled!="boolean"?null:{enabled:t.enabled,installId:t.installId,decidedAt:typeof t.decidedAt=="string"?t.decidedAt:""}}catch{return null}}function Xa(t){let e=Oe();(0,Ut.mkdirSync)(e,{recursive:!0}),(0,Ut.writeFileSync)((0,Or.join)(e,bi),JSON.stringify(t,null,2)+`
|
|
15
|
-
`)}function Ti(){let t=Ir();if(t?.installId)return t.installId;let e=(0,_i.randomUUID)();return Xa({installId:e,decidedAt:""}),e}var qa=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","install_method","interactive","bun_version","uv_version","claude_code_version","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","fabrication_detected","fabricated_count","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count"]),Mi=200;function Ci(t){let e={};try{if(!t||typeof t!="object")return e;for(let r of Object.keys(t)){if(!qa.has(r))continue;let s=t[r];typeof s=="string"?e[r]=s.length>Mi?s.slice(0,Mi):s:(typeof s=="number"&&Number.isFinite(s)||typeof s=="boolean")&&(e[r]=s)}}catch{}return e}var Dr=X(require("os"),1),Va="13.6.
|
|
15
|
+
`)}function Ti(){let t=Ir();if(t?.installId)return t.installId;let e=(0,_i.randomUUID)();return Xa({installId:e,decidedAt:""}),e}var qa=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","install_method","interactive","bun_version","uv_version","claude_code_version","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","fabrication_detected","fabricated_count","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_invalid_output","top_model","fabrication_count","window_start_ts","total_tokens","avg_tokens"]),Mi=200;function Ci(t){let e={};try{if(!t||typeof t!="object")return e;for(let r of Object.keys(t)){if(!qa.has(r))continue;let s=t[r];typeof s=="string"?e[r]=s.length>Mi?s.slice(0,Mi):s:(typeof s=="number"&&Number.isFinite(s)||typeof s=="boolean")&&(e[r]=s)}}catch{}return e}var Dr=X(require("os"),1),Va="13.6.2",Qa="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",Za="https://us.i.posthog.com";function Ai(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||Qa}function ki(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||Za}var el=["version","os","os_version","is_wsl","arch","runtime","locale","ide","provider","runtime_mode","install_method","claude_code_version","first_active_date","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs"];function Ri(t){let e={};for(let r of el)t[r]!==void 0&&(e[r]=t[r]);return e}function tl(){try{return Dr.default.release()}catch{return"unknown"}}function rl(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||Dr.default.release().toLowerCase().includes("microsoft")}catch{return!1}}function Oi(){return{version:Va,os:process.platform,os_version:tl(),is_wsl:rl(),arch:process.arch,runtime:process.versions.bun?"bun":"node",runtime_version:process.versions.bun??process.versions.node,node_version:process.versions.node,is_ci:!!process.env.CI,locale:Intl.DateTimeFormat().resolvedOptions().locale}}var sl=2e3;async function Ii(t,e,r){try{if(!vi(process.env,Ir()))return;let s=Ci({...Oi(),...e??{}});if(r?.person?s.$set=Ri(s):s.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:t,properties:s})+`
|
|
16
16
|
`);return}let i=Ai();if(!i)return;let n=new AbortController,o=setTimeout(()=>n.abort(),sl);try{await fetch(`${ki()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:i,event:t,distinct_id:Ti(),properties:s}),signal:n.signal})}finally{clearTimeout(o)}}catch{}}var Te=X(require("path"),1),Pi=require("os"),se=require("fs"),rt=require("child_process");var xi=require("util");var bu=(0,xi.promisify)(rt.exec),vu=R.dataDir(),Tu=R.workerPid();function Di(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function nl(t,e){let r=e==="win32"?`where ${t}`:`which ${t}`,s;try{s=(0,rt.execSync)(r,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(n){return n instanceof Error?d.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},n):d.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},new Error(String(n))),null}return s.split(/\r?\n/).map(n=>n.trim()).find(n=>n.length>0)||null}var Pr;function Li(t={}){let e=Object.keys(t).length===0;if(e&&Pr!==void 0)return Pr;let r=ol(t);return e&&r!==null&&(Pr=r),r}function ol(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(Di(r))return r;let s=t.env??process.env,i=t.homeDirectory??(0,Pi.homedir)(),n=t.pathExists??se.existsSync,o=t.lookupInPath??nl,a=e==="win32"?[s.BUN,s.BUN_PATH,Te.default.join(i,".bun","bin","bun.exe"),Te.default.join(i,".bun","bin","bun"),s.USERPROFILE?Te.default.join(s.USERPROFILE,".bun","bin","bun.exe"):void 0,s.LOCALAPPDATA?Te.default.join(s.LOCALAPPDATA,"bun","bun.exe"):void 0,s.LOCALAPPDATA?Te.default.join(s.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[s.BUN,s.BUN_PATH,Te.default.join(i,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun"];for(let l of a){let c=l?.trim();if(c&&(Di(c)&&n(c)||c.toLowerCase()==="bun"))return c}return o("bun",e)}var Ni=X(require("path"),1);var Ui=require("fs");async function al(t,e,r="GET"){let s=await fetch(`http://127.0.0.1:${t}${e}`,{method:r}),i="";try{i=await s.text()}catch{}return{ok:s.ok,statusCode:s.status,body:i}}function ll(){try{let t=Ni.default.join(ct,"package.json");return JSON.parse((0,Ui.readFileSync)(t,"utf-8")).version}catch(t){if(t instanceof Error){let e=t.code;if(e==="ENOENT"||e==="EBUSY")return d.debug("SYSTEM","Could not read plugin version (shutdown race)",{code:e}),"unknown";throw t}throw t}}async function cl(t){try{let e=await al(t,"/api/version");return e.ok?JSON.parse(e.body).version:null}catch{return d.debug("SYSTEM","Could not fetch worker version",{}),null}}async function Fi(t){let e=ll(),r=await cl(t);return!r||e==="unknown"?{matches:!0,pluginVersion:e,workerVersion:r}:{matches:e===r,pluginVersion:e,workerVersion:r}}var Ft=require("path"),B=require("fs");var ul=6e4;function Wi(){return(0,Ft.join)(Oe(),"spawn.lock")}function $i(){let t=Wi(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return(0,B.mkdirSync)((0,Ft.dirname)(t),{recursive:!0}),(0,B.writeFileSync)(t,e,{flag:"wx"}),!0}catch(s){if(s?.code!=="EEXIST")return!0;if(r>0)return!1;let n;try{n=(0,B.statSync)(t).mtimeMs}catch{continue}if(Date.now()-n<=ul)return!1;let o;try{o=(0,B.statSync)(t).mtimeMs}catch{continue}if(o!==n)return!1;try{(0,B.unlinkSync)(t)}catch{return!1}}return!1}function Hi(){let t=Wi();try{if(JSON.parse((0,B.readFileSync)(t,"utf-8")).pid!==process.pid)return;(0,B.unlinkSync)(t)}catch{}}function Ur(t,e,r){let s=process.env[t];if(s){let i=parseInt(s,10);if(Number.isFinite(i)&&i>=r.min&&i<=r.max)return i;d.warn("SYSTEM",`Invalid ${t}, using default`,{value:s,min:r.min,max:r.max})}return e}var Gt=Ur("CLAUDE_MEM_HEALTH_TIMEOUT_MS",ce(W.HEALTH_CHECK),{min:500,max:3e5}),Vu=Ur("CLAUDE_MEM_API_TIMEOUT_MS",ce(W.API_REQUEST),{min:500,max:3e5}),Yi=Ur("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",ce(W.HOOK_READINESS_WAIT),{min:0,max:3e5}),hl={min:500,max:3e5};function Fr(t,e={},r){return new Promise((s,i)=>{let n=setTimeout(()=>i(new Error(`Request timed out after ${r}ms`)),r);fetch(t,e).then(o=>{clearTimeout(n),s(o)},o=>{clearTimeout(n),i(o)})})}var Wt=null,$t=null,Ht=null,jt=null;function dl(){return Fe.default.join(ee.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function Wr(){return Ht!==null||(Ht=ee.loadFromFile(dl())),Ht}function ji(t,e){if(!t)return null;let r=parseInt(t,10);return Number.isFinite(r)&&r>=e.min&&r<=e.max?r:null}function pl(t,e,r){let s=process.env[t];if(s!==void 0){let o=ji(s,r);return o!==null?o:(d.warn("SYSTEM",`Invalid ${t}, using default`,{value:s,min:r.min,max:r.max}),e)}let i=Wr()[t],n=ji(i,r);return n!==null?n:(d.warn("SYSTEM",`Invalid ${t} in settings.json, using default`,{value:i,min:r.min,max:r.max}),e)}function zi(){if(Wt!==null)return Wt;let t=Wr();return Wt=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),Wt}function fl(){return $t!==null||($t=Wr().CLAUDE_MEM_WORKER_HOST),$t}function ml(){return jt!==null||(jt=pl("CLAUDE_MEM_API_TIMEOUT_MS",ce(W.API_REQUEST),hl)),jt}function gl(t){return`http://${fl()}:${zi()}${t}`}function he(t,e={}){let r=e.method??"GET",s=e.timeoutMs??ml(),i=gl(t),n={method:r};return e.headers&&(n.headers=e.headers),e.body&&(n.body=e.body),s>0?Fr(i,n,s):fetch(i,n)}async function Sl(){return(await he("/api/health",{timeoutMs:Gt})).ok}async function Bi(){return(await he("/api/readiness",{timeoutMs:Gt})).ok}function El(){let t=[Fe.default.join(ct,"plugin","scripts","worker-service.cjs"),Fe.default.join(process.cwd(),"plugin","scripts","worker-service.cjs")];for(let e of t)if((0,Y.existsSync)(e))return e;return null}async function wl(t){let e=t.backoffMs;for(let r=1;r<=t.attempts;r++){if(await Xi())return!0;r<t.attempts&&(await new Promise(s=>setTimeout(s,e)),e*=2)}return!1}async function xr(t=Yi){if(t<=0)try{return await Bi()}catch{return!1}let e=Date.now();for(;Date.now()-e<t;){try{if(await Bi())return!0}catch(s){d.debug("SYSTEM","Worker readiness check threw",{error:s instanceof Error?s.message:String(s)})}let r=t-(Date.now()-e);if(r<=0)break;await new Promise(s=>setTimeout(s,Math.min(250,r)))}return!1}async function Ji(){try{let e=await(await he("/api/health",{timeoutMs:Gt})).json();return typeof e.version=="string"?e.version:null}catch{return null}}async function yl(t,e=Yi){let r=Date.now();for(;Date.now()-r<e;){if(await Ji()===t)return!0;let i=e-(Date.now()-r);if(i<=0)break;await new Promise(n=>setTimeout(n,Math.min(500,i)))}return!1}async function Lr(t){let e=await Ji();e!==null&&e!==t&&d.warn("SYSTEM","Worker is ready but still reports a stale version; not recycling again in this hook invocation (one recycle per hook event)",{pluginVersion:t,workerVersion:e})}async function Xi(){let t;try{t=await Sl()}catch(r){return d.debug("SYSTEM","Worker health check threw",{error:r instanceof Error?r.message:String(r)}),!1}if(!t)return!1;let e=Lt({logAlive:!1});return e==="missing"||e==="alive"}async function Kt(){let t=null;if(await Xi()){let{matches:n,pluginVersion:o,workerVersion:a}=await Fi(zi());if(o!=="unknown"&&(t=o),n)return await xr()?(t!==null&&await Lr(t),!0):(d.warn("SYSTEM","Worker is healthy but not ready; skipping hook API call"),!1);d.info("SYSTEM","Worker version mismatch \u2014 recycling stale worker",{pluginVersion:o,workerVersion:a});try{if(await he("/api/admin/restart",{method:"POST",timeoutMs:Gt}),await yl(o))return await xr()?(t!==null&&await Lr(t),!0):(d.warn("SYSTEM","Recycled worker appeared but did not become ready; skipping hook API call"),!1);d.warn("SYSTEM","No successor worker appeared after recycle; falling through to lazy-spawn",{pluginVersion:o,workerVersion:a})}catch(l){d.debug("SYSTEM","Worker restart request failed; falling through to lazy-spawn",{error:l instanceof Error?l.message:String(l)})}}let e=Li(),r=El();if(!e)return d.warn("SYSTEM","Cannot lazy-spawn worker: Bun runtime not found on PATH"),!1;if(!r)return d.warn("SYSTEM","Cannot lazy-spawn worker: worker-service.cjs not found in plugin/scripts"),!1;let s=$i();try{if(s){d.info("SYSTEM","Worker not running \u2014 lazy-spawning",{runtimePath:e,scriptPath:r});try{It(e,[r,"--daemon"],{detached:!0,stdio:["ignore","ignore","ignore"]}).unref()}catch(o){return o instanceof Error?d.error("SYSTEM","Lazy-spawn of worker failed",{runtimePath:e,scriptPath:r},o):d.error("SYSTEM","Lazy-spawn of worker failed (non-Error)",{runtimePath:e,scriptPath:r,error:String(o)}),!1}}else d.info("SYSTEM","Another launcher holds the spawn lock \u2014 skipping lazy-spawn and waiting for its worker");if(!await wl({attempts:6,backoffMs:500}))return d.warn("SYSTEM",s?"Worker port did not open after lazy-spawn within the cold-boot wait (~15s)":"Spawn-lock holder's worker port did not open within the cold-boot wait (~15s)"),!1}finally{s&&Hi()}return await xr()?(t!==null&&await Lr(t),!0):(d.warn("SYSTEM","Worker lazy-spawned but did not become ready before hook readiness timeout"),!1)}var Bt=null;async function _l(){return Bt!==null||(Bt=await Kt()),Bt}var bl=3;function qi(){return Fe.default.join(v,"state")}function Vi(){return Fe.default.join(qi(),"hook-failures.json")}function Qi(){try{let t=(0,Y.readFileSync)(Vi(),"utf-8"),e=JSON.parse(t);return{consecutiveFailures:typeof e.consecutiveFailures=="number"&&Number.isFinite(e.consecutiveFailures)?Math.max(0,Math.floor(e.consecutiveFailures)):0,lastFailureAt:typeof e.lastFailureAt=="number"&&Number.isFinite(e.lastFailureAt)?e.lastFailureAt:0}}catch{return{consecutiveFailures:0,lastFailureAt:0}}}function Zi(t){let e=qi(),r=Vi(),s=`${r}.tmp`;try{(0,Y.existsSync)(e)||(0,Y.mkdirSync)(e,{recursive:!0}),(0,Y.writeFileSync)(s,JSON.stringify(t),"utf-8"),(0,Y.renameSync)(s,r)}catch(i){d.debug("SYSTEM","Failed to persist hook-failure counter",{error:i instanceof Error?i.message:String(i)})}}function vl(){try{let e=ue().CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD,r=parseInt(e,10);if(Number.isFinite(r)&&r>=1)return r}catch{}return bl}var Gi=null;async function Tl(){let e={consecutiveFailures:Qi().consecutiveFailures+1,lastFailureAt:Date.now()};Zi(e);let r=vl();return e.consecutiveFailures>=r&&(e.consecutiveFailures===r&&await Ii("hook_failed",{...Gi!==null?{hook_type:Gi}:{},error_mode:"worker_unavailable",consecutive_failures:e.consecutiveFailures,threshold_tripped:!0}),Yr(`claude-mem worker unreachable for ${e.consecutiveFailures} consecutive hooks.`)),e.consecutiveFailures}function Ki(){Qi().consecutiveFailures!==0&&Zi({consecutiveFailures:0,lastFailureAt:0})}var Nr=Symbol.for("claude-mem/worker-fallback");function st(t){return typeof t=="object"&&t!==null&&t[Nr]===!0}async function it(t,e,r,s={}){if(!await _l())return await Tl(),{continue:!0,reason:"worker_unreachable",[Nr]:!0};let n={method:e};r!==void 0&&(n.headers={"Content-Type":"application/json"},n.body=JSON.stringify(r)),s.timeoutMs!==void 0&&(n.timeoutMs=s.timeoutMs);let o=await he(t,n);if(!o.ok){let l=await o.text().catch(()=>"");if(Ki(),o.status===429||o.status>=500)return d.warn("SYSTEM",`Worker API ${e} ${t} returned ${o.status}; skipping hook API call`,{body:l.substring(0,200)}),{continue:!0,reason:`worker_api_${o.status}`,[Nr]:!0};let c=l;try{c=JSON.parse(l)}catch{}return c}Ki();let a=await o.text();if(a.length!==0)try{return JSON.parse(a)}catch{return a}}var tn=require("os"),rn=X(require("path"),1),sn=require("child_process");var zt=require("fs"),Yt=X(require("path"),1);var nt={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function en(t){let e=Yt.default.join(t,".git"),r;try{r=(0,zt.statSync)(e)}catch(u){return u instanceof Error&&u.code!=="ENOENT"&&d.warn("GIT","Unexpected error checking .git",{error:u instanceof Error?u.message:String(u)}),nt}if(!r.isFile())return nt;let s;try{s=(0,zt.readFileSync)(e,"utf-8").trim()}catch(u){return d.warn("GIT","Failed to read .git file",{error:u instanceof Error?u.message:String(u)}),nt}let i=s.match(/^gitdir:\s*(.+)$/);if(!i)return nt;let o=i[1].match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!o)return nt;let a=o[1],l=Yt.default.basename(t),c=Yt.default.basename(a);return{isWorktree:!0,worktreeName:l,parentRepoPath:a,parentProjectName:c}}function nn(t){return t==="~"||t.startsWith("~/")?t.replace(/^~/,(0,tn.homedir)()):t}function Ml(t){try{return(0,sn.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function Cl(t){if(!t||t.trim()==="")return d.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),"unknown-project";let e=nn(t),s=Ml(e)??e,i=rn.default.basename(s);if(i===""){if(process.platform==="win32"){let o=t.match(/^([A-Z]):\\/i);if(o){let l=`drive-${o[1].toUpperCase()}`;return d.info("PROJECT_NAME","Drive root detected",{cwd:t,projectName:l}),l}}return d.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:t}),"unknown-project"}return i}function Me(t){let e=Cl(t);if(!t)return{primary:e,parent:null,isWorktree:!1,allProjects:[e]};let r=nn(t),s=en(r);if(s.isWorktree&&s.parentProjectName){let i=`${s.parentProjectName}/${e}`;return{primary:i,parent:s.parentProjectName,isWorktree:!0,allProjects:[s.parentProjectName,i]}}return{primary:e,parent:null,isWorktree:!1,allProjects:[e]}}var Ce=require("path");var on=require("os"),an=require("path");function Al(t){let e=t.startsWith("~")?(0,on.homedir)()+t.slice(1):t;e=e.replace(/\\/g,"/");let r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return r=r.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${r}$`)}function Jt(t,e){if(!e||!e.trim())return!1;let r=t.replace(/\\/g,"/"),s=(0,an.basename)(r),i=e.split(",").map(n=>n.trim()).filter(Boolean);for(let n of i)try{let o=Al(n);if(o.test(r)||o.test(s))return!0}catch(o){d.warn("PROJECT_NAME","Invalid exclusion pattern",{pattern:n,error:o instanceof Error?o.message:String(o)});continue}return!1}function kl(t,e){let r=(0,Ce.normalize)(t),s=(0,Ce.normalize)(e);if(r===s)return!0;let i=(0,Ce.relative)(s,r);return i.length>0&&!i.startsWith("..")&&!(0,Ce.isAbsolute)(i)}function Xt(t){if(process.env.CLAUDE_MEM_INTERNAL==="1")return!1;if(!t)return!0;if(kl(t,ht))return!1;let e=ue();return!Jt(t,e.CLAUDE_MEM_EXCLUDED_PROJECTS)}var ln="claude";function Rl(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function we(t){if(!t)return ln;let e=Rl(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:ln}var hn=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],cn=new RegExp(`<(${hn.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g");var un=100;function Ol(t){let e=Object.fromEntries(hn.map(i=>[i,0]));cn.lastIndex=0;let r=0,s=t.replace(cn,(i,n)=>(e[n]=(e[n]??0)+1,r+=1,""));return r>un&&d.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:r,maxAllowed:un,contentLength:t.length}),{stripped:s.trim(),counts:e}}function $r(t){return Ol(t).stripped}var Il=["task-notification"],Dl=new RegExp(`^\\s*<(${Il.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),Pl=256*1024;function dn(t){return!t||t.length>Pl?!1:Dl.test(t)}var xl=ce(W.API_REQUEST),de=class extends Error{kind;status;cause;constructor(e,r,s={}){super(r),this.name="ServerBetaClientError",this.kind=e,this.status=s.status??null,this.cause=s.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},qt=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=Ll(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??xl}async startSession(e){let r=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",r)}async recordEvent(e){let r=this.buildEventPayload(e),s=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",s,r)}async endSession(e){if(!e.sessionId)throw new de("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async getJobStatus(e){if(!e)throw new de("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,s=e.kind??"manual",i=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:s,type:s,narrative:r,...i?{title:i}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:e.platformSource}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,r,s){if(!this.apiKey||!this.apiKey.trim())throw new de("missing_api_key","Server beta API key is not configured (CLAUDE_MEM_SERVER_BETA_API_KEY).");let i=`${this.baseUrl}${r}`,n={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};s!==void 0&&(n.body=JSON.stringify(s));let o;try{o=await Fr(i,n,this.timeoutMs)}catch(l){let c=l instanceof Error?l.message:String(l),u=/timed out|timeout/i.test(c);throw new de(u?"timeout":"transport",`Server beta ${e} ${r} failed: ${c}`,{cause:l})}if(!o.ok){let l=await o.text().catch(()=>"");throw new de("http_error",`Server beta ${e} ${r} returned ${o.status}: ${Nl(l,200)}`,{status:o.status})}let a=await o.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(l){throw new de("invalid_response",`Server beta ${e} ${r} returned non-JSON response`,{cause:l})}}};function pn(t){return t instanceof de}function Ll(t){return t.replace(/\/+$/,"")}function Nl(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Ul(){return(ue().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase()==="server-beta"?"server-beta":"worker"}function Fl(){let t=ue(),e=(t.CLAUDE_MEM_SERVER_BETA_URL??"").trim(),r=(t.CLAUDE_MEM_SERVER_BETA_API_KEY??"").trim(),s=(t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID??"").trim();if(!e)return d.warn("HOOK","[server-beta-fallback] reason=missing_base_url"),null;if(!r)return d.warn("HOOK","[server-beta-fallback] reason=missing_api_key"),null;if(!s)return d.warn("HOOK","[server-beta-fallback] reason=missing_project_id"),null;let i={serverBaseUrl:e,apiKey:r};return{runtime:"server-beta",client:new qt(i),projectId:s,serverBaseUrl:e}}function fn(){if(Ul()!=="server-beta")return{runtime:"worker"};let t=Fl();return t||{runtime:"worker"}}function mn(t,e){d.warn("HOOK",`[server-beta-fallback] reason=${t}`,e??{})}var gn={async execute(t){let{sessionId:e,prompt:r}=t,s=t.cwd??process.cwd();if(!e)return d.warn("HOOK","session-init: No sessionId provided, skipping (Codex CLI or unknown platform)"),{continue:!0,suppressOutput:!0,exitCode:Ee.SUCCESS};if(!Xt(s))return d.info("HOOK","Project excluded from tracking",{cwd:s}),{continue:!0,suppressOutput:!0};if(r&&dn(r))return d.debug("HOOK","session-init: skipping internal protocol payload",{preview:r.slice(0,80)}),{continue:!0,suppressOutput:!0};let i=!r||!r.trim()?"[media prompt]":r,n=Me(s).primary,o=we(t.platform),a=fn();if(a.runtime==="server-beta")try{return await a.client.startSession({projectId:a.projectId,externalSessionId:e,contentSessionId:e,agentId:t.agentId??null,agentType:t.agentType??null,platformSource:o,metadata:{project:n,prompt:i}}),d.info("HOOK","session-init: server-beta session started",{contentSessionId:e,project:n}),{continue:!0,suppressOutput:!0}}catch(m){if(pn(m)&&m.isFallbackEligible())mn(m.kind,{status:m.status,message:m.message,route:"/v1/sessions/start"});else return d.error("HOOK","Server beta session-start failed (non-recoverable)",{error:m instanceof Error?m.message:String(m)}),{continue:!0,suppressOutput:!0,exitCode:Ee.SUCCESS}}d.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:e,project:n});let l=await it("/api/sessions/init","POST",{contentSessionId:e,project:n,prompt:i,platformSource:o});if(st(l))return{continue:!0,suppressOutput:!0,exitCode:Ee.SUCCESS};if(typeof l?.sessionDbId!="number")return d.failure("HOOK","Session initialization returned malformed response",{contentSessionId:e,project:n}),{continue:!0,suppressOutput:!0,exitCode:Ee.SUCCESS};let c=l.sessionDbId,u=l.promptNumber;if(d.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:c,promptNumber:u,skipped:l.skipped,contextInjected:l.contextInjected}),d.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${e} | prompt#=${u} | sessionDbId=${c}`),l.skipped&&l.reason==="private")return d.info("HOOK",`INIT_COMPLETE | sessionDbId=${c} | promptNumber=${u} | skipped=true | reason=private`,{sessionId:c}),{continue:!0,suppressOutput:!0};let h=ue(),p=String(h.CLAUDE_MEM_SEMANTIC_INJECT).toLowerCase()==="true",f="";if(p&&i&&i.length>=20&&i!=="[media prompt]"){let m=h.CLAUDE_MEM_SEMANTIC_INJECT_LIMIT||"5",g=await it("/api/context/semantic","POST",{q:i,project:n,limit:m});!st(g)&&g?.context&&(d.debug("HOOK",`Semantic injection: ${g.count} observations for prompt`,{sessionId:c,count:g.count}),f=g.context)}return d.info("HOOK",`INIT_COMPLETE | sessionDbId=${c} | promptNumber=${u} | project=${n}`,{sessionId:c}),f?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:f}}:{continue:!0,suppressOutput:!0}}};var Sn={async execute(t){let{sessionId:e,cwd:r,filePath:s,edits:i}=t,n=we(t.platform);if(!s)throw new Error("fileEditHandler requires filePath");if(d.dataIn("HOOK",`FileEdit: ${s}`,{editCount:i?.length??0}),!r)throw new Error(`Missing cwd in FileEdit hook input for session ${e}, file ${s}`);if(!Xt(r))return d.debug("HOOK","Project excluded from tracking, skipping file edit observation",{cwd:r,filePath:s}),{continue:!0,suppressOutput:!0,exitCode:Ee.SUCCESS};let o=await it("/api/sessions/observations","POST",{contentSessionId:e,platformSource:n,tool_name:"write_file",tool_input:{filePath:s,edits:i},tool_response:{success:!0},cwd:r});return st(o)?{continue:!0,suppressOutput:!0,exitCode:Ee.SUCCESS}:(d.debug("HOOK","File edit observation sent successfully",{filePath:s}),{continue:!0,suppressOutput:!0})}};var z=require("fs"),Vt=require("path");var Vh=R.settings();function En(t,e){let r="<claude-mem-context>",s="</claude-mem-context>";if(!t)return`${r}
|
|
17
17
|
${e}
|
|
18
18
|
${s}`;let i=t.indexOf(r),n=t.indexOf(s);return i!==-1&&n!==-1?t.substring(0,i)+`${r}
|