memindex 1.7.0 → 1.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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/hook-runner.cjs +1 -1
- package/plugin/scripts/mcp-server.cjs +133 -104
- package/plugin/scripts/mcp-server.cjs.map +2 -2
- package/plugin/scripts/transcript-watcher.cjs +2 -2
- package/plugin/scripts/transcript-watcher.cjs.map +1 -1
- package/plugin/scripts/worker-service.cjs +542 -523
- package/plugin/scripts/worker-service.cjs.map +3 -3
- package/plugin/sqlite/SessionStore.js +62 -47
- package/plugin/sqlite/SessionStore.js.map +3 -3
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "memindex",
|
|
3
|
-
"version": "1.7.
|
|
3
|
+
"version": "1.7.1",
|
|
4
4
|
"description": "Memory for AI coding agents: what you decided, fixed and tried comes back in your next session. Works with Claude Code, Codex, Cursor, OpenCode, Windsurf and more.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Imogen Labs"
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "memindex",
|
|
3
|
-
"version": "1.7.
|
|
3
|
+
"version": "1.7.1",
|
|
4
4
|
"description": "Memory for AI coding agents: what you decided, fixed and tried comes back in your next session. Works with Claude Code, Codex, Cursor, OpenCode, Windsurf and more.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Imogen Labs",
|
package/dist/npx-cli/index.js
CHANGED
|
@@ -14,7 +14,7 @@ ${g.stack??""}
|
|
|
14
14
|
`),...l!==void 0?{id:l}:{}}:null;return c=null,l=void 0,u=null,a=0,I}if(g[0]===_N)return t.onActivity?.(),null;m(g.length),a+=g.length;let y=n.decode(g),E=y.indexOf(":"),S=E===-1?y:y.slice(0,E),b=E===-1?"":y.slice(E+1);return b.startsWith(" ")&&(b=b.slice(1)),S==="event"?c=b:S==="data"?(u??=[]).push(b):S==="id"&&(l=b),null};for await(let g of AN(e)){let y=0;for(let E=0;E<g.length;E++){let S=g[E];if(i&&(i=!1,S===pE)){y=E+1;continue}if(S!==dE&&S!==pE)continue;o.push(g.subarray(y,E));let b=PN(o,s+(E-y));o=[],s=0;let w=f(b);w&&(t.terminalEventNames?.includes(w.event)&&(d=!0),yield w),i=S===dE,y=E+1}if(y<g.length){let E=g.slice(y);o.push(E),s+=E.length,m(s)}}if(t.terminalEventNames&&t.terminalEventNames.length>0&&!d)throw new _d(t.terminalEventNames)}var Rd,_d,dE,pE,_N,fE=h(()=>{"use strict";Rd=class extends Error{constructor(r){super(`SSE event exceeded ${r} bytes`);this.maxEventBytes=r;this.name="SseEventTooLargeError"}maxEventBytes},_d=class extends Error{constructor(r){super(`SSE stream ended before a terminal event (${r.join(", ")})`);this.terminalEventNames=r;this.name="StreamEndedEarlyError"}terminalEventNames},dE=13,pE=10,_N=58});function he(){return Oa!==null||(Oa=j.loadFromFile(U)),Oa}var Oa,dr=h(()=>{"use strict";ge();L();Oa=null});function sn(e){return(e.MEMINDEX_WORKER_AUTOSTART??"true").trim().toLowerCase()==="false"}var Ra=h(()=>{"use strict"});function Ad(e,t){let r=(process.env.MEMINDEX_PUBLIC_URL??t??"").trim();return r?r.replace(/\/+$/,""):`http://localhost:${e}`}var Pd=h(()=>{"use strict"});function pr(e){return e.startsWith("[")&&e.endsWith("]")?e:e.includes(":")?`[${e}]`:e}var Nd=h(()=>{"use strict"});import{spawn as NN,spawnSync as gE}from"node:child_process";import{existsSync as DN}from"node:fs";import{dirname as LN,extname as _a,join as UN}from"node:path";function At(e,t,r){return NN(e,t??[],{...r,windowsHide:!0})}function FN(e){return`"${e.replace(/"/g,'""')}"`}function Hs(e){return hE.has(_a(e).toLowerCase())}function Ld(e){if(process.platform!=="win32")return[];try{let t=gE("where",[e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0});return t.status!==0||!t.stdout.trim()?[]:t.stdout.split(/\r?\n/).map(r=>r.trim()).filter(Boolean).filter(r=>DN(r))}catch{return[]}}function BN(e,t){let r=e.find(Hs);if(r)return r;let n=e.find(o=>Dd.has(_a(o).toLowerCase()));if(n&&t){let o=t(n);if(o&&Hs(o))return o}return n??e.find(o=>jN.has(_a(o).toLowerCase()))??e[0]??null}function KN(e,t,r=WN){if(!/[\\/]volta[\\/]bin[\\/]/i.test(t))return null;try{let n=r(UN(LN(t),"volta.exe"),["which",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:HN,windowsHide:!0});return n.status!==0||!n.stdout.trim()?null:n.stdout.split(/\r?\n/).map(o=>o.trim()).find(Boolean)??null}catch{return null}}function Pt(e){return BN(Ld(e),t=>KN(e,t))}function Nt(e,t,r,n=process.platform){let o={...r,...n==="win32"?{windowsHide:!0}:{}};if(n==="win32"&&Dd.has(_a(e).toLowerCase())){let s=[e,...t].map(FN).join(" ");return{command:process.env.ComSpec??"cmd.exe",args:["/d","/s","/c",`"${s}"`],options:{...o,windowsVerbatimArguments:!0}}}return{command:e,args:[...t],options:o}}var Dd,hE,jN,HN,WN,wt=h(()=>{"use strict";Dd=new Set([".cmd",".bat"]),hE=new Set([".exe",".com"]),jN=new Set([...hE,...Dd]);HN=5e3,WN=(e,t,r)=>gE(e,t,r)});function de(e=process.env){let t={};for(let[r,n]of Object.entries(e))if(n!==void 0){if(JN.has(r)){t[r]=n;continue}$N.has(r)||XN.some(o=>r.startsWith(o))||(t[r]=n)}return t}var XN,$N,GN,JN,an=h(()=>{"use strict";XN=["CLAUDECODE_","CLAUDE_CODE_"],$N=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),GN=new Set(["NODE_USE_ENV_PROXY","HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy","npm_config_noproxy"]),JN=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_TMPDIR","CLAUDE_CODE_PATH","CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS",...GN])});import{spawnSync as Fd}from"child_process";import{readFileSync as YN}from"fs";function Aa(e){return`${Ud}${e}`}function Hd(e,t,r){if(r.status!==0)return null;if(typeof r.stdout!="string")return p.warn("SYSTEM","captureProcessStartToken: start-token probe returned no stdout",{pid:t,source:e,status:r.status}),null;let n=r.stdout.trim();return n.length>0?n:null}function qN(e){jd+=1;let t=Fd("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${e}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...de(process.env),LC_ALL:"C",LANG:"C",TZ:"UTC"}});return Hd("powershell-cim",e,t)}function zN(e,t=!1){if(!t){let n=yE.get(e);if(n&&(e===process.pid||Date.now()-n.capturedAtMs<VN))return n.token}let r=null;try{r=qN(e)}catch(n){p.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:e,error:n instanceof Error?n.message:String(n)}),r=null}return(r!==null||e!==process.pid)&&yE.set(e,{token:r,capturedAtMs:Date.now()}),r}function EE(e,t){if(!Number.isInteger(e)||e<=0)return null;if(process.platform==="linux"){jd+=1;try{let r=YN(`/proc/${e}/stat`,"utf-8"),n=r.lastIndexOf(") ");if(n<0)return null;let s=r.slice(n+2).split(" ")[19];return s&&/^\d+$/.test(s)?s:null}catch(r){return p.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:e,error:r instanceof Error?r.message:String(r)}),null}}if(process.platform==="win32")return zN(e,t);jd+=1;try{let r=Fd("ps",["-p",String(e),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...de(process.env),LC_ALL:"C",LANG:"C",TZ:"UTC"}}),n=Hd("ps-lstart",e,r);return n===null?null:Aa(n)}catch(r){return p.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:e,error:r instanceof Error?r.message:String(r)}),null}}function _r(e){return EE(e,!1)}function SE(e,t){let r=EE(e,!0);if(r===null||!r.startsWith(Ud)||t.startsWith(Ud))return r;try{let n=Fd("ps",["-p",String(e),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...de(process.env),LC_ALL:"C",LANG:"C"}});return Hd("ps-lstart",e,n)}catch{return null}}function Dt(e,t){if(t===null)return!0;let r=SE(e,t);return r===null?!0:r===t}function wE(e,t){return SE(e,t)===t}var Ud,VN,yE,jd,Pa=h(()=>{"use strict";P();an();Ud="utc:";VN=5e3,yE=new Map,jd=0});import{execFile as ZN}from"child_process";import{readdirSync as QN,readFileSync as e0}from"fs";import{promisify as t0}from"util";async function bt(e,t={}){let r=t.signalMode==="immediate",n=t.expectedStartToken!==void 0?t.expectedStartToken:_r(e),o=()=>Dt(e,n);if(!o()){p.warn("PROCESS","Skipping tree-kill: root PID was reused since it was captured",{pid:e});return}if(p.debug("PROCESS",`Killing process tree rooted at PID ${e}`,{immediate:r}),process.platform==="win32"){try{await Wd("taskkill",["/PID",String(e),"/T","/F"],{timeout:5e3,windowsHide:!0})}catch(s){let i=s.code,a=String(s.stderr??""),c=s instanceof Error?s.message:String(s);if(i===r0||n0.test(`${a} ${c}`)){p.debug("PROCESS","taskkill reported the process was already gone",{pid:e});return}throw new Na(e,`taskkill failed for PID ${e} (exit ${String(i)}): ${a.trim()||c}`,{cause:s})}return}try{let s=r?"SIGKILL":"SIGTERM",i=await Da(e);for(let l of i){if(!Dt(l.pid,l.startToken)){p.debug("PROCESS",`Skipping ${s}: descendant PID was reused since enumeration`,{pid:l.pid,rootPid:e});continue}try{process.kill(l.pid,s)}catch{}}if(o())try{process.kill(e,s)}catch(l){let u=l instanceof Error?l:new Error(String(l)),d=u.code;d!=="ESRCH"&&p.debug("PROCESS",`Failed to ${s} PID ${e}`,{code:d},u)}else p.warn("PROCESS","Skipping root signal: PID was reused during descendant enumeration",{pid:e,signal:s});r||await new Promise(l=>setTimeout(l,500));let a=o()?await Da(e):[],c=new Map;for(let l of i)c.set(l.pid,l.startToken);for(let l of a)c.set(l.pid,l.startToken);for(let[l,u]of c){if(!Dt(l,u)){p.debug("PROCESS","Skipping SIGKILL: descendant PID was reused since the scan",{pid:l,rootPid:e});continue}try{process.kill(l,"SIGKILL")}catch{}}if(!r&&o())try{process.kill(e,"SIGKILL")}catch{}}catch(s){throw new Na(e,`tree-kill failed for PID ${e}: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}async function o0(){return process.platform==="win32"?a0():process.platform==="linux"?s0():i0()}function s0(){let e=[],t;try{t=QN("/proc")}catch(r){return p.warn("PROCESS","Cannot read /proc \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),e}for(let r of t){if(!/^\d+$/.test(r))continue;let n;try{n=e0(`/proc/${r}/stat`,"utf-8")}catch{continue}let o=n.lastIndexOf(") ");if(o<0)continue;let s=n.slice(o+2).split(" "),i=Number.parseInt(s[1]??"",10),a=s[19];Number.isFinite(i)&&e.push({pid:Number.parseInt(r,10),ppid:i,startToken:a&&/^\d+$/.test(a)?a:null})}return e}async function i0(){let e;try{e=(await Wd("ps",["-eo","pid=,ppid=,lstart="],{timeout:1e4,maxBuffer:33554432,env:{...process.env,LC_ALL:"C",LANG:"C",TZ:"UTC"}})).stdout}catch(r){return p.warn("PROCESS","Cannot enumerate the process table \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),[]}let t=[];for(let r of e.split(`
|
|
15
15
|
`)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);if(!n)continue;let o=n[3].trim();t.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:o.length>0?Aa(o):null})}return t}async function a0(){let e;try{e=(await Wd("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 p.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 t=[];for(let r of e.split(/\r?\n/).slice(1)){let n=r.match(/^"(\d+)","(\d+)","(.*)"$/);if(!n)continue;let o=n[3].trim();t.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:o.length>0?o:null})}return t}async function Da(e){let t=await o0(),r=new Map;for(let i of t){let a=r.get(i.ppid);a?a.push(i):r.set(i.ppid,[i])}let n=new Set([e]),o=[],s=i=>{for(let a of r.get(i)??[])n.has(a.pid)||(n.add(a.pid),s(a.pid),o.push({pid:a.pid,startToken:a.startToken}))};return s(e),o}var Wd,r0,n0,Na,No=h(()=>{"use strict";P();Pa();Wd=t0(ZN),r0=128,n0=/not found|no running instance|no tasks/i,Na=class extends Error{pid;constructor(t,r,n){super(r,n),this.name="ProcessTreeKillError",this.pid=t}}});import{existsSync as bE,readFileSync as $d}from"fs";import l0 from"path";function oe(e){if(!Number.isInteger(e)||e<0||e===0)return!1;try{return process.kill(e,0),!0}catch(t){if(t instanceof Error){let r=t.code;return r==="EPERM"?!0:(p.debug("SYSTEM","PID check failed",{pid:e,code:r}),!1)}return p.warn("SYSTEM","PID check threw non-Error",{pid:e,error:String(t)}),!1}}async function La(e,t){let r=Date.now()+t;for(;Date.now()<r;){if(e.every(n=>!oe(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function kE(e){if(!e||!oe(e.pid))return!1;if(!e.startToken)return!0;let t=Dt(e.pid,e.startToken);return t||p.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:e.pid,stored:e.startToken}),t}function Do(e,t=f0){if(!kE(e))return!1;if(e.startToken||t.platform!=="linux")return!0;let r;try{r=t.readCommandLine(e.pid)}catch(o){return p.debug("SYSTEM","Could not read the command line of a token-less worker PID; trusting the live PID",{pid:e.pid,error:o instanceof Error?o.message:String(o)}),!0}let n=r.split("\0").some(o=>l0.basename(o)==="worker-service.cjs");return n||p.debug("SYSTEM","Token-less worker PID now belongs to another program (PID reused)",{pid:e.pid}),n}function ze(e=G.workerPid()){if(!bE(e))return null;let t;try{t=JSON.parse($d(e,"utf-8"))}catch{return null}return t!==null&&Do(t)?t:null}async function Ua(e){if(!e.startToken||!wE(e.pid,e.startToken))return!1;try{return process.platform==="win32"?await bt(e.pid,{expectedStartToken:e.startToken}):process.kill(e.pid,"SIGTERM"),!0}catch{return!1}}function ja(){return Bd||(Bd=new Xd),Bd}function Kd(){let e=g0.shift();e&&e.notify()}var u0,d0,p0,m0,f0,Xd,Bd,Nz,g0,ot=h(()=>{"use strict";wt();P();J();an();L();Pa();No();u0=5e3,d0=1e3,p0=G.supervisorRegistry(),m0=null;f0={platform:process.platform,readCommandLine:e=>$d(`/proc/${e}/cmdline`,"utf-8")};Xd=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(t=p0){this.registryPath=t}initialize(){if(this.initialized)return;if(this.initialized=!0,!bE(this.registryPath)){this.persist();return}try{let n=JSON.parse($d(this.registryPath,"utf-8")).processes??{};for(let[o,s]of Object.entries(n))this.entries.set(o,s)}catch(r){r instanceof Error?p.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):p.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let t=this.pruneDeadEntries();t>0&&p.info("SYSTEM","Removed dead processes from supervisor registry",{removed:t}),this.persist()}retainSupersededEntry(t,r){let n=this.entries.get(t);if(!n||n.pid===r||!oe(n.pid))return;let o=`${t}#superseded:${n.pid}`;this.entries.set(o,n);let s=this.runtimeProcesses.get(t);s&&(this.runtimeProcesses.set(o,s),this.runtimeProcesses.delete(t)),p.warn("SYSTEM","Registry id reused while the previous process was still alive; kept it for reaping",{id:t,supersededId:o,supersededPid:n.pid,incomingPid:r})}register(t,r,n){this.initialize(),this.retainSupersededEntry(t,r.pid),this.entries.set(t,r),n&&this.runtimeProcesses.set(t,n),this.persist()}unregister(t,r){this.initialize();let n=t,o=this.entries.get(n);r!==void 0&&o?.pid!==r&&(n=`${t}#superseded:${r}`,o=this.entries.get(n),o?.pid!==r)||o&&(this.entries.delete(n),this.runtimeProcesses.delete(n),this.persist(),o?.type==="sdk"&&Kd())}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([t,r])=>({id:t,...r})).sort((t,r)=>{let n=Date.parse(t.startedAt),o=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(o)?0:o)})}getBySession(t){let r=String(t);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===r)}getRuntimeProcess(t){return this.runtimeProcesses.get(t)}pruneDeadEntries(){this.initialize();let t=0,r=0;for(let[n,o]of this.entries)oe(o.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),t+=1,o.type==="sdk"&&(r+=1));t>0&&this.persist();for(let n=0;n<r;n+=1)Kd();return t}async reapSession(t){this.initialize();let r=this.getBySession(t);if(r.length===0)return 0;let n=typeof t=="number"?t:Number(t)||void 0;p.info("SYSTEM",`Reaping ${r.length} process(es) for session ${t}`,{sessionId:n,pids:r.map(a=>a.pid)});let o=r.filter(a=>oe(a.pid)),s=new Map(o.map(a=>[a.pid,_r(a.pid)]));for(let a of o)try{process.platform==="win32"?await bt(a.pid,{expectedStartToken:s.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"&&p.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):p.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}await La(o,u0);let i=o.filter(a=>oe(a.pid));for(let a of i){p.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});let c=s.get(a.pid)??null;if(!Dt(a.pid,c)){p.warn("SYSTEM","Skipping SIGKILL: session process PID was reused during the grace window",{pid:a.pid,sessionId:n});continue}try{process.platform==="win32"?await bt(a.pid,{expectedStartToken:c}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(l){l instanceof Error?l.code!=="ESRCH"&&p.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},l):p.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(l)})}}if(i.length>0){let a=Date.now()+d0;for(;Date.now()<a&&i.filter(l=>oe(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,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"&&Kd();return p.info("SYSTEM",`Reaped ${r.length} process(es) for session ${t}`,{sessionId:n,reaped:r.length}),r.length}persist(){let t={processes:Object.fromEntries(this.entries.entries())};try{N(this.registryPath,t),this.persistDegraded=!1}catch(r){this.reportPersistFailure(r)}}reportPersistFailure(t){if(this.persistDegraded)return;this.persistDegraded=!0;let r=t instanceof Error?t:new Error(String(t));p.warn("SYSTEM","Failed to persist supervisor registry; keeping it in memory",{path:this.registryPath},r);try{m0?.({errorCategory:r.code??"unknown"})}catch{}}},Bd=null;Nz=180*1e3,g0=[]});import{existsSync as h0,readFileSync as y0,rmSync as E0}from"fs";async function xE(e){let t=e.currentPid??process.pid,r=e.pidFilePath??S0,n=e.registry.getAll(),o=[...n].filter(c=>c.pid!==t).sort((c,l)=>Date.parse(l.startedAt)-Date.parse(c.startedAt)),s=new Map,i=new Map;for(let c of o){if(!oe(c.pid)){e.registry.unregister(c.id);continue}i.set(c.id,_r(c.pid)),s.set(c.id,await Da(c.pid));try{await vE(c,"SIGTERM")}catch(l){l instanceof Error?p.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:c.pid,pgid:c.pgid,type:c.type},l):p.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(l)})}}await La(o,5e3);let a=o.filter(c=>oe(c.pid)||(s.get(c.id)??[]).some(l=>oe(l.pid)));for(let c of a){let l=Dt(c.pid,i.get(c.id)??null);l||p.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:c.pid,type:c.type});try{l&&await vE(c,"SIGKILL")}catch(u){u instanceof Error?p.debug("SYSTEM","Failed to force kill child process",{pid:c.pid,pgid:c.pgid,type:c.type},u):p.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(u)})}finally{w0(s.get(c.id)??[],c.pid)}}await La(a,1e3);for(let c of o)e.registry.unregister(c.id);for(let c of n.filter(l=>l.pid===t))e.registry.unregister(c.id);Gd(r,t),e.registry.pruneDeadEntries()}function Gd(e,t,r=!1){if(!h0(e))return;let n=null;try{let i=JSON.parse(y0(e,"utf-8"));n=typeof i.pid=="number"?i.pid:null}catch(i){p.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:e,error:i instanceof Error?i.message:String(i)});return}let o=t!==null&&n===t,s=n===null||!oe(n);if(!o&&!(r&&s)){p.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:e,recordedPid:n,currentPid:t});return}try{E0(e,{force:!0})}catch(i){i instanceof Error?p.debug("SYSTEM","Failed to remove PID file",{pidFilePath:e},i):p.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:e,error:String(i)})}}function w0(e,t){for(let{pid:r,startToken:n}of e)if(!(r===t||!oe(r))){if(!Dt(r,n)){p.debug("SYSTEM","Skipping reap: PID was recycled during the grace window",{pid:r,rootPid:t});continue}try{process.kill(r,"SIGKILL"),p.debug("SYSTEM","Reaped orphaned descendant during shutdown cascade",{pid:r,rootPid:t})}catch(o){let s=o instanceof Error?o.code:void 0;s!=="ESRCH"&&p.warn("SYSTEM","Failed to reap orphaned descendant during shutdown cascade",{pid:r,rootPid:t,errno:s})}}}async function vE(e,t){let{pid:r,pgid:n}=e;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,t);return}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}if(t==="SIGKILL"){await bt(r,{signalMode:"immediate"});return}try{process.kill(r,t)}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}return}await bt(r)}var S0,Jd=h(()=>{"use strict";P();ot();L();No();S0=G.workerPid()});function b0(){let t=ja().pruneDeadEntries();t>0&&p.info("SYSTEM",`Health check: pruned ${t} dead process(es) from registry`)}function TE(){Lo===null&&(Lo=setInterval(b0,IE),Lo.unref(),p.debug("SYSTEM","Health checker started",{intervalMs:IE}))}function ME(){Lo!==null&&(clearInterval(Lo),Lo=null,p.debug("SYSTEM","Health checker stopped"))}var IE,Lo,CE=h(()=>{"use strict";P();ot();IE=3e4,Lo=null});import{execFile as k0}from"child_process";import{promisify as v0}from"util";function T0(e){let t=[];for(let r of e.split(`
|
|
16
16
|
`)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);n&&t.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),command:n[3].trim()})}return t}async function Yd(){let e=await x0("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return T0(e.stdout)}function Vd(e,t){let r=e.filter(i=>I0.test(i.command)&&i.pid!==t.selfPid),n=new Set(r.map(i=>i.pid)),o=r.filter(i=>!n.has(i.ppid)),s=o.filter(i=>i.ppid===t.selfPid?!1:i.ppid===1?!0:!t.isAlive(i.ppid));return{matched:r,roots:o,orphans:s}}async function OE(e={}){let t=e.platform??process.platform,r={matched:0,trees:0,orphans:0,killed:0,failed:0,unregistered:0,skipped:null};if(t==="win32")return r.skipped="windows",r;let n=e.readTable??Yd,o=e.isAlive??oe,s=e.killTree??(f=>bt(f,{signalMode:"graceful"})),i=e.selfPid??process.pid,a;try{a=await n()}catch(f){return p.warn("PROCESS","Orphaned chroma-mcp sweep skipped: cannot read the process table",{error:f instanceof Error?f.message:String(f)}),r.skipped="unreadable",r}let{matched:c,roots:l,orphans:u}=Vd(a,{isAlive:o,selfPid:i});if(r.matched=c.length,r.trees=l.length,r.orphans=u.length,u.length===0)return p.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:r.matched,trees:r.trees}),r;p.warn("PROCESS","Reaping orphaned chroma-mcp trees left by dead workers",{orphans:u.length,roots:u.map(f=>f.pid)});let d=new Set,m=8;for(let f=0;f<u.length;f+=m){let g=u.slice(f,f+m);(await Promise.allSettled(g.map(E=>s(E.pid)))).forEach((E,S)=>{let b=g[S];E.status==="fulfilled"?(r.killed+=1,d.add(b.pid)):(r.failed+=1,p.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:b.pid,ppid:b.ppid,error:E.reason instanceof Error?E.reason.message:String(E.reason)}))})}if(e.registry)for(let f of e.registry.getAll())f.type==="chroma"&&d.has(f.pid)&&(e.registry.unregister(f.id),r.unregistered+=1);return p.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:r.orphans,killed:r.killed,failed:r.failed,unregistered:r.unregistered}),r}var x0,I0,qd=h(()=>{"use strict";P();No();ot();x0=v0(k0),I0=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/});import{existsSync as M0,readFileSync as C0,rmSync as RE}from"fs";function Zd(){return R0}function Qd(e={}){let t=e.pidFilePath??O0;if(!M0(t))return"missing";let r=null;try{r=JSON.parse(C0(t,"utf-8"))}catch(o){return o instanceof Error?p.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:t},o):p.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:t,error:String(o)}),RE(t,{force:!0}),"invalid"}return Do(r)&&r?((e.logAlive??!0)&&p.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(e.removeStale===!1||(p.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),RE(t,{force:!0})),"stale")}var O0,zd,R0,Ws=h(()=>{"use strict";P();ot();Jd();CE();qd();L();ot();O0=G.workerPid(),zd=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(t){this.registry=t}async start(){if(this.started)return;if(this.registry.initialize(),Qd({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,OE({registry:this.registry}).catch(r=>{p.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),TE()}configureSignalHandlers(t){if(this.shutdownHandler=t,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){p.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,p.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(o){o instanceof Error?p.error("SYSTEM","Error during shutdown",{},o):p.error("SYSTEM","Error during shutdown (non-Error)",{error:String(o)});try{await this.stop()}catch(s){s instanceof Error?p.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):p.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(s)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{p.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}ME(),this.stopPromise=xE({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(t){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${t}`)}registerProcess(t,r,n){this.registry.register(t,r,n)}unregisterProcess(t,r){this.registry.unregister(t,r)}getRegistry(){return this.registry}},R0=new zd(ja())});import{existsSync as _0,readFileSync as A0}from"fs";function ye(e,t){if(!_0(e))return t;try{return He(A0(e,"utf-8"))}catch(r){throw new Error(`Corrupt JSON file, refusing to overwrite: ${e}: ${r instanceof Error?r.message:String(r)}`)}}var Ar=h(()=>{"use strict";J()});import{join as _E}from"path";import{mkdirSync as P0,writeFileSync as N0}from"fs";import{randomUUID as D0}from"crypto";function L0(e){let t=e.DO_NOT_TRACK;return t===void 0||t===""?!1:t!=="0"&&t!=="false"}function ep(e,t){if(L0(e))return{enabled:!1,source:"DO_NOT_TRACK"};let r=e.MEMINDEX_TELEMETRY?.toLowerCase();return r==="0"||r==="false"||r==="off"?{enabled:!1,source:"env"}:e.MEMINDEX_TELEMETRY_KEY?r==="1"||r==="true"||r==="on"?{enabled:!0,source:"env"}:t?.enabled===!0?{enabled:!0,source:"config"}:t?.enabled===!1?{enabled:!1,source:"config"}:{enabled:!1,source:"default"}:{enabled:!1,source:"no-key"}}function PE(e,t){return ep(e,t).enabled}function Bs(){return _E(W(),AE)}function cn(){let e;try{e=ye(Bs(),null)}catch(t){let r=t instanceof Error?t:new Error(String(t));return p.warn("SYSTEM","Telemetry: corrupt telemetry.json; treating as no recorded consent",void 0,r),null}return!e||typeof e!="object"||typeof e.installId!="string"||e.enabled!==void 0&&typeof e.enabled!="boolean"?null:{enabled:e.enabled,installId:e.installId,decidedAt:typeof e.decidedAt=="string"?e.decidedAt:""}}function Uo(e){let t=W();P0(t,{recursive:!0}),N0(_E(t,AE),JSON.stringify(e,null,2)+`
|
|
17
|
-
`)}function Fa(){let e=cn();if(e?.installId)return e.installId;let t=D0();return Uo({installId:t,decidedAt:""}),t}var AE,Ha=h(()=>{"use strict";L();Ar();P();AE="telemetry.json"});import U0 from"os";function j0(e){try{if(typeof e!="string"){if(e==null)return"";try{e=String(e)}catch(r){let n=r instanceof Error?r:new Error(String(r));return p.warn("SYSTEM","error-scrub: String() coercion of non-string input failed",void 0,n),""}}let t=e;return t.length>NE?t.slice(0,NE):t}catch{return""}}function F0(e){if(typeof e!="string"||e.length===0)return e??"";let t="";try{t=U0.homedir()||""}catch(n){let o=n instanceof Error?n:new Error(String(n));p.warn("SYSTEM","error-scrub: os.homedir() failed; skipping home-dir redaction",void 0,o),t=""}if(!t)return e;let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");try{return e.replace(new RegExp(r,"g"),"~")}catch(n){let o=n instanceof Error?n:new Error(String(n));return p.warn("SYSTEM","error-scrub: home-dir RegExp replace failed; using split/join fallback",void 0,o),e.split(t).join("~")}}function H0(e){return typeof e!="string"||e.length===0?e??"":e.replace(/(?<![~\w])\/(?:[^\s/:"'()]+\/)+([^\s/:"'()]+)/g,"$1").replace(/[A-Za-z]:\\(?:[^\s\\:"'()]+\\)*([^\s\\:"'()]+)/g,"$1").replace(/\\\\[^\s\\:"'()]+(?:\\[^\s\\:"'()]+)*\\([^\s\\:"'()]+)/g,"$1")}function W0(e){return typeof e!="string"||e.length===0?e??"":e.replace(/\b[A-Za-z][A-Za-z0-9+.-]*:\/\/[^\s"'()]+/g,t=>/^https?:\/\/hooks\.slack\.com\/services\//i.test(t)?t.replace(/^(https?:\/\/hooks\.slack\.com\/services\/)[^\s"'()]+/i,`$1${Lt}`):t.replace(/[?#].*$/,"").replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/@\s]+@/,`$1${Lt}@`))}function B0(e){return typeof e!="string"||e.length===0?e??"":e.replace(/\?[^\s"'()]*/g,"")}function K0(e){return typeof e!="string"||e.length===0?e??"":e.replace(/\b(?:access[_-]?token|api[_-]?key|auth(?:orization)?|secret|password|passwd|jwt|session[_-]?id|token)=[^\s"'&]+/gi,t=>{let r=t.indexOf("=");return`${t.slice(0,r+1)}${Lt}`})}function X0(e){if(typeof e!="string"||e.length===0)return e??"";let t=e;return t=t.replace(/[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}/g,Lt),t=t.replace(/\b[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\b/g,Lt),t=t.replace(/\b(?:sk|pk|rk|ak|phc|phx|ph|ghp|gho|ghs|xox[bpasr])[-_][A-Za-z0-9_-]{8,512}\b/gi,Lt),t=t.replace(/\bBearer\s+[A-Za-z0-9._-]{8,512}\b/gi,Lt),t=t.replace(/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g,Lt),t=t.replace(/\b[0-9a-fA-F]{24,4096}\b/g,Lt),t=t.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,Lt),t=t.replace(/\b(?=[A-Za-z0-9+/_-]{0,4096}\d)[A-Za-z0-9+/_-]{32,4096}={0,2}\b/g,Lt),t=t.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,Lt),t}function DE(e){let t=j0(e);return t.length===0?"":(t=F0(t),t=W0(t),t=H0(t),t=B0(t),t=K0(t),t=X0(t),t)}var NE,Lt,LE=h(()=>{"use strict";P();NE=8192,Lt="[REDACTED]"});function G0(e,t){if(!(!e||typeof e!="object"))for(let r of Object.keys(e)){if(!$0.has(r))continue;let n=e[r];if(typeof n=="string"){let o=n.length>UE?n.slice(0,UE):n;t[r]=DE(o)}else(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(t[r]=n)}}function jE(e){let t={};try{G0(e,t)}catch{}return t}var $0,UE,FE=h(()=>{"use strict";LE();$0=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"]),UE=200});import HE from"os";function WE(){return process.env.MEMINDEX_TELEMETRY_KEY??""}function BE(){return process.env.MEMINDEX_TELEMETRY_HOST||Y0}function KE(e){let t={};for(let r of V0)e[r]!==void 0&&(t[r]=e[r]);return t}function q0(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||HE.release().toLowerCase().includes("microsoft")}catch(e){let t=e instanceof Error?e:new Error(String(e));return p.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,t),!1}}function XE(){return{version:J0,os:process.platform,os_version:HE.release(),is_wsl:q0(),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 J0,Y0,V0,$E=h(()=>{"use strict";P();J0="1.7.
|
|
17
|
+
`)}function Fa(){let e=cn();if(e?.installId)return e.installId;let t=D0();return Uo({installId:t,decidedAt:""}),t}var AE,Ha=h(()=>{"use strict";L();Ar();P();AE="telemetry.json"});import U0 from"os";function j0(e){try{if(typeof e!="string"){if(e==null)return"";try{e=String(e)}catch(r){let n=r instanceof Error?r:new Error(String(r));return p.warn("SYSTEM","error-scrub: String() coercion of non-string input failed",void 0,n),""}}let t=e;return t.length>NE?t.slice(0,NE):t}catch{return""}}function F0(e){if(typeof e!="string"||e.length===0)return e??"";let t="";try{t=U0.homedir()||""}catch(n){let o=n instanceof Error?n:new Error(String(n));p.warn("SYSTEM","error-scrub: os.homedir() failed; skipping home-dir redaction",void 0,o),t=""}if(!t)return e;let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");try{return e.replace(new RegExp(r,"g"),"~")}catch(n){let o=n instanceof Error?n:new Error(String(n));return p.warn("SYSTEM","error-scrub: home-dir RegExp replace failed; using split/join fallback",void 0,o),e.split(t).join("~")}}function H0(e){return typeof e!="string"||e.length===0?e??"":e.replace(/(?<![~\w])\/(?:[^\s/:"'()]+\/)+([^\s/:"'()]+)/g,"$1").replace(/[A-Za-z]:\\(?:[^\s\\:"'()]+\\)*([^\s\\:"'()]+)/g,"$1").replace(/\\\\[^\s\\:"'()]+(?:\\[^\s\\:"'()]+)*\\([^\s\\:"'()]+)/g,"$1")}function W0(e){return typeof e!="string"||e.length===0?e??"":e.replace(/\b[A-Za-z][A-Za-z0-9+.-]*:\/\/[^\s"'()]+/g,t=>/^https?:\/\/hooks\.slack\.com\/services\//i.test(t)?t.replace(/^(https?:\/\/hooks\.slack\.com\/services\/)[^\s"'()]+/i,`$1${Lt}`):t.replace(/[?#].*$/,"").replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/@\s]+@/,`$1${Lt}@`))}function B0(e){return typeof e!="string"||e.length===0?e??"":e.replace(/\?[^\s"'()]*/g,"")}function K0(e){return typeof e!="string"||e.length===0?e??"":e.replace(/\b(?:access[_-]?token|api[_-]?key|auth(?:orization)?|secret|password|passwd|jwt|session[_-]?id|token)=[^\s"'&]+/gi,t=>{let r=t.indexOf("=");return`${t.slice(0,r+1)}${Lt}`})}function X0(e){if(typeof e!="string"||e.length===0)return e??"";let t=e;return t=t.replace(/[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}/g,Lt),t=t.replace(/\b[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\b/g,Lt),t=t.replace(/\b(?:sk|pk|rk|ak|phc|phx|ph|ghp|gho|ghs|xox[bpasr])[-_][A-Za-z0-9_-]{8,512}\b/gi,Lt),t=t.replace(/\bBearer\s+[A-Za-z0-9._-]{8,512}\b/gi,Lt),t=t.replace(/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g,Lt),t=t.replace(/\b[0-9a-fA-F]{24,4096}\b/g,Lt),t=t.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,Lt),t=t.replace(/\b(?=[A-Za-z0-9+/_-]{0,4096}\d)[A-Za-z0-9+/_-]{32,4096}={0,2}\b/g,Lt),t=t.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,Lt),t}function DE(e){let t=j0(e);return t.length===0?"":(t=F0(t),t=W0(t),t=H0(t),t=B0(t),t=K0(t),t=X0(t),t)}var NE,Lt,LE=h(()=>{"use strict";P();NE=8192,Lt="[REDACTED]"});function G0(e,t){if(!(!e||typeof e!="object"))for(let r of Object.keys(e)){if(!$0.has(r))continue;let n=e[r];if(typeof n=="string"){let o=n.length>UE?n.slice(0,UE):n;t[r]=DE(o)}else(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(t[r]=n)}}function jE(e){let t={};try{G0(e,t)}catch{}return t}var $0,UE,FE=h(()=>{"use strict";LE();$0=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"]),UE=200});import HE from"os";function WE(){return process.env.MEMINDEX_TELEMETRY_KEY??""}function BE(){return process.env.MEMINDEX_TELEMETRY_HOST||Y0}function KE(e){let t={};for(let r of V0)e[r]!==void 0&&(t[r]=e[r]);return t}function q0(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||HE.release().toLowerCase().includes("microsoft")}catch(e){let t=e instanceof Error?e:new Error(String(e));return p.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,t),!1}}function XE(){return{version:J0,os:process.platform,os_version:HE.release(),is_wsl:q0(),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 J0,Y0,V0,$E=h(()=>{"use strict";P();J0="1.7.1",Y0="https://us.i.posthog.com";V0=["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 Pr(e,t,r){try{if(!PE(process.env,cn()))return;let n=jE({...XE(),...t??{}});if(r?.person?n.$set=KE(n):n.$process_person_profile=!1,process.env.MEMINDEX_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:e,properties:n})+`
|
|
18
18
|
`);return}let o=WE(),s=new AbortController,i=setTimeout(()=>s.abort(),z0);try{await Z0(o,e,n,s.signal)}finally{clearTimeout(i)}}catch{}}async function Z0(e,t,r,n){await fetch(`${BE()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:e,event:t,distinct_id:Fa(),properties:r}),signal:n})}var z0,Ks=h(()=>{"use strict";Ha();FE();$E();z0=2e3});import{createHash as O8,randomUUID as R8}from"crypto";var GE=h(()=>{"use strict";P()});import{randomUUID as U8}from"crypto";var JE=h(()=>{"use strict";P();GE()});import{spawn as B8,spawnSync as Q0}from"child_process";function Xs(e,t,r=eD){let n=Q0("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:Math.min(r,tD),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 eD,tD,Wa=h(()=>{"use strict";P();eD=5e3,tD=5e3});import{statSync as rD,readFileSync as nD}from"fs";import Fn from"path";function YE(e){let t=Fn.join(e,".git"),r;try{r=rD(t)}catch(c){return c instanceof Error&&c.code!=="ENOENT"&&p.warn("GIT","Unexpected error checking .git",{error:c instanceof Error?c.message:String(c)}),$s}if(!r.isFile())return $s;let n;try{n=nD(t,"utf-8").trim()}catch(c){return p.warn("GIT","Failed to read .git file",{error:c instanceof Error?c.message:String(c)}),$s}let o=n.match(/^gitdir:\s*(.+)$/);if(!o)return $s;let s=Fn.resolve(Fn.dirname(t),o[1]),i=s.match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(i){let c=i[1];return{isWorktree:!0,isSubmodule:!1,worktreeName:Fn.basename(e),parentRepoPath:c,parentProjectName:Fn.basename(c)}}let a=s.match(/^(.+)[/\\]\.git[/\\]modules[/\\](.+)$/);if(a){let c=a[1];return{isWorktree:!1,isSubmodule:!0,worktreeName:Fn.basename(e),parentRepoPath:c,parentProjectName:Fn.basename(c)}}return $s}var $s,VE=h(()=>{"use strict";P();$s={isWorktree:!1,isSubmodule:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null}});import{basename as qE}from"path";function zE(e){let t=Ie(e.replace(/\\/g,"/"));t=t.replace(/\\/g,"/");let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&");return r=r.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${r}$`)}function ZE(e,t){if(!t.length)return!1;let r=e.replace(/\\/g,"/"),n=qE(r);for(let o of t){let s=o.trim();if(s)try{let i=zE(s);if(i.test(r)||i.test(n))return!0}catch(i){p.warn("PROJECT_NAME","Invalid glob pattern",{pattern:s,error:i instanceof Error?i.message:String(i)});continue}}return!1}function QE(e,t){if(!t||!t.trim())return!1;let r=e.replace(/\\/g,"/"),n=qE(r),o=t.split(",").map(s=>s.trim()).filter(Boolean);for(let s of o)try{let i=zE(s);if(i.test(r)||i.test(n))return!0}catch(i){p.warn("PROJECT_NAME","Invalid exclusion pattern",{pattern:s,error:i instanceof Error?i.message:String(i)});continue}return!1}var tp=h(()=>{"use strict";rn();P()});import{realpathSync as oD}from"fs";function eS(e){let t=e;if(typeof t=="string"){if(!t.trim())return[];try{t=JSON.parse(t)}catch(n){return p.warn("PROJECT_NAME","MEMINDEX_PROJECT_ENVIRONMENTS is not valid JSON; ignoring it",{error:n instanceof Error?n.message:String(n)}),[]}}if(!Array.isArray(t))return t!=null&&p.warn("PROJECT_NAME","MEMINDEX_PROJECT_ENVIRONMENTS must be an array; ignoring it",{}),[];let r=[];for(let n of t){let o=typeof n?.name=="string"?n.name.trim():"",s=Array.isArray(n?.patterns)?n.patterns.filter(i=>typeof i=="string"&&i.trim()!==""):[];if(!o||s.length===0){p.warn("PROJECT_NAME","Ignoring a project environment without a name or patterns",{name:o});continue}r.push({name:o,patterns:s})}return r}function sD(e){try{return oD(e)}catch{return e}}function rp(e,t){if(t.length===0)return null;let r=[...new Set([e,sD(e)])].flatMap(n=>[n,`${n.replace(/[\\/]+$/,"")}/`]);for(let n of t)if(r.some(o=>ZE(o,n.patterns)))return n.name;return null}var tS=h(()=>{"use strict";tp();P()});import ft from"path";import{existsSync as iD,realpathSync as aD,statSync as cD}from"fs";import{homedir as lD,tmpdir as uD}from"os";function iS(e){let t=process.env[dD]?.trim();return t||(!e||e.trim()===""?null:e)}function aS(e){return pD(e,Xs(e,["rev-parse","--show-toplevel"]))}function pD(e,t){return t.status===0&&t.stdout?t.stdout:(p.debug("PROJECT_NAME","git rev-parse failed, falling back to non-git root",{dir:e},t.error),null)}function cS(e){try{return aD(e)}catch{return e}}function gD(e,t){let r=ft.relative(t,e);return r===""||!r.startsWith("..")&&!ft.isAbsolute(r)}function hD(){return[lD(),uD(),Rt].flatMap(e=>{let t=ft.resolve(e);return[t,cS(t)]})}function lS(e){let t=hD(),r=ft.resolve(e);if([ft.resolve(Rt),cS(ft.resolve(Rt))].some(o=>gD(r,o)))return null;for(let o=0;o<fD;o++){if(t.includes(r))return null;let s=ft.dirname(r);if(s===r)return null;if(mD.some(i=>iD(ft.join(r,i))))return r;r=s}return null}function op(e,t){let r=ft.basename(t);if(r===""){if(process.platform==="win32"){let o=e.match(/^([A-Z]):\\/i);if(o){let i=`drive-${o[1].toUpperCase()}`;return p.info("PROJECT_NAME","Drive root detected",{cwd:e,projectName:i}),i}}return p.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:e}),sp}return r}function rS(){try{return cD(U).mtimeMs}catch{return-1}}function uS(){let e=rS();if(e===-1)return j.getAllDefaults();if(Ba&&Ba.mtimeMs===e)return Ba.settings;let t=j.loadFromFile(U);return Ba={mtimeMs:rS(),settings:t},t}function ED(){let e=process.env[yD]??uS().MEMINDEX_PROJECT_NAME_SOURCE;return String(e??"path").trim().toLowerCase()==="git-remote"}function dS(){let e=process.env[SD]??uS().MEMINDEX_PROJECT_ENVIRONMENTS;return(!Ka||Ka.raw!==e)&&(Ka={raw:e,environments:eS(e)}),Ka.environments}function ip(e){let t=(e??"").trim();if(!t||/^file:/i.test(t)||t.startsWith("/")||t.startsWith(".")||t.startsWith("~")||t.startsWith("\\\\")||/^[a-z]:[\\/]/i.test(t))return null;let n=t.replace(/\/+$/,"").replace(/\.git$/i,""),o=n.match(/^[a-z][a-z0-9+.-]*:\/\/[^/]+\/(.+)$/i),s=o?null:n.match(/^(?:[^/@\s]+@)?[^:/\s]+:(?!\/\/)(.+)$/),i=o?.[1]??s?.[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 wD(e,t){return t.status===0&&t.stdout?ip(t.stdout):(p.debug("PROJECT_NAME","No usable origin remote, keeping the path-based name",{repoRoot:e},t.error),null)}function pS(e){return ED()?(np.has(e)||np.set(e,wD(e,Xs(e,["remote","get-url","origin"]))),np.get(e)??null):null}function bD(e,t=process.platform){if(!e||e.trim()==="")return p.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:e}),sp;let r=Ie(e,t),n=rp(r,dS());if(n)return n;let o=aS(r),s=o?pS(o):null;if(s)return s;let i=o??lS(r)??r;return op(e,i)}function mS(e,t){return t===e?e:`${e}/${t}`}function kD(e,t){if(!e.isSubmodule||!e.parentRepoPath)return null;let r=ft.relative(e.parentRepoPath,t);return!r||r.startsWith("..")||ft.isAbsolute(r)?null:r.split(ft.sep).join("/")}function Be(e,t=process.platform){if(!e||e.trim()==="")return vD(e,t);let r=Ie(e,t),n=aS(r),o=n?pS(n):null;return xD(e,r,n,o)}function vD(e,t){let r=bD(e,t);return{primary:r,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[r],keySource:"path"}}function xD(e,t,r,n){let o=ID(e,t,r),s=n?nS(o,n,"git-remote"):o,i=rp(t,dS());return i?nS(s,i,"environment"):s}function nS(e,t,r){return{primary:t,parent:null,isWorktree:e.isWorktree,isSubmodule:e.isSubmodule,allProjects:[...e.allProjects.filter(n=>n!==t),t],keySource:r}}function ID(e,t,r){let n=r?null:lS(t),o=op(e,r??n??t),s=r??t,i=YE(s);if((i.isWorktree||i.isSubmodule)&&i.parentProjectName){let a=i.parentProjectName,c,l;return i.isSubmodule?(c=`${a}/${kD(i,s)??o}`,l=o!==a?[o]:[]):(c=mS(a,o),l=c===a?[`${a}/${o}`]:[]),{primary:c,parent:a,isWorktree:i.isWorktree,isSubmodule:i.isSubmodule,allProjects:[...new Set([a,...l,c])].filter(u=>u!==c).concat(c),keySource:"path"}}if(n&&ft.resolve(n)!==ft.resolve(t)){let a=op(e,t);if(a!==o&&a!==sp)return{primary:o,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[a,o],keySource:"path"}}return{primary:o,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[o],keySource:"path"}}var dD,sp,mD,fD,yD,Ba,SD,Ka,np,er=h(()=>{"use strict";rn();L();ge();P();Wa();VE();tS();dD="CLAUDE_PROJECT_DIR",sp="unknown-project";mD=[".memindex-project",".memindex.json"],fD=64;yD="MEMINDEX_PROJECT_NAME_SOURCE",Ba=null;SD="MEMINDEX_PROJECT_ENVIRONMENTS",Ka=null;np=new Map});import kt from"path";import{homedir as TD,tmpdir as E6}from"os";import{existsSync as Xa,writeFileSync as w6,readFileSync as MD,unlinkSync as b6,mkdirSync as CD,statSync as k6,utimesSync as OD,copyFileSync as v6,realpathSync as RD}from"fs";import{execFileSync as _D,spawnSync as AD}from"child_process";function PD(e){try{return RD(e)}catch{return null}}function ap(e){return e?/(^|[\\/])bun(\.exe)?$/i.test(e.trim()):!1}function ND(e,t){let r=t==="win32"?"where.exe":"which",n=[e],o;try{o=_D(r,n,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(i){return i instanceof Error?p.debug("SYSTEM",`Binary lookup failed for ${e}`,{command:r,args:n},i):p.debug("SYSTEM",`Binary lookup failed for ${e}`,{command:r,args:n},new Error(String(i))),null}return o.split(/\r?\n/).map(i=>i.trim()).find(i=>i.length>0)||null}function Wn(e={}){let t=Object.keys(e).length===0;if(t&&cp!==void 0)return cp;let r=DD(e);return t&&r!==null&&(cp=r),r}function fS(e,t){let r=e?.trim();return r?t==="win32"?[kt.join(r,"bin","bun.exe"),kt.join(r,"bin","bun"),kt.join(r,"bun.exe")]:[kt.join(r,"bin","bun"),kt.join(r,"bun")]:[]}function DD(e){let t=e.platform??process.platform,r=e.execPath??process.execPath;if(ap(r))return r;let n=e.env??process.env,o=e.homeDirectory??TD(),s=e.pathExists??Xa,i=e.lookupInPath??ND,a=e.realpath??PD,c=t==="win32"?[n.BUN,n.BUN_PATH,...fS(n.BUN_INSTALL,t),kt.join(o,".bun","bin","bun.exe"),kt.join(o,".bun","bin","bun"),n.USERPROFILE?kt.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?kt.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?kt.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0,n.npm_config_prefix?kt.join(n.npm_config_prefix,"bun.exe"):void 0]:[n.BUN,n.BUN_PATH,...fS(n.BUN_INSTALL,t),kt.join(o,".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?kt.join(n.npm_config_prefix,"bin","bun"):void 0];for(let d of c){let m=d?.trim();if(m&&(ap(m)&&s(m)||m.toLowerCase()==="bun"))return m}let l=i("bun",t)?.trim();if(!l||!ap(l))return null;let u=a(l)??l;return s(u)?u:null}function yS(){if(!Xa(Hn))return null;try{return JSON.parse(MD(Hn,"utf-8"))}catch(e){return e instanceof Error?p.warn("SYSTEM","Failed to parse PID file",{path:Hn},e):p.warn("SYSTEM","Failed to parse PID file",{path:Hn},new Error(String(e))),null}}function ES(e){Gd(Hn,e,!0)}function ln(e){return process.platform==="win32"?Math.round(e*2):e}function LD(){let e=G.dataDir();return CD(e,{recursive:!0}),e}function FD(e,t,r){return e?.code!=="ETIMEDOUT"?!1:t<r/2}function SS(e,t=ln(UD)){let r=Wn();if(!r)return;let n=()=>{let a=Date.now();try{return{result:AD(r,[e,"status"],{encoding:"utf-8",timeout:t,windowsHide:!0,env:de({...process.env})}),elapsedMs:Date.now()-a}}catch(c){let l=c instanceof Error?c:new Error(String(c));p.debug("SYSTEM","Worker boot probe could not be launched",{scriptPath:e},l);return}},o=n();if(o===void 0||FD(o.result.error,o.elapsedMs,t)&&(p.debug("SYSTEM","Worker boot probe timed out before it could run \u2014 retrying once",{scriptPath:e,elapsedMs:o.elapsedMs,timeoutMs:t}),o=n(),o===void 0))return;let{result:s}=o;if(s.error||s.status===0)return;let i=`${s.stdout??""}${s.stderr??""}`.trim();if(i)return i.split(/\r?\n/).slice(0,jD).join(`
|
|
19
19
|
`)}function HD(e,t,r,n=process.platform,o=Xa(gS)){let s=n!=="win32"&&o;return{command:s?gS:e,args:s?[e,t,"--daemon"]:[t,"--daemon"],options:{detached:!0,stdio:"ignore",cwd:LD(),env:r}}}function jo(e,t,r,n=process.platform){let{command:o,args:s,options:i}=HD(e,t,r,n),a=At(o,s,i);if(a.on("error",c=>{p.error("SYSTEM",hS,{runtimePath:e,execPath:o},c)}),a.pid!==void 0)return a.unref(),a.pid}function wS(e,t,r={}){Zd().assertCanSpawn("worker daemon");let n=de({...process.env,MEMINDEX_WORKER_PORT:String(t),...r}),o=Wn();if(!o){p.error("SYSTEM",hS);return}return jo(o,e,n)}function bS(){try{if(!Xa(Hn))return;let e=new Date;OD(Hn,e,e)}catch{}}function Gs(e={}){return Qd({logAlive:!1,removeStale:e.removeStale})}var N6,Hn,hS,cp,UD,jD,gS,$a=h(()=>{"use strict";wt();P();an();Jd();Ws();JE();er();Wa();L();ot();N6=G.dataDir(),Hn=G.workerPid(),hS="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.";UD=5e3,jD=8;gS="/usr/bin/setsid"});import WD from"net";function lp(){return j.loadFromFile(U).MEMINDEX_WORKER_HOST}function kS(e){return e.startsWith("[")&&e.endsWith("]")?e:e.includes(":")?`[${e}]`:e}async function vS(e,t,r="GET",n=Bn){let o={method:r,signal:AbortSignal.timeout(Math.max(1,n))},s=await fetch(`http://${kS(lp())}:${e}${t}`,r==="GET"||r==="HEAD"?o:on(o)),i="";try{i=await s.text()}catch{}return{ok:s.ok,statusCode:s.status,body:i}}async function Ga(e,t=Bn){let r=Date.now()+t;if(process.platform==="win32")try{let o=await fetch(`http://${kS(lp())}:${e}/api/health`,{signal:AbortSignal.timeout(Math.max(1,r-Date.now()))});if(o.ok)return!0;p.debug("SYSTEM","Windows health check returned non-ok; falling through to socket probe",{port:e,status:o.status})}catch(o){o instanceof Error?p.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:e,message:o.message}):p.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:e,error:String(o)})}let n=await Ja(e,Math.max(1,r-Date.now()));return n==="occupied"||n==="indeterminate"}async function Ja(e,t=Bn){return(await up(e,t)).occupancy}function up(e,t=Bn){return t<=0?Promise.resolve({occupancy:"indeterminate"}):new Promise(r=>{let n=!1,o=!1,s=!1,i;try{i=WD.createServer()}catch{r({occupancy:"indeterminate"});return}let a=u=>{if(s){u?.();return}s=!0;try{i.close(u)}catch(d){u?.(d instanceof Error?d:new Error(String(d)))}},c=setTimeout(()=>{if(o)a();else try{i.close()}catch{}l({occupancy:"indeterminate"})},t),l=u=>{n||(n=!0,clearTimeout(c),r(u))};i.once("error",u=>{if(o)a();else try{i.close()}catch{}u.code==="EADDRINUSE"?l({occupancy:"occupied"}):vy(u)?l({occupancy:"unbindable",bindErrorCode:u.code}):l({occupancy:"indeterminate"})}),i.once("listening",()=>{if(o=!0,n){a();return}try{a(u=>l({occupancy:u?"indeterminate":"free"}))}catch{l({occupancy:"indeterminate"})}});try{i.listen(e,lp())}catch{try{i.close()}catch{}l({occupancy:"indeterminate"})}})}async function xS(e,t,r,n){let o=Date.now()+r;for(;Date.now()<o;){try{let i=o-Date.now();if((await vS(e,t,"GET",Math.min(Bn,i))).ok)return!0}catch(i){i instanceof Error?p.debug("SYSTEM",n,{},i):p.debug("SYSTEM",n,{error:String(i)})}let s=Math.min(500,o-Date.now());s>0&&await new Promise(i=>setTimeout(i,s))}return!1}function un(e,t=3e4){return xS(e,"/api/health",t,"Service not ready yet, will retry")}function Fo(e,t=3e4){return xS(e,"/api/readiness",t,"Worker not ready yet, will retry")}async function BD(e,t=Bn){try{let r=await vS(e,"/api/health","GET",t);return r.ok?JSON.parse(r.body).version:null}catch{return p.debug("SYSTEM","Could not fetch worker version",{}),null}}async function IS(e,t,r=Bn){let n=t??"unknown",o=await BD(e,r);return!o||n==="unknown"?{matches:!0,pluginVersion:n,workerVersion:o}:{matches:n===o,pluginVersion:n,workerVersion:o}}var Bn,Js=h(()=>{"use strict";P();ge();L();Zt();mt();ot();Bn=5e3});var TS=h(()=>{"use strict";P();Ws()});var MS=h(()=>{"use strict";$a();Js();TS()});function CS(e){let t=KD.exec(e.trim());if(!t)return null;let r=t[4]===void 0?[]:t[4].split(".");return r.some(n=>n.length>1&&n.startsWith("0")&&dp.test(n))?null:{core:[Number(t[1]),Number(t[2]),Number(t[3])],pre:r}}function XD(e,t){if(e.length===0||t.length===0)return t.length-e.length;for(let r=0;r<Math.min(e.length,t.length);r++){let n=dp.test(e[r]),o=dp.test(t[r]);if(n&&o){let s=Number(e[r])-Number(t[r]);if(s!==0)return s}else{if(n!==o)return n?-1:1;if(e[r]!==t[r])return e[r]<t[r]?-1:1}}return e.length-t.length}function $D(e,t){let r=CS(e),n=CS(t);if(r===null||n===null)return null;for(let o=0;o<3;o++)if(r.core[o]!==n.core[o])return r.core[o]-n.core[o];return XD(r.pre,n.pre)}function OS(e,t){let r=$D(e,t);return r===null?"unreadable":r>0?"upgrade":r<0?"plugin-older":"same"}var KD,dp,RS=h(()=>{"use strict";KD=/^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,dp=/^\d+$/});import{dirname as GD,join as JD}from"path";import{mkdirSync as YD,readFileSync as Ya,statSync as _S,unlinkSync as AS,utimesSync as VD,writeFileSync as qD}from"fs";function mp(){return JD(W(),"spawn.lock")}function pp(e){try{let t=JSON.parse(Ya(e,"utf-8"));return typeof t.pid!="number"||!Number.isInteger(t.pid)||t.pid<=0?null:t.pid}catch{return null}}function QD(e){if(e===null)return null;try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}function Kn(){let e=mp(),t=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return YD(GD(e),{recursive:!0}),qD(e,t,{flag:"wx"}),!0}catch(n){let o=n instanceof Error?n:new Error(String(n)),s=o.code;if(s!=="EEXIST")return p.warn("SYSTEM","Spawn lock write failed for a non-contention reason; failing open (spawning unlocked)",{lockPath:e,code:s},o),!0;if(r>0)return!1;let i;try{i=_S(e).mtimeMs}catch{continue}let a=pp(e),c=null;if(a===null)try{c=Ya(e,"utf-8")}catch{continue}if(Date.now()-i<=Va&&QD(a)!==!1)return!1;let u;try{u=_S(e).mtimeMs}catch{continue}if(u!==i)return!1;if(a!==null){if(pp(e)!==a)return!1}else try{if(Ya(e,"utf-8")!==c)return!1}catch{continue}try{AS(e)}catch{return!1}}return!1}function dn(){let e=mp();try{if(JSON.parse(Ya(e,"utf-8")).pid!==process.pid)return;AS(e)}catch{}}async function fp(e,t=zD){let r=Date.now()+e;for(;!Kn();){if(Date.now()>=r)return null;await new Promise(o=>setTimeout(o,ZD))}let n=setInterval(eL,t);return n.unref(),()=>{clearInterval(n),dn()}}function eL(){let e=mp();try{if(pp(e)!==process.pid)return;let t=new Date;VD(e,t,t)}catch{}}var Va,zD,ZD,qa=h(()=>{"use strict";L();P();Va=9e4,zD=Va/3,ZD=250});import{execFile as tL}from"node:child_process";import{readdirSync as PS,readFileSync as hp,readlinkSync as rL,statSync as i5,promises as a5}from"node:fs";import{promisify as nL}from"node:util";function NS(e){return oL.test(e.trim())}function sL(e,t){if(!e)return!1;let r=e.toLowerCase().replace(/\\/g,"/"),n=r.indexOf("--data-dir");if(n<0)return!1;let o=r.slice(n+10).trim();if(o.startsWith('"')){let i=o.indexOf('"',1);o=i<0?o.slice(1):o.slice(1,i)}let s=t.toLowerCase().replace(/\\/g,"/");return o===s||o.startsWith(s)&&o[s.length]==="/"}function Za(e,t){return t===void 0?e:Math.max(1,Math.min(e,t))}async function iL(e){try{let t=await za("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:Za(3e4,e),windowsHide:!0,maxBuffer:33554432}),r=JSON.parse(t.stdout),n=Array.isArray(r)?r:r===null?[]:[r],o=[];for(let s of n){let i=typeof s.Name=="string"?s.Name.trim():"";if(!i)continue;let a=typeof s.ProcessId=="number"?s.ProcessId:Number.parseInt(String(s.ProcessId),10),c=typeof s.ParentProcessId=="number"?s.ParentProcessId:Number.parseInt(String(s.ParentProcessId),10);!Number.isInteger(a)||!Number.isInteger(c)||o.push({pid:a,ppid:c,name:i,cmdline:typeof s.CommandLine=="string"?s.CommandLine:null,startToken:typeof s.StartToken=="string"&&s.StartToken.length>0?s.StartToken:null})}return o}catch(t){return p.warn("PROCESS","Cannot enumerate the Windows process table with names \u2014 ghost-port reclaim disabled",{error:t instanceof Error?t.message:String(t)}),null}}async function aL(e,t){try{let r=await za("netstat",["-ano"],{timeout:Za(15e3,t),windowsHide:!0,maxBuffer:16777216});return mL(r.stdout,e)}catch(r){return p.warn("PROCESS","netstat failed \u2014 ghost-port reclaim disabled for this attempt",{port:e,error:r instanceof Error?r.message:String(r)}),null}}async function cL(e,t){try{let r=await za("lsof",["-nP",`-iTCP:${e}`,"-sTCP:LISTEN","-t"],{timeout:Za(1e4,t),maxBuffer:1048576});return lL(r.stdout)}catch(r){let n=r;return n.code===1&&typeof n.stdout=="string"&&n.stdout.trim()===""?[]:(p.warn("PROCESS","lsof failed \u2014 cannot verify the worker port owner",{port:e,error:r instanceof Error?r.message:String(r)}),null)}}function lL(e){let t=new Set;for(let r of e.split(/\r?\n/)){let n=Number.parseInt(r.trim(),10);Number.isInteger(n)&&n>0&&t.add(n)}return[...t]}function uL(e,t){let r=t.toString(16).toUpperCase().padStart(4,"0"),n=[];for(let o of e.split(/\r?\n/).slice(1)){let s=o.trim().split(/\s+/);s.length<10||s[1].split(":").pop()?.toUpperCase()===r&&s[3]==="0A"&&s[9]!=="0"&&n.push(s[9])}return n}function dL(e,t={}){let r=t.deadlineAt??null,n=t.now??Date.now,o=()=>r!==null&&n()>=r;if(o())return null;let s=new Set,i=!1;for(let l of["/proc/net/tcp","/proc/net/tcp6"]){if(o())return null;try{for(let u of uL(hp(l,"utf8"),e))s.add(u);i=!0}catch{}}if(!i||o())return null;if(s.size===0)return[];let a;try{a=PS("/proc")}catch{return null}let c=new Set;for(let l of a){if(o())return null;if(!/^\d+$/.test(l))continue;let u;try{u=PS(`/proc/${l}/fd`)}catch{continue}for(let d of u){if(o())return null;try{let m=/^socket:\[(\d+)\]$/.exec(rL(`/proc/${l}/fd/${d}`));if(m&&s.has(m[1])){c.add(Number.parseInt(l,10));break}}catch{}}}return o()?null:[...c]}async function pL(e,t){if(process.platform==="linux")try{return hp(`/proc/${e}/cmdline`,"utf8").split("\0").filter(Boolean).join(" ")||null}catch{return null}try{let n=(await za("ps",["-p",String(e),"-o","command="],{timeout:Za(5e3,t)})).stdout.trim();return n.length>0?n:null}catch{return null}}function mL(e,t){let r=new Set,n=`:${t}`;for(let o of e.split(/\r?\n/)){let s=o.trim();if(!/^TCP\b/i.test(s))continue;let i=s.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 gL(e,t){let r=t.readOwnedWorker();if(r===null||r.port!==e)return null;let n=(u,d={})=>(p.info("PROCESS","Wedged-worker reclaim declined",{port:e,pid:r.pid,reason:u,...d}),{reclaimed:!1,reason:u,killedPids:[]}),o=(t.now()-Date.parse(r.startedAt))/1e3;if(!Number.isFinite(o)||o<t.minOwnerAgeSeconds)return n("owner-booting",{ageSeconds:o,minOwnerAgeSeconds:t.minOwnerAgeSeconds});for(let u=0;u<2;u++)if(u>0&&await t.sleep(US),await t.probeHealth(e))return n("owner-responding");let s=await t.listOwners(e);if(s===null)return n("netstat-unreadable");if(!s.includes(r.pid))return p.info("PROCESS","Wedged-worker reclaim: our worker does not own the port \u2014 deferring to the ghost-listener check",{port:e,pid:r.pid,listeners:s}),null;let i=t.readHeartbeat();if(i?.pid===r.pid){let u=t.now(),d=Math.max(0,u-i.beatAtMs),m=Math.max(0,u-i.lastResponseAtMs);if(d<t.heartbeatStaleMs&&m<t.maxSilentProtectionMs)return n("owner-progressing",{heartbeatAgeMs:d,sinceLastResponseMs:m})}let a=await t.readIdentity(r.pid),c=r.startToken!==void 0&&a.startToken!==null&&a.startToken!==r.startToken;if(c||a.cmdline===null||!fL.test(a.cmdline))return n("owner-identity-mismatch",{tokenMismatch:c,hasCmdline:a.cmdline!==null});if(!t.hasKillBudget())return n("out-of-budget");p.warn("PROCESS","Reclaiming wedged worker: past its boot grace, silent on two health probes, and still holding the port",{port:e,pid:r.pid,ageSeconds:Math.round(o)});try{await t.killTree(r.pid,{expectedStartToken:a.startToken??r.startToken??void 0,signalMode:"graceful"})}catch(u){return p.error("PROCESS","Wedged-worker reclaim tree-kill failed",{port:e,pid:r.pid},u instanceof Error?u:new Error(String(u))),{reclaimed:!1,reason:"kill-failed",killedPids:[]}}let l=await t.listOwners(e);return l!==null&&l.length===0?(p.info("PROCESS","Wedged worker reclaimed \u2014 port is free again",{port:e,killedPids:[r.pid]}),{reclaimed:!0,killedPids:[r.pid]}):(p.warn("PROCESS","Wedged-worker reclaim killed the worker but the port is still bound",{port:e,pid:r.pid,stillOwnedBy:l}),{reclaimed:!1,reason:"still-bound",killedPids:[r.pid]})}async function hL(e,t,r,n){let o=_r(e),s=t?(await r(n))?.find(i=>i.pid===e)?.cmdline??null:await pL(e,n);return Dt(e,o)?{startToken:o,cmdline:s}:{startToken:null,cmdline:null}}async function Qa(e,t={}){let r=t.isWin32??(()=>process.platform==="win32"),n=t.now??Date.now,o=t.deadlineAt??null,s=T=>o!==null&&o-n()<T,i=()=>o===null?void 0:Math.max(1,o-n());if(s(DS))return p.info("PROCESS","Port reclaim skipped: not enough of the hook budget is left to finish one",{port:e,remainingMs:i(),neededMs:DS}),{reclaimed:!1,reason:"out-of-budget",killedPids:[]};let a=t.listOwners??((T,R)=>r()?aL(T,R):process.platform==="linux"?Promise.resolve(dL(T,{deadlineAt:o,now:n})):cL(T,R)),c=T=>a(T,i()),l=t.readTable??iL,u=()=>l(i()),d=t.killTree??((T,R)=>bt(T,R)),m=t.dataDir??(()=>Z),f=t.readIdentity??((T,R)=>hL(T,r(),l,R)),g=await gL(e,{listOwners:c,killTree:d,readOwnedWorker:t.readOwnedWorker??ze,probeHealth:t.probeHealth??(T=>un(T,LS)),readIdentity:T=>f(T,i()),minOwnerAgeSeconds:t.minOwnerAgeSeconds??Dy(),readHeartbeat:t.readHeartbeat??(()=>wL()),heartbeatStaleMs:t.heartbeatStaleMs??SL(),maxSilentProtectionMs:t.maxSilentProtectionMs??yL,now:n,sleep:t.sleep??(T=>new Promise(R=>setTimeout(R,T))),hasKillBudget:()=>!s(gp)});if(g!==null)return g;if(!r())return{reclaimed:!1,reason:"not-supported",killedPids:[]};let y=await c(e);if(y===null)return{reclaimed:!1,reason:"netstat-unreadable",killedPids:[]};if(y.length===0)return{reclaimed:!1,reason:"no-listener",killedPids:[]};let E=await u();if(E===null)return{reclaimed:!1,reason:"table-unreadable",killedPids:[]};if(y.filter(T=>oe(T)).length>0)return{reclaimed:!1,reason:"owner-alive",killedPids:[]};let b=new Map;for(let T of E){let R=b.get(T.ppid);R?R.push(T):b.set(T.ppid,[T])}let w=new Map,I=new Set,C=T=>{for(let R of b.get(T)??[])I.has(R.pid)||(I.add(R.pid),C(R.pid),NS(R.name)&&w.set(R.pid,R))};for(let T of y)C(T);let v=m();if(v)for(let T of E)w.has(T.pid)||NS(T.name)&&sL(T.cmdline,v)&&w.set(T.pid,T);if(w.size===0)return p.info("PROCESS","Ghost listener owner is dead but no chroma-sidecar descendants found",{port:e,deadOwners:y,processTableRows:E.length,dataDir:v??"(unresolved)"}),{reclaimed:!1,reason:"no-chroma-descendants",killedPids:[]};p.warn("PROCESS","Reclaiming ghost listener: killing dead worker's surviving chroma sidecar chain",{port:e,deadOwners:y,targets:[...w.values()].map(T=>({pid:T.pid,name:T.name}))});let x=[];for(let T of w.values()){if(s(gp))return p.info("PROCESS","Ghost-listener reclaim stopped before a kill: the hook budget is spent",{port:e,killedPids:x}),{reclaimed:!1,reason:"out-of-budget",killedPids:x};try{await d(T.pid,{expectedStartToken:T.startToken,signalMode:"immediate"}),x.push(T.pid)}catch(R){return p.error("PROCESS","Ghost-port reclaim tree-kill failed",{port:e,pid:T.pid},R instanceof Error?R:new Error(String(R))),{reclaimed:!1,reason:"kill-failed",killedPids:x}}}let _=await c(e);return _!==null&&_.length===0?(p.info("PROCESS","Ghost listener reclaimed \u2014 port is free again",{port:e,killedPids:x}),{reclaimed:!0,killedPids:x}):(p.warn("PROCESS","Ghost-port reclaim killed the sidecar chain but the port is still bound",{port:e,killedPids:x,stillOwnedBy:_}),{reclaimed:!1,reason:"still-bound",killedPids:x})}function SL(e=process.env,t=U){let r=e.MEMINDEX_WORKER_HEARTBEAT_STALE_MS??j.loadFromFile(t,!1,{readOnly:!0}).MEMINDEX_WORKER_HEARTBEAT_STALE_MS,n=Number(r);return Number.isSafeInteger(n)&&n>=1e4&&n<=36e5?n:EL}function wL(e=G.workerHeartbeat()){try{let t=JSON.parse(hp(e,"utf8"));if(t&&Number.isSafeInteger(t.pid)&&Number.isFinite(t.beatAtMs)&&Number.isFinite(t.lastResponseAtMs))return{pid:t.pid,beatAtMs:t.beatAtMs,lastResponseAtMs:t.lastResponseAtMs}}catch{}return null}var za,oL,fL,LS,US,gp,DS,yL,EL,yp=h(()=>{"use strict";P();No();ot();Ws();Js();Pa();Qt();L();ge();za=nL(tL),oL=/^(uv|uvx|python|chroma-mcp)(\.exe)?$/i;fL=/worker-service/i,LS=1500,US=1e3,gp=5500,DS=2*LS+US+gp;yL=6e5,EL=12e4});import{existsSync as bL,readFileSync as kL,realpathSync as vL}from"fs";import{createRequire as xL}from"module";import Xn from"path";function jS(e){try{return vL(e)}catch{return e}}function TL(e,t){let r=Xn.relative(t,e);return r!==""&&!r.startsWith("..")&&!Xn.isAbsolute(r)}function Ep(e){let t;try{let o=JSON.parse(kL(Xn.join(e,"package.json"),"utf-8"));t=Object.keys(o?.dependencies??{})}catch{return[]}if(t.length===0)return[];let r=Xn.join(e,"node_modules"),n=t.filter(o=>!bL(Xn.join(r,...o.split("/"),"package.json")));if(t.includes("zod")&&!n.includes("zod")){let o=xL(Xn.join(r,"noop.js")),s=jS(Xn.join(r,"zod"));for(let i of IL)try{let a=o.resolve(i,{paths:[r]});TL(jS(a),s)||n.push(i)}catch{n.push(i)}}return n}var IL,FS=h(()=>{"use strict";IL=["zod/v3","zod/v4","zod/v4-mini"]});import Sp from"path";import{readFileSync as ML,unlinkSync as CL}from"fs";function BS(){return Sp.join(W(),"worker-standby.json")}function kp(){return Sp.join(W(),"worker-standby-attempt.json")}function vp(){return Sp.join(W(),"worker-standby-failure.json")}function xp(e){try{return JSON.parse(ML(e,"utf-8"))}catch{return null}}function Ip(e){try{CL(e)}catch(t){t.code!=="ENOENT"&&p.debug("SYSTEM","Could not remove worker standby file",{path:e,error:t instanceof Error?t.message:String(t)})}}function ec(){let e=xp(BS());return!e||typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0||typeof e.port!="number"||!Number.isInteger(e.port)||e.port<=0||typeof e.version!="string"?null:{pid:e.pid,port:e.port,version:e.version,startedAt:typeof e.startedAt=="string"?e.startedAt:""}}function tc(e){if(e!==void 0){let t=ec();if(t!==null&&t.pid!==e)return}Ip(BS())}function OL(){let e=xp(vp());return!e||typeof e.buildKey!="string"||typeof e.failedAt!="string"?null:{buildKey:e.buildKey,failedAt:e.failedAt,reason:typeof e.reason=="string"?e.reason:""}}function KS(e,t,r=new Date){try{N(vp(),{buildKey:e,failedAt:r.toISOString(),reason:t})}catch(n){p.warn("SYSTEM","Could not save the failed worker update attempt",{error:n instanceof Error?n.message:String(n)})}}function XS(){Ip(vp())}function $S(e,t=Date.now()){if(e===null)return null;let r=OL();if(r===null||r.buildKey!==e)return null;let n=Date.parse(r.failedAt);return!Number.isFinite(n)||t-n>=bp?null:r}function GS(){let e=xp(kp());return!e||typeof e.buildKey!="string"||typeof e.launchedAtMs!="number"||!Number.isFinite(e.launchedAtMs)?null:{buildKey:e.buildKey,launchedAtMs:e.launchedAtMs}}function JS(e){try{N(kp(),e)}catch(t){p.debug("SYSTEM","Could not save the worker update attempt",{error:t instanceof Error?t.message:String(t)})}}function YS(){Ip(kp())}var HS,wp,WS,bp,VS=h(()=>{"use strict";L();J();P();HS="MEMINDEX_WORKER_STANDBY",wp=12e4,WS=2e4,bp=10*6e4});import se from"path";import{randomUUID as RL}from"crypto";import{readFileSync as Yn,existsSync as Vn,writeFileSync as lw,renameSync as _L,mkdirSync as uw,readdirSync as AL,statSync as zs,unlinkSync as Zs}from"fs";function _p(e,t,r){let n=process.env[e];if(n){let o=parseInt(n,10);if(Number.isFinite(o)&&o>=r.min&&o<=r.max)return o;p.warn("SYSTEM",`Invalid ${e}, using default`,{value:n,min:r.min,max:r.max})}return t}function dw(e=process.env){let t=e.MEMINDEX_FETCH_VERBOSE;if(t===void 0)return!1;let r=t.trim().toLowerCase();return r==="1"||r==="true"||r==="on"||r==="yes"}function LL(e){return dw()?{...e,verbose:!0}:e}function UL(e){let t={},r=e;for(let n=0;r&&n<4;n++){let o=n===0?"error":`cause${n}`;if(r instanceof Error){let s=r;t[o]={name:r.name,message:r.message,...s.code!==void 0?{code:s.code}:{}},r=r.cause;continue}t[o]=String(r);break}return t}function jL(e,t,r){let n=typeof t.method=="string"?t.method:"GET",o=UL(r),s=JSON.stringify(o);p.warn("SYSTEM","Worker IPC fetch failed",{url:e,method:n},s),Cr(`[memindex] fetch verbose: ${n} ${e} ${s}
|
|
20
20
|
`)}async function Qs(e,t={}){let r=LL(t);try{return await fetch(e,r)}catch(n){throw dw()&&jL(e,t,n),n}}async function Ho(e,t={},r){try{return await Qs(e,{...t,signal:AbortSignal.timeout(r)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new Error(`Request timed out after ${r}ms`):n}}function FL(e,t){let r=new AbortController,n=null,o=null,s=null,i=!1,a=()=>{o!==null&&(clearTimeout(o),o=null)},c=()=>{i=!0,a(),s!==null&&(clearTimeout(s),s=null)},l=d=>{i||(n=d,c(),r.abort(d))},u=()=>{i||(a(),o=setTimeout(()=>l(new Error(`Request timed out after ${e.idleTimeoutMs}ms idle`)),e.idleTimeoutMs))};if(e.absoluteCapMs!==void 0&&e.absoluteCapMs>0){let d=e.absoluteCapMs;s=setTimeout(()=>l(new Error(`Request timed out after ${d}ms`)),d)}return u(),{signal:t?AbortSignal.any([t,r.signal]):r.signal,touch:u,pause:a,dispose:c,translate:d=>n??d}}async function pw(e,t,r){let n=FL(r,t.signal),o;try{o=await Qs(e,{...t,signal:n.signal})}catch(l){throw n.dispose(),n.translate(l)}n.touch();let s=o.body,i=s?s.getReader():null,a=!1;async function*c(){if(!i){a=!0,n.dispose();return}try{for(;;){n.touch();let l;try{l=await i.read()}catch(u){throw a=!0,n.translate(u)}if(l.done){a=!0;return}n.pause(),r.onChunk?.(l.value),yield l.value}}finally{n.dispose(),a||await i.cancel()}}return{status:o.status,statusText:o.statusText,ok:o.ok,headers:o.headers,chunks:c(),cancel:async()=>{n.dispose(),i&&!a&&(a=!0,await i.cancel())}}}async function HL(e,t,r){let n=await pw(e,t,r),o=new TextDecoder,s="";for await(let i of n.chunks)s+=o.decode(i,{stream:!0});return s+=o.decode(),{status:n.status,statusText:n.statusText,ok:n.ok,headers:n.headers,text:s}}function qS(){return se.join(j.get("MEMINDEX_DATA_DIR"),"settings.json")}function lc(e={}){return e.readOnly?j.loadFromFile(qS(),!0,e):(rc!==null||(rc=j.loadFromFile(qS())),rc)}function zS(e,t){if(!e)return null;let r=parseInt(e,10);return Number.isFinite(r)&&r>=t.min&&r<=t.max?r:null}function mw(e,t,r){let n=process.env[e];if(n!==void 0){let i=zS(n,r);return i!==null?i:(p.warn("SYSTEM",`Invalid ${e}, using default`,{value:n,min:r.min,max:r.max}),t)}let o=lc()[e],s=zS(o,r);return s!==null?s:(p.warn("SYSTEM",`Invalid ${e} in settings.json, using default`,{value:o,min:r.min,max:r.max}),t)}function re(e={}){if(!e.readOnly&&Tp!==null)return Tp;let t=parseInt(lc(e).MEMINDEX_WORKER_PORT,10),r=t===Ed()&&js()?wd(W()):t;return e.readOnly||(Tp=r),r}function mn(e={}){if(!e.readOnly&&Mp!==null)return Mp;let t=lc(e).MEMINDEX_WORKER_HOST;return e.readOnly||(Mp=t),t}function Pp(e){return Ad(e,lc().MEMINDEX_PUBLIC_URL)}function WL(){return nc!==null||(nc=mw("MEMINDEX_API_TIMEOUT_MS",Rr(ue.API_REQUEST),NL)),nc}function fw(){return oc!==null||(oc=Math.min(mw("MEMINDEX_SESSION_INIT_TIMEOUT_MS",Ls(),DL),Uy())),oc}function gw(e){return e===null?null:Math.max(0,e-Date.now())}function ic(e){let t=gw(e);return t!==null&&t<Ap}function Ut(e,t){let r=gw(t);return r===null?e:Math.max(1,Math.min(e,r))}function be(e){return`http://${pr(mn())}:${re()}${e}`}function BL(e){let t=e.split("?")[0].toLowerCase().replace(/\/+$/,"");return t==="/api/health"||t==="/api/readiness"||t==="/api/ready"}async function XL(e){if(!await _t(be(""),{timeoutMs:e,fetchImpl:Qs}))throw ZS||(ZS=!0,p.warn("SECURITY","The listener on the worker port did not prove it is this install's worker; nothing was sent to it",{port:re(),host:mn()})),new qe(KL)}async function Ze(e,t={}){let r=t.method??"GET",n=be(e),o={method:r};t.headers&&(o.headers=t.headers),t.body&&(o.body=t.body);let s=BL(e),i=Date.now(),a=t.idleTimeoutMs!==void 0&&t.idleTimeoutMs>0?t.timeoutMs:t.timeoutMs??WL(),c=()=>Date.now()-i,l=u=>u===void 0||u<=0?u:Math.max(1,u-c());try{s||await XL(a!==void 0&&a>0?Math.min(jt,a):jt);let u=s?o:on(o);if(t.idleTimeoutMs!==void 0&&t.idleTimeoutMs>0){let m=await HL(n,u,{idleTimeoutMs:t.idleTimeoutMs,absoluteCapMs:l(t.timeoutMs)});return new Response(m.text.length>0?m.text:null,{status:m.status,statusText:m.statusText,headers:m.headers})}let d=l(a)??0;return d>0?await Ho(n,u,d):await Qs(n,u)}catch(u){throw u instanceof qe||Ay(),u}}async function $L(e){return(await Ze("/api/health",{timeoutMs:e})).ok}async function QS(e=jt){return(await Ze("/api/readiness",{timeoutMs:e})).ok}function hw(e){let t=Vn(se.join(e,"plugin","scripts"))?se.join(e,"plugin"):e;return se.join(t,"scripts","worker-service.cjs")}function Np(e,t){let r=d=>{let m=d.split("-")[0].split(".");return[parseInt(m[0],10)||0,parseInt(m[1],10)||0,parseInt(m[2],10)||0]},[n,o,s]=r(e),[i,a,c]=r(t);if(i!==n)return i-n;if(a!==o)return a-o;if(c!==s)return c-s;let l=e.includes("-")?1:0,u=t.includes("-")?1:0;return l!==u?l-u:e<t?1:e>t?-1:0}function Dp(e=se.join(se.dirname(se.dirname(We)),"cache","memindex","memindex")){try{return AL(e).filter(t=>/^\d/.test(t)).map(t=>se.join(e,t)).filter(t=>{try{if(!zs(t).isDirectory())return!1}catch{return!1}return!Vn(se.join(t,".orphaned_at"))}).map(t=>({scriptPath:hw(t),version:se.basename(t)}))}catch{return[]}}function ew(e){try{let t=JSON.parse(Yn(e,"utf-8"));return typeof t.version=="string"?t.version:null}catch(t){let r=t.code;return r!=="ENOENT"&&p.debug("SYSTEM","Could not read package version for worker resolution",{packageJsonPath:e,code:r}),null}}function yw(){return{cacheRoot:se.join(se.dirname(se.dirname(We)),"cache","memindex","memindex"),marketplaceRoot:We,cwd:process.cwd()}}function Wo(e=yw()){let t=process.env.MEMINDEX_WORKER_SCRIPT_PATH?.trim();if(t){if(Vn(t))return{scriptPath:t,version:null};p.debug("SYSTEM","Ignoring missing MEMINDEX_WORKER_SCRIPT_PATH override",{override:t})}let r=cc([...Dp(e.cacheRoot),{scriptPath:hw(se.join(e.marketplaceRoot,"plugin")),version:ew(se.join(e.marketplaceRoot,"package.json"))}]);return r||!Ye()?r:cc([{scriptPath:se.join(e.cwd,"plugin","scripts","worker-service.cjs"),version:ew(se.join(e.cwd,"package.json"))}])}function Ew(e){return se.dirname(se.dirname(e))}function GL(e){return Ep(Ew(e.scriptPath)).length===0}function cc(e,t=GL){let r=e.filter(n=>Vn(n.scriptPath));return r.length===0?null:(r.sort((n,o)=>n.version===null&&o.version===null?0:n.version===null?1:o.version===null?-1:Np(n.version,o.version)),r.find(t)??r[0])}function JL(){return Wo()?.scriptPath??null}function mr(e=yw()){let t=Wo(e);if(!t)return null;let r=Ew(t.scriptPath);return{root:r,version:t.version,missingDependencies:Ep(r)}}async function YL(e){let t=e.deadlineAt??null,r=e.backoffMs;for(let n=1;n<=e.attempts;n++){if(ic(t))return!1;if(await Mw(t??Number.POSITIVE_INFINITY))return!0;n<e.attempts&&(await new Promise(o=>setTimeout(o,Ut(r,t))),r*=2)}return!1}function tw(e){return e instanceof Error&&/^Request timed out after \d+ms idle$/.test(e.message)}function rw(e){return e instanceof Error&&/^Request timed out after \d+ms$/.test(e.message)}async function VL(e){let t;try{t=await pw(be("/api/ready"),{method:"GET"},{idleTimeoutMs:PL,absoluteCapMs:Math.max(1,e)})}catch(s){return tw(s)?{outcome:"unresponsive",detail:"no response headers within the idle window"}:rw(s)?{outcome:"still_booting",detail:"budget spent before response headers"}:(p.debug("SYSTEM","Worker /api/ready connection failed",{error:s instanceof Error?s.message:String(s)}),{outcome:"not_running"})}let r=()=>t.cancel().catch(s=>{p.debug("SYSTEM","Releasing the /api/ready body failed",{error:s instanceof Error?s.message:String(s)})}),n=t.headers?.get("content-type")??"";if(!t.ok||!n.includes("text/event-stream"))return ac(),await r(),{outcome:"unsupported"};let o=null;try{for await(let s of mE(t.chunks)){if(s.event!=="phase")continue;let i=JSON.parse(s.data);if(o=typeof i.phase=="string"?i.phase:null,o==="ready")return ac(),await r(),{outcome:"ready"};if(o==="failed")return await r(),{outcome:"failed",detail:typeof i.message=="string"?i.message:"unknown init failure"}}}catch(s){return rw(s)?(ac(),{outcome:"still_booting",detail:`last phase ${o??"none"}`}):tw(s)?{outcome:"unresponsive",detail:`silent past the idle window after response headers (last phase ${o??"none"})`}:{outcome:"wedged",detail:`stream error: ${s instanceof Error?s.message:String(s)} (last phase ${o??"none"})`}}return{outcome:"wedged",detail:`stream closed before ready/failed (last phase ${o??"none"})`}}async function qL(e){if(e<=0)try{return await QS()?{outcome:"ready"}:{outcome:"still_booting"}}catch(r){return p.debug("SYSTEM","Worker readiness check threw",{},r instanceof Error?r:new Error(String(r))),{outcome:"still_booting"}}let t=Date.now();do{let r=e-(Date.now()-t);try{if(await QS(Math.max(1,Math.min(jt,r))))return{outcome:"ready"}}catch(o){p.debug("SYSTEM","Worker readiness check threw",{error:o instanceof Error?o.message:String(o)})}let n=e-(Date.now()-t);if(n<=0)break;await new Promise(o=>setTimeout(o,Math.min(250,n)))}while(Date.now()-t<e);return{outcome:"still_booting",detail:"legacy /api/readiness never reported ready"}}async function pn(e=Gn){let t=e>0?e:jt,r=await VL(t);return r.outcome==="ready"&&nU(),r.outcome!=="unsupported"?r:(p.debug("SYSTEM","Worker has no /api/ready stream; falling back to /api/readiness"),qL(e))}async function zL(e=jt){try{let r=await(await Ze("/api/health",{timeoutMs:e})).json();return typeof r.version=="string"?r.version:null}catch(t){let r=t instanceof Error?t:new Error(String(t));return p.debug("SYSTEM","Worker health-version fetch failed",{},r),null}}async function ZL(e=5e3){let t=Date.now()+e;for(;;){let r=t-Date.now();if(r<=0)return!1;if(await Ja(re(),Math.min(1e3,r))==="free")return!0;let n=Math.min(200,t-Date.now());n>0&&await new Promise(o=>setTimeout(o,n))}}function Sw(e,t){if(!e)return null;try{let r=zs(e.scriptPath);return JSON.stringify([e.scriptPath,t,r.size,r.mtimeMs,r.ctimeMs])}catch{return null}}function ww(){return se.join(W(),"worker-version-recycle.json")}function QL(e,t){if(e===null||t===null)return!1;try{let r=JSON.parse(Yn(ww(),"utf-8"));return r?.buildKey===e&&r?.workerVersion===t}catch{return!1}}async function nw(e,t=null,r=jt){let n=await zL(r);if(n!==null&&n!==e){if(t!==null)try{N(ww(),{buildKey:t,workerVersion:n})}catch(o){p.warn("SYSTEM","Could not persist the failed worker version recycle",{error:o instanceof Error?o.message:String(o)})}p.warn("SYSTEM","Worker is ready but still reports a stale version; rebuild or reinstall the worker bundle before retrying",{pluginVersion:e,workerVersion:n})}}function Lp(){return se.join(W(),"worker-unresponsive.json")}function eU(){try{let e=JSON.parse(Yn(Lp(),"utf-8"));return typeof e?.pid!="number"||typeof e?.firstUnresponsiveAtEpochMs!="number"?null:{pid:e.pid,firstUnresponsiveAtEpochMs:e.firstUnresponsiveAtEpochMs}}catch{return null}}function ac(){let e=Lp();if(Vn(e))try{Zs(e)}catch(t){p.debug("SYSTEM","Could not clear the unresponsive-worker record",{error:t instanceof Error?t.message:String(t)})}}function tU(e=Date.now()){let t=ze()?.pid??null;if(t===null)return!1;let r=eU();if(r!==null&&r.pid===t)return e-r.firstUnresponsiveAtEpochMs>=bw;try{N(Lp(),{pid:t,firstUnresponsiveAtEpochMs:e})}catch(n){p.warn("SYSTEM","Could not persist the unresponsive-worker record",{error:n instanceof Error?n.message:String(n)})}return!1}function Up(){return se.join(W(),"worker-never-ready-recycle.json")}function rU(){try{let e=JSON.parse(Yn(Up(),"utf-8"));return typeof e?.buildKey!="string"||typeof e?.failureMessage!="string"?null:{buildKey:e.buildKey,failureMessage:e.failureMessage,refusalLogged:e.refusalLogged===!0}}catch{return null}}function kw(e){try{N(Up(),e)}catch(t){p.warn("SYSTEM","Could not persist the never-ready worker recycle",{error:t instanceof Error?t.message:String(t)})}}function nU(){let e=Up();if(Vn(e))try{Zs(e)}catch(t){p.debug("SYSTEM","Could not clear the never-ready worker recycle record",{error:t instanceof Error?t.message:String(t)})}}function vw(e){return Sw(e,e?.version??"unknown")??"unresolved-worker-bundle"}function xw(e){return e.outcome==="failed"?e.detail??"unknown init failure":e.outcome}function Iw(e,t){if(e.outcome==="unresponsive"&&!tU())return p.warn("SYSTEM","Worker went silent on /api/ready; skipping this hook without killing it",{detail:e.detail,wedgedAfterMs:bw}),!1;let r=xw(e),n=rU();return n!==null&&n.buildKey===t&&n.failureMessage===r?(n.refusalLogged?p.debug("SYSTEM","Never-ready worker recycle already refused for this bundle and failure",{failureMessage:r}):(p.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:e.outcome,failureMessage:r,logsDir:se.join(W(),"logs")}),kw({...n,refusalLogged:!0})),!1):!0}function Tw(e,t){kw({buildKey:t,failureMessage:xw(e)}),ac()}async function Mw(e=Number.POSITIVE_INFINITY){let t=e-Date.now();if(t<=0)return!1;let r;try{r=await $L(Math.min(jt,t))}catch(n){return p.debug("SYSTEM","Worker health check threw",{error:n instanceof Error?n.message:String(n)}),!1}return r}async function jp(e,t){let r=ze();if(r===null||r.port!==re())return p.error("SYSTEM","Stale worker is serving the port but the PID file does not identify it; kill the memindex worker process manually",{port:re(),pidFilePid:r?.pid??null,pidFilePort:r?.port??null}),!1;if(t("stale-worker recycle"))return!1;try{await bt(r.pid,{signalMode:"immediate"})}catch(n){return p.error("SYSTEM","Could not kill stale worker",{pid:r.pid,port:r.port},n instanceof Error?n:new Error(String(n))),!1}return await ZL(Ut(5e3,e))?!0:(t("stale port release")||(Jn=re(),p.error("SYSTEM","Stale worker port still open after SIGKILL; skipping spawn this hook event",{pid:r.pid,port:re(),fix:uc})),!1)}function Op(e,t){return`http://127.0.0.1:${e}${t}`}async function Cw(e,t){if(t<=0)return{answered:!1,version:null};try{let n=await(await Ho(Op(e.port,"/api/health"),{},t)).json();return n.pid!==e.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 Ow(e){try{process.kill(e.pid,"SIGKILL")}catch(t){p.debug("SYSTEM","Could not stop the standby worker",{pid:e.pid,error:t instanceof Error?t.message:String(t)})}tc(e.pid)}async function oU(e,t,r,n){let o=await sU(e,t,r,n);return o.kind!=="out-of-budget"&&YS(),o}async function sU(e,t,r,n){let o=ec(),s=o===null?null:await Cw(o,Ut(jt,n));if(o!==null&&s!==null&&s.answered&&s.version===t)return p.info("SYSTEM","Found the updated worker already waiting to take over",{pid:o.pid,port:o.port}),{kind:"ready",record:o};let i={kind:"failed",reason:`it did not answer its health check within ${Math.round(Ys/1e3)} seconds; the worker log has the reason`};if(o!==null&&s!==null)if(s.answered)Ow(o);else{let d=Date.parse(o.startedAt);if((Number.isFinite(d)?Date.now()-d:Number.POSITIVE_INFINITY)<wp&&oe(o.pid)){let f=Math.min(d+wp,Math.max(d+Ys,Date.now()+2e3)),g=await Cp(t,f,n,i);return g.kind==="failed"&&tc(o.pid),g}tc(o.pid)}let a=r===null?null:GS();if(a!==null&&a.buildKey===r)return Date.now()-a.launchedAtMs>=Ys?i:Cp(t,a.launchedAtMs+Ys,n,i);let c=Wn();if(!c)return{kind:"failed",reason:"Bun, which runs the worker, was not found"};if(!e)return{kind:"failed",reason:"the new worker program (worker-service.cjs) was not found"};p.info("SYSTEM","Starting the updated worker next to the running one",{runtimePath:c,scriptPath:e});let l;try{l=jo(c,e,de({...process.env,MEMINDEX_WORKER_PORT:String(re()),[HS]:"1"}),process.platform)}catch(d){return{kind:"failed",reason:`it could not be launched (${d instanceof Error?d.message:String(d)})`}}if(l===void 0)return{kind:"failed",reason:"it could not be launched"};let u=Date.now();return r!==null&&JS({buildKey:r,launchedAtMs:u}),Cp(t,u+Ys,n,i)}async function Cp(e,t,r,n){let o=Math.min(t,r??Number.POSITIVE_INFINITY);for(;Date.now()<o;){let s=ec();if(s!==null){let a=await Cw(s,Math.min(1e3,o-Date.now()));if(a.answered)return a.version===e?{kind:"ready",record:s}:(Ow(s),{kind:"failed",reason:`it reports version ${a.version??"unknown"} instead of ${e}; the installed files are mislabelled`})}let i=Math.min(200,o-Date.now());i>0&&await new Promise(a=>setTimeout(a,i))}return Date.now()<t?{kind:"out-of-budget"}:n}async function iU(e,t){try{if(!await _t(Op(e.port,""),{timeoutMs:t,fetchImpl:Qs}))return"the standby worker did not prove it holds this install's secret";let r=await Ho(Op(e.port,"/api/admin/promote"),on({method:"POST"}),t);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 aU(e){let{scriptPath:t,pluginVersion:r,workerVersion:n,buildKey:o,deadlineAt:s,outOfBudget:i}=e,a=n??"unknown",c=$S(o);if(c!==null)return p.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 l=ze();if(l===null||l.port!==re())return p.error("SYSTEM","Stale worker is serving the port but the PID file does not identify it; kill the memindex worker process manually",{port:re(),pidFilePid:l?.pid??null,pidFilePort:l?.port??null}),"failed";if(!Kn())return p.info("SYSTEM","Another launcher is starting the updated worker; the running worker keeps serving meanwhile"),"kept-old";let u=!1;try{let d=await oU(t,r,o,s);if(d.kind==="out-of-budget")return p.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 o!==null&&KS(o,d.reason),p.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(bp/6e4)} minutes, or as soon as the plugin is reinstalled.`,{pluginVersion:r,workerVersion:n,scriptPath:t}),"kept-old";if(i("stale-worker recycle"))return"kept-old";if(!await jp(s,i))return"failed";u=!0;let m=await iU(d.record,Ut(1e4,s));return m===null?(XS(),p.info("SYSTEM","The updated worker took over from the old one",{from:n,to:r,pid:d.record.pid}),"promoted"):(p.warn("SYSTEM","The updated worker could not take over the worker port; starting a new worker the usual way",{pluginVersion:r,reason:m}),"old-stopped")}finally{u||dn()}}async function Fp(e){let t=e===void 0?null:Date.now()+e,r=S=>ic(t)?(p.warn("SYSTEM","Worker check ran out of the hook budget; skipping the rest this hook event",{step:S,budgetMs:e}),!0):!1,n=()=>t===null?void 0:Ut(jt,t),o=Math.min(Date.now()+5e3,t??Number.POSITIVE_INFINITY),s=Wo(),i=null,a=null,c=!1,l=!1,u=!1,d=null,m=null,f=sn(he());if(r("health probe"))return!1;if(await Mw(o)){if(r("version probe"))return!1;let{matches:S,pluginVersion:b,workerVersion:w}=await IS(re(),s?.version??null,n());if(b!=="unknown"&&(i=b),S){if(r("readiness wait"))return!1;let I=await pn(Ut(Gn,t));if(I.outcome==="ready")return i!==null&&!ic(t)&&await nw(i,null,n()),!0;if(I.outcome==="still_booting"||I.outcome==="not_running")return p.warn("SYSTEM","Worker is healthy but not ready yet; skipping hook API call",{outcome:I.outcome,detail:I.detail}),!1;if(f)return p.warn("SYSTEM","Worker will never become ready; MEMINDEX_WORKER_AUTOSTART=false, so leaving it to whatever manages it",{outcome:I.outcome,detail:I.detail}),!1;if(m=vw(s),!Iw(I,m))return!1;d=I,p.info("SYSTEM","Worker will never become ready \u2014 recycling wedged worker",{outcome:I.outcome,detail:I.detail,version:w})}else{let I=w===null?"unreadable":OS(b,w);if(I!=="upgrade")return ow||(ow=!0,p.info("SYSTEM",I==="plugin-older"?"This plugin is older than the running worker, so the running worker stays; update this session (npx memindex update) to use the newer one":"Could not tell which of the plugin and the running worker is newer, so the running worker stays",{pluginVersion:b,workerVersion:w})),r("readiness wait")?!1:(await pn(Ut(Gn,t))).outcome==="ready";if(f)return p.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 pn(Ut(Gn,t))).outcome==="ready";if(a=Sw(s,b),QL(a,w))return p.warn("SYSTEM","Skipping repeated worker recycle: the unchanged bundle still reports a stale version; rebuild or reinstall it",{pluginVersion:b,workerVersion:w,scriptPath:s?.scriptPath}),r("readiness wait")?!1:(await pn(Ut(Gn,t))).outcome==="ready";p.info("SYSTEM","Worker version changed \u2014 starting the new worker before stopping the old one",{pluginVersion:b,workerVersion:w});let C=await aU({scriptPath:s?.scriptPath??null,pluginVersion:b,workerVersion:w,buildKey:a,deadlineAt:t,outOfBudget:r});if(C==="failed")return!1;if(C==="kept-old")return r("readiness wait")?!1:(await pn(Ut(Gn,t))).outcome==="ready";l=!0,u=C==="promoted"}if(!l&&!await jp(t,r))return!1;d!==null&&m!==null&&Tw(d,m),c=!0}if(f)return p.debug("SYSTEM","Worker not running and MEMINDEX_WORKER_AUTOSTART=false \u2014 not lazy-spawning"),!1;let g=s?.scriptPath??null;if(r("lazy spawn"))return l&&dn(),!1;let y=l||Kn();try{if(y&&!u){if(!c&&!await cU(o,t,g))return!1;let b=Wn();if(!b)return p.warn("SYSTEM","Cannot lazy-spawn worker: Bun runtime not found (PATH, BUN / BUN_PATH / BUN_INSTALL, or ~/.bun/bin)"),!1;if(!g)return p.warn("SYSTEM","Cannot lazy-spawn worker: worker-service.cjs not found in plugin/scripts"),!1;p.info("SYSTEM","Worker not running \u2014 lazy-spawning",{runtimePath:b,scriptPath:g});try{if(jo(b,g,de({...process.env,MEMINDEX_WORKER_PORT:String(re())}),process.platform)===void 0)return!1}catch(w){return w instanceof Error?p.error("SYSTEM","Lazy-spawn of worker failed",{runtimePath:b,scriptPath:g},w):p.error("SYSTEM","Lazy-spawn of worker failed (non-Error)",{runtimePath:b,scriptPath:g,error:String(w)}),!1}}else y||p.info("SYSTEM","Another launcher holds the spawn lock \u2014 skipping lazy-spawn and waiting for its worker");if(!await YL({attempts:6,backoffMs:500,deadlineAt:t}))return r("cold-boot port wait")||(p.warn("SYSTEM",y?"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)"),ze()===null&&await Ga(re(),t===null?void 0:Ut(5e3,t))&&(Jn=re(),p.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:Jn,fix:uc}))),!1}finally{y&&dn()}if(r("readiness wait"))return!1;let E=await pn(Ut(Gn,t));return E.outcome!=="ready"?(p.warn("SYSTEM","Worker lazy-spawned but did not become ready before hook readiness timeout",{outcome:E.outcome,detail:E.detail}),!1):(i!==null&&!ic(t)&&await nw(i,a,n()),!0)}async function cU(e,t,r){let n=re(),o=e-Date.now();if(o<=0)return!1;let s=await Ja(n,o);if(s==="free")return!0;if(s==="unbindable")return Rp=n,p.error("SYSTEM","Worker port cannot be bound (EACCES or EADDRNOTAVAIL) \u2014 skipping lazy-spawn",{port:n,host:mn(),fix:Ao}),!1;if(s==="indeterminate")return p.warn("SYSTEM","Worker port state could not be determined in time \u2014 skipping lazy-spawn",{port:n}),!1;let i=await Qa(n,{deadlineAt:t});return i.reclaimed?(p.info("SYSTEM","Reclaimed the worker port before lazy-spawn",{port:n,killedPids:i.killedPids}),!0):(i.reason==="out-of-budget"&&t!==null&&pU(n,r),ze()===null&&(Jn=n),p.warn("SYSTEM","Worker port is held by a listener that does not answer health \u2014 skipping lazy-spawn",{port:n,reclaimReason:i.reason,...Jn===n?{fix:uc}:{}}),!1)}function dU(e){let t;try{t=Date.now()-zs(e).mtimeMs}catch{return!1}if(t<lU)return!0;if(t>=uU)return!1;try{let{daemonPid:r}=JSON.parse(Yn(e,"utf8"));return!Number.isInteger(r)||r<=0||oe(r)}catch{return!0}}function pU(e,t){let r=se.join(W(),"reclaim-handoff.json");if(dU(r))return;let n=Wn();if(!n||!t)return;let o=i=>{N(r,{hookPid:process.pid,daemonPid:i,port:e})},s=()=>{try{Zs(r)}catch{}};try{o(null)}catch(i){p.warn("SYSTEM","Could not record the reclaim handoff; skipping detached reclaim",{port:e},i instanceof Error?i:new Error(String(i)));return}try{let i=jo(n,t,de({...process.env,MEMINDEX_WORKER_PORT:String(e)}),process.platform);if(i===void 0){s();return}if(i>0)try{o(i)}catch{}p.info("SYSTEM","Handed the port reclaim to a detached worker daemon",{port:e,daemonPid:i})}catch(i){s(),p.warn("SYSTEM","Could not launch the detached reclaim daemon",{port:e},i instanceof Error?i:new Error(String(i)))}}async function mU(e){if($n!==void 0)return $n;try{let t=fd(),n=await(await Ho(yd(be(""),t),{method:"GET",redirect:"error"},e)).json();gd(n.proof,t)&&hd(be("")),$n=xa(n.dataDir,W())==="foreign"?String(n.dataDir):null}catch(t){p.debug("SYSTEM","Could not read the worker data folder; treating the worker as ours",{error:t instanceof Error?t.message:String(t)}),$n=null}return $n!==null&&p.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:$n,dataDir:W(),port:re()}),$n}async function fU(e){return sc!==null||(sc=await Fp(e)),sc}async function gU(e){let t=Date.now()+e,r=()=>t-Date.now(),n=l=>r()>=Ap?!1:(p.debug("SYSTEM","Bounded worker startup ran out of budget",{step:l,budgetMs:e}),!0),o=await pn(Math.max(1,r()));if(o.outcome==="ready")return!0;if(o.outcome==="still_booting")return p.warn("SYSTEM","Worker is still booting; bounded startup budget spent, skipping this call",{detail:o.detail,budgetMs:e}),!1;if(!!sn(he()))return sw(t);let i=Wn(),a=JL();if(!i||!a)return!1;if(o.outcome==="failed"||o.outcome==="wedged"||o.outcome==="unresponsive"){let l=vw(Wo());if(!Iw(o,l)||(p.info("SYSTEM","Worker will never become ready \u2014 recycling wedged worker",{outcome:o.outcome,detail:o.detail}),!await jp(t,n)))return!1;Tw(o,l)}let c=Kn();try{return c&&jo(i,a,de({...process.env,MEMINDEX_WORKER_PORT:String(re())}),process.platform)===void 0?!1:await sw(t)}catch(l){return p.debug("SYSTEM","Bounded worker startup failed",{error:l instanceof Error?l.message:String(l)}),!1}finally{c&&dn()}}async function sw(e){for(;e-Date.now()>0;){let t=await pn(Math.max(1,e-Date.now()));if(t.outcome==="ready")return!0;if(t.outcome!=="not_running")return p.debug("SYSTEM","Bounded worker startup did not reach ready",{outcome:t.outcome,detail:t.detail}),!1;let r=Math.min(100,e-Date.now());r>0&&await new Promise(n=>setTimeout(n,r))}return!1}function dc(){return se.join(Z,"state")}function Pw(){return se.join(dc(),"hook-failures.json")}function Nw(){return se.join(dc(),"hook-failures.lock")}async function Hp(e=_w){let t=dc(),r=Nw(),n=RL(),o=JSON.stringify({pid:process.pid,token:n}),s=Date.now()+e;for(;Date.now()<=s;)try{return uw(t,{recursive:!0}),lw(r,o,{flag:"wx"}),n}catch(i){let a=i instanceof Error?i:new Error(String(i)),c=a.code;if(c!=="EEXIST")return p.warn("SYSTEM","Hook-failure lock unavailable; skipping failure-state update",{lockPath:r,code:c},a),null;let l;try{l=zs(r).mtimeMs}catch{continue}if(Date.now()-l>Aw){let u;try{u=zs(r).mtimeMs}catch{continue}if(u===l)try{Zs(r);continue}catch{}}await new Promise(u=>setTimeout(u,yU))}return p.warn("SYSTEM","Timed out waiting for hook-failure lock; skipping failure-state update",{lockPath:r,waitMs:e}),null}function Wp(e){let t=Nw();try{if(JSON.parse(Yn(t,"utf-8")).token!==e)return;Zs(t)}catch{}}function SU(e){let t=JSON.parse(e);return{consecutiveFailures:typeof t.consecutiveFailures=="number"&&Number.isFinite(t.consecutiveFailures)?Math.max(0,Math.floor(t.consecutiveFailures)):0,lastFailureAt:typeof t.lastFailureAt=="number"&&Number.isFinite(t.lastFailureAt)?t.lastFailureAt:0,thresholdTripped:t.thresholdTripped===!0,notifiedSessionIds:Array.isArray(t.notifiedSessionIds)?t.notifiedSessionIds.filter(r=>typeof r=="string").slice(-Rw):void 0}}function qs(){try{return SU(Yn(Pw(),"utf-8"))}catch{return{consecutiveFailures:0,lastFailureAt:0,thresholdTripped:!1}}}function Bp(e){let t=dc(),r=Pw(),n=`${r}.tmp`;try{return Vn(t)||uw(t,{recursive:!0}),lw(n,JSON.stringify(e),"utf-8"),_L(n,r),!0}catch(o){return p.debug("SYSTEM","Failed to persist hook-failure counter",{error:o instanceof Error?o.message:String(o)}),!1}}function wU(){try{let t=he().MEMINDEX_HOOK_FAIL_LOUD_THRESHOLD,r=parseInt(t,10);if(Number.isFinite(r)&&r>=1)return r}catch{}return hU}function Dw(e){let t=Rp!==null?`The worker cannot bind port ${Rp} on ${mn()}: the system refuses it (EACCES or EADDRNOTAVAIL). ${Ao}.`:Jn!==null?`Port ${Jn} is held by an unreachable process that no PID file claims, so the worker cannot bind it. ${uc}.`:"Run `npx memindex restart`; if it keeps failing, run `npx memindex doctor`.";return`memindex worker unreachable for ${e} consecutive hooks \u2014 memory features are degraded, but your prompts are not blocked. ${t}`}async function Vs(){if(bU){if(aw)return qs().consecutiveFailures;aw=!0}let e=await Hp();if(e===null)return qs().consecutiveFailures;let t,r=!1;try{let n=qs();t={consecutiveFailures:n.consecutiveFailures+1,lastFailureAt:Date.now(),thresholdTripped:n.thresholdTripped,notifiedSessionIds:n.notifiedSessionIds};let o=wU();r=t.consecutiveFailures>=o&&!t.thresholdTripped,r&&(t.thresholdTripped=!0);let s=Bp(t);r=r&&s}finally{Wp(e)}return r&&(await Pr("hook_failed",{...iw!==null?{hook_type:iw}:{},error_mode:"worker_unavailable",consecutive_failures:t.consecutiveFailures,threshold_tripped:!0}),Cr(`${Dw(t.consecutiveFailures)}
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "MemIndex (Persistent Memory)",
|
|
4
4
|
"description": "OpenClaw plugin for MemIndex. Records observations from embedded runner sessions and streams them to messaging channels.",
|
|
5
5
|
"kind": "memory",
|
|
6
|
-
"version": "1.7.
|
|
6
|
+
"version": "1.7.1",
|
|
7
7
|
"license": "Apache-2.0",
|
|
8
8
|
"author": "memindex",
|
|
9
9
|
"homepage": "https://memindex.ai",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "memindex",
|
|
3
|
-
"version": "1.7.
|
|
3
|
+
"version": "1.7.1",
|
|
4
4
|
"description": "Memory for AI coding agents: what you decided, fixed and tried comes back in your next session. Works with Claude Code, Codex, Cursor, OpenCode, Windsurf and more.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"memory",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "memindex",
|
|
3
|
-
"version": "1.7.
|
|
3
|
+
"version": "1.7.1",
|
|
4
4
|
"description": "Memory for AI coding agents: what you decided, fixed and tried comes back in your next session. Works with Claude Code, Codex, Cursor, OpenCode, Windsurf and more.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Imogen Labs"
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "memindex",
|
|
3
|
-
"version": "1.7.
|
|
3
|
+
"version": "1.7.1",
|
|
4
4
|
"description": "Memory for AI coding agents: what you decided, fixed and tried comes back in your next session. Works with Claude Code, Codex, Cursor, OpenCode, Windsurf and more.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Imogen Labs",
|