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
13 KiB
JavaScript
Executable File
12 lines
13 KiB
JavaScript
Executable File
#!/usr/bin/env node
|
|
var nt=Object.defineProperty;var m=(n,t)=>()=>(n&&(t=n(n=0)),t);var st=(n,t)=>{for(var e in t)nt(n,e,{get:t[e],enumerable:!0})};var at,ct,x,$,H=m(()=>{"use strict";at=["bugfix","feature","refactor","discovery","decision","change"],ct=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"],x=at.join(","),$=ct.join(",")});import{readFileSync as ut,writeFileSync as pt,existsSync as lt}from"fs";import{join as ft}from"path";import{homedir as gt}from"os";var E,D=m(()=>{"use strict";H();h();E=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:ft(gt(),".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(!lt(t))return this.getAllDefaults();let e=ut(t,"utf-8"),r=JSON.parse(e),o=r;if(r.env&&typeof r.env=="object"){o=r.env;try{pt(t,JSON.stringify(o,null,2),"utf-8"),l.info("SETTINGS","Migrated settings file from nested to flat schema",{settingsPath:t})}catch(i){l.warn("SETTINGS","Failed to auto-migrate settings file",{settingsPath:t},i)}}let s={...this.DEFAULTS};for(let i of Object.keys(this.DEFAULTS))o[i]!==void 0&&(s[i]=o[i]);return s}}});var L,y,l,h=m(()=>{"use strict";D();L=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.WARN=2]="WARN",s[s.ERROR=3]="ERROR",s[s.SILENT=4]="SILENT",s))(L||{}),y=class{level=null;useColor;constructor(){this.useColor=process.stdout.isTTY??!1}getLevel(){if(this.level===null){let t=E.get("CLAUDE_MEM_LOG_LEVEL").toUpperCase();this.level=L[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 r=typeof e=="string"?JSON.parse(e):e;if(t==="Bash"&&r.command){let o=r.command.length>50?r.command.substring(0,50)+"...":r.command;return`${t}(${o})`}if(t==="Read"&&r.file_path){let o=r.file_path.split("/").pop()||r.file_path;return`${t}(${o})`}if(t==="Edit"&&r.file_path){let o=r.file_path.split("/").pop()||r.file_path;return`${t}(${o})`}if(t==="Write"&&r.file_path){let o=r.file_path.split("/").pop()||r.file_path;return`${t}(${o})`}return t}catch{return t}}log(t,e,r,o,s){if(t<this.getLevel())return;let i=new Date().toISOString().replace("T"," ").substring(0,23),u=L[t].padEnd(5),c=e.padEnd(6),p="";o?.correlationId?p=`[${o.correlationId}] `:o?.sessionId&&(p=`[session-${o.sessionId}] `);let g="";s!=null&&(this.getLevel()===0&&typeof s=="object"?g=`
|
|
`+JSON.stringify(s,null,2):g=" "+this.formatData(s));let P="";if(o){let{sessionId:Nt,sdkSessionId:xt,correlationId:$t,...b}=o;Object.keys(b).length>0&&(P=` {${Object.entries(b).map(([rt,ot])=>`${rt}=${ot}`).join(", ")}}`)}let U=`[${i}] [${u}] [${c}] ${p}${r}${P}${g}`;t===3?console.error(U):console.log(U)}debug(t,e,r,o){this.log(0,t,e,r,o)}info(t,e,r,o){this.log(1,t,e,r,o)}warn(t,e,r,o){this.log(2,t,e,r,o)}error(t,e,r,o){this.log(3,t,e,r,o)}dataIn(t,e,r,o){this.info(t,`\u2192 ${e}`,r,o)}dataOut(t,e,r,o){this.info(t,`\u2190 ${e}`,r,o)}success(t,e,r,o){this.info(t,`\u2713 ${e}`,r,o)}failure(t,e,r,o){this.error(t,`\u2717 ${e}`,r,o)}timing(t,e,r,o){this.info(t,`\u23F1 ${e}`,o,{duration:`${r}ms`})}},l=new y});import{join as f,dirname as Et,basename as Zt}from"path";import{homedir as mt}from"os";import{fileURLToPath as _t}from"url";function dt(){return typeof __dirname<"u"?__dirname:Et(_t(import.meta.url))}var ne,a,w,se,ie,ae,ce,ue,pe,le,fe,ge,Ee,I=m(()=>{"use strict";D();ne=dt(),a=E.get("CLAUDE_MEM_DATA_DIR"),w=process.env.CLAUDE_CONFIG_DIR||f(mt(),".claude"),se=f(a,"archives"),ie=f(a,"logs"),ae=f(a,"trash"),ce=f(a,"backups"),ue=f(a,"settings.json"),pe=f(a,"claude-mem.db"),le=f(a,"vector-db"),fe=f(w,"settings.json"),ge=f(w,"commands"),Ee=f(w,"CLAUDE.md")});var G={};st(G,{BinaryManager:()=>M});import{existsSync as W,mkdirSync as St,writeFileSync as B,readFileSync as K}from"fs";import{join as d}from"path";var A,R,Tt,M,V=m(()=>{"use strict";I();A=d(a,"bin"),R=d(A,"version.txt"),Tt="https://github.com/thedotmack/claude-mem/releases/download",M=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=`${Tt}/v${t}/worker-service-v${t}-win-x64.exe`;console.log(`Downloading worker binary v${t}...`);let r=await fetch(e);if(!r.ok)throw new Error(`Download failed: ${r.status}
|
|
URL: ${e}
|
|
Make sure the release exists with a Windows binary attached.`);let o=await r.arrayBuffer();St(A,{recursive:!0});let s=d(A,"worker-service.exe");B(s,Buffer.from(o)),B(R,t),console.log("Download complete")}static getCurrentVersion(){try{return JSON.parse(K(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)?K(R,"utf-8").trim():null}catch{return null}}}});import{stdin as et}from"process";function it(n,t,e){return n==="SessionStart"?t&&e.context?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.context}}:{continue:!0,suppressOutput:!0}:n==="UserPromptSubmit"||n==="PostToolUse"?{continue:!0,suppressOutput:!0}:n==="Stop"?{continue:!0,suppressOutput:!0}:{continue:t,suppressOutput:!0,...e.reason&&!t?{stopReason:e.reason}:{}}}function N(n,t,e={}){let r=it(n,t,e);return JSON.stringify(r)}h();h();import Dt from"path";import{homedir as Lt}from"os";import{spawnSync as yt}from"child_process";var _={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,WINDOWS_MULTIPLIER:1.5};function F(n){return process.platform==="win32"?Math.round(n*_.WINDOWS_MULTIPLIER):n}I();import{existsSync as v,readFileSync as Ot,writeFileSync as ht,unlinkSync as At,mkdirSync as X}from"fs";import{createWriteStream as j}from"fs";import{join as T}from"path";import{spawn as Y}from"child_process";import{homedir as Ct}from"os";var S=T(a,"worker.pid"),J=T(a,"logs"),q=T(Ct(),".claude","plugins","marketplaces","thedotmack"),C=class{static async start(t){if(await this.isRunning())return{success:!0,pid:this.getPidInfo()?.pid};X(J,{recursive:!0});let e=T(q,"plugin","scripts","worker-service.cjs");if(!v(e))return{success:!1,error:`Worker script not found at ${e}`};let r=this.getLogFilePath();return process.platform==="win32"?this.startWindows(t):this.startUnix(e,r,t)}static async startUnix(t,e,r){try{let o=Y("bun",[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(r)},cwd:q}),s=j(e,{flags:"a"});return o.stdout?.pipe(s),o.stderr?.pipe(s),o.unref(),o.pid?(this.writePidFile({pid:o.pid,port:r,startedAt:new Date().toISOString(),version:process.env.npm_package_version||"unknown"}),this.waitForHealth(o.pid,r)):{success:!1,error:"Failed to get PID from spawned process"}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}static async startWindows(t){let{BinaryManager:e}=await Promise.resolve().then(()=>(V(),G));try{let r=await e.getExecutablePath(),o=Y(r,[],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(t)},windowsHide:!0}),s=this.getLogFilePath(),i=j(s,{flags:"a"});return o.stdout?.pipe(i),o.stderr?.pipe(i),o.unref(),o.pid?(this.writePidFile({pid:o.pid,port:t,startedAt:new Date().toISOString(),version:process.env.npm_package_version||"unknown"}),this.waitForHealth(o.pid,t)):{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=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(!v(S))return null;let t=Ot(S,"utf-8");return JSON.parse(t)}catch{return null}}static writePidFile(t){X(a,{recursive:!0}),ht(S,JSON.stringify(t,null,2))}static removePidFile(){try{v(S)&&At(S)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,r=1e4){let o=Date.now(),s=200;for(;Date.now()-o<r;){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,s))}return{success:!1,error:"Health check timed out"}}static async waitForExit(t,e){let r=Date.now(),o=100;for(;Date.now()-r<e;){if(!this.isProcessAlive(t))return;await new Promise(s=>setTimeout(s,o))}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(),o=Date.now()-e,s=Math.floor(o/1e3),i=Math.floor(s/60),u=Math.floor(i/60),c=Math.floor(u/24);return c>0?`${c}d ${u%24}h`:u>0?`${u}h ${i%60}m`:i>0?`${i}m ${s%60}s`:`${s}s`}};var wt=Dt.join(Lt(),".claude","plugins","marketplaces","thedotmack"),It=F(_.HEALTH_CHECK),Rt=38888;function O(){return Rt}async function Q(){try{let n=O();return(await fetch(`http://127.0.0.1:${n}/health`,{signal:AbortSignal.timeout(It)})).ok}catch(n){return l.debug("SYSTEM","Worker health check failed",{error:n instanceof Error?n.message:String(n),errorType:n?.constructor?.name}),!1}}async function Mt(){if(process.platform!=="win32")try{yt("pm2",["delete","claude-mem-worker"],{stdio:"ignore"})}catch{}let n=O(),t=await C.start(n);return t.success||l.error("SYSTEM","Failed to start worker",{platform:process.platform,port:n,error:t.error,marketplaceRoot:wt}),t.success}async function z(){if(await Q())return;let n=await Mt();if(!(!n&&await Q())&&!n){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 vt}from"fs";import{homedir as kt}from"os";import{join as Pt}from"path";var Ut=Pt(kt(),".claude-mem","silent.log");function Z(n,t,e=""){let r=new Date().toISOString(),u=((new Error().stack||"").split(`
|
|
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),c=u?`${u[1].split("/").pop()}:${u[2]}`:"unknown",p=`[${r}] [HAPPY-PATH-ERROR] [${c}] ${n}`;if(t!==void 0)try{p+=` ${JSON.stringify(t)}`}catch(g){p+=` [stringify error: ${g}]`}p+=`
|
|
`;try{vt(Ut,p)}catch(g){console.error("[silent-debug] Failed to write to log:",g)}return e}function tt(n){throw n.cause?.code==="ECONNREFUSED"||n.name==="TimeoutError"||n.message?.includes("fetch failed")?new Error("There's a problem with the worker. Try: npm run worker:restart"):n}async function bt(n){if(await z(),!n)throw new Error("saveHook requires input");let{session_id:t,cwd:e,tool_name:r,tool_input:o,tool_response:s}=n,i=O(),u=l.formatTool(r,o);l.dataIn("HOOK",`PostToolUse: ${u}`,{workerPort:i});try{let c=await fetch(`http://127.0.0.1:${i}/api/sessions/observations`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({claudeSessionId:t,tool_name:r,tool_input:o,tool_response:s,cwd:Z("Missing cwd in PostToolUse hook input",{session_id:t,tool_name:r},e||"")}),signal:AbortSignal.timeout(_.DEFAULT)});if(!c.ok){let p=await c.text();throw l.failure("HOOK","Failed to send observation",{status:c.status},p),new Error(`Failed to send observation to worker: ${c.status} ${p}`)}l.debug("HOOK","Observation sent successfully",{toolName:r})}catch(c){tt(c)}console.log(N("PostToolUse",!0))}var k="";et.on("data",n=>k+=n);et.on("end",async()=>{let n=k?JSON.parse(k):void 0;await bt(n)});
|