keepmind 1.3.0 → 1.3.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.
@@ -10,7 +10,7 @@ ${n.stack}`:` ${n.message}`;else if(this.getLevel()===0&&typeof n=="object")try{
10
10
  `)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),h=c?`${c[1].split("/").pop()}:${c[2]}`:"unknown",u={...i,location:h};return this.warn(t,`[HAPPY-PATH] ${r}`,u,s),n}},d=new ar;var Pn={};function vn(){return typeof __dirname<"u"?__dirname:(0,_.dirname)((0,zr.fileURLToPath)(Pn.url))}var Il=vn();function cr(){let e=process.env.KEEPMIND_DATA_DIR??process.env.CLAUDE_MEM_DATA_DIR;if(e)return e;let t=(0,_.join)((0,lr.homedir)(),".keepmind"),r=(0,_.join)(t,"settings.json");try{if((0,N.existsSync)(r)){let i=JSON.parse((0,N.readFileSync)(r,"utf-8")),s=i.env??i,n=s.KEEPMIND_DATA_DIR??s.CLAUDE_MEM_DATA_DIR;if(n)return n}}catch{}return t}var T=cr(),le=process.env.CLAUDE_CONFIG_DIR||(0,_.join)((0,lr.homedir)(),".claude"),ce=(0,_.join)(le,"plugins","marketplaces","keepmind"),bn=(0,_.join)(T,"archives"),Tn=(0,_.join)(T,"logs"),Mn=(0,_.join)(T,"trash"),kn=(0,_.join)(T,"backups"),Rn=(0,_.join)(T,"modes"),he=(0,_.join)(T,"settings.json"),It=(0,_.join)(T,"keepmind.db"),Bt=(0,_.join)(T,"claude-mem.db"),Cn=(0,_.join)(T,"vector-db"),ue=(0,_.join)(T,"observer-sessions"),An=(0,_.basename)(ue),xl=(0,_.join)(le,"settings.json"),Ll=(0,_.join)(le,"commands"),Nl=(0,_.join)(le,"CLAUDE.md");function On(){try{if((0,N.existsSync)(It)||!(0,N.existsSync)(Bt))return(0,N.existsSync)(It);for(let e of["","-wal","-shm"]){let t=Bt+e,r=It+e;(0,N.existsSync)(t)&&!(0,N.existsSync)(r)&&(0,N.renameSync)(t,r)}return d.info("DB","Migrated legacy claude-mem.db to keepmind.db",{from:Bt,to:It}),!0}catch(e){return d.warn("DB","Could not rename legacy claude-mem.db to keepmind.db (file may be locked) \u2014 falling back to legacy path",{},e instanceof Error?e:new Error(String(e))),!1}}function Dn(){return On(),!(0,N.existsSync)(It)&&(0,N.existsSync)(Bt)?Bt:It}var R={dataDir:()=>T,workerPid:()=>(0,_.join)(T,"worker.pid"),workerPort:()=>(0,_.join)(T,"worker.port"),serverPid:()=>(0,_.join)(T,".server-beta.pid"),serverPort:()=>(0,_.join)(T,".server-beta.port"),serverRuntime:()=>(0,_.join)(T,".server-beta.runtime.json"),settings:()=>(0,_.join)(T,"settings.json"),database:()=>Dn(),chroma:()=>(0,_.join)(T,"chroma"),combinedCerts:()=>(0,_.join)(T,"combined_certs.pem"),transcriptsConfig:()=>(0,_.join)(T,"transcript-watch.json"),transcriptsState:()=>(0,_.join)(T,"transcript-watch-state.json"),corpora:()=>(0,_.join)(T,"corpora"),supervisorRegistry:()=>(0,_.join)(T,"supervisor.json"),envFile:()=>(0,_.join)(T,".env"),logsDir:()=>Tn,archives:()=>bn,trash:()=>Mn,backups:()=>kn,modes:()=>Rn,vectorDb:()=>Cn,observerSessions:()=>ue};var xt=R.transcriptsConfig(),de=R.transcriptsState();var In={version:1,schemas:{},watches:[],stateFile:de};function xn(e){let t=typeof e.schema=="string"?e.schema:e.schema?.name;if(!(e.name==="codex"||t==="codex")||!e.path)return!1;let i=W(e.path).replace(/\\/g,"/"),s=(0,Kt.join)((0,hr.homedir)(),".codex","sessions").replace(/\\/g,"/");return i===`${s}/**/*.jsonl`}function Yr(e){let t=typeof e.schema=="string"?e.schema:e.schema?.name,r=e.name==="codex"&&(!t||t==="codex");return e.context?.mode==="agents"&&r&&xn(e)}function W(e){return e&&(e.startsWith("~")?(0,Kt.join)((0,hr.homedir)(),e.slice(1)):e)}function zt(e=xt){let t=W(e);if(!(0,at.existsSync)(t))throw new Error(`Transcript watch config not found: ${t}`);let r=(0,at.readFileSync)(t,"utf-8"),i=JSON.parse(r);if(!i.version||!i.watches)throw new Error(`Invalid transcript watch config: ${t}`);return i.stateFile||(i.stateFile=de),i}function pe(e=xt){let t=W(e),r=(0,Kt.dirname)(t);(0,at.existsSync)(r)||(0,at.mkdirSync)(r,{recursive:!0}),(0,at.writeFileSync)(t,JSON.stringify(In,null,2))}var L=require("fs"),q=require("path");var Ai=require("node:url"),Ut=require("node:path"),xi=require("node:url"),tt=require("fs"),jo=ot(require("node:fs"),1),_t=require("node:fs/promises"),Ce=require("node:events"),vr=ot(require("node:stream"),1),Li=require("node:string_decoder"),Si=(e,t,r)=>{let i=e instanceof RegExp?Jr(e,r):e,s=t instanceof RegExp?Jr(t,r):t,n=i!==null&&s!=null&&Ln(i,s,r);return n&&{start:n[0],end:n[1],pre:r.slice(0,n[0]),body:r.slice(n[0]+i.length,n[1]),post:r.slice(n[1]+s.length)}},Jr=(e,t)=>{let r=t.match(e);return r?r[0]:null},Ln=(e,t,r)=>{let i,s,n,o,a,l=r.indexOf(e),c=r.indexOf(t,l+1),h=l;if(l>=0&&c>0){if(e===t)return[l,c];for(i=[],n=r.length;h>=0&&!a;){if(h===l)i.push(h),l=r.indexOf(e,h+1);else if(i.length===1){let u=i.pop();u!==void 0&&(a=[u,c])}else s=i.pop(),s!==void 0&&s<n&&(n=s,o=c),c=r.indexOf(t,h+1);h=l<c&&l>=0?l:c}i.length&&o!==void 0&&(a=[n,o])}return a},Ei="\0SLASH"+Math.random()+"\0",wi="\0OPEN"+Math.random()+"\0",yr="\0CLOSE"+Math.random()+"\0",yi="\0COMMA"+Math.random()+"\0",_i="\0PERIOD"+Math.random()+"\0",Nn=new RegExp(Ei,"g"),Fn=new RegExp(wi,"g"),Un=new RegExp(yr,"g"),Wn=new RegExp(yi,"g"),$n=new RegExp(_i,"g"),jn=/\\\\/g,Hn=/\\{/g,Gn=/\\}/g,Bn=/\\,/g,Kn=/\\./g,zn=1e5;function ur(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function Yn(e){return e.replace(jn,Ei).replace(Hn,wi).replace(Gn,yr).replace(Bn,yi).replace(Kn,_i)}function Jn(e){return e.replace(Nn,"\\").replace(Fn,"{").replace(Un,"}").replace(Wn,",").replace($n,".")}function vi(e){if(!e)return[""];let t=[],r=Si("{","}",e);if(!r)return e.split(",");let{pre:i,body:s,post:n}=r,o=i.split(",");o[o.length-1]+="{"+s+"}";let a=vi(n);return n.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),t.push.apply(t,o),t}function Xn(e,t={}){if(!e)return[];let{max:r=zn}=t;return e.slice(0,2)==="{}"&&(e="\\{\\}"+e.slice(2)),Zt(Yn(e),r,!0).map(Jn)}function Vn(e){return"{"+e+"}"}function qn(e){return/^-?0\d/.test(e)}function Qn(e,t){return e<=t}function Zn(e,t){return e>=t}function Zt(e,t,r){let i=[],s=Si("{","}",e);if(!s)return[e];let n=s.pre,o=s.post.length?Zt(s.post,t,!1):[""];if(/\$$/.test(s.pre))for(let a=0;a<o.length&&a<t;a++){let l=n+"{"+s.body+"}"+o[a];i.push(l)}else{let a=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(s.body),l=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(s.body),c=a||l,h=s.body.indexOf(",")>=0;if(!c&&!h)return s.post.match(/,(?!,).*\}/)?(e=s.pre+"{"+s.body+yr+s.post,Zt(e,t,!0)):[e];let u;if(c)u=s.body.split(/\.\./);else if(u=vi(s.body),u.length===1&&u[0]!==void 0&&(u=Zt(u[0],t,!1).map(Vn),u.length===1))return o.map(f=>s.pre+u[0]+f);let p;if(c&&u[0]!==void 0&&u[1]!==void 0){let f=ur(u[0]),m=ur(u[1]),g=Math.max(u[0].length,u[1].length),w=u.length===3&&u[2]!==void 0?Math.abs(ur(u[2])):1,S=Qn;m<f&&(w*=-1,S=Zn);let E=u.some(qn);p=[];for(let y=f;S(y,m);y+=w){let v;if(l)v=String.fromCharCode(y),v==="\\"&&(v="");else if(v=String(y),E){let M=g-v.length;if(M>0){let St=new Array(M+1).join("0");y<0?v="-"+St+v.slice(1):v=St+v}}p.push(v)}}else{p=[];for(let f=0;f<u.length;f++)p.push.apply(p,Zt(u[f],t,!1))}for(let f=0;f<p.length;f++)for(let m=0;m<o.length&&i.length<t;m++){let g=n+p[f]+o[m];(!r||c||g)&&i.push(g)}}return i}var Te=e=>{if(typeof e!="string")throw new TypeError("invalid pattern");if(e.length>65536)throw new TypeError("pattern is too long")},to={"[: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]},Yt=e=>e.replace(/[[\]\\-]/g,"\\$&"),eo=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Xr=e=>e.join(""),ro=(e,t)=>{let r=t;if(e.charAt(r)!=="[")throw new Error("not in a brace expression");let i=[],s=[],n=r+1,o=!1,a=!1,l=!1,c=!1,h=r,u="";t:for(;n<e.length;){let m=e.charAt(n);if((m==="!"||m==="^")&&n===r+1){c=!0,n++;continue}if(m==="]"&&o&&!l){h=n+1;break}if(o=!0,m==="\\"&&!l){l=!0,n++;continue}if(m==="["&&!l){for(let[g,[w,S,E]]of Object.entries(to))if(e.startsWith(g,n)){if(u)return["$.",!1,e.length-r,!0];n+=g.length,E?s.push(w):i.push(w),a=a||S;continue t}}if(l=!1,u){m>u?i.push(Yt(u)+"-"+Yt(m)):m===u&&i.push(Yt(m)),u="",n++;continue}if(e.startsWith("-]",n+1)){i.push(Yt(m+"-")),n+=2;continue}if(e.startsWith("-",n+1)){u=m,n+=2;continue}i.push(Yt(m)),n++}if(h<n)return["",!1,0,!1];if(!i.length&&!s.length)return["$.",!1,e.length-r,!0];if(s.length===0&&i.length===1&&/^\\?.$/.test(i[0])&&!c){let m=i[0].length===2?i[0].slice(-1):i[0];return[eo(m),!1,h-r,!1]}let p="["+(c?"^":"")+Xr(i)+"]",f="["+(c?"":"^")+Xr(s)+"]";return[i.length&&s.length?"("+p+"|"+f+")":i.length?p:f,a,h-r,!0]},Ft=(e,{windowsPathsNoEscape:t=!1,magicalBraces:r=!0}={})=>r?t?e.replace(/\[([^\/\\])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):t?e.replace(/\[([^\/\\{}])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1"),io=new Set(["!","?","+","*","@"]),Vr=e=>io.has(e),so="(?!(?:^|/)\\.\\.?(?:$|/))",fe="(?!\\.)",no=new Set(["[","."]),oo=new Set(["..","."]),ao=new Set("().*{}+?[]^$\\!"),lo=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),_r="[^/]",qr=_r+"*?",Qr=_r+"+?",bi=class j{type;#t;#r;#n=!1;#s=[];#o;#y;#S;#h=!1;#a;#d;#u=!1;constructor(t,r,i={}){this.type=t,t&&(this.#r=!0),this.#o=r,this.#t=this.#o?this.#o.#t:this,this.#a=this.#t===this?i:this.#t.#a,this.#S=this.#t===this?[]:this.#t.#S,t==="!"&&!this.#t.#h&&this.#S.push(this),this.#y=this.#o?this.#o.#s.length:0}get hasMagic(){if(this.#r!==void 0)return this.#r;for(let t of this.#s)if(typeof t!="string"&&(t.type||t.hasMagic))return this.#r=!0;return this.#r}toString(){return this.#d!==void 0?this.#d:this.type?this.#d=this.type+"("+this.#s.map(t=>String(t)).join("|")+")":this.#d=this.#s.map(t=>String(t)).join("")}#l(){if(this!==this.#t)throw new Error("should only call on root");if(this.#h)return this;this.toString(),this.#h=!0;let t;for(;t=this.#S.pop();){if(t.type!=="!")continue;let r=t,i=r.#o;for(;i;){for(let s=r.#y+1;!i.type&&s<i.#s.length;s++)for(let n of t.#s){if(typeof n=="string")throw new Error("string part in extglob AST??");n.copyIn(i.#s[s])}r=i,i=r.#o}}return this}push(...t){for(let r of t)if(r!==""){if(typeof r!="string"&&!(r instanceof j&&r.#o===this))throw new Error("invalid part: "+r);this.#s.push(r)}}toJSON(){let t=this.type===null?this.#s.slice().map(r=>typeof r=="string"?r:r.toJSON()):[this.type,...this.#s.map(r=>r.toJSON())];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===this.#t||this.#t.#h&&this.#o?.type==="!")&&t.push({}),t}isStart(){if(this.#t===this)return!0;if(!this.#o?.isStart())return!1;if(this.#y===0)return!0;let t=this.#o;for(let r=0;r<this.#y;r++){let i=t.#s[r];if(!(i instanceof j&&i.type==="!"))return!1}return!0}isEnd(){if(this.#t===this||this.#o?.type==="!")return!0;if(!this.#o?.isEnd())return!1;if(!this.type)return this.#o?.isEnd();let t=this.#o?this.#o.#s.length:0;return this.#y===t-1}copyIn(t){typeof t=="string"?this.push(t):this.push(t.clone(this))}clone(t){let r=new j(this.type,t);for(let i of this.#s)r.copyIn(i);return r}static#i(t,r,i,s){let n=!1,o=!1,a=-1,l=!1;if(r.type===null){let f=i,m="";for(;f<t.length;){let g=t.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(!s.noext&&Vr(g)&&t.charAt(f)==="("){r.push(m),m="";let w=new j(g,r);f=j.#i(t,w,f,s),r.push(w);continue}m+=g}return r.push(m),f}let c=i+1,h=new j(null,r),u=[],p="";for(;c<t.length;){let f=t.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(Vr(f)&&t.charAt(c)==="("){h.push(p),p="";let m=new j(f,h);h.push(m),c=j.#i(t,m,c,s);continue}if(f==="|"){h.push(p),p="",u.push(h),h=new j(null,r);continue}if(f===")")return p===""&&r.#s.length===0&&(r.#u=!0),h.push(p),p="",r.push(...u,h),c;p+=f}return r.type=null,r.#r=void 0,r.#s=[t.substring(i-1)],c}static fromGlob(t,r={}){let i=new j(null,void 0,r);return j.#i(t,i,0,r),i}toMMPattern(){if(this!==this.#t)return this.#t.toMMPattern();let t=this.toString(),[r,i,s,n]=this.toRegExpSource();if(!(s||this.#r||this.#a.nocase&&!this.#a.nocaseMagicOnly&&t.toUpperCase()!==t.toLowerCase()))return i;let o=(this.#a.nocase?"i":"")+(n?"u":"");return Object.assign(new RegExp(`^${r}$`,o),{_src:r,_glob:t})}get options(){return this.#a}toRegExpSource(t){let r=t??!!this.#a.dot;if(this.#t===this&&this.#l(),!this.type){let l=this.isStart()&&this.isEnd()&&!this.#s.some(p=>typeof p!="string"),c=this.#s.map(p=>{let[f,m,g,w]=typeof p=="string"?j.#_(p,this.#r,l):p.toRegExpSource(t);return this.#r=this.#r||g,this.#n=this.#n||w,f}).join(""),h="";if(this.isStart()&&typeof this.#s[0]=="string"&&!(this.#s.length===1&&oo.has(this.#s[0]))){let p=no,f=r&&p.has(c.charAt(0))||c.startsWith("\\.")&&p.has(c.charAt(2))||c.startsWith("\\.\\.")&&p.has(c.charAt(4)),m=!r&&!t&&p.has(c.charAt(0));h=f?so:m?fe:""}let u="";return this.isEnd()&&this.#t.#h&&this.#o?.type==="!"&&(u="(?:$|\\/)"),[h+c+u,Ft(c),this.#r=!!this.#r,this.#n]}let i=this.type==="*"||this.type==="+",s=this.type==="!"?"(?:(?!(?:":"(?:",n=this.#p(r);if(this.isStart()&&this.isEnd()&&!n&&this.type!=="!"){let l=this.toString();return this.#s=[l],this.type=null,this.#r=void 0,[l,Ft(this.toString()),!1,!1]}let o=!i||t||r||!fe?"":this.#p(!0);o===n&&(o=""),o&&(n=`(?:${n})(?:${o})*?`);let a="";if(this.type==="!"&&this.#u)a=(this.isStart()&&!r?fe:"")+Qr;else{let l=this.type==="!"?"))"+(this.isStart()&&!r&&!t?fe:"")+qr+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;a=s+n+l}return[a,Ft(n),this.#r=!!this.#r,this.#n]}#p(t){return this.#s.map(r=>{if(typeof r=="string")throw new Error("string type in extglob ast??");let[i,s,n,o]=r.toRegExpSource(t);return this.#n=this.#n||o,i}).filter(r=>!(this.isStart()&&this.isEnd())||!!r).join("|")}static#_(t,r,i=!1){let s=!1,n="",o=!1,a=!1;for(let l=0;l<t.length;l++){let c=t.charAt(l);if(s){s=!1,n+=(ao.has(c)?"\\":"")+c;continue}if(c==="*"){if(a)continue;a=!0,n+=i&&/^[*]+$/.test(t)?Qr:qr,r=!0;continue}else a=!1;if(c==="\\"){l===t.length-1?n+="\\\\":s=!0;continue}if(c==="["){let[h,u,p,f]=ro(t,l);if(p){n+=h,o=o||u,l+=p-1,r=r||f;continue}}if(c==="?"){n+=_r,r=!0;continue}n+=lo(c)}return[n,Ft(t),!!r,o]}},Ti=(e,{windowsPathsNoEscape:t=!1,magicalBraces:r=!1}={})=>r?t?e.replace(/[?*()[\]{}]/g,"[$&]"):e.replace(/[?*()[\]\\{}]/g,"\\$&"):t?e.replace(/[?*()[\]]/g,"[$&]"):e.replace(/[?*()[\]\\]/g,"\\$&"),x=(e,t,r={})=>(Te(t),!r.nocomment&&t.charAt(0)==="#"?!1:new yt(t,r).match(e)),co=/^\*+([^+@!?\*\[\(]*)$/,ho=e=>t=>!t.startsWith(".")&&t.endsWith(e),uo=e=>t=>t.endsWith(e),po=e=>(e=e.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(e)),fo=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),mo=/^\*+\.\*+$/,go=e=>!e.startsWith(".")&&e.includes("."),So=e=>e!=="."&&e!==".."&&e.includes("."),Eo=/^\.\*+$/,wo=e=>e!=="."&&e!==".."&&e.startsWith("."),yo=/^\*+$/,_o=e=>e.length!==0&&!e.startsWith("."),vo=e=>e.length!==0&&e!=="."&&e!=="..",bo=/^\?+([^+@!?\*\[\(]*)?$/,To=([e,t=""])=>{let r=Mi([e]);return t?(t=t.toLowerCase(),i=>r(i)&&i.toLowerCase().endsWith(t)):r},Mo=([e,t=""])=>{let r=ki([e]);return t?(t=t.toLowerCase(),i=>r(i)&&i.toLowerCase().endsWith(t)):r},ko=([e,t=""])=>{let r=ki([e]);return t?i=>r(i)&&i.endsWith(t):r},Ro=([e,t=""])=>{let r=Mi([e]);return t?i=>r(i)&&i.endsWith(t):r},Mi=([e])=>{let t=e.length;return r=>r.length===t&&!r.startsWith(".")},ki=([e])=>{let t=e.length;return r=>r.length===t&&r!=="."&&r!==".."},Ri=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",Zr={win32:{sep:"\\"},posix:{sep:"/"}},Co=Ri==="win32"?Zr.win32.sep:Zr.posix.sep;x.sep=Co;var I=Symbol("globstar **");x.GLOBSTAR=I;var Ao="[^/]",Oo=Ao+"*?",Do="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",Po="(?:(?!(?:\\/|^)\\.).)*?",Io=(e,t={})=>r=>x(r,e,t);x.filter=Io;var G=(e,t={})=>Object.assign({},e,t),xo=e=>{if(!e||typeof e!="object"||!Object.keys(e).length)return x;let t=x;return Object.assign((r,i,s={})=>t(r,i,G(e,s)),{Minimatch:class extends t.Minimatch{constructor(r,i={}){super(r,G(e,i))}static defaults(r){return t.defaults(G(e,r)).Minimatch}},AST:class extends t.AST{constructor(r,i,s={}){super(r,i,G(e,s))}static fromGlob(r,i={}){return t.AST.fromGlob(r,G(e,i))}},unescape:(r,i={})=>t.unescape(r,G(e,i)),escape:(r,i={})=>t.escape(r,G(e,i)),filter:(r,i={})=>t.filter(r,G(e,i)),defaults:r=>t.defaults(G(e,r)),makeRe:(r,i={})=>t.makeRe(r,G(e,i)),braceExpand:(r,i={})=>t.braceExpand(r,G(e,i)),match:(r,i,s={})=>t.match(r,i,G(e,s)),sep:t.sep,GLOBSTAR:I})};x.defaults=xo;var Ci=(e,t={})=>(Te(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:Xn(e,{max:t.braceExpandMax}));x.braceExpand=Ci;var Lo=(e,t={})=>new yt(e,t).makeRe();x.makeRe=Lo;var No=(e,t,r={})=>{let i=new yt(t,r);return e=e.filter(s=>i.match(s)),i.options.nonull&&!e.length&&e.push(t),e};x.match=No;var ti=/[?*]|[+@!]\(.*?\)|\[|\]/,Fo=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),yt=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(e,t={}){Te(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||Ri,this.isWindows=this.platform==="win32";let r="allowWindowsEscape";this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t[r]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!t.nonegate,this.comment=!1,this.empty=!1,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot!==void 0?t.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let t of e)if(typeof t!="string")return!0;return!1}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)==="#"){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...s)=>console.error(...s)),this.debug(this.pattern,this.globSet);let r=this.globSet.map(s=>this.slashSplit(s));this.globParts=this.preprocess(r),this.debug(this.pattern,this.globParts);let i=this.globParts.map((s,n,o)=>{if(this.isWindows&&this.windowsNoMagicRoot){let a=s[0]===""&&s[1]===""&&(s[2]==="?"||!ti.test(s[2]))&&!ti.test(s[3]),l=/^[a-z]:/i.test(s[0]);if(a)return[...s.slice(0,4),...s.slice(4).map(c=>this.parse(c))];if(l)return[s[0],...s.slice(1).map(c=>this.parse(c))]}return s.map(a=>this.parse(a))});if(this.debug(this.pattern,i),this.set=i.filter(s=>s.indexOf(!1)===-1),this.isWindows)for(let s=0;s<this.set.length;s++){let n=this.set[s];n[0]===""&&n[1]===""&&this.globParts[s][2]==="?"&&typeof n[3]=="string"&&/^[a-z]:$/i.test(n[3])&&(n[2]="?")}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let r=0;r<e.length;r++)for(let i=0;i<e[r].length;i++)e[r][i]==="**"&&(e[r][i]="*");let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):t>=1?e=this.levelOneOptimize(e):e=this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(t=>{let r=-1;for(;(r=t.indexOf("**",r+1))!==-1;){let i=r;for(;t[i+1]==="**";)i++;i!==r&&t.splice(r,i-r)}return t})}levelOneOptimize(e){return e.map(t=>(t=t.reduce((r,i)=>{let s=r[r.length-1];return i==="**"&&s==="**"?r:i===".."&&s&&s!==".."&&s!=="."&&s!=="**"?(r.pop(),r):(r.push(i),r)},[]),t.length===0?[""]:t))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=!1;do{if(t=!1,!this.preserveMultipleSlashes){for(let i=1;i<e.length-1;i++){let s=e[i];i===1&&s===""&&e[0]===""||(s==="."||s==="")&&(t=!0,e.splice(i,1),i--)}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(t=!0,e.pop())}let r=0;for(;(r=e.indexOf("..",r+1))!==-1;){let i=e[r-1];i&&i!=="."&&i!==".."&&i!=="**"&&(t=!0,e.splice(r-1,2),r-=2)}}while(t);return e.length===0?[""]:e}firstPhasePreProcess(e){let t=!1;do{t=!1;for(let r of e){let i=-1;for(;(i=r.indexOf("**",i+1))!==-1;){let n=i;for(;r[n+1]==="**";)n++;n>i&&r.splice(i+1,n-i);let o=r[i+1],a=r[i+2],l=r[i+3];if(o!==".."||!a||a==="."||a===".."||!l||l==="."||l==="..")continue;t=!0,r.splice(i,1);let c=r.slice(0);c[i]="**",e.push(c),i--}if(!this.preserveMultipleSlashes){for(let n=1;n<r.length-1;n++){let o=r[n];n===1&&o===""&&r[0]===""||(o==="."||o==="")&&(t=!0,r.splice(n,1),n--)}r[0]==="."&&r.length===2&&(r[1]==="."||r[1]==="")&&(t=!0,r.pop())}let s=0;for(;(s=r.indexOf("..",s+1))!==-1;){let n=r[s-1];if(n&&n!=="."&&n!==".."&&n!=="**"){t=!0;let o=s===1&&r[s+1]==="**"?["."]:[];r.splice(s-1,2,...o),r.length===0&&r.push(""),s-=2}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let r=t+1;r<e.length;r++){let i=this.partsMatch(e[t],e[r],!this.preserveMultipleSlashes);if(i){e[t]=[],e[r]=i;break}}return e.filter(t=>t.length)}partsMatch(e,t,r=!1){let i=0,s=0,n=[],o="";for(;i<e.length&&s<t.length;)if(e[i]===t[s])n.push(o==="b"?t[s]:e[i]),i++,s++;else if(r&&e[i]==="**"&&t[s]===e[i+1])n.push(e[i]),i++;else if(r&&t[s]==="**"&&e[i]===t[s+1])n.push(t[s]),s++;else if(e[i]==="*"&&t[s]&&(this.options.dot||!t[s].startsWith("."))&&t[s]!=="**"){if(o==="b")return!1;o="a",n.push(e[i]),i++,s++}else if(t[s]==="*"&&e[i]&&(this.options.dot||!e[i].startsWith("."))&&e[i]!=="**"){if(o==="a")return!1;o="b",n.push(t[s]),i++,s++}else return!1;return e.length===t.length&&n}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=!1,r=0;for(let i=0;i<e.length&&e.charAt(i)==="!";i++)t=!t,r++;r&&(this.pattern=e.slice(r)),this.negate=t}matchOne(e,t,r=!1){let i=this.options;if(this.isWindows){let m=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),g=!m&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),w=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),S=!w&&t[0]===""&&t[1]===""&&t[2]==="?"&&typeof t[3]=="string"&&/^[a-z]:$/i.test(t[3]),E=g?3:m?0:void 0,y=S?3:w?0:void 0;if(typeof E=="number"&&typeof y=="number"){let[v,M]=[e[E],t[y]];v.toLowerCase()===M.toLowerCase()&&(t[y]=v,y>E?t=t.slice(y):E>y&&(e=e.slice(E)))}}let{optimizationLevel:s=1}=this.options;s>=2&&(e=this.levelTwoFileOptimize(e)),this.debug("matchOne",this,{file:e,pattern:t}),this.debug("matchOne",e.length,t.length);for(var n=0,o=0,a=e.length,l=t.length;n<a&&o<l;n++,o++){this.debug("matchOne loop");var c=t[o],h=e[n];if(this.debug(t,c,h),c===!1)return!1;if(c===I){this.debug("GLOBSTAR",[t,c,h]);var u=n,p=o+1;if(p===l){for(this.debug("** at the end");n<a;n++)if(e[n]==="."||e[n]===".."||!i.dot&&e[n].charAt(0)===".")return!1;return!0}for(;u<a;){var f=e[u];if(this.debug(`
11
11
  globstar while`,e,u,t,p,f),this.matchOne(e.slice(u),t.slice(p),r))return this.debug("globstar found match!",u,a,f),!0;if(f==="."||f===".."||!i.dot&&f.charAt(0)==="."){this.debug("dot detected!",e,u,t,p);break}this.debug("globstar swallow a segment, and continue"),u++}return!!(r&&(this.debug(`
12
12
  >>> no match, partial?`,e,u,t,p),u===a))}let m;if(typeof c=="string"?(m=h===c,this.debug("string match",c,h,m)):(m=c.test(h),this.debug("pattern match",c,h,m)),!m)return!1}if(n===a&&o===l)return!0;if(n===a)return r;if(o===l)return n===a-1&&e[n]==="";throw new Error("wtf?")}braceExpand(){return Ci(this.pattern,this.options)}parse(e){Te(e);let t=this.options;if(e==="**")return I;if(e==="")return"";let r,i=null;(r=e.match(yo))?i=t.dot?vo:_o:(r=e.match(co))?i=(t.nocase?t.dot?fo:po:t.dot?uo:ho)(r[1]):(r=e.match(bo))?i=(t.nocase?t.dot?Mo:To:t.dot?ko:Ro)(r):(r=e.match(mo))?i=t.dot?So:go:(r=e.match(Eo))&&(i=wo);let s=bi.fromGlob(e,this.options).toMMPattern();return i&&typeof s=="object"&&Reflect.defineProperty(s,"test",{value:i}),s}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let t=this.options,r=t.noglobstar?Oo:t.dot?Do:Po,i=new Set(t.nocase?["i"]:[]),s=e.map(a=>{let l=a.map(h=>{if(h instanceof RegExp)for(let u of h.flags.split(""))i.add(u);return typeof h=="string"?Fo(h):h===I?I:h._src});l.forEach((h,u)=>{let p=l[u+1],f=l[u-1];h!==I||f===I||(f===void 0?p!==void 0&&p!==I?l[u+1]="(?:\\/|"+r+"\\/)?"+p:l[u]=r:p===void 0?l[u-1]=f+"(?:\\/|\\/"+r+")?":p!==I&&(l[u-1]=f+"(?:\\/|\\/"+r+"\\/)"+p,l[u+1]=I))});let c=l.filter(h=>h!==I);if(this.partial&&c.length>=1){let h=[];for(let u=1;u<=c.length;u++)h.push(c.slice(0,u).join("/"));return"(?:"+h.join("|")+")"}return c.join("/")}).join("|"),[n,o]=e.length>1?["(?:",")"]:["",""];s="^"+n+s+o+"$",this.partial&&(s="^(?:\\/|"+n+s.slice(1,-1)+o+")$"),this.negate&&(s="^(?!"+s+").+$");try{this.regexp=new RegExp(s,[...i].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return e==="";if(e==="/"&&t)return!0;let r=this.options;this.isWindows&&(e=e.split("\\").join("/"));let i=this.slashSplit(e);this.debug(this.pattern,"split",i);let s=this.set;this.debug(this.pattern,"set",s);let n=i[i.length-1];if(!n)for(let o=i.length-2;!n&&o>=0;o--)n=i[o];for(let o=0;o<s.length;o++){let a=s[o],l=i;if(r.matchBase&&a.length===1&&(l=[n]),this.matchOne(l,a,t))return r.flipNegate?!0:!this.negate}return r.flipNegate?!1:this.negate}static defaults(e){return x.defaults(e).Minimatch}};x.AST=bi;x.Minimatch=yt;x.escape=Ti;x.unescape=Ft;var Uo=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Oi=new Set,wr=typeof process=="object"&&process?process:{},Di=(e,t,r,i)=>{typeof wr.emitWarning=="function"?wr.emitWarning(e,t,r,i):console.error(`[${r}] ${t}: ${e}`)},Me=globalThis.AbortController,ei=globalThis.AbortSignal;if(typeof Me>"u"){ei=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,i){this._onabort.push(i)}},Me=class{constructor(){t()}signal=new ei;abort(r){if(!this.signal.aborted){this.signal.reason=r,this.signal.aborted=!0;for(let i of this.signal._onabort)i(r);this.signal.onabort?.(r)}}};let e=wr.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{e&&(e=!1,Di("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}var Wo=e=>!Oi.has(e),wt=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),Pi=e=>wt(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?ve:null:null,ve=class extends Array{constructor(e){super(e),this.fill(0)}},$o=class te{heap;length;static#t=!1;static create(t){let r=Pi(t);if(!r)return[];te.#t=!0;let i=new te(t,r);return te.#t=!1,i}constructor(t,r){if(!te.#t)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new r(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}},Re=class Ii{#t;#r;#n;#s;#o;#y;#S;#h;get perf(){return this.#h}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#a;#d;#u;#l;#i;#p;#_;#w;#f;#C;#m;#T;#M;#g;#E;#v;#k;#e;#x;static unsafeExposeInternals(t){return{starts:t.#M,ttls:t.#g,autopurgeTimers:t.#E,sizes:t.#T,keyMap:t.#u,keyList:t.#l,valList:t.#i,next:t.#p,prev:t.#_,get head(){return t.#w},get tail(){return t.#f},free:t.#C,isBackgroundFetch:r=>t.#c(r),backgroundFetch:(r,i,s,n)=>t.#H(r,i,s,n),moveToTail:r=>t.#N(r),indexes:r=>t.#O(r),rindexes:r=>t.#D(r),isStale:r=>t.#b(r)}}get max(){return this.#t}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.#s}get disposeAfter(){return this.#o}constructor(t){let{max:r=0,ttl:i,ttlResolution:s=1,ttlAutopurge:n,updateAgeOnGet:o,updateAgeOnHas:a,allowStale:l,dispose:c,onInsert:h,disposeAfter:u,noDisposeOnSet:p,noUpdateTTL:f,maxSize:m=0,maxEntrySize:g=0,sizeCalculation:w,fetchMethod:S,memoMethod:E,noDeleteOnFetchRejection:y,noDeleteOnStaleGet:v,allowStaleOnFetchRejection:M,allowStaleOnFetchAbort:St,ignoreFetchAbort:Ot,perf:Dt}=t;if(Dt!==void 0&&typeof Dt?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#h=Dt??Uo,r!==0&&!wt(r))throw new TypeError("max option must be a nonnegative integer");let Pt=r?Pi(r):Array;if(!Pt)throw new Error("invalid max value: "+r);if(this.#t=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.#k=!!S,this.#u=new Map,this.#l=new Array(r).fill(void 0),this.#i=new Array(r).fill(void 0),this.#p=new Pt(r),this.#_=new Pt(r),this.#w=0,this.#f=0,this.#C=$o.create(r),this.#a=0,this.#d=0,typeof c=="function"&&(this.#n=c),typeof h=="function"&&(this.#s=h),typeof u=="function"?(this.#o=u,this.#m=[]):(this.#o=void 0,this.#m=void 0),this.#v=!!this.#n,this.#x=!!this.#s,this.#e=!!this.#o,this.noDisposeOnSet=!!p,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!y,this.allowStaleOnFetchRejection=!!M,this.allowStaleOnFetchAbort=!!St,this.ignoreFetchAbort=!!Ot,this.maxEntrySize!==0){if(this.#r!==0&&!wt(this.#r))throw new TypeError("maxSize must be a positive integer if specified");if(!wt(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#B()}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!v,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!a,this.ttlResolution=wt(s)||s===0?s:1,this.ttlAutopurge=!!n,this.ttl=i||0,this.ttl){if(!wt(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#P()}if(this.#t===0&&this.ttl===0&&this.#r===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#t&&!this.#r){let ir="LRU_CACHE_UNBOUNDED";Wo(ir)&&(Oi.add(ir),Di("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",ir,Ii))}}getRemainingTTL(t){return this.#u.has(t)?1/0:0}#P(){let t=new ve(this.#t),r=new ve(this.#t);this.#g=t,this.#M=r;let i=this.ttlAutopurge?new Array(this.#t):void 0;this.#E=i,this.#U=(o,a,l=this.#h.now())=>{if(r[o]=a!==0?l:0,t[o]=a,i?.[o]&&(clearTimeout(i[o]),i[o]=void 0),a!==0&&i){let c=setTimeout(()=>{this.#b(o)&&this.#A(this.#l[o],"expire")},a+1);c.unref&&c.unref(),i[o]=c}},this.#R=o=>{r[o]=t[o]!==0?this.#h.now():0},this.#I=(o,a)=>{if(t[a]){let l=t[a],c=r[a];if(!l||!c)return;o.ttl=l,o.start=c,o.now=s||n();let h=o.now-c;o.remainingTTL=l-h}};let s=0,n=()=>{let o=this.#h.now();if(this.ttlResolution>0){s=o;let a=setTimeout(()=>s=0,this.ttlResolution);a.unref&&a.unref()}return o};this.getRemainingTTL=o=>{let a=this.#u.get(o);if(a===void 0)return 0;let l=t[a],c=r[a];if(!l||!c)return 1/0;let h=(s||n())-c;return l-h},this.#b=o=>{let a=r[o],l=t[o];return!!l&&!!a&&(s||n())-a>l}}#R=()=>{};#I=()=>{};#U=()=>{};#b=()=>!1;#B(){let t=new ve(this.#t);this.#d=0,this.#T=t,this.#F=r=>{this.#d-=t[r],t[r]=0},this.#W=(r,i,s,n)=>{if(this.#c(i))return 0;if(!wt(s))if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(s=n(i,r),!wt(s))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 s},this.#L=(r,i,s)=>{if(t[r]=i,this.#r){let n=this.#r-t[r];for(;this.#d>n;)this.#j(!0)}this.#d+=t[r],s&&(s.entrySize=i,s.totalCalculatedSize=this.#d)}}#F=t=>{};#L=(t,r,i)=>{};#W=(t,r,i,s)=>{if(i||s)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#O({allowStale:t=this.allowStale}={}){if(this.#a)for(let r=this.#f;!(!this.#$(r)||((t||!this.#b(r))&&(yield r),r===this.#w));)r=this.#_[r]}*#D({allowStale:t=this.allowStale}={}){if(this.#a)for(let r=this.#w;!(!this.#$(r)||((t||!this.#b(r))&&(yield r),r===this.#f));)r=this.#p[r]}#$(t){return t!==void 0&&this.#u.get(this.#l[t])===t}*entries(){for(let t of this.#O())this.#i[t]!==void 0&&this.#l[t]!==void 0&&!this.#c(this.#i[t])&&(yield[this.#l[t],this.#i[t]])}*rentries(){for(let t of this.#D())this.#i[t]!==void 0&&this.#l[t]!==void 0&&!this.#c(this.#i[t])&&(yield[this.#l[t],this.#i[t]])}*keys(){for(let t of this.#O()){let r=this.#l[t];r!==void 0&&!this.#c(this.#i[t])&&(yield r)}}*rkeys(){for(let t of this.#D()){let r=this.#l[t];r!==void 0&&!this.#c(this.#i[t])&&(yield r)}}*values(){for(let t of this.#O())this.#i[t]!==void 0&&!this.#c(this.#i[t])&&(yield this.#i[t])}*rvalues(){for(let t of this.#D())this.#i[t]!==void 0&&!this.#c(this.#i[t])&&(yield this.#i[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,r={}){for(let i of this.#O()){let s=this.#i[i],n=this.#c(s)?s.__staleWhileFetching:s;if(n!==void 0&&t(n,this.#l[i],this))return this.get(this.#l[i],r)}}forEach(t,r=this){for(let i of this.#O()){let s=this.#i[i],n=this.#c(s)?s.__staleWhileFetching:s;n!==void 0&&t.call(r,n,this.#l[i],this)}}rforEach(t,r=this){for(let i of this.#D()){let s=this.#i[i],n=this.#c(s)?s.__staleWhileFetching:s;n!==void 0&&t.call(r,n,this.#l[i],this)}}purgeStale(){let t=!1;for(let r of this.#D({allowStale:!0}))this.#b(r)&&(this.#A(this.#l[r],"expire"),t=!0);return t}info(t){let r=this.#u.get(t);if(r===void 0)return;let i=this.#i[r],s=this.#c(i)?i.__staleWhileFetching:i;if(s===void 0)return;let n={value:s};if(this.#g&&this.#M){let o=this.#g[r],a=this.#M[r];if(o&&a){let l=o-(this.#h.now()-a);n.ttl=l,n.start=Date.now()}}return this.#T&&(n.size=this.#T[r]),n}dump(){let t=[];for(let r of this.#O({allowStale:!0})){let i=this.#l[r],s=this.#i[r],n=this.#c(s)?s.__staleWhileFetching:s;if(n===void 0||i===void 0)continue;let o={value:n};if(this.#g&&this.#M){o.ttl=this.#g[r];let a=this.#h.now()-this.#M[r];o.start=Math.floor(Date.now()-a)}this.#T&&(o.size=this.#T[r]),t.unshift([i,o])}return t}load(t){this.clear();for(let[r,i]of t){if(i.start){let s=Date.now()-i.start;i.start=this.#h.now()-s}this.set(r,i.value,i)}}set(t,r,i={}){if(r===void 0)return this.delete(t),this;let{ttl:s=this.ttl,start:n,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=i,{noUpdateTTL:c=this.noUpdateTTL}=i,h=this.#W(t,r,i.size||0,a);if(this.maxEntrySize&&h>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=!0),this.#A(t,"set"),this;let u=this.#a===0?void 0:this.#u.get(t);if(u===void 0)u=this.#a===0?this.#f:this.#C.length!==0?this.#C.pop():this.#a===this.#t?this.#j(!1):this.#a,this.#l[u]=t,this.#i[u]=r,this.#u.set(t,u),this.#p[this.#f]=u,this.#_[u]=this.#f,this.#f=u,this.#a++,this.#L(u,h,l),l&&(l.set="add"),c=!1,this.#x&&this.#s?.(r,t,"add");else{this.#N(u);let p=this.#i[u];if(r!==p){if(this.#k&&this.#c(p)){p.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:f}=p;f!==void 0&&!o&&(this.#v&&this.#n?.(f,t,"set"),this.#e&&this.#m?.push([f,t,"set"]))}else o||(this.#v&&this.#n?.(p,t,"set"),this.#e&&this.#m?.push([p,t,"set"]));if(this.#F(u),this.#L(u,h,l),this.#i[u]=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,t,r===p?"update":"replace")}if(s!==0&&!this.#g&&this.#P(),this.#g&&(c||this.#U(u,s,n),l&&this.#I(l,u)),!o&&this.#e&&this.#m){let p=this.#m,f;for(;f=p?.shift();)this.#o?.(...f)}return this}pop(){try{for(;this.#a;){let t=this.#i[this.#w];if(this.#j(!0),this.#c(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#e&&this.#m){let t=this.#m,r;for(;r=t?.shift();)this.#o?.(...r)}}}#j(t){let r=this.#w,i=this.#l[r],s=this.#i[r];return this.#k&&this.#c(s)?s.__abortController.abort(new Error("evicted")):(this.#v||this.#e)&&(this.#v&&this.#n?.(s,i,"evict"),this.#e&&this.#m?.push([s,i,"evict"])),this.#F(r),this.#E?.[r]&&(clearTimeout(this.#E[r]),this.#E[r]=void 0),t&&(this.#l[r]=void 0,this.#i[r]=void 0,this.#C.push(r)),this.#a===1?(this.#w=this.#f=0,this.#C.length=0):this.#w=this.#p[r],this.#u.delete(i),this.#a--,r}has(t,r={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:s}=r,n=this.#u.get(t);if(n!==void 0){let o=this.#i[n];if(this.#c(o)&&o.__staleWhileFetching===void 0)return!1;if(this.#b(n))s&&(s.has="stale",this.#I(s,n));else return i&&this.#R(n),s&&(s.has="hit",this.#I(s,n)),!0}else s&&(s.has="miss");return!1}peek(t,r={}){let{allowStale:i=this.allowStale}=r,s=this.#u.get(t);if(s===void 0||!i&&this.#b(s))return;let n=this.#i[s];return this.#c(n)?n.__staleWhileFetching:n}#H(t,r,i,s){let n=r===void 0?void 0:this.#i[r];if(this.#c(n))return n;let o=new Me,{signal:a}=i;a?.addEventListener("abort",()=>o.abort(a.reason),{signal:o.signal});let l={signal:o.signal,options:i,context:s},c=(g,w=!1)=>{let{aborted:S}=o.signal,E=i.ignoreFetchAbort&&g!==void 0,y=i.ignoreFetchAbort||!!(i.allowStaleOnFetchAbort&&g!==void 0);if(i.status&&(S&&!w?(i.status.fetchAborted=!0,i.status.fetchError=o.signal.reason,E&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),S&&!E&&!w)return u(o.signal.reason,y);let v=f,M=this.#i[r];return(M===f||E&&w&&M===void 0)&&(g===void 0?v.__staleWhileFetching!==void 0?this.#i[r]=v.__staleWhileFetching:this.#A(t,"fetch"):(i.status&&(i.status.fetchUpdated=!0),this.set(t,g,l.options))),g},h=g=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=g),u(g,!1)),u=(g,w)=>{let{aborted:S}=o.signal,E=S&&i.allowStaleOnFetchAbort,y=E||i.allowStaleOnFetchRejection,v=y||i.noDeleteOnFetchRejection,M=f;if(this.#i[r]===f&&(!v||!w&&M.__staleWhileFetching===void 0?this.#A(t,"fetch"):E||(this.#i[r]=M.__staleWhileFetching)),y)return i.status&&M.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),M.__staleWhileFetching;if(M.__returned===M)throw g},p=(g,w)=>{let S=this.#y?.(t,n,l);S&&S instanceof Promise&&S.then(E=>g(E===void 0?void 0:E),w),o.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(g(void 0),i.allowStaleOnFetchAbort&&(g=E=>c(E,!0)))})};i.status&&(i.status.fetchDispatched=!0);let f=new Promise(p).then(c,h),m=Object.assign(f,{__abortController:o,__staleWhileFetching:n,__returned:void 0});return r===void 0?(this.set(t,m,{...l.options,status:void 0}),r=this.#u.get(t)):this.#i[r]=m,m}#c(t){if(!this.#k)return!1;let r=t;return!!r&&r instanceof Promise&&r.hasOwnProperty("__staleWhileFetching")&&r.__abortController instanceof Me}async fetch(t,r={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:l=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:h=this.noUpdateTTL,noDeleteOnFetchRejection:u=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.#k)return S&&(S.fetch="get"),this.get(t,{allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,status:S});let y={allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,ttl:o,noDisposeOnSet:a,size:l,sizeCalculation:c,noUpdateTTL:h,noDeleteOnFetchRejection:u,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:m,ignoreFetchAbort:f,status:S,signal:E},v=this.#u.get(t);if(v===void 0){S&&(S.fetch="miss");let M=this.#H(t,v,y,g);return M.__returned=M}else{let M=this.#i[v];if(this.#c(M)){let Pt=i&&M.__staleWhileFetching!==void 0;return S&&(S.fetch="inflight",Pt&&(S.returnedStale=!0)),Pt?M.__staleWhileFetching:M.__returned=M}let St=this.#b(v);if(!w&&!St)return S&&(S.fetch="hit"),this.#N(v),s&&this.#R(v),S&&this.#I(S,v),M;let Ot=this.#H(t,v,y,g),Dt=Ot.__staleWhileFetching!==void 0&&i;return S&&(S.fetch=St?"stale":"refresh",Dt&&St&&(S.returnedStale=!0)),Dt?Ot.__staleWhileFetching:Ot.__returned=Ot}}async forceFetch(t,r={}){let i=await this.fetch(t,r);if(i===void 0)throw new Error("fetch() returned undefined");return i}memo(t,r={}){let i=this.#S;if(!i)throw new Error("no memoMethod provided to constructor");let{context:s,forceRefresh:n,...o}=r,a=this.get(t,o);if(!n&&a!==void 0)return a;let l=i(t,a,{options:o,context:s});return this.set(t,l,o),l}get(t,r={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:o}=r,a=this.#u.get(t);if(a!==void 0){let l=this.#i[a],c=this.#c(l);return o&&this.#I(o,a),this.#b(a)?(o&&(o.get="stale"),c?(o&&i&&l.__staleWhileFetching!==void 0&&(o.returnedStale=!0),i?l.__staleWhileFetching:void 0):(n||this.#A(t,"expire"),o&&i&&(o.returnedStale=!0),i?l:void 0)):(o&&(o.get="hit"),c?l.__staleWhileFetching:(this.#N(a),s&&this.#R(a),l))}else o&&(o.get="miss")}#G(t,r){this.#_[r]=t,this.#p[t]=r}#N(t){t!==this.#f&&(t===this.#w?this.#w=this.#p[t]:this.#G(this.#_[t],this.#p[t]),this.#G(this.#f,t),this.#f=t)}delete(t){return this.#A(t,"delete")}#A(t,r){let i=!1;if(this.#a!==0){let s=this.#u.get(t);if(s!==void 0)if(this.#E?.[s]&&(clearTimeout(this.#E?.[s]),this.#E[s]=void 0),i=!0,this.#a===1)this.#K(r);else{this.#F(s);let n=this.#i[s];if(this.#c(n)?n.__abortController.abort(new Error("deleted")):(this.#v||this.#e)&&(this.#v&&this.#n?.(n,t,r),this.#e&&this.#m?.push([n,t,r])),this.#u.delete(t),this.#l[s]=void 0,this.#i[s]=void 0,s===this.#f)this.#f=this.#_[s];else if(s===this.#w)this.#w=this.#p[s];else{let o=this.#_[s];this.#p[o]=this.#p[s];let a=this.#p[s];this.#_[a]=this.#_[s]}this.#a--,this.#C.push(s)}}if(this.#e&&this.#m?.length){let s=this.#m,n;for(;n=s?.shift();)this.#o?.(...n)}return i}clear(){return this.#K("delete")}#K(t){for(let r of this.#D({allowStale:!0})){let i=this.#i[r];if(this.#c(i))i.__abortController.abort(new Error("deleted"));else{let s=this.#l[r];this.#v&&this.#n?.(i,s,t),this.#e&&this.#m?.push([i,s,t])}}if(this.#u.clear(),this.#i.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.#C.length=0,this.#d=0,this.#a=0,this.#e&&this.#m){let r=this.#m,i;for(;i=r?.shift();)this.#o?.(...i)}}},ri=typeof process=="object"&&process?process:{stdout:null,stderr:null},Ho=e=>!!e&&typeof e=="object"&&(e instanceof ke||e instanceof vr.default||Go(e)||Bo(e)),Go=e=>!!e&&typeof e=="object"&&e instanceof Ce.EventEmitter&&typeof e.pipe=="function"&&e.pipe!==vr.default.Writable.prototype.pipe,Bo=e=>!!e&&typeof e=="object"&&e instanceof Ce.EventEmitter&&typeof e.write=="function"&&typeof e.end=="function",lt=Symbol("EOF"),ct=Symbol("maybeEmitEnd"),Et=Symbol("emittedEnd"),me=Symbol("emittingEnd"),Jt=Symbol("emittedError"),ge=Symbol("closed"),ii=Symbol("read"),Se=Symbol("flush"),si=Symbol("flushChunk"),J=Symbol("encoding"),Lt=Symbol("decoder"),C=Symbol("flowing"),Xt=Symbol("paused"),Nt=Symbol("resume"),A=Symbol("buffer"),P=Symbol("pipes"),O=Symbol("bufferLength"),dr=Symbol("bufferPush"),Ee=Symbol("bufferShift"),D=Symbol("objectMode"),k=Symbol("destroyed"),pr=Symbol("error"),fr=Symbol("emitData"),ni=Symbol("emitEnd"),mr=Symbol("emitEnd2"),Q=Symbol("async"),gr=Symbol("abort"),we=Symbol("aborted"),Vt=Symbol("signal"),Tt=Symbol("dataListeners"),$=Symbol("discarded"),qt=e=>Promise.resolve().then(e),Ko=e=>e(),zo=e=>e==="end"||e==="finish"||e==="prefinish",Yo=e=>e instanceof ArrayBuffer||!!e&&typeof e=="object"&&e.constructor&&e.constructor.name==="ArrayBuffer"&&e.byteLength>=0,Jo=e=>!Buffer.isBuffer(e)&&ArrayBuffer.isView(e),Ni=class{src;dest;opts;ondrain;constructor(e,t,r){this.src=e,this.dest=t,this.opts=r,this.ondrain=()=>e[Nt](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Xo=class extends Ni{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(e,t,r){super(e,t,r),this.proxyErrors=i=>this.dest.emit("error",i),e.on("error",this.proxyErrors)}},Vo=e=>!!e.objectMode,qo=e=>!e.objectMode&&!!e.encoding&&e.encoding!=="buffer",ke=class extends Ce.EventEmitter{[C]=!1;[Xt]=!1;[P]=[];[A]=[];[D];[J];[Q];[Lt];[lt]=!1;[Et]=!1;[me]=!1;[ge]=!1;[Jt]=null;[O]=0;[k]=!1;[Vt];[we]=!1;[Tt]=0;[$]=!1;writable=!0;readable=!0;constructor(...e){let t=e[0]||{};if(super(),t.objectMode&&typeof t.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Vo(t)?(this[D]=!0,this[J]=null):qo(t)?(this[J]=t.encoding,this[D]=!1):(this[D]=!1,this[J]=null),this[Q]=!!t.async,this[Lt]=this[J]?new Li.StringDecoder(this[J]):null,t&&t.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[A]}),t&&t.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[P]});let{signal:r}=t;r&&(this[Vt]=r,r.aborted?this[gr]():r.addEventListener("abort",()=>this[gr]()))}get bufferLength(){return this[O]}get encoding(){return this[J]}set encoding(e){throw new Error("Encoding must be set at instantiation time")}setEncoding(e){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[D]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Q]}set async(e){this[Q]=this[Q]||!!e}[gr](){this[we]=!0,this.emit("abort",this[Vt]?.reason),this.destroy(this[Vt]?.reason)}get aborted(){return this[we]}set aborted(e){}write(e,t,r){if(this[we])return!1;if(this[lt])throw new Error("write after end");if(this[k])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof t=="function"&&(r=t,t="utf8"),t||(t="utf8");let i=this[Q]?qt:Ko;if(!this[D]&&!Buffer.isBuffer(e)){if(Jo(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(Yo(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[D]?(this[C]&&this[O]!==0&&this[Se](!0),this[C]?this.emit("data",e):this[dr](e),this[O]!==0&&this.emit("readable"),r&&i(r),this[C]):e.length?(typeof e=="string"&&!(t===this[J]&&!this[Lt]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[J]&&(e=this[Lt].write(e)),this[C]&&this[O]!==0&&this[Se](!0),this[C]?this.emit("data",e):this[dr](e),this[O]!==0&&this.emit("readable"),r&&i(r),this[C]):(this[O]!==0&&this.emit("readable"),r&&i(r),this[C])}read(e){if(this[k])return null;if(this[$]=!1,this[O]===0||e===0||e&&e>this[O])return this[ct](),null;this[D]&&(e=null),this[A].length>1&&!this[D]&&(this[A]=[this[J]?this[A].join(""):Buffer.concat(this[A],this[O])]);let t=this[ii](e||null,this[A][0]);return this[ct](),t}[ii](e,t){if(this[D])this[Ee]();else{let r=t;e===r.length||e===null?this[Ee]():typeof r=="string"?(this[A][0]=r.slice(e),t=r.slice(0,e),this[O]-=e):(this[A][0]=r.subarray(e),t=r.subarray(0,e),this[O]-=e)}return this.emit("data",t),!this[A].length&&!this[lt]&&this.emit("drain"),t}end(e,t,r){return typeof e=="function"&&(r=e,e=void 0),typeof t=="function"&&(r=t,t="utf8"),e!==void 0&&this.write(e,t),r&&this.once("end",r),this[lt]=!0,this.writable=!1,(this[C]||!this[Xt])&&this[ct](),this}[Nt](){this[k]||(!this[Tt]&&!this[P].length&&(this[$]=!0),this[Xt]=!1,this[C]=!0,this.emit("resume"),this[A].length?this[Se]():this[lt]?this[ct]():this.emit("drain"))}resume(){return this[Nt]()}pause(){this[C]=!1,this[Xt]=!0,this[$]=!1}get destroyed(){return this[k]}get flowing(){return this[C]}get paused(){return this[Xt]}[dr](e){this[D]?this[O]+=1:this[O]+=e.length,this[A].push(e)}[Ee](){return this[D]?this[O]-=1:this[O]-=this[A][0].length,this[A].shift()}[Se](e=!1){do;while(this[si](this[Ee]())&&this[A].length);!e&&!this[A].length&&!this[lt]&&this.emit("drain")}[si](e){return this.emit("data",e),this[C]}pipe(e,t){if(this[k])return e;this[$]=!1;let r=this[Et];return t=t||{},e===ri.stdout||e===ri.stderr?t.end=!1:t.end=t.end!==!1,t.proxyErrors=!!t.proxyErrors,r?t.end&&e.end():(this[P].push(t.proxyErrors?new Xo(this,e,t):new Ni(this,e,t)),this[Q]?qt(()=>this[Nt]()):this[Nt]()),e}unpipe(e){let t=this[P].find(r=>r.dest===e);t&&(this[P].length===1?(this[C]&&this[Tt]===0&&(this[C]=!1),this[P]=[]):this[P].splice(this[P].indexOf(t),1),t.unpipe())}addListener(e,t){return this.on(e,t)}on(e,t){let r=super.on(e,t);if(e==="data")this[$]=!1,this[Tt]++,!this[P].length&&!this[C]&&this[Nt]();else if(e==="readable"&&this[O]!==0)super.emit("readable");else if(zo(e)&&this[Et])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[Jt]){let i=t;this[Q]?qt(()=>i.call(this,this[Jt])):i.call(this,this[Jt])}return r}removeListener(e,t){return this.off(e,t)}off(e,t){let r=super.off(e,t);return e==="data"&&(this[Tt]=this.listeners("data").length,this[Tt]===0&&!this[$]&&!this[P].length&&(this[C]=!1)),r}removeAllListeners(e){let t=super.removeAllListeners(e);return(e==="data"||e===void 0)&&(this[Tt]=0,!this[$]&&!this[P].length&&(this[C]=!1)),t}get emittedEnd(){return this[Et]}[ct](){!this[me]&&!this[Et]&&!this[k]&&this[A].length===0&&this[lt]&&(this[me]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[ge]&&this.emit("close"),this[me]=!1)}emit(e,...t){let r=t[0];if(e!=="error"&&e!=="close"&&e!==k&&this[k])return!1;if(e==="data")return!this[D]&&!r?!1:this[Q]?(qt(()=>this[fr](r)),!0):this[fr](r);if(e==="end")return this[ni]();if(e==="close"){if(this[ge]=!0,!this[Et]&&!this[k])return!1;let s=super.emit("close");return this.removeAllListeners("close"),s}else if(e==="error"){this[Jt]=r,super.emit(pr,r);let s=!this[Vt]||this.listeners("error").length?super.emit("error",r):!1;return this[ct](),s}else if(e==="resume"){let s=super.emit("resume");return this[ct](),s}else if(e==="finish"||e==="prefinish"){let s=super.emit(e);return this.removeAllListeners(e),s}let i=super.emit(e,...t);return this[ct](),i}[fr](e){for(let r of this[P])r.dest.write(e)===!1&&this.pause();let t=this[$]?!1:super.emit("data",e);return this[ct](),t}[ni](){return this[Et]?!1:(this[Et]=!0,this.readable=!1,this[Q]?(qt(()=>this[mr]()),!0):this[mr]())}[mr](){if(this[Lt]){let t=this[Lt].end();if(t){for(let r of this[P])r.dest.write(t);this[$]||super.emit("data",t)}}for(let t of this[P])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[D]||(e.dataLength=0);let t=this.promise();return this.on("data",r=>{e.push(r),this[D]||(e.dataLength+=r.length)}),await t,e}async concat(){if(this[D])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[J]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(k,()=>t(new Error("stream destroyed"))),this.on("error",r=>t(r)),this.on("end",()=>e())})}[Symbol.asyncIterator](){this[$]=!1;let e=!1,t=async()=>(this.pause(),e=!0,{value:void 0,done:!0});return{next:()=>{if(e)return t();let r=this.read();if(r!==null)return Promise.resolve({done:!1,value:r});if(this[lt])return t();let i,s,n=c=>{this.off("data",o),this.off("end",a),this.off(k,l),t(),s(c)},o=c=>{this.off("error",n),this.off("end",a),this.off(k,l),this.pause(),i({value:c,done:!!this[lt]})},a=()=>{this.off("error",n),this.off("data",o),this.off(k,l),t(),i({done:!0,value:void 0})},l=()=>n(new Error("stream destroyed"));return new Promise((c,h)=>{s=h,i=c,this.once(k,l),this.once("error",n),this.once("end",a),this.once("data",o)})},throw:t,return:t,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[$]=!1;let e=!1,t=()=>(this.pause(),this.off(pr,t),this.off(k,t),this.off("end",t),e=!0,{done:!0,value:void 0}),r=()=>{if(e)return t();let i=this.read();return i===null?t():{done:!1,value:i}};return this.once("end",t),this.once(pr,t),this.once(k,t),{next:r,throw:t,return:t,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(e){if(this[k])return e?this.emit("error",e):this.emit(k),this;this[k]=!0,this[$]=!0,this[A].length=0,this[O]=0;let t=this;return typeof t.close=="function"&&!this[ge]&&t.close(),e?this.emit("error",e):this.emit(k),this}static get isStream(){return Ho}},Qo=tt.realpathSync.native,ee={lstatSync:tt.lstatSync,readdir:tt.readdir,readdirSync:tt.readdirSync,readlinkSync:tt.readlinkSync,realpathSync:Qo,promises:{lstat:_t.lstat,readdir:_t.readdir,readlink:_t.readlink,realpath:_t.realpath}},Fi=e=>!e||e===ee||e===jo?ee:{...ee,...e,promises:{...ee.promises,...e.promises||{}}},Ui=/^\\\\\?\\([a-z]:)\\?$/i,Zo=e=>e.replace(/\//g,"\\").replace(Ui,"$1\\"),ta=/[\\\/]/,K=0,Wi=1,$i=2,Z=4,ji=6,Hi=8,Mt=10,Gi=12,B=15,Qt=~B,Sr=16,oi=32,re=64,X=128,ye=256,be=512,ai=re|X|be,ea=1023,Er=e=>e.isFile()?Hi:e.isDirectory()?Z:e.isSymbolicLink()?Mt:e.isCharacterDevice()?$i:e.isBlockDevice()?ji:e.isSocket()?Gi:e.isFIFO()?Wi:K,li=new Re({max:2**12}),ie=e=>{let t=li.get(e);if(t)return t;let r=e.normalize("NFKD");return li.set(e,r),r},ci=new Re({max:2**12}),_e=e=>{let t=ci.get(e);if(t)return t;let r=ie(e.toLowerCase());return ci.set(e,r),r},hi=class extends Re{constructor(){super({max:256})}},ra=class extends Re{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1})}},Bi=Symbol("PathScurry setAsCwd"),F=class{name;root;roots;parent;nocase;isCWD=!1;#t;#r;get dev(){return this.#r}#n;get mode(){return this.#n}#s;get nlink(){return this.#s}#o;get uid(){return this.#o}#y;get gid(){return this.#y}#S;get rdev(){return this.#S}#h;get blksize(){return this.#h}#a;get ino(){return this.#a}#d;get size(){return this.#d}#u;get blocks(){return this.#u}#l;get atimeMs(){return this.#l}#i;get mtimeMs(){return this.#i}#p;get ctimeMs(){return this.#p}#_;get birthtimeMs(){return this.#_}#w;get atime(){return this.#w}#f;get mtime(){return this.#f}#C;get ctime(){return this.#C}#m;get birthtime(){return this.#m}#T;#M;#g;#E;#v;#k;#e;#x;#P;#R;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,t=K,r,i,s,n,o){this.name=e,this.#T=s?_e(e):ie(e),this.#e=t&ea,this.nocase=s,this.roots=i,this.root=r||this,this.#x=n,this.#g=o.fullpath,this.#v=o.relative,this.#k=o.relativePosix,this.parent=o.parent,this.parent?this.#t=this.parent.#t:this.#t=Fi(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(e){if(!e)return this;let t=this.getRootString(e),r=e.substring(t.length).split(this.splitSep);return t?this.getRoot(t).#I(r):this.#I(r)}#I(e){let t=this;for(let r of e)t=t.child(r);return t}children(){let e=this.#x.get(this);if(e)return e;let t=Object.assign([],{provisional:0});return this.#x.set(this,t),this.#e&=~Sr,t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let r=this.children(),i=this.nocase?_e(e):ie(e);for(let a of r)if(a.#T===i)return a;let s=this.parent?this.sep:"",n=this.#g?this.#g+s+e:void 0,o=this.newChild(e,K,{...t,parent:this,fullpath:n});return this.canReaddir()||(o.#e|=X),r.push(o),o}relative(){if(this.isCWD)return"";if(this.#v!==void 0)return this.#v;let e=this.name,t=this.parent;if(!t)return this.#v=this.name;let r=t.relative();return r+(!r||!t.parent?"":this.sep)+e}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#k!==void 0)return this.#k;let e=this.name,t=this.parent;if(!t)return this.#k=this.fullpathPosix();let r=t.relativePosix();return r+(!r||!t.parent?"":"/")+e}fullpath(){if(this.#g!==void 0)return this.#g;let e=this.name,t=this.parent;if(!t)return this.#g=this.name;let r=t.fullpath()+(t.parent?this.sep:"")+e;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 i=this.fullpath().replace(/\\/g,"/");return/^[a-z]:\//i.test(i)?this.#E=`//?/${i}`:this.#E=i}let e=this.parent,t=e.fullpathPosix(),r=t+(!t||!e.parent?"":"/")+this.name;return this.#E=r}isUnknown(){return(this.#e&B)===K}isType(e){return this[`is${e}`]()}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.#e&B)===Hi}isDirectory(){return(this.#e&B)===Z}isCharacterDevice(){return(this.#e&B)===$i}isBlockDevice(){return(this.#e&B)===ji}isFIFO(){return(this.#e&B)===Wi}isSocket(){return(this.#e&B)===Gi}isSymbolicLink(){return(this.#e&Mt)===Mt}lstatCached(){return this.#e&oi?this:void 0}readlinkCached(){return this.#P}realpathCached(){return this.#R}readdirCached(){let e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(this.#P)return!0;if(!this.parent)return!1;let e=this.#e&B;return!(e!==K&&e!==Mt||this.#e&ye||this.#e&X)}calledReaddir(){return!!(this.#e&Sr)}isENOENT(){return!!(this.#e&X)}isNamed(e){return this.nocase?this.#T===_e(e):this.#T===ie(e)}async readlink(){let e=this.#P;if(e)return e;if(this.canReadlink()&&this.parent)try{let t=await this.#t.promises.readlink(this.fullpath()),r=(await this.parent.realpath())?.resolve(t);if(r)return this.#P=r}catch(t){this.#D(t.code);return}}readlinkSync(){let e=this.#P;if(e)return e;if(this.canReadlink()&&this.parent)try{let t=this.#t.readlinkSync(this.fullpath()),r=this.parent.realpathSync()?.resolve(t);if(r)return this.#P=r}catch(t){this.#D(t.code);return}}#U(e){this.#e|=Sr;for(let t=e.provisional;t<e.length;t++){let r=e[t];r&&r.#b()}}#b(){this.#e&X||(this.#e=(this.#e|X)&Qt,this.#B())}#B(){let e=this.children();e.provisional=0;for(let t of e)t.#b()}#F(){this.#e|=be,this.#L()}#L(){if(this.#e&re)return;let e=this.#e;(e&B)===Z&&(e&=Qt),this.#e=e|re,this.#B()}#W(e=""){e==="ENOTDIR"||e==="EPERM"?this.#L():e==="ENOENT"?this.#b():this.children().provisional=0}#O(e=""){e==="ENOTDIR"?this.parent.#L():e==="ENOENT"&&this.#b()}#D(e=""){let t=this.#e;t|=ye,e==="ENOENT"&&(t|=X),(e==="EINVAL"||e==="UNKNOWN")&&(t&=Qt),this.#e=t,e==="ENOTDIR"&&this.parent&&this.parent.#L()}#$(e,t){return this.#H(e,t)||this.#j(e,t)}#j(e,t){let r=Er(e),i=this.newChild(e.name,r,{parent:this}),s=i.#e&B;return s!==Z&&s!==Mt&&s!==K&&(i.#e|=re),t.unshift(i),t.provisional++,i}#H(e,t){for(let r=t.provisional;r<t.length;r++){let i=t[r];if((this.nocase?_e(e.name):ie(e.name))===i.#T)return this.#c(e,i,r,t)}}#c(e,t,r,i){let s=t.name;return t.#e=t.#e&Qt|Er(e),s!==e.name&&(t.name=e.name),r!==i.provisional&&(r===i.length-1?i.pop():i.splice(r,1),i.unshift(t)),i.provisional++,t}async lstat(){if((this.#e&X)===0)try{return this.#G(await this.#t.promises.lstat(this.fullpath())),this}catch(e){this.#O(e.code)}}lstatSync(){if((this.#e&X)===0)try{return this.#G(this.#t.lstatSync(this.fullpath())),this}catch(e){this.#O(e.code)}}#G(e){let{atime:t,atimeMs:r,birthtime:i,birthtimeMs:s,blksize:n,blocks:o,ctime:a,ctimeMs:l,dev:c,gid:h,ino:u,mode:p,mtime:f,mtimeMs:m,nlink:g,rdev:w,size:S,uid:E}=e;this.#w=t,this.#l=r,this.#m=i,this.#_=s,this.#h=n,this.#u=o,this.#C=a,this.#p=l,this.#r=c,this.#y=h,this.#a=u,this.#n=p,this.#f=f,this.#i=m,this.#s=g,this.#S=w,this.#d=S,this.#o=E;let y=Er(e);this.#e=this.#e&Qt|y|oi,y!==K&&y!==Z&&y!==Mt&&(this.#e|=re)}#N=[];#A=!1;#K(e){this.#A=!1;let t=this.#N.slice();this.#N.length=0,t.forEach(r=>r(null,e))}readdirCB(e,t=!1){if(!this.canReaddir()){t?e(null,[]):queueMicrotask(()=>e(null,[]));return}let r=this.children();if(this.calledReaddir()){let s=r.slice(0,r.provisional);t?e(null,s):queueMicrotask(()=>e(null,s));return}if(this.#N.push(e),this.#A)return;this.#A=!0;let i=this.fullpath();this.#t.readdir(i,{withFileTypes:!0},(s,n)=>{if(s)this.#W(s.code),r.provisional=0;else{for(let o of n)this.#$(o,r);this.#U(r)}this.#K(r.slice(0,r.provisional))})}#z;async readdir(){if(!this.canReaddir())return[];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();if(this.#z)await this.#z;else{let r=()=>{};this.#z=new Promise(i=>r=i);try{for(let i of await this.#t.promises.readdir(t,{withFileTypes:!0}))this.#$(i,e);this.#U(e)}catch(i){this.#W(i.code),e.provisional=0}this.#z=void 0,r()}return e.slice(0,e.provisional)}readdirSync(){if(!this.canReaddir())return[];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();try{for(let r of this.#t.readdirSync(t,{withFileTypes:!0}))this.#$(r,e);this.#U(e)}catch(r){this.#W(r.code),e.provisional=0}return e.slice(0,e.provisional)}canReaddir(){if(this.#e&ai)return!1;let e=B&this.#e;return e===K||e===Z||e===Mt}shouldWalk(e,t){return(this.#e&Z)===Z&&!(this.#e&ai)&&!e.has(this)&&(!t||t(this))}async realpath(){if(this.#R)return this.#R;if(!((be|ye|X)&this.#e))try{let e=await this.#t.promises.realpath(this.fullpath());return this.#R=this.resolve(e)}catch{this.#F()}}realpathSync(){if(this.#R)return this.#R;if(!((be|ye|X)&this.#e))try{let e=this.#t.realpathSync(this.fullpath());return this.#R=this.resolve(e)}catch{this.#F()}}[Bi](e){if(e===this)return;e.isCWD=!1,this.isCWD=!0;let t=new Set([]),r=[],i=this;for(;i&&i.parent;)t.add(i),i.#v=r.join(this.sep),i.#k=r.join("/"),i=i.parent,r.push("..");for(i=e;i&&i.parent&&!t.has(i);)i.#v=void 0,i.#k=void 0,i=i.parent}},Ki=class zi extends F{sep="\\";splitSep=ta;constructor(t,r=K,i,s,n,o,a){super(t,r,i,s,n,o,a)}newChild(t,r=K,i={}){return new zi(t,r,this.root,this.roots,this.nocase,this.childrenCache(),i)}getRootString(t){return Ut.win32.parse(t).root}getRoot(t){if(t=Zo(t.toUpperCase()),t===this.root.name)return this.root;for(let[r,i]of Object.entries(this.roots))if(this.sameRoot(t,r))return this.roots[t]=i;return this.roots[t]=new br(t,this).root}sameRoot(t,r=this.root.name){return t=t.toUpperCase().replace(/\//g,"\\").replace(Ui,"$1\\"),t===r}},Yi=class Ji extends F{splitSep="/";sep="/";constructor(t,r=K,i,s,n,o,a){super(t,r,i,s,n,o,a)}getRootString(t){return t.startsWith("/")?"/":""}getRoot(t){return this.root}newChild(t,r=K,i={}){return new Ji(t,r,this.root,this.roots,this.nocase,this.childrenCache(),i)}},Xi=class{root;rootPath;roots;cwd;#t;#r;#n;nocase;#s;constructor(e=process.cwd(),t,r,{nocase:i,childrenCacheSize:s=16*1024,fs:n=ee}={}){this.#s=Fi(n),(e instanceof URL||e.startsWith("file://"))&&(e=(0,xi.fileURLToPath)(e));let o=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(o),this.#t=new hi,this.#r=new hi,this.#n=new ra(s);let a=o.substring(this.rootPath.length).split(r);if(a.length===1&&!a[0]&&a.pop(),i===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=i,this.root=this.newRoot(this.#s),this.roots[this.rootPath]=this.root;let l=this.root,c=a.length-1,h=t.sep,u=this.rootPath,p=!1;for(let f of a){let m=c--;l=l.child(f,{relative:new Array(m).fill("..").join(h),relativePosix:new Array(m).fill("..").join("/"),fullpath:u+=(p?"":h)+f}),p=!0}this.cwd=l}depth(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return this.#n}resolve(...e){let t="";for(let s=e.length-1;s>=0;s--){let n=e[s];if(!(!n||n===".")&&(t=t?`${n}/${t}`:n,this.isAbsolute(n)))break}let r=this.#t.get(t);if(r!==void 0)return r;let i=this.cwd.resolve(t).fullpath();return this.#t.set(t,i),i}resolvePosix(...e){let t="";for(let s=e.length-1;s>=0;s--){let n=e[s];if(!(!n||n===".")&&(t=t?`${n}/${t}`:n,this.isAbsolute(n)))break}let r=this.#r.get(t);if(r!==void 0)return r;let i=this.cwd.resolve(t).fullpathPosix();return this.#r.set(t,i),i}relative(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relative()}relativePosix(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relativePosix()}basename(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.name}dirname(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),(e.parent||e).fullpath()}async readdir(e=this.cwd,t={withFileTypes:!0}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof F||(t=e,e=this.cwd);let{withFileTypes:r}=t;if(e.canReaddir()){let i=await e.readdir();return r?i:i.map(s=>s.name)}else return[]}readdirSync(e=this.cwd,t={withFileTypes:!0}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof F||(t=e,e=this.cwd);let{withFileTypes:r=!0}=t;return e.canReaddir()?r?e.readdirSync():e.readdirSync().map(i=>i.name):[]}async lstat(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstat()}lstatSync(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstatSync()}async readlink(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof F||(t=e.withFileTypes,e=this.cwd);let r=await e.readlink();return t?r:r?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof F||(t=e.withFileTypes,e=this.cwd);let r=e.readlinkSync();return t?r:r?.fullpath()}async realpath(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof F||(t=e.withFileTypes,e=this.cwd);let r=await e.realpath();return t?r:r?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof F||(t=e.withFileTypes,e=this.cwd);let r=e.realpathSync();return t?r:r?.fullpath()}async walk(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof F||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:i=!1,filter:s,walkFilter:n}=t,o=[];(!s||s(e))&&o.push(r?e:e.fullpath());let a=new Set,l=(h,u)=>{a.add(h),h.readdirCB((p,f)=>{if(p)return u(p);let m=f.length;if(!m)return u();let g=()=>{--m===0&&u()};for(let w of f)(!s||s(w))&&o.push(r?w:w.fullpath()),i&&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=e;return new Promise((h,u)=>{l(c,p=>{if(p)return u(p);h(o)})})}walkSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof F||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:i=!1,filter:s,walkFilter:n}=t,o=[];(!s||s(e))&&o.push(r?e:e.fullpath());let a=new Set([e]);for(let l of a){let c=l.readdirSync();for(let h of c){(!s||s(h))&&o.push(r?h:h.fullpath());let u=h;if(h.isSymbolicLink()){if(!(i&&(u=h.realpathSync())))continue;u.isUnknown()&&u.lstatSync()}u.shouldWalk(a,n)&&a.add(u)}}return o}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,t={}){return typeof e=="string"?e=this.cwd.resolve(e):e instanceof F||(t=e,e=this.cwd),this.stream(e,t)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof F||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:i=!1,filter:s,walkFilter:n}=t;(!s||s(e))&&(yield r?e:e.fullpath());let o=new Set([e]);for(let a of o){let l=a.readdirSync();for(let c of l){(!s||s(c))&&(yield r?c:c.fullpath());let h=c;if(c.isSymbolicLink()){if(!(i&&(h=c.realpathSync())))continue;h.isUnknown()&&h.lstatSync()}h.shouldWalk(o,n)&&o.add(h)}}}stream(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof F||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:i=!1,filter:s,walkFilter:n}=t,o=new ke({objectMode:!0});(!s||s(e))&&o.write(r?e:e.fullpath());let a=new Set,l=[e],c=0,h=()=>{let u=!1;for(;!u;){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(i&&!S){let E=[];for(let y of w)y.isSymbolicLink()&&E.push(y.realpath().then(v=>v?.isUnknown()?v.lstat():v));if(E.length){Promise.all(E).then(()=>f(null,w,!0));return}}for(let E of w)E&&(!s||s(E))&&(o.write(r?E:E.fullpath())||(u=!0));c--;for(let E of w){let y=E.realpathCached()||E;y.shouldWalk(a,n)&&l.push(y)}u&&!o.flowing?o.once("drain",h):m||h()},m=!0;p.readdirCB(f,!0),m=!1}};return h(),o}streamSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof F||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:i=!1,filter:s,walkFilter:n}=t,o=new ke({objectMode:!0}),a=new Set;(!s||s(e))&&o.write(r?e:e.fullpath());let l=[e],c=0,h=()=>{let u=!1;for(;!u;){let p=l.shift();if(!p){c===0&&o.end();return}c++,a.add(p);let f=p.readdirSync();for(let m of f)(!s||s(m))&&(o.write(r?m:m.fullpath())||(u=!0));c--;for(let m of f){let g=m;if(m.isSymbolicLink()){if(!(i&&(g=m.realpathSync())))continue;g.isUnknown()&&g.lstatSync()}g.shouldWalk(a,n)&&l.push(g)}}u&&!o.flowing&&o.once("drain",h)};return h(),o}chdir(e=this.cwd){let t=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[Bi](t)}},br=class extends Xi{sep="\\";constructor(e=process.cwd(),t={}){let{nocase:r=!0}=t;super(e,Ut.win32,"\\",{...t,nocase:r}),this.nocase=r;for(let i=this.cwd;i;i=i.parent)i.nocase=this.nocase}parseRootPath(e){return Ut.win32.parse(e).root.toUpperCase()}newRoot(e){return new Ki(this.rootPath,Z,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")||e.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(e)}},Tr=class extends Xi{sep="/";constructor(e=process.cwd(),t={}){let{nocase:r=!1}=t;super(e,Ut.posix,"/",{...t,nocase:r}),this.nocase=r}parseRootPath(e){return"/"}newRoot(e){return new Yi(this.rootPath,Z,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}},Vi=class extends Tr{constructor(e=process.cwd(),t={}){let{nocase:r=!0}=t;super(e,{...t,nocase:r})}},$l=process.platform==="win32"?Ki:Yi,ia=process.platform==="win32"?br:process.platform==="darwin"?Vi:Tr,sa=e=>e.length>=1,na=e=>e.length>=1,oa=Symbol.for("nodejs.util.inspect.custom"),qi=class Qi{#t;#r;#n;length;#s;#o;#y;#S;#h;#a;#d=!0;constructor(t,r,i,s){if(!sa(t))throw new TypeError("empty pattern list");if(!na(r))throw new TypeError("empty glob list");if(r.length!==t.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=t.length,i<0||i>=this.length)throw new TypeError("index out of range");if(this.#t=t,this.#r=r,this.#n=i,this.#s=s,this.#n===0){if(this.isUNC()){let[n,o,a,l,...c]=this.#t,[h,u,p,f,...m]=this.#r;c[0]===""&&(c.shift(),m.shift());let g=[n,o,a,l,""].join("/"),w=[h,u,p,f,""].join("/");this.#t=[g,...c],this.#r=[w,...m],this.length=this.#t.length}else if(this.isDrive()||this.isAbsolute()){let[n,...o]=this.#t,[a,...l]=this.#r;o[0]===""&&(o.shift(),l.shift());let c=n+"/",h=a+"/";this.#t=[c,...o],this.#r=[h,...l],this.length=this.#t.length}}}[oa](){return"Pattern <"+this.#r.slice(this.#n).join("/")+">"}pattern(){return this.#t[this.#n]}isString(){return typeof this.#t[this.#n]=="string"}isGlobstar(){return this.#t[this.#n]===I}isRegExp(){return this.#t[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 Qi(this.#t,this.#r,this.#n+1,this.#s),this.#o.#a=this.#a,this.#o.#h=this.#h,this.#o.#S=this.#S,this.#o):this.#o=null}isUNC(){let t=this.#t;return this.#h!==void 0?this.#h:this.#h=this.#s==="win32"&&this.#n===0&&t[0]===""&&t[1]===""&&typeof t[2]=="string"&&!!t[2]&&typeof t[3]=="string"&&!!t[3]}isDrive(){let t=this.#t;return this.#S!==void 0?this.#S:this.#S=this.#s==="win32"&&this.#n===0&&this.length>1&&typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0])}isAbsolute(){let t=this.#t;return this.#a!==void 0?this.#a:this.#a=t[0]===""&&t.length>1||this.isDrive()||this.isUNC()}root(){let t=this.#t[0];return typeof t=="string"&&this.isAbsolute()&&this.#n===0?t:""}checkFollowGlobstar(){return!(this.#n===0||!this.isGlobstar()||!this.#d)}markFollowGlobstar(){return this.#n===0||!this.isGlobstar()||!this.#d?!1:(this.#d=!1,!0)}},aa=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",ui=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:t,nocase:r,noext:i,noglobstar:s,platform:n=aa}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=n,this.mmopts={dot:!0,nobrace:t,nocase:r,noext:i,noglobstar:s,optimizationLevel:2,platform:n,nocomment:!0,nonegate:!0};for(let o of e)this.add(o)}add(e){let t=new yt(e,this.mmopts);for(let r=0;r<t.set.length;r++){let i=t.set[r],s=t.globParts[r];if(!i||!s)throw new Error("invalid pattern object");for(;i[0]==="."&&s[0]===".";)i.shift(),s.shift();let n=new qi(i,s,0,this.platform),o=new yt(n.globString(),this.mmopts),a=s[s.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(e){let t=e.fullpath(),r=`${t}/`,i=e.relative()||".",s=`${i}/`;for(let n of this.relative)if(n.match(i)||n.match(s))return!0;for(let n of this.absolute)if(n.match(t)||n.match(r))return!0;return!1}childrenIgnored(e){let t=e.fullpath()+"/",r=(e.relative()||".")+"/";for(let i of this.relativeChildren)if(i.match(r))return!0;for(let i of this.absoluteChildren)if(i.match(t))return!0;return!1}},la=class Zi{store;constructor(t=new Map){this.store=t}copy(){return new Zi(new Map(this.store))}hasWalked(t,r){return this.store.get(t.fullpath())?.has(r.globString())}storeWalked(t,r){let i=t.fullpath(),s=this.store.get(i);s?s.add(r.globString()):this.store.set(i,new Set([r.globString()]))}},ca=class{store=new Map;add(e,t,r){let i=(t?2:0)|(r?1:0),s=this.store.get(e);this.store.set(e,s===void 0?i:i&s)}entries(){return[...this.store.entries()].map(([e,t])=>[e,!!(t&2),!!(t&1)])}},ha=class{store=new Map;add(e,t){if(!e.canReaddir())return;let r=this.store.get(e);r?r.find(i=>i.globString()===t.globString())||r.push(t):this.store.set(e,[t])}get(e){let t=this.store.get(e);if(!t)throw new Error("attempting to walk unknown path");return t}entries(){return this.keys().map(e=>[e,this.store.get(e)])}keys(){return[...this.store.keys()].filter(e=>e.canReaddir())}},di=class ts{hasWalkedCache;matches=new ca;subwalks=new ha;patterns;follow;dot;opts;constructor(t,r){this.opts=t,this.follow=!!t.follow,this.dot=!!t.dot,this.hasWalkedCache=r?r.copy():new la}processPatterns(t,r){this.patterns=r;let i=r.map(s=>[t,s]);for(let[s,n]of i){this.hasWalkedCache.storeWalked(s,n);let o=n.root(),a=n.isAbsolute()&&this.opts.absolute!==!1;if(o){s=s.resolve(o==="/"&&this.opts.root!==void 0?this.opts.root:o);let u=n.rest();if(u)n=u;else{this.matches.add(s,!0,!1);continue}}if(s.isENOENT())continue;let l,c,h=!1;for(;typeof(l=n.pattern())=="string"&&(c=n.rest());)s=s.resolve(l),n=c,h=!0;if(l=n.pattern(),c=n.rest(),h){if(this.hasWalkedCache.hasWalked(s,n))continue;this.hasWalkedCache.storeWalked(s,n)}if(typeof l=="string"){let u=l===".."||l===""||l===".";this.matches.add(s.resolve(l),a,u);continue}else if(l===I){(!s.isSymbolicLink()||this.follow||n.checkFollowGlobstar())&&this.subwalks.add(s,n);let u=c?.pattern(),p=c?.rest();if(!c||(u===""||u===".")&&!p)this.matches.add(s,a,u===""||u===".");else if(u===".."){let f=s.parent||s;p?this.hasWalkedCache.hasWalked(f,p)||this.subwalks.add(f,p):this.matches.add(f,a,!0)}}else l instanceof RegExp&&this.subwalks.add(s,n)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new ts(this.opts,this.hasWalkedCache)}filterEntries(t,r){let i=this.subwalks.get(t),s=this.child();for(let n of r)for(let o of i){let a=o.isAbsolute(),l=o.pattern(),c=o.rest();l===I?s.testGlobstar(n,o,c,a):l instanceof RegExp?s.testRegExp(n,l,c,a):s.testString(n,l,c,a)}return s}testGlobstar(t,r,i,s){if((this.dot||!t.name.startsWith("."))&&(r.hasMore()||this.matches.add(t,s,!1),t.canReaddir()&&(this.follow||!t.isSymbolicLink()?this.subwalks.add(t,r):t.isSymbolicLink()&&(i&&r.checkFollowGlobstar()?this.subwalks.add(t,i):r.markFollowGlobstar()&&this.subwalks.add(t,r)))),i){let n=i.pattern();if(typeof n=="string"&&n!==".."&&n!==""&&n!==".")this.testString(t,n,i.rest(),s);else if(n===".."){let o=t.parent||t;this.subwalks.add(o,i)}else n instanceof RegExp&&this.testRegExp(t,n,i.rest(),s)}}testRegExp(t,r,i,s){r.test(t.name)&&(i?this.subwalks.add(t,i):this.matches.add(t,s,!1))}testString(t,r,i,s){t.isNamed(r)&&(i?this.subwalks.add(t,i):this.matches.add(t,s,!1))}},ua=(e,t)=>typeof e=="string"?new ui([e],t):Array.isArray(e)?new ui(e,t):e,es=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#t=[];#r;#n;signal;maxDepth;includeChildMatches;constructor(e,t,r){if(this.patterns=e,this.path=t,this.opts=r,this.#n=!r.posix&&r.platform==="win32"?"\\":"/",this.includeChildMatches=r.includeChildMatches!==!1,(r.ignore||!this.includeChildMatches)&&(this.#r=ua(r.ignore??[],r),!this.includeChildMatches&&typeof this.#r.add!="function")){let i="cannot ignore child matches, ignore lacks add() method.";throw new Error(i)}this.maxDepth=r.maxDepth||1/0,r.signal&&(this.signal=r.signal,this.signal.addEventListener("abort",()=>{this.#t.length=0}))}#s(e){return this.seen.has(e)||!!this.#r?.ignored?.(e)}#o(e){return!!this.#r?.childrenIgnored?.(e)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let e;for(;!this.paused&&(e=this.#t.shift());)e()}onResume(e){this.signal?.aborted||(this.paused?this.#t.push(e):e())}async matchCheck(e,t){if(t&&this.opts.nodir)return;let r;if(this.opts.realpath){if(r=e.realpathCached()||await e.realpath(),!r)return;e=r}let i=e.isUnknown()||this.opts.stat?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&i?.isSymbolicLink()){let s=await i.realpath();s&&(s.isUnknown()||this.opts.stat)&&await s.lstat()}return this.matchCheckTest(i,t)}matchCheckTest(e,t){return e&&(this.maxDepth===1/0||e.depth()<=this.maxDepth)&&(!t||e.canReaddir())&&(!this.opts.nodir||!e.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!e.isSymbolicLink()||!e.realpathCached()?.isDirectory())&&!this.#s(e)?e:void 0}matchCheckSync(e,t){if(t&&this.opts.nodir)return;let r;if(this.opts.realpath){if(r=e.realpathCached()||e.realpathSync(),!r)return;e=r}let i=e.isUnknown()||this.opts.stat?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&i?.isSymbolicLink()){let s=i.realpathSync();s&&(s?.isUnknown()||this.opts.stat)&&s.lstatSync()}return this.matchCheckTest(i,t)}matchFinish(e,t){if(this.#s(e))return;if(!this.includeChildMatches&&this.#r?.add){let s=`${e.relativePosix()}/**`;this.#r.add(s)}let r=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(e);let i=this.opts.mark&&e.isDirectory()?this.#n:"";if(this.opts.withFileTypes)this.matchEmit(e);else if(r){let s=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(s+i)}else{let s=this.opts.posix?e.relativePosix():e.relative(),n=this.opts.dotRelative&&!s.startsWith(".."+this.#n)?"."+this.#n:"";this.matchEmit(s?n+s+i:"."+i)}}async match(e,t,r){let i=await this.matchCheck(e,r);i&&this.matchFinish(i,t)}matchSync(e,t,r){let i=this.matchCheckSync(e,r);i&&this.matchFinish(i,t)}walkCB(e,t,r){this.signal?.aborted&&r(),this.walkCB2(e,t,new di(this.opts),r)}walkCB2(e,t,r,i){if(this.#o(e))return i();if(this.signal?.aborted&&i(),this.paused){this.onResume(()=>this.walkCB2(e,t,r,i));return}r.processPatterns(e,t);let s=1,n=()=>{--s===0&&i()};for(let[o,a,l]of r.matches.entries())this.#s(o)||(s++,this.match(o,a,l).then(()=>n()));for(let o of r.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;s++;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(e,t,r,i){r=r.filterEntries(e,t);let s=1,n=()=>{--s===0&&i()};for(let[o,a,l]of r.matches.entries())this.#s(o)||(s++,this.match(o,a,l).then(()=>n()));for(let[o,a]of r.subwalks.entries())s++,this.walkCB2(o,a,r.child(),n);n()}walkCBSync(e,t,r){this.signal?.aborted&&r(),this.walkCB2Sync(e,t,new di(this.opts),r)}walkCB2Sync(e,t,r,i){if(this.#o(e))return i();if(this.signal?.aborted&&i(),this.paused){this.onResume(()=>this.walkCB2Sync(e,t,r,i));return}r.processPatterns(e,t);let s=1,n=()=>{--s===0&&i()};for(let[o,a,l]of r.matches.entries())this.#s(o)||this.matchSync(o,a,l);for(let o of r.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;s++;let a=o.readdirSync();this.walkCB3Sync(o,a,r,n)}n()}walkCB3Sync(e,t,r,i){r=r.filterEntries(e,t);let s=1,n=()=>{--s===0&&i()};for(let[o,a,l]of r.matches.entries())this.#s(o)||this.matchSync(o,a,l);for(let[o,a]of r.subwalks.entries())s++,this.walkCB2Sync(o,a,r.child(),n);n()}},pi=class extends es{matches=new Set;constructor(e,t,r){super(e,t,r)}matchEmit(e){this.matches.add(e)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((e,t)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?t(this.signal.reason):e(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}},fi=class extends es{results;constructor(e,t,r){super(e,t,r),this.results=new ke({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(e){this.results.write(e),this.results.flowing||this.pause()}stream(){let e=this.path;return e.isUnknown()?e.lstat().then(()=>{this.walkCB(e,this.patterns,()=>this.results.end())}):this.walkCB(e,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}},da=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",kt=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(e,t){if(!t)throw new TypeError("glob options required");if(this.withFileTypes=!!t.withFileTypes,this.signal=t.signal,this.follow=!!t.follow,this.dot=!!t.dot,this.dotRelative=!!t.dotRelative,this.nodir=!!t.nodir,this.mark=!!t.mark,t.cwd?(t.cwd instanceof URL||t.cwd.startsWith("file://"))&&(t.cwd=(0,Ai.fileURLToPath)(t.cwd)):this.cwd="",this.cwd=t.cwd||"",this.root=t.root,this.magicalBraces=!!t.magicalBraces,this.nobrace=!!t.nobrace,this.noext=!!t.noext,this.realpath=!!t.realpath,this.absolute=t.absolute,this.includeChildMatches=t.includeChildMatches!==!1,this.noglobstar=!!t.noglobstar,this.matchBase=!!t.matchBase,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:1/0,this.stat=!!t.stat,this.ignore=t.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof e=="string"&&(e=[e]),this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(e=e.map(a=>a.replace(/\\/g,"/"))),this.matchBase){if(t.noglobstar)throw new TypeError("base matching requires globstar");e=e.map(a=>a.includes("/")?a:`./**/${a}`)}if(this.pattern=e,this.platform=t.platform||da,this.opts={...t,platform:this.platform},t.scurry){if(this.scurry=t.scurry,t.nocase!==void 0&&t.nocase!==t.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let a=t.platform==="win32"?br:t.platform==="darwin"?Vi:t.platform?Tr:ia;this.scurry=new a(this.cwd,{nocase:t.nocase,fs:t.fs})}this.nocase=this.scurry.nocase;let r=this.platform==="darwin"||this.platform==="win32",i={braceExpandMax:1e4,...t,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},s=this.pattern.map(a=>new yt(a,i)),[n,o]=s.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 qi(a,c,0,this.platform)})}async walk(){return[...await new pi(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 pi(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 fi(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 fi(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()}},pa=(e,t={})=>{Array.isArray(e)||(e=[e]);for(let r of e)if(new yt(r,t).hasMagic())return!0;return!1};function Ae(e,t={}){return new kt(e,t).streamSync()}function rs(e,t={}){return new kt(e,t).stream()}function se(e,t={}){return new kt(e,t).walkSync()}async function mi(e,t={}){return new kt(e,t).walk()}function Oe(e,t={}){return new kt(e,t).iterateSync()}function is(e,t={}){return new kt(e,t).iterate()}var fa=Ae,ma=Object.assign(rs,{sync:Ae}),ga=Oe,Sa=Object.assign(is,{sync:Oe}),Ea=Object.assign(se,{stream:Ae,iterate:Oe}),gi=Object.assign(mi,{glob:mi,globSync:se,sync:Ea,globStream:rs,stream:ma,globStreamSync:Ae,streamSync:fa,globIterate:is,iterate:Sa,globIterateSync:Oe,iterateSync:ga,Glob:kt,hasMagic:pa,escape:Ti,unescape:Ft});gi.glob=gi;var ht=require("fs"),ss=require("path");function ns(e){try{if(!(0,ht.existsSync)(e))return{offsets:{}};let t=(0,ht.readFileSync)(e,"utf-8"),r=JSON.parse(t);return r.offsets?r:{offsets:{}}}catch(t){return d.warn("TRANSCRIPT","Failed to load watch state, starting fresh",{statePath:e,error:t instanceof Error?t.message:String(t)}),{offsets:{}}}}function os(e,t){try{let r=(0,ss.dirname)(e);(0,ht.existsSync)(r)||(0,ht.mkdirSync)(r,{recursive:!0}),(0,ht.writeFileSync)(e,JSON.stringify(t,null,2))}catch(r){d.warn("TRANSCRIPT","Failed to save watch state",{statePath:e,error:r instanceof Error?r.message:String(r)})}}var ae=ot(require("path"),1);var jt=ot(require("path"),1),H=require("fs");var as=require("node:child_process");function De(e,t,r){return(0,as.spawn)(e,t??[],{windowsHide:!0,...r})}var z={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},vt={SUCCESS:0,FAILURE:1,BLOCKING_ERROR:2,USER_MESSAGE_ONLY:3};function ut(e){return process.platform==="win32"?Math.round(e*z.WINDOWS_MULTIPLIER):e}var rt=require("fs"),ne=require("path"),Mr=require("os");var b=require("fs");var et=require("path");var ls=require("crypto");var wa=process.platform==="win32";function ya(e){(0,b.existsSync)(e)||(0,b.mkdirSync)(e,{recursive:!0})}function Pe(e,t){let r=e;try{if((0,b.lstatSync)(e).isSymbolicLink())try{r=(0,b.realpathSync)(e)}catch{let c=(0,b.readlinkSync)(e);r=(0,et.resolve)((0,et.dirname)(e),c)}}catch(c){let h=c.code;if(h!=="ENOENT"&&h!=="ENOTDIR")throw c}ya((0,et.dirname)(r));let i=(0,et.dirname)(r),s=(0,et.basename)(r),n=(0,et.join)(i,`.${s}.${process.pid}.${(0,ls.randomBytes)(6).toString("hex")}.tmp`),o=Buffer.from(JSON.stringify(t,null,2)+`
13
- `,"utf-8"),a;try{a=(0,b.statSync)(r).mode&511}catch{}let l;try{l=a!==void 0?(0,b.openSync)(n,"w",a):(0,b.openSync)(n,"w");let c=0;for(;c<o.length;){let h=(0,b.writeSync)(l,o,c,o.length-c);if(h===0)throw new Error(`writeSync stalled at ${c}/${o.length} bytes`);c+=h}if((0,b.fsyncSync)(l),(0,b.closeSync)(l),l=void 0,(0,b.renameSync)(n,r),!wa){let h;try{h=(0,b.openSync)(i,"r"),(0,b.fsyncSync)(h)}catch{}finally{if(h!==void 0)try{(0,b.closeSync)(h)}catch{}}}}catch(c){if(l!==void 0)try{(0,b.closeSync)(l)}catch{}try{(0,b.unlinkSync)(n)}catch{}throw c}}var it=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(ut(z.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,ne.join)((0,Mr.homedir)(),".keepmind"),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:"5",CLAUDE_MEM_OBSERVATION_BATCH_MAX:"1",CLAUDE_MEM_MAX_CONTEXT_MESSAGES:"40",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,ne.join)((0,Mr.homedir)(),".keepmind","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_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_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",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 envOverride(t){let r=t.replace(/^CLAUDE_MEM_/,"KEEPMIND_");return process.env[r]??process.env[t]}static get(t){return this.envOverride(t)??this.DEFAULTS[t]}static getInt(t){let r=this.get(t);return parseInt(r,10)}static getBool(t){let r=this.get(t);return r==="true"||r===!0}static applyEnvOverrides(t){let r={...t};for(let i of Object.keys(this.DEFAULTS)){let s=this.envOverride(i);s!==void 0&&(r[i]=s)}return r}static loadFromFile(t,r=!0){try{if(!(0,rt.existsSync)(t)){let a=this.getAllDefaults();try{let l=(0,ne.dirname)(t);(0,rt.existsSync)(l)||(0,rt.mkdirSync)(l,{recursive:!0}),Pe(t,a),console.warn("[SETTINGS] Created settings file with defaults:",t)}catch(l){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",t,l instanceof Error?l.message:String(l))}return r?this.applyEnvOverrides(a):a}let i=(0,rt.readFileSync)(t,"utf-8"),s=JSON.parse(i.replace(/^\uFEFF/,"")),n=s;if(s.env&&typeof s.env=="object"){n=s.env;try{Pe(t,n),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",t)}catch(a){console.warn("[SETTINGS] Failed to auto-migrate settings file:",t,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(i){console.warn("[SETTINGS] Failed to load settings, using defaults:",t,i instanceof Error?i.message:String(i));let s=this.getAllDefaults();try{if((0,rt.existsSync)(t)){let n=`${t}.corrupt-${Date.now()}`;(0,rt.renameSync)(t,n),console.warn("[SETTINGS] Backed up corrupt settings file to:",n)}Pe(t,s),console.warn("[SETTINGS] Recovered settings file with defaults:",t)}catch(n){console.warn("[SETTINGS] Failed to recover corrupt settings file:",t,n instanceof Error?n.message:String(n))}return r?this.applyEnvOverrides(s):s}}};var Ie=null;function dt(){return Ie!==null||(Ie=it.loadFromFile(he)),Ie}var Rt=require("fs");var Or=require("child_process");var st=require("fs"),Cr=ot(require("path"),1);var _a=["CLAUDECODE_","CLAUDE_CODE_"],va=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID","HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy"]),ba=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 xe(e=process.env){let t={};for(let[r,i]of Object.entries(e))if(i!==void 0){if(ba.has(r)){t[r]=i;continue}va.has(r)||_a.some(s=>r.startsWith(s))||(t[r]=i)}return t}var Ta=5e3,Ma=1e3,ka=R.supervisorRegistry();function pt(e){if(!Number.isInteger(e)||e<0||e===0)return!1;try{return process.kill(e,0),!0}catch(t){if(t instanceof Error){let r=t.code;return r==="EPERM"?!0:(d.debug("SYSTEM","PID check failed",{pid:e,code:r}),!1)}return d.warn("SYSTEM","PID check threw non-Error",{pid:e,error:String(t)}),!1}}async function Le(e,t){let r=Date.now()+t;for(;Date.now()<r;){if(e.every(i=>!pt(i.pid)))return;await new Promise(i=>setTimeout(i,100))}}var Ra=5e3,cs=new Map;function Ca(e){let t=cs.get(e);if(t&&Date.now()-t.capturedAtMs<Ra)return t.token;let r=null;try{let i=(0,Or.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${e}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...xe(process.env),LC_ALL:"C",LANG:"C"}});if(i.status===0){let s=i.stdout.trim();r=s.length>0?s:null}}catch(i){d.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:e,error:i instanceof Error?i.message:String(i)}),r=null}return cs.set(e,{token:r,capturedAtMs:Date.now()}),r}function hs(e){if(!Number.isInteger(e)||e<=0)return null;if(process.platform==="linux")try{let t=(0,st.readFileSync)(`/proc/${e}/stat`,"utf-8"),r=t.lastIndexOf(") ");if(r<0)return null;let s=t.slice(r+2).split(" ")[19];return s&&/^\d+$/.test(s)?s:null}catch(t){return d.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:e,error:t instanceof Error?t.message:String(t)}),null}if(process.platform==="win32")return Ca(e);try{let t=(0,Or.spawnSync)("ps",["-p",String(e),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...xe(process.env),LC_ALL:"C",LANG:"C"}});if(t.status!==0)return null;let r=t.stdout.trim();return r.length>0?r:null}catch(t){return d.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:e,error:t instanceof Error?t.message:String(t)}),null}}function Dr(e){if(!e||!pt(e.pid))return!1;if(!e.startToken)return!0;let t=hs(e.pid);if(t===null)return!0;let r=t===e.startToken;return r||d.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:e.pid,stored:e.startToken,current:t}),r}var Ar=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(t=ka){this.registryPath=t}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,st.mkdirSync)(Cr.default.dirname(this.registryPath),{recursive:!0}),!(0,st.existsSync)(this.registryPath)){this.persist();return}try{let i=JSON.parse((0,st.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[s,n]of Object.entries(i))this.entries.set(s,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 t=this.pruneDeadEntries();t>0&&d.info("SYSTEM","Removed dead processes from supervisor registry",{removed:t}),this.persist()}register(t,r,i){this.initialize(),this.entries.set(t,r),i&&this.runtimeProcesses.set(t,i),this.persist()}unregister(t){this.initialize();let r=this.entries.get(t);this.entries.delete(t),this.runtimeProcesses.delete(t),this.persist(),r?.type==="sdk"&&Rr()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([t,r])=>({id:t,...r})).sort((t,r)=>{let i=Date.parse(t.startedAt),s=Date.parse(r.startedAt);return(Number.isNaN(i)?0:i)-(Number.isNaN(s)?0:s)})}getBySession(t){let r=String(t);return this.getAll().filter(i=>i.sessionId!==void 0&&String(i.sessionId)===r)}getRuntimeProcess(t){return this.runtimeProcesses.get(t)}getByPid(t){return this.getAll().filter(r=>r.pid===t)}pruneDeadEntries(){this.initialize();let t=0,r=0;for(let[i,s]of this.entries)pt(s.pid)||(this.entries.delete(i),this.runtimeProcesses.delete(i),t+=1,s.type==="sdk"&&(r+=1));t>0&&this.persist();for(let i=0;i<r;i+=1)Rr();return t}async reapSession(t){this.initialize();let r=this.getBySession(t);if(r.length===0)return 0;let i=typeof t=="number"?t:Number(t)||void 0;d.info("SYSTEM",`Reaping ${r.length} process(es) for session ${t}`,{sessionId:i,pids:r.map(o=>o.pid)});let s=r.filter(o=>pt(o.pid));for(let o of s)try{typeof o.pgid=="number"&&process.platform!=="win32"?process.kill(-o.pgid,"SIGTERM"):process.kill(o.pid,"SIGTERM")}catch(a){a instanceof Error?a.code!=="ESRCH"&&d.debug("SYSTEM",`Failed to SIGTERM session process PID ${o.pid}`,{pid:o.pid,pgid:o.pgid},a):d.warn("SYSTEM",`Failed to SIGTERM session process PID ${o.pid} (non-Error)`,{pid:o.pid,pgid:o.pgid,error:String(a)})}await Le(s,Ta);let n=s.filter(o=>pt(o.pid));for(let o of n){d.warn("SYSTEM",`Session process PID ${o.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:o.pid,pgid:o.pgid,sessionId:i});try{typeof o.pgid=="number"&&process.platform!=="win32"?process.kill(-o.pgid,"SIGKILL"):process.kill(o.pid,"SIGKILL")}catch(a){a instanceof Error?a.code!=="ESRCH"&&d.debug("SYSTEM",`Failed to SIGKILL session process PID ${o.pid}`,{pid:o.pid,pgid:o.pgid},a):d.warn("SYSTEM",`Failed to SIGKILL session process PID ${o.pid} (non-Error)`,{pid:o.pid,pgid:o.pgid,error:String(a)})}}if(n.length>0){let o=Date.now()+Ma;for(;Date.now()<o&&n.filter(l=>pt(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let o of r)this.entries.delete(o.id),this.runtimeProcesses.delete(o.id);this.persist();for(let o of r)o.type==="sdk"&&Rr();return d.info("SYSTEM",`Reaped ${r.length} process(es) for session ${t}`,{sessionId:i,reaped:r.length}),r.length}persist(){let t={processes:Object.fromEntries(this.entries.entries())};(0,st.mkdirSync)(Cr.default.dirname(this.registryPath),{recursive:!0}),(0,st.writeFileSync)(this.registryPath,JSON.stringify(t,null,2))}},kr=null;function Ne(){return kr||(kr=new Ar),kr}var Aa=[];function Rr(){let e=Aa.shift();e&&e()}var ds=require("child_process"),Wt=require("fs"),ps=require("util");var Oa=(0,ps.promisify)(ds.execFile),Da=R.workerPid();async function fs(e){let t=e.currentPid??process.pid,r=e.pidFilePath??Da,i=e.registry.getAll(),s=[...i].filter(o=>o.pid!==t).sort((o,a)=>Date.parse(a.startedAt)-Date.parse(o.startedAt));for(let o of s){if(!pt(o.pid)){e.registry.unregister(o.id);continue}try{await us(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 Le(s,5e3);let n=s.filter(o=>pt(o.pid));for(let o of n)try{await us(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 Le(n,1e3);for(let o of s)e.registry.unregister(o.id);for(let o of i.filter(a=>a.pid===t))e.registry.unregister(o.id);Pa(r,t),e.registry.pruneDeadEntries()}function Pa(e,t){if(!(0,Wt.existsSync)(e))return;let r=null;try{let i=JSON.parse((0,Wt.readFileSync)(e,"utf-8"));r=typeof i.pid=="number"?i.pid:null}catch(i){d.debug("SYSTEM","PID file unreadable during shutdown \u2014 leaving it (cannot prove ownership)",{pidFilePath:e,error:i instanceof Error?i.message:String(i)});return}if(r!==t){d.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:e,recordedPid:r,currentPid:t});return}try{(0,Wt.rmSync)(e,{force:!0})}catch(i){i instanceof Error?d.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:e},i):d.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:e,error:String(i)})}}async function us(e,t){let{pid:r,pgid:i}=e;if(process.platform!=="win32"){if(typeof i=="number")try{process.kill(-i,t);return}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}try{process.kill(r,t)}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}return}if(t==="SIGTERM"){try{process.kill(r,t)}catch(o){if(o instanceof Error&&o.code==="ESRCH")return;throw o}return}let s=await Ia();if(s){await new Promise((o,a)=>{s(r,t,l=>{if(!l){o();return}if(l.code==="ESRCH"){o();return}a(l)})});return}let n=["/PID",String(r),"/T"];t==="SIGKILL"&&n.push("/F"),await Oa("taskkill",n,{timeout:z.POWERSHELL_COMMAND,windowsHide:!0})}async function Ia(){let e="tree-kill";try{let t=await import(e);return t.default??t}catch(t){return d.debug("SYSTEM","tree-kill module not available, using fallback",{},t instanceof Error?t:void 0),null}}var ms=3e4,$t=null;function xa(){let t=Ne().pruneDeadEntries();t>0&&d.info("SYSTEM",`Health check: pruned ${t} dead process(es) from registry`)}function gs(){$t===null&&($t=setInterval(xa,ms),$t.unref(),d.debug("SYSTEM","Health checker started",{intervalMs:ms}))}function Ss(){$t!==null&&(clearInterval($t),$t=null,d.debug("SYSTEM","Health checker stopped"))}var La=R.workerPid(),Pr=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(t){this.registry=t}async start(){if(this.started)return;if(this.registry.initialize(),Fe({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,gs()}configureSignalHandlers(t){if(this.shutdownHandler=t,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async i=>{if(this.shutdownInitiated){d.warn("SYSTEM",`Received ${i} but shutdown already in progress`);return}this.shutdownInitiated=!0,d.info("SYSTEM",`Received ${i}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(s){s instanceof Error?d.error("SYSTEM","Error during shutdown",{},s):d.error("SYSTEM","Error during shutdown (non-Error)",{error:String(s)});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}Ss(),this.stopPromise=fs({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(t){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${t}`)}registerProcess(t,r,i){this.registry.register(t,r,i)}unregisterProcess(t){this.registry.unregister(t)}getRegistry(){return this.registry}},Kc=new Pr(Ne());function Fe(e={}){let t=e.pidFilePath??La;if(!(0,Rt.existsSync)(t))return"missing";let r=null;try{r=JSON.parse((0,Rt.readFileSync)(t,"utf-8"))}catch(s){return s instanceof Error?d.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:t},s):d.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:t,error:String(s)}),(0,Rt.rmSync)(t,{force:!0}),"invalid"}return Dr(r)&&r?((e.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,Rt.rmSync)(t,{force:!0}),"stale")}var ws=ot(require("path"),1),ys=require("os"),ft=require("fs"),_s=require("child_process");var eh=R.dataDir(),rh=R.workerPid(),ih=R.workerPort();function Es(e){return e?/(^|[\\/])node(\.exe)?$/i.test(e.trim()):!1}function Fa(e,t){let r=t==="win32"?`where ${e}`:`which ${e}`,i;try{i=(0,_s.execSync)(r,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(n){return n instanceof Error?d.debug("SYSTEM",`Binary lookup failed for ${e}`,{command:r},n):d.debug("SYSTEM",`Binary lookup failed for ${e}`,{command:r},new Error(String(n))),null}return i.split(/\r?\n/).map(n=>n.trim()).find(n=>n.length>0)||null}var Ir;function vs(e={}){let t=Object.keys(e).length===0;if(t&&Ir!==void 0)return Ir;let r=Ua(e);return t&&r!==null&&(Ir=r),r}function Ua(e){let t=e.platform??process.platform,r=e.execPath??process.execPath;if(Es(r))return r;let i=e.env??process.env,s=e.homeDirectory??(0,ys.homedir)(),n=e.pathExists??ft.existsSync,o=e.lookupInPath??Fa,a=t==="win32"?[i.NODE,ws.default.join(s,".nvm","current","bin","node.exe"),"node"]:[i.NODE,"/usr/local/bin/node","/opt/homebrew/bin/node","/usr/bin/node","node"];for(let l of a){let c=l?.trim();if(c&&(Es(c)&&n(c)||c.toLowerCase()==="node"))return c}return o("node",t)}var bs=ot(require("path"),1);var Ts=require("fs");var Wa=2500;async function $a(e,t,r="GET"){let i=await fetch(`http://127.0.0.1:${e}${t}`,{method:r,signal:AbortSignal.timeout(Wa)}),s="";try{s=await i.text()}catch{}return{ok:i.ok,statusCode:i.status,body:s}}function ja(){try{let e=bs.default.join(ce,"package.json");return JSON.parse((0,Ts.readFileSync)(e,"utf-8")).version}catch(e){if(e instanceof Error){let t=e.code;if(t==="ENOENT"||t==="EBUSY")return d.debug("SYSTEM","Could not read plugin version (shutdown race)",{code:t}),"unknown";throw e}throw e}}async function Ha(e){try{let t=await $a(e,"/api/version");return t.ok?JSON.parse(t.body).version:null}catch{return d.debug("SYSTEM","Could not fetch worker version",{}),null}}async function Ms(e){let t=ja(),r=await Ha(e);return!r||t==="unknown"?{matches:!0,pluginVersion:t,workerVersion:r}:{matches:t===r,pluginVersion:t,workerVersion:r}}var Ue=require("path"),Y=require("fs");var Ga=6e4;function ks(){return(0,Ue.join)(cr(),"spawn.lock")}function Rs(){let e=ks(),t=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return(0,Y.mkdirSync)((0,Ue.dirname)(e),{recursive:!0}),(0,Y.writeFileSync)(e,t,{flag:"wx"}),!0}catch(i){if(i?.code!=="EEXIST")return!0;if(r>0)return!1;let n;try{n=(0,Y.statSync)(e).mtimeMs}catch{continue}if(Date.now()-n<=Ga)return!1;let o;try{o=(0,Y.statSync)(e).mtimeMs}catch{continue}if(o!==n)return!1;try{(0,Y.unlinkSync)(e)}catch{return!1}}return!1}function Cs(){let e=ks();try{if(JSON.parse((0,Y.readFileSync)(e,"utf-8")).pid!==process.pid)return;(0,Y.unlinkSync)(e)}catch{}}function Fr(e,t,r){let i=process.env[e];if(i){let s=parseInt(i,10);if(Number.isFinite(s)&&s>=r.min&&s<=r.max)return s;d.warn("SYSTEM",`Invalid ${e}, using default`,{value:i,min:r.min,max:r.max})}return t}var Be=Fr("CLAUDE_MEM_HEALTH_TIMEOUT_MS",ut(z.HEALTH_CHECK),{min:500,max:3e5}),Ah=Fr("CLAUDE_MEM_API_TIMEOUT_MS",ut(z.API_REQUEST),{min:500,max:3e5}),Ps=Fr("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",ut(z.HOOK_READINESS_WAIT),{min:0,max:3e5}),Ba={min:500,max:3e5};async function Ur(e,t={},r){try{return await fetch(e,{...t,signal:AbortSignal.timeout(r)})}catch(i){throw i instanceof DOMException&&i.name==="TimeoutError"?new Error(`Request timed out after ${r}ms`):i}}var We=null,$e=null,je=null,He=null;function Ka(){return jt.default.join(it.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function za(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}function Ya(){try{let e=R.workerPid();if(!(0,H.existsSync)(e))return null;let t=JSON.parse((0,H.readFileSync)(e,"utf-8"));return typeof t.pid!="number"||typeof t.port!="number"||!za(t.pid)?null:t.port}catch{return null}}function Wr(){return je!==null||(je=it.loadFromFile(Ka())),je}function As(e,t){if(!e)return null;let r=parseInt(e,10);return Number.isFinite(r)&&r>=t.min&&r<=t.max?r:null}function Ja(e,t,r){let i=process.env[e];if(i!==void 0){let o=As(i,r);return o!==null?o:(d.warn("SYSTEM",`Invalid ${e}, using default`,{value:i,min:r.min,max:r.max}),t)}let s=Wr()[e],n=As(s,r);return n!==null?n:(d.warn("SYSTEM",`Invalid ${e} in settings.json, using default`,{value:s,min:r.min,max:r.max}),t)}function Xa(){if(We!==null)return We;let e=Wr();return We=parseInt(e.CLAUDE_MEM_WORKER_PORT,10),We}function Is(){let e=Ya();return e!==null?e:Xa()}function Va(){return $e!==null||($e=Wr().CLAUDE_MEM_WORKER_HOST),$e}function qa(){return He!==null||(He=Ja("CLAUDE_MEM_API_TIMEOUT_MS",ut(z.API_REQUEST),Ba)),He}function Qa(e){return`http://${Va()}:${Is()}${e}`}function mt(e,t={}){let r=t.method??"GET",i=t.timeoutMs??qa(),s=Qa(e),n={method:r};return t.headers&&(n.headers=t.headers),t.body&&(n.body=t.body),i>0?Ur(s,n,i):fetch(s,n)}async function Za(){return(await mt("/api/health",{timeoutMs:Be})).ok}async function Os(){return(await mt("/api/readiness",{timeoutMs:Be})).ok}function tl(){let e=[jt.default.join(ce,"plugin","scripts","worker-service.cjs"),jt.default.join(process.cwd(),"plugin","scripts","worker-service.cjs")];for(let t of e)if((0,H.existsSync)(t))return t;return null}async function el(e){let t=e.backoffMs;for(let r=1;r<=e.attempts;r++){if(await Ls())return!0;r<e.attempts&&(await new Promise(i=>setTimeout(i,t)),t*=2)}return!1}async function xr(e=Ps){if(e<=0)try{return await Os()}catch{return!1}let t=Date.now();for(;Date.now()-t<e;){try{if(await Os())return!0}catch(i){d.debug("SYSTEM","Worker readiness check threw",{error:i instanceof Error?i.message:String(i)})}let r=e-(Date.now()-t);if(r<=0)break;await new Promise(i=>setTimeout(i,Math.min(250,r)))}return!1}async function xs(){try{let t=await(await mt("/api/health",{timeoutMs:Be})).json();return typeof t.version=="string"?t.version:null}catch{return null}}async function rl(e,t=Ps){let r=Date.now();for(;Date.now()-r<t;){if(await xs()===e)return!0;let s=t-(Date.now()-r);if(s<=0)break;await new Promise(n=>setTimeout(n,Math.min(500,s)))}return!1}async function Lr(e){let t=await xs();t!==null&&t!==e&&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:e,workerVersion:t})}async function Ls(){let e;try{e=await Za()}catch(r){return d.debug("SYSTEM","Worker health check threw",{error:r instanceof Error?r.message:String(r)}),!1}if(!e)return!1;let t=Fe({logAlive:!1});return t==="missing"||t==="alive"}async function Ke(){let e=null;if(await Ls()){let{matches:n,pluginVersion:o,workerVersion:a}=await Ms(Is());if(o!=="unknown"&&(e=o),n)return await xr()?(e!==null&&await Lr(e),!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 mt("/api/admin/restart",{method:"POST",timeoutMs:Be}),await rl(o))return await xr()?(e!==null&&await Lr(e),!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 t=vs(),r=tl();if(!t)return d.warn("SYSTEM","Cannot lazy-spawn worker: Node 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 i=Rs();try{if(i){d.info("SYSTEM","Worker not running \u2014 lazy-spawning",{runtimePath:t,scriptPath:r});try{De(t,[r,"--daemon"],{detached:!0,stdio:["ignore","ignore","ignore"]}).unref()}catch(o){return o instanceof Error?d.error("SYSTEM","Lazy-spawn of worker failed",{runtimePath:t,scriptPath:r},o):d.error("SYSTEM","Lazy-spawn of worker failed (non-Error)",{runtimePath:t,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 el({attempts:6,backoffMs:500}))return d.warn("SYSTEM",i?"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{i&&Cs()}return await xr()?(e!==null&&await Lr(e),!0):(d.warn("SYSTEM","Worker lazy-spawned but did not become ready before hook readiness timeout"),!1)}var Ge=null;async function il(){return Ge!==null||(Ge=await Ke()),Ge}var sl=3;function Ns(){return jt.default.join(T,"state")}function Fs(){return jt.default.join(Ns(),"hook-failures.json")}function Us(){try{let e=(0,H.readFileSync)(Fs(),"utf-8"),t=JSON.parse(e);return{consecutiveFailures:typeof t.consecutiveFailures=="number"&&Number.isFinite(t.consecutiveFailures)?Math.max(0,Math.floor(t.consecutiveFailures)):0,lastFailureAt:typeof t.lastFailureAt=="number"&&Number.isFinite(t.lastFailureAt)?t.lastFailureAt:0}}catch{return{consecutiveFailures:0,lastFailureAt:0}}}function Ws(e){let t=Ns(),r=Fs(),i=`${r}.tmp`;try{(0,H.existsSync)(t)||(0,H.mkdirSync)(t,{recursive:!0}),(0,H.writeFileSync)(i,JSON.stringify(e),"utf-8"),(0,H.renameSync)(i,r)}catch(s){d.debug("SYSTEM","Failed to persist hook-failure counter",{error:s instanceof Error?s.message:String(s)})}}function nl(){try{let t=dt().CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD,r=parseInt(t,10);if(Number.isFinite(r)&&r>=1)return r}catch{}return sl}async function ol(){let t={consecutiveFailures:Us().consecutiveFailures+1,lastFailureAt:Date.now()};Ws(t);let r=nl();return t.consecutiveFailures>=r&&Gt(`keepmind worker unreachable for ${t.consecutiveFailures} consecutive hooks \u2014 continuing without memory capture. Run \`keepmind doctor\` to diagnose.`),t.consecutiveFailures}function Ds(){Us().consecutiveFailures!==0&&Ws({consecutiveFailures:0,lastFailureAt:0})}var Nr=Symbol.for("claude-mem/worker-fallback");function ze(e){return typeof e=="object"&&e!==null&&e[Nr]===!0}async function Ye(e,t,r,i={}){if(!await il())return await ol(),{continue:!0,reason:"worker_unreachable",[Nr]:!0};let n={method:t};r!==void 0&&(n.headers={"Content-Type":"application/json"},n.body=JSON.stringify(r)),i.timeoutMs!==void 0&&(n.timeoutMs=i.timeoutMs);let o=await mt(e,n);if(!o.ok){let l=await o.text().catch(()=>"");if(Ds(),o.status===429||o.status>=500)return d.warn("SYSTEM",`Worker API ${t} ${e} 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}Ds();let a=await o.text();if(a.length!==0)try{return JSON.parse(a)}catch{return a}}var js=require("os"),Hs=ot(require("path"),1),Gs=require("child_process");var Xe=require("fs"),Je=ot(require("path"),1);var oe={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function $s(e){let t=Je.default.join(e,".git"),r;try{r=(0,Xe.statSync)(t)}catch(h){return h instanceof Error&&h.code!=="ENOENT"&&d.warn("GIT","Unexpected error checking .git",{error:h instanceof Error?h.message:String(h)}),oe}if(!r.isFile())return oe;let i;try{i=(0,Xe.readFileSync)(t,"utf-8").trim()}catch(h){return d.warn("GIT","Failed to read .git file",{error:h instanceof Error?h.message:String(h)}),oe}let s=i.match(/^gitdir:\s*(.+)$/);if(!s)return oe;let o=s[1].match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!o)return oe;let a=o[1],l=Je.default.basename(e),c=Je.default.basename(a);return{isWorktree:!0,worktreeName:l,parentRepoPath:a,parentProjectName:c}}function Bs(e){return e==="~"||e.startsWith("~/")?e.replace(/^~/,(0,js.homedir)()):e}function al(e){try{return(0,Gs.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function ll(e){if(!e||e.trim()==="")return d.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:e}),"unknown-project";let t=Bs(e),i=al(t)??t,s=Hs.default.basename(i);if(s===""){if(process.platform==="win32"){let o=e.match(/^([A-Z]):\\/i);if(o){let l=`drive-${o[1].toUpperCase()}`;return d.info("PROJECT_NAME","Drive root detected",{cwd:e,projectName:l}),l}}return d.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:e}),"unknown-project"}return s}function Ct(e){let t=ll(e);if(!e)return{primary:t,parent:null,isWorktree:!1,allProjects:[t]};let r=Bs(e),i=$s(r);if(i.isWorktree&&i.parentProjectName){let s=`${i.parentProjectName}/${t}`;return{primary:s,parent:i.parentProjectName,isWorktree:!0,allProjects:[i.parentProjectName,s]}}return{primary:t,parent:null,isWorktree:!1,allProjects:[t]}}var At=require("path");var Ks=require("os"),zs=require("path");function cl(e){let t=e.startsWith("~")?(0,Ks.homedir)()+e.slice(1):e;t=t.replace(/\\/g,"/");let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&");return r=r.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${r}$`)}function Ve(e,t){if(!t||!t.trim())return!1;let r=e.replace(/\\/g,"/"),i=(0,zs.basename)(r),s=t.split(",").map(n=>n.trim()).filter(Boolean);for(let n of s)try{let o=cl(n);if(o.test(r)||o.test(i))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 hl(e,t){let r=(0,At.normalize)(e),i=(0,At.normalize)(t);if(r===i)return!0;let s=(0,At.relative)(i,r);return s.length>0&&!s.startsWith("..")&&!(0,At.isAbsolute)(s)}function qe(e){if(process.env.CLAUDE_MEM_INTERNAL==="1")return!1;if(!e)return!0;if(hl(e,ue))return!1;let t=dt();return!Ve(e,t.CLAUDE_MEM_EXCLUDED_PROJECTS)}var Ys="claude";function ul(e){return e.trim().toLowerCase().replace(/\s+/g,"-")}function nt(e){if(!e)return Ys;let t=ul(e);return t?t==="transcript"||t.includes("codex")?"codex":t.includes("cursor")?"cursor":t.includes("claude")?"claude":t:Ys}var Vs=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],Js=new RegExp(`<(${Vs.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g");var Xs=100;function dl(e){let t=Object.fromEntries(Vs.map(s=>[s,0]));Js.lastIndex=0;let r=0,i=e.replace(Js,(s,n)=>(t[n]=(t[n]??0)+1,r+=1,""));return r>Xs&&d.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:r,maxAllowed:Xs,contentLength:e.length}),{stripped:i.trim(),counts:t}}function $r(e){return dl(e).stripped}var pl=["task-notification"],fl=new RegExp(`^\\s*<(${pl.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),ml=256*1024;function qs(e){return!e||e.length>ml?!1:fl.test(e)}var gl=ut(z.API_REQUEST),gt=class extends Error{kind;status;cause;constructor(t,r,i={}){super(r),this.name="ServerClientError",this.kind=t,this.status=i.status??null,this.cause=i.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)}},Qe=class{baseUrl;apiKey;timeoutMs;constructor(t){this.baseUrl=Sl(t.serverBaseUrl),this.apiKey=t.apiKey,this.timeoutMs=t.timeoutMs??gl}async startSession(t){let r=this.buildStartSessionPayload(t);return this.request("POST","/v1/sessions/start",r)}async recordEvent(t){let r=this.buildEventPayload(t),i=t.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",i,r)}async endSession(t){if(!t.sessionId)throw new gt("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(t.sessionId)}/end`,{})}async addObservation(t){return this.request("POST","/v1/memories",this.buildAddObservationPayload(t))}async searchObservations(t){return this.request("POST","/v1/search",this.buildSearchPayload(t))}async contextObservations(t){return this.request("POST","/v1/context",this.buildSearchPayload(t))}async getJobStatus(t){if(!t)throw new gt("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(t)}`)}buildAddObservationPayload(t){let r=t.content,i=t.kind??"manual",s=typeof t.metadata?.title=="string"?t.metadata.title:void 0;return{projectId:t.projectId,kind:i,type:i,narrative:r,...s?{title:s}:{},...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}}}buildSearchPayload(t){return{projectId:t.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:jr(t.platformSource)}:{}}}buildStartSessionPayload(t){return{projectId:t.projectId,...t.externalSessionId!==void 0?{externalSessionId:t.externalSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.agentId!==void 0?{agentId:t.agentId}:{},...t.agentType!==void 0?{agentType:t.agentType}:{},...t.platformSource!==void 0?{platformSource:jr(t.platformSource)}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}}}buildEventPayload(t){return{projectId:t.projectId,sourceType:t.sourceType,eventType:t.eventType,occurredAtEpoch:t.occurredAtEpoch,...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.memorySessionId!==void 0?{memorySessionId:t.memorySessionId}:{},...t.platformSource!==void 0?{platformSource:jr(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{}}}async request(t,r,i){if(!this.apiKey||!this.apiKey.trim())throw new gt("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let s=`${this.baseUrl}${r}`,n={method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};i!==void 0&&(n.body=JSON.stringify(i));let o;try{o=await Ur(s,n,this.timeoutMs)}catch(l){let c=l instanceof Error?l.message:String(l),h=/timed out|timeout/i.test(c);throw new gt(h?"timeout":"transport",`Server ${t} ${r} failed: ${c}`,{cause:l})}if(!o.ok){let l=await o.text().catch(()=>"");throw new gt("http_error",`Server ${t} ${r} returned ${o.status}: ${El(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 gt("invalid_response",`Server ${t} ${r} returned non-JSON response`,{cause:l})}}};function Qs(e){return e instanceof gt}function Sl(e){return e.replace(/\/+$/,"")}function jr(e){return typeof e=="string"?nt(e):null}function El(e,t){return e.length<=t?e:`${e.slice(0,t)}\u2026`}function wl(){let t=(dt().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return t==="server"||t==="server-beta"?"server":"worker"}function yl(){let e=dt(),t=(...o)=>{for(let a of o){let l=(a??"").trim();if(l.length>0)return l}return""},r=t(e.CLAUDE_MEM_SERVER_URL,e.CLAUDE_MEM_SERVER_BETA_URL),i=t(e.CLAUDE_MEM_SERVER_API_KEY,e.CLAUDE_MEM_SERVER_BETA_API_KEY),s=t(e.CLAUDE_MEM_SERVER_PROJECT_ID,e.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!r)return d.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!i)return d.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!s)return d.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let n={serverBaseUrl:r,apiKey:i};return{runtime:"server",client:new Qe(n),projectId:s,serverBaseUrl:r}}function Zs(){if(wl()!=="server")return{runtime:"worker"};let e=yl();return e||{runtime:"worker"}}function tn(e,t){d.warn("HOOK",`[server-fallback] reason=${e}`,t??{})}var _l={executeWithWorkerFallback:Ye,isWorkerFallback:ze,loadFromFileOnce:dt,resolveRuntimeContext:Zs,logServerFallback:tn,shouldTrackProject:qe},bt=_l;var en={async execute(e){let{sessionId:t,prompt:r}=e,i=e.cwd??process.cwd();if(!t)return d.warn("HOOK","session-init: No sessionId provided, skipping (Codex CLI or unknown platform)"),{continue:!0,suppressOutput:!0,exitCode:vt.SUCCESS};if(!bt.shouldTrackProject(i))return d.info("HOOK","Project excluded from tracking",{cwd:i}),{continue:!0,suppressOutput:!0};if(r&&qs(r))return d.debug("HOOK","session-init: skipping internal protocol payload",{preview:r.slice(0,80)}),{continue:!0,suppressOutput:!0};let s=!r||!r.trim()?"[media prompt]":r,n=Ct(i).primary,o=nt(e.platform),a=bt.loadFromFileOnce(),l=String(a.CLAUDE_MEM_SEMANTIC_INJECT).toLowerCase()==="true",c=bt.resolveRuntimeContext();if(c.runtime==="server")try{return await c.client.startSession({projectId:c.projectId,externalSessionId:t,contentSessionId:t,agentId:e.agentId??null,agentType:e.agentType??null,platformSource:o,metadata:{project:n,prompt:s}}),d.info("HOOK","session-init: server session started",{contentSessionId:t,project:n}),{continue:!0,suppressOutput:!0}}catch(m){if(Qs(m)&&m.isFallbackEligible())bt.logServerFallback(m.kind,{status:m.status,message:m.message,route:"/v1/sessions/start"});else return d.error("HOOK","Server session-start failed (non-recoverable)",{error:m instanceof Error?m.message:String(m)}),{continue:!0,suppressOutput:!0,exitCode:vt.SUCCESS}}d.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:t,project:n});let h=await bt.executeWithWorkerFallback("/api/sessions/init","POST",{contentSessionId:t,project:n,prompt:s,platformSource:o});if(bt.isWorkerFallback(h))return{continue:!0,suppressOutput:!0,exitCode:vt.SUCCESS};if(typeof h?.sessionDbId!="number")return d.failure("HOOK","Session initialization returned malformed response",{contentSessionId:t,project:n}),{continue:!0,suppressOutput:!0,exitCode:vt.SUCCESS};let u=h.sessionDbId,p=h.promptNumber;if(d.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:u,promptNumber:p,skipped:h.skipped,contextInjected:h.contextInjected}),d.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${t} | prompt#=${p} | sessionDbId=${u}`),h.skipped&&h.reason==="private")return d.info("HOOK",`INIT_COMPLETE | sessionDbId=${u} | promptNumber=${p} | skipped=true | reason=private`,{sessionId:u}),{continue:!0,suppressOutput:!0};let f="";if(l&&s&&s.length>=20&&s!=="[media prompt]"){let m=a.CLAUDE_MEM_SEMANTIC_INJECT_LIMIT||"5",g=await bt.executeWithWorkerFallback("/api/context/semantic","POST",{q:s,project:n,limit:m,platformSource:o});!bt.isWorkerFallback(g)&&g?.context&&(d.debug("HOOK",`Semantic injection: ${g.count} observations for prompt`,{sessionId:u,count:g.count}),f=g.context)}return d.info("HOOK",`INIT_COMPLETE | sessionDbId=${u} | promptNumber=${p} | project=${n}`,{sessionId:u}),f?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:f}}:{continue:!0,suppressOutput:!0}}};var rn={async execute(e){let{sessionId:t,cwd:r,filePath:i,edits:s}=e,n=nt(e.platform);if(!i)throw new Error("fileEditHandler requires filePath");if(d.dataIn("HOOK",`FileEdit: ${i}`,{editCount:s?.length??0}),!r)throw new Error(`Missing cwd in FileEdit hook input for session ${t}, file ${i}`);if(!qe(r))return d.debug("HOOK","Project excluded from tracking, skipping file edit observation",{cwd:r,filePath:i}),{continue:!0,suppressOutput:!0,exitCode:vt.SUCCESS};let o=await Ye("/api/sessions/observations","POST",{contentSessionId:t,platformSource:n,tool_name:"write_file",tool_input:{filePath:i,edits:s},tool_response:{success:!0},cwd:r});return ze(o)?{continue:!0,suppressOutput:!0,exitCode:vt.SUCCESS}:(d.debug("HOOK","File edit observation sent successfully",{filePath:i}),{continue:!0,suppressOutput:!0})}};var V=require("fs"),Ze=require("path");var Ou=R.settings();function sn(e,t){let r="<claude-mem-context>",i="</claude-mem-context>";if(!e)return`${r}
13
+ `,"utf-8"),a;try{a=(0,b.statSync)(r).mode&511}catch{}let l;try{l=a!==void 0?(0,b.openSync)(n,"w",a):(0,b.openSync)(n,"w");let c=0;for(;c<o.length;){let h=(0,b.writeSync)(l,o,c,o.length-c);if(h===0)throw new Error(`writeSync stalled at ${c}/${o.length} bytes`);c+=h}if((0,b.fsyncSync)(l),(0,b.closeSync)(l),l=void 0,(0,b.renameSync)(n,r),!wa){let h;try{h=(0,b.openSync)(i,"r"),(0,b.fsyncSync)(h)}catch{}finally{if(h!==void 0)try{(0,b.closeSync)(h)}catch{}}}}catch(c){if(l!==void 0)try{(0,b.closeSync)(l)}catch{}try{(0,b.unlinkSync)(n)}catch{}throw c}}var it=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(ut(z.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,ne.join)((0,Mr.homedir)(),".keepmind"),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:"5",CLAUDE_MEM_OBSERVATION_BATCH_MAX:"3",CLAUDE_MEM_MAX_CONTEXT_MESSAGES:"40",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_UPDATE_CHECK_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,ne.join)((0,Mr.homedir)(),".keepmind","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_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_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",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 envOverride(t){let r=t.replace(/^CLAUDE_MEM_/,"KEEPMIND_");return process.env[r]??process.env[t]}static get(t){return this.envOverride(t)??this.DEFAULTS[t]}static getInt(t){let r=this.get(t);return parseInt(r,10)}static getBool(t){let r=this.get(t);return r==="true"||r===!0}static applyEnvOverrides(t){let r={...t};for(let i of Object.keys(this.DEFAULTS)){let s=this.envOverride(i);s!==void 0&&(r[i]=s)}return r}static loadFromFile(t,r=!0){try{if(!(0,rt.existsSync)(t)){let a=this.getAllDefaults();try{let l=(0,ne.dirname)(t);(0,rt.existsSync)(l)||(0,rt.mkdirSync)(l,{recursive:!0}),Pe(t,a),console.warn("[SETTINGS] Created settings file with defaults:",t)}catch(l){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",t,l instanceof Error?l.message:String(l))}return r?this.applyEnvOverrides(a):a}let i=(0,rt.readFileSync)(t,"utf-8"),s=JSON.parse(i.replace(/^\uFEFF/,"")),n=s;if(s.env&&typeof s.env=="object"){n=s.env;try{Pe(t,n),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",t)}catch(a){console.warn("[SETTINGS] Failed to auto-migrate settings file:",t,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(i){console.warn("[SETTINGS] Failed to load settings, using defaults:",t,i instanceof Error?i.message:String(i));let s=this.getAllDefaults();try{if((0,rt.existsSync)(t)){let n=`${t}.corrupt-${Date.now()}`;(0,rt.renameSync)(t,n),console.warn("[SETTINGS] Backed up corrupt settings file to:",n)}Pe(t,s),console.warn("[SETTINGS] Recovered settings file with defaults:",t)}catch(n){console.warn("[SETTINGS] Failed to recover corrupt settings file:",t,n instanceof Error?n.message:String(n))}return r?this.applyEnvOverrides(s):s}}};var Ie=null;function dt(){return Ie!==null||(Ie=it.loadFromFile(he)),Ie}var Rt=require("fs");var Or=require("child_process");var st=require("fs"),Cr=ot(require("path"),1);var _a=["CLAUDECODE_","CLAUDE_CODE_"],va=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID","HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy"]),ba=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 xe(e=process.env){let t={};for(let[r,i]of Object.entries(e))if(i!==void 0){if(ba.has(r)){t[r]=i;continue}va.has(r)||_a.some(s=>r.startsWith(s))||(t[r]=i)}return t}var Ta=5e3,Ma=1e3,ka=R.supervisorRegistry();function pt(e){if(!Number.isInteger(e)||e<0||e===0)return!1;try{return process.kill(e,0),!0}catch(t){if(t instanceof Error){let r=t.code;return r==="EPERM"?!0:(d.debug("SYSTEM","PID check failed",{pid:e,code:r}),!1)}return d.warn("SYSTEM","PID check threw non-Error",{pid:e,error:String(t)}),!1}}async function Le(e,t){let r=Date.now()+t;for(;Date.now()<r;){if(e.every(i=>!pt(i.pid)))return;await new Promise(i=>setTimeout(i,100))}}var Ra=5e3,cs=new Map;function Ca(e){let t=cs.get(e);if(t&&Date.now()-t.capturedAtMs<Ra)return t.token;let r=null;try{let i=(0,Or.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${e}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...xe(process.env),LC_ALL:"C",LANG:"C"}});if(i.status===0){let s=i.stdout.trim();r=s.length>0?s:null}}catch(i){d.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:e,error:i instanceof Error?i.message:String(i)}),r=null}return cs.set(e,{token:r,capturedAtMs:Date.now()}),r}function hs(e){if(!Number.isInteger(e)||e<=0)return null;if(process.platform==="linux")try{let t=(0,st.readFileSync)(`/proc/${e}/stat`,"utf-8"),r=t.lastIndexOf(") ");if(r<0)return null;let s=t.slice(r+2).split(" ")[19];return s&&/^\d+$/.test(s)?s:null}catch(t){return d.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:e,error:t instanceof Error?t.message:String(t)}),null}if(process.platform==="win32")return Ca(e);try{let t=(0,Or.spawnSync)("ps",["-p",String(e),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...xe(process.env),LC_ALL:"C",LANG:"C"}});if(t.status!==0)return null;let r=t.stdout.trim();return r.length>0?r:null}catch(t){return d.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:e,error:t instanceof Error?t.message:String(t)}),null}}function Dr(e){if(!e||!pt(e.pid))return!1;if(!e.startToken)return!0;let t=hs(e.pid);if(t===null)return!0;let r=t===e.startToken;return r||d.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:e.pid,stored:e.startToken,current:t}),r}var Ar=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(t=ka){this.registryPath=t}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,st.mkdirSync)(Cr.default.dirname(this.registryPath),{recursive:!0}),!(0,st.existsSync)(this.registryPath)){this.persist();return}try{let i=JSON.parse((0,st.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[s,n]of Object.entries(i))this.entries.set(s,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 t=this.pruneDeadEntries();t>0&&d.info("SYSTEM","Removed dead processes from supervisor registry",{removed:t}),this.persist()}register(t,r,i){this.initialize(),this.entries.set(t,r),i&&this.runtimeProcesses.set(t,i),this.persist()}unregister(t){this.initialize();let r=this.entries.get(t);this.entries.delete(t),this.runtimeProcesses.delete(t),this.persist(),r?.type==="sdk"&&Rr()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([t,r])=>({id:t,...r})).sort((t,r)=>{let i=Date.parse(t.startedAt),s=Date.parse(r.startedAt);return(Number.isNaN(i)?0:i)-(Number.isNaN(s)?0:s)})}getBySession(t){let r=String(t);return this.getAll().filter(i=>i.sessionId!==void 0&&String(i.sessionId)===r)}getRuntimeProcess(t){return this.runtimeProcesses.get(t)}getByPid(t){return this.getAll().filter(r=>r.pid===t)}pruneDeadEntries(){this.initialize();let t=0,r=0;for(let[i,s]of this.entries)pt(s.pid)||(this.entries.delete(i),this.runtimeProcesses.delete(i),t+=1,s.type==="sdk"&&(r+=1));t>0&&this.persist();for(let i=0;i<r;i+=1)Rr();return t}async reapSession(t){this.initialize();let r=this.getBySession(t);if(r.length===0)return 0;let i=typeof t=="number"?t:Number(t)||void 0;d.info("SYSTEM",`Reaping ${r.length} process(es) for session ${t}`,{sessionId:i,pids:r.map(o=>o.pid)});let s=r.filter(o=>pt(o.pid));for(let o of s)try{typeof o.pgid=="number"&&process.platform!=="win32"?process.kill(-o.pgid,"SIGTERM"):process.kill(o.pid,"SIGTERM")}catch(a){a instanceof Error?a.code!=="ESRCH"&&d.debug("SYSTEM",`Failed to SIGTERM session process PID ${o.pid}`,{pid:o.pid,pgid:o.pgid},a):d.warn("SYSTEM",`Failed to SIGTERM session process PID ${o.pid} (non-Error)`,{pid:o.pid,pgid:o.pgid,error:String(a)})}await Le(s,Ta);let n=s.filter(o=>pt(o.pid));for(let o of n){d.warn("SYSTEM",`Session process PID ${o.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:o.pid,pgid:o.pgid,sessionId:i});try{typeof o.pgid=="number"&&process.platform!=="win32"?process.kill(-o.pgid,"SIGKILL"):process.kill(o.pid,"SIGKILL")}catch(a){a instanceof Error?a.code!=="ESRCH"&&d.debug("SYSTEM",`Failed to SIGKILL session process PID ${o.pid}`,{pid:o.pid,pgid:o.pgid},a):d.warn("SYSTEM",`Failed to SIGKILL session process PID ${o.pid} (non-Error)`,{pid:o.pid,pgid:o.pgid,error:String(a)})}}if(n.length>0){let o=Date.now()+Ma;for(;Date.now()<o&&n.filter(l=>pt(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let o of r)this.entries.delete(o.id),this.runtimeProcesses.delete(o.id);this.persist();for(let o of r)o.type==="sdk"&&Rr();return d.info("SYSTEM",`Reaped ${r.length} process(es) for session ${t}`,{sessionId:i,reaped:r.length}),r.length}persist(){let t={processes:Object.fromEntries(this.entries.entries())};(0,st.mkdirSync)(Cr.default.dirname(this.registryPath),{recursive:!0}),(0,st.writeFileSync)(this.registryPath,JSON.stringify(t,null,2))}},kr=null;function Ne(){return kr||(kr=new Ar),kr}var Aa=[];function Rr(){let e=Aa.shift();e&&e()}var ds=require("child_process"),Wt=require("fs"),ps=require("util");var Oa=(0,ps.promisify)(ds.execFile),Da=R.workerPid();async function fs(e){let t=e.currentPid??process.pid,r=e.pidFilePath??Da,i=e.registry.getAll(),s=[...i].filter(o=>o.pid!==t).sort((o,a)=>Date.parse(a.startedAt)-Date.parse(o.startedAt));for(let o of s){if(!pt(o.pid)){e.registry.unregister(o.id);continue}try{await us(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 Le(s,5e3);let n=s.filter(o=>pt(o.pid));for(let o of n)try{await us(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 Le(n,1e3);for(let o of s)e.registry.unregister(o.id);for(let o of i.filter(a=>a.pid===t))e.registry.unregister(o.id);Pa(r,t),e.registry.pruneDeadEntries()}function Pa(e,t){if(!(0,Wt.existsSync)(e))return;let r=null;try{let i=JSON.parse((0,Wt.readFileSync)(e,"utf-8"));r=typeof i.pid=="number"?i.pid:null}catch(i){d.debug("SYSTEM","PID file unreadable during shutdown \u2014 leaving it (cannot prove ownership)",{pidFilePath:e,error:i instanceof Error?i.message:String(i)});return}if(r!==t){d.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:e,recordedPid:r,currentPid:t});return}try{(0,Wt.rmSync)(e,{force:!0})}catch(i){i instanceof Error?d.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:e},i):d.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:e,error:String(i)})}}async function us(e,t){let{pid:r,pgid:i}=e;if(process.platform!=="win32"){if(typeof i=="number")try{process.kill(-i,t);return}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}try{process.kill(r,t)}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}return}if(t==="SIGTERM"){try{process.kill(r,t)}catch(o){if(o instanceof Error&&o.code==="ESRCH")return;throw o}return}let s=await Ia();if(s){await new Promise((o,a)=>{s(r,t,l=>{if(!l){o();return}if(l.code==="ESRCH"){o();return}a(l)})});return}let n=["/PID",String(r),"/T"];t==="SIGKILL"&&n.push("/F"),await Oa("taskkill",n,{timeout:z.POWERSHELL_COMMAND,windowsHide:!0})}async function Ia(){let e="tree-kill";try{let t=await import(e);return t.default??t}catch(t){return d.debug("SYSTEM","tree-kill module not available, using fallback",{},t instanceof Error?t:void 0),null}}var ms=3e4,$t=null;function xa(){let t=Ne().pruneDeadEntries();t>0&&d.info("SYSTEM",`Health check: pruned ${t} dead process(es) from registry`)}function gs(){$t===null&&($t=setInterval(xa,ms),$t.unref(),d.debug("SYSTEM","Health checker started",{intervalMs:ms}))}function Ss(){$t!==null&&(clearInterval($t),$t=null,d.debug("SYSTEM","Health checker stopped"))}var La=R.workerPid(),Pr=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(t){this.registry=t}async start(){if(this.started)return;if(this.registry.initialize(),Fe({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,gs()}configureSignalHandlers(t){if(this.shutdownHandler=t,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async i=>{if(this.shutdownInitiated){d.warn("SYSTEM",`Received ${i} but shutdown already in progress`);return}this.shutdownInitiated=!0,d.info("SYSTEM",`Received ${i}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(s){s instanceof Error?d.error("SYSTEM","Error during shutdown",{},s):d.error("SYSTEM","Error during shutdown (non-Error)",{error:String(s)});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}Ss(),this.stopPromise=fs({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(t){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${t}`)}registerProcess(t,r,i){this.registry.register(t,r,i)}unregisterProcess(t){this.registry.unregister(t)}getRegistry(){return this.registry}},Kc=new Pr(Ne());function Fe(e={}){let t=e.pidFilePath??La;if(!(0,Rt.existsSync)(t))return"missing";let r=null;try{r=JSON.parse((0,Rt.readFileSync)(t,"utf-8"))}catch(s){return s instanceof Error?d.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:t},s):d.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:t,error:String(s)}),(0,Rt.rmSync)(t,{force:!0}),"invalid"}return Dr(r)&&r?((e.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,Rt.rmSync)(t,{force:!0}),"stale")}var ws=ot(require("path"),1),ys=require("os"),ft=require("fs"),_s=require("child_process");var eh=R.dataDir(),rh=R.workerPid(),ih=R.workerPort();function Es(e){return e?/(^|[\\/])node(\.exe)?$/i.test(e.trim()):!1}function Fa(e,t){let r=t==="win32"?`where ${e}`:`which ${e}`,i;try{i=(0,_s.execSync)(r,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(n){return n instanceof Error?d.debug("SYSTEM",`Binary lookup failed for ${e}`,{command:r},n):d.debug("SYSTEM",`Binary lookup failed for ${e}`,{command:r},new Error(String(n))),null}return i.split(/\r?\n/).map(n=>n.trim()).find(n=>n.length>0)||null}var Ir;function vs(e={}){let t=Object.keys(e).length===0;if(t&&Ir!==void 0)return Ir;let r=Ua(e);return t&&r!==null&&(Ir=r),r}function Ua(e){let t=e.platform??process.platform,r=e.execPath??process.execPath;if(Es(r))return r;let i=e.env??process.env,s=e.homeDirectory??(0,ys.homedir)(),n=e.pathExists??ft.existsSync,o=e.lookupInPath??Fa,a=t==="win32"?[i.NODE,ws.default.join(s,".nvm","current","bin","node.exe"),"node"]:[i.NODE,"/usr/local/bin/node","/opt/homebrew/bin/node","/usr/bin/node","node"];for(let l of a){let c=l?.trim();if(c&&(Es(c)&&n(c)||c.toLowerCase()==="node"))return c}return o("node",t)}var bs=ot(require("path"),1);var Ts=require("fs");var Wa=2500;async function $a(e,t,r="GET"){let i=await fetch(`http://127.0.0.1:${e}${t}`,{method:r,signal:AbortSignal.timeout(Wa)}),s="";try{s=await i.text()}catch{}return{ok:i.ok,statusCode:i.status,body:s}}function ja(){try{let e=bs.default.join(ce,"package.json");return JSON.parse((0,Ts.readFileSync)(e,"utf-8")).version}catch(e){if(e instanceof Error){let t=e.code;if(t==="ENOENT"||t==="EBUSY")return d.debug("SYSTEM","Could not read plugin version (shutdown race)",{code:t}),"unknown";throw e}throw e}}async function Ha(e){try{let t=await $a(e,"/api/version");return t.ok?JSON.parse(t.body).version:null}catch{return d.debug("SYSTEM","Could not fetch worker version",{}),null}}async function Ms(e){let t=ja(),r=await Ha(e);return!r||t==="unknown"?{matches:!0,pluginVersion:t,workerVersion:r}:{matches:t===r,pluginVersion:t,workerVersion:r}}var Ue=require("path"),Y=require("fs");var Ga=6e4;function ks(){return(0,Ue.join)(cr(),"spawn.lock")}function Rs(){let e=ks(),t=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return(0,Y.mkdirSync)((0,Ue.dirname)(e),{recursive:!0}),(0,Y.writeFileSync)(e,t,{flag:"wx"}),!0}catch(i){if(i?.code!=="EEXIST")return!0;if(r>0)return!1;let n;try{n=(0,Y.statSync)(e).mtimeMs}catch{continue}if(Date.now()-n<=Ga)return!1;let o;try{o=(0,Y.statSync)(e).mtimeMs}catch{continue}if(o!==n)return!1;try{(0,Y.unlinkSync)(e)}catch{return!1}}return!1}function Cs(){let e=ks();try{if(JSON.parse((0,Y.readFileSync)(e,"utf-8")).pid!==process.pid)return;(0,Y.unlinkSync)(e)}catch{}}function Fr(e,t,r){let i=process.env[e];if(i){let s=parseInt(i,10);if(Number.isFinite(s)&&s>=r.min&&s<=r.max)return s;d.warn("SYSTEM",`Invalid ${e}, using default`,{value:i,min:r.min,max:r.max})}return t}var Be=Fr("CLAUDE_MEM_HEALTH_TIMEOUT_MS",ut(z.HEALTH_CHECK),{min:500,max:3e5}),Ah=Fr("CLAUDE_MEM_API_TIMEOUT_MS",ut(z.API_REQUEST),{min:500,max:3e5}),Ps=Fr("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",ut(z.HOOK_READINESS_WAIT),{min:0,max:3e5}),Ba={min:500,max:3e5};async function Ur(e,t={},r){try{return await fetch(e,{...t,signal:AbortSignal.timeout(r)})}catch(i){throw i instanceof DOMException&&i.name==="TimeoutError"?new Error(`Request timed out after ${r}ms`):i}}var We=null,$e=null,je=null,He=null;function Ka(){return jt.default.join(it.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function za(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}function Ya(){try{let e=R.workerPid();if(!(0,H.existsSync)(e))return null;let t=JSON.parse((0,H.readFileSync)(e,"utf-8"));return typeof t.pid!="number"||typeof t.port!="number"||!za(t.pid)?null:t.port}catch{return null}}function Wr(){return je!==null||(je=it.loadFromFile(Ka())),je}function As(e,t){if(!e)return null;let r=parseInt(e,10);return Number.isFinite(r)&&r>=t.min&&r<=t.max?r:null}function Ja(e,t,r){let i=process.env[e];if(i!==void 0){let o=As(i,r);return o!==null?o:(d.warn("SYSTEM",`Invalid ${e}, using default`,{value:i,min:r.min,max:r.max}),t)}let s=Wr()[e],n=As(s,r);return n!==null?n:(d.warn("SYSTEM",`Invalid ${e} in settings.json, using default`,{value:s,min:r.min,max:r.max}),t)}function Xa(){if(We!==null)return We;let e=Wr();return We=parseInt(e.CLAUDE_MEM_WORKER_PORT,10),We}function Is(){let e=Ya();return e!==null?e:Xa()}function Va(){return $e!==null||($e=Wr().CLAUDE_MEM_WORKER_HOST),$e}function qa(){return He!==null||(He=Ja("CLAUDE_MEM_API_TIMEOUT_MS",ut(z.API_REQUEST),Ba)),He}function Qa(e){return`http://${Va()}:${Is()}${e}`}function mt(e,t={}){let r=t.method??"GET",i=t.timeoutMs??qa(),s=Qa(e),n={method:r};return t.headers&&(n.headers=t.headers),t.body&&(n.body=t.body),i>0?Ur(s,n,i):fetch(s,n)}async function Za(){return(await mt("/api/health",{timeoutMs:Be})).ok}async function Os(){return(await mt("/api/readiness",{timeoutMs:Be})).ok}function tl(){let e=[jt.default.join(ce,"plugin","scripts","worker-service.cjs"),jt.default.join(process.cwd(),"plugin","scripts","worker-service.cjs")];for(let t of e)if((0,H.existsSync)(t))return t;return null}async function el(e){let t=e.backoffMs;for(let r=1;r<=e.attempts;r++){if(await Ls())return!0;r<e.attempts&&(await new Promise(i=>setTimeout(i,t)),t*=2)}return!1}async function xr(e=Ps){if(e<=0)try{return await Os()}catch{return!1}let t=Date.now();for(;Date.now()-t<e;){try{if(await Os())return!0}catch(i){d.debug("SYSTEM","Worker readiness check threw",{error:i instanceof Error?i.message:String(i)})}let r=e-(Date.now()-t);if(r<=0)break;await new Promise(i=>setTimeout(i,Math.min(250,r)))}return!1}async function xs(){try{let t=await(await mt("/api/health",{timeoutMs:Be})).json();return typeof t.version=="string"?t.version:null}catch{return null}}async function rl(e,t=Ps){let r=Date.now();for(;Date.now()-r<t;){if(await xs()===e)return!0;let s=t-(Date.now()-r);if(s<=0)break;await new Promise(n=>setTimeout(n,Math.min(500,s)))}return!1}async function Lr(e){let t=await xs();t!==null&&t!==e&&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:e,workerVersion:t})}async function Ls(){let e;try{e=await Za()}catch(r){return d.debug("SYSTEM","Worker health check threw",{error:r instanceof Error?r.message:String(r)}),!1}if(!e)return!1;let t=Fe({logAlive:!1});return t==="missing"||t==="alive"}async function Ke(){let e=null;if(await Ls()){let{matches:n,pluginVersion:o,workerVersion:a}=await Ms(Is());if(o!=="unknown"&&(e=o),n)return await xr()?(e!==null&&await Lr(e),!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 mt("/api/admin/restart",{method:"POST",timeoutMs:Be}),await rl(o))return await xr()?(e!==null&&await Lr(e),!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 t=vs(),r=tl();if(!t)return d.warn("SYSTEM","Cannot lazy-spawn worker: Node 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 i=Rs();try{if(i){d.info("SYSTEM","Worker not running \u2014 lazy-spawning",{runtimePath:t,scriptPath:r});try{De(t,[r,"--daemon"],{detached:!0,stdio:["ignore","ignore","ignore"]}).unref()}catch(o){return o instanceof Error?d.error("SYSTEM","Lazy-spawn of worker failed",{runtimePath:t,scriptPath:r},o):d.error("SYSTEM","Lazy-spawn of worker failed (non-Error)",{runtimePath:t,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 el({attempts:6,backoffMs:500}))return d.warn("SYSTEM",i?"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{i&&Cs()}return await xr()?(e!==null&&await Lr(e),!0):(d.warn("SYSTEM","Worker lazy-spawned but did not become ready before hook readiness timeout"),!1)}var Ge=null;async function il(){return Ge!==null||(Ge=await Ke()),Ge}var sl=3;function Ns(){return jt.default.join(T,"state")}function Fs(){return jt.default.join(Ns(),"hook-failures.json")}function Us(){try{let e=(0,H.readFileSync)(Fs(),"utf-8"),t=JSON.parse(e);return{consecutiveFailures:typeof t.consecutiveFailures=="number"&&Number.isFinite(t.consecutiveFailures)?Math.max(0,Math.floor(t.consecutiveFailures)):0,lastFailureAt:typeof t.lastFailureAt=="number"&&Number.isFinite(t.lastFailureAt)?t.lastFailureAt:0}}catch{return{consecutiveFailures:0,lastFailureAt:0}}}function Ws(e){let t=Ns(),r=Fs(),i=`${r}.tmp`;try{(0,H.existsSync)(t)||(0,H.mkdirSync)(t,{recursive:!0}),(0,H.writeFileSync)(i,JSON.stringify(e),"utf-8"),(0,H.renameSync)(i,r)}catch(s){d.debug("SYSTEM","Failed to persist hook-failure counter",{error:s instanceof Error?s.message:String(s)})}}function nl(){try{let t=dt().CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD,r=parseInt(t,10);if(Number.isFinite(r)&&r>=1)return r}catch{}return sl}async function ol(){let t={consecutiveFailures:Us().consecutiveFailures+1,lastFailureAt:Date.now()};Ws(t);let r=nl();return t.consecutiveFailures>=r&&Gt(`keepmind worker unreachable for ${t.consecutiveFailures} consecutive hooks \u2014 continuing without memory capture. Run \`keepmind doctor\` to diagnose.`),t.consecutiveFailures}function Ds(){Us().consecutiveFailures!==0&&Ws({consecutiveFailures:0,lastFailureAt:0})}var Nr=Symbol.for("claude-mem/worker-fallback");function ze(e){return typeof e=="object"&&e!==null&&e[Nr]===!0}async function Ye(e,t,r,i={}){if(!await il())return await ol(),{continue:!0,reason:"worker_unreachable",[Nr]:!0};let n={method:t};r!==void 0&&(n.headers={"Content-Type":"application/json"},n.body=JSON.stringify(r)),i.timeoutMs!==void 0&&(n.timeoutMs=i.timeoutMs);let o=await mt(e,n);if(!o.ok){let l=await o.text().catch(()=>"");if(Ds(),o.status===429||o.status>=500)return d.warn("SYSTEM",`Worker API ${t} ${e} 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}Ds();let a=await o.text();if(a.length!==0)try{return JSON.parse(a)}catch{return a}}var js=require("os"),Hs=ot(require("path"),1),Gs=require("child_process");var Xe=require("fs"),Je=ot(require("path"),1);var oe={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function $s(e){let t=Je.default.join(e,".git"),r;try{r=(0,Xe.statSync)(t)}catch(h){return h instanceof Error&&h.code!=="ENOENT"&&d.warn("GIT","Unexpected error checking .git",{error:h instanceof Error?h.message:String(h)}),oe}if(!r.isFile())return oe;let i;try{i=(0,Xe.readFileSync)(t,"utf-8").trim()}catch(h){return d.warn("GIT","Failed to read .git file",{error:h instanceof Error?h.message:String(h)}),oe}let s=i.match(/^gitdir:\s*(.+)$/);if(!s)return oe;let o=s[1].match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!o)return oe;let a=o[1],l=Je.default.basename(e),c=Je.default.basename(a);return{isWorktree:!0,worktreeName:l,parentRepoPath:a,parentProjectName:c}}function Bs(e){return e==="~"||e.startsWith("~/")?e.replace(/^~/,(0,js.homedir)()):e}function al(e){try{return(0,Gs.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim()||null}catch{return null}}function ll(e){if(!e||e.trim()==="")return d.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:e}),"unknown-project";let t=Bs(e),i=al(t)??t,s=Hs.default.basename(i);if(s===""){if(process.platform==="win32"){let o=e.match(/^([A-Z]):\\/i);if(o){let l=`drive-${o[1].toUpperCase()}`;return d.info("PROJECT_NAME","Drive root detected",{cwd:e,projectName:l}),l}}return d.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:e}),"unknown-project"}return s}function Ct(e){let t=ll(e);if(!e)return{primary:t,parent:null,isWorktree:!1,allProjects:[t]};let r=Bs(e),i=$s(r);if(i.isWorktree&&i.parentProjectName){let s=`${i.parentProjectName}/${t}`;return{primary:s,parent:i.parentProjectName,isWorktree:!0,allProjects:[i.parentProjectName,s]}}return{primary:t,parent:null,isWorktree:!1,allProjects:[t]}}var At=require("path");var Ks=require("os"),zs=require("path");function cl(e){let t=e.startsWith("~")?(0,Ks.homedir)()+e.slice(1):e;t=t.replace(/\\/g,"/");let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&");return r=r.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${r}$`)}function Ve(e,t){if(!t||!t.trim())return!1;let r=e.replace(/\\/g,"/"),i=(0,zs.basename)(r),s=t.split(",").map(n=>n.trim()).filter(Boolean);for(let n of s)try{let o=cl(n);if(o.test(r)||o.test(i))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 hl(e,t){let r=(0,At.normalize)(e),i=(0,At.normalize)(t);if(r===i)return!0;let s=(0,At.relative)(i,r);return s.length>0&&!s.startsWith("..")&&!(0,At.isAbsolute)(s)}function qe(e){if(process.env.CLAUDE_MEM_INTERNAL==="1")return!1;if(!e)return!0;if(hl(e,ue))return!1;let t=dt();return!Ve(e,t.CLAUDE_MEM_EXCLUDED_PROJECTS)}var Ys="claude";function ul(e){return e.trim().toLowerCase().replace(/\s+/g,"-")}function nt(e){if(!e)return Ys;let t=ul(e);return t?t==="transcript"||t.includes("codex")?"codex":t.includes("cursor")?"cursor":t.includes("claude")?"claude":t:Ys}var Vs=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],Js=new RegExp(`<(${Vs.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g");var Xs=100;function dl(e){let t=Object.fromEntries(Vs.map(s=>[s,0]));Js.lastIndex=0;let r=0,i=e.replace(Js,(s,n)=>(t[n]=(t[n]??0)+1,r+=1,""));return r>Xs&&d.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:r,maxAllowed:Xs,contentLength:e.length}),{stripped:i.trim(),counts:t}}function $r(e){return dl(e).stripped}var pl=["task-notification"],fl=new RegExp(`^\\s*<(${pl.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),ml=256*1024;function qs(e){return!e||e.length>ml?!1:fl.test(e)}var gl=ut(z.API_REQUEST),gt=class extends Error{kind;status;cause;constructor(t,r,i={}){super(r),this.name="ServerClientError",this.kind=t,this.status=i.status??null,this.cause=i.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)}},Qe=class{baseUrl;apiKey;timeoutMs;constructor(t){this.baseUrl=Sl(t.serverBaseUrl),this.apiKey=t.apiKey,this.timeoutMs=t.timeoutMs??gl}async startSession(t){let r=this.buildStartSessionPayload(t);return this.request("POST","/v1/sessions/start",r)}async recordEvent(t){let r=this.buildEventPayload(t),i=t.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",i,r)}async endSession(t){if(!t.sessionId)throw new gt("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(t.sessionId)}/end`,{})}async addObservation(t){return this.request("POST","/v1/memories",this.buildAddObservationPayload(t))}async searchObservations(t){return this.request("POST","/v1/search",this.buildSearchPayload(t))}async contextObservations(t){return this.request("POST","/v1/context",this.buildSearchPayload(t))}async getJobStatus(t){if(!t)throw new gt("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(t)}`)}buildAddObservationPayload(t){let r=t.content,i=t.kind??"manual",s=typeof t.metadata?.title=="string"?t.metadata.title:void 0;return{projectId:t.projectId,kind:i,type:i,narrative:r,...s?{title:s}:{},...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}}}buildSearchPayload(t){return{projectId:t.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:jr(t.platformSource)}:{}}}buildStartSessionPayload(t){return{projectId:t.projectId,...t.externalSessionId!==void 0?{externalSessionId:t.externalSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.agentId!==void 0?{agentId:t.agentId}:{},...t.agentType!==void 0?{agentType:t.agentType}:{},...t.platformSource!==void 0?{platformSource:jr(t.platformSource)}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}}}buildEventPayload(t){return{projectId:t.projectId,sourceType:t.sourceType,eventType:t.eventType,occurredAtEpoch:t.occurredAtEpoch,...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.memorySessionId!==void 0?{memorySessionId:t.memorySessionId}:{},...t.platformSource!==void 0?{platformSource:jr(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{}}}async request(t,r,i){if(!this.apiKey||!this.apiKey.trim())throw new gt("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let s=`${this.baseUrl}${r}`,n={method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};i!==void 0&&(n.body=JSON.stringify(i));let o;try{o=await Ur(s,n,this.timeoutMs)}catch(l){let c=l instanceof Error?l.message:String(l),h=/timed out|timeout/i.test(c);throw new gt(h?"timeout":"transport",`Server ${t} ${r} failed: ${c}`,{cause:l})}if(!o.ok){let l=await o.text().catch(()=>"");throw new gt("http_error",`Server ${t} ${r} returned ${o.status}: ${El(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 gt("invalid_response",`Server ${t} ${r} returned non-JSON response`,{cause:l})}}};function Qs(e){return e instanceof gt}function Sl(e){return e.replace(/\/+$/,"")}function jr(e){return typeof e=="string"?nt(e):null}function El(e,t){return e.length<=t?e:`${e.slice(0,t)}\u2026`}function wl(){let t=(dt().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return t==="server"||t==="server-beta"?"server":"worker"}function yl(){let e=dt(),t=(...o)=>{for(let a of o){let l=(a??"").trim();if(l.length>0)return l}return""},r=t(e.CLAUDE_MEM_SERVER_URL,e.CLAUDE_MEM_SERVER_BETA_URL),i=t(e.CLAUDE_MEM_SERVER_API_KEY,e.CLAUDE_MEM_SERVER_BETA_API_KEY),s=t(e.CLAUDE_MEM_SERVER_PROJECT_ID,e.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!r)return d.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!i)return d.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!s)return d.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let n={serverBaseUrl:r,apiKey:i};return{runtime:"server",client:new Qe(n),projectId:s,serverBaseUrl:r}}function Zs(){if(wl()!=="server")return{runtime:"worker"};let e=yl();return e||{runtime:"worker"}}function tn(e,t){d.warn("HOOK",`[server-fallback] reason=${e}`,t??{})}var _l={executeWithWorkerFallback:Ye,isWorkerFallback:ze,loadFromFileOnce:dt,resolveRuntimeContext:Zs,logServerFallback:tn,shouldTrackProject:qe},bt=_l;var en={async execute(e){let{sessionId:t,prompt:r}=e,i=e.cwd??process.cwd();if(!t)return d.warn("HOOK","session-init: No sessionId provided, skipping (Codex CLI or unknown platform)"),{continue:!0,suppressOutput:!0,exitCode:vt.SUCCESS};if(!bt.shouldTrackProject(i))return d.info("HOOK","Project excluded from tracking",{cwd:i}),{continue:!0,suppressOutput:!0};if(r&&qs(r))return d.debug("HOOK","session-init: skipping internal protocol payload",{preview:r.slice(0,80)}),{continue:!0,suppressOutput:!0};let s=!r||!r.trim()?"[media prompt]":r,n=Ct(i).primary,o=nt(e.platform),a=bt.loadFromFileOnce(),l=String(a.CLAUDE_MEM_SEMANTIC_INJECT).toLowerCase()==="true",c=bt.resolveRuntimeContext();if(c.runtime==="server")try{return await c.client.startSession({projectId:c.projectId,externalSessionId:t,contentSessionId:t,agentId:e.agentId??null,agentType:e.agentType??null,platformSource:o,metadata:{project:n,prompt:s}}),d.info("HOOK","session-init: server session started",{contentSessionId:t,project:n}),{continue:!0,suppressOutput:!0}}catch(m){if(Qs(m)&&m.isFallbackEligible())bt.logServerFallback(m.kind,{status:m.status,message:m.message,route:"/v1/sessions/start"});else return d.error("HOOK","Server session-start failed (non-recoverable)",{error:m instanceof Error?m.message:String(m)}),{continue:!0,suppressOutput:!0,exitCode:vt.SUCCESS}}d.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:t,project:n});let h=await bt.executeWithWorkerFallback("/api/sessions/init","POST",{contentSessionId:t,project:n,prompt:s,platformSource:o});if(bt.isWorkerFallback(h))return{continue:!0,suppressOutput:!0,exitCode:vt.SUCCESS};if(typeof h?.sessionDbId!="number")return d.failure("HOOK","Session initialization returned malformed response",{contentSessionId:t,project:n}),{continue:!0,suppressOutput:!0,exitCode:vt.SUCCESS};let u=h.sessionDbId,p=h.promptNumber;if(d.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:u,promptNumber:p,skipped:h.skipped,contextInjected:h.contextInjected}),d.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${t} | prompt#=${p} | sessionDbId=${u}`),h.skipped&&h.reason==="private")return d.info("HOOK",`INIT_COMPLETE | sessionDbId=${u} | promptNumber=${p} | skipped=true | reason=private`,{sessionId:u}),{continue:!0,suppressOutput:!0};let f="";if(l&&s&&s.length>=20&&s!=="[media prompt]"){let m=a.CLAUDE_MEM_SEMANTIC_INJECT_LIMIT||"5",g=await bt.executeWithWorkerFallback("/api/context/semantic","POST",{q:s,project:n,limit:m,platformSource:o});!bt.isWorkerFallback(g)&&g?.context&&(d.debug("HOOK",`Semantic injection: ${g.count} observations for prompt`,{sessionId:u,count:g.count}),f=g.context)}return d.info("HOOK",`INIT_COMPLETE | sessionDbId=${u} | promptNumber=${p} | project=${n}`,{sessionId:u}),f?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:f}}:{continue:!0,suppressOutput:!0}}};var rn={async execute(e){let{sessionId:t,cwd:r,filePath:i,edits:s}=e,n=nt(e.platform);if(!i)throw new Error("fileEditHandler requires filePath");if(d.dataIn("HOOK",`FileEdit: ${i}`,{editCount:s?.length??0}),!r)throw new Error(`Missing cwd in FileEdit hook input for session ${t}, file ${i}`);if(!qe(r))return d.debug("HOOK","Project excluded from tracking, skipping file edit observation",{cwd:r,filePath:i}),{continue:!0,suppressOutput:!0,exitCode:vt.SUCCESS};let o=await Ye("/api/sessions/observations","POST",{contentSessionId:t,platformSource:n,tool_name:"write_file",tool_input:{filePath:i,edits:s},tool_response:{success:!0},cwd:r});return ze(o)?{continue:!0,suppressOutput:!0,exitCode:vt.SUCCESS}:(d.debug("HOOK","File edit observation sent successfully",{filePath:i}),{continue:!0,suppressOutput:!0})}};var V=require("fs"),Ze=require("path");var Ou=R.settings();function sn(e,t){let r="<claude-mem-context>",i="</claude-mem-context>";if(!e)return`${r}
14
14
  ${t}
15
15
  ${i}`;let s=e.indexOf(r),n=e.indexOf(i);return s!==-1&&n!==-1?e.substring(0,s)+`${r}
16
16
  ${t}