Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More
TypeScript aiai-agentsai-memoryanthropicartificial-intelligencechromadbclaudeclaude-agent-sdkclaude-agentsclaude-codeclaude-code-pluginclaude-skillsembeddingslong-term-memorymem0memory-engineopenmemoryragsqlitesupermemory
#!/usr/bin/env bun
"use strict";var W=require("child_process"),a=require("fs"),x=require("os"),i=require("path");var H="1.2.16";function L(n){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(n.trim());return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function D(n){let t=L(n??""),e=L(H);if(!t)return!1;for(let r=0;r<3;r++)if(t[r]!==e[r])return t[r]>e[r];return!0}var O=require("child_process"),S=require("fs"),R=require("os"),d=require("path");var b=require("node:path");var $=new Set([".cmd",".bat"]),F=new Set([".exe",".com"]),hn=new Set([...F,...$]);function N(n,t=process.cwd()){let r=/^[a-zA-Z]:[\\/]|\\\\/.test(n)?b.win32.dirname(n):(0,b.dirname)(n),o=s=>s.replace(/[\\/]+/g,"/").replace(/\/+$/,"").toLowerCase();return o(r)===o(t)}var T=require("os"),A=require("path");function _(n,t=process.platform,e=(0,T.homedir)()){return typeof n!="string"||n.length===0?n:n==="~"?e:n.startsWith("~/")||t==="win32"&&n.startsWith("~\\")?(0,A.join)(e,n.slice(2)):n}var J=1500;function j(n,t){let e=t.SystemRoot||t.SYSTEMROOT||t.windir||t.WINDIR||"C:\\Windows";return(0,d.join)(e,"System32",n)}function G(n,t){let e=typeof n.CLAUDE_MEM_DATA_DIR=="string"?n.CLAUDE_MEM_DATA_DIR.trim():"",r=e?_(e,"win32",t):(0,d.join)(t,".claude-mem");return(0,d.join)(r,"run","bun-path")}function Y(n,t,e){if(!n)return null;try{let r=(0,S.readFileSync)(n,"utf-8").trim();return!r||N(r,e)?null:t(r)?r:null}catch{return null}}function I(n,t){if(n)try{(0,S.mkdirSync)((0,d.dirname)(n),{recursive:!0,mode:448}),(0,S.writeFileSync)(n,`${t}
`,{mode:384})}catch{}}function X(n,t,e){let r=typeof t.BUN_INSTALL=="string"?t.BUN_INSTALL.trim():"",o=typeof t.BUN=="string"?t.BUN.trim():"",s=typeof t.BUN_PATH=="string"?t.BUN_PATH.trim():"";return n==="win32"?[o,s,r?(0,d.join)(r,"bin","bun.exe"):"",r?(0,d.join)(r,"bin","bun"):"",r?(0,d.join)(r,"bun.exe"):"",(0,d.join)(e,".bun","bin","bun.exe")]:[o,s,r?(0,d.join)(r,"bin","bun"):"",r?(0,d.join)(r,"bun"):"",(0,d.join)(e,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun"]}function z(n,t,e,r,o){return new Promise(s=>{let u;try{u=r(n,t,{stdio:["ignore","pipe","ignore"],...e==="win32"?{windowsHide:!0}:{}})}catch{s({status:null,stdout:""});return}let p="",c=!1,h=l=>{c||(c=!0,clearTimeout(m),s(l))},m=setTimeout(()=>{try{u.kill()}catch{}h({status:null,stdout:""})},o);u.stdout?.on("data",l=>{p+=l.toString()}),u.once("error",()=>h({status:null,stdout:""})),u.once("close",l=>h({status:l,stdout:p}))})}async function M(n={}){let t=n.platform??process.platform,e=n.env??process.env,r=n.homeDirectory??(0,R.homedir)(),o=n.exists??S.existsSync,s=X(t,e,r),u=n.cwd??process.cwd();if(t==="win32"){for(let l of s)if(l&&o(l))return l;let c=n.cacheFilePath===void 0?G(e,r):n.cacheFilePath,h=Y(c,o,u);if(h)return h;let m=await z(j("where.exe",e),["bun"],t,n.spawnProcess??O.spawn,n.timeoutMs??J);if(m.status===0&&m.stdout.trim()){let l=m.stdout.split(/\r?\n/).map(g=>g.trim()).filter(Boolean).filter(g=>!N(g,u)).filter(g=>o(g)),C=l.find(g=>{let v=g.toLowerCase();return v.endsWith("bun.exe")||v.endsWith("bun.cmd")}),w=C?(0,d.dirname)(C).toLowerCase():null,f=w?l.filter(g=>(0,d.dirname)(g).toLowerCase()===w):[],y=f.find(g=>g.toLowerCase().endsWith("bun.exe"));if(y)return I(c,y),y;let P=f.find(g=>g.toLowerCase().endsWith("bun.cmd"));if(P)return I(c,P),P;let B=l.find(Boolean);if(B)return I(c,B),B}return null}let p=(0,O.spawnSync)("which",["bun"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});if(p.status===0&&p.stdout?.trim())return"bun";for(let c of s)if(c&&o(c))return c;return null}var q=process.platform==="win32",Z=5e3,Q="usage: claude-mem hook <platform> <event> | claude-mem <worker-service subcommand> | claude-mem --version",k=process.argv[2]==="messages",nn=["SIGTERM","SIGINT","SIGHUP"];function E(n,t=1){k&&(process.stderr.write(`claude-mem: ${n}
`),process.exit(t)),process.stderr.write(`claude-mem: ${n}, continuing without memory
`),process.exit(0)}function V(){return process.env.CLAUDE_CONFIG_DIR||(0,i.join)((0,x.homedir)(),".claude")}function U(n){let t=n.split("-")[0].split(".");return[parseInt(t[0],10)||0,parseInt(t[1],10)||0,parseInt(t[2],10)||0]}function tn(n,t){let e=U(n),r=U(t);return r[0]-e[0]||r[1]-e[1]||r[2]-e[2]||(n.indexOf("-")<0?0:1)-(t.indexOf("-")<0?0:1)||(n<t?1:n>t?-1:0)}function en(n){try{return(0,a.readdirSync)(n).filter(t=>{let e=t.charAt(0);return e>="0"&&e<="9"}).map(t=>(0,i.join)(n,t)).filter(t=>{try{return(0,a.statSync)(t).isDirectory()&&!(0,a.existsSync)((0,i.join)(t,".orphaned_at"))}catch{return!1}}).sort((t,e)=>tn((0,i.basename)(t),(0,i.basename)(e)))}catch{return[]}}function rn(){let n=V(),t=[];for(let e of[process.env.CLAUDE_PLUGIN_ROOT,process.env.PLUGIN_ROOT])e&&t.push(e);t.push(...en((0,i.join)(n,"plugins","cache","thedotmack","claude-mem"))),t.push((0,i.join)(n,"plugins","marketplaces","thedotmack","plugin"));for(let e of t){let r=e.replace(/[\\/]+$/,"")||e,o=(0,a.existsSync)((0,i.join)(r,"plugin","scripts"))?(0,i.join)(r,"plugin"):r;if((0,a.existsSync)((0,i.join)(o,"scripts","worker-service.cjs")))return(0,i.resolve)(o)}return null}function on(){try{let n=(0,i.join)(V(),"settings.json");if(!(0,a.existsSync)(n))return!1;let t=JSON.parse((0,a.readFileSync)(n,"utf-8").replace(/^\uFEFF/,""));return!!(t&&t.enabledPlugins&&t.enabledPlugins["claude-mem@thedotmack"]===!1)}catch{return!1}}function sn(n){if(n[0]!=="hook")return!1;let t=n[2],e=t==="observation"?"CLAUDE_MEM_DISABLE_OBSERVATION":t==="file-context"?"CLAUDE_MEM_DISABLE_FILE_CONTEXT":void 0;return e?process.env.CLAUDE_MEM_DISABLE_TOOL_HOOKS==="1"||process.env[e]==="1":!1}function un(){if(!process.versions.bun)return!1;let n=(0,i.basename)(process.execPath).toLowerCase().replace(/\.exe$/,"");return n!=="bun"&&n!=="node"}async function cn(){let n=await M();return n?{bunExecutablePath:n,extraEnvironment:{}}:un()&&D(process.versions.bun)?{bunExecutablePath:process.execPath,extraEnvironment:{BUN_BE_BUN:"1"}}:null}function an(){let n=process.stdin;return n.isTTY?Promise.resolve(null):new Promise(t=>{let e=[],r=c=>{clearTimeout(p),n.removeListener("data",o),n.removeListener("end",s),n.removeListener("error",u),n.pause(),t(c)},o=c=>{if(e.push(c),!c.toString("utf8").trimEnd().endsWith("}"))return;let h=Buffer.concat(e),m;try{m=JSON.parse(h.toString("utf8").trim())}catch{return}m&&typeof m=="object"&&!Array.isArray(m)&&r(h)},s=()=>r(e.length>0?Buffer.concat(e):null),u=()=>r(null),p=setTimeout(s,Z);n.on("data",o),n.on("end",s),n.on("error",u)})}function ln(n,t,e){let r=process.env.CLAUDE_MEM_DATA_DIR?_(process.env.CLAUDE_MEM_DATA_DIR):(0,i.join)((0,x.homedir)(),".claude-mem"),o=n===null?"null (no data event or stream error)":"empty Buffer (zero bytes received)",s=["[claude-mem-launcher] empty stdin payload received \u2014 issue #2188",` script: ${t}`,` payload byte length: ${n?n.length:0}`,` payload type: ${o}`,` platform: ${process.platform}`,` shell: ${process.env.SHELL||"n/a"}`,` stdin TTY: ${process.stdin.isTTY===!0?"true":process.stdin.isTTY===!1?"false":"undefined"}`,` timestamp: ${new Date().toISOString()}`,` CLAUDE_PLUGIN_ROOT: ${e}`].join(`
`);process.stderr.write(s+`
`);try{let u=(0,i.join)(r,"logs");(0,a.mkdirSync)(u,{recursive:!0}),(0,a.appendFileSync)((0,i.join)(u,"runner-errors.log"),s+`
`)}catch(u){process.stderr.write(`[claude-mem-launcher] failed to persist diagnostic: ${u instanceof Error?u.message:u}
`)}process.exit(0)}function dn(){let n=process.env.CLAUDE_MEM_DATA_DIR?_(process.env.CLAUDE_MEM_DATA_DIR):(0,i.join)((0,x.homedir)(),".claude-mem"),t=(0,i.join)(n,"run");try{return(0,a.mkdirSync)(t,{recursive:!0,mode:448}),process.platform!=="win32"&&(0,a.chmodSync)(t,448),t}catch(e){return process.stderr.write(`[claude-mem-launcher] could not prepare ${t} (${e instanceof Error?e.message:String(e)}); starting Bun from the home directory
`),(0,x.homedir)()}}async function pn(n){(sn(n)||on())&&(k&&E("plugin is disabled"),process.exit(0));let t=rn();t||E("plugin scripts not found");let e=(0,i.join)(t,"scripts","worker-service.cjs"),r=(0,i.join)(t,"scripts","hook-service.cjs"),o=n[0]==="hook"&&(0,a.existsSync)(r)?r:e,s=await cn();s||E("Bun not found (install Bun, then restart your terminal)");let u=n[0]==="hook",p=null;u&&(p=await an(),(!p||p.length===0)&&ln(p,o,t));let c=[o,...n],h={stdio:["pipe","inherit","inherit"],windowsHide:!0,env:{...process.env,...s.extraEnvironment,CLAUDE_MEM_HOOK_ORIGINAL_CWD:process.cwd()},cwd:dn()},m=s.bunExecutablePath,l=c;if(q&&/\.(cmd|bat)$/i.test(s.bunExecutablePath)){let w=f=>`"${String(f).replace(/"/g,'\\"')}"`;h.shell=!0,m=[s.bunExecutablePath,...c].map(w).join(" "),l=[]}return new Promise(()=>{let w=(0,W.spawn)(m,l,h);for(let f of nn)process.on(f,()=>{try{w.kill(f)}catch{}});w.on("error",f=>{E(`failed to start Bun (${f.message})`)}),w.on("close",(f,y)=>{f===0&&process.exit(0),E(`worker exited ${y??f}`,f??1)}),w.stdin&&(w.stdin.on("error",()=>{}),p&&w.stdin.write(p),w.stdin.end())})}async function mn(){let n=process.argv.slice(2);n.length===0&&(process.stderr.write(`${Q}
`),process.exit(0)),n[0]==="--version"&&(process.stdout.write(`${6}
`),process.exit(0)),process.env.BUN_BE_BUN==="1"&&(process.stderr.write(`claude-mem: started with BUN_BE_BUN=1 but Bun ${process.versions.bun??"unknown"} ignored it; not starting the worker again (upgrade Bun to 1.2.16+ and run \`npx claude-mem install\`)
`),process.exit(1)),await pn(n)}mn().catch(n=>{E(`launcher error (${n instanceof Error?n.message:String(n)})`)});
//# sourceMappingURL=claude-mem-launcher.cjs.map