claude-mem 13.9.2 → 13.9.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.codex-plugin/plugin.json +1 -1
- package/dist/npx-cli/index.js +401 -406
- package/dist/opencode-plugin/index.js +1 -1
- package/openclaw/openclaw.plugin.json +1 -1
- package/package.json +8 -32
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/.codex-plugin/plugin.json +1 -1
- package/plugin/bun.lock +0 -3
- package/plugin/package.json +1 -2
- package/plugin/scripts/context-generator.cjs +256 -411
- package/plugin/scripts/mcp-server.cjs +61 -61
- package/plugin/scripts/server-service.cjs +152 -163
- package/plugin/scripts/transcript-watcher.cjs +20 -22
- package/plugin/scripts/worker-service.cjs +555 -801
- package/plugin/ui/viewer-bundle.js +13 -13
- package/plugin/ui/viewer.html +1 -744
|
@@ -1,28 +1,26 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
-
"use strict";var
|
|
3
|
-
`)?
|
|
4
|
-
`),e.skipExit||process.exit(2)}var
|
|
5
|
-
${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let
|
|
6
|
-
${
|
|
7
|
-
${
|
|
8
|
-
`+JSON.stringify(
|
|
9
|
-
`,"utf8")}catch(
|
|
10
|
-
|
|
11
|
-
`)}
|
|
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 ar;var Gn={};function Ln(){return typeof __dirname<"u"?__dirname:(0,y.dirname)((0,Xr.fileURLToPath)(Gn.url))}var Vl=Ln();function De(){if(process.env.CLAUDE_MEM_DATA_DIR)return process.env.CLAUDE_MEM_DATA_DIR;let t=(0,y.join)((0,lr.homedir)(),".claude-mem"),e=(0,y.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=De(),ot=process.env.CLAUDE_CONFIG_DIR||(0,y.join)((0,lr.homedir)(),".claude"),at=(0,y.join)(ot,"plugins","marketplaces","thedotmack"),Nn=(0,y.join)(v,"archives"),Un=(0,y.join)(v,"logs"),Fn=(0,y.join)(v,"trash"),Wn=(0,y.join)(v,"backups"),jn=(0,y.join)(v,"modes"),lt=(0,y.join)(v,"settings.json"),ql=(0,y.join)(v,"claude-mem.db"),Hn=(0,y.join)(v,"vector-db"),ct=(0,y.join)(v,"observer-sessions"),$n=(0,y.basename)(ct),Xl=(0,y.join)(ot,"settings.json"),Ql=(0,y.join)(ot,"commands"),Zl=(0,y.join)(ot,"CLAUDE.md");var A={dataDir:()=>v,workerPid:()=>(0,y.join)(v,"worker.pid"),serverPid:()=>(0,y.join)(v,".server-beta.pid"),serverPort:()=>(0,y.join)(v,".server-beta.port"),serverRuntime:()=>(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:()=>Un,archives:()=>Nn,trash:()=>Fn,backups:()=>Wn,modes:()=>jn,vectorDb:()=>Hn,observerSessions:()=>ct};var Pe=A.transcriptsConfig(),ut=A.transcriptsState();var Bn={version:1,schemas:{},watches:[],stateFile:ut};function Kn(t){let e=typeof t.schema=="string"?t.schema:t.schema?.name;if(!(t.name==="codex"||e==="codex")||!t.path)return!1;let s=N(t.path).replace(/\\/g,"/"),i=(0,$e.join)((0,cr.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&&Kn(t)}function N(t){return t&&(t.startsWith("~")?(0,$e.join)((0,cr.homedir)(),t.slice(1)):t)}function Ge(t=Pe){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=ut),s}function ht(t=Pe){let e=N(t),r=(0,$e.dirname)(e);(0,ne.existsSync)(r)||(0,ne.mkdirSync)(r,{recursive:!0}),(0,ne.writeFileSync)(e,JSON.stringify(Bn,null,2))}var x=require("fs"),J=require("path");var xs=require("node:url"),Ne=require("node:path"),Ws=require("node:url"),Q=require("fs"),Qo=V(require("node:fs"),1),Ee=require("node:fs/promises"),kt=require("node:events"),yr=V(require("node:stream"),1),js=require("node:string_decoder"),bs=(t,e,r)=>{let s=t instanceof RegExp?Zr(t,r):t,i=e instanceof RegExp?Zr(e,r):e,n=s!==null&&i!=null&&Yn(s,i,r);return n&&{start:n[0],end:n[1],pre:r.slice(0,n[0]),body:r.slice(n[0]+s.length,n[1]),post:r.slice(n[1]+i.length)}},Zr=(t,e)=>{let r=e.match(t);return r?r[0]:null},Yn=(t,e,r)=>{let s,i,n,o,a,l=r.indexOf(t),c=r.indexOf(e,l+1),u=l;if(l>=0&&c>0){if(t===e)return[l,c];for(s=[],n=r.length;u>=0&&!a;){if(u===l)s.push(u),l=r.indexOf(t,u+1);else if(s.length===1){let h=s.pop();h!==void 0&&(a=[h,c])}else i=s.pop(),i!==void 0&&i<n&&(n=i,o=c),c=r.indexOf(e,u+1);u=l<c&&l>=0?l:c}s.length&&o!==void 0&&(a=[n,o])}return a},vs="\0SLASH"+Math.random()+"\0",Ts="\0OPEN"+Math.random()+"\0",wr="\0CLOSE"+Math.random()+"\0",Ms="\0COMMA"+Math.random()+"\0",ks="\0PERIOD"+Math.random()+"\0",zn=new RegExp(vs,"g"),Jn=new RegExp(Ts,"g"),Vn=new RegExp(wr,"g"),qn=new RegExp(Ms,"g"),Xn=new RegExp(ks,"g"),Qn=/\\\\/g,Zn=/\\{/g,eo=/\\}/g,to=/\\,/g,ro=/\\./g,so=1e5;function ur(t){return isNaN(t)?t.charCodeAt(0):parseInt(t,10)}function io(t){return t.replace(Qn,vs).replace(Zn,Ts).replace(eo,wr).replace(to,Ms).replace(ro,ks)}function no(t){return t.replace(zn,"\\").replace(Jn,"{").replace(Vn,"}").replace(qn,",").replace(Xn,".")}function Rs(t){if(!t)return[""];let e=[],r=bs("{","}",t);if(!r)return t.split(",");let{pre:s,body:i,post:n}=r,o=s.split(",");o[o.length-1]+="{"+i+"}";let a=Rs(n);return n.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),e.push.apply(e,o),e}function oo(t,e={}){if(!t)return[];let{max:r=so}=e;return t.slice(0,2)==="{}"&&(t="\\{\\}"+t.slice(2)),qe(io(t),r,!0).map(no)}function ao(t){return"{"+t+"}"}function lo(t){return/^-?0\d/.test(t)}function co(t,e){return t<=e}function uo(t,e){return t>=e}function qe(t,e,r){let s=[],i=bs("{","}",t);if(!i)return[t];let n=i.pre,o=i.post.length?qe(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+wr+i.post,qe(t,e,!0)):[t];let h;if(c)h=i.body.split(/\.\./);else if(h=Rs(i.body),h.length===1&&h[0]!==void 0&&(h=qe(h[0],e,!1).map(ao),h.length===1))return o.map(f=>i.pre+h[0]+f);let p;if(c&&h[0]!==void 0&&h[1]!==void 0){let f=ur(h[0]),m=ur(h[1]),g=Math.max(h[0].length,h[1].length),w=h.length===3&&h[2]!==void 0?Math.abs(ur(h[2])):1,S=co;m<f&&(w*=-1,S=uo);let E=h.some(lo);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 fe=new Array(T+1).join("0");_<0?b="-"+fe+b.slice(1):b=fe+b}}p.push(b)}}else{p=[];for(let f=0;f<h.length;f++)p.push.apply(p,qe(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 bt=t=>{if(typeof t!="string")throw new TypeError("invalid pattern");if(t.length>65536)throw new TypeError("pattern is too long")},ho={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},Be=t=>t.replace(/[[\]\\-]/g,"\\$&"),po=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),es=t=>t.join(""),fo=(t,e)=>{let r=e;if(t.charAt(r)!=="[")throw new Error("not in a brace expression");let s=[],i=[],n=r+1,o=!1,a=!1,l=!1,c=!1,u=r,h="";e:for(;n<t.length;){let m=t.charAt(n);if((m==="!"||m==="^")&&n===r+1){c=!0,n++;continue}if(m==="]"&&o&&!l){u=n+1;break}if(o=!0,m==="\\"&&!l){l=!0,n++;continue}if(m==="["&&!l){for(let[g,[w,S,E]]of Object.entries(ho))if(t.startsWith(g,n)){if(h)return["$.",!1,t.length-r,!0];n+=g.length,E?i.push(w):s.push(w),a=a||S;continue e}}if(l=!1,h){m>h?s.push(Be(h)+"-"+Be(m)):m===h&&s.push(Be(m)),h="",n++;continue}if(t.startsWith("-]",n+1)){s.push(Be(m+"-")),n+=2;continue}if(t.startsWith("-",n+1)){h=m,n+=2;continue}s.push(Be(m)),n++}if(u<n)return["",!1,0,!1];if(!s.length&&!i.length)return["$.",!1,t.length-r,!0];if(i.length===0&&s.length===1&&/^\\?.$/.test(s[0])&&!c){let m=s[0].length===2?s[0].slice(-1):s[0];return[po(m),!1,u-r,!1]}let p="["+(c?"^":"")+es(s)+"]",f="["+(c?"":"^")+es(i)+"]";return[s.length&&i.length?"("+p+"|"+f+")":s.length?p:f,a,u-r,!0]},Le=(t,{windowsPathsNoEscape:e=!1,magicalBraces:r=!0}={})=>r?e?t.replace(/\[([^\/\\])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):e?t.replace(/\[([^\/\\{}])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1"),mo=new Set(["!","?","+","*","@"]),ts=t=>mo.has(t),go="(?!(?:^|/)\\.\\.?(?:$|/))",dt="(?!\\.)",So=new Set(["[","."]),Eo=new Set(["..","."]),wo=new Set("().*{}+?[]^$\\!"),_o=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),_r="[^/]",rs=_r+"*?",ss=_r+"+?",Cs=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&&ts(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(ts(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&&Eo.has(this.#i[0]))){let p=So,f=r&&p.has(c.charAt(0))||c.startsWith("\\.")&&p.has(c.charAt(2))||c.startsWith("\\.\\.")&&p.has(c.charAt(4)),m=!r&&!e&&p.has(c.charAt(0));u=f?go:m?dt:""}let h="";return this.isEnd()&&this.#e.#u&&this.#o?.type==="!"&&(h="(?:$|\\/)"),[u+c+h,Le(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,Le(this.toString()),!1,!1]}let o=!s||e||r||!dt?"":this.#p(!0);o===n&&(o=""),o&&(n=`(?:${n})(?:${o})*?`);let a="";if(this.type==="!"&&this.#h)a=(this.isStart()&&!r?dt:"")+ss;else{let l=this.type==="!"?"))"+(this.isStart()&&!r&&!e?dt:"")+rs+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;a=i+n+l}return[a,Le(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+=(wo.has(c)?"\\":"")+c;continue}if(c==="*"){if(a)continue;a=!0,n+=s&&/^[*]+$/.test(e)?ss:rs,r=!0;continue}else a=!1;if(c==="\\"){l===e.length-1?n+="\\\\":i=!0;continue}if(c==="["){let[u,h,p,f]=fo(e,l);if(p){n+=u,o=o||h,l+=p-1,r=r||f;continue}}if(c==="?"){n+=_r,r=!0;continue}n+=_o(c)}return[n,Le(e),!!r,o]}},As=(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={})=>(bt(e),!r.nocomment&&e.charAt(0)==="#"?!1:new Se(e,r).match(t)),yo=/^\*+([^+@!?\*\[\(]*)$/,bo=t=>e=>!e.startsWith(".")&&e.endsWith(t),vo=t=>e=>e.endsWith(t),To=t=>(t=t.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(t)),Mo=t=>(t=t.toLowerCase(),e=>e.toLowerCase().endsWith(t)),ko=/^\*+\.\*+$/,Ro=t=>!t.startsWith(".")&&t.includes("."),Co=t=>t!=="."&&t!==".."&&t.includes("."),Ao=/^\.\*+$/,Oo=t=>t!=="."&&t!==".."&&t.startsWith("."),Do=/^\*+$/,Po=t=>t.length!==0&&!t.startsWith("."),Io=t=>t.length!==0&&t!=="."&&t!=="..",xo=/^\?+([^+@!?\*\[\(]*)?$/,Lo=([t,e=""])=>{let r=Os([t]);return e?(e=e.toLowerCase(),s=>r(s)&&s.toLowerCase().endsWith(e)):r},No=([t,e=""])=>{let r=Ds([t]);return e?(e=e.toLowerCase(),s=>r(s)&&s.toLowerCase().endsWith(e)):r},Uo=([t,e=""])=>{let r=Ds([t]);return e?s=>r(s)&&s.endsWith(e):r},Fo=([t,e=""])=>{let r=Os([t]);return e?s=>r(s)&&s.endsWith(e):r},Os=([t])=>{let e=t.length;return r=>r.length===e&&!r.startsWith(".")},Ds=([t])=>{let e=t.length;return r=>r.length===e&&r!=="."&&r!==".."},Ps=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",is={win32:{sep:"\\"},posix:{sep:"/"}},Wo=Ps==="win32"?is.win32.sep:is.posix.sep;I.sep=Wo;var P=Symbol("globstar **");I.GLOBSTAR=P;var jo="[^/]",Ho=jo+"*?",$o="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",Go="(?:(?!(?:\\/|^)\\.).)*?",Bo=(t,e={})=>r=>I(r,t,e);I.filter=Bo;var W=(t,e={})=>Object.assign({},t,e),Ko=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=Ko;var Is=(t,e={})=>(bt(t),e.nobrace||!/\{(?:(?!\{).)*\}/.test(t)?[t]:oo(t,{max:e.braceExpandMax}));I.braceExpand=Is;var Yo=(t,e={})=>new Se(t,e).makeRe();I.makeRe=Yo;var zo=(t,e,r={})=>{let s=new Se(e,r);return t=t.filter(i=>s.match(i)),s.options.nonull&&!t.length&&t.push(e),t};I.match=zo;var ns=/[?*]|[+@!]\(.*?\)|\[|\]/,Jo=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Se=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(t,e={}){bt(t),e=e||{},this.options=e,this.pattern=t,this.platform=e.platform||Ps,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]==="?"||!ns.test(i[2]))&&!ns.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===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
|
-
|
|
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){bt(t);let e=this.options;if(t==="**")return P;if(t==="")return"";let r,s=null;(r=t.match(Do))?s=e.dot?Io:Po:(r=t.match(yo))?s=(e.nocase?e.dot?Mo:To:e.dot?vo:bo)(r[1]):(r=t.match(xo))?s=(e.nocase?e.dot?No:Lo:e.dot?Uo:Fo)(r):(r=t.match(ko))?s=e.dot?Co:Ro:(r=t.match(Ao))&&(s=Oo);let i=Cs.fromGlob(t,this.options).toMMPattern();return s&&typeof i=="object"&&Reflect.defineProperty(i,"test",{value:s}),i}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let t=this.set;if(!t.length)return this.regexp=!1,this.regexp;let e=this.options,r=e.noglobstar?Ho:e.dot?$o: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"?Jo(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=Cs;I.Minimatch=Se;I.escape=As;I.unescape=Le;var Vo=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Ls=new Set,Er=typeof process=="object"&&process?process:{},Ns=(t,e,r,s)=>{typeof Er.emitWarning=="function"?Er.emitWarning(t,e,r,s):console.error(`[${r}] ${e}: ${t}`)},vt=globalThis.AbortController,os=globalThis.AbortSignal;if(typeof vt>"u"){os=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,s){this._onabort.push(s)}},vt=class{constructor(){e()}signal=new os;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=Er.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,Ns("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var qo=t=>!Ls.has(t),ge=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),Us=t=>ge(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 Xe{heap;length;static#e=!1;static create(e){let r=Us(e);if(!r)return[];Xe.#e=!0;let s=new Xe(e,r);return Xe.#e=!1,s}constructor(e,r){if(!Xe.#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]}},Mt=class Fs{#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;#C;#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.#C,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.#_}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:fe,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??Vo,r!==0&&!ge(r))throw new TypeError("max option must be a nonnegative integer");let Oe=r?Us(r):Array;if(!Oe)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 Oe(r),this.#y=new Oe(r),this.#w=0,this.#f=0,this.#C=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=!!_,this.allowStaleOnFetchRejection=!!T,this.allowStaleOnFetchAbort=!!fe,this.ignoreFetchAbort=!!Ce,this.maxEntrySize!==0){if(this.#r!==0&&!ge(this.#r))throw new TypeError("maxSize must be a positive integer if specified");if(!ge(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#B()}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!b,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!a,this.ttlResolution=ge(i)||i===0?i:1,this.ttlAutopurge=!!n,this.ttl=s||0,this.ttl){if(!ge(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 rr="LRU_CACHE_UNBOUNDED";qo(rr)&&(Ls.add(rr),Ns("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",rr,Fs))}}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.#A(this.#l[o],"expire")},a+1);c.unref&&c.unref(),s[o]=c}},this.#R=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}}#R=()=>{};#I=()=>{};#F=()=>{};#v=()=>!1;#B(){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(!ge(i))if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(i=n(s,r),!ge(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.#j(r)||((e||!this.#v(r))&&(yield r),r===this.#w));)r=this.#y[r]}*#D({allowStale:e=this.allowStale}={}){if(this.#a)for(let r=this.#w;!(!this.#j(r)||((e||!this.#v(r))&&(yield r),r===this.#f));)r=this.#p[r]}#j(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.#A(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.#A(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.#C.length!==0?this.#C.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.#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.#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.#C.push(r)),this.#a===1?(this.#w=this.#f=0,this.#C.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.#R(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 vt,{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.#A(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.#A(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 vt}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.#$(e,b,_,g);return T.__returned=T}else{let T=this.#s[b];if(this.#c(T)){let Oe=s&&T.__staleWhileFetching!==void 0;return S&&(S.fetch="inflight",Oe&&(S.returnedStale=!0)),Oe?T.__staleWhileFetching:T.__returned=T}let fe=this.#v(b);if(!w&&!fe)return S&&(S.fetch="hit"),this.#N(b),i&&this.#R(b),S&&this.#I(S,b),T;let Ce=this.#$(e,b,_,g),Ae=Ce.__staleWhileFetching!==void 0&&s;return S&&(S.fetch=fe?"stale":"refresh",Ae&&fe&&(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.#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.#A(e,"expire"),o&&s&&(o.returnedStale=!0),s?l:void 0)):(o&&(o.get="hit"),c?l.__staleWhileFetching:(this.#N(a),i&&this.#R(a),l))}else o&&(o.get="miss")}#G(e,r){this.#y[r]=e,this.#p[e]=r}#N(e){e!==this.#f&&(e===this.#w?this.#w=this.#p[e]:this.#G(this.#y[e],this.#p[e]),this.#G(this.#f,e),this.#f=e)}delete(e){return this.#A(e,"delete")}#A(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.#C.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.#C.length=0,this.#d=0,this.#a=0,this.#t&&this.#m){let r=this.#m,s;for(;s=r?.shift();)this.#o?.(...s)}}},as=typeof process=="object"&&process?process:{stdout:null,stderr:null},Zo=t=>!!t&&typeof t=="object"&&(t instanceof Tt||t instanceof yr.default||ea(t)||ta(t)),ea=t=>!!t&&typeof t=="object"&&t instanceof kt.EventEmitter&&typeof t.pipe=="function"&&t.pipe!==yr.default.Writable.prototype.pipe,ta=t=>!!t&&typeof t=="object"&&t instanceof kt.EventEmitter&&typeof t.write=="function"&&typeof t.end=="function",oe=Symbol("EOF"),ae=Symbol("maybeEmitEnd"),me=Symbol("emittedEnd"),pt=Symbol("emittingEnd"),Ke=Symbol("emittedError"),ft=Symbol("closed"),ls=Symbol("read"),mt=Symbol("flush"),cs=Symbol("flushChunk"),B=Symbol("encoding"),Ie=Symbol("decoder"),k=Symbol("flowing"),Ye=Symbol("paused"),xe=Symbol("resume"),R=Symbol("buffer"),D=Symbol("pipes"),C=Symbol("bufferLength"),hr=Symbol("bufferPush"),gt=Symbol("bufferShift"),O=Symbol("objectMode"),M=Symbol("destroyed"),dr=Symbol("error"),pr=Symbol("emitData"),us=Symbol("emitEnd"),fr=Symbol("emitEnd2"),q=Symbol("async"),mr=Symbol("abort"),St=Symbol("aborted"),ze=Symbol("signal"),ye=Symbol("dataListeners"),U=Symbol("discarded"),Je=t=>Promise.resolve().then(t),ra=t=>t(),sa=t=>t==="end"||t==="finish"||t==="prefinish",ia=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,na=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Hs=class{src;dest;opts;ondrain;constructor(t,e,r){this.src=t,this.dest=e,this.opts=r,this.ondrain=()=>t[xe](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},oa=class extends Hs{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,r){super(t,e,r),this.proxyErrors=s=>this.dest.emit("error",s),t.on("error",this.proxyErrors)}},aa=t=>!!t.objectMode,la=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Tt=class extends kt.EventEmitter{[k]=!1;[Ye]=!1;[D]=[];[R]=[];[O];[B];[q];[Ie];[oe]=!1;[me]=!1;[pt]=!1;[ft]=!1;[Ke]=null;[C]=0;[M]=!1;[ze];[St]=!1;[ye]=0;[U]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");aa(e)?(this[O]=!0,this[B]=null):la(e)?(this[B]=e.encoding,this[O]=!1):(this[O]=!1,this[B]=null),this[q]=!!e.async,this[Ie]=this[B]?new js.StringDecoder(this[B]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[R]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[D]});let{signal:r}=e;r&&(this[ze]=r,r.aborted?this[mr]():r.addEventListener("abort",()=>this[mr]()))}get bufferLength(){return this[C]}get encoding(){return this[B]}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}[mr](){this[St]=!0,this.emit("abort",this[ze]?.reason),this.destroy(this[ze]?.reason)}get aborted(){return this[St]}set aborted(t){}write(t,e,r){if(this[St])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]?Je:ra;if(!this[O]&&!Buffer.isBuffer(t)){if(na(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(ia(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[O]?(this[k]&&this[C]!==0&&this[mt](!0),this[k]?this.emit("data",t):this[hr](t),this[C]!==0&&this.emit("readable"),r&&s(r),this[k]):t.length?(typeof t=="string"&&!(e===this[B]&&!this[Ie]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[B]&&(t=this[Ie].write(t)),this[k]&&this[C]!==0&&this[mt](!0),this[k]?this.emit("data",t):this[hr](t),this[C]!==0&&this.emit("readable"),r&&s(r),this[k]):(this[C]!==0&&this.emit("readable"),r&&s(r),this[k])}read(t){if(this[M])return null;if(this[U]=!1,this[C]===0||t===0||t&&t>this[C])return this[ae](),null;this[O]&&(t=null),this[R].length>1&&!this[O]&&(this[R]=[this[B]?this[R].join(""):Buffer.concat(this[R],this[C])]);let e=this[ls](t||null,this[R][0]);return this[ae](),e}[ls](t,e){if(this[O])this[gt]();else{let r=e;t===r.length||t===null?this[gt]():typeof r=="string"?(this[R][0]=r.slice(t),e=r.slice(0,t),this[C]-=t):(this[R][0]=r.subarray(t),e=r.subarray(0,t),this[C]-=t)}return this.emit("data",e),!this[R].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[Ye])&&this[ae](),this}[xe](){this[M]||(!this[ye]&&!this[D].length&&(this[U]=!0),this[Ye]=!1,this[k]=!0,this.emit("resume"),this[R].length?this[mt]():this[oe]?this[ae]():this.emit("drain"))}resume(){return this[xe]()}pause(){this[k]=!1,this[Ye]=!0,this[U]=!1}get destroyed(){return this[M]}get flowing(){return this[k]}get paused(){return this[Ye]}[hr](t){this[O]?this[C]+=1:this[C]+=t.length,this[R].push(t)}[gt](){return this[O]?this[C]-=1:this[C]-=this[R][0].length,this[R].shift()}[mt](t=!1){do;while(this[cs](this[gt]())&&this[R].length);!t&&!this[R].length&&!this[oe]&&this.emit("drain")}[cs](t){return this.emit("data",t),this[k]}pipe(t,e){if(this[M])return t;this[U]=!1;let r=this[me];return e=e||{},t===as.stdout||t===as.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[D].push(e.proxyErrors?new oa(this,t,e):new Hs(this,t,e)),this[q]?Je(()=>this[xe]()):this[xe]()),t}unpipe(t){let e=this[D].find(r=>r.dest===t);e&&(this[D].length===1?(this[k]&&this[ye]===0&&(this[k]=!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[k]&&this[xe]();else if(t==="readable"&&this[C]!==0)super.emit("readable");else if(sa(t)&&this[me])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[Ke]){let s=e;this[q]?Je(()=>s.call(this,this[Ke])):s.call(this,this[Ke])}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[k]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[ye]=0,!this[U]&&!this[D].length&&(this[k]=!1)),e}get emittedEnd(){return this[me]}[ae](){!this[pt]&&!this[me]&&!this[M]&&this[R].length===0&&this[oe]&&(this[pt]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[ft]&&this.emit("close"),this[pt]=!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]?(Je(()=>this[pr](r)),!0):this[pr](r);if(t==="end")return this[us]();if(t==="close"){if(this[ft]=!0,!this[me]&&!this[M])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(t==="error"){this[Ke]=r,super.emit(dr,r);let i=!this[ze]||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}[pr](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[ae](),e}[us](){return this[me]?!1:(this[me]=!0,this.readable=!1,this[q]?(Je(()=>this[fr]()),!0):this[fr]())}[fr](){if(this[Ie]){let e=this[Ie].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[B]?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(dr,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(dr,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[R].length=0,this[C]=0;let e=this;return typeof e.close=="function"&&!this[ft]&&e.close(),t?this.emit("error",t):this.emit(M),this}static get isStream(){return Zo}},ca=Q.realpathSync.native,Qe={lstatSync:Q.lstatSync,readdir:Q.readdir,readdirSync:Q.readdirSync,readlinkSync:Q.readlinkSync,realpathSync:ca,promises:{lstat:Ee.lstat,readdir:Ee.readdir,readlink:Ee.readlink,realpath:Ee.realpath}},$s=t=>!t||t===Qe||t===Qo?Qe:{...Qe,...t,promises:{...Qe.promises,...t.promises||{}}},Gs=/^\\\\\?\\([a-z]:)\\?$/i,ua=t=>t.replace(/\//g,"\\").replace(Gs,"$1\\"),ha=/[\\\/]/,H=0,Bs=1,Ks=2,X=4,Ys=6,zs=8,be=10,Js=12,j=15,Ve=~j,gr=16,hs=32,Ze=64,K=128,Et=256,yt=512,ds=Ze|K|yt,da=1023,Sr=t=>t.isFile()?zs:t.isDirectory()?X:t.isSymbolicLink()?be:t.isCharacterDevice()?Ks:t.isBlockDevice()?Ys:t.isSocket()?Js:t.isFIFO()?Bs:H,ps=new Mt({max:2**12}),et=t=>{let e=ps.get(t);if(e)return e;let r=t.normalize("NFKD");return ps.set(t,r),r},fs=new Mt({max:2**12}),wt=t=>{let e=fs.get(t);if(e)return e;let r=et(t.toLowerCase());return fs.set(t,r),r},ms=class extends Mt{constructor(){super({max:256})}},pa=class extends Mt{constructor(t=16*1024){super({maxSize:t,sizeCalculation:e=>e.length+1})}},Vs=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}#C;get ctime(){return this.#C}#m;get birthtime(){return this.#m}#T;#M;#g;#E;#b;#k;#t;#x;#P;#R;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(t,e=H,r,s,i,n,o){this.name=t,this.#T=i?wt(t):et(t),this.#t=e&da,this.nocase=i,this.roots=s,this.root=r||this,this.#x=n,this.#g=o.fullpath,this.#b=o.relative,this.#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).#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&=~gr,e}child(t,e){if(t===""||t===".")return this;if(t==="..")return this.parent||this;let r=this.children(),s=this.nocase?wt(t):et(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,H,{...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&j)===H}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&j)===zs}isDirectory(){return(this.#t&j)===X}isCharacterDevice(){return(this.#t&j)===Ks}isBlockDevice(){return(this.#t&j)===Ys}isFIFO(){return(this.#t&j)===Bs}isSocket(){return(this.#t&j)===Js}isSymbolicLink(){return(this.#t&be)===be}lstatCached(){return this.#t&hs?this:void 0}readlinkCached(){return this.#P}realpathCached(){return this.#R}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&j;return!(t!==H&&t!==be||this.#t&Et||this.#t&K)}calledReaddir(){return!!(this.#t&gr)}isENOENT(){return!!(this.#t&K)}isNamed(t){return this.nocase?this.#T===wt(t):this.#T===et(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|=gr;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)&Ve,this.#B())}#B(){let t=this.children();t.provisional=0;for(let e of t)e.#v()}#U(){this.#t|=yt,this.#L()}#L(){if(this.#t&Ze)return;let t=this.#t;(t&j)===X&&(t&=Ve),this.#t=t|Ze,this.#B()}#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|=Et,t==="ENOENT"&&(e|=K),(t==="EINVAL"||t==="UNKNOWN")&&(e&=Ve),this.#t=e,t==="ENOTDIR"&&this.parent&&this.parent.#L()}#j(t,e){return this.#$(t,e)||this.#H(t,e)}#H(t,e){let r=Sr(t),s=this.newChild(t.name,r,{parent:this}),i=s.#t&j;return i!==X&&i!==be&&i!==H&&(s.#t|=Ze),e.unshift(s),e.provisional++,s}#$(t,e){for(let r=e.provisional;r<e.length;r++){let s=e[r];if((this.nocase?wt(t.name):et(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&Ve|Sr(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.#G(await this.#e.promises.lstat(this.fullpath())),this}catch(t){this.#O(t.code)}}lstatSync(){if((this.#t&K)===0)try{return this.#G(this.#e.lstatSync(this.fullpath())),this}catch(t){this.#O(t.code)}}#G(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.#C=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 _=Sr(t);this.#t=this.#t&Ve|_|hs,_!==H&&_!==X&&_!==be&&(this.#t|=Ze)}#N=[];#A=!1;#K(t){this.#A=!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.#A)return;this.#A=!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.#j(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.#j(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.#j(r,t);this.#F(t)}catch(r){this.#W(r.code),t.provisional=0}return t.slice(0,t.provisional)}canReaddir(){if(this.#t&ds)return!1;let t=j&this.#t;return t===H||t===X||t===be}shouldWalk(t,e){return(this.#t&X)===X&&!(this.#t&ds)&&!t.has(this)&&(!e||e(this))}async realpath(){if(this.#R)return this.#R;if(!((yt|Et|K)&this.#t))try{let t=await this.#e.promises.realpath(this.fullpath());return this.#R=this.resolve(t)}catch{this.#U()}}realpathSync(){if(this.#R)return this.#R;if(!((yt|Et|K)&this.#t))try{let t=this.#e.realpathSync(this.fullpath());return this.#R=this.resolve(t)}catch{this.#U()}}[Vs](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}},qs=class Xs extends L{sep="\\";splitSep=ha;constructor(e,r=H,s,i,n,o,a){super(e,r,s,i,n,o,a)}newChild(e,r=H,s={}){return new Xs(e,r,this.root,this.roots,this.nocase,this.childrenCache(),s)}getRootString(e){return Ne.win32.parse(e).root}getRoot(e){if(e=ua(e.toUpperCase()),e===this.root.name)return this.root;for(let[r,s]of Object.entries(this.roots))if(this.sameRoot(e,r))return this.roots[e]=s;return this.roots[e]=new br(e,this).root}sameRoot(e,r=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(Gs,"$1\\"),e===r}},Qs=class Zs extends L{splitSep="/";sep="/";constructor(e,r=H,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=H,s={}){return new Zs(e,r,this.root,this.roots,this.nocase,this.childrenCache(),s)}},ei=class{root;rootPath;roots;cwd;#e;#r;#n;nocase;#i;constructor(t=process.cwd(),e,r,{nocase:s,childrenCacheSize:i=16*1024,fs:n=Qe}={}){this.#i=$s(n),(t instanceof URL||t.startsWith("file://"))&&(t=(0,Ws.fileURLToPath)(t));let o=e.resolve(t);this.roots=Object.create(null),this.rootPath=this.parseRootPath(o),this.#e=new ms,this.#r=new ms,this.#n=new pa(i);let a=o.substring(this.rootPath.length).split(r);if(a.length===1&&!a[0]&&a.pop(),s===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=s,this.root=this.newRoot(this.#i),this.roots[this.rootPath]=this.root;let l=this.root,c=a.length-1,u=e.sep,h=this.rootPath,p=!1;for(let f of a){let m=c--;l=l.child(f,{relative:new Array(m).fill("..").join(u),relativePosix:new Array(m).fill("..").join("/"),fullpath:h+=(p?"":u)+f}),p=!0}this.cwd=l}depth(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.depth()}childrenCache(){return this.#n}resolve(...t){let e="";for(let i=t.length-1;i>=0;i--){let n=t[i];if(!(!n||n===".")&&(e=e?`${n}/${e}`:n,this.isAbsolute(n)))break}let r=this.#e.get(e);if(r!==void 0)return r;let s=this.cwd.resolve(e).fullpath();return this.#e.set(e,s),s}resolvePosix(...t){let e="";for(let i=t.length-1;i>=0;i--){let n=t[i];if(!(!n||n===".")&&(e=e?`${n}/${e}`:n,this.isAbsolute(n)))break}let r=this.#r.get(e);if(r!==void 0)return r;let s=this.cwd.resolve(e).fullpathPosix();return this.#r.set(e,s),s}relative(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relative()}relativePosix(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relativePosix()}basename(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.name}dirname(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),(t.parent||t).fullpath()}async readdir(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r}=e;if(t.canReaddir()){let s=await t.readdir();return r?s:s.map(i=>i.name)}else return[]}readdirSync(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0}=e;return t.canReaddir()?r?t.readdirSync():t.readdirSync().map(s=>s.name):[]}async lstat(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstat()}lstatSync(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstatSync()}async readlink(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t.withFileTypes,t=this.cwd);let r=await t.readlink();return e?r:r?.fullpath()}readlinkSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t.withFileTypes,t=this.cwd);let r=t.readlinkSync();return e?r:r?.fullpath()}async realpath(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t.withFileTypes,t=this.cwd);let r=await t.realpath();return e?r:r?.fullpath()}realpathSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t.withFileTypes,t=this.cwd);let r=t.realpathSync();return e?r:r?.fullpath()}async walk(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=e,o=[];(!i||i(t))&&o.push(r?t:t.fullpath());let a=new Set,l=(u,h)=>{a.add(u),u.readdirCB((p,f)=>{if(p)return h(p);let m=f.length;if(!m)return h();let g=()=>{--m===0&&h()};for(let w of f)(!i||i(w))&&o.push(r?w:w.fullpath()),s&&w.isSymbolicLink()?w.realpath().then(S=>S?.isUnknown()?S.lstat():S).then(S=>S?.shouldWalk(a,n)?l(S,g):g()):w.shouldWalk(a,n)?l(w,g):g()},!0)},c=t;return new Promise((u,h)=>{l(c,p=>{if(p)return h(p);u(o)})})}walkSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=e,o=[];(!i||i(t))&&o.push(r?t:t.fullpath());let a=new Set([t]);for(let l of a){let c=l.readdirSync();for(let u of c){(!i||i(u))&&o.push(r?u:u.fullpath());let h=u;if(u.isSymbolicLink()){if(!(s&&(h=u.realpathSync())))continue;h.isUnknown()&&h.lstatSync()}h.shouldWalk(a,n)&&a.add(h)}}return o}[Symbol.asyncIterator](){return this.iterate()}iterate(t=this.cwd,e={}){return typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd),this.stream(t,e)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=e;(!i||i(t))&&(yield r?t:t.fullpath());let o=new Set([t]);for(let a of o){let l=a.readdirSync();for(let c of l){(!i||i(c))&&(yield r?c:c.fullpath());let u=c;if(c.isSymbolicLink()){if(!(s&&(u=c.realpathSync())))continue;u.isUnknown()&&u.lstatSync()}u.shouldWalk(o,n)&&o.add(u)}}}stream(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof L||(e=t,t=this.cwd);let{withFileTypes:r=!0,follow:s=!1,filter:i,walkFilter:n}=e,o=new Tt({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 Tt({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[Vs](e)}},br=class extends ei{sep="\\";constructor(t=process.cwd(),e={}){let{nocase:r=!0}=e;super(t,Ne.win32,"\\",{...e,nocase:r}),this.nocase=r;for(let s=this.cwd;s;s=s.parent)s.nocase=this.nocase}parseRootPath(t){return Ne.win32.parse(t).root.toUpperCase()}newRoot(t){return new qs(this.rootPath,X,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")||t.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(t)}},vr=class extends ei{sep="/";constructor(t=process.cwd(),e={}){let{nocase:r=!1}=e;super(t,Ne.posix,"/",{...e,nocase:r}),this.nocase=r}parseRootPath(t){return"/"}newRoot(t){return new Qs(this.rootPath,X,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")}},ti=class extends vr{constructor(t=process.cwd(),e={}){let{nocase:r=!0}=e;super(t,{...e,nocase:r})}},sc=process.platform==="win32"?qs:Qs,fa=process.platform==="win32"?br:process.platform==="darwin"?ti:vr,ma=t=>t.length>=1,ga=t=>t.length>=1,Sa=Symbol.for("nodejs.util.inspect.custom"),ri=class si{#e;#r;#n;length;#i;#o;#_;#S;#u;#a;#d=!0;constructor(e,r,s,i){if(!ma(e))throw new TypeError("empty pattern list");if(!ga(r))throw new TypeError("empty glob list");if(r.length!==e.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=e.length,s<0||s>=this.length)throw new TypeError("index out of range");if(this.#e=e,this.#r=r,this.#n=s,this.#i=i,this.#n===0){if(this.isUNC()){let[n,o,a,l,...c]=this.#e,[u,h,p,f,...m]=this.#r;c[0]===""&&(c.shift(),m.shift());let g=[n,o,a,l,""].join("/"),w=[u,h,p,f,""].join("/");this.#e=[g,...c],this.#r=[w,...m],this.length=this.#e.length}else if(this.isDrive()||this.isAbsolute()){let[n,...o]=this.#e,[a,...l]=this.#r;o[0]===""&&(o.shift(),l.shift());let c=n+"/",u=a+"/";this.#e=[c,...o],this.#r=[u,...l],this.length=this.#e.length}}}[Sa](){return"Pattern <"+this.#r.slice(this.#n).join("/")+">"}pattern(){return this.#e[this.#n]}isString(){return typeof this.#e[this.#n]=="string"}isGlobstar(){return this.#e[this.#n]===P}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 si(this.#e,this.#r,this.#n+1,this.#i),this.#o.#a=this.#a,this.#o.#u=this.#u,this.#o.#S=this.#S,this.#o):this.#o=null}isUNC(){let e=this.#e;return this.#u!==void 0?this.#u:this.#u=this.#i==="win32"&&this.#n===0&&e[0]===""&&e[1]===""&&typeof e[2]=="string"&&!!e[2]&&typeof e[3]=="string"&&!!e[3]}isDrive(){let e=this.#e;return this.#S!==void 0?this.#S:this.#S=this.#i==="win32"&&this.#n===0&&this.length>1&&typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0])}isAbsolute(){let e=this.#e;return this.#a!==void 0?this.#a:this.#a=e[0]===""&&e.length>1||this.isDrive()||this.isUNC()}root(){let e=this.#e[0];return typeof e=="string"&&this.isAbsolute()&&this.#n===0?e:""}checkFollowGlobstar(){return!(this.#n===0||!this.isGlobstar()||!this.#d)}markFollowGlobstar(){return this.#n===0||!this.isGlobstar()||!this.#d?!1:(this.#d=!1,!0)}},Ea=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",gs=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(t,{nobrace:e,nocase:r,noext:s,noglobstar:i,platform:n=Ea}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=n,this.mmopts={dot:!0,nobrace:e,nocase:r,noext:s,noglobstar:i,optimizationLevel:2,platform:n,nocomment:!0,nonegate:!0};for(let o of t)this.add(o)}add(t){let e=new Se(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 ri(s,i,0,this.platform),o=new Se(n.globString(),this.mmopts),a=i[i.length-1]==="**",l=n.isAbsolute();l?this.absolute.push(o):this.relative.push(o),a&&(l?this.absoluteChildren.push(o):this.relativeChildren.push(o))}}ignored(t){let e=t.fullpath(),r=`${e}/`,s=t.relative()||".",i=`${s}/`;for(let n of this.relative)if(n.match(s)||n.match(i))return!0;for(let n of this.absolute)if(n.match(e)||n.match(r))return!0;return!1}childrenIgnored(t){let e=t.fullpath()+"/",r=(t.relative()||".")+"/";for(let s of this.relativeChildren)if(s.match(r))return!0;for(let s of this.absoluteChildren)if(s.match(e))return!0;return!1}},wa=class ii{store;constructor(e=new Map){this.store=e}copy(){return new ii(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()]))}},_a=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)])}},ya=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())}},Ss=class ni{hasWalkedCache;matches=new _a;subwalks=new ya;patterns;follow;dot;opts;constructor(e,r){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=r?r.copy():new wa}processPatterns(e,r){this.patterns=r;let s=r.map(i=>[e,i]);for(let[i,n]of s){this.hasWalkedCache.storeWalked(i,n);let o=n.root(),a=n.isAbsolute()&&this.opts.absolute!==!1;if(o){i=i.resolve(o==="/"&&this.opts.root!==void 0?this.opts.root:o);let h=n.rest();if(h)n=h;else{this.matches.add(i,!0,!1);continue}}if(i.isENOENT())continue;let l,c,u=!1;for(;typeof(l=n.pattern())=="string"&&(c=n.rest());)i=i.resolve(l),n=c,u=!0;if(l=n.pattern(),c=n.rest(),u){if(this.hasWalkedCache.hasWalked(i,n))continue;this.hasWalkedCache.storeWalked(i,n)}if(typeof l=="string"){let h=l===".."||l===""||l===".";this.matches.add(i.resolve(l),a,h);continue}else if(l===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 ni(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))}},ba=(t,e)=>typeof t=="string"?new gs([t],e):Array.isArray(t)?new gs(t,e):t,oi=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#e=[];#r;#n;signal;maxDepth;includeChildMatches;constructor(t,e,r){if(this.patterns=t,this.path=e,this.opts=r,this.#n=!r.posix&&r.platform==="win32"?"\\":"/",this.includeChildMatches=r.includeChildMatches!==!1,(r.ignore||!this.includeChildMatches)&&(this.#r=ba(r.ignore??[],r),!this.includeChildMatches&&typeof this.#r.add!="function")){let s="cannot ignore child matches, ignore lacks add() method.";throw new Error(s)}this.maxDepth=r.maxDepth||1/0,r.signal&&(this.signal=r.signal,this.signal.addEventListener("abort",()=>{this.#e.length=0}))}#i(t){return this.seen.has(t)||!!this.#r?.ignored?.(t)}#o(t){return!!this.#r?.childrenIgnored?.(t)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let t;for(;!this.paused&&(t=this.#e.shift());)t()}onResume(t){this.signal?.aborted||(this.paused?this.#e.push(t):t())}async matchCheck(t,e){if(e&&this.opts.nodir)return;let r;if(this.opts.realpath){if(r=t.realpathCached()||await t.realpath(),!r)return;t=r}let s=t.isUnknown()||this.opts.stat?await t.lstat():t;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let i=await s.realpath();i&&(i.isUnknown()||this.opts.stat)&&await i.lstat()}return this.matchCheckTest(s,e)}matchCheckTest(t,e){return t&&(this.maxDepth===1/0||t.depth()<=this.maxDepth)&&(!e||t.canReaddir())&&(!this.opts.nodir||!t.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!t.isSymbolicLink()||!t.realpathCached()?.isDirectory())&&!this.#i(t)?t:void 0}matchCheckSync(t,e){if(e&&this.opts.nodir)return;let r;if(this.opts.realpath){if(r=t.realpathCached()||t.realpathSync(),!r)return;t=r}let s=t.isUnknown()||this.opts.stat?t.lstatSync():t;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let i=s.realpathSync();i&&(i?.isUnknown()||this.opts.stat)&&i.lstatSync()}return this.matchCheckTest(s,e)}matchFinish(t,e){if(this.#i(t))return;if(!this.includeChildMatches&&this.#r?.add){let i=`${t.relativePosix()}/**`;this.#r.add(i)}let r=this.opts.absolute===void 0?e:this.opts.absolute;this.seen.add(t);let s=this.opts.mark&&t.isDirectory()?this.#n:"";if(this.opts.withFileTypes)this.matchEmit(t);else if(r){let i=this.opts.posix?t.fullpathPosix():t.fullpath();this.matchEmit(i+s)}else{let i=this.opts.posix?t.relativePosix():t.relative(),n=this.opts.dotRelative&&!i.startsWith(".."+this.#n)?"."+this.#n:"";this.matchEmit(i?n+i+s:"."+s)}}async match(t,e,r){let s=await this.matchCheck(t,r);s&&this.matchFinish(s,e)}matchSync(t,e,r){let s=this.matchCheckSync(t,r);s&&this.matchFinish(s,e)}walkCB(t,e,r){this.signal?.aborted&&r(),this.walkCB2(t,e,new Ss(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 Ss(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()}},Es=class extends oi{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}},ws=class extends oi{results;constructor(t,e,r){super(t,e,r),this.results=new Tt({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(t){this.results.write(t),this.results.flowing||this.pause()}stream(){let t=this.path;return t.isUnknown()?t.lstat().then(()=>{this.walkCB(t,this.patterns,()=>this.results.end())}):this.walkCB(t,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}},va=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",ve=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,xs.fileURLToPath)(e.cwd)):this.cwd="",this.cwd=e.cwd||"",this.root=e.root,this.magicalBraces=!!e.magicalBraces,this.nobrace=!!e.nobrace,this.noext=!!e.noext,this.realpath=!!e.realpath,this.absolute=e.absolute,this.includeChildMatches=e.includeChildMatches!==!1,this.noglobstar=!!e.noglobstar,this.matchBase=!!e.matchBase,this.maxDepth=typeof e.maxDepth=="number"?e.maxDepth:1/0,this.stat=!!e.stat,this.ignore=e.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof t=="string"&&(t=[t]),this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(t=t.map(a=>a.replace(/\\/g,"/"))),this.matchBase){if(e.noglobstar)throw new TypeError("base matching requires globstar");t=t.map(a=>a.includes("/")?a:`./**/${a}`)}if(this.pattern=t,this.platform=e.platform||va,this.opts={...e,platform:this.platform},e.scurry){if(this.scurry=e.scurry,e.nocase!==void 0&&e.nocase!==e.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let a=e.platform==="win32"?br:e.platform==="darwin"?ti:e.platform?vr:fa;this.scurry=new a(this.cwd,{nocase:e.nocase,fs:e.fs})}this.nocase=this.scurry.nocase;let r=this.platform==="darwin"||this.platform==="win32",s={braceExpandMax:1e4,...e,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:r,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},i=this.pattern.map(a=>new Se(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 ri(a,c,0,this.platform)})}async walk(){return[...await new Es(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return[...new Es(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new ws(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 ws(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}},Ta=(t,e={})=>{Array.isArray(t)||(t=[t]);for(let r of t)if(new Se(r,e).hasMagic())return!0;return!1};function Rt(t,e={}){return new ve(t,e).streamSync()}function ai(t,e={}){return new ve(t,e).stream()}function tt(t,e={}){return new ve(t,e).walkSync()}async function _s(t,e={}){return new ve(t,e).walk()}function Ct(t,e={}){return new ve(t,e).iterateSync()}function li(t,e={}){return new ve(t,e).iterate()}var Ma=Rt,ka=Object.assign(ai,{sync:Rt}),Ra=Ct,Ca=Object.assign(li,{sync:Ct}),Aa=Object.assign(tt,{stream:Rt,iterate:Ct}),ys=Object.assign(_s,{glob:_s,globSync:tt,sync:Aa,globStream:ai,stream:ka,globStreamSync:Rt,streamSync:Ma,globIterate:li,iterate:Ca,globIterateSync:Ct,iterateSync:Ra,Glob:ve,hasMagic:Ta,escape:As,unescape:Le});ys.glob=ys;var le=require("fs"),ci=require("path");function ui(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 hi(t,e){try{let r=(0,ci.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 it=V(require("path"),1);var We=V(require("path"),1),Y=require("fs");var di=require("node:child_process");function At(t,e,r){return(0,di.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},we={SUCCESS:0,FAILURE:1,BLOCKING_ERROR:2,USER_MESSAGE_ONLY:3};function ce(t){return process.platform==="win32"?Math.round(t*$.WINDOWS_MULTIPLIER):t}var Z=require("fs"),rt=require("path"),Tr=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($.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_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_DATA_DIR:(0,rt.join)((0,Tr.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,rt.join)((0,Tr.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_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static 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,rt.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 Ot=null;function ue(){return Ot!==null||(Ot=ee.loadFromFile(lt)),Ot}var Te=require("fs");var Ar=require("child_process");var te=require("fs"),Rr=V(require("path"),1);var Oa=["CLAUDECODE_","CLAUDE_CODE_"],Da=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"]),Pa=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS"]);function Dt(t=process.env){let e={};for(let[r,s]of Object.entries(t))if(s!==void 0){if(Pa.has(r)){e[r]=s;continue}Da.has(r)||Oa.some(i=>r.startsWith(i))||(e[r]=s)}return e}var Ia=5e3,xa=1e3,La=A.supervisorRegistry();function he(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 Pt(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(s=>!he(s.pid)))return;await new Promise(s=>setTimeout(s,100))}}var Na=5e3,pi=new Map;function Ua(t){let e=pi.get(t);if(e&&Date.now()-e.capturedAtMs<Na)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:{...Dt(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 pi.set(t,{token:r,capturedAtMs:Date.now()}),r}function fi(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 Ua(t);try{let e=(0,Ar.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Dt(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 Or(t){if(!t||!he(t.pid))return!1;if(!t.startToken)return!0;let e=fi(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=La){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,te.mkdirSync)(Rr.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"&&kr()}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)he(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)kr();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=>he(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 Pt(i,Ia);let n=i.filter(o=>he(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()+xa;for(;Date.now()<o&&n.filter(l=>he(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"&&kr();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)(Rr.default.dirname(this.registryPath),{recursive:!0}),(0,te.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},Mr=null;function It(){return Mr||(Mr=new Cr),Mr}var Fa=[];function kr(){let t=Fa.shift();t&&t()}var gi=require("child_process"),Ue=require("fs"),Si=require("util");var Wa=(0,Si.promisify)(gi.execFile),ja=A.workerPid();async function Ei(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(!he(o.pid)){t.registry.unregister(o.id);continue}try{await mi(o,"SIGTERM")}catch(a){a instanceof Error?d.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:o.pid,pgid:o.pgid,type:o.type},a):d.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:o.pid,pgid:o.pgid,type:o.type,error:String(a)})}}await Pt(i,5e3);let n=i.filter(o=>he(o.pid));for(let o of n)try{await mi(o,"SIGKILL")}catch(a){a instanceof Error?d.debug("SYSTEM","Failed to force kill child process",{pid:o.pid,pgid:o.pgid,type:o.type},a):d.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:o.pid,pgid:o.pgid,type:o.type,error:String(a)})}await Pt(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);Ha(r,e),t.registry.pruneDeadEntries()}function Ha(t,e){if(!(0,Ue.existsSync)(t))return;let r=null;try{let s=JSON.parse((0,Ue.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,Ue.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 mi(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 $a();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 Wa("taskkill",n,{timeout:$.POWERSHELL_COMMAND,windowsHide:!0})}async function $a(){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 wi=3e4,Fe=null;function Ga(){let e=It().pruneDeadEntries();e>0&&d.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function _i(){Fe===null&&(Fe=setInterval(Ga,wi),Fe.unref(),d.debug("SYSTEM","Health checker started",{intervalMs:wi}))}function yi(){Fe!==null&&(clearInterval(Fe),Fe=null,d.debug("SYSTEM","Health checker stopped"))}var Ba=A.workerPid(),Dr=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(),xt({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,_i()}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}yi(),this.stopPromise=Ei({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}},su=new Dr(It());function xt(t={}){let e=t.pidFilePath??Ba;if(!(0,Te.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,Te.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,Te.rmSync)(e,{force:!0}),"invalid"}return Or(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,Te.rmSync)(e,{force:!0}),"stale")}var Pr=require("path"),Nt=require("fs"),vi=require("crypto");var Lt=require("fs");function bi(t,e){if(!(0,Lt.existsSync)(t))return e;try{return JSON.parse((0,Lt.readFileSync)(t,"utf-8"))}catch(r){throw new Error(`Corrupt JSON file, refusing to overwrite: ${t}: ${r instanceof Error?r.message:String(r)}`)}}var Ti="telemetry.json";function Ka(t){let e=t.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function Ya(t,e){if(Ka(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 Mi(t,e){return Ya(t,e).enabled}function za(){return(0,Pr.join)(De(),Ti)}function Ir(){try{let t=bi(za(),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 Ja(t){let e=De();(0,Nt.mkdirSync)(e,{recursive:!0}),(0,Nt.writeFileSync)((0,Pr.join)(e,Ti),JSON.stringify(t,null,2)+`
|
|
15
|
-
`)}function ki(){let t=Ir();if(t?.installId)return t.installId;let e=(0,vi.randomUUID)();return Ja({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","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","observations_created","total_observations_injected","total_tokens_saved_vs_naive"]),Ri=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>Ri?s.slice(0,Ri):s:(typeof s=="number"&&Number.isFinite(s)||typeof s=="boolean")&&(e[r]=s)}}catch{}return e}var xr=V(require("os"),1),qa="13.9.2",Xa="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",Qa="https://us.i.posthog.com";function Ai(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||Xa}function Oi(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||Qa}var Za=["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 Di(t){let e={};for(let r of Za)t[r]!==void 0&&(e[r]=t[r]);return e}function el(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||xr.default.release().toLowerCase().includes("microsoft")}catch{return!1}}function Pi(){return{version:qa,os:process.platform,os_version:xr.default.release(),is_wsl:el(),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 tl=2e3;async function Ii(t,e,r){try{if(!Mi(process.env,Ir()))return;let s=Ci({...Pi(),...e??{}});if(r?.person?s.$set=Di(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(),tl);try{await fetch(`${Oi()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:i,event:t,distinct_id:ki(),properties:s}),signal:n.signal})}finally{clearTimeout(o)}}catch{}}var Me=V(require("path"),1),Li=require("os"),re=require("fs"),Nr=require("child_process");var vu=A.dataDir(),Tu=A.workerPid();function xi(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function sl(t,e){let r=e==="win32"?`where ${t}`:`which ${t}`,s;try{s=(0,Nr.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 Lr;function Ni(t={}){let e=Object.keys(t).length===0;if(e&&Lr!==void 0)return Lr;let r=il(t);return e&&r!==null&&(Lr=r),r}function il(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(xi(r))return r;let s=t.env??process.env,i=t.homeDirectory??(0,Li.homedir)(),n=t.pathExists??re.existsSync,o=t.lookupInPath??sl,a=e==="win32"?[s.BUN,s.BUN_PATH,Me.default.join(i,".bun","bin","bun.exe"),Me.default.join(i,".bun","bin","bun"),s.USERPROFILE?Me.default.join(s.USERPROFILE,".bun","bin","bun.exe"):void 0,s.LOCALAPPDATA?Me.default.join(s.LOCALAPPDATA,"bun","bun.exe"):void 0,s.LOCALAPPDATA?Me.default.join(s.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[s.BUN,s.BUN_PATH,Me.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&&(xi(c)&&n(c)||c.toLowerCase()==="bun"))return c}return o("bun",e)}var Ui=V(require("path"),1);var Fi=require("fs");async function nl(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 ol(){try{let t=Ui.default.join(at,"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 al(t){try{let e=await nl(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=ol(),r=await al(t);return!r||e==="unknown"?{matches:!0,pluginVersion:e,workerVersion:r}:{matches:e===r,pluginVersion:e,workerVersion:r}}var Ut=require("path"),G=require("fs");var ll=6e4;function ji(){return(0,Ut.join)(De(),"spawn.lock")}function Hi(){let t=ji(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return(0,G.mkdirSync)((0,Ut.dirname)(t),{recursive:!0}),(0,G.writeFileSync)(t,e,{flag:"wx"}),!0}catch(s){if(s?.code!=="EEXIST")return!0;if(r>0)return!1;let n;try{n=(0,G.statSync)(t).mtimeMs}catch{continue}if(Date.now()-n<=ll)return!1;let o;try{o=(0,G.statSync)(t).mtimeMs}catch{continue}if(o!==n)return!1;try{(0,G.unlinkSync)(t)}catch{return!1}}return!1}function $i(){let t=ji();try{if(JSON.parse((0,G.readFileSync)(t,"utf-8")).pid!==process.pid)return;(0,G.unlinkSync)(t)}catch{}}function jr(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=jr("CLAUDE_MEM_HEALTH_TIMEOUT_MS",ce($.HEALTH_CHECK),{min:500,max:3e5}),Xu=jr("CLAUDE_MEM_API_TIMEOUT_MS",ce($.API_REQUEST),{min:500,max:3e5}),zi=jr("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",ce($.HOOK_READINESS_WAIT),{min:0,max:3e5}),cl={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 Ft=null,Wt=null,jt=null,Ht=null;function ul(){return We.default.join(ee.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function $r(){return jt!==null||(jt=ee.loadFromFile(ul())),jt}function Gi(t,e){if(!t)return null;let r=parseInt(t,10);return Number.isFinite(r)&&r>=e.min&&r<=e.max?r:null}function hl(t,e,r){let s=process.env[t];if(s!==void 0){let o=Gi(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=Gi(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(Ft!==null)return Ft;let t=$r();return Ft=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),Ft}function dl(){return Wt!==null||(Wt=$r().CLAUDE_MEM_WORKER_HOST),Wt}function pl(){return Ht!==null||(Ht=hl("CLAUDE_MEM_API_TIMEOUT_MS",ce($.API_REQUEST),cl)),Ht}function fl(t){return`http://${dl()}:${Ji()}${t}`}function de(t,e={}){let r=e.method??"GET",s=e.timeoutMs??pl(),i=fl(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 ml(){return(await de("/api/health",{timeoutMs:Gt})).ok}async function Bi(){return(await de("/api/readiness",{timeoutMs:Gt})).ok}function gl(){let t=[We.default.join(at,"plugin","scripts","worker-service.cjs"),We.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 Sl(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 Ur(t=zi){if(t<=0)try{return await Bi()}catch{return!1}let e=Date.now();for(;Date.now()-e<t;){try{if(await Bi())return!0}catch(s){d.debug("SYSTEM","Worker readiness check threw",{error:s instanceof Error?s.message:String(s)})}let r=t-(Date.now()-e);if(r<=0)break;await new Promise(s=>setTimeout(s,Math.min(250,r)))}return!1}async function Vi(){try{let e=await(await de("/api/health",{timeoutMs:Gt})).json();return typeof e.version=="string"?e.version:null}catch{return null}}async function El(t,e=zi){let r=Date.now();for(;Date.now()-r<e;){if(await Vi()===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 Fr(t){let e=await Vi();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 ml()}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=xt({logAlive:!1});return e==="missing"||e==="alive"}async function Bt(){let t=null;if(await qi()){let{matches:n,pluginVersion:o,workerVersion:a}=await Wi(Ji());if(o!=="unknown"&&(t=o),n)return await Ur()?(t!==null&&await Fr(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 de("/api/admin/restart",{method:"POST",timeoutMs:Gt}),await El(o))return await Ur()?(t!==null&&await Fr(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=gl();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{At(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 Sl({attempts:6,backoffMs:500}))return d.warn("SYSTEM",s?"Worker port did not open after lazy-spawn within the cold-boot wait (~15s)":"Spawn-lock holder's worker port did not open within the cold-boot wait (~15s)"),!1}finally{s&&$i()}return await Ur()?(t!==null&&await Fr(t),!0):(d.warn("SYSTEM","Worker lazy-spawned but did not become ready before hook readiness timeout"),!1)}var $t=null;async function wl(){return $t!==null||($t=await Bt()),$t}var _l=3;function Xi(){return We.default.join(v,"state")}function Qi(){return We.default.join(Xi(),"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=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 yl(){try{let e=ue().CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD,r=parseInt(e,10);if(Number.isFinite(r)&&r>=1)return r}catch{}return _l}var Ki=null;async function bl(){let e={consecutiveFailures:Zi().consecutiveFailures+1,lastFailureAt:Date.now()};en(e);let r=yl();return e.consecutiveFailures>=r&&(e.consecutiveFailures===r&&await Ii("hook_failed",{...Ki!==null?{hook_type:Ki}:{},error_mode:"worker_unavailable",consecutive_failures:e.consecutiveFailures,threshold_tripped:!0}),Vr(`claude-mem worker unreachable for ${e.consecutiveFailures} consecutive hooks.`)),e.consecutiveFailures}function Yi(){Zi().consecutiveFailures!==0&&en({consecutiveFailures:0,lastFailureAt:0})}var Wr=Symbol.for("claude-mem/worker-fallback");function Kt(t){return typeof t=="object"&&t!==null&&t[Wr]===!0}async function Yt(t,e,r,s={}){if(!await wl())return await bl(),{continue:!0,reason:"worker_unreachable",[Wr]:!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 de(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}`,[Wr]:!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=V(require("path"),1),nn=require("child_process");var Jt=require("fs"),zt=V(require("path"),1);var st={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function tn(t){let e=zt.default.join(t,".git"),r;try{r=(0,Jt.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)}),st}if(!r.isFile())return st;let s;try{s=(0,Jt.readFileSync)(e,"utf-8").trim()}catch(u){return d.warn("GIT","Failed to read .git file",{error:u instanceof Error?u.message:String(u)}),st}let i=s.match(/^gitdir:\s*(.+)$/);if(!i)return st;let o=i[1].match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!o)return st;let a=o[1],l=zt.default.basename(t),c=zt.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 vl(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 Tl(t){if(!t||t.trim()==="")return d.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),"unknown-project";let e=on(t),s=vl(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 ke(t){let e=Tl(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 Re=require("path");var an=require("os"),ln=require("path");function Ml(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 Vt(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=Ml(n);if(o.test(r)||o.test(s))return!0}catch(o){d.warn("PROJECT_NAME","Invalid exclusion pattern",{pattern:n,error:o instanceof Error?o.message:String(o)});continue}return!1}function kl(t,e){let r=(0,Re.normalize)(t),s=(0,Re.normalize)(e);if(r===s)return!0;let i=(0,Re.relative)(s,r);return i.length>0&&!i.startsWith("..")&&!(0,Re.isAbsolute)(i)}function qt(t){if(process.env.CLAUDE_MEM_INTERNAL==="1")return!1;if(!t)return!0;if(kl(t,ct))return!1;let e=ue();return!Vt(t,e.CLAUDE_MEM_EXCLUDED_PROJECTS)}var cn="claude";function Rl(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function se(t){if(!t)return cn;let e=Rl(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 Cl(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 Gr(t){return Cl(t).stripped}var Al=["task-notification"],Ol=new RegExp(`^\\s*<(${Al.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),Dl=256*1024;function pn(t){return!t||t.length>Dl?!1:Ol.test(t)}var Pl=ce($.API_REQUEST),pe=class extends Error{kind;status;cause;constructor(e,r,s={}){super(r),this.name="ServerClientError",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)}},Xt=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=Il(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??Pl}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 pe("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 pe("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}:{},...e.platformSource!==void 0?{platformSource:Br(e.platformSource)}:{}}}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:Br(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.platformSource!==void 0?{platformSource:Br(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,r,s){if(!this.apiKey||!this.apiKey.trim())throw new pe("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_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 pe(u?"timeout":"transport",`Server ${e} ${r} failed: ${c}`,{cause:l})}if(!o.ok){let l=await o.text().catch(()=>"");throw new pe("http_error",`Server ${e} ${r} returned ${o.status}: ${xl(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 pe("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:l})}}};function fn(t){return t instanceof pe}function Il(t){return t.replace(/\/+$/,"")}function Br(t){return typeof t=="string"?se(t):null}function xl(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Ll(){let e=(ue().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function Nl(){let t=ue(),e=(...o)=>{for(let a of o){let l=(a??"").trim();if(l.length>0)return l}return""},r=e(t.CLAUDE_MEM_SERVER_URL,t.CLAUDE_MEM_SERVER_BETA_URL),s=e(t.CLAUDE_MEM_SERVER_API_KEY,t.CLAUDE_MEM_SERVER_BETA_API_KEY),i=e(t.CLAUDE_MEM_SERVER_PROJECT_ID,t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!r)return d.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!s)return d.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!i)return d.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let n={serverBaseUrl:r,apiKey:s};return{runtime:"server",client:new Xt(n),projectId:i,serverBaseUrl:r}}function mn(){if(Ll()!=="server")return{runtime:"worker"};let t=Nl();return t||{runtime:"worker"}}function gn(t,e){d.warn("HOOK",`[server-fallback] reason=${t}`,e??{})}var Ul={executeWithWorkerFallback:Yt,isWorkerFallback:Kt,loadFromFileOnce:ue,resolveRuntimeContext:mn,logServerFallback:gn,shouldTrackProject:qt},_e=Ul;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:we.SUCCESS};if(!_e.shouldTrackProject(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=ke(s).primary,o=se(t.platform),a=_e.loadFromFileOnce(),l=String(a.CLAUDE_MEM_SEMANTIC_INJECT).toLowerCase()==="true",c=_e.resolveRuntimeContext();if(c.runtime==="server")try{return await c.client.startSession({projectId:c.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 session started",{contentSessionId:e,project:n}),{continue:!0,suppressOutput:!0}}catch(m){if(fn(m)&&m.isFallbackEligible())_e.logServerFallback(m.kind,{status:m.status,message:m.message,route:"/v1/sessions/start"});else return d.error("HOOK","Server session-start failed (non-recoverable)",{error:m instanceof Error?m.message:String(m)}),{continue:!0,suppressOutput:!0,exitCode:we.SUCCESS}}d.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:e,project:n});let u=await _e.executeWithWorkerFallback("/api/sessions/init","POST",{contentSessionId:e,project:n,prompt:i,platformSource:o});if(_e.isWorkerFallback(u))return{continue:!0,suppressOutput:!0,exitCode:we.SUCCESS};if(typeof u?.sessionDbId!="number")return d.failure("HOOK","Session initialization returned malformed response",{contentSessionId:e,project:n}),{continue:!0,suppressOutput:!0,exitCode:we.SUCCESS};let h=u.sessionDbId,p=u.promptNumber;if(d.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:h,promptNumber:p,skipped:u.skipped,contextInjected:u.contextInjected}),d.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${e} | prompt#=${p} | sessionDbId=${h}`),u.skipped&&u.reason==="private")return d.info("HOOK",`INIT_COMPLETE | sessionDbId=${h} | promptNumber=${p} | skipped=true | reason=private`,{sessionId:h}),{continue:!0,suppressOutput:!0};let f="";if(l&&i&&i.length>=20&&i!=="[media prompt]"){let m=a.CLAUDE_MEM_SEMANTIC_INJECT_LIMIT||"5",g=await _e.executeWithWorkerFallback("/api/context/semantic","POST",{q:i,project:n,limit:m,platformSource:o});!_e.isWorkerFallback(g)&&g?.context&&(d.debug("HOOK",`Semantic injection: ${g.count} observations for prompt`,{sessionId:h,count:g.count}),f=g.context)}return d.info("HOOK",`INIT_COMPLETE | sessionDbId=${h} | promptNumber=${p} | project=${n}`,{sessionId:h}),f?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:f}}:{continue:!0,suppressOutput:!0}}};var En={async execute(t){let{sessionId:e,cwd:r,filePath:s,edits:i}=t,n=se(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(!qt(r))return d.debug("HOOK","Project excluded from tracking, skipping file edit observation",{cwd:r,filePath:s}),{continue:!0,suppressOutput:!0,exitCode:we.SUCCESS};let o=await Yt("/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 Kt(o)?{continue:!0,suppressOutput:!0,exitCode:we.SUCCESS}:(d.debug("HOOK","File edit observation sent successfully",{filePath:s}),{continue:!0,suppressOutput:!0})}};var z=require("fs"),Qt=require("path");var Qh=A.settings();function wn(t,e){let r="<claude-mem-context>",s="</claude-mem-context>";if(!t)return`${r}
|
|
2
|
+
"use strict";var Gr=Object.create;var St=Object.defineProperty;var Kr=Object.getOwnPropertyDescriptor;var Yr=Object.getOwnPropertyNames;var Br=Object.getPrototypeOf,Jr=Object.prototype.hasOwnProperty;var Vr=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Yr(e))!Jr.call(r,o)&&o!==t&&St(r,o,{get:()=>e[o],enumerable:!(n=Kr(e,o))||n.enumerable});return r};var H=(r,e,t)=>(t=r!=null?Gr(Br(r)):{},Vr(e||!r||!r.__esModule?St(t,"default",{value:r,enumerable:!0}):t,r));var P=require("fs"),je=require("os"),re=require("path");var p=require("path"),He=require("os"),te=require("fs"),_t=require("url"),Zr={};function Xr(){return typeof __dirname<"u"?__dirname:(0,p.dirname)((0,_t.fileURLToPath)(Zr.url))}var yo=Xr();function X(){if(process.env.CLAUDE_MEM_DATA_DIR)return process.env.CLAUDE_MEM_DATA_DIR;let r=(0,p.join)((0,He.homedir)(),".claude-mem"),e=(0,p.join)(r,"settings.json");try{if((0,te.existsSync)(e)){let t=JSON.parse((0,te.readFileSync)(e,"utf-8")),n=t.env??t;if(n.CLAUDE_MEM_DATA_DIR)return n.CLAUDE_MEM_DATA_DIR}}catch{}return r}var m=X(),qr=process.env.CLAUDE_CONFIG_DIR||(0,p.join)((0,He.homedir)(),".claude"),ce=(0,p.join)(qr,"plugins","marketplaces","thedotmack"),zr=(0,p.join)(m,"logs"),ue=(0,p.join)(m,"settings.json"),Mo=(0,p.join)(m,"claude-mem.db"),$e=(0,p.join)(m,"observer-sessions"),Qr=(0,p.basename)($e);var E={dataDir:()=>m,workerPid:()=>(0,p.join)(m,"worker.pid"),serverPid:()=>(0,p.join)(m,".server-beta.pid"),serverPort:()=>(0,p.join)(m,".server-beta.port"),serverRuntime:()=>(0,p.join)(m,".server-beta.runtime.json"),settings:()=>(0,p.join)(m,"settings.json"),database:()=>(0,p.join)(m,"claude-mem.db"),chroma:()=>(0,p.join)(m,"chroma"),combinedCerts:()=>(0,p.join)(m,"combined_certs.pem"),transcriptsConfig:()=>(0,p.join)(m,"transcript-watch.json"),transcriptsState:()=>(0,p.join)(m,"transcript-watch-state.json"),corpora:()=>(0,p.join)(m,"corpora"),supervisorRegistry:()=>(0,p.join)(m,"supervisor.json"),envFile:()=>(0,p.join)(m,".env"),logsDir:()=>zr};var q=E.transcriptsConfig(),le=E.transcriptsState(),en={version:1,schemas:{},watches:[],stateFile:le};function tn(r){let e=typeof r.schema=="string"?r.schema:r.schema?.name;if(!(r.name==="codex"||e==="codex")||!r.path)return!1;let n=T(r.path).replace(/\\/g,"/"),o=(0,re.join)((0,je.homedir)(),".codex","sessions").replace(/\\/g,"/");return n===`${o}/**/*.jsonl`}function ht(r){let e=typeof r.schema=="string"?r.schema:r.schema?.name,t=r.name==="codex"&&(!e||e==="codex");return r.context?.mode==="agents"&&t&&tn(r)}function T(r){return r&&(r.startsWith("~")?(0,re.join)((0,je.homedir)(),r.slice(1)):r)}function ne(r=q){let e=T(r);if(!(0,P.existsSync)(e))throw new Error(`Transcript watch config not found: ${e}`);let t=(0,P.readFileSync)(e,"utf-8"),n=JSON.parse(t);if(!n.version||!n.watches)throw new Error(`Invalid transcript watch config: ${e}`);return n.stateFile||(n.stateFile=le),n}function de(r=q){let e=T(r),t=(0,re.dirname)(e);(0,P.existsSync)(t)||(0,P.mkdirSync)(t,{recursive:!0}),(0,P.writeFileSync)(e,JSON.stringify(en,null,2))}var h=require("fs"),A=require("path");var D=require("fs"),wt=require("path");var rn=null;function Ge(r){return(rn??process.stderr.write.bind(process.stderr))(r)}var pe=null;function Ke(r){Ge(r)}function Tt(r,e={}){pe&&pe.length>0&&(Ge(pe.join("")),pe=[]),Ge(r.endsWith(`
|
|
3
|
+
`)?r:`${r}
|
|
4
|
+
`),e.skipExit||process.exit(2)}var Be=(i=>(i[i.DEBUG=0]="DEBUG",i[i.INFO=1]="INFO",i[i.WARN=2]="WARN",i[i.ERROR=3]="ERROR",i[i.SILENT=4]="SILENT",i))(Be||{}),Ye=null,Je=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=E.logsDir();(0,D.existsSync)(e)||(0,D.mkdirSync)(e,{recursive:!0});let t=new Date().toISOString().split("T")[0];this.logFilePath=(0,wt.join)(e,`claude-mem-${t}.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=E.settings();if((0,D.existsSync)(e)){let t=(0,D.readFileSync)(e,"utf-8"),o=(JSON.parse(t).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=Be[o]??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
|
+
${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let t=Object.keys(e);return t.length===0?"{}":t.length<=3?JSON.stringify(e):`{${t.length} keys: ${t.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,t){if(!t)return e;let n=t;if(typeof t=="string")try{n=JSON.parse(t)}catch{n=t}if(e==="Bash"&&n.command)return`${e}(${n.command})`;if(n.file_path)return`${e}(${n.file_path})`;if(n.notebook_path)return`${e}(${n.notebook_path})`;if(e==="Glob"&&n.pattern)return`${e}(${n.pattern})`;if(e==="Grep"&&n.pattern)return`${e}(${n.pattern})`;if(n.url)return`${e}(${n.url})`;if(n.query)return`${e}(${n.query})`;if(e==="Task"){if(n.subagent_type)return`${e}(${n.subagent_type})`;if(n.description)return`${e}(${n.description})`}return e==="Skill"&&n.skill?`${e}(${n.skill})`:e==="LSP"&&n.operation?`${e}(${n.operation})`:e}formatTimestamp(e){let t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0"),i=String(e.getHours()).padStart(2,"0"),s=String(e.getMinutes()).padStart(2,"0"),c=String(e.getSeconds()).padStart(2,"0"),u=String(e.getMilliseconds()).padStart(3,"0");return`${t}-${n}-${o} ${i}:${s}:${c}.${u}`}log(e,t,n,o,i){if(e<this.getLevel())return;this.ensureLogFileInitialized();let s=this.formatTimestamp(new Date),c=Be[e].padEnd(5),u=t.padEnd(6),d="";o?.correlationId?d=`[${o.correlationId}] `:o?.sessionId&&(d=`[session-${o.sessionId}] `);let l="";if(i!=null)if(i instanceof Error)l=this.getLevel()===0?`
|
|
6
|
+
${i.message}
|
|
7
|
+
${i.stack}`:` ${i.message}`;else if(this.getLevel()===0&&typeof i=="object")try{l=`
|
|
8
|
+
`+JSON.stringify(i,null,2)}catch{l=" "+this.formatData(i)}else l=" "+this.formatData(i);let S="";if(o){let{sessionId:_,memorySessionId:f,correlationId:W,...ae}=o;Object.keys(ae).length>0&&(S=` {${Object.entries(ae).map(([K,jr])=>`${K}=${jr}`).join(", ")}}`)}let g=`[${s}] [${c}] [${u}] ${d}${n}${S}${l}`;if(this.logFilePath)try{(0,D.appendFileSync)(this.logFilePath,g+`
|
|
9
|
+
`,"utf8")}catch(_){let f=_ instanceof Error?_:new Error(String(_));Ke(`[LOGGER] Failed to write to log file: ${f.message}
|
|
10
|
+
${f.stack??""}
|
|
11
|
+
`)}else Ke(g+`
|
|
12
|
+
`)}debug(e,t,n,o){this.log(0,e,t,n,o)}info(e,t,n,o){this.log(1,e,t,n,o)}warn(e,t,n,o){this.log(2,e,t,n,o)}setErrorSink(e){Ye=e}error(e,t,n,o){this.log(3,e,t,n,o),this.routeErrorToSink(t,n,o)}routeErrorToSink(e,t,n){try{if(!Ye||!(n instanceof Error))return;Ye(n)}catch{}}dataIn(e,t,n,o){this.info(e,`\u2192 ${t}`,n,o)}dataOut(e,t,n,o){this.info(e,`\u2190 ${t}`,n,o)}success(e,t,n,o){this.info(e,`\u2713 ${t}`,n,o)}failure(e,t,n,o){this.error(e,`\u2717 ${t}`,n,o)}},a=new Je;var L=require("fs"),yt=require("path");function Mt(r){try{if(!(0,L.existsSync)(r))return{offsets:{}};let e=(0,L.readFileSync)(r,"utf-8"),t=JSON.parse(e);return t.offsets?t:{offsets:{}}}catch(e){return a.warn("TRANSCRIPT","Failed to load watch state, starting fresh",{statePath:r,error:e instanceof Error?e.message:String(e)}),{offsets:{}}}}function vt(r,e){try{let t=(0,yt.dirname)(r);(0,L.existsSync)(t)||(0,L.mkdirSync)(t,{recursive:!0}),(0,L.writeFileSync)(r,JSON.stringify(e,null,2))}catch(t){a.warn("TRANSCRIPT","Failed to save watch state",{statePath:r,error:t instanceof Error?t.message:String(t)})}}var ie=H(require("path"),1);var Z=H(require("path"),1),v=require("fs");var Rt=require("node:child_process");function fe(r,e,t){return(0,Rt.spawn)(r,e??[],{windowsHide:!0,...t})}var M={HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5},$={SUCCESS:0,BLOCKING_ERROR:2};function j(r){return process.platform==="win32"?Math.round(r*M.WINDOWS_MULTIPLIER):r}var C=require("fs"),oe=require("path"),Ve=require("os");var k=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(j(M.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_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_DATA_DIR:(0,oe.join)((0,Ve.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,oe.join)((0,Ve.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_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let t=this.get(e);return parseInt(t,10)}static applyEnvOverrides(e){let t={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(t[n]=process.env[n]);return t}static loadFromFile(e,t=!0){try{if(!(0,C.existsSync)(e)){let c=this.getAllDefaults();try{let u=(0,oe.dirname)(e);(0,C.existsSync)(u)||(0,C.mkdirSync)(u,{recursive:!0}),(0,C.writeFileSync)(e,JSON.stringify(c,null,2),"utf-8"),console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(u){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,u instanceof Error?u.message:String(u))}return t?this.applyEnvOverrides(c):c}let n=(0,C.readFileSync)(e,"utf-8"),o=JSON.parse(n.replace(/^\uFEFF/,"")),i=o;if(o.env&&typeof o.env=="object"){i=o.env;try{(0,C.writeFileSync)(e,JSON.stringify(i,null,2),"utf-8"),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(c){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,c instanceof Error?c.message:String(c))}}let s={...this.DEFAULTS};for(let c of Object.keys(this.DEFAULTS))i[c]!==void 0&&(s[c]=i[c]);return t?this.applyEnvOverrides(s):s}catch(n){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,n instanceof Error?n.message:String(n));let o=this.getAllDefaults();return t?this.applyEnvOverrides(o):o}}};var me=null;function x(){return me!==null||(me=k.loadFromFile(ue)),me}var Y=require("fs");var Ze=require("child_process");var O=require("fs"),ze=H(require("path"),1);var nn=["CLAUDECODE_","CLAUDE_CODE_"],on=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"]),sn=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 ge(r=process.env){let e={};for(let[t,n]of Object.entries(r))if(n!==void 0){if(sn.has(t)){e[t]=n;continue}on.has(t)||nn.some(o=>t.startsWith(o))||(e[t]=n)}return e}var an=5e3,cn=1e3,un=E.supervisorRegistry();function b(r){if(!Number.isInteger(r)||r<0||r===0)return!1;try{return process.kill(r,0),!0}catch(e){if(e instanceof Error){let t=e.code;return t==="EPERM"?!0:(a.debug("SYSTEM","PID check failed",{pid:r,code:t}),!1)}return a.warn("SYSTEM","PID check threw non-Error",{pid:r,error:String(e)}),!1}}async function Ee(r,e){let t=Date.now()+e;for(;Date.now()<t;){if(r.every(n=>!b(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}var ln=5e3,At=new Map;function dn(r){let e=(0,Ze.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${r}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...ge(process.env),LC_ALL:"C",LANG:"C"}});if(e.status===0){let t=e.stdout.trim();return t.length>0?t:null}return null}function pn(r){let e=At.get(r);if(e&&Date.now()-e.capturedAtMs<ln)return e.token;let t=null;try{t=dn(r)}catch(n){a.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:r,error:n instanceof Error?n.message:String(n)}),t=null}return At.set(r,{token:t,capturedAtMs:Date.now()}),t}function Ct(r){if(!Number.isInteger(r)||r<=0)return null;if(process.platform==="linux")try{let e=(0,O.readFileSync)(`/proc/${r}/stat`,"utf-8"),t=e.lastIndexOf(") ");if(t<0)return null;let o=e.slice(t+2).split(" ")[19];return o&&/^\d+$/.test(o)?o:null}catch(e){return a.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return pn(r);try{let e=(0,Ze.spawnSync)("ps",["-p",String(r),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...ge(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let t=e.stdout.trim();return t.length>0?t:null}catch(e){return a.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}}function et(r){if(!r||!b(r.pid))return!1;if(!r.startToken)return!0;let e=Ct(r.pid);if(e===null)return!0;let t=e===r.startToken;return t||a.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:r.pid,stored:r.startToken,current:e}),t}var Qe=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=un){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,O.mkdirSync)(ze.default.dirname(this.registryPath),{recursive:!0}),!(0,O.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,O.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[o,i]of Object.entries(n))this.entries.set(o,i)}catch(t){t instanceof Error?a.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},t):a.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(t)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&a.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,t,n){this.initialize(),this.entries.set(e,t),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let t=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),t?.type==="sdk"&&qe()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,t])=>({id:e,...t})).sort((e,t)=>{let n=Date.parse(e.startedAt),o=Date.parse(t.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(o)?0:o)})}getBySession(e){let t=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===t)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,t=0;for(let[n,o]of this.entries)b(o.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,o.type==="sdk"&&(t+=1));e>0&&this.persist();for(let n=0;n<t;n+=1)qe();return e}async reapSession(e){this.initialize();let t=this.getBySession(e);if(t.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;a.info("SYSTEM",`Reaping ${t.length} process(es) for session ${e}`,{sessionId:n,pids:t.map(s=>s.pid)});let o=t.filter(s=>b(s.pid));for(let s of o)try{typeof s.pgid=="number"&&process.platform!=="win32"?process.kill(-s.pgid,"SIGTERM"):process.kill(s.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&a.debug("SYSTEM",`Failed to SIGTERM session process PID ${s.pid}`,{pid:s.pid,pgid:s.pgid},c):a.warn("SYSTEM",`Failed to SIGTERM session process PID ${s.pid} (non-Error)`,{pid:s.pid,pgid:s.pgid,error:String(c)})}await Ee(o,an);let i=o.filter(s=>b(s.pid));for(let s of i){a.warn("SYSTEM",`Session process PID ${s.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:s.pid,pgid:s.pgid,sessionId:n});try{typeof s.pgid=="number"&&process.platform!=="win32"?process.kill(-s.pgid,"SIGKILL"):process.kill(s.pid,"SIGKILL")}catch(c){c instanceof Error?c.code!=="ESRCH"&&a.debug("SYSTEM",`Failed to SIGKILL session process PID ${s.pid}`,{pid:s.pid,pgid:s.pgid},c):a.warn("SYSTEM",`Failed to SIGKILL session process PID ${s.pid} (non-Error)`,{pid:s.pid,pgid:s.pgid,error:String(c)})}}if(i.length>0){let s=Date.now()+cn;for(;Date.now()<s&&i.filter(u=>b(u.pid)).length!==0;)await new Promise(u=>setTimeout(u,100))}for(let s of t)this.entries.delete(s.id),this.runtimeProcesses.delete(s.id);this.persist();for(let s of t)s.type==="sdk"&&qe();return a.info("SYSTEM",`Reaped ${t.length} process(es) for session ${e}`,{sessionId:n,reaped:t.length}),t.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,O.mkdirSync)(ze.default.dirname(this.registryPath),{recursive:!0}),(0,O.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},Xe=null;function Se(){return Xe||(Xe=new Qe),Xe}var fn=[];function qe(){let r=fn.shift();r&&r()}var bt=require("child_process"),z=require("fs"),Ot=require("util");var mn=(0,Ot.promisify)(bt.execFile),gn=E.workerPid();async function It(r){let e=r.currentPid??process.pid,t=r.pidFilePath??gn,n=r.registry.getAll(),o=[...n].filter(s=>s.pid!==e).sort((s,c)=>Date.parse(c.startedAt)-Date.parse(s.startedAt));for(let s of o){if(!b(s.pid)){r.registry.unregister(s.id);continue}try{await kt(s,"SIGTERM")}catch(c){c instanceof Error?a.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:s.pid,pgid:s.pgid,type:s.type},c):a.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:s.pid,pgid:s.pgid,type:s.type,error:String(c)})}}await Ee(o,5e3);let i=o.filter(s=>b(s.pid));for(let s of i)try{await kt(s,"SIGKILL")}catch(c){c instanceof Error?a.debug("SYSTEM","Failed to force kill child process",{pid:s.pid,pgid:s.pgid,type:s.type},c):a.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:s.pid,pgid:s.pgid,type:s.type,error:String(c)})}await Ee(i,1e3);for(let s of o)r.registry.unregister(s.id);for(let s of n.filter(c=>c.pid===e))r.registry.unregister(s.id);Pt(t,e),r.registry.pruneDeadEntries()}function Pt(r,e,t=!1){if(!(0,z.existsSync)(r))return;let n=null;try{let s=JSON.parse((0,z.readFileSync)(r,"utf-8"));n=typeof s.pid=="number"?s.pid:null}catch(s){a.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:r,error:s instanceof Error?s.message:String(s)});return}let o=e!==null&&n===e,i=n===null||!b(n);if(!o&&!(t&&i)){a.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:r,recordedPid:n,currentPid:e});return}try{(0,z.rmSync)(r,{force:!0})}catch(s){s instanceof Error?a.debug("SYSTEM","Failed to remove PID file",{pidFilePath:r},s):a.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:r,error:String(s)})}}async function kt(r,e){let{pid:t,pgid:n}=r;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}try{process.kill(t,e)}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}return}if(e==="SIGTERM"){try{process.kill(t,e)}catch(i){if(i instanceof Error&&i.code==="ESRCH")return;throw i}return}let o=["/PID",String(t),"/T"];e==="SIGKILL"&&o.push("/F"),await mn("taskkill",o,{timeout:M.POWERSHELL_COMMAND,windowsHide:!0})}var Dt=3e4,Q=null;function En(){let e=Se().pruneDeadEntries();e>0&&a.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function Lt(){Q===null&&(Q=setInterval(En,Dt),Q.unref(),a.debug("SYSTEM","Health checker started",{intervalMs:Dt}))}function xt(){Q!==null&&(clearInterval(Q),Q=null,a.debug("SYSTEM","Health checker stopped"))}var Sn=E.workerPid(),tt=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(),_e({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,Lt()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let t=async n=>{if(this.shutdownInitiated){a.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,a.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(o){o instanceof Error?a.error("SYSTEM","Error during shutdown",{},o):a.error("SYSTEM","Error during shutdown (non-Error)",{error:String(o)});try{await this.stop()}catch(i){i instanceof Error?a.debug("SYSTEM","Supervisor shutdown fallback failed",{},i):a.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(i)})}}process.exit(0)};process.on("SIGTERM",()=>{t("SIGTERM")}),process.on("SIGINT",()=>{t("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{a.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{t("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}xt(),this.stopPromise=It({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,t,n){this.registry.register(e,t,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},is=new tt(Se());function _e(r={}){let e=r.pidFilePath??Sn;if(!(0,Y.existsSync)(e))return"missing";let t=null;try{t=JSON.parse((0,Y.readFileSync)(e,"utf-8"))}catch(o){return o instanceof Error?a.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},o):a.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(o)}),(0,Y.rmSync)(e,{force:!0}),"invalid"}return et(t)&&t?((r.logAlive??!0)&&a.info("SYSTEM","Worker already running (PID alive)",{existingPid:t.pid,existingPort:t.port,startedAt:t.startedAt}),"alive"):(a.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:t?.pid,port:t?.port,startedAt:t?.startedAt}),(0,Y.rmSync)(e,{force:!0}),"stale")}var rt=require("path"),Te=require("fs"),Ut=require("crypto");var he=require("fs");function Nt(r,e){if(!(0,he.existsSync)(r))return e;try{return JSON.parse((0,he.readFileSync)(r,"utf-8"))}catch(t){throw new Error(`Corrupt JSON file, refusing to overwrite: ${r}: ${t instanceof Error?t.message:String(t)}`)}}var Ft="telemetry.json";function _n(r){let e=r.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function hn(r,e){if(_n(r))return{enabled:!1,source:"DO_NOT_TRACK"};let t=r.CLAUDE_MEM_TELEMETRY?.toLowerCase();return t==="0"||t==="false"||t==="off"?{enabled:!1,source:"env"}:t==="1"||t==="true"||t==="on"?{enabled:!0,source:"env"}:e?.enabled===!0?{enabled:!0,source:"config"}:e?.enabled===!1?{enabled:!1,source:"config"}:{enabled:!0,source:"default"}}function Wt(r,e){return hn(r,e).enabled}function Tn(){return(0,rt.join)(X(),Ft)}function nt(){let r;try{r=Nt(Tn(),null)}catch(e){let t=e instanceof Error?e:new Error(String(e));return a.warn("SYSTEM","Telemetry: corrupt telemetry.json; treating as no recorded consent",void 0,t),null}return!r||typeof r!="object"||typeof r.installId!="string"||r.enabled!==void 0&&typeof r.enabled!="boolean"?null:{enabled:r.enabled,installId:r.installId,decidedAt:typeof r.decidedAt=="string"?r.decidedAt:""}}function wn(r){let e=X();(0,Te.mkdirSync)(e,{recursive:!0}),(0,Te.writeFileSync)((0,rt.join)(e,Ft),JSON.stringify(r,null,2)+`
|
|
13
|
+
`)}function Ht(){let r=nt();if(r?.installId)return r.installId;let e=(0,Ut.randomUUID)();return wn({installId:e,decidedAt:""}),e}var yn=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","observations_created","total_observations_injected","total_tokens_saved_vs_naive"]),$t=200;function Mn(r,e){if(!(!r||typeof r!="object"))for(let t of Object.keys(r)){if(!yn.has(t))continue;let n=r[t];typeof n=="string"?e[t]=n.length>$t?n.slice(0,$t):n:(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(e[t]=n)}}function jt(r){let e={};try{Mn(r,e)}catch{}return e}var ot=H(require("os"),1);var vn="13.9.3",Rn="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",An="https://us.i.posthog.com";function Gt(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||Rn}function Kt(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||An}var Cn=["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 Yt(r){let e={};for(let t of Cn)r[t]!==void 0&&(e[t]=r[t]);return e}function kn(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||ot.default.release().toLowerCase().includes("microsoft")}catch(r){let e=r instanceof Error?r:new Error(String(r));return a.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function Bt(){return{version:vn,os:process.platform,os_version:ot.default.release(),is_wsl:kn(),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 bn=2e3;async function Jt(r,e,t){try{if(!Wt(process.env,nt()))return;let n=jt({...Bt(),...e??{}});if(t?.person?n.$set=Yt(n):n.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:r,properties:n})+`
|
|
14
|
+
`);return}let o=Gt(),i=new AbortController,s=setTimeout(()=>i.abort(),bn);try{await On(o,r,n,i.signal)}finally{clearTimeout(s)}}catch{}}async function On(r,e,t,n){await fetch(`${Kt()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:r,event:e,distinct_id:Ht(),properties:t}),signal:n})}var B=H(require("path"),1),Xt=require("os"),N=require("fs"),it=require("child_process");var As=E.dataDir(),Cs=E.workerPid();function Vt(r){return r?/(^|[\\/])bun(\.exe)?$/i.test(r.trim()):!1}function Pn(r,e){let t=e==="win32"?`where ${r}`:`which ${r}`,n;try{n=(0,it.execSync)(t,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(i){return i instanceof Error?a.debug("SYSTEM",`Binary lookup failed for ${r}`,{command:t},i):a.debug("SYSTEM",`Binary lookup failed for ${r}`,{command:t},new Error(String(i))),null}return n.split(/\r?\n/).map(i=>i.trim()).find(i=>i.length>0)||null}var st;function qt(r={}){let e=Object.keys(r).length===0;if(e&&st!==void 0)return st;let t=Dn(r);return e&&t!==null&&(st=t),t}function Dn(r){let e=r.platform??process.platform,t=r.execPath??process.execPath;if(Vt(t))return t;let n=r.env??process.env,o=r.homeDirectory??(0,Xt.homedir)(),i=r.pathExists??N.existsSync,s=r.lookupInPath??Pn,c=e==="win32"?[n.BUN,n.BUN_PATH,B.default.join(o,".bun","bin","bun.exe"),B.default.join(o,".bun","bin","bun"),n.USERPROFILE?B.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?B.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?B.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[n.BUN,n.BUN_PATH,B.default.join(o,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun"];for(let u of c){let d=u?.trim();if(d&&(Vt(d)&&i(d)||d.toLowerCase()==="bun"))return d}return s("bun",e)}var zt=H(require("path"),1);var Qt=require("fs");async function Ln(r,e,t="GET"){let n=await fetch(`http://127.0.0.1:${r}${e}`,{method:t}),o="";try{o=await n.text()}catch{}return{ok:n.ok,statusCode:n.status,body:o}}function xn(){try{let r=zt.default.join(ce,"package.json");return JSON.parse((0,Qt.readFileSync)(r,"utf-8")).version}catch(r){if(r instanceof Error){let e=r.code;if(e==="ENOENT"||e==="EBUSY")return a.debug("SYSTEM","Could not read plugin version (shutdown race)",{code:e}),"unknown";throw r}throw r}}async function Nn(r){try{let e=await Ln(r,"/api/version");return e.ok?JSON.parse(e.body).version:null}catch{return a.debug("SYSTEM","Could not fetch worker version",{}),null}}async function Zt(r){let e=xn(),t=await Nn(r);return!t||e==="unknown"?{matches:!0,pluginVersion:e,workerVersion:t}:{matches:e===t,pluginVersion:e,workerVersion:t}}var we=require("path"),w=require("fs");var Un=6e4;function er(){return(0,we.join)(X(),"spawn.lock")}function tr(){let r=er(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let t=0;t<2;t++)try{return(0,w.mkdirSync)((0,we.dirname)(r),{recursive:!0}),(0,w.writeFileSync)(r,e,{flag:"wx"}),!0}catch(n){let o=n instanceof Error?n:new Error(String(n)),i=o.code;if(i!=="EEXIST")return a.warn("SYSTEM","Spawn lock write failed for a non-contention reason; failing open (spawning unlocked)",{lockPath:r,code:i},o),!0;if(t>0)return!1;let s;try{s=(0,w.statSync)(r).mtimeMs}catch{continue}if(Date.now()-s<=Un)return!1;let c;try{c=(0,w.statSync)(r).mtimeMs}catch{continue}if(c!==s)return!1;try{(0,w.unlinkSync)(r)}catch{return!1}}return!1}function rr(){let r=er();try{if(JSON.parse((0,w.readFileSync)(r,"utf-8")).pid!==process.pid)return;(0,w.unlinkSync)(r)}catch{}}function ar(r,e,t){let n=process.env[r];if(n){let o=parseInt(n,10);if(Number.isFinite(o)&&o>=t.min&&o<=t.max)return o;a.warn("SYSTEM",`Invalid ${r}, using default`,{value:n,min:t.min,max:t.max})}return e}var Ce=ar("CLAUDE_MEM_HEALTH_TIMEOUT_MS",j(M.HEALTH_CHECK),{min:500,max:3e5}),cr=ar("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",j(M.HOOK_READINESS_WAIT),{min:0,max:3e5}),Fn={min:500,max:3e5};async function lt(r,e={},t){try{return await fetch(r,{...e,signal:AbortSignal.timeout(t)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new Error(`Request timed out after ${t}ms`):n}}var ye=null,Me=null,ve=null,Re=null;function Wn(){return Z.default.join(k.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function dt(){return ve!==null||(ve=k.loadFromFile(Wn())),ve}function nr(r,e){if(!r)return null;let t=parseInt(r,10);return Number.isFinite(t)&&t>=e.min&&t<=e.max?t:null}function Hn(r,e,t){let n=process.env[r];if(n!==void 0){let s=nr(n,t);return s!==null?s:(a.warn("SYSTEM",`Invalid ${r}, using default`,{value:n,min:t.min,max:t.max}),e)}let o=dt()[r],i=nr(o,t);return i!==null?i:(a.warn("SYSTEM",`Invalid ${r} in settings.json, using default`,{value:o,min:t.min,max:t.max}),e)}function ur(){if(ye!==null)return ye;let r=dt();return ye=parseInt(r.CLAUDE_MEM_WORKER_PORT,10),ye}function $n(){return Me!==null||(Me=dt().CLAUDE_MEM_WORKER_HOST),Me}function jn(){return Re!==null||(Re=Hn("CLAUDE_MEM_API_TIMEOUT_MS",j(M.API_REQUEST),Fn)),Re}function Gn(r){return`http://${$n()}:${ur()}${r}`}function U(r,e={}){let t=e.method??"GET",n=e.timeoutMs??jn(),o=Gn(r),i={method:t};return e.headers&&(i.headers=e.headers),e.body&&(i.body=e.body),n>0?lt(o,i,n):fetch(o,i)}async function Kn(){return(await U("/api/health",{timeoutMs:Ce})).ok}async function or(){return(await U("/api/readiness",{timeoutMs:Ce})).ok}function Yn(){let r=[Z.default.join(ce,"plugin","scripts","worker-service.cjs"),Z.default.join(process.cwd(),"plugin","scripts","worker-service.cjs")];for(let e of r)if((0,v.existsSync)(e))return e;return null}async function Bn(r){let e=r.backoffMs;for(let t=1;t<=r.attempts;t++){if(await dr())return!0;t<r.attempts&&(await new Promise(n=>setTimeout(n,e)),e*=2)}return!1}async function at(r=cr){if(r<=0)try{return await or()}catch(t){let n=t instanceof Error?t:new Error(String(t));return a.debug("SYSTEM","Worker readiness check threw",{},n),!1}let e=Date.now();for(;Date.now()-e<r;){try{if(await or())return!0}catch(n){a.debug("SYSTEM","Worker readiness check threw",{error:n instanceof Error?n.message:String(n)})}let t=r-(Date.now()-e);if(t<=0)break;await new Promise(n=>setTimeout(n,Math.min(250,t)))}return!1}async function lr(){try{let e=await(await U("/api/health",{timeoutMs:Ce})).json();return typeof e.version=="string"?e.version:null}catch(r){let e=r instanceof Error?r:new Error(String(r));return a.debug("SYSTEM","Worker health-version fetch failed",{},e),null}}async function Jn(r,e=cr){let t=Date.now();for(;Date.now()-t<e;){if(await lr()===r)return!0;let o=e-(Date.now()-t);if(o<=0)break;await new Promise(i=>setTimeout(i,Math.min(500,o)))}return!1}async function ct(r){let e=await lr();e!==null&&e!==r&&a.warn("SYSTEM","Worker is ready but still reports a stale version; not recycling again in this hook invocation (one recycle per hook event)",{pluginVersion:r,workerVersion:e})}async function dr(){let r;try{r=await Kn()}catch(t){return a.debug("SYSTEM","Worker health check threw",{error:t instanceof Error?t.message:String(t)}),!1}if(!r)return!1;let e=_e({logAlive:!1});return e==="missing"||e==="alive"}async function ke(){let r=null;if(await dr()){let{matches:i,pluginVersion:s,workerVersion:c}=await Zt(ur());if(s!=="unknown"&&(r=s),i)return await at()?(r!==null&&await ct(r),!0):(a.warn("SYSTEM","Worker is healthy but not ready; skipping hook API call"),!1);a.info("SYSTEM","Worker version mismatch \u2014 recycling stale worker",{pluginVersion:s,workerVersion:c});let u=!1;try{await U("/api/admin/restart",{method:"POST",timeoutMs:Ce}),u=!0}catch(d){let l=d instanceof Error?d:new Error(String(d));a.debug("SYSTEM","Worker restart request failed; falling through to lazy-spawn",{},l)}if(u){if(await Jn(s))return await at()?(r!==null&&await ct(r),!0):(a.warn("SYSTEM","Recycled worker appeared but did not become ready; skipping hook API call"),!1);a.warn("SYSTEM","No successor worker appeared after recycle; falling through to lazy-spawn",{pluginVersion:s,workerVersion:c})}}let e=qt(),t=Yn();if(!e)return a.warn("SYSTEM","Cannot lazy-spawn worker: Bun runtime not found on PATH"),!1;if(!t)return a.warn("SYSTEM","Cannot lazy-spawn worker: worker-service.cjs not found in plugin/scripts"),!1;let n=tr();try{if(n){a.info("SYSTEM","Worker not running \u2014 lazy-spawning",{runtimePath:e,scriptPath:t});try{fe(e,[t,"--daemon"],{detached:!0,stdio:["ignore","ignore","ignore"]}).unref()}catch(s){return s instanceof Error?a.error("SYSTEM","Lazy-spawn of worker failed",{runtimePath:e,scriptPath:t},s):a.error("SYSTEM","Lazy-spawn of worker failed (non-Error)",{runtimePath:e,scriptPath:t,error:String(s)}),!1}}else a.info("SYSTEM","Another launcher holds the spawn lock \u2014 skipping lazy-spawn and waiting for its worker");if(!await Bn({attempts:6,backoffMs:500}))return a.warn("SYSTEM",n?"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{n&&rr()}return await at()?(r!==null&&await ct(r),!0):(a.warn("SYSTEM","Worker lazy-spawned but did not become ready before hook readiness timeout"),!1)}var Ae=null;async function Vn(){return Ae!==null||(Ae=await ke()),Ae}var Xn=3;function pr(){return Z.default.join(m,"state")}function fr(){return Z.default.join(pr(),"hook-failures.json")}function qn(r){let e=JSON.parse(r);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}}function mr(){try{return qn((0,v.readFileSync)(fr(),"utf-8"))}catch{return{consecutiveFailures:0,lastFailureAt:0}}}function gr(r){let e=pr(),t=fr(),n=`${t}.tmp`;try{(0,v.existsSync)(e)||(0,v.mkdirSync)(e,{recursive:!0}),(0,v.writeFileSync)(n,JSON.stringify(r),"utf-8"),(0,v.renameSync)(n,t)}catch(o){a.debug("SYSTEM","Failed to persist hook-failure counter",{error:o instanceof Error?o.message:String(o)})}}function zn(){try{let e=x().CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD,t=parseInt(e,10);if(Number.isFinite(t)&&t>=1)return t}catch{}return Xn}var sr=null;async function Qn(){let e={consecutiveFailures:mr().consecutiveFailures+1,lastFailureAt:Date.now()};gr(e);let t=zn();return e.consecutiveFailures>=t&&(e.consecutiveFailures===t&&await Jt("hook_failed",{...sr!==null?{hook_type:sr}:{},error_mode:"worker_unavailable",consecutive_failures:e.consecutiveFailures,threshold_tripped:!0}),Tt(`claude-mem worker unreachable for ${e.consecutiveFailures} consecutive hooks.`)),e.consecutiveFailures}function ir(){mr().consecutiveFailures!==0&&gr({consecutiveFailures:0,lastFailureAt:0})}var ut=Symbol.for("claude-mem/worker-fallback");function be(r){return typeof r=="object"&&r!==null&&r[ut]===!0}async function Oe(r,e,t,n={}){if(!await Vn())return await Qn(),{continue:!0,reason:"worker_unreachable",[ut]:!0};let i={method:e};t!==void 0&&(i.headers={"Content-Type":"application/json"},i.body=JSON.stringify(t)),n.timeoutMs!==void 0&&(i.timeoutMs=n.timeoutMs);let s=await U(r,i);if(!s.ok){let u=await s.text().catch(()=>"");if(ir(),s.status===429||s.status>=500)return a.warn("SYSTEM",`Worker API ${e} ${r} returned ${s.status}; skipping hook API call`,{body:u.substring(0,200)}),{continue:!0,reason:`worker_api_${s.status}`,[ut]:!0};let d=u;try{d=JSON.parse(u)}catch{}return d}ir();let c=await s.text();if(c.length!==0)try{return JSON.parse(c)}catch{return c}}var Sr=require("os"),_r=H(require("path"),1),hr=require("child_process");var Pe=require("fs"),Ie=H(require("path"),1);var se={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function Er(r){let e=Ie.default.join(r,".git"),t;try{t=(0,Pe.statSync)(e)}catch(l){return l instanceof Error&&l.code!=="ENOENT"&&a.warn("GIT","Unexpected error checking .git",{error:l instanceof Error?l.message:String(l)}),se}if(!t.isFile())return se;let n;try{n=(0,Pe.readFileSync)(e,"utf-8").trim()}catch(l){return a.warn("GIT","Failed to read .git file",{error:l instanceof Error?l.message:String(l)}),se}let o=n.match(/^gitdir:\s*(.+)$/);if(!o)return se;let s=o[1].match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!s)return se;let c=s[1],u=Ie.default.basename(r),d=Ie.default.basename(c);return{isWorktree:!0,worktreeName:u,parentRepoPath:c,parentProjectName:d}}function Tr(r){return r==="~"||r.startsWith("~/")?r.replace(/^~/,(0,Sr.homedir)()):r}function Zn(r){try{return(0,hr.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:r,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch(e){let t=e instanceof Error?e:new Error(String(e));return a.debug("PROJECT_NAME","git rev-parse failed, falling back to basename",{dir:r},t),null}}function eo(r){if(!r||r.trim()==="")return a.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:r}),"unknown-project";let e=Tr(r),n=Zn(e)??e,o=_r.default.basename(n);if(o===""){if(process.platform==="win32"){let s=r.match(/^([A-Z]):\\/i);if(s){let u=`drive-${s[1].toUpperCase()}`;return a.info("PROJECT_NAME","Drive root detected",{cwd:r,projectName:u}),u}}return a.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:r}),"unknown-project"}return o}function J(r){let e=eo(r);if(!r)return{primary:e,parent:null,isWorktree:!1,allProjects:[e]};let t=Tr(r),n=Er(t);if(n.isWorktree&&n.parentProjectName){let o=`${n.parentProjectName}/${e}`;return{primary:o,parent:n.parentProjectName,isWorktree:!0,allProjects:[n.parentProjectName,o]}}return{primary:e,parent:null,isWorktree:!1,allProjects:[e]}}var V=require("path");var wr=require("os"),yr=require("path");function to(r){let e=r.startsWith("~")?(0,wr.homedir)()+r.slice(1):r;e=e.replace(/\\/g,"/");let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return t=t.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${t}$`)}function De(r,e){if(!e||!e.trim())return!1;let t=r.replace(/\\/g,"/"),n=(0,yr.basename)(t),o=e.split(",").map(i=>i.trim()).filter(Boolean);for(let i of o)try{let s=to(i);if(s.test(t)||s.test(n))return!0}catch(s){a.warn("PROJECT_NAME","Invalid exclusion pattern",{pattern:i,error:s instanceof Error?s.message:String(s)});continue}return!1}function ro(r,e){let t=(0,V.normalize)(r),n=(0,V.normalize)(e);if(t===n)return!0;let o=(0,V.relative)(n,t);return o.length>0&&!o.startsWith("..")&&!(0,V.isAbsolute)(o)}function Le(r){if(process.env.CLAUDE_MEM_INTERNAL==="1")return!1;if(!r)return!0;if(ro(r,$e))return!1;let e=x();return!De(r,e.CLAUDE_MEM_EXCLUDED_PROJECTS)}var Mr="claude";function no(r){return r.trim().toLowerCase().replace(/\s+/g,"-")}function I(r){if(!r)return Mr;let e=no(r);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:Mr}var Ar=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],vr=new RegExp(`<(${Ar.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g");var Rr=100;function oo(r){let e=Object.fromEntries(Ar.map(o=>[o,0]));vr.lastIndex=0;let t=0,n=r.replace(vr,(o,i)=>(e[i]=(e[i]??0)+1,t+=1,""));return t>Rr&&a.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:t,maxAllowed:Rr,contentLength:r.length}),{stripped:n.trim(),counts:e}}function pt(r){return oo(r).stripped}var so=["task-notification"],io=new RegExp(`^\\s*<(${so.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),ao=256*1024;function Cr(r){return!r||r.length>ao?!1:io.test(r)}var co=j(M.API_REQUEST),F=class extends Error{kind;status;cause;constructor(e,t,n={}){super(t),this.name="ServerClientError",this.kind=e,this.status=n.status??null,this.cause=n.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)}},xe=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=uo(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??co}async startSession(e){let t=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",t)}async recordEvent(e){let t=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,t)}async endSession(e){if(!e.sessionId)throw new F("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 F("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let t=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,type:n,narrative:t,...o?{title:o}:{},...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}:{},...e.platformSource!==void 0?{platformSource:ft(e.platformSource)}:{}}}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:ft(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.platformSource!==void 0?{platformSource:ft(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,t,n){if(!this.apiKey||!this.apiKey.trim())throw new F("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let o=`${this.baseUrl}${t}`,i={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(i.body=JSON.stringify(n));let s;try{s=await lt(o,i,this.timeoutMs)}catch(u){let d=u instanceof Error?u.message:String(u),l=/timed out|timeout/i.test(d);throw new F(l?"timeout":"transport",`Server ${e} ${t} failed: ${d}`,{cause:u})}if(!s.ok){let u=await s.text().catch(()=>"");throw new F("http_error",`Server ${e} ${t} returned ${s.status}: ${lo(u,200)}`,{status:s.status})}let c=await s.text();if(!c||c.length===0)return{};try{return JSON.parse(c)}catch(u){let d=u instanceof Error?u:new Error(String(u));throw new F("invalid_response",`Server ${e} ${t} returned non-JSON response`,{cause:d})}}};function kr(r){return r instanceof F}function uo(r){return r.replace(/\/+$/,"")}function ft(r){return typeof r=="string"?I(r):null}function lo(r,e){return r.length<=e?r:`${r.slice(0,e)}\u2026`}function po(){let e=(x().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function fo(){let r=x(),e=(...s)=>{for(let c of s){let u=(c??"").trim();if(u.length>0)return u}return""},t=e(r.CLAUDE_MEM_SERVER_URL,r.CLAUDE_MEM_SERVER_BETA_URL),n=e(r.CLAUDE_MEM_SERVER_API_KEY,r.CLAUDE_MEM_SERVER_BETA_API_KEY),o=e(r.CLAUDE_MEM_SERVER_PROJECT_ID,r.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!t)return a.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return a.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return a.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let i={serverBaseUrl:t,apiKey:n};return{runtime:"server",client:new xe(i),projectId:o,serverBaseUrl:t}}function br(){if(po()!=="server")return{runtime:"worker"};let r=fo();return r||{runtime:"worker"}}function Or(r,e){a.warn("HOOK",`[server-fallback] reason=${r}`,e??{})}var mo={executeWithWorkerFallback:Oe,isWorkerFallback:be,loadFromFileOnce:x,resolveRuntimeContext:br,logServerFallback:Or,shouldTrackProject:Le},G=mo;var Ir={async execute(r){let{sessionId:e,prompt:t}=r,n=r.cwd??process.cwd();if(!e)return a.warn("HOOK","session-init: No sessionId provided, skipping (Codex CLI or unknown platform)"),{continue:!0,suppressOutput:!0,exitCode:$.SUCCESS};if(!G.shouldTrackProject(n))return a.info("HOOK","Project excluded from tracking",{cwd:n}),{continue:!0,suppressOutput:!0};if(t&&Cr(t))return a.debug("HOOK","session-init: skipping internal protocol payload",{preview:t.slice(0,80)}),{continue:!0,suppressOutput:!0};let o=!t||!t.trim()?"[media prompt]":t,i=J(n).primary,s=I(r.platform),c=G.loadFromFileOnce(),u=String(c.CLAUDE_MEM_SEMANTIC_INJECT).toLowerCase()==="true",d=G.resolveRuntimeContext();if(d.runtime==="server")try{return await go(d,r,e,s,i,o),{continue:!0,suppressOutput:!0}}catch(f){if(kr(f)&&f.isFallbackEligible())G.logServerFallback(f.kind,{status:f.status,message:f.message,route:"/v1/sessions/start"});else return a.error("HOOK","Server session-start failed (non-recoverable)",{error:f instanceof Error?f.message:String(f)}),{continue:!0,suppressOutput:!0,exitCode:$.SUCCESS}}a.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:e,project:i});let l=await G.executeWithWorkerFallback("/api/sessions/init","POST",{contentSessionId:e,project:i,prompt:o,platformSource:s});if(G.isWorkerFallback(l))return{continue:!0,suppressOutput:!0,exitCode:$.SUCCESS};if(typeof l?.sessionDbId!="number")return a.failure("HOOK","Session initialization returned malformed response",{contentSessionId:e,project:i}),{continue:!0,suppressOutput:!0,exitCode:$.SUCCESS};let S=l.sessionDbId,g=l.promptNumber;if(a.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:S,promptNumber:g,skipped:l.skipped,contextInjected:l.contextInjected}),a.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${e} | prompt#=${g} | sessionDbId=${S}`),l.skipped&&l.reason==="private")return a.info("HOOK",`INIT_COMPLETE | sessionDbId=${S} | promptNumber=${g} | skipped=true | reason=private`,{sessionId:S}),{continue:!0,suppressOutput:!0};let _="";if(u&&o&&o.length>=20&&o!=="[media prompt]"){let f=c.CLAUDE_MEM_SEMANTIC_INJECT_LIMIT||"5",W=await G.executeWithWorkerFallback("/api/context/semantic","POST",{q:o,project:i,limit:f,platformSource:s});!G.isWorkerFallback(W)&&W?.context&&(a.debug("HOOK",`Semantic injection: ${W.count} observations for prompt`,{sessionId:S,count:W.count}),_=W.context)}return a.info("HOOK",`INIT_COMPLETE | sessionDbId=${S} | promptNumber=${g} | project=${i}`,{sessionId:S}),_?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:_}}:{continue:!0,suppressOutput:!0}}};async function go(r,e,t,n,o,i){await r.client.startSession({projectId:r.projectId,externalSessionId:t,contentSessionId:t,agentId:e.agentId??null,agentType:e.agentType??null,platformSource:n,metadata:{project:o,prompt:i}}),a.info("HOOK","session-init: server session started",{contentSessionId:t,project:o})}var Pr={async execute(r){let{sessionId:e,cwd:t,filePath:n,edits:o}=r,i=I(r.platform);if(!n)throw new Error("fileEditHandler requires filePath");if(a.dataIn("HOOK",`FileEdit: ${n}`,{editCount:o?.length??0}),!t)throw new Error(`Missing cwd in FileEdit hook input for session ${e}, file ${n}`);if(!Le(t))return a.debug("HOOK","Project excluded from tracking, skipping file edit observation",{cwd:t,filePath:n}),{continue:!0,suppressOutput:!0,exitCode:$.SUCCESS};let s=await Oe("/api/sessions/observations","POST",{contentSessionId:e,platformSource:i,tool_name:"write_file",tool_input:{filePath:n,edits:o},tool_response:{success:!0},cwd:t});return be(s)?{continue:!0,suppressOutput:!0,exitCode:$.SUCCESS}:(a.debug("HOOK","File edit observation sent successfully",{filePath:n}),{continue:!0,suppressOutput:!0})}};var R=require("fs"),Ne=require("path");var ta=E.settings();function Dr(r,e){let t="<claude-mem-context>",n="</claude-mem-context>";if(!r)return`${t}
|
|
17
15
|
${e}
|
|
18
|
-
${
|
|
16
|
+
${n}`;let o=r.indexOf(t),i=r.indexOf(n);return o!==-1&&i!==-1?r.substring(0,o)+`${t}
|
|
19
17
|
${e}
|
|
20
|
-
${
|
|
18
|
+
${n}`+r.substring(i+n.length):r+`
|
|
21
19
|
|
|
22
|
-
${
|
|
20
|
+
${t}
|
|
23
21
|
${e}
|
|
24
|
-
${
|
|
22
|
+
${n}`}function Lr(r,e){if(!r)return;let t=(0,Ne.resolve)(r);if(t.includes("/.git/")||t.includes("\\.git\\")||t.endsWith("/.git")||t.endsWith("\\.git"))return;let n=(0,Ne.dirname)(r);(0,R.existsSync)(n)||(0,R.mkdirSync)(n,{recursive:!0});let o="";(0,R.existsSync)(r)&&(o=(0,R.readFileSync)(r,"utf-8"));let i=`# Memory Context
|
|
25
23
|
|
|
26
|
-
${e}`,
|
|
27
|
-
`);for(let
|
|
28
|
-
`);this.tailState.partial=
|
|
24
|
+
${e}`,s=Dr(o,i),c=`${r}.tmp`;try{(0,R.writeFileSync)(c,s),(0,R.renameSync)(c,r)}catch(u){a.error("AGENTS_MD","Failed to write AGENTS.md",{agentsPath:r},u instanceof Error?u:new Error(String(u)))}}function Eo(r){let e=r.trim().replace(/^\$\.?/,"");if(!e)return[];let t=[],n=e.split(".");for(let o of n){let i=/([^[\]]+)|\[(\d+)\]/g,s;for(;(s=i.exec(o))!==null;)s[1]?t.push(s[1]):s[2]&&t.push(parseInt(s[2],10))}return t}function mt(r,e){if(!e)return;let t=Eo(e),n=r;for(let o of t){if(n==null)return;n=n[o]}return n}function xr(r){return r==null||r===""}function Nr(r,e){if(r.startsWith("$watch.")){let t=r.slice(7);return e.watch[t]}if(r.startsWith("$schema.")){let t=r.slice(8);return e.schema[t]}if(r.startsWith("$session.")){let t=r.slice(9);return e.session?e.session[t]:void 0}if(r==="$cwd")return e.watch.workspace;if(r==="$project")return e.watch.project}function ee(r,e,t){if(r!==void 0){if(typeof r=="string"){let n=Nr(r,t);return n!==void 0?n:mt(e,r)}if(r.coalesce&&Array.isArray(r.coalesce))for(let n of r.coalesce){let o=ee(n,e,t);if(!xr(o))return o}if(r.path){let n=Nr(r.path,t);if(n!==void 0)return n;let o=mt(e,r.path);if(!xr(o))return o}if(r.value!==void 0)return r.value;if(r.default!==void 0)return r.default}}function Ur(r,e,t){let n={};if(!r)return n;for(let[o,i]of Object.entries(r))n[o]=ee(i,e,t);return n}function Fr(r,e,t){if(!e)return!0;let n=e.path||t.eventTypePath||"type",o=n?mt(r,n):void 0,i=o==null||o==="";if(e.exists!==void 0&&(e.exists&&i||!e.exists&&!i)||e.equals!==void 0&&o!==e.equals||e.not_equals!==void 0&&o===e.not_equals||e.in&&Array.isArray(e.in)&&!e.in.includes(o)||e.not_in&&Array.isArray(e.not_in)&&e.not_in.includes(o)||e.contains!==void 0&&(typeof o!="string"||!o.includes(e.contains))||e.not_contains!==void 0&&typeof o=="string"&&o.includes(e.not_contains))return!1;if(e.regex)try{if(!new RegExp(e.regex).test(String(o??"")))return!1}catch(s){return a.debug("WORKER","Invalid regex in match rule",{regex:e.regex},s instanceof Error?s:void 0),!1}return!0}var Ue=class{static checkUserPromptPrivacy(e,t,n,o,i,s){let c=e.getUserPrompt(t,n,i);return c===null?(a.warn("HOOK",`${o}: no user_prompts row for prompt #${n} \u2014 ingesting anyway (session-init likely raced worker boot; see #2794/#2795)`,{sessionId:i,contentSessionId:t,promptNumber:n,...s}),{allow:!0,prompt:""}):c.trim()===""?(a.debug("HOOK",`Skipping ${o} - user prompt was entirely private`,{sessionId:i,promptNumber:n,...s}),{allow:!1,reason:"private"}):{allow:!0,prompt:c}}};var Wr=null;function So(){if(!Wr)throw new Error("ingest helpers used before setIngestContext() \u2014 wiring bug");return Wr}async function Hr(r){let{sessionManager:e,dbManager:t,eventBroadcaster:n,ensureGeneratorRunning:o}=So(),i=I(r.platformSource),s=typeof r.cwd=="string"?r.cwd:"",c=s.trim()?J(s).primary:"",u=k.loadFromFile(ue);if(s&&De(s,u.CLAUDE_MEM_EXCLUDED_PROJECTS))return{ok:!0,status:"skipped",reason:"project_excluded"};if(new Set(u.CLAUDE_MEM_SKIP_TOOLS.split(",").map(y=>y.trim()).filter(Boolean)).has(r.toolName))return{ok:!0,status:"skipped",reason:"tool_excluded"};if(new Set(["Edit","Write","Read","NotebookEdit"]).has(r.toolName)&&r.toolInput&&typeof r.toolInput=="object"){let y=r.toolInput,K=y.file_path||y.notebook_path;if(K&&K.includes("session-memory"))return{ok:!0,status:"skipped",reason:"session_memory_meta"}}let S=t.getSessionStore(),g,_;try{g=S.createSDKSession(r.contentSessionId,c,"",void 0,i),_=S.getPromptNumberFromUserPrompts(r.contentSessionId,g)}catch(y){let K=y instanceof Error?y.message:String(y);return a.error("INGEST","Observation session resolution failed",{contentSessionId:r.contentSessionId,toolName:r.toolName},y instanceof Error?y:new Error(K)),{ok:!1,reason:K,status:500}}if(!Ue.checkUserPromptPrivacy(S,r.contentSessionId,_,"observation",g,{tool_name:r.toolName}).allow)return{ok:!0,status:"skipped",reason:"private"};let W=r.toolInput!==void 0?pt(JSON.stringify(r.toolInput)):"{}",ae=r.toolResponse!==void 0?pt(JSON.stringify(r.toolResponse)):"{}";return await e.queueObservation(g,{tool_name:r.toolName,tool_input:W,tool_response:ae,prompt_number:_,cwd:s||(a.error("INGEST","Missing cwd when ingesting observation",{sessionId:g,toolName:r.toolName}),""),agentId:typeof r.agentId=="string"?r.agentId:void 0,agentType:typeof r.agentType=="string"?r.agentType:void 0,toolUseId:typeof r.toolUseId=="string"?r.toolUseId:void 0}),await o?.(g,"observation"),n.broadcastObservationQueued(g),{ok:!0,sessionDbId:g}}var Fe=class{sessions=new Map;async processEntry(e,t,n,o){for(let i of n.events)Fr(e,i.match,n)&&await this.handleEvent(e,t,n,i,o??void 0)}getSessionKey(e,t){return`${e.name}:${t}`}getOrCreateSession(e,t){let n=this.getSessionKey(e,t),o=this.sessions.get(n);return o||(o={sessionId:t,platformSource:I(e.name)},this.sessions.set(n,o)),o}resolveSessionId(e,t,n,o,i){let s={watch:t,schema:n},c=o.fields?.sessionId??(n.sessionIdPath?{path:n.sessionIdPath}:void 0),u=ee(c,e,s);return typeof u=="string"&&u.trim()?u:typeof u=="number"?String(u):i&&i.trim()?i:null}resolveCwd(e,t,n,o,i){let s={watch:t,schema:n,session:i},c=o.fields?.cwd??(n.cwdPath?{path:n.cwdPath}:void 0),u=ee(c,e,s);return typeof u=="string"&&u.trim()?u:t.workspace?t.workspace:i.cwd}resolveProject(e,t,n,o,i){let s={watch:t,schema:n,session:i},c=o.fields?.project??(n.projectPath?{path:n.projectPath}:void 0),u=ee(c,e,s);return typeof u=="string"&&u.trim()?u:t.project?t.project:i.cwd?J(i.cwd).primary:i.project}async handleEvent(e,t,n,o,i){let s=this.resolveSessionId(e,t,n,o,i);if(!s){a.debug("TRANSCRIPT","Skipping event without sessionId",{event:o.name,watch:t.name});return}let c=this.getOrCreateSession(t,s),u=this.resolveCwd(e,t,n,o,c);u&&(c.cwd=u);let d=this.resolveProject(e,t,n,o,c);d&&(c.project=d);let l=Ur(o.fields,e,{watch:t,schema:n,session:c});switch(o.action){case"session_context":this.applySessionContext(c,l);break;case"session_init":await this.handleSessionInit(c,l),t.context?.updateOn?.includes("session_start")&&await this.updateContext(c,t);break;case"user_message":typeof l.message=="string"&&(c.lastUserMessage=l.message),typeof l.prompt=="string"&&(c.lastUserMessage=l.prompt);break;case"assistant_message":typeof l.message=="string"&&(c.lastAssistantMessage=l.message);break;case"tool_use":await this.handleToolUse(c,l);break;case"tool_result":await this.handleToolResult(c,l);break;case"observation":await this.sendObservation(c,l);break;case"file_edit":await this.sendFileEdit(c,l);break;case"session_end":await this.handleSessionEnd(c,t);break;default:break}}applySessionContext(e,t){let n=typeof t.cwd=="string"?t.cwd:void 0,o=typeof t.project=="string"?t.project:void 0;n&&(e.cwd=n),o&&(e.project=o)}async handleSessionInit(e,t){let n=typeof t.prompt=="string"?t.prompt:"",o=e.cwd??process.cwd();n&&(e.lastUserMessage=n),await Ir.execute({sessionId:e.sessionId,cwd:o,prompt:n,platform:e.platformSource})}async handleToolUse(e,t){let n=typeof t.toolId=="string"?t.toolId:void 0,o=typeof t.toolName=="string"?t.toolName:void 0,i=this.maybeParseJson(t.toolInput),s=this.maybeParseJson(t.toolResponse);if(o==="apply_patch"&&typeof i=="string"){let c=this.parseApplyPatchFiles(i);for(let u of c)await this.sendFileEdit(e,{filePath:u,edits:[{type:"apply_patch",patch:i}]})}o&&s!==void 0?await this.sendObservation(e,{toolName:o,toolInput:i,toolResponse:s,toolUseId:n}):o&&n&&(e.pendingTools||(e.pendingTools=new Map),e.pendingTools.set(n,{toolName:o,toolInput:i}))}async handleToolResult(e,t){let n=typeof t.toolId=="string"?t.toolId:void 0,o=typeof t.toolName=="string"?t.toolName:void 0,i=this.maybeParseJson(t.toolResponse),s=this.maybeParseJson(t.toolInput);if(n&&e.pendingTools){let c=e.pendingTools.get(n);c&&(o||(o=c.toolName),s===void 0&&(s=c.toolInput),e.pendingTools.delete(n))}o?await this.sendObservation(e,{toolName:o,toolInput:s,toolResponse:i,toolUseId:n}):a.debug("TRANSCRIPT","Dropping tool_result with no resolvable toolName",{sessionId:e.sessionId,toolId:n})}async sendObservation(e,t){let n=typeof t.toolName=="string"?t.toolName:void 0;if(!n)return;let o=await Hr({contentSessionId:e.sessionId,cwd:e.cwd??process.cwd(),toolName:n,toolInput:this.maybeParseJson(t.toolInput),toolResponse:this.maybeParseJson(t.toolResponse),platformSource:e.platformSource,toolUseId:typeof t.toolUseId=="string"?t.toolUseId:void 0});if(!o.ok)throw new Error(`ingestObservation failed: ${o.reason}`)}async sendFileEdit(e,t){let n=typeof t.filePath=="string"?t.filePath:void 0;n&&await Pr.execute({sessionId:e.sessionId,cwd:e.cwd??process.cwd(),filePath:n,edits:Array.isArray(t.edits)?t.edits:void 0,platform:e.platformSource})}maybeParseJson(e){if(typeof e!="string")return e;let t=e.trim();if(!t||!(t.startsWith("{")||t.startsWith("[")))return e;try{return JSON.parse(t)}catch(n){return a.debug("TRANSCRIPT","Field looked like JSON but did not parse; using raw string",{preview:t.slice(0,120)},n instanceof Error?n:void 0),e}}parseApplyPatchFiles(e){let t=[],n=e.split(`
|
|
25
|
+
`);for(let o of n){let i=o.trim();if(i.startsWith("*** Update File: "))t.push(i.replace("*** Update File: ","").trim());else if(i.startsWith("*** Add File: "))t.push(i.replace("*** Add File: ","").trim());else if(i.startsWith("*** Delete File: "))t.push(i.replace("*** Delete File: ","").trim());else if(i.startsWith("*** Move to: "))t.push(i.replace("*** Move to: ","").trim());else if(i.startsWith("+++ ")){let s=i.replace("+++ ","").replace(/^b\//,"").trim();s&&s!=="/dev/null"&&t.push(s)}}return Array.from(new Set(t))}async handleSessionEnd(e,t){await this.queueSummary(e),await this.updateContext(e,t),e.pendingTools?.clear();let n=this.getSessionKey(t,e.sessionId);this.sessions.delete(n)}async queueSummary(e){if(!await ke())return;let n=e.lastAssistantMessage??"",o=JSON.stringify({contentSessionId:e.sessionId,last_assistant_message:n,platformSource:e.platformSource});try{await U("/api/sessions/summarize",{method:"POST",headers:{"Content-Type":"application/json"},body:o})}catch(i){a.warn("TRANSCRIPT","Summary request failed",{error:i instanceof Error?i.message:String(i)})}}async updateContext(e,t){if(!t.context||t.context.mode!=="agents"||ht(t)||!await ke())return;let o=e.cwd??t.workspace;if(!o)return;let s=J(o).allProjects.join(","),c=`/api/context/inject?projects=${encodeURIComponent(s)}&platformSource=${encodeURIComponent(e.platformSource)}`,u=T(t.context.path??`${o}/AGENTS.md`),d=ie.default.resolve(u),l=[ie.default.resolve(o),ie.default.resolve(m)];if(!l.some(f=>d.startsWith(f+ie.default.sep)||d===f)){a.warn("SECURITY","Rejected path traversal attempt in watch.context.path",{original:t.context.path,resolved:d,allowedRoots:l});return}let g;try{g=await U(c)}catch(f){a.warn("TRANSCRIPT","Failed to fetch AGENTS.md context",{error:f instanceof Error?f.message:String(f)});return}if(!g.ok)return;let _=(await g.text()).trim();_&&(Lr(u,_),a.debug("TRANSCRIPT","Updated AGENTS.md context",{agentsPath:u,watch:t.name}))}};var gt=class{constructor(e,t,n,o){this.filePath=e;this.onLine=n;this.onOffset=o;this.tailState={offset:t,partial:""}}filePath;onLine;onOffset;watcher=null;tailState;start(){this.readNewData().catch(()=>{}),this.watcher=(0,h.watch)(this.filePath,{persistent:!0},()=>{this.readNewData().catch(()=>{})})}close(){this.watcher?.close(),this.watcher=null}poke(){this.readNewData().catch(()=>{})}async readNewData(){if(!(0,h.existsSync)(this.filePath))return;let e=0;try{e=(0,h.statSync)(this.filePath).size}catch(s){a.debug("WORKER","Failed to stat transcript file",{file:this.filePath},s instanceof Error?s:void 0);return}if(e<this.tailState.offset&&(this.tailState.offset=0),e===this.tailState.offset)return;let t=(0,h.createReadStream)(this.filePath,{start:this.tailState.offset,end:e-1,encoding:"utf8"}),n="";for await(let s of t)n+=s;this.tailState.offset=e,this.onOffset(this.tailState.offset);let i=(this.tailState.partial+n).split(`
|
|
26
|
+
`);this.tailState.partial=i.pop()??"";for(let s of i){let c=s.trim();c&&await this.onLine(c)}}},We=class{constructor(e,t){this.config=e;this.statePath=t;this.state=Mt(t)}config;statePath;processor=new Fe;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 t=this.resolveSchema(e);if(!t){a.warn("TRANSCRIPT","Missing schema for watch",{watch:e.name});return}let n=T(e.path),o=this.resolveWatchFiles(n);for(let s of o)await this.addTailer(s,e,t);let i=this.deepestNonGlobAncestor(n);if(!i||!(0,h.existsSync)(i)){a.debug("TRANSCRIPT","Watch root does not exist, skipping fs.watch",{watch:e.name,watchRoot:i});return}try{let s=(0,h.watch)(i,{recursive:!0,persistent:!0},(c,u)=>{this.handleRootWatchEvent(i,n,e,t,u)});this.rootWatchers.push(s),a.info("TRANSCRIPT","Watching transcript root recursively",{watch:e.name,watchRoot:i})}catch(s){a.warn("TRANSCRIPT","Failed to start recursive fs.watch on transcript root",{watch:e.name,watchRoot:i},s instanceof Error?s:void 0)}}handleRootWatchEvent(e,t,n,o,i){if(!i)return;let s=(0,A.resolve)(e,i).replace(/\\/g,"/"),c=this.tailers.get(s);if(c){c.poke();return}let u=this.resolveWatchFiles(t);for(let d of u)this.tailers.has(d)||this.addTailer(d,n,o)}deepestNonGlobAncestor(e){if(!this.hasGlob(e)){if((0,h.existsSync)(e))try{return(0,h.statSync)(e).isDirectory()?e:(0,A.resolve)(e,"..")}catch(o){return a.debug("TRANSCRIPT","Failed to stat watch path ancestor, falling back to parent directory",{path:e},o instanceof Error?o:new Error(String(o))),(0,A.resolve)(e,"..")}return e}let t=e.split(/[/\\]/),n=[];for(let o of t){if(/[*?[\]{}()]/.test(o))break;n.push(o)}return n.length===0||n.length===1&&n[0]===""?"":n.join(A.sep)}resolveSchema(e){return typeof e.schema=="string"?this.config.schemas?.[e.schema]??null:e.schema}resolveWatchFiles(e){if(this.hasGlob(e))return this.scanGlob(this.normalizeGlobPattern(e));if((0,h.existsSync)(e))try{if((0,h.statSync)(e).isDirectory()){let n=(0,A.join)(e,"**","*.jsonl");return this.scanGlob(this.normalizeGlobPattern(n))}return[e]}catch(t){return a.debug("WORKER","Failed to stat watch path",{path:e},t instanceof Error?t:void 0),[]}return[]}scanGlob(e){return Array.from(new Bun.Glob(e).scanSync({absolute:!0,onlyFiles:!0}))}normalizeGlobPattern(e){return e.replace(/\\/g,"/")}hasGlob(e){return/[*?[\]{}()]/.test(e)}async addTailer(e,t,n){if(this.tailers.has(e))return;let o=this.extractSessionIdFromPath(e),i=this.state.offsets[e]??0;if(i===0&&t.startAtEnd)try{i=(0,h.statSync)(e).size}catch(c){a.debug("WORKER","Failed to stat file for startAtEnd offset",{file:e},c instanceof Error?c:void 0),i=0}let s=new gt(e,i,async c=>{await this.handleLine(c,t,n,e,o)},c=>{this.state.offsets[e]=c,vt(this.statePath,this.state)});s.start(),this.tailers.set(e,s),a.info("TRANSCRIPT","Watching transcript file",{file:e,watch:t.name,schema:n.name})}async handleLine(e,t,n,o,i){try{let s=JSON.parse(e);await this.processor.processEntry(s,t,n,i??void 0)}catch(s){s instanceof Error?a.debug("TRANSCRIPT","Failed to parse transcript line",{watch:t.name,file:(0,A.basename)(o)},s):a.warn("TRANSCRIPT","Failed to parse transcript line (non-Error thrown)",{watch:t.name,file:(0,A.basename)(o),error:String(s)})}}extractSessionIdFromPath(e){let t=e.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i);return t?t[0]:null}};function Et(r,e){let t=r.indexOf(e);return t===-1?null:r[t+1]??null}async function $r(r,e){switch(r){case"init":{let t=Et(e,"--config")??q;return de(t),console.log(`Created sample config: ${T(t)}`),0}case"watch":{let t=Et(e,"--config")??q,n;try{n=ne(t)}catch(c){if(c instanceof Error&&c.message.includes("not found"))de(t),console.log(`Created sample config: ${T(t)}`),n=ne(t);else throw c}let o=T(n.stateFile??le),i=new We(n,o);await i.start(),console.log("Transcript watcher running. Press Ctrl+C to stop.");let s=()=>{i.stop(),process.exit(0)};return process.on("SIGINT",s),process.on("SIGTERM",s),await new Promise(()=>{})}case"validate":{let t=Et(e,"--config")??q;try{ne(t)}catch(n){if(n instanceof Error&&n.message.includes("not found"))de(t),console.log(`Created sample config: ${T(t)}`),ne(t);else throw n}return console.log(`Config OK: ${T(t)}`),0}default:return console.log("Usage: claude-mem transcript <init|watch|validate> [--config <path>]"),1}}var _o=process.argv[2],ho=process.argv.slice(3);$r(_o,ho).then(r=>{process.exit(r)}).catch(r=>{console.error(r),process.exit(1)});
|