claude-mem 13.12.1 → 13.12.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.codex-plugin/plugin.json +1 -1
- package/dist/npx-cli/index.js +284 -284
- package/dist/opencode-plugin/index.js +1 -1
- package/openclaw/install.sh +1 -1
- package/openclaw/openclaw.plugin.json +1 -1
- package/openclaw/test-install.sh +1 -1
- package/openclaw/tsconfig.json +2 -1
- package/package.json +1 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/.codex-plugin/plugin.json +1 -1
- package/plugin/.mcp.json +1 -1
- package/plugin/hooks/hooks.json +1 -1
- package/plugin/package.json +1 -1
- package/plugin/scripts/bun-runner.js +33 -4
- package/plugin/scripts/context-generator.cjs +28 -888
- package/plugin/scripts/mcp-server.cjs +29 -29
- package/plugin/scripts/server-service.cjs +127 -127
- package/plugin/scripts/transcript-watcher.cjs +17 -17
- package/plugin/scripts/worker-service.cjs +1755 -1711
- package/plugin/scripts/worker-wrapper.cjs +1 -1
- package/plugin/skills/version-bump/SKILL.md +1 -1
- package/plugin/sqlite/SessionStore.js +41 -41
- package/plugin/sqlite/observations/files.js +7 -7
- package/plugin/ui/viewer-bundle.js +12 -12
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
-
"use strict";var
|
|
2
|
+
"use strict";var tn=Object.create;var Rt=Object.defineProperty;var rn=Object.getOwnPropertyDescriptor;var nn=Object.getOwnPropertyNames;var on=Object.getPrototypeOf,sn=Object.prototype.hasOwnProperty;var _e=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};var an=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of nn(e))!sn.call(r,o)&&o!==t&&Rt(r,o,{get:()=>e[o],enumerable:!(n=rn(e,o))||n.enumerable});return r};var q=(r,e,t)=>(t=r!=null?tn(on(r)):{},an(e||!r||!r.__esModule?Rt(t,"default",{value:r,enumerable:!0}):t,r));function Xe(r){return(cn??process.stderr.write.bind(process.stderr))(r)}function ee(r){Xe(r)}function At(r,e={}){Se&&Se.length>0&&(Xe(Se.join("")),Se=[]),Xe(r.endsWith(`
|
|
3
3
|
`)?r:`${r}
|
|
4
|
-
`),e.skipExit||process.exit(2)}var
|
|
5
|
-
`);let E=(0,p.readlinkSync)(r);t=(0,
|
|
6
|
-
`,"utf-8"),c;try{c=(0,p.statSync)(t).mode&511}catch{}let
|
|
7
|
-
`)}finally{if(
|
|
8
|
-
${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let t=Object.keys(e);return t.length===0?"{}":t.length<=3?JSON.stringify(e):`{${t.length} keys: ${t.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,t){if(!t)return e;let n=t;if(typeof t=="string")try{n=JSON.parse(t)}catch{n=t}if(e==="Bash"&&n.command)return`${e}(${n.command})`;if(n.file_path)return`${e}(${n.file_path})`;if(n.notebook_path)return`${e}(${n.notebook_path})`;if(e==="Glob"&&n.pattern)return`${e}(${n.pattern})`;if(e==="Grep"&&n.pattern)return`${e}(${n.pattern})`;if(n.url)return`${e}(${n.url})`;if(n.query)return`${e}(${n.query})`;if(e==="Task"){if(n.subagent_type)return`${e}(${n.subagent_type})`;if(n.description)return`${e}(${n.description})`}return e==="Skill"&&n.skill?`${e}(${n.skill})`:e==="LSP"&&n.operation?`${e}(${n.operation})`:e}formatTimestamp(e){let t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0"),i=String(e.getHours()).padStart(2,"0"),s=String(e.getMinutes()).padStart(2,"0"),c=String(e.getSeconds()).padStart(2,"0"),
|
|
4
|
+
`),e.skipExit||process.exit(2)}var cn,Se,he=_e(()=>{"use strict";cn=null;Se=null});function ln(r){return r.replace(/^\uFEFF/,"")}function G(r){return JSON.parse(ln(r))}function dn(r){(0,p.existsSync)(r)||(0,p.mkdirSync)(r,{recursive:!0})}function ze(r,e){let t=r;try{if((0,p.lstatSync)(r).isSymbolicLink())try{t=(0,p.realpathSync)(r)}catch(d){let l=d instanceof Error?d:new Error(String(d));ee(`claude-mem: realpathSync failed for ${r}, resolving symlink manually: ${l.message}
|
|
5
|
+
`);let E=(0,p.readlinkSync)(r);t=(0,I.resolve)((0,I.dirname)(r),E)}}catch(d){let l=d.code;if(l!=="ENOENT"&&l!=="ENOTDIR")throw d}dn((0,I.dirname)(t));let n=(0,I.dirname)(t),o=(0,I.basename)(t),i=(0,I.join)(n,`.${o}.${process.pid}.${(0,kt.randomBytes)(6).toString("hex")}.tmp`),s=Buffer.from(JSON.stringify(e,null,2)+`
|
|
6
|
+
`,"utf-8"),c;try{c=(0,p.statSync)(t).mode&511}catch{}let u;try{u=c!==void 0?(0,p.openSync)(i,"w",c):(0,p.openSync)(i,"w");let d=0;for(;d<s.length;){let l=(0,p.writeSync)(u,s,d,s.length-d);if(l===0)throw new Error(`writeSync stalled at ${d}/${s.length} bytes`);d+=l}if((0,p.fsyncSync)(u),(0,p.closeSync)(u),u=void 0,(0,p.renameSync)(i,t),!un){let l;try{l=(0,p.openSync)(n,"r"),(0,p.fsyncSync)(l)}catch(E){let g=E instanceof Error?E:new Error(String(E));ee(`claude-mem: directory fsync failed for ${n}: ${g.message}
|
|
7
|
+
`)}finally{if(l!==void 0)try{(0,p.closeSync)(l)}catch{}}}}catch(d){if(u!==void 0)try{(0,p.closeSync)(u)}catch{}try{(0,p.unlinkSync)(i)}catch{}throw d}}var p,kt,I,un,ce=_e(()=>{"use strict";p=require("fs"),kt=require("crypto"),I=require("path");he();un=process.platform==="win32"});function pn(){return typeof __dirname<"u"?__dirname:(0,m.dirname)((0,Dt.fileURLToPath)(En.url))}function Ot(r){return typeof r!="string"||r.length===0?r:r==="~"?(0,ue.homedir)():r.startsWith("~/")?(0,m.join)((0,ue.homedir)(),r.slice(2)):r}function te(){if(process.env.CLAUDE_MEM_DATA_DIR)return Ot(process.env.CLAUDE_MEM_DATA_DIR);let r=(0,m.join)((0,ue.homedir)(),".claude-mem"),e=(0,m.join)(r,"settings.json");try{if((0,le.existsSync)(e)){let t=G((0,le.readFileSync)(e,"utf-8")),n=t.env??t;if(n.CLAUDE_MEM_DATA_DIR)return Ot(n.CLAUDE_MEM_DATA_DIR)}}catch{}return r}var m,ue,le,Dt,En,Vo,S,fn,ye,mn,re,qo,Qe,gn,y,w=_e(()=>{"use strict";m=require("path"),ue=require("os"),le=require("fs"),Dt=require("url");ce();En={};Vo=pn();S=te(),fn=process.env.CLAUDE_CONFIG_DIR||(0,m.join)((0,ue.homedir)(),".claude"),ye=(0,m.join)(fn,"plugins","marketplaces","thedotmack"),mn=(0,m.join)(S,"logs"),re=(0,m.join)(S,"settings.json"),qo=(0,m.join)(S,"claude-mem.db"),Qe=(0,m.join)(S,"observer-sessions"),gn=(0,m.basename)(Qe),y={dataDir:()=>S,workerPid:()=>(0,m.join)(S,"worker.pid"),serverPid:()=>(0,m.join)(S,".server-beta.pid"),serverPort:()=>(0,m.join)(S,".server-beta.port"),serverRuntime:()=>(0,m.join)(S,".server-beta.runtime.json"),settings:()=>(0,m.join)(S,"settings.json"),database:()=>(0,m.join)(S,"claude-mem.db"),chroma:()=>(0,m.join)(S,"chroma"),combinedCerts:()=>(0,m.join)(S,"combined_certs.pem"),transcriptsConfig:()=>(0,m.join)(S,"transcript-watch.json"),transcriptsState:()=>(0,m.join)(S,"transcript-watch-state.json"),corpora:()=>(0,m.join)(S,"corpora"),supervisorRegistry:()=>(0,m.join)(S,"supervisor.json"),envFile:()=>(0,m.join)(S,".env"),logsDir:()=>mn}});var U,Pt,tt,et,rt,a,f=_e(()=>{"use strict";U=require("fs"),Pt=require("path");w();he();ce();tt=(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))(tt||{}),et=null,rt=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){if(!this.logFileInitialized){this.logFileInitialized=!0;try{let e=y.logsDir();(0,U.existsSync)(e)||(0,U.mkdirSync)(e,{recursive:!0});let t=new Date().toISOString().split("T")[0];this.logFilePath=(0,Pt.join)(e,`claude-mem-${t}.log`)}catch(e){console.error("[LOGGER] Failed to initialize log file:",e instanceof Error?e.message:String(e)),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let e=y.settings();if((0,U.existsSync)(e)){let t=(0,U.readFileSync)(e,"utf-8"),o=(G(t).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=tt[o]??1}else this.level=1}catch(e){console.error("[LOGGER] Failed to load log level from settings:",e instanceof Error?e.message:String(e)),this.level=1}return this.level}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.getLevel()===0?`${e.message}
|
|
8
|
+
${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let t=Object.keys(e);return t.length===0?"{}":t.length<=3?JSON.stringify(e):`{${t.length} keys: ${t.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,t){if(!t)return e;let n=t;if(typeof t=="string")try{n=JSON.parse(t)}catch{n=t}if(e==="Bash"&&n.command)return`${e}(${n.command})`;if(n.file_path)return`${e}(${n.file_path})`;if(n.notebook_path)return`${e}(${n.notebook_path})`;if(e==="Glob"&&n.pattern)return`${e}(${n.pattern})`;if(e==="Grep"&&n.pattern)return`${e}(${n.pattern})`;if(n.url)return`${e}(${n.url})`;if(n.query)return`${e}(${n.query})`;if(e==="Task"){if(n.subagent_type)return`${e}(${n.subagent_type})`;if(n.description)return`${e}(${n.description})`}return e==="Skill"&&n.skill?`${e}(${n.skill})`:e==="LSP"&&n.operation?`${e}(${n.operation})`:e}formatTimestamp(e){let t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0"),i=String(e.getHours()).padStart(2,"0"),s=String(e.getMinutes()).padStart(2,"0"),c=String(e.getSeconds()).padStart(2,"0"),u=String(e.getMilliseconds()).padStart(3,"0");return`${t}-${n}-${o} ${i}:${s}:${c}.${u}`}log(e,t,n,o,i){if(e<this.getLevel())return;this.ensureLogFileInitialized();let s=this.formatTimestamp(new Date),c=tt[e].padEnd(5),u=t.padEnd(6),d="";o?.correlationId?d=`[${o.correlationId}] `:o?.sessionId&&(d=`[session-${o.sessionId}] `);let l="";if(i!=null)if(i instanceof Error)l=this.getLevel()===0?`
|
|
9
9
|
${i.message}
|
|
10
|
-
${i.stack}`:` ${i.message}`;else if(this.getLevel()===0&&typeof i=="object")try{
|
|
11
|
-
`+JSON.stringify(i,null,2)}catch{
|
|
12
|
-
`,"utf8")}catch(b){let _=b instanceof Error?b:new Error(String(b));
|
|
10
|
+
${i.stack}`:` ${i.message}`;else if(this.getLevel()===0&&typeof i=="object")try{l=`
|
|
11
|
+
`+JSON.stringify(i,null,2)}catch{l=" "+this.formatData(i)}else l=" "+this.formatData(i);let E="";if(o){let{sessionId:b,memorySessionId:_,correlationId:Y,...Ee}=o;Object.keys(Ee).length>0&&(E=` {${Object.entries(Ee).map(([V,en])=>`${V}=${en}`).join(", ")}}`)}let g=`[${s}] [${c}] [${u}] ${d}${n}${E}${l}`;if(this.logFilePath)try{(0,U.appendFileSync)(this.logFilePath,g+`
|
|
12
|
+
`,"utf8")}catch(b){let _=b instanceof Error?b:new Error(String(b));ee(`[LOGGER] Failed to write to log file: ${_.message}
|
|
13
13
|
${_.stack??""}
|
|
14
|
-
`)}else
|
|
15
|
-
`)}debug(e,t,n,o){this.log(0,e,t,n,o)}info(e,t,n,o){this.log(1,e,t,n,o)}warn(e,t,n,o){this.log(2,e,t,n,o)}setErrorSink(e){et=e}error(e,t,n,o){this.log(3,e,t,n,o),this.routeErrorToSink(t,n,o)}routeErrorToSink(e,t,n){try{if(!et||!(n instanceof Error))return;et(n)}catch{}}dataIn(e,t,n,o){this.info(e,`\u2192 ${t}`,n,o)}dataOut(e,t,n,o){this.info(e,`\u2190 ${t}`,n,o)}success(e,t,n,o){this.info(e,`\u2713 ${t}`,n,o)}failure(e,t,n,o){this.error(e,`\u2717 ${t}`,n,o)}},a=new rt});var N=require("fs"),Ze=require("os"),le=require("path");w();var ne=y.transcriptsConfig(),ye=y.transcriptsState(),gn={version:1,schemas:{},watches:[],stateFile:ye};function En(r){let e=typeof r.schema=="string"?r.schema:r.schema?.name;if(!(r.name==="codex"||e==="codex")||!r.path)return!1;let n=v(r.path).replace(/\\/g,"/"),o=(0,le.join)((0,Ze.homedir)(),".codex","sessions").replace(/\\/g,"/");return n===`${o}/**/*.jsonl`}function It(r){let e=typeof r.schema=="string"?r.schema:r.schema?.name,t=r.name==="codex"&&(!e||e==="codex");return r.context?.mode==="agents"&&t&&En(r)}function v(r){return r&&(r.startsWith("~")?(0,le.join)((0,Ze.homedir)(),r.slice(1)):r)}function ue(r=ne){let e=v(r);if(!(0,N.existsSync)(e))throw new Error(`Transcript watch config not found: ${e}`);let t=(0,N.readFileSync)(e,"utf-8"),n=JSON.parse(t);if(!n.version||!n.watches)throw new Error(`Invalid transcript watch config: ${e}`);return n.stateFile||(n.stateFile=ye),n}function Te(r=ne){let e=v(r),t=(0,le.dirname)(e);(0,N.existsSync)(t)||(0,N.mkdirSync)(t,{recursive:!0}),(0,N.writeFileSync)(e,JSON.stringify(gn,null,2))}var M=require("fs"),I=require("path");f();var F=require("fs"),Pt=require("path");f();function Lt(r){try{if(!(0,F.existsSync)(r))return{offsets:{}};let e=(0,F.readFileSync)(r,"utf-8"),t=JSON.parse(e);return t.offsets?t:{offsets:{}}}catch(e){return a.warn("TRANSCRIPT","Failed to load watch state, starting fresh",{statePath:r,error:e instanceof Error?e.message:String(e)}),{offsets:{}}}}function xt(r,e){try{let t=(0,Pt.dirname)(r);(0,F.existsSync)(t)||(0,F.mkdirSync)(t,{recursive:!0}),(0,F.writeFileSync)(r,JSON.stringify(e,null,2))}catch(t){a.warn("TRANSCRIPT","Failed to save watch state",{statePath:r,error:t instanceof Error?t.message:String(t)})}}var fe=V(require("path"),1);var T=V(require("path"),1),h=require("fs");var nt=require("node:child_process");function we(r,e,t){return(0,nt.spawn)(r,e??[],{windowsHide:!0,...t})}var _n=new Set([".cmd",".bat"]),Sn=new Set([".exe",".com"]),os=new Set([...Sn,..._n]);f();var k={HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5},G={SUCCESS:0,BLOCKING_ERROR:2};function K(r){return process.platform==="win32"?Math.round(r*k.WINDOWS_MULTIPLIER):r}var be=require("fs"),ot=require("path"),de=require("os");Se();var C=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_API_TIMEOUT_MS:String(K(k.API_REQUEST)),CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_DATA_DIR:(0,ot.join)((0,de.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",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",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,ot.join)((0,de.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_CLOUD_SYNC_TOKEN:"",CLAUDE_MEM_CLOUD_SYNC_USER_ID:"",CLAUDE_MEM_CLOUD_SYNC_HUB_URL:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_ID:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_NAME:(0,de.hostname)(),CLAUDE_MEM_CLOUD_SYNC_WS:"true",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let t=this.get(e);return parseInt(t,10)}static applyEnvOverrides(e){let t={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(t[n]=process.env[n]);return t}static loadFromFile(e,t=!0){try{if(!(0,be.existsSync)(e)){let c=this.getAllDefaults();try{Xe(e,c),console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(l){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,l instanceof Error?l.message:String(l))}return t?this.applyEnvOverrides(c):c}let n=(0,be.readFileSync)(e,"utf-8"),o=ee(n),i=o;if(o.env&&typeof o.env=="object"){i=o.env;try{Xe(e,i),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(c){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,c instanceof Error?c.message:String(c))}}let s={...this.DEFAULTS};for(let c of Object.keys(this.DEFAULTS))i[c]!==void 0&&(s[c]=i[c]);return t?this.applyEnvOverrides(s):s}catch(n){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,n instanceof Error?n.message:String(n));let o=this.getAllDefaults();return t?this.applyEnvOverrides(o):o}}};w();w();var Me=null;function W(){return Me!==null||(Me=C.loadFromFile(re)),Me}var q=require("fs");f();var lt=require("child_process");var L=require("fs"),at=V(require("path"),1);f();var hn=["CLAUDECODE_","CLAUDE_CODE_"],yn=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),Tn=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy","npm_config_noproxy"]),wn=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS",...Tn]);function ve(r=process.env){let e={};for(let[t,n]of Object.entries(r))if(n!==void 0){if(wn.has(t)){e[t]=n;continue}yn.has(t)||hn.some(o=>t.startsWith(o))||(e[t]=n)}return e}w();var bn=5e3,Mn=1e3,vn=y.supervisorRegistry();function P(r){if(!Number.isInteger(r)||r<0||r===0)return!1;try{return process.kill(r,0),!0}catch(e){if(e instanceof Error){let t=e.code;return t==="EPERM"?!0:(a.debug("SYSTEM","PID check failed",{pid:r,code:t}),!1)}return a.warn("SYSTEM","PID check threw non-Error",{pid:r,error:String(e)}),!1}}async function Ce(r,e){let t=Date.now()+e;for(;Date.now()<t;){if(r.every(n=>!P(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}var Cn=5e3,Nt=new Map;function Rn(r){let e=(0,lt.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${r}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...ve(process.env),LC_ALL:"C",LANG:"C"}});if(e.status===0){let t=e.stdout.trim();return t.length>0?t:null}return null}function An(r){let e=Nt.get(r);if(e&&Date.now()-e.capturedAtMs<Cn)return e.token;let t=null;try{t=Rn(r)}catch(n){a.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:r,error:n instanceof Error?n.message:String(n)}),t=null}return Nt.set(r,{token:t,capturedAtMs:Date.now()}),t}function Ut(r){if(!Number.isInteger(r)||r<=0)return null;if(process.platform==="linux")try{let e=(0,L.readFileSync)(`/proc/${r}/stat`,"utf-8"),t=e.lastIndexOf(") ");if(t<0)return null;let o=e.slice(t+2).split(" ")[19];return o&&/^\d+$/.test(o)?o:null}catch(e){return a.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return An(r);try{let e=(0,lt.spawnSync)("ps",["-p",String(r),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...ve(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let t=e.stdout.trim();return t.length>0?t:null}catch(e){return a.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}}function ut(r){if(!r||!P(r.pid))return!1;if(!r.startToken)return!0;let e=Ut(r.pid);if(e===null)return!0;let t=e===r.startToken;return t||a.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:r.pid,stored:r.startToken,current:e}),t}var ct=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=vn){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,L.mkdirSync)(at.default.dirname(this.registryPath),{recursive:!0}),!(0,L.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,L.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[o,i]of Object.entries(n))this.entries.set(o,i)}catch(t){t instanceof Error?a.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},t):a.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(t)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&a.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,t,n){this.initialize(),this.entries.set(e,t),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let t=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),t?.type==="sdk"&&it()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,t])=>({id:e,...t})).sort((e,t)=>{let n=Date.parse(e.startedAt),o=Date.parse(t.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(o)?0:o)})}getBySession(e){let t=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===t)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,t=0;for(let[n,o]of this.entries)P(o.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,o.type==="sdk"&&(t+=1));e>0&&this.persist();for(let n=0;n<t;n+=1)it();return e}async reapSession(e){this.initialize();let t=this.getBySession(e);if(t.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;a.info("SYSTEM",`Reaping ${t.length} process(es) for session ${e}`,{sessionId:n,pids:t.map(s=>s.pid)});let o=t.filter(s=>P(s.pid));for(let s of o)try{typeof s.pgid=="number"&&process.platform!=="win32"?process.kill(-s.pgid,"SIGTERM"):process.kill(s.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&a.debug("SYSTEM",`Failed to SIGTERM session process PID ${s.pid}`,{pid:s.pid,pgid:s.pgid},c):a.warn("SYSTEM",`Failed to SIGTERM session process PID ${s.pid} (non-Error)`,{pid:s.pid,pgid:s.pgid,error:String(c)})}await Ce(o,bn);let i=o.filter(s=>P(s.pid));for(let s of i){a.warn("SYSTEM",`Session process PID ${s.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:s.pid,pgid:s.pgid,sessionId:n});try{typeof s.pgid=="number"&&process.platform!=="win32"?process.kill(-s.pgid,"SIGKILL"):process.kill(s.pid,"SIGKILL")}catch(c){c instanceof Error?c.code!=="ESRCH"&&a.debug("SYSTEM",`Failed to SIGKILL session process PID ${s.pid}`,{pid:s.pid,pgid:s.pgid},c):a.warn("SYSTEM",`Failed to SIGKILL session process PID ${s.pid} (non-Error)`,{pid:s.pid,pgid:s.pgid,error:String(c)})}}if(i.length>0){let s=Date.now()+Mn;for(;Date.now()<s&&i.filter(l=>P(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let s of t)this.entries.delete(s.id),this.runtimeProcesses.delete(s.id);this.persist();for(let s of t)s.type==="sdk"&&it();return a.info("SYSTEM",`Reaped ${t.length} process(es) for session ${e}`,{sessionId:n,reaped:t.length}),t.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,L.mkdirSync)(at.default.dirname(this.registryPath),{recursive:!0}),(0,L.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},st=null;function Re(){return st||(st=new ct),st}var kn=[];function it(){let r=kn.shift();r&&r()}var Wt=require("child_process"),oe=require("fs"),jt=require("util");f();w();var On=(0,jt.promisify)(Wt.execFile),In=y.workerPid();async function Ht(r){let e=r.currentPid??process.pid,t=r.pidFilePath??In,n=r.registry.getAll(),o=[...n].filter(s=>s.pid!==e).sort((s,c)=>Date.parse(c.startedAt)-Date.parse(s.startedAt));for(let s of o){if(!P(s.pid)){r.registry.unregister(s.id);continue}try{await Ft(s,"SIGTERM")}catch(c){c instanceof Error?a.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:s.pid,pgid:s.pgid,type:s.type},c):a.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:s.pid,pgid:s.pgid,type:s.type,error:String(c)})}}await Ce(o,5e3);let i=o.filter(s=>P(s.pid));for(let s of i)try{await Ft(s,"SIGKILL")}catch(c){c instanceof Error?a.debug("SYSTEM","Failed to force kill child process",{pid:s.pid,pgid:s.pgid,type:s.type},c):a.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:s.pid,pgid:s.pgid,type:s.type,error:String(c)})}await Ce(i,1e3);for(let s of o)r.registry.unregister(s.id);for(let s of n.filter(c=>c.pid===e))r.registry.unregister(s.id);$t(t,e),r.registry.pruneDeadEntries()}function $t(r,e,t=!1){if(!(0,oe.existsSync)(r))return;let n=null;try{let s=JSON.parse((0,oe.readFileSync)(r,"utf-8"));n=typeof s.pid=="number"?s.pid:null}catch(s){a.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:r,error:s instanceof Error?s.message:String(s)});return}let o=e!==null&&n===e,i=n===null||!P(n);if(!o&&!(t&&i)){a.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:r,recordedPid:n,currentPid:e});return}try{(0,oe.rmSync)(r,{force:!0})}catch(s){s instanceof Error?a.debug("SYSTEM","Failed to remove PID file",{pidFilePath:r},s):a.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:r,error:String(s)})}}async function Ft(r,e){let{pid:t,pgid:n}=r;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}try{process.kill(t,e)}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}return}if(e==="SIGTERM"){try{process.kill(t,e)}catch(i){if(i instanceof Error&&i.code==="ESRCH")return;throw i}return}let o=["/PID",String(t),"/T"];e==="SIGKILL"&&o.push("/F"),await On("taskkill",o,{timeout:k.POWERSHELL_COMMAND,windowsHide:!0})}f();var Yt=3e4,se=null;function Dn(){let e=Re().pruneDeadEntries();e>0&&a.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function Gt(){se===null&&(se=setInterval(Dn,Yt),se.unref(),a.debug("SYSTEM","Health checker started",{intervalMs:Yt}))}function Kt(){se!==null&&(clearInterval(se),se=null,a.debug("SYSTEM","Health checker stopped"))}w();var Pn=y.workerPid(),dt=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),Ae({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,Gt()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let t=async n=>{if(this.shutdownInitiated){a.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,a.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(o){o instanceof Error?a.error("SYSTEM","Error during shutdown",{},o):a.error("SYSTEM","Error during shutdown (non-Error)",{error:String(o)});try{await this.stop()}catch(i){i instanceof Error?a.debug("SYSTEM","Supervisor shutdown fallback failed",{},i):a.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(i)})}}process.exit(0)};process.on("SIGTERM",()=>{t("SIGTERM")}),process.on("SIGINT",()=>{t("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{a.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{t("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}Kt(),this.stopPromise=Ht({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,t,n){this.registry.register(e,t,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},Ps=new dt(Re());function Ae(r={}){let e=r.pidFilePath??Pn;if(!(0,q.existsSync)(e))return"missing";let t=null;try{t=JSON.parse((0,q.readFileSync)(e,"utf-8"))}catch(o){return o instanceof Error?a.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},o):a.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(o)}),(0,q.rmSync)(e,{force:!0}),"invalid"}return ut(t)&&t?((r.logAlive??!0)&&a.info("SYSTEM","Worker already running (PID alive)",{existingPid:t.pid,existingPort:t.port,startedAt:t.startedAt}),"alive"):(a.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:t?.pid,port:t?.port,startedAt:t?.startedAt}),(0,q.rmSync)(e,{force:!0}),"stale")}_e();var pt=require("path"),Oe=require("fs"),Jt=require("crypto");w();var ke=require("fs");function Bt(r,e){if(!(0,ke.existsSync)(r))return e;try{return JSON.parse((0,ke.readFileSync)(r,"utf-8"))}catch(t){throw new Error(`Corrupt JSON file, refusing to overwrite: ${r}: ${t instanceof Error?t.message:String(t)}`)}}f();var Vt="telemetry.json";function Ln(r){let e=r.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function xn(r,e){if(Ln(r))return{enabled:!1,source:"DO_NOT_TRACK"};let t=r.CLAUDE_MEM_TELEMETRY?.toLowerCase();return t==="0"||t==="false"||t==="off"?{enabled:!1,source:"env"}:t==="1"||t==="true"||t==="on"?{enabled:!0,source:"env"}:e?.enabled===!0?{enabled:!0,source:"config"}:e?.enabled===!1?{enabled:!1,source:"config"}:{enabled:!0,source:"default"}}function qt(r,e){return xn(r,e).enabled}function Nn(){return(0,pt.join)(te(),Vt)}function ft(){let r;try{r=Bt(Nn(),null)}catch(e){let t=e instanceof Error?e:new Error(String(e));return a.warn("SYSTEM","Telemetry: corrupt telemetry.json; treating as no recorded consent",void 0,t),null}return!r||typeof r!="object"||typeof r.installId!="string"||r.enabled!==void 0&&typeof r.enabled!="boolean"?null:{enabled:r.enabled,installId:r.installId,decidedAt:typeof r.decidedAt=="string"?r.decidedAt:""}}function Un(r){let e=te();(0,Oe.mkdirSync)(e,{recursive:!0}),(0,Oe.writeFileSync)((0,pt.join)(e,Vt),JSON.stringify(r,null,2)+`
|
|
16
|
-
`)}function
|
|
17
|
-
`);return}let o=Zt(),i=new AbortController,s=setTimeout(()=>i.abort(),Kn);try{await Bn(o,r,n,i.signal)}finally{clearTimeout(s)}}catch{}}async function Bn(r,e,t,n){await fetch(`${er()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:r,event:e,distinct_id:Xt(),properties:t}),signal:n})}var X=V(require("path"),1),sr=require("os"),j=require("fs"),Et=require("child_process");f();f();f();w();var ui=y.dataDir(),di=y.workerPid();function or(r){return r?/(^|[\\/])bun(\.exe)?$/i.test(r.trim()):!1}function Vn(r,e){let t=e==="win32"?`where ${r}`:`which ${r}`,n;try{n=(0,Et.execSync)(t,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(i){return i instanceof Error?a.debug("SYSTEM",`Binary lookup failed for ${r}`,{command:t},i):a.debug("SYSTEM",`Binary lookup failed for ${r}`,{command:t},new Error(String(i))),null}return n.split(/\r?\n/).map(i=>i.trim()).find(i=>i.length>0)||null}var gt;function ir(r={}){let e=Object.keys(r).length===0;if(e&>!==void 0)return gt;let t=qn(r);return e&&t!==null&&(gt=t),t}function qn(r){let e=r.platform??process.platform,t=r.execPath??process.execPath;if(or(t))return t;let n=r.env??process.env,o=r.homeDirectory??(0,sr.homedir)(),i=r.pathExists??j.existsSync,s=r.lookupInPath??Vn,c=e==="win32"?[n.BUN,n.BUN_PATH,X.default.join(o,".bun","bin","bun.exe"),X.default.join(o,".bun","bin","bun"),n.USERPROFILE?X.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?X.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?X.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[n.BUN,n.BUN_PATH,X.default.join(o,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun"];for(let l of c){let d=l?.trim();if(d&&(or(d)&&i(d)||d.toLowerCase()==="bun"))return d}return s("bun",e)}f();w();function Xn(){return C.loadFromFile(re).CLAUDE_MEM_WORKER_HOST}function zn(r){return r.startsWith("[")&&r.endsWith("]")?r:r.includes(":")?`[${r}]`:r}async function Qn(r,e,t="GET"){let n=await fetch(`http://${zn(Xn())}:${r}${e}`,{method:t}),o="";try{o=await n.text()}catch{}return{ok:n.ok,statusCode:n.status,body:o}}async function Zn(r){try{let e=await Qn(r,"/api/health");return e.ok?JSON.parse(e.body).version:null}catch{return a.debug("SYSTEM","Could not fetch worker version",{}),null}}async function ar(r,e){let t=e??"unknown",n=await Zn(r);return!n||t==="unknown"?{matches:!0,pluginVersion:t,workerVersion:n}:{matches:t===n,pluginVersion:t,workerVersion:n}}f();var Ie=require("path"),R=require("fs");w();f();var eo=6e4;function cr(){return(0,Ie.join)(te(),"spawn.lock")}function lr(){let r=cr(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let t=0;t<2;t++)try{return(0,R.mkdirSync)((0,Ie.dirname)(r),{recursive:!0}),(0,R.writeFileSync)(r,e,{flag:"wx"}),!0}catch(n){let o=n instanceof Error?n:new Error(String(n)),i=o.code;if(i!=="EEXIST")return a.warn("SYSTEM","Spawn lock write failed for a non-contention reason; failing open (spawning unlocked)",{lockPath:r,code:i},o),!0;if(t>0)return!1;let s;try{s=(0,R.statSync)(r).mtimeMs}catch{continue}if(Date.now()-s<=eo)return!1;let c;try{c=(0,R.statSync)(r).mtimeMs}catch{continue}if(c!==s)return!1;try{(0,R.unlinkSync)(r)}catch{return!1}}return!1}function ur(){let r=cr();try{if(JSON.parse((0,R.readFileSync)(r,"utf-8")).pid!==process.pid)return;(0,R.unlinkSync)(r)}catch{}}function Er(r,e,t){let n=process.env[r];if(n){let o=parseInt(n,10);if(Number.isFinite(o)&&o>=t.min&&o<=t.max)return o;a.warn("SYSTEM",`Invalid ${r}, using default`,{value:n,min:t.min,max:t.max})}return e}var Ue=Er("CLAUDE_MEM_HEALTH_TIMEOUT_MS",K(k.HEALTH_CHECK),{min:500,max:3e5}),_r=Er("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",K(k.HOOK_READINESS_WAIT),{min:0,max:3e5}),to={min:500,max:3e5};async function yt(r,e={},t){try{return await fetch(r,{...e,signal:AbortSignal.timeout(t)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new Error(`Request timed out after ${t}ms`):n}}var De=null,Pe=null,Le=null,xe=null;function ro(){return T.default.join(C.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function Tt(){return Le!==null||(Le=C.loadFromFile(ro())),Le}function dr(r,e){if(!r)return null;let t=parseInt(r,10);return Number.isFinite(t)&&t>=e.min&&t<=e.max?t:null}function no(r,e,t){let n=process.env[r];if(n!==void 0){let s=dr(n,t);return s!==null?s:(a.warn("SYSTEM",`Invalid ${r}, using default`,{value:n,min:t.min,max:t.max}),e)}let o=Tt()[r],i=dr(o,t);return i!==null?i:(a.warn("SYSTEM",`Invalid ${r} in settings.json, using default`,{value:o,min:t.min,max:t.max}),e)}function Sr(){if(De!==null)return De;let r=Tt();return De=parseInt(r.CLAUDE_MEM_WORKER_PORT,10),De}function oo(){return Pe!==null||(Pe=Tt().CLAUDE_MEM_WORKER_HOST),Pe}function so(){return xe!==null||(xe=no("CLAUDE_MEM_API_TIMEOUT_MS",K(k.API_REQUEST),to)),xe}function io(r){return r.startsWith("[")&&r.endsWith("]")?r:r.includes(":")?`[${r}]`:r}function ao(r){return`http://${io(oo())}:${Sr()}${r}`}function H(r,e={}){let t=e.method??"GET",n=e.timeoutMs??so(),o=ao(r),i={method:t};return e.headers&&(i.headers=e.headers),e.body&&(i.body=e.body),n>0?yt(o,i,n):fetch(o,i)}async function co(){return(await H("/api/health",{timeoutMs:Ue})).ok}async function pr(){return(await H("/api/readiness",{timeoutMs:Ue})).ok}function hr(r){let e=(0,h.existsSync)(T.default.join(r,"plugin","scripts"))?T.default.join(r,"plugin"):r;return T.default.join(e,"scripts","worker-service.cjs")}function lo(r,e){let t=E=>{let m=E.split("-")[0].split(".");return[parseInt(m[0],10)||0,parseInt(m[1],10)||0,parseInt(m[2],10)||0]},[n,o,i]=t(r),[s,c,l]=t(e);if(s!==n)return s-n;if(c!==o)return c-o;if(l!==i)return l-i;let d=r.includes("-")?1:0,u=e.includes("-")?1:0;return d!==u?d-u:r<e?1:r>e?-1:0}function uo(r=T.default.join(T.default.dirname(T.default.dirname(he)),"cache","thedotmack","claude-mem")){try{return(0,h.readdirSync)(r).filter(e=>/^\d/.test(e)).map(e=>T.default.join(r,e)).filter(e=>{try{if(!(0,h.statSync)(e).isDirectory())return!1}catch{return!1}return!(0,h.existsSync)(T.default.join(e,".orphaned_at"))}).map(e=>({scriptPath:hr(e),version:T.default.basename(e)}))}catch{return[]}}function fr(r){try{let e=JSON.parse((0,h.readFileSync)(r,"utf-8"));return typeof e.version=="string"?e.version:null}catch(e){let t=e.code;return t!=="ENOENT"&&a.debug("SYSTEM","Could not read package version for worker resolution",{packageJsonPath:r,code:t}),null}}function po(){let r=process.env.CLAUDE_MEM_WORKER_SCRIPT_PATH?.trim();if(r){if((0,h.existsSync)(r))return{scriptPath:r,version:null};a.debug("SYSTEM","Ignoring missing CLAUDE_MEM_WORKER_SCRIPT_PATH override",{override:r})}let e=[...uo(),{scriptPath:hr(T.default.join(he,"plugin")),version:fr(T.default.join(he,"package.json"))},{scriptPath:T.default.join(process.cwd(),"plugin","scripts","worker-service.cjs"),version:fr(T.default.join(process.cwd(),"package.json"))}];return fo(e)}function fo(r){let e=r.filter(t=>(0,h.existsSync)(t.scriptPath));return e.length===0?null:(e.sort((t,n)=>t.version===null&&n.version===null?0:t.version===null?1:n.version===null?-1:lo(t.version,n.version)),e[0])}async function mo(r){let e=r.backoffMs;for(let t=1;t<=r.attempts;t++){if(await Tr())return!0;t<r.attempts&&(await new Promise(n=>setTimeout(n,e)),e*=2)}return!1}async function _t(r=_r){if(r<=0)try{return await pr()}catch(t){let n=t instanceof Error?t:new Error(String(t));return a.debug("SYSTEM","Worker readiness check threw",{},n),!1}let e=Date.now();for(;Date.now()-e<r;){try{if(await pr())return!0}catch(n){a.debug("SYSTEM","Worker readiness check threw",{error:n instanceof Error?n.message:String(n)})}let t=r-(Date.now()-e);if(t<=0)break;await new Promise(n=>setTimeout(n,Math.min(250,t)))}return!1}async function yr(){try{let e=await(await H("/api/health",{timeoutMs:Ue})).json();return typeof e.version=="string"?e.version:null}catch(r){let e=r instanceof Error?r:new Error(String(r));return a.debug("SYSTEM","Worker health-version fetch failed",{},e),null}}async function go(r,e=_r){let t=Date.now();for(;Date.now()-t<e;){if(await yr()===r)return!0;let o=e-(Date.now()-t);if(o<=0)break;await new Promise(i=>setTimeout(i,Math.min(500,o)))}return!1}async function St(r){let e=await yr();e!==null&&e!==r&&a.warn("SYSTEM","Worker is ready but still reports a stale version; not recycling again in this hook invocation (one recycle per hook event)",{pluginVersion:r,workerVersion:e})}async function Tr(){let r;try{r=await co()}catch(t){return a.debug("SYSTEM","Worker health check threw",{error:t instanceof Error?t.message:String(t)}),!1}if(!r)return!1;let e=Ae({logAlive:!1});return e==="missing"||e==="alive"}async function Fe(){let r=po(),e=null;if(await Tr()){let{matches:s,pluginVersion:c,workerVersion:l}=await ar(Sr(),r?.version??null);if(c!=="unknown"&&(e=c),s)return await _t()?(e!==null&&await St(e),!0):(a.warn("SYSTEM","Worker is healthy but not ready; skipping hook API call"),!1);a.info("SYSTEM","Worker version mismatch \u2014 recycling stale worker",{pluginVersion:c,workerVersion:l});let d=!1;try{await H("/api/admin/restart",{method:"POST",timeoutMs:Ue}),d=!0}catch(u){let E=u instanceof Error?u:new Error(String(u));a.debug("SYSTEM","Worker restart request failed; falling through to lazy-spawn",{},E)}if(d){if(await go(c))return await _t()?(e!==null&&await St(e),!0):(a.warn("SYSTEM","Recycled worker appeared but did not become ready; skipping hook API call"),!1);a.warn("SYSTEM","No successor worker appeared after recycle; falling through to lazy-spawn",{pluginVersion:c,workerVersion:l})}}let t=ir(),n=r?.scriptPath??null;if(!t)return a.warn("SYSTEM","Cannot lazy-spawn worker: Bun runtime not found on PATH"),!1;if(!n)return a.warn("SYSTEM","Cannot lazy-spawn worker: worker-service.cjs not found in plugin/scripts"),!1;let o=lr();try{if(o){a.info("SYSTEM","Worker not running \u2014 lazy-spawning",{runtimePath:t,scriptPath:n});try{we(t,[n,"--daemon"],{detached:!0,stdio:["ignore","ignore","ignore"]}).unref()}catch(c){return c instanceof Error?a.error("SYSTEM","Lazy-spawn of worker failed",{runtimePath:t,scriptPath:n},c):a.error("SYSTEM","Lazy-spawn of worker failed (non-Error)",{runtimePath:t,scriptPath:n,error:String(c)}),!1}}else a.info("SYSTEM","Another launcher holds the spawn lock \u2014 skipping lazy-spawn and waiting for its worker");if(!await mo({attempts:6,backoffMs:500}))return a.warn("SYSTEM",o?"Worker port did not open after lazy-spawn within the cold-boot wait (~15s)":"Spawn-lock holder's worker port did not open within the cold-boot wait (~15s)"),!1}finally{o&&ur()}return await _t()?(e!==null&&await St(e),!0):(a.warn("SYSTEM","Worker lazy-spawned but did not become ready before hook readiness timeout"),!1)}var Ne=null;async function Eo(){return Ne!==null||(Ne=await Fe()),Ne}var _o=3;function wr(){return T.default.join(S,"state")}function br(){return T.default.join(wr(),"hook-failures.json")}function So(r){let e=JSON.parse(r);return{consecutiveFailures:typeof e.consecutiveFailures=="number"&&Number.isFinite(e.consecutiveFailures)?Math.max(0,Math.floor(e.consecutiveFailures)):0,lastFailureAt:typeof e.lastFailureAt=="number"&&Number.isFinite(e.lastFailureAt)?e.lastFailureAt:0}}function Mr(){try{return So((0,h.readFileSync)(br(),"utf-8"))}catch{return{consecutiveFailures:0,lastFailureAt:0}}}function vr(r){let e=wr(),t=br(),n=`${t}.tmp`;try{(0,h.existsSync)(e)||(0,h.mkdirSync)(e,{recursive:!0}),(0,h.writeFileSync)(n,JSON.stringify(r),"utf-8"),(0,h.renameSync)(n,t)}catch(o){a.debug("SYSTEM","Failed to persist hook-failure counter",{error:o instanceof Error?o.message:String(o)})}}function ho(){try{let e=W().CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD,t=parseInt(e,10);if(Number.isFinite(t)&&t>=1)return t}catch{}return _o}var mr=null;async function yo(){let e={consecutiveFailures:Mr().consecutiveFailures+1,lastFailureAt:Date.now()};vr(e);let t=ho();return e.consecutiveFailures>=t&&(e.consecutiveFailures===t&&await nr("hook_failed",{...mr!==null?{hook_type:mr}:{},error_mode:"worker_unavailable",consecutive_failures:e.consecutiveFailures,threshold_tripped:!0}),At(`claude-mem worker unreachable for ${e.consecutiveFailures} consecutive hooks.`)),e.consecutiveFailures}function gr(){Mr().consecutiveFailures!==0&&vr({consecutiveFailures:0,lastFailureAt:0})}var ht=Symbol.for("claude-mem/worker-fallback");function We(r){return typeof r=="object"&&r!==null&&r[ht]===!0}async function je(r,e,t,n={}){if(!await Eo())return await yo(),{continue:!0,reason:"worker_unreachable",[ht]:!0};let i={method:e};t!==void 0&&(i.headers={"Content-Type":"application/json"},i.body=JSON.stringify(t)),n.timeoutMs!==void 0&&(i.timeoutMs=n.timeoutMs);let s=await H(r,i);if(!s.ok){let l=await s.text().catch(()=>"");if(gr(),s.status===429||s.status>=500)return a.warn("SYSTEM",`Worker API ${e} ${r} returned ${s.status}; skipping hook API call`,{body:l.substring(0,200)}),{continue:!0,reason:`worker_api_${s.status}`,[ht]:!0};let d=l;try{d=JSON.parse(l)}catch{}return d}gr();let c=await s.text();if(c.length!==0)try{return JSON.parse(c)}catch{return c}}var Rr=require("os"),Ar=V(require("path"),1),kr=require("child_process");f();var He=require("fs"),ie=V(require("path"),1);f();var pe={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function Cr(r){let e=ie.default.join(r,".git"),t;try{t=(0,He.statSync)(e)}catch(u){return u instanceof Error&&u.code!=="ENOENT"&&a.warn("GIT","Unexpected error checking .git",{error:u instanceof Error?u.message:String(u)}),pe}if(!t.isFile())return pe;let n;try{n=(0,He.readFileSync)(e,"utf-8").trim()}catch(u){return a.warn("GIT","Failed to read .git file",{error:u instanceof Error?u.message:String(u)}),pe}let o=n.match(/^gitdir:\s*(.+)$/);if(!o)return pe;let s=ie.default.resolve(ie.default.dirname(e),o[1]).match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!s)return pe;let c=s[1],l=ie.default.basename(r),d=ie.default.basename(c);return{isWorktree:!0,worktreeName:l,parentRepoPath:c,parentProjectName:d}}function Or(r){return r==="~"||r.startsWith("~/")?r.replace(/^~/,(0,Rr.homedir)()):r}function To(r){try{return(0,kr.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:r,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch(e){let t=e instanceof Error?e:new Error(String(e));return a.debug("PROJECT_NAME","git rev-parse failed, falling back to basename",{dir:r},t),null}}function wo(r){if(!r||r.trim()==="")return a.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:r}),"unknown-project";let e=Or(r),n=To(e)??e,o=Ar.default.basename(n);if(o===""){if(process.platform==="win32"){let s=r.match(/^([A-Z]):\\/i);if(s){let l=`drive-${s[1].toUpperCase()}`;return a.info("PROJECT_NAME","Drive root detected",{cwd:r,projectName:l}),l}}return a.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:r}),"unknown-project"}return o}function z(r){let e=wo(r);if(!r)return{primary:e,parent:null,isWorktree:!1,allProjects:[e]};let t=Or(r),n=Cr(t);if(n.isWorktree&&n.parentProjectName){let o=`${n.parentProjectName}/${e}`;return{primary:o,parent:n.parentProjectName,isWorktree:!0,allProjects:[n.parentProjectName,o]}}return{primary:e,parent:null,isWorktree:!1,allProjects:[e]}}f();var Q=require("path");var Ir=require("os"),Dr=require("path");f();function bo(r){let e=r.startsWith("~")?(0,Ir.homedir)()+r.slice(1):r;e=e.replace(/\\/g,"/");let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return t=t.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${t}$`)}function $e(r,e){if(!e||!e.trim())return!1;let t=r.replace(/\\/g,"/"),n=(0,Dr.basename)(t),o=e.split(",").map(i=>i.trim()).filter(Boolean);for(let i of o)try{let s=bo(i);if(s.test(t)||s.test(n))return!0}catch(s){a.warn("PROJECT_NAME","Invalid exclusion pattern",{pattern:i,error:s instanceof Error?s.message:String(s)});continue}return!1}w();function Mo(r,e){let t=(0,Q.normalize)(r),n=(0,Q.normalize)(e);if(t===n)return!0;let o=(0,Q.relative)(n,t);return o.length>0&&!o.startsWith("..")&&!(0,Q.isAbsolute)(o)}function Ye(r){if(process.env.CLAUDE_MEM_INTERNAL==="1")return!1;if(!r)return!0;if(Mo(r,Qe))return!1;let e=W();return!$e(r,e.CLAUDE_MEM_EXCLUDED_PROJECTS)}var Pr="claude";function vo(r){return r.trim().toLowerCase().replace(/\s+/g,"-")}function x(r){if(!r)return Pr;let e=vo(r);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:Pr}f();var Nr=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],Lr=new RegExp(`<(${Nr.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g");var xr=100;function Co(r){let e=Object.fromEntries(Nr.map(o=>[o,0]));Lr.lastIndex=0;let t=0,n=r.replace(Lr,(o,i)=>(e[i]=(e[i]??0)+1,t+=1,""));return t>xr&&a.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:t,maxAllowed:xr,contentLength:r.length}),{stripped:n.trim(),counts:e}}function wt(r){return Co(r).stripped}var Ro=["task-notification"],Ao=new RegExp(`^\\s*<(${Ro.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),ko=256*1024;function Ur(r){return!r||r.length>ko?!1:Ao.test(r)}f();var Oo=K(k.API_REQUEST),$=class extends Error{kind;status;cause;constructor(e,t,n={}){super(t),this.name="ServerClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},Ge=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=Io(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??Oo}async startSession(e){let t=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",t)}async recordEvent(e){let t=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,t)}async endSession(e){if(!e.sessionId)throw new $("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async getJobStatus(e){if(!e)throw new $("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let t=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,type:n,narrative:t,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:bt(e.platformSource)}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:bt(e.platformSource)}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:bt(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,t,n){if(!this.apiKey||!this.apiKey.trim())throw new $("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let o=`${this.baseUrl}${t}`,i={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(i.body=JSON.stringify(n));let s;try{s=await yt(o,i,this.timeoutMs)}catch(l){let d=l instanceof Error?l.message:String(l),u=/timed out|timeout/i.test(d);throw new $(u?"timeout":"transport",`Server ${e} ${t} failed: ${d}`,{cause:l})}if(!s.ok){let l=await s.text().catch(()=>"");throw new $("http_error",`Server ${e} ${t} returned ${s.status}: ${Do(l,200)}`,{status:s.status})}let c=await s.text();if(!c||c.length===0)return{};try{return JSON.parse(c)}catch(l){let d=l instanceof Error?l:new Error(String(l));throw new $("invalid_response",`Server ${e} ${t} returned non-JSON response`,{cause:d})}}};function Fr(r){return r instanceof $}function Io(r){return r.replace(/\/+$/,"")}function bt(r){return typeof r=="string"?x(r):null}function Do(r,e){return r.length<=e?r:`${r.slice(0,e)}\u2026`}function Po(){let e=(W().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function Lo(){let r=W(),e=(...s)=>{for(let c of s){let l=(c??"").trim();if(l.length>0)return l}return""},t=e(r.CLAUDE_MEM_SERVER_URL,r.CLAUDE_MEM_SERVER_BETA_URL),n=e(r.CLAUDE_MEM_SERVER_API_KEY,r.CLAUDE_MEM_SERVER_BETA_API_KEY),o=e(r.CLAUDE_MEM_SERVER_PROJECT_ID,r.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!t)return a.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return a.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return a.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let i={serverBaseUrl:t,apiKey:n};return{runtime:"server",client:new Ge(i),projectId:o,serverBaseUrl:t}}function Wr(){if(Po()!=="server")return{runtime:"worker"};let r=Lo();return r||{runtime:"worker"}}function jr(r,e){a.warn("HOOK",`[server-fallback] reason=${r}`,e??{})}var xo={executeWithWorkerFallback:je,isWorkerFallback:We,loadFromFileOnce:W,resolveRuntimeContext:Wr,logServerFallback:jr,shouldTrackProject:Ye},B=xo;var Hr={async execute(r){let{sessionId:e,prompt:t}=r,n=r.cwd??process.cwd();if(!e)return a.warn("HOOK","session-init: No sessionId provided, skipping (Codex CLI or unknown platform)"),{continue:!0,suppressOutput:!0,exitCode:G.SUCCESS};if(!B.shouldTrackProject(n))return a.info("HOOK","Project excluded from tracking",{cwd:n}),{continue:!0,suppressOutput:!0};if(t&&Ur(t))return a.debug("HOOK","session-init: skipping internal protocol payload",{preview:t.slice(0,80)}),{continue:!0,suppressOutput:!0};let o=!t||!t.trim()?"[media prompt]":t,i=z(n).primary,s=x(r.platform),c=B.loadFromFileOnce(),l=String(c.CLAUDE_MEM_SEMANTIC_INJECT).toLowerCase()==="true",d=B.resolveRuntimeContext();if(d.runtime==="server")try{return await No(d,r,e,s,i,o),{continue:!0,suppressOutput:!0}}catch(_){if(Fr(_)&&_.isFallbackEligible())B.logServerFallback(_.kind,{status:_.status,message:_.message,route:"/v1/sessions/start"});else return a.error("HOOK","Server session-start failed (non-recoverable)",{error:_ instanceof Error?_.message:String(_)}),{continue:!0,suppressOutput:!0,exitCode:G.SUCCESS}}a.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:e,project:i});let u=await B.executeWithWorkerFallback("/api/sessions/init","POST",{contentSessionId:e,project:i,prompt:o,platformSource:s});if(B.isWorkerFallback(u))return{continue:!0,suppressOutput:!0,exitCode:G.SUCCESS};if(typeof u?.sessionDbId!="number")return a.failure("HOOK","Session initialization returned malformed response",{contentSessionId:e,project:i}),{continue:!0,suppressOutput:!0,exitCode:G.SUCCESS};let E=u.sessionDbId,m=u.promptNumber;if(a.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:E,promptNumber:m,skipped:u.skipped,contextInjected:u.contextInjected}),a.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${e} | prompt#=${m} | sessionDbId=${E}`),u.skipped&&u.reason==="private")return a.info("HOOK",`INIT_COMPLETE | sessionDbId=${E} | promptNumber=${m} | skipped=true | reason=private`,{sessionId:E}),{continue:!0,suppressOutput:!0};let b="";if(l&&o&&o.length>=20&&o!=="[media prompt]"){let _=c.CLAUDE_MEM_SEMANTIC_INJECT_LIMIT||"5",Y=await B.executeWithWorkerFallback("/api/context/semantic","POST",{q:o,project:i,limit:_,platformSource:s});!B.isWorkerFallback(Y)&&Y?.context&&(a.debug("HOOK",`Semantic injection: ${Y.count} observations for prompt`,{sessionId:E,count:Y.count}),b=Y.context)}return a.info("HOOK",`INIT_COMPLETE | sessionDbId=${E} | promptNumber=${m} | project=${i}`,{sessionId:E}),b?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:b}}:{continue:!0,suppressOutput:!0}}};async function No(r,e,t,n,o,i){await r.client.startSession({projectId:r.projectId,externalSessionId:t,contentSessionId:t,agentId:e.agentId??null,agentType:e.agentType??null,platformSource:n,metadata:{project:o,prompt:i}}),a.info("HOOK","session-init: server session started",{contentSessionId:t,project:o})}f();var $r={async execute(r){let{sessionId:e,cwd:t,filePath:n,edits:o}=r,i=x(r.platform);if(!n)throw new Error("fileEditHandler requires filePath");if(a.dataIn("HOOK",`FileEdit: ${n}`,{editCount:o?.length??0}),!t)throw new Error(`Missing cwd in FileEdit hook input for session ${e}, file ${n}`);if(!Ye(t))return a.debug("HOOK","Project excluded from tracking, skipping file edit observation",{cwd:t,filePath:n}),{continue:!0,suppressOutput:!0,exitCode:G.SUCCESS};let s=await je("/api/sessions/observations","POST",{contentSessionId:e,platformSource:i,tool_name:"write_file",tool_input:{filePath:n,edits:o},tool_response:{success:!0},cwd:t});return We(s)?{continue:!0,suppressOutput:!0,exitCode:G.SUCCESS}:(a.debug("HOOK","File edit observation sent successfully",{filePath:n}),{continue:!0,suppressOutput:!0})}};w();f();var O=require("fs"),Ke=require("path");f();f();w();var ja=y.settings();function Yr(r,e){let t="<claude-mem-context>",n="</claude-mem-context>";if(!r)return`${t}
|
|
14
|
+
`)}else ee(g+`
|
|
15
|
+
`)}debug(e,t,n,o){this.log(0,e,t,n,o)}info(e,t,n,o){this.log(1,e,t,n,o)}warn(e,t,n,o){this.log(2,e,t,n,o)}setErrorSink(e){et=e}error(e,t,n,o){this.log(3,e,t,n,o),this.routeErrorToSink(t,n,o)}routeErrorToSink(e,t,n){try{if(!et||!(n instanceof Error))return;et(n)}catch{}}dataIn(e,t,n,o){this.info(e,`\u2192 ${t}`,n,o)}dataOut(e,t,n,o){this.info(e,`\u2190 ${t}`,n,o)}success(e,t,n,o){this.info(e,`\u2713 ${t}`,n,o)}failure(e,t,n,o){this.error(e,`\u2717 ${t}`,n,o)}},a=new rt});var N=require("fs"),Ze=require("os"),de=require("path");w();var ne=y.transcriptsConfig(),Te=y.transcriptsState(),_n={version:1,schemas:{},watches:[],stateFile:Te};function Sn(r){let e=typeof r.schema=="string"?r.schema:r.schema?.name;if(!(r.name==="codex"||e==="codex")||!r.path)return!1;let n=v(r.path).replace(/\\/g,"/"),o=(0,de.join)((0,Ze.homedir)(),".codex","sessions").replace(/\\/g,"/");return n===`${o}/**/*.jsonl`}function It(r){let e=typeof r.schema=="string"?r.schema:r.schema?.name,t=r.name==="codex"&&(!e||e==="codex");return r.context?.mode==="agents"&&t&&Sn(r)}function v(r){return r&&(r.startsWith("~")?(0,de.join)((0,Ze.homedir)(),r.slice(1)):r)}function pe(r=ne){let e=v(r);if(!(0,N.existsSync)(e))throw new Error(`Transcript watch config not found: ${e}`);let t=(0,N.readFileSync)(e,"utf-8"),n=JSON.parse(t);if(!n.version||!n.watches)throw new Error(`Invalid transcript watch config: ${e}`);return n.stateFile||(n.stateFile=Te),n}function we(r=ne){let e=v(r),t=(0,de.dirname)(e);(0,N.existsSync)(t)||(0,N.mkdirSync)(t,{recursive:!0}),(0,N.writeFileSync)(e,JSON.stringify(_n,null,2))}var M=require("fs"),D=require("path");f();var F=require("fs"),Lt=require("path");f();function xt(r){try{if(!(0,F.existsSync)(r))return{offsets:{}};let e=(0,F.readFileSync)(r,"utf-8"),t=JSON.parse(e);return t.offsets?t:{offsets:{}}}catch(e){return a.warn("TRANSCRIPT","Failed to load watch state, starting fresh",{statePath:r,error:e instanceof Error?e.message:String(e)}),{offsets:{}}}}function Nt(r,e){try{let t=(0,Lt.dirname)(r);(0,F.existsSync)(t)||(0,F.mkdirSync)(t,{recursive:!0}),(0,F.writeFileSync)(r,JSON.stringify(e,null,2))}catch(t){a.warn("TRANSCRIPT","Failed to save watch state",{statePath:r,error:t instanceof Error?t.message:String(t)})}}var ge=q(require("path"),1);var T=q(require("path"),1),h=require("fs");var nt=require("node:child_process");function be(r,e,t){return(0,nt.spawn)(r,e??[],{windowsHide:!0,...t})}var hn=new Set([".cmd",".bat"]),yn=new Set([".exe",".com"]),ss=new Set([...yn,...hn]);f();var k={HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5},K={SUCCESS:0,BLOCKING_ERROR:2};function B(r){return process.platform==="win32"?Math.round(r*k.WINDOWS_MULTIPLIER):r}var Me=require("fs"),ot=require("path"),fe=require("os");ce();var C=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_API_TIMEOUT_MS:String(B(k.API_REQUEST)),CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-flash-latest",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_DATA_DIR:(0,ot.join)((0,fe.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",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",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,ot.join)((0,fe.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_CLOUD_SYNC_TOKEN:"",CLAUDE_MEM_CLOUD_SYNC_USER_ID:"",CLAUDE_MEM_CLOUD_SYNC_HUB_URL:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_ID:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_NAME:(0,fe.hostname)(),CLAUDE_MEM_CLOUD_SYNC_WS:"true",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let t=this.get(e);return parseInt(t,10)}static applyEnvOverrides(e){let t={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(t[n]=process.env[n]);return t}static loadFromFile(e,t=!0){try{if(!(0,Me.existsSync)(e)){let c=this.getAllDefaults();try{ze(e,c),console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(u){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,u instanceof Error?u.message:String(u))}return t?this.applyEnvOverrides(c):c}let n=(0,Me.readFileSync)(e,"utf-8"),o=G(n),i=o;if(o.env&&typeof o.env=="object"){i=o.env;try{ze(e,i),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(c){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,c instanceof Error?c.message:String(c))}}let s={...this.DEFAULTS};for(let c of Object.keys(this.DEFAULTS))i[c]!==void 0&&(s[c]=i[c]);return t?this.applyEnvOverrides(s):s}catch(n){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,n instanceof Error?n.message:String(n));let o=this.getAllDefaults();return t?this.applyEnvOverrides(o):o}}};w();w();var ve=null;function W(){return ve!==null||(ve=C.loadFromFile(re)),ve}var X=require("fs");f();var ut=require("child_process");var L=require("fs"),at=q(require("path"),1);f();var Tn=["CLAUDECODE_","CLAUDE_CODE_"],wn=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),bn=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy","npm_config_noproxy"]),Mn=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS",...bn]);function Ce(r=process.env){let e={};for(let[t,n]of Object.entries(r))if(n!==void 0){if(Mn.has(t)){e[t]=n;continue}wn.has(t)||Tn.some(o=>t.startsWith(o))||(e[t]=n)}return e}w();var vn=5e3,Cn=1e3,Rn=y.supervisorRegistry();function P(r){if(!Number.isInteger(r)||r<0||r===0)return!1;try{return process.kill(r,0),!0}catch(e){if(e instanceof Error){let t=e.code;return t==="EPERM"?!0:(a.debug("SYSTEM","PID check failed",{pid:r,code:t}),!1)}return a.warn("SYSTEM","PID check threw non-Error",{pid:r,error:String(e)}),!1}}async function Re(r,e){let t=Date.now()+e;for(;Date.now()<t;){if(r.every(n=>!P(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}var An=5e3,Ut=new Map;function kn(r){let e=(0,ut.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${r}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Ce(process.env),LC_ALL:"C",LANG:"C"}});if(e.status===0){let t=e.stdout.trim();return t.length>0?t:null}return null}function On(r){let e=Ut.get(r);if(e&&Date.now()-e.capturedAtMs<An)return e.token;let t=null;try{t=kn(r)}catch(n){a.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:r,error:n instanceof Error?n.message:String(n)}),t=null}return Ut.set(r,{token:t,capturedAtMs:Date.now()}),t}function Ft(r){if(!Number.isInteger(r)||r<=0)return null;if(process.platform==="linux")try{let e=(0,L.readFileSync)(`/proc/${r}/stat`,"utf-8"),t=e.lastIndexOf(") ");if(t<0)return null;let o=e.slice(t+2).split(" ")[19];return o&&/^\d+$/.test(o)?o:null}catch(e){return a.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return On(r);try{let e=(0,ut.spawnSync)("ps",["-p",String(r),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Ce(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let t=e.stdout.trim();return t.length>0?t:null}catch(e){return a.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}}function lt(r){if(!r||!P(r.pid))return!1;if(!r.startToken)return!0;let e=Ft(r.pid);if(e===null)return!0;let t=e===r.startToken;return t||a.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:r.pid,stored:r.startToken,current:e}),t}var ct=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=Rn){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,L.mkdirSync)(at.default.dirname(this.registryPath),{recursive:!0}),!(0,L.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,L.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[o,i]of Object.entries(n))this.entries.set(o,i)}catch(t){t instanceof Error?a.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},t):a.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(t)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&a.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,t,n){this.initialize(),this.entries.set(e,t),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let t=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),t?.type==="sdk"&&it()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,t])=>({id:e,...t})).sort((e,t)=>{let n=Date.parse(e.startedAt),o=Date.parse(t.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(o)?0:o)})}getBySession(e){let t=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===t)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,t=0;for(let[n,o]of this.entries)P(o.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,o.type==="sdk"&&(t+=1));e>0&&this.persist();for(let n=0;n<t;n+=1)it();return e}async reapSession(e){this.initialize();let t=this.getBySession(e);if(t.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;a.info("SYSTEM",`Reaping ${t.length} process(es) for session ${e}`,{sessionId:n,pids:t.map(s=>s.pid)});let o=t.filter(s=>P(s.pid));for(let s of o)try{typeof s.pgid=="number"&&process.platform!=="win32"?process.kill(-s.pgid,"SIGTERM"):process.kill(s.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&a.debug("SYSTEM",`Failed to SIGTERM session process PID ${s.pid}`,{pid:s.pid,pgid:s.pgid},c):a.warn("SYSTEM",`Failed to SIGTERM session process PID ${s.pid} (non-Error)`,{pid:s.pid,pgid:s.pgid,error:String(c)})}await Re(o,vn);let i=o.filter(s=>P(s.pid));for(let s of i){a.warn("SYSTEM",`Session process PID ${s.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:s.pid,pgid:s.pgid,sessionId:n});try{typeof s.pgid=="number"&&process.platform!=="win32"?process.kill(-s.pgid,"SIGKILL"):process.kill(s.pid,"SIGKILL")}catch(c){c instanceof Error?c.code!=="ESRCH"&&a.debug("SYSTEM",`Failed to SIGKILL session process PID ${s.pid}`,{pid:s.pid,pgid:s.pgid},c):a.warn("SYSTEM",`Failed to SIGKILL session process PID ${s.pid} (non-Error)`,{pid:s.pid,pgid:s.pgid,error:String(c)})}}if(i.length>0){let s=Date.now()+Cn;for(;Date.now()<s&&i.filter(u=>P(u.pid)).length!==0;)await new Promise(u=>setTimeout(u,100))}for(let s of t)this.entries.delete(s.id),this.runtimeProcesses.delete(s.id);this.persist();for(let s of t)s.type==="sdk"&&it();return a.info("SYSTEM",`Reaped ${t.length} process(es) for session ${e}`,{sessionId:n,reaped:t.length}),t.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,L.mkdirSync)(at.default.dirname(this.registryPath),{recursive:!0}),(0,L.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},st=null;function Ae(){return st||(st=new ct),st}var Dn=[];function it(){let r=Dn.shift();r&&r()}var Ht=require("child_process"),oe=require("fs"),jt=require("util");f();w();var In=(0,jt.promisify)(Ht.execFile),Pn=y.workerPid();async function $t(r){let e=r.currentPid??process.pid,t=r.pidFilePath??Pn,n=r.registry.getAll(),o=[...n].filter(s=>s.pid!==e).sort((s,c)=>Date.parse(c.startedAt)-Date.parse(s.startedAt));for(let s of o){if(!P(s.pid)){r.registry.unregister(s.id);continue}try{await Wt(s,"SIGTERM")}catch(c){c instanceof Error?a.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:s.pid,pgid:s.pgid,type:s.type},c):a.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:s.pid,pgid:s.pgid,type:s.type,error:String(c)})}}await Re(o,5e3);let i=o.filter(s=>P(s.pid));for(let s of i)try{await Wt(s,"SIGKILL")}catch(c){c instanceof Error?a.debug("SYSTEM","Failed to force kill child process",{pid:s.pid,pgid:s.pgid,type:s.type},c):a.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:s.pid,pgid:s.pgid,type:s.type,error:String(c)})}await Re(i,1e3);for(let s of o)r.registry.unregister(s.id);for(let s of n.filter(c=>c.pid===e))r.registry.unregister(s.id);Yt(t,e),r.registry.pruneDeadEntries()}function Yt(r,e,t=!1){if(!(0,oe.existsSync)(r))return;let n=null;try{let s=JSON.parse((0,oe.readFileSync)(r,"utf-8"));n=typeof s.pid=="number"?s.pid:null}catch(s){a.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:r,error:s instanceof Error?s.message:String(s)});return}let o=e!==null&&n===e,i=n===null||!P(n);if(!o&&!(t&&i)){a.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:r,recordedPid:n,currentPid:e});return}try{(0,oe.rmSync)(r,{force:!0})}catch(s){s instanceof Error?a.debug("SYSTEM","Failed to remove PID file",{pidFilePath:r},s):a.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:r,error:String(s)})}}async function Wt(r,e){let{pid:t,pgid:n}=r;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}try{process.kill(t,e)}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}return}if(e==="SIGTERM"){try{process.kill(t,e)}catch(i){if(i instanceof Error&&i.code==="ESRCH")return;throw i}return}let o=["/PID",String(t),"/T"];e==="SIGKILL"&&o.push("/F"),await In("taskkill",o,{timeout:k.POWERSHELL_COMMAND,windowsHide:!0})}f();var Gt=3e4,se=null;function Ln(){let e=Ae().pruneDeadEntries();e>0&&a.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function Kt(){se===null&&(se=setInterval(Ln,Gt),se.unref(),a.debug("SYSTEM","Health checker started",{intervalMs:Gt}))}function Bt(){se!==null&&(clearInterval(se),se=null,a.debug("SYSTEM","Health checker stopped"))}w();var xn=y.workerPid(),dt=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),ke({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,Kt()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let t=async n=>{if(this.shutdownInitiated){a.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,a.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(o){o instanceof Error?a.error("SYSTEM","Error during shutdown",{},o):a.error("SYSTEM","Error during shutdown (non-Error)",{error:String(o)});try{await this.stop()}catch(i){i instanceof Error?a.debug("SYSTEM","Supervisor shutdown fallback failed",{},i):a.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(i)})}}process.exit(0)};process.on("SIGTERM",()=>{t("SIGTERM")}),process.on("SIGINT",()=>{t("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{a.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{t("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}Bt(),this.stopPromise=$t({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,t,n){this.registry.register(e,t,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},Ls=new dt(Ae());function ke(r={}){let e=r.pidFilePath??xn;if(!(0,X.existsSync)(e))return"missing";let t=null;try{t=JSON.parse((0,X.readFileSync)(e,"utf-8"))}catch(o){return o instanceof Error?a.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},o):a.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(o)}),(0,X.rmSync)(e,{force:!0}),"invalid"}return lt(t)&&t?((r.logAlive??!0)&&a.info("SYSTEM","Worker already running (PID alive)",{existingPid:t.pid,existingPort:t.port,startedAt:t.startedAt}),"alive"):(a.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:t?.pid,port:t?.port,startedAt:t?.startedAt}),(0,X.rmSync)(e,{force:!0}),"stale")}he();var pt=require("path"),De=require("fs"),Vt=require("crypto");w();var Oe=require("fs");ce();function Jt(r,e){if(!(0,Oe.existsSync)(r))return e;try{return G((0,Oe.readFileSync)(r,"utf-8"))}catch(t){throw new Error(`Corrupt JSON file, refusing to overwrite: ${r}: ${t instanceof Error?t.message:String(t)}`)}}f();var qt="telemetry.json";function Nn(r){let e=r.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function Un(r,e){if(Nn(r))return{enabled:!1,source:"DO_NOT_TRACK"};let t=r.CLAUDE_MEM_TELEMETRY?.toLowerCase();return t==="0"||t==="false"||t==="off"?{enabled:!1,source:"env"}:t==="1"||t==="true"||t==="on"?{enabled:!0,source:"env"}:e?.enabled===!0?{enabled:!0,source:"config"}:e?.enabled===!1?{enabled:!1,source:"config"}:{enabled:!0,source:"default"}}function Xt(r,e){return Un(r,e).enabled}function Fn(){return(0,pt.join)(te(),qt)}function ft(){let r;try{r=Jt(Fn(),null)}catch(e){let t=e instanceof Error?e:new Error(String(e));return a.warn("SYSTEM","Telemetry: corrupt telemetry.json; treating as no recorded consent",void 0,t),null}return!r||typeof r!="object"||typeof r.installId!="string"||r.enabled!==void 0&&typeof r.enabled!="boolean"?null:{enabled:r.enabled,installId:r.installId,decidedAt:typeof r.decidedAt=="string"?r.decidedAt:""}}function Wn(r){let e=te();(0,De.mkdirSync)(e,{recursive:!0}),(0,De.writeFileSync)((0,pt.join)(e,qt),JSON.stringify(r,null,2)+`
|
|
16
|
+
`)}function zt(){let r=ft();if(r?.installId)return r.installId;let e=(0,Vt.randomUUID)();return Wn({installId:e,decidedAt:""}),e}var Hn=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","install_method","interactive","bun_version","uv_version","claude_code_version","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_invalid_output","top_model","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","observations_created","total_observations_injected","total_tokens_saved_vs_naive"]),Qt=200;function jn(r,e){if(!(!r||typeof r!="object"))for(let t of Object.keys(r)){if(!Hn.has(t))continue;let n=r[t];typeof n=="string"?e[t]=n.length>Qt?n.slice(0,Qt):n:(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(e[t]=n)}}function Zt(r){let e={};try{jn(r,e)}catch{}return e}var mt=q(require("os"),1);f();var $n="13.12.2",Yn="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",Gn="https://us.i.posthog.com";function er(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||Yn}function tr(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||Gn}var Kn=["version","os","os_version","is_wsl","arch","runtime","locale","ide","provider","runtime_mode","install_method","claude_code_version","first_active_date","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs"];function rr(r){let e={};for(let t of Kn)r[t]!==void 0&&(e[t]=r[t]);return e}function Bn(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||mt.default.release().toLowerCase().includes("microsoft")}catch(r){let e=r instanceof Error?r:new Error(String(r));return a.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function nr(){return{version:$n,os:process.platform,os_version:mt.default.release(),is_wsl:Bn(),arch:process.arch,runtime:process.versions.bun?"bun":"node",runtime_version:process.versions.bun??process.versions.node,node_version:process.versions.node,is_ci:!!process.env.CI,locale:Intl.DateTimeFormat().resolvedOptions().locale}}var Jn=2e3;async function or(r,e,t){try{if(!Xt(process.env,ft()))return;let n=Zt({...nr(),...e??{}});if(t?.person?n.$set=rr(n):n.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:r,properties:n})+`
|
|
17
|
+
`);return}let o=er(),i=new AbortController,s=setTimeout(()=>i.abort(),Jn);try{await Vn(o,r,n,i.signal)}finally{clearTimeout(s)}}catch{}}async function Vn(r,e,t,n){await fetch(`${tr()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:r,event:e,distinct_id:zt(),properties:t}),signal:n})}var z=q(require("path"),1),ir=require("os"),H=require("fs"),Et=require("child_process");f();f();f();w();var pi=y.dataDir(),fi=y.workerPid();function sr(r){return r?/(^|[\\/])bun(\.exe)?$/i.test(r.trim()):!1}function Xn(r,e){let t=e==="win32"?`where ${r}`:`which ${r}`,n;try{n=(0,Et.execSync)(t,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(i){return i instanceof Error?a.debug("SYSTEM",`Binary lookup failed for ${r}`,{command:t},i):a.debug("SYSTEM",`Binary lookup failed for ${r}`,{command:t},new Error(String(i))),null}return n.split(/\r?\n/).map(i=>i.trim()).find(i=>i.length>0)||null}var gt;function ar(r={}){let e=Object.keys(r).length===0;if(e&>!==void 0)return gt;let t=zn(r);return e&&t!==null&&(gt=t),t}function zn(r){let e=r.platform??process.platform,t=r.execPath??process.execPath;if(sr(t))return t;let n=r.env??process.env,o=r.homeDirectory??(0,ir.homedir)(),i=r.pathExists??H.existsSync,s=r.lookupInPath??Xn,c=e==="win32"?[n.BUN,n.BUN_PATH,z.default.join(o,".bun","bin","bun.exe"),z.default.join(o,".bun","bin","bun"),n.USERPROFILE?z.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?z.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?z.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[n.BUN,n.BUN_PATH,z.default.join(o,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun"];for(let u of c){let d=u?.trim();if(d&&(sr(d)&&i(d)||d.toLowerCase()==="bun"))return d}return s("bun",e)}f();w();function Qn(){return C.loadFromFile(re).CLAUDE_MEM_WORKER_HOST}function Zn(r){return r.startsWith("[")&&r.endsWith("]")?r:r.includes(":")?`[${r}]`:r}async function eo(r,e,t="GET"){let n=await fetch(`http://${Zn(Qn())}:${r}${e}`,{method:t}),o="";try{o=await n.text()}catch{}return{ok:n.ok,statusCode:n.status,body:o}}async function to(r){try{let e=await eo(r,"/api/health");return e.ok?JSON.parse(e.body).version:null}catch{return a.debug("SYSTEM","Could not fetch worker version",{}),null}}async function cr(r,e){let t=e??"unknown",n=await to(r);return!n||t==="unknown"?{matches:!0,pluginVersion:t,workerVersion:n}:{matches:t===n,pluginVersion:t,workerVersion:n}}f();var Ie=require("path"),R=require("fs");w();f();var ro=9e4;function ur(){return(0,Ie.join)(te(),"spawn.lock")}function lr(){let r=ur(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let t=0;t<2;t++)try{return(0,R.mkdirSync)((0,Ie.dirname)(r),{recursive:!0}),(0,R.writeFileSync)(r,e,{flag:"wx"}),!0}catch(n){let o=n instanceof Error?n:new Error(String(n)),i=o.code;if(i!=="EEXIST")return a.warn("SYSTEM","Spawn lock write failed for a non-contention reason; failing open (spawning unlocked)",{lockPath:r,code:i},o),!0;if(t>0)return!1;let s;try{s=(0,R.statSync)(r).mtimeMs}catch{continue}if(Date.now()-s<=ro)return!1;let c;try{c=(0,R.statSync)(r).mtimeMs}catch{continue}if(c!==s)return!1;try{(0,R.unlinkSync)(r)}catch{return!1}}return!1}function dr(){let r=ur();try{if(JSON.parse((0,R.readFileSync)(r,"utf-8")).pid!==process.pid)return;(0,R.unlinkSync)(r)}catch{}}function _r(r,e,t){let n=process.env[r];if(n){let o=parseInt(n,10);if(Number.isFinite(o)&&o>=t.min&&o<=t.max)return o;a.warn("SYSTEM",`Invalid ${r}, using default`,{value:n,min:t.min,max:t.max})}return e}var Fe=_r("CLAUDE_MEM_HEALTH_TIMEOUT_MS",B(k.HEALTH_CHECK),{min:500,max:3e5}),Sr=_r("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",B(k.HOOK_READINESS_WAIT),{min:0,max:3e5}),no={min:500,max:3e5};async function yt(r,e={},t){try{return await fetch(r,{...e,signal:AbortSignal.timeout(t)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new Error(`Request timed out after ${t}ms`):n}}var Pe=null,Le=null,xe=null,Ne=null;function oo(){return T.default.join(C.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function Tt(){return xe!==null||(xe=C.loadFromFile(oo())),xe}function pr(r,e){if(!r)return null;let t=parseInt(r,10);return Number.isFinite(t)&&t>=e.min&&t<=e.max?t:null}function so(r,e,t){let n=process.env[r];if(n!==void 0){let s=pr(n,t);return s!==null?s:(a.warn("SYSTEM",`Invalid ${r}, using default`,{value:n,min:t.min,max:t.max}),e)}let o=Tt()[r],i=pr(o,t);return i!==null?i:(a.warn("SYSTEM",`Invalid ${r} in settings.json, using default`,{value:o,min:t.min,max:t.max}),e)}function hr(){if(Pe!==null)return Pe;let r=Tt();return Pe=parseInt(r.CLAUDE_MEM_WORKER_PORT,10),Pe}function io(){return Le!==null||(Le=Tt().CLAUDE_MEM_WORKER_HOST),Le}function ao(){return Ne!==null||(Ne=so("CLAUDE_MEM_API_TIMEOUT_MS",B(k.API_REQUEST),no)),Ne}function co(r){return r.startsWith("[")&&r.endsWith("]")?r:r.includes(":")?`[${r}]`:r}function uo(r){return`http://${co(io())}:${hr()}${r}`}function j(r,e={}){let t=e.method??"GET",n=e.timeoutMs??ao(),o=uo(r),i={method:t};return e.headers&&(i.headers=e.headers),e.body&&(i.body=e.body),n>0?yt(o,i,n):fetch(o,i)}async function lo(){return(await j("/api/health",{timeoutMs:Fe})).ok}async function fr(){return(await j("/api/readiness",{timeoutMs:Fe})).ok}function yr(r){let e=(0,h.existsSync)(T.default.join(r,"plugin","scripts"))?T.default.join(r,"plugin"):r;return T.default.join(e,"scripts","worker-service.cjs")}function po(r,e){let t=E=>{let g=E.split("-")[0].split(".");return[parseInt(g[0],10)||0,parseInt(g[1],10)||0,parseInt(g[2],10)||0]},[n,o,i]=t(r),[s,c,u]=t(e);if(s!==n)return s-n;if(c!==o)return c-o;if(u!==i)return u-i;let d=r.includes("-")?1:0,l=e.includes("-")?1:0;return d!==l?d-l:r<e?1:r>e?-1:0}function fo(r=T.default.join(T.default.dirname(T.default.dirname(ye)),"cache","thedotmack","claude-mem")){try{return(0,h.readdirSync)(r).filter(e=>/^\d/.test(e)).map(e=>T.default.join(r,e)).filter(e=>{try{if(!(0,h.statSync)(e).isDirectory())return!1}catch{return!1}return!(0,h.existsSync)(T.default.join(e,".orphaned_at"))}).map(e=>({scriptPath:yr(e),version:T.default.basename(e)}))}catch{return[]}}function mr(r){try{let e=JSON.parse((0,h.readFileSync)(r,"utf-8"));return typeof e.version=="string"?e.version:null}catch(e){let t=e.code;return t!=="ENOENT"&&a.debug("SYSTEM","Could not read package version for worker resolution",{packageJsonPath:r,code:t}),null}}function mo(){let r=process.env.CLAUDE_MEM_WORKER_SCRIPT_PATH?.trim();if(r){if((0,h.existsSync)(r))return{scriptPath:r,version:null};a.debug("SYSTEM","Ignoring missing CLAUDE_MEM_WORKER_SCRIPT_PATH override",{override:r})}let e=[...fo(),{scriptPath:yr(T.default.join(ye,"plugin")),version:mr(T.default.join(ye,"package.json"))},{scriptPath:T.default.join(process.cwd(),"plugin","scripts","worker-service.cjs"),version:mr(T.default.join(process.cwd(),"package.json"))}];return go(e)}function go(r){let e=r.filter(t=>(0,h.existsSync)(t.scriptPath));return e.length===0?null:(e.sort((t,n)=>t.version===null&&n.version===null?0:t.version===null?1:n.version===null?-1:po(t.version,n.version)),e[0])}async function Eo(r){let e=r.backoffMs;for(let t=1;t<=r.attempts;t++){if(await wr())return!0;t<r.attempts&&(await new Promise(n=>setTimeout(n,e)),e*=2)}return!1}async function _t(r=Sr){if(r<=0)try{return await fr()}catch(t){let n=t instanceof Error?t:new Error(String(t));return a.debug("SYSTEM","Worker readiness check threw",{},n),!1}let e=Date.now();for(;Date.now()-e<r;){try{if(await fr())return!0}catch(n){a.debug("SYSTEM","Worker readiness check threw",{error:n instanceof Error?n.message:String(n)})}let t=r-(Date.now()-e);if(t<=0)break;await new Promise(n=>setTimeout(n,Math.min(250,t)))}return!1}async function Tr(){try{let e=await(await j("/api/health",{timeoutMs:Fe})).json();return typeof e.version=="string"?e.version:null}catch(r){let e=r instanceof Error?r:new Error(String(r));return a.debug("SYSTEM","Worker health-version fetch failed",{},e),null}}async function _o(r,e=Sr){let t=Date.now();for(;Date.now()-t<e;){if(await Tr()===r)return!0;let o=e-(Date.now()-t);if(o<=0)break;await new Promise(i=>setTimeout(i,Math.min(500,o)))}return!1}async function St(r){let e=await Tr();e!==null&&e!==r&&a.warn("SYSTEM","Worker is ready but still reports a stale version; not recycling again in this hook invocation (one recycle per hook event)",{pluginVersion:r,workerVersion:e})}async function wr(){let r;try{r=await lo()}catch(t){return a.debug("SYSTEM","Worker health check threw",{error:t instanceof Error?t.message:String(t)}),!1}if(!r)return!1;let e=ke({logAlive:!1});return e==="missing"||e==="alive"}async function We(){let r=mo(),e=null;if(await wr()){let{matches:s,pluginVersion:c,workerVersion:u}=await cr(hr(),r?.version??null);if(c!=="unknown"&&(e=c),s)return await _t()?(e!==null&&await St(e),!0):(a.warn("SYSTEM","Worker is healthy but not ready; skipping hook API call"),!1);a.info("SYSTEM","Worker version mismatch \u2014 recycling stale worker",{pluginVersion:c,workerVersion:u});let d=!1;try{await j("/api/admin/restart",{method:"POST",timeoutMs:Fe}),d=!0}catch(l){let E=l instanceof Error?l:new Error(String(l));a.debug("SYSTEM","Worker restart request failed; falling through to lazy-spawn",{},E)}if(d){if(await _o(c))return await _t()?(e!==null&&await St(e),!0):(a.warn("SYSTEM","Recycled worker appeared but did not become ready; skipping hook API call"),!1);a.warn("SYSTEM","No successor worker appeared after recycle; falling through to lazy-spawn",{pluginVersion:c,workerVersion:u})}}let t=ar(),n=r?.scriptPath??null;if(!t)return a.warn("SYSTEM","Cannot lazy-spawn worker: Bun runtime not found on PATH"),!1;if(!n)return a.warn("SYSTEM","Cannot lazy-spawn worker: worker-service.cjs not found in plugin/scripts"),!1;let o=lr();try{if(o){a.info("SYSTEM","Worker not running \u2014 lazy-spawning",{runtimePath:t,scriptPath:n});try{be(t,[n,"--daemon"],{detached:!0,stdio:["ignore","ignore","ignore"]}).unref()}catch(c){return c instanceof Error?a.error("SYSTEM","Lazy-spawn of worker failed",{runtimePath:t,scriptPath:n},c):a.error("SYSTEM","Lazy-spawn of worker failed (non-Error)",{runtimePath:t,scriptPath:n,error:String(c)}),!1}}else a.info("SYSTEM","Another launcher holds the spawn lock \u2014 skipping lazy-spawn and waiting for its worker");if(!await Eo({attempts:6,backoffMs:500}))return a.warn("SYSTEM",o?"Worker port did not open after lazy-spawn within the cold-boot wait (~15s)":"Spawn-lock holder's worker port did not open within the cold-boot wait (~15s)"),!1}finally{o&&dr()}return await _t()?(e!==null&&await St(e),!0):(a.warn("SYSTEM","Worker lazy-spawned but did not become ready before hook readiness timeout"),!1)}var Ue=null;async function So(){return Ue!==null||(Ue=await We()),Ue}var ho=3;function br(){return T.default.join(S,"state")}function Mr(){return T.default.join(br(),"hook-failures.json")}function yo(r){let e=JSON.parse(r);return{consecutiveFailures:typeof e.consecutiveFailures=="number"&&Number.isFinite(e.consecutiveFailures)?Math.max(0,Math.floor(e.consecutiveFailures)):0,lastFailureAt:typeof e.lastFailureAt=="number"&&Number.isFinite(e.lastFailureAt)?e.lastFailureAt:0}}function vr(){try{return yo((0,h.readFileSync)(Mr(),"utf-8"))}catch{return{consecutiveFailures:0,lastFailureAt:0}}}function Cr(r){let e=br(),t=Mr(),n=`${t}.tmp`;try{(0,h.existsSync)(e)||(0,h.mkdirSync)(e,{recursive:!0}),(0,h.writeFileSync)(n,JSON.stringify(r),"utf-8"),(0,h.renameSync)(n,t)}catch(o){a.debug("SYSTEM","Failed to persist hook-failure counter",{error:o instanceof Error?o.message:String(o)})}}function To(){try{let e=W().CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD,t=parseInt(e,10);if(Number.isFinite(t)&&t>=1)return t}catch{}return ho}var gr=null;async function wo(){let e={consecutiveFailures:vr().consecutiveFailures+1,lastFailureAt:Date.now()};Cr(e);let t=To();return e.consecutiveFailures>=t&&(e.consecutiveFailures===t&&await or("hook_failed",{...gr!==null?{hook_type:gr}:{},error_mode:"worker_unavailable",consecutive_failures:e.consecutiveFailures,threshold_tripped:!0}),At(`claude-mem worker unreachable for ${e.consecutiveFailures} consecutive hooks.`)),e.consecutiveFailures}function Er(){vr().consecutiveFailures!==0&&Cr({consecutiveFailures:0,lastFailureAt:0})}var ht=Symbol.for("claude-mem/worker-fallback");function He(r){return typeof r=="object"&&r!==null&&r[ht]===!0}async function je(r,e,t,n={}){if(!await So())return await wo(),{continue:!0,reason:"worker_unreachable",[ht]:!0};let i={method:e};t!==void 0&&(i.headers={"Content-Type":"application/json"},i.body=JSON.stringify(t)),n.timeoutMs!==void 0&&(i.timeoutMs=n.timeoutMs);let s=await j(r,i);if(!s.ok){let u=await s.text().catch(()=>"");if(Er(),s.status===429||s.status>=500)return a.warn("SYSTEM",`Worker API ${e} ${r} returned ${s.status}; skipping hook API call`,{body:u.substring(0,200)}),{continue:!0,reason:`worker_api_${s.status}`,[ht]:!0};let d=u;try{d=JSON.parse(u)}catch{}return d}Er();let c=await s.text();if(c.length!==0)try{return JSON.parse(c)}catch{return c}}var Ar=require("os"),kr=q(require("path"),1),Or=require("child_process");f();var $e=require("fs"),ie=q(require("path"),1);f();var me={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function Rr(r){let e=ie.default.join(r,".git"),t;try{t=(0,$e.statSync)(e)}catch(l){return l instanceof Error&&l.code!=="ENOENT"&&a.warn("GIT","Unexpected error checking .git",{error:l instanceof Error?l.message:String(l)}),me}if(!t.isFile())return me;let n;try{n=(0,$e.readFileSync)(e,"utf-8").trim()}catch(l){return a.warn("GIT","Failed to read .git file",{error:l instanceof Error?l.message:String(l)}),me}let o=n.match(/^gitdir:\s*(.+)$/);if(!o)return me;let s=ie.default.resolve(ie.default.dirname(e),o[1]).match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!s)return me;let c=s[1],u=ie.default.basename(r),d=ie.default.basename(c);return{isWorktree:!0,worktreeName:u,parentRepoPath:c,parentProjectName:d}}function Dr(r){return r==="~"||r.startsWith("~/")?r.replace(/^~/,(0,Ar.homedir)()):r}function Ir(r){try{return(0,Or.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:r,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim()||null}catch(e){let t=e instanceof Error?e:new Error(String(e));return a.debug("PROJECT_NAME","git rev-parse failed, falling back to basename",{dir:r},t),null}}function bo(r){if(!r||r.trim()==="")return a.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:r}),"unknown-project";let e=Dr(r),n=Ir(e)??e,o=kr.default.basename(n);if(o===""){if(process.platform==="win32"){let s=r.match(/^([A-Z]):\\/i);if(s){let u=`drive-${s[1].toUpperCase()}`;return a.info("PROJECT_NAME","Drive root detected",{cwd:r,projectName:u}),u}}return a.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:r}),"unknown-project"}return o}function Q(r){let e=bo(r);if(!r)return{primary:e,parent:null,isWorktree:!1,allProjects:[e]};let t=Dr(r),n=Rr(Ir(t)??t);if(n.isWorktree&&n.parentProjectName){let o=`${n.parentProjectName}/${e}`;return{primary:o,parent:n.parentProjectName,isWorktree:!0,allProjects:[n.parentProjectName,o]}}return{primary:e,parent:null,isWorktree:!1,allProjects:[e]}}f();var Z=require("path");var Pr=require("os"),Lr=require("path");f();function Mo(r){let e=r.startsWith("~")?(0,Pr.homedir)()+r.slice(1):r;e=e.replace(/\\/g,"/");let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return t=t.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${t}$`)}function Ye(r,e){if(!e||!e.trim())return!1;let t=r.replace(/\\/g,"/"),n=(0,Lr.basename)(t),o=e.split(",").map(i=>i.trim()).filter(Boolean);for(let i of o)try{let s=Mo(i);if(s.test(t)||s.test(n))return!0}catch(s){a.warn("PROJECT_NAME","Invalid exclusion pattern",{pattern:i,error:s instanceof Error?s.message:String(s)});continue}return!1}w();function vo(r,e){let t=(0,Z.normalize)(r),n=(0,Z.normalize)(e);if(t===n)return!0;let o=(0,Z.relative)(n,t);return o.length>0&&!o.startsWith("..")&&!(0,Z.isAbsolute)(o)}function Ge(r){if(process.env.CLAUDE_MEM_INTERNAL==="1")return!1;if(!r)return!0;if(vo(r,Qe))return!1;let e=W();return!Ye(r,e.CLAUDE_MEM_EXCLUDED_PROJECTS)}var xr="claude";function Co(r){return r.trim().toLowerCase().replace(/\s+/g,"-")}function x(r){if(!r)return xr;let e=Co(r);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:xr}f();var Fr=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],Nr=new RegExp(`<(${Fr.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g");var Ur=100;function Ro(r){let e=Object.fromEntries(Fr.map(o=>[o,0]));Nr.lastIndex=0;let t=0,n=r.replace(Nr,(o,i)=>(e[i]=(e[i]??0)+1,t+=1,""));return t>Ur&&a.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:t,maxAllowed:Ur,contentLength:r.length}),{stripped:n.trim(),counts:e}}function wt(r){return Ro(r).stripped}var Ao=["task-notification"],ko=new RegExp(`^\\s*<(${Ao.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),Oo=256*1024;function Wr(r){return!r||r.length>Oo?!1:ko.test(r)}f();var Do=B(k.API_REQUEST),$=class extends Error{kind;status;cause;constructor(e,t,n={}){super(t),this.name="ServerClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},Ke=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=Io(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??Do}async startSession(e){let t=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",t)}async recordEvent(e){let t=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,t)}async endSession(e){if(!e.sessionId)throw new $("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async getJobStatus(e){if(!e)throw new $("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let t=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,type:n,narrative:t,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:bt(e.platformSource)}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:bt(e.platformSource)}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:bt(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,t,n){if(!this.apiKey||!this.apiKey.trim())throw new $("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let o=`${this.baseUrl}${t}`,i={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(i.body=JSON.stringify(n));let s;try{s=await yt(o,i,this.timeoutMs)}catch(u){let d=u instanceof Error?u.message:String(u),l=/timed out|timeout/i.test(d);throw new $(l?"timeout":"transport",`Server ${e} ${t} failed: ${d}`,{cause:u})}if(!s.ok){let u=await s.text().catch(()=>"");throw new $("http_error",`Server ${e} ${t} returned ${s.status}: ${Po(u,200)}`,{status:s.status})}let c=await s.text();if(!c||c.length===0)return{};try{return JSON.parse(c)}catch(u){let d=u instanceof Error?u:new Error(String(u));throw new $("invalid_response",`Server ${e} ${t} returned non-JSON response`,{cause:d})}}};function Hr(r){return r instanceof $}function Io(r){return r.replace(/\/+$/,"")}function bt(r){return typeof r=="string"?x(r):null}function Po(r,e){return r.length<=e?r:`${r.slice(0,e)}\u2026`}function Lo(){let e=(W().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function xo(){let r=W(),e=(...s)=>{for(let c of s){let u=(c??"").trim();if(u.length>0)return u}return""},t=e(r.CLAUDE_MEM_SERVER_URL,r.CLAUDE_MEM_SERVER_BETA_URL),n=e(r.CLAUDE_MEM_SERVER_API_KEY,r.CLAUDE_MEM_SERVER_BETA_API_KEY),o=e(r.CLAUDE_MEM_SERVER_PROJECT_ID,r.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!t)return a.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return a.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return a.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let i={serverBaseUrl:t,apiKey:n};return{runtime:"server",client:new Ke(i),projectId:o,serverBaseUrl:t}}function jr(){if(Lo()!=="server")return{runtime:"worker"};let r=xo();return r||{runtime:"worker"}}function $r(r,e){a.warn("HOOK",`[server-fallback] reason=${r}`,e??{})}var No={executeWithWorkerFallback:je,isWorkerFallback:He,loadFromFileOnce:W,resolveRuntimeContext:jr,logServerFallback:$r,shouldTrackProject:Ge},J=No;var Yr={async execute(r){let{sessionId:e,prompt:t}=r,n=r.cwd??process.cwd();if(!e)return a.warn("HOOK","session-init: No sessionId provided, skipping (Codex CLI or unknown platform)"),{continue:!0,suppressOutput:!0,exitCode:K.SUCCESS};if(!J.shouldTrackProject(n))return a.info("HOOK","Project excluded from tracking",{cwd:n}),{continue:!0,suppressOutput:!0};if(t&&Wr(t))return a.debug("HOOK","session-init: skipping internal protocol payload",{preview:t.slice(0,80)}),{continue:!0,suppressOutput:!0};let o=!t||!t.trim()?"[media prompt]":t,i=Q(n).primary,s=x(r.platform),c=J.loadFromFileOnce(),u=String(c.CLAUDE_MEM_SEMANTIC_INJECT).toLowerCase()==="true",d=J.resolveRuntimeContext();if(d.runtime==="server")try{return await Uo(d,r,e,s,i,o),{continue:!0,suppressOutput:!0}}catch(_){if(Hr(_)&&_.isFallbackEligible())J.logServerFallback(_.kind,{status:_.status,message:_.message,route:"/v1/sessions/start"});else return a.error("HOOK","Server session-start failed (non-recoverable)",{error:_ instanceof Error?_.message:String(_)}),{continue:!0,suppressOutput:!0,exitCode:K.SUCCESS}}a.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:e,project:i});let l=await J.executeWithWorkerFallback("/api/sessions/init","POST",{contentSessionId:e,project:i,prompt:o,platformSource:s});if(J.isWorkerFallback(l))return{continue:!0,suppressOutput:!0,exitCode:K.SUCCESS};if(typeof l?.sessionDbId!="number")return a.failure("HOOK","Session initialization returned malformed response",{contentSessionId:e,project:i}),{continue:!0,suppressOutput:!0,exitCode:K.SUCCESS};let E=l.sessionDbId,g=l.promptNumber;if(a.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:E,promptNumber:g,skipped:l.skipped,contextInjected:l.contextInjected}),a.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${e} | prompt#=${g} | sessionDbId=${E}`),l.skipped&&l.reason==="private")return a.info("HOOK",`INIT_COMPLETE | sessionDbId=${E} | promptNumber=${g} | skipped=true | reason=private`,{sessionId:E}),{continue:!0,suppressOutput:!0};let b="";if(u&&o&&o.length>=20&&o!=="[media prompt]"){let _=c.CLAUDE_MEM_SEMANTIC_INJECT_LIMIT||"5",Y=await J.executeWithWorkerFallback("/api/context/semantic","POST",{q:o,project:i,limit:_,platformSource:s});!J.isWorkerFallback(Y)&&Y?.context&&(a.debug("HOOK",`Semantic injection: ${Y.count} observations for prompt`,{sessionId:E,count:Y.count}),b=Y.context)}return a.info("HOOK",`INIT_COMPLETE | sessionDbId=${E} | promptNumber=${g} | project=${i}`,{sessionId:E}),b?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:b}}:{continue:!0,suppressOutput:!0}}};async function Uo(r,e,t,n,o,i){await r.client.startSession({projectId:r.projectId,externalSessionId:t,contentSessionId:t,agentId:e.agentId??null,agentType:e.agentType??null,platformSource:n,metadata:{project:o,prompt:i}}),a.info("HOOK","session-init: server session started",{contentSessionId:t,project:o})}f();var Gr={async execute(r){let{sessionId:e,cwd:t,filePath:n,edits:o}=r,i=x(r.platform);if(!n)throw new Error("fileEditHandler requires filePath");if(a.dataIn("HOOK",`FileEdit: ${n}`,{editCount:o?.length??0}),!t)throw new Error(`Missing cwd in FileEdit hook input for session ${e}, file ${n}`);if(!Ge(t))return a.debug("HOOK","Project excluded from tracking, skipping file edit observation",{cwd:t,filePath:n}),{continue:!0,suppressOutput:!0,exitCode:K.SUCCESS};let s=await je("/api/sessions/observations","POST",{contentSessionId:e,platformSource:i,tool_name:"write_file",tool_input:{filePath:n,edits:o},tool_response:{success:!0},cwd:t});return He(s)?{continue:!0,suppressOutput:!0,exitCode:K.SUCCESS}:(a.debug("HOOK","File edit observation sent successfully",{filePath:n}),{continue:!0,suppressOutput:!0})}};w();f();var O=require("fs"),Be=require("path");f();f();w();var $a=y.settings();function Kr(r,e){let t="<claude-mem-context>",n="</claude-mem-context>";if(!r)return`${t}
|
|
18
18
|
${e}
|
|
19
19
|
${n}`;let o=r.indexOf(t),i=r.indexOf(n);return o!==-1&&i!==-1?r.substring(0,o)+`${t}
|
|
20
20
|
${e}
|
|
@@ -22,8 +22,8 @@ ${n}`+r.substring(i+n.length):r+`
|
|
|
22
22
|
|
|
23
23
|
${t}
|
|
24
24
|
${e}
|
|
25
|
-
${n}`}f();function
|
|
25
|
+
${n}`}f();function Br(r,e){if(!r)return;let t=(0,Be.resolve)(r);if(t.includes("/.git/")||t.includes("\\.git\\")||t.endsWith("/.git")||t.endsWith("\\.git"))return;let n=(0,Be.dirname)(r);(0,O.existsSync)(n)||(0,O.mkdirSync)(n,{recursive:!0});let o="";(0,O.existsSync)(r)&&(o=(0,O.readFileSync)(r,"utf-8"));let i=`# Memory Context
|
|
26
26
|
|
|
27
|
-
${e}`,s=
|
|
28
|
-
`);for(let o of n){let i=o.trim();if(i.startsWith("*** Update File: "))t.push(i.replace("*** Update File: ","").trim());else if(i.startsWith("*** Add File: "))t.push(i.replace("*** Add File: ","").trim());else if(i.startsWith("*** Delete File: "))t.push(i.replace("*** Delete File: ","").trim());else if(i.startsWith("*** Move to: "))t.push(i.replace("*** Move to: ","").trim());else if(i.startsWith("+++ ")){let s=i.replace("+++ ","").replace(/^b\//,"").trim();s&&s!=="/dev/null"&&t.push(s)}}return Array.from(new Set(t))}async handleSessionEnd(e,t){await this.queueSummary(e),await this.updateContext(e,t),e.pendingTools?.clear();let n=this.getSessionKey(t,e.sessionId);this.sessions.delete(n)}async queueSummary(e){if(!await
|
|
29
|
-
`);this.tailState.partial=i.pop()??"";for(let s of i){let c=s.trim();c&&await this.onLine(c)}}},
|
|
27
|
+
${e}`,s=Kr(o,i),c=`${r}.tmp`;try{(0,O.writeFileSync)(c,s),(0,O.renameSync)(c,r)}catch(u){a.error("AGENTS_MD","Failed to write AGENTS.md",{agentsPath:r},u instanceof Error?u:new Error(String(u)))}}f();function Fo(r){let e=r.trim().replace(/^\$\.?/,"");if(!e)return[];let t=[],n=e.split(".");for(let o of n){let i=/([^[\]]+)|\[(\d+)\]/g,s;for(;(s=i.exec(o))!==null;)s[1]?t.push(s[1]):s[2]&&t.push(parseInt(s[2],10))}return t}function Mt(r,e){if(!e)return;let t=Fo(e),n=r;for(let o of t){if(n==null)return;n=n[o]}return n}function Jr(r){return r==null||r===""}function Vr(r,e){if(r.startsWith("$watch.")){let t=r.slice(7);return e.watch[t]}if(r.startsWith("$schema.")){let t=r.slice(8);return e.schema[t]}if(r.startsWith("$session.")){let t=r.slice(9);return e.session?e.session[t]:void 0}if(r==="$cwd")return e.watch.workspace;if(r==="$project")return e.watch.project}function ae(r,e,t){if(r!==void 0){if(typeof r=="string"){let n=Vr(r,t);return n!==void 0?n:Mt(e,r)}if(r.coalesce&&Array.isArray(r.coalesce))for(let n of r.coalesce){let o=ae(n,e,t);if(!Jr(o))return o}if(r.path){let n=Vr(r.path,t);if(n!==void 0)return n;let o=Mt(e,r.path);if(!Jr(o))return o}if(r.value!==void 0)return r.value;if(r.default!==void 0)return r.default}}function qr(r,e,t){let n={};if(!r)return n;for(let[o,i]of Object.entries(r))n[o]=ae(i,e,t);return n}function Xr(r,e,t){if(!e)return!0;let n=e.path||t.eventTypePath||"type",o=n?Mt(r,n):void 0,i=o==null||o==="";if(e.exists!==void 0&&(e.exists&&i||!e.exists&&!i)||e.equals!==void 0&&o!==e.equals||e.not_equals!==void 0&&o===e.not_equals||e.in&&Array.isArray(e.in)&&!e.in.includes(o)||e.not_in&&Array.isArray(e.not_in)&&e.not_in.includes(o)||e.contains!==void 0&&(typeof o!="string"||!o.includes(e.contains))||e.not_contains!==void 0&&typeof o=="string"&&o.includes(e.not_contains))return!1;if(e.regex)try{if(!new RegExp(e.regex).test(String(o??"")))return!1}catch(s){return a.debug("WORKER","Invalid regex in match rule",{regex:e.regex},s instanceof Error?s:void 0),!1}return!0}f();w();f();var Je=class{static checkUserPromptPrivacy(e,t,n,o,i,s){let c=e.getUserPrompt(t,n,i);return c===null?(a.warn("HOOK",`${o}: no user_prompts row for prompt #${n} \u2014 ingesting anyway (session-init likely raced worker boot; see #2794/#2795)`,{sessionId:i,contentSessionId:t,promptNumber:n,...s}),{allow:!0,prompt:""}):c.trim()===""?(a.debug("HOOK",`Skipping ${o} - user prompt was entirely private`,{sessionId:i,promptNumber:n,...s}),{allow:!1,reason:"private"}):{allow:!0,prompt:c}}};var zr=null;function Wo(){if(!zr)throw new Error("ingest helpers used before setIngestContext() \u2014 wiring bug");return zr}async function Qr(r){let{sessionManager:e,dbManager:t,eventBroadcaster:n,ensureGeneratorRunning:o}=Wo(),i=x(r.platformSource),s=typeof r.cwd=="string"?r.cwd:"",c=s.trim()?Q(s).primary:"",u=C.loadFromFile(re);if(s&&Ye(s,u.CLAUDE_MEM_EXCLUDED_PROJECTS))return{ok:!0,status:"skipped",reason:"project_excluded"};if(new Set(u.CLAUDE_MEM_SKIP_TOOLS.split(",").map(A=>A.trim()).filter(Boolean)).has(r.toolName))return{ok:!0,status:"skipped",reason:"tool_excluded"};if(new Set(["Edit","Write","Read","NotebookEdit"]).has(r.toolName)&&r.toolInput&&typeof r.toolInput=="object"){let A=r.toolInput,V=A.file_path||A.notebook_path;if(V&&V.includes("session-memory"))return{ok:!0,status:"skipped",reason:"session_memory_meta"}}let E=t.getSessionStore(),g,b;try{g=E.createSDKSession(r.contentSessionId,c,"",void 0,i),b=E.getPromptNumberFromUserPrompts(r.contentSessionId,g)}catch(A){let V=A instanceof Error?A.message:String(A);return a.error("INGEST","Observation session resolution failed",{contentSessionId:r.contentSessionId,toolName:r.toolName},A instanceof Error?A:new Error(V)),{ok:!1,reason:V,status:500}}if(!Je.checkUserPromptPrivacy(E,r.contentSessionId,b,"observation",g,{tool_name:r.toolName}).allow)return{ok:!0,status:"skipped",reason:"private"};let Y=r.toolInput!==void 0?wt(JSON.stringify(r.toolInput)):"{}",Ee=r.toolResponse!==void 0?wt(JSON.stringify(r.toolResponse)):"{}";return await e.queueObservation(g,{tool_name:r.toolName,tool_input:Y,tool_response:Ee,prompt_number:b,cwd:s||(a.error("INGEST","Missing cwd when ingesting observation",{sessionId:g,toolName:r.toolName}),""),agentId:typeof r.agentId=="string"?r.agentId:void 0,agentType:typeof r.agentType=="string"?r.agentType:void 0,toolUseId:typeof r.toolUseId=="string"?r.toolUseId:void 0}),await o?.(g,"observation"),n.broadcastObservationQueued(g),{ok:!0,sessionDbId:g}}var Ve=class{sessions=new Map;async processEntry(e,t,n,o){for(let i of n.events)Xr(e,i.match,n)&&await this.handleEvent(e,t,n,i,o??void 0)}getSessionKey(e,t){return`${e.name}:${t}`}getOrCreateSession(e,t){let n=this.getSessionKey(e,t),o=this.sessions.get(n);return o||(o={sessionId:t,platformSource:x(e.name)},this.sessions.set(n,o)),o}resolveSessionId(e,t,n,o,i){let s={watch:t,schema:n},c=o.fields?.sessionId??(n.sessionIdPath?{path:n.sessionIdPath}:void 0),u=ae(c,e,s);return typeof u=="string"&&u.trim()?u:typeof u=="number"?String(u):i&&i.trim()?i:null}resolveCwd(e,t,n,o,i){let s={watch:t,schema:n,session:i},c=o.fields?.cwd??(n.cwdPath?{path:n.cwdPath}:void 0),u=ae(c,e,s);return typeof u=="string"&&u.trim()?u:t.workspace?t.workspace:i.cwd}resolveProject(e,t,n,o,i){let s={watch:t,schema:n,session:i},c=o.fields?.project??(n.projectPath?{path:n.projectPath}:void 0),u=ae(c,e,s);return typeof u=="string"&&u.trim()?u:t.project?t.project:i.cwd?Q(i.cwd).primary:i.project}async handleEvent(e,t,n,o,i){let s=this.resolveSessionId(e,t,n,o,i);if(!s){a.debug("TRANSCRIPT","Skipping event without sessionId",{event:o.name,watch:t.name});return}let c=this.getOrCreateSession(t,s),u=this.resolveCwd(e,t,n,o,c);u&&(c.cwd=u);let d=this.resolveProject(e,t,n,o,c);d&&(c.project=d);let l=qr(o.fields,e,{watch:t,schema:n,session:c});switch(o.action){case"session_context":this.applySessionContext(c,l);break;case"session_init":await this.handleSessionInit(c,l),t.context?.updateOn?.includes("session_start")&&await this.updateContext(c,t);break;case"user_message":typeof l.message=="string"&&(c.lastUserMessage=l.message),typeof l.prompt=="string"&&(c.lastUserMessage=l.prompt);break;case"assistant_message":typeof l.message=="string"&&(c.lastAssistantMessage=l.message);break;case"tool_use":await this.handleToolUse(c,l);break;case"tool_result":await this.handleToolResult(c,l);break;case"observation":await this.sendObservation(c,l);break;case"file_edit":await this.sendFileEdit(c,l);break;case"session_end":await this.handleSessionEnd(c,t);break;default:break}}applySessionContext(e,t){let n=typeof t.cwd=="string"?t.cwd:void 0,o=typeof t.project=="string"?t.project:void 0;n&&(e.cwd=n),o&&(e.project=o)}async handleSessionInit(e,t){let n=typeof t.prompt=="string"?t.prompt:"",o=e.cwd??process.cwd();n&&(e.lastUserMessage=n),await Yr.execute({sessionId:e.sessionId,cwd:o,prompt:n,platform:e.platformSource})}async handleToolUse(e,t){let n=typeof t.toolId=="string"?t.toolId:void 0,o=typeof t.toolName=="string"?t.toolName:void 0,i=this.maybeParseJson(t.toolInput),s=this.maybeParseJson(t.toolResponse);if(o==="apply_patch"&&typeof i=="string"){let c=this.parseApplyPatchFiles(i);for(let u of c)await this.sendFileEdit(e,{filePath:u,edits:[{type:"apply_patch",patch:i}]})}o&&s!==void 0?await this.sendObservation(e,{toolName:o,toolInput:i,toolResponse:s,toolUseId:n}):o&&n&&(e.pendingTools||(e.pendingTools=new Map),e.pendingTools.set(n,{toolName:o,toolInput:i}))}async handleToolResult(e,t){let n=typeof t.toolId=="string"?t.toolId:void 0,o=typeof t.toolName=="string"?t.toolName:void 0,i=this.maybeParseJson(t.toolResponse),s=this.maybeParseJson(t.toolInput);if(n&&e.pendingTools){let c=e.pendingTools.get(n);c&&(o||(o=c.toolName),s===void 0&&(s=c.toolInput),e.pendingTools.delete(n))}o?await this.sendObservation(e,{toolName:o,toolInput:s,toolResponse:i,toolUseId:n}):a.debug("TRANSCRIPT","Dropping tool_result with no resolvable toolName",{sessionId:e.sessionId,toolId:n})}async sendObservation(e,t){let n=typeof t.toolName=="string"?t.toolName:void 0;if(!n)return;let o=await Qr({contentSessionId:e.sessionId,cwd:e.cwd??process.cwd(),toolName:n,toolInput:this.maybeParseJson(t.toolInput),toolResponse:this.maybeParseJson(t.toolResponse),platformSource:e.platformSource,toolUseId:typeof t.toolUseId=="string"?t.toolUseId:void 0});if(!o.ok)throw new Error(`ingestObservation failed: ${o.reason}`)}async sendFileEdit(e,t){let n=typeof t.filePath=="string"?t.filePath:void 0;n&&await Gr.execute({sessionId:e.sessionId,cwd:e.cwd??process.cwd(),filePath:n,edits:Array.isArray(t.edits)?t.edits:void 0,platform:e.platformSource})}maybeParseJson(e){if(typeof e!="string")return e;let t=e.trim();if(!t||!(t.startsWith("{")||t.startsWith("[")))return e;try{return JSON.parse(t)}catch(n){return a.debug("TRANSCRIPT","Field looked like JSON but did not parse; using raw string",{preview:t.slice(0,120)},n instanceof Error?n:void 0),e}}parseApplyPatchFiles(e){let t=[],n=e.split(`
|
|
28
|
+
`);for(let o of n){let i=o.trim();if(i.startsWith("*** Update File: "))t.push(i.replace("*** Update File: ","").trim());else if(i.startsWith("*** Add File: "))t.push(i.replace("*** Add File: ","").trim());else if(i.startsWith("*** Delete File: "))t.push(i.replace("*** Delete File: ","").trim());else if(i.startsWith("*** Move to: "))t.push(i.replace("*** Move to: ","").trim());else if(i.startsWith("+++ ")){let s=i.replace("+++ ","").replace(/^b\//,"").trim();s&&s!=="/dev/null"&&t.push(s)}}return Array.from(new Set(t))}async handleSessionEnd(e,t){await this.queueSummary(e),await this.updateContext(e,t),e.pendingTools?.clear();let n=this.getSessionKey(t,e.sessionId);this.sessions.delete(n)}async queueSummary(e){if(!await We())return;let n=e.lastAssistantMessage??"",o=JSON.stringify({contentSessionId:e.sessionId,last_assistant_message:n,platformSource:e.platformSource});try{await j("/api/sessions/summarize",{method:"POST",headers:{"Content-Type":"application/json"},body:o})}catch(i){a.warn("TRANSCRIPT","Summary request failed",{error:i instanceof Error?i.message:String(i)})}}async updateContext(e,t){if(!t.context||t.context.mode!=="agents"||It(t)||!await We())return;let o=e.cwd??t.workspace;if(!o)return;let s=Q(o).allProjects.join(","),c=`/api/context/inject?projects=${encodeURIComponent(s)}&platformSource=${encodeURIComponent(e.platformSource)}`,u=v(t.context.path??`${o}/AGENTS.md`),d=ge.default.resolve(u),l=[ge.default.resolve(o),ge.default.resolve(S)];if(!l.some(_=>d.startsWith(_+ge.default.sep)||d===_)){a.warn("SECURITY","Rejected path traversal attempt in watch.context.path",{original:t.context.path,resolved:d,allowedRoots:l});return}let g;try{g=await j(c)}catch(_){a.warn("TRANSCRIPT","Failed to fetch AGENTS.md context",{error:_ instanceof Error?_.message:String(_)});return}if(!g.ok)return;let b=(await g.text()).trim();b&&(Br(u,b),a.debug("TRANSCRIPT","Updated AGENTS.md context",{agentsPath:u,watch:t.name}))}};var vt=class{constructor(e,t,n,o){this.filePath=e;this.onLine=n;this.onOffset=o;this.tailState={offset:t,partial:""}}filePath;onLine;onOffset;watcher=null;tailState;start(){this.readNewData().catch(()=>{}),this.watcher=(0,M.watch)(this.filePath,{persistent:!0},()=>{this.readNewData().catch(()=>{})})}close(){this.watcher?.close(),this.watcher=null}poke(){this.readNewData().catch(()=>{})}async readNewData(){if(!(0,M.existsSync)(this.filePath))return;let e=0;try{e=(0,M.statSync)(this.filePath).size}catch(s){a.debug("WORKER","Failed to stat transcript file",{file:this.filePath},s instanceof Error?s:void 0);return}if(e<this.tailState.offset&&(this.tailState.offset=0),e===this.tailState.offset)return;let t=(0,M.createReadStream)(this.filePath,{start:this.tailState.offset,end:e-1,encoding:"utf8"}),n="";for await(let s of t)n+=s;this.tailState.offset=e,this.onOffset(this.tailState.offset);let i=(this.tailState.partial+n).split(`
|
|
29
|
+
`);this.tailState.partial=i.pop()??"";for(let s of i){let c=s.trim();c&&await this.onLine(c)}}},qe=class{constructor(e,t){this.config=e;this.statePath=t;this.state=xt(t)}config;statePath;processor=new Ve;tailers=new Map;state;rootWatchers=[];async start(){for(let e of this.config.watches)await this.setupWatch(e)}stop(){for(let e of this.tailers.values())e.close();this.tailers.clear();for(let e of this.rootWatchers)e.close();this.rootWatchers=[]}async setupWatch(e){let t=this.resolveSchema(e);if(!t){a.warn("TRANSCRIPT","Missing schema for watch",{watch:e.name});return}let n=v(e.path),o=this.resolveWatchFiles(n);for(let s of o)await this.addTailer(s,e,t);let i=this.deepestNonGlobAncestor(n);if(!i||!(0,M.existsSync)(i)){a.debug("TRANSCRIPT","Watch root does not exist, skipping fs.watch",{watch:e.name,watchRoot:i});return}try{let s=(0,M.watch)(i,{recursive:!0,persistent:!0},(c,u)=>{this.handleRootWatchEvent(i,n,e,t,u)});this.rootWatchers.push(s),a.info("TRANSCRIPT","Watching transcript root recursively",{watch:e.name,watchRoot:i})}catch(s){a.warn("TRANSCRIPT","Failed to start recursive fs.watch on transcript root",{watch:e.name,watchRoot:i},s instanceof Error?s:void 0)}}handleRootWatchEvent(e,t,n,o,i){if(!i)return;let s=(0,D.resolve)(e,i).replace(/\\/g,"/"),c=this.tailers.get(s);if(c){c.poke();return}let u=this.resolveWatchFiles(t);for(let d of u)this.tailers.has(d)||this.addTailer(d,n,o)}deepestNonGlobAncestor(e){if(!this.hasGlob(e)){if((0,M.existsSync)(e))try{return(0,M.statSync)(e).isDirectory()?e:(0,D.resolve)(e,"..")}catch(o){return a.debug("TRANSCRIPT","Failed to stat watch path ancestor, falling back to parent directory",{path:e},o instanceof Error?o:new Error(String(o))),(0,D.resolve)(e,"..")}return e}let t=e.split(/[/\\]/),n=[];for(let o of t){if(/[*?[\]{}()]/.test(o))break;n.push(o)}return n.length===0||n.length===1&&n[0]===""?"":n.join(D.sep)}resolveSchema(e){return typeof e.schema=="string"?this.config.schemas?.[e.schema]??null:e.schema}resolveWatchFiles(e){if(this.hasGlob(e))return this.scanGlob(this.normalizeGlobPattern(e));if((0,M.existsSync)(e))try{if((0,M.statSync)(e).isDirectory()){let n=(0,D.join)(e,"**","*.jsonl");return this.scanGlob(this.normalizeGlobPattern(n))}return[e]}catch(t){return a.debug("WORKER","Failed to stat watch path",{path:e},t instanceof Error?t:void 0),[]}return[]}scanGlob(e){return Array.from(new Bun.Glob(e).scanSync({absolute:!0,onlyFiles:!0}))}normalizeGlobPattern(e){return e.replace(/\\/g,"/")}hasGlob(e){return/[*?[\]{}()]/.test(e)}async addTailer(e,t,n){if(this.tailers.has(e))return;let o=this.extractSessionIdFromPath(e),i=this.state.offsets[e]??0;if(i===0&&t.startAtEnd)try{i=(0,M.statSync)(e).size}catch(c){a.debug("WORKER","Failed to stat file for startAtEnd offset",{file:e},c instanceof Error?c:void 0),i=0}let s=new vt(e,i,async c=>{await this.handleLine(c,t,n,e,o)},c=>{this.state.offsets[e]=c,Nt(this.statePath,this.state)});s.start(),this.tailers.set(e,s),a.info("TRANSCRIPT","Watching transcript file",{file:e,watch:t.name,schema:n.name})}async handleLine(e,t,n,o,i){try{let s=JSON.parse(e);await this.processor.processEntry(s,t,n,i??void 0)}catch(s){s instanceof Error?a.debug("TRANSCRIPT","Failed to parse transcript line",{watch:t.name,file:(0,D.basename)(o)},s):a.warn("TRANSCRIPT","Failed to parse transcript line (non-Error thrown)",{watch:t.name,file:(0,D.basename)(o),error:String(s)})}}extractSessionIdFromPath(e){let t=e.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i);return t?t[0]:null}};function Ct(r,e){let t=r.indexOf(e);return t===-1?null:r[t+1]??null}async function Zr(r,e){switch(r){case"init":{let t=Ct(e,"--config")??ne;return we(t),console.log(`Created sample config: ${v(t)}`),0}case"watch":{let t=Ct(e,"--config")??ne,n;try{n=pe(t)}catch(c){if(c instanceof Error&&c.message.includes("not found"))we(t),console.log(`Created sample config: ${v(t)}`),n=pe(t);else throw c}let o=v(n.stateFile??Te),i=new qe(n,o);await i.start(),console.log("Transcript watcher running. Press Ctrl+C to stop.");let s=()=>{i.stop(),process.exit(0)};return process.on("SIGINT",s),process.on("SIGTERM",s),await new Promise(()=>{})}case"validate":{let t=Ct(e,"--config")??ne;try{pe(t)}catch(n){if(n instanceof Error&&n.message.includes("not found"))we(t),console.log(`Created sample config: ${v(t)}`),pe(t);else throw n}return console.log(`Config OK: ${v(t)}`),0}default:return console.log("Usage: claude-mem transcript <init|watch|validate> [--config <path>]"),1}}var Ho=process.argv[2],jo=process.argv.slice(3);Zr(Ho,jo).then(r=>{process.exit(r)}).catch(r=>{console.error(r),process.exit(1)});
|