Files
claude-mem/plugin/scripts/worker-cli.js
Alex Newman 5cd68f4a96 build: sync plugin build artifacts for v7.1.2
Updated built plugin files with latest changes including localhost
binding security improvements and enhanced runtime detection.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-12 23:03:27 -05:00

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 y}from"fs";import{createWriteStream as z}from"fs";import{join as f}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 ht}from"path";import{homedir as G}from"os";import{fileURLToPath as X}from"url";import{readFileSync as H,writeFileSync as F,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 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 n=typeof e=="string"?JSON.parse(e):e;if(t==="Bash"&&n.command){let r=n.command.length>50?n.command.substring(0,50)+"...":n.command;return`${t}(${r})`}if(t==="Read"&&n.file_path){let r=n.file_path.split("/").pop()||n.file_path;return`${t}(${r})`}if(t==="Edit"&&n.file_path){let r=n.file_path.split("/").pop()||n.file_path;return`${t}(${r})`}if(t==="Write"&&n.file_path){let r=n.file_path.split("/").pop()||n.file_path;return`${t}(${r})`}return t}catch{return t}}log(t,e,n,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),S="";r?.correlationId?S=`[${r.correlationId}] `:r?.sessionId&&(S=`[session-${r.sessionId}] `);let T="";o!=null&&(this.getLevel()===0&&typeof o=="object"?T=`
`+JSON.stringify(o,null,2):T=" "+this.formatData(o));let h="";if(r){let{sessionId:lt,sdkSessionId:pt,correlationId:Et,...L}=r;Object.keys(L).length>0&&(h=` {${Object.entries(L).map(([k,x])=>`${k}=${x}`).join(", ")}}`)}let D=`[${i}] [${p}] [${m}] ${S}${n}${h}${T}`;t===3?console.error(D):console.log(D)}debug(t,e,n,r){this.log(0,t,e,n,r)}info(t,e,n,r){this.log(1,t,e,n,r)}warn(t,e,n,r){this.log(2,t,e,n,r)}error(t,e,n,r){this.log(3,t,e,n,r)}dataIn(t,e,n,r){this.info(t,`\u2192 ${e}`,n,r)}dataOut(t,e,n,r){this.info(t,`\u2190 ${e}`,n,r)}success(t,e,n,r){this.info(t,`\u2713 ${e}`,n,r)}failure(t,e,n,r){this.error(t,`\u2717 ${e}`,n,r)}timing(t,e,n,r){this.info(t,`\u23F1 ${e}`,r,{duration:`${n}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=H(t,"utf-8"),n=JSON.parse(e),r=n;if(n.env&&typeof n.env=="object"){r=n.env;try{F(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 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:j(X(import.meta.url))}var yt=Y(),c=u.get("CLAUDE_MEM_DATA_DIR"),A=process.env.CLAUDE_CONFIG_DIR||a(G(),".claude"),Pt=a(c,"archives"),wt=a(c,"logs"),Ut=a(c,"trash"),vt=a(c,"backups"),Nt=a(c,"settings.json"),bt=a(c,"claude-mem.db"),kt=a(c,"vector-db"),xt=a(A,"settings.json"),Wt=a(A,"commands"),$t=a(A,"CLAUDE.md");var _=f(c,"worker.pid"),P=f(c,"logs"),w=f(et(),".claude","plugins","marketplaces","thedotmack"),rt=5e3,nt=1e4,ot=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};y(P,{recursive:!0});let e=f(w,"plugin","scripts","worker-service.cjs");if(!C(e))return{success:!1,error:`Worker script not found at ${e}`};let n=this.getLogFilePath();return this.startWithBun(e,n,t)}static isBunAvailable(){try{return tt("bun",["--version"],{stdio:"pipe",timeout:5e3}).status===0}catch{return!1}}static async startWithBun(t,e,n){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(n)},cwd:w,...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:n,startedAt:new Date().toISOString(),version:process.env.npm_package_version||"unknown"}),this.waitForHealth(o.pid,n)):{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(_))return null;let t=J(_,"utf-8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.port!="number"?null:e}catch{return null}}static writePidFile(t){y(c,{recursive:!0}),q(_,JSON.stringify(t,null,2))}static removePidFile(){try{C(_)&&Q(_)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,n=nt){let r=Date.now();for(;Date.now()-r<n;){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(o=>setTimeout(o,ot))}return{success:!1,error:"Health check timed out"}}static async waitForExit(t,e){let n=Date.now();for(;Date.now()-n<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 f(P,`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 v from"path";import{homedir as at}from"os";var M={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,WINDOWS_MULTIPLIER:1.5};function U(s){return process.platform==="win32"?Math.round(s*M.WINDOWS_MULTIPLIER):s}var ee=v.join(at(),".claude","plugins","marketplaces","thedotmack"),re=U(M.HEALTH_CHECK),E=null;function N(){if(E!==null)return E;try{let s=v.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=N();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)});