claude-mem 13.24.19 → 13.24.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.codex-plugin/plugin.json +1 -1
- package/README.md +1 -1
- package/dist/npx-cli/index.js +1 -1
- package/openclaw/openclaw.plugin.json +1 -1
- package/package.json +2 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/.codex-plugin/plugin.json +1 -1
- package/plugin/package.json +1 -1
- package/plugin/scripts/context-generator.cjs +4 -1
- package/plugin/scripts/context-generator.cjs.map +6 -0
- package/plugin/scripts/mcp-server.cjs +6 -3
- package/plugin/scripts/mcp-server.cjs.map +6 -0
- package/plugin/scripts/server-service.cjs +68 -67
- package/plugin/scripts/server-service.cjs.map +6 -0
- package/plugin/scripts/transcript-watcher.cjs +5 -2
- package/plugin/scripts/transcript-watcher.cjs.map +6 -0
- package/plugin/scripts/worker-service.cjs +31 -22
- package/plugin/scripts/worker-service.cjs.map +6 -0
- package/plugin/sqlite/SessionStore.js +16 -5
- package/plugin/sqlite/SessionStore.js.map +6 -0
- package/plugin/sqlite/observations/files.js +5 -2
- package/plugin/sqlite/observations/files.js.map +6 -0
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
var __CM_FILENAME__ = typeof __filename !== "undefined" ? __filename : require("node:path").resolve(process.argv[1] || "");
|
|
3
|
+
var __CM_DIRNAME__ = typeof __dirname !== "undefined" ? __dirname : require("node:path").dirname(__CM_FILENAME__);
|
|
2
4
|
"use strict";var Pb=Object.create;var Qi=Object.defineProperty;var $b=Object.getOwnPropertyDescriptor;var Tb=Object.getOwnPropertyNames;var Rb=Object.getPrototypeOf,Ob=Object.prototype.hasOwnProperty;var ln=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var w=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},dd=(e,t)=>{for(var r in t)Qi(e,r,{get:t[r],enumerable:!0})},Ib=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Tb(t))!Ob.call(e,o)&&o!==r&&Qi(e,o,{get:()=>t[o],enumerable:!(n=$b(t,o))||n.enumerable});return e};var Lt=(e,t,r)=>(r=e!=null?Pb(Rb(e)):{},Ib(t||!e||!e.__esModule?Qi(r,"default",{value:e,enumerable:!0}):r,e));function Cb(e){return(Ab??process.stderr.write.bind(process.stderr))(e)}function jt(e){Cb(e)}var Ab,Co=ln(()=>{"use strict";Ab=null});function zb(e){return e.replace(/^\uFEFF/,"")}function or(e){return JSON.parse(zb(e))}function Db(e){(0,V.existsSync)(e)||(0,V.mkdirSync)(e,{recursive:!0})}function dn(e,t){let r=e;try{if((0,V.lstatSync)(e).isSymbolicLink())try{r=(0,V.realpathSync)(e)}catch(u){let l=u instanceof Error?u:new Error(String(u));jt(`claude-mem: realpathSync failed for ${e}, resolving symlink manually: ${l.message}
|
|
3
5
|
`);let d=(0,V.readlinkSync)(e);r=(0,yt.resolve)((0,yt.dirname)(e),d)}}catch(u){let l=u.code;if(l!=="ENOENT"&&l!=="ENOTDIR")throw u}Db((0,yt.dirname)(r));let n=(0,yt.dirname)(r),o=(0,yt.basename)(r),s=(0,yt.join)(n,`.${o}.${process.pid}.${(0,fd.randomBytes)(6).toString("hex")}.tmp`),i=Buffer.from(JSON.stringify(t,null,2)+`
|
|
4
6
|
`,"utf-8"),a;try{a=(0,V.statSync)(r).mode&511}catch{}let c;try{c=a!==void 0?(0,V.openSync)(s,"w",a):(0,V.openSync)(s,"w");let u=0;for(;u<i.length;){let l=(0,V.writeSync)(c,i,u,i.length-u);if(l===0)throw new Error(`writeSync stalled at ${u}/${i.length} bytes`);u+=l}if((0,V.fsyncSync)(c),(0,V.closeSync)(c),c=void 0,(0,V.renameSync)(s,r),!Mb){let l;try{l=(0,V.openSync)(n,"r"),(0,V.fsyncSync)(l)}catch(d){let f=d instanceof Error?d:new Error(String(d));jt(`claude-mem: directory fsync failed for ${n}: ${f.message}
|
|
5
|
-
`)}finally{if(l!==void 0)try{(0,V.closeSync)(l)}catch{}}}}catch(u){if(c!==void 0)try{(0,V.closeSync)(c)}catch{}try{(0,V.unlinkSync)(s)}catch{}throw u}}var V,fd,yt,Mb,Pr=ln(()=>{"use strict";V=require("fs"),fd=require("crypto"),yt=require("path");Co();Mb=process.platform==="win32"});function Mo(e,t=process.platform,r=(0,pd.homedir)()){return typeof e!="string"||e.length===0?e:e==="~"?r:e.startsWith("~/")||t==="win32"&&e.startsWith("~\\")?(0,md.join)(r,e.slice(2)):e}var pd,md,ea=ln(()=>{"use strict";pd=require("os"),md=require("path")});function Nb(){return typeof
|
|
7
|
+
`)}finally{if(l!==void 0)try{(0,V.closeSync)(l)}catch{}}}}catch(u){if(c!==void 0)try{(0,V.closeSync)(c)}catch{}try{(0,V.unlinkSync)(s)}catch{}throw u}}var V,fd,yt,Mb,Pr=ln(()=>{"use strict";V=require("fs"),fd=require("crypto"),yt=require("path");Co();Mb=process.platform==="win32"});function Mo(e,t=process.platform,r=(0,pd.homedir)()){return typeof e!="string"||e.length===0?e:e==="~"?r:e.startsWith("~/")||t==="win32"&&e.startsWith("~\\")?(0,md.join)(r,e.slice(2)):e}var pd,md,ea=ln(()=>{"use strict";pd=require("os"),md=require("path")});function Nb(){return typeof __CM_DIRNAME__<"u"?__CM_DIRNAME__:(0,Y.dirname)((0,hd.fileURLToPath)(qb.url))}function sr(){if(process.env.CLAUDE_MEM_DATA_DIR)return Mo(process.env.CLAUDE_MEM_DATA_DIR);let e=(0,Y.join)((0,ta.homedir)(),".claude-mem"),t=(0,Y.join)(e,"settings.json");try{if((0,fn.existsSync)(t)){let r=or((0,fn.readFileSync)(t,"utf-8")),n=r.env??r;if(n.CLAUDE_MEM_DATA_DIR)return Mo(n.CLAUDE_MEM_DATA_DIR)}}catch{}return e}var Y,ta,fn,hd,qb,_A,ce,Lb,jb,zo,Ub,Do,gd,yA,Fb,SA,qe,Ze=ln(()=>{"use strict";Y=require("path"),ta=require("os"),fn=require("fs"),hd=require("url");Pr();ea();ea();qb={};_A=Nb();ce=sr(),Lb=(0,Y.join)((0,ta.homedir)(),".claude"),jb=process.env.CLAUDE_CONFIG_DIR||Lb,zo=(0,Y.join)(jb,"plugins","marketplaces","thedotmack"),Ub=(0,Y.join)(ce,"logs"),Do=(0,Y.join)(ce,"settings.json"),gd="claude-mem.db",yA=(0,Y.join)(ce,gd),Fb=(0,Y.join)(ce,"observer-sessions"),SA=(0,Y.basename)(Fb),qe={dataDir:()=>ce,workerPid:()=>(0,Y.join)(ce,"worker.pid"),serverPid:()=>(0,Y.join)(ce,".server-beta.pid"),serverPort:()=>(0,Y.join)(ce,".server-beta.port"),serverRuntime:()=>(0,Y.join)(ce,".server-beta.runtime.json"),settings:()=>(0,Y.join)(ce,"settings.json"),database:()=>(0,Y.join)(ce,gd),chroma:()=>(0,Y.join)(ce,"chroma"),combinedCerts:()=>(0,Y.join)(ce,"combined_certs.pem"),transcriptsConfig:()=>(0,Y.join)(ce,"transcript-watch.json"),transcriptsState:()=>(0,Y.join)(ce,"transcript-watch-state.json"),corpora:()=>(0,Y.join)(ce,"corpora"),supervisorRegistry:()=>(0,Y.join)(ce,"supervisor.json"),envFile:()=>(0,Y.join)(ce,".env"),logsDir:()=>Ub}});var kt,_d,na,ra,oa,_,ne=ln(()=>{"use strict";kt=require("fs"),_d=require("path");Ze();Co();Pr();na=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.WARN=2]="WARN",s[s.ERROR=3]="ERROR",s[s.SILENT=4]="SILENT",s))(na||{}),ra=null,oa=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){if(!this.logFileInitialized){this.logFileInitialized=!0;try{let t=qe.logsDir();(0,kt.existsSync)(t)||(0,kt.mkdirSync)(t,{recursive:!0});let r=new Date().toISOString().split("T")[0];this.logFilePath=(0,_d.join)(t,`claude-mem-${r}.log`)}catch(t){console.error("[LOGGER] Failed to initialize log file:",t instanceof Error?t.message:String(t)),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let t=qe.settings();if((0,kt.existsSync)(t)){let r=(0,kt.readFileSync)(t,"utf-8"),o=(or(r).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=na[o]??1}else this.level=1}catch(t){console.error("[LOGGER] Failed to load log level from settings:",t instanceof Error?t.message:String(t)),this.level=1}return this.level}formatData(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return t.toString();if(typeof t=="object"){if(t instanceof Error)return this.getLevel()===0?`${t.message}
|
|
6
8
|
${t.stack}`:t.message;if(Array.isArray(t))return`[${t.length} items]`;let r=Object.keys(t);return r.length===0?"{}":r.length<=3?JSON.stringify(t):`{${r.length} keys: ${r.slice(0,3).join(", ")}...}`}return String(t)}formatTool(t,r){if(!r)return t;let n=r;if(typeof r=="string")try{n=JSON.parse(r)}catch{n=r}if(t==="Bash"&&n.command)return`${t}(${n.command})`;if(n.file_path)return`${t}(${n.file_path})`;if(n.notebook_path)return`${t}(${n.notebook_path})`;if(t==="Glob"&&n.pattern)return`${t}(${n.pattern})`;if(t==="Grep"&&n.pattern)return`${t}(${n.pattern})`;if(n.url)return`${t}(${n.url})`;if(n.query)return`${t}(${n.query})`;if(t==="Task"){if(n.subagent_type)return`${t}(${n.subagent_type})`;if(n.description)return`${t}(${n.description})`}return t==="Skill"&&n.skill?`${t}(${n.skill})`:t==="LSP"&&n.operation?`${t}(${n.operation})`:t}formatTimestamp(t){let r=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),o=String(t.getDate()).padStart(2,"0"),s=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0"),a=String(t.getSeconds()).padStart(2,"0"),c=String(t.getMilliseconds()).padStart(3,"0");return`${r}-${n}-${o} ${s}:${i}:${a}.${c}`}log(t,r,n,o,s){if(t<this.getLevel())return;this.ensureLogFileInitialized();let i=this.formatTimestamp(new Date),a=na[t].padEnd(5),c=r.padEnd(6),u="";o?.correlationId?u=`[${o.correlationId}] `:o?.sessionId&&(u=`[session-${o.sessionId}] `);let l="";if(s!=null)if(s instanceof Error)l=this.getLevel()===0?`
|
|
7
9
|
${s.message}
|
|
8
10
|
${s.stack}`:` ${s.message}`;else if(this.getLevel()===0&&typeof s=="object")try{l=`
|
|
@@ -79,7 +81,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
79
81
|
`)){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?o:null})}return t}async function bO(){let e;try{e=(await Il("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 _.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 Oi(e){let t=await _O(),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 EO=5e3,vO=1e3,wO=qe.supervisorRegistry();function pe(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:(_.debug("SYSTEM","PID check failed",{pid:e,code:r}),!1)}return _.warn("SYSTEM","PID check threw non-Error",{pid:e,error:String(t)}),!1}}async function Ai(e,t){let r=Date.now()+t;for(;Date.now()<r;){if(e.every(n=>!pe(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function Dl(e){if(!e||!pe(e.pid))return!1;if(!e.startToken)return!0;let t=rr(e.pid);if(t===null)return!0;let r=t===e.startToken;return r||_.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:e.pid,stored:e.startToken,current:t}),r}var zl=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(t=wO){this.registryPath=t}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,Dt.mkdirSync)(Ml.default.dirname(this.registryPath),{recursive:!0}),!(0,Dt.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Dt.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[o,s]of Object.entries(n))this.entries.set(o,s)}catch(r){r instanceof Error?_.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):_.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let t=this.pruneDeadEntries();t>0&&_.info("SYSTEM","Removed dead processes from supervisor registry",{removed:t}),this.persist()}register(t,r,n){this.initialize(),this.entries.set(t,r),n&&this.runtimeProcesses.set(t,n),this.persist()}unregister(t){this.initialize();let r=this.entries.get(t);this.entries.delete(t),this.runtimeProcesses.delete(t),this.persist(),r?.type==="sdk"&&Cl()}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)pe(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)Cl();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;_.info("SYSTEM",`Reaping ${r.length} process(es) for session ${t}`,{sessionId:n,pids:r.map(a=>a.pid)});let o=r.filter(a=>pe(a.pid)),s=new Map(o.map(a=>[a.pid,rr(a.pid)]));for(let a of o)try{process.platform==="win32"?await gt(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"&&_.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):_.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}await Ai(o,EO);let i=o.filter(a=>pe(a.pid));for(let a of i){_.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(!zt(a.pid,c)){_.warn("SYSTEM","Skipping SIGKILL: session process PID was reused during the grace window",{pid:a.pid,sessionId:n});continue}try{process.platform==="win32"?await gt(a.pid,{expectedStartToken:c}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(u){u instanceof Error?u.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},u):_.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(u)})}}if(i.length>0){let a=Date.now()+vO;for(;Date.now()<a&&i.filter(u=>pe(u.pid)).length!==0;)await new Promise(u=>setTimeout(u,100))}for(let a of r)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of r)a.type==="sdk"&&Cl();return _.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())};(0,Dt.mkdirSync)(Ml.default.dirname(this.registryPath),{recursive:!0}),(0,Dt.writeFileSync)(this.registryPath,JSON.stringify(t,null,2))}},Al=null;function Ci(){return Al||(Al=new zl),Al}var Y1=180*1e3,kO=[];function Cl(){let e=kO.shift();e&&e.notify()}var on=require("fs");ne();Ze();var xO=qe.workerPid();async function gS(e){let t=e.currentPid??process.pid,r=e.pidFilePath??xO,n=e.registry.getAll(),o=[...n].filter(c=>c.pid!==t).sort((c,u)=>Date.parse(u.startedAt)-Date.parse(c.startedAt)),s=new Map,i=new Map;for(let c of o){if(!pe(c.pid)){e.registry.unregister(c.id);continue}i.set(c.id,rr(c.pid)),s.set(c.id,await Oi(c.pid));try{await hS(c,"SIGTERM")}catch(u){u instanceof Error?_.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:c.pid,pgid:c.pgid,type:c.type},u):_.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(u)})}}await Ai(o,5e3);let a=o.filter(c=>pe(c.pid)||(s.get(c.id)??[]).some(u=>pe(u.pid)));for(let c of a){let u=zt(c.pid,i.get(c.id)??null);u||_.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:c.pid,type:c.type});try{u&&await hS(c,"SIGKILL")}catch(l){l instanceof Error?_.debug("SYSTEM","Failed to force kill child process",{pid:c.pid,pgid:c.pgid,type:c.type},l):_.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(l)})}finally{PO(s.get(c.id)??[],c.pid)}}await Ai(a,1e3);for(let c of o)e.registry.unregister(c.id);for(let c of n.filter(u=>u.pid===t))e.registry.unregister(c.id);_S(r,t),e.registry.pruneDeadEntries()}function _S(e,t,r=!1){if(!(0,on.existsSync)(e))return;let n=null;try{let i=JSON.parse((0,on.readFileSync)(e,"utf-8"));n=typeof i.pid=="number"?i.pid:null}catch(i){_.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||!pe(n);if(!o&&!(r&&s)){_.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{(0,on.rmSync)(e,{force:!0})}catch(i){i instanceof Error?_.debug("SYSTEM","Failed to remove PID file",{pidFilePath:e},i):_.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:e,error:String(i)})}}function PO(e,t){for(let{pid:r,startToken:n}of e)if(!(r===t||!pe(r))){if(!zt(r,n)){_.debug("SYSTEM","Skipping reap: PID was recycled during the grace window",{pid:r,rootPid:t});continue}try{process.kill(r,"SIGKILL"),_.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"&&_.warn("SYSTEM","Failed to reap orphaned descendant during shutdown cascade",{pid:r,rootPid:t,errno:s})}}}async function hS(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 gt(r,{signalMode:"immediate"});return}try{process.kill(r,t)}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}return}await gt(r)}ne();var yS=3e4,sn=null;function $O(){let t=Ci().pruneDeadEntries();t>0&&_.info("SYSTEM",`Health check: pruned ${t} dead process(es) from registry`)}function SS(){sn===null&&(sn=setInterval($O,yS),sn.unref(),_.debug("SYSTEM","Health checker started",{intervalMs:yS}))}function bS(){sn!==null&&(clearInterval(sn),sn=null,_.debug("SYSTEM","Health checker stopped"))}var ES=require("child_process"),vS=require("util");ne();var TO=(0,vS.promisify)(ES.execFile),RO=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/;function OO(e){let t=[];for(let r of e.split(`
|
|
80
82
|
`)){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 IO(){let e=await TO("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return OO(e.stdout)}function AO(e,t){let r=e.filter(i=>RO.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 wS(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??IO,o=e.isAlive??pe,s=e.killTree??(p=>gt(p,{signalMode:"graceful"})),i=e.selfPid??process.pid,a;try{a=await n()}catch(p){return _.warn("PROCESS","Orphaned chroma-mcp sweep skipped: cannot read the process table",{error:p instanceof Error?p.message:String(p)}),r.skipped="unreadable",r}let{matched:c,roots:u,orphans:l}=AO(a,{isAlive:o,selfPid:i});if(r.matched=c.length,r.trees=u.length,r.orphans=l.length,l.length===0)return _.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:r.matched,trees:r.trees}),r;_.warn("PROCESS","Reaping orphaned chroma-mcp trees left by dead workers",{orphans:l.length,roots:l.map(p=>p.pid)});let d=new Set,f=8;for(let p=0;p<l.length;p+=f){let m=l.slice(p,p+f);(await Promise.allSettled(m.map(g=>s(g.pid)))).forEach((g,y)=>{let E=m[y];g.status==="fulfilled"?(r.killed+=1,d.add(E.pid)):(r.failed+=1,_.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:E.pid,ppid:E.ppid,error:g.reason instanceof Error?g.reason.message:String(g.reason)}))})}if(e.registry)for(let p of e.registry.getAll())p.type==="chroma"&&d.has(p.pid)&&(e.registry.unregister(p.id),r.unregistered+=1);return _.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:r.orphans,killed:r.killed,failed:r.failed,unregistered:r.unregistered}),r}Ze();var CO=qe.workerPid(),Nl=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(),Mi({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,wS({registry:this.registry}).catch(r=>{_.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),SS()}configureSignalHandlers(t){if(this.shutdownHandler=t,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){_.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,_.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(o){o instanceof Error?_.error("SYSTEM","Error during shutdown",{},o):_.error("SYSTEM","Error during shutdown (non-Error)",{error:String(o)});try{await this.stop()}catch(s){s instanceof Error?_.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):_.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",()=>{_.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}bS(),this.stopPromise=gS({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){this.registry.unregister(t)}getRegistry(){return this.registry}},MO=new Nl(Ci());function Ll(){return MO}function Mi(e={}){let t=e.pidFilePath??CO;if(!(0,vr.existsSync)(t))return"missing";let r=null;try{r=JSON.parse((0,vr.readFileSync)(t,"utf-8"))}catch(o){return o instanceof Error?_.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:t},o):_.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:t,error:String(o)}),(0,vr.rmSync)(t,{force:!0}),"invalid"}return Dl(r)&&r?((e.logAlive??!0)&&_.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(_.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,vr.rmSync)(t,{force:!0}),"stale")}Co();Ze();Pr();ne();ne();var Nt=Lt(require("path"),1),PS=require("os"),Ie=require("fs"),vo=require("child_process");ne();ne();ne();Ze();var rF=qe.dataDir(),kS=qe.workerPid(),xS="Bun runtime not found \u2014 install from https://bun.sh and ensure it is on PATH or set BUN env var. The worker daemon requires Bun because it uses bun:sqlite.";function zO(e){try{return(0,Ie.realpathSync)(e)}catch{return null}}function jl(e){return e?/(^|[\\/])bun(\.exe)?$/i.test(e.trim()):!1}function DO(e,t){let r=t==="win32"?`where ${e}`:`which ${e}`,n;try{n=(0,vo.execSync)(r,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(s){return s instanceof Error?_.debug("SYSTEM",`Binary lookup failed for ${e}`,{command:r},s):_.debug("SYSTEM",`Binary lookup failed for ${e}`,{command:r},new Error(String(s))),null}return n.split(/\r?\n/).map(s=>s.trim()).find(s=>s.length>0)||null}var Ul;function Fl(e={}){let t=Object.keys(e).length===0;if(t&&Ul!==void 0)return Ul;let r=NO(e);return t&&r!==null&&(Ul=r),r}function NO(e){let t=e.platform??process.platform,r=e.execPath??process.execPath;if(jl(r))return r;let n=e.env??process.env,o=e.homeDirectory??(0,PS.homedir)(),s=e.pathExists??Ie.existsSync,i=e.lookupInPath??DO,a=e.realpath??zO,c=t==="win32"?[n.BUN,n.BUN_PATH,Nt.default.join(o,".bun","bin","bun.exe"),Nt.default.join(o,".bun","bin","bun"),n.USERPROFILE?Nt.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?Nt.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?Nt.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0,n.npm_config_prefix?Nt.default.join(n.npm_config_prefix,"bun.exe"):void 0]:[n.BUN,n.BUN_PATH,Nt.default.join(o,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun",n.npm_config_prefix?Nt.default.join(n.npm_config_prefix,"bin","bun"):void 0];for(let d of c){let f=d?.trim();if(f&&(jl(f)&&s(f)||f.toLowerCase()==="bun"))return f}let u=i("bun",t)?.trim();if(!u||!jl(u))return null;let l=a(u)??u;return s(l)?l:null}function wr(e){return process.platform==="win32"?Math.round(e*2):e}function $S(){let e=qe.dataDir();return(0,Ie.mkdirSync)(e,{recursive:!0}),e}function LO(e,t,r=$S()){let n=o=>o.replace(/'/g,"''");return`Start-Process -FilePath '${n(e)}' -ArgumentList @('"${n(t)}"','--daemon') -WorkingDirectory '${n(r)}' -WindowStyle Hidden`}var jO=5e3,UO=8;function FO(e,t,r){return e?.code!=="ETIMEDOUT"?!1:t<r/2}function TS(e,t=wr(jO)){let r=Fl();if(!r)return;let n=()=>{let a=Date.now();try{return{result:(0,vo.spawnSync)(r,[e,"status"],{encoding:"utf-8",timeout:t,windowsHide:!0,env:Er({...process.env})}),elapsedMs:Date.now()-a}}catch(c){let u=c instanceof Error?c:new Error(String(c));_.debug("SYSTEM","Worker boot probe could not be launched",{scriptPath:e},u);return}},o=n();if(o===void 0||FO(o.result.error,o.elapsedMs,t)&&(_.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,UO).join(`
|
|
81
83
|
`)}function RS(e,t,r={}){Ll().assertCanSpawn("worker daemon");let n=Er({...process.env,CLAUDE_MEM_WORKER_PORT:String(t),...r}),o=Fl();if(!o){_.error("SYSTEM",xS);return}if(process.platform==="win32"){let l=LO(o,e),d=Buffer.from(l,"utf16le").toString("base64");try{return(0,vo.execSync)(`powershell -NoProfile -EncodedCommand ${d}`,{stdio:"ignore",windowsHide:!0,env:n}),0}catch(f){let p=f instanceof Error?f:new Error(String(f));_.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:o},p);return}}let s="/usr/bin/setsid",i=(0,Ie.existsSync)(s),a=i?s:o,u=xi(a,i?[o,e,"--daemon"]:[e,"--daemon"],{detached:!0,stdio:"ignore",cwd:$S(),env:n});if(u.on("error",l=>{_.error("SYSTEM",xS,{runtimePath:o,execPath:a},l)}),u.pid!==void 0)return u.unref(),u.pid}function OS(){try{if(!(0,Ie.existsSync)(kS))return;let e=new Date;(0,Ie.utimesSync)(kS,e,e)}catch{}}function zi(){return Mi({logAlive:!1})}var IS=Lt(require("net"),1);ne();Ze();function ql(){return ht.loadFromFile(Do).CLAUDE_MEM_WORKER_HOST}function AS(e){return e.startsWith("[")&&e.endsWith("]")?e:e.includes(":")?`[${e}]`:e}var Zl=5e3;async function qO(e,t,r="GET",n=Zl){let o=await fetch(`http://${AS(ql())}:${e}${t}`,{method:r,signal:AbortSignal.timeout(Math.max(1,n))}),s="";try{s=await o.text()}catch{}return{ok:o.ok,statusCode:o.status,body:s}}async function Hl(e,t=Zl){if(process.platform==="win32")try{let r=await fetch(`http://${AS(ql())}:${e}/api/health`,{signal:AbortSignal.timeout(Math.max(1,t))});if(r.ok)return!0;_.debug("SYSTEM","Windows health check returned non-ok; falling through to socket probe",{port:e,status:r.status})}catch(r){r instanceof Error?_.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:e,message:r.message}):_.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:e,error:String(r)})}return new Promise(r=>{let n=IS.default.createServer(),o=ql();n.once("error",s=>{s.code==="EADDRINUSE"?r(!0):r(!1)}),n.once("listening",()=>{n.close(()=>r(!1))}),n.listen(e,o)})}async function CS(e,t,r,n){let o=Date.now()+r;for(;Date.now()<o;){try{let i=o-Date.now();if((await qO(e,t,"GET",Math.min(Zl,i))).ok)return!0}catch(i){i instanceof Error?_.debug("SYSTEM",n,{},i):_.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 wo(e,t=3e4){return CS(e,"/api/health",t,"Service not ready yet, will retry")}function ko(e,t=3e4){return CS(e,"/api/readiness",t,"Worker not ready yet, will retry")}ne();var Di=require("path"),nt=require("fs");Ze();ne();var ZO=9e4;function MS(){return(0,Di.join)(sr(),"spawn.lock")}function Wl(){let e=MS(),t=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return(0,nt.mkdirSync)((0,Di.dirname)(e),{recursive:!0}),(0,nt.writeFileSync)(e,t,{flag:"wx"}),!0}catch(n){let o=n instanceof Error?n:new Error(String(n)),s=o.code;if(s!=="EEXIST")return _.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=(0,nt.statSync)(e).mtimeMs}catch{continue}if(Date.now()-i<=ZO)return!1;let a;try{a=(0,nt.statSync)(e).mtimeMs}catch{continue}if(a!==i)return!1;try{(0,nt.unlinkSync)(e)}catch{return!1}}return!1}function Vl(){let e=MS();try{if(JSON.parse((0,nt.readFileSync)(e,"utf-8")).pid!==process.pid)return;(0,nt.unlinkSync)(e)}catch{}}Pr();function NS(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;_.warn("SYSTEM",`Invalid ${e}, using default`,{value:n,min:r.min,max:r.max})}return t}var NF=NS("CLAUDE_MEM_HEALTH_TIMEOUT_MS",tr(Oe.HEALTH_CHECK),{min:500,max:3e5}),LF=NS("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",tr(Oe.HOOK_READINESS_WAIT),{min:0,max:3e5}),HO={min:500,max:3e5};function LS(e=process.env){let t=e.CLAUDE_MEM_FETCH_VERBOSE;if(t===void 0)return!1;let r=t.trim().toLowerCase();return r==="1"||r==="true"||r==="on"||r==="yes"}function WO(e){return LS()?{...e,verbose:!0}:e}function VO(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 KO(e,t,r){let n=typeof t.method=="string"?t.method:"GET",o=VO(r),s=JSON.stringify(o);_.warn("SYSTEM","Worker IPC fetch failed",{url:e,method:n},s),jt(`[claude-mem] fetch verbose: ${n} ${e} ${s}
|
|
82
|
-
`)}async function jS(e,t={}){let r=WO(t);try{return await fetch(e,r)}catch(n){throw LS()&&KO(e,t,n),n}}async function Kl(e,t={},r){try{return await jS(e,{...t,signal:AbortSignal.timeout(r)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new Error(`Request timed out after ${r}ms`):n}}var Ni=null,Li=null,ji=null,Ui=null;function BO(){return Ae.default.join(ht.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function Bl(){return ji!==null||(ji=ht.loadFromFile(BO())),ji}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 GO(e,t,r){let n=process.env[e];if(n!==void 0){let i=zS(n,r);return i!==null?i:(_.warn("SYSTEM",`Invalid ${e}, using default`,{value:n,min:r.min,max:r.max}),t)}let o=Bl()[e],s=zS(o,r);return s!==null?s:(_.warn("SYSTEM",`Invalid ${e} in settings.json, using default`,{value:o,min:r.min,max:r.max}),t)}function Gl(){if(Ni!==null)return Ni;let e=Bl();return Ni=parseInt(e.CLAUDE_MEM_WORKER_PORT,10),Ni}function YO(){return Li!==null||(Li=Bl().CLAUDE_MEM_WORKER_HOST),Li}function JO(){return Ui!==null||(Ui=GO("CLAUDE_MEM_API_TIMEOUT_MS",tr(Oe.API_REQUEST),HO)),Ui}function XO(e){return e.startsWith("[")&&e.endsWith("]")?e:e.includes(":")?`[${e}]`:e}function QO(e){return`http://${XO(YO())}:${Gl()}${e}`}function Fi(e,t={}){let r=t.method??"GET",n=t.timeoutMs??JO(),o=QO(e),s={method:r};return t.headers&&(s.headers=t.headers),t.body&&(s.body=t.body),n>0?Kl(o,s,n):jS(o,s)}function US(e){let t=(0,Ce.existsSync)(Ae.default.join(e,"plugin","scripts"))?Ae.default.join(e,"plugin"):e;return Ae.default.join(t,"scripts","worker-service.cjs")}function eI(e,t){let r=d=>{let f=d.split("-")[0].split(".");return[parseInt(f[0],10)||0,parseInt(f[1],10)||0,parseInt(f[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 u=e.includes("-")?1:0,l=t.includes("-")?1:0;return u!==l?u-l:e<t?1:e>t?-1:0}function tI(e=Ae.default.join(Ae.default.dirname(Ae.default.dirname(zo)),"cache","thedotmack","claude-mem")){try{return(0,Ce.readdirSync)(e).filter(t=>/^\d/.test(t)).map(t=>Ae.default.join(e,t)).filter(t=>{try{if(!(0,Ce.statSync)(t).isDirectory())return!1}catch{return!1}return!(0,Ce.existsSync)(Ae.default.join(t,".orphaned_at"))}).map(t=>({scriptPath:US(t),version:Ae.default.basename(t)}))}catch{return[]}}function DS(e){try{let t=JSON.parse((0,Ce.readFileSync)(e,"utf-8"));return typeof t.version=="string"?t.version:null}catch(t){let r=t.code;return r!=="ENOENT"&&_.debug("SYSTEM","Could not read package version for worker resolution",{packageJsonPath:e,code:r}),null}}function rI(){let e=process.env.CLAUDE_MEM_WORKER_SCRIPT_PATH?.trim();if(e){if((0,Ce.existsSync)(e))return{scriptPath:e,version:null};_.debug("SYSTEM","Ignoring missing CLAUDE_MEM_WORKER_SCRIPT_PATH override",{override:e})}let t=[...tI(),{scriptPath:US(Ae.default.join(zo,"plugin")),version:DS(Ae.default.join(zo,"package.json"))},{scriptPath:Ae.default.join(process.cwd(),"plugin","scripts","worker-service.cjs"),version:DS(Ae.default.join(process.cwd(),"package.json"))}];return nI(t)}function nI(e){let t=e.filter(r=>(0,Ce.existsSync)(r.scriptPath));return t.length===0?null:(t.sort((r,n)=>r.version===null&&n.version===null?0:r.version===null?1:n.version===null?-1:eI(r.version,n.version)),t[0])}function FS(){return rI()?.scriptPath??null}var oI=1e3;var sI=5e3,jF=sI+oI;var Yl=Lt(require("path"),1),ot=require("fs");ne();var ZS=require("node:child_process"),HS=require("node:util");ne();Ze();var WS=(0,HS.promisify)(ZS.execFile),iI=/^(uv|uvx|python|chroma-mcp)(\.exe)?$/i;function qS(e){return iI.test(e.trim())}function aI(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]==="/"}async function cI(){try{let e=await WS("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:3e4,windowsHide:!0,maxBuffer:33554432}),t=JSON.parse(e.stdout),r=Array.isArray(t)?t:t===null?[]:[t],n=[];for(let o of r){let s=typeof o.Name=="string"?o.Name.trim():"";if(!s)continue;let i=typeof o.ProcessId=="number"?o.ProcessId:Number.parseInt(String(o.ProcessId),10),a=typeof o.ParentProcessId=="number"?o.ParentProcessId:Number.parseInt(String(o.ParentProcessId),10);!Number.isInteger(i)||!Number.isInteger(a)||n.push({pid:i,ppid:a,name:s,cmdline:typeof o.CommandLine=="string"?o.CommandLine:null,startToken:typeof o.StartToken=="string"&&o.StartToken.length>0?o.StartToken:null})}return n}catch(e){return _.warn("PROCESS","Cannot enumerate the Windows process table with names \u2014 ghost-port reclaim disabled",{error:e instanceof Error?e.message:String(e)}),null}}async function uI(e){try{let t=await WS("netstat",["-ano"],{timeout:15e3,windowsHide:!0,maxBuffer:16777216});return lI(t.stdout,e)}catch(t){return _.warn("PROCESS","netstat failed \u2014 ghost-port reclaim disabled for this attempt",{port:e,error:t instanceof Error?t.message:String(t)}),null}}function lI(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 VS(e,t={}){let r=t.isWin32??(()=>process.platform==="win32"),n=t.listOwners??uI,o=t.readTable??cI,s=t.killTree??((y,E)=>gt(y,E)),i=t.dataDir??(()=>ce);if(!r())return{reclaimed:!1,reason:"not-supported",killedPids:[]};let a=await n(e);if(a===null)return{reclaimed:!1,reason:"netstat-unreadable",killedPids:[]};if(a.length===0)return{reclaimed:!1,reason:"no-listener",killedPids:[]};let c=await o();if(c===null)return{reclaimed:!1,reason:"table-unreadable",killedPids:[]};if(a.filter(y=>pe(y)).length>0)return{reclaimed:!1,reason:"owner-alive",killedPids:[]};let l=new Map;for(let y of c){let E=l.get(y.ppid);E?E.push(y):l.set(y.ppid,[y])}let d=new Map,f=new Set,p=y=>{for(let E of l.get(y)??[])f.has(E.pid)||(f.add(E.pid),p(E.pid),qS(E.name)&&d.set(E.pid,E))};for(let y of a)p(y);let m=i();if(m)for(let y of c)d.has(y.pid)||qS(y.name)&&aI(y.cmdline,m)&&d.set(y.pid,y);if(d.size===0)return _.info("PROCESS","Ghost listener owner is dead but no chroma-sidecar descendants found",{port:e,deadOwners:a,processTableRows:c.length,dataDir:m??"(unresolved)"}),{reclaimed:!1,reason:"no-chroma-descendants",killedPids:[]};_.warn("PROCESS","Reclaiming ghost listener: killing dead worker's surviving chroma sidecar chain",{port:e,deadOwners:a,targets:[...d.values()].map(y=>({pid:y.pid,name:y.name}))});let h=[];for(let y of d.values())try{await s(y.pid,{expectedStartToken:y.startToken,signalMode:"immediate"}),h.push(y.pid)}catch(E){return _.error("PROCESS","Ghost-port reclaim tree-kill failed",{port:e,pid:y.pid},E instanceof Error?E:new Error(String(E))),{reclaimed:!1,reason:"kill-failed",killedPids:h}}let g=await n(e);return g!==null&&g.length===0?(_.info("PROCESS","Ghost listener reclaimed \u2014 port is free again",{port:e,killedPids:h}),{reclaimed:!0,killedPids:h}):(_.warn("PROCESS","Ghost-port reclaim killed the sidecar chain but the port is still bound",{port:e,killedPids:h,stillOwnedBy:g}),{reclaimed:!1,reason:"still-bound",killedPids:h})}var dI=120*1e3;function Jl(){return Yl.default.join(ht.get("CLAUDE_MEM_DATA_DIR"),".worker-start-attempted")}function fI(){if(process.platform!=="win32")return!1;let e=Jl();if(!(0,ot.existsSync)(e))return!1;try{let t=(0,ot.statSync)(e).mtimeMs;return Date.now()-t<dI}catch(t){return t instanceof Error?_.debug("SYSTEM","Could not stat worker spawn lock file",{},t):_.debug("SYSTEM","Could not stat worker spawn lock file",{error:String(t)}),!1}}function pI(){if(process.platform==="win32")try{let e=Jl();(0,ot.mkdirSync)(Yl.default.dirname(e),{recursive:!0}),(0,ot.writeFileSync)(e,"","utf-8")}catch{}}function xo(){if(process.platform==="win32")try{let e=Jl();(0,ot.existsSync)(e)&&(0,ot.unlinkSync)(e)}catch{}}var qi;async function KS(e,t){if(qi=void 0,!t)return _.error("SYSTEM","ensureWorkerStarted called with empty workerScriptPath \u2014 caller bug"),"dead";if(!(0,ot.existsSync)(t))return _.error("SYSTEM","ensureWorkerStarted: worker script not found at expected path \u2014 likely a partial install or build artifact missing",{workerScriptPath:t}),"dead";if(zi()==="alive"){if(_.info("SYSTEM","Worker PID file points to a live process, skipping duplicate spawn"),await ko(e,wr(Oe.READINESS_WAIT)))return xo(),_.info("SYSTEM","Worker became ready while waiting on live PID"),"ready";let a=await wo(e,1e3),c=zi()==="alive";return!a&&!c?(_.error("SYSTEM","Live PID disappeared before readiness endpoint became available"),"dead"):(_.warn("SYSTEM","Live PID detected but worker did not become ready before timeout"),"warming")}if(await wo(e,1e3)){xo();let i=await ko(e,wr(Oe.READINESS_WAIT));return i||_.warn("SYSTEM","Worker is alive but readiness timed out \u2014 proceeding anyway"),_.info("SYSTEM","Worker already running and healthy"),i?"ready":"warming"}if(await Hl(e)){if(_.info("SYSTEM","Port in use, waiting for worker to become healthy"),await wo(e,wr(Oe.PORT_IN_USE_WAIT))){xo();let c=await ko(e,wr(Oe.READINESS_WAIT));return _.info("SYSTEM","Worker is now healthy"),c?"ready":"warming"}let a=await VS(e);if(a.reclaimed)_.info("SYSTEM","Reclaimed ghost listener left by a dead worker \u2014 proceeding to spawn",{port:e,killedPids:a.killedPids}),xo();else return _.error("SYSTEM","Port in use but worker not responding to health checks",{port:e,reclaimReason:a.reason}),"dead"}if(fI())return _.warn("SYSTEM","Worker unavailable on Windows \u2014 skipping spawn (recent attempt failed within cooldown)"),"dead";let o=Wl(),s;try{if(o){if(_.info("SYSTEM","Starting worker daemon",{workerScriptPath:t}),pI(),s=RS(t,e),s===void 0)return _.error("SYSTEM","Failed to spawn worker daemon"),"dead"}else _.info("SYSTEM","Another launcher holds the spawn lock \u2014 skipping duplicate spawn and waiting for its worker");if(!await ko(e,wr(Oe.READINESS_WAIT))){let a=await wo(e,1e3),c=zi()==="alive",u=s!==void 0&&s>0&&pe(s);return!a&&!c&&!u?o?(qi=TS(t),_.error("SYSTEM","Worker exited before readiness endpoint became available",qi?{bootFailure:qi}:{}),"dead"):(_.error("SYSTEM","Spawn-lock holder never produced a live worker before readiness timed out"),"dead"):(_.warn("SYSTEM",o?"Worker spawned but readiness endpoint not responding within window":"Spawn-lock holder's worker not ready within window"),"warming")}return xo(),OS(),_.info("SYSTEM",o?"Worker started successfully":"Worker is up (started by another launcher)"),"ready"}finally{o&&Vl()}}var cn=require("node:fs/promises"),Po=require("node:path");var nd=require("node:child_process"),be=require("node:fs"),Me=require("node:path"),od=require("node:os"),ed=require("node:module");ne();Ze();var II={},td=typeof __filename<"u"?(0,ed.createRequire)(__filename):(0,ed.createRequire)(II.url),mI={".js":"javascript",".mjs":"javascript",".cjs":"javascript",".jsx":"tsx",".ts":"typescript",".tsx":"tsx",".py":"python",".pyw":"python",".go":"go",".rs":"rust",".rb":"ruby",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".kt":"kotlin",".kts":"kotlin",".swift":"swift",".php":"php",".lua":"lua",".scala":"scala",".sc":"scala",".sh":"bash",".bash":"bash",".zsh":"bash",".hs":"haskell",".zig":"zig",".css":"css",".scss":"scss",".toml":"toml",".yml":"yaml",".yaml":"yaml",".sql":"sql",".md":"markdown",".mdx":"markdown"};function QS(e){let t=e.slice(e.lastIndexOf("."));return mI[t]??"unknown"}var hI={javascript:"tree-sitter-javascript",typescript:"tree-sitter-typescript/typescript",tsx:"tree-sitter-typescript/tsx",python:"tree-sitter-python",go:"tree-sitter-go",rust:"tree-sitter-rust",ruby:"tree-sitter-ruby",java:"tree-sitter-java",c:"tree-sitter-c",cpp:"tree-sitter-cpp",kotlin:"tree-sitter-kotlin",swift:"tree-sitter-swift",php:"tree-sitter-php/php",lua:"@tree-sitter-grammars/tree-sitter-lua",scala:"tree-sitter-scala",bash:"tree-sitter-bash",haskell:"tree-sitter-haskell",zig:"@tree-sitter-grammars/tree-sitter-zig",css:"tree-sitter-css",scss:"tree-sitter-scss",toml:"@tree-sitter-grammars/tree-sitter-toml",yaml:"@tree-sitter-grammars/tree-sitter-yaml",sql:"@derekstride/tree-sitter-sql",markdown:"@tree-sitter-grammars/tree-sitter-markdown"},gI={markdown:"tree-sitter-markdown"};function eb(e){let t=hI[e];if(!t)return null;let r=gI[e];if(r){try{let n=td.resolve(t+"/package.json"),o=(0,Me.join)((0,Me.dirname)(n),r);if((0,be.existsSync)((0,Me.join)(o,"src")))return o}catch{}return null}try{let n=td.resolve(t+"/package.json");return(0,Me.dirname)(n)}catch{return null}}var _I={jsts:`
|
|
84
|
+
`)}async function jS(e,t={}){let r=WO(t);try{return await fetch(e,r)}catch(n){throw LS()&&KO(e,t,n),n}}async function Kl(e,t={},r){try{return await jS(e,{...t,signal:AbortSignal.timeout(r)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new Error(`Request timed out after ${r}ms`):n}}var Ni=null,Li=null,ji=null,Ui=null;function BO(){return Ae.default.join(ht.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function Bl(){return ji!==null||(ji=ht.loadFromFile(BO())),ji}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 GO(e,t,r){let n=process.env[e];if(n!==void 0){let i=zS(n,r);return i!==null?i:(_.warn("SYSTEM",`Invalid ${e}, using default`,{value:n,min:r.min,max:r.max}),t)}let o=Bl()[e],s=zS(o,r);return s!==null?s:(_.warn("SYSTEM",`Invalid ${e} in settings.json, using default`,{value:o,min:r.min,max:r.max}),t)}function Gl(){if(Ni!==null)return Ni;let e=Bl();return Ni=parseInt(e.CLAUDE_MEM_WORKER_PORT,10),Ni}function YO(){return Li!==null||(Li=Bl().CLAUDE_MEM_WORKER_HOST),Li}function JO(){return Ui!==null||(Ui=GO("CLAUDE_MEM_API_TIMEOUT_MS",tr(Oe.API_REQUEST),HO)),Ui}function XO(e){return e.startsWith("[")&&e.endsWith("]")?e:e.includes(":")?`[${e}]`:e}function QO(e){return`http://${XO(YO())}:${Gl()}${e}`}function Fi(e,t={}){let r=t.method??"GET",n=t.timeoutMs??JO(),o=QO(e),s={method:r};return t.headers&&(s.headers=t.headers),t.body&&(s.body=t.body),n>0?Kl(o,s,n):jS(o,s)}function US(e){let t=(0,Ce.existsSync)(Ae.default.join(e,"plugin","scripts"))?Ae.default.join(e,"plugin"):e;return Ae.default.join(t,"scripts","worker-service.cjs")}function eI(e,t){let r=d=>{let f=d.split("-")[0].split(".");return[parseInt(f[0],10)||0,parseInt(f[1],10)||0,parseInt(f[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 u=e.includes("-")?1:0,l=t.includes("-")?1:0;return u!==l?u-l:e<t?1:e>t?-1:0}function tI(e=Ae.default.join(Ae.default.dirname(Ae.default.dirname(zo)),"cache","thedotmack","claude-mem")){try{return(0,Ce.readdirSync)(e).filter(t=>/^\d/.test(t)).map(t=>Ae.default.join(e,t)).filter(t=>{try{if(!(0,Ce.statSync)(t).isDirectory())return!1}catch{return!1}return!(0,Ce.existsSync)(Ae.default.join(t,".orphaned_at"))}).map(t=>({scriptPath:US(t),version:Ae.default.basename(t)}))}catch{return[]}}function DS(e){try{let t=JSON.parse((0,Ce.readFileSync)(e,"utf-8"));return typeof t.version=="string"?t.version:null}catch(t){let r=t.code;return r!=="ENOENT"&&_.debug("SYSTEM","Could not read package version for worker resolution",{packageJsonPath:e,code:r}),null}}function rI(){let e=process.env.CLAUDE_MEM_WORKER_SCRIPT_PATH?.trim();if(e){if((0,Ce.existsSync)(e))return{scriptPath:e,version:null};_.debug("SYSTEM","Ignoring missing CLAUDE_MEM_WORKER_SCRIPT_PATH override",{override:e})}let t=[...tI(),{scriptPath:US(Ae.default.join(zo,"plugin")),version:DS(Ae.default.join(zo,"package.json"))},{scriptPath:Ae.default.join(process.cwd(),"plugin","scripts","worker-service.cjs"),version:DS(Ae.default.join(process.cwd(),"package.json"))}];return nI(t)}function nI(e){let t=e.filter(r=>(0,Ce.existsSync)(r.scriptPath));return t.length===0?null:(t.sort((r,n)=>r.version===null&&n.version===null?0:r.version===null?1:n.version===null?-1:eI(r.version,n.version)),t[0])}function FS(){return rI()?.scriptPath??null}var oI=1e3;var sI=5e3,jF=sI+oI;var Yl=Lt(require("path"),1),ot=require("fs");ne();var ZS=require("node:child_process"),HS=require("node:util");ne();Ze();var WS=(0,HS.promisify)(ZS.execFile),iI=/^(uv|uvx|python|chroma-mcp)(\.exe)?$/i;function qS(e){return iI.test(e.trim())}function aI(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]==="/"}async function cI(){try{let e=await WS("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:3e4,windowsHide:!0,maxBuffer:33554432}),t=JSON.parse(e.stdout),r=Array.isArray(t)?t:t===null?[]:[t],n=[];for(let o of r){let s=typeof o.Name=="string"?o.Name.trim():"";if(!s)continue;let i=typeof o.ProcessId=="number"?o.ProcessId:Number.parseInt(String(o.ProcessId),10),a=typeof o.ParentProcessId=="number"?o.ParentProcessId:Number.parseInt(String(o.ParentProcessId),10);!Number.isInteger(i)||!Number.isInteger(a)||n.push({pid:i,ppid:a,name:s,cmdline:typeof o.CommandLine=="string"?o.CommandLine:null,startToken:typeof o.StartToken=="string"&&o.StartToken.length>0?o.StartToken:null})}return n}catch(e){return _.warn("PROCESS","Cannot enumerate the Windows process table with names \u2014 ghost-port reclaim disabled",{error:e instanceof Error?e.message:String(e)}),null}}async function uI(e){try{let t=await WS("netstat",["-ano"],{timeout:15e3,windowsHide:!0,maxBuffer:16777216});return lI(t.stdout,e)}catch(t){return _.warn("PROCESS","netstat failed \u2014 ghost-port reclaim disabled for this attempt",{port:e,error:t instanceof Error?t.message:String(t)}),null}}function lI(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 VS(e,t={}){let r=t.isWin32??(()=>process.platform==="win32"),n=t.listOwners??uI,o=t.readTable??cI,s=t.killTree??((y,E)=>gt(y,E)),i=t.dataDir??(()=>ce);if(!r())return{reclaimed:!1,reason:"not-supported",killedPids:[]};let a=await n(e);if(a===null)return{reclaimed:!1,reason:"netstat-unreadable",killedPids:[]};if(a.length===0)return{reclaimed:!1,reason:"no-listener",killedPids:[]};let c=await o();if(c===null)return{reclaimed:!1,reason:"table-unreadable",killedPids:[]};if(a.filter(y=>pe(y)).length>0)return{reclaimed:!1,reason:"owner-alive",killedPids:[]};let l=new Map;for(let y of c){let E=l.get(y.ppid);E?E.push(y):l.set(y.ppid,[y])}let d=new Map,f=new Set,p=y=>{for(let E of l.get(y)??[])f.has(E.pid)||(f.add(E.pid),p(E.pid),qS(E.name)&&d.set(E.pid,E))};for(let y of a)p(y);let m=i();if(m)for(let y of c)d.has(y.pid)||qS(y.name)&&aI(y.cmdline,m)&&d.set(y.pid,y);if(d.size===0)return _.info("PROCESS","Ghost listener owner is dead but no chroma-sidecar descendants found",{port:e,deadOwners:a,processTableRows:c.length,dataDir:m??"(unresolved)"}),{reclaimed:!1,reason:"no-chroma-descendants",killedPids:[]};_.warn("PROCESS","Reclaiming ghost listener: killing dead worker's surviving chroma sidecar chain",{port:e,deadOwners:a,targets:[...d.values()].map(y=>({pid:y.pid,name:y.name}))});let h=[];for(let y of d.values())try{await s(y.pid,{expectedStartToken:y.startToken,signalMode:"immediate"}),h.push(y.pid)}catch(E){return _.error("PROCESS","Ghost-port reclaim tree-kill failed",{port:e,pid:y.pid},E instanceof Error?E:new Error(String(E))),{reclaimed:!1,reason:"kill-failed",killedPids:h}}let g=await n(e);return g!==null&&g.length===0?(_.info("PROCESS","Ghost listener reclaimed \u2014 port is free again",{port:e,killedPids:h}),{reclaimed:!0,killedPids:h}):(_.warn("PROCESS","Ghost-port reclaim killed the sidecar chain but the port is still bound",{port:e,killedPids:h,stillOwnedBy:g}),{reclaimed:!1,reason:"still-bound",killedPids:h})}var dI=120*1e3;function Jl(){return Yl.default.join(ht.get("CLAUDE_MEM_DATA_DIR"),".worker-start-attempted")}function fI(){if(process.platform!=="win32")return!1;let e=Jl();if(!(0,ot.existsSync)(e))return!1;try{let t=(0,ot.statSync)(e).mtimeMs;return Date.now()-t<dI}catch(t){return t instanceof Error?_.debug("SYSTEM","Could not stat worker spawn lock file",{},t):_.debug("SYSTEM","Could not stat worker spawn lock file",{error:String(t)}),!1}}function pI(){if(process.platform==="win32")try{let e=Jl();(0,ot.mkdirSync)(Yl.default.dirname(e),{recursive:!0}),(0,ot.writeFileSync)(e,"","utf-8")}catch{}}function xo(){if(process.platform==="win32")try{let e=Jl();(0,ot.existsSync)(e)&&(0,ot.unlinkSync)(e)}catch{}}var qi;async function KS(e,t){if(qi=void 0,!t)return _.error("SYSTEM","ensureWorkerStarted called with empty workerScriptPath \u2014 caller bug"),"dead";if(!(0,ot.existsSync)(t))return _.error("SYSTEM","ensureWorkerStarted: worker script not found at expected path \u2014 likely a partial install or build artifact missing",{workerScriptPath:t}),"dead";if(zi()==="alive"){if(_.info("SYSTEM","Worker PID file points to a live process, skipping duplicate spawn"),await ko(e,wr(Oe.READINESS_WAIT)))return xo(),_.info("SYSTEM","Worker became ready while waiting on live PID"),"ready";let a=await wo(e,1e3),c=zi()==="alive";return!a&&!c?(_.error("SYSTEM","Live PID disappeared before readiness endpoint became available"),"dead"):(_.warn("SYSTEM","Live PID detected but worker did not become ready before timeout"),"warming")}if(await wo(e,1e3)){xo();let i=await ko(e,wr(Oe.READINESS_WAIT));return i||_.warn("SYSTEM","Worker is alive but readiness timed out \u2014 proceeding anyway"),_.info("SYSTEM","Worker already running and healthy"),i?"ready":"warming"}if(await Hl(e)){if(_.info("SYSTEM","Port in use, waiting for worker to become healthy"),await wo(e,wr(Oe.PORT_IN_USE_WAIT))){xo();let c=await ko(e,wr(Oe.READINESS_WAIT));return _.info("SYSTEM","Worker is now healthy"),c?"ready":"warming"}let a=await VS(e);if(a.reclaimed)_.info("SYSTEM","Reclaimed ghost listener left by a dead worker \u2014 proceeding to spawn",{port:e,killedPids:a.killedPids}),xo();else return _.error("SYSTEM","Port in use but worker not responding to health checks",{port:e,reclaimReason:a.reason}),"dead"}if(fI())return _.warn("SYSTEM","Worker unavailable on Windows \u2014 skipping spawn (recent attempt failed within cooldown)"),"dead";let o=Wl(),s;try{if(o){if(_.info("SYSTEM","Starting worker daemon",{workerScriptPath:t}),pI(),s=RS(t,e),s===void 0)return _.error("SYSTEM","Failed to spawn worker daemon"),"dead"}else _.info("SYSTEM","Another launcher holds the spawn lock \u2014 skipping duplicate spawn and waiting for its worker");if(!await ko(e,wr(Oe.READINESS_WAIT))){let a=await wo(e,1e3),c=zi()==="alive",u=s!==void 0&&s>0&&pe(s);return!a&&!c&&!u?o?(qi=TS(t),_.error("SYSTEM","Worker exited before readiness endpoint became available",qi?{bootFailure:qi}:{}),"dead"):(_.error("SYSTEM","Spawn-lock holder never produced a live worker before readiness timed out"),"dead"):(_.warn("SYSTEM",o?"Worker spawned but readiness endpoint not responding within window":"Spawn-lock holder's worker not ready within window"),"warming")}return xo(),OS(),_.info("SYSTEM",o?"Worker started successfully":"Worker is up (started by another launcher)"),"ready"}finally{o&&Vl()}}var cn=require("node:fs/promises"),Po=require("node:path");var nd=require("node:child_process"),be=require("node:fs"),Me=require("node:path"),od=require("node:os"),ed=require("node:module");ne();Ze();var II={},td=typeof __CM_FILENAME__<"u"?(0,ed.createRequire)(__CM_FILENAME__):(0,ed.createRequire)(II.url),mI={".js":"javascript",".mjs":"javascript",".cjs":"javascript",".jsx":"tsx",".ts":"typescript",".tsx":"tsx",".py":"python",".pyw":"python",".go":"go",".rs":"rust",".rb":"ruby",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".kt":"kotlin",".kts":"kotlin",".swift":"swift",".php":"php",".lua":"lua",".scala":"scala",".sc":"scala",".sh":"bash",".bash":"bash",".zsh":"bash",".hs":"haskell",".zig":"zig",".css":"css",".scss":"scss",".toml":"toml",".yml":"yaml",".yaml":"yaml",".sql":"sql",".md":"markdown",".mdx":"markdown"};function QS(e){let t=e.slice(e.lastIndexOf("."));return mI[t]??"unknown"}var hI={javascript:"tree-sitter-javascript",typescript:"tree-sitter-typescript/typescript",tsx:"tree-sitter-typescript/tsx",python:"tree-sitter-python",go:"tree-sitter-go",rust:"tree-sitter-rust",ruby:"tree-sitter-ruby",java:"tree-sitter-java",c:"tree-sitter-c",cpp:"tree-sitter-cpp",kotlin:"tree-sitter-kotlin",swift:"tree-sitter-swift",php:"tree-sitter-php/php",lua:"@tree-sitter-grammars/tree-sitter-lua",scala:"tree-sitter-scala",bash:"tree-sitter-bash",haskell:"tree-sitter-haskell",zig:"@tree-sitter-grammars/tree-sitter-zig",css:"tree-sitter-css",scss:"tree-sitter-scss",toml:"@tree-sitter-grammars/tree-sitter-toml",yaml:"@tree-sitter-grammars/tree-sitter-yaml",sql:"@derekstride/tree-sitter-sql",markdown:"@tree-sitter-grammars/tree-sitter-markdown"},gI={markdown:"tree-sitter-markdown"};function eb(e){let t=hI[e];if(!t)return null;let r=gI[e];if(r){try{let n=td.resolve(t+"/package.json"),o=(0,Me.join)((0,Me.dirname)(n),r);if((0,be.existsSync)((0,Me.join)(o,"src")))return o}catch{}return null}try{let n=td.resolve(t+"/package.json");return(0,Me.dirname)(n)}catch{return null}}var _I={jsts:`
|
|
83
85
|
(function_declaration name: (identifier) @name) @func
|
|
84
86
|
(lexical_declaration (variable_declarator name: (identifier) @name value: [(arrow_function) (function_expression)])) @const_func
|
|
85
87
|
(class_declaration name: (type_identifier) @name) @cls
|
|
@@ -219,7 +221,7 @@ ${p}`}let a=s.lineStart;for(let u=s.lineStart-1;u>=0;u--){let l=i[u].trim();if(l
|
|
|
219
221
|
${c}`}ne();var AI=new Set([".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".pyw",".go",".rs",".rb",".java",".cs",".cpp",".cc",".cxx",".c",".h",".hpp",".hh",".swift",".kt",".kts",".php",".vue",".svelte",".lua",".scala",".sc",".sh",".bash",".zsh",".hs",".zig",".css",".scss",".toml",".yml",".yaml",".sql",".md",".mdx"]),CI=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),MI=512*1024;async function*ub(e,t,r=20){if(r<=0)return;let n;try{n=await(0,cn.readdir)(e,{withFileTypes:!0})}catch(o){_.debug("WORKER",`walkDir: failed to read directory ${e}`,void 0,o instanceof Error?o:void 0);return}for(let o of n){if(o.name.startsWith(".")&&o.name!=="."||CI.has(o.name))continue;let s=(0,Po.join)(e,o.name);if(o.isDirectory())yield*ub(s,t,r-1);else if(o.isFile()){let i=o.name.slice(o.name.lastIndexOf("."));AI.has(i)&&(yield s)}}}async function zI(e){try{let t=await(0,cn.stat)(e);if(t.size>MI||t.size===0)return null;let r=await(0,cn.readFile)(e,"utf-8");return r.slice(0,1e3).includes("\0")?null:r}catch(t){return _.debug("WORKER",`safeReadFile: failed to read ${e}`,void 0,t instanceof Error?t:void 0),null}}async function lb(e,t,r={}){let n=r.maxResults||20,o=t.toLowerCase(),s=o.split(/[\s_\-./]+/).filter(h=>h.length>0),i=[];for await(let h of ub(e,e,20)){if(r.filePattern&&!(0,Po.relative)(e,h).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let g=await zI(h);g&&i.push({absolutePath:h,relativePath:(0,Po.relative)(e,h),content:g})}let a=ib(i),c=[],u=[],l=0;for(let[h,g]of a){l+=DI(g);let E=Wi(h.toLowerCase(),s)>0,v=[],I=(x,z)=>{for(let j of x){let Be=0,Pe="",Ge=Wi(j.name.toLowerCase(),s);Ge>0&&(Be+=Ge*3,Pe="name match"),j.signature.toLowerCase().includes(o)&&(Be+=2,Pe=Pe?`${Pe} + signature`:"signature match"),j.jsdoc&&j.jsdoc.toLowerCase().includes(o)&&(Be+=1,Pe=Pe?`${Pe} + jsdoc`:"jsdoc match"),Be>0&&(E=!0,v.push({filePath:h,symbolName:z?`${z}.${j.name}`:j.name,kind:j.kind,signature:j.signature,jsdoc:j.jsdoc,lineStart:j.lineStart,lineEnd:j.lineEnd,matchReason:Pe})),j.children&&I(j.children,j.name)}};I(g.symbols),E&&(c.push(g),u.push(...v))}u.sort((h,g)=>{let y=Wi(h.symbolName.toLowerCase(),s);return Wi(g.symbolName.toLowerCase(),s)-y});let d=u.slice(0,n),f=new Set(d.map(h=>h.filePath)),p=c.filter(h=>f.has(h.filePath)).slice(0,n),m=p.reduce((h,g)=>h+g.foldedTokenEstimate,0);return{foldedFiles:p,matchingSymbols:d,totalFilesScanned:i.length,totalSymbolsFound:l,tokenEstimate:m}}function Wi(e,t){let r=0;for(let n of t)if(e===n)r+=10;else if(e.includes(n))r+=5;else{let o=0,s=0;for(let i of n){let a=e.indexOf(i,o);a!==-1&&(s++,o=a+1)}s===n.length&&(r+=1)}return r}function DI(e){let t=e.symbols.length;for(let r of e.symbols)r.children&&(t+=r.children.length);return t}function db(e,t){let r=[];if(r.push(`\u{1F50D} Smart Search: "${t}"`),r.push(` Scanned ${e.totalFilesScanned} files, found ${e.totalSymbolsFound} symbols`),r.push(` ${e.matchingSymbols.length} matches across ${e.foldedFiles.length} files (~${e.tokenEstimate} tokens for folded view)`),r.push(""),e.matchingSymbols.length===0)return r.push(" No matching symbols found."),r.join(`
|
|
220
222
|
`);r.push("\u2500\u2500 Matching Symbols \u2500\u2500"),r.push("");for(let n of e.matchingSymbols){if(r.push(` ${n.kind} ${n.symbolName} (${n.filePath}:${n.lineStart+1})`),r.push(` ${n.signature}`),n.jsdoc){let o=n.jsdoc.split(`
|
|
221
223
|
`).find(s=>s.replace(/^[\s*/]+/,"").trim().length>0);o&&r.push(` \u{1F4AC} ${o.replace(/^[\s*/]+/,"").trim()}`)}r.push("")}r.push("\u2500\u2500 Folded File Views \u2500\u2500"),r.push("");for(let n of e.foldedFiles)r.push(an(n)),r.push("");return r.push("\u2500\u2500 Actions \u2500\u2500"),r.push(" To see full implementation: use smart_unfold with file path and symbol name"),r.join(`
|
|
222
|
-
`)}var sd=require("node:fs/promises"),id=require("node:os"),kr=require("node:path");function NI(e){return e==="~"?(0,id.homedir)():e.startsWith("~/")||e.startsWith("~\\")?(0,kr.join)((0,id.homedir)(),e.slice(2)):e}async function Vi(e,t=process.cwd()){if(typeof e!="string"||e.trim().length===0)throw new Error("file_path is required");let r=await(0,sd.realpath)((0,kr.resolve)(t)),n=(0,kr.resolve)(r,NI(e.trim())),o;try{o=await(0,sd.realpath)(n)}catch{o=n}if(o!==r&&!o.startsWith(r+kr.sep))throw new Error(`Access denied: "${e}" resolves outside the workspace (${r}). MCP file tools can only read files within the current project.`);return o}var cd=require("node:fs/promises"),Yi=require("node:fs"),nr=require("node:path"),yb=require("node:os"),Sb=require("node:url");var fb="claude";function LI(e){return e.trim().toLowerCase().replace(/\s+/g,"-")}function Ki(e){if(!e)return fb;let t=LI(e);return t?t==="transcript"||t.includes("codex")?"codex":t.includes("cursor")?"cursor":t.includes("claude")?"claude":t:fb}var jI=tr(Oe.API_REQUEST),st=class extends Error{kind;status;cause;constructor(t,r,n={}){super(r),this.name="ServerClientError",this.kind=t,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},Bi=class{baseUrl;apiKey;timeoutMs;constructor(t){this.baseUrl=UI(t.serverBaseUrl),this.apiKey=t.apiKey,this.timeoutMs=t.timeoutMs??jI}async startSession(t){let r=this.buildStartSessionPayload(t);return this.request("POST","/v1/sessions/start",r)}async recordEvent(t){let r=this.buildEventPayload(t),n=t.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(t){if(!t.sessionId)throw new st("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(t.sessionId)}/end`,{})}async addObservation(t){return this.request("POST","/v1/memories",this.buildAddObservationPayload(t))}async searchObservations(t){return this.request("POST","/v1/search",this.buildSearchPayload(t))}async contextObservations(t){return this.request("POST","/v1/context",this.buildSearchPayload(t))}async getJobStatus(t){if(!t)throw new st("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(t)}`)}buildAddObservationPayload(t){let r=t.content,n=t.kind??"manual",o=typeof t.metadata?.title=="string"?t.metadata.title:void 0;return{projectId:t.projectId,kind:n,type:n,narrative:r,...o?{title:o}:{},...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.platformSource!==void 0?{platformSource:t.platformSource}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}}}buildSearchPayload(t){return{projectId:t.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:ad(t.platformSource)}:{}}}buildStartSessionPayload(t){return{projectId:t.projectId,...t.externalSessionId!==void 0?{externalSessionId:t.externalSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.agentId!==void 0?{agentId:t.agentId}:{},...t.agentType!==void 0?{agentType:t.agentType}:{},...t.platformSource!==void 0?{platformSource:ad(t.platformSource)}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}}}buildEventPayload(t){return{projectId:t.projectId,sourceType:t.sourceType,eventType:t.eventType,occurredAtEpoch:t.occurredAtEpoch,...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.memorySessionId!==void 0?{memorySessionId:t.memorySessionId}:{},...t.platformSource!==void 0?{platformSource:ad(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{}}}async request(t,r,n){if(!this.apiKey||!this.apiKey.trim())throw new st("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let o=`${this.baseUrl}${r}`,s={method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(s.body=JSON.stringify(n));let i;try{i=await Kl(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new st(l?"timeout":"transport",`Server ${t} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new st("http_error",`Server ${t} ${r} returned ${i.status}: ${FI(c,200)}`,{status:i.status})}let a=await i.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(c){let u=c instanceof Error?c:new Error(String(c));throw new st("invalid_response",`Server ${t} ${r} returned non-JSON response`,{cause:u})}}};function pb(e){return e instanceof st}function UI(e){return e.replace(/\/+$/,"")}function ad(e){return typeof e=="string"?Ki(e):null}function FI(e,t){return e.length<=t?e:`${e.slice(0,t)}\u2026`}ne();function Gi(){let t=(Ti().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return t==="server"||t==="server-beta"?"server":"worker"}function mb(){let e=Ti(),t=(...i)=>{for(let a of i){let c=(a??"").trim();if(c.length>0)return c}return""},r=t(e.CLAUDE_MEM_SERVER_URL,e.CLAUDE_MEM_SERVER_BETA_URL),n=t(e.CLAUDE_MEM_SERVER_API_KEY,e.CLAUDE_MEM_SERVER_BETA_API_KEY),o=t(e.CLAUDE_MEM_SERVER_PROJECT_ID,e.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!r)return _.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return _.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return _.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let s={serverBaseUrl:r,apiKey:n};return{runtime:"server",client:new Bi(s),projectId:o,serverBaseUrl:r}}ne();var hb=["observation_add","observation_record_event","observation_search","observation_context","observation_generation_status","memory_add","memory_search","memory_context"],qI=new Set(hb);function gb(e,t){return t==="server"?[...e]:(_.debug("SYSTEM","Filtering server-beta-only MCP tools from worker runtime advertisement",{runtime:t,hiddenToolCount:hb.length}),e.filter(r=>!qI.has(r.name)))}var cA={},ZI="13.24.19";console.log=(...e)=>{_.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:e})};var bb=!1,Eb=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,nr.dirname)((0,Sb.fileURLToPath)(cA.url))}catch(e){return bb=!0,_.warn("SYSTEM","mcp-server: failed to resolve module directory from import.meta.url, falling back to process.cwd()",void 0,e instanceof Error?e:new Error(String(e))),process.cwd()}})(),ud=FS()??(0,nr.resolve)(Eb,"worker-service.cjs");function HI(){bb&&((0,Yi.existsSync)(ud)||_.error("SYSTEM","mcp-server: dirname resolution failed (both __dirname and import.meta.url are unavailable). Fell back to process.cwd() and the resolved WORKER_SCRIPT_PATH does not exist. This is the actual problem \u2014 the worker bundle is fine, but mcp-server cannot locate it. Worker auto-start will fail until the dirname-resolution path is fixed.",{workerScriptPath:ud,mcpServerDir:Eb}))}async function _t(e,t={}){_.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:e});try{let r;if(t.body)r=await Fi(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t.body)});else{let n=new URLSearchParams;for(let[o,s]of Object.entries(t.query??{}))s!=null&&n.append(o,String(s));r=await Fi(`${e}?${n}`)}if(!r.ok){let n=await r.text();throw new Error(`Worker API error (${r.status}): ${n}`)}return _.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:e}),t.text?{content:[{type:"text",text:await r.text()}]}:t.body?{content:[{type:"text",text:JSON.stringify(await r.json(),null,2)}]}:await r.json()}catch(r){return _.error("SYSTEM","\u2190 Worker API error",{endpoint:e},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function WI(){try{return(await Fi("/api/health")).ok}catch(e){return _.debug("SYSTEM","Worker health check failed",{},e instanceof Error?e:new Error(String(e))),!1}}function vb(){if(Gi()!=="server")return null;let t=mb();return t?{...t,available:!0}:{runtime:"server",available:!1,reason:"server runtime is selected but configuration is incomplete (missing url, api key, or project id)"}}function VI(e){return pb(e)?{content:[{type:"text",text:`Server error (${e.kind}${e.status?` ${e.status}`:""}): ${e.message}`}],isError:!0}:{content:[{type:"text",text:`Tool error: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}function un(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function To(e){let t=vb();if(!t)throw new st("transport",`${e} requires CLAUDE_MEM_RUNTIME=server. Current runtime is "worker"; use the existing search/timeline/get_observations tools for worker-mode memory access.`);if(!t.available)throw new st("missing_api_key",`${e}: ${t.reason}`);return t}function Ro(e,t){return async r=>{try{return await t(r)}catch(n){let o=n instanceof Error?n:new Error(String(n));return _.warn("SYSTEM",`${e} failed`,void 0,o),VI(n)}}}var KI=Ro("observation_add",async e=>{let t=To("observation_add");if(typeof e?.content!="string"||e.content.trim().length===0)throw new Error('observation_add: "content" is required');let n={projectId:e.projectId&&e.projectId.trim().length>0?e.projectId:t.projectId,content:e.content,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.platformSource!==void 0?{platformSource:e.platformSource}:{},...e.kind!==void 0?{kind:e.kind}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}},o=await t.client.addObservation(n);return un(o)});function Xi(e){return typeof e=="string"?Ki(e):null}var BI=Ro("observation_record_event",async e=>{let t=To("observation_record_event");if(typeof e?.eventType!="string"||e.eventType.trim().length===0)throw new Error('observation_record_event: "eventType" is required');let n={projectId:e.projectId&&e.projectId.trim().length>0?e.projectId:t.projectId,sourceType:e.sourceType??"api",eventType:e.eventType,occurredAtEpoch:typeof e.occurredAtEpoch=="number"?e.occurredAtEpoch:Date.now(),...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:Xi(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{},...e.generate!==void 0?{generate:e.generate}:{}},o=await t.client.recordEvent(n);return un(o)}),GI=Ro("observation_search",async e=>{let t=To("observation_search");if(typeof e?.query!="string"||e.query.trim().length===0)throw new Error('observation_search: "query" is required');let n={projectId:e.projectId&&e.projectId.trim().length>0?e.projectId:t.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Xi(e.platformSource)}:{}},o=await t.client.searchObservations(n);return un(o)}),YI=Ro("observation_context",async e=>{let t=To("observation_context");if(typeof e?.query!="string"||e.query.trim().length===0)throw new Error('observation_context: "query" is required');let n={projectId:e.projectId&&e.projectId.trim().length>0?e.projectId:t.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Xi(e.platformSource)}:{}},o=await t.client.contextObservations(n);return un(o)});function JI(e){return Array.isArray(e.projects)?e.projects.map(t=>typeof t=="string"?t.trim():"").filter(Boolean):typeof e.projects=="string"?e.projects.split(",").map(t=>t.trim()).filter(Boolean):typeof e.project=="string"&&e.project.trim().length>0?[e.project.trim()]:[]}async function XI(e){let t=JI(e);return t.length===0?{content:[{type:"text",text:'session_start_context: "project" or "projects" is required'}],isError:!0}:_t("/api/context/inject",{query:{projects:t.join(","),...e.platformSource!==void 0?{platformSource:Xi(e.platformSource)}:{},...e.full!==void 0?{full:e.full}:{},...e.colors!==void 0?{colors:e.colors}:{}},text:!0})}var QI=Ro("observation_generation_status",async e=>{let t=To("observation_generation_status"),r=(e?.jobId??e?.job_id??"").trim();if(!r)throw new Error('observation_generation_status: "jobId" is required');let n=await t.client.getJobStatus(r);return un(n)});async function eA(){if(await WI())return!0;_.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),HI();try{let e=Gl(),t=await KS(e,ud);return t==="dead"&&_.error("SYSTEM","Worker auto-start failed \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running. Check earlier log lines for the specific failure reason (Bun not found, missing worker bundle, port conflict, etc.)."),t!=="dead"}catch(e){return _.error("SYSTEM","Worker auto-start threw \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running.",void 0,e instanceof Error?e:new Error(String(e))),!1}}var wb=[{name:"important_workflow",description:`LAYERED WORKFLOW (ALWAYS FOLLOW):
|
|
224
|
+
`)}var sd=require("node:fs/promises"),id=require("node:os"),kr=require("node:path");function NI(e){return e==="~"?(0,id.homedir)():e.startsWith("~/")||e.startsWith("~\\")?(0,kr.join)((0,id.homedir)(),e.slice(2)):e}async function Vi(e,t=process.cwd()){if(typeof e!="string"||e.trim().length===0)throw new Error("file_path is required");let r=await(0,sd.realpath)((0,kr.resolve)(t)),n=(0,kr.resolve)(r,NI(e.trim())),o;try{o=await(0,sd.realpath)(n)}catch{o=n}if(o!==r&&!o.startsWith(r+kr.sep))throw new Error(`Access denied: "${e}" resolves outside the workspace (${r}). MCP file tools can only read files within the current project.`);return o}var cd=require("node:fs/promises"),Yi=require("node:fs"),nr=require("node:path"),yb=require("node:os"),Sb=require("node:url");var fb="claude";function LI(e){return e.trim().toLowerCase().replace(/\s+/g,"-")}function Ki(e){if(!e)return fb;let t=LI(e);return t?t==="transcript"||t.includes("codex")?"codex":t.includes("cursor")?"cursor":t.includes("claude")?"claude":t:fb}var jI=tr(Oe.API_REQUEST),st=class extends Error{kind;status;cause;constructor(t,r,n={}){super(r),this.name="ServerClientError",this.kind=t,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},Bi=class{baseUrl;apiKey;timeoutMs;constructor(t){this.baseUrl=UI(t.serverBaseUrl),this.apiKey=t.apiKey,this.timeoutMs=t.timeoutMs??jI}async startSession(t){let r=this.buildStartSessionPayload(t);return this.request("POST","/v1/sessions/start",r)}async recordEvent(t){let r=this.buildEventPayload(t),n=t.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(t){if(!t.sessionId)throw new st("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(t.sessionId)}/end`,{})}async addObservation(t){return this.request("POST","/v1/memories",this.buildAddObservationPayload(t))}async searchObservations(t){return this.request("POST","/v1/search",this.buildSearchPayload(t))}async contextObservations(t){return this.request("POST","/v1/context",this.buildSearchPayload(t))}async getJobStatus(t){if(!t)throw new st("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(t)}`)}buildAddObservationPayload(t){let r=t.content,n=t.kind??"manual",o=typeof t.metadata?.title=="string"?t.metadata.title:void 0;return{projectId:t.projectId,kind:n,type:n,narrative:r,...o?{title:o}:{},...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.platformSource!==void 0?{platformSource:t.platformSource}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}}}buildSearchPayload(t){return{projectId:t.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:ad(t.platformSource)}:{}}}buildStartSessionPayload(t){return{projectId:t.projectId,...t.externalSessionId!==void 0?{externalSessionId:t.externalSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.agentId!==void 0?{agentId:t.agentId}:{},...t.agentType!==void 0?{agentType:t.agentType}:{},...t.platformSource!==void 0?{platformSource:ad(t.platformSource)}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}}}buildEventPayload(t){return{projectId:t.projectId,sourceType:t.sourceType,eventType:t.eventType,occurredAtEpoch:t.occurredAtEpoch,...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.memorySessionId!==void 0?{memorySessionId:t.memorySessionId}:{},...t.platformSource!==void 0?{platformSource:ad(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{}}}async request(t,r,n){if(!this.apiKey||!this.apiKey.trim())throw new st("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let o=`${this.baseUrl}${r}`,s={method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(s.body=JSON.stringify(n));let i;try{i=await Kl(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new st(l?"timeout":"transport",`Server ${t} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new st("http_error",`Server ${t} ${r} returned ${i.status}: ${FI(c,200)}`,{status:i.status})}let a=await i.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(c){let u=c instanceof Error?c:new Error(String(c));throw new st("invalid_response",`Server ${t} ${r} returned non-JSON response`,{cause:u})}}};function pb(e){return e instanceof st}function UI(e){return e.replace(/\/+$/,"")}function ad(e){return typeof e=="string"?Ki(e):null}function FI(e,t){return e.length<=t?e:`${e.slice(0,t)}\u2026`}ne();function Gi(){let t=(Ti().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return t==="server"||t==="server-beta"?"server":"worker"}function mb(){let e=Ti(),t=(...i)=>{for(let a of i){let c=(a??"").trim();if(c.length>0)return c}return""},r=t(e.CLAUDE_MEM_SERVER_URL,e.CLAUDE_MEM_SERVER_BETA_URL),n=t(e.CLAUDE_MEM_SERVER_API_KEY,e.CLAUDE_MEM_SERVER_BETA_API_KEY),o=t(e.CLAUDE_MEM_SERVER_PROJECT_ID,e.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!r)return _.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return _.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return _.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let s={serverBaseUrl:r,apiKey:n};return{runtime:"server",client:new Bi(s),projectId:o,serverBaseUrl:r}}ne();var hb=["observation_add","observation_record_event","observation_search","observation_context","observation_generation_status","memory_add","memory_search","memory_context"],qI=new Set(hb);function gb(e,t){return t==="server"?[...e]:(_.debug("SYSTEM","Filtering server-beta-only MCP tools from worker runtime advertisement",{runtime:t,hiddenToolCount:hb.length}),e.filter(r=>!qI.has(r.name)))}var cA={},ZI="13.24.21";console.log=(...e)=>{_.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:e})};var bb=!1,Eb=(()=>{if(typeof __CM_DIRNAME__<"u")return __CM_DIRNAME__;try{return(0,nr.dirname)((0,Sb.fileURLToPath)(cA.url))}catch(e){return bb=!0,_.warn("SYSTEM","mcp-server: failed to resolve module directory from import.meta.url, falling back to process.cwd()",void 0,e instanceof Error?e:new Error(String(e))),process.cwd()}})(),ud=FS()??(0,nr.resolve)(Eb,"worker-service.cjs");function HI(){bb&&((0,Yi.existsSync)(ud)||_.error("SYSTEM","mcp-server: dirname resolution failed (both __dirname and import.meta.url are unavailable). Fell back to process.cwd() and the resolved WORKER_SCRIPT_PATH does not exist. This is the actual problem \u2014 the worker bundle is fine, but mcp-server cannot locate it. Worker auto-start will fail until the dirname-resolution path is fixed.",{workerScriptPath:ud,mcpServerDir:Eb}))}async function _t(e,t={}){_.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:e});try{let r;if(t.body)r=await Fi(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t.body)});else{let n=new URLSearchParams;for(let[o,s]of Object.entries(t.query??{}))s!=null&&n.append(o,String(s));r=await Fi(`${e}?${n}`)}if(!r.ok){let n=await r.text();throw new Error(`Worker API error (${r.status}): ${n}`)}return _.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:e}),t.text?{content:[{type:"text",text:await r.text()}]}:t.body?{content:[{type:"text",text:JSON.stringify(await r.json(),null,2)}]}:await r.json()}catch(r){return _.error("SYSTEM","\u2190 Worker API error",{endpoint:e},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function WI(){try{return(await Fi("/api/health")).ok}catch(e){return _.debug("SYSTEM","Worker health check failed",{},e instanceof Error?e:new Error(String(e))),!1}}function vb(){if(Gi()!=="server")return null;let t=mb();return t?{...t,available:!0}:{runtime:"server",available:!1,reason:"server runtime is selected but configuration is incomplete (missing url, api key, or project id)"}}function VI(e){return pb(e)?{content:[{type:"text",text:`Server error (${e.kind}${e.status?` ${e.status}`:""}): ${e.message}`}],isError:!0}:{content:[{type:"text",text:`Tool error: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}function un(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function To(e){let t=vb();if(!t)throw new st("transport",`${e} requires CLAUDE_MEM_RUNTIME=server. Current runtime is "worker"; use the existing search/timeline/get_observations tools for worker-mode memory access.`);if(!t.available)throw new st("missing_api_key",`${e}: ${t.reason}`);return t}function Ro(e,t){return async r=>{try{return await t(r)}catch(n){let o=n instanceof Error?n:new Error(String(n));return _.warn("SYSTEM",`${e} failed`,void 0,o),VI(n)}}}var KI=Ro("observation_add",async e=>{let t=To("observation_add");if(typeof e?.content!="string"||e.content.trim().length===0)throw new Error('observation_add: "content" is required');let n={projectId:e.projectId&&e.projectId.trim().length>0?e.projectId:t.projectId,content:e.content,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.platformSource!==void 0?{platformSource:e.platformSource}:{},...e.kind!==void 0?{kind:e.kind}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}},o=await t.client.addObservation(n);return un(o)});function Xi(e){return typeof e=="string"?Ki(e):null}var BI=Ro("observation_record_event",async e=>{let t=To("observation_record_event");if(typeof e?.eventType!="string"||e.eventType.trim().length===0)throw new Error('observation_record_event: "eventType" is required');let n={projectId:e.projectId&&e.projectId.trim().length>0?e.projectId:t.projectId,sourceType:e.sourceType??"api",eventType:e.eventType,occurredAtEpoch:typeof e.occurredAtEpoch=="number"?e.occurredAtEpoch:Date.now(),...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:Xi(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{},...e.generate!==void 0?{generate:e.generate}:{}},o=await t.client.recordEvent(n);return un(o)}),GI=Ro("observation_search",async e=>{let t=To("observation_search");if(typeof e?.query!="string"||e.query.trim().length===0)throw new Error('observation_search: "query" is required');let n={projectId:e.projectId&&e.projectId.trim().length>0?e.projectId:t.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Xi(e.platformSource)}:{}},o=await t.client.searchObservations(n);return un(o)}),YI=Ro("observation_context",async e=>{let t=To("observation_context");if(typeof e?.query!="string"||e.query.trim().length===0)throw new Error('observation_context: "query" is required');let n={projectId:e.projectId&&e.projectId.trim().length>0?e.projectId:t.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Xi(e.platformSource)}:{}},o=await t.client.contextObservations(n);return un(o)});function JI(e){return Array.isArray(e.projects)?e.projects.map(t=>typeof t=="string"?t.trim():"").filter(Boolean):typeof e.projects=="string"?e.projects.split(",").map(t=>t.trim()).filter(Boolean):typeof e.project=="string"&&e.project.trim().length>0?[e.project.trim()]:[]}async function XI(e){let t=JI(e);return t.length===0?{content:[{type:"text",text:'session_start_context: "project" or "projects" is required'}],isError:!0}:_t("/api/context/inject",{query:{projects:t.join(","),...e.platformSource!==void 0?{platformSource:Xi(e.platformSource)}:{},...e.full!==void 0?{full:e.full}:{},...e.colors!==void 0?{colors:e.colors}:{}},text:!0})}var QI=Ro("observation_generation_status",async e=>{let t=To("observation_generation_status"),r=(e?.jobId??e?.job_id??"").trim();if(!r)throw new Error('observation_generation_status: "jobId" is required');let n=await t.client.getJobStatus(r);return un(n)});async function eA(){if(await WI())return!0;_.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),HI();try{let e=Gl(),t=await KS(e,ud);return t==="dead"&&_.error("SYSTEM","Worker auto-start failed \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running. Check earlier log lines for the specific failure reason (Bun not found, missing worker bundle, port conflict, etc.)."),t!=="dead"}catch(e){return _.error("SYSTEM","Worker auto-start threw \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running.",void 0,e instanceof Error?e:new Error(String(e))),!1}}var wb=[{name:"important_workflow",description:`LAYERED WORKFLOW (ALWAYS FOLLOW):
|
|
223
225
|
1. search(query) \u2192 Get index with IDs (~50-100 tokens/result)
|
|
224
226
|
2. timeline(anchor=ID) \u2192 Get context around interesting results
|
|
225
227
|
3. get_observations([IDs]) \u2192 Fetch full details ONLY for filtered IDs
|
|
@@ -249,3 +251,4 @@ NEVER fetch full details without filtering first. 10x token savings.`,inputSchem
|
|
|
249
251
|
|
|
250
252
|
Available symbols:
|
|
251
253
|
${s}`}]}}return{content:[{type:"text",text:`Could not parse ${e.file_path}. File may be unsupported or empty.`}]}}},{name:"smart_outline",description:"Get structural outline of a file \u2014 shows all symbols (functions, classes, methods, types) with signatures but bodies folded. Much cheaper than reading the full file.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Path to the source file"}},required:["file_path"]},handler:async e=>{let t=await Vi(e.file_path),r=await(0,cd.readFile)(t,"utf-8"),n=Hi(r,t);return n.symbols.length>0?{content:[{type:"text",text:an(n)}]}:{content:[{type:"text",text:`Could not parse ${e.file_path}. File may use an unsupported language or be empty.`}]}}},{name:"build_corpus",description:"Build a knowledge corpus from filtered observations. Creates a queryable knowledge agent. Params: name (required), description, project, types (comma-separated), concepts (comma-separated), files (comma-separated), query, dateStart, dateEnd, limit",inputSchema:{type:"object",properties:{name:{type:"string",description:"Corpus name (used as filename)"},description:{type:"string",description:"What this corpus is about"},project:{type:"string",description:"Filter by project"},types:{type:"string",description:"Comma-separated observation types: decision,bugfix,feature,refactor,discovery,change"},concepts:{type:"string",description:"Comma-separated concepts to filter by"},files:{type:"string",description:"Comma-separated file paths to filter by"},query:{type:"string",description:"Semantic search query"},dateStart:{type:"string",description:"Start date (ISO format)"},dateEnd:{type:"string",description:"End date (ISO format)"},limit:{type:"number",description:"Maximum observations (default 500)"}},required:["name"],additionalProperties:!0},handler:async e=>await _t("/api/corpus",{body:e})},{name:"list_corpora",description:"List all knowledge corpora with their stats and priming status",inputSchema:{type:"object",properties:{},additionalProperties:!0},handler:async e=>await _t("/api/corpus",{query:e})},{name:"prime_corpus",description:"Prime a knowledge corpus \u2014 creates an AI session loaded with the corpus knowledge. Must be called before query_corpus.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Name of the corpus to prime"}},required:["name"],additionalProperties:!0},handler:async e=>{let{name:t,...r}=e;if(typeof t!="string"||t.trim()==="")throw new Error("Missing required argument: name");return await _t(`/api/corpus/${encodeURIComponent(t)}/prime`,{body:r})}},{name:"query_corpus",description:"Ask a question to a primed knowledge corpus. The corpus must be primed first with prime_corpus.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Name of the corpus to query"},question:{type:"string",description:"The question to ask"}},required:["name","question"],additionalProperties:!0},handler:async e=>{let{name:t,...r}=e;if(typeof t!="string"||t.trim()==="")throw new Error("Missing required argument: name");return await _t(`/api/corpus/${encodeURIComponent(t)}/query`,{body:r})}},{name:"rebuild_corpus",description:"Rebuild a knowledge corpus from its stored filter \u2014 re-runs the search to refresh with new observations. Does not re-prime the session.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Name of the corpus to rebuild"}},required:["name"],additionalProperties:!0},handler:async e=>{let{name:t,...r}=e;if(typeof t!="string"||t.trim()==="")throw new Error("Missing required argument: name");return await _t(`/api/corpus/${encodeURIComponent(t)}/rebuild`,{body:r})}},{name:"reprime_corpus",description:"Create a fresh knowledge agent session for a corpus, clearing prior Q&A context. Use when conversation has drifted or after rebuilding.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Name of the corpus to reprime"}},required:["name"],additionalProperties:!0},handler:async e=>{let{name:t,...r}=e;if(typeof t!="string"||t.trim()==="")throw new Error("Missing required argument: name");return await _t(`/api/corpus/${encodeURIComponent(t)}/reprime`,{body:r})}}],ld=new vi({name:"claude-mem",version:ZI},{capabilities:{tools:{}}});ld.setRequestHandler(vc,async()=>({tools:gb(wb,Gi()).map(t=>({name:t.name,description:t.description,inputSchema:t.inputSchema}))}));ld.setRequestHandler(Un,async e=>{let t=wb.find(r=>r.name===e.params.name);if(!t)throw new Error(`Unknown tool: ${e.params.name}`);try{return await t.handler(e.params.arguments||{})}catch(r){return _.error("SYSTEM","Tool execution failed",{tool:e.params.name},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Tool execution failed: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}});var tA=3e4,$o=null,_b=!1;function Ji(){Oo("stdio-closed")}function kb(e){_.warn("SYSTEM","MCP stdio stream errored, shutting down",{message:e.message}),Oo("stdio-error")}function rA(){process.stdin.on("end",Ji),process.stdin.on("close",Ji),process.stdin.on("error",kb)}function nA(){process.stdin.off("end",Ji),process.stdin.off("close",Ji),process.stdin.off("error",kb)}function oA(){if(process.platform==="win32")return;let e=process.ppid;$o=setInterval(()=>{(process.ppid===1||process.ppid!==e)&&(_.info("SYSTEM","Parent process died, self-exiting to prevent orphan",{initialPpid:e,currentPpid:process.ppid}),Oo())},tA),$o.unref&&$o.unref()}function Oo(e="shutdown"){_b||(_b=!0,$o&&clearInterval($o),nA(),_.info("SYSTEM","MCP server shutting down",{reason:e}),process.exit(0))}process.on("SIGTERM",Oo);process.on("SIGINT",Oo);function sA(){let e=(0,yb.homedir)(),t=[(0,nr.resolve)(e,".claude","plugins","marketplaces","thedotmack"),(0,nr.resolve)(e,".config","claude","plugins","marketplaces","thedotmack")],r=t.some(i=>i&&(0,Yi.existsSync)(i)),n=[(0,nr.resolve)(e,".claude","plugins","cache","thedotmack","claude-mem"),(0,nr.resolve)(e,".config","claude","plugins","cache","thedotmack","claude-mem")],o=n.some(i=>i&&(0,Yi.existsSync)(i)),s=n[0];!r&&o&&_.error("SYSTEM","claude-mem MCP started but no marketplace directory was found at ~/.claude/plugins/marketplaces/thedotmack or the XDG equivalent. The IDE plugin loader needs that directory to fire claude-mem hooks (SessionStart, PostToolUse, Stop, etc.). Without it, MCP search will work but no new memories will be captured. To self-heal, run: node ~/.claude/plugins/cache/thedotmack/claude-mem/*/scripts/smart-install.js (or reinstall the plugin from the marketplace).",{marketplaceCandidates:t,cacheRoot:s})}function iA(){try{sA()}catch(e){_.warn("SYSTEM","checkMarketplaceMarker failed (non-fatal startup check)",void 0,e instanceof Error?e:new Error(String(e)))}}async function aA(){let e=new ki;rA(),await ld.connect(e),_.info("SYSTEM","Claude-mem search server started"),iA(),oA(),setTimeout(async()=>{if(Gi()==="server"){_.info("SYSTEM","MCP runtime=server \u2014 skipping worker auto-start",void 0,{});return}await eA()?_.info("SYSTEM","Worker available",void 0,{}):(_.error("SYSTEM","Worker not available",void 0,{}),_.error("SYSTEM","Tools will fail until Worker is started"),_.error("SYSTEM","Start Worker with: npm run worker:restart"))},0)}aA().catch(e=>{_.error("SYSTEM","Fatal error",void 0,e),process.exit(0)});
|
|
254
|
+
//# sourceMappingURL=mcp-server.cjs.map
|