mirror of
https://github.com/thedotmack/claude-mem
synced 2026-04-25 17:15:04 +02:00
- Updated multiple hooks (context-hook, new-hook, save-hook, summary-hook, user-message-hook) to throw errors using `getWorkerRestartInstructions` for improved user guidance on worker connection issues. - Enhanced `handleWorkerError` function to utilize the new error message generator for consistent error reporting. - Modified `ensureWorkerRunning` function to provide detailed instructions based on the worker's state, including port information. - Introduced `getWorkerRestartInstructions` utility in `error-messages.ts` to generate platform-aware error messages for worker failures.
5 lines
9.5 KiB
JavaScript
Executable File
5 lines
9.5 KiB
JavaScript
Executable File
#!/usr/bin/env bun
|
|
import{existsSync as C,readFileSync as J,writeFileSync as q,unlinkSync as Q,mkdirSync as P}from"fs";import{createWriteStream as z}from"fs";import{join as _}from"path";import{spawn as Z,spawnSync as tt}from"child_process";import{homedir as et}from"os";import{join as a,dirname as j,basename as Mt}from"path";import{homedir as G}from"os";import{fileURLToPath as X}from"url";import{readFileSync as F,writeFileSync as H,existsSync as K}from"fs";import{join as V}from"path";import{homedir as B}from"os";var W=["bugfix","feature","refactor","discovery","decision","change"],$=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"];var I=W.join(","),R=$.join(",");var T=(n=>(n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR",n[n.SILENT=4]="SILENT",n))(T||{}),O=class{level=null;useColor;constructor(){this.useColor=process.stdout.isTTY??!1}getLevel(){if(this.level===null){let t=u.get("CLAUDE_MEM_LOG_LEVEL").toUpperCase();this.level=T[t]??1}return this.level}correlationId(t,e){return`obs-${t}-${e}`}sessionId(t){return`session-${t}`}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}
|
|
${t.stack}`:t.message;if(Array.isArray(t))return`[${t.length} items]`;let e=Object.keys(t);return e.length===0?"{}":e.length<=3?JSON.stringify(t):`{${e.length} keys: ${e.slice(0,3).join(", ")}...}`}return String(t)}formatTool(t,e){if(!e)return t;try{let o=typeof e=="string"?JSON.parse(e):e;if(t==="Bash"&&o.command){let r=o.command.length>50?o.command.substring(0,50)+"...":o.command;return`${t}(${r})`}if(t==="Read"&&o.file_path){let r=o.file_path.split("/").pop()||o.file_path;return`${t}(${r})`}if(t==="Edit"&&o.file_path){let r=o.file_path.split("/").pop()||o.file_path;return`${t}(${r})`}if(t==="Write"&&o.file_path){let r=o.file_path.split("/").pop()||o.file_path;return`${t}(${r})`}return t}catch{return t}}log(t,e,o,r,n){if(t<this.getLevel())return;let i=new Date().toISOString().replace("T"," ").substring(0,23),p=T[t].padEnd(5),m=e.padEnd(6),S="";r?.correlationId?S=`[${r.correlationId}] `:r?.sessionId&&(S=`[session-${r.sessionId}] `);let d="";n!=null&&(this.getLevel()===0&&typeof n=="object"?d=`
|
|
`+JSON.stringify(n,null,2):d=" "+this.formatData(n));let M="";if(r){let{sessionId:lt,sdkSessionId:pt,correlationId:Et,...L}=r;Object.keys(L).length>0&&(M=` {${Object.entries(L).map(([N,x])=>`${N}=${x}`).join(", ")}}`)}let D=`[${i}] [${p}] [${m}] ${S}${o}${M}${d}`;t===3?console.error(D):console.log(D)}debug(t,e,o,r){this.log(0,t,e,o,r)}info(t,e,o,r){this.log(1,t,e,o,r)}warn(t,e,o,r){this.log(2,t,e,o,r)}error(t,e,o,r){this.log(3,t,e,o,r)}dataIn(t,e,o,r){this.info(t,`\u2192 ${e}`,o,r)}dataOut(t,e,o,r){this.info(t,`\u2190 ${e}`,o,r)}success(t,e,o,r){this.info(t,`\u2713 ${e}`,o,r)}failure(t,e,o,r){this.error(t,`\u2717 ${e}`,o,r)}timing(t,e,o,r){this.info(t,`\u23F1 ${e}`,r,{duration:`${o}ms`})}},g=new O;var u=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:"37777",CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_DATA_DIR:V(B(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"true",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"true",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"true",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES:I,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:R,CLAUDE_MEM_CONTEXT_FULL_COUNT:"5",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false"};static getAllDefaults(){return{...this.DEFAULTS}}static get(t){return this.DEFAULTS[t]}static getInt(t){let e=this.get(t);return parseInt(e,10)}static getBool(t){return this.get(t)==="true"}static loadFromFile(t){if(!K(t))return this.getAllDefaults();let e=F(t,"utf-8"),o=JSON.parse(e),r=o;if(o.env&&typeof o.env=="object"){r=o.env;try{H(t,JSON.stringify(r,null,2),"utf-8"),g.info("SETTINGS","Migrated settings file from nested to flat schema",{settingsPath:t})}catch(i){g.warn("SETTINGS","Failed to auto-migrate settings file",{settingsPath:t},i)}}let n={...this.DEFAULTS};for(let i of Object.keys(this.DEFAULTS))r[i]!==void 0&&(n[i]=r[i]);return n}};function Y(){return typeof __dirname<"u"?__dirname:j(X(import.meta.url))}var Pt=Y(),c=u.get("CLAUDE_MEM_DATA_DIR"),A=process.env.CLAUDE_CONFIG_DIR||a(G(),".claude"),yt=a(c,"archives"),wt=a(c,"logs"),kt=a(c,"trash"),Ut=a(c,"backups"),vt=a(c,"settings.json"),bt=a(c,"claude-mem.db"),Nt=a(c,"vector-db"),xt=a(A,"settings.json"),Wt=a(A,"commands"),$t=a(A,"CLAUDE.md");var f=_(c,"worker.pid"),y=_(c,"logs"),w=_(et(),".claude","plugins","marketplaces","thedotmack"),rt=5e3,ot=1e4,nt=200,st=1e3,it=100,l=class{static async start(t){if(isNaN(t)||t<1024||t>65535)return{success:!1,error:`Invalid port ${t}. Must be between 1024 and 65535`};if(await this.isRunning())return{success:!0,pid:this.getPidInfo()?.pid};P(y,{recursive:!0});let e=_(w,"plugin","scripts","worker-service.cjs");if(!C(e))return{success:!1,error:`Worker script not found at ${e}`};let o=this.getLogFilePath();return this.startWithBun(e,o,t)}static isBunAvailable(){try{return tt("bun",["--version"],{stdio:"pipe",timeout:5e3}).status===0}catch{return!1}}static async startWithBun(t,e,o){if(!this.isBunAvailable())return{success:!1,error:"Bun is required but not found in PATH. Install from https://bun.sh"};try{let r=process.platform==="win32",n=Z("bun",[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(o)},cwd:w,...r&&{windowsHide:!0}}),i=z(e,{flags:"a"});return n.stdout?.pipe(i),n.stderr?.pipe(i),n.unref(),n.pid?(this.writePidFile({pid:n.pid,port:o,startedAt:new Date().toISOString(),version:process.env.npm_package_version||"unknown"}),this.waitForHealth(n.pid,o)):{success:!1,error:"Failed to get PID from spawned process"}}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r)}}}static async stop(t=rt){let e=this.getPidInfo();if(!e)return!0;try{process.kill(e.pid,"SIGTERM"),await this.waitForExit(e.pid,t)}catch{try{process.kill(e.pid,"SIGKILL")}catch{}}return this.removePidFile(),!0}static async restart(t){return await this.stop(),this.start(t)}static async status(){let t=this.getPidInfo();if(!t)return{running:!1};let e=this.isProcessAlive(t.pid);return{running:e,pid:e?t.pid:void 0,port:e?t.port:void 0,uptime:e?this.formatUptime(t.startedAt):void 0}}static async isRunning(){let t=this.getPidInfo();if(!t)return!1;let e=this.isProcessAlive(t.pid);return e||this.removePidFile(),e}static getPidInfo(){try{if(!C(f))return null;let t=J(f,"utf-8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.port!="number"?null:e}catch{return null}}static writePidFile(t){P(c,{recursive:!0}),q(f,JSON.stringify(t,null,2))}static removePidFile(){try{C(f)&&Q(f)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,o=ot){let r=Date.now();for(;Date.now()-r<o;){if(!this.isProcessAlive(t))return{success:!1,error:"Process died during startup"};try{if((await fetch(`http://127.0.0.1:${e}/health`,{signal:AbortSignal.timeout(st)})).ok)return{success:!0,pid:t}}catch{}await new Promise(n=>setTimeout(n,nt))}return{success:!1,error:"Health check timed out"}}static async waitForExit(t,e){let o=Date.now();for(;Date.now()-o<e;){if(!this.isProcessAlive(t))return;await new Promise(r=>setTimeout(r,it))}throw new Error("Process did not exit within timeout")}static getLogFilePath(){let t=new Date().toISOString().slice(0,10);return _(y,`worker-${t}.log`)}static formatUptime(t){let e=new Date(t).getTime(),r=Date.now()-e,n=Math.floor(r/1e3),i=Math.floor(n/60),p=Math.floor(i/60),m=Math.floor(p/24);return m>0?`${m}d ${p%24}h`:p>0?`${p}h ${i%60}m`:i>0?`${i}m ${n%60}s`:`${n}s`}};import U from"path";import{homedir as at}from"os";var h={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,WINDOWS_MULTIPLIER:1.5};function k(s){return process.platform==="win32"?Math.round(s*h.WINDOWS_MULTIPLIER):s}var ne=U.join(at(),".claude","plugins","marketplaces","thedotmack"),se=k(h.HEALTH_CHECK),E=null;function v(){if(E!==null)return E;try{let s=U.join(u.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),t=u.loadFromFile(s);return E=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),E}catch(s){return g.debug("SYSTEM","Failed to load port from settings, using default",{error:s}),E=parseInt(u.get("CLAUDE_MEM_WORKER_PORT"),10),E}}var ct=process.argv[2],b=v();async function ut(){switch(ct){case"start":{let s=await l.start(b);if(s.success){console.log(`Worker started (PID: ${s.pid})`);let t=new Date().toISOString().slice(0,10);console.log(`Logs: ~/.claude-mem/logs/worker-${t}.log`),process.exit(0)}else console.error(`Failed to start: ${s.error}`),process.exit(1);break}case"stop":await l.stop(),console.log("Worker stopped"),process.exit(0);case"restart":{let s=await l.restart(b);s.success?(console.log(`Worker restarted (PID: ${s.pid})`),process.exit(0)):(console.error(`Failed to restart: ${s.error}`),process.exit(1));break}case"status":{let s=await l.status();s.running?(console.log("Worker is running"),console.log(` PID: ${s.pid}`),console.log(` Port: ${s.port}`),console.log(` Uptime: ${s.uptime}`)):console.log("Worker is not running"),process.exit(0)}default:console.log("Usage: worker-cli.js <start|stop|restart|status>"),process.exit(1)}}ut().catch(s=>{console.error(s),process.exit(1)});
|