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