keepmind 1.0.1 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.codex-plugin/plugin.json +1 -1
- package/dist/npx-cli/index.js +127 -127
- package/package.json +1 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/.codex-plugin/plugin.json +1 -1
- package/plugin/package.json +1 -1
- package/plugin/scripts/mcp-server.cjs +21 -21
- package/plugin/scripts/transcript-watcher.cjs +12 -14
- package/plugin/scripts/worker-service.cjs +126 -126
|
@@ -1,18 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var
|
|
3
|
-
`)?
|
|
4
|
-
`),t.skipExit||process.exit(2)}var ar=(n=>(n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR",n[n.SILENT=4]="SILENT",n))(ar||{}),or=null,lr=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){if(!this.logFileInitialized){this.logFileInitialized=!0;try{let t=R.logsDir();(0,at.existsSync)(t)||(0,at.mkdirSync)(t,{recursive:!0});let r=new Date().toISOString().split("T")[0];this.logFilePath=(0,Vr.join)(t,`keepmind-${r}.log`)}catch(t){console.error("[LOGGER] Failed to initialize log file:",t instanceof Error?t.message:String(t)),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let t=R.settings();if((0,at.existsSync)(t)){let r=(0,at.readFileSync)(t,"utf-8"),i=(JSON.parse(r).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=ar[i]??1}else this.level=1}catch(t){console.error("[LOGGER] Failed to load log level from settings:",t instanceof Error?t.message:String(t)),this.level=1}return this.level}formatData(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return t.toString();if(typeof t=="object"){if(t instanceof Error)return this.getLevel()===0?`${t.message}
|
|
5
|
-
${t.stack}`:t.message;if(Array.isArray(t))return`[${t.length} items]`;let r=Object.keys(t);return r.length===0?"{}":r.length<=3?JSON.stringify(t):`{${r.length} keys: ${r.slice(0,3).join(", ")}...}`}return String(t)}formatTool(t,r){if(!r)return t;let s=r;if(typeof r=="string")try{s=JSON.parse(r)}catch{s=r}if(t==="Bash"&&s.command)return`${t}(${s.command})`;if(s.file_path)return`${t}(${s.file_path})`;if(s.notebook_path)return`${t}(${s.notebook_path})`;if(t==="Glob"&&s.pattern)return`${t}(${s.pattern})`;if(t==="Grep"&&s.pattern)return`${t}(${s.pattern})`;if(s.url)return`${t}(${s.url})`;if(s.query)return`${t}(${s.query})`;if(t==="Task"){if(s.subagent_type)return`${t}(${s.subagent_type})`;if(s.description)return`${t}(${s.description})`}return t==="Skill"&&s.skill?`${t}(${s.skill})`:t==="LSP"&&s.operation?`${t}(${s.operation})`:t}formatTimestamp(t){let r=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0"),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),a=String(t.getSeconds()).padStart(2,"0"),l=String(t.getMilliseconds()).padStart(3,"0");return`${r}-${s}-${i} ${n}:${o}:${a}.${l}`}log(t,r,s,i,n){if(t<this.getLevel())return;this.ensureLogFileInitialized();let o=this.formatTimestamp(new Date),a=ar[t].padEnd(5),l=r.padEnd(6),c="";i?.correlationId?c=`[${i.correlationId}] `:i?.sessionId&&(c=`[session-${i.sessionId}] `);let u="";if(n!=null)if(n instanceof Error)u=this.getLevel()===0?`
|
|
2
|
+
"use strict";var pn=Object.create;var Kr=Object.defineProperty;var fn=Object.getOwnPropertyDescriptor;var mn=Object.getOwnPropertyNames;var gn=Object.getPrototypeOf,Sn=Object.prototype.hasOwnProperty;var En=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of mn(t))!Sn.call(e,i)&&i!==r&&Kr(e,i,{get:()=>t[i],enumerable:!(s=fn(t,i))||s.enumerable});return e};var ot=(e,t,r)=>(r=e!=null?pn(gn(e)):{},En(t||!e||!e.__esModule?Kr(r,"default",{value:e,enumerable:!0}):r,e));var lt=require("fs"),cr=require("os"),Kt=require("path");var _=require("path"),ar=require("os"),N=require("fs");var Yr=require("url");var at=require("fs"),zr=require("path");var wn=null;function yn(e){return(wn??process.stderr.write.bind(process.stderr))(e)}function Gt(e){yn(e)}var nr=(n=>(n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR",n[n.SILENT=4]="SILENT",n))(nr||{}),ir=null,or=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){if(!this.logFileInitialized){this.logFileInitialized=!0;try{let t=R.logsDir();(0,at.existsSync)(t)||(0,at.mkdirSync)(t,{recursive:!0});let r=new Date().toISOString().split("T")[0];this.logFilePath=(0,zr.join)(t,`keepmind-${r}.log`)}catch(t){console.error("[LOGGER] Failed to initialize log file:",t instanceof Error?t.message:String(t)),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let t=R.settings();if((0,at.existsSync)(t)){let r=(0,at.readFileSync)(t,"utf-8"),i=(JSON.parse(r).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=nr[i]??1}else this.level=1}catch(t){console.error("[LOGGER] Failed to load log level from settings:",t instanceof Error?t.message:String(t)),this.level=1}return this.level}formatData(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return t.toString();if(typeof t=="object"){if(t instanceof Error)return this.getLevel()===0?`${t.message}
|
|
3
|
+
${t.stack}`:t.message;if(Array.isArray(t))return`[${t.length} items]`;let r=Object.keys(t);return r.length===0?"{}":r.length<=3?JSON.stringify(t):`{${r.length} keys: ${r.slice(0,3).join(", ")}...}`}return String(t)}formatTool(t,r){if(!r)return t;let s=r;if(typeof r=="string")try{s=JSON.parse(r)}catch{s=r}if(t==="Bash"&&s.command)return`${t}(${s.command})`;if(s.file_path)return`${t}(${s.file_path})`;if(s.notebook_path)return`${t}(${s.notebook_path})`;if(t==="Glob"&&s.pattern)return`${t}(${s.pattern})`;if(t==="Grep"&&s.pattern)return`${t}(${s.pattern})`;if(s.url)return`${t}(${s.url})`;if(s.query)return`${t}(${s.query})`;if(t==="Task"){if(s.subagent_type)return`${t}(${s.subagent_type})`;if(s.description)return`${t}(${s.description})`}return t==="Skill"&&s.skill?`${t}(${s.skill})`:t==="LSP"&&s.operation?`${t}(${s.operation})`:t}formatTimestamp(t){let r=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0"),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),a=String(t.getSeconds()).padStart(2,"0"),l=String(t.getMilliseconds()).padStart(3,"0");return`${r}-${s}-${i} ${n}:${o}:${a}.${l}`}log(t,r,s,i,n){if(t<this.getLevel())return;this.ensureLogFileInitialized();let o=this.formatTimestamp(new Date),a=nr[t].padEnd(5),l=r.padEnd(6),c="";i?.correlationId?c=`[${i.correlationId}] `:i?.sessionId&&(c=`[session-${i.sessionId}] `);let u="";if(n!=null)if(n instanceof Error)u=this.getLevel()===0?`
|
|
6
4
|
${n.message}
|
|
7
5
|
${n.stack}`:` ${n.message}`;else if(this.getLevel()===0&&typeof n=="object")try{u=`
|
|
8
6
|
`+JSON.stringify(n,null,2)}catch{u=" "+this.formatData(n)}else u=" "+this.formatData(n);let h="";if(i){let{sessionId:f,memorySessionId:m,correlationId:g,...w}=i;Object.keys(w).length>0&&(h=` {${Object.entries(w).map(([E,y])=>`${E}=${y}`).join(", ")}}`)}let p=`[${o}] [${a}] [${l}] ${c}${s}${h}${u}`;if(this.logFilePath)try{(0,at.appendFileSync)(this.logFilePath,p+`
|
|
9
|
-
`,"utf8")}catch(f){
|
|
10
|
-
`)}else
|
|
11
|
-
`)}debug(t,r,s,i){this.log(0,t,r,s,i)}info(t,r,s,i){this.log(1,t,r,s,i)}warn(t,r,s,i){this.log(2,t,r,s,i)}setErrorSink(t){
|
|
12
|
-
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),u=c?`${c[1].split("/").pop()}:${c[2]}`:"unknown",h={...s,location:u};return this.warn(t,`[HAPPY-PATH] ${r}`,h,i),n}},d=new lr;var In={};function bn(){return typeof __dirname<"u"?__dirname:(0,_.dirname)((0,Xr.fileURLToPath)(In.url))}var Ll=bn();function ur(){let e=process.env.KEEPMIND_DATA_DIR??process.env.CLAUDE_MEM_DATA_DIR;if(e)return e;let t=(0,_.join)((0,cr.homedir)(),".keepmind"),r=(0,_.join)(t,"settings.json");try{if((0,N.existsSync)(r)){let s=JSON.parse((0,N.readFileSync)(r,"utf-8")),i=s.env??s,n=i.KEEPMIND_DATA_DIR??i.CLAUDE_MEM_DATA_DIR;if(n)return n}}catch{}return t}var T=ur(),le=process.env.CLAUDE_CONFIG_DIR||(0,_.join)((0,cr.homedir)(),".claude"),ce=(0,_.join)(le,"plugins","marketplaces","keepmind"),Tn=(0,_.join)(T,"archives"),kn=(0,_.join)(T,"logs"),Mn=(0,_.join)(T,"trash"),Rn=(0,_.join)(T,"backups"),An=(0,_.join)(T,"modes"),ue=(0,_.join)(T,"settings.json"),It=(0,_.join)(T,"keepmind.db"),Gt=(0,_.join)(T,"claude-mem.db"),Cn=(0,_.join)(T,"vector-db"),he=(0,_.join)(T,"observer-sessions"),On=(0,_.basename)(he),Nl=(0,_.join)(le,"settings.json"),Fl=(0,_.join)(le,"commands"),Ul=(0,_.join)(le,"CLAUDE.md");function Dn(){try{if((0,N.existsSync)(It)||!(0,N.existsSync)(Gt))return(0,N.existsSync)(It);for(let e of["","-wal","-shm"]){let t=Gt+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:Gt,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 Pn(){return Dn(),!(0,N.existsSync)(It)&&(0,N.existsSync)(Gt)?Gt: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:()=>Pn(),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:()=>kn,archives:()=>Tn,trash:()=>Mn,backups:()=>Rn,modes:()=>An,vectorDb:()=>Cn,observerSessions:()=>he};var xt=R.transcriptsConfig(),de=R.transcriptsState();var xn={version:1,schemas:{},watches:[],stateFile:de};function Ln(e){let t=typeof e.schema=="string"?e.schema:e.schema?.name;if(!(e.name==="codex"||t==="codex")||!e.path)return!1;let s=U(e.path).replace(/\\/g,"/"),i=(0,Bt.join)((0,hr.homedir)(),".codex","sessions").replace(/\\/g,"/");return s===`${i}/**/*.jsonl`}function qr(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&&Ln(e)}function U(e){return e&&(e.startsWith("~")?(0,Bt.join)((0,hr.homedir)(),e.slice(1)):e)}function Kt(e=xt){let t=U(e);if(!(0,lt.existsSync)(t))throw new Error(`Transcript watch config not found: ${t}`);let r=(0,lt.readFileSync)(t,"utf-8"),s=JSON.parse(r);if(!s.version||!s.watches)throw new Error(`Invalid transcript watch config: ${t}`);return s.stateFile||(s.stateFile=de),s}function pe(e=xt){let t=U(e),r=(0,Bt.dirname)(t);(0,lt.existsSync)(r)||(0,lt.mkdirSync)(r,{recursive:!0}),(0,lt.writeFileSync)(t,JSON.stringify(xn,null,2))}var L=require("fs"),X=require("path");var Is=require("node:url"),Ut=require("node:path"),Us=require("node:url"),Z=require("fs"),Ho=ot(require("node:fs"),1),_t=require("node:fs/promises"),Ae=require("node:events"),br=ot(require("node:stream"),1),Ws=require("node:string_decoder"),_s=(e,t,r)=>{let s=e instanceof RegExp?Qr(e,r):e,i=t instanceof RegExp?Qr(t,r):t,n=s!==null&&i!=null&&Nn(s,i,r);return n&&{start:n[0],end:n[1],pre:r.slice(0,n[0]),body:r.slice(n[0]+s.length,n[1]),post:r.slice(n[1]+i.length)}},Qr=(e,t)=>{let r=t.match(e);return r?r[0]:null},Nn=(e,t,r)=>{let s,i,n,o,a,l=r.indexOf(e),c=r.indexOf(t,l+1),u=l;if(l>=0&&c>0){if(e===t)return[l,c];for(s=[],n=r.length;u>=0&&!a;){if(u===l)s.push(u),l=r.indexOf(e,u+1);else if(s.length===1){let h=s.pop();h!==void 0&&(a=[h,c])}else i=s.pop(),i!==void 0&&i<n&&(n=i,o=c),c=r.indexOf(t,u+1);u=l<c&&l>=0?l:c}s.length&&o!==void 0&&(a=[n,o])}return a},vs="\0SLASH"+Math.random()+"\0",bs="\0OPEN"+Math.random()+"\0",_r="\0CLOSE"+Math.random()+"\0",Ts="\0COMMA"+Math.random()+"\0",ks="\0PERIOD"+Math.random()+"\0",Fn=new RegExp(vs,"g"),Un=new RegExp(bs,"g"),Wn=new RegExp(_r,"g"),$n=new RegExp(Ts,"g"),jn=new RegExp(ks,"g"),Hn=/\\\\/g,Gn=/\\{/g,Bn=/\\}/g,Kn=/\\,/g,zn=/\\./g,Yn=1e5;function dr(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function Jn(e){return e.replace(Hn,vs).replace(Gn,bs).replace(Bn,_r).replace(Kn,Ts).replace(zn,ks)}function Vn(e){return e.replace(Fn,"\\").replace(Un,"{").replace(Wn,"}").replace($n,",").replace(jn,".")}function Ms(e){if(!e)return[""];let t=[],r=_s("{","}",e);if(!r)return e.split(",");let{pre:s,body:i,post:n}=r,o=s.split(",");o[o.length-1]+="{"+i+"}";let a=Ms(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=Yn}=t;return e.slice(0,2)==="{}"&&(e="\\{\\}"+e.slice(2)),Qt(Jn(e),r,!0).map(Vn)}function qn(e){return"{"+e+"}"}function Qn(e){return/^-?0\d/.test(e)}function Zn(e,t){return e<=t}function to(e,t){return e>=t}function Qt(e,t,r){let s=[],i=_s("{","}",e);if(!i)return[e];let n=i.pre,o=i.post.length?Qt(i.post,t,!1):[""];if(/\$$/.test(i.pre))for(let a=0;a<o.length&&a<t;a++){let l=n+"{"+i.body+"}"+o[a];s.push(l)}else{let a=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(i.body),l=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(i.body),c=a||l,u=i.body.indexOf(",")>=0;if(!c&&!u)return i.post.match(/,(?!,).*\}/)?(e=i.pre+"{"+i.body+_r+i.post,Qt(e,t,!0)):[e];let h;if(c)h=i.body.split(/\.\./);else if(h=Ms(i.body),h.length===1&&h[0]!==void 0&&(h=Qt(h[0],t,!1).map(qn),h.length===1))return o.map(f=>i.pre+h[0]+f);let p;if(c&&h[0]!==void 0&&h[1]!==void 0){let f=dr(h[0]),m=dr(h[1]),g=Math.max(h[0].length,h[1].length),w=h.length===3&&h[2]!==void 0?Math.abs(dr(h[2])):1,S=Zn;m<f&&(w*=-1,S=to);let E=h.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 k=g-v.length;if(k>0){let St=new Array(k+1).join("0");y<0?v="-"+St+v.slice(1):v=St+v}}p.push(v)}}else{p=[];for(let f=0;f<h.length;f++)p.push.apply(p,Qt(h[f],t,!1))}for(let f=0;f<p.length;f++)for(let m=0;m<o.length&&s.length<t;m++){let g=n+p[f]+o[m];(!r||c||g)&&s.push(g)}}return s}var Te=e=>{if(typeof e!="string")throw new TypeError("invalid pattern");if(e.length>65536)throw new TypeError("pattern is too long")},eo={"[: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]},zt=e=>e.replace(/[[\]\\-]/g,"\\$&"),ro=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Zr=e=>e.join(""),so=(e,t)=>{let r=t;if(e.charAt(r)!=="[")throw new Error("not in a brace expression");let s=[],i=[],n=r+1,o=!1,a=!1,l=!1,c=!1,u=r,h="";t:for(;n<e.length;){let m=e.charAt(n);if((m==="!"||m==="^")&&n===r+1){c=!0,n++;continue}if(m==="]"&&o&&!l){u=n+1;break}if(o=!0,m==="\\"&&!l){l=!0,n++;continue}if(m==="["&&!l){for(let[g,[w,S,E]]of Object.entries(eo))if(e.startsWith(g,n)){if(h)return["$.",!1,e.length-r,!0];n+=g.length,E?i.push(w):s.push(w),a=a||S;continue t}}if(l=!1,h){m>h?s.push(zt(h)+"-"+zt(m)):m===h&&s.push(zt(m)),h="",n++;continue}if(e.startsWith("-]",n+1)){s.push(zt(m+"-")),n+=2;continue}if(e.startsWith("-",n+1)){h=m,n+=2;continue}s.push(zt(m)),n++}if(u<n)return["",!1,0,!1];if(!s.length&&!i.length)return["$.",!1,e.length-r,!0];if(i.length===0&&s.length===1&&/^\\?.$/.test(s[0])&&!c){let m=s[0].length===2?s[0].slice(-1):s[0];return[ro(m),!1,u-r,!1]}let p="["+(c?"^":"")+Zr(s)+"]",f="["+(c?"":"^")+Zr(i)+"]";return[s.length&&i.length?"("+p+"|"+f+")":s.length?p:f,a,u-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(["!","?","+","*","@"]),ts=e=>io.has(e),no="(?!(?:^|/)\\.\\.?(?:$|/))",fe="(?!\\.)",oo=new Set(["[","."]),ao=new Set(["..","."]),lo=new Set("().*{}+?[]^$\\!"),co=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),vr="[^/]",es=vr+"*?",rs=vr+"+?",Rs=class ${type;#t;#r;#n=!1;#i=[];#o;#y;#S;#u=!1;#a;#d;#h=!1;constructor(t,r,s={}){this.type=t,t&&(this.#r=!0),this.#o=r,this.#t=this.#o?this.#o.#t:this,this.#a=this.#t===this?s:this.#t.#a,this.#S=this.#t===this?[]:this.#t.#S,t==="!"&&!this.#t.#u&&this.#S.push(this),this.#y=this.#o?this.#o.#i.length:0}get hasMagic(){if(this.#r!==void 0)return this.#r;for(let t of this.#i)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.#i.map(t=>String(t)).join("|")+")":this.#d=this.#i.map(t=>String(t)).join("")}#l(){if(this!==this.#t)throw new Error("should only call on root");if(this.#u)return this;this.toString(),this.#u=!0;let t;for(;t=this.#S.pop();){if(t.type!=="!")continue;let r=t,s=r.#o;for(;s;){for(let i=r.#y+1;!s.type&&i<s.#i.length;i++)for(let n of t.#i){if(typeof n=="string")throw new Error("string part in extglob AST??");n.copyIn(s.#i[i])}r=s,s=r.#o}}return this}push(...t){for(let r of t)if(r!==""){if(typeof r!="string"&&!(r instanceof $&&r.#o===this))throw new Error("invalid part: "+r);this.#i.push(r)}}toJSON(){let t=this.type===null?this.#i.slice().map(r=>typeof r=="string"?r:r.toJSON()):[this.type,...this.#i.map(r=>r.toJSON())];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===this.#t||this.#t.#u&&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 s=t.#i[r];if(!(s instanceof $&&s.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.#i.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 $(this.type,t);for(let s of this.#i)r.copyIn(s);return r}static#s(t,r,s,i){let n=!1,o=!1,a=-1,l=!1;if(r.type===null){let f=s,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(!i.noext&&ts(g)&&t.charAt(f)==="("){r.push(m),m="";let w=new $(g,r);f=$.#s(t,w,f,i),r.push(w);continue}m+=g}return r.push(m),f}let c=s+1,u=new $(null,r),h=[],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(ts(f)&&t.charAt(c)==="("){u.push(p),p="";let m=new $(f,u);u.push(m),c=$.#s(t,m,c,i);continue}if(f==="|"){u.push(p),p="",h.push(u),u=new $(null,r);continue}if(f===")")return p===""&&r.#i.length===0&&(r.#h=!0),u.push(p),p="",r.push(...h,u),c;p+=f}return r.type=null,r.#r=void 0,r.#i=[t.substring(s-1)],c}static fromGlob(t,r={}){let s=new $(null,void 0,r);return $.#s(t,s,0,r),s}toMMPattern(){if(this!==this.#t)return this.#t.toMMPattern();let t=this.toString(),[r,s,i,n]=this.toRegExpSource();if(!(i||this.#r||this.#a.nocase&&!this.#a.nocaseMagicOnly&&t.toUpperCase()!==t.toLowerCase()))return s;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.#i.some(p=>typeof p!="string"),c=this.#i.map(p=>{let[f,m,g,w]=typeof p=="string"?$.#_(p,this.#r,l):p.toRegExpSource(t);return this.#r=this.#r||g,this.#n=this.#n||w,f}).join(""),u="";if(this.isStart()&&typeof this.#i[0]=="string"&&!(this.#i.length===1&&ao.has(this.#i[0]))){let p=oo,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));u=f?no:m?fe:""}let h="";return this.isEnd()&&this.#t.#u&&this.#o?.type==="!"&&(h="(?:$|\\/)"),[u+c+h,Ft(c),this.#r=!!this.#r,this.#n]}let s=this.type==="*"||this.type==="+",i=this.type==="!"?"(?:(?!(?:":"(?:",n=this.#p(r);if(this.isStart()&&this.isEnd()&&!n&&this.type!=="!"){let l=this.toString();return this.#i=[l],this.type=null,this.#r=void 0,[l,Ft(this.toString()),!1,!1]}let o=!s||t||r||!fe?"":this.#p(!0);o===n&&(o=""),o&&(n=`(?:${n})(?:${o})*?`);let a="";if(this.type==="!"&&this.#h)a=(this.isStart()&&!r?fe:"")+rs;else{let l=this.type==="!"?"))"+(this.isStart()&&!r&&!t?fe:"")+es+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;a=i+n+l}return[a,Ft(n),this.#r=!!this.#r,this.#n]}#p(t){return this.#i.map(r=>{if(typeof r=="string")throw new Error("string type in extglob ast??");let[s,i,n,o]=r.toRegExpSource(t);return this.#n=this.#n||o,s}).filter(r=>!(this.isStart()&&this.isEnd())||!!r).join("|")}static#_(t,r,s=!1){let i=!1,n="",o=!1,a=!1;for(let l=0;l<t.length;l++){let c=t.charAt(l);if(i){i=!1,n+=(lo.has(c)?"\\":"")+c;continue}if(c==="*"){if(a)continue;a=!0,n+=s&&/^[*]+$/.test(t)?rs:es,r=!0;continue}else a=!1;if(c==="\\"){l===t.length-1?n+="\\\\":i=!0;continue}if(c==="["){let[u,h,p,f]=so(t,l);if(p){n+=u,o=o||h,l+=p-1,r=r||f;continue}}if(c==="?"){n+=vr,r=!0;continue}n+=co(c)}return[n,Ft(t),!!r,o]}},As=(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)),uo=/^\*+([^+@!?\*\[\(]*)$/,ho=e=>t=>!t.startsWith(".")&&t.endsWith(e),po=e=>t=>t.endsWith(e),fo=e=>(e=e.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(e)),mo=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),go=/^\*+\.\*+$/,So=e=>!e.startsWith(".")&&e.includes("."),Eo=e=>e!=="."&&e!==".."&&e.includes("."),wo=/^\.\*+$/,yo=e=>e!=="."&&e!==".."&&e.startsWith("."),_o=/^\*+$/,vo=e=>e.length!==0&&!e.startsWith("."),bo=e=>e.length!==0&&e!=="."&&e!=="..",To=/^\?+([^+@!?\*\[\(]*)?$/,ko=([e,t=""])=>{let r=Cs([e]);return t?(t=t.toLowerCase(),s=>r(s)&&s.toLowerCase().endsWith(t)):r},Mo=([e,t=""])=>{let r=Os([e]);return t?(t=t.toLowerCase(),s=>r(s)&&s.toLowerCase().endsWith(t)):r},Ro=([e,t=""])=>{let r=Os([e]);return t?s=>r(s)&&s.endsWith(t):r},Ao=([e,t=""])=>{let r=Cs([e]);return t?s=>r(s)&&s.endsWith(t):r},Cs=([e])=>{let t=e.length;return r=>r.length===t&&!r.startsWith(".")},Os=([e])=>{let t=e.length;return r=>r.length===t&&r!=="."&&r!==".."},Ds=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",ss={win32:{sep:"\\"},posix:{sep:"/"}},Co=Ds==="win32"?ss.win32.sep:ss.posix.sep;x.sep=Co;var I=Symbol("globstar **");x.GLOBSTAR=I;var Oo="[^/]",Do=Oo+"*?",Po="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",Io="(?:(?!(?:\\/|^)\\.).)*?",xo=(e,t={})=>r=>x(r,e,t);x.filter=xo;var H=(e,t={})=>Object.assign({},e,t),Lo=e=>{if(!e||typeof e!="object"||!Object.keys(e).length)return x;let t=x;return Object.assign((r,s,i={})=>t(r,s,H(e,i)),{Minimatch:class extends t.Minimatch{constructor(r,s={}){super(r,H(e,s))}static defaults(r){return t.defaults(H(e,r)).Minimatch}},AST:class extends t.AST{constructor(r,s,i={}){super(r,s,H(e,i))}static fromGlob(r,s={}){return t.AST.fromGlob(r,H(e,s))}},unescape:(r,s={})=>t.unescape(r,H(e,s)),escape:(r,s={})=>t.escape(r,H(e,s)),filter:(r,s={})=>t.filter(r,H(e,s)),defaults:r=>t.defaults(H(e,r)),makeRe:(r,s={})=>t.makeRe(r,H(e,s)),braceExpand:(r,s={})=>t.braceExpand(r,H(e,s)),match:(r,s,i={})=>t.match(r,s,H(e,i)),sep:t.sep,GLOBSTAR:I})};x.defaults=Lo;var Ps=(e,t={})=>(Te(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:Xn(e,{max:t.braceExpandMax}));x.braceExpand=Ps;var No=(e,t={})=>new yt(e,t).makeRe();x.makeRe=No;var Fo=(e,t,r={})=>{let s=new yt(t,r);return e=e.filter(i=>s.match(i)),s.options.nonull&&!e.length&&e.push(t),e};x.match=Fo;var is=/[?*]|[+@!]\(.*?\)|\[|\]/,Uo=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||Ds,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=(...i)=>console.error(...i)),this.debug(this.pattern,this.globSet);let r=this.globSet.map(i=>this.slashSplit(i));this.globParts=this.preprocess(r),this.debug(this.pattern,this.globParts);let s=this.globParts.map((i,n,o)=>{if(this.isWindows&&this.windowsNoMagicRoot){let a=i[0]===""&&i[1]===""&&(i[2]==="?"||!is.test(i[2]))&&!is.test(i[3]),l=/^[a-z]:/i.test(i[0]);if(a)return[...i.slice(0,4),...i.slice(4).map(c=>this.parse(c))];if(l)return[i[0],...i.slice(1).map(c=>this.parse(c))]}return i.map(a=>this.parse(a))});if(this.debug(this.pattern,s),this.set=s.filter(i=>i.indexOf(!1)===-1),this.isWindows)for(let i=0;i<this.set.length;i++){let n=this.set[i];n[0]===""&&n[1]===""&&this.globParts[i][2]==="?"&&typeof n[3]=="string"&&/^[a-z]:$/i.test(n[3])&&(n[2]="?")}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let r=0;r<e.length;r++)for(let s=0;s<e[r].length;s++)e[r][s]==="**"&&(e[r][s]="*");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 s=r;for(;t[s+1]==="**";)s++;s!==r&&t.splice(r,s-r)}return t})}levelOneOptimize(e){return e.map(t=>(t=t.reduce((r,s)=>{let i=r[r.length-1];return s==="**"&&i==="**"?r:s===".."&&i&&i!==".."&&i!=="."&&i!=="**"?(r.pop(),r):(r.push(s),r)},[]),t.length===0?[""]:t))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=!1;do{if(t=!1,!this.preserveMultipleSlashes){for(let s=1;s<e.length-1;s++){let i=e[s];s===1&&i===""&&e[0]===""||(i==="."||i==="")&&(t=!0,e.splice(s,1),s--)}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(t=!0,e.pop())}let r=0;for(;(r=e.indexOf("..",r+1))!==-1;){let s=e[r-1];s&&s!=="."&&s!==".."&&s!=="**"&&(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 s=-1;for(;(s=r.indexOf("**",s+1))!==-1;){let n=s;for(;r[n+1]==="**";)n++;n>s&&r.splice(s+1,n-s);let o=r[s+1],a=r[s+2],l=r[s+3];if(o!==".."||!a||a==="."||a===".."||!l||l==="."||l==="..")continue;t=!0,r.splice(s,1);let c=r.slice(0);c[s]="**",e.push(c),s--}if(!this.preserveMultipleSlashes){for(let n=1;n<r.length-1;n++){let o=r[n];n===1&&o===""&&r[0]===""||(o==="."||o==="")&&(t=!0,r.splice(n,1),n--)}r[0]==="."&&r.length===2&&(r[1]==="."||r[1]==="")&&(t=!0,r.pop())}let i=0;for(;(i=r.indexOf("..",i+1))!==-1;){let n=r[i-1];if(n&&n!=="."&&n!==".."&&n!=="**"){t=!0;let o=i===1&&r[i+1]==="**"?["."]:[];r.splice(i-1,2,...o),r.length===0&&r.push(""),i-=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 s=this.partsMatch(e[t],e[r],!this.preserveMultipleSlashes);if(s){e[t]=[],e[r]=s;break}}return e.filter(t=>t.length)}partsMatch(e,t,r=!1){let s=0,i=0,n=[],o="";for(;s<e.length&&i<t.length;)if(e[s]===t[i])n.push(o==="b"?t[i]:e[s]),s++,i++;else if(r&&e[s]==="**"&&t[i]===e[s+1])n.push(e[s]),s++;else if(r&&t[i]==="**"&&e[s]===t[i+1])n.push(t[i]),i++;else if(e[s]==="*"&&t[i]&&(this.options.dot||!t[i].startsWith("."))&&t[i]!=="**"){if(o==="b")return!1;o="a",n.push(e[s]),s++,i++}else if(t[i]==="*"&&e[s]&&(this.options.dot||!e[s].startsWith("."))&&e[s]!=="**"){if(o==="a")return!1;o="b",n.push(t[i]),s++,i++}else return!1;return e.length===t.length&&n}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=!1,r=0;for(let s=0;s<e.length&&e.charAt(s)==="!";s++)t=!t,r++;r&&(this.pattern=e.slice(r)),this.negate=t}matchOne(e,t,r=!1){let s=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,k]=[e[E],t[y]];v.toLowerCase()===k.toLowerCase()&&(t[y]=v,y>E?t=t.slice(y):E>y&&(e=e.slice(E)))}}let{optimizationLevel:i=1}=this.options;i>=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],u=e[n];if(this.debug(t,c,u),c===!1)return!1;if(c===I){this.debug("GLOBSTAR",[t,c,u]);var h=n,p=o+1;if(p===l){for(this.debug("** at the end");n<a;n++)if(e[n]==="."||e[n]===".."||!s.dot&&e[n].charAt(0)===".")return!1;return!0}for(;h<a;){var f=e[h];if(this.debug(`
|
|
7
|
+
`,"utf8")}catch(f){Gt(`[LOGGER] Failed to write to log file: ${f instanceof Error?f.message:String(f)}
|
|
8
|
+
`)}else Gt(p+`
|
|
9
|
+
`)}debug(t,r,s,i){this.log(0,t,r,s,i)}info(t,r,s,i){this.log(1,t,r,s,i)}warn(t,r,s,i){this.log(2,t,r,s,i)}setErrorSink(t){ir=t}error(t,r,s,i){this.log(3,t,r,s,i),this.routeErrorToSink(r,s,i)}routeErrorToSink(t,r,s){try{if(!ir||!(s instanceof Error))return;ir(s)}catch{}}dataIn(t,r,s,i){this.info(t,`\u2192 ${r}`,s,i)}dataOut(t,r,s,i){this.info(t,`\u2190 ${r}`,s,i)}success(t,r,s,i){this.info(t,`\u2713 ${r}`,s,i)}failure(t,r,s,i){this.error(t,`\u2717 ${r}`,s,i)}happyPathError(t,r,s,i,n=""){let c=((new Error().stack||"").split(`
|
|
10
|
+
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),u=c?`${c[1].split("/").pop()}:${c[2]}`:"unknown",h={...s,location:u};return this.warn(t,`[HAPPY-PATH] ${r}`,h,i),n}},d=new or;var Dn={};function _n(){return typeof __dirname<"u"?__dirname:(0,_.dirname)((0,Yr.fileURLToPath)(Dn.url))}var Il=_n();function lr(){let e=process.env.KEEPMIND_DATA_DIR??process.env.CLAUDE_MEM_DATA_DIR;if(e)return e;let t=(0,_.join)((0,ar.homedir)(),".keepmind"),r=(0,_.join)(t,"settings.json");try{if((0,N.existsSync)(r)){let s=JSON.parse((0,N.readFileSync)(r,"utf-8")),i=s.env??s,n=i.KEEPMIND_DATA_DIR??i.CLAUDE_MEM_DATA_DIR;if(n)return n}}catch{}return t}var T=lr(),le=process.env.CLAUDE_CONFIG_DIR||(0,_.join)((0,ar.homedir)(),".claude"),ce=(0,_.join)(le,"plugins","marketplaces","keepmind"),vn=(0,_.join)(T,"archives"),bn=(0,_.join)(T,"logs"),Tn=(0,_.join)(T,"trash"),kn=(0,_.join)(T,"backups"),Mn=(0,_.join)(T,"modes"),ue=(0,_.join)(T,"settings.json"),It=(0,_.join)(T,"keepmind.db"),Bt=(0,_.join)(T,"claude-mem.db"),Rn=(0,_.join)(T,"vector-db"),he=(0,_.join)(T,"observer-sessions"),An=(0,_.basename)(he),xl=(0,_.join)(le,"settings.json"),Ll=(0,_.join)(le,"commands"),Nl=(0,_.join)(le,"CLAUDE.md");function Cn(){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 On(){return Cn(),!(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:()=>On(),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:()=>bn,archives:()=>vn,trash:()=>Tn,backups:()=>kn,modes:()=>Mn,vectorDb:()=>Rn,observerSessions:()=>he};var xt=R.transcriptsConfig(),de=R.transcriptsState();var Pn={version:1,schemas:{},watches:[],stateFile:de};function In(e){let t=typeof e.schema=="string"?e.schema:e.schema?.name;if(!(e.name==="codex"||t==="codex")||!e.path)return!1;let s=U(e.path).replace(/\\/g,"/"),i=(0,Kt.join)((0,cr.homedir)(),".codex","sessions").replace(/\\/g,"/");return s===`${i}/**/*.jsonl`}function Jr(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&&In(e)}function U(e){return e&&(e.startsWith("~")?(0,Kt.join)((0,cr.homedir)(),e.slice(1)):e)}function zt(e=xt){let t=U(e);if(!(0,lt.existsSync)(t))throw new Error(`Transcript watch config not found: ${t}`);let r=(0,lt.readFileSync)(t,"utf-8"),s=JSON.parse(r);if(!s.version||!s.watches)throw new Error(`Invalid transcript watch config: ${t}`);return s.stateFile||(s.stateFile=de),s}function pe(e=xt){let t=U(e),r=(0,Kt.dirname)(t);(0,lt.existsSync)(r)||(0,lt.mkdirSync)(r,{recursive:!0}),(0,lt.writeFileSync)(t,JSON.stringify(Pn,null,2))}var L=require("fs"),X=require("path");var Os=require("node:url"),Ut=require("node:path"),Ls=require("node:url"),Z=require("fs"),$o=ot(require("node:fs"),1),_t=require("node:fs/promises"),Ae=require("node:events"),_r=ot(require("node:stream"),1),Ns=require("node:string_decoder"),Es=(e,t,r)=>{let s=e instanceof RegExp?Vr(e,r):e,i=t instanceof RegExp?Vr(t,r):t,n=s!==null&&i!=null&&xn(s,i,r);return n&&{start:n[0],end:n[1],pre:r.slice(0,n[0]),body:r.slice(n[0]+s.length,n[1]),post:r.slice(n[1]+i.length)}},Vr=(e,t)=>{let r=t.match(e);return r?r[0]:null},xn=(e,t,r)=>{let s,i,n,o,a,l=r.indexOf(e),c=r.indexOf(t,l+1),u=l;if(l>=0&&c>0){if(e===t)return[l,c];for(s=[],n=r.length;u>=0&&!a;){if(u===l)s.push(u),l=r.indexOf(e,u+1);else if(s.length===1){let h=s.pop();h!==void 0&&(a=[h,c])}else i=s.pop(),i!==void 0&&i<n&&(n=i,o=c),c=r.indexOf(t,u+1);u=l<c&&l>=0?l:c}s.length&&o!==void 0&&(a=[n,o])}return a},ws="\0SLASH"+Math.random()+"\0",ys="\0OPEN"+Math.random()+"\0",wr="\0CLOSE"+Math.random()+"\0",_s="\0COMMA"+Math.random()+"\0",vs="\0PERIOD"+Math.random()+"\0",Ln=new RegExp(ws,"g"),Nn=new RegExp(ys,"g"),Fn=new RegExp(wr,"g"),Un=new RegExp(_s,"g"),Wn=new RegExp(vs,"g"),$n=/\\\\/g,jn=/\\{/g,Hn=/\\}/g,Gn=/\\,/g,Bn=/\\./g,Kn=1e5;function ur(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function zn(e){return e.replace($n,ws).replace(jn,ys).replace(Hn,wr).replace(Gn,_s).replace(Bn,vs)}function Yn(e){return e.replace(Ln,"\\").replace(Nn,"{").replace(Fn,"}").replace(Un,",").replace(Wn,".")}function bs(e){if(!e)return[""];let t=[],r=Es("{","}",e);if(!r)return e.split(",");let{pre:s,body:i,post:n}=r,o=s.split(",");o[o.length-1]+="{"+i+"}";let a=bs(n);return n.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),t.push.apply(t,o),t}function Jn(e,t={}){if(!e)return[];let{max:r=Kn}=t;return e.slice(0,2)==="{}"&&(e="\\{\\}"+e.slice(2)),Zt(zn(e),r,!0).map(Yn)}function Vn(e){return"{"+e+"}"}function Xn(e){return/^-?0\d/.test(e)}function qn(e,t){return e<=t}function Qn(e,t){return e>=t}function Zt(e,t,r){let s=[],i=Es("{","}",e);if(!i)return[e];let n=i.pre,o=i.post.length?Zt(i.post,t,!1):[""];if(/\$$/.test(i.pre))for(let a=0;a<o.length&&a<t;a++){let l=n+"{"+i.body+"}"+o[a];s.push(l)}else{let a=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(i.body),l=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(i.body),c=a||l,u=i.body.indexOf(",")>=0;if(!c&&!u)return i.post.match(/,(?!,).*\}/)?(e=i.pre+"{"+i.body+wr+i.post,Zt(e,t,!0)):[e];let h;if(c)h=i.body.split(/\.\./);else if(h=bs(i.body),h.length===1&&h[0]!==void 0&&(h=Zt(h[0],t,!1).map(Vn),h.length===1))return o.map(f=>i.pre+h[0]+f);let p;if(c&&h[0]!==void 0&&h[1]!==void 0){let f=ur(h[0]),m=ur(h[1]),g=Math.max(h[0].length,h[1].length),w=h.length===3&&h[2]!==void 0?Math.abs(ur(h[2])):1,S=qn;m<f&&(w*=-1,S=Qn);let E=h.some(Xn);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 k=g-v.length;if(k>0){let St=new Array(k+1).join("0");y<0?v="-"+St+v.slice(1):v=St+v}}p.push(v)}}else{p=[];for(let f=0;f<h.length;f++)p.push.apply(p,Zt(h[f],t,!1))}for(let f=0;f<p.length;f++)for(let m=0;m<o.length&&s.length<t;m++){let g=n+p[f]+o[m];(!r||c||g)&&s.push(g)}}return s}var Te=e=>{if(typeof e!="string")throw new TypeError("invalid pattern");if(e.length>65536)throw new TypeError("pattern is too long")},Zn={"[: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,"\\$&"),to=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Xr=e=>e.join(""),eo=(e,t)=>{let r=t;if(e.charAt(r)!=="[")throw new Error("not in a brace expression");let s=[],i=[],n=r+1,o=!1,a=!1,l=!1,c=!1,u=r,h="";t:for(;n<e.length;){let m=e.charAt(n);if((m==="!"||m==="^")&&n===r+1){c=!0,n++;continue}if(m==="]"&&o&&!l){u=n+1;break}if(o=!0,m==="\\"&&!l){l=!0,n++;continue}if(m==="["&&!l){for(let[g,[w,S,E]]of Object.entries(Zn))if(e.startsWith(g,n)){if(h)return["$.",!1,e.length-r,!0];n+=g.length,E?i.push(w):s.push(w),a=a||S;continue t}}if(l=!1,h){m>h?s.push(Yt(h)+"-"+Yt(m)):m===h&&s.push(Yt(m)),h="",n++;continue}if(e.startsWith("-]",n+1)){s.push(Yt(m+"-")),n+=2;continue}if(e.startsWith("-",n+1)){h=m,n+=2;continue}s.push(Yt(m)),n++}if(u<n)return["",!1,0,!1];if(!s.length&&!i.length)return["$.",!1,e.length-r,!0];if(i.length===0&&s.length===1&&/^\\?.$/.test(s[0])&&!c){let m=s[0].length===2?s[0].slice(-1):s[0];return[to(m),!1,u-r,!1]}let p="["+(c?"^":"")+Xr(s)+"]",f="["+(c?"":"^")+Xr(i)+"]";return[s.length&&i.length?"("+p+"|"+f+")":s.length?p:f,a,u-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"),ro=new Set(["!","?","+","*","@"]),qr=e=>ro.has(e),so="(?!(?:^|/)\\.\\.?(?:$|/))",fe="(?!\\.)",io=new Set(["[","."]),no=new Set(["..","."]),oo=new Set("().*{}+?[]^$\\!"),ao=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),yr="[^/]",Qr=yr+"*?",Zr=yr+"+?",Ts=class ${type;#t;#r;#n=!1;#i=[];#o;#y;#S;#u=!1;#a;#d;#h=!1;constructor(t,r,s={}){this.type=t,t&&(this.#r=!0),this.#o=r,this.#t=this.#o?this.#o.#t:this,this.#a=this.#t===this?s:this.#t.#a,this.#S=this.#t===this?[]:this.#t.#S,t==="!"&&!this.#t.#u&&this.#S.push(this),this.#y=this.#o?this.#o.#i.length:0}get hasMagic(){if(this.#r!==void 0)return this.#r;for(let t of this.#i)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.#i.map(t=>String(t)).join("|")+")":this.#d=this.#i.map(t=>String(t)).join("")}#l(){if(this!==this.#t)throw new Error("should only call on root");if(this.#u)return this;this.toString(),this.#u=!0;let t;for(;t=this.#S.pop();){if(t.type!=="!")continue;let r=t,s=r.#o;for(;s;){for(let i=r.#y+1;!s.type&&i<s.#i.length;i++)for(let n of t.#i){if(typeof n=="string")throw new Error("string part in extglob AST??");n.copyIn(s.#i[i])}r=s,s=r.#o}}return this}push(...t){for(let r of t)if(r!==""){if(typeof r!="string"&&!(r instanceof $&&r.#o===this))throw new Error("invalid part: "+r);this.#i.push(r)}}toJSON(){let t=this.type===null?this.#i.slice().map(r=>typeof r=="string"?r:r.toJSON()):[this.type,...this.#i.map(r=>r.toJSON())];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===this.#t||this.#t.#u&&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 s=t.#i[r];if(!(s instanceof $&&s.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.#i.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 $(this.type,t);for(let s of this.#i)r.copyIn(s);return r}static#s(t,r,s,i){let n=!1,o=!1,a=-1,l=!1;if(r.type===null){let f=s,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(!i.noext&&qr(g)&&t.charAt(f)==="("){r.push(m),m="";let w=new $(g,r);f=$.#s(t,w,f,i),r.push(w);continue}m+=g}return r.push(m),f}let c=s+1,u=new $(null,r),h=[],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(qr(f)&&t.charAt(c)==="("){u.push(p),p="";let m=new $(f,u);u.push(m),c=$.#s(t,m,c,i);continue}if(f==="|"){u.push(p),p="",h.push(u),u=new $(null,r);continue}if(f===")")return p===""&&r.#i.length===0&&(r.#h=!0),u.push(p),p="",r.push(...h,u),c;p+=f}return r.type=null,r.#r=void 0,r.#i=[t.substring(s-1)],c}static fromGlob(t,r={}){let s=new $(null,void 0,r);return $.#s(t,s,0,r),s}toMMPattern(){if(this!==this.#t)return this.#t.toMMPattern();let t=this.toString(),[r,s,i,n]=this.toRegExpSource();if(!(i||this.#r||this.#a.nocase&&!this.#a.nocaseMagicOnly&&t.toUpperCase()!==t.toLowerCase()))return s;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.#i.some(p=>typeof p!="string"),c=this.#i.map(p=>{let[f,m,g,w]=typeof p=="string"?$.#_(p,this.#r,l):p.toRegExpSource(t);return this.#r=this.#r||g,this.#n=this.#n||w,f}).join(""),u="";if(this.isStart()&&typeof this.#i[0]=="string"&&!(this.#i.length===1&&no.has(this.#i[0]))){let p=io,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));u=f?so:m?fe:""}let h="";return this.isEnd()&&this.#t.#u&&this.#o?.type==="!"&&(h="(?:$|\\/)"),[u+c+h,Ft(c),this.#r=!!this.#r,this.#n]}let s=this.type==="*"||this.type==="+",i=this.type==="!"?"(?:(?!(?:":"(?:",n=this.#p(r);if(this.isStart()&&this.isEnd()&&!n&&this.type!=="!"){let l=this.toString();return this.#i=[l],this.type=null,this.#r=void 0,[l,Ft(this.toString()),!1,!1]}let o=!s||t||r||!fe?"":this.#p(!0);o===n&&(o=""),o&&(n=`(?:${n})(?:${o})*?`);let a="";if(this.type==="!"&&this.#h)a=(this.isStart()&&!r?fe:"")+Zr;else{let l=this.type==="!"?"))"+(this.isStart()&&!r&&!t?fe:"")+Qr+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;a=i+n+l}return[a,Ft(n),this.#r=!!this.#r,this.#n]}#p(t){return this.#i.map(r=>{if(typeof r=="string")throw new Error("string type in extglob ast??");let[s,i,n,o]=r.toRegExpSource(t);return this.#n=this.#n||o,s}).filter(r=>!(this.isStart()&&this.isEnd())||!!r).join("|")}static#_(t,r,s=!1){let i=!1,n="",o=!1,a=!1;for(let l=0;l<t.length;l++){let c=t.charAt(l);if(i){i=!1,n+=(oo.has(c)?"\\":"")+c;continue}if(c==="*"){if(a)continue;a=!0,n+=s&&/^[*]+$/.test(t)?Zr:Qr,r=!0;continue}else a=!1;if(c==="\\"){l===t.length-1?n+="\\\\":i=!0;continue}if(c==="["){let[u,h,p,f]=eo(t,l);if(p){n+=u,o=o||h,l+=p-1,r=r||f;continue}}if(c==="?"){n+=yr,r=!0;continue}n+=ao(c)}return[n,Ft(t),!!r,o]}},ks=(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)),lo=/^\*+([^+@!?\*\[\(]*)$/,co=e=>t=>!t.startsWith(".")&&t.endsWith(e),uo=e=>t=>t.endsWith(e),ho=e=>(e=e.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(e)),po=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),fo=/^\*+\.\*+$/,mo=e=>!e.startsWith(".")&&e.includes("."),go=e=>e!=="."&&e!==".."&&e.includes("."),So=/^\.\*+$/,Eo=e=>e!=="."&&e!==".."&&e.startsWith("."),wo=/^\*+$/,yo=e=>e.length!==0&&!e.startsWith("."),_o=e=>e.length!==0&&e!=="."&&e!=="..",vo=/^\?+([^+@!?\*\[\(]*)?$/,bo=([e,t=""])=>{let r=Ms([e]);return t?(t=t.toLowerCase(),s=>r(s)&&s.toLowerCase().endsWith(t)):r},To=([e,t=""])=>{let r=Rs([e]);return t?(t=t.toLowerCase(),s=>r(s)&&s.toLowerCase().endsWith(t)):r},ko=([e,t=""])=>{let r=Rs([e]);return t?s=>r(s)&&s.endsWith(t):r},Mo=([e,t=""])=>{let r=Ms([e]);return t?s=>r(s)&&s.endsWith(t):r},Ms=([e])=>{let t=e.length;return r=>r.length===t&&!r.startsWith(".")},Rs=([e])=>{let t=e.length;return r=>r.length===t&&r!=="."&&r!==".."},As=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",ts={win32:{sep:"\\"},posix:{sep:"/"}},Ro=As==="win32"?ts.win32.sep:ts.posix.sep;x.sep=Ro;var I=Symbol("globstar **");x.GLOBSTAR=I;var Ao="[^/]",Co=Ao+"*?",Oo="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",Do="(?:(?!(?:\\/|^)\\.).)*?",Po=(e,t={})=>r=>x(r,e,t);x.filter=Po;var H=(e,t={})=>Object.assign({},e,t),Io=e=>{if(!e||typeof e!="object"||!Object.keys(e).length)return x;let t=x;return Object.assign((r,s,i={})=>t(r,s,H(e,i)),{Minimatch:class extends t.Minimatch{constructor(r,s={}){super(r,H(e,s))}static defaults(r){return t.defaults(H(e,r)).Minimatch}},AST:class extends t.AST{constructor(r,s,i={}){super(r,s,H(e,i))}static fromGlob(r,s={}){return t.AST.fromGlob(r,H(e,s))}},unescape:(r,s={})=>t.unescape(r,H(e,s)),escape:(r,s={})=>t.escape(r,H(e,s)),filter:(r,s={})=>t.filter(r,H(e,s)),defaults:r=>t.defaults(H(e,r)),makeRe:(r,s={})=>t.makeRe(r,H(e,s)),braceExpand:(r,s={})=>t.braceExpand(r,H(e,s)),match:(r,s,i={})=>t.match(r,s,H(e,i)),sep:t.sep,GLOBSTAR:I})};x.defaults=Io;var Cs=(e,t={})=>(Te(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:Jn(e,{max:t.braceExpandMax}));x.braceExpand=Cs;var xo=(e,t={})=>new yt(e,t).makeRe();x.makeRe=xo;var Lo=(e,t,r={})=>{let s=new yt(t,r);return e=e.filter(i=>s.match(i)),s.options.nonull&&!e.length&&e.push(t),e};x.match=Lo;var es=/[?*]|[+@!]\(.*?\)|\[|\]/,No=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||As,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=(...i)=>console.error(...i)),this.debug(this.pattern,this.globSet);let r=this.globSet.map(i=>this.slashSplit(i));this.globParts=this.preprocess(r),this.debug(this.pattern,this.globParts);let s=this.globParts.map((i,n,o)=>{if(this.isWindows&&this.windowsNoMagicRoot){let a=i[0]===""&&i[1]===""&&(i[2]==="?"||!es.test(i[2]))&&!es.test(i[3]),l=/^[a-z]:/i.test(i[0]);if(a)return[...i.slice(0,4),...i.slice(4).map(c=>this.parse(c))];if(l)return[i[0],...i.slice(1).map(c=>this.parse(c))]}return i.map(a=>this.parse(a))});if(this.debug(this.pattern,s),this.set=s.filter(i=>i.indexOf(!1)===-1),this.isWindows)for(let i=0;i<this.set.length;i++){let n=this.set[i];n[0]===""&&n[1]===""&&this.globParts[i][2]==="?"&&typeof n[3]=="string"&&/^[a-z]:$/i.test(n[3])&&(n[2]="?")}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let r=0;r<e.length;r++)for(let s=0;s<e[r].length;s++)e[r][s]==="**"&&(e[r][s]="*");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 s=r;for(;t[s+1]==="**";)s++;s!==r&&t.splice(r,s-r)}return t})}levelOneOptimize(e){return e.map(t=>(t=t.reduce((r,s)=>{let i=r[r.length-1];return s==="**"&&i==="**"?r:s===".."&&i&&i!==".."&&i!=="."&&i!=="**"?(r.pop(),r):(r.push(s),r)},[]),t.length===0?[""]:t))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=!1;do{if(t=!1,!this.preserveMultipleSlashes){for(let s=1;s<e.length-1;s++){let i=e[s];s===1&&i===""&&e[0]===""||(i==="."||i==="")&&(t=!0,e.splice(s,1),s--)}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(t=!0,e.pop())}let r=0;for(;(r=e.indexOf("..",r+1))!==-1;){let s=e[r-1];s&&s!=="."&&s!==".."&&s!=="**"&&(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 s=-1;for(;(s=r.indexOf("**",s+1))!==-1;){let n=s;for(;r[n+1]==="**";)n++;n>s&&r.splice(s+1,n-s);let o=r[s+1],a=r[s+2],l=r[s+3];if(o!==".."||!a||a==="."||a===".."||!l||l==="."||l==="..")continue;t=!0,r.splice(s,1);let c=r.slice(0);c[s]="**",e.push(c),s--}if(!this.preserveMultipleSlashes){for(let n=1;n<r.length-1;n++){let o=r[n];n===1&&o===""&&r[0]===""||(o==="."||o==="")&&(t=!0,r.splice(n,1),n--)}r[0]==="."&&r.length===2&&(r[1]==="."||r[1]==="")&&(t=!0,r.pop())}let i=0;for(;(i=r.indexOf("..",i+1))!==-1;){let n=r[i-1];if(n&&n!=="."&&n!==".."&&n!=="**"){t=!0;let o=i===1&&r[i+1]==="**"?["."]:[];r.splice(i-1,2,...o),r.length===0&&r.push(""),i-=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 s=this.partsMatch(e[t],e[r],!this.preserveMultipleSlashes);if(s){e[t]=[],e[r]=s;break}}return e.filter(t=>t.length)}partsMatch(e,t,r=!1){let s=0,i=0,n=[],o="";for(;s<e.length&&i<t.length;)if(e[s]===t[i])n.push(o==="b"?t[i]:e[s]),s++,i++;else if(r&&e[s]==="**"&&t[i]===e[s+1])n.push(e[s]),s++;else if(r&&t[i]==="**"&&e[s]===t[i+1])n.push(t[i]),i++;else if(e[s]==="*"&&t[i]&&(this.options.dot||!t[i].startsWith("."))&&t[i]!=="**"){if(o==="b")return!1;o="a",n.push(e[s]),s++,i++}else if(t[i]==="*"&&e[s]&&(this.options.dot||!e[s].startsWith("."))&&e[s]!=="**"){if(o==="a")return!1;o="b",n.push(t[i]),s++,i++}else return!1;return e.length===t.length&&n}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=!1,r=0;for(let s=0;s<e.length&&e.charAt(s)==="!";s++)t=!t,r++;r&&(this.pattern=e.slice(r)),this.negate=t}matchOne(e,t,r=!1){let s=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,k]=[e[E],t[y]];v.toLowerCase()===k.toLowerCase()&&(t[y]=v,y>E?t=t.slice(y):E>y&&(e=e.slice(E)))}}let{optimizationLevel:i=1}=this.options;i>=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],u=e[n];if(this.debug(t,c,u),c===!1)return!1;if(c===I){this.debug("GLOBSTAR",[t,c,u]);var h=n,p=o+1;if(p===l){for(this.debug("** at the end");n<a;n++)if(e[n]==="."||e[n]===".."||!s.dot&&e[n].charAt(0)===".")return!1;return!0}for(;h<a;){var f=e[h];if(this.debug(`
|
|
13
11
|
globstar while`,e,h,t,p,f),this.matchOne(e.slice(h),t.slice(p),r))return this.debug("globstar found match!",h,a,f),!0;if(f==="."||f===".."||!s.dot&&f.charAt(0)==="."){this.debug("dot detected!",e,h,t,p);break}this.debug("globstar swallow a segment, and continue"),h++}return!!(r&&(this.debug(`
|
|
14
|
-
>>> no match, partial?`,e,h,t,p),h===a))}let m;if(typeof c=="string"?(m=u===c,this.debug("string match",c,u,m)):(m=c.test(u),this.debug("pattern match",c,u,m)),!m)return!1}if(n===a&&o===l)return!0;if(n===a)return r;if(o===l)return n===a-1&&e[n]==="";throw new Error("wtf?")}braceExpand(){return Ps(this.pattern,this.options)}parse(e){Te(e);let t=this.options;if(e==="**")return I;if(e==="")return"";let r,s=null;(r=e.match(_o))?s=t.dot?bo:vo:(r=e.match(uo))?s=(t.nocase?t.dot?mo:fo:t.dot?po:ho)(r[1]):(r=e.match(To))?s=(t.nocase?t.dot?Mo:ko:t.dot?Ro:Ao)(r):(r=e.match(go))?s=t.dot?Eo:So:(r=e.match(wo))&&(s=yo);let i=Rs.fromGlob(e,this.options).toMMPattern();return s&&typeof i=="object"&&Reflect.defineProperty(i,"test",{value:s}),i}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let t=this.options,r=t.noglobstar?Do:t.dot?Po:Io,s=new Set(t.nocase?["i"]:[]),i=e.map(a=>{let l=a.map(u=>{if(u instanceof RegExp)for(let h of u.flags.split(""))s.add(h);return typeof u=="string"?Uo(u):u===I?I:u._src});l.forEach((u,h)=>{let p=l[h+1],f=l[h-1];u!==I||f===I||(f===void 0?p!==void 0&&p!==I?l[h+1]="(?:\\/|"+r+"\\/)?"+p:l[h]=r:p===void 0?l[h-1]=f+"(?:\\/|\\/"+r+")?":p!==I&&(l[h-1]=f+"(?:\\/|\\/"+r+"\\/)"+p,l[h+1]=I))});let c=l.filter(u=>u!==I);if(this.partial&&c.length>=1){let u=[];for(let h=1;h<=c.length;h++)u.push(c.slice(0,h).join("/"));return"(?:"+u.join("|")+")"}return c.join("/")}).join("|"),[n,o]=e.length>1?["(?:",")"]:["",""];i="^"+n+i+o+"$",this.partial&&(i="^(?:\\/|"+n+i.slice(1,-1)+o+")$"),this.negate&&(i="^(?!"+i+").+$");try{this.regexp=new RegExp(i,[...s].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(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 s=this.slashSplit(e);this.debug(this.pattern,"split",s);let i=this.set;this.debug(this.pattern,"set",i);let n=s[s.length-1];if(!n)for(let o=s.length-2;!n&&o>=0;o--)n=s[o];for(let o=0;o<i.length;o++){let a=i[o],l=s;if(r.matchBase&&a.length===1&&(l=[n]),this.matchOne(l,a,t))return r.flipNegate?!0:!this.negate}return r.flipNegate?!1:this.negate}static defaults(e){return x.defaults(e).Minimatch}};x.AST=Rs;x.Minimatch=yt;x.escape=As;x.unescape=Ft;var Wo=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,xs=new Set,yr=typeof process=="object"&&process?process:{},Ls=(e,t,r,s)=>{typeof yr.emitWarning=="function"?yr.emitWarning(e,t,r,s):console.error(`[${r}] ${t}: ${e}`)},ke=globalThis.AbortController,ns=globalThis.AbortSignal;if(typeof ke>"u"){ns=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,s){this._onabort.push(s)}},ke=class{constructor(){t()}signal=new ns;abort(r){if(!this.signal.aborted){this.signal.reason=r,this.signal.aborted=!0;for(let s of this.signal._onabort)s(r);this.signal.onabort?.(r)}}};let e=yr.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{e&&(e=!1,Ls("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 $o=e=>!xs.has(e),wt=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),Ns=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)}},jo=class Zt{heap;length;static#t=!1;static create(t){let r=Ns(t);if(!r)return[];Zt.#t=!0;let s=new Zt(t,r);return Zt.#t=!1,s}constructor(t,r){if(!Zt.#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 Fs{#t;#r;#n;#i;#o;#y;#S;#u;get perf(){return this.#u}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#a;#d;#h;#l;#s;#p;#_;#w;#f;#A;#m;#T;#k;#g;#E;#v;#M;#e;#x;static unsafeExposeInternals(t){return{starts:t.#k,ttls:t.#g,autopurgeTimers:t.#E,sizes:t.#T,keyMap:t.#h,keyList:t.#l,valList:t.#s,next:t.#p,prev:t.#_,get head(){return t.#w},get tail(){return t.#f},free:t.#A,isBackgroundFetch:r=>t.#c(r),backgroundFetch:(r,s,i,n)=>t.#H(r,s,i,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.#i}get disposeAfter(){return this.#o}constructor(t){let{max:r=0,ttl:s,ttlResolution:i=1,ttlAutopurge:n,updateAgeOnGet:o,updateAgeOnHas:a,allowStale:l,dispose:c,onInsert:u,disposeAfter:h,noDisposeOnSet:p,noUpdateTTL:f,maxSize:m=0,maxEntrySize:g=0,sizeCalculation:w,fetchMethod:S,memoMethod:E,noDeleteOnFetchRejection:y,noDeleteOnStaleGet:v,allowStaleOnFetchRejection:k,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.#u=Dt??Wo,r!==0&&!wt(r))throw new TypeError("max option must be a nonnegative integer");let Pt=r?Ns(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.#M=!!S,this.#h=new Map,this.#l=new Array(r).fill(void 0),this.#s=new Array(r).fill(void 0),this.#p=new Pt(r),this.#_=new Pt(r),this.#w=0,this.#f=0,this.#A=jo.create(r),this.#a=0,this.#d=0,typeof c=="function"&&(this.#n=c),typeof u=="function"&&(this.#i=u),typeof h=="function"?(this.#o=h,this.#m=[]):(this.#o=void 0,this.#m=void 0),this.#v=!!this.#n,this.#x=!!this.#i,this.#e=!!this.#o,this.noDisposeOnSet=!!p,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!y,this.allowStaleOnFetchRejection=!!k,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(i)||i===0?i:1,this.ttlAutopurge=!!n,this.ttl=s||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 sr="LRU_CACHE_UNBOUNDED";$o(sr)&&(xs.add(sr),Ls("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",sr,Fs))}}getRemainingTTL(t){return this.#h.has(t)?1/0:0}#P(){let t=new ve(this.#t),r=new ve(this.#t);this.#g=t,this.#k=r;let s=this.ttlAutopurge?new Array(this.#t):void 0;this.#E=s,this.#U=(o,a,l=this.#u.now())=>{if(r[o]=a!==0?l:0,t[o]=a,s?.[o]&&(clearTimeout(s[o]),s[o]=void 0),a!==0&&s){let c=setTimeout(()=>{this.#b(o)&&this.#C(this.#l[o],"expire")},a+1);c.unref&&c.unref(),s[o]=c}},this.#R=o=>{r[o]=t[o]!==0?this.#u.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=i||n();let u=o.now-c;o.remainingTTL=l-u}};let i=0,n=()=>{let o=this.#u.now();if(this.ttlResolution>0){i=o;let a=setTimeout(()=>i=0,this.ttlResolution);a.unref&&a.unref()}return o};this.getRemainingTTL=o=>{let a=this.#h.get(o);if(a===void 0)return 0;let l=t[a],c=r[a];if(!l||!c)return 1/0;let u=(i||n())-c;return l-u},this.#b=o=>{let a=r[o],l=t[o];return!!l&&!!a&&(i||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,s,i,n)=>{if(this.#c(s))return 0;if(!wt(i))if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(i=n(s,r),!wt(i))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return i},this.#L=(r,s,i)=>{if(t[r]=s,this.#r){let n=this.#r-t[r];for(;this.#d>n;)this.#j(!0)}this.#d+=t[r],i&&(i.entrySize=s,i.totalCalculatedSize=this.#d)}}#F=t=>{};#L=(t,r,s)=>{};#W=(t,r,s,i)=>{if(s||i)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.#h.get(this.#l[t])===t}*entries(){for(let t of this.#O())this.#s[t]!==void 0&&this.#l[t]!==void 0&&!this.#c(this.#s[t])&&(yield[this.#l[t],this.#s[t]])}*rentries(){for(let t of this.#D())this.#s[t]!==void 0&&this.#l[t]!==void 0&&!this.#c(this.#s[t])&&(yield[this.#l[t],this.#s[t]])}*keys(){for(let t of this.#O()){let r=this.#l[t];r!==void 0&&!this.#c(this.#s[t])&&(yield r)}}*rkeys(){for(let t of this.#D()){let r=this.#l[t];r!==void 0&&!this.#c(this.#s[t])&&(yield r)}}*values(){for(let t of this.#O())this.#s[t]!==void 0&&!this.#c(this.#s[t])&&(yield this.#s[t])}*rvalues(){for(let t of this.#D())this.#s[t]!==void 0&&!this.#c(this.#s[t])&&(yield this.#s[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,r={}){for(let s of this.#O()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;if(n!==void 0&&t(n,this.#l[s],this))return this.get(this.#l[s],r)}}forEach(t,r=this){for(let s of this.#O()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;n!==void 0&&t.call(r,n,this.#l[s],this)}}rforEach(t,r=this){for(let s of this.#D()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;n!==void 0&&t.call(r,n,this.#l[s],this)}}purgeStale(){let t=!1;for(let r of this.#D({allowStale:!0}))this.#b(r)&&(this.#C(this.#l[r],"expire"),t=!0);return t}info(t){let r=this.#h.get(t);if(r===void 0)return;let s=this.#s[r],i=this.#c(s)?s.__staleWhileFetching:s;if(i===void 0)return;let n={value:i};if(this.#g&&this.#k){let o=this.#g[r],a=this.#k[r];if(o&&a){let l=o-(this.#u.now()-a);n.ttl=l,n.start=Date.now()}}return this.#T&&(n.size=this.#T[r]),n}dump(){let t=[];for(let r of this.#O({allowStale:!0})){let s=this.#l[r],i=this.#s[r],n=this.#c(i)?i.__staleWhileFetching:i;if(n===void 0||s===void 0)continue;let o={value:n};if(this.#g&&this.#k){o.ttl=this.#g[r];let a=this.#u.now()-this.#k[r];o.start=Math.floor(Date.now()-a)}this.#T&&(o.size=this.#T[r]),t.unshift([s,o])}return t}load(t){this.clear();for(let[r,s]of t){if(s.start){let i=Date.now()-s.start;s.start=this.#u.now()-i}this.set(r,s.value,s)}}set(t,r,s={}){if(r===void 0)return this.delete(t),this;let{ttl:i=this.ttl,start:n,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=s,{noUpdateTTL:c=this.noUpdateTTL}=s,u=this.#W(t,r,s.size||0,a);if(this.maxEntrySize&&u>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=!0),this.#C(t,"set"),this;let h=this.#a===0?void 0:this.#h.get(t);if(h===void 0)h=this.#a===0?this.#f:this.#A.length!==0?this.#A.pop():this.#a===this.#t?this.#j(!1):this.#a,this.#l[h]=t,this.#s[h]=r,this.#h.set(t,h),this.#p[this.#f]=h,this.#_[h]=this.#f,this.#f=h,this.#a++,this.#L(h,u,l),l&&(l.set="add"),c=!1,this.#x&&this.#i?.(r,t,"add");else{this.#N(h);let p=this.#s[h];if(r!==p){if(this.#M&&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(h),this.#L(h,u,l),this.#s[h]=r,l){l.set="replace";let f=p&&this.#c(p)?p.__staleWhileFetching:p;f!==void 0&&(l.oldValue=f)}}else l&&(l.set="update");this.#x&&this.onInsert?.(r,t,r===p?"update":"replace")}if(i!==0&&!this.#g&&this.#P(),this.#g&&(c||this.#U(h,i,n),l&&this.#I(l,h)),!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.#s[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,s=this.#l[r],i=this.#s[r];return this.#M&&this.#c(i)?i.__abortController.abort(new Error("evicted")):(this.#v||this.#e)&&(this.#v&&this.#n?.(i,s,"evict"),this.#e&&this.#m?.push([i,s,"evict"])),this.#F(r),this.#E?.[r]&&(clearTimeout(this.#E[r]),this.#E[r]=void 0),t&&(this.#l[r]=void 0,this.#s[r]=void 0,this.#A.push(r)),this.#a===1?(this.#w=this.#f=0,this.#A.length=0):this.#w=this.#p[r],this.#h.delete(s),this.#a--,r}has(t,r={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:i}=r,n=this.#h.get(t);if(n!==void 0){let o=this.#s[n];if(this.#c(o)&&o.__staleWhileFetching===void 0)return!1;if(this.#b(n))i&&(i.has="stale",this.#I(i,n));else return s&&this.#R(n),i&&(i.has="hit",this.#I(i,n)),!0}else i&&(i.has="miss");return!1}peek(t,r={}){let{allowStale:s=this.allowStale}=r,i=this.#h.get(t);if(i===void 0||!s&&this.#b(i))return;let n=this.#s[i];return this.#c(n)?n.__staleWhileFetching:n}#H(t,r,s,i){let n=r===void 0?void 0:this.#s[r];if(this.#c(n))return n;let o=new ke,{signal:a}=s;a?.addEventListener("abort",()=>o.abort(a.reason),{signal:o.signal});let l={signal:o.signal,options:s,context:i},c=(g,w=!1)=>{let{aborted:S}=o.signal,E=s.ignoreFetchAbort&&g!==void 0,y=s.ignoreFetchAbort||!!(s.allowStaleOnFetchAbort&&g!==void 0);if(s.status&&(S&&!w?(s.status.fetchAborted=!0,s.status.fetchError=o.signal.reason,E&&(s.status.fetchAbortIgnored=!0)):s.status.fetchResolved=!0),S&&!E&&!w)return h(o.signal.reason,y);let v=f,k=this.#s[r];return(k===f||E&&w&&k===void 0)&&(g===void 0?v.__staleWhileFetching!==void 0?this.#s[r]=v.__staleWhileFetching:this.#C(t,"fetch"):(s.status&&(s.status.fetchUpdated=!0),this.set(t,g,l.options))),g},u=g=>(s.status&&(s.status.fetchRejected=!0,s.status.fetchError=g),h(g,!1)),h=(g,w)=>{let{aborted:S}=o.signal,E=S&&s.allowStaleOnFetchAbort,y=E||s.allowStaleOnFetchRejection,v=y||s.noDeleteOnFetchRejection,k=f;if(this.#s[r]===f&&(!v||!w&&k.__staleWhileFetching===void 0?this.#C(t,"fetch"):E||(this.#s[r]=k.__staleWhileFetching)),y)return s.status&&k.__staleWhileFetching!==void 0&&(s.status.returnedStale=!0),k.__staleWhileFetching;if(k.__returned===k)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",()=>{(!s.ignoreFetchAbort||s.allowStaleOnFetchAbort)&&(g(void 0),s.allowStaleOnFetchAbort&&(g=E=>c(E,!0)))})};s.status&&(s.status.fetchDispatched=!0);let f=new Promise(p).then(c,u),m=Object.assign(f,{__abortController:o,__staleWhileFetching:n,__returned:void 0});return r===void 0?(this.set(t,m,{...l.options,status:void 0}),r=this.#h.get(t)):this.#s[r]=m,m}#c(t){if(!this.#M)return!1;let r=t;return!!r&&r instanceof Promise&&r.hasOwnProperty("__staleWhileFetching")&&r.__abortController instanceof ke}async fetch(t,r={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:l=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:h=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:p=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:m=this.allowStaleOnFetchAbort,context:g,forceRefresh:w=!1,status:S,signal:E}=r;if(!this.#M)return S&&(S.fetch="get"),this.get(t,{allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:n,status:S});let y={allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:n,ttl:o,noDisposeOnSet:a,size:l,sizeCalculation:c,noUpdateTTL:u,noDeleteOnFetchRejection:h,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:m,ignoreFetchAbort:f,status:S,signal:E},v=this.#h.get(t);if(v===void 0){S&&(S.fetch="miss");let k=this.#H(t,v,y,g);return k.__returned=k}else{let k=this.#s[v];if(this.#c(k)){let Pt=s&&k.__staleWhileFetching!==void 0;return S&&(S.fetch="inflight",Pt&&(S.returnedStale=!0)),Pt?k.__staleWhileFetching:k.__returned=k}let St=this.#b(v);if(!w&&!St)return S&&(S.fetch="hit"),this.#N(v),i&&this.#R(v),S&&this.#I(S,v),k;let Ot=this.#H(t,v,y,g),Dt=Ot.__staleWhileFetching!==void 0&&s;return S&&(S.fetch=St?"stale":"refresh",Dt&&St&&(S.returnedStale=!0)),Dt?Ot.__staleWhileFetching:Ot.__returned=Ot}}async forceFetch(t,r={}){let s=await this.fetch(t,r);if(s===void 0)throw new Error("fetch() returned undefined");return s}memo(t,r={}){let s=this.#S;if(!s)throw new Error("no memoMethod provided to constructor");let{context:i,forceRefresh:n,...o}=r,a=this.get(t,o);if(!n&&a!==void 0)return a;let l=s(t,a,{options:o,context:i});return this.set(t,l,o),l}get(t,r={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:o}=r,a=this.#h.get(t);if(a!==void 0){let l=this.#s[a],c=this.#c(l);return o&&this.#I(o,a),this.#b(a)?(o&&(o.get="stale"),c?(o&&s&&l.__staleWhileFetching!==void 0&&(o.returnedStale=!0),s?l.__staleWhileFetching:void 0):(n||this.#C(t,"expire"),o&&s&&(o.returnedStale=!0),s?l:void 0)):(o&&(o.get="hit"),c?l.__staleWhileFetching:(this.#N(a),i&&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.#C(t,"delete")}#C(t,r){let s=!1;if(this.#a!==0){let i=this.#h.get(t);if(i!==void 0)if(this.#E?.[i]&&(clearTimeout(this.#E?.[i]),this.#E[i]=void 0),s=!0,this.#a===1)this.#K(r);else{this.#F(i);let n=this.#s[i];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.#h.delete(t),this.#l[i]=void 0,this.#s[i]=void 0,i===this.#f)this.#f=this.#_[i];else if(i===this.#w)this.#w=this.#p[i];else{let o=this.#_[i];this.#p[o]=this.#p[i];let a=this.#p[i];this.#_[a]=this.#_[i]}this.#a--,this.#A.push(i)}}if(this.#e&&this.#m?.length){let i=this.#m,n;for(;n=i?.shift();)this.#o?.(...n)}return s}clear(){return this.#K("delete")}#K(t){for(let r of this.#D({allowStale:!0})){let s=this.#s[r];if(this.#c(s))s.__abortController.abort(new Error("deleted"));else{let i=this.#l[r];this.#v&&this.#n?.(s,i,t),this.#e&&this.#m?.push([s,i,t])}}if(this.#h.clear(),this.#s.fill(void 0),this.#l.fill(void 0),this.#g&&this.#k){this.#g.fill(0),this.#k.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.#A.length=0,this.#d=0,this.#a=0,this.#e&&this.#m){let r=this.#m,s;for(;s=r?.shift();)this.#o?.(...s)}}},os=typeof process=="object"&&process?process:{stdout:null,stderr:null},Go=e=>!!e&&typeof e=="object"&&(e instanceof Me||e instanceof br.default||Bo(e)||Ko(e)),Bo=e=>!!e&&typeof e=="object"&&e instanceof Ae.EventEmitter&&typeof e.pipe=="function"&&e.pipe!==br.default.Writable.prototype.pipe,Ko=e=>!!e&&typeof e=="object"&&e instanceof Ae.EventEmitter&&typeof e.write=="function"&&typeof e.end=="function",ct=Symbol("EOF"),ut=Symbol("maybeEmitEnd"),Et=Symbol("emittedEnd"),me=Symbol("emittingEnd"),Yt=Symbol("emittedError"),ge=Symbol("closed"),as=Symbol("read"),Se=Symbol("flush"),ls=Symbol("flushChunk"),Y=Symbol("encoding"),Lt=Symbol("decoder"),A=Symbol("flowing"),Jt=Symbol("paused"),Nt=Symbol("resume"),C=Symbol("buffer"),P=Symbol("pipes"),O=Symbol("bufferLength"),pr=Symbol("bufferPush"),Ee=Symbol("bufferShift"),D=Symbol("objectMode"),M=Symbol("destroyed"),fr=Symbol("error"),mr=Symbol("emitData"),cs=Symbol("emitEnd"),gr=Symbol("emitEnd2"),q=Symbol("async"),Sr=Symbol("abort"),we=Symbol("aborted"),Vt=Symbol("signal"),Tt=Symbol("dataListeners"),W=Symbol("discarded"),Xt=e=>Promise.resolve().then(e),zo=e=>e(),Yo=e=>e==="end"||e==="finish"||e==="prefinish",Jo=e=>e instanceof ArrayBuffer||!!e&&typeof e=="object"&&e.constructor&&e.constructor.name==="ArrayBuffer"&&e.byteLength>=0,Vo=e=>!Buffer.isBuffer(e)&&ArrayBuffer.isView(e),$s=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 $s{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(e,t,r){super(e,t,r),this.proxyErrors=s=>this.dest.emit("error",s),e.on("error",this.proxyErrors)}},qo=e=>!!e.objectMode,Qo=e=>!e.objectMode&&!!e.encoding&&e.encoding!=="buffer",Me=class extends Ae.EventEmitter{[A]=!1;[Jt]=!1;[P]=[];[C]=[];[D];[Y];[q];[Lt];[ct]=!1;[Et]=!1;[me]=!1;[ge]=!1;[Yt]=null;[O]=0;[M]=!1;[Vt];[we]=!1;[Tt]=0;[W]=!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");qo(t)?(this[D]=!0,this[Y]=null):Qo(t)?(this[Y]=t.encoding,this[D]=!1):(this[D]=!1,this[Y]=null),this[q]=!!t.async,this[Lt]=this[Y]?new Ws.StringDecoder(this[Y]):null,t&&t.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[C]}),t&&t.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[P]});let{signal:r}=t;r&&(this[Vt]=r,r.aborted?this[Sr]():r.addEventListener("abort",()=>this[Sr]()))}get bufferLength(){return this[O]}get encoding(){return this[Y]}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}[Sr](){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[ct])throw new Error("write after end");if(this[M])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof t=="function"&&(r=t,t="utf8"),t||(t="utf8");let s=this[q]?Xt:zo;if(!this[D]&&!Buffer.isBuffer(e)){if(Vo(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(Jo(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[A]&&this[O]!==0&&this[Se](!0),this[A]?this.emit("data",e):this[pr](e),this[O]!==0&&this.emit("readable"),r&&s(r),this[A]):e.length?(typeof e=="string"&&!(t===this[Y]&&!this[Lt]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[Y]&&(e=this[Lt].write(e)),this[A]&&this[O]!==0&&this[Se](!0),this[A]?this.emit("data",e):this[pr](e),this[O]!==0&&this.emit("readable"),r&&s(r),this[A]):(this[O]!==0&&this.emit("readable"),r&&s(r),this[A])}read(e){if(this[M])return null;if(this[W]=!1,this[O]===0||e===0||e&&e>this[O])return this[ut](),null;this[D]&&(e=null),this[C].length>1&&!this[D]&&(this[C]=[this[Y]?this[C].join(""):Buffer.concat(this[C],this[O])]);let t=this[as](e||null,this[C][0]);return this[ut](),t}[as](e,t){if(this[D])this[Ee]();else{let r=t;e===r.length||e===null?this[Ee]():typeof r=="string"?(this[C][0]=r.slice(e),t=r.slice(0,e),this[O]-=e):(this[C][0]=r.subarray(e),t=r.subarray(0,e),this[O]-=e)}return this.emit("data",t),!this[C].length&&!this[ct]&&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[ct]=!0,this.writable=!1,(this[A]||!this[Jt])&&this[ut](),this}[Nt](){this[M]||(!this[Tt]&&!this[P].length&&(this[W]=!0),this[Jt]=!1,this[A]=!0,this.emit("resume"),this[C].length?this[Se]():this[ct]?this[ut]():this.emit("drain"))}resume(){return this[Nt]()}pause(){this[A]=!1,this[Jt]=!0,this[W]=!1}get destroyed(){return this[M]}get flowing(){return this[A]}get paused(){return this[Jt]}[pr](e){this[D]?this[O]+=1:this[O]+=e.length,this[C].push(e)}[Ee](){return this[D]?this[O]-=1:this[O]-=this[C][0].length,this[C].shift()}[Se](e=!1){do;while(this[ls](this[Ee]())&&this[C].length);!e&&!this[C].length&&!this[ct]&&this.emit("drain")}[ls](e){return this.emit("data",e),this[A]}pipe(e,t){if(this[M])return e;this[W]=!1;let r=this[Et];return t=t||{},e===os.stdout||e===os.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 $s(this,e,t)),this[q]?Xt(()=>this[Nt]()):this[Nt]()),e}unpipe(e){let t=this[P].find(r=>r.dest===e);t&&(this[P].length===1?(this[A]&&this[Tt]===0&&(this[A]=!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[W]=!1,this[Tt]++,!this[P].length&&!this[A]&&this[Nt]();else if(e==="readable"&&this[O]!==0)super.emit("readable");else if(Yo(e)&&this[Et])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[Yt]){let s=t;this[q]?Xt(()=>s.call(this,this[Yt])):s.call(this,this[Yt])}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[W]&&!this[P].length&&(this[A]=!1)),r}removeAllListeners(e){let t=super.removeAllListeners(e);return(e==="data"||e===void 0)&&(this[Tt]=0,!this[W]&&!this[P].length&&(this[A]=!1)),t}get emittedEnd(){return this[Et]}[ut](){!this[me]&&!this[Et]&&!this[M]&&this[C].length===0&&this[ct]&&(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!==M&&this[M])return!1;if(e==="data")return!this[D]&&!r?!1:this[q]?(Xt(()=>this[mr](r)),!0):this[mr](r);if(e==="end")return this[cs]();if(e==="close"){if(this[ge]=!0,!this[Et]&&!this[M])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(e==="error"){this[Yt]=r,super.emit(fr,r);let i=!this[Vt]||this.listeners("error").length?super.emit("error",r):!1;return this[ut](),i}else if(e==="resume"){let i=super.emit("resume");return this[ut](),i}else if(e==="finish"||e==="prefinish"){let i=super.emit(e);return this.removeAllListeners(e),i}let s=super.emit(e,...t);return this[ut](),s}[mr](e){for(let r of this[P])r.dest.write(e)===!1&&this.pause();let t=this[W]?!1:super.emit("data",e);return this[ut](),t}[cs](){return this[Et]?!1:(this[Et]=!0,this.readable=!1,this[q]?(Xt(()=>this[gr]()),!0):this[gr]())}[gr](){if(this[Lt]){let t=this[Lt].end();if(t){for(let r of this[P])r.dest.write(t);this[W]||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[Y]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(M,()=>t(new Error("stream destroyed"))),this.on("error",r=>t(r)),this.on("end",()=>e())})}[Symbol.asyncIterator](){this[W]=!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[ct])return t();let s,i,n=c=>{this.off("data",o),this.off("end",a),this.off(M,l),t(),i(c)},o=c=>{this.off("error",n),this.off("end",a),this.off(M,l),this.pause(),s({value:c,done:!!this[ct]})},a=()=>{this.off("error",n),this.off("data",o),this.off(M,l),t(),s({done:!0,value:void 0})},l=()=>n(new Error("stream destroyed"));return new Promise((c,u)=>{i=u,s=c,this.once(M,l),this.once("error",n),this.once("end",a),this.once("data",o)})},throw:t,return:t,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[W]=!1;let e=!1,t=()=>(this.pause(),this.off(fr,t),this.off(M,t),this.off("end",t),e=!0,{done:!0,value:void 0}),r=()=>{if(e)return t();let s=this.read();return s===null?t():{done:!1,value:s}};return this.once("end",t),this.once(fr,t),this.once(M,t),{next:r,throw:t,return:t,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(e){if(this[M])return e?this.emit("error",e):this.emit(M),this;this[M]=!0,this[W]=!0,this[C].length=0,this[O]=0;let t=this;return typeof t.close=="function"&&!this[ge]&&t.close(),e?this.emit("error",e):this.emit(M),this}static get isStream(){return Go}},Zo=Z.realpathSync.native,te={lstatSync:Z.lstatSync,readdir:Z.readdir,readdirSync:Z.readdirSync,readlinkSync:Z.readlinkSync,realpathSync:Zo,promises:{lstat:_t.lstat,readdir:_t.readdir,readlink:_t.readlink,realpath:_t.realpath}},js=e=>!e||e===te||e===Ho?te:{...te,...e,promises:{...te.promises,...e.promises||{}}},Hs=/^\\\\\?\\([a-z]:)\\?$/i,ta=e=>e.replace(/\//g,"\\").replace(Hs,"$1\\"),ea=/[\\\/]/,B=0,Gs=1,Bs=2,Q=4,Ks=6,zs=8,kt=10,Ys=12,G=15,qt=~G,Er=16,us=32,ee=64,J=128,ye=256,be=512,hs=ee|J|be,ra=1023,wr=e=>e.isFile()?zs:e.isDirectory()?Q:e.isSymbolicLink()?kt:e.isCharacterDevice()?Bs:e.isBlockDevice()?Ks:e.isSocket()?Ys:e.isFIFO()?Gs:B,ds=new Re({max:2**12}),re=e=>{let t=ds.get(e);if(t)return t;let r=e.normalize("NFKD");return ds.set(e,r),r},ps=new Re({max:2**12}),_e=e=>{let t=ps.get(e);if(t)return t;let r=re(e.toLowerCase());return ps.set(e,r),r},fs=class extends Re{constructor(){super({max:256})}},sa=class extends Re{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1})}},Js=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}#i;get nlink(){return this.#i}#o;get uid(){return this.#o}#y;get gid(){return this.#y}#S;get rdev(){return this.#S}#u;get blksize(){return this.#u}#a;get ino(){return this.#a}#d;get size(){return this.#d}#h;get blocks(){return this.#h}#l;get atimeMs(){return this.#l}#s;get mtimeMs(){return this.#s}#p;get ctimeMs(){return this.#p}#_;get birthtimeMs(){return this.#_}#w;get atime(){return this.#w}#f;get mtime(){return this.#f}#A;get ctime(){return this.#A}#m;get birthtime(){return this.#m}#T;#k;#g;#E;#v;#M;#e;#x;#P;#R;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,t=B,r,s,i,n,o){this.name=e,this.#T=i?_e(e):re(e),this.#e=t&ra,this.nocase=i,this.roots=s,this.root=r||this,this.#x=n,this.#g=o.fullpath,this.#v=o.relative,this.#M=o.relativePosix,this.parent=o.parent,this.parent?this.#t=this.parent.#t:this.#t=js(o.fs)}depth(){return this.#k!==void 0?this.#k:this.parent?this.#k=this.parent.depth()+1:this.#k=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&=~Er,t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let r=this.children(),s=this.nocase?_e(e):re(e);for(let a of r)if(a.#T===s)return a;let i=this.parent?this.sep:"",n=this.#g?this.#g+i+e:void 0,o=this.newChild(e,B,{...t,parent:this,fullpath:n});return this.canReaddir()||(o.#e|=J),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.#M!==void 0)return this.#M;let e=this.name,t=this.parent;if(!t)return this.#M=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 s=this.fullpath().replace(/\\/g,"/");return/^[a-z]:\//i.test(s)?this.#E=`//?/${s}`:this.#E=s}let e=this.parent,t=e.fullpathPosix(),r=t+(!t||!e.parent?"":"/")+this.name;return this.#E=r}isUnknown(){return(this.#e&G)===B}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&G)===zs}isDirectory(){return(this.#e&G)===Q}isCharacterDevice(){return(this.#e&G)===Bs}isBlockDevice(){return(this.#e&G)===Ks}isFIFO(){return(this.#e&G)===Gs}isSocket(){return(this.#e&G)===Ys}isSymbolicLink(){return(this.#e&kt)===kt}lstatCached(){return this.#e&us?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&G;return!(e!==B&&e!==kt||this.#e&ye||this.#e&J)}calledReaddir(){return!!(this.#e&Er)}isENOENT(){return!!(this.#e&J)}isNamed(e){return this.nocase?this.#T===_e(e):this.#T===re(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|=Er;for(let t=e.provisional;t<e.length;t++){let r=e[t];r&&r.#b()}}#b(){this.#e&J||(this.#e=(this.#e|J)&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&ee)return;let e=this.#e;(e&G)===Q&&(e&=qt),this.#e=e|ee,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|=J),(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=wr(e),s=this.newChild(e.name,r,{parent:this}),i=s.#e&G;return i!==Q&&i!==kt&&i!==B&&(s.#e|=ee),t.unshift(s),t.provisional++,s}#H(e,t){for(let r=t.provisional;r<t.length;r++){let s=t[r];if((this.nocase?_e(e.name):re(e.name))===s.#T)return this.#c(e,s,r,t)}}#c(e,t,r,s){let i=t.name;return t.#e=t.#e&qt|wr(e),i!==e.name&&(t.name=e.name),r!==s.provisional&&(r===s.length-1?s.pop():s.splice(r,1),s.unshift(t)),s.provisional++,t}async lstat(){if((this.#e&J)===0)try{return this.#G(await this.#t.promises.lstat(this.fullpath())),this}catch(e){this.#O(e.code)}}lstatSync(){if((this.#e&J)===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:s,birthtimeMs:i,blksize:n,blocks:o,ctime:a,ctimeMs:l,dev:c,gid:u,ino:h,mode:p,mtime:f,mtimeMs:m,nlink:g,rdev:w,size:S,uid:E}=e;this.#w=t,this.#l=r,this.#m=s,this.#_=i,this.#u=n,this.#h=o,this.#A=a,this.#p=l,this.#r=c,this.#y=u,this.#a=h,this.#n=p,this.#f=f,this.#s=m,this.#i=g,this.#S=w,this.#d=S,this.#o=E;let y=wr(e);this.#e=this.#e&qt|y|us,y!==B&&y!==Q&&y!==kt&&(this.#e|=ee)}#N=[];#C=!1;#K(e){this.#C=!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 i=r.slice(0,r.provisional);t?e(null,i):queueMicrotask(()=>e(null,i));return}if(this.#N.push(e),this.#C)return;this.#C=!0;let s=this.fullpath();this.#t.readdir(s,{withFileTypes:!0},(i,n)=>{if(i)this.#W(i.code),r.provisional=0;else{for(let o of n)this.#$(o,r);this.#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(s=>r=s);try{for(let s of await this.#t.promises.readdir(t,{withFileTypes:!0}))this.#$(s,e);this.#U(e)}catch(s){this.#W(s.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&hs)return!1;let e=G&this.#e;return e===B||e===Q||e===kt}shouldWalk(e,t){return(this.#e&Q)===Q&&!(this.#e&hs)&&!e.has(this)&&(!t||t(this))}async realpath(){if(this.#R)return this.#R;if(!((be|ye|J)&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|J)&this.#e))try{let e=this.#t.realpathSync(this.fullpath());return this.#R=this.resolve(e)}catch{this.#F()}}[Js](e){if(e===this)return;e.isCWD=!1,this.isCWD=!0;let t=new Set([]),r=[],s=this;for(;s&&s.parent;)t.add(s),s.#v=r.join(this.sep),s.#M=r.join("/"),s=s.parent,r.push("..");for(s=e;s&&s.parent&&!t.has(s);)s.#v=void 0,s.#M=void 0,s=s.parent}},Vs=class Xs extends F{sep="\\";splitSep=ea;constructor(t,r=B,s,i,n,o,a){super(t,r,s,i,n,o,a)}newChild(t,r=B,s={}){return new Xs(t,r,this.root,this.roots,this.nocase,this.childrenCache(),s)}getRootString(t){return Ut.win32.parse(t).root}getRoot(t){if(t=ta(t.toUpperCase()),t===this.root.name)return this.root;for(let[r,s]of Object.entries(this.roots))if(this.sameRoot(t,r))return this.roots[t]=s;return this.roots[t]=new Tr(t,this).root}sameRoot(t,r=this.root.name){return t=t.toUpperCase().replace(/\//g,"\\").replace(Hs,"$1\\"),t===r}},qs=class Qs extends F{splitSep="/";sep="/";constructor(t,r=B,s,i,n,o,a){super(t,r,s,i,n,o,a)}getRootString(t){return t.startsWith("/")?"/":""}getRoot(t){return this.root}newChild(t,r=B,s={}){return new Qs(t,r,this.root,this.roots,this.nocase,this.childrenCache(),s)}},Zs=class{root;rootPath;roots;cwd;#t;#r;#n;nocase;#i;constructor(e=process.cwd(),t,r,{nocase:s,childrenCacheSize:i=16*1024,fs:n=te}={}){this.#i=js(n),(e instanceof URL||e.startsWith("file://"))&&(e=(0,Us.fileURLToPath)(e));let o=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(o),this.#t=new fs,this.#r=new fs,this.#n=new sa(i);let a=o.substring(this.rootPath.length).split(r);if(a.length===1&&!a[0]&&a.pop(),s===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=s,this.root=this.newRoot(this.#i),this.roots[this.rootPath]=this.root;let l=this.root,c=a.length-1,u=t.sep,h=this.rootPath,p=!1;for(let f of a){let m=c--;l=l.child(f,{relative:new Array(m).fill("..").join(u),relativePosix:new Array(m).fill("..").join("/"),fullpath:h+=(p?"":u)+f}),p=!0}this.cwd=l}depth(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return this.#n}resolve(...e){let t="";for(let i=e.length-1;i>=0;i--){let n=e[i];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 s=this.cwd.resolve(t).fullpath();return this.#t.set(t,s),s}resolvePosix(...e){let t="";for(let i=e.length-1;i>=0;i--){let n=e[i];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 s=this.cwd.resolve(t).fullpathPosix();return this.#r.set(t,s),s}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 s=await e.readdir();return r?s:s.map(i=>i.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(s=>s.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:s=!1,filter:i,walkFilter:n}=t,o=[];(!i||i(e))&&o.push(r?e:e.fullpath());let a=new Set,l=(u,h)=>{a.add(u),u.readdirCB((p,f)=>{if(p)return h(p);let m=f.length;if(!m)return h();let g=()=>{--m===0&&h()};for(let w of f)(!i||i(w))&&o.push(r?w:w.fullpath()),s&&w.isSymbolicLink()?w.realpath().then(S=>S?.isUnknown()?S.lstat():S).then(S=>S?.shouldWalk(a,n)?l(S,g):g()):w.shouldWalk(a,n)?l(w,g):g()},!0)},c=e;return new Promise((u,h)=>{l(c,p=>{if(p)return h(p);u(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:s=!1,filter:i,walkFilter:n}=t,o=[];(!i||i(e))&&o.push(r?e:e.fullpath());let a=new Set([e]);for(let l of a){let c=l.readdirSync();for(let u of c){(!i||i(u))&&o.push(r?u:u.fullpath());let h=u;if(u.isSymbolicLink()){if(!(s&&(h=u.realpathSync())))continue;h.isUnknown()&&h.lstatSync()}h.shouldWalk(a,n)&&a.add(h)}}return o}[Symbol.asyncIterator](){return this.iterate()}iterate(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:s=!1,filter:i,walkFilter:n}=t;(!i||i(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){(!i||i(c))&&(yield r?c:c.fullpath());let u=c;if(c.isSymbolicLink()){if(!(s&&(u=c.realpathSync())))continue;u.isUnknown()&&u.lstatSync()}u.shouldWalk(o,n)&&o.add(u)}}}stream(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:s=!1,filter:i,walkFilter:n}=t,o=new Me({objectMode:!0});(!i||i(e))&&o.write(r?e:e.fullpath());let a=new Set,l=[e],c=0,u=()=>{let h=!1;for(;!h;){let p=l.shift();if(!p){c===0&&o.end();return}c++,a.add(p);let f=(g,w,S=!1)=>{if(g)return o.emit("error",g);if(s&&!S){let E=[];for(let y of w)y.isSymbolicLink()&&E.push(y.realpath().then(v=>v?.isUnknown()?v.lstat():v));if(E.length){Promise.all(E).then(()=>f(null,w,!0));return}}for(let E of w)E&&(!i||i(E))&&(o.write(r?E:E.fullpath())||(h=!0));c--;for(let E of w){let y=E.realpathCached()||E;y.shouldWalk(a,n)&&l.push(y)}h&&!o.flowing?o.once("drain",u):m||u()},m=!0;p.readdirCB(f,!0),m=!1}};return u(),o}streamSync(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:s=!1,filter:i,walkFilter:n}=t,o=new Me({objectMode:!0}),a=new Set;(!i||i(e))&&o.write(r?e:e.fullpath());let l=[e],c=0,u=()=>{let h=!1;for(;!h;){let p=l.shift();if(!p){c===0&&o.end();return}c++,a.add(p);let f=p.readdirSync();for(let m of f)(!i||i(m))&&(o.write(r?m:m.fullpath())||(h=!0));c--;for(let m of f){let g=m;if(m.isSymbolicLink()){if(!(s&&(g=m.realpathSync())))continue;g.isUnknown()&&g.lstatSync()}g.shouldWalk(a,n)&&l.push(g)}}h&&!o.flowing&&o.once("drain",u)};return u(),o}chdir(e=this.cwd){let t=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[Js](t)}},Tr=class extends Zs{sep="\\";constructor(e=process.cwd(),t={}){let{nocase:r=!0}=t;super(e,Ut.win32,"\\",{...t,nocase:r}),this.nocase=r;for(let s=this.cwd;s;s=s.parent)s.nocase=this.nocase}parseRootPath(e){return Ut.win32.parse(e).root.toUpperCase()}newRoot(e){return new Vs(this.rootPath,Q,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")||e.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(e)}},kr=class extends Zs{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 qs(this.rootPath,Q,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}},ti=class extends kr{constructor(e=process.cwd(),t={}){let{nocase:r=!0}=t;super(e,{...t,nocase:r})}},Hl=process.platform==="win32"?Vs:qs,ia=process.platform==="win32"?Tr:process.platform==="darwin"?ti:kr,na=e=>e.length>=1,oa=e=>e.length>=1,aa=Symbol.for("nodejs.util.inspect.custom"),ei=class ri{#t;#r;#n;length;#i;#o;#y;#S;#u;#a;#d=!0;constructor(t,r,s,i){if(!na(t))throw new TypeError("empty pattern list");if(!oa(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,s<0||s>=this.length)throw new TypeError("index out of range");if(this.#t=t,this.#r=r,this.#n=s,this.#i=i,this.#n===0){if(this.isUNC()){let[n,o,a,l,...c]=this.#t,[u,h,p,f,...m]=this.#r;c[0]===""&&(c.shift(),m.shift());let g=[n,o,a,l,""].join("/"),w=[u,h,p,f,""].join("/");this.#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+"/",u=a+"/";this.#t=[c,...o],this.#r=[u,...l],this.length=this.#t.length}}}[aa](){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 ri(this.#t,this.#r,this.#n+1,this.#i),this.#o.#a=this.#a,this.#o.#u=this.#u,this.#o.#S=this.#S,this.#o):this.#o=null}isUNC(){let t=this.#t;return this.#u!==void 0?this.#u:this.#u=this.#i==="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.#i==="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)}},la=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",ms=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:t,nocase:r,noext:s,noglobstar:i,platform:n=la}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=n,this.mmopts={dot:!0,nobrace:t,nocase:r,noext:s,noglobstar:i,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 s=t.set[r],i=t.globParts[r];if(!s||!i)throw new Error("invalid pattern object");for(;s[0]==="."&&i[0]===".";)s.shift(),i.shift();let n=new ei(s,i,0,this.platform),o=new yt(n.globString(),this.mmopts),a=i[i.length-1]==="**",l=n.isAbsolute();l?this.absolute.push(o):this.relative.push(o),a&&(l?this.absoluteChildren.push(o):this.relativeChildren.push(o))}}ignored(e){let t=e.fullpath(),r=`${t}/`,s=e.relative()||".",i=`${s}/`;for(let n of this.relative)if(n.match(s)||n.match(i))return!0;for(let n of this.absolute)if(n.match(t)||n.match(r))return!0;return!1}childrenIgnored(e){let t=e.fullpath()+"/",r=(e.relative()||".")+"/";for(let s of this.relativeChildren)if(s.match(r))return!0;for(let s of this.absoluteChildren)if(s.match(t))return!0;return!1}},ca=class si{store;constructor(t=new Map){this.store=t}copy(){return new si(new Map(this.store))}hasWalked(t,r){return this.store.get(t.fullpath())?.has(r.globString())}storeWalked(t,r){let s=t.fullpath(),i=this.store.get(s);i?i.add(r.globString()):this.store.set(s,new Set([r.globString()]))}},ua=class{store=new Map;add(e,t,r){let s=(t?2:0)|(r?1:0),i=this.store.get(e);this.store.set(e,i===void 0?s:s&i)}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(s=>s.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())}},gs=class ii{hasWalkedCache;matches=new ua;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 ca}processPatterns(t,r){this.patterns=r;let s=r.map(i=>[t,i]);for(let[i,n]of s){this.hasWalkedCache.storeWalked(i,n);let o=n.root(),a=n.isAbsolute()&&this.opts.absolute!==!1;if(o){i=i.resolve(o==="/"&&this.opts.root!==void 0?this.opts.root:o);let h=n.rest();if(h)n=h;else{this.matches.add(i,!0,!1);continue}}if(i.isENOENT())continue;let l,c,u=!1;for(;typeof(l=n.pattern())=="string"&&(c=n.rest());)i=i.resolve(l),n=c,u=!0;if(l=n.pattern(),c=n.rest(),u){if(this.hasWalkedCache.hasWalked(i,n))continue;this.hasWalkedCache.storeWalked(i,n)}if(typeof l=="string"){let h=l===".."||l===""||l===".";this.matches.add(i.resolve(l),a,h);continue}else if(l===I){(!i.isSymbolicLink()||this.follow||n.checkFollowGlobstar())&&this.subwalks.add(i,n);let h=c?.pattern(),p=c?.rest();if(!c||(h===""||h===".")&&!p)this.matches.add(i,a,h===""||h===".");else if(h===".."){let f=i.parent||i;p?this.hasWalkedCache.hasWalked(f,p)||this.subwalks.add(f,p):this.matches.add(f,a,!0)}}else l instanceof RegExp&&this.subwalks.add(i,n)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new ii(this.opts,this.hasWalkedCache)}filterEntries(t,r){let s=this.subwalks.get(t),i=this.child();for(let n of r)for(let o of s){let a=o.isAbsolute(),l=o.pattern(),c=o.rest();l===I?i.testGlobstar(n,o,c,a):l instanceof RegExp?i.testRegExp(n,l,c,a):i.testString(n,l,c,a)}return i}testGlobstar(t,r,s,i){if((this.dot||!t.name.startsWith("."))&&(r.hasMore()||this.matches.add(t,i,!1),t.canReaddir()&&(this.follow||!t.isSymbolicLink()?this.subwalks.add(t,r):t.isSymbolicLink()&&(s&&r.checkFollowGlobstar()?this.subwalks.add(t,s):r.markFollowGlobstar()&&this.subwalks.add(t,r)))),s){let n=s.pattern();if(typeof n=="string"&&n!==".."&&n!==""&&n!==".")this.testString(t,n,s.rest(),i);else if(n===".."){let o=t.parent||t;this.subwalks.add(o,s)}else n instanceof RegExp&&this.testRegExp(t,n,s.rest(),i)}}testRegExp(t,r,s,i){r.test(t.name)&&(s?this.subwalks.add(t,s):this.matches.add(t,i,!1))}testString(t,r,s,i){t.isNamed(r)&&(s?this.subwalks.add(t,s):this.matches.add(t,i,!1))}},da=(e,t)=>typeof e=="string"?new ms([e],t):Array.isArray(e)?new ms(e,t):e,ni=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=da(r.ignore??[],r),!this.includeChildMatches&&typeof this.#r.add!="function")){let s="cannot ignore child matches, ignore lacks add() method.";throw new Error(s)}this.maxDepth=r.maxDepth||1/0,r.signal&&(this.signal=r.signal,this.signal.addEventListener("abort",()=>{this.#t.length=0}))}#i(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 s=e.isUnknown()||this.opts.stat?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let i=await s.realpath();i&&(i.isUnknown()||this.opts.stat)&&await i.lstat()}return this.matchCheckTest(s,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.#i(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 s=e.isUnknown()||this.opts.stat?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let i=s.realpathSync();i&&(i?.isUnknown()||this.opts.stat)&&i.lstatSync()}return this.matchCheckTest(s,t)}matchFinish(e,t){if(this.#i(e))return;if(!this.includeChildMatches&&this.#r?.add){let i=`${e.relativePosix()}/**`;this.#r.add(i)}let r=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(e);let s=this.opts.mark&&e.isDirectory()?this.#n:"";if(this.opts.withFileTypes)this.matchEmit(e);else if(r){let i=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(i+s)}else{let i=this.opts.posix?e.relativePosix():e.relative(),n=this.opts.dotRelative&&!i.startsWith(".."+this.#n)?"."+this.#n:"";this.matchEmit(i?n+i+s:"."+s)}}async match(e,t,r){let s=await this.matchCheck(e,r);s&&this.matchFinish(s,t)}matchSync(e,t,r){let s=this.matchCheckSync(e,r);s&&this.matchFinish(s,t)}walkCB(e,t,r){this.signal?.aborted&&r(),this.walkCB2(e,t,new gs(this.opts),r)}walkCB2(e,t,r,s){if(this.#o(e))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2(e,t,r,s));return}r.processPatterns(e,t);let i=1,n=()=>{--i===0&&s()};for(let[o,a,l]of r.matches.entries())this.#i(o)||(i++,this.match(o,a,l).then(()=>n()));for(let o of r.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;i++;let a=o.readdirCached();o.calledReaddir()?this.walkCB3(o,a,r,n):o.readdirCB((l,c)=>this.walkCB3(o,c,r,n),!0)}n()}walkCB3(e,t,r,s){r=r.filterEntries(e,t);let i=1,n=()=>{--i===0&&s()};for(let[o,a,l]of r.matches.entries())this.#i(o)||(i++,this.match(o,a,l).then(()=>n()));for(let[o,a]of r.subwalks.entries())i++,this.walkCB2(o,a,r.child(),n);n()}walkCBSync(e,t,r){this.signal?.aborted&&r(),this.walkCB2Sync(e,t,new gs(this.opts),r)}walkCB2Sync(e,t,r,s){if(this.#o(e))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2Sync(e,t,r,s));return}r.processPatterns(e,t);let i=1,n=()=>{--i===0&&s()};for(let[o,a,l]of r.matches.entries())this.#i(o)||this.matchSync(o,a,l);for(let o of r.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;i++;let a=o.readdirSync();this.walkCB3Sync(o,a,r,n)}n()}walkCB3Sync(e,t,r,s){r=r.filterEntries(e,t);let i=1,n=()=>{--i===0&&s()};for(let[o,a,l]of r.matches.entries())this.#i(o)||this.matchSync(o,a,l);for(let[o,a]of r.subwalks.entries())i++,this.walkCB2Sync(o,a,r.child(),n);n()}},Ss=class extends ni{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}},Es=class extends ni{results;constructor(e,t,r){super(e,t,r),this.results=new Me({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}},pa=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Mt=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,Is.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||pa,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"?Tr:t.platform==="darwin"?ti:t.platform?kr: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",s={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},i=this.pattern.map(a=>new yt(a,s)),[n,o]=i.reduce((a,l)=>(a[0].push(...l.set),a[1].push(...l.globParts),a),[[],[]]);this.patterns=n.map((a,l)=>{let c=o[l];if(!c)throw new Error("invalid pattern object");return new ei(a,c,0,this.platform)})}async walk(){return[...await new Ss(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 Ss(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 Es(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 Es(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()}},fa=(e,t={})=>{Array.isArray(e)||(e=[e]);for(let r of e)if(new yt(r,t).hasMagic())return!0;return!1};function Ce(e,t={}){return new Mt(e,t).streamSync()}function oi(e,t={}){return new Mt(e,t).stream()}function se(e,t={}){return new Mt(e,t).walkSync()}async function ws(e,t={}){return new Mt(e,t).walk()}function Oe(e,t={}){return new Mt(e,t).iterateSync()}function ai(e,t={}){return new Mt(e,t).iterate()}var ma=Ce,ga=Object.assign(oi,{sync:Ce}),Sa=Oe,Ea=Object.assign(ai,{sync:Oe}),wa=Object.assign(se,{stream:Ce,iterate:Oe}),ys=Object.assign(ws,{glob:ws,globSync:se,sync:wa,globStream:oi,stream:ga,globStreamSync:Ce,streamSync:ma,globIterate:ai,iterate:Ea,globIterateSync:Oe,iterateSync:Sa,Glob:Mt,hasMagic:fa,escape:As,unescape:Ft});ys.glob=ys;var ht=require("fs"),li=require("path");function ci(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 ui(e,t){try{let r=(0,li.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 oe=ot(require("path"),1);var jt=ot(require("path"),1),j=require("fs");var hi=require("node:child_process");function De(e,t,r){return(0,hi.spawn)(e,t??[],{windowsHide:!0,...r})}var K={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 dt(e){return process.platform==="win32"?Math.round(e*K.WINDOWS_MULTIPLIER):e}var et=require("fs"),ie=require("path"),Mr=require("os");var b=require("fs");var tt=require("path");var di=require("crypto");var ya=process.platform==="win32";function _a(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,tt.resolve)((0,tt.dirname)(e),c)}}catch(c){let u=c.code;if(u!=="ENOENT"&&u!=="ENOTDIR")throw c}_a((0,tt.dirname)(r));let s=(0,tt.dirname)(r),i=(0,tt.basename)(r),n=(0,tt.join)(s,`.${i}.${process.pid}.${(0,di.randomBytes)(6).toString("hex")}.tmp`),o=Buffer.from(JSON.stringify(t,null,2)+`
|
|
15
|
-
`,"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 u=(0,b.writeSync)(l,o,c,o.length-c);if(u===0)throw new Error(`writeSync stalled at ${c}/${o.length} bytes`);c+=u}if((0,b.fsyncSync)(l),(0,b.closeSync)(l),l=void 0,(0,b.renameSync)(n,r),!ya){let u;try{u=(0,b.openSync)(s,"r"),(0,b.fsyncSync)(u)}catch{}finally{if(u!==void 0)try{(0,b.closeSync)(u)}catch{}}}}catch(c){if(l!==void 0)try{(0,b.closeSync)(l)}catch{}try{(0,b.unlinkSync)(n)}catch{}throw c}}var rt=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(dt(K.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,ie.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:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,ie.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 s of Object.keys(this.DEFAULTS)){let i=this.envOverride(s);i!==void 0&&(r[s]=i)}return r}static loadFromFile(t,r=!0){try{if(!(0,et.existsSync)(t)){let a=this.getAllDefaults();try{let l=(0,ie.dirname)(t);(0,et.existsSync)(l)||(0,et.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 s=(0,et.readFileSync)(t,"utf-8"),i=JSON.parse(s.replace(/^\uFEFF/,"")),n=i;if(i.env&&typeof i.env=="object"){n=i.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(s){console.warn("[SETTINGS] Failed to load settings, using defaults:",t,s instanceof Error?s.message:String(s));let i=this.getAllDefaults();try{if((0,et.existsSync)(t)){let n=`${t}.corrupt-${Date.now()}`;(0,et.renameSync)(t,n),console.warn("[SETTINGS] Backed up corrupt settings file to:",n)}Pe(t,i),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(i):i}}};var Ie=null;function pt(){return Ie!==null||(Ie=rt.loadFromFile(ue)),Ie}var Rt=require("fs");var Dr=require("child_process");var st=require("fs"),Cr=ot(require("path"),1);var va=["CLAUDECODE_","CLAUDE_CODE_"],ba=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"]),Ta=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,s]of Object.entries(e))if(s!==void 0){if(Ta.has(r)){t[r]=s;continue}ba.has(r)||va.some(i=>r.startsWith(i))||(t[r]=s)}return t}var ka=5e3,Ma=1e3,Ra=R.supervisorRegistry();function ft(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(s=>!ft(s.pid)))return;await new Promise(s=>setTimeout(s,100))}}var Aa=5e3,pi=new Map;function Ca(e){let t=pi.get(e);if(t&&Date.now()-t.capturedAtMs<Aa)return t.token;let r=null;try{let s=(0,Dr.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(s.status===0){let i=s.stdout.trim();r=i.length>0?i:null}}catch(s){d.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:e,error:s instanceof Error?s.message:String(s)}),r=null}return pi.set(e,{token:r,capturedAtMs:Date.now()}),r}function fi(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 i=t.slice(r+2).split(" ")[19];return i&&/^\d+$/.test(i)?i: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,Dr.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 Pr(e){if(!e||!ft(e.pid))return!1;if(!e.startToken)return!0;let t=fi(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 Or=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(t=Ra){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 s=JSON.parse((0,st.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[i,n]of Object.entries(s))this.entries.set(i,n)}catch(r){r instanceof Error?d.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):d.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let t=this.pruneDeadEntries();t>0&&d.info("SYSTEM","Removed dead processes from supervisor registry",{removed:t}),this.persist()}register(t,r,s){this.initialize(),this.entries.set(t,r),s&&this.runtimeProcesses.set(t,s),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"&&Ar()}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 s=Date.parse(t.startedAt),i=Date.parse(r.startedAt);return(Number.isNaN(s)?0:s)-(Number.isNaN(i)?0:i)})}getBySession(t){let r=String(t);return this.getAll().filter(s=>s.sessionId!==void 0&&String(s.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[s,i]of this.entries)ft(i.pid)||(this.entries.delete(s),this.runtimeProcesses.delete(s),t+=1,i.type==="sdk"&&(r+=1));t>0&&this.persist();for(let s=0;s<r;s+=1)Ar();return t}async reapSession(t){this.initialize();let r=this.getBySession(t);if(r.length===0)return 0;let s=typeof t=="number"?t:Number(t)||void 0;d.info("SYSTEM",`Reaping ${r.length} process(es) for session ${t}`,{sessionId:s,pids:r.map(o=>o.pid)});let i=r.filter(o=>ft(o.pid));for(let o of i)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(i,ka);let n=i.filter(o=>ft(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:s});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=>ft(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"&&Ar();return d.info("SYSTEM",`Reaped ${r.length} process(es) for session ${t}`,{sessionId:s,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))}},Rr=null;function Ne(){return Rr||(Rr=new Or),Rr}var Oa=[];function Ar(){let e=Oa.shift();e&&e()}var gi=require("child_process"),Wt=require("fs"),Si=require("util");var Da=(0,Si.promisify)(gi.execFile),Pa=R.workerPid();async function Ei(e){let t=e.currentPid??process.pid,r=e.pidFilePath??Pa,s=e.registry.getAll(),i=[...s].filter(o=>o.pid!==t).sort((o,a)=>Date.parse(a.startedAt)-Date.parse(o.startedAt));for(let o of i){if(!ft(o.pid)){e.registry.unregister(o.id);continue}try{await mi(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(i,5e3);let n=i.filter(o=>ft(o.pid));for(let o of n)try{await mi(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 i)e.registry.unregister(o.id);for(let o of s.filter(a=>a.pid===t))e.registry.unregister(o.id);Ia(r,t),e.registry.pruneDeadEntries()}function Ia(e,t){if(!(0,Wt.existsSync)(e))return;let r=null;try{let s=JSON.parse((0,Wt.readFileSync)(e,"utf-8"));r=typeof s.pid=="number"?s.pid:null}catch(s){d.debug("SYSTEM","PID file unreadable during shutdown \u2014 leaving it (cannot prove ownership)",{pidFilePath:e,error:s instanceof Error?s.message:String(s)});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(s){s instanceof Error?d.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:e},s):d.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:e,error:String(s)})}}async function mi(e,t){let{pid:r,pgid:s}=e;if(process.platform!=="win32"){if(typeof s=="number")try{process.kill(-s,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 i=await xa();if(i){await new Promise((o,a)=>{i(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 Da("taskkill",n,{timeout:K.POWERSHELL_COMMAND,windowsHide:!0})}async function xa(){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 wi=3e4,$t=null;function La(){let t=Ne().pruneDeadEntries();t>0&&d.info("SYSTEM",`Health check: pruned ${t} dead process(es) from registry`)}function yi(){$t===null&&($t=setInterval(La,wi),$t.unref(),d.debug("SYSTEM","Health checker started",{intervalMs:wi}))}function _i(){$t!==null&&(clearInterval($t),$t=null,d.debug("SYSTEM","Health checker stopped"))}var Na=R.workerPid(),Ir=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,yi()}configureSignalHandlers(t){if(this.shutdownHandler=t,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async s=>{if(this.shutdownInitiated){d.warn("SYSTEM",`Received ${s} but shutdown already in progress`);return}this.shutdownInitiated=!0,d.info("SYSTEM",`Received ${s}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){i instanceof Error?d.error("SYSTEM","Error during shutdown",{},i):d.error("SYSTEM","Error during shutdown (non-Error)",{error:String(i)});try{await this.stop()}catch(n){n instanceof Error?d.debug("SYSTEM","Supervisor shutdown fallback failed",{},n):d.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(n)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{d.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}_i(),this.stopPromise=Ei({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,s){this.registry.register(t,r,s)}unregisterProcess(t){this.registry.unregister(t)}getRegistry(){return this.registry}},Yc=new Ir(Ne());function Fe(e={}){let t=e.pidFilePath??Na;if(!(0,Rt.existsSync)(t))return"missing";let r=null;try{r=JSON.parse((0,Rt.readFileSync)(t,"utf-8"))}catch(i){return i instanceof Error?d.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:t},i):d.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:t,error:String(i)}),(0,Rt.rmSync)(t,{force:!0}),"invalid"}return Pr(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 bi=ot(require("path"),1),Ti=require("os"),it=require("fs"),Lr=require("child_process");var Fa=require("node:sqlite");var au=R.dataDir(),lu=R.workerPid(),cu=R.workerPort();function vi(e){return e?/(^|[\\/])node(\.exe)?$/i.test(e.trim()):!1}function Wa(e,t){let r=t==="win32"?`where ${e}`:`which ${e}`,s;try{s=(0,Lr.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 s.split(/\r?\n/).map(n=>n.trim()).find(n=>n.length>0)||null}var xr;function ki(e={}){let t=Object.keys(e).length===0;if(t&&xr!==void 0)return xr;let r=$a(e);return t&&r!==null&&(xr=r),r}function $a(e){let t=e.platform??process.platform,r=e.execPath??process.execPath;if(vi(r))return r;let s=e.env??process.env,i=e.homeDirectory??(0,Ti.homedir)(),n=e.pathExists??it.existsSync,o=e.lookupInPath??Wa,a=t==="win32"?[s.NODE,bi.default.join(i,".nvm","current","bin","node.exe"),"node"]:[s.NODE,"/usr/local/bin/node","/opt/homebrew/bin/node","/usr/bin/node","node"];for(let l of a){let c=l?.trim();if(c&&(vi(c)&&n(c)||c.toLowerCase()==="node"))return c}return o("node",t)}var Mi=ot(require("path"),1);var Ri=require("fs");var ja=2500;async function Ha(e,t,r="GET"){let s=await fetch(`http://127.0.0.1:${e}${t}`,{method:r,signal:AbortSignal.timeout(ja)}),i="";try{i=await s.text()}catch{}return{ok:s.ok,statusCode:s.status,body:i}}function Ga(){try{let e=Mi.default.join(ce,"package.json");return JSON.parse((0,Ri.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 Ba(e){try{let t=await Ha(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 Ai(e){let t=Ga(),r=await Ba(e);return!r||t==="unknown"?{matches:!0,pluginVersion:t,workerVersion:r}:{matches:t===r,pluginVersion:t,workerVersion:r}}var Ue=require("path"),z=require("fs");var Ka=6e4;function Ci(){return(0,Ue.join)(ur(),"spawn.lock")}function Oi(){let e=Ci(),t=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return(0,z.mkdirSync)((0,Ue.dirname)(e),{recursive:!0}),(0,z.writeFileSync)(e,t,{flag:"wx"}),!0}catch(s){if(s?.code!=="EEXIST")return!0;if(r>0)return!1;let n;try{n=(0,z.statSync)(e).mtimeMs}catch{continue}if(Date.now()-n<=Ka)return!1;let o;try{o=(0,z.statSync)(e).mtimeMs}catch{continue}if(o!==n)return!1;try{(0,z.unlinkSync)(e)}catch{return!1}}return!1}function Di(){let e=Ci();try{if(JSON.parse((0,z.readFileSync)(e,"utf-8")).pid!==process.pid)return;(0,z.unlinkSync)(e)}catch{}}function Wr(e,t,r){let s=process.env[e];if(s){let i=parseInt(s,10);if(Number.isFinite(i)&&i>=r.min&&i<=r.max)return i;d.warn("SYSTEM",`Invalid ${e}, using default`,{value:s,min:r.min,max:r.max})}return t}var Be=Wr("CLAUDE_MEM_HEALTH_TIMEOUT_MS",dt(K.HEALTH_CHECK),{min:500,max:3e5}),Lu=Wr("CLAUDE_MEM_API_TIMEOUT_MS",dt(K.API_REQUEST),{min:500,max:3e5}),Li=Wr("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",dt(K.HOOK_READINESS_WAIT),{min:0,max:3e5}),za={min:500,max:3e5};async function $r(e,t={},r){try{return await fetch(e,{...t,signal:AbortSignal.timeout(r)})}catch(s){throw s instanceof DOMException&&s.name==="TimeoutError"?new Error(`Request timed out after ${r}ms`):s}}var We=null,$e=null,je=null,He=null;function Ya(){return jt.default.join(rt.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function Ja(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}function Va(){try{let e=R.workerPid();if(!(0,j.existsSync)(e))return null;let t=JSON.parse((0,j.readFileSync)(e,"utf-8"));return typeof t.pid!="number"||typeof t.port!="number"||!Ja(t.pid)?null:t.port}catch{return null}}function jr(){return je!==null||(je=rt.loadFromFile(Ya())),je}function Pi(e,t){if(!e)return null;let r=parseInt(e,10);return Number.isFinite(r)&&r>=t.min&&r<=t.max?r:null}function Xa(e,t,r){let s=process.env[e];if(s!==void 0){let o=Pi(s,r);return o!==null?o:(d.warn("SYSTEM",`Invalid ${e}, using default`,{value:s,min:r.min,max:r.max}),t)}let i=jr()[e],n=Pi(i,r);return n!==null?n:(d.warn("SYSTEM",`Invalid ${e} in settings.json, using default`,{value:i,min:r.min,max:r.max}),t)}function qa(){if(We!==null)return We;let e=jr();return We=parseInt(e.CLAUDE_MEM_WORKER_PORT,10),We}function Ni(){let e=Va();return e!==null?e:qa()}function Qa(){return $e!==null||($e=jr().CLAUDE_MEM_WORKER_HOST),$e}function Za(){return He!==null||(He=Xa("CLAUDE_MEM_API_TIMEOUT_MS",dt(K.API_REQUEST),za)),He}function tl(e){return`http://${Qa()}:${Ni()}${e}`}function mt(e,t={}){let r=t.method??"GET",s=t.timeoutMs??Za(),i=tl(e),n={method:r};return t.headers&&(n.headers=t.headers),t.body&&(n.body=t.body),s>0?$r(i,n,s):fetch(i,n)}async function el(){return(await mt("/api/health",{timeoutMs:Be})).ok}async function Ii(){return(await mt("/api/readiness",{timeoutMs:Be})).ok}function rl(){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,j.existsSync)(t))return t;return null}async function sl(e){let t=e.backoffMs;for(let r=1;r<=e.attempts;r++){if(await Ui())return!0;r<e.attempts&&(await new Promise(s=>setTimeout(s,t)),t*=2)}return!1}async function Nr(e=Li){if(e<=0)try{return await Ii()}catch{return!1}let t=Date.now();for(;Date.now()-t<e;){try{if(await Ii())return!0}catch(s){d.debug("SYSTEM","Worker readiness check threw",{error:s instanceof Error?s.message:String(s)})}let r=e-(Date.now()-t);if(r<=0)break;await new Promise(s=>setTimeout(s,Math.min(250,r)))}return!1}async function Fi(){try{let t=await(await mt("/api/health",{timeoutMs:Be})).json();return typeof t.version=="string"?t.version:null}catch{return null}}async function il(e,t=Li){let r=Date.now();for(;Date.now()-r<t;){if(await Fi()===e)return!0;let i=t-(Date.now()-r);if(i<=0)break;await new Promise(n=>setTimeout(n,Math.min(500,i)))}return!1}async function Fr(e){let t=await Fi();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 Ui(){let e;try{e=await el()}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 Ui()){let{matches:n,pluginVersion:o,workerVersion:a}=await Ai(Ni());if(o!=="unknown"&&(e=o),n)return await Nr()?(e!==null&&await Fr(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 il(o))return await Nr()?(e!==null&&await Fr(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=ki(),r=rl();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 s=Oi();try{if(s){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 sl({attempts:6,backoffMs:500}))return d.warn("SYSTEM",s?"Worker port did not open after lazy-spawn within the cold-boot wait (~15s)":"Spawn-lock holder's worker port did not open within the cold-boot wait (~15s)"),!1}finally{s&&Di()}return await Nr()?(e!==null&&await Fr(e),!0):(d.warn("SYSTEM","Worker lazy-spawned but did not become ready before hook readiness timeout"),!1)}var Ge=null;async function nl(){return Ge!==null||(Ge=await Ke()),Ge}var ol=3;function Wi(){return jt.default.join(T,"state")}function $i(){return jt.default.join(Wi(),"hook-failures.json")}function ji(){try{let e=(0,j.readFileSync)($i(),"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 Hi(e){let t=Wi(),r=$i(),s=`${r}.tmp`;try{(0,j.existsSync)(t)||(0,j.mkdirSync)(t,{recursive:!0}),(0,j.writeFileSync)(s,JSON.stringify(e),"utf-8"),(0,j.renameSync)(s,r)}catch(i){d.debug("SYSTEM","Failed to persist hook-failure counter",{error:i instanceof Error?i.message:String(i)})}}function al(){try{let t=pt().CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD,r=parseInt(t,10);if(Number.isFinite(r)&&r>=1)return r}catch{}return ol}async function ll(){let t={consecutiveFailures:ji().consecutiveFailures+1,lastFailureAt:Date.now()};Hi(t);let r=al();return t.consecutiveFailures>=r&&Jr(`keepmind worker unreachable for ${t.consecutiveFailures} consecutive hooks.`),t.consecutiveFailures}function xi(){ji().consecutiveFailures!==0&&Hi({consecutiveFailures:0,lastFailureAt:0})}var Ur=Symbol.for("claude-mem/worker-fallback");function ze(e){return typeof e=="object"&&e!==null&&e[Ur]===!0}async function Ye(e,t,r,s={}){if(!await nl())return await ll(),{continue:!0,reason:"worker_unreachable",[Ur]:!0};let n={method:t};r!==void 0&&(n.headers={"Content-Type":"application/json"},n.body=JSON.stringify(r)),s.timeoutMs!==void 0&&(n.timeoutMs=s.timeoutMs);let o=await mt(e,n);if(!o.ok){let l=await o.text().catch(()=>"");if(xi(),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}`,[Ur]:!0};let c=l;try{c=JSON.parse(l)}catch{}return c}xi();let a=await o.text();if(a.length!==0)try{return JSON.parse(a)}catch{return a}}var Bi=require("os"),Ki=ot(require("path"),1),zi=require("child_process");var Ve=require("fs"),Je=ot(require("path"),1);var ne={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function Gi(e){let t=Je.default.join(e,".git"),r;try{r=(0,Ve.statSync)(t)}catch(u){return u instanceof Error&&u.code!=="ENOENT"&&d.warn("GIT","Unexpected error checking .git",{error:u instanceof Error?u.message:String(u)}),ne}if(!r.isFile())return ne;let s;try{s=(0,Ve.readFileSync)(t,"utf-8").trim()}catch(u){return d.warn("GIT","Failed to read .git file",{error:u instanceof Error?u.message:String(u)}),ne}let i=s.match(/^gitdir:\s*(.+)$/);if(!i)return ne;let o=i[1].match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!o)return ne;let a=o[1],l=Je.default.basename(e),c=Je.default.basename(a);return{isWorktree:!0,worktreeName:l,parentRepoPath:a,parentProjectName:c}}function Yi(e){return e==="~"||e.startsWith("~/")?e.replace(/^~/,(0,Bi.homedir)()):e}function cl(e){try{return(0,zi.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function ul(e){if(!e||e.trim()==="")return d.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:e}),"unknown-project";let t=Yi(e),s=cl(t)??t,i=Ki.default.basename(s);if(i===""){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 i}function At(e){let t=ul(e);if(!e)return{primary:t,parent:null,isWorktree:!1,allProjects:[t]};let r=Yi(e),s=Gi(r);if(s.isWorktree&&s.parentProjectName){let i=`${s.parentProjectName}/${t}`;return{primary:i,parent:s.parentProjectName,isWorktree:!0,allProjects:[s.parentProjectName,i]}}return{primary:t,parent:null,isWorktree:!1,allProjects:[t]}}var Ct=require("path");var Ji=require("os"),Vi=require("path");function hl(e){let t=e.startsWith("~")?(0,Ji.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 Xe(e,t){if(!t||!t.trim())return!1;let r=e.replace(/\\/g,"/"),s=(0,Vi.basename)(r),i=t.split(",").map(n=>n.trim()).filter(Boolean);for(let n of i)try{let o=hl(n);if(o.test(r)||o.test(s))return!0}catch(o){d.warn("PROJECT_NAME","Invalid exclusion pattern",{pattern:n,error:o instanceof Error?o.message:String(o)});continue}return!1}function dl(e,t){let r=(0,Ct.normalize)(e),s=(0,Ct.normalize)(t);if(r===s)return!0;let i=(0,Ct.relative)(s,r);return i.length>0&&!i.startsWith("..")&&!(0,Ct.isAbsolute)(i)}function qe(e){if(process.env.CLAUDE_MEM_INTERNAL==="1")return!1;if(!e)return!0;if(dl(e,he))return!1;let t=pt();return!Xe(e,t.CLAUDE_MEM_EXCLUDED_PROJECTS)}var Xi="claude";function pl(e){return e.trim().toLowerCase().replace(/\s+/g,"-")}function nt(e){if(!e)return Xi;let t=pl(e);return t?t==="transcript"||t.includes("codex")?"codex":t.includes("cursor")?"cursor":t.includes("claude")?"claude":t:Xi}var Zi=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],qi=new RegExp(`<(${Zi.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g");var Qi=100;function fl(e){let t=Object.fromEntries(Zi.map(i=>[i,0]));qi.lastIndex=0;let r=0,s=e.replace(qi,(i,n)=>(t[n]=(t[n]??0)+1,r+=1,""));return r>Qi&&d.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:r,maxAllowed:Qi,contentLength:e.length}),{stripped:s.trim(),counts:t}}function Hr(e){return fl(e).stripped}var ml=["task-notification"],gl=new RegExp(`^\\s*<(${ml.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),Sl=256*1024;function tn(e){return!e||e.length>Sl?!1:gl.test(e)}var El=dt(K.API_REQUEST),gt=class extends Error{kind;status;cause;constructor(t,r,s={}){super(r),this.name="ServerClientError",this.kind=t,this.status=s.status??null,this.cause=s.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},Qe=class{baseUrl;apiKey;timeoutMs;constructor(t){this.baseUrl=wl(t.serverBaseUrl),this.apiKey=t.apiKey,this.timeoutMs=t.timeoutMs??El}async startSession(t){let r=this.buildStartSessionPayload(t);return this.request("POST","/v1/sessions/start",r)}async recordEvent(t){let r=this.buildEventPayload(t),s=t.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",s,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,s=t.kind??"manual",i=typeof t.metadata?.title=="string"?t.metadata.title:void 0;return{projectId:t.projectId,kind:s,type:s,narrative:r,...i?{title:i}:{},...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:Gr(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:Gr(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:Gr(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{}}}async request(t,r,s){if(!this.apiKey||!this.apiKey.trim())throw new gt("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let i=`${this.baseUrl}${r}`,n={method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};s!==void 0&&(n.body=JSON.stringify(s));let o;try{o=await $r(i,n,this.timeoutMs)}catch(l){let c=l instanceof Error?l.message:String(l),u=/timed out|timeout/i.test(c);throw new gt(u?"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}: ${yl(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 en(e){return e instanceof gt}function wl(e){return e.replace(/\/+$/,"")}function Gr(e){return typeof e=="string"?nt(e):null}function yl(e,t){return e.length<=t?e:`${e.slice(0,t)}\u2026`}function _l(){let t=(pt().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return t==="server"||t==="server-beta"?"server":"worker"}function vl(){let e=pt(),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),s=t(e.CLAUDE_MEM_SERVER_API_KEY,e.CLAUDE_MEM_SERVER_BETA_API_KEY),i=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(!s)return d.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!i)return d.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let n={serverBaseUrl:r,apiKey:s};return{runtime:"server",client:new Qe(n),projectId:i,serverBaseUrl:r}}function rn(){if(_l()!=="server")return{runtime:"worker"};let e=vl();return e||{runtime:"worker"}}function sn(e,t){d.warn("HOOK",`[server-fallback] reason=${e}`,t??{})}var bl={executeWithWorkerFallback:Ye,isWorkerFallback:ze,loadFromFileOnce:pt,resolveRuntimeContext:rn,logServerFallback:sn,shouldTrackProject:qe},bt=bl;var nn={async execute(e){let{sessionId:t,prompt:r}=e,s=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(s))return d.info("HOOK","Project excluded from tracking",{cwd:s}),{continue:!0,suppressOutput:!0};if(r&&tn(r))return d.debug("HOOK","session-init: skipping internal protocol payload",{preview:r.slice(0,80)}),{continue:!0,suppressOutput:!0};let i=!r||!r.trim()?"[media prompt]":r,n=At(s).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:i}}),d.info("HOOK","session-init: server session started",{contentSessionId:t,project:n}),{continue:!0,suppressOutput:!0}}catch(m){if(en(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 u=await bt.executeWithWorkerFallback("/api/sessions/init","POST",{contentSessionId:t,project:n,prompt:i,platformSource:o});if(bt.isWorkerFallback(u))return{continue:!0,suppressOutput:!0,exitCode:vt.SUCCESS};if(typeof u?.sessionDbId!="number")return d.failure("HOOK","Session initialization returned malformed response",{contentSessionId:t,project:n}),{continue:!0,suppressOutput:!0,exitCode:vt.SUCCESS};let h=u.sessionDbId,p=u.promptNumber;if(d.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:h,promptNumber:p,skipped:u.skipped,contextInjected:u.contextInjected}),d.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${t} | prompt#=${p} | sessionDbId=${h}`),u.skipped&&u.reason==="private")return d.info("HOOK",`INIT_COMPLETE | sessionDbId=${h} | promptNumber=${p} | skipped=true | reason=private`,{sessionId:h}),{continue:!0,suppressOutput:!0};let f="";if(l&&i&&i.length>=20&&i!=="[media prompt]"){let m=a.CLAUDE_MEM_SEMANTIC_INJECT_LIMIT||"5",g=await bt.executeWithWorkerFallback("/api/context/semantic","POST",{q:i,project:n,limit:m,platformSource:o});!bt.isWorkerFallback(g)&&g?.context&&(d.debug("HOOK",`Semantic injection: ${g.count} observations for prompt`,{sessionId:h,count:g.count}),f=g.context)}return d.info("HOOK",`INIT_COMPLETE | sessionDbId=${h} | promptNumber=${p} | project=${n}`,{sessionId:h}),f?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:f}}:{continue:!0,suppressOutput:!0}}};var on={async execute(e){let{sessionId:t,cwd:r,filePath:s,edits:i}=e,n=nt(e.platform);if(!s)throw new Error("fileEditHandler requires filePath");if(d.dataIn("HOOK",`FileEdit: ${s}`,{editCount:i?.length??0}),!r)throw new Error(`Missing cwd in FileEdit hook input for session ${t}, file ${s}`);if(!qe(r))return d.debug("HOOK","Project excluded from tracking, skipping file edit observation",{cwd:r,filePath:s}),{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:s,edits:i},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:s}),{continue:!0,suppressOutput:!0})}};var V=require("fs"),Ze=require("path");var Nh=R.settings();function an(e,t){let r="<claude-mem-context>",s="</claude-mem-context>";if(!e)return`${r}
|
|
12
|
+
>>> no match, partial?`,e,h,t,p),h===a))}let m;if(typeof c=="string"?(m=u===c,this.debug("string match",c,u,m)):(m=c.test(u),this.debug("pattern match",c,u,m)),!m)return!1}if(n===a&&o===l)return!0;if(n===a)return r;if(o===l)return n===a-1&&e[n]==="";throw new Error("wtf?")}braceExpand(){return Cs(this.pattern,this.options)}parse(e){Te(e);let t=this.options;if(e==="**")return I;if(e==="")return"";let r,s=null;(r=e.match(wo))?s=t.dot?_o:yo:(r=e.match(lo))?s=(t.nocase?t.dot?po:ho:t.dot?uo:co)(r[1]):(r=e.match(vo))?s=(t.nocase?t.dot?To:bo:t.dot?ko:Mo)(r):(r=e.match(fo))?s=t.dot?go:mo:(r=e.match(So))&&(s=Eo);let i=Ts.fromGlob(e,this.options).toMMPattern();return s&&typeof i=="object"&&Reflect.defineProperty(i,"test",{value:s}),i}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let t=this.options,r=t.noglobstar?Co:t.dot?Oo:Do,s=new Set(t.nocase?["i"]:[]),i=e.map(a=>{let l=a.map(u=>{if(u instanceof RegExp)for(let h of u.flags.split(""))s.add(h);return typeof u=="string"?No(u):u===I?I:u._src});l.forEach((u,h)=>{let p=l[h+1],f=l[h-1];u!==I||f===I||(f===void 0?p!==void 0&&p!==I?l[h+1]="(?:\\/|"+r+"\\/)?"+p:l[h]=r:p===void 0?l[h-1]=f+"(?:\\/|\\/"+r+")?":p!==I&&(l[h-1]=f+"(?:\\/|\\/"+r+"\\/)"+p,l[h+1]=I))});let c=l.filter(u=>u!==I);if(this.partial&&c.length>=1){let u=[];for(let h=1;h<=c.length;h++)u.push(c.slice(0,h).join("/"));return"(?:"+u.join("|")+")"}return c.join("/")}).join("|"),[n,o]=e.length>1?["(?:",")"]:["",""];i="^"+n+i+o+"$",this.partial&&(i="^(?:\\/|"+n+i.slice(1,-1)+o+")$"),this.negate&&(i="^(?!"+i+").+$");try{this.regexp=new RegExp(i,[...s].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(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 s=this.slashSplit(e);this.debug(this.pattern,"split",s);let i=this.set;this.debug(this.pattern,"set",i);let n=s[s.length-1];if(!n)for(let o=s.length-2;!n&&o>=0;o--)n=s[o];for(let o=0;o<i.length;o++){let a=i[o],l=s;if(r.matchBase&&a.length===1&&(l=[n]),this.matchOne(l,a,t))return r.flipNegate?!0:!this.negate}return r.flipNegate?!1:this.negate}static defaults(e){return x.defaults(e).Minimatch}};x.AST=Ts;x.Minimatch=yt;x.escape=ks;x.unescape=Ft;var Fo=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Ds=new Set,Er=typeof process=="object"&&process?process:{},Ps=(e,t,r,s)=>{typeof Er.emitWarning=="function"?Er.emitWarning(e,t,r,s):console.error(`[${r}] ${t}: ${e}`)},ke=globalThis.AbortController,rs=globalThis.AbortSignal;if(typeof ke>"u"){rs=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,s){this._onabort.push(s)}},ke=class{constructor(){t()}signal=new rs;abort(r){if(!this.signal.aborted){this.signal.reason=r,this.signal.aborted=!0;for(let s of this.signal._onabort)s(r);this.signal.onabort?.(r)}}};let e=Er.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{e&&(e=!1,Ps("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}var Uo=e=>!Ds.has(e),wt=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),Is=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)}},Wo=class te{heap;length;static#t=!1;static create(t){let r=Is(t);if(!r)return[];te.#t=!0;let s=new te(t,r);return te.#t=!1,s}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 xs{#t;#r;#n;#i;#o;#y;#S;#u;get perf(){return this.#u}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#a;#d;#h;#l;#s;#p;#_;#w;#f;#A;#m;#T;#k;#g;#E;#v;#M;#e;#x;static unsafeExposeInternals(t){return{starts:t.#k,ttls:t.#g,autopurgeTimers:t.#E,sizes:t.#T,keyMap:t.#h,keyList:t.#l,valList:t.#s,next:t.#p,prev:t.#_,get head(){return t.#w},get tail(){return t.#f},free:t.#A,isBackgroundFetch:r=>t.#c(r),backgroundFetch:(r,s,i,n)=>t.#H(r,s,i,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.#i}get disposeAfter(){return this.#o}constructor(t){let{max:r=0,ttl:s,ttlResolution:i=1,ttlAutopurge:n,updateAgeOnGet:o,updateAgeOnHas:a,allowStale:l,dispose:c,onInsert:u,disposeAfter:h,noDisposeOnSet:p,noUpdateTTL:f,maxSize:m=0,maxEntrySize:g=0,sizeCalculation:w,fetchMethod:S,memoMethod:E,noDeleteOnFetchRejection:y,noDeleteOnStaleGet:v,allowStaleOnFetchRejection:k,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.#u=Dt??Fo,r!==0&&!wt(r))throw new TypeError("max option must be a nonnegative integer");let Pt=r?Is(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.#M=!!S,this.#h=new Map,this.#l=new Array(r).fill(void 0),this.#s=new Array(r).fill(void 0),this.#p=new Pt(r),this.#_=new Pt(r),this.#w=0,this.#f=0,this.#A=Wo.create(r),this.#a=0,this.#d=0,typeof c=="function"&&(this.#n=c),typeof u=="function"&&(this.#i=u),typeof h=="function"?(this.#o=h,this.#m=[]):(this.#o=void 0,this.#m=void 0),this.#v=!!this.#n,this.#x=!!this.#i,this.#e=!!this.#o,this.noDisposeOnSet=!!p,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!y,this.allowStaleOnFetchRejection=!!k,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(i)||i===0?i:1,this.ttlAutopurge=!!n,this.ttl=s||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 sr="LRU_CACHE_UNBOUNDED";Uo(sr)&&(Ds.add(sr),Ps("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",sr,xs))}}getRemainingTTL(t){return this.#h.has(t)?1/0:0}#P(){let t=new ve(this.#t),r=new ve(this.#t);this.#g=t,this.#k=r;let s=this.ttlAutopurge?new Array(this.#t):void 0;this.#E=s,this.#U=(o,a,l=this.#u.now())=>{if(r[o]=a!==0?l:0,t[o]=a,s?.[o]&&(clearTimeout(s[o]),s[o]=void 0),a!==0&&s){let c=setTimeout(()=>{this.#b(o)&&this.#C(this.#l[o],"expire")},a+1);c.unref&&c.unref(),s[o]=c}},this.#R=o=>{r[o]=t[o]!==0?this.#u.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=i||n();let u=o.now-c;o.remainingTTL=l-u}};let i=0,n=()=>{let o=this.#u.now();if(this.ttlResolution>0){i=o;let a=setTimeout(()=>i=0,this.ttlResolution);a.unref&&a.unref()}return o};this.getRemainingTTL=o=>{let a=this.#h.get(o);if(a===void 0)return 0;let l=t[a],c=r[a];if(!l||!c)return 1/0;let u=(i||n())-c;return l-u},this.#b=o=>{let a=r[o],l=t[o];return!!l&&!!a&&(i||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,s,i,n)=>{if(this.#c(s))return 0;if(!wt(i))if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(i=n(s,r),!wt(i))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return i},this.#L=(r,s,i)=>{if(t[r]=s,this.#r){let n=this.#r-t[r];for(;this.#d>n;)this.#j(!0)}this.#d+=t[r],i&&(i.entrySize=s,i.totalCalculatedSize=this.#d)}}#F=t=>{};#L=(t,r,s)=>{};#W=(t,r,s,i)=>{if(s||i)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.#h.get(this.#l[t])===t}*entries(){for(let t of this.#O())this.#s[t]!==void 0&&this.#l[t]!==void 0&&!this.#c(this.#s[t])&&(yield[this.#l[t],this.#s[t]])}*rentries(){for(let t of this.#D())this.#s[t]!==void 0&&this.#l[t]!==void 0&&!this.#c(this.#s[t])&&(yield[this.#l[t],this.#s[t]])}*keys(){for(let t of this.#O()){let r=this.#l[t];r!==void 0&&!this.#c(this.#s[t])&&(yield r)}}*rkeys(){for(let t of this.#D()){let r=this.#l[t];r!==void 0&&!this.#c(this.#s[t])&&(yield r)}}*values(){for(let t of this.#O())this.#s[t]!==void 0&&!this.#c(this.#s[t])&&(yield this.#s[t])}*rvalues(){for(let t of this.#D())this.#s[t]!==void 0&&!this.#c(this.#s[t])&&(yield this.#s[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,r={}){for(let s of this.#O()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;if(n!==void 0&&t(n,this.#l[s],this))return this.get(this.#l[s],r)}}forEach(t,r=this){for(let s of this.#O()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;n!==void 0&&t.call(r,n,this.#l[s],this)}}rforEach(t,r=this){for(let s of this.#D()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;n!==void 0&&t.call(r,n,this.#l[s],this)}}purgeStale(){let t=!1;for(let r of this.#D({allowStale:!0}))this.#b(r)&&(this.#C(this.#l[r],"expire"),t=!0);return t}info(t){let r=this.#h.get(t);if(r===void 0)return;let s=this.#s[r],i=this.#c(s)?s.__staleWhileFetching:s;if(i===void 0)return;let n={value:i};if(this.#g&&this.#k){let o=this.#g[r],a=this.#k[r];if(o&&a){let l=o-(this.#u.now()-a);n.ttl=l,n.start=Date.now()}}return this.#T&&(n.size=this.#T[r]),n}dump(){let t=[];for(let r of this.#O({allowStale:!0})){let s=this.#l[r],i=this.#s[r],n=this.#c(i)?i.__staleWhileFetching:i;if(n===void 0||s===void 0)continue;let o={value:n};if(this.#g&&this.#k){o.ttl=this.#g[r];let a=this.#u.now()-this.#k[r];o.start=Math.floor(Date.now()-a)}this.#T&&(o.size=this.#T[r]),t.unshift([s,o])}return t}load(t){this.clear();for(let[r,s]of t){if(s.start){let i=Date.now()-s.start;s.start=this.#u.now()-i}this.set(r,s.value,s)}}set(t,r,s={}){if(r===void 0)return this.delete(t),this;let{ttl:i=this.ttl,start:n,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=s,{noUpdateTTL:c=this.noUpdateTTL}=s,u=this.#W(t,r,s.size||0,a);if(this.maxEntrySize&&u>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=!0),this.#C(t,"set"),this;let h=this.#a===0?void 0:this.#h.get(t);if(h===void 0)h=this.#a===0?this.#f:this.#A.length!==0?this.#A.pop():this.#a===this.#t?this.#j(!1):this.#a,this.#l[h]=t,this.#s[h]=r,this.#h.set(t,h),this.#p[this.#f]=h,this.#_[h]=this.#f,this.#f=h,this.#a++,this.#L(h,u,l),l&&(l.set="add"),c=!1,this.#x&&this.#i?.(r,t,"add");else{this.#N(h);let p=this.#s[h];if(r!==p){if(this.#M&&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(h),this.#L(h,u,l),this.#s[h]=r,l){l.set="replace";let f=p&&this.#c(p)?p.__staleWhileFetching:p;f!==void 0&&(l.oldValue=f)}}else l&&(l.set="update");this.#x&&this.onInsert?.(r,t,r===p?"update":"replace")}if(i!==0&&!this.#g&&this.#P(),this.#g&&(c||this.#U(h,i,n),l&&this.#I(l,h)),!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.#s[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,s=this.#l[r],i=this.#s[r];return this.#M&&this.#c(i)?i.__abortController.abort(new Error("evicted")):(this.#v||this.#e)&&(this.#v&&this.#n?.(i,s,"evict"),this.#e&&this.#m?.push([i,s,"evict"])),this.#F(r),this.#E?.[r]&&(clearTimeout(this.#E[r]),this.#E[r]=void 0),t&&(this.#l[r]=void 0,this.#s[r]=void 0,this.#A.push(r)),this.#a===1?(this.#w=this.#f=0,this.#A.length=0):this.#w=this.#p[r],this.#h.delete(s),this.#a--,r}has(t,r={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:i}=r,n=this.#h.get(t);if(n!==void 0){let o=this.#s[n];if(this.#c(o)&&o.__staleWhileFetching===void 0)return!1;if(this.#b(n))i&&(i.has="stale",this.#I(i,n));else return s&&this.#R(n),i&&(i.has="hit",this.#I(i,n)),!0}else i&&(i.has="miss");return!1}peek(t,r={}){let{allowStale:s=this.allowStale}=r,i=this.#h.get(t);if(i===void 0||!s&&this.#b(i))return;let n=this.#s[i];return this.#c(n)?n.__staleWhileFetching:n}#H(t,r,s,i){let n=r===void 0?void 0:this.#s[r];if(this.#c(n))return n;let o=new ke,{signal:a}=s;a?.addEventListener("abort",()=>o.abort(a.reason),{signal:o.signal});let l={signal:o.signal,options:s,context:i},c=(g,w=!1)=>{let{aborted:S}=o.signal,E=s.ignoreFetchAbort&&g!==void 0,y=s.ignoreFetchAbort||!!(s.allowStaleOnFetchAbort&&g!==void 0);if(s.status&&(S&&!w?(s.status.fetchAborted=!0,s.status.fetchError=o.signal.reason,E&&(s.status.fetchAbortIgnored=!0)):s.status.fetchResolved=!0),S&&!E&&!w)return h(o.signal.reason,y);let v=f,k=this.#s[r];return(k===f||E&&w&&k===void 0)&&(g===void 0?v.__staleWhileFetching!==void 0?this.#s[r]=v.__staleWhileFetching:this.#C(t,"fetch"):(s.status&&(s.status.fetchUpdated=!0),this.set(t,g,l.options))),g},u=g=>(s.status&&(s.status.fetchRejected=!0,s.status.fetchError=g),h(g,!1)),h=(g,w)=>{let{aborted:S}=o.signal,E=S&&s.allowStaleOnFetchAbort,y=E||s.allowStaleOnFetchRejection,v=y||s.noDeleteOnFetchRejection,k=f;if(this.#s[r]===f&&(!v||!w&&k.__staleWhileFetching===void 0?this.#C(t,"fetch"):E||(this.#s[r]=k.__staleWhileFetching)),y)return s.status&&k.__staleWhileFetching!==void 0&&(s.status.returnedStale=!0),k.__staleWhileFetching;if(k.__returned===k)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",()=>{(!s.ignoreFetchAbort||s.allowStaleOnFetchAbort)&&(g(void 0),s.allowStaleOnFetchAbort&&(g=E=>c(E,!0)))})};s.status&&(s.status.fetchDispatched=!0);let f=new Promise(p).then(c,u),m=Object.assign(f,{__abortController:o,__staleWhileFetching:n,__returned:void 0});return r===void 0?(this.set(t,m,{...l.options,status:void 0}),r=this.#h.get(t)):this.#s[r]=m,m}#c(t){if(!this.#M)return!1;let r=t;return!!r&&r instanceof Promise&&r.hasOwnProperty("__staleWhileFetching")&&r.__abortController instanceof ke}async fetch(t,r={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:l=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:h=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:p=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:m=this.allowStaleOnFetchAbort,context:g,forceRefresh:w=!1,status:S,signal:E}=r;if(!this.#M)return S&&(S.fetch="get"),this.get(t,{allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:n,status:S});let y={allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:n,ttl:o,noDisposeOnSet:a,size:l,sizeCalculation:c,noUpdateTTL:u,noDeleteOnFetchRejection:h,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:m,ignoreFetchAbort:f,status:S,signal:E},v=this.#h.get(t);if(v===void 0){S&&(S.fetch="miss");let k=this.#H(t,v,y,g);return k.__returned=k}else{let k=this.#s[v];if(this.#c(k)){let Pt=s&&k.__staleWhileFetching!==void 0;return S&&(S.fetch="inflight",Pt&&(S.returnedStale=!0)),Pt?k.__staleWhileFetching:k.__returned=k}let St=this.#b(v);if(!w&&!St)return S&&(S.fetch="hit"),this.#N(v),i&&this.#R(v),S&&this.#I(S,v),k;let Ot=this.#H(t,v,y,g),Dt=Ot.__staleWhileFetching!==void 0&&s;return S&&(S.fetch=St?"stale":"refresh",Dt&&St&&(S.returnedStale=!0)),Dt?Ot.__staleWhileFetching:Ot.__returned=Ot}}async forceFetch(t,r={}){let s=await this.fetch(t,r);if(s===void 0)throw new Error("fetch() returned undefined");return s}memo(t,r={}){let s=this.#S;if(!s)throw new Error("no memoMethod provided to constructor");let{context:i,forceRefresh:n,...o}=r,a=this.get(t,o);if(!n&&a!==void 0)return a;let l=s(t,a,{options:o,context:i});return this.set(t,l,o),l}get(t,r={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:o}=r,a=this.#h.get(t);if(a!==void 0){let l=this.#s[a],c=this.#c(l);return o&&this.#I(o,a),this.#b(a)?(o&&(o.get="stale"),c?(o&&s&&l.__staleWhileFetching!==void 0&&(o.returnedStale=!0),s?l.__staleWhileFetching:void 0):(n||this.#C(t,"expire"),o&&s&&(o.returnedStale=!0),s?l:void 0)):(o&&(o.get="hit"),c?l.__staleWhileFetching:(this.#N(a),i&&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.#C(t,"delete")}#C(t,r){let s=!1;if(this.#a!==0){let i=this.#h.get(t);if(i!==void 0)if(this.#E?.[i]&&(clearTimeout(this.#E?.[i]),this.#E[i]=void 0),s=!0,this.#a===1)this.#K(r);else{this.#F(i);let n=this.#s[i];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.#h.delete(t),this.#l[i]=void 0,this.#s[i]=void 0,i===this.#f)this.#f=this.#_[i];else if(i===this.#w)this.#w=this.#p[i];else{let o=this.#_[i];this.#p[o]=this.#p[i];let a=this.#p[i];this.#_[a]=this.#_[i]}this.#a--,this.#A.push(i)}}if(this.#e&&this.#m?.length){let i=this.#m,n;for(;n=i?.shift();)this.#o?.(...n)}return s}clear(){return this.#K("delete")}#K(t){for(let r of this.#D({allowStale:!0})){let s=this.#s[r];if(this.#c(s))s.__abortController.abort(new Error("deleted"));else{let i=this.#l[r];this.#v&&this.#n?.(s,i,t),this.#e&&this.#m?.push([s,i,t])}}if(this.#h.clear(),this.#s.fill(void 0),this.#l.fill(void 0),this.#g&&this.#k){this.#g.fill(0),this.#k.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.#A.length=0,this.#d=0,this.#a=0,this.#e&&this.#m){let r=this.#m,s;for(;s=r?.shift();)this.#o?.(...s)}}},ss=typeof process=="object"&&process?process:{stdout:null,stderr:null},jo=e=>!!e&&typeof e=="object"&&(e instanceof Me||e instanceof _r.default||Ho(e)||Go(e)),Ho=e=>!!e&&typeof e=="object"&&e instanceof Ae.EventEmitter&&typeof e.pipe=="function"&&e.pipe!==_r.default.Writable.prototype.pipe,Go=e=>!!e&&typeof e=="object"&&e instanceof Ae.EventEmitter&&typeof e.write=="function"&&typeof e.end=="function",ct=Symbol("EOF"),ut=Symbol("maybeEmitEnd"),Et=Symbol("emittedEnd"),me=Symbol("emittingEnd"),Jt=Symbol("emittedError"),ge=Symbol("closed"),is=Symbol("read"),Se=Symbol("flush"),ns=Symbol("flushChunk"),Y=Symbol("encoding"),Lt=Symbol("decoder"),A=Symbol("flowing"),Vt=Symbol("paused"),Nt=Symbol("resume"),C=Symbol("buffer"),P=Symbol("pipes"),O=Symbol("bufferLength"),hr=Symbol("bufferPush"),Ee=Symbol("bufferShift"),D=Symbol("objectMode"),M=Symbol("destroyed"),dr=Symbol("error"),pr=Symbol("emitData"),os=Symbol("emitEnd"),fr=Symbol("emitEnd2"),q=Symbol("async"),mr=Symbol("abort"),we=Symbol("aborted"),Xt=Symbol("signal"),Tt=Symbol("dataListeners"),W=Symbol("discarded"),qt=e=>Promise.resolve().then(e),Bo=e=>e(),Ko=e=>e==="end"||e==="finish"||e==="prefinish",zo=e=>e instanceof ArrayBuffer||!!e&&typeof e=="object"&&e.constructor&&e.constructor.name==="ArrayBuffer"&&e.byteLength>=0,Yo=e=>!Buffer.isBuffer(e)&&ArrayBuffer.isView(e),Fs=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()}},Jo=class extends Fs{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(e,t,r){super(e,t,r),this.proxyErrors=s=>this.dest.emit("error",s),e.on("error",this.proxyErrors)}},Vo=e=>!!e.objectMode,Xo=e=>!e.objectMode&&!!e.encoding&&e.encoding!=="buffer",Me=class extends Ae.EventEmitter{[A]=!1;[Vt]=!1;[P]=[];[C]=[];[D];[Y];[q];[Lt];[ct]=!1;[Et]=!1;[me]=!1;[ge]=!1;[Jt]=null;[O]=0;[M]=!1;[Xt];[we]=!1;[Tt]=0;[W]=!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[Y]=null):Xo(t)?(this[Y]=t.encoding,this[D]=!1):(this[D]=!1,this[Y]=null),this[q]=!!t.async,this[Lt]=this[Y]?new Ns.StringDecoder(this[Y]):null,t&&t.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[C]}),t&&t.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[P]});let{signal:r}=t;r&&(this[Xt]=r,r.aborted?this[mr]():r.addEventListener("abort",()=>this[mr]()))}get bufferLength(){return this[O]}get encoding(){return this[Y]}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}[mr](){this[we]=!0,this.emit("abort",this[Xt]?.reason),this.destroy(this[Xt]?.reason)}get aborted(){return this[we]}set aborted(e){}write(e,t,r){if(this[we])return!1;if(this[ct])throw new Error("write after end");if(this[M])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof t=="function"&&(r=t,t="utf8"),t||(t="utf8");let s=this[q]?qt:Bo;if(!this[D]&&!Buffer.isBuffer(e)){if(Yo(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(zo(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[A]&&this[O]!==0&&this[Se](!0),this[A]?this.emit("data",e):this[hr](e),this[O]!==0&&this.emit("readable"),r&&s(r),this[A]):e.length?(typeof e=="string"&&!(t===this[Y]&&!this[Lt]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[Y]&&(e=this[Lt].write(e)),this[A]&&this[O]!==0&&this[Se](!0),this[A]?this.emit("data",e):this[hr](e),this[O]!==0&&this.emit("readable"),r&&s(r),this[A]):(this[O]!==0&&this.emit("readable"),r&&s(r),this[A])}read(e){if(this[M])return null;if(this[W]=!1,this[O]===0||e===0||e&&e>this[O])return this[ut](),null;this[D]&&(e=null),this[C].length>1&&!this[D]&&(this[C]=[this[Y]?this[C].join(""):Buffer.concat(this[C],this[O])]);let t=this[is](e||null,this[C][0]);return this[ut](),t}[is](e,t){if(this[D])this[Ee]();else{let r=t;e===r.length||e===null?this[Ee]():typeof r=="string"?(this[C][0]=r.slice(e),t=r.slice(0,e),this[O]-=e):(this[C][0]=r.subarray(e),t=r.subarray(0,e),this[O]-=e)}return this.emit("data",t),!this[C].length&&!this[ct]&&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[ct]=!0,this.writable=!1,(this[A]||!this[Vt])&&this[ut](),this}[Nt](){this[M]||(!this[Tt]&&!this[P].length&&(this[W]=!0),this[Vt]=!1,this[A]=!0,this.emit("resume"),this[C].length?this[Se]():this[ct]?this[ut]():this.emit("drain"))}resume(){return this[Nt]()}pause(){this[A]=!1,this[Vt]=!0,this[W]=!1}get destroyed(){return this[M]}get flowing(){return this[A]}get paused(){return this[Vt]}[hr](e){this[D]?this[O]+=1:this[O]+=e.length,this[C].push(e)}[Ee](){return this[D]?this[O]-=1:this[O]-=this[C][0].length,this[C].shift()}[Se](e=!1){do;while(this[ns](this[Ee]())&&this[C].length);!e&&!this[C].length&&!this[ct]&&this.emit("drain")}[ns](e){return this.emit("data",e),this[A]}pipe(e,t){if(this[M])return e;this[W]=!1;let r=this[Et];return t=t||{},e===ss.stdout||e===ss.stderr?t.end=!1:t.end=t.end!==!1,t.proxyErrors=!!t.proxyErrors,r?t.end&&e.end():(this[P].push(t.proxyErrors?new Jo(this,e,t):new Fs(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[A]&&this[Tt]===0&&(this[A]=!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[W]=!1,this[Tt]++,!this[P].length&&!this[A]&&this[Nt]();else if(e==="readable"&&this[O]!==0)super.emit("readable");else if(Ko(e)&&this[Et])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[Jt]){let s=t;this[q]?qt(()=>s.call(this,this[Jt])):s.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[W]&&!this[P].length&&(this[A]=!1)),r}removeAllListeners(e){let t=super.removeAllListeners(e);return(e==="data"||e===void 0)&&(this[Tt]=0,!this[W]&&!this[P].length&&(this[A]=!1)),t}get emittedEnd(){return this[Et]}[ut](){!this[me]&&!this[Et]&&!this[M]&&this[C].length===0&&this[ct]&&(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!==M&&this[M])return!1;if(e==="data")return!this[D]&&!r?!1:this[q]?(qt(()=>this[pr](r)),!0):this[pr](r);if(e==="end")return this[os]();if(e==="close"){if(this[ge]=!0,!this[Et]&&!this[M])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(e==="error"){this[Jt]=r,super.emit(dr,r);let i=!this[Xt]||this.listeners("error").length?super.emit("error",r):!1;return this[ut](),i}else if(e==="resume"){let i=super.emit("resume");return this[ut](),i}else if(e==="finish"||e==="prefinish"){let i=super.emit(e);return this.removeAllListeners(e),i}let s=super.emit(e,...t);return this[ut](),s}[pr](e){for(let r of this[P])r.dest.write(e)===!1&&this.pause();let t=this[W]?!1:super.emit("data",e);return this[ut](),t}[os](){return this[Et]?!1:(this[Et]=!0,this.readable=!1,this[q]?(qt(()=>this[fr]()),!0):this[fr]())}[fr](){if(this[Lt]){let t=this[Lt].end();if(t){for(let r of this[P])r.dest.write(t);this[W]||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[Y]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(M,()=>t(new Error("stream destroyed"))),this.on("error",r=>t(r)),this.on("end",()=>e())})}[Symbol.asyncIterator](){this[W]=!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[ct])return t();let s,i,n=c=>{this.off("data",o),this.off("end",a),this.off(M,l),t(),i(c)},o=c=>{this.off("error",n),this.off("end",a),this.off(M,l),this.pause(),s({value:c,done:!!this[ct]})},a=()=>{this.off("error",n),this.off("data",o),this.off(M,l),t(),s({done:!0,value:void 0})},l=()=>n(new Error("stream destroyed"));return new Promise((c,u)=>{i=u,s=c,this.once(M,l),this.once("error",n),this.once("end",a),this.once("data",o)})},throw:t,return:t,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[W]=!1;let e=!1,t=()=>(this.pause(),this.off(dr,t),this.off(M,t),this.off("end",t),e=!0,{done:!0,value:void 0}),r=()=>{if(e)return t();let s=this.read();return s===null?t():{done:!1,value:s}};return this.once("end",t),this.once(dr,t),this.once(M,t),{next:r,throw:t,return:t,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(e){if(this[M])return e?this.emit("error",e):this.emit(M),this;this[M]=!0,this[W]=!0,this[C].length=0,this[O]=0;let t=this;return typeof t.close=="function"&&!this[ge]&&t.close(),e?this.emit("error",e):this.emit(M),this}static get isStream(){return jo}},qo=Z.realpathSync.native,ee={lstatSync:Z.lstatSync,readdir:Z.readdir,readdirSync:Z.readdirSync,readlinkSync:Z.readlinkSync,realpathSync:qo,promises:{lstat:_t.lstat,readdir:_t.readdir,readlink:_t.readlink,realpath:_t.realpath}},Us=e=>!e||e===ee||e===$o?ee:{...ee,...e,promises:{...ee.promises,...e.promises||{}}},Ws=/^\\\\\?\\([a-z]:)\\?$/i,Qo=e=>e.replace(/\//g,"\\").replace(Ws,"$1\\"),Zo=/[\\\/]/,B=0,$s=1,js=2,Q=4,Hs=6,Gs=8,kt=10,Bs=12,G=15,Qt=~G,gr=16,as=32,re=64,J=128,ye=256,be=512,ls=re|J|be,ta=1023,Sr=e=>e.isFile()?Gs:e.isDirectory()?Q:e.isSymbolicLink()?kt:e.isCharacterDevice()?js:e.isBlockDevice()?Hs:e.isSocket()?Bs:e.isFIFO()?$s:B,cs=new Re({max:2**12}),se=e=>{let t=cs.get(e);if(t)return t;let r=e.normalize("NFKD");return cs.set(e,r),r},us=new Re({max:2**12}),_e=e=>{let t=us.get(e);if(t)return t;let r=se(e.toLowerCase());return us.set(e,r),r},hs=class extends Re{constructor(){super({max:256})}},ea=class extends Re{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1})}},Ks=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}#i;get nlink(){return this.#i}#o;get uid(){return this.#o}#y;get gid(){return this.#y}#S;get rdev(){return this.#S}#u;get blksize(){return this.#u}#a;get ino(){return this.#a}#d;get size(){return this.#d}#h;get blocks(){return this.#h}#l;get atimeMs(){return this.#l}#s;get mtimeMs(){return this.#s}#p;get ctimeMs(){return this.#p}#_;get birthtimeMs(){return this.#_}#w;get atime(){return this.#w}#f;get mtime(){return this.#f}#A;get ctime(){return this.#A}#m;get birthtime(){return this.#m}#T;#k;#g;#E;#v;#M;#e;#x;#P;#R;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,t=B,r,s,i,n,o){this.name=e,this.#T=i?_e(e):se(e),this.#e=t&ta,this.nocase=i,this.roots=s,this.root=r||this,this.#x=n,this.#g=o.fullpath,this.#v=o.relative,this.#M=o.relativePosix,this.parent=o.parent,this.parent?this.#t=this.parent.#t:this.#t=Us(o.fs)}depth(){return this.#k!==void 0?this.#k:this.parent?this.#k=this.parent.depth()+1:this.#k=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&=~gr,t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let r=this.children(),s=this.nocase?_e(e):se(e);for(let a of r)if(a.#T===s)return a;let i=this.parent?this.sep:"",n=this.#g?this.#g+i+e:void 0,o=this.newChild(e,B,{...t,parent:this,fullpath:n});return this.canReaddir()||(o.#e|=J),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.#M!==void 0)return this.#M;let e=this.name,t=this.parent;if(!t)return this.#M=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 s=this.fullpath().replace(/\\/g,"/");return/^[a-z]:\//i.test(s)?this.#E=`//?/${s}`:this.#E=s}let e=this.parent,t=e.fullpathPosix(),r=t+(!t||!e.parent?"":"/")+this.name;return this.#E=r}isUnknown(){return(this.#e&G)===B}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&G)===Gs}isDirectory(){return(this.#e&G)===Q}isCharacterDevice(){return(this.#e&G)===js}isBlockDevice(){return(this.#e&G)===Hs}isFIFO(){return(this.#e&G)===$s}isSocket(){return(this.#e&G)===Bs}isSymbolicLink(){return(this.#e&kt)===kt}lstatCached(){return this.#e&as?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&G;return!(e!==B&&e!==kt||this.#e&ye||this.#e&J)}calledReaddir(){return!!(this.#e&gr)}isENOENT(){return!!(this.#e&J)}isNamed(e){return this.nocase?this.#T===_e(e):this.#T===se(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|=gr;for(let t=e.provisional;t<e.length;t++){let r=e[t];r&&r.#b()}}#b(){this.#e&J||(this.#e=(this.#e|J)&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&G)===Q&&(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|=J),(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=Sr(e),s=this.newChild(e.name,r,{parent:this}),i=s.#e&G;return i!==Q&&i!==kt&&i!==B&&(s.#e|=re),t.unshift(s),t.provisional++,s}#H(e,t){for(let r=t.provisional;r<t.length;r++){let s=t[r];if((this.nocase?_e(e.name):se(e.name))===s.#T)return this.#c(e,s,r,t)}}#c(e,t,r,s){let i=t.name;return t.#e=t.#e&Qt|Sr(e),i!==e.name&&(t.name=e.name),r!==s.provisional&&(r===s.length-1?s.pop():s.splice(r,1),s.unshift(t)),s.provisional++,t}async lstat(){if((this.#e&J)===0)try{return this.#G(await this.#t.promises.lstat(this.fullpath())),this}catch(e){this.#O(e.code)}}lstatSync(){if((this.#e&J)===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:s,birthtimeMs:i,blksize:n,blocks:o,ctime:a,ctimeMs:l,dev:c,gid:u,ino:h,mode:p,mtime:f,mtimeMs:m,nlink:g,rdev:w,size:S,uid:E}=e;this.#w=t,this.#l=r,this.#m=s,this.#_=i,this.#u=n,this.#h=o,this.#A=a,this.#p=l,this.#r=c,this.#y=u,this.#a=h,this.#n=p,this.#f=f,this.#s=m,this.#i=g,this.#S=w,this.#d=S,this.#o=E;let y=Sr(e);this.#e=this.#e&Qt|y|as,y!==B&&y!==Q&&y!==kt&&(this.#e|=re)}#N=[];#C=!1;#K(e){this.#C=!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 i=r.slice(0,r.provisional);t?e(null,i):queueMicrotask(()=>e(null,i));return}if(this.#N.push(e),this.#C)return;this.#C=!0;let s=this.fullpath();this.#t.readdir(s,{withFileTypes:!0},(i,n)=>{if(i)this.#W(i.code),r.provisional=0;else{for(let o of n)this.#$(o,r);this.#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(s=>r=s);try{for(let s of await this.#t.promises.readdir(t,{withFileTypes:!0}))this.#$(s,e);this.#U(e)}catch(s){this.#W(s.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&ls)return!1;let e=G&this.#e;return e===B||e===Q||e===kt}shouldWalk(e,t){return(this.#e&Q)===Q&&!(this.#e&ls)&&!e.has(this)&&(!t||t(this))}async realpath(){if(this.#R)return this.#R;if(!((be|ye|J)&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|J)&this.#e))try{let e=this.#t.realpathSync(this.fullpath());return this.#R=this.resolve(e)}catch{this.#F()}}[Ks](e){if(e===this)return;e.isCWD=!1,this.isCWD=!0;let t=new Set([]),r=[],s=this;for(;s&&s.parent;)t.add(s),s.#v=r.join(this.sep),s.#M=r.join("/"),s=s.parent,r.push("..");for(s=e;s&&s.parent&&!t.has(s);)s.#v=void 0,s.#M=void 0,s=s.parent}},zs=class Ys extends F{sep="\\";splitSep=Zo;constructor(t,r=B,s,i,n,o,a){super(t,r,s,i,n,o,a)}newChild(t,r=B,s={}){return new Ys(t,r,this.root,this.roots,this.nocase,this.childrenCache(),s)}getRootString(t){return Ut.win32.parse(t).root}getRoot(t){if(t=Qo(t.toUpperCase()),t===this.root.name)return this.root;for(let[r,s]of Object.entries(this.roots))if(this.sameRoot(t,r))return this.roots[t]=s;return this.roots[t]=new vr(t,this).root}sameRoot(t,r=this.root.name){return t=t.toUpperCase().replace(/\//g,"\\").replace(Ws,"$1\\"),t===r}},Js=class Vs extends F{splitSep="/";sep="/";constructor(t,r=B,s,i,n,o,a){super(t,r,s,i,n,o,a)}getRootString(t){return t.startsWith("/")?"/":""}getRoot(t){return this.root}newChild(t,r=B,s={}){return new Vs(t,r,this.root,this.roots,this.nocase,this.childrenCache(),s)}},Xs=class{root;rootPath;roots;cwd;#t;#r;#n;nocase;#i;constructor(e=process.cwd(),t,r,{nocase:s,childrenCacheSize:i=16*1024,fs:n=ee}={}){this.#i=Us(n),(e instanceof URL||e.startsWith("file://"))&&(e=(0,Ls.fileURLToPath)(e));let o=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(o),this.#t=new hs,this.#r=new hs,this.#n=new ea(i);let a=o.substring(this.rootPath.length).split(r);if(a.length===1&&!a[0]&&a.pop(),s===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=s,this.root=this.newRoot(this.#i),this.roots[this.rootPath]=this.root;let l=this.root,c=a.length-1,u=t.sep,h=this.rootPath,p=!1;for(let f of a){let m=c--;l=l.child(f,{relative:new Array(m).fill("..").join(u),relativePosix:new Array(m).fill("..").join("/"),fullpath:h+=(p?"":u)+f}),p=!0}this.cwd=l}depth(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return this.#n}resolve(...e){let t="";for(let i=e.length-1;i>=0;i--){let n=e[i];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 s=this.cwd.resolve(t).fullpath();return this.#t.set(t,s),s}resolvePosix(...e){let t="";for(let i=e.length-1;i>=0;i--){let n=e[i];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 s=this.cwd.resolve(t).fullpathPosix();return this.#r.set(t,s),s}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 s=await e.readdir();return r?s:s.map(i=>i.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(s=>s.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:s=!1,filter:i,walkFilter:n}=t,o=[];(!i||i(e))&&o.push(r?e:e.fullpath());let a=new Set,l=(u,h)=>{a.add(u),u.readdirCB((p,f)=>{if(p)return h(p);let m=f.length;if(!m)return h();let g=()=>{--m===0&&h()};for(let w of f)(!i||i(w))&&o.push(r?w:w.fullpath()),s&&w.isSymbolicLink()?w.realpath().then(S=>S?.isUnknown()?S.lstat():S).then(S=>S?.shouldWalk(a,n)?l(S,g):g()):w.shouldWalk(a,n)?l(w,g):g()},!0)},c=e;return new Promise((u,h)=>{l(c,p=>{if(p)return h(p);u(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:s=!1,filter:i,walkFilter:n}=t,o=[];(!i||i(e))&&o.push(r?e:e.fullpath());let a=new Set([e]);for(let l of a){let c=l.readdirSync();for(let u of c){(!i||i(u))&&o.push(r?u:u.fullpath());let h=u;if(u.isSymbolicLink()){if(!(s&&(h=u.realpathSync())))continue;h.isUnknown()&&h.lstatSync()}h.shouldWalk(a,n)&&a.add(h)}}return o}[Symbol.asyncIterator](){return this.iterate()}iterate(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:s=!1,filter:i,walkFilter:n}=t;(!i||i(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){(!i||i(c))&&(yield r?c:c.fullpath());let u=c;if(c.isSymbolicLink()){if(!(s&&(u=c.realpathSync())))continue;u.isUnknown()&&u.lstatSync()}u.shouldWalk(o,n)&&o.add(u)}}}stream(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:s=!1,filter:i,walkFilter:n}=t,o=new Me({objectMode:!0});(!i||i(e))&&o.write(r?e:e.fullpath());let a=new Set,l=[e],c=0,u=()=>{let h=!1;for(;!h;){let p=l.shift();if(!p){c===0&&o.end();return}c++,a.add(p);let f=(g,w,S=!1)=>{if(g)return o.emit("error",g);if(s&&!S){let E=[];for(let y of w)y.isSymbolicLink()&&E.push(y.realpath().then(v=>v?.isUnknown()?v.lstat():v));if(E.length){Promise.all(E).then(()=>f(null,w,!0));return}}for(let E of w)E&&(!i||i(E))&&(o.write(r?E:E.fullpath())||(h=!0));c--;for(let E of w){let y=E.realpathCached()||E;y.shouldWalk(a,n)&&l.push(y)}h&&!o.flowing?o.once("drain",u):m||u()},m=!0;p.readdirCB(f,!0),m=!1}};return u(),o}streamSync(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:s=!1,filter:i,walkFilter:n}=t,o=new Me({objectMode:!0}),a=new Set;(!i||i(e))&&o.write(r?e:e.fullpath());let l=[e],c=0,u=()=>{let h=!1;for(;!h;){let p=l.shift();if(!p){c===0&&o.end();return}c++,a.add(p);let f=p.readdirSync();for(let m of f)(!i||i(m))&&(o.write(r?m:m.fullpath())||(h=!0));c--;for(let m of f){let g=m;if(m.isSymbolicLink()){if(!(s&&(g=m.realpathSync())))continue;g.isUnknown()&&g.lstatSync()}g.shouldWalk(a,n)&&l.push(g)}}h&&!o.flowing&&o.once("drain",u)};return u(),o}chdir(e=this.cwd){let t=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[Ks](t)}},vr=class extends Xs{sep="\\";constructor(e=process.cwd(),t={}){let{nocase:r=!0}=t;super(e,Ut.win32,"\\",{...t,nocase:r}),this.nocase=r;for(let s=this.cwd;s;s=s.parent)s.nocase=this.nocase}parseRootPath(e){return Ut.win32.parse(e).root.toUpperCase()}newRoot(e){return new zs(this.rootPath,Q,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")||e.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(e)}},br=class extends Xs{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 Js(this.rootPath,Q,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}},qs=class extends br{constructor(e=process.cwd(),t={}){let{nocase:r=!0}=t;super(e,{...t,nocase:r})}},$l=process.platform==="win32"?zs:Js,ra=process.platform==="win32"?vr:process.platform==="darwin"?qs:br,sa=e=>e.length>=1,ia=e=>e.length>=1,na=Symbol.for("nodejs.util.inspect.custom"),Qs=class Zs{#t;#r;#n;length;#i;#o;#y;#S;#u;#a;#d=!0;constructor(t,r,s,i){if(!sa(t))throw new TypeError("empty pattern list");if(!ia(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,s<0||s>=this.length)throw new TypeError("index out of range");if(this.#t=t,this.#r=r,this.#n=s,this.#i=i,this.#n===0){if(this.isUNC()){let[n,o,a,l,...c]=this.#t,[u,h,p,f,...m]=this.#r;c[0]===""&&(c.shift(),m.shift());let g=[n,o,a,l,""].join("/"),w=[u,h,p,f,""].join("/");this.#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+"/",u=a+"/";this.#t=[c,...o],this.#r=[u,...l],this.length=this.#t.length}}}[na](){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 Zs(this.#t,this.#r,this.#n+1,this.#i),this.#o.#a=this.#a,this.#o.#u=this.#u,this.#o.#S=this.#S,this.#o):this.#o=null}isUNC(){let t=this.#t;return this.#u!==void 0?this.#u:this.#u=this.#i==="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.#i==="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)}},oa=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",ds=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:t,nocase:r,noext:s,noglobstar:i,platform:n=oa}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=n,this.mmopts={dot:!0,nobrace:t,nocase:r,noext:s,noglobstar:i,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 s=t.set[r],i=t.globParts[r];if(!s||!i)throw new Error("invalid pattern object");for(;s[0]==="."&&i[0]===".";)s.shift(),i.shift();let n=new Qs(s,i,0,this.platform),o=new yt(n.globString(),this.mmopts),a=i[i.length-1]==="**",l=n.isAbsolute();l?this.absolute.push(o):this.relative.push(o),a&&(l?this.absoluteChildren.push(o):this.relativeChildren.push(o))}}ignored(e){let t=e.fullpath(),r=`${t}/`,s=e.relative()||".",i=`${s}/`;for(let n of this.relative)if(n.match(s)||n.match(i))return!0;for(let n of this.absolute)if(n.match(t)||n.match(r))return!0;return!1}childrenIgnored(e){let t=e.fullpath()+"/",r=(e.relative()||".")+"/";for(let s of this.relativeChildren)if(s.match(r))return!0;for(let s of this.absoluteChildren)if(s.match(t))return!0;return!1}},aa=class ti{store;constructor(t=new Map){this.store=t}copy(){return new ti(new Map(this.store))}hasWalked(t,r){return this.store.get(t.fullpath())?.has(r.globString())}storeWalked(t,r){let s=t.fullpath(),i=this.store.get(s);i?i.add(r.globString()):this.store.set(s,new Set([r.globString()]))}},la=class{store=new Map;add(e,t,r){let s=(t?2:0)|(r?1:0),i=this.store.get(e);this.store.set(e,i===void 0?s:s&i)}entries(){return[...this.store.entries()].map(([e,t])=>[e,!!(t&2),!!(t&1)])}},ca=class{store=new Map;add(e,t){if(!e.canReaddir())return;let r=this.store.get(e);r?r.find(s=>s.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())}},ps=class ei{hasWalkedCache;matches=new la;subwalks=new ca;patterns;follow;dot;opts;constructor(t,r){this.opts=t,this.follow=!!t.follow,this.dot=!!t.dot,this.hasWalkedCache=r?r.copy():new aa}processPatterns(t,r){this.patterns=r;let s=r.map(i=>[t,i]);for(let[i,n]of s){this.hasWalkedCache.storeWalked(i,n);let o=n.root(),a=n.isAbsolute()&&this.opts.absolute!==!1;if(o){i=i.resolve(o==="/"&&this.opts.root!==void 0?this.opts.root:o);let h=n.rest();if(h)n=h;else{this.matches.add(i,!0,!1);continue}}if(i.isENOENT())continue;let l,c,u=!1;for(;typeof(l=n.pattern())=="string"&&(c=n.rest());)i=i.resolve(l),n=c,u=!0;if(l=n.pattern(),c=n.rest(),u){if(this.hasWalkedCache.hasWalked(i,n))continue;this.hasWalkedCache.storeWalked(i,n)}if(typeof l=="string"){let h=l===".."||l===""||l===".";this.matches.add(i.resolve(l),a,h);continue}else if(l===I){(!i.isSymbolicLink()||this.follow||n.checkFollowGlobstar())&&this.subwalks.add(i,n);let h=c?.pattern(),p=c?.rest();if(!c||(h===""||h===".")&&!p)this.matches.add(i,a,h===""||h===".");else if(h===".."){let f=i.parent||i;p?this.hasWalkedCache.hasWalked(f,p)||this.subwalks.add(f,p):this.matches.add(f,a,!0)}}else l instanceof RegExp&&this.subwalks.add(i,n)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new ei(this.opts,this.hasWalkedCache)}filterEntries(t,r){let s=this.subwalks.get(t),i=this.child();for(let n of r)for(let o of s){let a=o.isAbsolute(),l=o.pattern(),c=o.rest();l===I?i.testGlobstar(n,o,c,a):l instanceof RegExp?i.testRegExp(n,l,c,a):i.testString(n,l,c,a)}return i}testGlobstar(t,r,s,i){if((this.dot||!t.name.startsWith("."))&&(r.hasMore()||this.matches.add(t,i,!1),t.canReaddir()&&(this.follow||!t.isSymbolicLink()?this.subwalks.add(t,r):t.isSymbolicLink()&&(s&&r.checkFollowGlobstar()?this.subwalks.add(t,s):r.markFollowGlobstar()&&this.subwalks.add(t,r)))),s){let n=s.pattern();if(typeof n=="string"&&n!==".."&&n!==""&&n!==".")this.testString(t,n,s.rest(),i);else if(n===".."){let o=t.parent||t;this.subwalks.add(o,s)}else n instanceof RegExp&&this.testRegExp(t,n,s.rest(),i)}}testRegExp(t,r,s,i){r.test(t.name)&&(s?this.subwalks.add(t,s):this.matches.add(t,i,!1))}testString(t,r,s,i){t.isNamed(r)&&(s?this.subwalks.add(t,s):this.matches.add(t,i,!1))}},ua=(e,t)=>typeof e=="string"?new ds([e],t):Array.isArray(e)?new ds(e,t):e,ri=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 s="cannot ignore child matches, ignore lacks add() method.";throw new Error(s)}this.maxDepth=r.maxDepth||1/0,r.signal&&(this.signal=r.signal,this.signal.addEventListener("abort",()=>{this.#t.length=0}))}#i(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 s=e.isUnknown()||this.opts.stat?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let i=await s.realpath();i&&(i.isUnknown()||this.opts.stat)&&await i.lstat()}return this.matchCheckTest(s,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.#i(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 s=e.isUnknown()||this.opts.stat?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let i=s.realpathSync();i&&(i?.isUnknown()||this.opts.stat)&&i.lstatSync()}return this.matchCheckTest(s,t)}matchFinish(e,t){if(this.#i(e))return;if(!this.includeChildMatches&&this.#r?.add){let i=`${e.relativePosix()}/**`;this.#r.add(i)}let r=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(e);let s=this.opts.mark&&e.isDirectory()?this.#n:"";if(this.opts.withFileTypes)this.matchEmit(e);else if(r){let i=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(i+s)}else{let i=this.opts.posix?e.relativePosix():e.relative(),n=this.opts.dotRelative&&!i.startsWith(".."+this.#n)?"."+this.#n:"";this.matchEmit(i?n+i+s:"."+s)}}async match(e,t,r){let s=await this.matchCheck(e,r);s&&this.matchFinish(s,t)}matchSync(e,t,r){let s=this.matchCheckSync(e,r);s&&this.matchFinish(s,t)}walkCB(e,t,r){this.signal?.aborted&&r(),this.walkCB2(e,t,new ps(this.opts),r)}walkCB2(e,t,r,s){if(this.#o(e))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2(e,t,r,s));return}r.processPatterns(e,t);let i=1,n=()=>{--i===0&&s()};for(let[o,a,l]of r.matches.entries())this.#i(o)||(i++,this.match(o,a,l).then(()=>n()));for(let o of r.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;i++;let a=o.readdirCached();o.calledReaddir()?this.walkCB3(o,a,r,n):o.readdirCB((l,c)=>this.walkCB3(o,c,r,n),!0)}n()}walkCB3(e,t,r,s){r=r.filterEntries(e,t);let i=1,n=()=>{--i===0&&s()};for(let[o,a,l]of r.matches.entries())this.#i(o)||(i++,this.match(o,a,l).then(()=>n()));for(let[o,a]of r.subwalks.entries())i++,this.walkCB2(o,a,r.child(),n);n()}walkCBSync(e,t,r){this.signal?.aborted&&r(),this.walkCB2Sync(e,t,new ps(this.opts),r)}walkCB2Sync(e,t,r,s){if(this.#o(e))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2Sync(e,t,r,s));return}r.processPatterns(e,t);let i=1,n=()=>{--i===0&&s()};for(let[o,a,l]of r.matches.entries())this.#i(o)||this.matchSync(o,a,l);for(let o of r.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;i++;let a=o.readdirSync();this.walkCB3Sync(o,a,r,n)}n()}walkCB3Sync(e,t,r,s){r=r.filterEntries(e,t);let i=1,n=()=>{--i===0&&s()};for(let[o,a,l]of r.matches.entries())this.#i(o)||this.matchSync(o,a,l);for(let[o,a]of r.subwalks.entries())i++,this.walkCB2Sync(o,a,r.child(),n);n()}},fs=class extends ri{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}},ms=class extends ri{results;constructor(e,t,r){super(e,t,r),this.results=new Me({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}},ha=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Mt=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,Os.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||ha,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"?vr:t.platform==="darwin"?qs:t.platform?br:ra;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",s={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},i=this.pattern.map(a=>new yt(a,s)),[n,o]=i.reduce((a,l)=>(a[0].push(...l.set),a[1].push(...l.globParts),a),[[],[]]);this.patterns=n.map((a,l)=>{let c=o[l];if(!c)throw new Error("invalid pattern object");return new Qs(a,c,0,this.platform)})}async walk(){return[...await new fs(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 fs(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 ms(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new ms(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}},da=(e,t={})=>{Array.isArray(e)||(e=[e]);for(let r of e)if(new yt(r,t).hasMagic())return!0;return!1};function Ce(e,t={}){return new Mt(e,t).streamSync()}function si(e,t={}){return new Mt(e,t).stream()}function ie(e,t={}){return new Mt(e,t).walkSync()}async function gs(e,t={}){return new Mt(e,t).walk()}function Oe(e,t={}){return new Mt(e,t).iterateSync()}function ii(e,t={}){return new Mt(e,t).iterate()}var pa=Ce,fa=Object.assign(si,{sync:Ce}),ma=Oe,ga=Object.assign(ii,{sync:Oe}),Sa=Object.assign(ie,{stream:Ce,iterate:Oe}),Ss=Object.assign(gs,{glob:gs,globSync:ie,sync:Sa,globStream:si,stream:fa,globStreamSync:Ce,streamSync:pa,globIterate:ii,iterate:ga,globIterateSync:Oe,iterateSync:ma,Glob:Mt,hasMagic:da,escape:ks,unescape:Ft});Ss.glob=Ss;var ht=require("fs"),ni=require("path");function oi(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 ai(e,t){try{let r=(0,ni.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),j=require("fs");var li=require("node:child_process");function De(e,t,r){return(0,li.spawn)(e,t??[],{windowsHide:!0,...r})}var K={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 dt(e){return process.platform==="win32"?Math.round(e*K.WINDOWS_MULTIPLIER):e}var et=require("fs"),ne=require("path"),Tr=require("os");var b=require("fs");var tt=require("path");var ci=require("crypto");var Ea=process.platform==="win32";function wa(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,tt.resolve)((0,tt.dirname)(e),c)}}catch(c){let u=c.code;if(u!=="ENOENT"&&u!=="ENOTDIR")throw c}wa((0,tt.dirname)(r));let s=(0,tt.dirname)(r),i=(0,tt.basename)(r),n=(0,tt.join)(s,`.${i}.${process.pid}.${(0,ci.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 u=(0,b.writeSync)(l,o,c,o.length-c);if(u===0)throw new Error(`writeSync stalled at ${c}/${o.length} bytes`);c+=u}if((0,b.fsyncSync)(l),(0,b.closeSync)(l),l=void 0,(0,b.renameSync)(n,r),!Ea){let u;try{u=(0,b.openSync)(s,"r"),(0,b.fsyncSync)(u)}catch{}finally{if(u!==void 0)try{(0,b.closeSync)(u)}catch{}}}}catch(c){if(l!==void 0)try{(0,b.closeSync)(l)}catch{}try{(0,b.unlinkSync)(n)}catch{}throw c}}var rt=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(dt(K.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,Tr.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:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,ne.join)((0,Tr.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 s of Object.keys(this.DEFAULTS)){let i=this.envOverride(s);i!==void 0&&(r[s]=i)}return r}static loadFromFile(t,r=!0){try{if(!(0,et.existsSync)(t)){let a=this.getAllDefaults();try{let l=(0,ne.dirname)(t);(0,et.existsSync)(l)||(0,et.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 s=(0,et.readFileSync)(t,"utf-8"),i=JSON.parse(s.replace(/^\uFEFF/,"")),n=i;if(i.env&&typeof i.env=="object"){n=i.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(s){console.warn("[SETTINGS] Failed to load settings, using defaults:",t,s instanceof Error?s.message:String(s));let i=this.getAllDefaults();try{if((0,et.existsSync)(t)){let n=`${t}.corrupt-${Date.now()}`;(0,et.renameSync)(t,n),console.warn("[SETTINGS] Backed up corrupt settings file to:",n)}Pe(t,i),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(i):i}}};var Ie=null;function pt(){return Ie!==null||(Ie=rt.loadFromFile(ue)),Ie}var Rt=require("fs");var Cr=require("child_process");var st=require("fs"),Rr=ot(require("path"),1);var ya=["CLAUDECODE_","CLAUDE_CODE_"],_a=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"]),va=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,s]of Object.entries(e))if(s!==void 0){if(va.has(r)){t[r]=s;continue}_a.has(r)||ya.some(i=>r.startsWith(i))||(t[r]=s)}return t}var ba=5e3,Ta=1e3,ka=R.supervisorRegistry();function ft(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(s=>!ft(s.pid)))return;await new Promise(s=>setTimeout(s,100))}}var Ma=5e3,ui=new Map;function Ra(e){let t=ui.get(e);if(t&&Date.now()-t.capturedAtMs<Ma)return t.token;let r=null;try{let s=(0,Cr.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(s.status===0){let i=s.stdout.trim();r=i.length>0?i:null}}catch(s){d.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:e,error:s instanceof Error?s.message:String(s)}),r=null}return ui.set(e,{token:r,capturedAtMs:Date.now()}),r}function hi(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 i=t.slice(r+2).split(" ")[19];return i&&/^\d+$/.test(i)?i: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 Ra(e);try{let t=(0,Cr.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 Or(e){if(!e||!ft(e.pid))return!1;if(!e.startToken)return!0;let t=hi(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)(Rr.default.dirname(this.registryPath),{recursive:!0}),!(0,st.existsSync)(this.registryPath)){this.persist();return}try{let s=JSON.parse((0,st.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[i,n]of Object.entries(s))this.entries.set(i,n)}catch(r){r instanceof Error?d.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):d.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let t=this.pruneDeadEntries();t>0&&d.info("SYSTEM","Removed dead processes from supervisor registry",{removed:t}),this.persist()}register(t,r,s){this.initialize(),this.entries.set(t,r),s&&this.runtimeProcesses.set(t,s),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"&&Mr()}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 s=Date.parse(t.startedAt),i=Date.parse(r.startedAt);return(Number.isNaN(s)?0:s)-(Number.isNaN(i)?0:i)})}getBySession(t){let r=String(t);return this.getAll().filter(s=>s.sessionId!==void 0&&String(s.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[s,i]of this.entries)ft(i.pid)||(this.entries.delete(s),this.runtimeProcesses.delete(s),t+=1,i.type==="sdk"&&(r+=1));t>0&&this.persist();for(let s=0;s<r;s+=1)Mr();return t}async reapSession(t){this.initialize();let r=this.getBySession(t);if(r.length===0)return 0;let s=typeof t=="number"?t:Number(t)||void 0;d.info("SYSTEM",`Reaping ${r.length} process(es) for session ${t}`,{sessionId:s,pids:r.map(o=>o.pid)});let i=r.filter(o=>ft(o.pid));for(let o of i)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(i,ba);let n=i.filter(o=>ft(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:s});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()+Ta;for(;Date.now()<o&&n.filter(l=>ft(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"&&Mr();return d.info("SYSTEM",`Reaped ${r.length} process(es) for session ${t}`,{sessionId:s,reaped:r.length}),r.length}persist(){let t={processes:Object.fromEntries(this.entries.entries())};(0,st.mkdirSync)(Rr.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 Mr(){let e=Aa.shift();e&&e()}var pi=require("child_process"),Wt=require("fs"),fi=require("util");var Ca=(0,fi.promisify)(pi.execFile),Oa=R.workerPid();async function mi(e){let t=e.currentPid??process.pid,r=e.pidFilePath??Oa,s=e.registry.getAll(),i=[...s].filter(o=>o.pid!==t).sort((o,a)=>Date.parse(a.startedAt)-Date.parse(o.startedAt));for(let o of i){if(!ft(o.pid)){e.registry.unregister(o.id);continue}try{await di(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(i,5e3);let n=i.filter(o=>ft(o.pid));for(let o of n)try{await di(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 i)e.registry.unregister(o.id);for(let o of s.filter(a=>a.pid===t))e.registry.unregister(o.id);Da(r,t),e.registry.pruneDeadEntries()}function Da(e,t){if(!(0,Wt.existsSync)(e))return;let r=null;try{let s=JSON.parse((0,Wt.readFileSync)(e,"utf-8"));r=typeof s.pid=="number"?s.pid:null}catch(s){d.debug("SYSTEM","PID file unreadable during shutdown \u2014 leaving it (cannot prove ownership)",{pidFilePath:e,error:s instanceof Error?s.message:String(s)});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(s){s instanceof Error?d.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:e},s):d.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:e,error:String(s)})}}async function di(e,t){let{pid:r,pgid:s}=e;if(process.platform!=="win32"){if(typeof s=="number")try{process.kill(-s,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 i=await Pa();if(i){await new Promise((o,a)=>{i(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 Ca("taskkill",n,{timeout:K.POWERSHELL_COMMAND,windowsHide:!0})}async function Pa(){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 gi=3e4,$t=null;function Ia(){let t=Ne().pruneDeadEntries();t>0&&d.info("SYSTEM",`Health check: pruned ${t} dead process(es) from registry`)}function Si(){$t===null&&($t=setInterval(Ia,gi),$t.unref(),d.debug("SYSTEM","Health checker started",{intervalMs:gi}))}function Ei(){$t!==null&&(clearInterval($t),$t=null,d.debug("SYSTEM","Health checker stopped"))}var xa=R.workerPid(),Dr=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,Si()}configureSignalHandlers(t){if(this.shutdownHandler=t,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async s=>{if(this.shutdownInitiated){d.warn("SYSTEM",`Received ${s} but shutdown already in progress`);return}this.shutdownInitiated=!0,d.info("SYSTEM",`Received ${s}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){i instanceof Error?d.error("SYSTEM","Error during shutdown",{},i):d.error("SYSTEM","Error during shutdown (non-Error)",{error:String(i)});try{await this.stop()}catch(n){n instanceof Error?d.debug("SYSTEM","Supervisor shutdown fallback failed",{},n):d.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(n)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{d.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}Ei(),this.stopPromise=mi({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,s){this.registry.register(t,r,s)}unregisterProcess(t){this.registry.unregister(t)}getRegistry(){return this.registry}},Kc=new Dr(Ne());function Fe(e={}){let t=e.pidFilePath??xa;if(!(0,Rt.existsSync)(t))return"missing";let r=null;try{r=JSON.parse((0,Rt.readFileSync)(t,"utf-8"))}catch(i){return i instanceof Error?d.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:t},i):d.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:t,error:String(i)}),(0,Rt.rmSync)(t,{force:!0}),"invalid"}return Or(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 yi=ot(require("path"),1),_i=require("os"),it=require("fs"),Ir=require("child_process");var La=require("node:sqlite");var nu=R.dataDir(),ou=R.workerPid(),au=R.workerPort();function wi(e){return e?/(^|[\\/])node(\.exe)?$/i.test(e.trim()):!1}function Fa(e,t){let r=t==="win32"?`where ${e}`:`which ${e}`,s;try{s=(0,Ir.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 s.split(/\r?\n/).map(n=>n.trim()).find(n=>n.length>0)||null}var Pr;function vi(e={}){let t=Object.keys(e).length===0;if(t&&Pr!==void 0)return Pr;let r=Ua(e);return t&&r!==null&&(Pr=r),r}function Ua(e){let t=e.platform??process.platform,r=e.execPath??process.execPath;if(wi(r))return r;let s=e.env??process.env,i=e.homeDirectory??(0,_i.homedir)(),n=e.pathExists??it.existsSync,o=e.lookupInPath??Fa,a=t==="win32"?[s.NODE,yi.default.join(i,".nvm","current","bin","node.exe"),"node"]:[s.NODE,"/usr/local/bin/node","/opt/homebrew/bin/node","/usr/bin/node","node"];for(let l of a){let c=l?.trim();if(c&&(wi(c)&&n(c)||c.toLowerCase()==="node"))return c}return o("node",t)}var bi=ot(require("path"),1);var Ti=require("fs");var Wa=2500;async function $a(e,t,r="GET"){let s=await fetch(`http://127.0.0.1:${e}${t}`,{method:r,signal:AbortSignal.timeout(Wa)}),i="";try{i=await s.text()}catch{}return{ok:s.ok,statusCode:s.status,body:i}}function ja(){try{let e=bi.default.join(ce,"package.json");return JSON.parse((0,Ti.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 ki(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"),z=require("fs");var Ga=6e4;function Mi(){return(0,Ue.join)(lr(),"spawn.lock")}function Ri(){let e=Mi(),t=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return(0,z.mkdirSync)((0,Ue.dirname)(e),{recursive:!0}),(0,z.writeFileSync)(e,t,{flag:"wx"}),!0}catch(s){if(s?.code!=="EEXIST")return!0;if(r>0)return!1;let n;try{n=(0,z.statSync)(e).mtimeMs}catch{continue}if(Date.now()-n<=Ga)return!1;let o;try{o=(0,z.statSync)(e).mtimeMs}catch{continue}if(o!==n)return!1;try{(0,z.unlinkSync)(e)}catch{return!1}}return!1}function Ai(){let e=Mi();try{if(JSON.parse((0,z.readFileSync)(e,"utf-8")).pid!==process.pid)return;(0,z.unlinkSync)(e)}catch{}}function Fr(e,t,r){let s=process.env[e];if(s){let i=parseInt(s,10);if(Number.isFinite(i)&&i>=r.min&&i<=r.max)return i;d.warn("SYSTEM",`Invalid ${e}, using default`,{value:s,min:r.min,max:r.max})}return t}var Be=Fr("CLAUDE_MEM_HEALTH_TIMEOUT_MS",dt(K.HEALTH_CHECK),{min:500,max:3e5}),Iu=Fr("CLAUDE_MEM_API_TIMEOUT_MS",dt(K.API_REQUEST),{min:500,max:3e5}),Pi=Fr("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",dt(K.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(s){throw s instanceof DOMException&&s.name==="TimeoutError"?new Error(`Request timed out after ${r}ms`):s}}var We=null,$e=null,je=null,He=null;function Ka(){return jt.default.join(rt.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,j.existsSync)(e))return null;let t=JSON.parse((0,j.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=rt.loadFromFile(Ka())),je}function Ci(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 s=process.env[e];if(s!==void 0){let o=Ci(s,r);return o!==null?o:(d.warn("SYSTEM",`Invalid ${e}, using default`,{value:s,min:r.min,max:r.max}),t)}let i=Wr()[e],n=Ci(i,r);return n!==null?n:(d.warn("SYSTEM",`Invalid ${e} in settings.json, using default`,{value:i,min:r.min,max:r.max}),t)}function Va(){if(We!==null)return We;let e=Wr();return We=parseInt(e.CLAUDE_MEM_WORKER_PORT,10),We}function Ii(){let e=Ya();return e!==null?e:Va()}function Xa(){return $e!==null||($e=Wr().CLAUDE_MEM_WORKER_HOST),$e}function qa(){return He!==null||(He=Ja("CLAUDE_MEM_API_TIMEOUT_MS",dt(K.API_REQUEST),Ba)),He}function Qa(e){return`http://${Xa()}:${Ii()}${e}`}function mt(e,t={}){let r=t.method??"GET",s=t.timeoutMs??qa(),i=Qa(e),n={method:r};return t.headers&&(n.headers=t.headers),t.body&&(n.body=t.body),s>0?Ur(i,n,s):fetch(i,n)}async function Za(){return(await mt("/api/health",{timeoutMs:Be})).ok}async function Oi(){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,j.existsSync)(t))return t;return null}async function el(e){let t=e.backoffMs;for(let r=1;r<=e.attempts;r++){if(await Li())return!0;r<e.attempts&&(await new Promise(s=>setTimeout(s,t)),t*=2)}return!1}async function xr(e=Pi){if(e<=0)try{return await Oi()}catch{return!1}let t=Date.now();for(;Date.now()-t<e;){try{if(await Oi())return!0}catch(s){d.debug("SYSTEM","Worker readiness check threw",{error:s instanceof Error?s.message:String(s)})}let r=e-(Date.now()-t);if(r<=0)break;await new Promise(s=>setTimeout(s,Math.min(250,r)))}return!1}async function xi(){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=Pi){let r=Date.now();for(;Date.now()-r<t;){if(await xi()===e)return!0;let i=t-(Date.now()-r);if(i<=0)break;await new Promise(n=>setTimeout(n,Math.min(500,i)))}return!1}async function Lr(e){let t=await xi();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 Li(){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 Li()){let{matches:n,pluginVersion:o,workerVersion:a}=await ki(Ii());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=vi(),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 s=Ri();try{if(s){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",s?"Worker port did not open after lazy-spawn within the cold-boot wait (~15s)":"Spawn-lock holder's worker port did not open within the cold-boot wait (~15s)"),!1}finally{s&&Ai()}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 sl(){return Ge!==null||(Ge=await Ke()),Ge}var il=3;function Ni(){return jt.default.join(T,"state")}function Fi(){return jt.default.join(Ni(),"hook-failures.json")}function Ui(){try{let e=(0,j.readFileSync)(Fi(),"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 Wi(e){let t=Ni(),r=Fi(),s=`${r}.tmp`;try{(0,j.existsSync)(t)||(0,j.mkdirSync)(t,{recursive:!0}),(0,j.writeFileSync)(s,JSON.stringify(e),"utf-8"),(0,j.renameSync)(s,r)}catch(i){d.debug("SYSTEM","Failed to persist hook-failure counter",{error:i instanceof Error?i.message:String(i)})}}function nl(){try{let t=pt().CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD,r=parseInt(t,10);if(Number.isFinite(r)&&r>=1)return r}catch{}return il}async function ol(){let t={consecutiveFailures:Ui().consecutiveFailures+1,lastFailureAt:Date.now()};Wi(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 Di(){Ui().consecutiveFailures!==0&&Wi({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,s={}){if(!await sl())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)),s.timeoutMs!==void 0&&(n.timeoutMs=s.timeoutMs);let o=await mt(e,n);if(!o.ok){let l=await o.text().catch(()=>"");if(Di(),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}Di();let a=await o.text();if(a.length!==0)try{return JSON.parse(a)}catch{return a}}var ji=require("os"),Hi=ot(require("path"),1),Gi=require("child_process");var Ve=require("fs"),Je=ot(require("path"),1);var oe={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function $i(e){let t=Je.default.join(e,".git"),r;try{r=(0,Ve.statSync)(t)}catch(u){return u instanceof Error&&u.code!=="ENOENT"&&d.warn("GIT","Unexpected error checking .git",{error:u instanceof Error?u.message:String(u)}),oe}if(!r.isFile())return oe;let s;try{s=(0,Ve.readFileSync)(t,"utf-8").trim()}catch(u){return d.warn("GIT","Failed to read .git file",{error:u instanceof Error?u.message:String(u)}),oe}let i=s.match(/^gitdir:\s*(.+)$/);if(!i)return oe;let o=i[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 Bi(e){return e==="~"||e.startsWith("~/")?e.replace(/^~/,(0,ji.homedir)()):e}function al(e){try{return(0,Gi.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=Bi(e),s=al(t)??t,i=Hi.default.basename(s);if(i===""){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 i}function At(e){let t=ll(e);if(!e)return{primary:t,parent:null,isWorktree:!1,allProjects:[t]};let r=Bi(e),s=$i(r);if(s.isWorktree&&s.parentProjectName){let i=`${s.parentProjectName}/${t}`;return{primary:i,parent:s.parentProjectName,isWorktree:!0,allProjects:[s.parentProjectName,i]}}return{primary:t,parent:null,isWorktree:!1,allProjects:[t]}}var Ct=require("path");var Ki=require("os"),zi=require("path");function cl(e){let t=e.startsWith("~")?(0,Ki.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 Xe(e,t){if(!t||!t.trim())return!1;let r=e.replace(/\\/g,"/"),s=(0,zi.basename)(r),i=t.split(",").map(n=>n.trim()).filter(Boolean);for(let n of i)try{let o=cl(n);if(o.test(r)||o.test(s))return!0}catch(o){d.warn("PROJECT_NAME","Invalid exclusion pattern",{pattern:n,error:o instanceof Error?o.message:String(o)});continue}return!1}function ul(e,t){let r=(0,Ct.normalize)(e),s=(0,Ct.normalize)(t);if(r===s)return!0;let i=(0,Ct.relative)(s,r);return i.length>0&&!i.startsWith("..")&&!(0,Ct.isAbsolute)(i)}function qe(e){if(process.env.CLAUDE_MEM_INTERNAL==="1")return!1;if(!e)return!0;if(ul(e,he))return!1;let t=pt();return!Xe(e,t.CLAUDE_MEM_EXCLUDED_PROJECTS)}var Yi="claude";function hl(e){return e.trim().toLowerCase().replace(/\s+/g,"-")}function nt(e){if(!e)return Yi;let t=hl(e);return t?t==="transcript"||t.includes("codex")?"codex":t.includes("cursor")?"cursor":t.includes("claude")?"claude":t:Yi}var Xi=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],Ji=new RegExp(`<(${Xi.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g");var Vi=100;function dl(e){let t=Object.fromEntries(Xi.map(i=>[i,0]));Ji.lastIndex=0;let r=0,s=e.replace(Ji,(i,n)=>(t[n]=(t[n]??0)+1,r+=1,""));return r>Vi&&d.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:r,maxAllowed:Vi,contentLength:e.length}),{stripped:s.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 qi(e){return!e||e.length>ml?!1:fl.test(e)}var gl=dt(K.API_REQUEST),gt=class extends Error{kind;status;cause;constructor(t,r,s={}){super(r),this.name="ServerClientError",this.kind=t,this.status=s.status??null,this.cause=s.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},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),s=t.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",s,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,s=t.kind??"manual",i=typeof t.metadata?.title=="string"?t.metadata.title:void 0;return{projectId:t.projectId,kind:s,type:s,narrative:r,...i?{title:i}:{},...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,s){if(!this.apiKey||!this.apiKey.trim())throw new gt("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let i=`${this.baseUrl}${r}`,n={method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};s!==void 0&&(n.body=JSON.stringify(s));let o;try{o=await Ur(i,n,this.timeoutMs)}catch(l){let c=l instanceof Error?l.message:String(l),u=/timed out|timeout/i.test(c);throw new gt(u?"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 Qi(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=(pt().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return t==="server"||t==="server-beta"?"server":"worker"}function yl(){let e=pt(),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),s=t(e.CLAUDE_MEM_SERVER_API_KEY,e.CLAUDE_MEM_SERVER_BETA_API_KEY),i=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(!s)return d.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!i)return d.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let n={serverBaseUrl:r,apiKey:s};return{runtime:"server",client:new Qe(n),projectId:i,serverBaseUrl:r}}function Zi(){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:pt,resolveRuntimeContext:Zi,logServerFallback:tn,shouldTrackProject:qe},bt=_l;var en={async execute(e){let{sessionId:t,prompt:r}=e,s=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(s))return d.info("HOOK","Project excluded from tracking",{cwd:s}),{continue:!0,suppressOutput:!0};if(r&&qi(r))return d.debug("HOOK","session-init: skipping internal protocol payload",{preview:r.slice(0,80)}),{continue:!0,suppressOutput:!0};let i=!r||!r.trim()?"[media prompt]":r,n=At(s).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:i}}),d.info("HOOK","session-init: server session started",{contentSessionId:t,project:n}),{continue:!0,suppressOutput:!0}}catch(m){if(Qi(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 u=await bt.executeWithWorkerFallback("/api/sessions/init","POST",{contentSessionId:t,project:n,prompt:i,platformSource:o});if(bt.isWorkerFallback(u))return{continue:!0,suppressOutput:!0,exitCode:vt.SUCCESS};if(typeof u?.sessionDbId!="number")return d.failure("HOOK","Session initialization returned malformed response",{contentSessionId:t,project:n}),{continue:!0,suppressOutput:!0,exitCode:vt.SUCCESS};let h=u.sessionDbId,p=u.promptNumber;if(d.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:h,promptNumber:p,skipped:u.skipped,contextInjected:u.contextInjected}),d.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${t} | prompt#=${p} | sessionDbId=${h}`),u.skipped&&u.reason==="private")return d.info("HOOK",`INIT_COMPLETE | sessionDbId=${h} | promptNumber=${p} | skipped=true | reason=private`,{sessionId:h}),{continue:!0,suppressOutput:!0};let f="";if(l&&i&&i.length>=20&&i!=="[media prompt]"){let m=a.CLAUDE_MEM_SEMANTIC_INJECT_LIMIT||"5",g=await bt.executeWithWorkerFallback("/api/context/semantic","POST",{q:i,project:n,limit:m,platformSource:o});!bt.isWorkerFallback(g)&&g?.context&&(d.debug("HOOK",`Semantic injection: ${g.count} observations for prompt`,{sessionId:h,count:g.count}),f=g.context)}return d.info("HOOK",`INIT_COMPLETE | sessionDbId=${h} | promptNumber=${p} | project=${n}`,{sessionId:h}),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:s,edits:i}=e,n=nt(e.platform);if(!s)throw new Error("fileEditHandler requires filePath");if(d.dataIn("HOOK",`FileEdit: ${s}`,{editCount:i?.length??0}),!r)throw new Error(`Missing cwd in FileEdit hook input for session ${t}, file ${s}`);if(!qe(r))return d.debug("HOOK","Project excluded from tracking, skipping file edit observation",{cwd:r,filePath:s}),{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:s,edits:i},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:s}),{continue:!0,suppressOutput:!0})}};var V=require("fs"),Ze=require("path");var xh=R.settings();function sn(e,t){let r="<claude-mem-context>",s="</claude-mem-context>";if(!e)return`${r}
|
|
16
14
|
${t}
|
|
17
15
|
${s}`;let i=e.indexOf(r),n=e.indexOf(s);return i!==-1&&n!==-1?e.substring(0,i)+`${r}
|
|
18
16
|
${t}
|
|
@@ -20,8 +18,8 @@ ${s}`+e.substring(n+s.length):e+`
|
|
|
20
18
|
|
|
21
19
|
${r}
|
|
22
20
|
${t}
|
|
23
|
-
${s}`}function
|
|
21
|
+
${s}`}function nn(e,t){if(!e)return;let r=(0,Ze.resolve)(e);if(r.includes("/.git/")||r.includes("\\.git\\")||r.endsWith("/.git")||r.endsWith("\\.git"))return;let s=(0,Ze.dirname)(e);(0,V.existsSync)(s)||(0,V.mkdirSync)(s,{recursive:!0});let i="";(0,V.existsSync)(e)&&(i=(0,V.readFileSync)(e,"utf-8"));let n=`# Memory Context
|
|
24
22
|
|
|
25
|
-
${t}`,o=
|
|
26
|
-
`);for(let i of s){let n=i.trim();if(n.startsWith("*** Update File: "))r.push(n.replace("*** Update File: ","").trim());else if(n.startsWith("*** Add File: "))r.push(n.replace("*** Add File: ","").trim());else if(n.startsWith("*** Delete File: "))r.push(n.replace("*** Delete File: ","").trim());else if(n.startsWith("*** Move to: "))r.push(n.replace("*** Move to: ","").trim());else if(n.startsWith("+++ ")){let o=n.replace("+++ ","").replace(/^b\//,"").trim();o&&o!=="/dev/null"&&r.push(o)}}return Array.from(new Set(r))}async handleSessionEnd(t,r){await this.queueSummary(t),await this.updateContext(t,r),t.pendingTools?.clear();let s=this.getSessionKey(r,t.sessionId);this.sessions.delete(s)}async queueSummary(t){if(!await Ke())return;let s=t.lastAssistantMessage??"",i=JSON.stringify({contentSessionId:t.sessionId,last_assistant_message:s,platformSource:t.platformSource});try{await mt("/api/sessions/summarize",{method:"POST",headers:{"Content-Type":"application/json"},body:i})}catch(n){d.warn("TRANSCRIPT","Summary request failed",{error:n instanceof Error?n.message:String(n)})}}async updateContext(t,r){if(!r.context||r.context.mode!=="agents"||
|
|
27
|
-
`);this.tailState.partial=n.pop()??"";for(let o of n){let a=o.trim();a&&await this.onLine(a)}}},rr=class{constructor(t,r){this.config=t;this.statePath=r;this.state=
|
|
23
|
+
${t}`,o=sn(i,n),a=`${e}.tmp`;try{(0,V.writeFileSync)(a,o),(0,V.renameSync)(a,e)}catch(l){d.error("AGENTS_MD","Failed to write AGENTS.md",{agentsPath:e},l instanceof Error?l:new Error(String(l)))}}function vl(e){let t=e.trim().replace(/^\$\.?/,"");if(!t)return[];let r=[],s=t.split(".");for(let i of s){let n=/([^[\]]+)|\[(\d+)\]/g,o;for(;(o=n.exec(i))!==null;)o[1]?r.push(o[1]):o[2]&&r.push(parseInt(o[2],10))}return r}function Hr(e,t){if(!t)return;let r=vl(t),s=e;for(let i of r){if(s==null)return;s=s[i]}return s}function on(e){return e==null||e===""}function an(e,t){if(e.startsWith("$watch.")){let r=e.slice(7);return t.watch[r]}if(e.startsWith("$schema.")){let r=e.slice(8);return t.schema[r]}if(e.startsWith("$session.")){let r=e.slice(9);return t.session?t.session[r]:void 0}if(e==="$cwd")return t.watch.workspace;if(e==="$project")return t.watch.project}function Ht(e,t,r){if(e!==void 0){if(typeof e=="string"){let s=an(e,r);return s!==void 0?s:Hr(t,e)}if(e.coalesce&&Array.isArray(e.coalesce))for(let s of e.coalesce){let i=Ht(s,t,r);if(!on(i))return i}if(e.path){let s=an(e.path,r);if(s!==void 0)return s;let i=Hr(t,e.path);if(!on(i))return i}if(e.value!==void 0)return e.value;if(e.default!==void 0)return e.default}}function ln(e,t,r){let s={};if(!e)return s;for(let[i,n]of Object.entries(e))s[i]=Ht(n,t,r);return s}function cn(e,t,r){if(!t)return!0;let s=t.path||r.eventTypePath||"type",i=s?Hr(e,s):void 0,n=i==null||i==="";if(t.exists!==void 0&&(t.exists&&n||!t.exists&&!n)||t.equals!==void 0&&i!==t.equals||t.not_equals!==void 0&&i===t.not_equals||t.in&&Array.isArray(t.in)&&!t.in.includes(i)||t.not_in&&Array.isArray(t.not_in)&&t.not_in.includes(i)||t.contains!==void 0&&(typeof i!="string"||!i.includes(t.contains))||t.not_contains!==void 0&&typeof i=="string"&&i.includes(t.not_contains))return!1;if(t.regex)try{if(!new RegExp(t.regex).test(String(i??"")))return!1}catch(o){return d.debug("WORKER","Invalid regex in match rule",{regex:t.regex},o instanceof Error?o:void 0),!1}return!0}var tr=class{static checkUserPromptPrivacy(t,r,s,i,n,o){let a=t.getUserPrompt(r,s,n);return a===null?(d.warn("HOOK",`${i}: no user_prompts row for prompt #${s} \u2014 ingesting anyway (session-init likely raced worker boot; see #2794/#2795)`,{sessionId:n,contentSessionId:r,promptNumber:s,...o}),{allow:!0,prompt:""}):a.trim()===""?(d.debug("HOOK",`Skipping ${i} - user prompt was entirely private`,{sessionId:n,promptNumber:s,...o}),{allow:!1,reason:"private"}):{allow:!0,prompt:a}}};var un=null;function bl(){if(!un)throw new Error("ingest helpers used before setIngestContext() \u2014 wiring bug");return un}async function hn(e){let{sessionManager:t,dbManager:r,eventBroadcaster:s,ensureGeneratorRunning:i}=bl(),n=nt(e.platformSource),o=typeof e.cwd=="string"?e.cwd:"",a=o.trim()?At(o).primary:"",l=rt.loadFromFile(ue);if(o&&Xe(o,l.CLAUDE_MEM_EXCLUDED_PROJECTS))return{ok:!0,status:"skipped",reason:"project_excluded"};if(new Set(l.CLAUDE_MEM_SKIP_TOOLS.split(",").map(S=>S.trim()).filter(Boolean)).has(e.toolName))return{ok:!0,status:"skipped",reason:"tool_excluded"};if(new Set(["Edit","Write","Read","NotebookEdit"]).has(e.toolName)&&e.toolInput&&typeof e.toolInput=="object"){let S=e.toolInput,E=S.file_path||S.notebook_path;if(E&&E.includes("session-memory"))return{ok:!0,status:"skipped",reason:"session_memory_meta"}}let h=r.getSessionStore(),p,f;try{p=h.createSDKSession(e.contentSessionId,a,"",void 0,n),f=h.getPromptNumberFromUserPrompts(e.contentSessionId,p)}catch(S){let E=S instanceof Error?S.message:String(S);return d.error("INGEST","Observation session resolution failed",{contentSessionId:e.contentSessionId,toolName:e.toolName},S instanceof Error?S:new Error(E)),{ok:!1,reason:E,status:500}}if(!tr.checkUserPromptPrivacy(h,e.contentSessionId,f,"observation",p,{tool_name:e.toolName}).allow)return{ok:!0,status:"skipped",reason:"private"};let g=e.toolInput!==void 0?$r(JSON.stringify(e.toolInput)):"{}",w=e.toolResponse!==void 0?$r(JSON.stringify(e.toolResponse)):"{}";return await t.queueObservation(p,{tool_name:e.toolName,tool_input:g,tool_response:w,prompt_number:f,cwd:o||(d.error("INGEST","Missing cwd when ingesting observation",{sessionId:p,toolName:e.toolName}),""),agentId:typeof e.agentId=="string"?e.agentId:void 0,agentType:typeof e.agentType=="string"?e.agentType:void 0,toolUseId:typeof e.toolUseId=="string"?e.toolUseId:void 0}),await i?.(p,"observation"),s.broadcastObservationQueued(p),{ok:!0,sessionDbId:p}}var er=class{sessions=new Map;async processEntry(t,r,s,i){for(let n of s.events)cn(t,n.match,s)&&await this.handleEvent(t,r,s,n,i??void 0)}getSessionKey(t,r){return`${t.name}:${r}`}getOrCreateSession(t,r){let s=this.getSessionKey(t,r),i=this.sessions.get(s);return i||(i={sessionId:r,platformSource:nt(t.name)},this.sessions.set(s,i)),i}resolveSessionId(t,r,s,i,n){let o={watch:r,schema:s},a=i.fields?.sessionId??(s.sessionIdPath?{path:s.sessionIdPath}:void 0),l=Ht(a,t,o);return typeof l=="string"&&l.trim()?l:typeof l=="number"?String(l):n&&n.trim()?n:null}resolveCwd(t,r,s,i,n){let o={watch:r,schema:s,session:n},a=i.fields?.cwd??(s.cwdPath?{path:s.cwdPath}:void 0),l=Ht(a,t,o);return typeof l=="string"&&l.trim()?l:r.workspace?r.workspace:n.cwd}resolveProject(t,r,s,i,n){let o={watch:r,schema:s,session:n},a=i.fields?.project??(s.projectPath?{path:s.projectPath}:void 0),l=Ht(a,t,o);return typeof l=="string"&&l.trim()?l:r.project?r.project:n.cwd?At(n.cwd).primary:n.project}async handleEvent(t,r,s,i,n){let o=this.resolveSessionId(t,r,s,i,n);if(!o){d.debug("TRANSCRIPT","Skipping event without sessionId",{event:i.name,watch:r.name});return}let a=this.getOrCreateSession(r,o),l=this.resolveCwd(t,r,s,i,a);l&&(a.cwd=l);let c=this.resolveProject(t,r,s,i,a);c&&(a.project=c);let u=ln(i.fields,t,{watch:r,schema:s,session:a});switch(i.action){case"session_context":this.applySessionContext(a,u);break;case"session_init":await this.handleSessionInit(a,u),r.context?.updateOn?.includes("session_start")&&await this.updateContext(a,r);break;case"user_message":typeof u.message=="string"&&(a.lastUserMessage=u.message),typeof u.prompt=="string"&&(a.lastUserMessage=u.prompt);break;case"assistant_message":typeof u.message=="string"&&(a.lastAssistantMessage=u.message);break;case"tool_use":await this.handleToolUse(a,u);break;case"tool_result":await this.handleToolResult(a,u);break;case"observation":await this.sendObservation(a,u);break;case"file_edit":await this.sendFileEdit(a,u);break;case"session_end":await this.handleSessionEnd(a,r);break;default:break}}applySessionContext(t,r){let s=typeof r.cwd=="string"?r.cwd:void 0,i=typeof r.project=="string"?r.project:void 0;s&&(t.cwd=s),i&&(t.project=i)}async handleSessionInit(t,r){let s=typeof r.prompt=="string"?r.prompt:"",i=t.cwd??process.cwd();s&&(t.lastUserMessage=s),await en.execute({sessionId:t.sessionId,cwd:i,prompt:s,platform:t.platformSource})}async handleToolUse(t,r){let s=typeof r.toolId=="string"?r.toolId:void 0,i=typeof r.toolName=="string"?r.toolName:void 0,n=this.maybeParseJson(r.toolInput),o=this.maybeParseJson(r.toolResponse);if(i==="apply_patch"&&typeof n=="string"){let a=this.parseApplyPatchFiles(n);for(let l of a)await this.sendFileEdit(t,{filePath:l,edits:[{type:"apply_patch",patch:n}]})}i&&o!==void 0?await this.sendObservation(t,{toolName:i,toolInput:n,toolResponse:o,toolUseId:s}):i&&s&&(t.pendingTools||(t.pendingTools=new Map),t.pendingTools.set(s,{toolName:i,toolInput:n}))}async handleToolResult(t,r){let s=typeof r.toolId=="string"?r.toolId:void 0,i=typeof r.toolName=="string"?r.toolName:void 0,n=this.maybeParseJson(r.toolResponse),o=this.maybeParseJson(r.toolInput);if(s&&t.pendingTools){let a=t.pendingTools.get(s);a&&(i||(i=a.toolName),o===void 0&&(o=a.toolInput),t.pendingTools.delete(s))}i?await this.sendObservation(t,{toolName:i,toolInput:o,toolResponse:n,toolUseId:s}):d.debug("TRANSCRIPT","Dropping tool_result with no resolvable toolName",{sessionId:t.sessionId,toolId:s})}async sendObservation(t,r){let s=typeof r.toolName=="string"?r.toolName:void 0;if(!s)return;let i=await hn({contentSessionId:t.sessionId,cwd:t.cwd??process.cwd(),toolName:s,toolInput:this.maybeParseJson(r.toolInput),toolResponse:this.maybeParseJson(r.toolResponse),platformSource:t.platformSource,toolUseId:typeof r.toolUseId=="string"?r.toolUseId:void 0});if(!i.ok)throw new Error(`ingestObservation failed: ${i.reason}`)}async sendFileEdit(t,r){let s=typeof r.filePath=="string"?r.filePath:void 0;s&&await rn.execute({sessionId:t.sessionId,cwd:t.cwd??process.cwd(),filePath:s,edits:Array.isArray(r.edits)?r.edits:void 0,platform:t.platformSource})}maybeParseJson(t){if(typeof t!="string")return t;let r=t.trim();if(!r||!(r.startsWith("{")||r.startsWith("[")))return t;try{return JSON.parse(r)}catch(s){return d.debug("TRANSCRIPT","Field looked like JSON but did not parse; using raw string",{preview:r.slice(0,120)},s instanceof Error?s:void 0),t}}parseApplyPatchFiles(t){let r=[],s=t.split(`
|
|
24
|
+
`);for(let i of s){let n=i.trim();if(n.startsWith("*** Update File: "))r.push(n.replace("*** Update File: ","").trim());else if(n.startsWith("*** Add File: "))r.push(n.replace("*** Add File: ","").trim());else if(n.startsWith("*** Delete File: "))r.push(n.replace("*** Delete File: ","").trim());else if(n.startsWith("*** Move to: "))r.push(n.replace("*** Move to: ","").trim());else if(n.startsWith("+++ ")){let o=n.replace("+++ ","").replace(/^b\//,"").trim();o&&o!=="/dev/null"&&r.push(o)}}return Array.from(new Set(r))}async handleSessionEnd(t,r){await this.queueSummary(t),await this.updateContext(t,r),t.pendingTools?.clear();let s=this.getSessionKey(r,t.sessionId);this.sessions.delete(s)}async queueSummary(t){if(!await Ke())return;let s=t.lastAssistantMessage??"",i=JSON.stringify({contentSessionId:t.sessionId,last_assistant_message:s,platformSource:t.platformSource});try{await mt("/api/sessions/summarize",{method:"POST",headers:{"Content-Type":"application/json"},body:i})}catch(n){d.warn("TRANSCRIPT","Summary request failed",{error:n instanceof Error?n.message:String(n)})}}async updateContext(t,r){if(!r.context||r.context.mode!=="agents"||Jr(r)||!await Ke())return;let i=t.cwd??r.workspace;if(!i)return;let o=At(i).allProjects.join(","),a=`/api/context/inject?projects=${encodeURIComponent(o)}&platformSource=${encodeURIComponent(t.platformSource)}`,l=U(r.context.path??`${i}/AGENTS.md`),c=ae.default.resolve(l),u=[ae.default.resolve(i),ae.default.resolve(T)];if(!u.some(m=>c.startsWith(m+ae.default.sep)||c===m)){d.warn("SECURITY","Rejected path traversal attempt in watch.context.path",{original:r.context.path,resolved:c,allowedRoots:u});return}let p;try{p=await mt(a)}catch(m){d.warn("TRANSCRIPT","Failed to fetch AGENTS.md context",{error:m instanceof Error?m.message:String(m)});return}if(!p.ok)return;let f=(await p.text()).trim();f&&(nn(l,f),d.debug("TRANSCRIPT","Updated AGENTS.md context",{agentsPath:l,watch:r.name}))}};var Gr=class{constructor(t,r,s,i){this.filePath=t;this.onLine=s;this.onOffset=i;this.tailState={offset:r,partial:""}}filePath;onLine;onOffset;watcher=null;tailState;start(){this.readNewData().catch(()=>{}),this.watcher=(0,L.watch)(this.filePath,{persistent:!0},()=>{this.readNewData().catch(()=>{})})}close(){this.watcher?.close(),this.watcher=null}poke(){this.readNewData().catch(()=>{})}async readNewData(){if(!(0,L.existsSync)(this.filePath))return;let t=0;try{t=(0,L.statSync)(this.filePath).size}catch(o){d.debug("WORKER","Failed to stat transcript file",{file:this.filePath},o instanceof Error?o:void 0);return}if(t<this.tailState.offset&&(this.tailState.offset=0),t===this.tailState.offset)return;let r=(0,L.createReadStream)(this.filePath,{start:this.tailState.offset,end:t-1,encoding:"utf8"}),s="";for await(let o of r)s+=o;this.tailState.offset=t,this.onOffset(this.tailState.offset);let n=(this.tailState.partial+s).split(`
|
|
25
|
+
`);this.tailState.partial=n.pop()??"";for(let o of n){let a=o.trim();a&&await this.onLine(a)}}},rr=class{constructor(t,r){this.config=t;this.statePath=r;this.state=oi(r)}config;statePath;processor=new er;tailers=new Map;state;rootWatchers=[];async start(){for(let t of this.config.watches)await this.setupWatch(t)}stop(){for(let t of this.tailers.values())t.close();this.tailers.clear();for(let t of this.rootWatchers)t.close();this.rootWatchers=[]}async setupWatch(t){let r=this.resolveSchema(t);if(!r){d.warn("TRANSCRIPT","Missing schema for watch",{watch:t.name});return}let s=U(t.path),i=this.resolveWatchFiles(s);for(let o of i)await this.addTailer(o,t,r);let n=this.deepestNonGlobAncestor(s);if(!n||!(0,L.existsSync)(n)){d.debug("TRANSCRIPT","Watch root does not exist, skipping fs.watch",{watch:t.name,watchRoot:n});return}try{let o=(0,L.watch)(n,{recursive:!0,persistent:!0},(a,l)=>{if(!l)return;let c=(0,X.resolve)(n,l).replace(/\\/g,"/"),u=this.tailers.get(c);if(u){u.poke();return}let h=this.resolveWatchFiles(s);for(let p of h)this.tailers.has(p)||this.addTailer(p,t,r)});this.rootWatchers.push(o),d.info("TRANSCRIPT","Watching transcript root recursively",{watch:t.name,watchRoot:n})}catch(o){d.warn("TRANSCRIPT","Failed to start recursive fs.watch on transcript root",{watch:t.name,watchRoot:n},o instanceof Error?o:void 0)}}deepestNonGlobAncestor(t){if(!this.hasGlob(t)){if((0,L.existsSync)(t))try{return(0,L.statSync)(t).isDirectory()?t:(0,X.resolve)(t,"..")}catch{return(0,X.resolve)(t,"..")}return t}let r=t.split(/[/\\]/),s=[];for(let i of r){if(/[*?[\]{}()]/.test(i))break;s.push(i)}return s.length===0||s.length===1&&s[0]===""?"":s.join(X.sep)}resolveSchema(t){return typeof t.schema=="string"?this.config.schemas?.[t.schema]??null:t.schema}resolveWatchFiles(t){if(this.hasGlob(t))return ie(this.normalizeGlobPattern(t),{nodir:!0,absolute:!0});if((0,L.existsSync)(t))try{if((0,L.statSync)(t).isDirectory()){let s=(0,X.join)(t,"**","*.jsonl");return ie(this.normalizeGlobPattern(s),{nodir:!0,absolute:!0})}return[t]}catch(r){return d.debug("WORKER","Failed to stat watch path",{path:t},r instanceof Error?r:void 0),[]}return[]}normalizeGlobPattern(t){return t.replace(/\\/g,"/")}hasGlob(t){return/[*?[\]{}()]/.test(t)}async addTailer(t,r,s){if(this.tailers.has(t))return;let i=this.extractSessionIdFromPath(t),n=this.state.offsets[t]??0;if(n===0&&r.startAtEnd)try{n=(0,L.statSync)(t).size}catch(a){d.debug("WORKER","Failed to stat file for startAtEnd offset",{file:t},a instanceof Error?a:void 0),n=0}let o=new Gr(t,n,async a=>{await this.handleLine(a,r,s,t,i)},a=>{this.state.offsets[t]=a,ai(this.statePath,this.state)});o.start(),this.tailers.set(t,o),d.info("TRANSCRIPT","Watching transcript file",{file:t,watch:r.name,schema:s.name})}async handleLine(t,r,s,i,n){try{let o=JSON.parse(t);await this.processor.processEntry(o,r,s,n??void 0)}catch(o){o instanceof Error?d.debug("TRANSCRIPT","Failed to parse transcript line",{watch:r.name,file:(0,X.basename)(i)},o):d.warn("TRANSCRIPT","Failed to parse transcript line (non-Error thrown)",{watch:r.name,file:(0,X.basename)(i),error:String(o)})}}extractSessionIdFromPath(t){let r=t.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i);return r?r[0]:null}};function Br(e,t){let r=e.indexOf(t);return r===-1?null:e[r+1]??null}async function dn(e,t){switch(e){case"init":{let r=Br(t,"--config")??xt;return pe(r),console.log(`Created sample config: ${U(r)}`),0}case"watch":{let r=Br(t,"--config")??xt,s;try{s=zt(r)}catch(a){if(a instanceof Error&&a.message.includes("not found"))pe(r),console.log(`Created sample config: ${U(r)}`),s=zt(r);else throw a}let i=U(s.stateFile??de),n=new rr(s,i);await n.start(),console.log("Transcript watcher running. Press Ctrl+C to stop.");let o=()=>{n.stop(),process.exit(0)};return process.on("SIGINT",o),process.on("SIGTERM",o),await new Promise(()=>{})}case"validate":{let r=Br(t,"--config")??xt;try{zt(r)}catch(s){if(s instanceof Error&&s.message.includes("not found"))pe(r),console.log(`Created sample config: ${U(r)}`),zt(r);else throw s}return console.log(`Config OK: ${U(r)}`),0}default:return console.log("Usage: claude-mem transcript <init|watch|validate> [--config <path>]"),1}}var Tl=process.argv[2],kl=process.argv.slice(3);dn(Tl,kl).then(e=>{process.exit(e)}).catch(e=>{console.error(e),process.exit(1)});
|