claude-mem 13.7.0 → 13.7.1

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,19 +1,19 @@
1
1
  #!/usr/bin/env bun
2
- "use strict";var Rn=Object.create;var Yr=Object.defineProperty;var On=Object.getOwnPropertyDescriptor;var In=Object.getOwnPropertyNames;var Dn=Object.getPrototypeOf,Pn=Object.prototype.hasOwnProperty;var xn=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of In(e))!Pn.call(t,i)&&i!==r&&Yr(t,i,{get:()=>e[i],enumerable:!(s=On(e,i))||s.enumerable});return t};var X=(t,e,r)=>(r=t!=null?Rn(Dn(t)):{},xn(e||!t||!t.__esModule?Yr(r,"default",{value:t,enumerable:!0}):r,t));var ne=require("fs"),lr=require("os"),He=require("path");var y=require("path"),ar=require("os"),$e=require("fs");var Xr=require("url");var ie=require("fs"),Jr=require("path");var Ln=null;function rr(t){return(Ln??process.stderr.write.bind(process.stderr))(t)}var at=null;function sr(t){rr(t)}function zr(t,e={}){at&&at.length>0&&(rr(at.join("")),at=[]),rr(t.endsWith(`
2
+ "use strict";var An=Object.create;var Yr=Object.defineProperty;var Cn=Object.getOwnPropertyDescriptor;var kn=Object.getOwnPropertyNames;var Rn=Object.getPrototypeOf,On=Object.prototype.hasOwnProperty;var Dn=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of kn(e))!On.call(t,i)&&i!==r&&Yr(t,i,{get:()=>e[i],enumerable:!(s=Cn(e,i))||s.enumerable});return t};var X=(t,e,r)=>(r=t!=null?An(Rn(t)):{},Dn(e||!t||!t.__esModule?Yr(r,"default",{value:t,enumerable:!0}):r,t));var ie=require("fs"),lr=require("os"),je=require("path");var _=require("path"),ar=require("os"),He=require("fs");var Xr=require("url");var se=require("fs"),Jr=require("path");var Pn=null;function rr(t){return(Pn??process.stderr.write.bind(process.stderr))(t)}var ot=null;function sr(t){rr(t)}function zr(t,e={}){ot&&ot.length>0&&(rr(ot.join("")),ot=[]),rr(t.endsWith(`
3
3
  `)?t:`${t}
4
- `),e.skipExit||process.exit(2)}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 e=R.logsDir();(0,ie.existsSync)(e)||(0,ie.mkdirSync)(e,{recursive:!0});let r=new Date().toISOString().split("T")[0];this.logFilePath=(0,Jr.join)(e,`claude-mem-${r}.log`)}catch(e){console.error("[LOGGER] Failed to initialize log file:",e instanceof Error?e.message:String(e)),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let e=R.settings();if((0,ie.existsSync)(e)){let r=(0,ie.readFileSync)(e,"utf-8"),i=(JSON.parse(r).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=nr[i]??1}else this.level=1}catch(e){console.error("[LOGGER] Failed to load log level from settings:",e instanceof Error?e.message:String(e)),this.level=1}return this.level}correlationId(e,r){return`obs-${e}-${r}`}sessionId(e){return`session-${e}`}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.getLevel()===0?`${e.message}
4
+ `),e.skipExit||process.exit(2)}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 e=R.logsDir();(0,se.existsSync)(e)||(0,se.mkdirSync)(e,{recursive:!0});let r=new Date().toISOString().split("T")[0];this.logFilePath=(0,Jr.join)(e,`claude-mem-${r}.log`)}catch(e){console.error("[LOGGER] Failed to initialize log file:",e instanceof Error?e.message:String(e)),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let e=R.settings();if((0,se.existsSync)(e)){let r=(0,se.readFileSync)(e,"utf-8"),i=(JSON.parse(r).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=nr[i]??1}else this.level=1}catch(e){console.error("[LOGGER] Failed to load log level from settings:",e instanceof Error?e.message:String(e)),this.level=1}return this.level}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.getLevel()===0?`${e.message}
5
5
  ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let r=Object.keys(e);return r.length===0?"{}":r.length<=3?JSON.stringify(e):`{${r.length} keys: ${r.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,r){if(!r)return e;let s=r;if(typeof r=="string")try{s=JSON.parse(r)}catch{s=r}if(e==="Bash"&&s.command)return`${e}(${s.command})`;if(s.file_path)return`${e}(${s.file_path})`;if(s.notebook_path)return`${e}(${s.notebook_path})`;if(e==="Glob"&&s.pattern)return`${e}(${s.pattern})`;if(e==="Grep"&&s.pattern)return`${e}(${s.pattern})`;if(s.url)return`${e}(${s.url})`;if(s.query)return`${e}(${s.query})`;if(e==="Task"){if(s.subagent_type)return`${e}(${s.subagent_type})`;if(s.description)return`${e}(${s.description})`}return e==="Skill"&&s.skill?`${e}(${s.skill})`:e==="LSP"&&s.operation?`${e}(${s.operation})`:e}formatTimestamp(e){let r=e.getFullYear(),s=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0"),n=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0"),l=String(e.getMilliseconds()).padStart(3,"0");return`${r}-${s}-${i} ${n}:${o}:${a}.${l}`}log(e,r,s,i,n){if(e<this.getLevel())return;this.ensureLogFileInitialized();let o=this.formatTimestamp(new Date),a=nr[e].padEnd(5),l=r.padEnd(6),c="";i?.correlationId?c=`[${i.correlationId}] `:i?.sessionId&&(c=`[session-${i.sessionId}] `);let u="";if(n!=null)if(n instanceof Error)u=this.getLevel()===0?`
6
6
  ${n.message}
7
7
  ${n.stack}`:` ${n.message}`;else if(this.getLevel()===0&&typeof n=="object")try{u=`
8
- `+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,_])=>`${E}=${_}`).join(", ")}}`)}let p=`[${o}] [${a}] [${l}] ${c}${s}${h}${u}`;if(this.logFilePath)try{(0,ie.appendFileSync)(this.logFilePath,p+`
8
+ `+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,se.appendFileSync)(this.logFilePath,p+`
9
9
  `,"utf8")}catch(f){sr(`[LOGGER] Failed to write to log file: ${f instanceof Error?f.message:String(f)}
10
10
  `)}else sr(p+`
11
- `)}debug(e,r,s,i){this.log(0,e,r,s,i)}info(e,r,s,i){this.log(1,e,r,s,i)}warn(e,r,s,i){this.log(2,e,r,s,i)}setErrorSink(e){ir=e}error(e,r,s,i){this.log(3,e,r,s,i),this.routeErrorToSink(r,s,i)}routeErrorToSink(e,r,s){try{if(!ir||!(s instanceof Error))return;ir(s)}catch{}}dataIn(e,r,s,i){this.info(e,`\u2192 ${r}`,s,i)}dataOut(e,r,s,i){this.info(e,`\u2190 ${r}`,s,i)}success(e,r,s,i){this.info(e,`\u2713 ${r}`,s,i)}failure(e,r,s,i){this.error(e,`\u2717 ${r}`,s,i)}timing(e,r,s,i){this.info(e,`\u23F1 ${r}`,i,{duration:`${s}ms`})}happyPathError(e,r,s,i,n=""){let c=((new Error().stack||"").split(`
12
- `)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),u=c?`${c[1].split("/").pop()}:${c[2]}`:"unknown",h={...s,location:u};return this.warn(e,`[HAPPY-PATH] ${r}`,h,i),n}},d=new or;var Gn={};function Nn(){return typeof __dirname<"u"?__dirname:(0,y.dirname)((0,Xr.fileURLToPath)(Gn.url))}var Vl=Nn();function Oe(){if(process.env.CLAUDE_MEM_DATA_DIR)return process.env.CLAUDE_MEM_DATA_DIR;let t=(0,y.join)((0,ar.homedir)(),".claude-mem"),e=(0,y.join)(t,"settings.json");try{if((0,$e.existsSync)(e)){let r=JSON.parse((0,$e.readFileSync)(e,"utf-8")),s=r.env??r;if(s.CLAUDE_MEM_DATA_DIR)return s.CLAUDE_MEM_DATA_DIR}}catch{}return t}var v=Oe(),lt=process.env.CLAUDE_CONFIG_DIR||(0,y.join)((0,ar.homedir)(),".claude"),ct=(0,y.join)(lt,"plugins","marketplaces","thedotmack"),Un=(0,y.join)(v,"archives"),Fn=(0,y.join)(v,"logs"),Wn=(0,y.join)(v,"trash"),$n=(0,y.join)(v,"backups"),Hn=(0,y.join)(v,"modes"),ut=(0,y.join)(v,"settings.json"),Ql=(0,y.join)(v,"claude-mem.db"),jn=(0,y.join)(v,"vector-db"),ht=(0,y.join)(v,"observer-sessions"),Bn=(0,y.basename)(ht),Zl=(0,y.join)(lt,"settings.json"),ec=(0,y.join)(lt,"commands"),tc=(0,y.join)(lt,"CLAUDE.md");var R={dataDir:()=>v,workerPid:()=>(0,y.join)(v,"worker.pid"),serverBetaPid:()=>(0,y.join)(v,".server-beta.pid"),serverBetaPort:()=>(0,y.join)(v,".server-beta.port"),serverBetaRuntime:()=>(0,y.join)(v,".server-beta.runtime.json"),settings:()=>(0,y.join)(v,"settings.json"),database:()=>(0,y.join)(v,"claude-mem.db"),chroma:()=>(0,y.join)(v,"chroma"),combinedCerts:()=>(0,y.join)(v,"combined_certs.pem"),transcriptsConfig:()=>(0,y.join)(v,"transcript-watch.json"),transcriptsState:()=>(0,y.join)(v,"transcript-watch-state.json"),corpora:()=>(0,y.join)(v,"corpora"),supervisorRegistry:()=>(0,y.join)(v,"supervisor.json"),envFile:()=>(0,y.join)(v,".env"),logsDir:()=>Fn,archives:()=>Un,trash:()=>Wn,backups:()=>$n,modes:()=>Hn,vectorDb:()=>jn,observerSessions:()=>ht};var Ie=R.transcriptsConfig(),dt=R.transcriptsState();var Kn={version:1,schemas:{},watches:[],stateFile:dt};function Yn(t){let e=typeof t.schema=="string"?t.schema:t.schema?.name;if(!(t.name==="codex"||e==="codex")||!t.path)return!1;let s=N(t.path).replace(/\\/g,"/"),i=(0,He.join)((0,lr.homedir)(),".codex","sessions").replace(/\\/g,"/");return s===`${i}/**/*.jsonl`}function qr(t){let e=typeof t.schema=="string"?t.schema:t.schema?.name,r=t.name==="codex"&&(!e||e==="codex");return t.context?.mode==="agents"&&r&&Yn(t)}function N(t){return t&&(t.startsWith("~")?(0,He.join)((0,lr.homedir)(),t.slice(1)):t)}function je(t=Ie){let e=N(t);if(!(0,ne.existsSync)(e))throw new Error(`Transcript watch config not found: ${e}`);let r=(0,ne.readFileSync)(e,"utf-8"),s=JSON.parse(r);if(!s.version||!s.watches)throw new Error(`Invalid transcript watch config: ${e}`);return s.stateFile||(s.stateFile=dt),s}function pt(t=Ie){let e=N(t),r=(0,He.dirname)(e);(0,ne.existsSync)(r)||(0,ne.mkdirSync)(r,{recursive:!0}),(0,ne.writeFileSync)(e,JSON.stringify(Kn,null,2))}var x=require("fs"),J=require("path");var Ds=require("node:url"),Le=require("node:path"),Us=require("node:url"),Q=require("fs"),Zo=X(require("node:fs"),1),Se=require("node:fs/promises"),At=require("node:events"),_r=X(require("node:stream"),1),Fs=require("node:string_decoder"),_s=(t,e,r)=>{let s=t instanceof RegExp?Vr(t,r):t,i=e instanceof RegExp?Vr(e,r):e,n=s!==null&&i!=null&&zn(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=(t,e)=>{let r=e.match(t);return r?r[0]:null},zn=(t,e,r)=>{let s,i,n,o,a,l=r.indexOf(t),c=r.indexOf(e,l+1),u=l;if(l>=0&&c>0){if(t===e)return[l,c];for(s=[],n=r.length;u>=0&&!a;){if(u===l)s.push(u),l=r.indexOf(t,u+1);else if(s.length===1){let h=s.pop();h!==void 0&&(a=[h,c])}else i=s.pop(),i!==void 0&&i<n&&(n=i,o=c),c=r.indexOf(e,u+1);u=l<c&&l>=0?l:c}s.length&&o!==void 0&&(a=[n,o])}return a},ys="\0SLASH"+Math.random()+"\0",bs="\0OPEN"+Math.random()+"\0",Er="\0CLOSE"+Math.random()+"\0",vs="\0COMMA"+Math.random()+"\0",Ts="\0PERIOD"+Math.random()+"\0",Jn=new RegExp(ys,"g"),Xn=new RegExp(bs,"g"),qn=new RegExp(Er,"g"),Vn=new RegExp(vs,"g"),Qn=new RegExp(Ts,"g"),Zn=/\\\\/g,eo=/\\{/g,to=/\\}/g,ro=/\\,/g,so=/\\./g,io=1e5;function cr(t){return isNaN(t)?t.charCodeAt(0):parseInt(t,10)}function no(t){return t.replace(Zn,ys).replace(eo,bs).replace(to,Er).replace(ro,vs).replace(so,Ts)}function oo(t){return t.replace(Jn,"\\").replace(Xn,"{").replace(qn,"}").replace(Vn,",").replace(Qn,".")}function Ms(t){if(!t)return[""];let e=[],r=_s("{","}",t);if(!r)return t.split(",");let{pre:s,body:i,post:n}=r,o=s.split(",");o[o.length-1]+="{"+i+"}";let a=Ms(n);return n.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),e.push.apply(e,o),e}function ao(t,e={}){if(!t)return[];let{max:r=io}=e;return t.slice(0,2)==="{}"&&(t="\\{\\}"+t.slice(2)),Xe(no(t),r,!0).map(oo)}function lo(t){return"{"+t+"}"}function co(t){return/^-?0\d/.test(t)}function uo(t,e){return t<=e}function ho(t,e){return t>=e}function Xe(t,e,r){let s=[],i=_s("{","}",t);if(!i)return[t];let n=i.pre,o=i.post.length?Xe(i.post,e,!1):[""];if(/\$$/.test(i.pre))for(let a=0;a<o.length&&a<e;a++){let l=n+"{"+i.body+"}"+o[a];s.push(l)}else{let a=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(i.body),l=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(i.body),c=a||l,u=i.body.indexOf(",")>=0;if(!c&&!u)return i.post.match(/,(?!,).*\}/)?(t=i.pre+"{"+i.body+Er+i.post,Xe(t,e,!0)):[t];let h;if(c)h=i.body.split(/\.\./);else if(h=Ms(i.body),h.length===1&&h[0]!==void 0&&(h=Xe(h[0],e,!1).map(lo),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=cr(h[0]),m=cr(h[1]),g=Math.max(h[0].length,h[1].length),w=h.length===3&&h[2]!==void 0?Math.abs(cr(h[2])):1,S=uo;m<f&&(w*=-1,S=ho);let E=h.some(co);p=[];for(let _=f;S(_,m);_+=w){let b;if(l)b=String.fromCharCode(_),b==="\\"&&(b="");else if(b=String(_),E){let T=g-b.length;if(T>0){let pe=new Array(T+1).join("0");_<0?b="-"+pe+b.slice(1):b=pe+b}}p.push(b)}}else{p=[];for(let f=0;f<h.length;f++)p.push.apply(p,Xe(h[f],e,!1))}for(let f=0;f<p.length;f++)for(let m=0;m<o.length&&s.length<e;m++){let g=n+p[f]+o[m];(!r||c||g)&&s.push(g)}}return s}var Tt=t=>{if(typeof t!="string")throw new TypeError("invalid pattern");if(t.length>65536)throw new TypeError("pattern is too long")},po={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},Be=t=>t.replace(/[[\]\\-]/g,"\\$&"),fo=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Qr=t=>t.join(""),mo=(t,e)=>{let r=e;if(t.charAt(r)!=="[")throw new Error("not in a brace expression");let s=[],i=[],n=r+1,o=!1,a=!1,l=!1,c=!1,u=r,h="";e:for(;n<t.length;){let m=t.charAt(n);if((m==="!"||m==="^")&&n===r+1){c=!0,n++;continue}if(m==="]"&&o&&!l){u=n+1;break}if(o=!0,m==="\\"&&!l){l=!0,n++;continue}if(m==="["&&!l){for(let[g,[w,S,E]]of Object.entries(po))if(t.startsWith(g,n)){if(h)return["$.",!1,t.length-r,!0];n+=g.length,E?i.push(w):s.push(w),a=a||S;continue e}}if(l=!1,h){m>h?s.push(Be(h)+"-"+Be(m)):m===h&&s.push(Be(m)),h="",n++;continue}if(t.startsWith("-]",n+1)){s.push(Be(m+"-")),n+=2;continue}if(t.startsWith("-",n+1)){h=m,n+=2;continue}s.push(Be(m)),n++}if(u<n)return["",!1,0,!1];if(!s.length&&!i.length)return["$.",!1,t.length-r,!0];if(i.length===0&&s.length===1&&/^\\?.$/.test(s[0])&&!c){let m=s[0].length===2?s[0].slice(-1):s[0];return[fo(m),!1,u-r,!1]}let p="["+(c?"^":"")+Qr(s)+"]",f="["+(c?"":"^")+Qr(i)+"]";return[s.length&&i.length?"("+p+"|"+f+")":s.length?p:f,a,u-r,!0]},xe=(t,{windowsPathsNoEscape:e=!1,magicalBraces:r=!0}={})=>r?e?t.replace(/\[([^\/\\])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):e?t.replace(/\[([^\/\\{}])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1"),go=new Set(["!","?","+","*","@"]),Zr=t=>go.has(t),So="(?!(?:^|/)\\.\\.?(?:$|/))",ft="(?!\\.)",Eo=new Set(["[","."]),wo=new Set(["..","."]),_o=new Set("().*{}+?[]^$\\!"),yo=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),wr="[^/]",es=wr+"*?",ts=wr+"+?",ks=class F{type;#e;#r;#n=!1;#i=[];#o;#_;#S;#u=!1;#a;#d;#h=!1;constructor(e,r,s={}){this.type=e,e&&(this.#r=!0),this.#o=r,this.#e=this.#o?this.#o.#e:this,this.#a=this.#e===this?s:this.#e.#a,this.#S=this.#e===this?[]:this.#e.#S,e==="!"&&!this.#e.#u&&this.#S.push(this),this.#_=this.#o?this.#o.#i.length:0}get hasMagic(){if(this.#r!==void 0)return this.#r;for(let e of this.#i)if(typeof e!="string"&&(e.type||e.hasMagic))return this.#r=!0;return this.#r}toString(){return this.#d!==void 0?this.#d:this.type?this.#d=this.type+"("+this.#i.map(e=>String(e)).join("|")+")":this.#d=this.#i.map(e=>String(e)).join("")}#l(){if(this!==this.#e)throw new Error("should only call on root");if(this.#u)return this;this.toString(),this.#u=!0;let e;for(;e=this.#S.pop();){if(e.type!=="!")continue;let r=e,s=r.#o;for(;s;){for(let i=r.#_+1;!s.type&&i<s.#i.length;i++)for(let n of e.#i){if(typeof n=="string")throw new Error("string part in extglob AST??");n.copyIn(s.#i[i])}r=s,s=r.#o}}return this}push(...e){for(let r of e)if(r!==""){if(typeof r!="string"&&!(r instanceof F&&r.#o===this))throw new Error("invalid part: "+r);this.#i.push(r)}}toJSON(){let e=this.type===null?this.#i.slice().map(r=>typeof r=="string"?r:r.toJSON()):[this.type,...this.#i.map(r=>r.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#u&&this.#o?.type==="!")&&e.push({}),e}isStart(){if(this.#e===this)return!0;if(!this.#o?.isStart())return!1;if(this.#_===0)return!0;let e=this.#o;for(let r=0;r<this.#_;r++){let s=e.#i[r];if(!(s instanceof F&&s.type==="!"))return!1}return!0}isEnd(){if(this.#e===this||this.#o?.type==="!")return!0;if(!this.#o?.isEnd())return!1;if(!this.type)return this.#o?.isEnd();let e=this.#o?this.#o.#i.length:0;return this.#_===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this))}clone(e){let r=new F(this.type,e);for(let s of this.#i)r.copyIn(s);return r}static#s(e,r,s,i){let n=!1,o=!1,a=-1,l=!1;if(r.type===null){let f=s,m="";for(;f<e.length;){let g=e.charAt(f++);if(n||g==="\\"){n=!n,m+=g;continue}if(o){f===a+1?(g==="^"||g==="!")&&(l=!0):g==="]"&&!(f===a+2&&l)&&(o=!1),m+=g;continue}else if(g==="["){o=!0,a=f,l=!1,m+=g;continue}if(!i.noext&&Zr(g)&&e.charAt(f)==="("){r.push(m),m="";let w=new F(g,r);f=F.#s(e,w,f,i),r.push(w);continue}m+=g}return r.push(m),f}let c=s+1,u=new F(null,r),h=[],p="";for(;c<e.length;){let f=e.charAt(c++);if(n||f==="\\"){n=!n,p+=f;continue}if(o){c===a+1?(f==="^"||f==="!")&&(l=!0):f==="]"&&!(c===a+2&&l)&&(o=!1),p+=f;continue}else if(f==="["){o=!0,a=c,l=!1,p+=f;continue}if(Zr(f)&&e.charAt(c)==="("){u.push(p),p="";let m=new F(f,u);u.push(m),c=F.#s(e,m,c,i);continue}if(f==="|"){u.push(p),p="",h.push(u),u=new F(null,r);continue}if(f===")")return p===""&&r.#i.length===0&&(r.#h=!0),u.push(p),p="",r.push(...h,u),c;p+=f}return r.type=null,r.#r=void 0,r.#i=[e.substring(s-1)],c}static fromGlob(e,r={}){let s=new F(null,void 0,r);return F.#s(e,s,0,r),s}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let e=this.toString(),[r,s,i,n]=this.toRegExpSource();if(!(i||this.#r||this.#a.nocase&&!this.#a.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return s;let o=(this.#a.nocase?"i":"")+(n?"u":"");return Object.assign(new RegExp(`^${r}$`,o),{_src:r,_glob:e})}get options(){return this.#a}toRegExpSource(e){let r=e??!!this.#a.dot;if(this.#e===this&&this.#l(),!this.type){let l=this.isStart()&&this.isEnd()&&!this.#i.some(p=>typeof p!="string"),c=this.#i.map(p=>{let[f,m,g,w]=typeof p=="string"?F.#y(p,this.#r,l):p.toRegExpSource(e);return this.#r=this.#r||g,this.#n=this.#n||w,f}).join(""),u="";if(this.isStart()&&typeof this.#i[0]=="string"&&!(this.#i.length===1&&wo.has(this.#i[0]))){let p=Eo,f=r&&p.has(c.charAt(0))||c.startsWith("\\.")&&p.has(c.charAt(2))||c.startsWith("\\.\\.")&&p.has(c.charAt(4)),m=!r&&!e&&p.has(c.charAt(0));u=f?So:m?ft:""}let h="";return this.isEnd()&&this.#e.#u&&this.#o?.type==="!"&&(h="(?:$|\\/)"),[u+c+h,xe(c),this.#r=!!this.#r,this.#n]}let s=this.type==="*"||this.type==="+",i=this.type==="!"?"(?:(?!(?:":"(?:",n=this.#p(r);if(this.isStart()&&this.isEnd()&&!n&&this.type!=="!"){let l=this.toString();return this.#i=[l],this.type=null,this.#r=void 0,[l,xe(this.toString()),!1,!1]}let o=!s||e||r||!ft?"":this.#p(!0);o===n&&(o=""),o&&(n=`(?:${n})(?:${o})*?`);let a="";if(this.type==="!"&&this.#h)a=(this.isStart()&&!r?ft:"")+ts;else{let l=this.type==="!"?"))"+(this.isStart()&&!r&&!e?ft:"")+es+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;a=i+n+l}return[a,xe(n),this.#r=!!this.#r,this.#n]}#p(e){return this.#i.map(r=>{if(typeof r=="string")throw new Error("string type in extglob ast??");let[s,i,n,o]=r.toRegExpSource(e);return this.#n=this.#n||o,s}).filter(r=>!(this.isStart()&&this.isEnd())||!!r).join("|")}static#y(e,r,s=!1){let i=!1,n="",o=!1,a=!1;for(let l=0;l<e.length;l++){let c=e.charAt(l);if(i){i=!1,n+=(_o.has(c)?"\\":"")+c;continue}if(c==="*"){if(a)continue;a=!0,n+=s&&/^[*]+$/.test(e)?ts:es,r=!0;continue}else a=!1;if(c==="\\"){l===e.length-1?n+="\\\\":i=!0;continue}if(c==="["){let[u,h,p,f]=mo(e,l);if(p){n+=u,o=o||h,l+=p-1,r=r||f;continue}}if(c==="?"){n+=wr,r=!0;continue}n+=yo(c)}return[n,xe(e),!!r,o]}},Cs=(t,{windowsPathsNoEscape:e=!1,magicalBraces:r=!1}={})=>r?e?t.replace(/[?*()[\]{}]/g,"[$&]"):t.replace(/[?*()[\]\\{}]/g,"\\$&"):e?t.replace(/[?*()[\]]/g,"[$&]"):t.replace(/[?*()[\]\\]/g,"\\$&"),P=(t,e,r={})=>(Tt(e),!r.nocomment&&e.charAt(0)==="#"?!1:new ge(e,r).match(t)),bo=/^\*+([^+@!?\*\[\(]*)$/,vo=t=>e=>!e.startsWith(".")&&e.endsWith(t),To=t=>e=>e.endsWith(t),Mo=t=>(t=t.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(t)),ko=t=>(t=t.toLowerCase(),e=>e.toLowerCase().endsWith(t)),Co=/^\*+\.\*+$/,Ao=t=>!t.startsWith(".")&&t.includes("."),Ro=t=>t!=="."&&t!==".."&&t.includes("."),Oo=/^\.\*+$/,Io=t=>t!=="."&&t!==".."&&t.startsWith("."),Do=/^\*+$/,Po=t=>t.length!==0&&!t.startsWith("."),xo=t=>t.length!==0&&t!=="."&&t!=="..",Lo=/^\?+([^+@!?\*\[\(]*)?$/,No=([t,e=""])=>{let r=As([t]);return e?(e=e.toLowerCase(),s=>r(s)&&s.toLowerCase().endsWith(e)):r},Uo=([t,e=""])=>{let r=Rs([t]);return e?(e=e.toLowerCase(),s=>r(s)&&s.toLowerCase().endsWith(e)):r},Fo=([t,e=""])=>{let r=Rs([t]);return e?s=>r(s)&&s.endsWith(e):r},Wo=([t,e=""])=>{let r=As([t]);return e?s=>r(s)&&s.endsWith(e):r},As=([t])=>{let e=t.length;return r=>r.length===e&&!r.startsWith(".")},Rs=([t])=>{let e=t.length;return r=>r.length===e&&r!=="."&&r!==".."},Os=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",rs={win32:{sep:"\\"},posix:{sep:"/"}},$o=Os==="win32"?rs.win32.sep:rs.posix.sep;P.sep=$o;var D=Symbol("globstar **");P.GLOBSTAR=D;var Ho="[^/]",jo=Ho+"*?",Bo="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",Go="(?:(?!(?:\\/|^)\\.).)*?",Ko=(t,e={})=>r=>P(r,t,e);P.filter=Ko;var $=(t,e={})=>Object.assign({},t,e),Yo=t=>{if(!t||typeof t!="object"||!Object.keys(t).length)return P;let e=P;return Object.assign((r,s,i={})=>e(r,s,$(t,i)),{Minimatch:class extends e.Minimatch{constructor(r,s={}){super(r,$(t,s))}static defaults(r){return e.defaults($(t,r)).Minimatch}},AST:class extends e.AST{constructor(r,s,i={}){super(r,s,$(t,i))}static fromGlob(r,s={}){return e.AST.fromGlob(r,$(t,s))}},unescape:(r,s={})=>e.unescape(r,$(t,s)),escape:(r,s={})=>e.escape(r,$(t,s)),filter:(r,s={})=>e.filter(r,$(t,s)),defaults:r=>e.defaults($(t,r)),makeRe:(r,s={})=>e.makeRe(r,$(t,s)),braceExpand:(r,s={})=>e.braceExpand(r,$(t,s)),match:(r,s,i={})=>e.match(r,s,$(t,i)),sep:e.sep,GLOBSTAR:D})};P.defaults=Yo;var Is=(t,e={})=>(Tt(t),e.nobrace||!/\{(?:(?!\{).)*\}/.test(t)?[t]:ao(t,{max:e.braceExpandMax}));P.braceExpand=Is;var zo=(t,e={})=>new ge(t,e).makeRe();P.makeRe=zo;var Jo=(t,e,r={})=>{let s=new ge(e,r);return t=t.filter(i=>s.match(i)),s.options.nonull&&!t.length&&t.push(e),t};P.match=Jo;var ss=/[?*]|[+@!]\(.*?\)|\[|\]/,Xo=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),ge=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(t,e={}){Tt(t),e=e||{},this.options=e,this.pattern=t,this.platform=e.platform||Os,this.isWindows=this.platform==="win32";let r="allowWindowsEscape";this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e[r]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!e.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!e.nonegate,this.comment=!1,this.empty=!1,this.partial=!!e.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=e.windowsNoMagicRoot!==void 0?e.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let t of this.set)for(let e of t)if(typeof e!="string")return!0;return!1}debug(...t){}make(){let t=this.pattern,e=this.options;if(!e.nocomment&&t.charAt(0)==="#"){this.comment=!0;return}if(!t){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],e.debug&&(this.debug=(...i)=>console.error(...i)),this.debug(this.pattern,this.globSet);let r=this.globSet.map(i=>this.slashSplit(i));this.globParts=this.preprocess(r),this.debug(this.pattern,this.globParts);let s=this.globParts.map((i,n,o)=>{if(this.isWindows&&this.windowsNoMagicRoot){let a=i[0]===""&&i[1]===""&&(i[2]==="?"||!ss.test(i[2]))&&!ss.test(i[3]),l=/^[a-z]:/i.test(i[0]);if(a)return[...i.slice(0,4),...i.slice(4).map(c=>this.parse(c))];if(l)return[i[0],...i.slice(1).map(c=>this.parse(c))]}return i.map(a=>this.parse(a))});if(this.debug(this.pattern,s),this.set=s.filter(i=>i.indexOf(!1)===-1),this.isWindows)for(let i=0;i<this.set.length;i++){let n=this.set[i];n[0]===""&&n[1]===""&&this.globParts[i][2]==="?"&&typeof n[3]=="string"&&/^[a-z]:$/i.test(n[3])&&(n[2]="?")}this.debug(this.pattern,this.set)}preprocess(t){if(this.options.noglobstar)for(let r=0;r<t.length;r++)for(let s=0;s<t[r].length;s++)t[r][s]==="**"&&(t[r][s]="*");let{optimizationLevel:e=1}=this.options;return e>=2?(t=this.firstPhasePreProcess(t),t=this.secondPhasePreProcess(t)):e>=1?t=this.levelOneOptimize(t):t=this.adjascentGlobstarOptimize(t),t}adjascentGlobstarOptimize(t){return t.map(e=>{let r=-1;for(;(r=e.indexOf("**",r+1))!==-1;){let s=r;for(;e[s+1]==="**";)s++;s!==r&&e.splice(r,s-r)}return e})}levelOneOptimize(t){return t.map(e=>(e=e.reduce((r,s)=>{let i=r[r.length-1];return s==="**"&&i==="**"?r:s===".."&&i&&i!==".."&&i!=="."&&i!=="**"?(r.pop(),r):(r.push(s),r)},[]),e.length===0?[""]:e))}levelTwoFileOptimize(t){Array.isArray(t)||(t=this.slashSplit(t));let e=!1;do{if(e=!1,!this.preserveMultipleSlashes){for(let s=1;s<t.length-1;s++){let i=t[s];s===1&&i===""&&t[0]===""||(i==="."||i==="")&&(e=!0,t.splice(s,1),s--)}t[0]==="."&&t.length===2&&(t[1]==="."||t[1]==="")&&(e=!0,t.pop())}let r=0;for(;(r=t.indexOf("..",r+1))!==-1;){let s=t[r-1];s&&s!=="."&&s!==".."&&s!=="**"&&(e=!0,t.splice(r-1,2),r-=2)}}while(e);return t.length===0?[""]:t}firstPhasePreProcess(t){let e=!1;do{e=!1;for(let r of t){let s=-1;for(;(s=r.indexOf("**",s+1))!==-1;){let n=s;for(;r[n+1]==="**";)n++;n>s&&r.splice(s+1,n-s);let o=r[s+1],a=r[s+2],l=r[s+3];if(o!==".."||!a||a==="."||a===".."||!l||l==="."||l==="..")continue;e=!0,r.splice(s,1);let c=r.slice(0);c[s]="**",t.push(c),s--}if(!this.preserveMultipleSlashes){for(let n=1;n<r.length-1;n++){let o=r[n];n===1&&o===""&&r[0]===""||(o==="."||o==="")&&(e=!0,r.splice(n,1),n--)}r[0]==="."&&r.length===2&&(r[1]==="."||r[1]==="")&&(e=!0,r.pop())}let i=0;for(;(i=r.indexOf("..",i+1))!==-1;){let n=r[i-1];if(n&&n!=="."&&n!==".."&&n!=="**"){e=!0;let o=i===1&&r[i+1]==="**"?["."]:[];r.splice(i-1,2,...o),r.length===0&&r.push(""),i-=2}}}}while(e);return t}secondPhasePreProcess(t){for(let e=0;e<t.length-1;e++)for(let r=e+1;r<t.length;r++){let s=this.partsMatch(t[e],t[r],!this.preserveMultipleSlashes);if(s){t[e]=[],t[r]=s;break}}return t.filter(e=>e.length)}partsMatch(t,e,r=!1){let s=0,i=0,n=[],o="";for(;s<t.length&&i<e.length;)if(t[s]===e[i])n.push(o==="b"?e[i]:t[s]),s++,i++;else if(r&&t[s]==="**"&&e[i]===t[s+1])n.push(t[s]),s++;else if(r&&e[i]==="**"&&t[s]===e[i+1])n.push(e[i]),i++;else if(t[s]==="*"&&e[i]&&(this.options.dot||!e[i].startsWith("."))&&e[i]!=="**"){if(o==="b")return!1;o="a",n.push(t[s]),s++,i++}else if(e[i]==="*"&&t[s]&&(this.options.dot||!t[s].startsWith("."))&&t[s]!=="**"){if(o==="a")return!1;o="b",n.push(e[i]),s++,i++}else return!1;return t.length===e.length&&n}parseNegate(){if(this.nonegate)return;let t=this.pattern,e=!1,r=0;for(let s=0;s<t.length&&t.charAt(s)==="!";s++)e=!e,r++;r&&(this.pattern=t.slice(r)),this.negate=e}matchOne(t,e,r=!1){let s=this.options;if(this.isWindows){let m=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),g=!m&&t[0]===""&&t[1]===""&&t[2]==="?"&&/^[a-z]:$/i.test(t[3]),w=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),S=!w&&e[0]===""&&e[1]===""&&e[2]==="?"&&typeof e[3]=="string"&&/^[a-z]:$/i.test(e[3]),E=g?3:m?0:void 0,_=S?3:w?0:void 0;if(typeof E=="number"&&typeof _=="number"){let[b,T]=[t[E],e[_]];b.toLowerCase()===T.toLowerCase()&&(e[_]=b,_>E?e=e.slice(_):E>_&&(t=t.slice(E)))}}let{optimizationLevel:i=1}=this.options;i>=2&&(t=this.levelTwoFileOptimize(t)),this.debug("matchOne",this,{file:t,pattern:e}),this.debug("matchOne",t.length,e.length);for(var n=0,o=0,a=t.length,l=e.length;n<a&&o<l;n++,o++){this.debug("matchOne loop");var c=e[o],u=t[n];if(this.debug(e,c,u),c===!1)return!1;if(c===D){this.debug("GLOBSTAR",[e,c,u]);var h=n,p=o+1;if(p===l){for(this.debug("** at the end");n<a;n++)if(t[n]==="."||t[n]===".."||!s.dot&&t[n].charAt(0)===".")return!1;return!0}for(;h<a;){var f=t[h];if(this.debug(`
11
+ `)}debug(e,r,s,i){this.log(0,e,r,s,i)}info(e,r,s,i){this.log(1,e,r,s,i)}warn(e,r,s,i){this.log(2,e,r,s,i)}setErrorSink(e){ir=e}error(e,r,s,i){this.log(3,e,r,s,i),this.routeErrorToSink(r,s,i)}routeErrorToSink(e,r,s){try{if(!ir||!(s instanceof Error))return;ir(s)}catch{}}dataIn(e,r,s,i){this.info(e,`\u2192 ${r}`,s,i)}dataOut(e,r,s,i){this.info(e,`\u2190 ${r}`,s,i)}success(e,r,s,i){this.info(e,`\u2713 ${r}`,s,i)}failure(e,r,s,i){this.error(e,`\u2717 ${r}`,s,i)}happyPathError(e,r,s,i,n=""){let c=((new Error().stack||"").split(`
12
+ `)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),u=c?`${c[1].split("/").pop()}:${c[2]}`:"unknown",h={...s,location:u};return this.warn(e,`[HAPPY-PATH] ${r}`,h,i),n}},d=new or;var jn={};function In(){return typeof __dirname<"u"?__dirname:(0,_.dirname)((0,Xr.fileURLToPath)(jn.url))}var Yl=In();function Oe(){if(process.env.CLAUDE_MEM_DATA_DIR)return process.env.CLAUDE_MEM_DATA_DIR;let t=(0,_.join)((0,ar.homedir)(),".claude-mem"),e=(0,_.join)(t,"settings.json");try{if((0,He.existsSync)(e)){let r=JSON.parse((0,He.readFileSync)(e,"utf-8")),s=r.env??r;if(s.CLAUDE_MEM_DATA_DIR)return s.CLAUDE_MEM_DATA_DIR}}catch{}return t}var v=Oe(),at=process.env.CLAUDE_CONFIG_DIR||(0,_.join)((0,ar.homedir)(),".claude"),lt=(0,_.join)(at,"plugins","marketplaces","thedotmack"),xn=(0,_.join)(v,"archives"),Ln=(0,_.join)(v,"logs"),Nn=(0,_.join)(v,"trash"),Un=(0,_.join)(v,"backups"),Fn=(0,_.join)(v,"modes"),ct=(0,_.join)(v,"settings.json"),zl=(0,_.join)(v,"claude-mem.db"),Wn=(0,_.join)(v,"vector-db"),ut=(0,_.join)(v,"observer-sessions"),Hn=(0,_.basename)(ut),Jl=(0,_.join)(at,"settings.json"),Xl=(0,_.join)(at,"commands"),ql=(0,_.join)(at,"CLAUDE.md");var R={dataDir:()=>v,workerPid:()=>(0,_.join)(v,"worker.pid"),serverBetaPid:()=>(0,_.join)(v,".server-beta.pid"),serverBetaPort:()=>(0,_.join)(v,".server-beta.port"),serverBetaRuntime:()=>(0,_.join)(v,".server-beta.runtime.json"),settings:()=>(0,_.join)(v,"settings.json"),database:()=>(0,_.join)(v,"claude-mem.db"),chroma:()=>(0,_.join)(v,"chroma"),combinedCerts:()=>(0,_.join)(v,"combined_certs.pem"),transcriptsConfig:()=>(0,_.join)(v,"transcript-watch.json"),transcriptsState:()=>(0,_.join)(v,"transcript-watch-state.json"),corpora:()=>(0,_.join)(v,"corpora"),supervisorRegistry:()=>(0,_.join)(v,"supervisor.json"),envFile:()=>(0,_.join)(v,".env"),logsDir:()=>Ln,archives:()=>xn,trash:()=>Nn,backups:()=>Un,modes:()=>Fn,vectorDb:()=>Wn,observerSessions:()=>ut};var De=R.transcriptsConfig(),ht=R.transcriptsState();var $n={version:1,schemas:{},watches:[],stateFile:ht};function Bn(t){let e=typeof t.schema=="string"?t.schema:t.schema?.name;if(!(t.name==="codex"||e==="codex")||!t.path)return!1;let s=N(t.path).replace(/\\/g,"/"),i=(0,je.join)((0,lr.homedir)(),".codex","sessions").replace(/\\/g,"/");return s===`${i}/**/*.jsonl`}function qr(t){let e=typeof t.schema=="string"?t.schema:t.schema?.name,r=t.name==="codex"&&(!e||e==="codex");return t.context?.mode==="agents"&&r&&Bn(t)}function N(t){return t&&(t.startsWith("~")?(0,je.join)((0,lr.homedir)(),t.slice(1)):t)}function $e(t=De){let e=N(t);if(!(0,ie.existsSync)(e))throw new Error(`Transcript watch config not found: ${e}`);let r=(0,ie.readFileSync)(e,"utf-8"),s=JSON.parse(r);if(!s.version||!s.watches)throw new Error(`Invalid transcript watch config: ${e}`);return s.stateFile||(s.stateFile=ht),s}function dt(t=De){let e=N(t),r=(0,je.dirname)(e);(0,ie.existsSync)(r)||(0,ie.mkdirSync)(r,{recursive:!0}),(0,ie.writeFileSync)(e,JSON.stringify($n,null,2))}var x=require("fs"),J=require("path");var Ps=require("node:url"),Le=require("node:path"),Us=require("node:url"),Q=require("fs"),qo=X(require("node:fs"),1),Se=require("node:fs/promises"),Ct=require("node:events"),yr=X(require("node:stream"),1),Fs=require("node:string_decoder"),ys=(t,e,r)=>{let s=t instanceof RegExp?Vr(t,r):t,i=e instanceof RegExp?Vr(e,r):e,n=s!==null&&i!=null&&Gn(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=(t,e)=>{let r=e.match(t);return r?r[0]:null},Gn=(t,e,r)=>{let s,i,n,o,a,l=r.indexOf(t),c=r.indexOf(e,l+1),u=l;if(l>=0&&c>0){if(t===e)return[l,c];for(s=[],n=r.length;u>=0&&!a;){if(u===l)s.push(u),l=r.indexOf(t,u+1);else if(s.length===1){let h=s.pop();h!==void 0&&(a=[h,c])}else i=s.pop(),i!==void 0&&i<n&&(n=i,o=c),c=r.indexOf(e,u+1);u=l<c&&l>=0?l:c}s.length&&o!==void 0&&(a=[n,o])}return a},_s="\0SLASH"+Math.random()+"\0",bs="\0OPEN"+Math.random()+"\0",Er="\0CLOSE"+Math.random()+"\0",vs="\0COMMA"+Math.random()+"\0",Ts="\0PERIOD"+Math.random()+"\0",Kn=new RegExp(_s,"g"),Yn=new RegExp(bs,"g"),zn=new RegExp(Er,"g"),Jn=new RegExp(vs,"g"),Xn=new RegExp(Ts,"g"),qn=/\\\\/g,Vn=/\\{/g,Qn=/\\}/g,Zn=/\\,/g,eo=/\\./g,to=1e5;function cr(t){return isNaN(t)?t.charCodeAt(0):parseInt(t,10)}function ro(t){return t.replace(qn,_s).replace(Vn,bs).replace(Qn,Er).replace(Zn,vs).replace(eo,Ts)}function so(t){return t.replace(Kn,"\\").replace(Yn,"{").replace(zn,"}").replace(Jn,",").replace(Xn,".")}function Ms(t){if(!t)return[""];let e=[],r=ys("{","}",t);if(!r)return t.split(",");let{pre:s,body:i,post:n}=r,o=s.split(",");o[o.length-1]+="{"+i+"}";let a=Ms(n);return n.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),e.push.apply(e,o),e}function io(t,e={}){if(!t)return[];let{max:r=to}=e;return t.slice(0,2)==="{}"&&(t="\\{\\}"+t.slice(2)),Xe(ro(t),r,!0).map(so)}function no(t){return"{"+t+"}"}function oo(t){return/^-?0\d/.test(t)}function ao(t,e){return t<=e}function lo(t,e){return t>=e}function Xe(t,e,r){let s=[],i=ys("{","}",t);if(!i)return[t];let n=i.pre,o=i.post.length?Xe(i.post,e,!1):[""];if(/\$$/.test(i.pre))for(let a=0;a<o.length&&a<e;a++){let l=n+"{"+i.body+"}"+o[a];s.push(l)}else{let a=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(i.body),l=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(i.body),c=a||l,u=i.body.indexOf(",")>=0;if(!c&&!u)return i.post.match(/,(?!,).*\}/)?(t=i.pre+"{"+i.body+Er+i.post,Xe(t,e,!0)):[t];let h;if(c)h=i.body.split(/\.\./);else if(h=Ms(i.body),h.length===1&&h[0]!==void 0&&(h=Xe(h[0],e,!1).map(no),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=cr(h[0]),m=cr(h[1]),g=Math.max(h[0].length,h[1].length),w=h.length===3&&h[2]!==void 0?Math.abs(cr(h[2])):1,S=ao;m<f&&(w*=-1,S=lo);let E=h.some(oo);p=[];for(let y=f;S(y,m);y+=w){let b;if(l)b=String.fromCharCode(y),b==="\\"&&(b="");else if(b=String(y),E){let T=g-b.length;if(T>0){let pe=new Array(T+1).join("0");y<0?b="-"+pe+b.slice(1):b=pe+b}}p.push(b)}}else{p=[];for(let f=0;f<h.length;f++)p.push.apply(p,Xe(h[f],e,!1))}for(let f=0;f<p.length;f++)for(let m=0;m<o.length&&s.length<e;m++){let g=n+p[f]+o[m];(!r||c||g)&&s.push(g)}}return s}var vt=t=>{if(typeof t!="string")throw new TypeError("invalid pattern");if(t.length>65536)throw new TypeError("pattern is too long")},co={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},Be=t=>t.replace(/[[\]\\-]/g,"\\$&"),uo=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Qr=t=>t.join(""),ho=(t,e)=>{let r=e;if(t.charAt(r)!=="[")throw new Error("not in a brace expression");let s=[],i=[],n=r+1,o=!1,a=!1,l=!1,c=!1,u=r,h="";e:for(;n<t.length;){let m=t.charAt(n);if((m==="!"||m==="^")&&n===r+1){c=!0,n++;continue}if(m==="]"&&o&&!l){u=n+1;break}if(o=!0,m==="\\"&&!l){l=!0,n++;continue}if(m==="["&&!l){for(let[g,[w,S,E]]of Object.entries(co))if(t.startsWith(g,n)){if(h)return["$.",!1,t.length-r,!0];n+=g.length,E?i.push(w):s.push(w),a=a||S;continue e}}if(l=!1,h){m>h?s.push(Be(h)+"-"+Be(m)):m===h&&s.push(Be(m)),h="",n++;continue}if(t.startsWith("-]",n+1)){s.push(Be(m+"-")),n+=2;continue}if(t.startsWith("-",n+1)){h=m,n+=2;continue}s.push(Be(m)),n++}if(u<n)return["",!1,0,!1];if(!s.length&&!i.length)return["$.",!1,t.length-r,!0];if(i.length===0&&s.length===1&&/^\\?.$/.test(s[0])&&!c){let m=s[0].length===2?s[0].slice(-1):s[0];return[uo(m),!1,u-r,!1]}let p="["+(c?"^":"")+Qr(s)+"]",f="["+(c?"":"^")+Qr(i)+"]";return[s.length&&i.length?"("+p+"|"+f+")":s.length?p:f,a,u-r,!0]},xe=(t,{windowsPathsNoEscape:e=!1,magicalBraces:r=!0}={})=>r?e?t.replace(/\[([^\/\\])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):e?t.replace(/\[([^\/\\{}])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1"),po=new Set(["!","?","+","*","@"]),Zr=t=>po.has(t),fo="(?!(?:^|/)\\.\\.?(?:$|/))",pt="(?!\\.)",mo=new Set(["[","."]),go=new Set(["..","."]),So=new Set("().*{}+?[]^$\\!"),Eo=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),wr="[^/]",es=wr+"*?",ts=wr+"+?",As=class F{type;#e;#r;#n=!1;#i=[];#o;#y;#S;#u=!1;#a;#d;#h=!1;constructor(e,r,s={}){this.type=e,e&&(this.#r=!0),this.#o=r,this.#e=this.#o?this.#o.#e:this,this.#a=this.#e===this?s:this.#e.#a,this.#S=this.#e===this?[]:this.#e.#S,e==="!"&&!this.#e.#u&&this.#S.push(this),this.#y=this.#o?this.#o.#i.length:0}get hasMagic(){if(this.#r!==void 0)return this.#r;for(let e of this.#i)if(typeof e!="string"&&(e.type||e.hasMagic))return this.#r=!0;return this.#r}toString(){return this.#d!==void 0?this.#d:this.type?this.#d=this.type+"("+this.#i.map(e=>String(e)).join("|")+")":this.#d=this.#i.map(e=>String(e)).join("")}#l(){if(this!==this.#e)throw new Error("should only call on root");if(this.#u)return this;this.toString(),this.#u=!0;let e;for(;e=this.#S.pop();){if(e.type!=="!")continue;let r=e,s=r.#o;for(;s;){for(let i=r.#y+1;!s.type&&i<s.#i.length;i++)for(let n of e.#i){if(typeof n=="string")throw new Error("string part in extglob AST??");n.copyIn(s.#i[i])}r=s,s=r.#o}}return this}push(...e){for(let r of e)if(r!==""){if(typeof r!="string"&&!(r instanceof F&&r.#o===this))throw new Error("invalid part: "+r);this.#i.push(r)}}toJSON(){let e=this.type===null?this.#i.slice().map(r=>typeof r=="string"?r:r.toJSON()):[this.type,...this.#i.map(r=>r.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#u&&this.#o?.type==="!")&&e.push({}),e}isStart(){if(this.#e===this)return!0;if(!this.#o?.isStart())return!1;if(this.#y===0)return!0;let e=this.#o;for(let r=0;r<this.#y;r++){let s=e.#i[r];if(!(s instanceof F&&s.type==="!"))return!1}return!0}isEnd(){if(this.#e===this||this.#o?.type==="!")return!0;if(!this.#o?.isEnd())return!1;if(!this.type)return this.#o?.isEnd();let e=this.#o?this.#o.#i.length:0;return this.#y===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this))}clone(e){let r=new F(this.type,e);for(let s of this.#i)r.copyIn(s);return r}static#s(e,r,s,i){let n=!1,o=!1,a=-1,l=!1;if(r.type===null){let f=s,m="";for(;f<e.length;){let g=e.charAt(f++);if(n||g==="\\"){n=!n,m+=g;continue}if(o){f===a+1?(g==="^"||g==="!")&&(l=!0):g==="]"&&!(f===a+2&&l)&&(o=!1),m+=g;continue}else if(g==="["){o=!0,a=f,l=!1,m+=g;continue}if(!i.noext&&Zr(g)&&e.charAt(f)==="("){r.push(m),m="";let w=new F(g,r);f=F.#s(e,w,f,i),r.push(w);continue}m+=g}return r.push(m),f}let c=s+1,u=new F(null,r),h=[],p="";for(;c<e.length;){let f=e.charAt(c++);if(n||f==="\\"){n=!n,p+=f;continue}if(o){c===a+1?(f==="^"||f==="!")&&(l=!0):f==="]"&&!(c===a+2&&l)&&(o=!1),p+=f;continue}else if(f==="["){o=!0,a=c,l=!1,p+=f;continue}if(Zr(f)&&e.charAt(c)==="("){u.push(p),p="";let m=new F(f,u);u.push(m),c=F.#s(e,m,c,i);continue}if(f==="|"){u.push(p),p="",h.push(u),u=new F(null,r);continue}if(f===")")return p===""&&r.#i.length===0&&(r.#h=!0),u.push(p),p="",r.push(...h,u),c;p+=f}return r.type=null,r.#r=void 0,r.#i=[e.substring(s-1)],c}static fromGlob(e,r={}){let s=new F(null,void 0,r);return F.#s(e,s,0,r),s}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let e=this.toString(),[r,s,i,n]=this.toRegExpSource();if(!(i||this.#r||this.#a.nocase&&!this.#a.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return s;let o=(this.#a.nocase?"i":"")+(n?"u":"");return Object.assign(new RegExp(`^${r}$`,o),{_src:r,_glob:e})}get options(){return this.#a}toRegExpSource(e){let r=e??!!this.#a.dot;if(this.#e===this&&this.#l(),!this.type){let l=this.isStart()&&this.isEnd()&&!this.#i.some(p=>typeof p!="string"),c=this.#i.map(p=>{let[f,m,g,w]=typeof p=="string"?F.#_(p,this.#r,l):p.toRegExpSource(e);return this.#r=this.#r||g,this.#n=this.#n||w,f}).join(""),u="";if(this.isStart()&&typeof this.#i[0]=="string"&&!(this.#i.length===1&&go.has(this.#i[0]))){let p=mo,f=r&&p.has(c.charAt(0))||c.startsWith("\\.")&&p.has(c.charAt(2))||c.startsWith("\\.\\.")&&p.has(c.charAt(4)),m=!r&&!e&&p.has(c.charAt(0));u=f?fo:m?pt:""}let h="";return this.isEnd()&&this.#e.#u&&this.#o?.type==="!"&&(h="(?:$|\\/)"),[u+c+h,xe(c),this.#r=!!this.#r,this.#n]}let s=this.type==="*"||this.type==="+",i=this.type==="!"?"(?:(?!(?:":"(?:",n=this.#p(r);if(this.isStart()&&this.isEnd()&&!n&&this.type!=="!"){let l=this.toString();return this.#i=[l],this.type=null,this.#r=void 0,[l,xe(this.toString()),!1,!1]}let o=!s||e||r||!pt?"":this.#p(!0);o===n&&(o=""),o&&(n=`(?:${n})(?:${o})*?`);let a="";if(this.type==="!"&&this.#h)a=(this.isStart()&&!r?pt:"")+ts;else{let l=this.type==="!"?"))"+(this.isStart()&&!r&&!e?pt:"")+es+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;a=i+n+l}return[a,xe(n),this.#r=!!this.#r,this.#n]}#p(e){return this.#i.map(r=>{if(typeof r=="string")throw new Error("string type in extglob ast??");let[s,i,n,o]=r.toRegExpSource(e);return this.#n=this.#n||o,s}).filter(r=>!(this.isStart()&&this.isEnd())||!!r).join("|")}static#_(e,r,s=!1){let i=!1,n="",o=!1,a=!1;for(let l=0;l<e.length;l++){let c=e.charAt(l);if(i){i=!1,n+=(So.has(c)?"\\":"")+c;continue}if(c==="*"){if(a)continue;a=!0,n+=s&&/^[*]+$/.test(e)?ts:es,r=!0;continue}else a=!1;if(c==="\\"){l===e.length-1?n+="\\\\":i=!0;continue}if(c==="["){let[u,h,p,f]=ho(e,l);if(p){n+=u,o=o||h,l+=p-1,r=r||f;continue}}if(c==="?"){n+=wr,r=!0;continue}n+=Eo(c)}return[n,xe(e),!!r,o]}},Cs=(t,{windowsPathsNoEscape:e=!1,magicalBraces:r=!1}={})=>r?e?t.replace(/[?*()[\]{}]/g,"[$&]"):t.replace(/[?*()[\]\\{}]/g,"\\$&"):e?t.replace(/[?*()[\]]/g,"[$&]"):t.replace(/[?*()[\]\\]/g,"\\$&"),I=(t,e,r={})=>(vt(e),!r.nocomment&&e.charAt(0)==="#"?!1:new ge(e,r).match(t)),wo=/^\*+([^+@!?\*\[\(]*)$/,yo=t=>e=>!e.startsWith(".")&&e.endsWith(t),_o=t=>e=>e.endsWith(t),bo=t=>(t=t.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(t)),vo=t=>(t=t.toLowerCase(),e=>e.toLowerCase().endsWith(t)),To=/^\*+\.\*+$/,Mo=t=>!t.startsWith(".")&&t.includes("."),Ao=t=>t!=="."&&t!==".."&&t.includes("."),Co=/^\.\*+$/,ko=t=>t!=="."&&t!==".."&&t.startsWith("."),Ro=/^\*+$/,Oo=t=>t.length!==0&&!t.startsWith("."),Do=t=>t.length!==0&&t!=="."&&t!=="..",Po=/^\?+([^+@!?\*\[\(]*)?$/,Io=([t,e=""])=>{let r=ks([t]);return e?(e=e.toLowerCase(),s=>r(s)&&s.toLowerCase().endsWith(e)):r},xo=([t,e=""])=>{let r=Rs([t]);return e?(e=e.toLowerCase(),s=>r(s)&&s.toLowerCase().endsWith(e)):r},Lo=([t,e=""])=>{let r=Rs([t]);return e?s=>r(s)&&s.endsWith(e):r},No=([t,e=""])=>{let r=ks([t]);return e?s=>r(s)&&s.endsWith(e):r},ks=([t])=>{let e=t.length;return r=>r.length===e&&!r.startsWith(".")},Rs=([t])=>{let e=t.length;return r=>r.length===e&&r!=="."&&r!==".."},Os=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",rs={win32:{sep:"\\"},posix:{sep:"/"}},Uo=Os==="win32"?rs.win32.sep:rs.posix.sep;I.sep=Uo;var P=Symbol("globstar **");I.GLOBSTAR=P;var Fo="[^/]",Wo=Fo+"*?",Ho="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",jo="(?:(?!(?:\\/|^)\\.).)*?",$o=(t,e={})=>r=>I(r,t,e);I.filter=$o;var W=(t,e={})=>Object.assign({},t,e),Bo=t=>{if(!t||typeof t!="object"||!Object.keys(t).length)return I;let e=I;return Object.assign((r,s,i={})=>e(r,s,W(t,i)),{Minimatch:class extends e.Minimatch{constructor(r,s={}){super(r,W(t,s))}static defaults(r){return e.defaults(W(t,r)).Minimatch}},AST:class extends e.AST{constructor(r,s,i={}){super(r,s,W(t,i))}static fromGlob(r,s={}){return e.AST.fromGlob(r,W(t,s))}},unescape:(r,s={})=>e.unescape(r,W(t,s)),escape:(r,s={})=>e.escape(r,W(t,s)),filter:(r,s={})=>e.filter(r,W(t,s)),defaults:r=>e.defaults(W(t,r)),makeRe:(r,s={})=>e.makeRe(r,W(t,s)),braceExpand:(r,s={})=>e.braceExpand(r,W(t,s)),match:(r,s,i={})=>e.match(r,s,W(t,i)),sep:e.sep,GLOBSTAR:P})};I.defaults=Bo;var Ds=(t,e={})=>(vt(t),e.nobrace||!/\{(?:(?!\{).)*\}/.test(t)?[t]:io(t,{max:e.braceExpandMax}));I.braceExpand=Ds;var Go=(t,e={})=>new ge(t,e).makeRe();I.makeRe=Go;var Ko=(t,e,r={})=>{let s=new ge(e,r);return t=t.filter(i=>s.match(i)),s.options.nonull&&!t.length&&t.push(e),t};I.match=Ko;var ss=/[?*]|[+@!]\(.*?\)|\[|\]/,Yo=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),ge=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(t,e={}){vt(t),e=e||{},this.options=e,this.pattern=t,this.platform=e.platform||Os,this.isWindows=this.platform==="win32";let r="allowWindowsEscape";this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e[r]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!e.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!e.nonegate,this.comment=!1,this.empty=!1,this.partial=!!e.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=e.windowsNoMagicRoot!==void 0?e.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let t of this.set)for(let e of t)if(typeof e!="string")return!0;return!1}debug(...t){}make(){let t=this.pattern,e=this.options;if(!e.nocomment&&t.charAt(0)==="#"){this.comment=!0;return}if(!t){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],e.debug&&(this.debug=(...i)=>console.error(...i)),this.debug(this.pattern,this.globSet);let r=this.globSet.map(i=>this.slashSplit(i));this.globParts=this.preprocess(r),this.debug(this.pattern,this.globParts);let s=this.globParts.map((i,n,o)=>{if(this.isWindows&&this.windowsNoMagicRoot){let a=i[0]===""&&i[1]===""&&(i[2]==="?"||!ss.test(i[2]))&&!ss.test(i[3]),l=/^[a-z]:/i.test(i[0]);if(a)return[...i.slice(0,4),...i.slice(4).map(c=>this.parse(c))];if(l)return[i[0],...i.slice(1).map(c=>this.parse(c))]}return i.map(a=>this.parse(a))});if(this.debug(this.pattern,s),this.set=s.filter(i=>i.indexOf(!1)===-1),this.isWindows)for(let i=0;i<this.set.length;i++){let n=this.set[i];n[0]===""&&n[1]===""&&this.globParts[i][2]==="?"&&typeof n[3]=="string"&&/^[a-z]:$/i.test(n[3])&&(n[2]="?")}this.debug(this.pattern,this.set)}preprocess(t){if(this.options.noglobstar)for(let r=0;r<t.length;r++)for(let s=0;s<t[r].length;s++)t[r][s]==="**"&&(t[r][s]="*");let{optimizationLevel:e=1}=this.options;return e>=2?(t=this.firstPhasePreProcess(t),t=this.secondPhasePreProcess(t)):e>=1?t=this.levelOneOptimize(t):t=this.adjascentGlobstarOptimize(t),t}adjascentGlobstarOptimize(t){return t.map(e=>{let r=-1;for(;(r=e.indexOf("**",r+1))!==-1;){let s=r;for(;e[s+1]==="**";)s++;s!==r&&e.splice(r,s-r)}return e})}levelOneOptimize(t){return t.map(e=>(e=e.reduce((r,s)=>{let i=r[r.length-1];return s==="**"&&i==="**"?r:s===".."&&i&&i!==".."&&i!=="."&&i!=="**"?(r.pop(),r):(r.push(s),r)},[]),e.length===0?[""]:e))}levelTwoFileOptimize(t){Array.isArray(t)||(t=this.slashSplit(t));let e=!1;do{if(e=!1,!this.preserveMultipleSlashes){for(let s=1;s<t.length-1;s++){let i=t[s];s===1&&i===""&&t[0]===""||(i==="."||i==="")&&(e=!0,t.splice(s,1),s--)}t[0]==="."&&t.length===2&&(t[1]==="."||t[1]==="")&&(e=!0,t.pop())}let r=0;for(;(r=t.indexOf("..",r+1))!==-1;){let s=t[r-1];s&&s!=="."&&s!==".."&&s!=="**"&&(e=!0,t.splice(r-1,2),r-=2)}}while(e);return t.length===0?[""]:t}firstPhasePreProcess(t){let e=!1;do{e=!1;for(let r of t){let s=-1;for(;(s=r.indexOf("**",s+1))!==-1;){let n=s;for(;r[n+1]==="**";)n++;n>s&&r.splice(s+1,n-s);let o=r[s+1],a=r[s+2],l=r[s+3];if(o!==".."||!a||a==="."||a===".."||!l||l==="."||l==="..")continue;e=!0,r.splice(s,1);let c=r.slice(0);c[s]="**",t.push(c),s--}if(!this.preserveMultipleSlashes){for(let n=1;n<r.length-1;n++){let o=r[n];n===1&&o===""&&r[0]===""||(o==="."||o==="")&&(e=!0,r.splice(n,1),n--)}r[0]==="."&&r.length===2&&(r[1]==="."||r[1]==="")&&(e=!0,r.pop())}let i=0;for(;(i=r.indexOf("..",i+1))!==-1;){let n=r[i-1];if(n&&n!=="."&&n!==".."&&n!=="**"){e=!0;let o=i===1&&r[i+1]==="**"?["."]:[];r.splice(i-1,2,...o),r.length===0&&r.push(""),i-=2}}}}while(e);return t}secondPhasePreProcess(t){for(let e=0;e<t.length-1;e++)for(let r=e+1;r<t.length;r++){let s=this.partsMatch(t[e],t[r],!this.preserveMultipleSlashes);if(s){t[e]=[],t[r]=s;break}}return t.filter(e=>e.length)}partsMatch(t,e,r=!1){let s=0,i=0,n=[],o="";for(;s<t.length&&i<e.length;)if(t[s]===e[i])n.push(o==="b"?e[i]:t[s]),s++,i++;else if(r&&t[s]==="**"&&e[i]===t[s+1])n.push(t[s]),s++;else if(r&&e[i]==="**"&&t[s]===e[i+1])n.push(e[i]),i++;else if(t[s]==="*"&&e[i]&&(this.options.dot||!e[i].startsWith("."))&&e[i]!=="**"){if(o==="b")return!1;o="a",n.push(t[s]),s++,i++}else if(e[i]==="*"&&t[s]&&(this.options.dot||!t[s].startsWith("."))&&t[s]!=="**"){if(o==="a")return!1;o="b",n.push(e[i]),s++,i++}else return!1;return t.length===e.length&&n}parseNegate(){if(this.nonegate)return;let t=this.pattern,e=!1,r=0;for(let s=0;s<t.length&&t.charAt(s)==="!";s++)e=!e,r++;r&&(this.pattern=t.slice(r)),this.negate=e}matchOne(t,e,r=!1){let s=this.options;if(this.isWindows){let m=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),g=!m&&t[0]===""&&t[1]===""&&t[2]==="?"&&/^[a-z]:$/i.test(t[3]),w=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),S=!w&&e[0]===""&&e[1]===""&&e[2]==="?"&&typeof e[3]=="string"&&/^[a-z]:$/i.test(e[3]),E=g?3:m?0:void 0,y=S?3:w?0:void 0;if(typeof E=="number"&&typeof y=="number"){let[b,T]=[t[E],e[y]];b.toLowerCase()===T.toLowerCase()&&(e[y]=b,y>E?e=e.slice(y):E>y&&(t=t.slice(E)))}}let{optimizationLevel:i=1}=this.options;i>=2&&(t=this.levelTwoFileOptimize(t)),this.debug("matchOne",this,{file:t,pattern:e}),this.debug("matchOne",t.length,e.length);for(var n=0,o=0,a=t.length,l=e.length;n<a&&o<l;n++,o++){this.debug("matchOne loop");var c=e[o],u=t[n];if(this.debug(e,c,u),c===!1)return!1;if(c===P){this.debug("GLOBSTAR",[e,c,u]);var h=n,p=o+1;if(p===l){for(this.debug("** at the end");n<a;n++)if(t[n]==="."||t[n]===".."||!s.dot&&t[n].charAt(0)===".")return!1;return!0}for(;h<a;){var f=t[h];if(this.debug(`
13
13
  globstar while`,t,h,e,p,f),this.matchOne(t.slice(h),e.slice(p),r))return this.debug("globstar found match!",h,a,f),!0;if(f==="."||f===".."||!s.dot&&f.charAt(0)==="."){this.debug("dot detected!",t,h,e,p);break}this.debug("globstar swallow a segment, and continue"),h++}return!!(r&&(this.debug(`
14
- >>> no match, partial?`,t,h,e,p),h===a))}let m;if(typeof c=="string"?(m=u===c,this.debug("string match",c,u,m)):(m=c.test(u),this.debug("pattern match",c,u,m)),!m)return!1}if(n===a&&o===l)return!0;if(n===a)return r;if(o===l)return n===a-1&&t[n]==="";throw new Error("wtf?")}braceExpand(){return Is(this.pattern,this.options)}parse(t){Tt(t);let e=this.options;if(t==="**")return D;if(t==="")return"";let r,s=null;(r=t.match(Do))?s=e.dot?xo:Po:(r=t.match(bo))?s=(e.nocase?e.dot?ko:Mo:e.dot?To:vo)(r[1]):(r=t.match(Lo))?s=(e.nocase?e.dot?Uo:No:e.dot?Fo:Wo)(r):(r=t.match(Co))?s=e.dot?Ro:Ao:(r=t.match(Oo))&&(s=Io);let i=ks.fromGlob(t,this.options).toMMPattern();return s&&typeof i=="object"&&Reflect.defineProperty(i,"test",{value:s}),i}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let t=this.set;if(!t.length)return this.regexp=!1,this.regexp;let e=this.options,r=e.noglobstar?jo:e.dot?Bo:Go,s=new Set(e.nocase?["i"]:[]),i=t.map(a=>{let l=a.map(u=>{if(u instanceof RegExp)for(let h of u.flags.split(""))s.add(h);return typeof u=="string"?Xo(u):u===D?D:u._src});l.forEach((u,h)=>{let p=l[h+1],f=l[h-1];u!==D||f===D||(f===void 0?p!==void 0&&p!==D?l[h+1]="(?:\\/|"+r+"\\/)?"+p:l[h]=r:p===void 0?l[h-1]=f+"(?:\\/|\\/"+r+")?":p!==D&&(l[h-1]=f+"(?:\\/|\\/"+r+"\\/)"+p,l[h+1]=D))});let c=l.filter(u=>u!==D);if(this.partial&&c.length>=1){let u=[];for(let h=1;h<=c.length;h++)u.push(c.slice(0,h).join("/"));return"(?:"+u.join("|")+")"}return c.join("/")}).join("|"),[n,o]=t.length>1?["(?:",")"]:["",""];i="^"+n+i+o+"$",this.partial&&(i="^(?:\\/|"+n+i.slice(1,-1)+o+")$"),this.negate&&(i="^(?!"+i+").+$");try{this.regexp=new RegExp(i,[...s].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(t){return this.preserveMultipleSlashes?t.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(t)?["",...t.split(/\/+/)]:t.split(/\/+/)}match(t,e=this.partial){if(this.debug("match",t,this.pattern),this.comment)return!1;if(this.empty)return t==="";if(t==="/"&&e)return!0;let r=this.options;this.isWindows&&(t=t.split("\\").join("/"));let s=this.slashSplit(t);this.debug(this.pattern,"split",s);let i=this.set;this.debug(this.pattern,"set",i);let n=s[s.length-1];if(!n)for(let o=s.length-2;!n&&o>=0;o--)n=s[o];for(let o=0;o<i.length;o++){let a=i[o],l=s;if(r.matchBase&&a.length===1&&(l=[n]),this.matchOne(l,a,e))return r.flipNegate?!0:!this.negate}return r.flipNegate?!1:this.negate}static defaults(t){return P.defaults(t).Minimatch}};P.AST=ks;P.Minimatch=ge;P.escape=Cs;P.unescape=xe;var qo=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Ps=new Set,Sr=typeof process=="object"&&process?process:{},xs=(t,e,r,s)=>{typeof Sr.emitWarning=="function"?Sr.emitWarning(t,e,r,s):console.error(`[${r}] ${e}: ${t}`)},Mt=globalThis.AbortController,is=globalThis.AbortSignal;if(typeof Mt>"u"){is=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,s){this._onabort.push(s)}},Mt=class{constructor(){e()}signal=new is;abort(r){if(!this.signal.aborted){this.signal.reason=r,this.signal.aborted=!0;for(let s of this.signal._onabort)s(r);this.signal.onabort?.(r)}}};let t=Sr.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,xs("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var Vo=t=>!Ps.has(t),me=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),Ls=t=>me(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?bt:null:null,bt=class extends Array{constructor(t){super(t),this.fill(0)}},Qo=class qe{heap;length;static#e=!1;static create(e){let r=Ls(e);if(!r)return[];qe.#e=!0;let s=new qe(e,r);return qe.#e=!1,s}constructor(e,r){if(!qe.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new r(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},Ct=class Ns{#e;#r;#n;#i;#o;#_;#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;#y;#w;#f;#A;#m;#T;#M;#g;#E;#b;#k;#t;#x;static unsafeExposeInternals(e){return{starts:e.#M,ttls:e.#g,autopurgeTimers:e.#E,sizes:e.#T,keyMap:e.#h,keyList:e.#l,valList:e.#s,next:e.#p,prev:e.#y,get head(){return e.#w},get tail(){return e.#f},free:e.#A,isBackgroundFetch:r=>e.#c(r),backgroundFetch:(r,s,i,n)=>e.#j(r,s,i,n),moveToTail:r=>e.#N(r),indexes:r=>e.#O(r),rindexes:r=>e.#I(r),isStale:r=>e.#v(r)}}get max(){return this.#e}get maxSize(){return this.#r}get calculatedSize(){return this.#d}get size(){return this.#a}get fetchMethod(){return this.#_}get memoMethod(){return this.#S}get dispose(){return this.#n}get onInsert(){return this.#i}get disposeAfter(){return this.#o}constructor(e){let{max:r=0,ttl:s,ttlResolution:i=1,ttlAutopurge:n,updateAgeOnGet:o,updateAgeOnHas:a,allowStale:l,dispose:c,onInsert:u,disposeAfter:h,noDisposeOnSet:p,noUpdateTTL:f,maxSize:m=0,maxEntrySize:g=0,sizeCalculation:w,fetchMethod:S,memoMethod:E,noDeleteOnFetchRejection:_,noDeleteOnStaleGet:b,allowStaleOnFetchRejection:T,allowStaleOnFetchAbort:pe,ignoreFetchAbort:Ce,perf:Ae}=e;if(Ae!==void 0&&typeof Ae?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#u=Ae??qo,r!==0&&!me(r))throw new TypeError("max option must be a nonnegative integer");let Re=r?Ls(r):Array;if(!Re)throw new Error("invalid max value: "+r);if(this.#e=r,this.#r=m,this.maxEntrySize=g||this.#r,this.sizeCalculation=w,this.sizeCalculation){if(!this.#r&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(E!==void 0&&typeof E!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#S=E,S!==void 0&&typeof S!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#_=S,this.#k=!!S,this.#h=new Map,this.#l=new Array(r).fill(void 0),this.#s=new Array(r).fill(void 0),this.#p=new Re(r),this.#y=new Re(r),this.#w=0,this.#f=0,this.#A=Qo.create(r),this.#a=0,this.#d=0,typeof c=="function"&&(this.#n=c),typeof u=="function"&&(this.#i=u),typeof h=="function"?(this.#o=h,this.#m=[]):(this.#o=void 0,this.#m=void 0),this.#b=!!this.#n,this.#x=!!this.#i,this.#t=!!this.#o,this.noDisposeOnSet=!!p,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!_,this.allowStaleOnFetchRejection=!!T,this.allowStaleOnFetchAbort=!!pe,this.ignoreFetchAbort=!!Ce,this.maxEntrySize!==0){if(this.#r!==0&&!me(this.#r))throw new TypeError("maxSize must be a positive integer if specified");if(!me(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#G()}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!b,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!a,this.ttlResolution=me(i)||i===0?i:1,this.ttlAutopurge=!!n,this.ttl=s||0,this.ttl){if(!me(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#D()}if(this.#e===0&&this.ttl===0&&this.#r===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#e&&!this.#r){let tr="LRU_CACHE_UNBOUNDED";Vo(tr)&&(Ps.add(tr),xs("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",tr,Ns))}}getRemainingTTL(e){return this.#h.has(e)?1/0:0}#D(){let e=new bt(this.#e),r=new bt(this.#e);this.#g=e,this.#M=r;let s=this.ttlAutopurge?new Array(this.#e):void 0;this.#E=s,this.#F=(o,a,l=this.#u.now())=>{if(r[o]=a!==0?l:0,e[o]=a,s?.[o]&&(clearTimeout(s[o]),s[o]=void 0),a!==0&&s){let c=setTimeout(()=>{this.#v(o)&&this.#R(this.#l[o],"expire")},a+1);c.unref&&c.unref(),s[o]=c}},this.#C=o=>{r[o]=e[o]!==0?this.#u.now():0},this.#P=(o,a)=>{if(e[a]){let l=e[a],c=r[a];if(!l||!c)return;o.ttl=l,o.start=c,o.now=i||n();let u=o.now-c;o.remainingTTL=l-u}};let i=0,n=()=>{let o=this.#u.now();if(this.ttlResolution>0){i=o;let a=setTimeout(()=>i=0,this.ttlResolution);a.unref&&a.unref()}return o};this.getRemainingTTL=o=>{let a=this.#h.get(o);if(a===void 0)return 0;let l=e[a],c=r[a];if(!l||!c)return 1/0;let u=(i||n())-c;return l-u},this.#v=o=>{let a=r[o],l=e[o];return!!l&&!!a&&(i||n())-a>l}}#C=()=>{};#P=()=>{};#F=()=>{};#v=()=>!1;#G(){let e=new bt(this.#e);this.#d=0,this.#T=e,this.#U=r=>{this.#d-=e[r],e[r]=0},this.#W=(r,s,i,n)=>{if(this.#c(s))return 0;if(!me(i))if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(i=n(s,r),!me(i))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return i},this.#L=(r,s,i)=>{if(e[r]=s,this.#r){let n=this.#r-e[r];for(;this.#d>n;)this.#H(!0)}this.#d+=e[r],i&&(i.entrySize=s,i.totalCalculatedSize=this.#d)}}#U=e=>{};#L=(e,r,s)=>{};#W=(e,r,s,i)=>{if(s||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#O({allowStale:e=this.allowStale}={}){if(this.#a)for(let r=this.#f;!(!this.#$(r)||((e||!this.#v(r))&&(yield r),r===this.#w));)r=this.#y[r]}*#I({allowStale:e=this.allowStale}={}){if(this.#a)for(let r=this.#w;!(!this.#$(r)||((e||!this.#v(r))&&(yield r),r===this.#f));)r=this.#p[r]}#$(e){return e!==void 0&&this.#h.get(this.#l[e])===e}*entries(){for(let e of this.#O())this.#s[e]!==void 0&&this.#l[e]!==void 0&&!this.#c(this.#s[e])&&(yield[this.#l[e],this.#s[e]])}*rentries(){for(let e of this.#I())this.#s[e]!==void 0&&this.#l[e]!==void 0&&!this.#c(this.#s[e])&&(yield[this.#l[e],this.#s[e]])}*keys(){for(let e of this.#O()){let r=this.#l[e];r!==void 0&&!this.#c(this.#s[e])&&(yield r)}}*rkeys(){for(let e of this.#I()){let r=this.#l[e];r!==void 0&&!this.#c(this.#s[e])&&(yield r)}}*values(){for(let e of this.#O())this.#s[e]!==void 0&&!this.#c(this.#s[e])&&(yield this.#s[e])}*rvalues(){for(let e of this.#I())this.#s[e]!==void 0&&!this.#c(this.#s[e])&&(yield this.#s[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,r={}){for(let s of this.#O()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;if(n!==void 0&&e(n,this.#l[s],this))return this.get(this.#l[s],r)}}forEach(e,r=this){for(let s of this.#O()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;n!==void 0&&e.call(r,n,this.#l[s],this)}}rforEach(e,r=this){for(let s of this.#I()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;n!==void 0&&e.call(r,n,this.#l[s],this)}}purgeStale(){let e=!1;for(let r of this.#I({allowStale:!0}))this.#v(r)&&(this.#R(this.#l[r],"expire"),e=!0);return e}info(e){let r=this.#h.get(e);if(r===void 0)return;let s=this.#s[r],i=this.#c(s)?s.__staleWhileFetching:s;if(i===void 0)return;let n={value:i};if(this.#g&&this.#M){let o=this.#g[r],a=this.#M[r];if(o&&a){let l=o-(this.#u.now()-a);n.ttl=l,n.start=Date.now()}}return this.#T&&(n.size=this.#T[r]),n}dump(){let e=[];for(let r of this.#O({allowStale:!0})){let s=this.#l[r],i=this.#s[r],n=this.#c(i)?i.__staleWhileFetching:i;if(n===void 0||s===void 0)continue;let o={value:n};if(this.#g&&this.#M){o.ttl=this.#g[r];let a=this.#u.now()-this.#M[r];o.start=Math.floor(Date.now()-a)}this.#T&&(o.size=this.#T[r]),e.unshift([s,o])}return e}load(e){this.clear();for(let[r,s]of e){if(s.start){let i=Date.now()-s.start;s.start=this.#u.now()-i}this.set(r,s.value,s)}}set(e,r,s={}){if(r===void 0)return this.delete(e),this;let{ttl:i=this.ttl,start:n,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=s,{noUpdateTTL:c=this.noUpdateTTL}=s,u=this.#W(e,r,s.size||0,a);if(this.maxEntrySize&&u>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=!0),this.#R(e,"set"),this;let h=this.#a===0?void 0:this.#h.get(e);if(h===void 0)h=this.#a===0?this.#f:this.#A.length!==0?this.#A.pop():this.#a===this.#e?this.#H(!1):this.#a,this.#l[h]=e,this.#s[h]=r,this.#h.set(e,h),this.#p[this.#f]=h,this.#y[h]=this.#f,this.#f=h,this.#a++,this.#L(h,u,l),l&&(l.set="add"),c=!1,this.#x&&this.#i?.(r,e,"add");else{this.#N(h);let p=this.#s[h];if(r!==p){if(this.#k&&this.#c(p)){p.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:f}=p;f!==void 0&&!o&&(this.#b&&this.#n?.(f,e,"set"),this.#t&&this.#m?.push([f,e,"set"]))}else o||(this.#b&&this.#n?.(p,e,"set"),this.#t&&this.#m?.push([p,e,"set"]));if(this.#U(h),this.#L(h,u,l),this.#s[h]=r,l){l.set="replace";let f=p&&this.#c(p)?p.__staleWhileFetching:p;f!==void 0&&(l.oldValue=f)}}else l&&(l.set="update");this.#x&&this.onInsert?.(r,e,r===p?"update":"replace")}if(i!==0&&!this.#g&&this.#D(),this.#g&&(c||this.#F(h,i,n),l&&this.#P(l,h)),!o&&this.#t&&this.#m){let p=this.#m,f;for(;f=p?.shift();)this.#o?.(...f)}return this}pop(){try{for(;this.#a;){let e=this.#s[this.#w];if(this.#H(!0),this.#c(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#t&&this.#m){let e=this.#m,r;for(;r=e?.shift();)this.#o?.(...r)}}}#H(e){let r=this.#w,s=this.#l[r],i=this.#s[r];return this.#k&&this.#c(i)?i.__abortController.abort(new Error("evicted")):(this.#b||this.#t)&&(this.#b&&this.#n?.(i,s,"evict"),this.#t&&this.#m?.push([i,s,"evict"])),this.#U(r),this.#E?.[r]&&(clearTimeout(this.#E[r]),this.#E[r]=void 0),e&&(this.#l[r]=void 0,this.#s[r]=void 0,this.#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(e,r={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:i}=r,n=this.#h.get(e);if(n!==void 0){let o=this.#s[n];if(this.#c(o)&&o.__staleWhileFetching===void 0)return!1;if(this.#v(n))i&&(i.has="stale",this.#P(i,n));else return s&&this.#C(n),i&&(i.has="hit",this.#P(i,n)),!0}else i&&(i.has="miss");return!1}peek(e,r={}){let{allowStale:s=this.allowStale}=r,i=this.#h.get(e);if(i===void 0||!s&&this.#v(i))return;let n=this.#s[i];return this.#c(n)?n.__staleWhileFetching:n}#j(e,r,s,i){let n=r===void 0?void 0:this.#s[r];if(this.#c(n))return n;let o=new Mt,{signal:a}=s;a?.addEventListener("abort",()=>o.abort(a.reason),{signal:o.signal});let l={signal:o.signal,options:s,context:i},c=(g,w=!1)=>{let{aborted:S}=o.signal,E=s.ignoreFetchAbort&&g!==void 0,_=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,_);let b=f,T=this.#s[r];return(T===f||E&&w&&T===void 0)&&(g===void 0?b.__staleWhileFetching!==void 0?this.#s[r]=b.__staleWhileFetching:this.#R(e,"fetch"):(s.status&&(s.status.fetchUpdated=!0),this.set(e,g,l.options))),g},u=g=>(s.status&&(s.status.fetchRejected=!0,s.status.fetchError=g),h(g,!1)),h=(g,w)=>{let{aborted:S}=o.signal,E=S&&s.allowStaleOnFetchAbort,_=E||s.allowStaleOnFetchRejection,b=_||s.noDeleteOnFetchRejection,T=f;if(this.#s[r]===f&&(!b||!w&&T.__staleWhileFetching===void 0?this.#R(e,"fetch"):E||(this.#s[r]=T.__staleWhileFetching)),_)return s.status&&T.__staleWhileFetching!==void 0&&(s.status.returnedStale=!0),T.__staleWhileFetching;if(T.__returned===T)throw g},p=(g,w)=>{let S=this.#_?.(e,n,l);S&&S instanceof Promise&&S.then(E=>g(E===void 0?void 0:E),w),o.signal.addEventListener("abort",()=>{(!s.ignoreFetchAbort||s.allowStaleOnFetchAbort)&&(g(void 0),s.allowStaleOnFetchAbort&&(g=E=>c(E,!0)))})};s.status&&(s.status.fetchDispatched=!0);let f=new Promise(p).then(c,u),m=Object.assign(f,{__abortController:o,__staleWhileFetching:n,__returned:void 0});return r===void 0?(this.set(e,m,{...l.options,status:void 0}),r=this.#h.get(e)):this.#s[r]=m,m}#c(e){if(!this.#k)return!1;let r=e;return!!r&&r instanceof Promise&&r.hasOwnProperty("__staleWhileFetching")&&r.__abortController instanceof Mt}async fetch(e,r={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:l=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:h=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:p=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:m=this.allowStaleOnFetchAbort,context:g,forceRefresh:w=!1,status:S,signal:E}=r;if(!this.#k)return S&&(S.fetch="get"),this.get(e,{allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:n,status:S});let _={allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:n,ttl:o,noDisposeOnSet:a,size:l,sizeCalculation:c,noUpdateTTL:u,noDeleteOnFetchRejection:h,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:m,ignoreFetchAbort:f,status:S,signal:E},b=this.#h.get(e);if(b===void 0){S&&(S.fetch="miss");let T=this.#j(e,b,_,g);return T.__returned=T}else{let T=this.#s[b];if(this.#c(T)){let Re=s&&T.__staleWhileFetching!==void 0;return S&&(S.fetch="inflight",Re&&(S.returnedStale=!0)),Re?T.__staleWhileFetching:T.__returned=T}let pe=this.#v(b);if(!w&&!pe)return S&&(S.fetch="hit"),this.#N(b),i&&this.#C(b),S&&this.#P(S,b),T;let Ce=this.#j(e,b,_,g),Ae=Ce.__staleWhileFetching!==void 0&&s;return S&&(S.fetch=pe?"stale":"refresh",Ae&&pe&&(S.returnedStale=!0)),Ae?Ce.__staleWhileFetching:Ce.__returned=Ce}}async forceFetch(e,r={}){let s=await this.fetch(e,r);if(s===void 0)throw new Error("fetch() returned undefined");return s}memo(e,r={}){let s=this.#S;if(!s)throw new Error("no memoMethod provided to constructor");let{context:i,forceRefresh:n,...o}=r,a=this.get(e,o);if(!n&&a!==void 0)return a;let l=s(e,a,{options:o,context:i});return this.set(e,l,o),l}get(e,r={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:o}=r,a=this.#h.get(e);if(a!==void 0){let l=this.#s[a],c=this.#c(l);return o&&this.#P(o,a),this.#v(a)?(o&&(o.get="stale"),c?(o&&s&&l.__staleWhileFetching!==void 0&&(o.returnedStale=!0),s?l.__staleWhileFetching:void 0):(n||this.#R(e,"expire"),o&&s&&(o.returnedStale=!0),s?l:void 0)):(o&&(o.get="hit"),c?l.__staleWhileFetching:(this.#N(a),i&&this.#C(a),l))}else o&&(o.get="miss")}#B(e,r){this.#y[r]=e,this.#p[e]=r}#N(e){e!==this.#f&&(e===this.#w?this.#w=this.#p[e]:this.#B(this.#y[e],this.#p[e]),this.#B(this.#f,e),this.#f=e)}delete(e){return this.#R(e,"delete")}#R(e,r){let s=!1;if(this.#a!==0){let i=this.#h.get(e);if(i!==void 0)if(this.#E?.[i]&&(clearTimeout(this.#E?.[i]),this.#E[i]=void 0),s=!0,this.#a===1)this.#K(r);else{this.#U(i);let n=this.#s[i];if(this.#c(n)?n.__abortController.abort(new Error("deleted")):(this.#b||this.#t)&&(this.#b&&this.#n?.(n,e,r),this.#t&&this.#m?.push([n,e,r])),this.#h.delete(e),this.#l[i]=void 0,this.#s[i]=void 0,i===this.#f)this.#f=this.#y[i];else if(i===this.#w)this.#w=this.#p[i];else{let o=this.#y[i];this.#p[o]=this.#p[i];let a=this.#p[i];this.#y[a]=this.#y[i]}this.#a--,this.#A.push(i)}}if(this.#t&&this.#m?.length){let i=this.#m,n;for(;n=i?.shift();)this.#o?.(...n)}return s}clear(){return this.#K("delete")}#K(e){for(let r of this.#I({allowStale:!0})){let s=this.#s[r];if(this.#c(s))s.__abortController.abort(new Error("deleted"));else{let i=this.#l[r];this.#b&&this.#n?.(s,i,e),this.#t&&this.#m?.push([s,i,e])}}if(this.#h.clear(),this.#s.fill(void 0),this.#l.fill(void 0),this.#g&&this.#M){this.#g.fill(0),this.#M.fill(0);for(let r of this.#E??[])r!==void 0&&clearTimeout(r);this.#E?.fill(void 0)}if(this.#T&&this.#T.fill(0),this.#w=0,this.#f=0,this.#A.length=0,this.#d=0,this.#a=0,this.#t&&this.#m){let r=this.#m,s;for(;s=r?.shift();)this.#o?.(...s)}}},ns=typeof process=="object"&&process?process:{stdout:null,stderr:null},ea=t=>!!t&&typeof t=="object"&&(t instanceof kt||t instanceof _r.default||ta(t)||ra(t)),ta=t=>!!t&&typeof t=="object"&&t instanceof At.EventEmitter&&typeof t.pipe=="function"&&t.pipe!==_r.default.Writable.prototype.pipe,ra=t=>!!t&&typeof t=="object"&&t instanceof At.EventEmitter&&typeof t.write=="function"&&typeof t.end=="function",oe=Symbol("EOF"),ae=Symbol("maybeEmitEnd"),fe=Symbol("emittedEnd"),mt=Symbol("emittingEnd"),Ge=Symbol("emittedError"),gt=Symbol("closed"),os=Symbol("read"),St=Symbol("flush"),as=Symbol("flushChunk"),G=Symbol("encoding"),De=Symbol("decoder"),k=Symbol("flowing"),Ke=Symbol("paused"),Pe=Symbol("resume"),C=Symbol("buffer"),I=Symbol("pipes"),A=Symbol("bufferLength"),ur=Symbol("bufferPush"),Et=Symbol("bufferShift"),O=Symbol("objectMode"),M=Symbol("destroyed"),hr=Symbol("error"),dr=Symbol("emitData"),ls=Symbol("emitEnd"),pr=Symbol("emitEnd2"),q=Symbol("async"),fr=Symbol("abort"),wt=Symbol("aborted"),Ye=Symbol("signal"),_e=Symbol("dataListeners"),U=Symbol("discarded"),ze=t=>Promise.resolve().then(t),sa=t=>t(),ia=t=>t==="end"||t==="finish"||t==="prefinish",na=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,oa=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Ws=class{src;dest;opts;ondrain;constructor(t,e,r){this.src=t,this.dest=e,this.opts=r,this.ondrain=()=>t[Pe](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},aa=class extends Ws{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,r){super(t,e,r),this.proxyErrors=s=>this.dest.emit("error",s),t.on("error",this.proxyErrors)}},la=t=>!!t.objectMode,ca=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",kt=class extends At.EventEmitter{[k]=!1;[Ke]=!1;[I]=[];[C]=[];[O];[G];[q];[De];[oe]=!1;[fe]=!1;[mt]=!1;[gt]=!1;[Ge]=null;[A]=0;[M]=!1;[Ye];[wt]=!1;[_e]=0;[U]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");la(e)?(this[O]=!0,this[G]=null):ca(e)?(this[G]=e.encoding,this[O]=!1):(this[O]=!1,this[G]=null),this[q]=!!e.async,this[De]=this[G]?new Fs.StringDecoder(this[G]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[C]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[I]});let{signal:r}=e;r&&(this[Ye]=r,r.aborted?this[fr]():r.addEventListener("abort",()=>this[fr]()))}get bufferLength(){return this[A]}get encoding(){return this[G]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[O]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[q]}set async(t){this[q]=this[q]||!!t}[fr](){this[wt]=!0,this.emit("abort",this[Ye]?.reason),this.destroy(this[Ye]?.reason)}get aborted(){return this[wt]}set aborted(t){}write(t,e,r){if(this[wt])return!1;if(this[oe])throw new Error("write after end");if(this[M])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(r=e,e="utf8"),e||(e="utf8");let s=this[q]?ze:sa;if(!this[O]&&!Buffer.isBuffer(t)){if(oa(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(na(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[O]?(this[k]&&this[A]!==0&&this[St](!0),this[k]?this.emit("data",t):this[ur](t),this[A]!==0&&this.emit("readable"),r&&s(r),this[k]):t.length?(typeof t=="string"&&!(e===this[G]&&!this[De]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[G]&&(t=this[De].write(t)),this[k]&&this[A]!==0&&this[St](!0),this[k]?this.emit("data",t):this[ur](t),this[A]!==0&&this.emit("readable"),r&&s(r),this[k]):(this[A]!==0&&this.emit("readable"),r&&s(r),this[k])}read(t){if(this[M])return null;if(this[U]=!1,this[A]===0||t===0||t&&t>this[A])return this[ae](),null;this[O]&&(t=null),this[C].length>1&&!this[O]&&(this[C]=[this[G]?this[C].join(""):Buffer.concat(this[C],this[A])]);let e=this[os](t||null,this[C][0]);return this[ae](),e}[os](t,e){if(this[O])this[Et]();else{let r=e;t===r.length||t===null?this[Et]():typeof r=="string"?(this[C][0]=r.slice(t),e=r.slice(0,t),this[A]-=t):(this[C][0]=r.subarray(t),e=r.subarray(0,t),this[A]-=t)}return this.emit("data",e),!this[C].length&&!this[oe]&&this.emit("drain"),e}end(t,e,r){return typeof t=="function"&&(r=t,t=void 0),typeof e=="function"&&(r=e,e="utf8"),t!==void 0&&this.write(t,e),r&&this.once("end",r),this[oe]=!0,this.writable=!1,(this[k]||!this[Ke])&&this[ae](),this}[Pe](){this[M]||(!this[_e]&&!this[I].length&&(this[U]=!0),this[Ke]=!1,this[k]=!0,this.emit("resume"),this[C].length?this[St]():this[oe]?this[ae]():this.emit("drain"))}resume(){return this[Pe]()}pause(){this[k]=!1,this[Ke]=!0,this[U]=!1}get destroyed(){return this[M]}get flowing(){return this[k]}get paused(){return this[Ke]}[ur](t){this[O]?this[A]+=1:this[A]+=t.length,this[C].push(t)}[Et](){return this[O]?this[A]-=1:this[A]-=this[C][0].length,this[C].shift()}[St](t=!1){do;while(this[as](this[Et]())&&this[C].length);!t&&!this[C].length&&!this[oe]&&this.emit("drain")}[as](t){return this.emit("data",t),this[k]}pipe(t,e){if(this[M])return t;this[U]=!1;let r=this[fe];return e=e||{},t===ns.stdout||t===ns.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[I].push(e.proxyErrors?new aa(this,t,e):new Ws(this,t,e)),this[q]?ze(()=>this[Pe]()):this[Pe]()),t}unpipe(t){let e=this[I].find(r=>r.dest===t);e&&(this[I].length===1?(this[k]&&this[_e]===0&&(this[k]=!1),this[I]=[]):this[I].splice(this[I].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let r=super.on(t,e);if(t==="data")this[U]=!1,this[_e]++,!this[I].length&&!this[k]&&this[Pe]();else if(t==="readable"&&this[A]!==0)super.emit("readable");else if(ia(t)&&this[fe])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[Ge]){let s=e;this[q]?ze(()=>s.call(this,this[Ge])):s.call(this,this[Ge])}return r}removeListener(t,e){return this.off(t,e)}off(t,e){let r=super.off(t,e);return t==="data"&&(this[_e]=this.listeners("data").length,this[_e]===0&&!this[U]&&!this[I].length&&(this[k]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[_e]=0,!this[U]&&!this[I].length&&(this[k]=!1)),e}get emittedEnd(){return this[fe]}[ae](){!this[mt]&&!this[fe]&&!this[M]&&this[C].length===0&&this[oe]&&(this[mt]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[gt]&&this.emit("close"),this[mt]=!1)}emit(t,...e){let r=e[0];if(t!=="error"&&t!=="close"&&t!==M&&this[M])return!1;if(t==="data")return!this[O]&&!r?!1:this[q]?(ze(()=>this[dr](r)),!0):this[dr](r);if(t==="end")return this[ls]();if(t==="close"){if(this[gt]=!0,!this[fe]&&!this[M])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(t==="error"){this[Ge]=r,super.emit(hr,r);let i=!this[Ye]||this.listeners("error").length?super.emit("error",r):!1;return this[ae](),i}else if(t==="resume"){let i=super.emit("resume");return this[ae](),i}else if(t==="finish"||t==="prefinish"){let i=super.emit(t);return this.removeAllListeners(t),i}let s=super.emit(t,...e);return this[ae](),s}[dr](t){for(let r of this[I])r.dest.write(t)===!1&&this.pause();let e=this[U]?!1:super.emit("data",t);return this[ae](),e}[ls](){return this[fe]?!1:(this[fe]=!0,this.readable=!1,this[q]?(ze(()=>this[pr]()),!0):this[pr]())}[pr](){if(this[De]){let e=this[De].end();if(e){for(let r of this[I])r.dest.write(e);this[U]||super.emit("data",e)}}for(let e of this[I])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[O]||(t.dataLength=0);let e=this.promise();return this.on("data",r=>{t.push(r),this[O]||(t.dataLength+=r.length)}),await e,t}async concat(){if(this[O])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[G]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(M,()=>e(new Error("stream destroyed"))),this.on("error",r=>e(r)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[U]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let r=this.read();if(r!==null)return Promise.resolve({done:!1,value:r});if(this[oe])return e();let s,i,n=c=>{this.off("data",o),this.off("end",a),this.off(M,l),e(),i(c)},o=c=>{this.off("error",n),this.off("end",a),this.off(M,l),this.pause(),s({value:c,done:!!this[oe]})},a=()=>{this.off("error",n),this.off("data",o),this.off(M,l),e(),s({done:!0,value:void 0})},l=()=>n(new Error("stream destroyed"));return new Promise((c,u)=>{i=u,s=c,this.once(M,l),this.once("error",n),this.once("end",a),this.once("data",o)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[U]=!1;let t=!1,e=()=>(this.pause(),this.off(hr,e),this.off(M,e),this.off("end",e),t=!0,{done:!0,value:void 0}),r=()=>{if(t)return e();let s=this.read();return s===null?e():{done:!1,value:s}};return this.once("end",e),this.once(hr,e),this.once(M,e),{next:r,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[M])return t?this.emit("error",t):this.emit(M),this;this[M]=!0,this[U]=!0,this[C].length=0,this[A]=0;let e=this;return typeof e.close=="function"&&!this[gt]&&e.close(),t?this.emit("error",t):this.emit(M),this}static get isStream(){return ea}},ua=Q.realpathSync.native,Ve={lstatSync:Q.lstatSync,readdir:Q.readdir,readdirSync:Q.readdirSync,readlinkSync:Q.readlinkSync,realpathSync:ua,promises:{lstat:Se.lstat,readdir:Se.readdir,readlink:Se.readlink,realpath:Se.realpath}},$s=t=>!t||t===Ve||t===Zo?Ve:{...Ve,...t,promises:{...Ve.promises,...t.promises||{}}},Hs=/^\\\\\?\\([a-z]:)\\?$/i,ha=t=>t.replace(/\//g,"\\").replace(Hs,"$1\\"),da=/[\\\/]/,j=0,js=1,Bs=2,V=4,Gs=6,Ks=8,ye=10,Ys=12,H=15,Je=~H,mr=16,cs=32,Qe=64,K=128,_t=256,vt=512,us=Qe|K|vt,pa=1023,gr=t=>t.isFile()?Ks:t.isDirectory()?V:t.isSymbolicLink()?ye:t.isCharacterDevice()?Bs:t.isBlockDevice()?Gs:t.isSocket()?Ys:t.isFIFO()?js:j,hs=new Ct({max:2**12}),Ze=t=>{let e=hs.get(t);if(e)return e;let r=t.normalize("NFKD");return hs.set(t,r),r},ds=new Ct({max:2**12}),yt=t=>{let e=ds.get(t);if(e)return e;let r=Ze(t.toLowerCase());return ds.set(t,r),r},ps=class extends Ct{constructor(){super({max:256})}},fa=class extends Ct{constructor(t=16*1024){super({maxSize:t,sizeCalculation:e=>e.length+1})}},zs=Symbol("PathScurry setAsCwd"),L=class{name;root;roots;parent;nocase;isCWD=!1;#e;#r;get dev(){return this.#r}#n;get mode(){return this.#n}#i;get nlink(){return this.#i}#o;get uid(){return this.#o}#_;get gid(){return this.#_}#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}#y;get birthtimeMs(){return this.#y}#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;#M;#g;#E;#b;#k;#t;#x;#D;#C;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(t,e=j,r,s,i,n,o){this.name=t,this.#T=i?yt(t):Ze(t),this.#t=e&pa,this.nocase=i,this.roots=s,this.root=r||this,this.#x=n,this.#g=o.fullpath,this.#b=o.relative,this.#k=o.relativePosix,this.parent=o.parent,this.parent?this.#e=this.parent.#e:this.#e=$s(o.fs)}depth(){return this.#M!==void 0?this.#M:this.parent?this.#M=this.parent.depth()+1:this.#M=0}childrenCache(){return this.#x}resolve(t){if(!t)return this;let e=this.getRootString(t),r=t.substring(e.length).split(this.splitSep);return e?this.getRoot(e).#P(r):this.#P(r)}#P(t){let e=this;for(let r of t)e=e.child(r);return e}children(){let t=this.#x.get(this);if(t)return t;let e=Object.assign([],{provisional:0});return this.#x.set(this,e),this.#t&=~mr,e}child(t,e){if(t===""||t===".")return this;if(t==="..")return this.parent||this;let r=this.children(),s=this.nocase?yt(t):Ze(t);for(let a of r)if(a.#T===s)return a;let i=this.parent?this.sep:"",n=this.#g?this.#g+i+t:void 0,o=this.newChild(t,j,{...e,parent:this,fullpath:n});return this.canReaddir()||(o.#t|=K),r.push(o),o}relative(){if(this.isCWD)return"";if(this.#b!==void 0)return this.#b;let t=this.name,e=this.parent;if(!e)return this.#b=this.name;let r=e.relative();return r+(!r||!e.parent?"":this.sep)+t}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#k!==void 0)return this.#k;let t=this.name,e=this.parent;if(!e)return this.#k=this.fullpathPosix();let r=e.relativePosix();return r+(!r||!e.parent?"":"/")+t}fullpath(){if(this.#g!==void 0)return this.#g;let t=this.name,e=this.parent;if(!e)return this.#g=this.name;let r=e.fullpath()+(e.parent?this.sep:"")+t;return this.#g=r}fullpathPosix(){if(this.#E!==void 0)return this.#E;if(this.sep==="/")return this.#E=this.fullpath();if(!this.parent){let s=this.fullpath().replace(/\\/g,"/");return/^[a-z]:\//i.test(s)?this.#E=`//?/${s}`:this.#E=s}let t=this.parent,e=t.fullpathPosix(),r=e+(!e||!t.parent?"":"/")+this.name;return this.#E=r}isUnknown(){return(this.#t&H)===j}isType(t){return this[`is${t}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return(this.#t&H)===Ks}isDirectory(){return(this.#t&H)===V}isCharacterDevice(){return(this.#t&H)===Bs}isBlockDevice(){return(this.#t&H)===Gs}isFIFO(){return(this.#t&H)===js}isSocket(){return(this.#t&H)===Ys}isSymbolicLink(){return(this.#t&ye)===ye}lstatCached(){return this.#t&cs?this:void 0}readlinkCached(){return this.#D}realpathCached(){return this.#C}readdirCached(){let t=this.children();return t.slice(0,t.provisional)}canReadlink(){if(this.#D)return!0;if(!this.parent)return!1;let t=this.#t&H;return!(t!==j&&t!==ye||this.#t&_t||this.#t&K)}calledReaddir(){return!!(this.#t&mr)}isENOENT(){return!!(this.#t&K)}isNamed(t){return this.nocase?this.#T===yt(t):this.#T===Ze(t)}async readlink(){let t=this.#D;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=await this.#e.promises.readlink(this.fullpath()),r=(await this.parent.realpath())?.resolve(e);if(r)return this.#D=r}catch(e){this.#I(e.code);return}}readlinkSync(){let t=this.#D;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=this.#e.readlinkSync(this.fullpath()),r=this.parent.realpathSync()?.resolve(e);if(r)return this.#D=r}catch(e){this.#I(e.code);return}}#F(t){this.#t|=mr;for(let e=t.provisional;e<t.length;e++){let r=t[e];r&&r.#v()}}#v(){this.#t&K||(this.#t=(this.#t|K)&Je,this.#G())}#G(){let t=this.children();t.provisional=0;for(let e of t)e.#v()}#U(){this.#t|=vt,this.#L()}#L(){if(this.#t&Qe)return;let t=this.#t;(t&H)===V&&(t&=Je),this.#t=t|Qe,this.#G()}#W(t=""){t==="ENOTDIR"||t==="EPERM"?this.#L():t==="ENOENT"?this.#v():this.children().provisional=0}#O(t=""){t==="ENOTDIR"?this.parent.#L():t==="ENOENT"&&this.#v()}#I(t=""){let e=this.#t;e|=_t,t==="ENOENT"&&(e|=K),(t==="EINVAL"||t==="UNKNOWN")&&(e&=Je),this.#t=e,t==="ENOTDIR"&&this.parent&&this.parent.#L()}#$(t,e){return this.#j(t,e)||this.#H(t,e)}#H(t,e){let r=gr(t),s=this.newChild(t.name,r,{parent:this}),i=s.#t&H;return i!==V&&i!==ye&&i!==j&&(s.#t|=Qe),e.unshift(s),e.provisional++,s}#j(t,e){for(let r=e.provisional;r<e.length;r++){let s=e[r];if((this.nocase?yt(t.name):Ze(t.name))===s.#T)return this.#c(t,s,r,e)}}#c(t,e,r,s){let i=e.name;return e.#t=e.#t&Je|gr(t),i!==t.name&&(e.name=t.name),r!==s.provisional&&(r===s.length-1?s.pop():s.splice(r,1),s.unshift(e)),s.provisional++,e}async lstat(){if((this.#t&K)===0)try{return this.#B(await this.#e.promises.lstat(this.fullpath())),this}catch(t){this.#O(t.code)}}lstatSync(){if((this.#t&K)===0)try{return this.#B(this.#e.lstatSync(this.fullpath())),this}catch(t){this.#O(t.code)}}#B(t){let{atime:e,atimeMs:r,birthtime:s,birthtimeMs:i,blksize:n,blocks:o,ctime:a,ctimeMs:l,dev:c,gid:u,ino:h,mode:p,mtime:f,mtimeMs:m,nlink:g,rdev:w,size:S,uid:E}=t;this.#w=e,this.#l=r,this.#m=s,this.#y=i,this.#u=n,this.#h=o,this.#A=a,this.#p=l,this.#r=c,this.#_=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 _=gr(t);this.#t=this.#t&Je|_|cs,_!==j&&_!==V&&_!==ye&&(this.#t|=Qe)}#N=[];#R=!1;#K(t){this.#R=!1;let e=this.#N.slice();this.#N.length=0,e.forEach(r=>r(null,t))}readdirCB(t,e=!1){if(!this.canReaddir()){e?t(null,[]):queueMicrotask(()=>t(null,[]));return}let r=this.children();if(this.calledReaddir()){let i=r.slice(0,r.provisional);e?t(null,i):queueMicrotask(()=>t(null,i));return}if(this.#N.push(t),this.#R)return;this.#R=!0;let s=this.fullpath();this.#e.readdir(s,{withFileTypes:!0},(i,n)=>{if(i)this.#W(i.code),r.provisional=0;else{for(let o of n)this.#$(o,r);this.#F(r)}this.#K(r.slice(0,r.provisional))})}#Y;async readdir(){if(!this.canReaddir())return[];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();if(this.#Y)await this.#Y;else{let r=()=>{};this.#Y=new Promise(s=>r=s);try{for(let s of await this.#e.promises.readdir(e,{withFileTypes:!0}))this.#$(s,t);this.#F(t)}catch(s){this.#W(s.code),t.provisional=0}this.#Y=void 0,r()}return t.slice(0,t.provisional)}readdirSync(){if(!this.canReaddir())return[];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();try{for(let r of this.#e.readdirSync(e,{withFileTypes:!0}))this.#$(r,t);this.#F(t)}catch(r){this.#W(r.code),t.provisional=0}return t.slice(0,t.provisional)}canReaddir(){if(this.#t&us)return!1;let t=H&this.#t;return t===j||t===V||t===ye}shouldWalk(t,e){return(this.#t&V)===V&&!(this.#t&us)&&!t.has(this)&&(!e||e(this))}async realpath(){if(this.#C)return this.#C;if(!((vt|_t|K)&this.#t))try{let t=await this.#e.promises.realpath(this.fullpath());return this.#C=this.resolve(t)}catch{this.#U()}}realpathSync(){if(this.#C)return this.#C;if(!((vt|_t|K)&this.#t))try{let t=this.#e.realpathSync(this.fullpath());return this.#C=this.resolve(t)}catch{this.#U()}}[zs](t){if(t===this)return;t.isCWD=!1,this.isCWD=!0;let e=new Set([]),r=[],s=this;for(;s&&s.parent;)e.add(s),s.#b=r.join(this.sep),s.#k=r.join("/"),s=s.parent,r.push("..");for(s=t;s&&s.parent&&!e.has(s);)s.#b=void 0,s.#k=void 0,s=s.parent}},Js=class Xs extends L{sep="\\";splitSep=da;constructor(e,r=j,s,i,n,o,a){super(e,r,s,i,n,o,a)}newChild(e,r=j,s={}){return new Xs(e,r,this.root,this.roots,this.nocase,this.childrenCache(),s)}getRootString(e){return Le.win32.parse(e).root}getRoot(e){if(e=ha(e.toUpperCase()),e===this.root.name)return this.root;for(let[r,s]of Object.entries(this.roots))if(this.sameRoot(e,r))return this.roots[e]=s;return this.roots[e]=new yr(e,this).root}sameRoot(e,r=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(Hs,"$1\\"),e===r}},qs=class Vs extends L{splitSep="/";sep="/";constructor(e,r=j,s,i,n,o,a){super(e,r,s,i,n,o,a)}getRootString(e){return e.startsWith("/")?"/":""}getRoot(e){return this.root}newChild(e,r=j,s={}){return new Vs(e,r,this.root,this.roots,this.nocase,this.childrenCache(),s)}},Qs=class{root;rootPath;roots;cwd;#e;#r;#n;nocase;#i;constructor(t=process.cwd(),e,r,{nocase:s,childrenCacheSize:i=16*1024,fs:n=Ve}={}){this.#i=$s(n),(t instanceof URL||t.startsWith("file://"))&&(t=(0,Us.fileURLToPath)(t));let o=e.resolve(t);this.roots=Object.create(null),this.rootPath=this.parseRootPath(o),this.#e=new ps,this.#r=new ps,this.#n=new fa(i);let a=o.substring(this.rootPath.length).split(r);if(a.length===1&&!a[0]&&a.pop(),s===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=s,this.root=this.newRoot(this.#i),this.roots[this.rootPath]=this.root;let l=this.root,c=a.length-1,u=e.sep,h=this.rootPath,p=!1;for(let f of a){let m=c--;l=l.child(f,{relative:new Array(m).fill("..").join(u),relativePosix:new Array(m).fill("..").join("/"),fullpath:h+=(p?"":u)+f}),p=!0}this.cwd=l}depth(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.depth()}childrenCache(){return this.#n}resolve(...t){let e="";for(let i=t.length-1;i>=0;i--){let n=t[i];if(!(!n||n===".")&&(e=e?`${n}/${e}`:n,this.isAbsolute(n)))break}let r=this.#e.get(e);if(r!==void 0)return r;let s=this.cwd.resolve(e).fullpath();return this.#e.set(e,s),s}resolvePosix(...t){let e="";for(let i=t.length-1;i>=0;i--){let n=t[i];if(!(!n||n===".")&&(e=e?`${n}/${e}`:n,this.isAbsolute(n)))break}let r=this.#r.get(e);if(r!==void 0)return r;let s=this.cwd.resolve(e).fullpathPosix();return this.#r.set(e,s),s}relative(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relative()}relativePosix(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relativePosix()}basename(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.name}dirname(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),(t.parent||t).fullpath()}async readdir(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r}=e;if(t.canReaddir()){let s=await t.readdir();return r?s:s.map(i=>i.name)}else return[]}readdirSync(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0}=e;return t.canReaddir()?r?t.readdirSync():t.readdirSync().map(s=>s.name):[]}async lstat(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstat()}lstatSync(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstatSync()}async readlink(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t.withFileTypes,t=this.cwd);let r=await t.readlink();return e?r:r?.fullpath()}readlinkSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t.withFileTypes,t=this.cwd);let r=t.readlinkSync();return e?r:r?.fullpath()}async realpath(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t.withFileTypes,t=this.cwd);let r=await t.realpath();return e?r:r?.fullpath()}realpathSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t.withFileTypes,t=this.cwd);let r=t.realpathSync();return e?r:r?.fullpath()}async walk(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=e,o=[];(!i||i(t))&&o.push(r?t:t.fullpath());let a=new Set,l=(u,h)=>{a.add(u),u.readdirCB((p,f)=>{if(p)return h(p);let m=f.length;if(!m)return h();let g=()=>{--m===0&&h()};for(let w of f)(!i||i(w))&&o.push(r?w:w.fullpath()),s&&w.isSymbolicLink()?w.realpath().then(S=>S?.isUnknown()?S.lstat():S).then(S=>S?.shouldWalk(a,n)?l(S,g):g()):w.shouldWalk(a,n)?l(w,g):g()},!0)},c=t;return new Promise((u,h)=>{l(c,p=>{if(p)return h(p);u(o)})})}walkSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=e,o=[];(!i||i(t))&&o.push(r?t:t.fullpath());let a=new Set([t]);for(let l of a){let c=l.readdirSync();for(let u of c){(!i||i(u))&&o.push(r?u:u.fullpath());let h=u;if(u.isSymbolicLink()){if(!(s&&(h=u.realpathSync())))continue;h.isUnknown()&&h.lstatSync()}h.shouldWalk(a,n)&&a.add(h)}}return o}[Symbol.asyncIterator](){return this.iterate()}iterate(t=this.cwd,e={}){return typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd),this.stream(t,e)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=e;(!i||i(t))&&(yield r?t:t.fullpath());let o=new Set([t]);for(let a of o){let l=a.readdirSync();for(let c of l){(!i||i(c))&&(yield r?c:c.fullpath());let u=c;if(c.isSymbolicLink()){if(!(s&&(u=c.realpathSync())))continue;u.isUnknown()&&u.lstatSync()}u.shouldWalk(o,n)&&o.add(u)}}}stream(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=e,o=new kt({objectMode:!0});(!i||i(t))&&o.write(r?t:t.fullpath());let a=new Set,l=[t],c=0,u=()=>{let h=!1;for(;!h;){let p=l.shift();if(!p){c===0&&o.end();return}c++,a.add(p);let f=(g,w,S=!1)=>{if(g)return o.emit("error",g);if(s&&!S){let E=[];for(let _ of w)_.isSymbolicLink()&&E.push(_.realpath().then(b=>b?.isUnknown()?b.lstat():b));if(E.length){Promise.all(E).then(()=>f(null,w,!0));return}}for(let E of w)E&&(!i||i(E))&&(o.write(r?E:E.fullpath())||(h=!0));c--;for(let E of w){let _=E.realpathCached()||E;_.shouldWalk(a,n)&&l.push(_)}h&&!o.flowing?o.once("drain",u):m||u()},m=!0;p.readdirCB(f,!0),m=!1}};return u(),o}streamSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=e,o=new kt({objectMode:!0}),a=new Set;(!i||i(t))&&o.write(r?t:t.fullpath());let l=[t],c=0,u=()=>{let h=!1;for(;!h;){let p=l.shift();if(!p){c===0&&o.end();return}c++,a.add(p);let f=p.readdirSync();for(let m of f)(!i||i(m))&&(o.write(r?m:m.fullpath())||(h=!0));c--;for(let m of f){let g=m;if(m.isSymbolicLink()){if(!(s&&(g=m.realpathSync())))continue;g.isUnknown()&&g.lstatSync()}g.shouldWalk(a,n)&&l.push(g)}}h&&!o.flowing&&o.once("drain",u)};return u(),o}chdir(t=this.cwd){let e=this.cwd;this.cwd=typeof t=="string"?this.cwd.resolve(t):t,this.cwd[zs](e)}},yr=class extends Qs{sep="\\";constructor(t=process.cwd(),e={}){let{nocase:r=!0}=e;super(t,Le.win32,"\\",{...e,nocase:r}),this.nocase=r;for(let s=this.cwd;s;s=s.parent)s.nocase=this.nocase}parseRootPath(t){return Le.win32.parse(t).root.toUpperCase()}newRoot(t){return new Js(this.rootPath,V,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")||t.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(t)}},br=class extends Qs{sep="/";constructor(t=process.cwd(),e={}){let{nocase:r=!1}=e;super(t,Le.posix,"/",{...e,nocase:r}),this.nocase=r}parseRootPath(t){return"/"}newRoot(t){return new qs(this.rootPath,V,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")}},Zs=class extends br{constructor(t=process.cwd(),e={}){let{nocase:r=!0}=e;super(t,{...e,nocase:r})}},nc=process.platform==="win32"?Js:qs,ma=process.platform==="win32"?yr:process.platform==="darwin"?Zs:br,ga=t=>t.length>=1,Sa=t=>t.length>=1,Ea=Symbol.for("nodejs.util.inspect.custom"),ei=class ti{#e;#r;#n;length;#i;#o;#_;#S;#u;#a;#d=!0;constructor(e,r,s,i){if(!ga(e))throw new TypeError("empty pattern list");if(!Sa(r))throw new TypeError("empty glob list");if(r.length!==e.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=e.length,s<0||s>=this.length)throw new TypeError("index out of range");if(this.#e=e,this.#r=r,this.#n=s,this.#i=i,this.#n===0){if(this.isUNC()){let[n,o,a,l,...c]=this.#e,[u,h,p,f,...m]=this.#r;c[0]===""&&(c.shift(),m.shift());let g=[n,o,a,l,""].join("/"),w=[u,h,p,f,""].join("/");this.#e=[g,...c],this.#r=[w,...m],this.length=this.#e.length}else if(this.isDrive()||this.isAbsolute()){let[n,...o]=this.#e,[a,...l]=this.#r;o[0]===""&&(o.shift(),l.shift());let c=n+"/",u=a+"/";this.#e=[c,...o],this.#r=[u,...l],this.length=this.#e.length}}}[Ea](){return"Pattern <"+this.#r.slice(this.#n).join("/")+">"}pattern(){return this.#e[this.#n]}isString(){return typeof this.#e[this.#n]=="string"}isGlobstar(){return this.#e[this.#n]===D}isRegExp(){return this.#e[this.#n]instanceof RegExp}globString(){return this.#_=this.#_||(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 ti(this.#e,this.#r,this.#n+1,this.#i),this.#o.#a=this.#a,this.#o.#u=this.#u,this.#o.#S=this.#S,this.#o):this.#o=null}isUNC(){let e=this.#e;return this.#u!==void 0?this.#u:this.#u=this.#i==="win32"&&this.#n===0&&e[0]===""&&e[1]===""&&typeof e[2]=="string"&&!!e[2]&&typeof e[3]=="string"&&!!e[3]}isDrive(){let e=this.#e;return this.#S!==void 0?this.#S:this.#S=this.#i==="win32"&&this.#n===0&&this.length>1&&typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0])}isAbsolute(){let e=this.#e;return this.#a!==void 0?this.#a:this.#a=e[0]===""&&e.length>1||this.isDrive()||this.isUNC()}root(){let e=this.#e[0];return typeof e=="string"&&this.isAbsolute()&&this.#n===0?e:""}checkFollowGlobstar(){return!(this.#n===0||!this.isGlobstar()||!this.#d)}markFollowGlobstar(){return this.#n===0||!this.isGlobstar()||!this.#d?!1:(this.#d=!1,!0)}},wa=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",fs=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(t,{nobrace:e,nocase:r,noext:s,noglobstar:i,platform:n=wa}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=n,this.mmopts={dot:!0,nobrace:e,nocase:r,noext:s,noglobstar:i,optimizationLevel:2,platform:n,nocomment:!0,nonegate:!0};for(let o of t)this.add(o)}add(t){let e=new ge(t,this.mmopts);for(let r=0;r<e.set.length;r++){let s=e.set[r],i=e.globParts[r];if(!s||!i)throw new Error("invalid pattern object");for(;s[0]==="."&&i[0]===".";)s.shift(),i.shift();let n=new ei(s,i,0,this.platform),o=new ge(n.globString(),this.mmopts),a=i[i.length-1]==="**",l=n.isAbsolute();l?this.absolute.push(o):this.relative.push(o),a&&(l?this.absoluteChildren.push(o):this.relativeChildren.push(o))}}ignored(t){let e=t.fullpath(),r=`${e}/`,s=t.relative()||".",i=`${s}/`;for(let n of this.relative)if(n.match(s)||n.match(i))return!0;for(let n of this.absolute)if(n.match(e)||n.match(r))return!0;return!1}childrenIgnored(t){let e=t.fullpath()+"/",r=(t.relative()||".")+"/";for(let s of this.relativeChildren)if(s.match(r))return!0;for(let s of this.absoluteChildren)if(s.match(e))return!0;return!1}},_a=class ri{store;constructor(e=new Map){this.store=e}copy(){return new ri(new Map(this.store))}hasWalked(e,r){return this.store.get(e.fullpath())?.has(r.globString())}storeWalked(e,r){let s=e.fullpath(),i=this.store.get(s);i?i.add(r.globString()):this.store.set(s,new Set([r.globString()]))}},ya=class{store=new Map;add(t,e,r){let s=(e?2:0)|(r?1:0),i=this.store.get(t);this.store.set(t,i===void 0?s:s&i)}entries(){return[...this.store.entries()].map(([t,e])=>[t,!!(e&2),!!(e&1)])}},ba=class{store=new Map;add(t,e){if(!t.canReaddir())return;let r=this.store.get(t);r?r.find(s=>s.globString()===e.globString())||r.push(e):this.store.set(t,[e])}get(t){let e=this.store.get(t);if(!e)throw new Error("attempting to walk unknown path");return e}entries(){return this.keys().map(t=>[t,this.store.get(t)])}keys(){return[...this.store.keys()].filter(t=>t.canReaddir())}},ms=class si{hasWalkedCache;matches=new ya;subwalks=new ba;patterns;follow;dot;opts;constructor(e,r){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=r?r.copy():new _a}processPatterns(e,r){this.patterns=r;let s=r.map(i=>[e,i]);for(let[i,n]of s){this.hasWalkedCache.storeWalked(i,n);let o=n.root(),a=n.isAbsolute()&&this.opts.absolute!==!1;if(o){i=i.resolve(o==="/"&&this.opts.root!==void 0?this.opts.root:o);let h=n.rest();if(h)n=h;else{this.matches.add(i,!0,!1);continue}}if(i.isENOENT())continue;let l,c,u=!1;for(;typeof(l=n.pattern())=="string"&&(c=n.rest());)i=i.resolve(l),n=c,u=!0;if(l=n.pattern(),c=n.rest(),u){if(this.hasWalkedCache.hasWalked(i,n))continue;this.hasWalkedCache.storeWalked(i,n)}if(typeof l=="string"){let h=l===".."||l===""||l===".";this.matches.add(i.resolve(l),a,h);continue}else if(l===D){(!i.isSymbolicLink()||this.follow||n.checkFollowGlobstar())&&this.subwalks.add(i,n);let h=c?.pattern(),p=c?.rest();if(!c||(h===""||h===".")&&!p)this.matches.add(i,a,h===""||h===".");else if(h===".."){let f=i.parent||i;p?this.hasWalkedCache.hasWalked(f,p)||this.subwalks.add(f,p):this.matches.add(f,a,!0)}}else l instanceof RegExp&&this.subwalks.add(i,n)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new si(this.opts,this.hasWalkedCache)}filterEntries(e,r){let s=this.subwalks.get(e),i=this.child();for(let n of r)for(let o of s){let a=o.isAbsolute(),l=o.pattern(),c=o.rest();l===D?i.testGlobstar(n,o,c,a):l instanceof RegExp?i.testRegExp(n,l,c,a):i.testString(n,l,c,a)}return i}testGlobstar(e,r,s,i){if((this.dot||!e.name.startsWith("."))&&(r.hasMore()||this.matches.add(e,i,!1),e.canReaddir()&&(this.follow||!e.isSymbolicLink()?this.subwalks.add(e,r):e.isSymbolicLink()&&(s&&r.checkFollowGlobstar()?this.subwalks.add(e,s):r.markFollowGlobstar()&&this.subwalks.add(e,r)))),s){let n=s.pattern();if(typeof n=="string"&&n!==".."&&n!==""&&n!==".")this.testString(e,n,s.rest(),i);else if(n===".."){let o=e.parent||e;this.subwalks.add(o,s)}else n instanceof RegExp&&this.testRegExp(e,n,s.rest(),i)}}testRegExp(e,r,s,i){r.test(e.name)&&(s?this.subwalks.add(e,s):this.matches.add(e,i,!1))}testString(e,r,s,i){e.isNamed(r)&&(s?this.subwalks.add(e,s):this.matches.add(e,i,!1))}},va=(t,e)=>typeof t=="string"?new fs([t],e):Array.isArray(t)?new fs(t,e):t,ii=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#e=[];#r;#n;signal;maxDepth;includeChildMatches;constructor(t,e,r){if(this.patterns=t,this.path=e,this.opts=r,this.#n=!r.posix&&r.platform==="win32"?"\\":"/",this.includeChildMatches=r.includeChildMatches!==!1,(r.ignore||!this.includeChildMatches)&&(this.#r=va(r.ignore??[],r),!this.includeChildMatches&&typeof this.#r.add!="function")){let s="cannot ignore child matches, ignore lacks add() method.";throw new Error(s)}this.maxDepth=r.maxDepth||1/0,r.signal&&(this.signal=r.signal,this.signal.addEventListener("abort",()=>{this.#e.length=0}))}#i(t){return this.seen.has(t)||!!this.#r?.ignored?.(t)}#o(t){return!!this.#r?.childrenIgnored?.(t)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let t;for(;!this.paused&&(t=this.#e.shift());)t()}onResume(t){this.signal?.aborted||(this.paused?this.#e.push(t):t())}async matchCheck(t,e){if(e&&this.opts.nodir)return;let r;if(this.opts.realpath){if(r=t.realpathCached()||await t.realpath(),!r)return;t=r}let s=t.isUnknown()||this.opts.stat?await t.lstat():t;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let i=await s.realpath();i&&(i.isUnknown()||this.opts.stat)&&await i.lstat()}return this.matchCheckTest(s,e)}matchCheckTest(t,e){return t&&(this.maxDepth===1/0||t.depth()<=this.maxDepth)&&(!e||t.canReaddir())&&(!this.opts.nodir||!t.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!t.isSymbolicLink()||!t.realpathCached()?.isDirectory())&&!this.#i(t)?t:void 0}matchCheckSync(t,e){if(e&&this.opts.nodir)return;let r;if(this.opts.realpath){if(r=t.realpathCached()||t.realpathSync(),!r)return;t=r}let s=t.isUnknown()||this.opts.stat?t.lstatSync():t;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let i=s.realpathSync();i&&(i?.isUnknown()||this.opts.stat)&&i.lstatSync()}return this.matchCheckTest(s,e)}matchFinish(t,e){if(this.#i(t))return;if(!this.includeChildMatches&&this.#r?.add){let i=`${t.relativePosix()}/**`;this.#r.add(i)}let r=this.opts.absolute===void 0?e:this.opts.absolute;this.seen.add(t);let s=this.opts.mark&&t.isDirectory()?this.#n:"";if(this.opts.withFileTypes)this.matchEmit(t);else if(r){let i=this.opts.posix?t.fullpathPosix():t.fullpath();this.matchEmit(i+s)}else{let i=this.opts.posix?t.relativePosix():t.relative(),n=this.opts.dotRelative&&!i.startsWith(".."+this.#n)?"."+this.#n:"";this.matchEmit(i?n+i+s:"."+s)}}async match(t,e,r){let s=await this.matchCheck(t,r);s&&this.matchFinish(s,e)}matchSync(t,e,r){let s=this.matchCheckSync(t,r);s&&this.matchFinish(s,e)}walkCB(t,e,r){this.signal?.aborted&&r(),this.walkCB2(t,e,new ms(this.opts),r)}walkCB2(t,e,r,s){if(this.#o(t))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2(t,e,r,s));return}r.processPatterns(t,e);let i=1,n=()=>{--i===0&&s()};for(let[o,a,l]of r.matches.entries())this.#i(o)||(i++,this.match(o,a,l).then(()=>n()));for(let o of r.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;i++;let a=o.readdirCached();o.calledReaddir()?this.walkCB3(o,a,r,n):o.readdirCB((l,c)=>this.walkCB3(o,c,r,n),!0)}n()}walkCB3(t,e,r,s){r=r.filterEntries(t,e);let i=1,n=()=>{--i===0&&s()};for(let[o,a,l]of r.matches.entries())this.#i(o)||(i++,this.match(o,a,l).then(()=>n()));for(let[o,a]of r.subwalks.entries())i++,this.walkCB2(o,a,r.child(),n);n()}walkCBSync(t,e,r){this.signal?.aborted&&r(),this.walkCB2Sync(t,e,new ms(this.opts),r)}walkCB2Sync(t,e,r,s){if(this.#o(t))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2Sync(t,e,r,s));return}r.processPatterns(t,e);let i=1,n=()=>{--i===0&&s()};for(let[o,a,l]of r.matches.entries())this.#i(o)||this.matchSync(o,a,l);for(let o of r.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;i++;let a=o.readdirSync();this.walkCB3Sync(o,a,r,n)}n()}walkCB3Sync(t,e,r,s){r=r.filterEntries(t,e);let i=1,n=()=>{--i===0&&s()};for(let[o,a,l]of r.matches.entries())this.#i(o)||this.matchSync(o,a,l);for(let[o,a]of r.subwalks.entries())i++,this.walkCB2Sync(o,a,r.child(),n);n()}},gs=class extends ii{matches=new Set;constructor(t,e,r){super(t,e,r)}matchEmit(t){this.matches.add(t)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((t,e)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?e(this.signal.reason):t(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},Ss=class extends ii{results;constructor(t,e,r){super(t,e,r),this.results=new kt({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(t){this.results.write(t),this.results.flowing||this.pause()}stream(){let t=this.path;return t.isUnknown()?t.lstat().then(()=>{this.walkCB(t,this.patterns,()=>this.results.end())}):this.walkCB(t,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}},Ta=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",be=class{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(t,e){if(!e)throw new TypeError("glob options required");if(this.withFileTypes=!!e.withFileTypes,this.signal=e.signal,this.follow=!!e.follow,this.dot=!!e.dot,this.dotRelative=!!e.dotRelative,this.nodir=!!e.nodir,this.mark=!!e.mark,e.cwd?(e.cwd instanceof URL||e.cwd.startsWith("file://"))&&(e.cwd=(0,Ds.fileURLToPath)(e.cwd)):this.cwd="",this.cwd=e.cwd||"",this.root=e.root,this.magicalBraces=!!e.magicalBraces,this.nobrace=!!e.nobrace,this.noext=!!e.noext,this.realpath=!!e.realpath,this.absolute=e.absolute,this.includeChildMatches=e.includeChildMatches!==!1,this.noglobstar=!!e.noglobstar,this.matchBase=!!e.matchBase,this.maxDepth=typeof e.maxDepth=="number"?e.maxDepth:1/0,this.stat=!!e.stat,this.ignore=e.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof t=="string"&&(t=[t]),this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(t=t.map(a=>a.replace(/\\/g,"/"))),this.matchBase){if(e.noglobstar)throw new TypeError("base matching requires globstar");t=t.map(a=>a.includes("/")?a:`./**/${a}`)}if(this.pattern=t,this.platform=e.platform||Ta,this.opts={...e,platform:this.platform},e.scurry){if(this.scurry=e.scurry,e.nocase!==void 0&&e.nocase!==e.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let a=e.platform==="win32"?yr:e.platform==="darwin"?Zs:e.platform?br:ma;this.scurry=new a(this.cwd,{nocase:e.nocase,fs:e.fs})}this.nocase=this.scurry.nocase;let r=this.platform==="darwin"||this.platform==="win32",s={braceExpandMax:1e4,...e,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:r,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},i=this.pattern.map(a=>new ge(a,s)),[n,o]=i.reduce((a,l)=>(a[0].push(...l.set),a[1].push(...l.globParts),a),[[],[]]);this.patterns=n.map((a,l)=>{let c=o[l];if(!c)throw new Error("invalid pattern object");return new ei(a,c,0,this.platform)})}async walk(){return[...await new gs(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return[...new gs(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new Ss(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new Ss(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}},Ma=(t,e={})=>{Array.isArray(t)||(t=[t]);for(let r of t)if(new ge(r,e).hasMagic())return!0;return!1};function Rt(t,e={}){return new be(t,e).streamSync()}function ni(t,e={}){return new be(t,e).stream()}function et(t,e={}){return new be(t,e).walkSync()}async function Es(t,e={}){return new be(t,e).walk()}function Ot(t,e={}){return new be(t,e).iterateSync()}function oi(t,e={}){return new be(t,e).iterate()}var ka=Rt,Ca=Object.assign(ni,{sync:Rt}),Aa=Ot,Ra=Object.assign(oi,{sync:Ot}),Oa=Object.assign(et,{stream:Rt,iterate:Ot}),ws=Object.assign(Es,{glob:Es,globSync:et,sync:Oa,globStream:ni,stream:Ca,globStreamSync:Rt,streamSync:ka,globIterate:oi,iterate:Ra,globIterateSync:Ot,iterateSync:Aa,Glob:be,hasMagic:Ma,escape:Cs,unescape:xe});ws.glob=ws;var le=require("fs"),ai=require("path");function li(t){try{if(!(0,le.existsSync)(t))return{offsets:{}};let e=(0,le.readFileSync)(t,"utf-8"),r=JSON.parse(e);return r.offsets?r:{offsets:{}}}catch(e){return d.warn("TRANSCRIPT","Failed to load watch state, starting fresh",{statePath:t,error:e instanceof Error?e.message:String(e)}),{offsets:{}}}}function ci(t,e){try{let r=(0,ai.dirname)(t);(0,le.existsSync)(r)||(0,le.mkdirSync)(r,{recursive:!0}),(0,le.writeFileSync)(t,JSON.stringify(e,null,2))}catch(r){d.warn("TRANSCRIPT","Failed to save watch state",{statePath:t,error:r instanceof Error?r.message:String(r)})}}var ot=X(require("path"),1);var Fe=X(require("path"),1),Y=require("fs");var ui=require("node:child_process");function It(t,e,r){return(0,ui.spawn)(t,e??[],{windowsHide:!0,...r})}var W={DEFAULT:3e5,HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,WORKER_STARTUP_WAIT:1e3,PRE_RESTART_SETTLE_DELAY:2e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5},Ee={SUCCESS:0,FAILURE:1,BLOCKING_ERROR:2,USER_MESSAGE_ONLY:3};function ce(t){return process.platform==="win32"?Math.round(t*W.WINDOWS_MULTIPLIER):t}var Z=require("fs"),tt=require("path"),vr=require("os");var ee=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_API_TIMEOUT_MS:String(ce(W.API_REQUEST)),CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_GEMINI_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_GEMINI_MAX_TOKENS:"100000",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_OPENROUTER_MAX_TOKENS:"100000",CLAUDE_MEM_DATA_DIR:(0,tt.join)((0,vr.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,tt.join)((0,vr.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let r=this.get(e);return parseInt(r,10)}static getBool(e){let r=this.get(e);return r==="true"||r===!0}static applyEnvOverrides(e){let r={...e};for(let s of Object.keys(this.DEFAULTS))process.env[s]!==void 0&&(r[s]=process.env[s]);return r}static loadFromFile(e,r=!0){try{if(!(0,Z.existsSync)(e)){let a=this.getAllDefaults();try{let l=(0,tt.dirname)(e);(0,Z.existsSync)(l)||(0,Z.mkdirSync)(l,{recursive:!0}),(0,Z.writeFileSync)(e,JSON.stringify(a,null,2),"utf-8"),console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(l){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,l instanceof Error?l.message:String(l))}return r?this.applyEnvOverrides(a):a}let s=(0,Z.readFileSync)(e,"utf-8"),i=JSON.parse(s.replace(/^\uFEFF/,"")),n=i;if(i.env&&typeof i.env=="object"){n=i.env;try{(0,Z.writeFileSync)(e,JSON.stringify(n,null,2),"utf-8"),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(a){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,a instanceof Error?a.message:String(a))}}let o={...this.DEFAULTS};for(let a of Object.keys(this.DEFAULTS))n[a]!==void 0&&(o[a]=n[a]);return r?this.applyEnvOverrides(o):o}catch(s){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,s instanceof Error?s.message:String(s));let i=this.getAllDefaults();return r?this.applyEnvOverrides(i):i}}};var Dt=null;function ue(){return Dt!==null||(Dt=ee.loadFromFile(ut)),Dt}var ve=require("fs");var Ar=require("child_process");var re=require("fs"),kr=X(require("path"),1);var Ia=["CLAUDECODE_","CLAUDE_CODE_"],Da=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),Pa=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy"]),xa=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS"]);function Pt(t=process.env){let e={};for(let[r,s]of Object.entries(t))if(s!==void 0){if(xa.has(r)){e[r]=s;continue}Da.has(r)||Pa.has(r)||Ia.some(i=>r.startsWith(i))||(e[r]=s)}return e}var La=5e3,Na=1e3,Ua=R.supervisorRegistry();function te(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;return r==="EPERM"?!0:(d.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return d.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}var Fa=5e3,hi=new Map;function Wa(t){let e=hi.get(t);if(e&&Date.now()-e.capturedAtMs<Fa)return e.token;let r=null;try{let s=(0,Ar.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Pt(process.env),LC_ALL:"C",LANG:"C"}});if(s.status===0){let i=s.stdout.trim();r=i.length>0?i:null}}catch(s){d.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:s instanceof Error?s.message:String(s)}),r=null}return hi.set(t,{token:r,capturedAtMs:Date.now()}),r}function di(t){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux")try{let e=(0,re.readFileSync)(`/proc/${t}/stat`,"utf-8"),r=e.lastIndexOf(") ");if(r<0)return null;let i=e.slice(r+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(e){return d.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return Wa(t);try{let e=(0,Ar.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Pt(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let r=e.stdout.trim();return r.length>0?r:null}catch(e){return d.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}}function Rr(t){if(!t||!te(t.pid))return!1;if(!t.startToken)return!0;let e=di(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||d.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}var Cr=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=Ua){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,re.mkdirSync)(kr.default.dirname(this.registryPath),{recursive:!0}),!(0,re.existsSync)(this.registryPath)){this.persist();return}try{let s=JSON.parse((0,re.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[i,n]of Object.entries(s))this.entries.set(i,n)}catch(r){r instanceof Error?d.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):d.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&d.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,r,s){this.initialize(),this.entries.set(e,r),s&&this.runtimeProcesses.set(e,s),this.persist()}unregister(e){this.initialize();let r=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),r?.type==="sdk"&&Mr()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let s=Date.parse(e.startedAt),i=Date.parse(r.startedAt);return(Number.isNaN(s)?0:s)-(Number.isNaN(i)?0:i)})}getBySession(e){let r=String(e);return this.getAll().filter(s=>s.sessionId!==void 0&&String(s.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}getByPid(e){return this.getAll().filter(r=>r.pid===e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[s,i]of this.entries)te(i.pid)||(this.entries.delete(s),this.runtimeProcesses.delete(s),e+=1,i.type==="sdk"&&(r+=1));e>0&&this.persist();for(let s=0;s<r;s+=1)Mr();return e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let s=typeof e=="number"?e:Number(e)||void 0;d.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:s,pids:r.map(a=>a.pid)});let i=r.filter(a=>te(a.pid));for(let a of i)try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(l){l instanceof Error?l.code!=="ESRCH"&&d.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},l):d.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(l)})}let n=Date.now()+La;for(;Date.now()<n&&i.filter(l=>te(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100));let o=i.filter(a=>te(a.pid));for(let a of o){d.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:s});try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(l){l instanceof Error?l.code!=="ESRCH"&&d.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},l):d.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(l)})}}if(o.length>0){let a=Date.now()+Na;for(;Date.now()<a&&o.filter(c=>te(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100))}for(let a of r)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of r)a.type==="sdk"&&Mr();return d.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:s,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,re.mkdirSync)(kr.default.dirname(this.registryPath),{recursive:!0}),(0,re.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},Tr=null;function xt(){return Tr||(Tr=new Cr),Tr}var $a=[];function Mr(){let t=$a.shift();t&&t()}var mi=require("child_process"),Ne=require("fs"),gi=require("util");var Ha=(0,gi.promisify)(mi.execFile),ja=R.workerPid();async function Si(t){let e=t.currentPid??process.pid,r=t.pidFilePath??ja,s=t.registry.getAll(),i=[...s].filter(o=>o.pid!==e).sort((o,a)=>Date.parse(a.startedAt)-Date.parse(o.startedAt));for(let o of i){if(!te(o.pid)){t.registry.unregister(o.id);continue}try{await fi(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 pi(i,5e3);let n=i.filter(o=>te(o.pid));for(let o of n)try{await fi(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 pi(n,1e3);for(let o of i)t.registry.unregister(o.id);for(let o of s.filter(a=>a.pid===e))t.registry.unregister(o.id);Ba(r,e),t.registry.pruneDeadEntries()}function Ba(t,e){if(!(0,Ne.existsSync)(t))return;let r=null;try{let s=JSON.parse((0,Ne.readFileSync)(t,"utf-8"));r=typeof s.pid=="number"?s.pid:null}catch(s){d.debug("SYSTEM","PID file unreadable during shutdown \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:s instanceof Error?s.message:String(s)});return}if(r!==e){d.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:r,currentPid:e});return}try{(0,Ne.rmSync)(t,{force:!0})}catch(s){s instanceof Error?d.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:t},s):d.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:t,error:String(s)})}}async function pi(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.filter(i=>te(i.pid)).length===0)return;await new Promise(i=>setTimeout(i,100))}}async function fi(t,e){let{pid:r,pgid:s}=t;if(process.platform!=="win32"){if(typeof s=="number")try{process.kill(-s,e);return}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}try{process.kill(r,e)}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}return}if(e==="SIGTERM"){try{process.kill(r,e)}catch(o){if(o instanceof Error&&o.code==="ESRCH")return;throw o}return}let i=await Ga();if(i){await new Promise((o,a)=>{i(r,e,l=>{if(!l){o();return}if(l.code==="ESRCH"){o();return}a(l)})});return}let n=["/PID",String(r),"/T"];e==="SIGKILL"&&n.push("/F"),await Ha("taskkill",n,{timeout:W.POWERSHELL_COMMAND,windowsHide:!0})}async function Ga(){let t="tree-kill";try{let e=await import(t);return e.default??e}catch(e){return d.debug("SYSTEM","tree-kill module not available, using fallback",{},e instanceof Error?e:void 0),null}}var Ei=3e4,Ue=null;function Ka(){let e=xt().pruneDeadEntries();e>0&&d.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function wi(){Ue===null&&(Ue=setInterval(Ka,Ei),Ue.unref(),d.debug("SYSTEM","Health checker started",{intervalMs:Ei}))}function _i(){Ue!==null&&(clearInterval(Ue),Ue=null,d.debug("SYSTEM","Health checker stopped"))}var Ya=R.workerPid(),Or=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),Lt({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,wi()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async s=>{if(this.shutdownInitiated){d.warn("SYSTEM",`Received ${s} but shutdown already in progress`);return}this.shutdownInitiated=!0,d.info("SYSTEM",`Received ${s}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){i instanceof Error?d.error("SYSTEM","Error during shutdown",{},i):d.error("SYSTEM","Error during shutdown (non-Error)",{error:String(i)});try{await this.stop()}catch(n){n instanceof Error?d.debug("SYSTEM","Supervisor shutdown fallback failed",{},n):d.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(n)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{d.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}_i(),this.stopPromise=Si({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,s){this.registry.register(e,r,s)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},nu=new Or(xt());function Lt(t={}){let e=t.pidFilePath??Ya;if(!(0,ve.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,ve.readFileSync)(e,"utf-8"))}catch(i){return i instanceof Error?d.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},i):d.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(i)}),(0,ve.rmSync)(e,{force:!0}),"invalid"}return Rr(r)&&r?((t.logAlive??!0)&&d.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(d.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,ve.rmSync)(e,{force:!0}),"stale")}var Ir=require("path"),Ut=require("fs"),bi=require("crypto");var Nt=require("fs");function yi(t,e){if(!(0,Nt.existsSync)(t))return e;try{return JSON.parse((0,Nt.readFileSync)(t,"utf-8"))}catch(r){throw new Error(`Corrupt JSON file, refusing to overwrite: ${t}: ${r instanceof Error?r.message:String(r)}`)}}var vi="telemetry.json";function za(t){let e=t.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function Ja(t,e){if(za(t))return{enabled:!1,source:"DO_NOT_TRACK"};let r=t.CLAUDE_MEM_TELEMETRY?.toLowerCase();return r==="0"||r==="false"||r==="off"?{enabled:!1,source:"env"}:r==="1"||r==="true"||r==="on"?{enabled:!0,source:"env"}:e?.enabled===!0?{enabled:!0,source:"config"}:e?.enabled===!1?{enabled:!1,source:"config"}:{enabled:!0,source:"default"}}function Ti(t,e){return Ja(t,e).enabled}function Xa(){return(0,Ir.join)(Oe(),vi)}function Dr(){try{let t=yi(Xa(),null);return!t||typeof t!="object"||typeof t.installId!="string"||t.enabled!==void 0&&typeof t.enabled!="boolean"?null:{enabled:t.enabled,installId:t.installId,decidedAt:typeof t.decidedAt=="string"?t.decidedAt:""}}catch{return null}}function qa(t){let e=Oe();(0,Ut.mkdirSync)(e,{recursive:!0}),(0,Ut.writeFileSync)((0,Ir.join)(e,vi),JSON.stringify(t,null,2)+`
15
- `)}function Mi(){let t=Dr();if(t?.installId)return t.installId;let e=(0,bi.randomUUID)();return qa({installId:e,decidedAt:""}),e}var Va=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","install_method","interactive","bun_version","uv_version","claude_code_version","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","fabrication_detected","fabricated_count","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_invalid_output","top_model","fabrication_count","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens"]),ki=200;function Ci(t){let e={};try{if(!t||typeof t!="object")return e;for(let r of Object.keys(t)){if(!Va.has(r))continue;let s=t[r];typeof s=="string"?e[r]=s.length>ki?s.slice(0,ki):s:(typeof s=="number"&&Number.isFinite(s)||typeof s=="boolean")&&(e[r]=s)}}catch{}return e}var Pr=X(require("os"),1),Qa="13.7.0",Za="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",el="https://us.i.posthog.com";function Ai(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||Za}function Ri(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||el}var tl=["version","os","os_version","is_wsl","arch","runtime","locale","ide","provider","runtime_mode","install_method","claude_code_version","first_active_date","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs"];function Oi(t){let e={};for(let r of tl)t[r]!==void 0&&(e[r]=t[r]);return e}function rl(){try{return Pr.default.release()}catch{return"unknown"}}function sl(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||Pr.default.release().toLowerCase().includes("microsoft")}catch{return!1}}function Ii(){return{version:Qa,os:process.platform,os_version:rl(),is_wsl:sl(),arch:process.arch,runtime:process.versions.bun?"bun":"node",runtime_version:process.versions.bun??process.versions.node,node_version:process.versions.node,is_ci:!!process.env.CI,locale:Intl.DateTimeFormat().resolvedOptions().locale}}var il=2e3;async function Di(t,e,r){try{if(!Ti(process.env,Dr()))return;let s=Ci({...Ii(),...e??{}});if(r?.person?s.$set=Oi(s):s.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:t,properties:s})+`
16
- `);return}let i=Ai();if(!i)return;let n=new AbortController,o=setTimeout(()=>n.abort(),il);try{await fetch(`${Ri()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:i,event:t,distinct_id:Mi(),properties:s}),signal:n.signal})}finally{clearTimeout(o)}}catch{}}var Te=X(require("path"),1),xi=require("os"),se=require("fs"),rt=require("child_process");var Li=require("util");var vu=(0,Li.promisify)(rt.exec),Tu=R.dataDir(),Mu=R.workerPid();function Pi(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function ol(t,e){let r=e==="win32"?`where ${t}`:`which ${t}`,s;try{s=(0,rt.execSync)(r,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(n){return n instanceof Error?d.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},n):d.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},new Error(String(n))),null}return s.split(/\r?\n/).map(n=>n.trim()).find(n=>n.length>0)||null}var xr;function Ni(t={}){let e=Object.keys(t).length===0;if(e&&xr!==void 0)return xr;let r=al(t);return e&&r!==null&&(xr=r),r}function al(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(Pi(r))return r;let s=t.env??process.env,i=t.homeDirectory??(0,xi.homedir)(),n=t.pathExists??se.existsSync,o=t.lookupInPath??ol,a=e==="win32"?[s.BUN,s.BUN_PATH,Te.default.join(i,".bun","bin","bun.exe"),Te.default.join(i,".bun","bin","bun"),s.USERPROFILE?Te.default.join(s.USERPROFILE,".bun","bin","bun.exe"):void 0,s.LOCALAPPDATA?Te.default.join(s.LOCALAPPDATA,"bun","bun.exe"):void 0,s.LOCALAPPDATA?Te.default.join(s.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[s.BUN,s.BUN_PATH,Te.default.join(i,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun"];for(let l of a){let c=l?.trim();if(c&&(Pi(c)&&n(c)||c.toLowerCase()==="bun"))return c}return o("bun",e)}var Ui=X(require("path"),1);var Fi=require("fs");async function ll(t,e,r="GET"){let s=await fetch(`http://127.0.0.1:${t}${e}`,{method:r}),i="";try{i=await s.text()}catch{}return{ok:s.ok,statusCode:s.status,body:i}}function cl(){try{let t=Ui.default.join(ct,"package.json");return JSON.parse((0,Fi.readFileSync)(t,"utf-8")).version}catch(t){if(t instanceof Error){let e=t.code;if(e==="ENOENT"||e==="EBUSY")return d.debug("SYSTEM","Could not read plugin version (shutdown race)",{code:e}),"unknown";throw t}throw t}}async function ul(t){try{let e=await ll(t,"/api/version");return e.ok?JSON.parse(e.body).version:null}catch{return d.debug("SYSTEM","Could not fetch worker version",{}),null}}async function Wi(t){let e=cl(),r=await ul(t);return!r||e==="unknown"?{matches:!0,pluginVersion:e,workerVersion:r}:{matches:e===r,pluginVersion:e,workerVersion:r}}var Ft=require("path"),B=require("fs");var hl=6e4;function $i(){return(0,Ft.join)(Oe(),"spawn.lock")}function Hi(){let t=$i(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return(0,B.mkdirSync)((0,Ft.dirname)(t),{recursive:!0}),(0,B.writeFileSync)(t,e,{flag:"wx"}),!0}catch(s){if(s?.code!=="EEXIST")return!0;if(r>0)return!1;let n;try{n=(0,B.statSync)(t).mtimeMs}catch{continue}if(Date.now()-n<=hl)return!1;let o;try{o=(0,B.statSync)(t).mtimeMs}catch{continue}if(o!==n)return!1;try{(0,B.unlinkSync)(t)}catch{return!1}}return!1}function ji(){let t=$i();try{if(JSON.parse((0,B.readFileSync)(t,"utf-8")).pid!==process.pid)return;(0,B.unlinkSync)(t)}catch{}}function Fr(t,e,r){let s=process.env[t];if(s){let i=parseInt(s,10);if(Number.isFinite(i)&&i>=r.min&&i<=r.max)return i;d.warn("SYSTEM",`Invalid ${t}, using default`,{value:s,min:r.min,max:r.max})}return e}var Gt=Fr("CLAUDE_MEM_HEALTH_TIMEOUT_MS",ce(W.HEALTH_CHECK),{min:500,max:3e5}),Qu=Fr("CLAUDE_MEM_API_TIMEOUT_MS",ce(W.API_REQUEST),{min:500,max:3e5}),zi=Fr("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",ce(W.HOOK_READINESS_WAIT),{min:0,max:3e5}),dl={min:500,max:3e5};function Wr(t,e={},r){return new Promise((s,i)=>{let n=setTimeout(()=>i(new Error(`Request timed out after ${r}ms`)),r);fetch(t,e).then(o=>{clearTimeout(n),s(o)},o=>{clearTimeout(n),i(o)})})}var Wt=null,$t=null,Ht=null,jt=null;function pl(){return Fe.default.join(ee.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function $r(){return Ht!==null||(Ht=ee.loadFromFile(pl())),Ht}function Bi(t,e){if(!t)return null;let r=parseInt(t,10);return Number.isFinite(r)&&r>=e.min&&r<=e.max?r:null}function fl(t,e,r){let s=process.env[t];if(s!==void 0){let o=Bi(s,r);return o!==null?o:(d.warn("SYSTEM",`Invalid ${t}, using default`,{value:s,min:r.min,max:r.max}),e)}let i=$r()[t],n=Bi(i,r);return n!==null?n:(d.warn("SYSTEM",`Invalid ${t} in settings.json, using default`,{value:i,min:r.min,max:r.max}),e)}function Ji(){if(Wt!==null)return Wt;let t=$r();return Wt=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),Wt}function ml(){return $t!==null||($t=$r().CLAUDE_MEM_WORKER_HOST),$t}function gl(){return jt!==null||(jt=fl("CLAUDE_MEM_API_TIMEOUT_MS",ce(W.API_REQUEST),dl)),jt}function Sl(t){return`http://${ml()}:${Ji()}${t}`}function he(t,e={}){let r=e.method??"GET",s=e.timeoutMs??gl(),i=Sl(t),n={method:r};return e.headers&&(n.headers=e.headers),e.body&&(n.body=e.body),s>0?Wr(i,n,s):fetch(i,n)}async function El(){return(await he("/api/health",{timeoutMs:Gt})).ok}async function Gi(){return(await he("/api/readiness",{timeoutMs:Gt})).ok}function wl(){let t=[Fe.default.join(ct,"plugin","scripts","worker-service.cjs"),Fe.default.join(process.cwd(),"plugin","scripts","worker-service.cjs")];for(let e of t)if((0,Y.existsSync)(e))return e;return null}async function _l(t){let e=t.backoffMs;for(let r=1;r<=t.attempts;r++){if(await qi())return!0;r<t.attempts&&(await new Promise(s=>setTimeout(s,e)),e*=2)}return!1}async function Lr(t=zi){if(t<=0)try{return await Gi()}catch{return!1}let e=Date.now();for(;Date.now()-e<t;){try{if(await Gi())return!0}catch(s){d.debug("SYSTEM","Worker readiness check threw",{error:s instanceof Error?s.message:String(s)})}let r=t-(Date.now()-e);if(r<=0)break;await new Promise(s=>setTimeout(s,Math.min(250,r)))}return!1}async function Xi(){try{let e=await(await he("/api/health",{timeoutMs:Gt})).json();return typeof e.version=="string"?e.version:null}catch{return null}}async function yl(t,e=zi){let r=Date.now();for(;Date.now()-r<e;){if(await Xi()===t)return!0;let i=e-(Date.now()-r);if(i<=0)break;await new Promise(n=>setTimeout(n,Math.min(500,i)))}return!1}async function Nr(t){let e=await Xi();e!==null&&e!==t&&d.warn("SYSTEM","Worker is ready but still reports a stale version; not recycling again in this hook invocation (one recycle per hook event)",{pluginVersion:t,workerVersion:e})}async function qi(){let t;try{t=await El()}catch(r){return d.debug("SYSTEM","Worker health check threw",{error:r instanceof Error?r.message:String(r)}),!1}if(!t)return!1;let e=Lt({logAlive:!1});return e==="missing"||e==="alive"}async function Kt(){let t=null;if(await qi()){let{matches:n,pluginVersion:o,workerVersion:a}=await Wi(Ji());if(o!=="unknown"&&(t=o),n)return await Lr()?(t!==null&&await Nr(t),!0):(d.warn("SYSTEM","Worker is healthy but not ready; skipping hook API call"),!1);d.info("SYSTEM","Worker version mismatch \u2014 recycling stale worker",{pluginVersion:o,workerVersion:a});try{if(await he("/api/admin/restart",{method:"POST",timeoutMs:Gt}),await yl(o))return await Lr()?(t!==null&&await Nr(t),!0):(d.warn("SYSTEM","Recycled worker appeared but did not become ready; skipping hook API call"),!1);d.warn("SYSTEM","No successor worker appeared after recycle; falling through to lazy-spawn",{pluginVersion:o,workerVersion:a})}catch(l){d.debug("SYSTEM","Worker restart request failed; falling through to lazy-spawn",{error:l instanceof Error?l.message:String(l)})}}let e=Ni(),r=wl();if(!e)return d.warn("SYSTEM","Cannot lazy-spawn worker: Bun runtime not found on PATH"),!1;if(!r)return d.warn("SYSTEM","Cannot lazy-spawn worker: worker-service.cjs not found in plugin/scripts"),!1;let s=Hi();try{if(s){d.info("SYSTEM","Worker not running \u2014 lazy-spawning",{runtimePath:e,scriptPath:r});try{It(e,[r,"--daemon"],{detached:!0,stdio:["ignore","ignore","ignore"]}).unref()}catch(o){return o instanceof Error?d.error("SYSTEM","Lazy-spawn of worker failed",{runtimePath:e,scriptPath:r},o):d.error("SYSTEM","Lazy-spawn of worker failed (non-Error)",{runtimePath:e,scriptPath:r,error:String(o)}),!1}}else d.info("SYSTEM","Another launcher holds the spawn lock \u2014 skipping lazy-spawn and waiting for its worker");if(!await _l({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&&ji()}return await Lr()?(t!==null&&await Nr(t),!0):(d.warn("SYSTEM","Worker lazy-spawned but did not become ready before hook readiness timeout"),!1)}var Bt=null;async function bl(){return Bt!==null||(Bt=await Kt()),Bt}var vl=3;function Vi(){return Fe.default.join(v,"state")}function Qi(){return Fe.default.join(Vi(),"hook-failures.json")}function Zi(){try{let t=(0,Y.readFileSync)(Qi(),"utf-8"),e=JSON.parse(t);return{consecutiveFailures:typeof e.consecutiveFailures=="number"&&Number.isFinite(e.consecutiveFailures)?Math.max(0,Math.floor(e.consecutiveFailures)):0,lastFailureAt:typeof e.lastFailureAt=="number"&&Number.isFinite(e.lastFailureAt)?e.lastFailureAt:0}}catch{return{consecutiveFailures:0,lastFailureAt:0}}}function en(t){let e=Vi(),r=Qi(),s=`${r}.tmp`;try{(0,Y.existsSync)(e)||(0,Y.mkdirSync)(e,{recursive:!0}),(0,Y.writeFileSync)(s,JSON.stringify(t),"utf-8"),(0,Y.renameSync)(s,r)}catch(i){d.debug("SYSTEM","Failed to persist hook-failure counter",{error:i instanceof Error?i.message:String(i)})}}function Tl(){try{let e=ue().CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD,r=parseInt(e,10);if(Number.isFinite(r)&&r>=1)return r}catch{}return vl}var Ki=null;async function Ml(){let e={consecutiveFailures:Zi().consecutiveFailures+1,lastFailureAt:Date.now()};en(e);let r=Tl();return e.consecutiveFailures>=r&&(e.consecutiveFailures===r&&await Di("hook_failed",{...Ki!==null?{hook_type:Ki}:{},error_mode:"worker_unavailable",consecutive_failures:e.consecutiveFailures,threshold_tripped:!0}),zr(`claude-mem worker unreachable for ${e.consecutiveFailures} consecutive hooks.`)),e.consecutiveFailures}function Yi(){Zi().consecutiveFailures!==0&&en({consecutiveFailures:0,lastFailureAt:0})}var Ur=Symbol.for("claude-mem/worker-fallback");function st(t){return typeof t=="object"&&t!==null&&t[Ur]===!0}async function it(t,e,r,s={}){if(!await bl())return await Ml(),{continue:!0,reason:"worker_unreachable",[Ur]:!0};let n={method:e};r!==void 0&&(n.headers={"Content-Type":"application/json"},n.body=JSON.stringify(r)),s.timeoutMs!==void 0&&(n.timeoutMs=s.timeoutMs);let o=await he(t,n);if(!o.ok){let l=await o.text().catch(()=>"");if(Yi(),o.status===429||o.status>=500)return d.warn("SYSTEM",`Worker API ${e} ${t} returned ${o.status}; skipping hook API call`,{body:l.substring(0,200)}),{continue:!0,reason:`worker_api_${o.status}`,[Ur]:!0};let c=l;try{c=JSON.parse(l)}catch{}return c}Yi();let a=await o.text();if(a.length!==0)try{return JSON.parse(a)}catch{return a}}var rn=require("os"),sn=X(require("path"),1),nn=require("child_process");var zt=require("fs"),Yt=X(require("path"),1);var nt={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function tn(t){let e=Yt.default.join(t,".git"),r;try{r=(0,zt.statSync)(e)}catch(u){return u instanceof Error&&u.code!=="ENOENT"&&d.warn("GIT","Unexpected error checking .git",{error:u instanceof Error?u.message:String(u)}),nt}if(!r.isFile())return nt;let s;try{s=(0,zt.readFileSync)(e,"utf-8").trim()}catch(u){return d.warn("GIT","Failed to read .git file",{error:u instanceof Error?u.message:String(u)}),nt}let i=s.match(/^gitdir:\s*(.+)$/);if(!i)return nt;let o=i[1].match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!o)return nt;let a=o[1],l=Yt.default.basename(t),c=Yt.default.basename(a);return{isWorktree:!0,worktreeName:l,parentRepoPath:a,parentProjectName:c}}function on(t){return t==="~"||t.startsWith("~/")?t.replace(/^~/,(0,rn.homedir)()):t}function kl(t){try{return(0,nn.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function Cl(t){if(!t||t.trim()==="")return d.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),"unknown-project";let e=on(t),s=kl(e)??e,i=sn.default.basename(s);if(i===""){if(process.platform==="win32"){let o=t.match(/^([A-Z]):\\/i);if(o){let l=`drive-${o[1].toUpperCase()}`;return d.info("PROJECT_NAME","Drive root detected",{cwd:t,projectName:l}),l}}return d.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:t}),"unknown-project"}return i}function Me(t){let e=Cl(t);if(!t)return{primary:e,parent:null,isWorktree:!1,allProjects:[e]};let r=on(t),s=tn(r);if(s.isWorktree&&s.parentProjectName){let i=`${s.parentProjectName}/${e}`;return{primary:i,parent:s.parentProjectName,isWorktree:!0,allProjects:[s.parentProjectName,i]}}return{primary:e,parent:null,isWorktree:!1,allProjects:[e]}}var ke=require("path");var an=require("os"),ln=require("path");function Al(t){let e=t.startsWith("~")?(0,an.homedir)()+t.slice(1):t;e=e.replace(/\\/g,"/");let r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return r=r.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${r}$`)}function Jt(t,e){if(!e||!e.trim())return!1;let r=t.replace(/\\/g,"/"),s=(0,ln.basename)(r),i=e.split(",").map(n=>n.trim()).filter(Boolean);for(let n of i)try{let o=Al(n);if(o.test(r)||o.test(s))return!0}catch(o){d.warn("PROJECT_NAME","Invalid exclusion pattern",{pattern:n,error:o instanceof Error?o.message:String(o)});continue}return!1}function Rl(t,e){let r=(0,ke.normalize)(t),s=(0,ke.normalize)(e);if(r===s)return!0;let i=(0,ke.relative)(s,r);return i.length>0&&!i.startsWith("..")&&!(0,ke.isAbsolute)(i)}function Xt(t){if(process.env.CLAUDE_MEM_INTERNAL==="1")return!1;if(!t)return!0;if(Rl(t,ht))return!1;let e=ue();return!Jt(t,e.CLAUDE_MEM_EXCLUDED_PROJECTS)}var cn="claude";function Ol(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function we(t){if(!t)return cn;let e=Ol(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:cn}var dn=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],un=new RegExp(`<(${dn.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g");var hn=100;function Il(t){let e=Object.fromEntries(dn.map(i=>[i,0]));un.lastIndex=0;let r=0,s=t.replace(un,(i,n)=>(e[n]=(e[n]??0)+1,r+=1,""));return r>hn&&d.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:r,maxAllowed:hn,contentLength:t.length}),{stripped:s.trim(),counts:e}}function Hr(t){return Il(t).stripped}var Dl=["task-notification"],Pl=new RegExp(`^\\s*<(${Dl.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),xl=256*1024;function pn(t){return!t||t.length>xl?!1:Pl.test(t)}var Ll=ce(W.API_REQUEST),de=class extends Error{kind;status;cause;constructor(e,r,s={}){super(r),this.name="ServerBetaClientError",this.kind=e,this.status=s.status??null,this.cause=s.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},qt=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=Nl(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??Ll}async startSession(e){let r=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",r)}async recordEvent(e){let r=this.buildEventPayload(e),s=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",s,r)}async endSession(e){if(!e.sessionId)throw new de("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async getJobStatus(e){if(!e)throw new de("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,s=e.kind??"manual",i=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:s,type:s,narrative:r,...i?{title:i}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:e.platformSource}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,r,s){if(!this.apiKey||!this.apiKey.trim())throw new de("missing_api_key","Server beta API key is not configured (CLAUDE_MEM_SERVER_BETA_API_KEY).");let i=`${this.baseUrl}${r}`,n={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};s!==void 0&&(n.body=JSON.stringify(s));let o;try{o=await Wr(i,n,this.timeoutMs)}catch(l){let c=l instanceof Error?l.message:String(l),u=/timed out|timeout/i.test(c);throw new de(u?"timeout":"transport",`Server beta ${e} ${r} failed: ${c}`,{cause:l})}if(!o.ok){let l=await o.text().catch(()=>"");throw new de("http_error",`Server beta ${e} ${r} returned ${o.status}: ${Ul(l,200)}`,{status:o.status})}let a=await o.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(l){throw new de("invalid_response",`Server beta ${e} ${r} returned non-JSON response`,{cause:l})}}};function fn(t){return t instanceof de}function Nl(t){return t.replace(/\/+$/,"")}function Ul(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Fl(){return(ue().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase()==="server-beta"?"server-beta":"worker"}function Wl(){let t=ue(),e=(t.CLAUDE_MEM_SERVER_BETA_URL??"").trim(),r=(t.CLAUDE_MEM_SERVER_BETA_API_KEY??"").trim(),s=(t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID??"").trim();if(!e)return d.warn("HOOK","[server-beta-fallback] reason=missing_base_url"),null;if(!r)return d.warn("HOOK","[server-beta-fallback] reason=missing_api_key"),null;if(!s)return d.warn("HOOK","[server-beta-fallback] reason=missing_project_id"),null;let i={serverBaseUrl:e,apiKey:r};return{runtime:"server-beta",client:new qt(i),projectId:s,serverBaseUrl:e}}function mn(){if(Fl()!=="server-beta")return{runtime:"worker"};let t=Wl();return t||{runtime:"worker"}}function gn(t,e){d.warn("HOOK",`[server-beta-fallback] reason=${t}`,e??{})}var Sn={async execute(t){let{sessionId:e,prompt:r}=t,s=t.cwd??process.cwd();if(!e)return d.warn("HOOK","session-init: No sessionId provided, skipping (Codex CLI or unknown platform)"),{continue:!0,suppressOutput:!0,exitCode:Ee.SUCCESS};if(!Xt(s))return d.info("HOOK","Project excluded from tracking",{cwd:s}),{continue:!0,suppressOutput:!0};if(r&&pn(r))return d.debug("HOOK","session-init: skipping internal protocol payload",{preview:r.slice(0,80)}),{continue:!0,suppressOutput:!0};let i=!r||!r.trim()?"[media prompt]":r,n=Me(s).primary,o=we(t.platform),a=mn();if(a.runtime==="server-beta")try{return await a.client.startSession({projectId:a.projectId,externalSessionId:e,contentSessionId:e,agentId:t.agentId??null,agentType:t.agentType??null,platformSource:o,metadata:{project:n,prompt:i}}),d.info("HOOK","session-init: server-beta session started",{contentSessionId:e,project:n}),{continue:!0,suppressOutput:!0}}catch(m){if(fn(m)&&m.isFallbackEligible())gn(m.kind,{status:m.status,message:m.message,route:"/v1/sessions/start"});else return d.error("HOOK","Server beta session-start failed (non-recoverable)",{error:m instanceof Error?m.message:String(m)}),{continue:!0,suppressOutput:!0,exitCode:Ee.SUCCESS}}d.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:e,project:n});let l=await it("/api/sessions/init","POST",{contentSessionId:e,project:n,prompt:i,platformSource:o});if(st(l))return{continue:!0,suppressOutput:!0,exitCode:Ee.SUCCESS};if(typeof l?.sessionDbId!="number")return d.failure("HOOK","Session initialization returned malformed response",{contentSessionId:e,project:n}),{continue:!0,suppressOutput:!0,exitCode:Ee.SUCCESS};let c=l.sessionDbId,u=l.promptNumber;if(d.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:c,promptNumber:u,skipped:l.skipped,contextInjected:l.contextInjected}),d.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${e} | prompt#=${u} | sessionDbId=${c}`),l.skipped&&l.reason==="private")return d.info("HOOK",`INIT_COMPLETE | sessionDbId=${c} | promptNumber=${u} | skipped=true | reason=private`,{sessionId:c}),{continue:!0,suppressOutput:!0};let h=ue(),p=String(h.CLAUDE_MEM_SEMANTIC_INJECT).toLowerCase()==="true",f="";if(p&&i&&i.length>=20&&i!=="[media prompt]"){let m=h.CLAUDE_MEM_SEMANTIC_INJECT_LIMIT||"5",g=await it("/api/context/semantic","POST",{q:i,project:n,limit:m});!st(g)&&g?.context&&(d.debug("HOOK",`Semantic injection: ${g.count} observations for prompt`,{sessionId:c,count:g.count}),f=g.context)}return d.info("HOOK",`INIT_COMPLETE | sessionDbId=${c} | promptNumber=${u} | project=${n}`,{sessionId:c}),f?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:f}}:{continue:!0,suppressOutput:!0}}};var En={async execute(t){let{sessionId:e,cwd:r,filePath:s,edits:i}=t,n=we(t.platform);if(!s)throw new Error("fileEditHandler requires filePath");if(d.dataIn("HOOK",`FileEdit: ${s}`,{editCount:i?.length??0}),!r)throw new Error(`Missing cwd in FileEdit hook input for session ${e}, file ${s}`);if(!Xt(r))return d.debug("HOOK","Project excluded from tracking, skipping file edit observation",{cwd:r,filePath:s}),{continue:!0,suppressOutput:!0,exitCode:Ee.SUCCESS};let o=await it("/api/sessions/observations","POST",{contentSessionId:e,platformSource:n,tool_name:"write_file",tool_input:{filePath:s,edits:i},tool_response:{success:!0},cwd:r});return st(o)?{continue:!0,suppressOutput:!0,exitCode:Ee.SUCCESS}:(d.debug("HOOK","File edit observation sent successfully",{filePath:s}),{continue:!0,suppressOutput:!0})}};var z=require("fs"),Vt=require("path");var Qh=R.settings();function wn(t,e){let r="<claude-mem-context>",s="</claude-mem-context>";if(!t)return`${r}
14
+ >>> no match, partial?`,t,h,e,p),h===a))}let m;if(typeof c=="string"?(m=u===c,this.debug("string match",c,u,m)):(m=c.test(u),this.debug("pattern match",c,u,m)),!m)return!1}if(n===a&&o===l)return!0;if(n===a)return r;if(o===l)return n===a-1&&t[n]==="";throw new Error("wtf?")}braceExpand(){return Ds(this.pattern,this.options)}parse(t){vt(t);let e=this.options;if(t==="**")return P;if(t==="")return"";let r,s=null;(r=t.match(Ro))?s=e.dot?Do:Oo:(r=t.match(wo))?s=(e.nocase?e.dot?vo:bo:e.dot?_o:yo)(r[1]):(r=t.match(Po))?s=(e.nocase?e.dot?xo:Io:e.dot?Lo:No)(r):(r=t.match(To))?s=e.dot?Ao:Mo:(r=t.match(Co))&&(s=ko);let i=As.fromGlob(t,this.options).toMMPattern();return s&&typeof i=="object"&&Reflect.defineProperty(i,"test",{value:s}),i}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let t=this.set;if(!t.length)return this.regexp=!1,this.regexp;let e=this.options,r=e.noglobstar?Wo:e.dot?Ho:jo,s=new Set(e.nocase?["i"]:[]),i=t.map(a=>{let l=a.map(u=>{if(u instanceof RegExp)for(let h of u.flags.split(""))s.add(h);return typeof u=="string"?Yo(u):u===P?P:u._src});l.forEach((u,h)=>{let p=l[h+1],f=l[h-1];u!==P||f===P||(f===void 0?p!==void 0&&p!==P?l[h+1]="(?:\\/|"+r+"\\/)?"+p:l[h]=r:p===void 0?l[h-1]=f+"(?:\\/|\\/"+r+")?":p!==P&&(l[h-1]=f+"(?:\\/|\\/"+r+"\\/)"+p,l[h+1]=P))});let c=l.filter(u=>u!==P);if(this.partial&&c.length>=1){let u=[];for(let h=1;h<=c.length;h++)u.push(c.slice(0,h).join("/"));return"(?:"+u.join("|")+")"}return c.join("/")}).join("|"),[n,o]=t.length>1?["(?:",")"]:["",""];i="^"+n+i+o+"$",this.partial&&(i="^(?:\\/|"+n+i.slice(1,-1)+o+")$"),this.negate&&(i="^(?!"+i+").+$");try{this.regexp=new RegExp(i,[...s].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(t){return this.preserveMultipleSlashes?t.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(t)?["",...t.split(/\/+/)]:t.split(/\/+/)}match(t,e=this.partial){if(this.debug("match",t,this.pattern),this.comment)return!1;if(this.empty)return t==="";if(t==="/"&&e)return!0;let r=this.options;this.isWindows&&(t=t.split("\\").join("/"));let s=this.slashSplit(t);this.debug(this.pattern,"split",s);let i=this.set;this.debug(this.pattern,"set",i);let n=s[s.length-1];if(!n)for(let o=s.length-2;!n&&o>=0;o--)n=s[o];for(let o=0;o<i.length;o++){let a=i[o],l=s;if(r.matchBase&&a.length===1&&(l=[n]),this.matchOne(l,a,e))return r.flipNegate?!0:!this.negate}return r.flipNegate?!1:this.negate}static defaults(t){return I.defaults(t).Minimatch}};I.AST=As;I.Minimatch=ge;I.escape=Cs;I.unescape=xe;var zo=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Is=new Set,Sr=typeof process=="object"&&process?process:{},xs=(t,e,r,s)=>{typeof Sr.emitWarning=="function"?Sr.emitWarning(t,e,r,s):console.error(`[${r}] ${e}: ${t}`)},Tt=globalThis.AbortController,is=globalThis.AbortSignal;if(typeof Tt>"u"){is=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,s){this._onabort.push(s)}},Tt=class{constructor(){e()}signal=new is;abort(r){if(!this.signal.aborted){this.signal.reason=r,this.signal.aborted=!0;for(let s of this.signal._onabort)s(r);this.signal.onabort?.(r)}}};let t=Sr.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,xs("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var Jo=t=>!Is.has(t),me=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),Ls=t=>me(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?_t:null:null,_t=class extends Array{constructor(t){super(t),this.fill(0)}},Xo=class qe{heap;length;static#e=!1;static create(e){let r=Ls(e);if(!r)return[];qe.#e=!0;let s=new qe(e,r);return qe.#e=!1,s}constructor(e,r){if(!qe.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new r(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},At=class Ns{#e;#r;#n;#i;#o;#y;#S;#u;get perf(){return this.#u}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#a;#d;#h;#l;#s;#p;#_;#w;#f;#k;#m;#T;#M;#g;#E;#b;#A;#t;#x;static unsafeExposeInternals(e){return{starts:e.#M,ttls:e.#g,autopurgeTimers:e.#E,sizes:e.#T,keyMap:e.#h,keyList:e.#l,valList:e.#s,next:e.#p,prev:e.#_,get head(){return e.#w},get tail(){return e.#f},free:e.#k,isBackgroundFetch:r=>e.#c(r),backgroundFetch:(r,s,i,n)=>e.#$(r,s,i,n),moveToTail:r=>e.#N(r),indexes:r=>e.#O(r),rindexes:r=>e.#D(r),isStale:r=>e.#v(r)}}get max(){return this.#e}get maxSize(){return this.#r}get calculatedSize(){return this.#d}get size(){return this.#a}get fetchMethod(){return this.#y}get memoMethod(){return this.#S}get dispose(){return this.#n}get onInsert(){return this.#i}get disposeAfter(){return this.#o}constructor(e){let{max:r=0,ttl:s,ttlResolution:i=1,ttlAutopurge:n,updateAgeOnGet:o,updateAgeOnHas:a,allowStale:l,dispose:c,onInsert:u,disposeAfter:h,noDisposeOnSet:p,noUpdateTTL:f,maxSize:m=0,maxEntrySize:g=0,sizeCalculation:w,fetchMethod:S,memoMethod:E,noDeleteOnFetchRejection:y,noDeleteOnStaleGet:b,allowStaleOnFetchRejection:T,allowStaleOnFetchAbort:pe,ignoreFetchAbort:Ce,perf:ke}=e;if(ke!==void 0&&typeof ke?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#u=ke??zo,r!==0&&!me(r))throw new TypeError("max option must be a nonnegative integer");let Re=r?Ls(r):Array;if(!Re)throw new Error("invalid max value: "+r);if(this.#e=r,this.#r=m,this.maxEntrySize=g||this.#r,this.sizeCalculation=w,this.sizeCalculation){if(!this.#r&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(E!==void 0&&typeof E!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#S=E,S!==void 0&&typeof S!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#y=S,this.#A=!!S,this.#h=new Map,this.#l=new Array(r).fill(void 0),this.#s=new Array(r).fill(void 0),this.#p=new Re(r),this.#_=new Re(r),this.#w=0,this.#f=0,this.#k=Xo.create(r),this.#a=0,this.#d=0,typeof c=="function"&&(this.#n=c),typeof u=="function"&&(this.#i=u),typeof h=="function"?(this.#o=h,this.#m=[]):(this.#o=void 0,this.#m=void 0),this.#b=!!this.#n,this.#x=!!this.#i,this.#t=!!this.#o,this.noDisposeOnSet=!!p,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!y,this.allowStaleOnFetchRejection=!!T,this.allowStaleOnFetchAbort=!!pe,this.ignoreFetchAbort=!!Ce,this.maxEntrySize!==0){if(this.#r!==0&&!me(this.#r))throw new TypeError("maxSize must be a positive integer if specified");if(!me(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#G()}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!b,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!a,this.ttlResolution=me(i)||i===0?i:1,this.ttlAutopurge=!!n,this.ttl=s||0,this.ttl){if(!me(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#P()}if(this.#e===0&&this.ttl===0&&this.#r===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#e&&!this.#r){let tr="LRU_CACHE_UNBOUNDED";Jo(tr)&&(Is.add(tr),xs("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",tr,Ns))}}getRemainingTTL(e){return this.#h.has(e)?1/0:0}#P(){let e=new _t(this.#e),r=new _t(this.#e);this.#g=e,this.#M=r;let s=this.ttlAutopurge?new Array(this.#e):void 0;this.#E=s,this.#F=(o,a,l=this.#u.now())=>{if(r[o]=a!==0?l:0,e[o]=a,s?.[o]&&(clearTimeout(s[o]),s[o]=void 0),a!==0&&s){let c=setTimeout(()=>{this.#v(o)&&this.#R(this.#l[o],"expire")},a+1);c.unref&&c.unref(),s[o]=c}},this.#C=o=>{r[o]=e[o]!==0?this.#u.now():0},this.#I=(o,a)=>{if(e[a]){let l=e[a],c=r[a];if(!l||!c)return;o.ttl=l,o.start=c,o.now=i||n();let u=o.now-c;o.remainingTTL=l-u}};let i=0,n=()=>{let o=this.#u.now();if(this.ttlResolution>0){i=o;let a=setTimeout(()=>i=0,this.ttlResolution);a.unref&&a.unref()}return o};this.getRemainingTTL=o=>{let a=this.#h.get(o);if(a===void 0)return 0;let l=e[a],c=r[a];if(!l||!c)return 1/0;let u=(i||n())-c;return l-u},this.#v=o=>{let a=r[o],l=e[o];return!!l&&!!a&&(i||n())-a>l}}#C=()=>{};#I=()=>{};#F=()=>{};#v=()=>!1;#G(){let e=new _t(this.#e);this.#d=0,this.#T=e,this.#U=r=>{this.#d-=e[r],e[r]=0},this.#W=(r,s,i,n)=>{if(this.#c(s))return 0;if(!me(i))if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(i=n(s,r),!me(i))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return i},this.#L=(r,s,i)=>{if(e[r]=s,this.#r){let n=this.#r-e[r];for(;this.#d>n;)this.#j(!0)}this.#d+=e[r],i&&(i.entrySize=s,i.totalCalculatedSize=this.#d)}}#U=e=>{};#L=(e,r,s)=>{};#W=(e,r,s,i)=>{if(s||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#O({allowStale:e=this.allowStale}={}){if(this.#a)for(let r=this.#f;!(!this.#H(r)||((e||!this.#v(r))&&(yield r),r===this.#w));)r=this.#_[r]}*#D({allowStale:e=this.allowStale}={}){if(this.#a)for(let r=this.#w;!(!this.#H(r)||((e||!this.#v(r))&&(yield r),r===this.#f));)r=this.#p[r]}#H(e){return e!==void 0&&this.#h.get(this.#l[e])===e}*entries(){for(let e of this.#O())this.#s[e]!==void 0&&this.#l[e]!==void 0&&!this.#c(this.#s[e])&&(yield[this.#l[e],this.#s[e]])}*rentries(){for(let e of this.#D())this.#s[e]!==void 0&&this.#l[e]!==void 0&&!this.#c(this.#s[e])&&(yield[this.#l[e],this.#s[e]])}*keys(){for(let e of this.#O()){let r=this.#l[e];r!==void 0&&!this.#c(this.#s[e])&&(yield r)}}*rkeys(){for(let e of this.#D()){let r=this.#l[e];r!==void 0&&!this.#c(this.#s[e])&&(yield r)}}*values(){for(let e of this.#O())this.#s[e]!==void 0&&!this.#c(this.#s[e])&&(yield this.#s[e])}*rvalues(){for(let e of this.#D())this.#s[e]!==void 0&&!this.#c(this.#s[e])&&(yield this.#s[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,r={}){for(let s of this.#O()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;if(n!==void 0&&e(n,this.#l[s],this))return this.get(this.#l[s],r)}}forEach(e,r=this){for(let s of this.#O()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;n!==void 0&&e.call(r,n,this.#l[s],this)}}rforEach(e,r=this){for(let s of this.#D()){let i=this.#s[s],n=this.#c(i)?i.__staleWhileFetching:i;n!==void 0&&e.call(r,n,this.#l[s],this)}}purgeStale(){let e=!1;for(let r of this.#D({allowStale:!0}))this.#v(r)&&(this.#R(this.#l[r],"expire"),e=!0);return e}info(e){let r=this.#h.get(e);if(r===void 0)return;let s=this.#s[r],i=this.#c(s)?s.__staleWhileFetching:s;if(i===void 0)return;let n={value:i};if(this.#g&&this.#M){let o=this.#g[r],a=this.#M[r];if(o&&a){let l=o-(this.#u.now()-a);n.ttl=l,n.start=Date.now()}}return this.#T&&(n.size=this.#T[r]),n}dump(){let e=[];for(let r of this.#O({allowStale:!0})){let s=this.#l[r],i=this.#s[r],n=this.#c(i)?i.__staleWhileFetching:i;if(n===void 0||s===void 0)continue;let o={value:n};if(this.#g&&this.#M){o.ttl=this.#g[r];let a=this.#u.now()-this.#M[r];o.start=Math.floor(Date.now()-a)}this.#T&&(o.size=this.#T[r]),e.unshift([s,o])}return e}load(e){this.clear();for(let[r,s]of e){if(s.start){let i=Date.now()-s.start;s.start=this.#u.now()-i}this.set(r,s.value,s)}}set(e,r,s={}){if(r===void 0)return this.delete(e),this;let{ttl:i=this.ttl,start:n,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=s,{noUpdateTTL:c=this.noUpdateTTL}=s,u=this.#W(e,r,s.size||0,a);if(this.maxEntrySize&&u>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=!0),this.#R(e,"set"),this;let h=this.#a===0?void 0:this.#h.get(e);if(h===void 0)h=this.#a===0?this.#f:this.#k.length!==0?this.#k.pop():this.#a===this.#e?this.#j(!1):this.#a,this.#l[h]=e,this.#s[h]=r,this.#h.set(e,h),this.#p[this.#f]=h,this.#_[h]=this.#f,this.#f=h,this.#a++,this.#L(h,u,l),l&&(l.set="add"),c=!1,this.#x&&this.#i?.(r,e,"add");else{this.#N(h);let p=this.#s[h];if(r!==p){if(this.#A&&this.#c(p)){p.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:f}=p;f!==void 0&&!o&&(this.#b&&this.#n?.(f,e,"set"),this.#t&&this.#m?.push([f,e,"set"]))}else o||(this.#b&&this.#n?.(p,e,"set"),this.#t&&this.#m?.push([p,e,"set"]));if(this.#U(h),this.#L(h,u,l),this.#s[h]=r,l){l.set="replace";let f=p&&this.#c(p)?p.__staleWhileFetching:p;f!==void 0&&(l.oldValue=f)}}else l&&(l.set="update");this.#x&&this.onInsert?.(r,e,r===p?"update":"replace")}if(i!==0&&!this.#g&&this.#P(),this.#g&&(c||this.#F(h,i,n),l&&this.#I(l,h)),!o&&this.#t&&this.#m){let p=this.#m,f;for(;f=p?.shift();)this.#o?.(...f)}return this}pop(){try{for(;this.#a;){let e=this.#s[this.#w];if(this.#j(!0),this.#c(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#t&&this.#m){let e=this.#m,r;for(;r=e?.shift();)this.#o?.(...r)}}}#j(e){let r=this.#w,s=this.#l[r],i=this.#s[r];return this.#A&&this.#c(i)?i.__abortController.abort(new Error("evicted")):(this.#b||this.#t)&&(this.#b&&this.#n?.(i,s,"evict"),this.#t&&this.#m?.push([i,s,"evict"])),this.#U(r),this.#E?.[r]&&(clearTimeout(this.#E[r]),this.#E[r]=void 0),e&&(this.#l[r]=void 0,this.#s[r]=void 0,this.#k.push(r)),this.#a===1?(this.#w=this.#f=0,this.#k.length=0):this.#w=this.#p[r],this.#h.delete(s),this.#a--,r}has(e,r={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:i}=r,n=this.#h.get(e);if(n!==void 0){let o=this.#s[n];if(this.#c(o)&&o.__staleWhileFetching===void 0)return!1;if(this.#v(n))i&&(i.has="stale",this.#I(i,n));else return s&&this.#C(n),i&&(i.has="hit",this.#I(i,n)),!0}else i&&(i.has="miss");return!1}peek(e,r={}){let{allowStale:s=this.allowStale}=r,i=this.#h.get(e);if(i===void 0||!s&&this.#v(i))return;let n=this.#s[i];return this.#c(n)?n.__staleWhileFetching:n}#$(e,r,s,i){let n=r===void 0?void 0:this.#s[r];if(this.#c(n))return n;let o=new Tt,{signal:a}=s;a?.addEventListener("abort",()=>o.abort(a.reason),{signal:o.signal});let l={signal:o.signal,options:s,context:i},c=(g,w=!1)=>{let{aborted:S}=o.signal,E=s.ignoreFetchAbort&&g!==void 0,y=s.ignoreFetchAbort||!!(s.allowStaleOnFetchAbort&&g!==void 0);if(s.status&&(S&&!w?(s.status.fetchAborted=!0,s.status.fetchError=o.signal.reason,E&&(s.status.fetchAbortIgnored=!0)):s.status.fetchResolved=!0),S&&!E&&!w)return h(o.signal.reason,y);let b=f,T=this.#s[r];return(T===f||E&&w&&T===void 0)&&(g===void 0?b.__staleWhileFetching!==void 0?this.#s[r]=b.__staleWhileFetching:this.#R(e,"fetch"):(s.status&&(s.status.fetchUpdated=!0),this.set(e,g,l.options))),g},u=g=>(s.status&&(s.status.fetchRejected=!0,s.status.fetchError=g),h(g,!1)),h=(g,w)=>{let{aborted:S}=o.signal,E=S&&s.allowStaleOnFetchAbort,y=E||s.allowStaleOnFetchRejection,b=y||s.noDeleteOnFetchRejection,T=f;if(this.#s[r]===f&&(!b||!w&&T.__staleWhileFetching===void 0?this.#R(e,"fetch"):E||(this.#s[r]=T.__staleWhileFetching)),y)return s.status&&T.__staleWhileFetching!==void 0&&(s.status.returnedStale=!0),T.__staleWhileFetching;if(T.__returned===T)throw g},p=(g,w)=>{let S=this.#y?.(e,n,l);S&&S instanceof Promise&&S.then(E=>g(E===void 0?void 0:E),w),o.signal.addEventListener("abort",()=>{(!s.ignoreFetchAbort||s.allowStaleOnFetchAbort)&&(g(void 0),s.allowStaleOnFetchAbort&&(g=E=>c(E,!0)))})};s.status&&(s.status.fetchDispatched=!0);let f=new Promise(p).then(c,u),m=Object.assign(f,{__abortController:o,__staleWhileFetching:n,__returned:void 0});return r===void 0?(this.set(e,m,{...l.options,status:void 0}),r=this.#h.get(e)):this.#s[r]=m,m}#c(e){if(!this.#A)return!1;let r=e;return!!r&&r instanceof Promise&&r.hasOwnProperty("__staleWhileFetching")&&r.__abortController instanceof Tt}async fetch(e,r={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:l=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:h=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:p=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:m=this.allowStaleOnFetchAbort,context:g,forceRefresh:w=!1,status:S,signal:E}=r;if(!this.#A)return S&&(S.fetch="get"),this.get(e,{allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:n,status:S});let y={allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:n,ttl:o,noDisposeOnSet:a,size:l,sizeCalculation:c,noUpdateTTL:u,noDeleteOnFetchRejection:h,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:m,ignoreFetchAbort:f,status:S,signal:E},b=this.#h.get(e);if(b===void 0){S&&(S.fetch="miss");let T=this.#$(e,b,y,g);return T.__returned=T}else{let T=this.#s[b];if(this.#c(T)){let Re=s&&T.__staleWhileFetching!==void 0;return S&&(S.fetch="inflight",Re&&(S.returnedStale=!0)),Re?T.__staleWhileFetching:T.__returned=T}let pe=this.#v(b);if(!w&&!pe)return S&&(S.fetch="hit"),this.#N(b),i&&this.#C(b),S&&this.#I(S,b),T;let Ce=this.#$(e,b,y,g),ke=Ce.__staleWhileFetching!==void 0&&s;return S&&(S.fetch=pe?"stale":"refresh",ke&&pe&&(S.returnedStale=!0)),ke?Ce.__staleWhileFetching:Ce.__returned=Ce}}async forceFetch(e,r={}){let s=await this.fetch(e,r);if(s===void 0)throw new Error("fetch() returned undefined");return s}memo(e,r={}){let s=this.#S;if(!s)throw new Error("no memoMethod provided to constructor");let{context:i,forceRefresh:n,...o}=r,a=this.get(e,o);if(!n&&a!==void 0)return a;let l=s(e,a,{options:o,context:i});return this.set(e,l,o),l}get(e,r={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:o}=r,a=this.#h.get(e);if(a!==void 0){let l=this.#s[a],c=this.#c(l);return o&&this.#I(o,a),this.#v(a)?(o&&(o.get="stale"),c?(o&&s&&l.__staleWhileFetching!==void 0&&(o.returnedStale=!0),s?l.__staleWhileFetching:void 0):(n||this.#R(e,"expire"),o&&s&&(o.returnedStale=!0),s?l:void 0)):(o&&(o.get="hit"),c?l.__staleWhileFetching:(this.#N(a),i&&this.#C(a),l))}else o&&(o.get="miss")}#B(e,r){this.#_[r]=e,this.#p[e]=r}#N(e){e!==this.#f&&(e===this.#w?this.#w=this.#p[e]:this.#B(this.#_[e],this.#p[e]),this.#B(this.#f,e),this.#f=e)}delete(e){return this.#R(e,"delete")}#R(e,r){let s=!1;if(this.#a!==0){let i=this.#h.get(e);if(i!==void 0)if(this.#E?.[i]&&(clearTimeout(this.#E?.[i]),this.#E[i]=void 0),s=!0,this.#a===1)this.#K(r);else{this.#U(i);let n=this.#s[i];if(this.#c(n)?n.__abortController.abort(new Error("deleted")):(this.#b||this.#t)&&(this.#b&&this.#n?.(n,e,r),this.#t&&this.#m?.push([n,e,r])),this.#h.delete(e),this.#l[i]=void 0,this.#s[i]=void 0,i===this.#f)this.#f=this.#_[i];else if(i===this.#w)this.#w=this.#p[i];else{let o=this.#_[i];this.#p[o]=this.#p[i];let a=this.#p[i];this.#_[a]=this.#_[i]}this.#a--,this.#k.push(i)}}if(this.#t&&this.#m?.length){let i=this.#m,n;for(;n=i?.shift();)this.#o?.(...n)}return s}clear(){return this.#K("delete")}#K(e){for(let r of this.#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.#b&&this.#n?.(s,i,e),this.#t&&this.#m?.push([s,i,e])}}if(this.#h.clear(),this.#s.fill(void 0),this.#l.fill(void 0),this.#g&&this.#M){this.#g.fill(0),this.#M.fill(0);for(let r of this.#E??[])r!==void 0&&clearTimeout(r);this.#E?.fill(void 0)}if(this.#T&&this.#T.fill(0),this.#w=0,this.#f=0,this.#k.length=0,this.#d=0,this.#a=0,this.#t&&this.#m){let r=this.#m,s;for(;s=r?.shift();)this.#o?.(...s)}}},ns=typeof process=="object"&&process?process:{stdout:null,stderr:null},Vo=t=>!!t&&typeof t=="object"&&(t instanceof Mt||t instanceof yr.default||Qo(t)||Zo(t)),Qo=t=>!!t&&typeof t=="object"&&t instanceof Ct.EventEmitter&&typeof t.pipe=="function"&&t.pipe!==yr.default.Writable.prototype.pipe,Zo=t=>!!t&&typeof t=="object"&&t instanceof Ct.EventEmitter&&typeof t.write=="function"&&typeof t.end=="function",ne=Symbol("EOF"),oe=Symbol("maybeEmitEnd"),fe=Symbol("emittedEnd"),ft=Symbol("emittingEnd"),Ge=Symbol("emittedError"),mt=Symbol("closed"),os=Symbol("read"),gt=Symbol("flush"),as=Symbol("flushChunk"),G=Symbol("encoding"),Pe=Symbol("decoder"),A=Symbol("flowing"),Ke=Symbol("paused"),Ie=Symbol("resume"),C=Symbol("buffer"),D=Symbol("pipes"),k=Symbol("bufferLength"),ur=Symbol("bufferPush"),St=Symbol("bufferShift"),O=Symbol("objectMode"),M=Symbol("destroyed"),hr=Symbol("error"),dr=Symbol("emitData"),ls=Symbol("emitEnd"),pr=Symbol("emitEnd2"),q=Symbol("async"),fr=Symbol("abort"),Et=Symbol("aborted"),Ye=Symbol("signal"),ye=Symbol("dataListeners"),U=Symbol("discarded"),ze=t=>Promise.resolve().then(t),ea=t=>t(),ta=t=>t==="end"||t==="finish"||t==="prefinish",ra=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,sa=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Ws=class{src;dest;opts;ondrain;constructor(t,e,r){this.src=t,this.dest=e,this.opts=r,this.ondrain=()=>t[Ie](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},ia=class extends Ws{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,r){super(t,e,r),this.proxyErrors=s=>this.dest.emit("error",s),t.on("error",this.proxyErrors)}},na=t=>!!t.objectMode,oa=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Mt=class extends Ct.EventEmitter{[A]=!1;[Ke]=!1;[D]=[];[C]=[];[O];[G];[q];[Pe];[ne]=!1;[fe]=!1;[ft]=!1;[mt]=!1;[Ge]=null;[k]=0;[M]=!1;[Ye];[Et]=!1;[ye]=0;[U]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");na(e)?(this[O]=!0,this[G]=null):oa(e)?(this[G]=e.encoding,this[O]=!1):(this[O]=!1,this[G]=null),this[q]=!!e.async,this[Pe]=this[G]?new Fs.StringDecoder(this[G]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[C]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[D]});let{signal:r}=e;r&&(this[Ye]=r,r.aborted?this[fr]():r.addEventListener("abort",()=>this[fr]()))}get bufferLength(){return this[k]}get encoding(){return this[G]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[O]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[q]}set async(t){this[q]=this[q]||!!t}[fr](){this[Et]=!0,this.emit("abort",this[Ye]?.reason),this.destroy(this[Ye]?.reason)}get aborted(){return this[Et]}set aborted(t){}write(t,e,r){if(this[Et])return!1;if(this[ne])throw new Error("write after end");if(this[M])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(r=e,e="utf8"),e||(e="utf8");let s=this[q]?ze:ea;if(!this[O]&&!Buffer.isBuffer(t)){if(sa(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(ra(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[O]?(this[A]&&this[k]!==0&&this[gt](!0),this[A]?this.emit("data",t):this[ur](t),this[k]!==0&&this.emit("readable"),r&&s(r),this[A]):t.length?(typeof t=="string"&&!(e===this[G]&&!this[Pe]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[G]&&(t=this[Pe].write(t)),this[A]&&this[k]!==0&&this[gt](!0),this[A]?this.emit("data",t):this[ur](t),this[k]!==0&&this.emit("readable"),r&&s(r),this[A]):(this[k]!==0&&this.emit("readable"),r&&s(r),this[A])}read(t){if(this[M])return null;if(this[U]=!1,this[k]===0||t===0||t&&t>this[k])return this[oe](),null;this[O]&&(t=null),this[C].length>1&&!this[O]&&(this[C]=[this[G]?this[C].join(""):Buffer.concat(this[C],this[k])]);let e=this[os](t||null,this[C][0]);return this[oe](),e}[os](t,e){if(this[O])this[St]();else{let r=e;t===r.length||t===null?this[St]():typeof r=="string"?(this[C][0]=r.slice(t),e=r.slice(0,t),this[k]-=t):(this[C][0]=r.subarray(t),e=r.subarray(0,t),this[k]-=t)}return this.emit("data",e),!this[C].length&&!this[ne]&&this.emit("drain"),e}end(t,e,r){return typeof t=="function"&&(r=t,t=void 0),typeof e=="function"&&(r=e,e="utf8"),t!==void 0&&this.write(t,e),r&&this.once("end",r),this[ne]=!0,this.writable=!1,(this[A]||!this[Ke])&&this[oe](),this}[Ie](){this[M]||(!this[ye]&&!this[D].length&&(this[U]=!0),this[Ke]=!1,this[A]=!0,this.emit("resume"),this[C].length?this[gt]():this[ne]?this[oe]():this.emit("drain"))}resume(){return this[Ie]()}pause(){this[A]=!1,this[Ke]=!0,this[U]=!1}get destroyed(){return this[M]}get flowing(){return this[A]}get paused(){return this[Ke]}[ur](t){this[O]?this[k]+=1:this[k]+=t.length,this[C].push(t)}[St](){return this[O]?this[k]-=1:this[k]-=this[C][0].length,this[C].shift()}[gt](t=!1){do;while(this[as](this[St]())&&this[C].length);!t&&!this[C].length&&!this[ne]&&this.emit("drain")}[as](t){return this.emit("data",t),this[A]}pipe(t,e){if(this[M])return t;this[U]=!1;let r=this[fe];return e=e||{},t===ns.stdout||t===ns.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[D].push(e.proxyErrors?new ia(this,t,e):new Ws(this,t,e)),this[q]?ze(()=>this[Ie]()):this[Ie]()),t}unpipe(t){let e=this[D].find(r=>r.dest===t);e&&(this[D].length===1?(this[A]&&this[ye]===0&&(this[A]=!1),this[D]=[]):this[D].splice(this[D].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let r=super.on(t,e);if(t==="data")this[U]=!1,this[ye]++,!this[D].length&&!this[A]&&this[Ie]();else if(t==="readable"&&this[k]!==0)super.emit("readable");else if(ta(t)&&this[fe])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[Ge]){let s=e;this[q]?ze(()=>s.call(this,this[Ge])):s.call(this,this[Ge])}return r}removeListener(t,e){return this.off(t,e)}off(t,e){let r=super.off(t,e);return t==="data"&&(this[ye]=this.listeners("data").length,this[ye]===0&&!this[U]&&!this[D].length&&(this[A]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[ye]=0,!this[U]&&!this[D].length&&(this[A]=!1)),e}get emittedEnd(){return this[fe]}[oe](){!this[ft]&&!this[fe]&&!this[M]&&this[C].length===0&&this[ne]&&(this[ft]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[mt]&&this.emit("close"),this[ft]=!1)}emit(t,...e){let r=e[0];if(t!=="error"&&t!=="close"&&t!==M&&this[M])return!1;if(t==="data")return!this[O]&&!r?!1:this[q]?(ze(()=>this[dr](r)),!0):this[dr](r);if(t==="end")return this[ls]();if(t==="close"){if(this[mt]=!0,!this[fe]&&!this[M])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(t==="error"){this[Ge]=r,super.emit(hr,r);let i=!this[Ye]||this.listeners("error").length?super.emit("error",r):!1;return this[oe](),i}else if(t==="resume"){let i=super.emit("resume");return this[oe](),i}else if(t==="finish"||t==="prefinish"){let i=super.emit(t);return this.removeAllListeners(t),i}let s=super.emit(t,...e);return this[oe](),s}[dr](t){for(let r of this[D])r.dest.write(t)===!1&&this.pause();let e=this[U]?!1:super.emit("data",t);return this[oe](),e}[ls](){return this[fe]?!1:(this[fe]=!0,this.readable=!1,this[q]?(ze(()=>this[pr]()),!0):this[pr]())}[pr](){if(this[Pe]){let e=this[Pe].end();if(e){for(let r of this[D])r.dest.write(e);this[U]||super.emit("data",e)}}for(let e of this[D])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[O]||(t.dataLength=0);let e=this.promise();return this.on("data",r=>{t.push(r),this[O]||(t.dataLength+=r.length)}),await e,t}async concat(){if(this[O])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[G]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(M,()=>e(new Error("stream destroyed"))),this.on("error",r=>e(r)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[U]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let r=this.read();if(r!==null)return Promise.resolve({done:!1,value:r});if(this[ne])return e();let s,i,n=c=>{this.off("data",o),this.off("end",a),this.off(M,l),e(),i(c)},o=c=>{this.off("error",n),this.off("end",a),this.off(M,l),this.pause(),s({value:c,done:!!this[ne]})},a=()=>{this.off("error",n),this.off("data",o),this.off(M,l),e(),s({done:!0,value:void 0})},l=()=>n(new Error("stream destroyed"));return new Promise((c,u)=>{i=u,s=c,this.once(M,l),this.once("error",n),this.once("end",a),this.once("data",o)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[U]=!1;let t=!1,e=()=>(this.pause(),this.off(hr,e),this.off(M,e),this.off("end",e),t=!0,{done:!0,value:void 0}),r=()=>{if(t)return e();let s=this.read();return s===null?e():{done:!1,value:s}};return this.once("end",e),this.once(hr,e),this.once(M,e),{next:r,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[M])return t?this.emit("error",t):this.emit(M),this;this[M]=!0,this[U]=!0,this[C].length=0,this[k]=0;let e=this;return typeof e.close=="function"&&!this[mt]&&e.close(),t?this.emit("error",t):this.emit(M),this}static get isStream(){return Vo}},aa=Q.realpathSync.native,Ve={lstatSync:Q.lstatSync,readdir:Q.readdir,readdirSync:Q.readdirSync,readlinkSync:Q.readlinkSync,realpathSync:aa,promises:{lstat:Se.lstat,readdir:Se.readdir,readlink:Se.readlink,realpath:Se.realpath}},Hs=t=>!t||t===Ve||t===qo?Ve:{...Ve,...t,promises:{...Ve.promises,...t.promises||{}}},js=/^\\\\\?\\([a-z]:)\\?$/i,la=t=>t.replace(/\//g,"\\").replace(js,"$1\\"),ca=/[\\\/]/,j=0,$s=1,Bs=2,V=4,Gs=6,Ks=8,_e=10,Ys=12,H=15,Je=~H,mr=16,cs=32,Qe=64,K=128,wt=256,bt=512,us=Qe|K|bt,ua=1023,gr=t=>t.isFile()?Ks:t.isDirectory()?V:t.isSymbolicLink()?_e:t.isCharacterDevice()?Bs:t.isBlockDevice()?Gs:t.isSocket()?Ys:t.isFIFO()?$s:j,hs=new At({max:2**12}),Ze=t=>{let e=hs.get(t);if(e)return e;let r=t.normalize("NFKD");return hs.set(t,r),r},ds=new At({max:2**12}),yt=t=>{let e=ds.get(t);if(e)return e;let r=Ze(t.toLowerCase());return ds.set(t,r),r},ps=class extends At{constructor(){super({max:256})}},ha=class extends At{constructor(t=16*1024){super({maxSize:t,sizeCalculation:e=>e.length+1})}},zs=Symbol("PathScurry setAsCwd"),L=class{name;root;roots;parent;nocase;isCWD=!1;#e;#r;get dev(){return this.#r}#n;get mode(){return this.#n}#i;get nlink(){return this.#i}#o;get uid(){return this.#o}#y;get gid(){return this.#y}#S;get rdev(){return this.#S}#u;get blksize(){return this.#u}#a;get ino(){return this.#a}#d;get size(){return this.#d}#h;get blocks(){return this.#h}#l;get atimeMs(){return this.#l}#s;get mtimeMs(){return this.#s}#p;get ctimeMs(){return this.#p}#_;get birthtimeMs(){return this.#_}#w;get atime(){return this.#w}#f;get mtime(){return this.#f}#k;get ctime(){return this.#k}#m;get birthtime(){return this.#m}#T;#M;#g;#E;#b;#A;#t;#x;#P;#C;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(t,e=j,r,s,i,n,o){this.name=t,this.#T=i?yt(t):Ze(t),this.#t=e&ua,this.nocase=i,this.roots=s,this.root=r||this,this.#x=n,this.#g=o.fullpath,this.#b=o.relative,this.#A=o.relativePosix,this.parent=o.parent,this.parent?this.#e=this.parent.#e:this.#e=Hs(o.fs)}depth(){return this.#M!==void 0?this.#M:this.parent?this.#M=this.parent.depth()+1:this.#M=0}childrenCache(){return this.#x}resolve(t){if(!t)return this;let e=this.getRootString(t),r=t.substring(e.length).split(this.splitSep);return e?this.getRoot(e).#I(r):this.#I(r)}#I(t){let e=this;for(let r of t)e=e.child(r);return e}children(){let t=this.#x.get(this);if(t)return t;let e=Object.assign([],{provisional:0});return this.#x.set(this,e),this.#t&=~mr,e}child(t,e){if(t===""||t===".")return this;if(t==="..")return this.parent||this;let r=this.children(),s=this.nocase?yt(t):Ze(t);for(let a of r)if(a.#T===s)return a;let i=this.parent?this.sep:"",n=this.#g?this.#g+i+t:void 0,o=this.newChild(t,j,{...e,parent:this,fullpath:n});return this.canReaddir()||(o.#t|=K),r.push(o),o}relative(){if(this.isCWD)return"";if(this.#b!==void 0)return this.#b;let t=this.name,e=this.parent;if(!e)return this.#b=this.name;let r=e.relative();return r+(!r||!e.parent?"":this.sep)+t}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#A!==void 0)return this.#A;let t=this.name,e=this.parent;if(!e)return this.#A=this.fullpathPosix();let r=e.relativePosix();return r+(!r||!e.parent?"":"/")+t}fullpath(){if(this.#g!==void 0)return this.#g;let t=this.name,e=this.parent;if(!e)return this.#g=this.name;let r=e.fullpath()+(e.parent?this.sep:"")+t;return this.#g=r}fullpathPosix(){if(this.#E!==void 0)return this.#E;if(this.sep==="/")return this.#E=this.fullpath();if(!this.parent){let s=this.fullpath().replace(/\\/g,"/");return/^[a-z]:\//i.test(s)?this.#E=`//?/${s}`:this.#E=s}let t=this.parent,e=t.fullpathPosix(),r=e+(!e||!t.parent?"":"/")+this.name;return this.#E=r}isUnknown(){return(this.#t&H)===j}isType(t){return this[`is${t}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return(this.#t&H)===Ks}isDirectory(){return(this.#t&H)===V}isCharacterDevice(){return(this.#t&H)===Bs}isBlockDevice(){return(this.#t&H)===Gs}isFIFO(){return(this.#t&H)===$s}isSocket(){return(this.#t&H)===Ys}isSymbolicLink(){return(this.#t&_e)===_e}lstatCached(){return this.#t&cs?this:void 0}readlinkCached(){return this.#P}realpathCached(){return this.#C}readdirCached(){let t=this.children();return t.slice(0,t.provisional)}canReadlink(){if(this.#P)return!0;if(!this.parent)return!1;let t=this.#t&H;return!(t!==j&&t!==_e||this.#t&wt||this.#t&K)}calledReaddir(){return!!(this.#t&mr)}isENOENT(){return!!(this.#t&K)}isNamed(t){return this.nocase?this.#T===yt(t):this.#T===Ze(t)}async readlink(){let t=this.#P;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=await this.#e.promises.readlink(this.fullpath()),r=(await this.parent.realpath())?.resolve(e);if(r)return this.#P=r}catch(e){this.#D(e.code);return}}readlinkSync(){let t=this.#P;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=this.#e.readlinkSync(this.fullpath()),r=this.parent.realpathSync()?.resolve(e);if(r)return this.#P=r}catch(e){this.#D(e.code);return}}#F(t){this.#t|=mr;for(let e=t.provisional;e<t.length;e++){let r=t[e];r&&r.#v()}}#v(){this.#t&K||(this.#t=(this.#t|K)&Je,this.#G())}#G(){let t=this.children();t.provisional=0;for(let e of t)e.#v()}#U(){this.#t|=bt,this.#L()}#L(){if(this.#t&Qe)return;let t=this.#t;(t&H)===V&&(t&=Je),this.#t=t|Qe,this.#G()}#W(t=""){t==="ENOTDIR"||t==="EPERM"?this.#L():t==="ENOENT"?this.#v():this.children().provisional=0}#O(t=""){t==="ENOTDIR"?this.parent.#L():t==="ENOENT"&&this.#v()}#D(t=""){let e=this.#t;e|=wt,t==="ENOENT"&&(e|=K),(t==="EINVAL"||t==="UNKNOWN")&&(e&=Je),this.#t=e,t==="ENOTDIR"&&this.parent&&this.parent.#L()}#H(t,e){return this.#$(t,e)||this.#j(t,e)}#j(t,e){let r=gr(t),s=this.newChild(t.name,r,{parent:this}),i=s.#t&H;return i!==V&&i!==_e&&i!==j&&(s.#t|=Qe),e.unshift(s),e.provisional++,s}#$(t,e){for(let r=e.provisional;r<e.length;r++){let s=e[r];if((this.nocase?yt(t.name):Ze(t.name))===s.#T)return this.#c(t,s,r,e)}}#c(t,e,r,s){let i=e.name;return e.#t=e.#t&Je|gr(t),i!==t.name&&(e.name=t.name),r!==s.provisional&&(r===s.length-1?s.pop():s.splice(r,1),s.unshift(e)),s.provisional++,e}async lstat(){if((this.#t&K)===0)try{return this.#B(await this.#e.promises.lstat(this.fullpath())),this}catch(t){this.#O(t.code)}}lstatSync(){if((this.#t&K)===0)try{return this.#B(this.#e.lstatSync(this.fullpath())),this}catch(t){this.#O(t.code)}}#B(t){let{atime:e,atimeMs:r,birthtime:s,birthtimeMs:i,blksize:n,blocks:o,ctime:a,ctimeMs:l,dev:c,gid:u,ino:h,mode:p,mtime:f,mtimeMs:m,nlink:g,rdev:w,size:S,uid:E}=t;this.#w=e,this.#l=r,this.#m=s,this.#_=i,this.#u=n,this.#h=o,this.#k=a,this.#p=l,this.#r=c,this.#y=u,this.#a=h,this.#n=p,this.#f=f,this.#s=m,this.#i=g,this.#S=w,this.#d=S,this.#o=E;let y=gr(t);this.#t=this.#t&Je|y|cs,y!==j&&y!==V&&y!==_e&&(this.#t|=Qe)}#N=[];#R=!1;#K(t){this.#R=!1;let e=this.#N.slice();this.#N.length=0,e.forEach(r=>r(null,t))}readdirCB(t,e=!1){if(!this.canReaddir()){e?t(null,[]):queueMicrotask(()=>t(null,[]));return}let r=this.children();if(this.calledReaddir()){let i=r.slice(0,r.provisional);e?t(null,i):queueMicrotask(()=>t(null,i));return}if(this.#N.push(t),this.#R)return;this.#R=!0;let s=this.fullpath();this.#e.readdir(s,{withFileTypes:!0},(i,n)=>{if(i)this.#W(i.code),r.provisional=0;else{for(let o of n)this.#H(o,r);this.#F(r)}this.#K(r.slice(0,r.provisional))})}#Y;async readdir(){if(!this.canReaddir())return[];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();if(this.#Y)await this.#Y;else{let r=()=>{};this.#Y=new Promise(s=>r=s);try{for(let s of await this.#e.promises.readdir(e,{withFileTypes:!0}))this.#H(s,t);this.#F(t)}catch(s){this.#W(s.code),t.provisional=0}this.#Y=void 0,r()}return t.slice(0,t.provisional)}readdirSync(){if(!this.canReaddir())return[];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();try{for(let r of this.#e.readdirSync(e,{withFileTypes:!0}))this.#H(r,t);this.#F(t)}catch(r){this.#W(r.code),t.provisional=0}return t.slice(0,t.provisional)}canReaddir(){if(this.#t&us)return!1;let t=H&this.#t;return t===j||t===V||t===_e}shouldWalk(t,e){return(this.#t&V)===V&&!(this.#t&us)&&!t.has(this)&&(!e||e(this))}async realpath(){if(this.#C)return this.#C;if(!((bt|wt|K)&this.#t))try{let t=await this.#e.promises.realpath(this.fullpath());return this.#C=this.resolve(t)}catch{this.#U()}}realpathSync(){if(this.#C)return this.#C;if(!((bt|wt|K)&this.#t))try{let t=this.#e.realpathSync(this.fullpath());return this.#C=this.resolve(t)}catch{this.#U()}}[zs](t){if(t===this)return;t.isCWD=!1,this.isCWD=!0;let e=new Set([]),r=[],s=this;for(;s&&s.parent;)e.add(s),s.#b=r.join(this.sep),s.#A=r.join("/"),s=s.parent,r.push("..");for(s=t;s&&s.parent&&!e.has(s);)s.#b=void 0,s.#A=void 0,s=s.parent}},Js=class Xs extends L{sep="\\";splitSep=ca;constructor(e,r=j,s,i,n,o,a){super(e,r,s,i,n,o,a)}newChild(e,r=j,s={}){return new Xs(e,r,this.root,this.roots,this.nocase,this.childrenCache(),s)}getRootString(e){return Le.win32.parse(e).root}getRoot(e){if(e=la(e.toUpperCase()),e===this.root.name)return this.root;for(let[r,s]of Object.entries(this.roots))if(this.sameRoot(e,r))return this.roots[e]=s;return this.roots[e]=new _r(e,this).root}sameRoot(e,r=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(js,"$1\\"),e===r}},qs=class Vs extends L{splitSep="/";sep="/";constructor(e,r=j,s,i,n,o,a){super(e,r,s,i,n,o,a)}getRootString(e){return e.startsWith("/")?"/":""}getRoot(e){return this.root}newChild(e,r=j,s={}){return new Vs(e,r,this.root,this.roots,this.nocase,this.childrenCache(),s)}},Qs=class{root;rootPath;roots;cwd;#e;#r;#n;nocase;#i;constructor(t=process.cwd(),e,r,{nocase:s,childrenCacheSize:i=16*1024,fs:n=Ve}={}){this.#i=Hs(n),(t instanceof URL||t.startsWith("file://"))&&(t=(0,Us.fileURLToPath)(t));let o=e.resolve(t);this.roots=Object.create(null),this.rootPath=this.parseRootPath(o),this.#e=new ps,this.#r=new ps,this.#n=new ha(i);let a=o.substring(this.rootPath.length).split(r);if(a.length===1&&!a[0]&&a.pop(),s===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=s,this.root=this.newRoot(this.#i),this.roots[this.rootPath]=this.root;let l=this.root,c=a.length-1,u=e.sep,h=this.rootPath,p=!1;for(let f of a){let m=c--;l=l.child(f,{relative:new Array(m).fill("..").join(u),relativePosix:new Array(m).fill("..").join("/"),fullpath:h+=(p?"":u)+f}),p=!0}this.cwd=l}depth(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.depth()}childrenCache(){return this.#n}resolve(...t){let e="";for(let i=t.length-1;i>=0;i--){let n=t[i];if(!(!n||n===".")&&(e=e?`${n}/${e}`:n,this.isAbsolute(n)))break}let r=this.#e.get(e);if(r!==void 0)return r;let s=this.cwd.resolve(e).fullpath();return this.#e.set(e,s),s}resolvePosix(...t){let e="";for(let i=t.length-1;i>=0;i--){let n=t[i];if(!(!n||n===".")&&(e=e?`${n}/${e}`:n,this.isAbsolute(n)))break}let r=this.#r.get(e);if(r!==void 0)return r;let s=this.cwd.resolve(e).fullpathPosix();return this.#r.set(e,s),s}relative(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relative()}relativePosix(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relativePosix()}basename(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.name}dirname(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),(t.parent||t).fullpath()}async readdir(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r}=e;if(t.canReaddir()){let s=await t.readdir();return r?s:s.map(i=>i.name)}else return[]}readdirSync(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0}=e;return t.canReaddir()?r?t.readdirSync():t.readdirSync().map(s=>s.name):[]}async lstat(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstat()}lstatSync(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstatSync()}async readlink(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t.withFileTypes,t=this.cwd);let r=await t.readlink();return e?r:r?.fullpath()}readlinkSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t.withFileTypes,t=this.cwd);let r=t.readlinkSync();return e?r:r?.fullpath()}async realpath(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t.withFileTypes,t=this.cwd);let r=await t.realpath();return e?r:r?.fullpath()}realpathSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t.withFileTypes,t=this.cwd);let r=t.realpathSync();return e?r:r?.fullpath()}async walk(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=e,o=[];(!i||i(t))&&o.push(r?t:t.fullpath());let a=new Set,l=(u,h)=>{a.add(u),u.readdirCB((p,f)=>{if(p)return h(p);let m=f.length;if(!m)return h();let g=()=>{--m===0&&h()};for(let w of f)(!i||i(w))&&o.push(r?w:w.fullpath()),s&&w.isSymbolicLink()?w.realpath().then(S=>S?.isUnknown()?S.lstat():S).then(S=>S?.shouldWalk(a,n)?l(S,g):g()):w.shouldWalk(a,n)?l(w,g):g()},!0)},c=t;return new Promise((u,h)=>{l(c,p=>{if(p)return h(p);u(o)})})}walkSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=e,o=[];(!i||i(t))&&o.push(r?t:t.fullpath());let a=new Set([t]);for(let l of a){let c=l.readdirSync();for(let u of c){(!i||i(u))&&o.push(r?u:u.fullpath());let h=u;if(u.isSymbolicLink()){if(!(s&&(h=u.realpathSync())))continue;h.isUnknown()&&h.lstatSync()}h.shouldWalk(a,n)&&a.add(h)}}return o}[Symbol.asyncIterator](){return this.iterate()}iterate(t=this.cwd,e={}){return typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd),this.stream(t,e)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=e;(!i||i(t))&&(yield r?t:t.fullpath());let o=new Set([t]);for(let a of o){let l=a.readdirSync();for(let c of l){(!i||i(c))&&(yield r?c:c.fullpath());let u=c;if(c.isSymbolicLink()){if(!(s&&(u=c.realpathSync())))continue;u.isUnknown()&&u.lstatSync()}u.shouldWalk(o,n)&&o.add(u)}}}stream(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=e,o=new Mt({objectMode:!0});(!i||i(t))&&o.write(r?t:t.fullpath());let a=new Set,l=[t],c=0,u=()=>{let h=!1;for(;!h;){let p=l.shift();if(!p){c===0&&o.end();return}c++,a.add(p);let f=(g,w,S=!1)=>{if(g)return o.emit("error",g);if(s&&!S){let E=[];for(let y of w)y.isSymbolicLink()&&E.push(y.realpath().then(b=>b?.isUnknown()?b.lstat():b));if(E.length){Promise.all(E).then(()=>f(null,w,!0));return}}for(let E of w)E&&(!i||i(E))&&(o.write(r?E:E.fullpath())||(h=!0));c--;for(let E of w){let y=E.realpathCached()||E;y.shouldWalk(a,n)&&l.push(y)}h&&!o.flowing?o.once("drain",u):m||u()},m=!0;p.readdirCB(f,!0),m=!1}};return u(),o}streamSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=e,o=new Mt({objectMode:!0}),a=new Set;(!i||i(t))&&o.write(r?t:t.fullpath());let l=[t],c=0,u=()=>{let h=!1;for(;!h;){let p=l.shift();if(!p){c===0&&o.end();return}c++,a.add(p);let f=p.readdirSync();for(let m of f)(!i||i(m))&&(o.write(r?m:m.fullpath())||(h=!0));c--;for(let m of f){let g=m;if(m.isSymbolicLink()){if(!(s&&(g=m.realpathSync())))continue;g.isUnknown()&&g.lstatSync()}g.shouldWalk(a,n)&&l.push(g)}}h&&!o.flowing&&o.once("drain",u)};return u(),o}chdir(t=this.cwd){let e=this.cwd;this.cwd=typeof t=="string"?this.cwd.resolve(t):t,this.cwd[zs](e)}},_r=class extends Qs{sep="\\";constructor(t=process.cwd(),e={}){let{nocase:r=!0}=e;super(t,Le.win32,"\\",{...e,nocase:r}),this.nocase=r;for(let s=this.cwd;s;s=s.parent)s.nocase=this.nocase}parseRootPath(t){return Le.win32.parse(t).root.toUpperCase()}newRoot(t){return new Js(this.rootPath,V,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")||t.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(t)}},br=class extends Qs{sep="/";constructor(t=process.cwd(),e={}){let{nocase:r=!1}=e;super(t,Le.posix,"/",{...e,nocase:r}),this.nocase=r}parseRootPath(t){return"/"}newRoot(t){return new qs(this.rootPath,V,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")}},Zs=class extends br{constructor(t=process.cwd(),e={}){let{nocase:r=!0}=e;super(t,{...e,nocase:r})}},ec=process.platform==="win32"?Js:qs,da=process.platform==="win32"?_r:process.platform==="darwin"?Zs:br,pa=t=>t.length>=1,fa=t=>t.length>=1,ma=Symbol.for("nodejs.util.inspect.custom"),ei=class ti{#e;#r;#n;length;#i;#o;#y;#S;#u;#a;#d=!0;constructor(e,r,s,i){if(!pa(e))throw new TypeError("empty pattern list");if(!fa(r))throw new TypeError("empty glob list");if(r.length!==e.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=e.length,s<0||s>=this.length)throw new TypeError("index out of range");if(this.#e=e,this.#r=r,this.#n=s,this.#i=i,this.#n===0){if(this.isUNC()){let[n,o,a,l,...c]=this.#e,[u,h,p,f,...m]=this.#r;c[0]===""&&(c.shift(),m.shift());let g=[n,o,a,l,""].join("/"),w=[u,h,p,f,""].join("/");this.#e=[g,...c],this.#r=[w,...m],this.length=this.#e.length}else if(this.isDrive()||this.isAbsolute()){let[n,...o]=this.#e,[a,...l]=this.#r;o[0]===""&&(o.shift(),l.shift());let c=n+"/",u=a+"/";this.#e=[c,...o],this.#r=[u,...l],this.length=this.#e.length}}}[ma](){return"Pattern <"+this.#r.slice(this.#n).join("/")+">"}pattern(){return this.#e[this.#n]}isString(){return typeof this.#e[this.#n]=="string"}isGlobstar(){return this.#e[this.#n]===P}isRegExp(){return this.#e[this.#n]instanceof RegExp}globString(){return this.#y=this.#y||(this.#n===0?this.isAbsolute()?this.#r[0]+this.#r.slice(1).join("/"):this.#r.join("/"):this.#r.slice(this.#n).join("/"))}hasMore(){return this.length>this.#n+1}rest(){return this.#o!==void 0?this.#o:this.hasMore()?(this.#o=new ti(this.#e,this.#r,this.#n+1,this.#i),this.#o.#a=this.#a,this.#o.#u=this.#u,this.#o.#S=this.#S,this.#o):this.#o=null}isUNC(){let e=this.#e;return this.#u!==void 0?this.#u:this.#u=this.#i==="win32"&&this.#n===0&&e[0]===""&&e[1]===""&&typeof e[2]=="string"&&!!e[2]&&typeof e[3]=="string"&&!!e[3]}isDrive(){let e=this.#e;return this.#S!==void 0?this.#S:this.#S=this.#i==="win32"&&this.#n===0&&this.length>1&&typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0])}isAbsolute(){let e=this.#e;return this.#a!==void 0?this.#a:this.#a=e[0]===""&&e.length>1||this.isDrive()||this.isUNC()}root(){let e=this.#e[0];return typeof e=="string"&&this.isAbsolute()&&this.#n===0?e:""}checkFollowGlobstar(){return!(this.#n===0||!this.isGlobstar()||!this.#d)}markFollowGlobstar(){return this.#n===0||!this.isGlobstar()||!this.#d?!1:(this.#d=!1,!0)}},ga=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",fs=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(t,{nobrace:e,nocase:r,noext:s,noglobstar:i,platform:n=ga}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=n,this.mmopts={dot:!0,nobrace:e,nocase:r,noext:s,noglobstar:i,optimizationLevel:2,platform:n,nocomment:!0,nonegate:!0};for(let o of t)this.add(o)}add(t){let e=new ge(t,this.mmopts);for(let r=0;r<e.set.length;r++){let s=e.set[r],i=e.globParts[r];if(!s||!i)throw new Error("invalid pattern object");for(;s[0]==="."&&i[0]===".";)s.shift(),i.shift();let n=new ei(s,i,0,this.platform),o=new ge(n.globString(),this.mmopts),a=i[i.length-1]==="**",l=n.isAbsolute();l?this.absolute.push(o):this.relative.push(o),a&&(l?this.absoluteChildren.push(o):this.relativeChildren.push(o))}}ignored(t){let e=t.fullpath(),r=`${e}/`,s=t.relative()||".",i=`${s}/`;for(let n of this.relative)if(n.match(s)||n.match(i))return!0;for(let n of this.absolute)if(n.match(e)||n.match(r))return!0;return!1}childrenIgnored(t){let e=t.fullpath()+"/",r=(t.relative()||".")+"/";for(let s of this.relativeChildren)if(s.match(r))return!0;for(let s of this.absoluteChildren)if(s.match(e))return!0;return!1}},Sa=class ri{store;constructor(e=new Map){this.store=e}copy(){return new ri(new Map(this.store))}hasWalked(e,r){return this.store.get(e.fullpath())?.has(r.globString())}storeWalked(e,r){let s=e.fullpath(),i=this.store.get(s);i?i.add(r.globString()):this.store.set(s,new Set([r.globString()]))}},Ea=class{store=new Map;add(t,e,r){let s=(e?2:0)|(r?1:0),i=this.store.get(t);this.store.set(t,i===void 0?s:s&i)}entries(){return[...this.store.entries()].map(([t,e])=>[t,!!(e&2),!!(e&1)])}},wa=class{store=new Map;add(t,e){if(!t.canReaddir())return;let r=this.store.get(t);r?r.find(s=>s.globString()===e.globString())||r.push(e):this.store.set(t,[e])}get(t){let e=this.store.get(t);if(!e)throw new Error("attempting to walk unknown path");return e}entries(){return this.keys().map(t=>[t,this.store.get(t)])}keys(){return[...this.store.keys()].filter(t=>t.canReaddir())}},ms=class si{hasWalkedCache;matches=new Ea;subwalks=new wa;patterns;follow;dot;opts;constructor(e,r){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=r?r.copy():new Sa}processPatterns(e,r){this.patterns=r;let s=r.map(i=>[e,i]);for(let[i,n]of s){this.hasWalkedCache.storeWalked(i,n);let o=n.root(),a=n.isAbsolute()&&this.opts.absolute!==!1;if(o){i=i.resolve(o==="/"&&this.opts.root!==void 0?this.opts.root:o);let h=n.rest();if(h)n=h;else{this.matches.add(i,!0,!1);continue}}if(i.isENOENT())continue;let l,c,u=!1;for(;typeof(l=n.pattern())=="string"&&(c=n.rest());)i=i.resolve(l),n=c,u=!0;if(l=n.pattern(),c=n.rest(),u){if(this.hasWalkedCache.hasWalked(i,n))continue;this.hasWalkedCache.storeWalked(i,n)}if(typeof l=="string"){let h=l===".."||l===""||l===".";this.matches.add(i.resolve(l),a,h);continue}else if(l===P){(!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 si(this.opts,this.hasWalkedCache)}filterEntries(e,r){let s=this.subwalks.get(e),i=this.child();for(let n of r)for(let o of s){let a=o.isAbsolute(),l=o.pattern(),c=o.rest();l===P?i.testGlobstar(n,o,c,a):l instanceof RegExp?i.testRegExp(n,l,c,a):i.testString(n,l,c,a)}return i}testGlobstar(e,r,s,i){if((this.dot||!e.name.startsWith("."))&&(r.hasMore()||this.matches.add(e,i,!1),e.canReaddir()&&(this.follow||!e.isSymbolicLink()?this.subwalks.add(e,r):e.isSymbolicLink()&&(s&&r.checkFollowGlobstar()?this.subwalks.add(e,s):r.markFollowGlobstar()&&this.subwalks.add(e,r)))),s){let n=s.pattern();if(typeof n=="string"&&n!==".."&&n!==""&&n!==".")this.testString(e,n,s.rest(),i);else if(n===".."){let o=e.parent||e;this.subwalks.add(o,s)}else n instanceof RegExp&&this.testRegExp(e,n,s.rest(),i)}}testRegExp(e,r,s,i){r.test(e.name)&&(s?this.subwalks.add(e,s):this.matches.add(e,i,!1))}testString(e,r,s,i){e.isNamed(r)&&(s?this.subwalks.add(e,s):this.matches.add(e,i,!1))}},ya=(t,e)=>typeof t=="string"?new fs([t],e):Array.isArray(t)?new fs(t,e):t,ii=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#e=[];#r;#n;signal;maxDepth;includeChildMatches;constructor(t,e,r){if(this.patterns=t,this.path=e,this.opts=r,this.#n=!r.posix&&r.platform==="win32"?"\\":"/",this.includeChildMatches=r.includeChildMatches!==!1,(r.ignore||!this.includeChildMatches)&&(this.#r=ya(r.ignore??[],r),!this.includeChildMatches&&typeof this.#r.add!="function")){let s="cannot ignore child matches, ignore lacks add() method.";throw new Error(s)}this.maxDepth=r.maxDepth||1/0,r.signal&&(this.signal=r.signal,this.signal.addEventListener("abort",()=>{this.#e.length=0}))}#i(t){return this.seen.has(t)||!!this.#r?.ignored?.(t)}#o(t){return!!this.#r?.childrenIgnored?.(t)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let t;for(;!this.paused&&(t=this.#e.shift());)t()}onResume(t){this.signal?.aborted||(this.paused?this.#e.push(t):t())}async matchCheck(t,e){if(e&&this.opts.nodir)return;let r;if(this.opts.realpath){if(r=t.realpathCached()||await t.realpath(),!r)return;t=r}let s=t.isUnknown()||this.opts.stat?await t.lstat():t;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let i=await s.realpath();i&&(i.isUnknown()||this.opts.stat)&&await i.lstat()}return this.matchCheckTest(s,e)}matchCheckTest(t,e){return t&&(this.maxDepth===1/0||t.depth()<=this.maxDepth)&&(!e||t.canReaddir())&&(!this.opts.nodir||!t.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!t.isSymbolicLink()||!t.realpathCached()?.isDirectory())&&!this.#i(t)?t:void 0}matchCheckSync(t,e){if(e&&this.opts.nodir)return;let r;if(this.opts.realpath){if(r=t.realpathCached()||t.realpathSync(),!r)return;t=r}let s=t.isUnknown()||this.opts.stat?t.lstatSync():t;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let i=s.realpathSync();i&&(i?.isUnknown()||this.opts.stat)&&i.lstatSync()}return this.matchCheckTest(s,e)}matchFinish(t,e){if(this.#i(t))return;if(!this.includeChildMatches&&this.#r?.add){let i=`${t.relativePosix()}/**`;this.#r.add(i)}let r=this.opts.absolute===void 0?e:this.opts.absolute;this.seen.add(t);let s=this.opts.mark&&t.isDirectory()?this.#n:"";if(this.opts.withFileTypes)this.matchEmit(t);else if(r){let i=this.opts.posix?t.fullpathPosix():t.fullpath();this.matchEmit(i+s)}else{let i=this.opts.posix?t.relativePosix():t.relative(),n=this.opts.dotRelative&&!i.startsWith(".."+this.#n)?"."+this.#n:"";this.matchEmit(i?n+i+s:"."+s)}}async match(t,e,r){let s=await this.matchCheck(t,r);s&&this.matchFinish(s,e)}matchSync(t,e,r){let s=this.matchCheckSync(t,r);s&&this.matchFinish(s,e)}walkCB(t,e,r){this.signal?.aborted&&r(),this.walkCB2(t,e,new ms(this.opts),r)}walkCB2(t,e,r,s){if(this.#o(t))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2(t,e,r,s));return}r.processPatterns(t,e);let i=1,n=()=>{--i===0&&s()};for(let[o,a,l]of r.matches.entries())this.#i(o)||(i++,this.match(o,a,l).then(()=>n()));for(let o of r.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;i++;let a=o.readdirCached();o.calledReaddir()?this.walkCB3(o,a,r,n):o.readdirCB((l,c)=>this.walkCB3(o,c,r,n),!0)}n()}walkCB3(t,e,r,s){r=r.filterEntries(t,e);let i=1,n=()=>{--i===0&&s()};for(let[o,a,l]of r.matches.entries())this.#i(o)||(i++,this.match(o,a,l).then(()=>n()));for(let[o,a]of r.subwalks.entries())i++,this.walkCB2(o,a,r.child(),n);n()}walkCBSync(t,e,r){this.signal?.aborted&&r(),this.walkCB2Sync(t,e,new ms(this.opts),r)}walkCB2Sync(t,e,r,s){if(this.#o(t))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2Sync(t,e,r,s));return}r.processPatterns(t,e);let i=1,n=()=>{--i===0&&s()};for(let[o,a,l]of r.matches.entries())this.#i(o)||this.matchSync(o,a,l);for(let o of r.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;i++;let a=o.readdirSync();this.walkCB3Sync(o,a,r,n)}n()}walkCB3Sync(t,e,r,s){r=r.filterEntries(t,e);let i=1,n=()=>{--i===0&&s()};for(let[o,a,l]of r.matches.entries())this.#i(o)||this.matchSync(o,a,l);for(let[o,a]of r.subwalks.entries())i++,this.walkCB2Sync(o,a,r.child(),n);n()}},gs=class extends ii{matches=new Set;constructor(t,e,r){super(t,e,r)}matchEmit(t){this.matches.add(t)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((t,e)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?e(this.signal.reason):t(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},Ss=class extends ii{results;constructor(t,e,r){super(t,e,r),this.results=new Mt({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(t){this.results.write(t),this.results.flowing||this.pause()}stream(){let t=this.path;return t.isUnknown()?t.lstat().then(()=>{this.walkCB(t,this.patterns,()=>this.results.end())}):this.walkCB(t,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}},_a=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",be=class{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(t,e){if(!e)throw new TypeError("glob options required");if(this.withFileTypes=!!e.withFileTypes,this.signal=e.signal,this.follow=!!e.follow,this.dot=!!e.dot,this.dotRelative=!!e.dotRelative,this.nodir=!!e.nodir,this.mark=!!e.mark,e.cwd?(e.cwd instanceof URL||e.cwd.startsWith("file://"))&&(e.cwd=(0,Ps.fileURLToPath)(e.cwd)):this.cwd="",this.cwd=e.cwd||"",this.root=e.root,this.magicalBraces=!!e.magicalBraces,this.nobrace=!!e.nobrace,this.noext=!!e.noext,this.realpath=!!e.realpath,this.absolute=e.absolute,this.includeChildMatches=e.includeChildMatches!==!1,this.noglobstar=!!e.noglobstar,this.matchBase=!!e.matchBase,this.maxDepth=typeof e.maxDepth=="number"?e.maxDepth:1/0,this.stat=!!e.stat,this.ignore=e.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof t=="string"&&(t=[t]),this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(t=t.map(a=>a.replace(/\\/g,"/"))),this.matchBase){if(e.noglobstar)throw new TypeError("base matching requires globstar");t=t.map(a=>a.includes("/")?a:`./**/${a}`)}if(this.pattern=t,this.platform=e.platform||_a,this.opts={...e,platform:this.platform},e.scurry){if(this.scurry=e.scurry,e.nocase!==void 0&&e.nocase!==e.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let a=e.platform==="win32"?_r:e.platform==="darwin"?Zs:e.platform?br:da;this.scurry=new a(this.cwd,{nocase:e.nocase,fs:e.fs})}this.nocase=this.scurry.nocase;let r=this.platform==="darwin"||this.platform==="win32",s={braceExpandMax:1e4,...e,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:r,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},i=this.pattern.map(a=>new ge(a,s)),[n,o]=i.reduce((a,l)=>(a[0].push(...l.set),a[1].push(...l.globParts),a),[[],[]]);this.patterns=n.map((a,l)=>{let c=o[l];if(!c)throw new Error("invalid pattern object");return new ei(a,c,0,this.platform)})}async walk(){return[...await new gs(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return[...new gs(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new Ss(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new Ss(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}},ba=(t,e={})=>{Array.isArray(t)||(t=[t]);for(let r of t)if(new ge(r,e).hasMagic())return!0;return!1};function kt(t,e={}){return new be(t,e).streamSync()}function ni(t,e={}){return new be(t,e).stream()}function et(t,e={}){return new be(t,e).walkSync()}async function Es(t,e={}){return new be(t,e).walk()}function Rt(t,e={}){return new be(t,e).iterateSync()}function oi(t,e={}){return new be(t,e).iterate()}var va=kt,Ta=Object.assign(ni,{sync:kt}),Ma=Rt,Aa=Object.assign(oi,{sync:Rt}),Ca=Object.assign(et,{stream:kt,iterate:Rt}),ws=Object.assign(Es,{glob:Es,globSync:et,sync:Ca,globStream:ni,stream:Ta,globStreamSync:kt,streamSync:va,globIterate:oi,iterate:Aa,globIterateSync:Rt,iterateSync:Ma,Glob:be,hasMagic:ba,escape:Cs,unescape:xe});ws.glob=ws;var ae=require("fs"),ai=require("path");function li(t){try{if(!(0,ae.existsSync)(t))return{offsets:{}};let e=(0,ae.readFileSync)(t,"utf-8"),r=JSON.parse(e);return r.offsets?r:{offsets:{}}}catch(e){return d.warn("TRANSCRIPT","Failed to load watch state, starting fresh",{statePath:t,error:e instanceof Error?e.message:String(e)}),{offsets:{}}}}function ci(t,e){try{let r=(0,ai.dirname)(t);(0,ae.existsSync)(r)||(0,ae.mkdirSync)(r,{recursive:!0}),(0,ae.writeFileSync)(t,JSON.stringify(e,null,2))}catch(r){d.warn("TRANSCRIPT","Failed to save watch state",{statePath:t,error:r instanceof Error?r.message:String(r)})}}var nt=X(require("path"),1);var Fe=X(require("path"),1),Y=require("fs");var ui=require("node:child_process");function Ot(t,e,r){return(0,ui.spawn)(t,e??[],{windowsHide:!0,...r})}var $={DEFAULT:3e5,HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,WORKER_STARTUP_WAIT:1e3,PRE_RESTART_SETTLE_DELAY:2e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5},Ee={SUCCESS:0,FAILURE:1,BLOCKING_ERROR:2,USER_MESSAGE_ONLY:3};function le(t){return process.platform==="win32"?Math.round(t*$.WINDOWS_MULTIPLIER):t}var Z=require("fs"),tt=require("path"),vr=require("os");var ee=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_API_TIMEOUT_MS:String(le($.API_REQUEST)),CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_GEMINI_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_GEMINI_MAX_TOKENS:"100000",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_OPENROUTER_MAX_TOKENS:"100000",CLAUDE_MEM_DATA_DIR:(0,tt.join)((0,vr.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,tt.join)((0,vr.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let r=this.get(e);return parseInt(r,10)}static getBool(e){let r=this.get(e);return r==="true"||r===!0}static applyEnvOverrides(e){let r={...e};for(let s of Object.keys(this.DEFAULTS))process.env[s]!==void 0&&(r[s]=process.env[s]);return r}static loadFromFile(e,r=!0){try{if(!(0,Z.existsSync)(e)){let a=this.getAllDefaults();try{let l=(0,tt.dirname)(e);(0,Z.existsSync)(l)||(0,Z.mkdirSync)(l,{recursive:!0}),(0,Z.writeFileSync)(e,JSON.stringify(a,null,2),"utf-8"),console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(l){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,l instanceof Error?l.message:String(l))}return r?this.applyEnvOverrides(a):a}let s=(0,Z.readFileSync)(e,"utf-8"),i=JSON.parse(s.replace(/^\uFEFF/,"")),n=i;if(i.env&&typeof i.env=="object"){n=i.env;try{(0,Z.writeFileSync)(e,JSON.stringify(n,null,2),"utf-8"),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(a){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,a instanceof Error?a.message:String(a))}}let o={...this.DEFAULTS};for(let a of Object.keys(this.DEFAULTS))n[a]!==void 0&&(o[a]=n[a]);return r?this.applyEnvOverrides(o):o}catch(s){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,s instanceof Error?s.message:String(s));let i=this.getAllDefaults();return r?this.applyEnvOverrides(i):i}}};var Dt=null;function ce(){return Dt!==null||(Dt=ee.loadFromFile(ct)),Dt}var ve=require("fs");var kr=require("child_process");var te=require("fs"),Ar=X(require("path"),1);var ka=["CLAUDECODE_","CLAUDE_CODE_"],Ra=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"]),Oa=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS"]);function Pt(t=process.env){let e={};for(let[r,s]of Object.entries(t))if(s!==void 0){if(Oa.has(r)){e[r]=s;continue}Ra.has(r)||ka.some(i=>r.startsWith(i))||(e[r]=s)}return e}var Da=5e3,Pa=1e3,Ia=R.supervisorRegistry();function ue(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;return r==="EPERM"?!0:(d.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return d.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function It(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(s=>!ue(s.pid)))return;await new Promise(s=>setTimeout(s,100))}}var xa=5e3,hi=new Map;function La(t){let e=hi.get(t);if(e&&Date.now()-e.capturedAtMs<xa)return e.token;let r=null;try{let s=(0,kr.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Pt(process.env),LC_ALL:"C",LANG:"C"}});if(s.status===0){let i=s.stdout.trim();r=i.length>0?i:null}}catch(s){d.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:s instanceof Error?s.message:String(s)}),r=null}return hi.set(t,{token:r,capturedAtMs:Date.now()}),r}function di(t){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux")try{let e=(0,te.readFileSync)(`/proc/${t}/stat`,"utf-8"),r=e.lastIndexOf(") ");if(r<0)return null;let i=e.slice(r+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(e){return d.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return La(t);try{let e=(0,kr.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Pt(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let r=e.stdout.trim();return r.length>0?r:null}catch(e){return d.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}}function Rr(t){if(!t||!ue(t.pid))return!1;if(!t.startToken)return!0;let e=di(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||d.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}var Cr=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=Ia){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,te.mkdirSync)(Ar.default.dirname(this.registryPath),{recursive:!0}),!(0,te.existsSync)(this.registryPath)){this.persist();return}try{let s=JSON.parse((0,te.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[i,n]of Object.entries(s))this.entries.set(i,n)}catch(r){r instanceof Error?d.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):d.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&d.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,r,s){this.initialize(),this.entries.set(e,r),s&&this.runtimeProcesses.set(e,s),this.persist()}unregister(e){this.initialize();let r=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),r?.type==="sdk"&&Mr()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let s=Date.parse(e.startedAt),i=Date.parse(r.startedAt);return(Number.isNaN(s)?0:s)-(Number.isNaN(i)?0:i)})}getBySession(e){let r=String(e);return this.getAll().filter(s=>s.sessionId!==void 0&&String(s.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}getByPid(e){return this.getAll().filter(r=>r.pid===e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[s,i]of this.entries)ue(i.pid)||(this.entries.delete(s),this.runtimeProcesses.delete(s),e+=1,i.type==="sdk"&&(r+=1));e>0&&this.persist();for(let s=0;s<r;s+=1)Mr();return e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let s=typeof e=="number"?e:Number(e)||void 0;d.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:s,pids:r.map(o=>o.pid)});let i=r.filter(o=>ue(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 It(i,Da);let n=i.filter(o=>ue(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()+Pa;for(;Date.now()<o&&n.filter(l=>ue(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 ${e}`,{sessionId:s,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,te.mkdirSync)(Ar.default.dirname(this.registryPath),{recursive:!0}),(0,te.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},Tr=null;function xt(){return Tr||(Tr=new Cr),Tr}var Na=[];function Mr(){let t=Na.shift();t&&t()}var fi=require("child_process"),Ne=require("fs"),mi=require("util");var Ua=(0,mi.promisify)(fi.execFile),Fa=R.workerPid();async function gi(t){let e=t.currentPid??process.pid,r=t.pidFilePath??Fa,s=t.registry.getAll(),i=[...s].filter(o=>o.pid!==e).sort((o,a)=>Date.parse(a.startedAt)-Date.parse(o.startedAt));for(let o of i){if(!ue(o.pid)){t.registry.unregister(o.id);continue}try{await pi(o,"SIGTERM")}catch(a){a instanceof Error?d.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:o.pid,pgid:o.pgid,type:o.type},a):d.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:o.pid,pgid:o.pgid,type:o.type,error:String(a)})}}await It(i,5e3);let n=i.filter(o=>ue(o.pid));for(let o of n)try{await pi(o,"SIGKILL")}catch(a){a instanceof Error?d.debug("SYSTEM","Failed to force kill child process",{pid:o.pid,pgid:o.pgid,type:o.type},a):d.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:o.pid,pgid:o.pgid,type:o.type,error:String(a)})}await It(n,1e3);for(let o of i)t.registry.unregister(o.id);for(let o of s.filter(a=>a.pid===e))t.registry.unregister(o.id);Wa(r,e),t.registry.pruneDeadEntries()}function Wa(t,e){if(!(0,Ne.existsSync)(t))return;let r=null;try{let s=JSON.parse((0,Ne.readFileSync)(t,"utf-8"));r=typeof s.pid=="number"?s.pid:null}catch(s){d.debug("SYSTEM","PID file unreadable during shutdown \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:s instanceof Error?s.message:String(s)});return}if(r!==e){d.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:r,currentPid:e});return}try{(0,Ne.rmSync)(t,{force:!0})}catch(s){s instanceof Error?d.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:t},s):d.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:t,error:String(s)})}}async function pi(t,e){let{pid:r,pgid:s}=t;if(process.platform!=="win32"){if(typeof s=="number")try{process.kill(-s,e);return}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}try{process.kill(r,e)}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}return}if(e==="SIGTERM"){try{process.kill(r,e)}catch(o){if(o instanceof Error&&o.code==="ESRCH")return;throw o}return}let i=await Ha();if(i){await new Promise((o,a)=>{i(r,e,l=>{if(!l){o();return}if(l.code==="ESRCH"){o();return}a(l)})});return}let n=["/PID",String(r),"/T"];e==="SIGKILL"&&n.push("/F"),await Ua("taskkill",n,{timeout:$.POWERSHELL_COMMAND,windowsHide:!0})}async function Ha(){let t="tree-kill";try{let e=await import(t);return e.default??e}catch(e){return d.debug("SYSTEM","tree-kill module not available, using fallback",{},e instanceof Error?e:void 0),null}}var Si=3e4,Ue=null;function ja(){let e=xt().pruneDeadEntries();e>0&&d.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function Ei(){Ue===null&&(Ue=setInterval(ja,Si),Ue.unref(),d.debug("SYSTEM","Health checker started",{intervalMs:Si}))}function wi(){Ue!==null&&(clearInterval(Ue),Ue=null,d.debug("SYSTEM","Health checker stopped"))}var $a=R.workerPid(),Or=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),Lt({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,Ei()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async s=>{if(this.shutdownInitiated){d.warn("SYSTEM",`Received ${s} but shutdown already in progress`);return}this.shutdownInitiated=!0,d.info("SYSTEM",`Received ${s}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){i instanceof Error?d.error("SYSTEM","Error during shutdown",{},i):d.error("SYSTEM","Error during shutdown (non-Error)",{error:String(i)});try{await this.stop()}catch(n){n instanceof Error?d.debug("SYSTEM","Supervisor shutdown fallback failed",{},n):d.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(n)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{d.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}wi(),this.stopPromise=gi({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,s){this.registry.register(e,r,s)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},eu=new Or(xt());function Lt(t={}){let e=t.pidFilePath??$a;if(!(0,ve.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,ve.readFileSync)(e,"utf-8"))}catch(i){return i instanceof Error?d.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},i):d.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(i)}),(0,ve.rmSync)(e,{force:!0}),"invalid"}return Rr(r)&&r?((t.logAlive??!0)&&d.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(d.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,ve.rmSync)(e,{force:!0}),"stale")}var Dr=require("path"),Ut=require("fs"),_i=require("crypto");var Nt=require("fs");function yi(t,e){if(!(0,Nt.existsSync)(t))return e;try{return JSON.parse((0,Nt.readFileSync)(t,"utf-8"))}catch(r){throw new Error(`Corrupt JSON file, refusing to overwrite: ${t}: ${r instanceof Error?r.message:String(r)}`)}}var bi="telemetry.json";function Ba(t){let e=t.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function Ga(t,e){if(Ba(t))return{enabled:!1,source:"DO_NOT_TRACK"};let r=t.CLAUDE_MEM_TELEMETRY?.toLowerCase();return r==="0"||r==="false"||r==="off"?{enabled:!1,source:"env"}:r==="1"||r==="true"||r==="on"?{enabled:!0,source:"env"}:e?.enabled===!0?{enabled:!0,source:"config"}:e?.enabled===!1?{enabled:!1,source:"config"}:{enabled:!0,source:"default"}}function vi(t,e){return Ga(t,e).enabled}function Ka(){return(0,Dr.join)(Oe(),bi)}function Pr(){try{let t=yi(Ka(),null);return!t||typeof t!="object"||typeof t.installId!="string"||t.enabled!==void 0&&typeof t.enabled!="boolean"?null:{enabled:t.enabled,installId:t.installId,decidedAt:typeof t.decidedAt=="string"?t.decidedAt:""}}catch{return null}}function Ya(t){let e=Oe();(0,Ut.mkdirSync)(e,{recursive:!0}),(0,Ut.writeFileSync)((0,Dr.join)(e,bi),JSON.stringify(t,null,2)+`
15
+ `)}function Ti(){let t=Pr();if(t?.installId)return t.installId;let e=(0,_i.randomUUID)();return Ya({installId:e,decidedAt:""}),e}var za=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","install_method","interactive","bun_version","uv_version","claude_code_version","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_invalid_output","top_model","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens"]),Mi=200;function Ai(t){let e={};try{if(!t||typeof t!="object")return e;for(let r of Object.keys(t)){if(!za.has(r))continue;let s=t[r];typeof s=="string"?e[r]=s.length>Mi?s.slice(0,Mi):s:(typeof s=="number"&&Number.isFinite(s)||typeof s=="boolean")&&(e[r]=s)}}catch{}return e}var Ir=X(require("os"),1),Ja="13.7.1",Xa="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",qa="https://us.i.posthog.com";function Ci(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||Xa}function ki(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||qa}var Va=["version","os","os_version","is_wsl","arch","runtime","locale","ide","provider","runtime_mode","install_method","claude_code_version","first_active_date","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs"];function Ri(t){let e={};for(let r of Va)t[r]!==void 0&&(e[r]=t[r]);return e}function Qa(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||Ir.default.release().toLowerCase().includes("microsoft")}catch{return!1}}function Oi(){return{version:Ja,os:process.platform,os_version:Ir.default.release(),is_wsl:Qa(),arch:process.arch,runtime:process.versions.bun?"bun":"node",runtime_version:process.versions.bun??process.versions.node,node_version:process.versions.node,is_ci:!!process.env.CI,locale:Intl.DateTimeFormat().resolvedOptions().locale}}var Za=2e3;async function Di(t,e,r){try{if(!vi(process.env,Pr()))return;let s=Ai({...Oi(),...e??{}});if(r?.person?s.$set=Ri(s):s.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:t,properties:s})+`
16
+ `);return}let i=Ci();if(!i)return;let n=new AbortController,o=setTimeout(()=>n.abort(),Za);try{await fetch(`${ki()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:i,event:t,distinct_id:Ti(),properties:s}),signal:n.signal})}finally{clearTimeout(o)}}catch{}}var Te=X(require("path"),1),Ii=require("os"),re=require("fs"),Lr=require("child_process");var yu=R.dataDir(),_u=R.workerPid();function Pi(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function tl(t,e){let r=e==="win32"?`where ${t}`:`which ${t}`,s;try{s=(0,Lr.execSync)(r,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(n){return n instanceof Error?d.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},n):d.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},new Error(String(n))),null}return s.split(/\r?\n/).map(n=>n.trim()).find(n=>n.length>0)||null}var xr;function xi(t={}){let e=Object.keys(t).length===0;if(e&&xr!==void 0)return xr;let r=rl(t);return e&&r!==null&&(xr=r),r}function rl(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(Pi(r))return r;let s=t.env??process.env,i=t.homeDirectory??(0,Ii.homedir)(),n=t.pathExists??re.existsSync,o=t.lookupInPath??tl,a=e==="win32"?[s.BUN,s.BUN_PATH,Te.default.join(i,".bun","bin","bun.exe"),Te.default.join(i,".bun","bin","bun"),s.USERPROFILE?Te.default.join(s.USERPROFILE,".bun","bin","bun.exe"):void 0,s.LOCALAPPDATA?Te.default.join(s.LOCALAPPDATA,"bun","bun.exe"):void 0,s.LOCALAPPDATA?Te.default.join(s.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[s.BUN,s.BUN_PATH,Te.default.join(i,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun"];for(let l of a){let c=l?.trim();if(c&&(Pi(c)&&n(c)||c.toLowerCase()==="bun"))return c}return o("bun",e)}var Li=X(require("path"),1);var Ni=require("fs");async function sl(t,e,r="GET"){let s=await fetch(`http://127.0.0.1:${t}${e}`,{method:r}),i="";try{i=await s.text()}catch{}return{ok:s.ok,statusCode:s.status,body:i}}function il(){try{let t=Li.default.join(lt,"package.json");return JSON.parse((0,Ni.readFileSync)(t,"utf-8")).version}catch(t){if(t instanceof Error){let e=t.code;if(e==="ENOENT"||e==="EBUSY")return d.debug("SYSTEM","Could not read plugin version (shutdown race)",{code:e}),"unknown";throw t}throw t}}async function nl(t){try{let e=await sl(t,"/api/version");return e.ok?JSON.parse(e.body).version:null}catch{return d.debug("SYSTEM","Could not fetch worker version",{}),null}}async function Ui(t){let e=il(),r=await nl(t);return!r||e==="unknown"?{matches:!0,pluginVersion:e,workerVersion:r}:{matches:e===r,pluginVersion:e,workerVersion:r}}var Ft=require("path"),B=require("fs");var ol=6e4;function Fi(){return(0,Ft.join)(Oe(),"spawn.lock")}function Wi(){let t=Fi(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return(0,B.mkdirSync)((0,Ft.dirname)(t),{recursive:!0}),(0,B.writeFileSync)(t,e,{flag:"wx"}),!0}catch(s){if(s?.code!=="EEXIST")return!0;if(r>0)return!1;let n;try{n=(0,B.statSync)(t).mtimeMs}catch{continue}if(Date.now()-n<=ol)return!1;let o;try{o=(0,B.statSync)(t).mtimeMs}catch{continue}if(o!==n)return!1;try{(0,B.unlinkSync)(t)}catch{return!1}}return!1}function Hi(){let t=Fi();try{if(JSON.parse((0,B.readFileSync)(t,"utf-8")).pid!==process.pid)return;(0,B.unlinkSync)(t)}catch{}}function Wr(t,e,r){let s=process.env[t];if(s){let i=parseInt(s,10);if(Number.isFinite(i)&&i>=r.min&&i<=r.max)return i;d.warn("SYSTEM",`Invalid ${t}, using default`,{value:s,min:r.min,max:r.max})}return e}var Gt=Wr("CLAUDE_MEM_HEALTH_TIMEOUT_MS",le($.HEALTH_CHECK),{min:500,max:3e5}),Ju=Wr("CLAUDE_MEM_API_TIMEOUT_MS",le($.API_REQUEST),{min:500,max:3e5}),Ki=Wr("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",le($.HOOK_READINESS_WAIT),{min:0,max:3e5}),al={min:500,max:3e5};async function Hr(t,e={},r){try{return await fetch(t,{...e,signal:AbortSignal.timeout(r)})}catch(s){throw s instanceof DOMException&&s.name==="TimeoutError"?new Error(`Request timed out after ${r}ms`):s}}var Wt=null,Ht=null,jt=null,$t=null;function ll(){return Fe.default.join(ee.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function jr(){return jt!==null||(jt=ee.loadFromFile(ll())),jt}function ji(t,e){if(!t)return null;let r=parseInt(t,10);return Number.isFinite(r)&&r>=e.min&&r<=e.max?r:null}function cl(t,e,r){let s=process.env[t];if(s!==void 0){let o=ji(s,r);return o!==null?o:(d.warn("SYSTEM",`Invalid ${t}, using default`,{value:s,min:r.min,max:r.max}),e)}let i=jr()[t],n=ji(i,r);return n!==null?n:(d.warn("SYSTEM",`Invalid ${t} in settings.json, using default`,{value:i,min:r.min,max:r.max}),e)}function Yi(){if(Wt!==null)return Wt;let t=jr();return Wt=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),Wt}function ul(){return Ht!==null||(Ht=jr().CLAUDE_MEM_WORKER_HOST),Ht}function hl(){return $t!==null||($t=cl("CLAUDE_MEM_API_TIMEOUT_MS",le($.API_REQUEST),al)),$t}function dl(t){return`http://${ul()}:${Yi()}${t}`}function he(t,e={}){let r=e.method??"GET",s=e.timeoutMs??hl(),i=dl(t),n={method:r};return e.headers&&(n.headers=e.headers),e.body&&(n.body=e.body),s>0?Hr(i,n,s):fetch(i,n)}async function pl(){return(await he("/api/health",{timeoutMs:Gt})).ok}async function $i(){return(await he("/api/readiness",{timeoutMs:Gt})).ok}function fl(){let t=[Fe.default.join(lt,"plugin","scripts","worker-service.cjs"),Fe.default.join(process.cwd(),"plugin","scripts","worker-service.cjs")];for(let e of t)if((0,Y.existsSync)(e))return e;return null}async function ml(t){let e=t.backoffMs;for(let r=1;r<=t.attempts;r++){if(await Ji())return!0;r<t.attempts&&(await new Promise(s=>setTimeout(s,e)),e*=2)}return!1}async function Nr(t=Ki){if(t<=0)try{return await $i()}catch{return!1}let e=Date.now();for(;Date.now()-e<t;){try{if(await $i())return!0}catch(s){d.debug("SYSTEM","Worker readiness check threw",{error:s instanceof Error?s.message:String(s)})}let r=t-(Date.now()-e);if(r<=0)break;await new Promise(s=>setTimeout(s,Math.min(250,r)))}return!1}async function zi(){try{let e=await(await he("/api/health",{timeoutMs:Gt})).json();return typeof e.version=="string"?e.version:null}catch{return null}}async function gl(t,e=Ki){let r=Date.now();for(;Date.now()-r<e;){if(await zi()===t)return!0;let i=e-(Date.now()-r);if(i<=0)break;await new Promise(n=>setTimeout(n,Math.min(500,i)))}return!1}async function Ur(t){let e=await zi();e!==null&&e!==t&&d.warn("SYSTEM","Worker is ready but still reports a stale version; not recycling again in this hook invocation (one recycle per hook event)",{pluginVersion:t,workerVersion:e})}async function Ji(){let t;try{t=await pl()}catch(r){return d.debug("SYSTEM","Worker health check threw",{error:r instanceof Error?r.message:String(r)}),!1}if(!t)return!1;let e=Lt({logAlive:!1});return e==="missing"||e==="alive"}async function Kt(){let t=null;if(await Ji()){let{matches:n,pluginVersion:o,workerVersion:a}=await Ui(Yi());if(o!=="unknown"&&(t=o),n)return await Nr()?(t!==null&&await Ur(t),!0):(d.warn("SYSTEM","Worker is healthy but not ready; skipping hook API call"),!1);d.info("SYSTEM","Worker version mismatch \u2014 recycling stale worker",{pluginVersion:o,workerVersion:a});try{if(await he("/api/admin/restart",{method:"POST",timeoutMs:Gt}),await gl(o))return await Nr()?(t!==null&&await Ur(t),!0):(d.warn("SYSTEM","Recycled worker appeared but did not become ready; skipping hook API call"),!1);d.warn("SYSTEM","No successor worker appeared after recycle; falling through to lazy-spawn",{pluginVersion:o,workerVersion:a})}catch(l){d.debug("SYSTEM","Worker restart request failed; falling through to lazy-spawn",{error:l instanceof Error?l.message:String(l)})}}let e=xi(),r=fl();if(!e)return d.warn("SYSTEM","Cannot lazy-spawn worker: Bun runtime not found on PATH"),!1;if(!r)return d.warn("SYSTEM","Cannot lazy-spawn worker: worker-service.cjs not found in plugin/scripts"),!1;let s=Wi();try{if(s){d.info("SYSTEM","Worker not running \u2014 lazy-spawning",{runtimePath:e,scriptPath:r});try{Ot(e,[r,"--daemon"],{detached:!0,stdio:["ignore","ignore","ignore"]}).unref()}catch(o){return o instanceof Error?d.error("SYSTEM","Lazy-spawn of worker failed",{runtimePath:e,scriptPath:r},o):d.error("SYSTEM","Lazy-spawn of worker failed (non-Error)",{runtimePath:e,scriptPath:r,error:String(o)}),!1}}else d.info("SYSTEM","Another launcher holds the spawn lock \u2014 skipping lazy-spawn and waiting for its worker");if(!await ml({attempts:6,backoffMs:500}))return d.warn("SYSTEM",s?"Worker port did not open after lazy-spawn within the cold-boot wait (~15s)":"Spawn-lock holder's worker port did not open within the cold-boot wait (~15s)"),!1}finally{s&&Hi()}return await Nr()?(t!==null&&await Ur(t),!0):(d.warn("SYSTEM","Worker lazy-spawned but did not become ready before hook readiness timeout"),!1)}var Bt=null;async function Sl(){return Bt!==null||(Bt=await Kt()),Bt}var El=3;function Xi(){return Fe.default.join(v,"state")}function qi(){return Fe.default.join(Xi(),"hook-failures.json")}function Vi(){try{let t=(0,Y.readFileSync)(qi(),"utf-8"),e=JSON.parse(t);return{consecutiveFailures:typeof e.consecutiveFailures=="number"&&Number.isFinite(e.consecutiveFailures)?Math.max(0,Math.floor(e.consecutiveFailures)):0,lastFailureAt:typeof e.lastFailureAt=="number"&&Number.isFinite(e.lastFailureAt)?e.lastFailureAt:0}}catch{return{consecutiveFailures:0,lastFailureAt:0}}}function Qi(t){let e=Xi(),r=qi(),s=`${r}.tmp`;try{(0,Y.existsSync)(e)||(0,Y.mkdirSync)(e,{recursive:!0}),(0,Y.writeFileSync)(s,JSON.stringify(t),"utf-8"),(0,Y.renameSync)(s,r)}catch(i){d.debug("SYSTEM","Failed to persist hook-failure counter",{error:i instanceof Error?i.message:String(i)})}}function wl(){try{let e=ce().CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD,r=parseInt(e,10);if(Number.isFinite(r)&&r>=1)return r}catch{}return El}var Bi=null;async function yl(){let e={consecutiveFailures:Vi().consecutiveFailures+1,lastFailureAt:Date.now()};Qi(e);let r=wl();return e.consecutiveFailures>=r&&(e.consecutiveFailures===r&&await Di("hook_failed",{...Bi!==null?{hook_type:Bi}:{},error_mode:"worker_unavailable",consecutive_failures:e.consecutiveFailures,threshold_tripped:!0}),zr(`claude-mem worker unreachable for ${e.consecutiveFailures} consecutive hooks.`)),e.consecutiveFailures}function Gi(){Vi().consecutiveFailures!==0&&Qi({consecutiveFailures:0,lastFailureAt:0})}var Fr=Symbol.for("claude-mem/worker-fallback");function rt(t){return typeof t=="object"&&t!==null&&t[Fr]===!0}async function st(t,e,r,s={}){if(!await Sl())return await yl(),{continue:!0,reason:"worker_unreachable",[Fr]:!0};let n={method:e};r!==void 0&&(n.headers={"Content-Type":"application/json"},n.body=JSON.stringify(r)),s.timeoutMs!==void 0&&(n.timeoutMs=s.timeoutMs);let o=await he(t,n);if(!o.ok){let l=await o.text().catch(()=>"");if(Gi(),o.status===429||o.status>=500)return d.warn("SYSTEM",`Worker API ${e} ${t} returned ${o.status}; skipping hook API call`,{body:l.substring(0,200)}),{continue:!0,reason:`worker_api_${o.status}`,[Fr]:!0};let c=l;try{c=JSON.parse(l)}catch{}return c}Gi();let a=await o.text();if(a.length!==0)try{return JSON.parse(a)}catch{return a}}var en=require("os"),tn=X(require("path"),1),rn=require("child_process");var zt=require("fs"),Yt=X(require("path"),1);var it={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function Zi(t){let e=Yt.default.join(t,".git"),r;try{r=(0,zt.statSync)(e)}catch(u){return u instanceof Error&&u.code!=="ENOENT"&&d.warn("GIT","Unexpected error checking .git",{error:u instanceof Error?u.message:String(u)}),it}if(!r.isFile())return it;let s;try{s=(0,zt.readFileSync)(e,"utf-8").trim()}catch(u){return d.warn("GIT","Failed to read .git file",{error:u instanceof Error?u.message:String(u)}),it}let i=s.match(/^gitdir:\s*(.+)$/);if(!i)return it;let o=i[1].match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!o)return it;let a=o[1],l=Yt.default.basename(t),c=Yt.default.basename(a);return{isWorktree:!0,worktreeName:l,parentRepoPath:a,parentProjectName:c}}function sn(t){return t==="~"||t.startsWith("~/")?t.replace(/^~/,(0,en.homedir)()):t}function _l(t){try{return(0,rn.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function bl(t){if(!t||t.trim()==="")return d.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),"unknown-project";let e=sn(t),s=_l(e)??e,i=tn.default.basename(s);if(i===""){if(process.platform==="win32"){let o=t.match(/^([A-Z]):\\/i);if(o){let l=`drive-${o[1].toUpperCase()}`;return d.info("PROJECT_NAME","Drive root detected",{cwd:t,projectName:l}),l}}return d.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:t}),"unknown-project"}return i}function Me(t){let e=bl(t);if(!t)return{primary:e,parent:null,isWorktree:!1,allProjects:[e]};let r=sn(t),s=Zi(r);if(s.isWorktree&&s.parentProjectName){let i=`${s.parentProjectName}/${e}`;return{primary:i,parent:s.parentProjectName,isWorktree:!0,allProjects:[s.parentProjectName,i]}}return{primary:e,parent:null,isWorktree:!1,allProjects:[e]}}var Ae=require("path");var nn=require("os"),on=require("path");function vl(t){let e=t.startsWith("~")?(0,nn.homedir)()+t.slice(1):t;e=e.replace(/\\/g,"/");let r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return r=r.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${r}$`)}function Jt(t,e){if(!e||!e.trim())return!1;let r=t.replace(/\\/g,"/"),s=(0,on.basename)(r),i=e.split(",").map(n=>n.trim()).filter(Boolean);for(let n of i)try{let o=vl(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 Tl(t,e){let r=(0,Ae.normalize)(t),s=(0,Ae.normalize)(e);if(r===s)return!0;let i=(0,Ae.relative)(s,r);return i.length>0&&!i.startsWith("..")&&!(0,Ae.isAbsolute)(i)}function Xt(t){if(process.env.CLAUDE_MEM_INTERNAL==="1")return!1;if(!t)return!0;if(Tl(t,ut))return!1;let e=ce();return!Jt(t,e.CLAUDE_MEM_EXCLUDED_PROJECTS)}var an="claude";function Ml(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function we(t){if(!t)return an;let e=Ml(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:an}var un=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],ln=new RegExp(`<(${un.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g");var cn=100;function Al(t){let e=Object.fromEntries(un.map(i=>[i,0]));ln.lastIndex=0;let r=0,s=t.replace(ln,(i,n)=>(e[n]=(e[n]??0)+1,r+=1,""));return r>cn&&d.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:r,maxAllowed:cn,contentLength:t.length}),{stripped:s.trim(),counts:e}}function $r(t){return Al(t).stripped}var Cl=["task-notification"],kl=new RegExp(`^\\s*<(${Cl.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),Rl=256*1024;function hn(t){return!t||t.length>Rl?!1:kl.test(t)}var Ol=le($.API_REQUEST),de=class extends Error{kind;status;cause;constructor(e,r,s={}){super(r),this.name="ServerBetaClientError",this.kind=e,this.status=s.status??null,this.cause=s.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},qt=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=Dl(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??Ol}async startSession(e){let r=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",r)}async recordEvent(e){let r=this.buildEventPayload(e),s=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",s,r)}async endSession(e){if(!e.sessionId)throw new de("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async getJobStatus(e){if(!e)throw new de("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,s=e.kind??"manual",i=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:s,type:s,narrative:r,...i?{title:i}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:e.platformSource}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,r,s){if(!this.apiKey||!this.apiKey.trim())throw new de("missing_api_key","Server beta API key is not configured (CLAUDE_MEM_SERVER_BETA_API_KEY).");let i=`${this.baseUrl}${r}`,n={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};s!==void 0&&(n.body=JSON.stringify(s));let o;try{o=await Hr(i,n,this.timeoutMs)}catch(l){let c=l instanceof Error?l.message:String(l),u=/timed out|timeout/i.test(c);throw new de(u?"timeout":"transport",`Server beta ${e} ${r} failed: ${c}`,{cause:l})}if(!o.ok){let l=await o.text().catch(()=>"");throw new de("http_error",`Server beta ${e} ${r} returned ${o.status}: ${Pl(l,200)}`,{status:o.status})}let a=await o.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(l){throw new de("invalid_response",`Server beta ${e} ${r} returned non-JSON response`,{cause:l})}}};function dn(t){return t instanceof de}function Dl(t){return t.replace(/\/+$/,"")}function Pl(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Il(){return(ce().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase()==="server-beta"?"server-beta":"worker"}function xl(){let t=ce(),e=(t.CLAUDE_MEM_SERVER_BETA_URL??"").trim(),r=(t.CLAUDE_MEM_SERVER_BETA_API_KEY??"").trim(),s=(t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID??"").trim();if(!e)return d.warn("HOOK","[server-beta-fallback] reason=missing_base_url"),null;if(!r)return d.warn("HOOK","[server-beta-fallback] reason=missing_api_key"),null;if(!s)return d.warn("HOOK","[server-beta-fallback] reason=missing_project_id"),null;let i={serverBaseUrl:e,apiKey:r};return{runtime:"server-beta",client:new qt(i),projectId:s,serverBaseUrl:e}}function pn(){if(Il()!=="server-beta")return{runtime:"worker"};let t=xl();return t||{runtime:"worker"}}function fn(t,e){d.warn("HOOK",`[server-beta-fallback] reason=${t}`,e??{})}var mn={async execute(t){let{sessionId:e,prompt:r}=t,s=t.cwd??process.cwd();if(!e)return d.warn("HOOK","session-init: No sessionId provided, skipping (Codex CLI or unknown platform)"),{continue:!0,suppressOutput:!0,exitCode:Ee.SUCCESS};if(!Xt(s))return d.info("HOOK","Project excluded from tracking",{cwd:s}),{continue:!0,suppressOutput:!0};if(r&&hn(r))return d.debug("HOOK","session-init: skipping internal protocol payload",{preview:r.slice(0,80)}),{continue:!0,suppressOutput:!0};let i=!r||!r.trim()?"[media prompt]":r,n=Me(s).primary,o=we(t.platform),a=pn();if(a.runtime==="server-beta")try{return await a.client.startSession({projectId:a.projectId,externalSessionId:e,contentSessionId:e,agentId:t.agentId??null,agentType:t.agentType??null,platformSource:o,metadata:{project:n,prompt:i}}),d.info("HOOK","session-init: server-beta session started",{contentSessionId:e,project:n}),{continue:!0,suppressOutput:!0}}catch(m){if(dn(m)&&m.isFallbackEligible())fn(m.kind,{status:m.status,message:m.message,route:"/v1/sessions/start"});else return d.error("HOOK","Server beta session-start failed (non-recoverable)",{error:m instanceof Error?m.message:String(m)}),{continue:!0,suppressOutput:!0,exitCode:Ee.SUCCESS}}d.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:e,project:n});let l=await st("/api/sessions/init","POST",{contentSessionId:e,project:n,prompt:i,platformSource:o});if(rt(l))return{continue:!0,suppressOutput:!0,exitCode:Ee.SUCCESS};if(typeof l?.sessionDbId!="number")return d.failure("HOOK","Session initialization returned malformed response",{contentSessionId:e,project:n}),{continue:!0,suppressOutput:!0,exitCode:Ee.SUCCESS};let c=l.sessionDbId,u=l.promptNumber;if(d.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:c,promptNumber:u,skipped:l.skipped,contextInjected:l.contextInjected}),d.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${e} | prompt#=${u} | sessionDbId=${c}`),l.skipped&&l.reason==="private")return d.info("HOOK",`INIT_COMPLETE | sessionDbId=${c} | promptNumber=${u} | skipped=true | reason=private`,{sessionId:c}),{continue:!0,suppressOutput:!0};let h=ce(),p=String(h.CLAUDE_MEM_SEMANTIC_INJECT).toLowerCase()==="true",f="";if(p&&i&&i.length>=20&&i!=="[media prompt]"){let m=h.CLAUDE_MEM_SEMANTIC_INJECT_LIMIT||"5",g=await st("/api/context/semantic","POST",{q:i,project:n,limit:m});!rt(g)&&g?.context&&(d.debug("HOOK",`Semantic injection: ${g.count} observations for prompt`,{sessionId:c,count:g.count}),f=g.context)}return d.info("HOOK",`INIT_COMPLETE | sessionDbId=${c} | promptNumber=${u} | project=${n}`,{sessionId:c}),f?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:f}}:{continue:!0,suppressOutput:!0}}};var gn={async execute(t){let{sessionId:e,cwd:r,filePath:s,edits:i}=t,n=we(t.platform);if(!s)throw new Error("fileEditHandler requires filePath");if(d.dataIn("HOOK",`FileEdit: ${s}`,{editCount:i?.length??0}),!r)throw new Error(`Missing cwd in FileEdit hook input for session ${e}, file ${s}`);if(!Xt(r))return d.debug("HOOK","Project excluded from tracking, skipping file edit observation",{cwd:r,filePath:s}),{continue:!0,suppressOutput:!0,exitCode:Ee.SUCCESS};let o=await st("/api/sessions/observations","POST",{contentSessionId:e,platformSource:n,tool_name:"write_file",tool_input:{filePath:s,edits:i},tool_response:{success:!0},cwd:r});return rt(o)?{continue:!0,suppressOutput:!0,exitCode:Ee.SUCCESS}:(d.debug("HOOK","File edit observation sent successfully",{filePath:s}),{continue:!0,suppressOutput:!0})}};var z=require("fs"),Vt=require("path");var Jh=R.settings();function Sn(t,e){let r="<claude-mem-context>",s="</claude-mem-context>";if(!t)return`${r}
17
17
  ${e}
18
18
  ${s}`;let i=t.indexOf(r),n=t.indexOf(s);return i!==-1&&n!==-1?t.substring(0,i)+`${r}
19
19
  ${e}
@@ -21,8 +21,8 @@ ${s}`+t.substring(n+s.length):t+`
21
21
 
22
22
  ${r}
23
23
  ${e}
24
- ${s}`}function _n(t,e){if(!t)return;let r=(0,Vt.resolve)(t);if(r.includes("/.git/")||r.includes("\\.git\\")||r.endsWith("/.git")||r.endsWith("\\.git"))return;let s=(0,Vt.dirname)(t);(0,z.existsSync)(s)||(0,z.mkdirSync)(s,{recursive:!0});let i="";(0,z.existsSync)(t)&&(i=(0,z.readFileSync)(t,"utf-8"));let n=`# Memory Context
24
+ ${s}`}function En(t,e){if(!t)return;let r=(0,Vt.resolve)(t);if(r.includes("/.git/")||r.includes("\\.git\\")||r.endsWith("/.git")||r.endsWith("\\.git"))return;let s=(0,Vt.dirname)(t);(0,z.existsSync)(s)||(0,z.mkdirSync)(s,{recursive:!0});let i="";(0,z.existsSync)(t)&&(i=(0,z.readFileSync)(t,"utf-8"));let n=`# Memory Context
25
25
 
26
- ${e}`,o=wn(i,n),a=`${t}.tmp`;try{(0,z.writeFileSync)(a,o),(0,z.renameSync)(a,t)}catch(l){d.error("AGENTS_MD","Failed to write AGENTS.md",{agentsPath:t},l instanceof Error?l:new Error(String(l)))}}function $l(t){let e=t.trim().replace(/^\$\.?/,"");if(!e)return[];let r=[],s=e.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 jr(t,e){if(!e)return;let r=$l(e),s=t;for(let i of r){if(s==null)return;s=s[i]}return s}function yn(t){return t==null||t===""}function bn(t,e){if(t.startsWith("$watch.")){let r=t.slice(7);return e.watch[r]}if(t.startsWith("$schema.")){let r=t.slice(8);return e.schema[r]}if(t.startsWith("$session.")){let r=t.slice(9);return e.session?e.session[r]:void 0}if(t==="$cwd")return e.watch.workspace;if(t==="$project")return e.watch.project}function We(t,e,r){if(t!==void 0){if(typeof t=="string"){let s=bn(t,r);return s!==void 0?s:jr(e,t)}if(t.coalesce&&Array.isArray(t.coalesce))for(let s of t.coalesce){let i=We(s,e,r);if(!yn(i))return i}if(t.path){let s=bn(t.path,r);if(s!==void 0)return s;let i=jr(e,t.path);if(!yn(i))return i}if(t.value!==void 0)return t.value;if(t.default!==void 0)return t.default}}function vn(t,e,r){let s={};if(!t)return s;for(let[i,n]of Object.entries(t))s[i]=We(n,e,r);return s}function Tn(t,e,r){if(!e)return!0;let s=e.path||r.eventTypePath||"type",i=s?jr(t,s):void 0,n=i==null||i==="";if(e.exists!==void 0&&(e.exists&&n||!e.exists&&!n)||e.equals!==void 0&&i!==e.equals||e.not_equals!==void 0&&i===e.not_equals||e.in&&Array.isArray(e.in)&&!e.in.includes(i)||e.not_in&&Array.isArray(e.not_in)&&e.not_in.includes(i)||e.contains!==void 0&&(typeof i!="string"||!i.includes(e.contains))||e.not_contains!==void 0&&typeof i=="string"&&i.includes(e.not_contains))return!1;if(e.regex)try{if(!new RegExp(e.regex).test(String(i??"")))return!1}catch(o){return d.debug("WORKER","Invalid regex in match rule",{regex:e.regex},o instanceof Error?o:void 0),!1}return!0}var Qt=class{static checkUserPromptPrivacy(e,r,s,i,n,o){let a=e.getUserPrompt(r,s);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 kn=require("events"),Br=class t extends kn.EventEmitter{recentStored=new Map;static RECENT_EVENT_TTL_MS=6e4;constructor(){super(),this.setMaxListeners(0),this.on("summaryStoredEvent",e=>{this.recentStored.set(e.sessionId,{event:e,at:Date.now()}),this.evictExpiredStored()})}takeRecentSummaryStored(e){let r=this.recentStored.get(e);if(r){if(Date.now()-r.at>t.RECENT_EVENT_TTL_MS){this.recentStored.delete(e);return}return r.event}}evictExpiredStored(){let e=Date.now()-t.RECENT_EVENT_TTL_MS;for(let[r,s]of this.recentStored)s.at<e&&this.recentStored.delete(r)}},md=new Br,Mn=null;function Hl(){if(!Mn)throw new Error("ingest helpers used before setIngestContext() \u2014 wiring bug");return Mn}async function Cn(t){let{sessionManager:e,dbManager:r,eventBroadcaster:s,ensureGeneratorRunning:i}=Hl(),n=we(t.platformSource),o=typeof t.cwd=="string"?t.cwd:"",a=o.trim()?Me(o).primary:"",l=ee.loadFromFile(ut);if(o&&Jt(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(t.toolName))return{ok:!0,status:"skipped",reason:"tool_excluded"};if(new Set(["Edit","Write","Read","NotebookEdit"]).has(t.toolName)&&t.toolInput&&typeof t.toolInput=="object"){let S=t.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(t.contentSessionId,a,"",void 0,n),f=h.getPromptNumberFromUserPrompts(t.contentSessionId)}catch(S){let E=S instanceof Error?S.message:String(S);return d.error("INGEST","Observation session resolution failed",{contentSessionId:t.contentSessionId,toolName:t.toolName},S instanceof Error?S:new Error(E)),{ok:!1,reason:E,status:500}}if(!Qt.checkUserPromptPrivacy(h,t.contentSessionId,f,"observation",p,{tool_name:t.toolName}).allow)return{ok:!0,status:"skipped",reason:"private"};let g=t.toolInput!==void 0?Hr(JSON.stringify(t.toolInput)):"{}",w=t.toolResponse!==void 0?Hr(JSON.stringify(t.toolResponse)):"{}";return await e.queueObservation(p,{tool_name:t.toolName,tool_input:g,tool_response:w,prompt_number:f,cwd:o||(d.error("INGEST","Missing cwd when ingesting observation",{sessionId:p,toolName:t.toolName}),""),agentId:typeof t.agentId=="string"?t.agentId:void 0,agentType:typeof t.agentType=="string"?t.agentType:void 0,toolUseId:typeof t.toolUseId=="string"?t.toolUseId:void 0}),await i?.(p,"observation"),s.broadcastObservationQueued(p),{ok:!0,sessionDbId:p}}var Zt=class{sessions=new Map;async processEntry(e,r,s,i){for(let n of s.events)Tn(e,n.match,s)&&await this.handleEvent(e,r,s,n,i??void 0)}getSessionKey(e,r){return`${e.name}:${r}`}getOrCreateSession(e,r){let s=this.getSessionKey(e,r),i=this.sessions.get(s);return i||(i={sessionId:r,platformSource:we(e.name)},this.sessions.set(s,i)),i}resolveSessionId(e,r,s,i,n){let o={watch:r,schema:s},a=i.fields?.sessionId??(s.sessionIdPath?{path:s.sessionIdPath}:void 0),l=We(a,e,o);return typeof l=="string"&&l.trim()?l:typeof l=="number"?String(l):n&&n.trim()?n:null}resolveCwd(e,r,s,i,n){let o={watch:r,schema:s,session:n},a=i.fields?.cwd??(s.cwdPath?{path:s.cwdPath}:void 0),l=We(a,e,o);return typeof l=="string"&&l.trim()?l:r.workspace?r.workspace:n.cwd}resolveProject(e,r,s,i,n){let o={watch:r,schema:s,session:n},a=i.fields?.project??(s.projectPath?{path:s.projectPath}:void 0),l=We(a,e,o);return typeof l=="string"&&l.trim()?l:r.project?r.project:n.cwd?Me(n.cwd).primary:n.project}async handleEvent(e,r,s,i,n){let o=this.resolveSessionId(e,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(e,r,s,i,a);l&&(a.cwd=l);let c=this.resolveProject(e,r,s,i,a);c&&(a.project=c);let u=vn(i.fields,e,{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(e,r){let s=typeof r.cwd=="string"?r.cwd:void 0,i=typeof r.project=="string"?r.project:void 0;s&&(e.cwd=s),i&&(e.project=i)}async handleSessionInit(e,r){let s=typeof r.prompt=="string"?r.prompt:"",i=e.cwd??process.cwd();s&&(e.lastUserMessage=s),await Sn.execute({sessionId:e.sessionId,cwd:i,prompt:s,platform:e.platformSource})}async handleToolUse(e,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(e,{filePath:l,edits:[{type:"apply_patch",patch:n}]})}i&&o!==void 0?await this.sendObservation(e,{toolName:i,toolInput:n,toolResponse:o,toolUseId:s}):i&&s&&(e.pendingTools||(e.pendingTools=new Map),e.pendingTools.set(s,{toolName:i,toolInput:n}))}async handleToolResult(e,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&&e.pendingTools){let a=e.pendingTools.get(s);a&&(i||(i=a.toolName),o===void 0&&(o=a.toolInput),e.pendingTools.delete(s))}i?await this.sendObservation(e,{toolName:i,toolInput:o,toolResponse:n,toolUseId:s}):d.debug("TRANSCRIPT","Dropping tool_result with no resolvable toolName",{sessionId:e.sessionId,toolId:s})}async sendObservation(e,r){let s=typeof r.toolName=="string"?r.toolName:void 0;if(!s)return;let i=await Cn({contentSessionId:e.sessionId,cwd:e.cwd??process.cwd(),toolName:s,toolInput:this.maybeParseJson(r.toolInput),toolResponse:this.maybeParseJson(r.toolResponse),platformSource:e.platformSource,toolUseId:typeof r.toolUseId=="string"?r.toolUseId:void 0});if(!i.ok)throw new Error(`ingestObservation failed: ${i.reason}`)}async sendFileEdit(e,r){let s=typeof r.filePath=="string"?r.filePath:void 0;s&&await En.execute({sessionId:e.sessionId,cwd:e.cwd??process.cwd(),filePath:s,edits:Array.isArray(r.edits)?r.edits:void 0,platform:e.platformSource})}maybeParseJson(e){if(typeof e!="string")return e;let r=e.trim();if(!r||!(r.startsWith("{")||r.startsWith("[")))return e;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),e}}parseApplyPatchFiles(e){let r=[],s=e.split(`
27
- `);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(e,r){await this.queueSummary(e),await this.updateContext(e,r),e.pendingTools?.clear();let s=this.getSessionKey(r,e.sessionId);this.sessions.delete(s)}async queueSummary(e){if(!await Kt())return;let s=e.lastAssistantMessage??"",i=JSON.stringify({contentSessionId:e.sessionId,last_assistant_message:s,platformSource:e.platformSource});try{await he("/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(e,r){if(!r.context||r.context.mode!=="agents"||qr(r)||!await Kt())return;let i=e.cwd??r.workspace;if(!i)return;let o=Me(i).allProjects.join(","),a=`/api/context/inject?projects=${encodeURIComponent(o)}`,l=N(r.context.path??`${i}/AGENTS.md`),c=ot.default.resolve(l),u=[ot.default.resolve(i),ot.default.resolve(v)];if(!u.some(m=>c.startsWith(m+ot.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 he(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&&(_n(l,f),d.debug("TRANSCRIPT","Updated AGENTS.md context",{agentsPath:l,watch:r.name}))}};var Gr=class{constructor(e,r,s,i){this.filePath=e;this.onLine=s;this.onOffset=i;this.tailState={offset:r,partial:""}}filePath;onLine;onOffset;watcher=null;tailState;start(){this.readNewData().catch(()=>{}),this.watcher=(0,x.watch)(this.filePath,{persistent:!0},()=>{this.readNewData().catch(()=>{})})}close(){this.watcher?.close(),this.watcher=null}poke(){this.readNewData().catch(()=>{})}async readNewData(){if(!(0,x.existsSync)(this.filePath))return;let e=0;try{e=(0,x.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(e<this.tailState.offset&&(this.tailState.offset=0),e===this.tailState.offset)return;let r=(0,x.createReadStream)(this.filePath,{start:this.tailState.offset,end:e-1,encoding:"utf8"}),s="";for await(let o of r)s+=o;this.tailState.offset=e,this.onOffset(this.tailState.offset);let n=(this.tailState.partial+s).split(`
28
- `);this.tailState.partial=n.pop()??"";for(let o of n){let a=o.trim();a&&await this.onLine(a)}}},er=class{constructor(e,r){this.config=e;this.statePath=r;this.state=li(r)}config;statePath;processor=new Zt;tailers=new Map;state;rootWatchers=[];async start(){for(let e of this.config.watches)await this.setupWatch(e)}stop(){for(let e of this.tailers.values())e.close();this.tailers.clear();for(let e of this.rootWatchers)e.close();this.rootWatchers=[]}async setupWatch(e){let r=this.resolveSchema(e);if(!r){d.warn("TRANSCRIPT","Missing schema for watch",{watch:e.name});return}let s=N(e.path),i=this.resolveWatchFiles(s);for(let o of i)await this.addTailer(o,e,r);let n=this.deepestNonGlobAncestor(s);if(!n||!(0,x.existsSync)(n)){d.debug("TRANSCRIPT","Watch root does not exist, skipping fs.watch",{watch:e.name,watchRoot:n});return}try{let o=(0,x.watch)(n,{recursive:!0,persistent:!0},(a,l)=>{if(!l)return;let c=(0,J.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,e,r)});this.rootWatchers.push(o),d.info("TRANSCRIPT","Watching transcript root recursively",{watch:e.name,watchRoot:n})}catch(o){d.warn("TRANSCRIPT","Failed to start recursive fs.watch on transcript root",{watch:e.name,watchRoot:n},o instanceof Error?o:void 0)}}deepestNonGlobAncestor(e){if(!this.hasGlob(e)){if((0,x.existsSync)(e))try{return(0,x.statSync)(e).isDirectory()?e:(0,J.resolve)(e,"..")}catch{return(0,J.resolve)(e,"..")}return e}let r=e.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(J.sep)}resolveSchema(e){return typeof e.schema=="string"?this.config.schemas?.[e.schema]??null:e.schema}resolveWatchFiles(e){if(this.hasGlob(e))return et(this.normalizeGlobPattern(e),{nodir:!0,absolute:!0});if((0,x.existsSync)(e))try{if((0,x.statSync)(e).isDirectory()){let s=(0,J.join)(e,"**","*.jsonl");return et(this.normalizeGlobPattern(s),{nodir:!0,absolute:!0})}return[e]}catch(r){return d.debug("WORKER","Failed to stat watch path",{path:e},r instanceof Error?r:void 0),[]}return[]}normalizeGlobPattern(e){return e.replace(/\\/g,"/")}hasGlob(e){return/[*?[\]{}()]/.test(e)}async addTailer(e,r,s){if(this.tailers.has(e))return;let i=this.extractSessionIdFromPath(e),n=this.state.offsets[e]??0;if(n===0&&r.startAtEnd)try{n=(0,x.statSync)(e).size}catch(a){d.debug("WORKER","Failed to stat file for startAtEnd offset",{file:e},a instanceof Error?a:void 0),n=0}let o=new Gr(e,n,async a=>{await this.handleLine(a,r,s,e,i)},a=>{this.state.offsets[e]=a,ci(this.statePath,this.state)});o.start(),this.tailers.set(e,o),d.info("TRANSCRIPT","Watching transcript file",{file:e,watch:r.name,schema:s.name})}async handleLine(e,r,s,i,n){try{let o=JSON.parse(e);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,J.basename)(i)},o):d.warn("TRANSCRIPT","Failed to parse transcript line (non-Error thrown)",{watch:r.name,file:(0,J.basename)(i),error:String(o)})}}extractSessionIdFromPath(e){let r=e.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 Kr(t,e){let r=t.indexOf(e);return r===-1?null:t[r+1]??null}async function An(t,e){switch(t){case"init":{let r=Kr(e,"--config")??Ie;return pt(r),console.log(`Created sample config: ${N(r)}`),0}case"watch":{let r=Kr(e,"--config")??Ie,s;try{s=je(r)}catch(a){if(a instanceof Error&&a.message.includes("not found"))pt(r),console.log(`Created sample config: ${N(r)}`),s=je(r);else throw a}let i=N(s.stateFile??dt),n=new er(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=Kr(e,"--config")??Ie;try{je(r)}catch(s){if(s instanceof Error&&s.message.includes("not found"))pt(r),console.log(`Created sample config: ${N(r)}`),je(r);else throw s}return console.log(`Config OK: ${N(r)}`),0}default:return console.log("Usage: claude-mem transcript <init|watch|validate> [--config <path>]"),1}}var jl=process.argv[2],Bl=process.argv.slice(3);An(jl,Bl).then(t=>{process.exit(t)}).catch(t=>{console.error(t),process.exit(1)});
26
+ ${e}`,o=Sn(i,n),a=`${t}.tmp`;try{(0,z.writeFileSync)(a,o),(0,z.renameSync)(a,t)}catch(l){d.error("AGENTS_MD","Failed to write AGENTS.md",{agentsPath:t},l instanceof Error?l:new Error(String(l)))}}function Ll(t){let e=t.trim().replace(/^\$\.?/,"");if(!e)return[];let r=[],s=e.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 Br(t,e){if(!e)return;let r=Ll(e),s=t;for(let i of r){if(s==null)return;s=s[i]}return s}function wn(t){return t==null||t===""}function yn(t,e){if(t.startsWith("$watch.")){let r=t.slice(7);return e.watch[r]}if(t.startsWith("$schema.")){let r=t.slice(8);return e.schema[r]}if(t.startsWith("$session.")){let r=t.slice(9);return e.session?e.session[r]:void 0}if(t==="$cwd")return e.watch.workspace;if(t==="$project")return e.watch.project}function We(t,e,r){if(t!==void 0){if(typeof t=="string"){let s=yn(t,r);return s!==void 0?s:Br(e,t)}if(t.coalesce&&Array.isArray(t.coalesce))for(let s of t.coalesce){let i=We(s,e,r);if(!wn(i))return i}if(t.path){let s=yn(t.path,r);if(s!==void 0)return s;let i=Br(e,t.path);if(!wn(i))return i}if(t.value!==void 0)return t.value;if(t.default!==void 0)return t.default}}function _n(t,e,r){let s={};if(!t)return s;for(let[i,n]of Object.entries(t))s[i]=We(n,e,r);return s}function bn(t,e,r){if(!e)return!0;let s=e.path||r.eventTypePath||"type",i=s?Br(t,s):void 0,n=i==null||i==="";if(e.exists!==void 0&&(e.exists&&n||!e.exists&&!n)||e.equals!==void 0&&i!==e.equals||e.not_equals!==void 0&&i===e.not_equals||e.in&&Array.isArray(e.in)&&!e.in.includes(i)||e.not_in&&Array.isArray(e.not_in)&&e.not_in.includes(i)||e.contains!==void 0&&(typeof i!="string"||!i.includes(e.contains))||e.not_contains!==void 0&&typeof i=="string"&&i.includes(e.not_contains))return!1;if(e.regex)try{if(!new RegExp(e.regex).test(String(i??"")))return!1}catch(o){return d.debug("WORKER","Invalid regex in match rule",{regex:e.regex},o instanceof Error?o:void 0),!1}return!0}var Qt=class{static checkUserPromptPrivacy(e,r,s,i,n,o){let a=e.getUserPrompt(r,s);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 vn=null;function Nl(){if(!vn)throw new Error("ingest helpers used before setIngestContext() \u2014 wiring bug");return vn}async function Tn(t){let{sessionManager:e,dbManager:r,eventBroadcaster:s,ensureGeneratorRunning:i}=Nl(),n=we(t.platformSource),o=typeof t.cwd=="string"?t.cwd:"",a=o.trim()?Me(o).primary:"",l=ee.loadFromFile(ct);if(o&&Jt(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(t.toolName))return{ok:!0,status:"skipped",reason:"tool_excluded"};if(new Set(["Edit","Write","Read","NotebookEdit"]).has(t.toolName)&&t.toolInput&&typeof t.toolInput=="object"){let S=t.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(t.contentSessionId,a,"",void 0,n),f=h.getPromptNumberFromUserPrompts(t.contentSessionId)}catch(S){let E=S instanceof Error?S.message:String(S);return d.error("INGEST","Observation session resolution failed",{contentSessionId:t.contentSessionId,toolName:t.toolName},S instanceof Error?S:new Error(E)),{ok:!1,reason:E,status:500}}if(!Qt.checkUserPromptPrivacy(h,t.contentSessionId,f,"observation",p,{tool_name:t.toolName}).allow)return{ok:!0,status:"skipped",reason:"private"};let g=t.toolInput!==void 0?$r(JSON.stringify(t.toolInput)):"{}",w=t.toolResponse!==void 0?$r(JSON.stringify(t.toolResponse)):"{}";return await e.queueObservation(p,{tool_name:t.toolName,tool_input:g,tool_response:w,prompt_number:f,cwd:o||(d.error("INGEST","Missing cwd when ingesting observation",{sessionId:p,toolName:t.toolName}),""),agentId:typeof t.agentId=="string"?t.agentId:void 0,agentType:typeof t.agentType=="string"?t.agentType:void 0,toolUseId:typeof t.toolUseId=="string"?t.toolUseId:void 0}),await i?.(p,"observation"),s.broadcastObservationQueued(p),{ok:!0,sessionDbId:p}}var Zt=class{sessions=new Map;async processEntry(e,r,s,i){for(let n of s.events)bn(e,n.match,s)&&await this.handleEvent(e,r,s,n,i??void 0)}getSessionKey(e,r){return`${e.name}:${r}`}getOrCreateSession(e,r){let s=this.getSessionKey(e,r),i=this.sessions.get(s);return i||(i={sessionId:r,platformSource:we(e.name)},this.sessions.set(s,i)),i}resolveSessionId(e,r,s,i,n){let o={watch:r,schema:s},a=i.fields?.sessionId??(s.sessionIdPath?{path:s.sessionIdPath}:void 0),l=We(a,e,o);return typeof l=="string"&&l.trim()?l:typeof l=="number"?String(l):n&&n.trim()?n:null}resolveCwd(e,r,s,i,n){let o={watch:r,schema:s,session:n},a=i.fields?.cwd??(s.cwdPath?{path:s.cwdPath}:void 0),l=We(a,e,o);return typeof l=="string"&&l.trim()?l:r.workspace?r.workspace:n.cwd}resolveProject(e,r,s,i,n){let o={watch:r,schema:s,session:n},a=i.fields?.project??(s.projectPath?{path:s.projectPath}:void 0),l=We(a,e,o);return typeof l=="string"&&l.trim()?l:r.project?r.project:n.cwd?Me(n.cwd).primary:n.project}async handleEvent(e,r,s,i,n){let o=this.resolveSessionId(e,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(e,r,s,i,a);l&&(a.cwd=l);let c=this.resolveProject(e,r,s,i,a);c&&(a.project=c);let u=_n(i.fields,e,{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(e,r){let s=typeof r.cwd=="string"?r.cwd:void 0,i=typeof r.project=="string"?r.project:void 0;s&&(e.cwd=s),i&&(e.project=i)}async handleSessionInit(e,r){let s=typeof r.prompt=="string"?r.prompt:"",i=e.cwd??process.cwd();s&&(e.lastUserMessage=s),await mn.execute({sessionId:e.sessionId,cwd:i,prompt:s,platform:e.platformSource})}async handleToolUse(e,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(e,{filePath:l,edits:[{type:"apply_patch",patch:n}]})}i&&o!==void 0?await this.sendObservation(e,{toolName:i,toolInput:n,toolResponse:o,toolUseId:s}):i&&s&&(e.pendingTools||(e.pendingTools=new Map),e.pendingTools.set(s,{toolName:i,toolInput:n}))}async handleToolResult(e,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&&e.pendingTools){let a=e.pendingTools.get(s);a&&(i||(i=a.toolName),o===void 0&&(o=a.toolInput),e.pendingTools.delete(s))}i?await this.sendObservation(e,{toolName:i,toolInput:o,toolResponse:n,toolUseId:s}):d.debug("TRANSCRIPT","Dropping tool_result with no resolvable toolName",{sessionId:e.sessionId,toolId:s})}async sendObservation(e,r){let s=typeof r.toolName=="string"?r.toolName:void 0;if(!s)return;let i=await Tn({contentSessionId:e.sessionId,cwd:e.cwd??process.cwd(),toolName:s,toolInput:this.maybeParseJson(r.toolInput),toolResponse:this.maybeParseJson(r.toolResponse),platformSource:e.platformSource,toolUseId:typeof r.toolUseId=="string"?r.toolUseId:void 0});if(!i.ok)throw new Error(`ingestObservation failed: ${i.reason}`)}async sendFileEdit(e,r){let s=typeof r.filePath=="string"?r.filePath:void 0;s&&await gn.execute({sessionId:e.sessionId,cwd:e.cwd??process.cwd(),filePath:s,edits:Array.isArray(r.edits)?r.edits:void 0,platform:e.platformSource})}maybeParseJson(e){if(typeof e!="string")return e;let r=e.trim();if(!r||!(r.startsWith("{")||r.startsWith("[")))return e;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),e}}parseApplyPatchFiles(e){let r=[],s=e.split(`
27
+ `);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(e,r){await this.queueSummary(e),await this.updateContext(e,r),e.pendingTools?.clear();let s=this.getSessionKey(r,e.sessionId);this.sessions.delete(s)}async queueSummary(e){if(!await Kt())return;let s=e.lastAssistantMessage??"",i=JSON.stringify({contentSessionId:e.sessionId,last_assistant_message:s,platformSource:e.platformSource});try{await he("/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(e,r){if(!r.context||r.context.mode!=="agents"||qr(r)||!await Kt())return;let i=e.cwd??r.workspace;if(!i)return;let o=Me(i).allProjects.join(","),a=`/api/context/inject?projects=${encodeURIComponent(o)}`,l=N(r.context.path??`${i}/AGENTS.md`),c=nt.default.resolve(l),u=[nt.default.resolve(i),nt.default.resolve(v)];if(!u.some(m=>c.startsWith(m+nt.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 he(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&&(En(l,f),d.debug("TRANSCRIPT","Updated AGENTS.md context",{agentsPath:l,watch:r.name}))}};var Gr=class{constructor(e,r,s,i){this.filePath=e;this.onLine=s;this.onOffset=i;this.tailState={offset:r,partial:""}}filePath;onLine;onOffset;watcher=null;tailState;start(){this.readNewData().catch(()=>{}),this.watcher=(0,x.watch)(this.filePath,{persistent:!0},()=>{this.readNewData().catch(()=>{})})}close(){this.watcher?.close(),this.watcher=null}poke(){this.readNewData().catch(()=>{})}async readNewData(){if(!(0,x.existsSync)(this.filePath))return;let e=0;try{e=(0,x.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(e<this.tailState.offset&&(this.tailState.offset=0),e===this.tailState.offset)return;let r=(0,x.createReadStream)(this.filePath,{start:this.tailState.offset,end:e-1,encoding:"utf8"}),s="";for await(let o of r)s+=o;this.tailState.offset=e,this.onOffset(this.tailState.offset);let n=(this.tailState.partial+s).split(`
28
+ `);this.tailState.partial=n.pop()??"";for(let o of n){let a=o.trim();a&&await this.onLine(a)}}},er=class{constructor(e,r){this.config=e;this.statePath=r;this.state=li(r)}config;statePath;processor=new Zt;tailers=new Map;state;rootWatchers=[];async start(){for(let e of this.config.watches)await this.setupWatch(e)}stop(){for(let e of this.tailers.values())e.close();this.tailers.clear();for(let e of this.rootWatchers)e.close();this.rootWatchers=[]}async setupWatch(e){let r=this.resolveSchema(e);if(!r){d.warn("TRANSCRIPT","Missing schema for watch",{watch:e.name});return}let s=N(e.path),i=this.resolveWatchFiles(s);for(let o of i)await this.addTailer(o,e,r);let n=this.deepestNonGlobAncestor(s);if(!n||!(0,x.existsSync)(n)){d.debug("TRANSCRIPT","Watch root does not exist, skipping fs.watch",{watch:e.name,watchRoot:n});return}try{let o=(0,x.watch)(n,{recursive:!0,persistent:!0},(a,l)=>{if(!l)return;let c=(0,J.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,e,r)});this.rootWatchers.push(o),d.info("TRANSCRIPT","Watching transcript root recursively",{watch:e.name,watchRoot:n})}catch(o){d.warn("TRANSCRIPT","Failed to start recursive fs.watch on transcript root",{watch:e.name,watchRoot:n},o instanceof Error?o:void 0)}}deepestNonGlobAncestor(e){if(!this.hasGlob(e)){if((0,x.existsSync)(e))try{return(0,x.statSync)(e).isDirectory()?e:(0,J.resolve)(e,"..")}catch{return(0,J.resolve)(e,"..")}return e}let r=e.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(J.sep)}resolveSchema(e){return typeof e.schema=="string"?this.config.schemas?.[e.schema]??null:e.schema}resolveWatchFiles(e){if(this.hasGlob(e))return et(this.normalizeGlobPattern(e),{nodir:!0,absolute:!0});if((0,x.existsSync)(e))try{if((0,x.statSync)(e).isDirectory()){let s=(0,J.join)(e,"**","*.jsonl");return et(this.normalizeGlobPattern(s),{nodir:!0,absolute:!0})}return[e]}catch(r){return d.debug("WORKER","Failed to stat watch path",{path:e},r instanceof Error?r:void 0),[]}return[]}normalizeGlobPattern(e){return e.replace(/\\/g,"/")}hasGlob(e){return/[*?[\]{}()]/.test(e)}async addTailer(e,r,s){if(this.tailers.has(e))return;let i=this.extractSessionIdFromPath(e),n=this.state.offsets[e]??0;if(n===0&&r.startAtEnd)try{n=(0,x.statSync)(e).size}catch(a){d.debug("WORKER","Failed to stat file for startAtEnd offset",{file:e},a instanceof Error?a:void 0),n=0}let o=new Gr(e,n,async a=>{await this.handleLine(a,r,s,e,i)},a=>{this.state.offsets[e]=a,ci(this.statePath,this.state)});o.start(),this.tailers.set(e,o),d.info("TRANSCRIPT","Watching transcript file",{file:e,watch:r.name,schema:s.name})}async handleLine(e,r,s,i,n){try{let o=JSON.parse(e);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,J.basename)(i)},o):d.warn("TRANSCRIPT","Failed to parse transcript line (non-Error thrown)",{watch:r.name,file:(0,J.basename)(i),error:String(o)})}}extractSessionIdFromPath(e){let r=e.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 Kr(t,e){let r=t.indexOf(e);return r===-1?null:t[r+1]??null}async function Mn(t,e){switch(t){case"init":{let r=Kr(e,"--config")??De;return dt(r),console.log(`Created sample config: ${N(r)}`),0}case"watch":{let r=Kr(e,"--config")??De,s;try{s=$e(r)}catch(a){if(a instanceof Error&&a.message.includes("not found"))dt(r),console.log(`Created sample config: ${N(r)}`),s=$e(r);else throw a}let i=N(s.stateFile??ht),n=new er(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=Kr(e,"--config")??De;try{$e(r)}catch(s){if(s instanceof Error&&s.message.includes("not found"))dt(r),console.log(`Created sample config: ${N(r)}`),$e(r);else throw s}return console.log(`Config OK: ${N(r)}`),0}default:return console.log("Usage: claude-mem transcript <init|watch|validate> [--config <path>]"),1}}var Ul=process.argv[2],Fl=process.argv.slice(3);Mn(Ul,Fl).then(t=>{process.exit(t)}).catch(t=>{console.error(t),process.exit(1)});