claude-mem 12.5.0 → 12.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "Claude-Mem (Persistent Memory)",
|
|
4
4
|
"description": "Official OpenClaw plugin for Claude-Mem. Records observations from embedded runner sessions and streams them to messaging channels.",
|
|
5
5
|
"kind": "memory",
|
|
6
|
-
"version": "
|
|
6
|
+
"version": "12.5.1",
|
|
7
7
|
"author": "thedotmack",
|
|
8
8
|
"homepage": "https://claude-mem.com",
|
|
9
9
|
"skills": ["skills/make-plan", "skills/do"],
|
package/package.json
CHANGED
package/plugin/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "claude-mem-plugin",
|
|
3
|
-
"version": "12.5.
|
|
3
|
+
"version": "12.5.1",
|
|
4
4
|
"private": true,
|
|
5
5
|
"description": "Runtime dependencies for claude-mem bundled hooks",
|
|
6
6
|
"type": "module",
|
|
@@ -35,6 +35,9 @@
|
|
|
35
35
|
"overrides": {
|
|
36
36
|
"tree-sitter": "^0.25.0"
|
|
37
37
|
},
|
|
38
|
+
"trustedDependencies": [
|
|
39
|
+
"tree-sitter-cli"
|
|
40
|
+
],
|
|
38
41
|
"engines": {
|
|
39
42
|
"node": ">=18.0.0",
|
|
40
43
|
"bun": ">=1.0.0"
|
|
@@ -149,7 +149,7 @@ ${m}`}let c=o.lineStart;for(let u=o.lineStart-1;u>=0;u--){let d=i[u].trim();if(d
|
|
|
149
149
|
${l}`}var Yu=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",".ex",".exs",".lua",".scala",".sc",".sh",".bash",".zsh",".hs",".zig",".css",".scss",".toml",".yml",".yaml",".sql",".md",".mdx"]),FS=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),HS=512*1024;async function*Bu(t,e,r=20,n){if(r<=0)return;let s;try{s=await(0,Ht.readdir)(t,{withFileTypes:!0})}catch(o){y.debug("WORKER",`walkDir: failed to read directory ${t}`,void 0,o instanceof Error?o:void 0);return}for(let o of s){if(o.name.startsWith(".")&&o.name!=="."||FS.has(o.name))continue;let i=(0,Fr.join)(t,o.name);if(o.isDirectory())yield*Bu(i,e,r-1,n);else if(o.isFile()){let c=o.name.slice(o.name.lastIndexOf("."));(Yu.has(c)||n&&n.has(c))&&(yield i)}}}async function WS(t){try{let e=await(0,Ht.stat)(t);if(e.size>HS||e.size===0)return null;let r=await(0,Ht.readFile)(t,"utf-8");return r.slice(0,1e3).includes("\0")?null:r}catch(e){return y.debug("WORKER",`safeReadFile: failed to read ${t}`,void 0,e instanceof Error?e:void 0),null}}async function Ju(t,e,r={}){let n=r.maxResults||20,s=e.toLowerCase(),o=s.split(/[\s_\-./]+/).filter(S=>S.length>0),i=r.projectRoot||t,c=Ur(i),l=new Set;for(let S of Object.values(c.grammars))for(let w of S.extensions)Yu.has(w)||l.add(w);let u=[];for await(let S of Bu(t,t,20,l.size>0?l:void 0)){if(r.filePattern&&!(0,Fr.relative)(t,S).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let w=await WS(S);w&&u.push({absolutePath:S,relativePath:(0,Fr.relative)(t,S),content:w})}let d=Vu(u,i),f=[],p=[],m=0;for(let[S,w]of d){m+=VS(w);let k=ns(S.toLowerCase(),o)>0,le=[],fe=(Vt,yt)=>{for(let H of Vt){let Ge=0,Ee="",Gt=ns(H.name.toLowerCase(),o);Gt>0&&(Ge+=Gt*3,Ee="name match"),H.signature.toLowerCase().includes(s)&&(Ge+=2,Ee=Ee?`${Ee} + signature`:"signature match"),H.jsdoc&&H.jsdoc.toLowerCase().includes(s)&&(Ge+=1,Ee=Ee?`${Ee} + jsdoc`:"jsdoc match"),Ge>0&&(k=!0,le.push({filePath:S,symbolName:yt?`${yt}.${H.name}`:H.name,kind:H.kind,signature:H.signature,jsdoc:H.jsdoc,lineStart:H.lineStart,lineEnd:H.lineEnd,matchReason:Ee})),H.children&&fe(H.children,H.name)}};fe(w.symbols),k&&(f.push(w),p.push(...le))}p.sort((S,w)=>{let A=ns(S.symbolName.toLowerCase(),o);return ns(w.symbolName.toLowerCase(),o)-A});let h=p.slice(0,n),g=new Set(h.map(S=>S.filePath)),_=f.filter(S=>g.has(S.filePath)).slice(0,n),E=_.reduce((S,w)=>S+w.foldedTokenEstimate,0);return{foldedFiles:_,matchingSymbols:h,totalFilesScanned:u.length,totalSymbolsFound:m,tokenEstimate:E}}function ns(t,e){let r=0;for(let n of e)if(t===n)r+=10;else if(t.includes(n))r+=5;else{let s=0,o=0;for(let i of n){let c=t.indexOf(i,s);c!==-1&&(o++,s=c+1)}o===n.length&&(r+=1)}return r}function VS(t){let e=t.symbols.length;for(let r of t.symbols)r.children&&(e+=r.children.length);return e}function Zu(t,e){let r=[];if(r.push(`\u{1F50D} Smart Search: "${e}"`),r.push(` Scanned ${t.totalFilesScanned} files, found ${t.totalSymbolsFound} symbols`),r.push(` ${t.matchingSymbols.length} matches across ${t.foldedFiles.length} files (~${t.tokenEstimate} tokens for folded view)`),r.push(""),t.matchingSymbols.length===0)return r.push(" No matching symbols found."),r.join(`
|
|
150
150
|
`);r.push("\u2500\u2500 Matching Symbols \u2500\u2500"),r.push("");for(let n of t.matchingSymbols){if(r.push(` ${n.kind} ${n.symbolName} (${n.filePath}:${n.lineStart+1})`),r.push(` ${n.signature}`),n.jsdoc){let s=n.jsdoc.split(`
|
|
151
151
|
`).find(o=>o.replace(/^[\s*/]+/,"").trim().length>0);s&&r.push(` \u{1F4AC} ${s.replace(/^[\s*/]+/,"").trim()}`)}r.push("")}r.push("\u2500\u2500 Folded File Views \u2500\u2500"),r.push("");for(let n of t.foldedFiles)r.push(Ft(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(`
|
|
152
|
-
`)}var Gi=require("node:fs/promises"),ss=require("node:fs"),Pe=require("node:path"),ed=require("node:os"),td=require("node:url"),nE={},GS="12.5.
|
|
152
|
+
`)}var Gi=require("node:fs/promises"),ss=require("node:fs"),Pe=require("node:path"),ed=require("node:os"),td=require("node:url"),nE={},GS="12.5.1";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var rd=!1,nd=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,Pe.dirname)((0,td.fileURLToPath)(nE.url))}catch{return rd=!0,process.cwd()}})(),Ki=(0,Pe.resolve)(nd,"worker-service.cjs");function KS(){rd&&((0,ss.existsSync)(Ki)||y.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:Ki,mcpServerDir:nd}))}var Xu={search:"/api/search",timeline:"/api/timeline"};async function Vi(t,e){y.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t,params:e});let r=new URLSearchParams;for(let[s,o]of Object.entries(e))o!=null&&r.append(s,String(o));let n=`${t}?${r}`;try{let s=await es(n);if(!s.ok){let i=await s.text();throw new Error(`Worker API error (${s.status}): ${i}`)}let o=await s.json();return y.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),o}catch(s){return y.error("SYSTEM","\u2190 Worker API error",{endpoint:t},s instanceof Error?s:new Error(String(s))),{content:[{type:"text",text:`Error calling Worker API: ${s instanceof Error?s.message:String(s)}`}],isError:!0}}}async function YS(t,e){let r=await es(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){let s=await r.text();throw new Error(`Worker API error (${r.status}): ${s}`)}let n=await r.json();return y.debug("HTTP","Worker API success (POST)",void 0,{endpoint:t}),{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}async function Wt(t,e){y.debug("HTTP","Worker API request (POST)",void 0,{endpoint:t});try{return await YS(t,e)}catch(r){return y.error("HTTP","Worker API error (POST)",{endpoint:t},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 BS(){try{return(await es("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}async function JS(){if(await BS())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),KS();try{let t=xi(),e=await Iu(t,Ki);return e==="dead"&&y.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.)."),e!=="dead"}catch(t){return y.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,t instanceof Error?t:new Error(String(t))),!1}}var sd=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
|
|
153
153
|
1. search(query) \u2192 Get index with IDs (~50-100 tokens/result)
|
|
154
154
|
2. timeline(anchor=ID) \u2192 Get context around interesting results
|
|
155
155
|
3. get_observations([IDs]) \u2192 Fetch full details ONLY for filtered IDs
|
|
@@ -1035,7 +1035,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
1035
1035
|
SELECT cwd FROM pending_messages
|
|
1036
1036
|
WHERE cwd IS NOT NULL AND cwd != ''
|
|
1037
1037
|
GROUP BY cwd
|
|
1038
|
-
`).all();for(let{cwd:u}of c){let l=LF(u);l&&n.add(l)}}finally{s?.close()}if(n.size===0)return v.debug("SYSTEM","Worktree adoption found no known parent repos"),i;for(let o of n)try{let a=await _R({repoPath:o,dataDirectory:e,dryRun:t.dryRun});i.push(a)}catch(a){v.warn("SYSTEM","Worktree adoption failed for parent repo (continuing)",{repoPath:o,error:a instanceof Error?a.message:String(a)})}return i}var j5=Ee(Wb(),1),z5=Ee(require("http"),1),FP=Ee(require("fs"),1),Ym=Ee(require("path"),1);var DP=["search","context","summarize","import","export"],E5=["workflow","search_params","examples","all"];ne();var jP=Ee(Wb(),1),C5=Ee(R5(),1),P5=Ee(require("path"),1);ht();ne();function zP(t){let e=[];e.push(jP.default.json({limit:"5mb"})),e.push((0,C5.default)({origin:(n,s)=>{!n||n.startsWith("http://localhost:")||n.startsWith("http://127.0.0.1:")?s(null,!0):s(new Error("CORS not allowed"))},methods:["GET","HEAD","POST","PUT","PATCH","DELETE"],allowedHeaders:["Content-Type","X-Requested-With"],credentials:!1})),e.push((n,s,o)=>{let c=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(f=>n.path.endsWith(f)),u=n.path==="/api/logs";if(n.path.startsWith("/health")||n.path==="/"||c||u)return o();let l=Date.now(),d=`${n.method}-${Date.now()}`,p=t(n.method,n.path,n.body);v.debug("HTTP",`\u2192 ${n.method} ${n.path}`,{requestId:d},p);let m=s.send.bind(s);s.send=function(f){let h=Date.now()-l;return v.debug("HTTP",`\u2190 ${s.statusCode} ${n.path}`,{requestId:d,duration:`${h}ms`}),m(f)},o()});let r=Fn(),i=P5.default.join(r,"plugin","ui");return e.push(jP.default.static(i)),e}function Vm(t,e,r){let i=t.ip||t.connection.remoteAddress||"";if(!(i==="127.0.0.1"||i==="::1"||i==="::ffff:127.0.0.1"||i==="localhost")){v.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:t.path,clientIp:i,method:t.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}r()}function UP(t,e,r){if(!r||Object.keys(r).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let i=r.tool_name||"?",n=r.tool_input;return`tool=${v.formatTool(i,n)}`}return e.includes("/summarize")?"requesting summary":""}Km();ca();lo();oa();function Cl(t,e,r){t.on("finish",async()=>{try{await r()}finally{process.exit(0)}}),t.json(e)}var U5=Ym.default.resolve(__dirname,"../skills/mem-search"),m0e=Ym.default.join(U5,"operations"),LP=Ym.default.join(U5,"SKILL.md"),M5=(()=>{try{let t=FP.readFileSync(LP,"utf-8");return v.info("SYSTEM","Cached SKILL.md at boot",{path:LP,bytes:Buffer.byteLength(t,"utf-8")}),t}catch(t){return v.debug("SYSTEM","SKILL.md not present at boot, /api/instructions will 404 for topic queries",{path:LP,message:t instanceof Error?t.message:String(t)}),null}})(),f0e=(()=>{let t=new Map;for(let e of DP){let r=Ym.default.join(m0e,`${e}.md`);try{t.set(e,FP.readFileSync(r,"utf-8"))}catch(i){v.debug("SYSTEM","Operation instruction file not present at boot",{path:r,message:i instanceof Error?i.message:String(i)})}}return t.size>0&&v.info("SYSTEM","Cached operation instruction files at boot",{count:t.size,operations:Array.from(t.keys())}),t})(),D5="12.5.
|
|
1038
|
+
`).all();for(let{cwd:u}of c){let l=LF(u);l&&n.add(l)}}finally{s?.close()}if(n.size===0)return v.debug("SYSTEM","Worktree adoption found no known parent repos"),i;for(let o of n)try{let a=await _R({repoPath:o,dataDirectory:e,dryRun:t.dryRun});i.push(a)}catch(a){v.warn("SYSTEM","Worktree adoption failed for parent repo (continuing)",{repoPath:o,error:a instanceof Error?a.message:String(a)})}return i}var j5=Ee(Wb(),1),z5=Ee(require("http"),1),FP=Ee(require("fs"),1),Ym=Ee(require("path"),1);var DP=["search","context","summarize","import","export"],E5=["workflow","search_params","examples","all"];ne();var jP=Ee(Wb(),1),C5=Ee(R5(),1),P5=Ee(require("path"),1);ht();ne();function zP(t){let e=[];e.push(jP.default.json({limit:"5mb"})),e.push((0,C5.default)({origin:(n,s)=>{!n||n.startsWith("http://localhost:")||n.startsWith("http://127.0.0.1:")?s(null,!0):s(new Error("CORS not allowed"))},methods:["GET","HEAD","POST","PUT","PATCH","DELETE"],allowedHeaders:["Content-Type","X-Requested-With"],credentials:!1})),e.push((n,s,o)=>{let c=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(f=>n.path.endsWith(f)),u=n.path==="/api/logs";if(n.path.startsWith("/health")||n.path==="/"||c||u)return o();let l=Date.now(),d=`${n.method}-${Date.now()}`,p=t(n.method,n.path,n.body);v.debug("HTTP",`\u2192 ${n.method} ${n.path}`,{requestId:d},p);let m=s.send.bind(s);s.send=function(f){let h=Date.now()-l;return v.debug("HTTP",`\u2190 ${s.statusCode} ${n.path}`,{requestId:d,duration:`${h}ms`}),m(f)},o()});let r=Fn(),i=P5.default.join(r,"plugin","ui");return e.push(jP.default.static(i)),e}function Vm(t,e,r){let i=t.ip||t.connection.remoteAddress||"";if(!(i==="127.0.0.1"||i==="::1"||i==="::ffff:127.0.0.1"||i==="localhost")){v.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:t.path,clientIp:i,method:t.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}r()}function UP(t,e,r){if(!r||Object.keys(r).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let i=r.tool_name||"?",n=r.tool_input;return`tool=${v.formatTool(i,n)}`}return e.includes("/summarize")?"requesting summary":""}Km();ca();lo();oa();function Cl(t,e,r){t.on("finish",async()=>{try{await r()}finally{process.exit(0)}}),t.json(e)}var U5=Ym.default.resolve(__dirname,"../skills/mem-search"),m0e=Ym.default.join(U5,"operations"),LP=Ym.default.join(U5,"SKILL.md"),M5=(()=>{try{let t=FP.readFileSync(LP,"utf-8");return v.info("SYSTEM","Cached SKILL.md at boot",{path:LP,bytes:Buffer.byteLength(t,"utf-8")}),t}catch(t){return v.debug("SYSTEM","SKILL.md not present at boot, /api/instructions will 404 for topic queries",{path:LP,message:t instanceof Error?t.message:String(t)}),null}})(),f0e=(()=>{let t=new Map;for(let e of DP){let r=Ym.default.join(m0e,`${e}.md`);try{t.set(e,FP.readFileSync(r,"utf-8"))}catch(i){v.debug("SYSTEM","Operation instruction file not present at boot",{path:r,message:i instanceof Error?i.message:String(i)})}}return t.size>0&&v.info("SYSTEM","Cached operation instruction files at boot",{count:t.size,operations:Array.from(t.keys())}),t})(),D5="12.5.1",Bb=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,j5.default)(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,r){return new Promise((i,n)=>{let s=z5.default.createServer(this.app);this.server=s;let o=c=>{s.off("listening",a),n(c)},a=()=>{s.off("error",o),v.info("SYSTEM","HTTP server started",{host:r,port:e,pid:process.pid}),i()};s.once("error",o),s.once("listening",a),s.listen(e,r)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{this.server.close(i=>i?r(i):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,v.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use($5),this.app.use(N5)}setupMiddleware(){zP(UP).forEach(r=>this.app.use(r))}setupCoreRoutes(){this.app.get("/api/health",(e,r)=>{r.status(200).json({status:"ok",version:D5,workerPath:this.options.workerPath,uptime:Date.now()-this.startTime,managed:process.env.CLAUDE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.options.getInitializationComplete(),mcpReady:this.options.getMcpReady(),ai:this.options.getAiStatus()})}),this.app.get("/api/readiness",(e,r)=>{this.options.getInitializationComplete()?r.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):r.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(e,r)=>{r.status(200).json({version:D5})}),this.app.get("/api/instructions",(e,r)=>{let i=e.query.topic||"all",n=e.query.operation;if(i&&!E5.includes(i))return r.status(400).json({error:"Invalid topic"});if(n&&!DP.includes(n))return r.status(400).json({error:"Invalid operation"});if(n){let o=f0e.get(n);return o===void 0?(v.debug("HTTP","Instruction file not cached at boot",{operation:n}),r.status(404).json({error:"Instruction not found"})):r.json({content:[{type:"text",text:o}]})}if(M5===null)return v.debug("HTTP","SKILL.md not cached at boot",{topic:i}),r.status(404).json({error:"Instruction not found"});let s=this.extractInstructionSection(M5,i);r.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",Vm,async(e,r)=>{process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(r.json({status:"restarting"}),v.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):Cl(r,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",Vm,async(e,r)=>{process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(r.json({status:"shutting_down"}),v.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown"})):Cl(r,{status:"shutting_down"},()=>this.options.onShutdown())}),this.app.get("/api/admin/doctor",Vm,(e,r)=>{let o=qr().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:ei(f.pid)?"alive":"dead",startedAt:f.startedAt})),a=o.filter(f=>f.status==="dead").map(f=>f.pid),c=!Object.keys(process.env).some(f=>q1.has(f)||F1.some(h=>f.startsWith(h))),u=Date.now()-this.startTime,l=Math.floor(u/1e3),d=Math.floor(l/3600),p=Math.floor(l%3600/60),m=d>0?`${d}h ${p}m`:`${p}m`;r.json({supervisor:{running:!0,pid:process.pid,uptime:m},processes:o,health:{deadProcessPids:a,envClean:c}})})}extractInstructionSection(e,r){let i={workflow:this.extractBetween(e,"## The Workflow","## Search Parameters"),search_params:this.extractBetween(e,"## Search Parameters","## Examples"),examples:this.extractBetween(e,"## Examples","## Why This Workflow"),all:e};return i[r]||i.all}extractBetween(e,r,i){let n=e.indexOf(r),s=e.indexOf(i);return n===-1?e:s===-1?e.substring(n):e.substring(n,s).trim()}};var At=Ee(require("path"),1),Xm=require("os"),Jt=require("fs"),q5=require("child_process"),H5=require("util");ne();vn();ht();var ji=require("fs"),Jm=require("path");ne();function L5(t){try{return(0,ji.existsSync)(t)?JSON.parse((0,ji.readFileSync)(t,"utf-8")):{}}catch(e){return v.error("CONFIG","Failed to read Cursor registry, using empty registry",{file:t,error:e instanceof Error?e.message:String(e)}),{}}}function F5(t,e){let r=(0,Jm.join)(t,"..");(0,ji.mkdirSync)(r,{recursive:!0}),(0,ji.writeFileSync)(t,JSON.stringify(e,null,2))}function qP(t,e){let r=(0,Jm.join)(t,".cursor","rules"),i=(0,Jm.join)(r,"claude-mem-context.mdc"),n=`${i}.tmp`;(0,ji.mkdirSync)(r,{recursive:!0});let s=`---
|
|
1039
1039
|
alwaysApply: true
|
|
1040
1040
|
description: "Claude-mem context from past sessions (auto-updated)"
|
|
1041
1041
|
---
|
|
@@ -1748,7 +1748,7 @@ ${s.formatTableHeader()}`,m=d.map((f,h)=>s.formatObservationIndex(f,h));i.json({
|
|
|
1748
1748
|
`);fr(Ei);let n=this.findClaudeExecutable(),s=Qn(ym()),o=ah({prompt:i,options:{model:this.getModelId(),cwd:Ei,disallowedTools:ree,pathToClaudeCodeExecutable:n,env:s,mcpServers:{},settingSources:[],strictMcpConfig:!0}}),a;try{for await(let c of o)c.session_id&&(a=c.session_id),c.type==="result"&&v.info("WORKER",`Knowledge agent primed for corpus "${e.name}"`)}catch(c){if(a)c instanceof Error?v.debug("WORKER",`SDK process exited after priming corpus "${e.name}" \u2014 session captured, continuing`,{},c):v.debug("WORKER",`SDK process exited after priming corpus "${e.name}" \u2014 session captured, continuing (non-Error thrown)`,{thrownValue:String(c)});else throw c}if(!a)throw new Error(`Failed to capture session_id while priming corpus "${e.name}"`);return e.session_id=a,this.corpusStore.write(e),a}async query(e,r){if(!e.session_id)throw new Error(`Corpus "${e.name}" has no session \u2014 call prime first`);try{let i=await this.executeQuery(e,r);return i.session_id!==e.session_id&&(e.session_id=i.session_id,this.corpusStore.write(e)),i}catch(i){if(!this.isSessionResumeError(i))throw i instanceof Error?v.error("WORKER",`Query failed for corpus "${e.name}"`,{},i):v.error("WORKER",`Query failed for corpus "${e.name}" (non-Error thrown)`,{thrownValue:String(i)}),i;v.info("WORKER",`Session expired for corpus "${e.name}", auto-repriming...`),await this.prime(e);let n=this.corpusStore.read(e.name);if(!n||!n.session_id)throw new Error(`Auto-reprime failed for corpus "${e.name}"`);let s=await this.executeQuery(n,r);return s.session_id!==n.session_id&&(n.session_id=s.session_id,this.corpusStore.write(n)),s}}async reprime(e){return e.session_id=null,this.prime(e)}isSessionResumeError(e){let r=e instanceof Error?e.message:String(e);return/session|resume|expired|invalid.*session|not found/i.test(r)}async executeQuery(e,r){fr(Ei);let i=this.findClaudeExecutable(),n=Qn(ym()),s=ah({prompt:r,options:{model:this.getModelId(),resume:e.session_id,cwd:Ei,disallowedTools:ree,pathToClaudeCodeExecutable:i,env:n,mcpServers:{},settingSources:[],strictMcpConfig:!0}}),o="",a=e.session_id;try{for await(let c of s)c.session_id&&(a=c.session_id),c.type==="assistant"&&(o=c.message.content.filter(l=>l.type==="text").map(l=>l.text).join(""))}catch(c){if(o)c instanceof Error?v.debug("WORKER","SDK process exited after query \u2014 answer captured, continuing",{},c):v.debug("WORKER","SDK process exited after query \u2014 answer captured, continuing (non-Error thrown)",{thrownValue:String(c)});else throw c}return{answer:o,session_id:a}}getModelId(){return ye.loadFromFile(mt).CLAUDE_MEM_MODEL}findClaudeExecutable(){let e=ye.loadFromFile(mt);if(e.CLAUDE_CODE_PATH){let{existsSync:r}=require("fs");if(!r(e.CLAUDE_CODE_PATH))throw new Error(`CLAUDE_CODE_PATH is set to "${e.CLAUDE_CODE_PATH}" but the file does not exist.`);return e.CLAUDE_CODE_PATH}if(process.platform==="win32")try{return(0,rD.execSync)("where claude.cmd",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"]}),"claude.cmd"}catch{}try{let r=(0,rD.execSync)(process.platform==="win32"?"where claude":"which claude",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"]}).trim().split(`
|
|
1749
1749
|
`)[0].trim();if(r)return r}catch(r){r instanceof Error?v.debug("WORKER","Claude executable auto-detection failed",{},r):v.debug("WORKER","Claude executable auto-detection failed (non-Error thrown)",{thrownValue:String(r)})}throw new Error(`Claude executable not found. Please either:
|
|
1750
1750
|
1. Add "claude" to your system PATH, or
|
|
1751
|
-
2. Set CLAUDE_CODE_PATH in ~/.claude-mem/settings.json`)}};var WMe={},LMe="12.5.
|
|
1751
|
+
2. Set CLAUDE_CODE_PATH in ~/.claude-mem/settings.json`)}};var WMe={},LMe="12.5.1";function Aee(t,e){return{continue:!0,suppressOutput:!0,status:t,...e&&{message:e}}}var aw=class t{server;startTime=Date.now();mcpClient;mcpReady=!1;initializationCompleteFlag=!1;isShuttingDown=!1;dbManager;sessionManager;sseBroadcaster;sdkAgent;geminiAgent;openRouterAgent;paginationHelper;settingsManager;sessionEventBroadcaster;completionHandler;corpusStore;searchRoutes=null;chromaMcpManager=null;transcriptWatcher=null;initializationComplete;resolveInitialization;lastAiInteraction=null;constructor(){this.initializationComplete=new Promise(e=>{this.resolveInitialization=e}),this.dbManager=new Kb,this.sessionManager=new Qb(this.dbManager),this.sseBroadcaster=new e_,this.sdkAgent=new JS(this.dbManager,this.sessionManager),this.geminiAgent=new XS(this.dbManager,this.sessionManager),this.openRouterAgent=new t0(this.dbManager,this.sessionManager),this.paginationHelper=new r0(this.dbManager),this.settingsManager=new n0(this.dbManager),this.sessionEventBroadcaster=new c0(this.sseBroadcaster,this),this.completionHandler=new u0(this.sessionManager,this.sessionEventBroadcaster,this.dbManager),this.corpusStore=new rw,dB({sessionManager:this.sessionManager,dbManager:this.dbManager,eventBroadcaster:this.sessionEventBroadcaster}),this.sessionManager.setOnPendingMutate(()=>this.broadcastProcessingStatus()),this.mcpClient=new Ju({name:"worker-search-proxy",version:LMe},{capabilities:{}}),this.server=new Bb({getInitializationComplete:()=>this.initializationCompleteFlag,getMcpReady:()=>this.mcpReady,onShutdown:()=>this.shutdown(),onRestart:()=>this.shutdown(),workerPath:__filename,getAiStatus:()=>{let e="claude";return Ed()&&Uc()?e="openrouter":xd()&&zc()&&(e="gemini"),{provider:e,authMethod:_y(),lastInteraction:this.lastAiInteraction?{timestamp:this.lastAiInteraction.timestamp,success:this.lastAiInteraction.success,...this.lastAiInteraction.error&&{error:this.lastAiInteraction.error}}:null}}}),this.registerRoutes(),this.registerSignalHandlers()}registerSignalHandlers(){eF(async()=>{this.isShuttingDown=!0,await this.shutdown()})}registerRoutes(){this.server.registerRoutes(new tw),this.server.app.get("/api/context/inject",async(r,i,n)=>{if(!this.initializationCompleteFlag||!this.searchRoutes){v.warn("SYSTEM","Context requested before initialization complete, returning empty"),i.status(200).json({content:[{type:"text",text:""}]});return}n()}),this.server.app.use("/api",async(r,i,n)=>{if(r.path==="/chroma/status"||r.path==="/health"||r.path==="/readiness"||r.path==="/version"){n();return}if(this.initializationCompleteFlag){n();return}let s=12e4,o=new Promise((a,c)=>setTimeout(()=>c(new Error("Database initialization timeout")),s));try{await Promise.race([this.initializationComplete,o]),n()}catch(a){a instanceof Error?v.error("WORKER",`Request to ${r.method} ${r.path} rejected \u2014 DB not initialized`,{},a):v.error("WORKER",`Request to ${r.method} ${r.path} rejected \u2014 DB not initialized with non-Error`,{},new Error(String(a))),i.status(503).json({error:"Service initializing",message:"Database is still initializing, please retry"});return}}),this.server.registerRoutes(new j0(this.sseBroadcaster,this.dbManager,this.sessionManager));let e=new U0(this.sessionManager,this.dbManager,this.sdkAgent,this.geminiAgent,this.openRouterAgent,this.sessionEventBroadcaster,this,this.completionHandler);this.server.registerRoutes(e),pB((r,i)=>e.ensureGeneratorRunning(r,i)),this.server.registerRoutes(new L0(this.paginationHelper,this.dbManager,this.sessionManager,this.sseBroadcaster,this,this.startTime)),this.server.registerRoutes(new Y0(this.settingsManager)),this.server.registerRoutes(new X0),this.server.registerRoutes(new Q0(this.dbManager,"claude-mem"))}async start(){let e=ri(),r=J1();await Q6(),await this.server.listen(e,r),kF({pid:process.pid,port:e,startedAt:new Date().toISOString()}),qr().registerProcess("worker",{pid:process.pid,type:"worker",startedAt:new Date().toISOString()}),v.info("SYSTEM","Worker started",{host:r,port:e,pid:process.pid}),this.initializeBackground().catch(i=>{v.error("SYSTEM","Background initialization failed",{},i)})}async initializeBackground(){try{v.info("WORKER","Background initialization starting...");let{ModeManager:e}=await Promise.resolve().then(()=>(_n(),tB)),{SettingsDefaultsManager:r}=await Promise.resolve().then(()=>(Bt(),I6)),{USER_SETTINGS_PATH:i}=await Promise.resolve().then(()=>(ht(),$6)),n=r.loadFromFile(i),s=n.CLAUDE_MEM_MODE;e.getInstance().loadMode(s),v.info("SYSTEM",`Mode loaded: ${s}`),(n.CLAUDE_MEM_MODE==="local"||!n.CLAUDE_MEM_MODE)&&(v.info("WORKER","Checking for one-time Chroma migration..."),TF()),v.info("WORKER","Checking for one-time CWD remap..."),IF(),v.info("WORKER","Adopting merged worktrees (background)..."),FF({}).then(g=>{if(g)for(let y of g)(y.adoptedObservations>0||y.adoptedSummaries>0||y.chromaUpdates>0)&&v.info("SYSTEM","Merged worktrees adopted in background",y),y.errors.length>0&&v.warn("SYSTEM","Worktree adoption had per-branch errors",{repoPath:y.repoPath,errors:y.errors})}).catch(g=>{v.error("WORKER","Worktree adoption failed (background)",{},g instanceof Error?g:new Error(String(g)))}),n.CLAUDE_MEM_CHROMA_ENABLED!=="false"?(this.chromaMcpManager=Ti.getInstance(),v.info("SYSTEM","ChromaMcpManager initialized (lazy - connects on first use)")):v.info("SYSTEM","Chroma disabled via CLAUDE_MEM_CHROMA_ENABLED=false, skipping ChromaMcpManager"),v.info("WORKER","Initializing database manager..."),await this.dbManager.initialize();let a=this.dbManager.getSessionStore().db.prepare(`
|
|
1752
1752
|
UPDATE pending_messages
|
|
1753
1753
|
SET status = 'pending'
|
|
1754
1754
|
WHERE status = 'processing'
|