Files
claude-mem/plugin/scripts/new-hook.js
T
Alex Newman 7cab32151e Enhance error handling and logging in early-settings and worker-utils
- Added silent debugging for settings file loading failures in early-settings.ts.
- Improved error logging in worker-utils.ts for health check and worker startup failures, including detailed error information and context.
2025-12-09 14:04:32 -05:00

13 lines
8.9 KiB
JavaScript
Executable File

#!/usr/bin/env node
import et from"path";import{stdin as k}from"process";function $(n,t,e){return n==="PreCompact"?t?{continue:!0,suppressOutput:!0}:{continue:!1,stopReason:e.reason||"Pre-compact operation failed",suppressOutput:!0}: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 S(n,t,e={}){let r=$(n,t,e);return JSON.stringify(r)}import E from"path";import{existsSync as h}from"fs";import{homedir as w}from"os";import{spawnSync as R}from"child_process";import{readFileSync as H,existsSync as W}from"fs";import{join as F}from"path";import{homedir as j}from"os";var v=["bugfix","feature","refactor","discovery","decision","change"],x=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"];var M=v.join(","),D=x.join(",");var g=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:"37777",CLAUDE_MEM_DATA_DIR:F(j(),".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:M,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:D,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 process.env[t]||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(!W(t))return this.getAllDefaults();let e=H(t,"utf-8"),o=JSON.parse(e).env||{},i={...this.DEFAULTS};for(let c of Object.keys(this.DEFAULTS))o[c]!==void 0&&(i[c]=o[c]);return i}};import{join as K}from"path";import{homedir as Y}from"os";import{existsSync as J,readFileSync as q}from"fs";import{appendFileSync as V}from"fs";import{homedir as X}from"os";import{join as B}from"path";var G=B(X(),".claude-mem","silent.log");function _(n,t,e=""){let r=new Date().toISOString(),p=((new Error().stack||"").split(`
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),l=p?`${p[1].split("/").pop()}:${p[2]}`:"unknown",s=`[${r}] [${l}] ${n}`;if(t!==void 0)try{s+=` ${JSON.stringify(t)}`}catch(a){s+=` [stringify error: ${a}]`}s+=`
`;try{V(G,s)}catch(a){console.error("[silent-debug] Failed to write to log:",a)}return e}var O=K(Y(),".claude-mem","settings.json");function N(n,t){try{if(J(O)){let r=JSON.parse(q(O,"utf-8")).env?.[n];if(r!==void 0)return r}}catch(e){_("Failed to load settings file",{error:e,settingsPath:O,key:n})}return process.env[n]||t}var T=(i=>(i[i.DEBUG=0]="DEBUG",i[i.INFO=1]="INFO",i[i.WARN=2]="WARN",i[i.ERROR=3]="ERROR",i[i.SILENT=4]="SILENT",i))(T||{}),d=class{level;useColor;constructor(){let t=N("CLAUDE_MEM_LOG_LEVEL","INFO").toUpperCase();this.level=T[t]??1,this.useColor=process.stdout.isTTY??!1}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.level===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,i){if(t<this.level)return;let c=new Date().toISOString().replace("T"," ").substring(0,23),p=T[t].padEnd(5),l=e.padEnd(6),s="";o?.correlationId?s=`[${o.correlationId}] `:o?.sessionId&&(s=`[session-${o.sessionId}] `);let a="";i!=null&&(this.level===0&&typeof i=="object"?a=`
`+JSON.stringify(i,null,2):a=" "+this.formatData(i));let f="";if(o){let{sessionId:ot,sdkSessionId:nt,correlationId:st,...L}=o;Object.keys(L).length>0&&(f=` {${Object.entries(L).map(([b,P])=>`${b}=${P}`).join(", ")}}`)}let y=`[${c}] [${p}] [${l}] ${s}${r}${f}${a}`;t===3?console.error(y):console.log(y)}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`})}},C=new d;var u=E.join(w(),".claude","plugins","marketplaces","thedotmack"),z=500,Q=1e3,Z=15;function m(){let n=E.join(w(),".claude-mem","settings.json"),t=g.loadFromFile(n);return parseInt(t.CLAUDE_MEM_WORKER_PORT,10)}async function U(){try{let n=m();return(await fetch(`http://127.0.0.1:${n}/health`,{signal:AbortSignal.timeout(z)})).ok}catch(n){return C.debug("SYSTEM","Worker health check failed",{error:n instanceof Error?n.message:String(n),errorType:n?.constructor?.name}),!1}}async function tt(){try{let n=E.join(u,"plugin","scripts","worker-service.cjs");if(!h(n))throw new Error(`Worker script not found at ${n}`);if(process.platform==="win32"){let t=R("powershell.exe",["-NoProfile","-NonInteractive","-Command",`Start-Process -FilePath 'node' -ArgumentList '${n}' -WorkingDirectory '${u}' -WindowStyle Hidden`],{cwd:u,stdio:"pipe",encoding:"utf-8",windowsHide:!0});if(t.status!==0)throw new Error(t.stderr||"PowerShell Start-Process failed")}else{let t=E.join(u,"ecosystem.config.cjs");if(!h(t))throw new Error(`Ecosystem config not found at ${t}`);let e=E.join(u,"node_modules",".bin","pm2"),r=h(e)?e:"pm2",o=R(r,["start",t],{cwd:u,stdio:"pipe",encoding:"utf-8"});if(o.status!==0)throw new Error(o.stderr||"PM2 start failed")}for(let t=0;t<Z;t++)if(await new Promise(e=>setTimeout(e,Q)),await U())return!0;return!1}catch(n){return C.error("SYSTEM","Failed to start worker",{platform:process.platform,workerScript:E.join(u,"plugin","scripts","worker-service.cjs"),error:n instanceof Error?n.message:String(n),marketplaceRoot:u}),!1}}async function I(){if(await U())return;if(!await tt()){let t=m();throw new Error(`Worker service failed to start on port ${t}.
To start manually, run:
cd ${u}
npx pm2 start ecosystem.config.cjs
If already running, try: npx pm2 restart claude-mem-worker`)}}async function rt(n){if(await I(),!n)throw new Error("newHook requires input");let{session_id:t,cwd:e,prompt:r}=n;_("[new-hook] Input received",{session_id:t,cwd:e,cwd_type:typeof e,cwd_length:e?.length,has_cwd:!!e,prompt_length:r?.length});let o=et.basename(e);_("[new-hook] Project extracted",{project:o,project_type:typeof o,project_length:o?.length,is_empty:o==="",cwd_was:e});let i=m(),c,p;try{let s=await fetch(`http://127.0.0.1:${i}/api/sessions/init`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({claudeSessionId:t,project:o,prompt:r}),signal:AbortSignal.timeout(5e3)});if(!s.ok){let f=await s.text();throw new Error(`Failed to initialize session: ${s.status} ${f}`)}let a=await s.json();if(c=a.sessionDbId,p=a.promptNumber,a.skipped&&a.reason==="private"){console.error(`[new-hook] Session ${c}, prompt #${p} (fully private - skipped)`),console.log(S("UserPromptSubmit",!0));return}console.error(`[new-hook] Session ${c}, prompt #${p}`)}catch(s){throw s.cause?.code==="ECONNREFUSED"||s.name==="TimeoutError"||s.message.includes("fetch failed")?new Error("There's a problem with the worker. If you just updated, type `pm2 restart claude-mem-worker` in your terminal to continue"):s}let l=r.startsWith("/")?r.substring(1):r;try{let s=await fetch(`http://127.0.0.1:${i}/sessions/${c}/init`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({project:o,userPrompt:l,promptNumber:p}),signal:AbortSignal.timeout(5e3)});if(!s.ok){let a=await s.text();throw new Error(`Failed to initialize session: ${s.status} ${a}`)}}catch(s){throw s.cause?.code==="ECONNREFUSED"||s.name==="TimeoutError"||s.message.includes("fetch failed")?new Error("There's a problem with the worker. If you just updated, type `pm2 restart claude-mem-worker` in your terminal to continue"):s}console.log(S("UserPromptSubmit",!0))}var A="";k.on("data",n=>A+=n);k.on("end",async()=>{let n=A?JSON.parse(A):void 0;await rt(n)});