Files
claude-mem/plugin/scripts/worker-cli.js
Alex Newman 1491123706 feat(ProcessManager): add Bun availability check and improve PID file validation
- Implemented a method to check if Bun is available in the system PATH.
- Updated the startWithBun method to return an error if Bun is not found.
- Enhanced PID file parsing to validate required fields and their types.
- Cleaned up stale PID files if the process is no longer alive.

fix(SettingsRoutes): clear port cache after updating settings

- Added a call to clearPortCache after writing updated settings to ensure the application uses the latest configuration.
2025-12-12 17:48:41 -05:00

5 lines
9.4 KiB
JavaScript
Executable File

#!/usr/bin/env bun
import{existsSync as C,readFileSync as J,writeFileSync as q,unlinkSync as Q,mkdirSync as y}from"fs";import{createWriteStream as z}from"fs";import{join as g}from"path";import{spawn as Z,spawnSync as tt}from"child_process";import{homedir as et}from"os";import{join as c,dirname as V,basename as ht}from"path";import{homedir as X}from"os";import{fileURLToPath as j}from"url";import{readFileSync as F,writeFileSync as W,existsSync as K}from"fs";import{join as B}from"path";import{homedir as G}from"os";var $=["bugfix","feature","refactor","discovery","decision","change"],H=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"];var I=$.join(","),R=H.join(",");var d=(o=>(o[o.DEBUG=0]="DEBUG",o[o.INFO=1]="INFO",o[o.WARN=2]="WARN",o[o.ERROR=3]="ERROR",o[o.SILENT=4]="SILENT",o))(d||{}),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=d[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 s=typeof e=="string"?JSON.parse(e):e;if(t==="Bash"&&s.command){let r=s.command.length>50?s.command.substring(0,50)+"...":s.command;return`${t}(${r})`}if(t==="Read"&&s.file_path){let r=s.file_path.split("/").pop()||s.file_path;return`${t}(${r})`}if(t==="Edit"&&s.file_path){let r=s.file_path.split("/").pop()||s.file_path;return`${t}(${r})`}if(t==="Write"&&s.file_path){let r=s.file_path.split("/").pop()||s.file_path;return`${t}(${r})`}return t}catch{return t}}log(t,e,s,r,o){if(t<this.getLevel())return;let i=new Date().toISOString().replace("T"," ").substring(0,23),p=d[t].padEnd(5),m=e.padEnd(6),T="";r?.correlationId?T=`[${r.correlationId}] `:r?.sessionId&&(T=`[session-${r.sessionId}] `);let S="";o!=null&&(this.getLevel()===0&&typeof o=="object"?S=`
`+JSON.stringify(o,null,2):S=" "+this.formatData(o));let h="";if(r){let{sessionId:lt,sdkSessionId:pt,correlationId:Et,...M}=r;Object.keys(M).length>0&&(h=` {${Object.entries(M).map(([k,x])=>`${k}=${x}`).join(", ")}}`)}let L=`[${i}] [${p}] [${m}] ${T}${s}${h}${S}`;t===3?console.error(L):console.log(L)}debug(t,e,s,r){this.log(0,t,e,s,r)}info(t,e,s,r){this.log(1,t,e,s,r)}warn(t,e,s,r){this.log(2,t,e,s,r)}error(t,e,s,r){this.log(3,t,e,s,r)}dataIn(t,e,s,r){this.info(t,`\u2192 ${e}`,s,r)}dataOut(t,e,s,r){this.info(t,`\u2190 ${e}`,s,r)}success(t,e,s,r){this.info(t,`\u2713 ${e}`,s,r)}failure(t,e,s,r){this.error(t,`\u2717 ${e}`,s,r)}timing(t,e,s,r){this.info(t,`\u23F1 ${e}`,r,{duration:`${s}ms`})}},_=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_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_DATA_DIR:B(G(),".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"),s=JSON.parse(e),r=s;if(s.env&&typeof s.env=="object"){r=s.env;try{W(t,JSON.stringify(r,null,2),"utf-8"),_.info("SETTINGS","Migrated settings file from nested to flat schema",{settingsPath:t})}catch(i){_.warn("SETTINGS","Failed to auto-migrate settings file",{settingsPath:t},i)}}let o={...this.DEFAULTS};for(let i of Object.keys(this.DEFAULTS))r[i]!==void 0&&(o[i]=r[i]);return o}};function Y(){return typeof __dirname<"u"?__dirname:V(j(import.meta.url))}var yt=Y(),a=u.get("CLAUDE_MEM_DATA_DIR"),A=process.env.CLAUDE_CONFIG_DIR||c(X(),".claude"),Ut=c(a,"archives"),Pt=c(a,"logs"),vt=c(a,"trash"),Nt=c(a,"backups"),bt=c(a,"settings.json"),wt=c(a,"claude-mem.db"),kt=c(a,"vector-db"),xt=c(A,"settings.json"),$t=c(A,"commands"),Ht=c(A,"CLAUDE.md");var f=g(a,"worker.pid"),U=g(a,"logs"),P=g(et(),".claude","plugins","marketplaces","thedotmack"),rt=5e3,st=1e4,ot=200,nt=1e3,it=100,l=class{static async start(t){if(await this.isRunning())return{success:!0,pid:this.getPidInfo()?.pid};y(U,{recursive:!0});let e=g(P,"plugin","scripts","worker-service.cjs");if(!C(e))return{success:!1,error:`Worker script not found at ${e}`};let s=this.getLogFilePath();return this.startWithBun(e,s,t)}static isBunAvailable(){try{return tt("bun",["--version"],{stdio:"pipe",timeout:5e3}).status===0}catch{return!1}}static async startWithBun(t,e,s){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",o=Z("bun",[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(s)},cwd:P,...r&&{windowsHide:!0}}),i=z(e,{flags:"a"});return o.stdout?.pipe(i),o.stderr?.pipe(i),o.unref(),o.pid?(this.writePidFile({pid:o.pid,port:s,startedAt:new Date().toISOString(),version:process.env.npm_package_version||"unknown"}),this.waitForHealth(o.pid,s)):{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){y(a,{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,s=st){let r=Date.now();for(;Date.now()-r<s;){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(nt)})).ok)return{success:!0,pid:t}}catch{}await new Promise(o=>setTimeout(o,ot))}return{success:!1,error:"Health check timed out"}}static async waitForExit(t,e){let s=Date.now();for(;Date.now()-s<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 g(U,`worker-${t}.log`)}static formatUptime(t){let e=new Date(t).getTime(),r=Date.now()-e,o=Math.floor(r/1e3),i=Math.floor(o/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 ${o%60}s`:`${o}s`}};import N from"path";import{homedir as ct}from"os";var D={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,WINDOWS_MULTIPLIER:1.5};function v(n){return process.platform==="win32"?Math.round(n*D.WINDOWS_MULTIPLIER):n}var ee=N.join(ct(),".claude","plugins","marketplaces","thedotmack"),re=v(D.HEALTH_CHECK),E=null;function b(){if(E!==null)return E;try{let n=N.join(u.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),t=u.loadFromFile(n);return E=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),E}catch(n){return _.debug("SYSTEM","Failed to load port from settings, using default",{error:n}),E=parseInt(u.get("CLAUDE_MEM_WORKER_PORT"),10),E}}var at=process.argv[2],w=b();async function ut(){switch(at){case"start":{let n=await l.start(w);if(n.success){console.log(`Worker started (PID: ${n.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: ${n.error}`),process.exit(1);break}case"stop":await l.stop(),console.log("Worker stopped"),process.exit(0);case"restart":{let n=await l.restart(w);n.success?(console.log(`Worker restarted (PID: ${n.pid})`),process.exit(0)):(console.error(`Failed to restart: ${n.error}`),process.exit(1))}case"status":{let n=await l.status();n.running?(console.log("Worker is running"),console.log(` PID: ${n.pid}`),console.log(` Port: ${n.port}`),console.log(` Uptime: ${n.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(n=>{console.error(n),process.exit(1)});