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.
10 lines
11 KiB
JavaScript
Executable File
10 lines
11 KiB
JavaScript
Executable File
#!/usr/bin/env bun
|
|
import{stdin as W}from"process";function G(n,t,e){return 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 I(n,t,e={}){let r=G(n,t,e);return JSON.stringify(r)}import{readFileSync as j,writeFileSync as Y,existsSync as J}from"fs";import{join as q}from"path";import{homedir as Q}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 U=V.join(","),P=X.join(",");var _=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:q(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:U,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(!J(t))return this.getAllDefaults();let e=j(t,"utf-8"),r=JSON.parse(e),o=r;if(r.env&&typeof r.env=="object"){o=r.env;try{Y(t,JSON.stringify(o,null,2),"utf-8"),u.info("SETTINGS","Migrated settings file from nested to flat schema",{settingsPath:t})}catch(i){u.warn("SETTINGS","Failed to auto-migrate settings file",{settingsPath:t},i)}}let s={...this.DEFAULTS};for(let i of Object.keys(this.DEFAULTS))o[i]!==void 0&&(s[i]=o[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=_.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 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,s){if(t<this.getLevel())return;let i=new Date().toISOString().replace("T"," ").substring(0,23),c=h[t].padEnd(5),a=e.padEnd(6),p="";o?.correlationId?p=`[${o.correlationId}] `:o?.sessionId&&(p=`[session-${o.sessionId}] `);let f="";s!=null&&(this.getLevel()===0&&typeof s=="object"?f=`
|
|
`+JSON.stringify(s,null,2):f=" "+this.formatData(s));let M="";if(o){let{sessionId:Lt,sdkSessionId:Dt,correlationId:Mt,...y}=o;Object.keys(y).length>0&&(M=` {${Object.entries(y).map(([K,B])=>`${K}=${B}`).join(", ")}}`)}let R=`[${i}] [${c}] [${a}] ${p}${r}${M}${f}`;t===3?console.error(R):console.log(R)}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`})}},u=new A;import x from"path";import{homedir as ft}from"os";import{spawnSync as mt}from"child_process";var g={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,WINDOWS_MULTIPLIER:1.5};function w(n){return process.platform==="win32"?Math.round(n*g.WINDOWS_MULTIPLIER):n}import{existsSync as L,readFileSync as rt,writeFileSync as ot,unlinkSync as nt,mkdirSync as b}from"fs";import{createWriteStream as st}from"fs";import{join as T}from"path";import{spawn as it,spawnSync as at}from"child_process";import{homedir as ct}from"os";import{join as l,dirname as z,basename as Ft}from"path";import{homedir as Z}from"os";import{fileURLToPath as tt}from"url";function et(){return typeof __dirname<"u"?__dirname:z(tt(import.meta.url))}var Vt=et(),E=_.get("CLAUDE_MEM_DATA_DIR"),C=process.env.CLAUDE_CONFIG_DIR||l(Z(),".claude"),Xt=l(E,"archives"),jt=l(E,"logs"),Yt=l(E,"trash"),Jt=l(E,"backups"),qt=l(E,"settings.json"),Qt=l(E,"claude-mem.db"),zt=l(E,"vector-db"),Zt=l(C,"settings.json"),te=l(C,"commands"),ee=l(C,"CLAUDE.md");var S=T(E,"worker.pid"),v=T(E,"logs"),N=T(ct(),".claude","plugins","marketplaces","thedotmack"),ut=5e3,pt=1e4,lt=200,Et=1e3,_t=100,O=class{static async start(t){if(await this.isRunning())return{success:!0,pid:this.getPidInfo()?.pid};b(v,{recursive:!0});let e=T(N,"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 at("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 o=process.platform==="win32",s=it("bun",[t],{detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDE_MEM_WORKER_PORT:String(r)},cwd:N,...o&&{windowsHide:!0}}),i=st(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(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}static async stop(t=ut){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=rt(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(E,{recursive:!0}),ot(S,JSON.stringify(t,null,2))}static removePidFile(){try{L(S)&&nt(S)}catch{}}static isProcessAlive(t){try{return process.kill(t,0),!0}catch{return!1}}static async waitForHealth(t,e,r=pt){let o=Date.now();for(;Date.now()-o<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(Et)})).ok)return{success:!0,pid:t}}catch{}await new Promise(s=>setTimeout(s,lt))}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(o=>setTimeout(o,_t))}throw new Error("Process did not exit within timeout")}static getLogFilePath(){let t=new Date().toISOString().slice(0,10);return T(v,`worker-${t}.log`)}static formatUptime(t){let e=new Date(t).getTime(),o=Date.now()-e,s=Math.floor(o/1e3),i=Math.floor(s/60),c=Math.floor(i/60),a=Math.floor(c/24);return a>0?`${a}d ${c%24}h`:c>0?`${c}h ${i%60}m`:i>0?`${i}m ${s%60}s`:`${s}s`}};var gt=x.join(ft(),".claude","plugins","marketplaces","thedotmack"),St=w(g.HEALTH_CHECK),m=null;function d(){if(m!==null)return m;try{let n=x.join(_.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),t=_.loadFromFile(n);return m=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),m}catch(n){return u.debug("SYSTEM","Failed to load port from settings, using default",{error:n}),m=parseInt(_.get("CLAUDE_MEM_WORKER_PORT"),10),m}}async function k(){try{let n=d();return(await fetch(`http://127.0.0.1:${n}/health`,{signal:AbortSignal.timeout(St)})).ok}catch(n){return u.debug("SYSTEM","Worker health check failed",{error:n instanceof Error?n.message:String(n),errorType:n?.constructor?.name}),!1}}async function Tt(){if(process.platform!=="win32")try{mt("pm2",["delete","claude-mem-worker"],{stdio:"ignore"})}catch{}let n=d(),t=await O.start(n);return t.success||u.error("SYSTEM","Failed to start worker",{platform:process.platform,port:n,error:t.error,marketplaceRoot:gt}),t.success}async function H(){if(await k())return;let n=await Tt();if(!(!n&&await k())&&!n){let t=d();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 dt}from"fs";import{homedir as Ot}from"os";import{join as ht}from"path";var At=ht(Ot(),".claude-mem","silent.log");function $(n,t,e=""){let r=new Date().toISOString(),c=((new Error().stack||"").split(`
|
|
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),a=c?`${c[1].split("/").pop()}:${c[2]}`:"unknown",p=`[${r}] [HAPPY-PATH-ERROR] [${a}] ${n}`;if(t!==void 0)try{p+=` ${JSON.stringify(t)}`}catch(f){p+=` [stringify error: ${f}]`}p+=`
|
|
`;try{dt(At,p)}catch(f){console.error("[silent-debug] Failed to write to log:",f)}return e}function F(n){throw n.cause?.code==="ECONNREFUSED"||n.name==="TimeoutError"||n.message?.includes("fetch failed")?new Error("There's a problem with the worker. Try: npm run worker:restart"):n}async function Ct(n){if(await H(),!n)throw new Error("saveHook requires input");let{session_id:t,cwd:e,tool_name:r,tool_input:o,tool_response:s}=n,i=d(),c=u.formatTool(r,o);u.dataIn("HOOK",`PostToolUse: ${c}`,{workerPort:i});try{let a=await fetch(`http://127.0.0.1:${i}/api/sessions/observations`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({claudeSessionId:t,tool_name:r,tool_input:o,tool_response:s,cwd:$("Missing cwd in PostToolUse hook input",{session_id:t,tool_name:r},e||"")}),signal:AbortSignal.timeout(g.DEFAULT)});if(!a.ok){let p=await a.text();throw u.failure("HOOK","Failed to send observation",{status:a.status},p),new Error(`Failed to send observation to worker: ${a.status} ${p}`)}u.debug("HOOK","Observation sent successfully",{toolName:r})}catch(a){F(a)}console.log(I("PostToolUse",!0))}var D="";W.on("data",n=>D+=n);W.on("end",async()=>{let n=D?JSON.parse(D):void 0;await Ct(n)});
|