Files
claude-mem/plugin/scripts/context-hook.js
T
Alex Newman bb0508d639 Refactor error handling to use platform-specific worker restart instructions
- Updated multiple hooks (context-hook, new-hook, save-hook, summary-hook, user-message-hook) to throw errors using `getWorkerRestartInstructions` for improved user guidance on worker connection issues.
- Enhanced `handleWorkerError` function to utilize the new error message generator for consistent error reporting.
- Modified `ensureWorkerRunning` function to provide detailed instructions based on the worker's state, including port information.
- Introduced `getWorkerRestartInstructions` utility in `error-messages.ts` to generate platform-aware error messages for worker failures.
2025-12-13 17:06:45 -05:00

13 lines
12 KiB
JavaScript
Executable File

#!/usr/bin/env bun
import At from"path";import{stdin as I}from"process";import h from"path";import{homedir as mt}from"os";import{spawnSync as St}from"child_process";import{existsSync as dt,writeFileSync as W,readFileSync as Tt}from"fs";import{readFileSync as J,writeFileSync as q,existsSync as Q}from"fs";import{join as z}from"path";import{homedir as Z}from"os";var X=["bugfix","feature","refactor","discovery","decision","change"],Y=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"];var P=X.join(","),U=Y.join(",");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:z(Z(),".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:P,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:U,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(!Q(t))return this.getAllDefaults();let e=J(t,"utf-8"),o=JSON.parse(e),r=o;if(o.env&&typeof o.env=="object"){r=o.env;try{q(t,JSON.stringify(r,null,2),"utf-8"),a.info("SETTINGS","Migrated settings file from nested to flat schema",{settingsPath:t})}catch(i){a.warn("SETTINGS","Failed to auto-migrate settings file",{settingsPath:t},i)}}let s={...this.DEFAULTS};for(let i of Object.keys(this.DEFAULTS))r[i]!==void 0&&(s[i]=r[i]);return s}};var A=(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))(A||{}),M=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=A[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 o=typeof e=="string"?JSON.parse(e):e;if(t==="Bash"&&o.command){let r=o.command.length>50?o.command.substring(0,50)+"...":o.command;return`${t}(${r})`}if(t==="Read"&&o.file_path){let r=o.file_path.split("/").pop()||o.file_path;return`${t}(${r})`}if(t==="Edit"&&o.file_path){let r=o.file_path.split("/").pop()||o.file_path;return`${t}(${r})`}if(t==="Write"&&o.file_path){let r=o.file_path.split("/").pop()||o.file_path;return`${t}(${r})`}return t}catch{return t}}log(t,e,o,r,s){if(t<this.getLevel())return;let i=new Date().toISOString().replace("T"," ").substring(0,23),E=A[t].padEnd(5),_=e.padEnd(6),c="";r?.correlationId?c=`[${r.correlationId}] `:r?.sessionId&&(c=`[session-${r.sessionId}] `);let C="";s!=null&&(this.getLevel()===0&&typeof s=="object"?C=`
`+JSON.stringify(s,null,2):C=" "+this.formatData(s));let w="";if(r){let{sessionId:Dt,sdkSessionId:Lt,correlationId:Rt,...k}=r;Object.keys(k).length>0&&(w=` {${Object.entries(k).map(([B,G])=>`${B}=${G}`).join(", ")}}`)}let y=`[${i}] [${E}] [${_}] ${c}${o}${w}${C}`;t===3?console.error(y):console.log(y)}debug(t,e,o,r){this.log(0,t,e,o,r)}info(t,e,o,r){this.log(1,t,e,o,r)}warn(t,e,o,r){this.log(2,t,e,o,r)}error(t,e,o,r){this.log(3,t,e,o,r)}dataIn(t,e,o,r){this.info(t,`\u2192 ${e}`,o,r)}dataOut(t,e,o,r){this.info(t,`\u2190 ${e}`,o,r)}success(t,e,o,r){this.info(t,`\u2713 ${e}`,o,r)}failure(t,e,o,r){this.error(t,`\u2717 ${e}`,o,r)}timing(t,e,o,r){this.info(t,`\u23F1 ${e}`,r,{duration:`${o}ms`})}},a=new M;var S={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,WINDOWS_MULTIPLIER:1.5};function v(n){return process.platform==="win32"?Math.round(n*S.WINDOWS_MULTIPLIER):n}import{existsSync as L,readFileSync as ot,writeFileSync as st,unlinkSync as it,mkdirSync as b}from"fs";import{createWriteStream as at}from"fs";import{join as T}from"path";import{spawn as ct,spawnSync as ut}from"child_process";import{homedir as lt}from"os";import{join as l,dirname as tt,basename as Ht}from"path";import{homedir as et}from"os";import{fileURLToPath as rt}from"url";function nt(){return typeof __dirname<"u"?__dirname:tt(rt(import.meta.url))}var Bt=nt(),p=u.get("CLAUDE_MEM_DATA_DIR"),D=process.env.CLAUDE_CONFIG_DIR||l(et(),".claude"),Gt=l(p,"archives"),Xt=l(p,"logs"),Yt=l(p,"trash"),Jt=l(p,"backups"),qt=l(p,"settings.json"),Qt=l(p,"claude-mem.db"),zt=l(p,"vector-db"),Zt=l(D,"settings.json"),te=l(D,"commands"),ee=l(D,"CLAUDE.md");var d=T(p,"worker.pid"),N=T(p,"logs"),x=T(lt(),".claude","plugins","marketplaces","thedotmack"),pt=5e3,Et=1e4,ft=200,gt=1e3,_t=100,O=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};b(N,{recursive:!0});let e=T(x,"plugin","scripts","worker-service.cjs");if(!L(e))return{success:!1,error:`Worker script not found at ${e}`};let o=this.getLogFilePath();return this.startWithBun(e,o,t)}static isBunAvailable(){try{return ut("bun",["--version"],{stdio:"pipe",timeout:5e3}).status===0}catch{return!1}}static async startWithBun(t,e,o){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",s=ct("bun",[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(o)},cwd:x,...r&&{windowsHide:!0}}),i=at(e,{flags:"a"});return s.stdout?.pipe(i),s.stderr?.pipe(i),s.unref(),s.pid?(this.writePidFile({pid:s.pid,port:o,startedAt:new Date().toISOString(),version:process.env.npm_package_version||"unknown"}),this.waitForHealth(s.pid,o)):{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=pt){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(!L(d))return null;let t=ot(d,"utf-8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.port!="number"?null:e}catch{return null}}static writePidFile(t){b(p,{recursive:!0}),st(d,JSON.stringify(t,null,2))}static removePidFile(){try{L(d)&&it(d)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,o=Et){let r=Date.now();for(;Date.now()-r<o;){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(gt)})).ok)return{success:!0,pid:t}}catch{}await new Promise(s=>setTimeout(s,ft))}return{success:!1,error:"Health check timed out"}}static async waitForExit(t,e){let o=Date.now();for(;Date.now()-o<e;){if(!this.isProcessAlive(t))return;await new Promise(r=>setTimeout(r,_t))}throw new Error("Process did not exit within timeout")}static getLogFilePath(){let t=new Date().toISOString().slice(0,10);return T(N,`worker-${t}.log`)}static formatUptime(t){let e=new Date(t).getTime(),r=Date.now()-e,s=Math.floor(r/1e3),i=Math.floor(s/60),E=Math.floor(i/60),_=Math.floor(E/24);return _>0?`${_}d ${E%24}h`:E>0?`${E}h ${i%60}m`:i>0?`${i}m ${s%60}s`:`${s}s`}};function g(n={}){let{port:t,includeSkillFallback:e=!1,customPrefix:o}=n,r=process.platform==="win32",s=r?"%USERPROFILE%\\.claude\\plugins\\marketplaces\\thedotmack":"~/.claude/plugins/marketplaces/thedotmack",i=r?"Command Prompt or PowerShell":"Terminal",E=o||"Worker service connection failed.",_=t?` (port ${t})`:"",c=`${E}${_}
`;return c+=`To restart the worker:
`,c+=`1. Exit Claude Code completely
`,c+=`2. Open ${i}
`,c+=`3. Navigate to: ${s}
`,c+="4. Run: npm run worker:restart",e&&(c+=`
If that doesn't work, try: /troubleshoot`),c}var H=h.join(mt(),".claude","plugins","marketplaces","thedotmack"),$=v(S.HEALTH_CHECK),m=null;function f(){if(m!==null)return m;try{let n=h.join(u.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),t=u.loadFromFile(n);return m=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),m}catch(n){return a.debug("SYSTEM","Failed to load port from settings, using default",{error:n}),m=parseInt(u.get("CLAUDE_MEM_WORKER_PORT"),10),m}}async function R(){try{let n=f();return(await fetch(`http://127.0.0.1:${n}/health`,{signal:AbortSignal.timeout($)})).ok}catch(n){return a.debug("SYSTEM","Worker health check failed",{error:n instanceof Error?n.message:String(n),errorType:n?.constructor?.name}),!1}}function Ot(){try{let n=h.join(H,"package.json");return JSON.parse(Tt(n,"utf-8")).version}catch(n){return a.debug("SYSTEM","Failed to read plugin version",{error:n instanceof Error?n.message:String(n)}),null}}async function ht(){try{let n=f(),t=await fetch(`http://127.0.0.1:${n}/api/version`,{signal:AbortSignal.timeout($)});return t.ok?(await t.json()).version:null}catch(n){return a.debug("SYSTEM","Failed to get worker version",{error:n instanceof Error?n.message:String(n)}),null}}async function F(){let n=Ot(),t=await ht();!n||!t||n!==t&&(a.info("SYSTEM","Worker version mismatch detected - restarting worker",{pluginVersion:n,workerVersion:t}),await O.restart(f()),await new Promise(e=>setTimeout(e,1e3)),await R()||a.error("SYSTEM","Worker failed to restart after version mismatch"))}async function Ct(){let n=h.join(u.get("CLAUDE_MEM_DATA_DIR"),".pm2-migrated");if(!dt(n))try{St("pm2",["delete","claude-mem-worker"],{stdio:"ignore"}),W(n,new Date().toISOString(),"utf-8"),a.debug("SYSTEM","PM2 cleanup completed and marked")}catch{W(n,new Date().toISOString(),"utf-8")}let t=f(),e=await O.start(t);return e.success||a.error("SYSTEM","Failed to start worker",{platform:process.platform,port:t,error:e.error,marketplaceRoot:H}),e.success}async function K(){if(await R()){await F();return}if(!await Ct()){let e=f();throw new Error(g({port:e,customPrefix:`Worker service failed to start on port ${e}.`}))}for(let e=0;e<5;e++)if(await new Promise(o=>setTimeout(o,500)),await R()){await F();return}let t=f();throw a.error("SYSTEM","Worker started but not responding to health checks"),new Error(g({port:t,customPrefix:`Worker service started but is not responding on port ${t}.`}))}function j(n){throw n.cause?.code==="ECONNREFUSED"||n.code==="ConnectionRefused"||n.name==="TimeoutError"||n.message?.includes("fetch failed")||n.message?.includes("Unable to connect")?new Error(g()):n}async function V(n){await K();let t=n?.cwd??process.cwd(),e=t?At.basename(t):"unknown-project",r=`http://127.0.0.1:${f()}/api/context/inject?project=${encodeURIComponent(e)}`;try{let s=await fetch(r,{signal:AbortSignal.timeout(S.DEFAULT)});if(!s.ok){let E=await s.text();throw new Error(g({includeSkillFallback:!0}))}return(await s.text()).trim()}catch(s){j(s)}}var Mt=process.argv.includes("--colors");if(I.isTTY||Mt)V(void 0).then(n=>{console.log(n),process.exit(0)});else{let n="";I.on("data",t=>n+=t),I.on("end",async()=>{let t=n.trim()?JSON.parse(n):void 0,e=await V(t);console.log(JSON.stringify({hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e}})),process.exit(0)})}