memindex 1.1.0 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/.qoder-plugin/plugin.json +1 -1
- package/dist/npx-cli/index.js +1 -1
- package/integrations/dsh/package.json +1 -1
- package/integrations/openclaw/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/.codex-plugin/plugin.json +1 -1
- package/plugin/.qoder-plugin/plugin.json +1 -1
- package/plugin/package.json +1 -1
- package/plugin/scripts/mcp-server.cjs +2 -2
- package/plugin/scripts/transcript-watcher.cjs +1 -1
- package/plugin/scripts/worker-service.cjs +299 -295
- package/plugin/scripts/worker-service.cjs.map +2 -2
|
@@ -17,7 +17,7 @@ ${m.stack??""}
|
|
|
17
17
|
`)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);if(!n)continue;let s=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:s.length>0?s:null})}return e}async function tb(){let t;try{t=(await tc("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,@{Name='StartToken';Expression={$_.CreationDate.ToString('yyyyMMddHHmmss.ffffff')}} | ConvertTo-Csv -NoTypeInformation"],{timeout:3e4,windowsHide:!0,maxBuffer:33554432})).stdout}catch(r){return f.warn("PROCESS","Cannot enumerate the Windows process table \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),[]}let e=[];for(let r of t.split(/\r?\n/).slice(1)){let n=r.match(/^"(\d+)","(\d+)","(.*)"$/);if(!n)continue;let s=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:s.length>0?s:null})}return e}async function js(t){let e=await Qy(),r=new Map;for(let i of e){let a=r.get(i.ppid);a?a.push(i):r.set(i.ppid,[i])}let n=new Set([t]),s=[],o=i=>{for(let a of r.get(i)??[])n.has(a.pid)||(n.add(a.pid),o(a.pid),s.push({pid:a.pid,startToken:a.startToken}))};return o(t),s}var vf,Hs,Rf,tc,qy,Jy,Ws,yr=E(()=>{"use strict";vf=require("child_process"),Hs=require("fs"),Rf=require("util");O();Bs();tc=(0,Rf.promisify)(vf.execFile),qy=128,Jy=/not found|no running instance|no tasks/i,Ws=class extends Error{pid;constructor(e,r,n){super(r,n),this.name="ProcessTreeKillError",this.pid=e}}});function Y(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:(f.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return f.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function Xs(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!Y(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function Of(t){if(!t||!Y(t.pid))return!1;if(!t.startToken)return!0;let e=Ye(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||f.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}function Ks(t,e=ab){if(!Of(t))return!1;if(t.startToken||e.platform!=="linux")return!0;let r;try{r=e.readCommandLine(t.pid)}catch(s){return f.debug("SYSTEM","Could not read the command line of a token-less worker PID; trusting the live PID",{pid:t.pid,error:s instanceof Error?s.message:String(s)}),!0}let n=r.split("\0").some(s=>Af.default.basename(s)==="worker-service.cjs");return n||f.debug("SYSTEM","Token-less worker PID now belongs to another program (PID reused)",{pid:t.pid}),n}function gt(t=K.workerPid()){if(!(0,Vt.existsSync)(t))return null;let e;try{e=JSON.parse((0,Vt.readFileSync)(t,"utf-8"))}catch{return null}return e!==null&&Ks(e)?e:null}function Gs(){return rc||(rc=new sc),rc}function nc(){let t=cb.shift();t&&t.notify()}var Vt,Af,nb,sb,ob,ib,ab,sc,rc,qx,cb,mt=E(()=>{"use strict";Qa();Vt=require("fs"),Af=be(require("path"),1);O();se();mn();C();Bs();yr();nb=5e3,sb=1e3,ob=K.supervisorRegistry(),ib=null;ab={platform:process.platform,readCommandLine:t=>(0,Vt.readFileSync)(`/proc/${t}/cmdline`,"utf-8")};sc=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(e=ob){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,!(0,Vt.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Vt.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[s,o]of Object.entries(n))this.entries.set(s,o)}catch(r){r instanceof Error?f.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):f.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&f.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}retainSupersededEntry(e,r){let n=this.entries.get(e);if(!n||n.pid===r||!Y(n.pid))return;let s=`${e}#superseded:${n.pid}`;this.entries.set(s,n);let o=this.runtimeProcesses.get(e);o&&(this.runtimeProcesses.set(s,o),this.runtimeProcesses.delete(e)),f.warn("SYSTEM","Registry id reused while the previous process was still alive; kept it for reaping",{id:e,supersededId:s,supersededPid:n.pid,incomingPid:r})}register(e,r,n){this.initialize(),this.retainSupersededEntry(e,r.pid),this.entries.set(e,r),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e,r){this.initialize();let n=e,s=this.entries.get(n);r!==void 0&&s?.pid!==r&&(n=`${e}#superseded:${r}`,s=this.entries.get(n),s?.pid!==r)||s&&(this.entries.delete(n),this.runtimeProcesses.delete(n),this.persist(),s?.type==="sdk"&&nc())}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 n=Date.parse(e.startedAt),s=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(s)?0:s)})}getBySession(e){let r=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[n,s]of this.entries)Y(s.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,s.type==="sdk"&&(r+=1));e>0&&this.persist();for(let n=0;n<r;n+=1)nc();return e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;f.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:n,pids:r.map(a=>a.pid)});let s=r.filter(a=>Y(a.pid)),o=new Map(s.map(a=>[a.pid,Ye(a.pid)]));for(let a of s)try{process.platform==="win32"?await we(a.pid,{expectedStartToken:o.get(a.pid)??null}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&f.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):f.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}await Xs(s,nb);let i=s.filter(a=>Y(a.pid));for(let a of i){f.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});let c=o.get(a.pid)??null;if(!Ce(a.pid,c)){f.warn("SYSTEM","Skipping SIGKILL: session process PID was reused during the grace window",{pid:a.pid,sessionId:n});continue}try{process.platform==="win32"?await we(a.pid,{expectedStartToken:c}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(u){u instanceof Error?u.code!=="ESRCH"&&f.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},u):f.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(u)})}}if(i.length>0){let a=Date.now()+sb;for(;Date.now()<a&&i.filter(u=>Y(u.pid)).length!==0;)await new Promise(u=>setTimeout(u,100))}for(let a of r)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of r)a.type==="sdk"&&nc();return f.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:n,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};try{U(this.registryPath,e),this.persistDegraded=!1}catch(r){this.reportPersistFailure(r)}}reportPersistFailure(e){if(this.persistDegraded)return;this.persistDegraded=!0;let r=e instanceof Error?e:new Error(String(e));f.warn("SYSTEM","Failed to persist supervisor registry; keeping it in memory",{path:this.registryPath},r);try{ib?.({errorCategory:r.code??"unknown"})}catch{}}},rc=null;qx=180*1e3,cb=[]});async function Mf(t){let e=t.currentPid??process.pid,r=t.pidFilePath??ub,n=t.registry.getAll(),s=[...n].filter(c=>c.pid!==e).sort((c,u)=>Date.parse(u.startedAt)-Date.parse(c.startedAt)),o=new Map,i=new Map;for(let c of s){if(!Y(c.pid)){t.registry.unregister(c.id);continue}i.set(c.id,Ye(c.pid)),o.set(c.id,await js(c.pid));try{await Pf(c,"SIGTERM")}catch(u){u instanceof Error?f.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:c.pid,pgid:c.pgid,type:c.type},u):f.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(u)})}}await Xs(s,5e3);let a=s.filter(c=>Y(c.pid)||(o.get(c.id)??[]).some(u=>Y(u.pid)));for(let c of a){let u=Ce(c.pid,i.get(c.id)??null);u||f.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:c.pid,type:c.type});try{u&&await Pf(c,"SIGKILL")}catch(l){l instanceof Error?f.debug("SYSTEM","Failed to force kill child process",{pid:c.pid,pgid:c.pgid,type:c.type},l):f.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(l)})}finally{lb(o.get(c.id)??[],c.pid)}}await Xs(a,1e3);for(let c of s)t.registry.unregister(c.id);for(let c of n.filter(u=>u.pid===e))t.registry.unregister(c.id);xf(r,e),t.registry.pruneDeadEntries()}function xf(t,e,r=!1){if(!(0,br.existsSync)(t))return;let n=null;try{let i=JSON.parse((0,br.readFileSync)(t,"utf-8"));n=typeof i.pid=="number"?i.pid:null}catch(i){f.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:i instanceof Error?i.message:String(i)});return}let s=e!==null&&n===e,o=n===null||!Y(n);if(!s&&!(r&&o)){f.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:n,currentPid:e});return}try{(0,br.rmSync)(t,{force:!0})}catch(i){i instanceof Error?f.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},i):f.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(i)})}}function lb(t,e){for(let{pid:r,startToken:n}of t)if(!(r===e||!Y(r))){if(!Ce(r,n)){f.debug("SYSTEM","Skipping reap: PID was recycled during the grace window",{pid:r,rootPid:e});continue}try{process.kill(r,"SIGKILL"),f.debug("SYSTEM","Reaped orphaned descendant during shutdown cascade",{pid:r,rootPid:e})}catch(s){let o=s instanceof Error?s.code:void 0;o!=="ESRCH"&&f.warn("SYSTEM","Failed to reap orphaned descendant during shutdown cascade",{pid:r,rootPid:e,errno:o})}}}async function Pf(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}if(e==="SIGKILL"){await we(r,{signalMode:"immediate"});return}try{process.kill(r,e)}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}return}await we(r)}var br,ub,oc=E(()=>{"use strict";br=require("fs");O();mt();C();yr();ub=K.workerPid()});function db(){let e=Gs().pruneDeadEntries();e>0&&f.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function Nf(){wr===null&&(wr=setInterval(db,kf),wr.unref(),f.debug("SYSTEM","Health checker started",{intervalMs:kf}))}function Cf(){wr!==null&&(clearInterval(wr),wr=null,f.debug("SYSTEM","Health checker stopped"))}var kf,wr,Df=E(()=>{"use strict";O();mt();kf=3e4,wr=null});function gb(t){let e=[];for(let r of t.split(`
|
|
18
18
|
`)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);n&&e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),command:n[3].trim()})}return e}async function mb(){let t=await fb("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return gb(t.stdout)}function hb(t,e){let r=t.filter(i=>pb.test(i.command)&&i.pid!==e.selfPid),n=new Set(r.map(i=>i.pid)),s=r.filter(i=>!n.has(i.ppid)),o=s.filter(i=>i.ppid===e.selfPid?!1:i.ppid===1?!0:!e.isAlive(i.ppid));return{matched:r,roots:s,orphans:o}}async function Uf(t={}){let e=t.platform??process.platform,r={matched:0,trees:0,orphans:0,killed:0,failed:0,unregistered:0,skipped:null};if(e==="win32")return r.skipped="windows",r;let n=t.readTable??mb,s=t.isAlive??Y,o=t.killTree??(g=>we(g,{signalMode:"graceful"})),i=t.selfPid??process.pid,a;try{a=await n()}catch(g){return f.warn("PROCESS","Orphaned chroma-mcp sweep skipped: cannot read the process table",{error:g instanceof Error?g.message:String(g)}),r.skipped="unreadable",r}let{matched:c,roots:u,orphans:l}=hb(a,{isAlive:s,selfPid:i});if(r.matched=c.length,r.trees=u.length,r.orphans=l.length,l.length===0)return f.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:r.matched,trees:r.trees}),r;f.warn("PROCESS","Reaping orphaned chroma-mcp trees left by dead workers",{orphans:l.length,roots:l.map(g=>g.pid)});let d=new Set,p=8;for(let g=0;g<l.length;g+=p){let m=l.slice(g,g+p);(await Promise.allSettled(m.map(_=>o(_.pid)))).forEach((_,S)=>{let b=m[S];_.status==="fulfilled"?(r.killed+=1,d.add(b.pid)):(r.failed+=1,f.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:b.pid,ppid:b.ppid,error:_.reason instanceof Error?_.reason.message:String(_.reason)}))})}if(t.registry)for(let g of t.registry.getAll())g.type==="chroma"&&d.has(g.pid)&&(t.registry.unregister(g.id),r.unregistered+=1);return f.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:r.orphans,killed:r.killed,failed:r.failed,unregistered:r.unregistered}),r}var Ff,Lf,fb,pb,$f=E(()=>{"use strict";Ff=require("child_process"),Lf=require("util");O();yr();mt();fb=(0,Lf.promisify)(Ff.execFile),pb=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/});function Bf(t={}){let e=t.pidFilePath??_b;if(!(0,Yt.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,Yt.readFileSync)(e,"utf-8"))}catch(s){return s instanceof Error?f.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},s):f.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(s)}),(0,Yt.rmSync)(e,{force:!0}),"invalid"}return Ks(r)&&r?((t.logAlive??!0)&&f.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(t.removeStale===!1||(f.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,Yt.rmSync)(e,{force:!0})),"stale")}var Yt,_b,ic,hk,hn=E(()=>{"use strict";Yt=require("fs");O();mt();oc();Df();$f();C();mt();_b=K.workerPid(),ic=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(),Bf({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,Uf({registry:this.registry}).catch(r=>{f.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),Nf()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){f.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,f.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(s){s instanceof Error?f.error("SYSTEM","Error during shutdown",{},s):f.error("SYSTEM","Error during shutdown (non-Error)",{error:String(s)});try{await this.stop()}catch(o){o instanceof Error?f.debug("SYSTEM","Supervisor shutdown fallback failed",{},o):f.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(o)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{f.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}Cf(),this.stopPromise=Mf({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,n){this.registry.register(e,r,n)}unregisterProcess(e,r){this.registry.unregister(e,r)}getRegistry(){return this.registry}},hk=new ic(Gs())});function Wf(t,e){if(!(0,zs.existsSync)(t))return e;try{return jt((0,zs.readFileSync)(t,"utf-8"))}catch(r){throw new Error(`Corrupt JSON file, refusing to overwrite: ${t}: ${r instanceof Error?r.message:String(r)}`)}}var zs,jf=E(()=>{"use strict";zs=require("fs");se()});function Eb(t){let e=t.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function Sb(t,e){if(Eb(t))return{enabled:!1,source:"DO_NOT_TRACK"};let r=t.MEMINDEX_TELEMETRY?.toLowerCase();return r==="0"||r==="false"||r==="off"?{enabled:!1,source:"env"}:t.MEMINDEX_TELEMETRY_KEY?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:!1,source:"default"}:{enabled:!1,source:"no-key"}}function Ys(t,e){return Sb(t,e).enabled}function Kf(t){let e=t.MEMINDEX_TELEMETRY_ERRORS?.toLowerCase();return!(e==="0"||e==="false"||e==="off")}function yb(){return(0,ac.join)(N(),Xf)}function _n(){let t;try{t=Wf(yb(),null)}catch(e){let r=e instanceof Error?e:new Error(String(e));return f.warn("SYSTEM","Telemetry: corrupt telemetry.json; treating as no recorded consent",void 0,r),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:""}}function bb(t){let e=N();(0,Vs.mkdirSync)(e,{recursive:!0}),(0,Vs.writeFileSync)((0,ac.join)(e,Xf),JSON.stringify(t,null,2)+`
|
|
19
19
|
`)}function qs(){let t=_n();if(t?.installId)return t.installId;let e=(0,Hf.randomUUID)();return bb({installId:e,decidedAt:""}),e}var ac,Vs,Hf,Xf,cc=E(()=>{"use strict";ac=require("path"),Vs=require("fs"),Hf=require("crypto");C();jf();O();Xf="telemetry.json"});function Yf(t){try{if(typeof t!="string"){if(t==null)return"";try{t=String(t)}catch(r){let n=r instanceof Error?r:new Error(String(r));return f.warn("SYSTEM","error-scrub: String() coercion of non-string input failed",void 0,n),""}}let e=t;return e.length>zf?e.slice(0,zf):e}catch{return""}}function uc(t){if(typeof t!="string"||t.length===0)return t??"";let e="";try{e=Vf.default.homedir()||""}catch(n){let s=n instanceof Error?n:new Error(String(n));f.warn("SYSTEM","error-scrub: os.homedir() failed; skipping home-dir redaction",void 0,s),e=""}if(!e)return t;let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");try{return t.replace(new RegExp(r,"g"),"~")}catch(n){let s=n instanceof Error?n:new Error(String(n));return f.warn("SYSTEM","error-scrub: home-dir RegExp replace failed; using split/join fallback",void 0,s),t.split(e).join("~")}}function lc(t){return typeof t!="string"||t.length===0?t??"":t.replace(/(?<![~\w])\/(?:[^\s/:"'()]+\/)+([^\s/:"'()]+)/g,"$1").replace(/[A-Za-z]:\\(?:[^\s\\:"'()]+\\)*([^\s\\:"'()]+)/g,"$1").replace(/\\\\[^\s\\:"'()]+(?:\\[^\s\\:"'()]+)*\\([^\s\\:"'()]+)/g,"$1")}function wb(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\b[A-Za-z][A-Za-z0-9+.-]*:\/\/[^\s"'()]+/g,e=>/^https?:\/\/hooks\.slack\.com\/services\//i.test(e)?e.replace(/^(https?:\/\/hooks\.slack\.com\/services\/)[^\s"'()]+/i,`$1${Te}`):e.replace(/[?#].*$/,"").replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/@\s]+@/,`$1${Te}@`))}function Tb(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\?[^\s"'()]*/g,"")}function Ib(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\b(?:access[_-]?token|api[_-]?key|auth(?:orization)?|secret|password|passwd|jwt|session[_-]?id|token)=[^\s"'&]+/gi,e=>{let r=e.indexOf("=");return`${e.slice(0,r+1)}${Te}`})}function vb(t){if(typeof t!="string"||t.length===0)return t??"";let e=t;return e=e.replace(/[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}/g,Te),e=e.replace(/\b[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\b/g,Te),e=e.replace(/\b(?:sk|pk|rk|ak|phc|phx|ph|ghp|gho|ghs|xox[bpasr])[-_][A-Za-z0-9_-]{8,512}\b/gi,Te),e=e.replace(/\bBearer\s+[A-Za-z0-9._-]{8,512}\b/gi,Te),e=e.replace(/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g,Te),e=e.replace(/\b[0-9a-fA-F]{24,4096}\b/g,Te),e=e.replace(/\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/g,Te),e=e.replace(/\b(?=[A-Za-z0-9+/_-]{0,4096}\d)[A-Za-z0-9+/_-]{32,4096}={0,2}\b/g,Te),e=e.replace(/\b(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}\b/g,Te),e}function Rb(t){return typeof t!="string"||t.length===0?t??"":t.replace(/[ \t\f\v]+/g," ").replace(/ *\n */g,`
|
|
20
|
-
`).trim()}function dc(t){let e=Yf(t);return e.length===0?"":(e=uc(e),e=wb(e),e=lc(e),e=Tb(e),e=Ib(e),e=vb(e),e)}function qf(t){try{let e=Rb(dc(Yf(t)));return e.length>Gf?e.slice(0,Gf):e}catch(e){let r=e instanceof Error?e:new Error(String(e));return f.warn("SYSTEM","error-scrub: message scrub failed; emitting empty message",void 0,r),""}}function Jf(t){return(typeof t=="string"?t:"").replace(/\[REDACTED\]/g,"\xA7").replace(/'[^']*'/g,"'\xA7'").replace(/"[^"]*"/g,'"\xA7"').replace(/\b\d+\b/g,"\xA7").replace(/[ \t]+/g," ").trim().slice(0,200)}var Vf,Gf,zf,Te,fc=E(()=>{"use strict";Vf=be(require("os"),1);O();Gf=500,zf=8192,Te="[REDACTED]"});function Ob(t,e){if(!(!t||typeof t!="object"))for(let r of Object.keys(t)){if(!Ab.has(r))continue;let n=t[r];if(typeof n=="string"){let s=n.length>Qf?n.slice(0,Qf):n;e[r]=dc(s)}else(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(e[r]=n)}}function Js(t){let e={};try{Ob(t,e)}catch{}return e}var Ab,Qf,pc=E(()=>{"use strict";fc();Ab=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","phase","install_method","interactive","provider_source","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","limit_window","overage_status","is_using_overage","resets_in_minutes","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_aborted_deadline_exceeded","outcomes_invalid_output","top_model","top_abort_reason","observed_model","observed_billing","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","skill_id","skill_source","skill_trigger","observations_created","total_observations_injected","total_tokens_saved_vs_naive"]),Qf=200});function Qs(){return process.env.MEMINDEX_TELEMETRY_KEY??""}function Zs(){return process.env.MEMINDEX_TELEMETRY_HOST||Mb}function eo(t){let e={};for(let r of xb)t[r]!==void 0&&(e[r]=t[r]);return e}function kb(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||gc.default.release().toLowerCase().includes("microsoft")}catch(t){let e=t instanceof Error?t:new Error(String(t));return f.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function to(){return{version:Pb,os:process.platform,os_version:gc.default.release(),is_wsl:kb(),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 gc,Pb,Mb,xb,mc=E(()=>{"use strict";gc=be(require("os"),1);O();Pb="1.1.
|
|
20
|
+
`).trim()}function dc(t){let e=Yf(t);return e.length===0?"":(e=uc(e),e=wb(e),e=lc(e),e=Tb(e),e=Ib(e),e=vb(e),e)}function qf(t){try{let e=Rb(dc(Yf(t)));return e.length>Gf?e.slice(0,Gf):e}catch(e){let r=e instanceof Error?e:new Error(String(e));return f.warn("SYSTEM","error-scrub: message scrub failed; emitting empty message",void 0,r),""}}function Jf(t){return(typeof t=="string"?t:"").replace(/\[REDACTED\]/g,"\xA7").replace(/'[^']*'/g,"'\xA7'").replace(/"[^"]*"/g,'"\xA7"').replace(/\b\d+\b/g,"\xA7").replace(/[ \t]+/g," ").trim().slice(0,200)}var Vf,Gf,zf,Te,fc=E(()=>{"use strict";Vf=be(require("os"),1);O();Gf=500,zf=8192,Te="[REDACTED]"});function Ob(t,e){if(!(!t||typeof t!="object"))for(let r of Object.keys(t)){if(!Ab.has(r))continue;let n=t[r];if(typeof n=="string"){let s=n.length>Qf?n.slice(0,Qf):n;e[r]=dc(s)}else(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(e[r]=n)}}function Js(t){let e={};try{Ob(t,e)}catch{}return e}var Ab,Qf,pc=E(()=>{"use strict";fc();Ab=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","phase","install_method","interactive","provider_source","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","limit_window","overage_status","is_using_overage","resets_in_minutes","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_aborted_deadline_exceeded","outcomes_invalid_output","top_model","top_abort_reason","observed_model","observed_billing","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","skill_id","skill_source","skill_trigger","observations_created","total_observations_injected","total_tokens_saved_vs_naive"]),Qf=200});function Qs(){return process.env.MEMINDEX_TELEMETRY_KEY??""}function Zs(){return process.env.MEMINDEX_TELEMETRY_HOST||Mb}function eo(t){let e={};for(let r of xb)t[r]!==void 0&&(e[r]=t[r]);return e}function kb(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||gc.default.release().toLowerCase().includes("microsoft")}catch(t){let e=t instanceof Error?t:new Error(String(t));return f.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function to(){return{version:Pb,os:process.platform,os_version:gc.default.release(),is_wsl:kb(),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 gc,Pb,Mb,xb,mc=E(()=>{"use strict";gc=be(require("os"),1);O();Pb="1.1.1",Mb="https://us.i.posthog.com";xb=["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"]});async function Zf(t,e,r){try{if(!Ys(process.env,_n()))return;let n=Js({...to(),...e??{}});if(r?.person?n.$set=eo(n):n.$process_person_profile=!1,process.env.MEMINDEX_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:t,properties:n})+`
|
|
21
21
|
`);return}let s=Qs(),o=new AbortController,i=setTimeout(()=>o.abort(),Nb);try{await Cb(s,t,n,o.signal)}finally{clearTimeout(i)}}catch{}}async function Cb(t,e,r,n){await fetch(`${Zs()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:t,event:e,distinct_id:qs(),properties:r}),signal:n})}var Nb,ep=E(()=>{"use strict";cc();pc();mc();Nb=2e3});var tp=E(()=>{"use strict";O()});var rp=E(()=>{"use strict";O();tp()});function no(t){return t.error?.name==="ETIMEDOUT"}function so(t,e,r=np){let n=`git -C ${t} ${e.join(" ")}`,s=Date.now();return new Promise(o=>{let i=!1,a=!1,c="",u="",l=g=>{if(i)return;i=!0,clearTimeout(p);let m=Date.now()-s;m>1e3&&f.debug("GIT",`Slow git operation: ${n} took ${m}ms`),o(g)},d=(0,ro.spawn)("git",["-C",t,...e],{stdio:["ignore","pipe","pipe"],windowsHide:!0}),p=setTimeout(()=>{a=!0,d.kill("SIGTERM"),d.stdout?.destroy(),d.stderr?.destroy();let g=Object.assign(new Error(`git timed out after ${r}ms`),{name:"ETIMEDOUT"});f.warn("GIT",`Git operation failed: ${n}`,{error:g.message,timedOut:!0}),l({status:null,stdout:"",error:g})},r);d.stdout?.setEncoding("utf8"),d.stderr?.setEncoding("utf8"),d.stdout?.on("data",g=>{c+=g}),d.stderr?.on("data",g=>{u+=g}),d.once("error",g=>{f.warn("GIT",`Git operation failed: ${n}`,{error:g.message,timedOut:!1}),l({status:null,stdout:"",error:g})}),d.once("close",(g,m)=>{if(!a){if(g!==0){f.debug("GIT",`Git returned non-zero exit code ${g??m}: ${n}`,{stderr:u.trim()}),l({status:g,stdout:"",error:void 0});return}l({status:g,stdout:c.trim(),error:void 0})}})})}function hc(t,e,r=np){let n=(0,ro.spawnSync)("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:Math.min(r,Db),windowsHide:!0});return n.error?{status:null,stdout:"",error:n.error}:n.status!==0?{status:n.status,stdout:"",error:void 0}:{status:0,stdout:(n.stdout??"").trim(),error:void 0}}var ro,np,Db,_c=E(()=>{"use strict";ro=require("child_process");O();np=5e3,Db=5e3});function sp(t){let e=Rt.default.join(t,".git"),r;try{r=(0,oo.statSync)(e)}catch(c){return c instanceof Error&&c.code!=="ENOENT"&&f.warn("GIT","Unexpected error checking .git",{error:c instanceof Error?c.message:String(c)}),En}if(!r.isFile())return En;let n;try{n=(0,oo.readFileSync)(e,"utf-8").trim()}catch(c){return f.warn("GIT","Failed to read .git file",{error:c instanceof Error?c.message:String(c)}),En}let s=n.match(/^gitdir:\s*(.+)$/);if(!s)return En;let o=Rt.default.resolve(Rt.default.dirname(e),s[1]),i=o.match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(i){let c=i[1];return{isWorktree:!0,isSubmodule:!1,worktreeName:Rt.default.basename(t),parentRepoPath:c,parentProjectName:Rt.default.basename(c)}}let a=o.match(/^(.+)[/\\]\.git[/\\]modules[/\\](.+)$/);if(a){let c=a[1];return{isWorktree:!1,isSubmodule:!0,worktreeName:Rt.default.basename(t),parentRepoPath:c,parentProjectName:Rt.default.basename(c)}}return En}var oo,Rt,En,op=E(()=>{"use strict";oo=require("fs"),Rt=be(require("path"),1);O();En={isWorktree:!1,isSubmodule:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null}});function ip(t){let e=he(t.replace(/\\/g,"/"));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 Sc(t,e){if(!e.length)return!1;let r=t.replace(/\\/g,"/"),n=(0,Ec.basename)(r);for(let s of e){let o=s.trim();if(o)try{let i=ip(o);if(i.test(r)||i.test(n))return!0}catch(i){f.warn("PROJECT_NAME","Invalid glob pattern",{pattern:o,error:i instanceof Error?i.message:String(i)});continue}}return!1}function io(t,e){if(!e||!e.trim())return!1;let r=t.replace(/\\/g,"/"),n=(0,Ec.basename)(r),s=e.split(",").map(o=>o.trim()).filter(Boolean);for(let o of s)try{let i=ip(o);if(i.test(r)||i.test(n))return!0}catch(i){f.warn("PROJECT_NAME","Invalid exclusion pattern",{pattern:o,error:i instanceof Error?i.message:String(i)});continue}return!1}var Ec,Sn=E(()=>{"use strict";Ec=require("path");Wt();O()});function cp(t){let e=t;if(typeof e=="string"){if(!e.trim())return[];try{e=JSON.parse(e)}catch(n){return f.warn("PROJECT_NAME","MEMINDEX_PROJECT_ENVIRONMENTS is not valid JSON; ignoring it",{error:n instanceof Error?n.message:String(n)}),[]}}if(!Array.isArray(e))return e!=null&&f.warn("PROJECT_NAME","MEMINDEX_PROJECT_ENVIRONMENTS must be an array; ignoring it",{}),[];let r=[];for(let n of e){let s=typeof n?.name=="string"?n.name.trim():"",o=Array.isArray(n?.patterns)?n.patterns.filter(i=>typeof i=="string"&&i.trim()!==""):[];if(!s||o.length===0){f.warn("PROJECT_NAME","Ignoring a project environment without a name or patterns",{name:s});continue}r.push({name:s,patterns:o})}return r}function Fb(t){try{return(0,ap.realpathSync)(t)}catch{return t}}function yc(t,e){if(e.length===0)return null;let r=[...new Set([t,Fb(t)])].flatMap(n=>[n,`${n.replace(/[\\/]+$/,"")}/`]);for(let n of e)if(r.some(s=>Sc(s,n.patterns)))return n.name;return null}var ap,up=E(()=>{"use strict";ap=require("fs");Sn();O()});function fp(t){let e=process.env[Lb]?.trim();return e||(!t||t.trim()===""?null:t)}function pp(t){return gp(t,hc(t,["rev-parse","--show-toplevel"]))}async function Bb(t){let e=Date.now(),r=Tr.get(t);if(r&&e-r.at<Ub)return(await r.answer).root;Tr.size>=$b&&Tr.clear();let n=so(t,["rev-parse","--show-toplevel"]).then(a=>({root:gp(t,a),kept:!no(a)})),s={at:e,answer:n};Tr.set(t,s);let{root:o,kept:i}=await n;return!i&&Tr.get(t)===s&&Tr.delete(t),o}function gp(t,e){return e.status===0&&e.stdout?e.stdout:(f.debug("PROJECT_NAME","git rev-parse failed, falling back to non-git root",{dir:t},e.error),null)}function mp(t){try{return(0,vr.realpathSync)(t)}catch{return t}}function Hb(t,e){let r=ue.default.relative(e,t);return r===""||!r.startsWith("..")&&!ue.default.isAbsolute(r)}function Xb(){return[(0,uo.homedir)(),(0,uo.tmpdir)(),lt].flatMap(t=>{let e=ue.default.resolve(t);return[e,mp(e)]})}function hp(t){let e=Xb(),r=ue.default.resolve(t);if([ue.default.resolve(lt),mp(ue.default.resolve(lt))].some(s=>Hb(r,s)))return null;for(let s=0;s<jb;s++){if(e.includes(r))return null;let o=ue.default.dirname(r);if(o===r)return null;if(Wb.some(i=>(0,vr.existsSync)(ue.default.join(r,i))))return r;r=o}return null}function bc(t,e){let r=ue.default.basename(e);if(r===""){if(process.platform==="win32"){let s=t.match(/^([A-Z]):\\/i);if(s){let i=`drive-${s[1].toUpperCase()}`;return f.info("PROJECT_NAME","Drive root detected",{cwd:t,projectName:i}),i}}return f.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:t}),wc}return r}function lp(){try{return(0,vr.statSync)(_e).mtimeMs}catch{return-1}}function _p(){let t=lp();if(t===-1)return V.getAllDefaults();if(ao&&ao.mtimeMs===t)return ao.settings;let e=V.loadFromFile(_e);return ao={mtimeMs:lp(),settings:e},e}function Ep(){let t=process.env[Kb]??_p().MEMINDEX_PROJECT_NAME_SOURCE;return String(t??"path").trim().toLowerCase()==="git-remote"}function Sp(){let t=process.env[Gb]??_p().MEMINDEX_PROJECT_ENVIRONMENTS;return(!co||co.raw!==t)&&(co={raw:t,environments:cp(t)}),co.environments}function zb(t){let e=(t??"").trim();if(!e||/^file:/i.test(e)||e.startsWith("/")||e.startsWith(".")||e.startsWith("~")||e.startsWith("\\\\")||/^[a-z]:[\\/]/i.test(e))return null;let n=e.replace(/\/+$/,"").replace(/\.git$/i,""),s=n.match(/^[a-z][a-z0-9+.-]*:\/\/[^/]+\/(.+)$/i),o=s?null:n.match(/^(?:[^/@\s]+@)?[^:/\s]+:(?!\/\/)(.+)$/),i=s?.[1]??o?.[1];if(!i)return null;let a=i.split("/").filter(c=>c&&c!=="_git");return a.length>=2?a.slice(-2).join("/"):a.length===1?a[0]:null}function yp(t,e){return e.status===0&&e.stdout?zb(e.stdout):(f.debug("PROJECT_NAME","No usable origin remote, keeping the path-based name",{repoRoot:t},e.error),null)}function bp(t){return Ep()?(Ir.has(t)||Ir.set(t,yp(t,hc(t,["remote","get-url","origin"]))),Ir.get(t)??null):null}async function Vb(t){if(!Ep())return null;if(!Ir.has(t)){let e=await so(t,["remote","get-url","origin"]);if(no(e))return null;Ir.set(t,yp(t,e))}return Ir.get(t)??null}function Yb(t,e=process.platform){if(!t||t.trim()==="")return f.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),wc;let r=he(t,e),n=yc(r,Sp());if(n)return n;let s=pp(r),o=s?bp(s):null;if(o)return o;let i=s??hp(r)??r;return bc(t,i)}function wp(t,e){return e===t?t:`${t}/${e}`}function qb(t,e){if(!t.isSubmodule||!t.parentRepoPath)return null;let r=ue.default.relative(t.parentRepoPath,e);return!r||r.startsWith("..")||ue.default.isAbsolute(r)?null:r.split(ue.default.sep).join("/")}function lo(t,e=process.platform){if(!t||t.trim()==="")return Tp(t,e);let r=he(t,e),n=pp(r),s=n?bp(n):null;return Ip(t,r,n,s)}async function yn(t,e=process.platform){if(!t||t.trim()==="")return Tp(t,e);let r=he(t,e),n=await Bb(r),s=n?await Vb(n):null;return Ip(t,r,n,s)}function Tp(t,e){let r=Yb(t,e);return{primary:r,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[r],keySource:"path"}}function Ip(t,e,r,n){let s=Jb(t,e,r),o=n?dp(s,n,"git-remote"):s,i=yc(e,Sp());return i?dp(o,i,"environment"):o}function dp(t,e,r){return{primary:e,parent:null,isWorktree:t.isWorktree,isSubmodule:t.isSubmodule,allProjects:[...t.allProjects.filter(n=>n!==e),e],keySource:r}}function Jb(t,e,r){let n=r?null:hp(e),s=bc(t,r??n??e),o=r??e,i=sp(o);if((i.isWorktree||i.isSubmodule)&&i.parentProjectName){let a=i.parentProjectName,c,u;return i.isSubmodule?(c=`${a}/${qb(i,o)??s}`,u=s!==a?[s]:[]):(c=wp(a,s),u=c===a?[`${a}/${s}`]:[]),{primary:c,parent:a,isWorktree:i.isWorktree,isSubmodule:i.isSubmodule,allProjects:[...new Set([a,...u,c])].filter(l=>l!==c).concat(c),keySource:"path"}}if(n&&ue.default.resolve(n)!==ue.default.resolve(e)){let a=bc(t,e);if(a!==s&&a!==wc)return{primary:s,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[a,s],keySource:"path"}}return{primary:s,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[s],keySource:"path"}}var ue,vr,uo,Lb,wc,Ub,$b,Tr,Wb,jb,Kb,ao,Gb,co,Ir,qt=E(()=>{"use strict";ue=be(require("path"),1),vr=require("fs"),uo=require("os");Wt();C();dt();O();_c();op();up();Lb="CLAUDE_PROJECT_DIR",wc="unknown-project";Ub=3e4,$b=500,Tr=new Map;Wb=[".memindex-project",".memindex.json"],jb=64;Kb="MEMINDEX_PROJECT_NAME_SOURCE",ao=null;Gb="MEMINDEX_PROJECT_ENVIRONMENTS",co=null;Ir=new Map});function Zb(t){return t===void 0?vp:Math.max(1,Math.min(vp,t))}function tw(t){try{return(0,Ee.realpathSync)(t)}catch{return null}}function Tc(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function rw(t,e){let r=e==="win32"?"where.exe":"which",n=[t],s;try{s=(0,fo.execFileSync)(r,n,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(i){return i instanceof Error?f.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r,args:n},i):f.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r,args:n},new Error(String(i))),null}return s.split(/\r?\n/).map(i=>i.trim()).find(i=>i.length>0)||null}function po(t={}){let e=Object.keys(t).length===0;if(e&&Ic!==void 0)return Ic;let r=nw(t);return e&&r!==null&&(Ic=r),r}function Rp(t,e){let r=t?.trim();return r?e==="win32"?[ge.default.join(r,"bin","bun.exe"),ge.default.join(r,"bin","bun"),ge.default.join(r,"bun.exe")]:[ge.default.join(r,"bin","bun"),ge.default.join(r,"bun")]:[]}function nw(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(Tc(r))return r;let n=t.env??process.env,s=t.homeDirectory??(0,vc.homedir)(),o=t.pathExists??Ee.existsSync,i=t.lookupInPath??rw,a=t.realpath??tw,c=e==="win32"?[n.BUN,n.BUN_PATH,...Rp(n.BUN_INSTALL,e),ge.default.join(s,".bun","bin","bun.exe"),ge.default.join(s,".bun","bin","bun"),n.USERPROFILE?ge.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?ge.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?ge.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0,n.npm_config_prefix?ge.default.join(n.npm_config_prefix,"bun.exe"):void 0]:[n.BUN,n.BUN_PATH,...Rp(n.BUN_INSTALL,e),ge.default.join(s,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun",n.npm_config_prefix?ge.default.join(n.npm_config_prefix,"bin","bun"):void 0];for(let d of c){let p=d?.trim();if(p&&(Tc(p)&&o(p)||p.toLowerCase()==="bun"))return p}let u=i("bun",e)?.trim();if(!u||!Tc(u))return null;let l=a(u)??u;return o(l)?l:null}function Rc(){let t=K.dataDir();return(0,Ee.mkdirSync)(t,{recursive:!0}),t}function sw(t,e,r=Rc()){let n=s=>s.replace(/'/g,"''");return`Start-Process -FilePath '${n(t)}' -ArgumentList @('"${n(e)}"','--daemon') -WorkingDirectory '${n(r)}' -WindowStyle Hidden`}function ow(t=process.env){let e=t.SystemRoot||t.SYSTEMROOT;return e?`${e}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`:"powershell.exe"}function iw(t,e,r=Rc()){return["-NoProfile","-WindowStyle","Hidden","-EncodedCommand",Buffer.from(sw(t,e,r),"utf16le").toString("base64")]}function go(t,e,r,n=process.platform,s){if(n==="win32"){let l=ow(r),d=iw(t,e),p=Zb(s);try{let g=(0,fo.spawnSync)(l,d,{stdio:"ignore",windowsHide:!0,env:r,timeout:p,killSignal:"SIGTERM"});if(g.error)throw g.error;if(g.signal)throw new Error(`powershell Start-Process killed by signal=${g.signal} after ${p}ms`);if(g.status!==0)throw new Error(`powershell Start-Process exited ${g.status??"null"}`);return 0}catch(g){let m=g instanceof Error?g:new Error(String(g));f.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:t,powershell:l},m);return}}let o="/usr/bin/setsid",i=(0,Ee.existsSync)(o),a=i?o:t,u=Ja(a,i?[t,e,"--daemon"]:[e,"--daemon"],{detached:!0,stdio:"ignore",cwd:Rc(),env:r});if(u.on("error",l=>{f.error("SYSTEM",ew,{runtimePath:t,execPath:a},l)}),u.pid!==void 0)return u.unref(),u.pid}var ge,vc,Ee,fo,vp,y0,b0,ew,Ic,Ac=E(()=>{"use strict";ge=be(require("path"),1),vc=require("os"),Ee=require("fs"),fo=require("child_process");Qa();O();mn();oc();hn();rp();qt();_c();C();xe();mt();vp=ze(Q.POWERSHELL_COMMAND);y0=K.dataDir(),b0=K.workerPid(),ew="Bun runtime not found \u2014 install from https://bun.sh and ensure it is on PATH, under ~/.bun/bin, or set BUN / BUN_PATH / BUN_INSTALL. The worker daemon requires Bun because it uses bun:sqlite."});function Ap(t){let e=t?.code;return e==="EACCES"||e==="EADDRNOTAVAIL"}var Oc,Pc=E(()=>{"use strict";Oc="Set MEMINDEX_WORKER_PORT to a port between 1024 and 65535 and MEMINDEX_WORKER_HOST to an address of this machine (127.0.0.1 by default) in memindex settings"});function Mc(){return V.loadFromFile(_e).MEMINDEX_WORKER_HOST}function Pp(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}async function Mp(t,e,r="GET",n=Jt){let s={method:r,signal:AbortSignal.timeout(Math.max(1,n))},o=await fetch(`http://${Pp(Mc())}:${t}${e}`,r==="GET"||r==="HEAD"?s:gn(s)),i="";try{i=await o.text()}catch{}return{ok:o.ok,statusCode:o.status,body:i}}async function xp(t,e=Jt){let r=Date.now()+e;if(process.platform==="win32")try{let s=await fetch(`http://${Pp(Mc())}:${t}/api/health`,{signal:AbortSignal.timeout(Math.max(1,r-Date.now()))});if(s.ok)return!0;f.debug("SYSTEM","Windows health check returned non-ok; falling through to socket probe",{port:t,status:s.status})}catch(s){s instanceof Error?f.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:t,message:s.message}):f.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:t,error:String(s)})}let n=await mo(t,Math.max(1,r-Date.now()));return n==="occupied"||n==="indeterminate"}async function mo(t,e=Jt){return(await aw(t,e)).occupancy}function aw(t,e=Jt){return e<=0?Promise.resolve({occupancy:"indeterminate"}):new Promise(r=>{let n=!1,s=!1,o=!1,i;try{i=Op.default.createServer()}catch{r({occupancy:"indeterminate"});return}let a=l=>{if(o){l?.();return}o=!0;try{i.close(l)}catch(d){l?.(d instanceof Error?d:new Error(String(d)))}},c=setTimeout(()=>{if(s)a();else try{i.close()}catch{}u({occupancy:"indeterminate"})},e),u=l=>{n||(n=!0,clearTimeout(c),r(l))};i.once("error",l=>{if(s)a();else try{i.close()}catch{}l.code==="EADDRINUSE"?u({occupancy:"occupied"}):Ap(l)?u({occupancy:"unbindable",bindErrorCode:l.code}):u({occupancy:"indeterminate"})}),i.once("listening",()=>{if(s=!0,n){a();return}try{a(l=>u({occupancy:l?"indeterminate":"free"}))}catch{u({occupancy:"indeterminate"})}});try{i.listen(t,Mc())}catch{try{i.close()}catch{}u({occupancy:"indeterminate"})}})}async function cw(t,e,r,n){let s=Date.now()+r;for(;Date.now()<s;){try{let i=s-Date.now();if((await Mp(t,e,"GET",Math.min(Jt,i))).ok)return!0}catch(i){i instanceof Error?f.debug("SYSTEM",n,{},i):f.debug("SYSTEM",n,{error:String(i)})}let o=Math.min(500,s-Date.now());o>0&&await new Promise(i=>setTimeout(i,o))}return!1}function kp(t,e=3e4){return cw(t,"/api/health",e,"Service not ready yet, will retry")}async function uw(t,e=Jt){try{let r=await Mp(t,"/api/health","GET",e);return r.ok?JSON.parse(r.body).version:null}catch{return f.debug("SYSTEM","Could not fetch worker version",{}),null}}async function Np(t,e,r=Jt){let n=e??"unknown",s=await uw(t,r);return!s||n==="unknown"?{matches:!0,pluginVersion:n,workerVersion:s}:{matches:n===s,pluginVersion:n,workerVersion:s}}var Op,Jt,ho=E(()=>{"use strict";Op=be(require("net"),1);O();dt();C();Pc();Ka();Jt=5e3});var Cp=E(()=>{"use strict";O();hn()});var Dp=E(()=>{"use strict";Ac();ho();Cp()});function Up(){return(0,_o.join)(N(),"spawn.lock")}function Fp(t){try{let e=JSON.parse((0,oe.readFileSync)(t,"utf-8"));return typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0?null:e.pid}catch{return null}}function lw(t){if(t===null)return null;try{return process.kill(t,0),!0}catch(e){return e?.code==="EPERM"}}function Eo(){let t=Up(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return(0,oe.mkdirSync)((0,_o.dirname)(t),{recursive:!0}),(0,oe.writeFileSync)(t,e,{flag:"wx"}),!0}catch(n){let s=n instanceof Error?n:new Error(String(n)),o=s.code;if(o!=="EEXIST")return f.warn("SYSTEM","Spawn lock write failed for a non-contention reason; failing open (spawning unlocked)",{lockPath:t,code:o},s),!0;if(r>0)return!1;let i;try{i=(0,oe.statSync)(t).mtimeMs}catch{continue}let a=Fp(t),c=null;if(a===null)try{c=(0,oe.readFileSync)(t,"utf-8")}catch{continue}if(Date.now()-i<=Lp&&lw(a)!==!1)return!1;let l;try{l=(0,oe.statSync)(t).mtimeMs}catch{continue}if(l!==i)return!1;if(a!==null){if(Fp(t)!==a)return!1}else try{if((0,oe.readFileSync)(t,"utf-8")!==c)return!1}catch{continue}try{(0,oe.unlinkSync)(t)}catch{return!1}}return!1}function bn(){let t=Up();try{if(JSON.parse((0,oe.readFileSync)(t,"utf-8")).pid!==process.pid)return;(0,oe.unlinkSync)(t)}catch{}}var _o,oe,Lp,W0,$p=E(()=>{"use strict";_o=require("path"),oe=require("fs");C();O();Lp=9e4,W0=Lp/3});function Bp(t){return dw.test(t.trim())}function fw(t,e){if(!t)return!1;let r=t.toLowerCase().replace(/\\/g,"/"),n=r.indexOf("--data-dir");if(n<0)return!1;let s=r.slice(n+10).trim();if(s.startsWith('"')){let i=s.indexOf('"',1);s=i<0?s.slice(1):s.slice(1,i)}let o=e.toLowerCase().replace(/\\/g,"/");return s===o||s.startsWith(o)&&s[o.length]==="/"}function yo(t,e){return e===void 0?t:Math.max(1,Math.min(t,e))}async function pw(t){try{let e=await So("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name,CommandLine,@{Name='StartToken';Expression={$_.CreationDate.ToString('yyyyMMddHHmmss.ffffff')}} | ConvertTo-Json -Compress"],{timeout:yo(3e4,t),windowsHide:!0,maxBuffer:33554432}),r=JSON.parse(e.stdout),n=Array.isArray(r)?r:r===null?[]:[r],s=[];for(let o of n){let i=typeof o.Name=="string"?o.Name.trim():"";if(!i)continue;let a=typeof o.ProcessId=="number"?o.ProcessId:Number.parseInt(String(o.ProcessId),10),c=typeof o.ParentProcessId=="number"?o.ParentProcessId:Number.parseInt(String(o.ParentProcessId),10);!Number.isInteger(a)||!Number.isInteger(c)||s.push({pid:a,ppid:c,name:i,cmdline:typeof o.CommandLine=="string"?o.CommandLine:null,startToken:typeof o.StartToken=="string"&&o.StartToken.length>0?o.StartToken:null})}return s}catch(e){return f.warn("PROCESS","Cannot enumerate the Windows process table with names \u2014 ghost-port reclaim disabled",{error:e instanceof Error?e.message:String(e)}),null}}async function gw(t,e){try{let r=await So("netstat",["-ano"],{timeout:yo(15e3,e),windowsHide:!0,maxBuffer:16777216});return Ew(r.stdout,t)}catch(r){return f.warn("PROCESS","netstat failed \u2014 ghost-port reclaim disabled for this attempt",{port:t,error:r instanceof Error?r.message:String(r)}),null}}async function mw(t,e){try{let r=await So("lsof",["-nP",`-iTCP:${t}`,"-sTCP:LISTEN","-t"],{timeout:yo(1e4,e),maxBuffer:1048576});return hw(r.stdout)}catch(r){let n=r;return n.code===1&&typeof n.stdout=="string"&&n.stdout.trim()===""?[]:(f.warn("PROCESS","lsof failed \u2014 cannot verify the worker port owner",{port:t,error:r instanceof Error?r.message:String(r)}),null)}}function hw(t){let e=new Set;for(let r of t.split(/\r?\n/)){let n=Number.parseInt(r.trim(),10);Number.isInteger(n)&&n>0&&e.add(n)}return[...e]}async function _w(t,e){try{let n=(await So("ps",["-p",String(t),"-o","command="],{timeout:yo(5e3,e)})).stdout.trim();return n.length>0?n:null}catch{return null}}function Ew(t,e){let r=new Set,n=`:${e}`;for(let s of t.split(/\r?\n/)){let o=s.trim();if(!/^TCP\b/i.test(o))continue;let i=o.split(/\s+/);if(!i[1]?.endsWith(n)||i[3]!=="LISTENING")continue;let c=Number.parseInt(i[4]??"",10);Number.isInteger(c)&&c>0&&r.add(c)}return[...r]}async function yw(t,e){let r=e.readOwnedWorker();if(r===null||r.port!==t)return null;let n=(u,l={})=>(f.info("PROCESS","Wedged-worker reclaim declined",{port:t,pid:r.pid,reason:u,...l}),{reclaimed:!1,reason:u,killedPids:[]}),s=(e.now()-Date.parse(r.startedAt))/1e3;if(!Number.isFinite(s)||s<e.minOwnerAgeSeconds)return n("owner-booting",{ageSeconds:s,minOwnerAgeSeconds:e.minOwnerAgeSeconds});for(let u=0;u<2;u++)if(u>0&&await e.sleep(Kp),await e.probeHealth(t))return n("owner-responding");let o=await e.listOwners(t);if(o===null)return n("netstat-unreadable");if(!o.includes(r.pid))return f.info("PROCESS","Wedged-worker reclaim: our worker does not own the port \u2014 deferring to the ghost-listener check",{port:t,pid:r.pid,listeners:o}),null;let i=await e.readIdentity(r.pid),a=r.startToken!==void 0&&i.startToken!==null&&i.startToken!==r.startToken;if(a||i.cmdline===null||!Sw.test(i.cmdline))return n("owner-identity-mismatch",{tokenMismatch:a,hasCmdline:i.cmdline!==null});if(!e.hasKillBudget())return n("out-of-budget");f.warn("PROCESS","Reclaiming wedged worker: past its boot grace, silent on two health probes, and still holding the port",{port:t,pid:r.pid,ageSeconds:Math.round(s)});try{await e.killTree(r.pid,{expectedStartToken:i.startToken??r.startToken??void 0,signalMode:"graceful"})}catch(u){return f.error("PROCESS","Wedged-worker reclaim tree-kill failed",{port:t,pid:r.pid},u instanceof Error?u:new Error(String(u))),{reclaimed:!1,reason:"kill-failed",killedPids:[]}}let c=await e.listOwners(t);return c!==null&&c.length===0?(f.info("PROCESS","Wedged worker reclaimed \u2014 port is free again",{port:t,killedPids:[r.pid]}),{reclaimed:!0,killedPids:[r.pid]}):(f.warn("PROCESS","Wedged-worker reclaim killed the worker but the port is still bound",{port:t,pid:r.pid,stillOwnedBy:c}),{reclaimed:!1,reason:"still-bound",killedPids:[r.pid]})}async function bw(t,e,r,n){let s=Ye(t),o=e?(await r(n))?.find(i=>i.pid===t)?.cmdline??null:await _w(t,n);return Ce(t,s)?{startToken:s,cmdline:o}:{startToken:null,cmdline:null}}async function Gp(t,e={}){let r=e.isWin32??(()=>process.platform==="win32"),n=e.now??Date.now,s=e.deadlineAt??null,o=I=>s!==null&&s-n()<I,i=()=>s===null?void 0:Math.max(1,s-n());if(o(Wp))return f.info("PROCESS","Port reclaim skipped: not enough of the hook budget is left to finish one",{port:t,remainingMs:i(),neededMs:Wp}),{reclaimed:!1,reason:"out-of-budget",killedPids:[]};let a=e.listOwners??((I,M)=>r()?gw(I,M):mw(I,M)),c=I=>a(I,i()),u=e.readTable??pw,l=()=>u(i()),d=e.killTree??((I,M)=>we(I,M)),p=e.dataDir??(()=>W),g=e.readIdentity??((I,M)=>bw(I,r(),u,M)),m=await yw(t,{listOwners:c,killTree:d,readOwnedWorker:e.readOwnedWorker??gt,probeHealth:e.probeHealth??(I=>kp(I,Xp)),readIdentity:I=>g(I,i()),minOwnerAgeSeconds:e.minOwnerAgeSeconds??Bd(),now:n,sleep:e.sleep??(I=>new Promise(M=>setTimeout(M,I))),hasKillBudget:()=>!o(xc)});if(m!==null)return m;if(!r())return{reclaimed:!1,reason:"not-supported",killedPids:[]};let h=await c(t);if(h===null)return{reclaimed:!1,reason:"netstat-unreadable",killedPids:[]};if(h.length===0)return{reclaimed:!1,reason:"no-listener",killedPids:[]};let _=await l();if(_===null)return{reclaimed:!1,reason:"table-unreadable",killedPids:[]};if(h.filter(I=>Y(I)).length>0)return{reclaimed:!1,reason:"owner-alive",killedPids:[]};let b=new Map;for(let I of _){let M=b.get(I.ppid);M?M.push(I):b.set(I.ppid,[I])}let w=new Map,T=new Set,y=I=>{for(let M of b.get(I)??[])T.has(M.pid)||(T.add(M.pid),y(M.pid),Bp(M.name)&&w.set(M.pid,M))};for(let I of h)y(I);let A=p();if(A)for(let I of _)w.has(I.pid)||Bp(I.name)&&fw(I.cmdline,A)&&w.set(I.pid,I);if(w.size===0)return f.info("PROCESS","Ghost listener owner is dead but no chroma-sidecar descendants found",{port:t,deadOwners:h,processTableRows:_.length,dataDir:A??"(unresolved)"}),{reclaimed:!1,reason:"no-chroma-descendants",killedPids:[]};f.warn("PROCESS","Reclaiming ghost listener: killing dead worker's surviving chroma sidecar chain",{port:t,deadOwners:h,targets:[...w.values()].map(I=>({pid:I.pid,name:I.name}))});let v=[];for(let I of w.values()){if(o(xc))return f.info("PROCESS","Ghost-listener reclaim stopped before a kill: the hook budget is spent",{port:t,killedPids:v}),{reclaimed:!1,reason:"out-of-budget",killedPids:v};try{await d(I.pid,{expectedStartToken:I.startToken,signalMode:"immediate"}),v.push(I.pid)}catch(M){return f.error("PROCESS","Ghost-port reclaim tree-kill failed",{port:t,pid:I.pid},M instanceof Error?M:new Error(String(M))),{reclaimed:!1,reason:"kill-failed",killedPids:v}}}let R=await c(t);return R!==null&&R.length===0?(f.info("PROCESS","Ghost listener reclaimed \u2014 port is free again",{port:t,killedPids:v}),{reclaimed:!0,killedPids:v}):(f.warn("PROCESS","Ghost-port reclaim killed the sidecar chain but the port is still bound",{port:t,killedPids:v,stillOwnedBy:R}),{reclaimed:!1,reason:"still-bound",killedPids:v})}var jp,Hp,So,dw,Sw,Xp,Kp,xc,Wp,zp=E(()=>{"use strict";jp=require("node:child_process"),Hp=require("node:util");O();yr();mt();hn();ho();Bs();xe();C();So=(0,Hp.promisify)(jp.execFile),dw=/^(uv|uvx|python|chroma-mcp)(\.exe)?$/i;Sw=/worker-service/i,Xp=1500,Kp=1e3,xc=5500,Wp=2*Xp+Kp+xc});function Vp(t){try{return(0,Rr.realpathSync)(t)}catch{return t}}function Tw(t,e){let r=At.default.relative(e,t);return r!==""&&!r.startsWith("..")&&!At.default.isAbsolute(r)}function qp(t){let e;try{let s=JSON.parse((0,Rr.readFileSync)(At.default.join(t,"package.json"),"utf-8"));e=Object.keys(s?.dependencies??{})}catch{return[]}if(e.length===0)return[];let r=At.default.join(t,"node_modules"),n=e.filter(s=>!(0,Rr.existsSync)(At.default.join(r,...s.split("/"),"package.json")));if(e.includes("zod")&&!n.includes("zod")){let s=(0,Yp.createRequire)(At.default.join(r,"noop.js")),o=Vp(At.default.join(r,"zod"));for(let i of ww)try{let a=s.resolve(i,{paths:[r]});Tw(Vp(a),o)||n.push(i)}catch{n.push(i)}}return n}var Rr,Yp,At,ww,Jp=E(()=>{"use strict";Rr=require("fs"),Yp=require("module"),At=be(require("path"),1),ww=["zod/v3","zod/v4","zod/v4-mini"]});function eg(){return bo.default.join(N(),"worker-standby.json")}function Cc(){return bo.default.join(N(),"worker-standby-attempt.json")}function Dc(){return bo.default.join(N(),"worker-standby-failure.json")}function Fc(t){try{return JSON.parse((0,wo.readFileSync)(t,"utf-8"))}catch{return null}}function Lc(t){try{(0,wo.unlinkSync)(t)}catch(e){e.code!=="ENOENT"&&f.debug("SYSTEM","Could not remove worker standby file",{path:t,error:e instanceof Error?e.message:String(e)})}}function To(){let t=Fc(eg());return!t||typeof t.pid!="number"||!Number.isInteger(t.pid)||t.pid<=0||typeof t.port!="number"||!Number.isInteger(t.port)||t.port<=0||typeof t.version!="string"?null:{pid:t.pid,port:t.port,version:t.version,startedAt:typeof t.startedAt=="string"?t.startedAt:""}}function Io(t){if(t!==void 0){let e=To();if(e!==null&&e.pid!==t)return}Lc(eg())}function Iw(){let t=Fc(Dc());return!t||typeof t.buildKey!="string"||typeof t.failedAt!="string"?null:{buildKey:t.buildKey,failedAt:t.failedAt,reason:typeof t.reason=="string"?t.reason:""}}function tg(t,e,r=new Date){try{U(Dc(),{buildKey:t,failedAt:r.toISOString(),reason:e})}catch(n){f.warn("SYSTEM","Could not save the failed worker update attempt",{error:n instanceof Error?n.message:String(n)})}}function rg(){Lc(Dc())}function ng(t,e=Date.now()){if(t===null)return null;let r=Iw();if(r===null||r.buildKey!==t)return null;let n=Date.parse(r.failedAt);return!Number.isFinite(n)||e-n>=Nc?null:r}function sg(){let t=Fc(Cc());return!t||typeof t.buildKey!="string"||typeof t.launchedAtMs!="number"||!Number.isFinite(t.launchedAtMs)?null:{buildKey:t.buildKey,launchedAtMs:t.launchedAtMs}}function og(t){try{U(Cc(),t)}catch(e){f.debug("SYSTEM","Could not save the worker update attempt",{error:e instanceof Error?e.message:String(e)})}}function ig(){Lc(Cc())}var bo,wo,Qp,kc,Zp,Nc,ag=E(()=>{"use strict";bo=be(require("path"),1),wo=require("fs");C();se();O();Qp="MEMINDEX_WORKER_STANDBY",kc=12e4,Zp=2e4,Nc=10*6e4});function jc(t,e,r){let n=process.env[t];if(n){let s=parseInt(n,10);if(Number.isFinite(s)&&s>=r.min&&s<=r.max)return s;f.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max})}return e}function yg(t=process.env){let e=t.MEMINDEX_FETCH_VERBOSE;if(e===void 0)return!1;let r=e.trim().toLowerCase();return r==="1"||r==="true"||r==="on"||r==="yes"}function Ow(t){return yg()?{...t,verbose:!0}:t}function Pw(t){let e={},r=t;for(let n=0;r&&n<4;n++){let s=n===0?"error":`cause${n}`;if(r instanceof Error){let o=r;e[s]={name:r.name,message:r.message,...o.code!==void 0?{code:o.code}:{}},r=r.cause;continue}e[s]=String(r);break}return e}function Mw(t,e,r){let n=typeof e.method=="string"?e.method:"GET",s=Pw(r),o=JSON.stringify(s);f.warn("SYSTEM","Worker IPC fetch failed",{url:t,method:n},o),ct(`[memindex] fetch verbose: ${n} ${t} ${o}
|
|
22
22
|
`)}async function Xc(t,e={}){let r=Ow(e);try{return await fetch(t,r)}catch(n){throw yg()&&Mw(t,e,n),n}}async function In(t,e={},r){try{return await Xc(t,{...e,signal:AbortSignal.timeout(r)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new Error(`Request timed out after ${r}ms`):n}}function xw(t,e){let r=new AbortController,n=null,s=null,o=null,i=!1,a=()=>{s!==null&&(clearTimeout(s),s=null)},c=()=>{i=!0,a(),o!==null&&(clearTimeout(o),o=null)},u=d=>{i||(n=d,c(),r.abort(d))},l=()=>{i||(a(),s=setTimeout(()=>u(new Error(`Request timed out after ${t.idleTimeoutMs}ms idle`)),t.idleTimeoutMs))};if(t.absoluteCapMs!==void 0&&t.absoluteCapMs>0){let d=t.absoluteCapMs;o=setTimeout(()=>u(new Error(`Request timed out after ${d}ms`)),d)}return l(),{signal:e?AbortSignal.any([e,r.signal]):r.signal,touch:l,pause:a,dispose:c,translate:d=>n??d}}async function bg(t,e,r){let n=xw(r,e.signal),s;try{s=await Xc(t,{...e,signal:n.signal})}catch(u){throw n.dispose(),n.translate(u)}n.touch();let o=s.body,i=o?o.getReader():null,a=!1;async function*c(){if(!i){a=!0,n.dispose();return}try{for(;;){n.touch();let u;try{u=await i.read()}catch(l){throw a=!0,n.translate(l)}if(u.done){a=!0;return}n.pause(),r.onChunk?.(u.value),yield u.value}}finally{n.dispose(),a||await i.cancel()}}return{status:s.status,statusText:s.statusText,ok:s.ok,headers:s.headers,chunks:c(),cancel:async()=>{n.dispose(),i&&!a&&(a=!0,await i.cancel())}}}async function kw(t,e,r){let n=await bg(t,e,r),s=new TextDecoder,o="";for await(let i of n.chunks)o+=s.decode(i,{stream:!0});return o+=s.decode(),{status:n.status,statusText:n.statusText,ok:n.ok,headers:n.headers,text:o}}function cg(){return L.default.join(V.get("MEMINDEX_DATA_DIR"),"settings.json")}function Kc(t={}){return t.readOnly?V.loadFromFile(cg(),!0,t):(vo!==null||(vo=V.loadFromFile(cg())),vo)}function ug(t,e){if(!t)return null;let r=parseInt(t,10);return Number.isFinite(r)&&r>=e.min&&r<=e.max?r:null}function wg(t,e,r){let n=process.env[t];if(n!==void 0){let i=ug(n,r);return i!==null?i:(f.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max}),e)}let s=Kc()[t],o=ug(s,r);return o!==null?o:(f.warn("SYSTEM",`Invalid ${t} in settings.json, using default`,{value:s,min:r.min,max:r.max}),e)}function ie(t={}){if(!t.readOnly&&Uc!==null)return Uc;let e=parseInt(Kc(t).MEMINDEX_WORKER_PORT,10),r=e===La()&&un()?Ua(N()):e;return t.readOnly||(Uc=r),r}function Gc(t={}){if(!t.readOnly&&$c!==null)return $c;let e=Kc(t).MEMINDEX_WORKER_HOST;return t.readOnly||($c=e),e}function Nw(){return Ro!==null||(Ro=wg("MEMINDEX_API_TIMEOUT_MS",ze(Q.API_REQUEST),Rw)),Ro}function Tg(){return Ao!==null||(Ao=Math.min(wg("MEMINDEX_SESSION_INIT_TIMEOUT_MS",cn(),Aw),Wd())),Ao}function ko(t){return t===null?null:Math.max(0,t-Date.now())}function Mo(t){let e=ko(t);return e!==null&&e<Hc}function De(t,e){let r=ko(e);return r===null?t:Math.max(1,Math.min(t,r))}function Ig(t){return`http://${Va(Gc())}:${ie()}${t}`}function le(t,e={}){let r=e.method??"GET",n=Ig(t),s={method:r};e.headers&&(s.headers=e.headers),e.body&&(s.body=e.body);let o=gn(s);if(e.idleTimeoutMs!==void 0&&e.idleTimeoutMs>0)return kw(n,o,{idleTimeoutMs:e.idleTimeoutMs,absoluteCapMs:e.timeoutMs}).then(a=>new Response(a.text.length>0?a.text:null,{status:a.status,statusText:a.statusText,headers:a.headers}));let i=e.timeoutMs??Nw();return i>0?In(n,o,i):Xc(n,o)}async function Cw(t){return(await le("/api/health",{timeoutMs:t})).ok}async function lg(t=qe){return(await le("/api/readiness",{timeoutMs:t})).ok}function vg(t){let e=(0,x.existsSync)(L.default.join(t,"plugin","scripts"))?L.default.join(t,"plugin"):t;return L.default.join(e,"scripts","worker-service.cjs")}function Dw(t,e){let r=d=>{let p=d.split("-")[0].split(".");return[parseInt(p[0],10)||0,parseInt(p[1],10)||0,parseInt(p[2],10)||0]},[n,s,o]=r(t),[i,a,c]=r(e);if(i!==n)return i-n;if(a!==s)return a-s;if(c!==o)return c-o;let u=t.includes("-")?1:0,l=e.includes("-")?1:0;return u!==l?u-l:t<e?1:t>e?-1:0}function Fw(t=L.default.join(L.default.dirname(L.default.dirname(Er)),"cache","memindex","memindex")){try{return(0,x.readdirSync)(t).filter(e=>/^\d/.test(e)).map(e=>L.default.join(t,e)).filter(e=>{try{if(!(0,x.statSync)(e).isDirectory())return!1}catch{return!1}return!(0,x.existsSync)(L.default.join(e,".orphaned_at"))}).map(e=>({scriptPath:vg(e),version:L.default.basename(e)}))}catch{return[]}}function dg(t){try{let e=JSON.parse((0,x.readFileSync)(t,"utf-8"));return typeof e.version=="string"?e.version:null}catch(e){let r=e.code;return r!=="ENOENT"&&f.debug("SYSTEM","Could not read package version for worker resolution",{packageJsonPath:t,code:r}),null}}function Lw(){return{cacheRoot:L.default.join(L.default.dirname(L.default.dirname(Er)),"cache","memindex","memindex"),marketplaceRoot:Er,cwd:process.cwd()}}function zc(t=Lw()){let e=process.env.MEMINDEX_WORKER_SCRIPT_PATH?.trim();if(e){if((0,x.existsSync)(e))return{scriptPath:e,version:null};f.debug("SYSTEM","Ignoring missing MEMINDEX_WORKER_SCRIPT_PATH override",{override:e})}let r=[...Fw(t.cacheRoot),{scriptPath:vg(L.default.join(t.marketplaceRoot,"plugin")),version:dg(L.default.join(t.marketplaceRoot,"package.json"))},{scriptPath:L.default.join(t.cwd,"plugin","scripts","worker-service.cjs"),version:dg(L.default.join(t.cwd,"package.json"))}];return Bw(r)}function Uw(t){return L.default.dirname(L.default.dirname(t))}function $w(t){return qp(Uw(t.scriptPath)).length===0}function Bw(t,e=$w){let r=t.filter(n=>(0,x.existsSync)(n.scriptPath));return r.length===0?null:(r.sort((n,s)=>n.version===null&&s.version===null?0:n.version===null?1:s.version===null?-1:Dw(n.version,s.version)),r.find(e)??r[0])}function Ww(){return zc()?.scriptPath??null}async function jw(t){let e=t.deadlineAt??null,r=t.backoffMs;for(let n=1;n<=t.attempts;n++){if(Mo(e))return!1;if(await Cg(e??Number.POSITIVE_INFINITY))return!0;n<t.attempts&&(await new Promise(s=>setTimeout(s,De(r,e))),r*=2)}return!1}function fg(t){return t instanceof Error&&/^Request timed out after \d+ms idle$/.test(t.message)}function pg(t){return t instanceof Error&&/^Request timed out after \d+ms$/.test(t.message)}async function Hw(t){let e;try{e=await bg(Ig("/api/ready"),{method:"GET"},{idleTimeoutMs:vw,absoluteCapMs:Math.max(1,t)})}catch(o){return fg(o)?{outcome:"unresponsive",detail:"no response headers within the idle window"}:pg(o)?{outcome:"still_booting",detail:"budget spent before response headers"}:(f.debug("SYSTEM","Worker /api/ready connection failed",{error:o instanceof Error?o.message:String(o)}),{outcome:"not_running"})}let r=()=>e.cancel().catch(o=>{f.debug("SYSTEM","Releasing the /api/ready body failed",{error:o instanceof Error?o.message:String(o)})}),n=e.headers?.get("content-type")??"";if(!e.ok||!n.includes("text/event-stream"))return xo(),await r(),{outcome:"unsupported"};let s=null;try{for await(let o of _f(e.chunks)){if(o.event!=="phase")continue;let i=JSON.parse(o.data);if(s=typeof i.phase=="string"?i.phase:null,s==="ready")return xo(),await r(),{outcome:"ready"};if(s==="failed")return await r(),{outcome:"failed",detail:typeof i.message=="string"?i.message:"unknown init failure"}}}catch(o){return pg(o)?(xo(),{outcome:"still_booting",detail:`last phase ${s??"none"}`}):fg(o)?{outcome:"unresponsive",detail:`silent past the idle window after response headers (last phase ${s??"none"})`}:{outcome:"wedged",detail:`stream error: ${o instanceof Error?o.message:String(o)} (last phase ${s??"none"})`}}return{outcome:"wedged",detail:`stream closed before ready/failed (last phase ${s??"none"})`}}async function Xw(t){if(t<=0)try{return await lg()?{outcome:"ready"}:{outcome:"still_booting"}}catch(r){return f.debug("SYSTEM","Worker readiness check threw",{},r instanceof Error?r:new Error(String(r))),{outcome:"still_booting"}}let e=Date.now();do{let r=t-(Date.now()-e);try{if(await lg(Math.max(1,Math.min(qe,r))))return{outcome:"ready"}}catch(s){f.debug("SYSTEM","Worker readiness check threw",{error:s instanceof Error?s.message:String(s)})}let n=t-(Date.now()-e);if(n<=0)break;await new Promise(s=>setTimeout(s,Math.min(250,n)))}while(Date.now()-e<t);return{outcome:"still_booting",detail:"legacy /api/readiness never reported ready"}}async function Zt(t=Ar){let e=t>0?t:qe,r=await Hw(e);return r.outcome==="ready"&&Jw(),r.outcome!=="unsupported"?r:(f.debug("SYSTEM","Worker has no /api/ready stream; falling back to /api/readiness"),Xw(t))}async function Kw(t=qe){try{let r=await(await le("/api/health",{timeoutMs:t})).json();return typeof r.version=="string"?r.version:null}catch(e){let r=e instanceof Error?e:new Error(String(e));return f.debug("SYSTEM","Worker health-version fetch failed",{},r),null}}async function Gw(t=5e3){let e=Date.now()+t;for(;;){let r=e-Date.now();if(r<=0)return!1;if(await mo(ie(),Math.min(1e3,r))==="free")return!0;let n=Math.min(200,e-Date.now());n>0&&await new Promise(s=>setTimeout(s,n))}}function Rg(t,e){if(!t)return null;try{let r=(0,x.statSync)(t.scriptPath);return JSON.stringify([t.scriptPath,e,r.size,r.mtimeMs,r.ctimeMs])}catch{return null}}function Ag(){return L.default.join(N(),"worker-version-recycle.json")}function zw(t,e){if(t===null||e===null)return!1;try{let r=JSON.parse((0,x.readFileSync)(Ag(),"utf-8"));return r?.buildKey===t&&r?.workerVersion===e}catch{return!1}}async function gg(t,e=null,r=qe){let n=await Kw(r);if(n!==null&&n!==t){if(e!==null)try{U(Ag(),{buildKey:e,workerVersion:n})}catch(s){f.warn("SYSTEM","Could not persist the failed worker version recycle",{error:s instanceof Error?s.message:String(s)})}f.warn("SYSTEM","Worker is ready but still reports a stale version; rebuild or reinstall the worker bundle before retrying",{pluginVersion:t,workerVersion:n})}}function Vc(){return L.default.join(N(),"worker-unresponsive.json")}function Vw(){try{let t=JSON.parse((0,x.readFileSync)(Vc(),"utf-8"));return typeof t?.pid!="number"||typeof t?.firstUnresponsiveAtEpochMs!="number"?null:{pid:t.pid,firstUnresponsiveAtEpochMs:t.firstUnresponsiveAtEpochMs}}catch{return null}}function xo(){let t=Vc();if((0,x.existsSync)(t))try{(0,x.unlinkSync)(t)}catch(e){f.debug("SYSTEM","Could not clear the unresponsive-worker record",{error:e instanceof Error?e.message:String(e)})}}function Yw(t=Date.now()){let e=gt()?.pid??null;if(e===null)return!1;let r=Vw();if(r!==null&&r.pid===e)return t-r.firstUnresponsiveAtEpochMs>=Og;try{U(Vc(),{pid:e,firstUnresponsiveAtEpochMs:t})}catch(n){f.warn("SYSTEM","Could not persist the unresponsive-worker record",{error:n instanceof Error?n.message:String(n)})}return!1}function Yc(){return L.default.join(N(),"worker-never-ready-recycle.json")}function qw(){try{let t=JSON.parse((0,x.readFileSync)(Yc(),"utf-8"));return typeof t?.buildKey!="string"||typeof t?.failureMessage!="string"?null:{buildKey:t.buildKey,failureMessage:t.failureMessage,refusalLogged:t.refusalLogged===!0}}catch{return null}}function Pg(t){try{U(Yc(),t)}catch(e){f.warn("SYSTEM","Could not persist the never-ready worker recycle",{error:e instanceof Error?e.message:String(e)})}}function Jw(){let t=Yc();if((0,x.existsSync)(t))try{(0,x.unlinkSync)(t)}catch(e){f.debug("SYSTEM","Could not clear the never-ready worker recycle record",{error:e instanceof Error?e.message:String(e)})}}function Mg(t){return Rg(t,t?.version??"unknown")??"unresolved-worker-bundle"}function xg(t){return t.outcome==="failed"?t.detail??"unknown init failure":t.outcome}function kg(t,e){if(t.outcome==="unresponsive"&&!Yw())return f.warn("SYSTEM","Worker went silent on /api/ready; skipping this hook without killing it",{detail:t.detail,wedgedAfterMs:Og}),!1;let r=xg(t),n=qw();return n!==null&&n.buildKey===e&&n.failureMessage===r?(n.refusalLogged?f.debug("SYSTEM","Never-ready worker recycle already refused for this bundle and failure",{failureMessage:r}):(f.error("SYSTEM","Worker keeps failing to start the same way after a recycle; not recycling again. Run `npx memindex doctor` and check the worker logs",{outcome:t.outcome,failureMessage:r,logsDir:L.default.join(N(),"logs")}),Pg({...n,refusalLogged:!0})),!1):!0}function Ng(t,e){Pg({buildKey:e,failureMessage:xg(t)}),xo()}async function Cg(t=Number.POSITIVE_INFINITY){let e=t-Date.now();if(e<=0)return!1;let r;try{r=await Cw(Math.min(qe,e))}catch(n){return f.debug("SYSTEM","Worker health check threw",{error:n instanceof Error?n.message:String(n)}),!1}return r}async function qc(t,e){let r=gt();if(r===null||r.port!==ie())return f.error("SYSTEM","Stale worker is serving the port but the PID file does not identify it; kill the memindex worker process manually",{port:ie(),pidFilePid:r?.pid??null,pidFilePort:r?.port??null}),!1;if(e("stale-worker recycle"))return!1;try{await we(r.pid,{signalMode:"immediate"})}catch(n){return f.error("SYSTEM","Could not kill stale worker",{pid:r.pid,port:r.port},n instanceof Error?n:new Error(String(n))),!1}return await Gw(De(5e3,t))?!0:(e("stale port release")||(er=ie(),f.error("SYSTEM","Stale worker port still open after SIGKILL; skipping spawn this hook event",{pid:r.pid,port:ie(),fix:No})),!1)}function Dg(t,e){return`http://127.0.0.1:${t}${e}`}async function Fg(t,e){if(e<=0)return{answered:!1,version:null};try{let n=await(await In(Dg(t.port,"/api/health"),{},e)).json();return n.pid!==t.pid||n.standby!==!0?{answered:!1,version:null}:{answered:!0,version:typeof n.version=="string"?n.version:null}}catch{return{answered:!1,version:null}}}function Lg(t){try{process.kill(t.pid,"SIGKILL")}catch(e){f.debug("SYSTEM","Could not stop the standby worker",{pid:t.pid,error:e instanceof Error?e.message:String(e)})}Io(t.pid)}async function Qw(t,e,r,n){let s=await Zw(t,e,r,n);return s.kind!=="out-of-budget"&&ig(),s}async function Zw(t,e,r,n){let s=To(),o=s===null?null:await Fg(s,De(qe,n));if(s!==null&&o!==null&&o.answered&&o.version===e)return f.info("SYSTEM","Found the updated worker already waiting to take over",{pid:s.pid,port:s.port}),{kind:"ready",record:s};let i={kind:"failed",reason:`it did not answer its health check within ${Math.round(wn/1e3)} seconds; the worker log has the reason`};if(s!==null&&o!==null)if(o.answered)Lg(s);else{let d=Date.parse(s.startedAt);if((Number.isFinite(d)?Date.now()-d:Number.POSITIVE_INFINITY)<kc&&Y(s.pid)){let g=Math.min(d+kc,Math.max(d+wn,Date.now()+2e3)),m=await Bc(e,g,n,i);return m.kind==="failed"&&Io(s.pid),m}Io(s.pid)}let a=r===null?null:sg();if(a!==null&&a.buildKey===r)return Date.now()-a.launchedAtMs>=wn?i:Bc(e,a.launchedAtMs+wn,n,i);let c=po();if(!c)return{kind:"failed",reason:"Bun, which runs the worker, was not found"};if(!t)return{kind:"failed",reason:"the new worker program (worker-service.cjs) was not found"};f.info("SYSTEM","Starting the updated worker next to the running one",{runtimePath:c,scriptPath:t});let u;try{u=go(c,t,pt({...process.env,MEMINDEX_WORKER_PORT:String(ie()),[Qp]:"1"}),process.platform,ko(n)??void 0)}catch(d){return{kind:"failed",reason:`it could not be launched (${d instanceof Error?d.message:String(d)})`}}if(u===void 0)return{kind:"failed",reason:"it could not be launched"};let l=Date.now();return r!==null&&og({buildKey:r,launchedAtMs:l}),Bc(e,l+wn,n,i)}async function Bc(t,e,r,n){let s=Math.min(e,r??Number.POSITIVE_INFINITY);for(;Date.now()<s;){let o=To();if(o!==null){let a=await Fg(o,Math.min(1e3,s-Date.now()));if(a.answered)return a.version===t?{kind:"ready",record:o}:(Lg(o),{kind:"failed",reason:`it reports version ${a.version??"unknown"} instead of ${t}; the installed files are mislabelled`})}let i=Math.min(200,s-Date.now());i>0&&await new Promise(a=>setTimeout(a,i))}return Date.now()<e?{kind:"out-of-budget"}:n}async function eT(t,e){try{let r=await In(Dg(t.port,"/api/admin/promote"),gn({method:"POST"}),e);if(r.ok)return null;let n=await r.json().catch(()=>({}));return typeof n.message=="string"?n.message:`HTTP ${r.status}`}catch(r){return r instanceof Error?r.message:String(r)}}async function tT(t){let{scriptPath:e,pluginVersion:r,workerVersion:n,buildKey:s,deadlineAt:o,outOfBudget:i}=t,a=n??"unknown",c=ng(s);if(c!==null)return f.debug("SYSTEM","Keeping the running worker: this update failed to start a short while ago",{pluginVersion:r,workerVersion:n,failedAt:c.failedAt,reason:c.reason}),"kept-old";let u=gt();if(u===null||u.port!==ie())return f.error("SYSTEM","Stale worker is serving the port but the PID file does not identify it; kill the memindex worker process manually",{port:ie(),pidFilePid:u?.pid??null,pidFilePort:u?.port??null}),"failed";if(!Eo())return f.info("SYSTEM","Another launcher is starting the updated worker; the running worker keeps serving meanwhile"),"kept-old";let l=!1;try{let d=await Qw(e,r,s,o);if(d.kind==="out-of-budget")return f.info("SYSTEM","The updated worker is still starting; the running worker keeps serving until a later hook hands over",{pluginVersion:r,workerVersion:n}),"kept-old";if(d.kind==="failed")return s!==null&&tg(s,d.reason),f.error("SYSTEM",`The updated MemIndex worker (version ${r}) did not start, so the running worker (version ${a}) keeps serving: ${d.reason}. MemIndex tries the update again in ${Math.round(Nc/6e4)} minutes, or as soon as the plugin is reinstalled.`,{pluginVersion:r,workerVersion:n,scriptPath:e}),"kept-old";if(i("stale-worker recycle"))return"kept-old";if(!await qc(o,i))return"failed";l=!0;let p=await eT(d.record,De(1e4,o));return p===null?(rg(),f.info("SYSTEM","The updated worker took over from the old one",{from:n,to:r,pid:d.record.pid}),"promoted"):(f.warn("SYSTEM","The updated worker could not take over the worker port; starting a new worker the usual way",{pluginVersion:r,reason:p}),"old-stopped")}finally{l||bn()}}async function Or(t){let e=t===void 0?null:Date.now()+t,r=S=>Mo(e)?(f.warn("SYSTEM","Worker check ran out of the hook budget; skipping the rest this hook event",{step:S,budgetMs:t}),!0):!1,n=()=>e===null?void 0:De(qe,e),s=Math.min(Date.now()+5e3,e??Number.POSITIVE_INFINITY),o=zc(),i=null,a=null,c=!1,u=!1,l=!1,d=null,p=null,g=$s(G());if(r("health probe"))return!1;if(await Cg(s)){if(r("version probe"))return!1;let{matches:S,pluginVersion:b,workerVersion:w}=await Np(ie(),o?.version??null,n());if(b!=="unknown"&&(i=b),S){if(r("readiness wait"))return!1;let T=await Zt(De(Ar,e));if(T.outcome==="ready")return i!==null&&!Mo(e)&&await gg(i,null,n()),!0;if(T.outcome==="still_booting"||T.outcome==="not_running")return f.warn("SYSTEM","Worker is healthy but not ready yet; skipping hook API call",{outcome:T.outcome,detail:T.detail}),!1;if(g)return f.warn("SYSTEM","Worker will never become ready; MEMINDEX_WORKER_AUTOSTART=false, so leaving it to whatever manages it",{outcome:T.outcome,detail:T.detail}),!1;if(p=Mg(o),!kg(T,p))return!1;d=T,f.info("SYSTEM","Worker will never become ready \u2014 recycling wedged worker",{outcome:T.outcome,detail:T.detail,version:w})}else{if(g)return f.warn("SYSTEM","Worker version differs from the installed plugin; MEMINDEX_WORKER_AUTOSTART=false, so using it as is",{pluginVersion:b,workerVersion:w}),r("readiness wait")?!1:(await Zt(De(Ar,e))).outcome==="ready";if(a=Rg(o,b),zw(a,w))return f.warn("SYSTEM","Skipping repeated worker recycle: the unchanged bundle still reports a stale version; rebuild or reinstall it",{pluginVersion:b,workerVersion:w,scriptPath:o?.scriptPath}),r("readiness wait")?!1:(await Zt(De(Ar,e))).outcome==="ready";f.info("SYSTEM","Worker version changed \u2014 starting the new worker before stopping the old one",{pluginVersion:b,workerVersion:w});let T=await tT({scriptPath:o?.scriptPath??null,pluginVersion:b,workerVersion:w,buildKey:a,deadlineAt:e,outOfBudget:r});if(T==="failed")return!1;if(T==="kept-old")return r("readiness wait")?!1:(await Zt(De(Ar,e))).outcome==="ready";u=!0,l=T==="promoted"}if(!u&&!await qc(e,r))return!1;d!==null&&p!==null&&Ng(d,p),c=!0}if(g)return f.debug("SYSTEM","Worker not running and MEMINDEX_WORKER_AUTOSTART=false \u2014 not lazy-spawning"),!1;let m=o?.scriptPath??null;if(r("lazy spawn"))return u&&bn(),!1;let h=u||Eo();try{if(h&&!l){if(!c&&!await rT(s,e))return!1;let b=po();if(!b)return f.warn("SYSTEM","Cannot lazy-spawn worker: Bun runtime not found (PATH, BUN / BUN_PATH / BUN_INSTALL, or ~/.bun/bin)"),!1;if(!m)return f.warn("SYSTEM","Cannot lazy-spawn worker: worker-service.cjs not found in plugin/scripts"),!1;f.info("SYSTEM","Worker not running \u2014 lazy-spawning",{runtimePath:b,scriptPath:m});try{if(go(b,m,pt({...process.env,MEMINDEX_WORKER_PORT:String(ie())}),process.platform,ko(e)??void 0)===void 0)return!1}catch(w){return w instanceof Error?f.error("SYSTEM","Lazy-spawn of worker failed",{runtimePath:b,scriptPath:m},w):f.error("SYSTEM","Lazy-spawn of worker failed (non-Error)",{runtimePath:b,scriptPath:m,error:String(w)}),!1}}else h||f.info("SYSTEM","Another launcher holds the spawn lock \u2014 skipping lazy-spawn and waiting for its worker");if(!await jw({attempts:6,backoffMs:500,deadlineAt:e}))return r("cold-boot port wait")||(f.warn("SYSTEM",h?"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)"),gt()===null&&await xp(ie(),e===null?void 0:De(5e3,e))&&(er=ie(),f.error("SYSTEM","Worker port is occupied by an unreachable process that no PID file claims (likely an orphaned OS socket); every lazy-spawn on this port will be silently refused",{port:er,fix:No}))),!1}finally{h&&bn()}if(r("readiness wait"))return!1;let _=await Zt(De(Ar,e));return _.outcome!=="ready"?(f.warn("SYSTEM","Worker lazy-spawned but did not become ready before hook readiness timeout",{outcome:_.outcome,detail:_.detail}),!1):(i!==null&&!Mo(e)&&await gg(i,a,n()),!0)}async function rT(t,e){let r=ie(),n=t-Date.now();if(n<=0)return!1;let s=await mo(r,n);if(s==="free")return!0;if(s==="unbindable")return Wc=r,f.error("SYSTEM","Worker port cannot be bound (EACCES or EADDRNOTAVAIL) \u2014 skipping lazy-spawn",{port:r,host:Gc(),fix:Oc}),!1;if(s==="indeterminate")return f.warn("SYSTEM","Worker port state could not be determined in time \u2014 skipping lazy-spawn",{port:r}),!1;let o=await Gp(r,{deadlineAt:e});return o.reclaimed?(f.info("SYSTEM","Reclaimed the worker port before lazy-spawn",{port:r,killedPids:o.killedPids}),!0):(gt()===null&&(er=r),f.warn("SYSTEM","Worker port is held by a listener that does not answer health \u2014 skipping lazy-spawn",{port:r,reclaimReason:o.reason,...er===r?{fix:No}:{}}),!1)}async function nT(t){if(Qt!==void 0)return Qt;try{let r=await(await le("/api/health",{timeoutMs:t})).json();Qt=Yd(r.dataDir,N())==="foreign"?String(r.dataDir):null}catch(e){f.debug("SYSTEM","Could not read the worker data folder; treating the worker as ours",{error:e instanceof Error?e.message:String(e)}),Qt=null}return Qt!==null&&f.warn("SYSTEM","The worker on this port writes to another data folder; observations wait in the hook spool and prompts and context are not delivered until it is gone",{workerDataDir:Qt,dataDir:N(),port:ie()}),Qt}async function sT(t){return Oo!==null||(Oo=await Or(t)),Oo}async function oT(t){let e=Date.now()+t,r=()=>e-Date.now(),n=u=>r()>=Hc?!1:(f.debug("SYSTEM","Bounded worker startup ran out of budget",{step:u,budgetMs:t}),!0),s=await Zt(Math.max(1,r()));if(s.outcome==="ready")return!0;if(s.outcome==="still_booting")return f.warn("SYSTEM","Worker is still booting; bounded startup budget spent, skipping this call",{detail:s.detail,budgetMs:t}),!1;if(!!$s(G()))return mg(e);let i=po(),a=Ww();if(!i||!a)return!1;if(s.outcome==="failed"||s.outcome==="wedged"||s.outcome==="unresponsive"){let u=Mg(zc());if(!kg(s,u)||(f.info("SYSTEM","Worker will never become ready \u2014 recycling wedged worker",{outcome:s.outcome,detail:s.detail}),!await qc(e,n)))return!1;Ng(s,u)}let c=Eo();try{return c&&go(i,a,pt({...process.env,MEMINDEX_WORKER_PORT:String(ie())}),process.platform,Math.max(1,r()))===void 0?!1:await mg(e)}catch(u){return f.debug("SYSTEM","Bounded worker startup failed",{error:u instanceof Error?u.message:String(u)}),!1}finally{c&&bn()}}async function mg(t){for(;t-Date.now()>0;){let e=await Zt(Math.max(1,t-Date.now()));if(e.outcome==="ready")return!0;if(e.outcome!=="not_running")return f.debug("SYSTEM","Bounded worker startup did not reach ready",{outcome:e.outcome,detail:e.detail}),!1;let r=Math.min(100,t-Date.now());r>0&&await new Promise(n=>setTimeout(n,r))}return!1}function Co(){return L.default.join(W,"state")}function Wg(){return L.default.join(Co(),"hook-failures.json")}function jg(){return L.default.join(Co(),"hook-failures.lock")}async function Jc(t=$g){let e=Co(),r=jg(),n=(0,Sg.randomUUID)(),s=JSON.stringify({pid:process.pid,token:n}),o=Date.now()+t;for(;Date.now()<=o;)try{return(0,x.mkdirSync)(e,{recursive:!0}),(0,x.writeFileSync)(r,s,{flag:"wx"}),n}catch(i){let a=i instanceof Error?i:new Error(String(i)),c=a.code;if(c!=="EEXIST")return f.warn("SYSTEM","Hook-failure lock unavailable; skipping failure-state update",{lockPath:r,code:c},a),null;let u;try{u=(0,x.statSync)(r).mtimeMs}catch{continue}if(Date.now()-u>Bg){let l;try{l=(0,x.statSync)(r).mtimeMs}catch{continue}if(l===u)try{(0,x.unlinkSync)(r);continue}catch{}}await new Promise(l=>setTimeout(l,aT))}return f.warn("SYSTEM","Timed out waiting for hook-failure lock; skipping failure-state update",{lockPath:r,waitMs:t}),null}function Qc(t){let e=jg();try{if(JSON.parse((0,x.readFileSync)(e,"utf-8")).token!==t)return;(0,x.unlinkSync)(e)}catch{}}function uT(t){let 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,thresholdTripped:e.thresholdTripped===!0,notifiedSessionIds:Array.isArray(e.notifiedSessionIds)?e.notifiedSessionIds.filter(r=>typeof r=="string").slice(-Ug):void 0}}function Tn(){try{return uT((0,x.readFileSync)(Wg(),"utf-8"))}catch{return{consecutiveFailures:0,lastFailureAt:0,thresholdTripped:!1}}}function Zc(t){let e=Co(),r=Wg(),n=`${r}.tmp`;try{return(0,x.existsSync)(e)||(0,x.mkdirSync)(e,{recursive:!0}),(0,x.writeFileSync)(n,JSON.stringify(t),"utf-8"),(0,x.renameSync)(n,r),!0}catch(s){return f.debug("SYSTEM","Failed to persist hook-failure counter",{error:s instanceof Error?s.message:String(s)}),!1}}function lT(){try{let e=G().MEMINDEX_HOOK_FAIL_LOUD_THRESHOLD,r=parseInt(e,10);if(Number.isFinite(r)&&r>=1)return r}catch{}return iT}function Hg(t){let e=Wc!==null?`The worker cannot bind port ${Wc} on ${Gc()}: the system refuses it (EACCES or EADDRNOTAVAIL). ${Oc}.`:er!==null?`Port ${er} is held by an unreachable process that no PID file claims, so the worker cannot bind it. ${No}.`:"Run `npx memindex restart`; if it keeps failing, run `npx memindex doctor`.";return`memindex worker unreachable for ${t} consecutive hooks \u2014 memory features are degraded, but your prompts are not blocked. ${e}`}async function Po(){if(dT){if(_g)return Tn().consecutiveFailures;_g=!0}let t=await Jc();if(t===null)return Tn().consecutiveFailures;let e,r=!1;try{let n=Tn();e={consecutiveFailures:n.consecutiveFailures+1,lastFailureAt:Date.now(),thresholdTripped:n.thresholdTripped,notifiedSessionIds:n.notifiedSessionIds};let s=lT();r=e.consecutiveFailures>=s&&!e.thresholdTripped,r&&(e.thresholdTripped=!0);let o=Zc(e);r=r&&o}finally{Qc(t)}return r&&(await Zf("hook_failed",{...hg!==null?{hook_type:hg}:{},error_mode:"worker_unavailable",consecutive_failures:e.consecutiveFailures,threshold_tripped:!0}),ct(`${Hg(e.consecutiveFailures)}
|
|
23
23
|
`)),e.consecutiveFailures}async function Xg(t){if(!t)return null;let e=await Jc();if(e===null)return null;try{let r=Tn(),n=r.notifiedSessionIds??[];return!r.thresholdTripped||n.includes(t)?null:Zc({...r,notifiedSessionIds:[...n,t].slice(-Ug)})?Hg(r.consecutiveFailures):null}finally{Qc(e)}}async function Eg(){let t=await Jc(cT);if(t!==null)try{let e=Tn();if(e.consecutiveFailures===0&&!e.thresholdTripped)return;Zc({consecutiveFailures:0,lastFailureAt:0,thresholdTripped:!1})}finally{Qc(t)}}function Kg(t){return typeof t=="object"&&t!==null&&t[Ot]===!0}async function Gg(t,e,r,n={}){let s=Date.now(),o=n.workerStartupTimeoutMs!==void 0;if(!(o?await oT(n.workerStartupTimeoutMs):await sT(n.timeoutMs)))return $s(G())?{continue:!0,reason:"worker_autostart_disabled",[Ot]:!0}:(o||await Po(),{continue:!0,reason:"worker_unreachable",[Ot]:!0});let a=n.timeoutMs===void 0?qe:Math.max(1,Math.min(qe,n.timeoutMs-(Date.now()-s)));if(await nT(a)!==null)return await Po(),{continue:!0,reason:"worker_foreign_data_dir",[Ot]:!0};let c={method:e};if(r!==void 0&&(c.headers={"Content-Type":"application/json"},c.body=JSON.stringify(r)),n.timeoutMs!==void 0){let d=o?n.timeoutMs:n.timeoutMs-(Date.now()-s);if(d<Hc)return f.debug("SYSTEM","Hook budget spent before the worker request; skipping it",{url:t}),o||await Po(),{continue:!0,reason:"worker_budget_exhausted",[Ot]:!0};c.timeoutMs=d}let u;try{u=await le(t,c)}catch(d){if(!o)throw d;return f.debug("SYSTEM","Worker unavailable for best-effort hook call",{error:d instanceof Error?d.message:String(d)}),{continue:!0,reason:"worker_unreachable",[Ot]:!0}}if(!u.ok){let d=await u.text().catch(()=>"");if(await Eg(),u.status===429||u.status>=500)return f.warn("SYSTEM",`Worker API ${e} ${t} returned ${u.status}; skipping hook API call`,{body:d.substring(0,200)}),{continue:!0,reason:`worker_api_${u.status}`,[Ot]:!0};let p=d;try{p=JSON.parse(d)}catch{}return p}let l;try{l=await u.text()}catch(d){return f.debug("SYSTEM","Worker response body could not be read; treating the worker as unreachable",{error:d instanceof Error?d.message:String(d)}),o||await Po(),{continue:!0,reason:"worker_body_read_failed",[Ot]:!0}}if(await Eg(),l.length!==0)try{return JSON.parse(l)}catch{return l}}var L,Sg,x,qe,Ar,wn,vw,Rw,Aw,Hc,Uc,$c,vo,Ro,Ao,Og,No,er,Wc,Oo,Qt,iT,Ug,$g,aT,Bg,cT,hg,dT,_g,Ot,Pt=E(()=>{"use strict";Ka();L=be(require("path"),1),Sg=require("crypto"),x=require("fs");O();xe();Ef();dt();C();ft();Sf();yf();Ya();$a();hn();mt();xs();ep();Dp();ho();Pc();Ac();$p();zp();mn();yr();se();Jp();ag();Ya();qe=jc("MEMINDEX_HEALTH_TIMEOUT_MS",ze(Q.HEALTH_CHECK),{min:500,max:3e5}),Ar=jc("MEMINDEX_HOOK_READINESS_TIMEOUT_MS",ze(Q.HOOK_READINESS_WAIT),{min:0,max:3e5}),wn=jc("MEMINDEX_WORKER_STANDBY_WAIT_MS",Zp,{min:500,max:3e5}),vw=5e3,Rw={min:500,max:3e5},Aw={min:500,max:Q.SESSION_INIT_REQUEST_MAX},Hc=100;Uc=null,$c=null,vo=null,Ro=null,Ao=null;Og=3e4;No="Set MEMINDEX_WORKER_PORT to a different port in memindex settings, or reboot to release the stuck port",er=null,Wc=null;Oo=null;iT=3,Ug=20,$g=1e3,aT=10,Bg=5e3,cT=Bg+$g;hg=null;dT=!1,_g=!1;Ot=Symbol.for("memindex/worker-fallback")});function eu(t,e){let r=(0,Je.normalize)(t),n=(0,Je.normalize)(e);if(r===n)return!0;let s=(0,Je.relative)(n,r);return s.length>0&&!s.startsWith("..")&&!(0,Je.isAbsolute)(s)}function Qe(t){if(process.env.MEMINDEX_INTERNAL==="1")return!1;if(!t)return!0;if(eu(t,Ns)||eu(t,_T)||eu(t,ET))return!1;let e=G();return!io(t,e.MEMINDEX_EXCLUDED_PROJECTS)}var Je,fT,pT,gT,mT,hT,_T,ET,Pr=E(()=>{"use strict";Je=require("path");Sn();ft();C();fT="plugins",pT="cache",gT="memindex",mT="memindex",hT="plugin",_T=(0,Je.join)(lt,fT,pT,gT,mT),ET=(0,Je.join)(Er,hT)});function ST(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function z(t){if(!t)return zg;let e=ST(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e.includes("kimi")?"kimi":e==="pi-mono"?"pi":e==="agy"||e==="antigravity"||e.startsWith("antigravity-")?"antigravity-cli":e:zg}var zg,ht=E(()=>{"use strict";zg="claude"});var Vg=E(()=>{"use strict"});function ru(t){return new RegExp(`${t}${yT}`,"gi")}function nu(t,e){if(!e.enabled||t.length===0)return{redacted:t,counts:{},oversize:!1};if(t.length>wT)return f.warn("REDACT","field exceeds the 1M-char redaction cap; replaced by an oversize marker",void 0,{inputLength:t.length}),{redacted:TT,counts:{oversize:1},oversize:!0};let r=new Set(e.disabledBuiltinPatterns??[]),n={},s=t,o=[];for(let a of e.customPatterns??[]){if(!a.name||a.name.length===0){f.warn("REDACT","custom pattern skipped: missing name",void 0,{pattern:a});continue}try{o.push({name:a.name,regex:new RegExp(a.regex,"g")})}catch(c){f.warn("REDACT","custom pattern skipped: invalid regex",{name:a.name},c instanceof Error?c:new Error(String(c)))}}let i=[...o,...bT];for(let a of i)r.has(a.name)||(a.regex.lastIndex=0,s=s.replace(a.regex,()=>(n[a.name]=(n[a.name]??0)+1,`<redacted type='${a.name}'/>`)));return e.logMatches&&Object.keys(n).length>0&&f.debug("REDACT","patterns matched",void 0,{counts:n}),{redacted:s,counts:n,oversize:!1}}function IT(t){if(!t||t.trim()==="")return[];try{let e=JSON.parse(t);return Array.isArray(e)?e.filter(r=>r&&typeof r.name=="string"&&typeof r.regex=="string"):(f.warn("REDACT","MEMINDEX_REDACT_CUSTOM_PATTERNS is not a JSON array, ignoring"),[])}catch(e){return f.warn("REDACT","failed to parse MEMINDEX_REDACT_CUSTOM_PATTERNS as JSON",void 0,e instanceof Error?e:new Error(String(e))),[]}}function vT(t){return{enabled:t.MEMINDEX_REDACT_ENABLED==="true",disabledBuiltinPatterns:(t.MEMINDEX_REDACT_DISABLED_BUILTINS??"").split(",").map(e=>e.trim()).filter(Boolean),customPatterns:IT(t.MEMINDEX_REDACT_CUSTOM_PATTERNS??"[]"),logMatches:t.MEMINDEX_REDACT_LOG_MATCHES==="true"}}function PT(t){if(!(0,Do.existsSync)(t))return null;try{return(0,Do.readFileSync)(t,"utf-8")}catch{return""}}function MT(t){if(t===null)return!1;try{let e=JSON.parse(Ma(t));return e===null||typeof e!="object"||Array.isArray(e)}catch{return!0}}function xT(t,e,r){return process.env.MEMINDEX_REDACT_ENABLED==="false"||!(Rn?.enabled===!0||OT.test(e))?r:(qg||(qg=!0,f.warn("REDACT","settings.json could not be read; secret redaction stays on until it is repaired",{settingsPath:t,using:Rn?.enabled?"the last configuration that loaded":"the built-in patterns"})),Rn?.enabled?Rn:AT)}function su(t=_e){let e=Date.now();if(vn&&e-Yg<RT)return vn;let r=V.loadFromFile(t),n=vT(r),s=n.enabled?null:PT(t);return MT(s)?vn=xT(t,s,n):(vn=n,Rn=n),Yg=e,vn}function Jg(t){return nu(t,su()).redacted}var Do,tu,yT,bT,wT,TT,vn,Yg,RT,Rn,qg,AT,OT,ou=E(()=>{"use strict";Do=require("fs");O();dt();C();se();tu=String.raw`[A-Za-z0-9_.\-+/=~@#$%^*!?]`,yT=`(?=${tu}{8})${tu}*[A-Za-z]${tu}*`;bT=[{name:"aws_access_key",regex:/AKIA[0-9A-Z]{16}/g},{name:"aws_secret_key",regex:/(?<=AWS_SECRET_ACCESS_KEY\s*[=:]\s*['"]?)[A-Za-z0-9/+=]{40}/g},{name:"github_pat",regex:/\bgh[oprs]_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{82}\b/g},{name:"openai_key",regex:/\bsk-(?!ant-)[A-Za-z0-9_-]{20,}\b/g},{name:"anthropic_key",regex:/\bsk-ant-[A-Za-z0-9_-]{20,}\b/g},{name:"slack_token",regex:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g},{name:"jwt",regex:/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g},{name:"private_key_pem",regex:/-----BEGIN (?:RSA |DSA |EC |OPENSSH |PGP )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |DSA |EC |OPENSSH |PGP )?PRIVATE KEY-----/g},{name:"stripe_key",regex:/\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]{24,}\b/g},{name:"google_api_key",regex:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:"memindex_key",regex:new RegExp("\\bmi_[A-Za-z0-9_-]{32,}","g")},{name:"generic_password",regex:ru(String.raw`(?<=\b\w*_?(?:password|passwd|pwd)\\{0,2}["']?\s*[=:]\s*\\{0,2}["']?)`)},{name:"generic_token",regex:ru(String.raw`(?<=\b\w*_(?:token|secret|api_key)\\{0,2}["']?\s*[=:]\s*\\{0,2}["']?)`)},{name:"bearer_token",regex:ru(String.raw`(?<=\bAuthorization\s*:\s*Bearer\s*)`)}],wT=1024*1024,TT="<redacted type='oversize'/>";vn=null,Yg=0,RT=5e3,Rn=null,qg=!1,AT={enabled:!0,disabledBuiltinPatterns:[],customPatterns:[],logMatches:!1},OT=/"(?:MEMINDEX|AGENT_MEM)_REDACT_ENABLED"\s*:\s*"true"/});function NT(t){let e=Object.fromEntries(iu.map(l=>[l,0])),r=t.length,n=new Int32Array(r+1);n[r]=r;for(let l=r-1;l>=0;l--)n[l]=t.charCodeAt(l)===62?l:n[l+1];let s=new Map,o=[],i=0,a=0;for(;a<r;){if(t.charCodeAt(a)!==60){a+=1;continue}Zg.lastIndex=a;let l=Zg.exec(t);if(l){let p=l[1],g=s.get(p),m=g&&g.head<g.items.length?g.items[g.head]:void 0;m&&a>=m.attrEnd&&(g.head+=1,o.push([m.start,a+l[0].length]),e[p]+=1,i+=1),a+=l[0].length;continue}Qg.lastIndex=a;let d=Qg.exec(t);if(d&&kT.has(d[1])){let p=d[1],g=a+d[0].length,m={start:a,attrEnd:n[g]},h=s.get(p);h?h.items.push(m):s.set(p,{items:[m],head:0}),a=g;continue}a+=1}o.sort((l,d)=>l[0]-d[0]);let c="",u=0;for(let[l,d]of o)l>u&&(c+=t.slice(u,l)),d>u&&(u=d);return c+=t.slice(u),{text:c,counts:e,total:i}}function CT(t){let{text:e,counts:r,total:n}=NT(t);return n>em&&f.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:n,maxAllowed:em,contentLength:t.length}),{stripped:nu(e.trim(),su()).redacted,counts:r}}function Ie(t){return CT(t).stripped}function An(t){let e=r=>typeof r=="string"?DT.test(r)?Ie(r):r:Array.isArray(r)?r.map(e):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).map(([n,s])=>[n,e(s)])):r;return e(t)}function Lo(t){return!t||t.length>UT?!1:LT.test(t)}function tm(t){let e=t.trimStart();return $T.some(r=>r.test(e))}var iu,kT,Qg,Zg,Fo,em,DT,FT,LT,UT,$T,Ze=E(()=>{"use strict";O();ou();iu=["private","memindex-context","agent-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],kT=new Set(iu),Qg=/<([A-Za-z_][A-Za-z0-9_-]*)/y,Zg=/<\/([A-Za-z_][A-Za-z0-9_-]*)\s*>/y;Fo=/<system-reminder>[\s\S]*?<\/system-reminder>/g,em=100;DT=new RegExp(`<(${iu.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`);FT=["task-notification"],LT=new RegExp(`^\\s*<(${FT.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),UT=256*1024;$T=[/^You are a helpful assistant\. You will be presented with a user prompt, and your job is to provide a short title/,/^## Memory Writing Agent: Phase 2 \(Consolidation\)/,/^# Overview\r?\n(?:\r?\n)?Generate 0 to 3 hyperpersonalized suggestions/]});function Fe(t){return t instanceof _t}function WT(t){return t.replace(/\/+$/,"")}function Uo(t){return typeof t=="string"?z(t):null}function jT(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}var BT,_t,$o,tr=E(()=>{"use strict";Pt();xe();ht();Ze();BT=ze(Q.API_REQUEST),_t=class extends Error{kind;status;cause;constructor(e,r,n={}){super(r),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)}},$o=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=WT(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??BT}async startSession(e,r={}){let n=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",n,r)}async recordEvent(e,r={}){let n=this.buildEventPayload(e),s=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",s,n,r)}async endSession(e,r={}){if(!e.sessionId)throw new _t("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{},r)}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,r={}){let n={projectId:e.projectId};return e.query!==void 0&&(n.query=e.query),e.limit!==void 0&&(n.limit=e.limit),e.summaryLimit!==void 0&&(n.summaryLimit=e.summaryLimit),e.platformSource!==void 0&&(n.platformSource=Uo(e.platformSource)),e.folderProjects&&e.folderProjects.length>0&&(n.folderProjects=e.folderProjects),e.excludeSubagents!==void 0&&(n.excludeSubagents=e.excludeSubagents),this.request("POST","/v1/context",n,r)}async getJobStatus(e){if(!e)throw new _t("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,n=e.kind??"manual",s=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,content:r,...s?{title:s}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.platformSource!==void 0?{platformSource:e.platformSource}:{},...e.metadata!==void 0?{metadata:e.metadata}:{},...e.generationKey!==void 0?{generationKey:e.generationKey}:{},...e.createdAtEpoch!==void 0?{createdAtEpoch:e.createdAtEpoch}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Uo(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:Uo(e.platformSource)}:{},...e.metadata!==void 0?{metadata:An(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:Uo(e.platformSource)}:{},...e.payload!==void 0?{payload:An(e.payload)}:{}}}async request(e,r,n,s={}){if(!this.apiKey||!this.apiKey.trim())throw new _t("missing_api_key","Server API key is not configured (MEMINDEX_SERVER_API_KEY).");let o=`${this.baseUrl}${r}`,i={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(i.body=JSON.stringify(n));let a=d=>{let p=d instanceof Error?d.message:String(d),g=/timed out|timeout/i.test(p)||d instanceof Error&&(d.name==="TimeoutError"||d.name==="AbortError");return new _t(g?"timeout":"transport",`Server ${e} ${r} failed: ${p}`,{cause:d})},c,u=s.timeoutMs??this.timeoutMs;try{c=await In(o,i,u)}catch(d){throw a(d)}if(!c.ok){let d=await c.text().catch(()=>"");throw new _t("http_error",`Server ${e} ${r} returned ${c.status}: ${jT(d,200)}`,{status:c.status})}let l;try{l=await c.text()}catch(d){throw a(d)}if(!l||l.length===0)return{};try{return JSON.parse(l)}catch(d){let p=d instanceof Error?d:new Error(String(d));throw new _t("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:p})}}}});function HT(){let e=(G().MEMINDEX_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function XT(){let t=G(),e=(...r)=>{for(let n of r){let s=(n??"").trim();if(s.length>0)return s}return""};return{serverBaseUrl:e(t.MEMINDEX_SERVER_URL,t.MEMINDEX_SERVER_BETA_URL),apiKey:e(t.MEMINDEX_SERVER_API_KEY,t.MEMINDEX_SERVER_BETA_API_KEY),projectId:e(t.MEMINDEX_SERVER_PROJECT_ID,t.MEMINDEX_SERVER_BETA_PROJECT_ID)}}function KT(){let{serverBaseUrl:t,apiKey:e,projectId:r}=XT();if(!t)return f.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!e)return f.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!r)return f.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let n={serverBaseUrl:t,apiKey:e};return{runtime:"server",client:new $o(n),projectId:r,serverBaseUrl:t}}function Le(){if(HT()!=="server")return{runtime:"worker"};let t=KT();return t||{runtime:"worker"}}function Ue(t,e){f.warn("HOOK",`[server-fallback] reason=${t}`,e??{})}var Mr=E(()=>{"use strict";ft();O();tr()});function qT(t){let e=t.trim().replace(/\/+$/,"");try{let r=new URL(e);return`${r.protocol}//${r.host}${r.pathname.replace(/\/+$/,"")}${r.search}`}catch{return e}}function $e(t){let e=(0,lu.createHash)("sha256").update(qT(t.serverBaseUrl)).update("\0").update(t.projectId).digest("hex").slice(0,16);return(0,Mt.join)(N(),"state","server-outbox",e)}function du(t){return(0,Mt.join)(t,"outage.json")}function Et(t){return Fe(t)&&t.isFallbackEligible()&&t.kind!=="missing_api_key"}function JT(){return au=Math.max(Date.now(),au+1),au}function QT(t,e){let r=(0,lu.createHash)("sha256").update(JSON.stringify(e)).digest("hex").slice(0,16);return`${String(t).padStart(15,"0")}-${e.op}-${r}.json`}function xt(t,e){(0,H.mkdirSync)(e,{recursive:!0});let r=An(t),n=JT(),s=(0,Mt.join)(e,QT(n,r));return U(s,{version:1,heldAtEpochMs:n,entry:r}),f.warn("HOOK","Hosted server unreachable; capture held on this computer until it is back",{op:t.op,path:s}),s}function sm(t){return(0,H.existsSync)(t)?(0,H.readdirSync)(t).filter(e=>e.endsWith(".json")&&e!=="outage.json").sort():[]}function uu(t){try{return sm(t).length}catch{return 0}}function ZT(t){for(let e of(0,H.readdirSync)(t)){if(!e.endsWith(`.json${cu}`))continue;let r=(0,Mt.join)(t,e);try{if(Date.now()-(0,H.statSync)(r).mtimeMs<GT)continue;(0,H.renameSync)(r,r.slice(0,-cu.length))}catch{}}}async function fu(t,e,r=()=>({}),n=()=>{}){let s=e;if(!s.serverSessionId){let i=await t.startSession({projectId:e.projectId,externalSessionId:e.contentSessionId,contentSessionId:e.contentSessionId,platformSource:e.platformSource},r());s={...s,serverSessionId:i.session.id},n(s)}let o=s.serverSessionId;s.eventRecorded||(await t.recordEvent({projectId:e.projectId,serverSessionId:o,contentSessionId:e.contentSessionId,platformSource:e.platformSource,sourceType:"hook",eventType:"assistant_message",occurredAtEpoch:e.occurredAtEpoch,payload:{last_assistant_message:e.lastAssistantMessage,platformSource:e.platformSource}},r()),s={...s,eventRecorded:!0},n(s)),await t.endSession({sessionId:o},r())}async function eI(t,e,r,n){let s=()=>({timeoutMs:Math.max(1,r-Date.now())});e.op==="event"?await t.recordEvent(e.request,s()):e.op==="session_start"?await t.startSession(e.request,s()):await fu(t,e.request,s,n)}function nm(t,e,r){try{(0,H.mkdirSync)((0,Mt.join)(t,rm),{recursive:!0}),(0,H.renameSync)(e,(0,Mt.join)(t,rm,r))}catch(n){f.error("HOOK","Could not move a rejected held capture aside",{name:r},n instanceof Error?n:new Error(String(n)))}}async function xr(t,e,r={}){let n=r.maxEntries??VT,s=Date.now()+(r.budgetMs??YT),o={delivered:0,remaining:0,rejected:0};try{if(!(0,H.existsSync)(e))return o;ZT(e);let i=sm(e),a=0;for(let c of i){if(a>=n||Date.now()>=s)break;let u=(0,Mt.join)(e,c),l=`${u}${cu}`;try{(0,H.renameSync)(u,l)}catch{continue}try{let p=new Date;(0,H.utimesSync)(l,p,p)}catch{}a++;let d;try{if(d=JSON.parse((0,H.readFileSync)(l,"utf-8")),d?.version!==1||!d.entry?.op)throw new Error("unrecognised held capture")}catch(p){f.error("HOOK","Held capture is unreadable; moved aside",{name:c},p instanceof Error?p:new Error(String(p))),nm(e,l,c),o.rejected++;continue}try{let p=m=>{try{U(l,{...d,entry:{op:"summarize",request:m}})}catch{}},g=a===1?Math.max(s,Date.now()+Q.API_REQUEST):s;await eI(t,d.entry,g,p),(0,H.unlinkSync)(l),o.delivered++}catch(p){if(Et(p)){(0,H.renameSync)(l,u);break}f.error("HOOK","Hosted server refused a held capture; moved aside",{name:c,op:d.entry.op,status:Fe(p)?p.status:null},p instanceof Error?p:new Error(String(p))),nm(e,l,c),o.rejected++}}o.remaining=uu(e),o.delivered>0&&f.info("HOOK","Sent held captures to the hosted server",{...o}),o.remaining===0&&rI(e)}catch(i){f.warn("HOOK","Could not send held captures; they stay on this computer",{},i instanceof Error?i:new Error(String(i))),o.remaining=uu(e)}return o}function tI(t){try{let e=JSON.parse((0,H.readFileSync)(du(t),"utf-8"));return{notifiedSessionIds:Array.isArray(e.notifiedSessionIds)?e.notifiedSessionIds:[]}}catch{return{notifiedSessionIds:[]}}}function rI(t){try{(0,H.unlinkSync)(du(t))}catch{}}function nI(t){return`MemIndex can't reach your hosted memory server. ${t===1?"1 capture from this computer is":`${t} captures from this computer are`} saved and will be sent automatically when it's back. Recall from hosted memory is paused until then.`}function om(t,e){if(!t)return null;let r=uu(e);if(r===0)return null;let n=tI(e);if(n.notifiedSessionIds.includes(t))return null;try{U(du(e),{notifiedSessionIds:[...n.notifiedSessionIds,t].slice(-zT)})}catch{}return nI(r)}var lu,H,Mt,cu,rm,GT,zT,VT,YT,au,On=E(()=>{"use strict";lu=require("crypto"),H=require("fs"),Mt=require("path");se();C();xe();O();Ze();tr();cu=".sending",rm="rejected",GT=120*1e3,zT=50,VT=20,YT=1500;au=0});function Wo(t){return pI.run(t,!0)}function gI(t,e,r,n,s,o){return{projectId:t.projectId,externalSessionId:r,contentSessionId:r,agentId:e.agentId??null,agentType:e.agentType??null,platformSource:n,metadata:{project:s,prompt:o}}}async function mI(t,e,r){await t.client.startSession(e,{timeoutMs:r}),f.info("HOOK","session-init: server session started",{contentSessionId:e.contentSessionId,project:e.metadata?.project})}function hI(t){let e=t.replace(cI," ").toLowerCase().match(/[\p{L}\p{N}_]{4,}/gu)??[],r=[...new Set(e)].slice(0,aI);return r.length>0?r.join(" or "):null}async function _I(t,e,r,n,s,o,i){if(e.length<20||e==="[media prompt]")return"";let a=hI(e);if(!a)return"";let c=pu(o,i);if(c<Bo)return f.warn("HOOK","session-init: skipping server semantic injection because the prompt budget is spent",{remainingMs:c}),"";try{let u=await t.client.contextObservations({projectId:t.projectId,query:a,limit:Math.min(200,yI(s.MEMINDEX_SEMANTIC_INJECT_LIMIT||"5")),platformSource:n,...r.length>0?{folderProjects:r.slice(0,20)}:{}},{timeoutMs:c}),l=Array.isArray(u?.observations)?u.observations.length:0;return f.debug("HOOK",`Server semantic injection: ${l} observations for prompt`,{count:l}),typeof u?.context=="string"?u.context.slice(0,uI):""}catch(u){return f.warn("HOOK","session-init: server semantic context unavailable",{error:u instanceof Error?u.message:String(u)}),""}}function EI(t){let e=String(t.MEMINDEX_SEMANTIC_INJECT).toLowerCase();return e==="auto"?String(t.MEMINDEX_MODE).toLowerCase()==="personal":e==="true"}function SI(t){let e=String(t.MEMINDEX_READ_ONLY??"").toLowerCase();return e==="1"||e==="true"}async function im(t,e,r,n,s,o,i){if(!e||e.length<20||e==="[media prompt]")return"";let a=pu(o,i);if(a<Bo)return f.warn("HOOK","session-init: skipping semantic injection because the prompt budget is spent",{project:r,remainingMs:a}),"";let c=await de.executeWithWorkerFallback("/api/context/semantic","POST",{q:e,project:r,projects:n,limit:t.MEMINDEX_SEMANTIC_INJECT_LIMIT||"5",format:t.MEMINDEX_SEMANTIC_INJECT_FORMAT,platformSource:s},am(s,a));return de.isWorkerFallback(c)||!c?.context?"":(f.debug("HOOK",`Semantic injection: ${c.count} matches for prompt`,{project:r,count:c.count}),c.context)}function yI(t){let e=typeof t=="number"?t:Number.parseInt(t,10);return!Number.isFinite(e)||e<=0?5:e}function pu(t,e){return Math.max(0,e-(Date.now()-t))}function am(t,e){return t==="codex"?{workerStartupTimeoutMs:Q.POST_SPAWN_WAIT,timeoutMs:Math.min(lI,e)}:{timeoutMs:e}}var oI,de,iI,aI,cI,uI,Bo,lI,kr,dI,fI,pI,gu=E(()=>{"use strict";Pt();qt();O();xe();Pr();ft();ht();Vg();Ze();Mr();tr();On();oI={executeWithWorkerFallback:Gg,getSessionInitRequestTimeoutMs:Tg,isWorkerFallback:Kg,consumeWorkerOutageNotice:Xg,loadFromFileOnce:G,resolveRuntimeContext:Le,logServerFallback:Ue,holdForServer:xt,consumeServerOutageNotice:om,shouldTrackProject:Qe,readHookEnvironment:()=>process.env},de=oI,iI=2,aI=12,cI=/<private\b[^>]*>[\s\S]*?<\/private\s*>/gi,uI=1e4,Bo=500,lI=2e3,kr=class extends Error{constructor(r){super(`session-init did not record the prompt (${r})`);this.reason=r;this.name="SessionPromptNotRecordedError"}reason};dI=t=>t?t.replace(/\\/g,"/").includes("/.qwen/"):!1,fI=(t,e=process.env)=>t?e.QWEN_PROJECT_DIR?!0:dI(t):!1,pI={async run(t,e){let{sessionId:r,prompt:n,submittedPrompt:s}=t,o=t.cwd??process.cwd();if(!r)return f.warn("HOOK","session-init: No sessionId provided, skipping (Codex CLI or unknown platform)"),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};if(!de.shouldTrackProject(o))return f.info("HOOK","Project excluded from tracking",{cwd:o}),{continue:!0,suppressOutput:!0};if(n&&Lo(n))return f.debug("HOOK","session-init: skipping internal protocol payload",{preview:n.slice(0,80)}),{continue:!0,suppressOutput:!0};if(n&&z(t.platform)==="codex"&&tm(n))return f.debug("HOOK","session-init: skipping a Codex internal helper prompt",{reason:"internal_system_prompt",preview:n.slice(0,80)}),{continue:!0,suppressOutput:!0};if(s===null)return f.debug("HOOK","session-init: host reported no user-submitted text; not storing a prompt",{sessionId:r}),{continue:!0,suppressOutput:!0};if(s===void 0&&!n?.trim()&&fI(t.transcriptPath,de.readHookEnvironment()))return f.debug("HOOK","session-init: Qwen send carried no submitted_prompt and no prompt text; not storing a prompt",{sessionId:r}),{continue:!0,suppressOutput:!0};let i=s??n,a=!i||!i.trim()?"[media prompt]":i,c=lo(o),u=c.primary,l=z(t.platform),d=de.loadFromFileOnce(),p=EI(d),g=de.resolveRuntimeContext(),m=Date.now(),h=de.getSessionInitRequestTimeoutMs();if(g.runtime==="server"){let y=gI(g,t,r,l,u,a);try{await mI(g,y,Math.max(Bo,Math.floor(h/iI)));let A=p?await _I(g,a,c.allProjects,l,d,m,h):"";return A?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:A}}:{continue:!0,suppressOutput:!0}}catch(A){if(Et(A)){de.logServerFallback(A.kind,{status:A.status,message:A.message,route:"/v1/sessions/start",held:!0});let v=$e(g);de.holdForServer({op:"session_start",request:y},v);let R=de.consumeServerOutageNotice(r,v);return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS,...R?{systemMessage:R,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:R}}:{}}}if(Fe(A)&&A.isFallbackEligible())de.logServerFallback(A.kind,{status:A.status,message:A.message,route:"/v1/sessions/start"});else return f.error("HOOK","Server session-start failed (non-recoverable)",{error:A instanceof Error?A.message:String(A)}),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS}}}if(SI(de.readHookEnvironment())){let y=p?await im(d,a,u,c.allProjects,l,m,h):"";return y?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:y}}:{continue:!0,suppressOutput:!0}}f.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:r,project:u});let _=pu(m,h);if(_<Bo){if(f.warn("HOOK","session-init: skipping the worker call because the prompt budget is spent",{contentSessionId:r,project:u,remainingMs:_}),e)throw new kr("budget_exhausted");return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS}}let S=await de.executeWithWorkerFallback("/api/sessions/init","POST",{contentSessionId:r,project:u,prompt:a,platformSource:l,cwd:o,projectKeySource:c.keySource},am(l,_));if(de.isWorkerFallback(S)){if(e)throw new kr("reason"in S?S.reason:"worker_fallback");let y=await de.consumeWorkerOutageNotice(r);return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS,...y?{systemMessage:y}:{}}}if(typeof S?.sessionDbId!="number")return f.failure("HOOK","Session initialization returned malformed response",{contentSessionId:r,project:u}),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};let b=S.sessionDbId,w=S.promptNumber;if(f.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:b,promptNumber:w,skipped:S.skipped,contextInjected:S.contextInjected}),f.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${r} | prompt#=${w} | sessionDbId=${b}`),S.skipped&&S.reason==="private")return f.info("HOOK",`INIT_COMPLETE | sessionDbId=${b} | promptNumber=${w} | skipped=true | reason=private`,{sessionId:b}),{continue:!0,suppressOutput:!0};let T=p?await im(d,a,u,c.allProjects,l,m,h):"";return f.info("HOOK",`INIT_COMPLETE | sessionDbId=${b} | promptNumber=${w} | project=${u}`,{sessionId:b}),T?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:T}}:{continue:!0,suppressOutput:!0}}}});var cm=E(()=>{"use strict";Wt();C()});function Ko(){return(0,Be.join)(N(),"state","hook-spool")}function Ho(t){if(t===null||typeof t!="object")return JSON.stringify(t)??"null";if(Array.isArray(t))return`[${t.map(Ho).join(",")}]`;let e=t;return`{${Object.keys(e).filter(n=>e[n]!==void 0).sort().map(n=>`${JSON.stringify(n)}:${Ho(e[n])}`).join(",")}}`}function RI(t,e){if(t==="summarize"&&e.turnId){let n=e;return(0,jo.createHash)("sha256").update(Ho({contentSessionId:n.contentSessionId,platformSource:z(n.platformSource),turnId:n.turnId,lastAssistantMessage:n.lastAssistantMessage})).digest("hex")}let r=e.toolUseId;return typeof r=="string"&&dm.test(r)?`${(0,jo.createHash)("sha256").update(e.contentSessionId).update("\0").update(z(e.platformSource)).digest("hex")}-${r}`:(0,jo.createHash)("sha256").update(t).update("\0").update(e.contentSessionId).update("\0").update(Ho(e)).digest("hex")}function lm(t){return typeof t=="string"&&t.length>0}function mu(t){let e;try{e=JSON.parse(t)}catch(o){return{corruptReason:`invalid JSON: ${o instanceof Error?o.message:String(o)}`}}if(e===null||typeof e!="object")return{corruptReason:"not an object"};let r=e;if(!bI.includes(r.kind))return{corruptReason:`unknown kind ${JSON.stringify(r.kind)}`};if(typeof r.enqueuedAtEpochMs!="number"||!Number.isFinite(r.enqueuedAtEpochMs))return{corruptReason:"missing enqueuedAtEpochMs"};let n=r.payload;if(n===null||typeof n!="object"||!lm(n.contentSessionId))return{corruptReason:"payload missing contentSessionId"};let s=r.kind;return(s==="observation"||s==="file_edit")&&!lm(n.toolName)?{corruptReason:"observation payload missing toolName"}:s==="summarize"&&typeof n.lastAssistantMessage!="string"?{corruptReason:"summarize payload missing lastAssistantMessage"}:s==="advisor_calls"&&(!Array.isArray(n.calls)||n.calls.length===0)?{corruptReason:"advisor_calls payload has no calls"}:{kind:s,payload:{...n,platformSource:z(n.platformSource)},enqueuedAtEpochMs:r.enqueuedAtEpochMs}}function AI(){return hu=Math.max(Date.now(),hu+1),hu}var jo,te,Be,bI,wI,dm,TI,II,um,vI,hu,Xo,_u=E(()=>{"use strict";jo=require("crypto"),te=require("fs"),Be=require("path");se();C();ht();O();cm();bI=["observation","file_edit","summarize","session_end","advisor_calls"],wI=/^[a-z_]+-[A-Za-z0-9_-]+\.json$/,dm=/^[A-Za-z0-9_-]{1,128}$/,TI="corrupt",II="expired",um=10080*60*1e3,vI=300*1e3;hu=0;Xo=class{constructor(e=Ko()){this.directory=e}directory;get corruptDirectory(){return(0,Be.join)(this.directory,TI)}get expiredDirectory(){return(0,Be.join)(this.directory,II)}enqueue(e,r,n){let s={...r,platformSource:z(r.platformSource)},o=(0,Be.join)(this.directory,`${e}-${RI(e,s)}.json`),i=s.toolUseId;if(typeof i=="string"&&dm.test(i)){let c=(0,Be.join)(this.directory,`${e}-${i}.json`);try{let u=mu((0,te.readFileSync)(c,"utf8"));!("corruptReason"in u)&&u.kind===e&&u.payload.contentSessionId===s.contentSessionId&&u.payload.platformSource===s.platformSource&&(o=c)}catch{}}let a=this.existingEnqueuedAt(o)??n??AI();return U(o,{kind:e,payload:s,enqueuedAtEpochMs:a}),o}entries(){return this.readEntries().files.map(e=>e.entry)}async drain(e,r){let{files:n,quarantined:s}=this.readEntries(),o=0,i=0,a=0;r?.pruneConsumedBefore(Date.now()-um);let c=new Set;for(let u of n){let l=u.filename.replace(/\.json$/,""),d=u.entry.kind==="summarize"&&!!u.entry.payload.turnId;if(r?.isConsumed(l)){f.info("HOOK","Hook spool entry was already handed to ingest before a restart; removing it without ingesting again",{kind:u.entry.kind,contentSessionId:u.entry.payload.contentSessionId,file:u.filename}),this.unlinkEntry(u)?(d||r.clearConsumed(l),o++):i++;continue}let p=JSON.stringify([u.entry.payload.contentSessionId,u.entry.payload.platformSource]);if((u.entry.kind==="summarize"||u.entry.kind==="session_end")&&c.has(p)){i++;continue}let g=!1,m=()=>{if(!g){g=!0;try{r?.markConsumed(l,Date.now())}catch(_){f.error("HOOK","Could not record a hook spool hand-off marker; a crash before the file is removed would ingest it twice",{kind:u.entry.kind,contentSessionId:u.entry.payload.contentSessionId,file:u.filename},_ instanceof Error?_:new Error(String(_)))}}},h;try{h=await e(u.entry,m)}catch(_){f.warn("HOOK",g?"Hook spool entry failed after ingest accepted it; removing it (a retry would send it twice)":"Hook spool entry failed to ingest; keeping it for the next drain",{kind:u.entry.kind,contentSessionId:u.entry.payload.contentSessionId,file:u.filename},_ instanceof Error?_:new Error(String(_))),h=!1}if(g&&(h=!0),h==="expired"){this.expireIfPastWindow(u,vI,"unknown-session grace window")?a++:i++;continue}if(!h){this.expireIfPastWindow(u,um,"retry window")?a++:((u.entry.kind==="observation"||u.entry.kind==="file_edit")&&c.add(p),i++);continue}this.unlinkEntry(u)?(d||r?.clearConsumed(l),o++):i++}return{drained:o,retained:i,quarantined:s,expired:a}}unlinkEntry(e){try{return(0,te.unlinkSync)(e.path),!0}catch(r){return r.code==="ENOENT"?!0:(f.warn("HOOK","Hook spool entry was ingested but could not be removed",{kind:e.entry.kind,file:e.filename},r instanceof Error?r:new Error(String(r))),!1)}}expireIfPastWindow(e,r,n){let s=Date.now()-e.entry.enqueuedAtEpochMs;if(s<=r)return!1;let o={kind:e.entry.kind,contentSessionId:e.entry.payload.contentSessionId,ageMinutes:Math.round(s/6e4),ageHours:Math.round(s/36e5),file:e.filename,expiredDirectory:this.expiredDirectory};try{(0,te.mkdirSync)(this.expiredDirectory,{recursive:!0}),(0,te.renameSync)(e.path,(0,Be.join)(this.expiredDirectory,e.filename))}catch(i){return f.error("HOOK",`Hook spool entry is past its ${n} but could not be moved to expired/; keeping it`,o,i instanceof Error?i:new Error(String(i))),!1}return f.error("HOOK",`Hook spool entry was never accepted within its ${n}; moved to expired/`,o),!0}existingEnqueuedAt(e){if(!(0,te.existsSync)(e))return null;try{let r=mu((0,te.readFileSync)(e,"utf-8"));return"corruptReason"in r?null:r.enqueuedAtEpochMs}catch(r){return f.debug("HOOK","Could not read existing hook spool entry; writing a fresh one",{entryPath:e},r instanceof Error?r:new Error(String(r))),null}}quarantine(e,r){let n=(0,Be.join)(this.directory,e);try{return(0,te.mkdirSync)(this.corruptDirectory,{recursive:!0}),(0,te.renameSync)(n,(0,Be.join)(this.corruptDirectory,e)),f.error("HOOK","Quarantined corrupt hook spool entry",{file:e,reason:r,corruptDirectory:this.corruptDirectory}),!0}catch(s){return f.error("HOOK","Corrupt hook spool entry could not be quarantined; leaving it in place",{file:e,reason:r},s instanceof Error?s:new Error(String(s))),!1}}readEntries(){if(!(0,te.existsSync)(this.directory))return{files:[],quarantined:0};let e;try{e=(0,te.readdirSync)(this.directory).filter(s=>wI.test(s))}catch(s){return f.warn("HOOK","Could not list hook spool entries",{directory:this.directory},s instanceof Error?s:new Error(String(s))),{files:[],quarantined:0}}let r=[],n=0;for(let s of e){let o=(0,Be.join)(this.directory,s),i;try{i=(0,te.readFileSync)(o,"utf-8")}catch(c){c.code!=="ENOENT"&&f.warn("HOOK","Could not read hook spool entry; will retry",{file:s},c instanceof Error?c:new Error(String(c)));continue}let a=mu(i);if("corruptReason"in a){this.quarantine(s,a.corruptReason)&&n++;continue}r.push({entry:a,path:o,filename:s})}return r.sort((s,o)=>s.entry.enqueuedAtEpochMs-o.entry.enqueuedAtEpochMs||s.filename.localeCompare(o.filename)),{files:r,quarantined:n}}}});var gm={};As(gm,{SPOOL_NUDGE_TIMEOUT_MS:()=>fm,nudgeWorkerToDrainHookSpool:()=>pm,settleHookSpoolNudges:()=>OI,spoolHookEvent:()=>We});function pm(){if(Pn)return Pn;let t=(async()=>{try{await(await le("/api/spool/nudge",{method:"POST",timeoutMs:fm})).body?.cancel()}catch(e){f.debug("HOOK","Hook spool nudge not delivered (worker will pick the entry up on its own)",{error:e instanceof Error?e.message:String(e)})}})();return Pn=t,Eu.add(t),t.finally(()=>{Eu.delete(t),Pn===t&&(Pn=null)}),t}async function OI(){await Promise.all([...Eu])}function We(t,e,r){let n=new Xo().enqueue(t,e,r);return f.debug("HOOK","Hook event spooled for the worker",{kind:t,entryPath:n}),pm(),n}var fm,Eu,Pn,Nr=E(()=>{"use strict";_u();Pt();O();fm=250,Eu=new Set,Pn=null});function kt(t,e){return e?new Set(e.split(",").map(n=>n.trim().toLowerCase()).filter(Boolean)).has(t.toLowerCase()):!1}var Mn=E(()=>{"use strict"});function wm(t,e){return!!t&&!!e}var Tm=E(()=>{"use strict"});function CI(t){return new Set((t??"").split(",").map(e=>e.trim()).filter(Boolean))}function Dr(t,e,r){return wm(t,e)?r.MEMINDEX_SKIP_SUBAGENT_OBSERVATIONS==="true"?{skip:!0,reason:"subagent_observation"}:e&&CI(r.MEMINDEX_SKIP_AGENT_TYPES).has(e)?{skip:!0,reason:"agent_type_excluded"}:Im:Im}var Im,zo=E(()=>{"use strict";Tm();Im={skip:!1}});var Tt,Tl=E(()=>{Tt="1.9.1"});function WA(t){let e=new Set([t]),r=new Set,n=t.match(v_);if(!n)return()=>!1;let s={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(s.prerelease!=null)return function(c){return c===t};function o(a){return r.add(a),!1}function i(a){return e.add(a),!0}return function(c){if(e.has(c))return!0;if(r.has(c))return!1;let u=c.match(v_);if(!u)return o(c);let l={major:+u[1],minor:+u[2],patch:+u[3],prerelease:u[4]};return l.prerelease!=null||s.major!==l.major?o(c):s.major===0?s.minor===l.minor&&s.patch<=l.patch?i(c):o(c):s.minor<=l.minor?i(c):o(c)}}var v_,R_,A_=E(()=>{Tl();v_=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;R_=WA(Tt)});function st(t,e,r,n=!1){var s;let o=ls[us]=(s=ls[us])!==null&&s!==void 0?s:{version:Tt};if(!n&&o[t]){let i=new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${t}`);return r.error(i.stack||i.message),!1}if(o.version!==Tt){let i=new Error(`@opentelemetry/api: Registration of version v${o.version} for ${t} does not match previously registered API v${Tt}`);return r.error(i.stack||i.message),!1}return o[t]=e,r.debug(`@opentelemetry/api: Registered a global for ${t} v${Tt}.`),!0}function ye(t){var e,r;let n=(e=ls[us])===null||e===void 0?void 0:e.version;if(!(!n||!R_(n)))return(r=ls[us])===null||r===void 0?void 0:r[t]}function ot(t,e){e.debug(`@opentelemetry/api: Unregistering a global for ${t} v${Tt}.`);let r=ls[us];r&&delete r[t]}var jA,us,ls,dr=E(()=>{Tl();A_();jA=Tt.split(".")[0],us=Symbol.for(`opentelemetry.js.api.${jA}`),ls=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{}});function ds(t,e,r){let n=ye("diag");if(n)return n[t](e,...r)}var Ni,O_=E(()=>{dr();Ni=class{constructor(e){this._namespace=e.namespace||"DiagComponentLogger"}debug(...e){return ds("debug",this._namespace,e)}error(...e){return ds("error",this._namespace,e)}info(...e){return ds("info",this._namespace,e)}warn(...e){return ds("warn",this._namespace,e)}verbose(...e){return ds("verbose",this._namespace,e)}}});var ne,Ci=E(()=>{(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(ne||(ne={}))});function P_(t,e){t<ne.NONE?t=ne.NONE:t>ne.ALL&&(t=ne.ALL),e=e||{};function r(n,s){let o=e[n];return typeof o=="function"&&t>=s?o.bind(e):function(){}}return{error:r("error",ne.ERROR),warn:r("warn",ne.WARN),info:r("info",ne.INFO),debug:r("debug",ne.DEBUG),verbose:r("verbose",ne.VERBOSE)}}var M_=E(()=>{Ci()});var HA,ee,fr=E(()=>{O_();M_();Ci();dr();HA="diag",ee=class t{static instance(){return this._instance||(this._instance=new t),this._instance}constructor(){function e(s){return function(...o){let i=ye("diag");if(i)return i[s](...o)}}let r=this,n=(s,o={logLevel:ne.INFO})=>{var i,a,c;if(s===r){let d=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((i=d.stack)!==null&&i!==void 0?i:d.message),!1}typeof o=="number"&&(o={logLevel:o});let u=ye("diag"),l=P_((a=o.logLevel)!==null&&a!==void 0?a:ne.INFO,s);if(u&&!o.suppressOverrideMessage){let d=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";u.warn(`Current logger will be overwritten from ${d}`),l.warn(`Current logger will overwrite one already registered from ${d}`)}return st("diag",l,r,!0)};r.setLogger=n,r.disable=()=>{ot(HA,r)},r.createComponentLogger=s=>new Ni(s),r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error")}}});var Di,x_=E(()=>{Di=class t{constructor(e){this._entries=e?new Map(e):new Map}getEntry(e){let r=this._entries.get(e);if(r)return Object.assign({},r)}getAllEntries(){return Array.from(this._entries.entries())}setEntry(e,r){let n=new t(this._entries);return n._entries.set(e,r),n}removeEntry(e){let r=new t(this._entries);return r._entries.delete(e),r}removeEntries(...e){let r=new t(this._entries);for(let n of e)r._entries.delete(n);return r}clear(){return new t}}});var k_,N_=E(()=>{k_=Symbol("BaggageEntryMetadata")});function C_(t={}){return new Di(new Map(Object.entries(t)))}function D_(t){return typeof t!="string"&&(XA.error(`Cannot create baggage metadata from unknown type: ${typeof t}`),t=""),{__TYPE__:k_,toString(){return t}}}var XA,Il=E(()=>{fr();x_();N_();XA=ee.instance()});function Yr(t){return Symbol.for(t)}var vl,Fi,fs=E(()=>{vl=class t{constructor(e){let r=this;r._currentContext=e?new Map(e):new Map,r.getValue=n=>r._currentContext.get(n),r.setValue=(n,s)=>{let o=new t(r._currentContext);return o._currentContext.set(n,s),o},r.deleteValue=n=>{let s=new t(r._currentContext);return s._currentContext.delete(n),s}}},Fi=new vl});var Rl,Al,Li,F_=E(()=>{Rl=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}],Al={};if(typeof console<"u"){let t=["error","warn","info","debug","trace","log"];for(let e of t)typeof console[e]=="function"&&(Al[e]=console[e])}Li=class{constructor(){function e(r){return function(...n){let s=Al[r];if(typeof s!="function"&&(s=Al.log),typeof s!="function"&&console&&(s=console[r],typeof s!="function"&&(s=console.log)),typeof s=="function")return s.apply(console,n)}}for(let r=0;r<Rl.length;r++)this[Rl[r].n]=e(Rl[r].c)}}});function L_(){return Fl}var Ol,qr,Pl,Ml,xl,kl,ps,Nl,Cl,Dl,Fl,KA,GA,zA,VA,YA,qA,JA,Ll=E(()=>{Ol=class{constructor(){}createGauge(e,r){return GA}createHistogram(e,r){return zA}createCounter(e,r){return KA}createUpDownCounter(e,r){return VA}createObservableGauge(e,r){return qA}createObservableCounter(e,r){return YA}createObservableUpDownCounter(e,r){return JA}addBatchObservableCallback(e,r){}removeBatchObservableCallback(e){}},qr=class{},Pl=class extends qr{add(e,r){}},Ml=class extends qr{add(e,r){}},xl=class extends qr{record(e,r){}},kl=class extends qr{record(e,r){}},ps=class{addCallback(e){}removeCallback(e){}},Nl=class extends ps{},Cl=class extends ps{},Dl=class extends ps{},Fl=new Ol,KA=new Pl,GA=new xl,zA=new kl,VA=new Ml,YA=new Nl,qA=new Cl,JA=new Dl});var Ui,U_=E(()=>{(function(t){t[t.INT=0]="INT",t[t.DOUBLE=1]="DOUBLE"})(Ui||(Ui={}))});var $i,Bi,Ul=E(()=>{$i={get(t,e){if(t!=null)return t[e]},keys(t){return t==null?[]:Object.keys(t)}},Bi={set(t,e,r){t!=null&&(t[e]=r)}}});var Wi,$_=E(()=>{fs();Wi=class{active(){return Fi}with(e,r,n,...s){return r.call(n,...s)}bind(e,r){return r}enable(){return this}disable(){return this}}});var $l,QA,it,gs=E(()=>{$_();dr();fr();$l="context",QA=new Wi,it=class t{constructor(){}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalContextManager(e){return st($l,e,ee.instance())}active(){return this._getContextManager().active()}with(e,r,n,...s){return this._getContextManager().with(e,r,n,...s)}bind(e,r){return this._getContextManager().bind(e,r)}_getContextManager(){return ye($l)||QA}disable(){this._getContextManager().disable(),ot($l,ee.instance())}}});var Jr,Bl=E(()=>{(function(t){t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED"})(Jr||(Jr={}))});var ms,hs,ji,Hi=E(()=>{Bl();ms="0000000000000000",hs="00000000000000000000000000000000",ji={traceId:hs,spanId:ms,traceFlags:Jr.NONE}});var at,Xi=E(()=>{Hi();at=class{constructor(e=ji){this._spanContext=e}spanContext(){return this._spanContext}setAttribute(e,r){return this}setAttributes(e){return this}addEvent(e,r){return this}addLink(e){return this}addLinks(e){return this}setStatus(e){return this}updateName(e){return this}end(e){}isRecording(){return!1}recordException(e,r){}}});function Ki(t){return t.getValue(Wl)||void 0}function B_(){return Ki(it.getInstance().active())}function _s(t,e){return t.setValue(Wl,e)}function W_(t){return t.deleteValue(Wl)}function j_(t,e){return _s(t,new at(e))}function Gi(t){var e;return(e=Ki(t))===null||e===void 0?void 0:e.spanContext()}var Wl,jl=E(()=>{fs();Xi();gs();Wl=Yr("OpenTelemetry Context Key SPAN")});function H_(t,e){if(typeof t!="string"||t.length!==e)return!1;let r=0;for(let n=0;n<t.length;n+=4)r+=(zi[t.charCodeAt(n)]|0)+(zi[t.charCodeAt(n+1)]|0)+(zi[t.charCodeAt(n+2)]|0)+(zi[t.charCodeAt(n+3)]|0);return r===e}function Hl(t){return H_(t,32)&&t!==hs}function Xl(t){return H_(t,16)&&t!==ms}function Qr(t){return Hl(t.traceId)&&Xl(t.spanId)}function X_(t){return new at(t)}var zi,Vi=E(()=>{Hi();Xi();zi=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1])});function ZA(t){return t!==null&&typeof t=="object"&&"spanId"in t&&typeof t.spanId=="string"&&"traceId"in t&&typeof t.traceId=="string"&&"traceFlags"in t&&typeof t.traceFlags=="number"}var Kl,Zr,Gl=E(()=>{gs();jl();Xi();Vi();Kl=it.getInstance(),Zr=class{startSpan(e,r,n=Kl.active()){if(!!r?.root)return new at;let o=n&&Gi(n);return ZA(o)&&Qr(o)?new at(o):new at}startActiveSpan(e,r,n,s){let o,i,a;if(arguments.length<2)return;arguments.length===2?a=r:arguments.length===3?(o=r,a=n):(o=r,i=n,a=s);let c=i??Kl.active(),u=this.startSpan(e,o,c),l=_s(c,u);return Kl.with(l,a,void 0,u)}}});var eO,en,zl=E(()=>{Gl();eO=new Zr,en=class{constructor(e,r,n,s){this._provider=e,this.name=r,this.version=n,this.options=s}startSpan(e,r,n){return this._getTracer().startSpan(e,r,n)}startActiveSpan(e,r,n,s){let o=this._getTracer();return Reflect.apply(o.startActiveSpan,o,arguments)}_getTracer(){if(this._delegate)return this._delegate;let e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):eO}}});var Yi,K_=E(()=>{Gl();Yi=class{getTracer(e,r,n){return new Zr}}});var tO,pr,Vl=E(()=>{zl();K_();tO=new Yi,pr=class{getTracer(e,r,n){var s;return(s=this.getDelegateTracer(e,r,n))!==null&&s!==void 0?s:new en(this,e,r,n)}getDelegate(){var e;return(e=this._delegate)!==null&&e!==void 0?e:tO}setDelegate(e){this._delegate=e}getDelegateTracer(e,r,n){var s;return(s=this._delegate)===null||s===void 0?void 0:s.getTracer(e,r,n)}}});var qi,G_=E(()=>{(function(t){t[t.NOT_RECORD=0]="NOT_RECORD",t[t.RECORD=1]="RECORD",t[t.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"})(qi||(qi={}))});var Ji,z_=E(()=>{(function(t){t[t.INTERNAL=0]="INTERNAL",t[t.SERVER=1]="SERVER",t[t.CLIENT=2]="CLIENT",t[t.PRODUCER=3]="PRODUCER",t[t.CONSUMER=4]="CONSUMER"})(Ji||(Ji={}))});var Qi,V_=E(()=>{(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(Qi||(Qi={}))});function Y_(t){return sO.test(t)}function q_(t){return oO.test(t)&&!iO.test(t)}var Yl,rO,nO,sO,oO,iO,J_=E(()=>{Yl="[_0-9a-z-*/]",rO=`[a-z]${Yl}{0,255}`,nO=`[a-z0-9]${Yl}{0,240}@[a-z]${Yl}{0,13}`,sO=new RegExp(`^(?:${rO}|${nO})$`),oO=/^[ -~]{0,255}[!-~]$/,iO=/,|=/});var Q_,aO,Z_,eE,Zi,tE=E(()=>{J_();Q_=32,aO=512,Z_=",",eE="=",Zi=class t{constructor(e){this._internalState=new Map,e&&this._parse(e)}set(e,r){let n=this._clone();return n._internalState.has(e)&&n._internalState.delete(e),n._internalState.set(e,r),n}unset(e){let r=this._clone();return r._internalState.delete(e),r}get(e){return this._internalState.get(e)}serialize(){return Array.from(this._internalState.keys()).reduceRight((e,r)=>(e.push(r+eE+this.get(r)),e),[]).join(Z_)}_parse(e){e.length>aO||(this._internalState=e.split(Z_).reduceRight((r,n)=>{let s=n.trim(),o=s.indexOf(eE);if(o!==-1){let i=s.slice(0,o),a=s.slice(o+1,n.length);Y_(i)&&q_(a)&&r.set(i,a)}return r},new Map),this._internalState.size>Q_&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,Q_))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let e=new t;return e._internalState=new Map(this._internalState),e}}});function rE(t){return new Zi(t)}var nE=E(()=>{tE()});var ql,sE=E(()=>{gs();ql=it.getInstance()});var Jl,oE=E(()=>{fr();Jl=ee.instance()});var Ql,iE,aE=E(()=>{Ll();Ql=class{getMeter(e,r,n){return Fl}},iE=new Ql});var Zl,ea,cE=E(()=>{aE();dr();fr();Zl="metrics",ea=class t{constructor(){}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalMeterProvider(e){return st(Zl,e,ee.instance())}getMeterProvider(){return ye(Zl)||iE}getMeter(e,r,n){return this.getMeterProvider().getMeter(e,r,n)}disable(){ot(Zl,ee.instance())}}});var ed,uE=E(()=>{cE();ed=ea.getInstance()});var ta,lE=E(()=>{ta=class{inject(e,r){}extract(e,r){return e}fields(){return[]}}});function rd(t){return t.getValue(td)||void 0}function dE(){return rd(it.getInstance().active())}function fE(t,e){return t.setValue(td,e)}function pE(t){return t.deleteValue(td)}var td,gE=E(()=>{gs();fs();td=Yr("OpenTelemetry Baggage Key")});var nd,cO,ra,mE=E(()=>{dr();lE();Ul();gE();Il();fr();nd="propagation",cO=new ta,ra=class t{constructor(){this.createBaggage=C_,this.getBaggage=rd,this.getActiveBaggage=dE,this.setBaggage=fE,this.deleteBaggage=pE}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalPropagator(e){return st(nd,e,ee.instance())}inject(e,r,n=Bi){return this._getGlobalPropagator().inject(e,r,n)}extract(e,r,n=$i){return this._getGlobalPropagator().extract(e,r,n)}fields(){return this._getGlobalPropagator().fields()}disable(){ot(nd,ee.instance())}_getGlobalPropagator(){return ye(nd)||cO}}});var sd,hE=E(()=>{mE();sd=ra.getInstance()});var od,na,_E=E(()=>{dr();Vl();Vi();jl();fr();od="trace",na=class t{constructor(){this._proxyTracerProvider=new pr,this.wrapSpanContext=X_,this.isSpanContextValid=Qr,this.deleteSpan=W_,this.getSpan=Ki,this.getActiveSpan=B_,this.getSpanContext=Gi,this.setSpan=_s,this.setSpanContext=j_}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalTracerProvider(e){let r=st(od,this._proxyTracerProvider,ee.instance());return r&&this._proxyTracerProvider.setDelegate(e),r}getTracerProvider(){return ye(od)||this._proxyTracerProvider}getTracer(e,r){return this.getTracerProvider().getTracer(e,r)}disable(){ot(od,ee.instance()),this._proxyTracerProvider=new pr}}});var id,EE=E(()=>{_E();id=na.getInstance()});var SE={};As(SE,{DiagConsoleLogger:()=>Li,DiagLogLevel:()=>ne,INVALID_SPANID:()=>ms,INVALID_SPAN_CONTEXT:()=>ji,INVALID_TRACEID:()=>hs,ProxyTracer:()=>en,ProxyTracerProvider:()=>pr,ROOT_CONTEXT:()=>Fi,SamplingDecision:()=>qi,SpanKind:()=>Ji,SpanStatusCode:()=>Qi,TraceFlags:()=>Jr,ValueType:()=>Ui,baggageEntryMetadataFromString:()=>D_,context:()=>ql,createContextKey:()=>Yr,createNoopMeter:()=>L_,createTraceState:()=>rE,default:()=>uO,defaultTextMapGetter:()=>$i,defaultTextMapSetter:()=>Bi,diag:()=>Jl,isSpanContextValid:()=>Qr,isValidSpanId:()=>Xl,isValidTraceId:()=>Hl,metrics:()=>ed,propagation:()=>sd,trace:()=>id});var uO,yE=E(()=>{Il();fs();F_();Ci();Ll();U_();Ul();zl();Vl();G_();z_();V_();Bl();nE();Vi();Hi();sE();oE();uE();hE();EE();uO={context:ql,diag:Jl,metrics:ed,propagation:sd,trace:id}});function WE(t){if(!t.startsWith("mcp__"))return null;let e=t.split("__");if(e.length<3)return null;let r=e[1].toLowerCase();return!r.includes("memindex")&&!r.includes("agent-mem")&&!r.includes("agent_mem")&&!r.includes("mcp-search")&&!r.includes("mcp_search")?null:e.slice(2).join("__")}function rn(t){if(!t)return!1;if(t.startsWith("memory_")||t==="mem_search"||t==="get_summaries")return!0;let e=WE(t);return e!==null&&tP.has(e)}function ma(t){return t==="save_memory"||WE(t)==="save_memory"}var tP,ha=E(()=>{"use strict";tP=new Set(["mem_search","search","timeline","get_observations","get_summaries","get_tool_uses","session_start_context","observation_search","observation_context","memory_search","memory_context"])});function hd(t){return typeof t=="string"&&t.length>0}var Is,nS=E(()=>{"use strict";Is=class extends Error{constructor(r){super(`adapter rejected input: ${r}`);this.reason=r;this.name="AdapterRejectedInput"}reason}});var yP,sS,_d,bP,wP,oS,iS=E(()=>{"use strict";nS();qt();yP=128,sS=t=>typeof t=="string"&&t.length>0&&t.length<=yP?t:void 0,_d=t=>typeof t=="string"?t:void 0,bP=t=>t.hook_event_name==="PostToolUseFailure"?{error:t.error,is_interrupt:t.is_interrupt===!0}:void 0,wP=t=>{if(typeof t!="object"||t===null)return;let e=t;if(!Object.prototype.hasOwnProperty.call(e,"submitted_prompt"))return;let r=e.submitted_prompt;return typeof r!="string"?null:r.trim()?r:null},oS={normalizeInput(t){let e=t??{},r=e.cwd??process.cwd();if(!hd(r))throw new Is("invalid_cwd");let n=fp(r);if(!hd(n))throw new Is("invalid_cwd");let s=e.source;return{sessionId:e.session_id??e.id??e.sessionId,hookEventName:_d(e.hook_event_name),cwd:n,sessionSource:s==="startup"||s==="resume"||s==="clear"||s==="compact"?s:void 0,prompt:e.prompt,submittedPrompt:wP(e),toolName:e.tool_name,toolInput:e.tool_input,toolResponse:e.tool_response??bP(e),toolUseId:typeof e.tool_use_id=="string"?e.tool_use_id:void 0,transcriptPath:e.transcript_path,lastAssistantMessage:_d(e.last_assistant_message),reason:_d(e.reason),agentId:sS(e.agent_id),agentType:sS(e.agent_type)}},formatOutput(t){let e=t??{};if(e.hookSpecificOutput){let n={hookSpecificOutput:t.hookSpecificOutput};return e.systemMessage&&(n.systemMessage=e.systemMessage),n}let r={};return e.systemMessage&&(r.systemMessage=e.systemMessage),r}}});function aS(t,e){return We("observation",{contentSessionId:t.sessionId,platformSource:e,toolName:t.toolName,toolInput:t.toolInput,toolResponse:t.toolResponse,cwd:t.cwd,agentId:t.agentId,agentType:t.agentType,toolUseId:t.toolUseId},t.spoolAtEpochMs),{continue:!0,suppressOutput:!0}}var cS,uS=E(()=>{"use strict";Nr();O();ou();xe();Pr();zo();ft();Mn();ht();Mr();tr();On();ha();cS={async execute(t){let{sessionId:e,cwd:r,toolName:n,toolInput:s,toolResponse:o}=t,i=z(t.platform);if(!n)return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};if(rn(n))return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};let a=Jg(f.formatTool(n,s));if(f.dataIn("HOOK",`PostToolUse: ${a}`,{}),!r)throw new Error(`Missing cwd in PostToolUse hook input for session ${e}, tool ${n}`);if(!Qe(r))return f.debug("HOOK","Project excluded from tracking, skipping observation",{cwd:r,toolName:n}),{continue:!0,suppressOutput:!0};let c=Dr(t.agentId,t.agentType,G());if(c.skip)return f.debug("HOOK",`Skipping observation: ${c.reason}`,{toolName:n,agentId:t.agentId,agentType:t.agentType}),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};if(ma(n))return aS(t,i);let u=Le();if(u.runtime==="server"){if(kt(n,G().MEMINDEX_SKIP_TOOLS))return f.debug("HOOK","Server runtime: tool excluded by MEMINDEX_SKIP_TOOLS",{toolName:n}),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};let l={projectId:u.projectId,contentSessionId:e,platformSource:i,sourceType:"hook",eventType:"tool_use",occurredAtEpoch:Date.now(),payload:{tool_name:n,tool_input:s,tool_response:o,cwd:r,agentId:t.agentId,agentType:t.agentType,platformSource:i,tool_use_id:t.toolUseId}};try{return await u.client.recordEvent(l),f.debug("HOOK","Observation sent successfully via server",{toolName:n}),await xr(u.client,$e(u)),{continue:!0,suppressOutput:!0}}catch(d){if(Et(d))return Ue(d.kind,{status:d.status,message:d.message,route:"/v1/events",held:!0}),xt({op:"event",request:l},$e(u)),{continue:!0,suppressOutput:!0};if(Fe(d)&&d.isFallbackEligible())Ue(d.kind,{status:d.status,message:d.message,route:"/v1/events"});else return f.error("HOOK","Server event failed (non-recoverable)",{error:d instanceof Error?d.message:String(d)}),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS}}}return aS(t,i)}}});function vP(t,e,r){let n=0;for(;n<e.length;){let s=(0,Xe.readSync)(t,e,n,e.length-n,r+n);if(s===0)break;n+=s}return n}function*RP(t,e){let r=Math.max(1,e.maxChunkBytes??lS),n=Math.min(r,Math.max(1,e.initialBytes??TP)),s=(0,Xe.openSync)(t,"r");try{let o=(0,Xe.fstatSync)(s).size,i=Buffer.alloc(0);for(;o>0;){let a=Math.max(0,o-n),c=Buffer.alloc(o-a),u=vP(s,c,a),l=u===c.length?c:c.subarray(0,u),d=i.length?Buffer.concat([l,i]):l;if(a===0){yield{text:d.toString("utf-8"),byteLength:l.length,isFirstChunkOfFile:!0};return}let p=d.indexOf(10);p===-1?(i=d,yield{text:"",byteLength:l.length,isFirstChunkOfFile:!1}):(i=d.subarray(0,p),yield{text:d.subarray(p+1).toString("utf-8"),byteLength:l.length,isFirstChunkOfFile:!1}),o=a,n=Math.min(n*4,r)}i.length&&(yield{text:i.toString("utf-8"),byteLength:0,isFirstChunkOfFile:!0})}finally{(0,Xe.closeSync)(s)}}function dS(t,e,r={}){if(!t||!(0,Xe.existsSync)(t)){f.warn("PARSER",`Transcript path missing or file does not exist: ${t}`);return}let n=!1;for(let s of RP(t,r)){!n&&s.text.trim()&&(n=!0);let o=e(s.text,s.isFirstChunkOfFile,s.byteLength);if(o!==void 0)return o}n||f.warn("PARSER",`Transcript file exists but is empty: ${t}`)}function*Ed(t){let e=t.split(`
|