Files
claude-mem/plugin/scripts/new-hook.js
T
Alex Newman 83b0f9551b feat: add admin endpoints for process management and improve error handling
- 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.
2025-12-10 23:46:17 -05:00

12 lines
13 KiB
JavaScript
Executable File

#!/usr/bin/env node
var ot=Object.defineProperty;var E=(o,t)=>()=>(o&&(t=o(o=0)),t);var st=(o,t)=>{for(var e in t)ot(o,e,{get:t[e],enumerable:!0})};var at,ct,$,H,F=E(()=>{"use strict";at=["bugfix","feature","refactor","discovery","decision","change"],ct=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"],$=at.join(","),H=ct.join(",")});import{readFileSync as pt,writeFileSync as ut,existsSync as lt}from"fs";import{join as ft}from"path";import{homedir as mt}from"os";var m,D=E(()=>{"use strict";F();y();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:ft(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(!lt(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{ut(t,JSON.stringify(n,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 s={...this.DEFAULTS};for(let i of Object.keys(this.DEFAULTS))n[i]!==void 0&&(s[i]=n[i]);return s}}});var L,w,g,y=E(()=>{"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||{}),w=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=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 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,s){if(t<this.getLevel())return;let i=new Date().toISOString().replace("T"," ").substring(0,23),c=L[t].padEnd(5),f=e.padEnd(6),a="";n?.correlationId?a=`[${n.correlationId}] `:n?.sessionId&&(a=`[session-${n.sessionId}] `);let p="";s!=null&&(this.getLevel()===0&&typeof s=="object"?p=`
`+JSON.stringify(s,null,2):p=" "+this.formatData(s));let h="";if(n){let{sessionId:xt,sdkSessionId:$t,correlationId:Ht,...x}=n;Object.keys(x).length>0&&(h=` {${Object.entries(x).map(([rt,nt])=>`${rt}=${nt}`).join(", ")}}`)}let N=`[${i}] [${c}] [${f}] ${a}${r}${h}${p}`;t===3?console.error(N):console.log(N)}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`})}},g=new w});import{join as l,dirname as gt,basename as te}from"path";import{homedir as Et}from"os";import{fileURLToPath as _t}from"url";function dt(){return typeof __dirname<"u"?__dirname:gt(_t(import.meta.url))}var se,u,I,ie,ae,ce,pe,ue,le,fe,me,ge,Ee,M=E(()=>{"use strict";D();se=dt(),u=m.get("CLAUDE_MEM_DATA_DIR"),I=process.env.CLAUDE_CONFIG_DIR||l(Et(),".claude"),ie=l(u,"archives"),ae=l(u,"logs"),ce=l(u,"trash"),pe=l(u,"backups"),ue=l(u,"settings.json"),le=l(u,"claude-mem.db"),fe=l(u,"vector-db"),me=l(I,"settings.json"),ge=l(I,"commands"),Ee=l(I,"CLAUDE.md")});var K={};st(K,{BinaryManager:()=>b});import{existsSync as B,mkdirSync as St,writeFileSync as G,readFileSync as V}from"fs";import{join as _}from"path";var O,k,Tt,b,j=E(()=>{"use strict";M();O=_(u,"bin"),k=_(O,"version.txt"),Tt="https://github.com/thedotmack/claude-mem/releases/download",b=class{static async getExecutablePath(){if(process.platform!=="win32")throw new Error("BinaryManager only used on Windows");let t=this.getCurrentVersion(),e=_(O,"worker-service.exe");return B(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();St(O,{recursive:!0});let s=_(O,"worker-service.exe");G(s,Buffer.from(n)),G(k,t),console.log("Download complete")}static getCurrentVersion(){try{return JSON.parse(V(_(u,"..",".claude","plugins","marketplaces","thedotmack","package.json"),"utf-8")).version}catch{return process.env.npm_package_version||"unknown"}}static getInstalledVersion(){try{return B(k)?V(k,"utf-8").trim():null}catch{return null}}}});import Ut from"path";import{stdin as et}from"process";function it(o,t,e){return o==="SessionStart"?t&&e.context?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.context}}:{continue:!0,suppressOutput:!0}:o==="UserPromptSubmit"||o==="PostToolUse"?{continue:!0,suppressOutput:!0}:o==="Stop"?{continue:!0,suppressOutput:!0}:{continue:t,suppressOutput:!0,...e.reason&&!t?{stopReason:e.reason}:{}}}function C(o,t,e={}){let r=it(o,t,e);return JSON.stringify(r)}y();import Dt from"path";import{homedir as yt}from"os";import{spawnSync as Lt}from"child_process";var R={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,WINDOWS_MULTIPLIER:1.5};function W(o){return process.platform==="win32"?Math.round(o*R.WINDOWS_MULTIPLIER):o}M();import{existsSync as v,readFileSync as ht,writeFileSync as Ot,unlinkSync as At,mkdirSync as X}from"fs";import{createWriteStream as Y}from"fs";import{join as S}from"path";import{spawn as J}from"child_process";import{homedir as Ct}from"os";var d=S(u,"worker.pid"),q=S(u,"logs"),z=S(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=S(z,"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 n=J("bun",[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(r)},cwd:z}),s=Y(e,{flags:"a"});return n.stdout?.pipe(s),n.stderr?.pipe(s),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(),K));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}),s=this.getLogFilePath(),i=Y(s,{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(!v(d))return null;let t=ht(d,"utf-8");return JSON.parse(t)}catch{return null}}static writePidFile(t){X(u,{recursive:!0}),Ot(d,JSON.stringify(t,null,2))}static removePidFile(){try{v(d)&&At(d)}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(),s=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,s))}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(s=>setTimeout(s,n))}throw new Error("Process did not exit within timeout")}static getLogFilePath(){let t=new Date().toISOString().slice(0,10);return S(q,`worker-${t}.log`)}static formatUptime(t){let e=new Date(t).getTime(),n=Date.now()-e,s=Math.floor(n/1e3),i=Math.floor(s/60),c=Math.floor(i/60),f=Math.floor(c/24);return f>0?`${f}d ${c%24}h`:c>0?`${c}h ${i%60}m`:i>0?`${i}m ${s%60}s`:`${s}s`}};var wt=Dt.join(yt(),".claude","plugins","marketplaces","thedotmack"),Rt=W(R.HEALTH_CHECK),It=38888;function T(){return It}async function Q(){try{let o=T();return(await fetch(`http://127.0.0.1:${o}/health`,{signal:AbortSignal.timeout(Rt)})).ok}catch(o){return g.debug("SYSTEM","Worker health check failed",{error:o instanceof Error?o.message:String(o),errorType:o?.constructor?.name}),!1}}async function Mt(){if(process.platform!=="win32")try{Lt("pm2",["delete","claude-mem-worker"],{stdio:"ignore"})}catch{}let o=T(),t=await A.start(o);return t.success||g.error("SYSTEM","Failed to start worker",{platform:process.platform,port:o,error:t.error,marketplaceRoot:wt}),t.success}async function Z(){if(await Q())return;let o=await Mt();if(!(!o&&await Q())&&!o){let t=T();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 kt}from"fs";import{homedir as bt}from"os";import{join as vt}from"path";var Pt=vt(bt(),".claude-mem","silent.log");function tt(o,t,e=""){let r=new Date().toISOString(),c=((new Error().stack||"").split(`
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),f=c?`${c[1].split("/").pop()}:${c[2]}`:"unknown",a=`[${r}] [HAPPY-PATH-ERROR] [${f}] ${o}`;if(t!==void 0)try{a+=` ${JSON.stringify(t)}`}catch(p){a+=` [stringify error: ${p}]`}a+=`
`;try{kt(Pt,a)}catch(p){console.error("[silent-debug] Failed to write to log:",p)}return e}function P(o){throw o.cause?.code==="ECONNREFUSED"||o.name==="TimeoutError"||o.message?.includes("fetch failed")?new Error("There's a problem with the worker. Try: npm run worker:restart"):o}async function Nt(o){if(await Z(),!o)throw new Error("newHook requires input");let{session_id:t,cwd:e,prompt:r}=o,n=Ut.basename(e);tt("[new-hook] Input received",{session_id:t,project:n,prompt_length:r?.length});let s=T(),i,c;try{let a=await fetch(`http://127.0.0.1:${s}/api/sessions/init`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({claudeSessionId:t,project:n,prompt:r}),signal:AbortSignal.timeout(5e3)});if(!a.ok){let h=await a.text();throw new Error(`Failed to initialize session: ${a.status} ${h}`)}let p=await a.json();if(i=p.sessionDbId,c=p.promptNumber,p.skipped&&p.reason==="private"){console.error(`[new-hook] Session ${i}, prompt #${c} (fully private - skipped)`),console.log(C("UserPromptSubmit",!0));return}console.error(`[new-hook] Session ${i}, prompt #${c}`)}catch(a){P(a)}let f=r.startsWith("/")?r.substring(1):r;try{let a=await fetch(`http://127.0.0.1:${s}/sessions/${i}/init`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({userPrompt:f,promptNumber:c}),signal:AbortSignal.timeout(5e3)});if(!a.ok){let p=await a.text();throw new Error(`Failed to start SDK agent: ${a.status} ${p}`)}}catch(a){P(a)}console.log(C("UserPromptSubmit",!0))}var U="";et.on("data",o=>U+=o);et.on("end",async()=>{let o=U?JSON.parse(U):void 0;await Nt(o)});