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