mirror of
https://github.com/thedotmack/claude-mem
synced 2026-04-26 09:35:19 +02:00
- Removed direct database operations in new-hook.ts and replaced them with an HTTP call to initialize sessions. - Added error handling for HTTP requests and improved logging for session initialization. - Updated SessionRoutes to handle new session initialization and privacy checks. - Enhanced privacy tag stripping logic to prevent saving fully private prompts. - Improved overall error handling and debugging messages throughout the session management process.
11 lines
6.0 KiB
JavaScript
Executable File
11 lines
6.0 KiB
JavaScript
Executable File
#!/usr/bin/env node
|
|
import X from"path";import{stdin as h}from"process";function D(e,t,r){return e==="PreCompact"?t?{continue:!0,suppressOutput:!0}:{continue:!1,stopReason:r.reason||"Pre-compact operation failed",suppressOutput:!0}:e==="SessionStart"?t&&r.context?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:r.context}}:{continue:!0,suppressOutput:!0}:e==="UserPromptSubmit"||e==="PostToolUse"?{continue:!0,suppressOutput:!0}:e==="Stop"?{continue:!0,suppressOutput:!0}:{continue:t,suppressOutput:!0,...r.reason&&!t?{stopReason:r.reason}:{}}}function T(e,t,r={}){let s=D(e,t,r);return JSON.stringify(s)}import u from"path";import{existsSync as O}from"fs";import{homedir as C}from"os";import{spawnSync as A}from"child_process";import{readFileSync as U,existsSync as R}from"fs";import{join as P}from"path";import{homedir as k}from"os";var w=["bugfix","feature","refactor","discovery","decision","change"],y=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"];var d=w.join(","),g=y.join(",");var _=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:"37777",CLAUDE_MEM_DATA_DIR:P(k(),".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:d,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:g,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 r=this.get(t);return parseInt(r,10)}static getBool(t){return this.get(t)==="true"}static loadFromFile(t){if(!R(t))return this.getAllDefaults();let r=U(t,"utf-8"),n=JSON.parse(r).env||{},p={...this.DEFAULTS};for(let a of Object.keys(this.DEFAULTS))n[a]!==void 0&&(p[a]=n[a]);return p}};var E=u.join(C(),".claude","plugins","marketplaces","thedotmack"),I=500,b=1e3,x=15;function l(){let e=u.join(C(),".claude-mem","settings.json"),t=_.loadFromFile(e);return parseInt(t.CLAUDE_MEM_WORKER_PORT,10)}async function M(){try{let e=l();return(await fetch(`http://127.0.0.1:${e}/health`,{signal:AbortSignal.timeout(I)})).ok}catch{return!1}}async function H(){try{let e=u.join(E,"plugin","scripts","worker-service.cjs");if(!O(e))throw new Error(`Worker script not found at ${e}`);if(process.platform==="win32"){let t=A("powershell.exe",["-NoProfile","-NonInteractive","-Command",`Start-Process -FilePath 'node' -ArgumentList '${e}' -WorkingDirectory '${E}' -WindowStyle Hidden`],{cwd:E,stdio:"pipe",encoding:"utf-8",windowsHide:!0});if(t.status!==0)throw new Error(t.stderr||"PowerShell Start-Process failed")}else{let t=u.join(E,"ecosystem.config.cjs");if(!O(t))throw new Error(`Ecosystem config not found at ${t}`);let r=u.join(E,"node_modules",".bin","pm2"),s=O(r)?r:"pm2",n=A(s,["start",t],{cwd:E,stdio:"pipe",encoding:"utf-8"});if(n.status!==0)throw new Error(n.stderr||"PM2 start failed")}for(let t=0;t<x;t++)if(await new Promise(r=>setTimeout(r,b)),await M())return!0;return!1}catch{return!1}}async function N(){if(await M())return;if(!await H()){let t=l();throw new Error(`Worker service failed to start on port ${t}.
|
|
|
|
To start manually, run:
|
|
cd ${E}
|
|
npx pm2 start ecosystem.config.cjs
|
|
|
|
If already running, try: npx pm2 restart claude-mem-worker`)}}import{appendFileSync as W}from"fs";import{homedir as F}from"os";import{join as $}from"path";var v=$(F(),".claude-mem","silent.log");function m(e,t,r=""){let s=new Date().toISOString(),c=((new Error().stack||"").split(`
|
|
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),S=c?`${c[1].split("/").pop()}:${c[2]}`:"unknown",o=`[${s}] [${S}] ${e}`;if(t!==void 0)try{o+=` ${JSON.stringify(t)}`}catch(i){o+=` [stringify error: ${i}]`}o+=`
|
|
`;try{W(v,o)}catch(i){console.error("[silent-debug] Failed to write to log:",i)}return r}async function j(e){if(await N(),!e)throw new Error("newHook requires input");let{session_id:t,cwd:r,prompt:s}=e;m("[new-hook] Input received",{session_id:t,cwd:r,cwd_type:typeof r,cwd_length:r?.length,has_cwd:!!r,prompt_length:s?.length});let n=X.basename(r);m("[new-hook] Project extracted",{project:n,project_type:typeof n,project_length:n?.length,is_empty:n==="",cwd_was:r});let p=l(),a,c;try{let o=await fetch(`http://127.0.0.1:${p}/api/sessions/init`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({claudeSessionId:t,project:n,prompt:s}),signal:AbortSignal.timeout(5e3)});if(!o.ok){let L=await o.text();throw new Error(`Failed to initialize session: ${o.status} ${L}`)}let i=await o.json();if(a=i.sessionDbId,c=i.promptNumber,i.skipped&&i.reason==="private"){console.error(`[new-hook] Session ${a}, prompt #${c} (fully private - skipped)`),console.log(T("UserPromptSubmit",!0));return}console.error(`[new-hook] Session ${a}, prompt #${c}`)}catch(o){throw o.cause?.code==="ECONNREFUSED"||o.name==="TimeoutError"||o.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"):o}let S=s.startsWith("/")?s.substring(1):s;try{let o=await fetch(`http://127.0.0.1:${p}/sessions/${a}/init`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({project:n,userPrompt:S,promptNumber:c}),signal:AbortSignal.timeout(5e3)});if(!o.ok){let i=await o.text();throw new Error(`Failed to initialize session: ${o.status} ${i}`)}}catch(o){throw o.cause?.code==="ECONNREFUSED"||o.name==="TimeoutError"||o.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"):o}console.log(T("UserPromptSubmit",!0))}var f="";h.on("data",e=>f+=e);h.on("end",async()=>{let e=f?JSON.parse(f):void 0;await j(e)});
|