mirror of
https://github.com/thedotmack/claude-mem
synced 2026-04-26 01:25:10 +02:00
- Implemented a method to check if Bun is available in the system PATH. - Updated the startWithBun method to return an error if Bun is not found. - Enhanced PID file parsing to validate required fields and their types. - Cleaned up stale PID files if the process is no longer alive. fix(SettingsRoutes): clear port cache after updating settings - Added a call to clearPortCache after writing updated settings to ensure the application uses the latest configuration.
14 lines
12 KiB
JavaScript
Executable File
14 lines
12 KiB
JavaScript
Executable File
#!/usr/bin/env bun
|
|
import{stdin as K}from"process";function V(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 U(o,t,e={}){let r=V(o,t,e);return JSON.stringify(r)}import{readFileSync as Y,writeFileSync as J,existsSync as q}from"fs";import{join as z}from"path";import{homedir as Q}from"os";var j=["bugfix","feature","refactor","discovery","decision","change"],X=["how-it-works","why-it-exists","what-changed","problem-solution","gotcha","pattern","trade-off"];var w=j.join(","),P=X.join(",");var 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:z(Q(),".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:w,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:P,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=Y(t,"utf-8"),r=JSON.parse(e),n=r;if(r.env&&typeof r.env=="object"){n=r.env;try{J(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 s={...this.DEFAULTS};for(let i of Object.keys(this.DEFAULTS))n[i]!==void 0&&(s[i]=n[i]);return s}};var h=(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))(h||{}),A=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=h[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),a=h[t].padEnd(5),p=e.padEnd(6),u="";n?.correlationId?u=`[${n.correlationId}] `:n?.sessionId&&(u=`[session-${n.sessionId}] `);let E="";s!=null&&(this.getLevel()===0&&typeof s=="object"?E=`
|
|
`+JSON.stringify(s,null,2):E=" "+this.formatData(s));let D="";if(n){let{sessionId:Dt,sdkSessionId:Rt,correlationId:It,...I}=n;Object.keys(I).length>0&&(D=` {${Object.entries(I).map(([B,G])=>`${B}=${G}`).join(", ")}}`)}let R=`[${i}] [${a}] [${p}] ${u}${r}${D}${E}`;t===3?console.error(R):console.log(R)}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 A;import H from"path";import{homedir as _t}from"os";import{spawnSync as gt}from"child_process";var g={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,WINDOWS_MULTIPLIER:1.5};function N(o){return process.platform==="win32"?Math.round(o*g.WINDOWS_MULTIPLIER):o}import{existsSync as L,readFileSync as nt,writeFileSync as ot,unlinkSync as st,mkdirSync as b}from"fs";import{createWriteStream as it}from"fs";import{join as d}from"path";import{spawn as at,spawnSync as ct}from"child_process";import{homedir as ut}from"os";import{join as l,dirname as Z,basename as Bt}from"path";import{homedir as tt}from"os";import{fileURLToPath as et}from"url";function rt(){return typeof __dirname<"u"?__dirname:Z(et(import.meta.url))}var Yt=rt(),f=m.get("CLAUDE_MEM_DATA_DIR"),C=process.env.CLAUDE_CONFIG_DIR||l(tt(),".claude"),Jt=l(f,"archives"),qt=l(f,"logs"),zt=l(f,"trash"),Qt=l(f,"backups"),Zt=l(f,"settings.json"),te=l(f,"claude-mem.db"),ee=l(f,"vector-db"),re=l(C,"settings.json"),ne=l(C,"commands"),oe=l(C,"CLAUDE.md");var S=d(f,"worker.pid"),k=d(f,"logs"),v=d(ut(),".claude","plugins","marketplaces","thedotmack"),pt=5e3,lt=1e4,ft=200,mt=1e3,Et=100,O=class{static async start(t){if(await this.isRunning())return{success:!0,pid:this.getPidInfo()?.pid};b(k,{recursive:!0});let e=d(v,"plugin","scripts","worker-service.cjs");if(!L(e))return{success:!1,error:`Worker script not found at ${e}`};let r=this.getLogFilePath();return this.startWithBun(e,r,t)}static isBunAvailable(){try{return ct("bun",["--version"],{stdio:"pipe",timeout:5e3}).status===0}catch{return!1}}static async startWithBun(t,e,r){if(!this.isBunAvailable())return{success:!1,error:"Bun is required but not found in PATH. Install from https://bun.sh"};try{let n=process.platform==="win32",s=at("bun",[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(r)},cwd:v,...n&&{windowsHide:!0}}),i=it(e,{flags:"a"});return s.stdout?.pipe(i),s.stderr?.pipe(i),s.unref(),s.pid?(this.writePidFile({pid:s.pid,port:r,startedAt:new Date().toISOString(),version:process.env.npm_package_version||"unknown"}),this.waitForHealth(s.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 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(S))return null;let t=nt(S,"utf-8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.port!="number"?null:e}catch{return null}}static writePidFile(t){b(f,{recursive:!0}),ot(S,JSON.stringify(t,null,2))}static removePidFile(){try{L(S)&&st(S)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,r=lt){let n=Date.now();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(mt)})).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 r=Date.now();for(;Date.now()-r<e;){if(!this.isProcessAlive(t))return;await new Promise(n=>setTimeout(n,Et))}throw new Error("Process did not exit within timeout")}static getLogFilePath(){let t=new Date().toISOString().slice(0,10);return d(k,`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),a=Math.floor(i/60),p=Math.floor(a/24);return p>0?`${p}d ${a%24}h`:a>0?`${a}h ${i%60}m`:i>0?`${i}m ${s%60}s`:`${s}s`}};var St=H.join(_t(),".claude","plugins","marketplaces","thedotmack"),dt=N(g.HEALTH_CHECK),_=null;function T(){if(_!==null)return _;try{let o=H.join(m.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),t=m.loadFromFile(o);return _=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),_}catch(o){return c.debug("SYSTEM","Failed to load port from settings, using default",{error:o}),_=parseInt(m.get("CLAUDE_MEM_WORKER_PORT"),10),_}}async function x(){try{let o=T();return(await fetch(`http://127.0.0.1:${o}/health`,{signal:AbortSignal.timeout(dt)})).ok}catch(o){return c.debug("SYSTEM","Worker health check failed",{error:o instanceof Error?o.message:String(o),errorType:o?.constructor?.name}),!1}}async function Tt(){if(process.platform!=="win32")try{gt("pm2",["delete","claude-mem-worker"],{stdio:"ignore"})}catch{}let o=T(),t=await O.start(o);return t.success||c.error("SYSTEM","Failed to start worker",{platform:process.platform,port:o,error:t.error,marketplaceRoot:St}),t.success}async function $(){if(await x())return;let o=await Tt();if(!(!o&&await x())&&!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 Ot}from"fs";import{homedir as ht}from"os";import{join as At}from"path";var Ct=At(ht(),".claude-mem","silent.log");function F(o,t,e=""){let r=new Date().toISOString(),a=((new Error().stack||"").split(`
|
|
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),p=a?`${a[1].split("/").pop()}:${a[2]}`:"unknown",u=`[${r}] [HAPPY-PATH-ERROR] [${p}] ${o}`;if(t!==void 0)try{u+=` ${JSON.stringify(t)}`}catch(E){u+=` [stringify error: ${E}]`}u+=`
|
|
`;try{Ot(Ct,u)}catch(E){console.error("[silent-debug] Failed to write to log:",E)}return e}function W(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}import{readFileSync as Lt,existsSync as yt}from"fs";function y(o,t,e=!1){if(!o||!yt(o))return"";try{let r=Lt(o,"utf-8").trim();if(!r)return"";let n=r.split(`
|
|
`);for(let s=n.length-1;s>=0;s--)try{let i=JSON.parse(n[s]);if(i.type===t&&i.message?.content){let a="",p=i.message.content;return typeof p=="string"?a=p:Array.isArray(p)&&(a=p.filter(u=>u.type==="text").map(u=>u.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:o},r)}return""}async function Mt(o){if(await $(),!o)throw new Error("summaryHook requires input");let{session_id:t}=o,e=T(),r=F("Missing transcript_path in Stop hook input",{session_id:t},o.transcript_path||""),n=y(r,"user"),s=y(r,"assistant",!0);c.dataIn("HOOK","Stop: Requesting summary",{workerPort:e,hasLastUserMessage:!!n,hasLastAssistantMessage:!!s});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:s}),signal:AbortSignal.timeout(g.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){W(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(U("Stop",!0))}var M="";K.on("data",o=>M+=o);K.on("end",async()=>{let o=M?JSON.parse(M):void 0;await Mt(o)});
|