83b0f9551b
- Introduced `/api/admin/restart` and `/api/admin/shutdown` endpoints in WorkerService for restarting and shutting down the service. - Updated error message in hook-error-handler to provide clearer instructions for restarting the worker. - Refactored worker-utils to remove PM2 dependency and implement ProcessManager for starting the worker service. - Cleaned up legacy PM2 references and provided new manual start instructions.
12 lines
12 KiB
JavaScript
Executable File
12 lines
12 KiB
JavaScript
Executable File
#!/usr/bin/env node
|
|
var rt=Object.defineProperty;var E=(s,t)=>()=>(s&&(t=s(s=0)),t);var nt=(s,t)=>{for(var e in t)rt(s,e,{get:t[e],enumerable:!0})};var ot,st,x,$,F=E(()=>{"use strict";ot=["bugfix","feature","refactor","discovery","decision","change"],st=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"],x=ot.join(","),$=st.join(",")});import{readFileSync as it,writeFileSync as at,existsSync as ct}from"fs";import{join as ut}from"path";import{homedir as pt}from"os";var g,D=E(()=>{"use strict";F();L();g=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:ut(pt(),".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:x,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:$,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(!ct(t))return this.getAllDefaults();let e=it(t,"utf-8"),n=JSON.parse(e),r=n;if(n.env&&typeof n.env=="object"){r=n.env;try{at(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}}});var y,I,_,L=E(()=>{"use strict";D();y=(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))(y||{}),I=class{level=null;useColor;constructor(){this.useColor=process.stdout.isTTY??!1}getLevel(){if(this.level===null){let t=g.get("CLAUDE_MEM_LOG_LEVEL").toUpperCase();this.level=y[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),u=y[t].padEnd(5),f=e.padEnd(6),p="";r?.correlationId?p=`[${r.correlationId}] `:r?.sessionId&&(p=`[session-${r.sessionId}] `);let l="";o!=null&&(this.getLevel()===0&&typeof o=="object"?l=`
|
|
`+JSON.stringify(o,null,2):l=" "+this.formatData(o));let U="";if(r){let{sessionId:kt,sdkSessionId:Pt,correlationId:Ut,...b}=r;Object.keys(b).length>0&&(U=` {${Object.entries(b).map(([tt,et])=>`${tt}=${et}`).join(", ")}}`)}let N=`[${i}] [${u}] [${f}] ${p}${n}${U}${l}`;t===3?console.error(N):console.log(N)}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`})}},_=new I});import{join as c,dirname as lt,basename as Yt}from"path";import{homedir as ft}from"os";import{fileURLToPath as gt}from"url";function _t(){return typeof __dirname<"u"?__dirname:lt(gt(import.meta.url))}var Zt,a,M,te,ee,re,ne,oe,se,ie,ae,ce,ue,w=E(()=>{"use strict";D();Zt=_t(),a=g.get("CLAUDE_MEM_DATA_DIR"),M=process.env.CLAUDE_CONFIG_DIR||c(ft(),".claude"),te=c(a,"archives"),ee=c(a,"logs"),re=c(a,"trash"),ne=c(a,"backups"),oe=c(a,"settings.json"),se=c(a,"claude-mem.db"),ie=c(a,"vector-db"),ae=c(M,"settings.json"),ce=c(M,"commands"),ue=c(M,"CLAUDE.md")});var V={};nt(V,{BinaryManager:()=>v});import{existsSync as W,mkdirSync as Et,writeFileSync as B,readFileSync as G}from"fs";import{join as d}from"path";var A,R,mt,v,K=E(()=>{"use strict";w();A=d(a,"bin"),R=d(A,"version.txt"),mt="https://github.com/thedotmack/claude-mem/releases/download",v=class{static async getExecutablePath(){if(process.platform!=="win32")throw new Error("BinaryManager only used on Windows");let t=this.getCurrentVersion(),e=d(A,"worker-service.exe");return W(e)&&this.getInstalledVersion()===t||await this.downloadBinary(t),e}static async downloadBinary(t){let e=`${mt}/v${t}/worker-service-v${t}-win-x64.exe`;console.log(`Downloading worker binary v${t}...`);let n=await fetch(e);if(!n.ok)throw new Error(`Download failed: ${n.status}
|
|
URL: ${e}
|
|
Make sure the release exists with a Windows binary attached.`);let r=await n.arrayBuffer();Et(A,{recursive:!0});let o=d(A,"worker-service.exe");B(o,Buffer.from(r)),B(R,t),console.log("Download complete")}static getCurrentVersion(){try{return JSON.parse(G(d(a,"..",".claude","plugins","marketplaces","thedotmack","package.json"),"utf-8")).version}catch{return process.env.npm_package_version||"unknown"}}static getInstalledVersion(){try{return W(R)?G(R,"utf-8").trim():null}catch{return null}}}});import{stdin as P}from"process";L();import ht from"path";import{homedir as At}from"os";import{spawnSync as Ct}from"child_process";var m={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,WINDOWS_MULTIPLIER:1.5};function H(s){return process.platform==="win32"?Math.round(s*m.WINDOWS_MULTIPLIER):s}w();import{existsSync as k,readFileSync as dt,writeFileSync as St,unlinkSync as Tt,mkdirSync as j}from"fs";import{createWriteStream as X}from"fs";import{join as T}from"path";import{spawn as Y}from"child_process";import{homedir as Ot}from"os";var S=T(a,"worker.pid"),J=T(a,"logs"),q=T(Ot(),".claude","plugins","marketplaces","thedotmack"),C=class{static async start(t){if(await this.isRunning())return{success:!0,pid:this.getPidInfo()?.pid};j(J,{recursive:!0});let e=T(q,"plugin","scripts","worker-service.cjs");if(!k(e))return{success:!1,error:`Worker script not found at ${e}`};let n=this.getLogFilePath();return process.platform==="win32"?this.startWindows(t):this.startUnix(e,n,t)}static async startUnix(t,e,n){try{let r=Y("bun",[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(n)},cwd:q}),o=X(e,{flags:"a"});return r.stdout?.pipe(o),r.stderr?.pipe(o),r.unref(),r.pid?(this.writePidFile({pid:r.pid,port:n,startedAt:new Date().toISOString(),version:process.env.npm_package_version||"unknown"}),this.waitForHealth(r.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 startWindows(t){let{BinaryManager:e}=await Promise.resolve().then(()=>(K(),V));try{let n=await e.getExecutablePath(),r=Y(n,[],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(t)},windowsHide:!0}),o=this.getLogFilePath(),i=X(o,{flags:"a"});return r.stdout?.pipe(i),r.stderr?.pipe(i),r.unref(),r.pid?(this.writePidFile({pid:r.pid,port:t,startedAt:new Date().toISOString(),version:process.env.npm_package_version||"unknown"}),this.waitForHealth(r.pid,t)):{success:!1,error:"Failed to get PID from spawned process"}}catch(n){return{success:!1,error:n instanceof Error?n.message:String(n)}}}static async stop(t=5e3){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();return t?this.isProcessAlive(t.pid):!1}static getPidInfo(){try{if(!k(S))return null;let t=dt(S,"utf-8");return JSON.parse(t)}catch{return null}}static writePidFile(t){j(a,{recursive:!0}),St(S,JSON.stringify(t,null,2))}static removePidFile(){try{k(S)&&Tt(S)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,n=1e4){let r=Date.now(),o=200;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(1e3)})).ok)return{success:!0,pid:t}}catch{}await new Promise(i=>setTimeout(i,o))}return{success:!1,error:"Health check timed out"}}static async waitForExit(t,e){let n=Date.now(),r=100;for(;Date.now()-n<e;){if(!this.isProcessAlive(t))return;await new Promise(o=>setTimeout(o,r))}throw new Error("Process did not exit within timeout")}static getLogFilePath(){let t=new Date().toISOString().slice(0,10);return T(J,`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),u=Math.floor(i/60),f=Math.floor(u/24);return f>0?`${f}d ${u%24}h`:u>0?`${u}h ${i%60}m`:i>0?`${i}m ${o%60}s`:`${o}s`}};var Dt=ht.join(At(),".claude","plugins","marketplaces","thedotmack"),Lt=H(m.HEALTH_CHECK),yt=38888;function O(){return yt}async function Q(){try{let s=O();return(await fetch(`http://127.0.0.1:${s}/health`,{signal:AbortSignal.timeout(Lt)})).ok}catch(s){return _.debug("SYSTEM","Worker health check failed",{error:s instanceof Error?s.message:String(s),errorType:s?.constructor?.name}),!1}}async function It(){if(process.platform!=="win32")try{Ct("pm2",["delete","claude-mem-worker"],{stdio:"ignore"})}catch{}let s=O(),t=await C.start(s);return t.success||_.error("SYSTEM","Failed to start worker",{platform:process.platform,port:s,error:t.error,marketplaceRoot:Dt}),t.success}async function z(){if(await Q())return;let s=await It();if(!(!s&&await Q())&&!s){let t=O();throw new Error(`Worker service failed to start on port ${t}.
|
|
|
|
To start manually, run: npm run worker:start
|
|
If already running, try: npm run worker:restart`)}}import{appendFileSync as Mt}from"fs";import{homedir as wt}from"os";import{join as Rt}from"path";var vt=Rt(wt(),".claude-mem","silent.log");function h(s,t,e=""){let n=new Date().toISOString(),u=((new Error().stack||"").split(`
|
|
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),f=u?`${u[1].split("/").pop()}:${u[2]}`:"unknown",p=`[${n}] [HAPPY-PATH-ERROR] [${f}] ${s}`;if(t!==void 0)try{p+=` ${JSON.stringify(t)}`}catch(l){p+=` [stringify error: ${l}]`}p+=`
|
|
`;try{Mt(vt,p)}catch(l){console.error("[silent-debug] Failed to write to log:",l)}return e}async function Z(s){if(await z(),h("[cleanup-hook] Hook fired",{session_id:s?.session_id,reason:s?.reason}),!s)throw new Error("cleanup-hook requires input from Claude Code");let{session_id:t,reason:e}=s,n=O();try{let r=await fetch(`http://127.0.0.1:${n}/api/sessions/complete`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({claudeSessionId:t,reason:e}),signal:AbortSignal.timeout(m.DEFAULT)});if(r.ok){let o=await r.json();h("[cleanup-hook] Session cleanup completed",o)}else h("[cleanup-hook] Session not found or already cleaned up")}catch(r){h("[cleanup-hook] Worker not reachable (non-critical)",{error:r.message})}console.log('{"continue": true, "suppressOutput": true}'),process.exit(0)}if(P.isTTY)Z(void 0);else{let s="";P.on("data",t=>s+=t),P.on("end",async()=>{let t=s?JSON.parse(s):void 0;await Z(t)})}
|