claude-mem 13.40.0 → 13.41.0
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/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/.qoder-plugin/plugin.json +1 -1
- package/README.md +1 -1
- package/dist/npx-cli/index.js +2 -2
- package/dist/opencode-plugin/index.js +3 -3
- package/dist/pi-extension/index.js +6 -6
- package/dsh/package.json +1 -1
- package/omp/hooks/claude-mem.ts +5 -1
- package/openclaw/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/.codex-plugin/plugin.json +1 -1
- package/plugin/.qoder-plugin/plugin.json +1 -1
- package/plugin/package.json +1 -1
- package/plugin/scripts/context-generator.cjs +21 -21
- package/plugin/scripts/context-generator.cjs.map +3 -3
- package/plugin/scripts/mcp-server.cjs +122 -115
- package/plugin/scripts/mcp-server.cjs.map +3 -3
- package/plugin/scripts/server-service.cjs +2 -2
- package/plugin/scripts/server-service.cjs.map +1 -1
- package/plugin/scripts/transcript-watcher.cjs +28 -27
- package/plugin/scripts/transcript-watcher.cjs.map +3 -3
- package/plugin/scripts/worker-service.cjs +525 -523
- package/plugin/scripts/worker-service.cjs.map +3 -3
- package/plugin/skills/build/SKILL.md +16 -0
- package/plugin/skills/build-and-release/SKILL.md +16 -0
- package/plugin/skills/childhood/SKILL.md +46 -0
- package/plugin/skills/release/SKILL.md +15 -0
- package/plugin/sqlite/SessionStore.js.map +1 -1
- package/plugin/sqlite/observations/files.js +6 -6
- package/plugin/sqlite/observations/files.js.map +1 -1
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
var __CM_FILENAME__ = typeof __filename !== "undefined" ? __filename : require("node:path").resolve(process.argv[1] || "");
|
|
2
2
|
var __CM_DIRNAME__ = typeof __dirname !== "undefined" ? __dirname : require("node:path").dirname(__CM_FILENAME__);
|
|
3
|
-
"use strict";var fi=Object.create;var ve=Object.defineProperty;var mi=Object.getOwnPropertyDescriptor;var pi=Object.getOwnPropertyNames;var Ei=Object.getPrototypeOf,
|
|
4
|
-
`);let s=(0,
|
|
5
|
-
`,"utf-8"),c=r.mode;if(c===void 0)try{c=(0,
|
|
6
|
-
`)}finally{if(p!==void 0)try{(0,
|
|
7
|
-
${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let r=Object.keys(e);return r.length===0?"{}":r.length<=3?this.safeStringify(e):`{${r.length} keys: ${r.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,r){if(!r)return e;let n=r;if(typeof r=="string")try{n=JSON.parse(r)}catch{n=r}if(n===null)return e;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 r=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"),a=String(e.getSeconds()).padStart(2,"0"),c=String(e.getMilliseconds()).padStart(3,"0");return`${r}-${n}-${o} ${i}:${s}:${a}.${c}`}log(e,r,n,o,i){if(e<this.getLevel())return;this.ensureLogFileInitialized();let s=this.formatTimestamp(new Date),a=
|
|
3
|
+
"use strict";var fi=Object.create;var ve=Object.defineProperty;var mi=Object.getOwnPropertyDescriptor;var pi=Object.getOwnPropertyNames;var Ei=Object.getPrototypeOf,_i=Object.prototype.hasOwnProperty;var te=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(n){throw r=[n],n}};var gi=(t,e)=>{for(var r in e)ve(t,r,{get:e[r],enumerable:!0})},or=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of pi(e))!_i.call(t,o)&&o!==r&&ve(t,o,{get:()=>e[o],enumerable:!(n=mi(e,o))||n.enumerable});return t};var oe=(t,e,r)=>(r=t!=null?fi(Ei(t)):{},or(e||!t||!t.__esModule?ve(r,"default",{value:t,enumerable:!0}):r,t)),Si=t=>or(ve({},"__esModule",{value:!0}),t);function yi(t){return(hi??process.stderr.write.bind(process.stderr))(t)}function V(t){yi(t)}var hi,Cc,Le=te(()=>{"use strict";hi=null;Cc=Promise.resolve()});function ft(t){return t.replace(/^\uFEFF/,"")}function ke(t){return JSON.parse(ft(t))}function Se(t){return ke((0,g.readFileSync)(t,"utf-8"))}function Ti(t){(0,g.existsSync)(t)||(0,g.mkdirSync)(t,{recursive:!0})}function sr(t){try{return(0,g.realpathSync)(t)}catch(e){if(e.code!=="ENOENT")throw e;let r=(0,v.dirname)(t);return r===t?t:(0,v.join)(sr(r),(0,v.basename)(t))}}function Ci(t){let e=t,r=new Set;try{for(;(0,g.lstatSync)(e).isSymbolicLink();){let n=(0,v.resolve)(e);if(r.has(n))throw Object.assign(new Error(`Symlink loop at ${e}`),{code:"ELOOP"});r.add(n);try{return(0,g.realpathSync)(e)}catch(o){if(o.code!=="ENOENT")throw o;let i=o instanceof Error?o:new Error(String(o));V(`claude-mem: realpathSync failed for ${e}, resolving symlink manually: ${i.message}
|
|
4
|
+
`);let s=(0,g.readlinkSync)(e);e=(0,v.resolve)(sr((0,v.dirname)((0,v.resolve)(e))),s)}}}catch(n){if(n.code!=="ENOENT")throw n}return e}function N(t,e,r={}){let n=Ci(t);Ti((0,v.dirname)(n));let o=(0,v.dirname)(n),i=(0,v.basename)(n),s=(0,v.join)(o,`.${i}.${process.pid}.${(0,ir.randomBytes)(6).toString("hex")}.tmp`),a=Buffer.from(JSON.stringify(e,null,2)+`
|
|
5
|
+
`,"utf-8"),c=r.mode;if(c===void 0)try{c=(0,g.statSync)(n).mode&511}catch{}let l;try{l=c!==void 0?(0,g.openSync)(s,"w",c):(0,g.openSync)(s,"w");let d=0;for(;d<a.length;){let p=(0,g.writeSync)(l,a,d,a.length-d);if(p===0)throw new Error(`writeSync stalled at ${d}/${a.length} bytes`);d+=p}if((0,g.fsyncSync)(l),(0,g.closeSync)(l),l=void 0,(0,g.renameSync)(s,n),!Ai){let p;try{p=(0,g.openSync)(o,"r"),(0,g.fsyncSync)(p)}catch(f){let E=f instanceof Error?f:new Error(String(f));V(`claude-mem: directory fsync failed for ${o}: ${E.message}
|
|
6
|
+
`)}finally{if(p!==void 0)try{(0,g.closeSync)(p)}catch{}}}}catch(d){if(l!==void 0)try{(0,g.closeSync)(l)}catch{}try{(0,g.unlinkSync)(s)}catch{}throw d}}var g,ir,v,Ai,$=te(()=>{"use strict";g=require("fs"),ir=require("crypto"),v=require("path");Le();Ai=process.platform==="win32"});function ar(t){let e=t.env;return Mi(e)&&Object.keys(e).some(r=>r.startsWith("CLAUDE_MEM_"))?"nested":"flat"}function ie(t){return ar(t)==="nested"?t.env:t}function cr(t){return ar(t)!=="nested"?t:Object.fromEntries(Object.entries(t).filter(([e])=>!e.startsWith("CLAUDE_MEM_")))}var Mi,Ie=te(()=>{"use strict";$();Mi=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)});function H(t,e=process.platform,r=(0,lr.homedir)()){return typeof t!="string"||t.length===0?t:t==="~"?r:t.startsWith("~/")||e==="win32"&&t.startsWith("~\\")?(0,ur.join)(r,t.slice(2)):t}var lr,ur,he=te(()=>{"use strict";lr=require("os"),ur=require("path")});function bi(){return typeof __CM_DIRNAME__<"u"?__CM_DIRNAME__:(0,h.dirname)((0,dr.fileURLToPath)(Di.url))}function ye(){if(process.env.CLAUDE_MEM_DATA_DIR)return H(process.env.CLAUDE_MEM_DATA_DIR);let t=(0,h.join)((0,Pe.homedir)(),".claude-mem"),e=(0,h.join)(t,"settings.json");try{if((0,mt.existsSync)(e)){let r=Se(e);if(r===null||typeof r!="object"||Array.isArray(r))return t;let n=ie(r);if(typeof n.CLAUDE_MEM_DATA_DIR=="string"&&n.CLAUDE_MEM_DATA_DIR)return H(n.CLAUDE_MEM_DATA_DIR)}}catch{}return t}function pr(){return(0,h.join)(Oi,"..")}function Er(t,e=(0,Pe.homedir)(),r=process.platform){return H(t,r,e)}var h,Pe,mt,dr,Di,Oi,C,pt,B,Ri,wi,K,fr,Et,mr,xc,A,T=te(()=>{"use strict";h=require("path"),Pe=require("os"),mt=require("fs"),dr=require("url");$();Ie();he();he();Di={};Oi=bi();C=ye(),pt=(0,h.join)((0,Pe.homedir)(),".claude"),B=process.env.CLAUDE_CONFIG_DIR||pt,Ri=(0,h.join)(B,"plugins","marketplaces","thedotmack"),wi=(0,h.join)(C,"logs"),K=(0,h.join)(C,"settings.json"),fr="claude-mem.db",Et=(0,h.join)(C,fr),mr=(0,h.join)(C,"observer-sessions"),xc=(0,h.basename)(mr);A={dataDir:()=>C,workerPid:()=>(0,h.join)(C,"worker.pid"),workerHeartbeat:()=>(0,h.join)(C,"worker-heartbeat.json"),serverPid:()=>(0,h.join)(C,".server-beta.pid"),serverPort:()=>(0,h.join)(C,".server-beta.port"),serverRuntime:()=>(0,h.join)(C,".server-beta.runtime.json"),settings:()=>(0,h.join)(C,"settings.json"),database:()=>(0,h.join)(C,fr),chroma:()=>(0,h.join)(C,"chroma"),combinedCerts:()=>(0,h.join)(C,"combined_certs.pem"),transcriptsConfig:()=>(0,h.join)(C,"transcript-watch.json"),transcriptsState:()=>(0,h.join)(C,"transcript-watch-state.json"),corpora:()=>(0,h.join)(C,"corpora"),supervisorRegistry:()=>(0,h.join)(C,"supervisor.json"),envFile:()=>(0,h.join)(C,".env"),logsDir:()=>wi}});var L,_r,gt,_t,St,u,_=te(()=>{"use strict";L=require("fs"),_r=require("path");T();Le();$();Ie();gt=(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))(gt||{}),_t=null,St=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;logFileDate=null;logFd=null;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){let e=new Date().toISOString().split("T")[0];if(this.logFileInitialized&&this.logFileDate===e)return;let r=this.logFileDate!==e;this.closeLogFd(),this.logFileInitialized=!1,this.logFileDate=e;try{let n=A.logsDir();(0,L.existsSync)(n)||(0,L.mkdirSync)(n,{recursive:!0}),this.logFilePath=(0,_r.join)(n,`claude-mem-${e}.log`),this.logFileInitialized=!0}catch(n){r&&console.error("[LOGGER] Failed to initialize log file:",n instanceof Error?n.message:String(n)),this.logFilePath=null}}closeLogFd(){if(this.logFd!==null){try{(0,L.closeSync)(this.logFd)}catch{}this.logFd=null}}appendLine(e,r){if(this.logFd!==null){let n=!1;try{let o=(0,L.fstatSync)(this.logFd),i=(0,L.statSync)(e);n=o.ino===i.ino&&o.dev===i.dev}catch{}n||this.closeLogFd()}this.logFd===null&&(this.logFd=(0,L.openSync)(e,"a"));try{let n=Buffer.from(r,"utf8");for(;n.length>0;){let o=(0,L.writeSync)(this.logFd,n);if(o<=0)throw new Error("log write accepted 0 bytes");n=n.subarray(o)}}catch(n){throw this.closeLogFd(),n}}getLevel(){if(this.level===null)try{let e=A.settings();if((0,L.existsSync)(e)){let n=(ie(Se(e)).CLAUDE_MEM_LOG_LEVEL||"INFO").toString().toUpperCase();this.level=gt[n]??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}safeStringify(e,r,n=6){let o=new WeakSet,i=(s,a)=>{if(typeof s=="bigint")return`${s}n`;if(s===null||typeof s!="object")return s;let c=s.toJSON,l=typeof c=="function"?c.call(s):s;if(typeof l=="bigint")return`${l}n`;if(l===null||typeof l!="object")return l;if(o.has(l))return"[Circular]";if(a>=n)return Array.isArray(l)?"[Array]":"[Object]";o.add(l);try{if(Array.isArray(l))return l.map(p=>i(p,a+1));let d={};for(let p of Object.keys(l))try{d[p]=i(l[p],a+1)}catch{d[p]="[unreadable]"}return d}finally{o.delete(l)}};try{return JSON.stringify(i(e,0),null,r)??String(e)}catch{return Array.isArray(e)?`[${e.length} items]`:"[unserializable]"}}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}
|
|
7
|
+
${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let r=Object.keys(e);return r.length===0?"{}":r.length<=3?this.safeStringify(e):`{${r.length} keys: ${r.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,r){if(!r)return e;let n=r;if(typeof r=="string")try{n=JSON.parse(r)}catch{n=r}if(n===null)return e;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 r=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"),a=String(e.getSeconds()).padStart(2,"0"),c=String(e.getMilliseconds()).padStart(3,"0");return`${r}-${n}-${o} ${i}:${s}:${a}.${c}`}log(e,r,n,o,i){if(e<this.getLevel())return;this.ensureLogFileInitialized();let s=this.formatTimestamp(new Date),a=gt[e].padEnd(5),c=r.padEnd(6),l="";o?.correlationId?l=`[${o.correlationId}] `:o?.sessionId&&(l=`[session-${o.sessionId}] `);let d="";i!=null&&(i instanceof Error?d=this.getLevel()===0?`
|
|
8
8
|
${i.message}
|
|
9
9
|
${i.stack}`:` ${i.message}`:this.getLevel()===0&&typeof i=="object"?d=`
|
|
10
10
|
`+this.safeStringify(i,2):d=" "+this.formatData(i));let p="";if(o){let{sessionId:E,memorySessionId:S,correlationId:R,...y}=o;Object.keys(y).length>0&&(p=` {${Object.entries(y).map(([x,I])=>typeof I!="object"||I===null||I instanceof Error||I instanceof Date?`${x}=${I}`:`${x}=${Array.isArray(I)?this.safeStringify(I):this.formatData(I)}`).join(", ")}}`)}let f=`[${s}] [${a}] [${c}] ${l}${n}${p}${d}`;if(this.logFilePath)try{this.appendLine(this.logFilePath,f+`
|
|
11
11
|
`)}catch(E){let S=E instanceof Error?E:new Error(String(E));V(`[LOGGER] Failed to write to log file: ${S.message}
|
|
12
12
|
${S.stack??""}
|
|
13
13
|
`)}else V(f+`
|
|
14
|
-
`)}debug(e,r,n,o){this.log(0,e,r,n,o)}info(e,r,n,o){this.log(1,e,r,n,o)}warn(e,r,n,o){this.log(2,e,r,n,o)}setErrorSink(e){gt=e}error(e,r,n,o){this.log(3,e,r,n,o),this.routeErrorToSink(r,n,o)}routeErrorToSink(e,r,n){try{if(!gt||!(n instanceof Error))return;gt(n)}catch{}}dataIn(e,r,n,o){this.info(e,`\u2192 ${r}`,n,o)}dataOut(e,r,n,o){this.info(e,`\u2190 ${r}`,n,o)}success(e,r,n,o){this.info(e,`\u2713 ${r}`,n,o)}failure(e,r,n,o){this.error(e,`\u2717 ${r}`,n,o)}},u=new St});var es,$r,Hr=te(()=>{"use strict";es=require("bun:sqlite");g();$r=5e3});var Ac={};_i(Ac,{generateContext:()=>ui,generateContextWithStats:()=>nr});module.exports=Si(Ac);var oi=oe(require("path"),1),ii=require("os"),ut=require("fs"),si=require("bun:sqlite");T();g();var k=oe(require("path"),1),se=require("fs"),$e=require("os"),Mt=require("child_process");he();T();var re=require("fs"),q=require("path"),Ae=require("os");var U={HEALTH_CHECK:3e3,API_REQUEST:3e4,SESSION_INIT_HOOK_CAP:15e3,SESSION_INIT_REQUEST:1e4,SESSION_INIT_REQUEST_MAX:14e3,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5};function vi(t=process.platform){return t==="win32"?8e3:5e3}function ht(t=process.platform){return U.SESSION_INIT_HOOK_CAP-vi(t)}function G(t){return process.platform==="win32"?Math.round(t*U.WINDOWS_MULTIPLIER):t}$();g();function _r(t){try{return new URL(t).hostname.toLowerCase()==="openrouter.ai"}catch{return!1}}Ie();var Li="security_alert",ki="sync-hub.black-pond-afbb.workers.dev",Ii="ziczmqtpmaxbornfghye.supabase.co",Pi="https://sync.cmem.ai",xi=new Set(["xiaomi/mimo-v2-flash:free"]);function Ni(t){return typeof t=="boolean"?String(t):t}function Ui(t){let e=t.CLAUDE_MEM_OPENROUTER_MODEL;if(typeof e!="string"||!xi.has(e.trim()))return!1;let r=typeof t.CLAUDE_MEM_OPENROUTER_BASE_URL=="string"?t.CLAUDE_MEM_OPENROUTER_BASE_URL.trim():"";return r===""||_r(r)}var Sr=18e4,hr=[{key:"CLAUDE_MEM_LLM_TIMEOUT_MS",legacy:"30000",markerTag:"llm-timeout-migrated-v1"},{key:"CLAUDE_MEM_FIELD_OPTIMIZE_TIMEOUT_MS",legacy:"30000",markerTag:"field-optimize-timeout-migrated-v1"}];function Ar(t,e){return(0,q.join)((0,q.dirname)(t),`.${(0,q.basename)(t)}.${e.markerTag}`)}function yt(t,e){try{(0,re.writeFileSync)(Ar(t,e),new Date().toISOString(),{encoding:"utf-8",mode:384})}catch{}}var yr=new Set;function $i(t){if(typeof t!="string")return null;let e=t.trim();if(e.length===0)return null;try{let r=new URL(e).hostname;if(r===ki||r===Ii)return Pi}catch{return null}return null}var b=class{static DEFAULTS={CLAUDE_MEM_MEMORY_SEARCH_HOOK_ENABLED:"true",CLAUDE_MEM_MEMORY_INSTRUCTIONS_ENABLED:"true",CLAUDE_MEM_MEMORY_WATCH_ROOTS:"",CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_SESSION_START_INCLUDE_ALL_SOURCES:"false",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_WORKER_INGEST_TOKEN:"",CLAUDE_MEM_HOOK_SPOOL_TRANSPORT:"auto",CLAUDE_MEM_ALLOWED_ORIGINS:"",CLAUDE_MEM_PUBLIC_URL:"",CLAUDE_MEM_API_TIMEOUT_MS:String(G(U.API_REQUEST)),CLAUDE_MEM_SESSION_INIT_TIMEOUT_MS:String(ht()),CLAUDE_MEM_IDLE_EXIT_SEC:"0",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_SKIP_BASH_PATTERNS:"",CLAUDE_MEM_SKIP_SUBAGENT_OBSERVATIONS:"false",CLAUDE_MEM_SKIP_AGENT_TYPES:"",CLAUDE_MEM_CAPTURE_ADVISOR_CALLS:"false",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CODEX_MODEL:"",CLAUDE_MEM_CODEX_PATH:"codex",CLAUDE_MEM_CODEX_REASONING_EFFORT:"low",CLAUDE_MEM_CODEX_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_CODEX_OBSERVATION_BATCH_SIZE:"8",CLAUDE_MEM_CODEX_OBSERVATION_BATCH_MAX_CHARS:"32000",CLAUDE_MEM_CLAUDE_OBSERVATION_BATCH_SIZE:"1",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_API_KEYS:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-flash-latest",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_API_KEYS:"",CLAUDE_MEM_OPENROUTER_MODEL:"cohere/north-mini-code:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_TEMPERATURE:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_EXTRA_BODY:"",CLAUDE_MEM_OPENROUTER_REASONING_EFFORT:"",CLAUDE_MEM_OPENAI_COMPAT_PRESET:"",CLAUDE_MEM_OPENAI_COMPAT_API_KEY:"",CLAUDE_MEM_OPENAI_COMPAT_API_KEYS:"",CLAUDE_MEM_OPENAI_COMPAT_BASE_URL:"",CLAUDE_MEM_OPENAI_COMPAT_MODEL:"",CLAUDE_MEM_QUOTA_FALLBACK_PROVIDER:"claude",CLAUDE_MEM_QUOTA_FALLBACK_MODEL:"",CLAUDE_MEM_QUOTA_THRESHOLD_FIVE_HOUR:"0.95",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY:"0.93",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY_OPUS:"0.93",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY_SONNET:"0.92",CLAUDE_MEM_QUOTA_THRESHOLD_OVERAGE:"0.95",CLAUDE_MEM_DATA_DIR:(0,q.join)((0,Ae.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_CLAUDE_CONFIG_DIR:"",CLAUDE_MEM_OBSERVER_CLAUDE_CONFIG_DIR:"",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_OBSERVATION_TYPES:"",CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:"",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_MAIN_AGENT_ONLY:"true",CLAUDE_MEM_REINFORCE_ALPHA:"0",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_WORK_STATE_ENABLED:"true",CLAUDE_MEM_FILE_READ_GATE_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,q.join)((0,Ae.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_CODEX_SUBAGENT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_OBSERVER_MAX_CONVERSATION_CHARS:"400000",CLAUDE_MEM_OBSERVER_THINKING:"disabled",CLAUDE_MEM_OBSERVER_CONTEXT_WINDOW:"",CLAUDE_MEM_OBSERVER_MAX_OUTPUT_TOKENS:"4096",CLAUDE_MEM_OBSERVE_BARE_PROMPTS:"false",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_REDACT_ENABLED:"false",CLAUDE_MEM_REDACT_DISABLED_BUILTINS:"",CLAUDE_MEM_REDACT_CUSTOM_PATTERNS:"[]",CLAUDE_MEM_REDACT_LOG_MATCHES:"false",CLAUDE_MEM_REDACT_GENERIC_ENABLED:"false",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_PROJECT_ENVIRONMENTS:"[]",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_SEMANTIC_INJECT_FORMAT:"narrative",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_CHROMA_MUTATION_TIMEOUT_MS:"600000",CLAUDE_MEM_CHROMA_MAX_PENDING_MUTATIONS:"5000",CLAUDE_MEM_CHROMA_EMBEDDING_FUNCTION:"default",CLAUDE_MEM_CHROMA_UVX_PATH:"",CLAUDE_MEM_SEARCH_RECENCY_DAYS:"90",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,Ae.hostname)(),CLAUDE_MEM_CLOUD_SYNC_WS:"true",CLAUDE_MEM_CLOUD_SYNC_CONTENT_BATCH_SIZE:"40",CLAUDE_MEM_CLOUD_SYNC_REQUEST_TIMEOUT_MS:"90000",CLAUDE_MEM_TEAMBRAIN_URL:"",CLAUDE_MEM_TEAMBRAIN_TEAM_ID:"",CLAUDE_MEM_LLM_TIMEOUT_MS:String(Sr),CLAUDE_MEM_FIELD_OPTIMIZE_TIMEOUT_MS:String(Sr),CLAUDE_MEM_LLM_STREAM_IDLE_TIMEOUT_MS:"90000",CLAUDE_MEM_WORKER_HEARTBEAT_STALE_MS:"120000",CLAUDE_MEM_TV_TOKEN:"",CLAUDE_MEM_PRO_TRIAL_EMAIL:"",CLAUDE_MEM_PRO_TRIAL_AT:"",CLAUDE_MEM_PRO_TRIAL_STATE:"",CLAUDE_MEM_PRO_TRIAL_ENDS_AT:"",CLAUDE_MEM_PRO_PLAN:"",CLAUDE_MEM_PRO_FALLBACK_AT:"",CLAUDE_MEM_PRO_FALLBACK_MESSAGE:"",CLAUDE_MEM_PRO_FALLBACK_ACTION:"",CLAUDE_MEM_PRO_FALLBACK_URL:"",CLAUDE_MEM_PRO_MEMORY_KEY:"",CLAUDE_MEM_PRO_MEMORY_BASE_URL:"",CLAUDE_MEM_PRO_MEMORY_MODEL:"",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_WRAPUPS_ENABLED:"true",CLAUDE_MEM_TELEGRAM_OBSERVATION_ALERTS_ENABLED:"false",CLAUDE_MEM_TELEGRAM_WRAPUP_ROUTES:"{}",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert,sensitive",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_AWARENESS_ENABLED:"true",CLAUDE_MEM_GROK_BOT_AWARENESS_AGENT_IDS:"521e962d-2ec3-4488-bfbc-54d5209ce118,95601360-61f7-4fd9-bb3a-2c976b2b85c0",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_WEBHOOK_URL:"",CLAUDE_MEM_GROK_BOT_WEBHOOK_SECRET:"",CLAUDE_MEM_GROK_BOT_INJECT_ENABLED:"true",CLAUDE_MEM_GROK_BOT_INJECT_AGENT_IDS:"*",CLAUDE_MEM_GROK_BOT_INJECT_TIER:"episode",CLAUDE_MEM_GROK_BOT_INJECT_WINDOW:"80",CLAUDE_MEM_GROK_BOT_INJECT_FALLBACK:"house",CLAUDE_MEM_GROK_BOT_INJECT_PLATFORM_SOURCE:"",CLAUDE_MEM_GROK_BOT_INJECT_PROJECTS_BY_AGENT:"",CLAUDE_MEM_GROK_BOT_INJECT_MAX_LINE_CHARS:"160",CLAUDE_MEM_GROK_BOT_INJECT_DEBOUNCE_MS:"1500",CLAUDE_MEM_GROK_BOT_INJECT_STANDING_LINE:"",CLAUDE_MEM_CCS_ALIGN_ENABLED:"true",CLAUDE_MEM_CCS_ALIGN_VIEWER_IDS:"ccs-align",CLAUDE_MEM_CCS_ALIGN_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_CCS_ALIGN_PATCH_SHADOWS:"false",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:"",CLAUDE_MEM_DEDUP_ENABLED:"false",CLAUDE_MEM_DEDUP_COSINE_THRESHOLD:"0.80",CLAUDE_MEM_DEDUP_IDF_VETO_DF:"10",CLAUDE_MEM_DEDUP_MIN_SHARED_TOKENS:"2",CLAUDE_MEM_DEDUP_MIN_PROJECT_DOCS:"10",CLAUDE_MEM_DEDUP_MAX_SCAN:"2000",CLAUDE_MEM_DEDUP_MAX_BACKFILL_ROWS:"50000",CLAUDE_MEM_TOOL_USES_RETENTION_DAYS:"0",CLAUDE_MEM_WORKER_AUTOSTART:"true",CLAUDE_MEM_PROJECT_NAME_SOURCE:"path"};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){let r=process.env[e]??this.DEFAULTS[e];return e==="CLAUDE_MEM_WORKER_HOST"?this.normalizeWorkerHost(r):r}static normalizeWorkerHost(e){return e==="localhost"?"127.0.0.1":e}static finalizeSettings(e,r){let n=r?this.applyEnvOverrides(e):e;return n.CLAUDE_MEM_WORKER_HOST=this.normalizeWorkerHost(n.CLAUDE_MEM_WORKER_HOST),n}static getInt(e){let r=this.get(e);return parseInt(r,10)}static applyEnvOverrides(e){let r={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(r[n]=process.env[n]);return r}static loadFromFile(e,r=!0,n={}){try{if(!(0,re.existsSync)(e)){let f=this.getAllDefaults();if(!n.readOnly)try{N(e,f,{mode:384});for(let E of hr)yt(e,E);console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(E){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,E instanceof Error?E.message:String(E))}return this.finalizeSettings(f,r)}let o=(0,re.readFileSync)(e,"utf-8"),i=ke(o),s=ie(i),a=s!==i,c=cr(i),l=a&&Object.keys(c).some(f=>f!=="env");if(a&&!l&&!n.readOnly)try{N(e,s,{mode:384}),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(f){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,f instanceof Error?f.message:String(f))}if(s.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES===Li&&(s={...s,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES},!n.readOnly))try{N(e,l?{...c,env:s}:s,{mode:384}),console.warn("[SETTINGS] Migrated Telegram trigger types off the legacy default:",e)}catch(f){console.warn("[SETTINGS] Failed to migrate Telegram trigger types:",e,f instanceof Error?f.message:String(f))}if(Ui(s)){let f=String(s.CLAUDE_MEM_OPENROUTER_MODEL).trim();if(s={...s,CLAUDE_MEM_OPENROUTER_MODEL:this.DEFAULTS.CLAUDE_MEM_OPENROUTER_MODEL},!n.readOnly)try{N(e,l?{...c,env:s}:s,{mode:384}),console.warn(`[SETTINGS] Migrated OpenRouter model off the retired default ${f} to ${this.DEFAULTS.CLAUDE_MEM_OPENROUTER_MODEL}:`,e)}catch(E){console.warn("[SETTINGS] Failed to migrate the retired OpenRouter model:",e,E instanceof Error?E.message:String(E))}}let d=$i(s.CLAUDE_MEM_CLOUD_SYNC_HUB_URL);if(d!==null&&(s={...s,CLAUDE_MEM_CLOUD_SYNC_HUB_URL:d},!n.readOnly))try{N(e,l?{...c,env:s}:s,{mode:384}),console.warn("[SETTINGS] Migrated cloud sync hub URL to",d,"from a retired hub host:",e)}catch(f){console.warn("[SETTINGS] Failed to migrate cloud sync hub URL:",e,f instanceof Error?f.message:String(f))}for(let f of hr)if(!(0,re.existsSync)(Ar(e,f))){if(s[f.key]!==f.legacy){n.readOnly||yt(e,f);continue}if(s={...s,[f.key]:this.DEFAULTS[f.key]},!n.readOnly)try{N(e,l?{...c,env:s}:s,{mode:384}),yt(e,f),console.warn(`[SETTINGS] Migrated ${f.key} off the old ${f.legacy}ms default to ${this.DEFAULTS[f.key]}ms:`,e)}catch(E){let S=`${f.key}\0${e}`;yr.has(S)||(yr.add(S),console.warn(`[SETTINGS] Failed to migrate ${f.key}; using the new default in memory (reported once per process):`,e,E instanceof Error?E.message:String(E)))}}let p={...this.DEFAULTS};for(let f of Object.keys(this.DEFAULTS))s[f]!==void 0&&(p[f]=Ni(s[f]));return this.finalizeSettings(p,r)}catch(o){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,o instanceof Error?o.message:String(o));let i=this.getAllDefaults();return this.finalizeSettings(i,r)}}};g();var xe=require("fs"),X=oe(require("path"),1);g();var Te={isWorktree:!1,isSubmodule:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function Tr(t){let e=X.default.join(t,".git"),r;try{r=(0,xe.statSync)(e)}catch(c){return c instanceof Error&&c.code!=="ENOENT"&&u.warn("GIT","Unexpected error checking .git",{error:c instanceof Error?c.message:String(c)}),Te}if(!r.isFile())return Te;let n;try{n=(0,xe.readFileSync)(e,"utf-8").trim()}catch(c){return u.warn("GIT","Failed to read .git file",{error:c instanceof Error?c.message:String(c)}),Te}let o=n.match(/^gitdir:\s*(.+)$/);if(!o)return Te;let i=X.default.resolve(X.default.dirname(e),o[1]),s=i.match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(s){let c=s[1];return{isWorktree:!0,isSubmodule:!1,worktreeName:X.default.basename(t),parentRepoPath:c,parentProjectName:X.default.basename(c)}}let a=i.match(/^(.+)[/\\]\.git[/\\]modules[/\\](.+)$/);if(a){let c=a[1];return{isWorktree:!1,isSubmodule:!0,worktreeName:X.default.basename(t),parentRepoPath:c,parentProjectName:X.default.basename(c)}}return Te}var Or=require("fs");var Mr=require("path");he();g();function Cr(t){let e=H(t.replace(/\\/g,"/"));e=e.replace(/\\/g,"/");let r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return r=r.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${r}$`)}function Hi(t,e,r){let n=Cr(t);return n.test(e)||n.test(r)?!0:t.replace(/\\/g,"/").endsWith("/**")?Cr(t.slice(0,-3)).test(e.replace(/\/+$/,"")):!1}function br(t,e){if(!e.length)return!1;let r=t.replace(/\\/g,"/"),n=(0,Mr.basename)(r);for(let o of e){let i=o.trim();if(i)try{if(Hi(i,r,n))return!0}catch(s){u.warn("PROJECT_NAME","Invalid glob pattern",{pattern:i,error:s instanceof Error?s.message:String(s)});continue}}return!1}g();function Rr(t){let e=t;if(typeof e=="string"){if(!e.trim())return[];try{e=JSON.parse(e)}catch(n){return u.warn("PROJECT_NAME","CLAUDE_MEM_PROJECT_ENVIRONMENTS is not valid JSON; ignoring it",{error:n instanceof Error?n.message:String(n)}),[]}}if(!Array.isArray(e))return e!=null&&u.warn("PROJECT_NAME","CLAUDE_MEM_PROJECT_ENVIRONMENTS must be an array; ignoring it",{}),[];let r=[];for(let n of e){let o=typeof n?.name=="string"?n.name.trim():"",i=Array.isArray(n?.patterns)?n.patterns.filter(s=>typeof s=="string"&&s.trim()!==""):[];if(!o||i.length===0){u.warn("PROJECT_NAME","Ignoring a project environment without a name or patterns",{name:o});continue}r.push({name:o,patterns:i})}return r}function Fi(t){try{return(0,Or.realpathSync)(t)}catch{return t}}function At(t,e){if(e.length===0)return null;let r=[...new Set([t,Fi(t)])].flatMap(n=>[n,`${n.replace(/[\\/]+$/,"")}/`]);for(let n of e)if(r.some(o=>br(o,n.patterns)))return n.name;return null}var bt="unknown-project";function vr(t){try{return(0,Mt.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim()||null}catch(e){let r=e instanceof Error?e:new Error(String(e));return u.debug("PROJECT_NAME","git rev-parse failed, falling back to non-git root",{dir:t},r),null}}var Wi=[".claude-mem-project",".claude-mem.json"],ji=64;function Lr(t){try{return(0,se.realpathSync)(t)}catch{return t}}function Bi(t,e){let r=k.default.relative(e,t);return r===""||!r.startsWith("..")&&!k.default.isAbsolute(r)}function Ki(){return[(0,$e.homedir)(),(0,$e.tmpdir)(),B].flatMap(t=>{let e=k.default.resolve(t);return[e,Lr(e)]})}function kr(t){let e=Ki(),r=k.default.resolve(t);if([k.default.resolve(B),Lr(k.default.resolve(B))].some(o=>Bi(r,o)))return null;for(let o=0;o<ji;o++){if(e.includes(r))return null;let i=k.default.dirname(r);if(i===r)return null;if(Wi.some(s=>(0,se.existsSync)(k.default.join(r,s))))return r;r=i}return null}function Ct(t,e){let r=k.default.basename(e);if(r===""){if(process.platform==="win32"){let o=t.match(/^([A-Z]):\\/i);if(o){let s=`drive-${o[1].toUpperCase()}`;return u.info("PROJECT_NAME","Drive root detected",{cwd:t,projectName:s}),s}}return u.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:t}),bt}return r}var Gi="CLAUDE_MEM_PROJECT_NAME_SOURCE",Ne=null;function wr(){try{return(0,se.statSync)(K).mtimeMs}catch{return-1}}function Ir(){let t=wr();if(t===-1)return b.getAllDefaults();if(Ne&&Ne.mtimeMs===t)return Ne.settings;let e=b.loadFromFile(K);return Ne={mtimeMs:wr(),settings:e},e}function Yi(){let t=process.env[Gi]??Ir().CLAUDE_MEM_PROJECT_NAME_SOURCE;return String(t??"path").trim().toLowerCase()==="git-remote"}var Ji="CLAUDE_MEM_PROJECT_ENVIRONMENTS",Ue=null;function He(){let t=process.env[Ji]??Ir().CLAUDE_MEM_PROJECT_ENVIRONMENTS;return(!Ue||Ue.raw!==t)&&(Ue={raw:t,environments:Rr(t)}),Ue.environments}function Vi(t){let e=(t??"").trim();if(!e||/^file:/i.test(e)||e.startsWith("/")||e.startsWith(".")||e.startsWith("~")||e.startsWith("\\\\")||/^[a-z]:[\\/]/i.test(e))return null;let n=e.replace(/\/+$/,"").replace(/\.git$/i,""),o=n.match(/^[a-z][a-z0-9+.-]*:\/\/[^/]+\/(.+)$/i),i=o?null:n.match(/^(?:[^/@\s]+@)?[^:/\s]+:(?!\/\/)(.+)$/),s=o?.[1]??i?.[1];if(!s)return null;let a=s.split("/").filter(c=>c&&c!=="_git");return a.length>=2?a.slice(-2).join("/"):a.length===1?a[0]:null}function qi(t){try{let e=(0,Mt.execFileSync)("git",["remote","get-url","origin"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim();return Vi(e)}catch(e){let r=e instanceof Error?e:new Error(String(e));return u.debug("PROJECT_NAME","No usable origin remote, keeping the path-based name",{repoRoot:t},r),null}}var Tt=new Map;function Pr(t){return Yi()?(Tt.has(t)||Tt.set(t,qi(t)),Tt.get(t)??null):null}function Xi(t,e=process.platform){if(!t||t.trim()==="")return u.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),bt;let r=H(t,e),n=At(r,He());if(n)return n;let o=vr(r),i=o?Pr(o):null;if(i)return i;let s=o??kr(r)??r;return Ct(t,s)}function xr(t,e){return e===t?t:`${t}/${e}`}function zi(t,e){if(!t.isSubmodule||!t.parentRepoPath)return null;let r=k.default.relative(t.parentRepoPath,e);return!r||r.startsWith("..")||k.default.isAbsolute(r)?null:r.split(k.default.sep).join("/")}function Nr(t,e=process.platform){if(!t||t.trim()===""){let c=Xi(t,e);return{primary:c,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[c],keySource:"path"}}let r=H(t,e),n=vr(r),o=Qi(t,r,n),i=n?Pr(n):null,s=i?Dr(o,i,"git-remote"):o,a=At(r,He());return a?Dr(s,a,"environment"):s}function Dr(t,e,r){return{primary:e,parent:null,isWorktree:t.isWorktree,isSubmodule:t.isSubmodule,allProjects:[...t.allProjects.filter(n=>n!==e),e],keySource:r}}function Qi(t,e,r){let n=r?null:kr(e),o=Ct(t,r??n??e),i=r??e,s=Tr(i);if((s.isWorktree||s.isSubmodule)&&s.parentProjectName){let a=s.parentProjectName,c,l;return s.isSubmodule?(c=`${a}/${zi(s,i)??o}`,l=o!==a?[o]:[]):(c=xr(a,o),l=c===a?[`${a}/${o}`]:[]),{primary:c,parent:a,isWorktree:s.isWorktree,isSubmodule:s.isSubmodule,allProjects:[...new Set([a,...l,c])].filter(d=>d!==c).concat(c),keySource:"path"}}if(n&&k.default.resolve(n)!==k.default.resolve(e)){let a=Ct(t,e);if(a!==o&&a!==bt)return{primary:o,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[a,o],keySource:"path"}}return{primary:o,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[o],keySource:"path"}}var Ur="claude";function Zi(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Fe(t){if(!t)return Ur;let e=Zi(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e.includes("kimi")?"kimi":e==="pi-mono"?"pi":e==="agy"||e==="antigravity"||e.startsWith("antigravity-")?"antigravity-cli":e:Ur}Hr();function ts(t){let e=t.projects?.length?t.projects:t.project?[t.project]:[];return[...new Set(e.map(r=>r.trim()).filter(Boolean))]}var rs=4;function Fr(t,e){let r=ts({projects:e});if(r.length===0)return[];let n=r.map(()=>"?").join(","),o=[[`SELECT project AS key FROM sdk_sessions WHERE project COLLATE NOCASE IN (${n})`,1],[`SELECT project FROM observations WHERE project COLLATE NOCASE IN (${n})`,1],[`SELECT merged_into_project FROM observations WHERE merged_into_project COLLATE NOCASE IN (${n})`,1],[`SELECT project FROM session_summaries WHERE project COLLATE NOCASE IN (${n})`,1],[`SELECT merged_into_project FROM session_summaries WHERE merged_into_project COLLATE NOCASE IN (${n})`,1],[`SELECT candidates.key FROM (
|
|
14
|
+
`)}debug(e,r,n,o){this.log(0,e,r,n,o)}info(e,r,n,o){this.log(1,e,r,n,o)}warn(e,r,n,o){this.log(2,e,r,n,o)}setErrorSink(e){_t=e}error(e,r,n,o){this.log(3,e,r,n,o),this.routeErrorToSink(r,n,o)}routeErrorToSink(e,r,n){try{if(!_t||!(n instanceof Error))return;_t(n)}catch{}}dataIn(e,r,n,o){this.info(e,`\u2192 ${r}`,n,o)}dataOut(e,r,n,o){this.info(e,`\u2190 ${r}`,n,o)}success(e,r,n,o){this.info(e,`\u2713 ${r}`,n,o)}failure(e,r,n,o){this.error(e,`\u2717 ${r}`,n,o)}},u=new St});var es,$r,Hr=te(()=>{"use strict";es=require("bun:sqlite");_();$r=5e3});var Ac={};gi(Ac,{generateContext:()=>ui,generateContextWithStats:()=>nr});module.exports=Si(Ac);var oi=oe(require("path"),1),ii=require("os"),ut=require("fs"),si=require("bun:sqlite");T();_();var k=oe(require("path"),1),se=require("fs"),$e=require("os"),Mt=require("child_process");he();T();var re=require("fs"),q=require("path"),Ae=require("os");var U={HEALTH_CHECK:3e3,API_REQUEST:3e4,SESSION_INIT_HOOK_CAP:15e3,SESSION_INIT_REQUEST:1e4,SESSION_INIT_REQUEST_MAX:14e3,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5};function vi(t=process.platform){return t==="win32"?8e3:5e3}function ht(t=process.platform){return U.SESSION_INIT_HOOK_CAP-vi(t)}function G(t){return process.platform==="win32"?Math.round(t*U.WINDOWS_MULTIPLIER):t}$();_();function gr(t){try{return new URL(t).hostname.toLowerCase()==="openrouter.ai"}catch{return!1}}Ie();var Li="security_alert",ki="sync-hub.black-pond-afbb.workers.dev",Ii="ziczmqtpmaxbornfghye.supabase.co",Pi="https://sync.cmem.ai",xi=new Set(["xiaomi/mimo-v2-flash:free"]);function Ni(t){return typeof t=="boolean"?String(t):t}function Ui(t){let e=t.CLAUDE_MEM_OPENROUTER_MODEL;if(typeof e!="string"||!xi.has(e.trim()))return!1;let r=typeof t.CLAUDE_MEM_OPENROUTER_BASE_URL=="string"?t.CLAUDE_MEM_OPENROUTER_BASE_URL.trim():"";return r===""||gr(r)}var Sr=18e4,hr=[{key:"CLAUDE_MEM_LLM_TIMEOUT_MS",legacy:"30000",markerTag:"llm-timeout-migrated-v1"},{key:"CLAUDE_MEM_FIELD_OPTIMIZE_TIMEOUT_MS",legacy:"30000",markerTag:"field-optimize-timeout-migrated-v1"}];function Ar(t,e){return(0,q.join)((0,q.dirname)(t),`.${(0,q.basename)(t)}.${e.markerTag}`)}function yt(t,e){try{(0,re.writeFileSync)(Ar(t,e),new Date().toISOString(),{encoding:"utf-8",mode:384})}catch{}}var yr=new Set;function $i(t){if(typeof t!="string")return null;let e=t.trim();if(e.length===0)return null;try{let r=new URL(e).hostname;if(r===ki||r===Ii)return Pi}catch{return null}return null}var b=class{static DEFAULTS={CLAUDE_MEM_MEMORY_SEARCH_HOOK_ENABLED:"true",CLAUDE_MEM_MEMORY_INSTRUCTIONS_ENABLED:"true",CLAUDE_MEM_MEMORY_WATCH_ROOTS:"",CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_SESSION_START_INCLUDE_ALL_SOURCES:"false",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_WORKER_INGEST_TOKEN:"",CLAUDE_MEM_HOOK_SPOOL_TRANSPORT:"auto",CLAUDE_MEM_ALLOWED_ORIGINS:"",CLAUDE_MEM_PUBLIC_URL:"",CLAUDE_MEM_API_TIMEOUT_MS:String(G(U.API_REQUEST)),CLAUDE_MEM_SESSION_INIT_TIMEOUT_MS:String(ht()),CLAUDE_MEM_IDLE_EXIT_SEC:"0",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_SKIP_BASH_PATTERNS:"",CLAUDE_MEM_SKIP_SUBAGENT_OBSERVATIONS:"false",CLAUDE_MEM_SKIP_AGENT_TYPES:"",CLAUDE_MEM_CAPTURE_ADVISOR_CALLS:"false",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CODEX_MODEL:"",CLAUDE_MEM_CODEX_PATH:"codex",CLAUDE_MEM_CODEX_REASONING_EFFORT:"low",CLAUDE_MEM_CODEX_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_CODEX_OBSERVATION_BATCH_SIZE:"8",CLAUDE_MEM_CODEX_OBSERVATION_BATCH_MAX_CHARS:"32000",CLAUDE_MEM_CLAUDE_OBSERVATION_BATCH_SIZE:"1",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_API_KEYS:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-flash-latest",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_API_KEYS:"",CLAUDE_MEM_OPENROUTER_MODEL:"cohere/north-mini-code:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_TEMPERATURE:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_EXTRA_BODY:"",CLAUDE_MEM_OPENROUTER_REASONING_EFFORT:"",CLAUDE_MEM_OPENAI_COMPAT_PRESET:"",CLAUDE_MEM_OPENAI_COMPAT_API_KEY:"",CLAUDE_MEM_OPENAI_COMPAT_API_KEYS:"",CLAUDE_MEM_OPENAI_COMPAT_BASE_URL:"",CLAUDE_MEM_OPENAI_COMPAT_MODEL:"",CLAUDE_MEM_QUOTA_FALLBACK_PROVIDER:"claude",CLAUDE_MEM_QUOTA_FALLBACK_MODEL:"",CLAUDE_MEM_QUOTA_THRESHOLD_FIVE_HOUR:"0.95",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY:"0.93",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY_OPUS:"0.93",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY_SONNET:"0.92",CLAUDE_MEM_QUOTA_THRESHOLD_OVERAGE:"0.95",CLAUDE_MEM_DATA_DIR:(0,q.join)((0,Ae.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_CLAUDE_CONFIG_DIR:"",CLAUDE_MEM_OBSERVER_CLAUDE_CONFIG_DIR:"",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_OBSERVATION_TYPES:"",CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:"",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_MAIN_AGENT_ONLY:"true",CLAUDE_MEM_REINFORCE_ALPHA:"0",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_WORK_STATE_ENABLED:"true",CLAUDE_MEM_FILE_READ_GATE_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,q.join)((0,Ae.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_CODEX_SUBAGENT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_OBSERVER_MAX_CONVERSATION_CHARS:"400000",CLAUDE_MEM_OBSERVER_THINKING:"disabled",CLAUDE_MEM_OBSERVER_CONTEXT_WINDOW:"",CLAUDE_MEM_OBSERVER_MAX_OUTPUT_TOKENS:"4096",CLAUDE_MEM_OBSERVE_BARE_PROMPTS:"false",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_REDACT_ENABLED:"false",CLAUDE_MEM_REDACT_DISABLED_BUILTINS:"",CLAUDE_MEM_REDACT_CUSTOM_PATTERNS:"[]",CLAUDE_MEM_REDACT_LOG_MATCHES:"false",CLAUDE_MEM_REDACT_GENERIC_ENABLED:"false",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_PROJECT_ENVIRONMENTS:"[]",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_SEMANTIC_INJECT_FORMAT:"narrative",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_CHROMA_MUTATION_TIMEOUT_MS:"600000",CLAUDE_MEM_CHROMA_MAX_PENDING_MUTATIONS:"5000",CLAUDE_MEM_CHROMA_EMBEDDING_FUNCTION:"default",CLAUDE_MEM_CHROMA_UVX_PATH:"",CLAUDE_MEM_SEARCH_RECENCY_DAYS:"90",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,Ae.hostname)(),CLAUDE_MEM_CLOUD_SYNC_WS:"true",CLAUDE_MEM_CLOUD_SYNC_CONTENT_BATCH_SIZE:"40",CLAUDE_MEM_CLOUD_SYNC_REQUEST_TIMEOUT_MS:"90000",CLAUDE_MEM_TEAMBRAIN_URL:"",CLAUDE_MEM_TEAMBRAIN_TEAM_ID:"",CLAUDE_MEM_LLM_TIMEOUT_MS:String(Sr),CLAUDE_MEM_FIELD_OPTIMIZE_TIMEOUT_MS:String(Sr),CLAUDE_MEM_LLM_STREAM_IDLE_TIMEOUT_MS:"90000",CLAUDE_MEM_WORKER_HEARTBEAT_STALE_MS:"120000",CLAUDE_MEM_TV_TOKEN:"",CLAUDE_MEM_PRO_TRIAL_EMAIL:"",CLAUDE_MEM_PRO_TRIAL_AT:"",CLAUDE_MEM_PRO_TRIAL_STATE:"",CLAUDE_MEM_PRO_TRIAL_ENDS_AT:"",CLAUDE_MEM_PRO_PLAN:"",CLAUDE_MEM_PRO_FALLBACK_AT:"",CLAUDE_MEM_PRO_FALLBACK_MESSAGE:"",CLAUDE_MEM_PRO_FALLBACK_ACTION:"",CLAUDE_MEM_PRO_FALLBACK_URL:"",CLAUDE_MEM_PRO_MEMORY_KEY:"",CLAUDE_MEM_PRO_MEMORY_BASE_URL:"",CLAUDE_MEM_PRO_MEMORY_MODEL:"",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_WRAPUPS_ENABLED:"true",CLAUDE_MEM_TELEGRAM_OBSERVATION_ALERTS_ENABLED:"false",CLAUDE_MEM_TELEGRAM_WRAPUP_ROUTES:"{}",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert,sensitive",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_AWARENESS_ENABLED:"true",CLAUDE_MEM_GROK_BOT_AWARENESS_AGENT_IDS:"521e962d-2ec3-4488-bfbc-54d5209ce118,95601360-61f7-4fd9-bb3a-2c976b2b85c0",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_WEBHOOK_URL:"",CLAUDE_MEM_GROK_BOT_WEBHOOK_SECRET:"",CLAUDE_MEM_GROK_BOT_INJECT_ENABLED:"true",CLAUDE_MEM_GROK_BOT_INJECT_AGENT_IDS:"*",CLAUDE_MEM_GROK_BOT_INJECT_TIER:"episode",CLAUDE_MEM_GROK_BOT_INJECT_WINDOW:"80",CLAUDE_MEM_GROK_BOT_INJECT_FALLBACK:"house",CLAUDE_MEM_GROK_BOT_INJECT_PLATFORM_SOURCE:"",CLAUDE_MEM_GROK_BOT_INJECT_PROJECTS_BY_AGENT:"",CLAUDE_MEM_GROK_BOT_INJECT_MAX_LINE_CHARS:"160",CLAUDE_MEM_GROK_BOT_INJECT_DEBOUNCE_MS:"1500",CLAUDE_MEM_GROK_BOT_INJECT_STANDING_LINE:"",CLAUDE_MEM_CCS_ALIGN_ENABLED:"true",CLAUDE_MEM_CCS_ALIGN_VIEWER_IDS:"ccs-align",CLAUDE_MEM_CCS_ALIGN_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_CCS_ALIGN_PATCH_SHADOWS:"false",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:"",CLAUDE_MEM_DEDUP_ENABLED:"false",CLAUDE_MEM_DEDUP_COSINE_THRESHOLD:"0.80",CLAUDE_MEM_DEDUP_IDF_VETO_DF:"10",CLAUDE_MEM_DEDUP_MIN_SHARED_TOKENS:"2",CLAUDE_MEM_DEDUP_MIN_PROJECT_DOCS:"10",CLAUDE_MEM_DEDUP_MAX_SCAN:"2000",CLAUDE_MEM_DEDUP_MAX_BACKFILL_ROWS:"50000",CLAUDE_MEM_TOOL_USES_RETENTION_DAYS:"0",CLAUDE_MEM_WORKER_AUTOSTART:"true",CLAUDE_MEM_PROJECT_NAME_SOURCE:"path"};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){let r=process.env[e]??this.DEFAULTS[e];return e==="CLAUDE_MEM_WORKER_HOST"?this.normalizeWorkerHost(r):r}static normalizeWorkerHost(e){return e==="localhost"?"127.0.0.1":e}static finalizeSettings(e,r){let n=r?this.applyEnvOverrides(e):e;return n.CLAUDE_MEM_WORKER_HOST=this.normalizeWorkerHost(n.CLAUDE_MEM_WORKER_HOST),n}static getInt(e){let r=this.get(e);return parseInt(r,10)}static applyEnvOverrides(e){let r={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(r[n]=process.env[n]);return r}static loadFromFile(e,r=!0,n={}){try{if(!(0,re.existsSync)(e)){let f=this.getAllDefaults();if(!n.readOnly)try{N(e,f,{mode:384});for(let E of hr)yt(e,E);console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(E){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,E instanceof Error?E.message:String(E))}return this.finalizeSettings(f,r)}let o=(0,re.readFileSync)(e,"utf-8"),i=ke(o),s=ie(i),a=s!==i,c=cr(i),l=a&&Object.keys(c).some(f=>f!=="env");if(a&&!l&&!n.readOnly)try{N(e,s,{mode:384}),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(f){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,f instanceof Error?f.message:String(f))}if(s.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES===Li&&(s={...s,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES},!n.readOnly))try{N(e,l?{...c,env:s}:s,{mode:384}),console.warn("[SETTINGS] Migrated Telegram trigger types off the legacy default:",e)}catch(f){console.warn("[SETTINGS] Failed to migrate Telegram trigger types:",e,f instanceof Error?f.message:String(f))}if(Ui(s)){let f=String(s.CLAUDE_MEM_OPENROUTER_MODEL).trim();if(s={...s,CLAUDE_MEM_OPENROUTER_MODEL:this.DEFAULTS.CLAUDE_MEM_OPENROUTER_MODEL},!n.readOnly)try{N(e,l?{...c,env:s}:s,{mode:384}),console.warn(`[SETTINGS] Migrated OpenRouter model off the retired default ${f} to ${this.DEFAULTS.CLAUDE_MEM_OPENROUTER_MODEL}:`,e)}catch(E){console.warn("[SETTINGS] Failed to migrate the retired OpenRouter model:",e,E instanceof Error?E.message:String(E))}}let d=$i(s.CLAUDE_MEM_CLOUD_SYNC_HUB_URL);if(d!==null&&(s={...s,CLAUDE_MEM_CLOUD_SYNC_HUB_URL:d},!n.readOnly))try{N(e,l?{...c,env:s}:s,{mode:384}),console.warn("[SETTINGS] Migrated cloud sync hub URL to",d,"from a retired hub host:",e)}catch(f){console.warn("[SETTINGS] Failed to migrate cloud sync hub URL:",e,f instanceof Error?f.message:String(f))}for(let f of hr)if(!(0,re.existsSync)(Ar(e,f))){if(s[f.key]!==f.legacy){n.readOnly||yt(e,f);continue}if(s={...s,[f.key]:this.DEFAULTS[f.key]},!n.readOnly)try{N(e,l?{...c,env:s}:s,{mode:384}),yt(e,f),console.warn(`[SETTINGS] Migrated ${f.key} off the old ${f.legacy}ms default to ${this.DEFAULTS[f.key]}ms:`,e)}catch(E){let S=`${f.key}\0${e}`;yr.has(S)||(yr.add(S),console.warn(`[SETTINGS] Failed to migrate ${f.key}; using the new default in memory (reported once per process):`,e,E instanceof Error?E.message:String(E)))}}let p={...this.DEFAULTS};for(let f of Object.keys(this.DEFAULTS))s[f]!==void 0&&(p[f]=Ni(s[f]));return this.finalizeSettings(p,r)}catch(o){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,o instanceof Error?o.message:String(o));let i=this.getAllDefaults();return this.finalizeSettings(i,r)}}};_();var xe=require("fs"),X=oe(require("path"),1);_();var Te={isWorktree:!1,isSubmodule:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function Tr(t){let e=X.default.join(t,".git"),r;try{r=(0,xe.statSync)(e)}catch(c){return c instanceof Error&&c.code!=="ENOENT"&&u.warn("GIT","Unexpected error checking .git",{error:c instanceof Error?c.message:String(c)}),Te}if(!r.isFile())return Te;let n;try{n=(0,xe.readFileSync)(e,"utf-8").trim()}catch(c){return u.warn("GIT","Failed to read .git file",{error:c instanceof Error?c.message:String(c)}),Te}let o=n.match(/^gitdir:\s*(.+)$/);if(!o)return Te;let i=X.default.resolve(X.default.dirname(e),o[1]),s=i.match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(s){let c=s[1];return{isWorktree:!0,isSubmodule:!1,worktreeName:X.default.basename(t),parentRepoPath:c,parentProjectName:X.default.basename(c)}}let a=i.match(/^(.+)[/\\]\.git[/\\]modules[/\\](.+)$/);if(a){let c=a[1];return{isWorktree:!1,isSubmodule:!0,worktreeName:X.default.basename(t),parentRepoPath:c,parentProjectName:X.default.basename(c)}}return Te}var Or=require("fs");var Mr=require("path");he();_();function Cr(t){let e=H(t.replace(/\\/g,"/"));e=e.replace(/\\/g,"/");let r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return r=r.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${r}$`)}function Hi(t,e,r){let n=Cr(t);return n.test(e)||n.test(r)?!0:t.replace(/\\/g,"/").endsWith("/**")?Cr(t.slice(0,-3)).test(e.replace(/\/+$/,"")):!1}function br(t,e){if(!e.length)return!1;let r=t.replace(/\\/g,"/"),n=(0,Mr.basename)(r);for(let o of e){let i=o.trim();if(i)try{if(Hi(i,r,n))return!0}catch(s){u.warn("PROJECT_NAME","Invalid glob pattern",{pattern:i,error:s instanceof Error?s.message:String(s)});continue}}return!1}_();function Rr(t){let e=t;if(typeof e=="string"){if(!e.trim())return[];try{e=JSON.parse(e)}catch(n){return u.warn("PROJECT_NAME","CLAUDE_MEM_PROJECT_ENVIRONMENTS is not valid JSON; ignoring it",{error:n instanceof Error?n.message:String(n)}),[]}}if(!Array.isArray(e))return e!=null&&u.warn("PROJECT_NAME","CLAUDE_MEM_PROJECT_ENVIRONMENTS must be an array; ignoring it",{}),[];let r=[];for(let n of e){let o=typeof n?.name=="string"?n.name.trim():"",i=Array.isArray(n?.patterns)?n.patterns.filter(s=>typeof s=="string"&&s.trim()!==""):[];if(!o||i.length===0){u.warn("PROJECT_NAME","Ignoring a project environment without a name or patterns",{name:o});continue}r.push({name:o,patterns:i})}return r}function Fi(t){try{return(0,Or.realpathSync)(t)}catch{return t}}function At(t,e){if(e.length===0)return null;let r=[...new Set([t,Fi(t)])].flatMap(n=>[n,`${n.replace(/[\\/]+$/,"")}/`]);for(let n of e)if(r.some(o=>br(o,n.patterns)))return n.name;return null}var bt="unknown-project";function vr(t){try{return(0,Mt.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim()||null}catch(e){let r=e instanceof Error?e:new Error(String(e));return u.debug("PROJECT_NAME","git rev-parse failed, falling back to non-git root",{dir:t},r),null}}var Wi=[".claude-mem-project",".claude-mem.json"],ji=64;function Lr(t){try{return(0,se.realpathSync)(t)}catch{return t}}function Bi(t,e){let r=k.default.relative(e,t);return r===""||!r.startsWith("..")&&!k.default.isAbsolute(r)}function Ki(){return[(0,$e.homedir)(),(0,$e.tmpdir)(),B].flatMap(t=>{let e=k.default.resolve(t);return[e,Lr(e)]})}function kr(t){let e=Ki(),r=k.default.resolve(t);if([k.default.resolve(B),Lr(k.default.resolve(B))].some(o=>Bi(r,o)))return null;for(let o=0;o<ji;o++){if(e.includes(r))return null;let i=k.default.dirname(r);if(i===r)return null;if(Wi.some(s=>(0,se.existsSync)(k.default.join(r,s))))return r;r=i}return null}function Ct(t,e){let r=k.default.basename(e);if(r===""){if(process.platform==="win32"){let o=t.match(/^([A-Z]):\\/i);if(o){let s=`drive-${o[1].toUpperCase()}`;return u.info("PROJECT_NAME","Drive root detected",{cwd:t,projectName:s}),s}}return u.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:t}),bt}return r}var Gi="CLAUDE_MEM_PROJECT_NAME_SOURCE",Ne=null;function wr(){try{return(0,se.statSync)(K).mtimeMs}catch{return-1}}function Ir(){let t=wr();if(t===-1)return b.getAllDefaults();if(Ne&&Ne.mtimeMs===t)return Ne.settings;let e=b.loadFromFile(K);return Ne={mtimeMs:wr(),settings:e},e}function Yi(){let t=process.env[Gi]??Ir().CLAUDE_MEM_PROJECT_NAME_SOURCE;return String(t??"path").trim().toLowerCase()==="git-remote"}var Ji="CLAUDE_MEM_PROJECT_ENVIRONMENTS",Ue=null;function He(){let t=process.env[Ji]??Ir().CLAUDE_MEM_PROJECT_ENVIRONMENTS;return(!Ue||Ue.raw!==t)&&(Ue={raw:t,environments:Rr(t)}),Ue.environments}function Vi(t){let e=(t??"").trim();if(!e||/^file:/i.test(e)||e.startsWith("/")||e.startsWith(".")||e.startsWith("~")||e.startsWith("\\\\")||/^[a-z]:[\\/]/i.test(e))return null;let n=e.replace(/\/+$/,"").replace(/\.git$/i,""),o=n.match(/^[a-z][a-z0-9+.-]*:\/\/[^/]+\/(.+)$/i),i=o?null:n.match(/^(?:[^/@\s]+@)?[^:/\s]+:(?!\/\/)(.+)$/),s=o?.[1]??i?.[1];if(!s)return null;let a=s.split("/").filter(c=>c&&c!=="_git");return a.length>=2?a.slice(-2).join("/"):a.length===1?a[0]:null}function qi(t){try{let e=(0,Mt.execFileSync)("git",["remote","get-url","origin"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim();return Vi(e)}catch(e){let r=e instanceof Error?e:new Error(String(e));return u.debug("PROJECT_NAME","No usable origin remote, keeping the path-based name",{repoRoot:t},r),null}}var Tt=new Map;function Pr(t){return Yi()?(Tt.has(t)||Tt.set(t,qi(t)),Tt.get(t)??null):null}function Xi(t,e=process.platform){if(!t||t.trim()==="")return u.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),bt;let r=H(t,e),n=At(r,He());if(n)return n;let o=vr(r),i=o?Pr(o):null;if(i)return i;let s=o??kr(r)??r;return Ct(t,s)}function xr(t,e){return e===t?t:`${t}/${e}`}function zi(t,e){if(!t.isSubmodule||!t.parentRepoPath)return null;let r=k.default.relative(t.parentRepoPath,e);return!r||r.startsWith("..")||k.default.isAbsolute(r)?null:r.split(k.default.sep).join("/")}function Nr(t,e=process.platform){if(!t||t.trim()===""){let c=Xi(t,e);return{primary:c,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[c],keySource:"path"}}let r=H(t,e),n=vr(r),o=Qi(t,r,n),i=n?Pr(n):null,s=i?Dr(o,i,"git-remote"):o,a=At(r,He());return a?Dr(s,a,"environment"):s}function Dr(t,e,r){return{primary:e,parent:null,isWorktree:t.isWorktree,isSubmodule:t.isSubmodule,allProjects:[...t.allProjects.filter(n=>n!==e),e],keySource:r}}function Qi(t,e,r){let n=r?null:kr(e),o=Ct(t,r??n??e),i=r??e,s=Tr(i);if((s.isWorktree||s.isSubmodule)&&s.parentProjectName){let a=s.parentProjectName,c,l;return s.isSubmodule?(c=`${a}/${zi(s,i)??o}`,l=o!==a?[o]:[]):(c=xr(a,o),l=c===a?[`${a}/${o}`]:[]),{primary:c,parent:a,isWorktree:s.isWorktree,isSubmodule:s.isSubmodule,allProjects:[...new Set([a,...l,c])].filter(d=>d!==c).concat(c),keySource:"path"}}if(n&&k.default.resolve(n)!==k.default.resolve(e)){let a=Ct(t,e);if(a!==o&&a!==bt)return{primary:o,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[a,o],keySource:"path"}}return{primary:o,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[o],keySource:"path"}}var Ur="claude";function Zi(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Fe(t){if(!t)return Ur;let e=Zi(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e.includes("kimi")?"kimi":e==="pi-mono"?"pi":e==="agy"||e==="antigravity"||e.startsWith("antigravity-")?"antigravity-cli":e:Ur}Hr();function ts(t){let e=t.projects?.length?t.projects:t.project?[t.project]:[];return[...new Set(e.map(r=>r.trim()).filter(Boolean))]}var rs=4;function Fr(t,e){let r=ts({projects:e});if(r.length===0)return[];let n=r.map(()=>"?").join(","),o=[[`SELECT project AS key FROM sdk_sessions WHERE project COLLATE NOCASE IN (${n})`,1],[`SELECT project FROM observations WHERE project COLLATE NOCASE IN (${n})`,1],[`SELECT merged_into_project FROM observations WHERE merged_into_project COLLATE NOCASE IN (${n})`,1],[`SELECT project FROM session_summaries WHERE project COLLATE NOCASE IN (${n})`,1],[`SELECT merged_into_project FROM session_summaries WHERE merged_into_project COLLATE NOCASE IN (${n})`,1],[`SELECT candidates.key FROM (
|
|
15
15
|
SELECT project AS key FROM observations WHERE merged_into_project COLLATE NOCASE IN (${n})
|
|
16
16
|
UNION
|
|
17
17
|
SELECT project AS key FROM session_summaries WHERE merged_into_project COLLATE NOCASE IN (${n})
|
|
@@ -24,7 +24,7 @@ ${S.stack??""}
|
|
|
24
24
|
WHERE project COLLATE NOCASE = candidates.key AND merged_into_project COLLATE NOCASE IN (${n}))
|
|
25
25
|
+ (SELECT COUNT(*) FROM session_summaries
|
|
26
26
|
WHERE project COLLATE NOCASE = candidates.key AND merged_into_project COLLATE NOCASE IN (${n}))
|
|
27
|
-
)`,rs]],i=t.prepare(o.map(([s])=>s).join(" UNION "));try{let s=i.all(...o.flatMap(([,a])=>Array(a).fill(r).flat()));return[...new Set([...r,...s.map(a=>a.key)])]}finally{i.finalize()}}var m={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",cyan:"\x1B[36m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",gray:"\x1B[90m",red:"\x1B[31m"},Wr=4,ae=1;T();var le=require("fs"),F=require("path");g();T();var ns=["system_identity","spatial_awareness","observer_role","recording_focus","skip_guidance","type_guidance","concept_guidance","field_guidance","output_format_header","format_examples","footer","xml_title_placeholder","xml_subtitle_placeholder","xml_fact_placeholder","xml_narrative_placeholder","xml_concept_placeholder","xml_file_placeholder","xml_summary_request_placeholder","xml_summary_investigated_placeholder","xml_summary_learned_placeholder","xml_summary_completed_placeholder","xml_summary_next_steps_placeholder","xml_summary_notes_placeholder","header_memory_start","header_memory_continued","header_summary_checkpoint","continuation_greeting","continuation_instruction","summary_instruction","summary_context_label","summary_format_instruction","summary_footer"],os=/^[a-z0-9]+(?:[-_][a-z0-9]+)*$/;function Ot(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function jr(t){if(!Ot(t))return["mode (must be an object)"];let e=[],r=(o,i,s=!1)=>{(typeof o!="string"||!s&&o.trim().length===0)&&e.push(i)};for(let o of["name","description","version"])r(t[o],o);let n=Ot(t.prompts)?t.prompts:{};for(let o of ns)r(n[o],`prompts.${o}`,o==="format_examples"||o==="xml_file_placeholder");for(let[o,i,s]of[["observation_types",["id","label","description","emoji","work_emoji"],"type_guidance"],["observation_concepts",["id","label","description"],"concept_guidance"]]){let a=t[o];if(!Array.isArray(a)||a.length===0){e.push(`${o} (must contain at least one item)`);continue}let c=new Set;for(let[l,d]of a.entries()){let p=`${o}[${l}]`;if(!Ot(d)){e.push(`${p} (must be an object)`);continue}for(let E of i)r(d[E],`${p}.${E}`);if(typeof d.id!="string"||!d.id.trim())continue;os.test(d.id)||e.push(`${p}.id (must be lowercase words separated by hyphens or underscores)`),c.has(d.id)&&e.push(`${p}.id (duplicate: ${d.id})`),c.add(d.id);let f=n[s];typeof f=="string"&&!f.includes(d.id)&&e.push(`prompts.${s} (must mention ${d.id})`)}}return e}var is=/^[a-z0-9]+(?:-[a-z0-9]+)*(?:--[a-z0-9]+(?:-[a-z0-9]+)*)?$/,ce=class extends Error{},w=class t{static instance=null;activeMode=null;activeModeId=null;bundledModeDirs;userModesDir;overrideModesDir;constructor(){let e=pr();this.overrideModesDir=process.env.CLAUDE_MEM_MODES_DIR,this.userModesDir=(0,F.join)(A.dataDir(),"modes"),this.bundledModeDirs=[...new Set([(0,F.join)(e,"modes"),(0,F.join)(e,"..","plugin","modes")])]}static getInstance(){return t.instance||(t.instance=new t),t.instance}parseInheritance(e){let r=e.split("--");if(r.length===1)return{hasParent:!1,parentId:"",overrideId:""};if(r.length>2)throw new Error(`Invalid mode inheritance: ${e}. Only one level of inheritance supported (parent--override)`);return{hasParent:!0,parentId:r[0],overrideId:e}}isPlainObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}deepMerge(e,r){let n={...e};for(let o in r){let i=r[o],s=e[o];this.isPlainObject(i)&&this.isPlainObject(s)?n[o]=this.deepMerge(s,i):n[o]=i}return n}loadModeFile(e,r=!1){if(!is.test(e))throw new Error(`Invalid mode ID: ${e}`);let n=this.bundledModeDirs.map(l=>(0,F.join)(l,`${e}.json`)).find(l=>(0,le.existsSync)(l)),o=e==="code"||!!n,i=(0,F.join)(this.userModesDir,`${e}.json`),s=this.overrideModesDir&&(0,F.resolve)(this.overrideModesDir)===(0,F.resolve)(this.userModesDir);o&&(0,le.existsSync)(i)&&(r||!s)&&u.error("SYSTEM",`Ignoring user mode file ${i}: bundled mode '${e}' cannot be shadowed. Use a ${e.split("--")[0]}--<name> override instead.`);let a=r?this.bundledModeDirs:[...this.overrideModesDir?[this.overrideModesDir]:[],...o?[]:[this.userModesDir],...this.bundledModeDirs],c=a.map(l=>(0,F.join)(l,`${e}.json`)).find(l=>(0,le.existsSync)(l));if(!c)throw new Error(`Mode file not found: ${e}.json (searched: ${a.join(", ")})`);try{let l=(0,le.readFileSync)(c,"utf-8");return{mode:JSON.parse(l),path:c}}catch(l){throw new ce(`Could not load mode file ${c}: ${l instanceof Error?l.message:String(l)}`)}}validateMode(e,r){let n=jr(e);if(n.length>0)throw new ce(`Invalid mode (${r.join(", ")}): missing or invalid keys: ${n.join(", ")}`)}loadMode(e){let r;try{let n=this.parseInheritance(e);if(n.hasParent){let o=this.loadModeFile(n.parentId),i=this.loadModeFile(n.overrideId);if(!this.isPlainObject(o.mode)||!this.isPlainObject(i.mode))throw new ce(`Invalid mode (${o.path}, ${i.path}): parent and override must be JSON objects`);r=this.deepMerge(o.mode,i.mode),this.validateMode(r,[o.path,i.path])}else{let o=this.loadModeFile(e);r=o.mode,this.validateMode(r,[o.path])}}catch(n){let o=n instanceof Error?n.message:String(n);if(n instanceof ce)throw u.error("WORKER",`Failed to load mode '${e}': ${o}`),n;u.error("WORKER",`Failed to load mode '${e}': ${o}; falling back to bundled 'code'`);try{let i=this.loadModeFile("code",!0);this.validateMode(i.mode,[i.path]),r=i.mode,e="code"}catch(i){let s=`Critical: could not load bundled 'code' mode: ${i instanceof Error?i.message:String(i)}`;throw u.error("WORKER",s),new Error(s)}}return r.id=e,this.activeMode=r,this.activeModeId=e,u.debug("SYSTEM",`Loaded mode: ${r.name} (${e})`,void 0,{types:r.observation_types.map(n=>n.id),concepts:r.observation_concepts.map(n=>n.id)}),r}getActiveMode(){if(!this.activeMode)throw new Error("No mode loaded. Call loadMode() first.");return this.activeMode}getActiveModeId(){if(!this.activeModeId)throw new Error("No mode loaded. Call loadMode() first.");return this.activeModeId}getObservationTypes(){return this.getActiveMode().observation_types}getTypeIcon(e){return this.getObservationTypes().find(n=>n.id===e)?.emoji||"\u{1F4DD}"}getWorkEmoji(e){return this.getObservationTypes().find(n=>n.id===e)?.work_emoji||"\u{1F4DD}"}};g();function Br(t){let e;if(typeof t=="number")e=t;else if(typeof t=="string"&&/^\d+$/.test(t.trim()))e=Number(t.trim());else return;return Number.isSafeInteger(e)&&e>=0?e:void 0}function ss(t){let e=Number(t);return Number.isFinite(e)&&e>0?e:0}function as(t,e,r){let n=Br(e);return n!==void 0?n:(e!==void 0&&u.warn("CONFIG",`${t} must be a whole number >= 0; using the default`,{value:e,default:r}),Number(r))}function cs(t){let e=(t??"").split(",").map(r=>r.trim()).filter(r=>r!=="");return e.length>0?e:null}function Kr(t,e,r){let n=cs(e);if(!n)return new Set(r);let o=n.filter(s=>r.includes(s)),i=n.filter(s=>!r.includes(s));return i.length>0&&u.warn("CONFIG",`${t} has ids not in the active mode; ignoring them`,{discardedIds:i.join(","),fallingBackToModeList:o.length===0}),new Set(o.length>0?o:r)}function Gr(){let t=A.settings(),e=b.loadFromFile(t),r=w.getInstance().getActiveMode(),n=Kr("CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES",e.CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES,r.observation_types.map(a=>a.id)),o=Kr("CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS",e.CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS,r.observation_concepts.map(a=>a.id)),i=b.getAllDefaults(),s=a=>as(a,e[a],i[a]);return{totalObservationCount:s("CLAUDE_MEM_CONTEXT_OBSERVATIONS"),fullObservationCount:s("CLAUDE_MEM_CONTEXT_FULL_COUNT"),sessionCount:s("CLAUDE_MEM_CONTEXT_SESSION_COUNT"),showReadTokens:e.CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS==="true",showWorkTokens:e.CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS==="true",showSavingsAmount:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT==="true",showSavingsPercent:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT==="true",observationTypes:n,observationConcepts:o,fullObservationField:e.CLAUDE_MEM_CONTEXT_FULL_FIELD,showLastSummary:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY==="true",showLastMessage:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE==="true",mainAgentOnly:e.CLAUDE_MEM_CONTEXT_MAIN_AGENT_ONLY!=="false",reinforcementAlpha:ss(e.CLAUDE_MEM_REINFORCE_ALPHA)}}function ls(t,e){return t.fullObservationCount>0?{config:{...t,fullObservationCount:0},observationCount:e}:t.showLastSummary?{config:{...t,showLastSummary:!1},observationCount:e}:t.showLastMessage?{config:{...t,showLastMessage:!1},observationCount:e}:t.sessionCount>0?{config:{...t,sessionCount:Math.floor(t.sessionCount/2)},observationCount:e}:e>1?{config:t,observationCount:Math.floor(e/2)}:null}function Yr(t,e,r,n=1e4){let o=e,i=t.length,s=r(t,o),a=0;for(;s.length>n;){let c=ls(o,i);if(!c)return{text:s,config:o,observationCount:i,reductions:a,overBudget:!0};o=c.config,i=c.observationCount,s=r(t.slice(0,i),o),a++}return{text:s,config:o,observationCount:i,reductions:a,overBudget:!1}}function Jr(t){let e=(t.title?.length||0)+(t.subtitle?.length||0)+(t.narrative?.length||0)+JSON.stringify(t.facts||[]).length;return Math.ceil(e/Wr)}function Rt(t){let e=t.length,r=t.reduce((s,a)=>s+Jr(a),0),n=t.reduce((s,a)=>s+(a.discovery_tokens||0),0),o=n-r,i=n>0?Math.round(o/n*100):0;return{totalObservations:e,totalReadTokens:r,totalDiscoveryTokens:n,savings:o,savingsPercent:i}}function us(t){return w.getInstance().getWorkEmoji(t)}function Ce(t,e){let r=Jr(t),n=t.discovery_tokens||0,o=us(t.type),i=n>0?`${o} ${n.toLocaleString()}`:"-";return{readTokens:r,discoveryTokens:n,discoveryDisplay:i,workEmoji:o}}function We(t){return t.showReadTokens||t.showWorkTokens||t.showSavingsAmount||t.showSavingsPercent}var pn=oe(require("path"),1),Ge=require("fs");g();g();var Ke=require("fs");g();T();$();var je=String.raw`[A-Za-z0-9_.\-+/=~@#$%^*!?]`,ds=`(?=${je}{8})${je}*[A-Za-z]${je}*`,Be=String.raw`(?:\\{0,3}["'])?`,Oe=String.raw`\s{0,8}`;function wt(t){return new RegExp(`${t}${ds}`,"gi")}function Vr(t){return`(?<=${t}${Be}${Oe}[=:]${Oe}${Be})`}var fs=[{name:"aws_access_key",regex:/AKIA[0-9A-Z]{16}/g},{name:"aws_secret_key",regex:/(?<=AWS_SECRET_ACCESS_KEY\s{0,8}[=:]\s{0,8}['"]?)[A-Za-z0-9/+=]{40}/g},{name:"github_pat",regex:/\bgh[oprs]_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{82}\b/g},{name:"openai_key",regex:/\bsk-(?!ant-)[A-Za-z0-9_-]{20,}\b/g},{name:"anthropic_key",regex:/\bsk-ant-[A-Za-z0-9_-]{20,}\b/g},{name:"slack_token",regex:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g},{name:"jwt",regex:/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g},{name:"private_key_pem",regex:/-----BEGIN (?:RSA |DSA |EC |OPENSSH |PGP )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |DSA |EC |OPENSSH |PGP )?PRIVATE KEY-----/g},{name:"stripe_key",regex:/\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]{24,}\b/g},{name:"google_api_key",regex:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:"claude_mem_key",regex:/\bcmem_[A-Za-z0-9_-]{32,}|\bcm_pro_[A-Za-z0-9_-]{8,}/g}],ms=[{name:"generic_password",regex:wt(Vr(String.raw`\b(?:\w*_?(?:password|passwd)|\w+_pwd)`))},{name:"generic_token",regex:wt(Vr(String.raw`\b\w*_(?:token|secret|api_key)`))},{name:"bearer_token",regex:wt(`(?<=\\bAuthorization${Be}${Oe}:${Oe}${Be}Bearer${Oe})`)}],ps=1024*1024,Es="<redacted type='oversize'/>";function zr(t,e){if(!e.enabled||t.length===0)return{redacted:t,counts:{},oversize:!1};if(t.length>ps)return u.warn("REDACT","field exceeds the 1M-char redaction cap; replaced by an oversize marker",void 0,{inputLength:t.length}),{redacted:Es,counts:{oversize:1},oversize:!0};let r=new Set(e.disabledBuiltinPatterns??[]),n={},o=t,i=[];for(let a of e.customPatterns??[]){if(!a.name||a.name.length===0){u.warn("REDACT","custom pattern skipped: missing name",void 0,{pattern:a});continue}try{i.push({name:a.name,regex:new RegExp(a.regex,"g")})}catch(c){u.warn("REDACT","custom pattern skipped: invalid regex",{name:a.name},c instanceof Error?c:new Error(String(c)))}}let s=[...i,...fs,...e.genericEnabled?ms:[]];for(let a of s)r.has(a.name)||(a.regex.lastIndex=0,o=o.replace(a.regex,()=>(n[a.name]=(n[a.name]??0)+1,`<redacted type='${a.name}'/>`)));return e.logMatches&&Object.keys(n).length>0&&u.debug("REDACT","patterns matched",void 0,{counts:n}),{redacted:o,counts:n,oversize:!1}}function gs(t){if(!t||t.trim()==="")return[];try{let e=JSON.parse(t);return Array.isArray(e)?e.filter(r=>r&&typeof r.name=="string"&&typeof r.regex=="string"):(u.warn("REDACT","CLAUDE_MEM_REDACT_CUSTOM_PATTERNS is not a JSON array, ignoring"),[])}catch(e){return u.warn("REDACT","failed to parse CLAUDE_MEM_REDACT_CUSTOM_PATTERNS as JSON",void 0,e instanceof Error?e:new Error(String(e))),[]}}function _s(t){return{enabled:t.CLAUDE_MEM_REDACT_ENABLED==="true",disabledBuiltinPatterns:(t.CLAUDE_MEM_REDACT_DISABLED_BUILTINS??"").split(",").map(e=>e.trim()).filter(Boolean),customPatterns:gs(t.CLAUDE_MEM_REDACT_CUSTOM_PATTERNS??"[]"),logMatches:t.CLAUDE_MEM_REDACT_LOG_MATCHES==="true",genericEnabled:t.CLAUDE_MEM_REDACT_GENERIC_ENABLED==="true"}}var Me=null,qr=0,Ss=5e3,be=null,Xr=!1,hs={enabled:!0,disabledBuiltinPatterns:[],customPatterns:[],logMatches:!1},ys=/"CLAUDE_MEM_REDACT_ENABLED"\s*:\s*"true"/;function As(t){if(!(0,Ke.existsSync)(t))return null;try{return(0,Ke.readFileSync)(t,"utf-8")}catch{return""}}function Ts(t){if(t===null)return!1;try{let e=JSON.parse(ft(t));return e===null||typeof e!="object"||Array.isArray(e)}catch{return!0}}function Cs(t,e,r){return process.env.CLAUDE_MEM_REDACT_ENABLED==="false"||!(be?.enabled===!0||ys.test(e))?r:(Xr||(Xr=!0,u.warn("REDACT","settings.json could not be read; secret redaction stays on until it is repaired",{settingsPath:t,using:be?.enabled?"the last configuration that loaded":"the built-in patterns"})),be?.enabled?be:hs)}function Qr(t=K){let e=Date.now();if(Me&&e-qr<Ss)return Me;let r=b.loadFromFile(t),n=_s(r),o=n.enabled?null:As(t);return Ts(o)?Me=Cs(t,o,n):(Me=n,be=n),qr=e,Me}var $l=new RegExp(`^${je}{8,}$`);var Dt=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],Ms=new Set(Dt),Zr=/<([A-Za-z_][A-Za-z0-9_-]*)/y,en=/<\/([A-Za-z_][A-Za-z0-9_-]*)\s*>/y;function bs(t){let e=Object.fromEntries(Dt.map(d=>[d,0]));if(!t.includes("<"))return{text:t,counts:e,total:0};let r=t.length,n=new Int32Array(r+1);n[r]=r;for(let d=r-1;d>=0;d--)n[d]=t.charCodeAt(d)===62?d:n[d+1];let o=new Map,i=[],s=0,a=0;for(;a<r;){if(t.charCodeAt(a)!==60){a+=1;continue}en.lastIndex=a;let d=en.exec(t);if(d){let f=d[1],E=o.get(f),S=E&&E.head<E.items.length?E.items[E.head]:void 0;S&&a>=S.attrEnd&&(E.head+=1,i.push([S.start,a+d[0].length]),e[f]+=1,s+=1),a+=d[0].length;continue}Zr.lastIndex=a;let p=Zr.exec(t);if(p&&Ms.has(p[1])){let f=p[1],E=a+p[0].length,S={start:a,attrEnd:n[E]},R=o.get(f);R?R.items.push(S):o.set(f,{items:[S],head:0}),a=E;continue}a+=1}i.sort((d,p)=>d[0]-p[0]);let c="",l=0;for(let[d,p]of i)d>l&&(c+=t.slice(l,d)),p>l&&(l=p);return c+=t.slice(l),{text:c,counts:e,total:s}}var rn=/<system-reminder>[\s\S]*?<\/system-reminder>/g,tn=100;function Os(t){let{text:e,counts:r,total:n}=bs(t);return n>tn&&u.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:n,maxAllowed:tn,contentLength:t.length}),{stripped:zr(e.trim(),Qr()).redacted,counts:r}}function Rs(t){return Os(t).stripped}var ws=new RegExp(`<(${Dt.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`);function vt(t){let e=r=>typeof r=="string"?ws.test(r)?Rs(r):r:Array.isArray(r)?r.map(e):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).map(([n,o])=>[n,e(o)])):r;return e(t)}var Ds=["task-notification"],jl=new RegExp(`^\\s*<(${Ds.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),Bl=256*1024;T();function nn(t){return`(COALESCE(${t}.agent_id, '') = '' OR COALESCE(${t}.agent_type, '') = '')`}function on(t,e){let r=Date.parse(t);if(Number.isNaN(r))return 1;let n=Math.floor((e.getTime()-r)/864e5);return n<1?1:n}function sn(t){if(!t)return[];try{let e=JSON.parse(t);return Array.isArray(e)?e.filter(r=>typeof r=="string"&&r.length>0):[]}catch{return[]}}function an(t=new Date){return t.toISOString().slice(0,10)}var vs=864e5,Ls=5,cn=500;function un(t,e){return!(e>0)||t>=cn?t:Math.min(cn,Math.max(t,t*Ls))}function ks(t,e){let r=Math.max(1,Math.floor((e.getTime()-t)/vs));return Math.pow(r,-.5)}function Is(t,e,r){let n=ks(t.created_at_epoch,e),o=sn(t.reinforcement_dates),i=an(new Date(t.created_at_epoch)),s=0;for(let a of o)a!==i&&(s+=Math.pow(on(a,e),-.5));return Math.log(1+n+r*s)}function Ps(t){return Math.max(1,Math.ceil(t/4))}function dn(t,e,r,n=new Date){if(t.length<=e)return t;if(!(r>0))return t.slice(0,e);let o=t.slice(0,Math.min(e,Ps(e))),i=t.slice(o.length).map((a,c)=>({item:a,i:c,score:Is(a,n,r)}));return i.sort((a,c)=>c.score-a.score||c.item.created_at_epoch-a.item.created_at_epoch||a.i-c.i),[...o,...i.slice(0,e-o.length).map(a=>a.item)].sort((a,c)=>c.created_at_epoch-a.created_at_epoch)}var fn=`
|
|
27
|
+
)`,rs]],i=t.prepare(o.map(([s])=>s).join(" UNION "));try{let s=i.all(...o.flatMap(([,a])=>Array(a).fill(r).flat()));return[...new Set([...r,...s.map(a=>a.key)])]}finally{i.finalize()}}var m={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",cyan:"\x1B[36m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",gray:"\x1B[90m",red:"\x1B[31m"},Wr=4,ae=1;T();var le=require("fs"),F=require("path");_();T();var ns=["system_identity","spatial_awareness","observer_role","recording_focus","skip_guidance","type_guidance","concept_guidance","field_guidance","output_format_header","format_examples","footer","xml_title_placeholder","xml_subtitle_placeholder","xml_fact_placeholder","xml_narrative_placeholder","xml_concept_placeholder","xml_file_placeholder","xml_summary_request_placeholder","xml_summary_investigated_placeholder","xml_summary_learned_placeholder","xml_summary_completed_placeholder","xml_summary_next_steps_placeholder","xml_summary_notes_placeholder","header_memory_start","header_memory_continued","header_summary_checkpoint","continuation_greeting","continuation_instruction","summary_instruction","summary_context_label","summary_format_instruction","summary_footer"],os=/^[a-z0-9]+(?:[-_][a-z0-9]+)*$/;function Ot(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function jr(t){if(!Ot(t))return["mode (must be an object)"];let e=[],r=(o,i,s=!1)=>{(typeof o!="string"||!s&&o.trim().length===0)&&e.push(i)};for(let o of["name","description","version"])r(t[o],o);let n=Ot(t.prompts)?t.prompts:{};for(let o of ns)r(n[o],`prompts.${o}`,o==="format_examples"||o==="xml_file_placeholder");for(let[o,i,s]of[["observation_types",["id","label","description","emoji","work_emoji"],"type_guidance"],["observation_concepts",["id","label","description"],"concept_guidance"]]){let a=t[o];if(!Array.isArray(a)||a.length===0){e.push(`${o} (must contain at least one item)`);continue}let c=new Set;for(let[l,d]of a.entries()){let p=`${o}[${l}]`;if(!Ot(d)){e.push(`${p} (must be an object)`);continue}for(let E of i)r(d[E],`${p}.${E}`);if(typeof d.id!="string"||!d.id.trim())continue;os.test(d.id)||e.push(`${p}.id (must be lowercase words separated by hyphens or underscores)`),c.has(d.id)&&e.push(`${p}.id (duplicate: ${d.id})`),c.add(d.id);let f=n[s];typeof f=="string"&&!f.includes(d.id)&&e.push(`prompts.${s} (must mention ${d.id})`)}}return e}var is=/^[a-z0-9]+(?:-[a-z0-9]+)*(?:--[a-z0-9]+(?:-[a-z0-9]+)*)?$/,ce=class extends Error{},w=class t{static instance=null;activeMode=null;activeModeId=null;bundledModeDirs;userModesDir;overrideModesDir;constructor(){let e=pr();this.overrideModesDir=process.env.CLAUDE_MEM_MODES_DIR,this.userModesDir=(0,F.join)(A.dataDir(),"modes"),this.bundledModeDirs=[...new Set([(0,F.join)(e,"modes"),(0,F.join)(e,"..","plugin","modes")])]}static getInstance(){return t.instance||(t.instance=new t),t.instance}parseInheritance(e){let r=e.split("--");if(r.length===1)return{hasParent:!1,parentId:"",overrideId:""};if(r.length>2)throw new Error(`Invalid mode inheritance: ${e}. Only one level of inheritance supported (parent--override)`);return{hasParent:!0,parentId:r[0],overrideId:e}}isPlainObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}deepMerge(e,r){let n={...e};for(let o in r){let i=r[o],s=e[o];this.isPlainObject(i)&&this.isPlainObject(s)?n[o]=this.deepMerge(s,i):n[o]=i}return n}loadModeFile(e,r=!1){if(!is.test(e))throw new Error(`Invalid mode ID: ${e}`);let n=this.bundledModeDirs.map(l=>(0,F.join)(l,`${e}.json`)).find(l=>(0,le.existsSync)(l)),o=e==="code"||!!n,i=(0,F.join)(this.userModesDir,`${e}.json`),s=this.overrideModesDir&&(0,F.resolve)(this.overrideModesDir)===(0,F.resolve)(this.userModesDir);o&&(0,le.existsSync)(i)&&(r||!s)&&u.error("SYSTEM",`Ignoring user mode file ${i}: bundled mode '${e}' cannot be shadowed. Use a ${e.split("--")[0]}--<name> override instead.`);let a=r?this.bundledModeDirs:[...this.overrideModesDir?[this.overrideModesDir]:[],...o?[]:[this.userModesDir],...this.bundledModeDirs],c=a.map(l=>(0,F.join)(l,`${e}.json`)).find(l=>(0,le.existsSync)(l));if(!c)throw new Error(`Mode file not found: ${e}.json (searched: ${a.join(", ")})`);try{let l=(0,le.readFileSync)(c,"utf-8");return{mode:JSON.parse(l),path:c}}catch(l){throw new ce(`Could not load mode file ${c}: ${l instanceof Error?l.message:String(l)}`)}}validateMode(e,r){let n=jr(e);if(n.length>0)throw new ce(`Invalid mode (${r.join(", ")}): missing or invalid keys: ${n.join(", ")}`)}loadMode(e){let r;try{let n=this.parseInheritance(e);if(n.hasParent){let o=this.loadModeFile(n.parentId),i=this.loadModeFile(n.overrideId);if(!this.isPlainObject(o.mode)||!this.isPlainObject(i.mode))throw new ce(`Invalid mode (${o.path}, ${i.path}): parent and override must be JSON objects`);r=this.deepMerge(o.mode,i.mode),this.validateMode(r,[o.path,i.path])}else{let o=this.loadModeFile(e);r=o.mode,this.validateMode(r,[o.path])}}catch(n){let o=n instanceof Error?n.message:String(n);if(n instanceof ce)throw u.error("WORKER",`Failed to load mode '${e}': ${o}`),n;u.error("WORKER",`Failed to load mode '${e}': ${o}; falling back to bundled 'code'`);try{let i=this.loadModeFile("code",!0);this.validateMode(i.mode,[i.path]),r=i.mode,e="code"}catch(i){let s=`Critical: could not load bundled 'code' mode: ${i instanceof Error?i.message:String(i)}`;throw u.error("WORKER",s),new Error(s)}}return r.id=e,this.activeMode=r,this.activeModeId=e,u.debug("SYSTEM",`Loaded mode: ${r.name} (${e})`,void 0,{types:r.observation_types.map(n=>n.id),concepts:r.observation_concepts.map(n=>n.id)}),r}getActiveMode(){if(!this.activeMode)throw new Error("No mode loaded. Call loadMode() first.");return this.activeMode}getActiveModeId(){if(!this.activeModeId)throw new Error("No mode loaded. Call loadMode() first.");return this.activeModeId}getObservationTypes(){return this.getActiveMode().observation_types}getTypeIcon(e){return this.getObservationTypes().find(n=>n.id===e)?.emoji||"\u{1F4DD}"}getWorkEmoji(e){return this.getObservationTypes().find(n=>n.id===e)?.work_emoji||"\u{1F4DD}"}};_();function Br(t){let e;if(typeof t=="number")e=t;else if(typeof t=="string"&&/^\d+$/.test(t.trim()))e=Number(t.trim());else return;return Number.isSafeInteger(e)&&e>=0?e:void 0}function ss(t){let e=Number(t);return Number.isFinite(e)&&e>0?e:0}function as(t,e,r){let n=Br(e);return n!==void 0?n:(e!==void 0&&u.warn("CONFIG",`${t} must be a whole number >= 0; using the default`,{value:e,default:r}),Number(r))}function cs(t){let e=(t??"").split(",").map(r=>r.trim()).filter(r=>r!=="");return e.length>0?e:null}function Kr(t,e,r){let n=cs(e);if(!n)return new Set(r);let o=n.filter(s=>r.includes(s)),i=n.filter(s=>!r.includes(s));return i.length>0&&u.warn("CONFIG",`${t} has ids not in the active mode; ignoring them`,{discardedIds:i.join(","),fallingBackToModeList:o.length===0}),new Set(o.length>0?o:r)}function Gr(){let t=A.settings(),e=b.loadFromFile(t),r=w.getInstance().getActiveMode(),n=Kr("CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES",e.CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES,r.observation_types.map(a=>a.id)),o=Kr("CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS",e.CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS,r.observation_concepts.map(a=>a.id)),i=b.getAllDefaults(),s=a=>as(a,e[a],i[a]);return{totalObservationCount:s("CLAUDE_MEM_CONTEXT_OBSERVATIONS"),fullObservationCount:s("CLAUDE_MEM_CONTEXT_FULL_COUNT"),sessionCount:s("CLAUDE_MEM_CONTEXT_SESSION_COUNT"),showReadTokens:e.CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS==="true",showWorkTokens:e.CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS==="true",showSavingsAmount:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT==="true",showSavingsPercent:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT==="true",observationTypes:n,observationConcepts:o,fullObservationField:e.CLAUDE_MEM_CONTEXT_FULL_FIELD,showLastSummary:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY==="true",showLastMessage:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE==="true",mainAgentOnly:e.CLAUDE_MEM_CONTEXT_MAIN_AGENT_ONLY!=="false",reinforcementAlpha:ss(e.CLAUDE_MEM_REINFORCE_ALPHA)}}function ls(t,e){return t.fullObservationCount>0?{config:{...t,fullObservationCount:0},observationCount:e}:t.showLastSummary?{config:{...t,showLastSummary:!1},observationCount:e}:t.showLastMessage?{config:{...t,showLastMessage:!1},observationCount:e}:t.sessionCount>0?{config:{...t,sessionCount:Math.floor(t.sessionCount/2)},observationCount:e}:e>1?{config:t,observationCount:Math.floor(e/2)}:null}function Yr(t,e,r,n=1e4){let o=e,i=t.length,s=r(t,o),a=0;for(;s.length>n;){let c=ls(o,i);if(!c)return{text:s,config:o,observationCount:i,reductions:a,overBudget:!0};o=c.config,i=c.observationCount,s=r(t.slice(0,i),o),a++}return{text:s,config:o,observationCount:i,reductions:a,overBudget:!1}}function Jr(t){let e=(t.title?.length||0)+(t.subtitle?.length||0)+(t.narrative?.length||0)+JSON.stringify(t.facts||[]).length;return Math.ceil(e/Wr)}function Rt(t){let e=t.length,r=t.reduce((s,a)=>s+Jr(a),0),n=t.reduce((s,a)=>s+(a.discovery_tokens||0),0),o=n-r,i=n>0?Math.round(o/n*100):0;return{totalObservations:e,totalReadTokens:r,totalDiscoveryTokens:n,savings:o,savingsPercent:i}}function us(t){return w.getInstance().getWorkEmoji(t)}function Ce(t,e){let r=Jr(t),n=t.discovery_tokens||0,o=us(t.type),i=n>0?`${o} ${n.toLocaleString()}`:"-";return{readTokens:r,discoveryTokens:n,discoveryDisplay:i,workEmoji:o}}function We(t){return t.showReadTokens||t.showWorkTokens||t.showSavingsAmount||t.showSavingsPercent}var pn=oe(require("path"),1),Ge=require("fs");_();_();var Ke=require("fs");_();T();$();var je=String.raw`[A-Za-z0-9_.\-+/=~@#$%^*!?]`,ds=`(?=${je}{8})${je}*[A-Za-z]${je}*`,Be=String.raw`(?:\\{0,3}["'])?`,Oe=String.raw`\s{0,8}`;function wt(t){return new RegExp(`${t}${ds}`,"gi")}function Vr(t){return`(?<=${t}${Be}${Oe}[=:]${Oe}${Be})`}var fs=[{name:"aws_access_key",regex:/AKIA[0-9A-Z]{16}/g},{name:"aws_secret_key",regex:/(?<=AWS_SECRET_ACCESS_KEY\s{0,8}[=:]\s{0,8}['"]?)[A-Za-z0-9/+=]{40}/g},{name:"github_pat",regex:/\bgh[oprs]_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{82}\b/g},{name:"openai_key",regex:/\bsk-(?!ant-)[A-Za-z0-9_-]{20,}\b/g},{name:"anthropic_key",regex:/\bsk-ant-[A-Za-z0-9_-]{20,}\b/g},{name:"slack_token",regex:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g},{name:"jwt",regex:/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g},{name:"private_key_pem",regex:/-----BEGIN (?:RSA |DSA |EC |OPENSSH |PGP )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |DSA |EC |OPENSSH |PGP )?PRIVATE KEY-----/g},{name:"stripe_key",regex:/\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]{24,}\b/g},{name:"google_api_key",regex:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:"claude_mem_key",regex:/\bcmem_[A-Za-z0-9_-]{32,}|\bcm_pro_[A-Za-z0-9_-]{8,}/g}],ms=[{name:"generic_password",regex:wt(Vr(String.raw`\b(?:\w*_?(?:password|passwd)|\w+_pwd)`))},{name:"generic_token",regex:wt(Vr(String.raw`\b\w*_(?:token|secret|api_key)`))},{name:"bearer_token",regex:wt(`(?<=\\bAuthorization${Be}${Oe}:${Oe}${Be}Bearer${Oe})`)}],ps=1024*1024,Es="<redacted type='oversize'/>";function zr(t,e){if(!e.enabled||t.length===0)return{redacted:t,counts:{},oversize:!1};if(t.length>ps)return u.warn("REDACT","field exceeds the 1M-char redaction cap; replaced by an oversize marker",void 0,{inputLength:t.length}),{redacted:Es,counts:{oversize:1},oversize:!0};let r=new Set(e.disabledBuiltinPatterns??[]),n={},o=t,i=[];for(let a of e.customPatterns??[]){if(!a.name||a.name.length===0){u.warn("REDACT","custom pattern skipped: missing name",void 0,{pattern:a});continue}try{i.push({name:a.name,regex:new RegExp(a.regex,"g")})}catch(c){u.warn("REDACT","custom pattern skipped: invalid regex",{name:a.name},c instanceof Error?c:new Error(String(c)))}}let s=[...i,...fs,...e.genericEnabled?ms:[]];for(let a of s)r.has(a.name)||(a.regex.lastIndex=0,o=o.replace(a.regex,()=>(n[a.name]=(n[a.name]??0)+1,`<redacted type='${a.name}'/>`)));return e.logMatches&&Object.keys(n).length>0&&u.debug("REDACT","patterns matched",void 0,{counts:n}),{redacted:o,counts:n,oversize:!1}}function _s(t){if(!t||t.trim()==="")return[];try{let e=JSON.parse(t);return Array.isArray(e)?e.filter(r=>r&&typeof r.name=="string"&&typeof r.regex=="string"):(u.warn("REDACT","CLAUDE_MEM_REDACT_CUSTOM_PATTERNS is not a JSON array, ignoring"),[])}catch(e){return u.warn("REDACT","failed to parse CLAUDE_MEM_REDACT_CUSTOM_PATTERNS as JSON",void 0,e instanceof Error?e:new Error(String(e))),[]}}function gs(t){return{enabled:t.CLAUDE_MEM_REDACT_ENABLED==="true",disabledBuiltinPatterns:(t.CLAUDE_MEM_REDACT_DISABLED_BUILTINS??"").split(",").map(e=>e.trim()).filter(Boolean),customPatterns:_s(t.CLAUDE_MEM_REDACT_CUSTOM_PATTERNS??"[]"),logMatches:t.CLAUDE_MEM_REDACT_LOG_MATCHES==="true",genericEnabled:t.CLAUDE_MEM_REDACT_GENERIC_ENABLED==="true"}}var Me=null,qr=0,Ss=5e3,be=null,Xr=!1,hs={enabled:!0,disabledBuiltinPatterns:[],customPatterns:[],logMatches:!1},ys=/"CLAUDE_MEM_REDACT_ENABLED"\s*:\s*"true"/;function As(t){if(!(0,Ke.existsSync)(t))return null;try{return(0,Ke.readFileSync)(t,"utf-8")}catch{return""}}function Ts(t){if(t===null)return!1;try{let e=JSON.parse(ft(t));return e===null||typeof e!="object"||Array.isArray(e)}catch{return!0}}function Cs(t,e,r){return process.env.CLAUDE_MEM_REDACT_ENABLED==="false"||!(be?.enabled===!0||ys.test(e))?r:(Xr||(Xr=!0,u.warn("REDACT","settings.json could not be read; secret redaction stays on until it is repaired",{settingsPath:t,using:be?.enabled?"the last configuration that loaded":"the built-in patterns"})),be?.enabled?be:hs)}function Qr(t=K){let e=Date.now();if(Me&&e-qr<Ss)return Me;let r=b.loadFromFile(t),n=gs(r),o=n.enabled?null:As(t);return Ts(o)?Me=Cs(t,o,n):(Me=n,be=n),qr=e,Me}var $l=new RegExp(`^${je}{8,}$`);var Dt=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],Ms=new Set(Dt),Zr=/<([A-Za-z_][A-Za-z0-9_-]*)/y,en=/<\/([A-Za-z_][A-Za-z0-9_-]*)\s*>/y;function bs(t){let e=Object.fromEntries(Dt.map(d=>[d,0]));if(!t.includes("<"))return{text:t,counts:e,total:0};let r=t.length,n=new Int32Array(r+1);n[r]=r;for(let d=r-1;d>=0;d--)n[d]=t.charCodeAt(d)===62?d:n[d+1];let o=new Map,i=[],s=0,a=0;for(;a<r;){if(t.charCodeAt(a)!==60){a+=1;continue}en.lastIndex=a;let d=en.exec(t);if(d){let f=d[1],E=o.get(f),S=E&&E.head<E.items.length?E.items[E.head]:void 0;S&&a>=S.attrEnd&&(E.head+=1,i.push([S.start,a+d[0].length]),e[f]+=1,s+=1),a+=d[0].length;continue}Zr.lastIndex=a;let p=Zr.exec(t);if(p&&Ms.has(p[1])){let f=p[1],E=a+p[0].length,S={start:a,attrEnd:n[E]},R=o.get(f);R?R.items.push(S):o.set(f,{items:[S],head:0}),a=E;continue}a+=1}i.sort((d,p)=>d[0]-p[0]);let c="",l=0;for(let[d,p]of i)d>l&&(c+=t.slice(l,d)),p>l&&(l=p);return c+=t.slice(l),{text:c,counts:e,total:s}}var rn=/<system-reminder>[\s\S]*?<\/system-reminder>/g,tn=100;function Os(t){let{text:e,counts:r,total:n}=bs(t);return n>tn&&u.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:n,maxAllowed:tn,contentLength:t.length}),{stripped:zr(e.trim(),Qr()).redacted,counts:r}}function Rs(t){return Os(t).stripped}var ws=new RegExp(`<(${Dt.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`);function vt(t){let e=r=>typeof r=="string"?ws.test(r)?Rs(r):r:Array.isArray(r)?r.map(e):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).map(([n,o])=>[n,e(o)])):r;return e(t)}var Ds=["task-notification"],jl=new RegExp(`^\\s*<(${Ds.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),Bl=256*1024;T();function nn(t){return`(COALESCE(${t}.agent_id, '') = '' OR COALESCE(${t}.agent_type, '') = '')`}function on(t,e){let r=Date.parse(t);if(Number.isNaN(r))return 1;let n=Math.floor((e.getTime()-r)/864e5);return n<1?1:n}function sn(t){if(!t)return[];try{let e=JSON.parse(t);return Array.isArray(e)?e.filter(r=>typeof r=="string"&&r.length>0):[]}catch{return[]}}function an(t=new Date){return t.toISOString().slice(0,10)}var vs=864e5,Ls=5,cn=500;function un(t,e){return!(e>0)||t>=cn?t:Math.min(cn,Math.max(t,t*Ls))}function ks(t,e){let r=Math.max(1,Math.floor((e.getTime()-t)/vs));return Math.pow(r,-.5)}function Is(t,e,r){let n=ks(t.created_at_epoch,e),o=sn(t.reinforcement_dates),i=an(new Date(t.created_at_epoch)),s=0;for(let a of o)a!==i&&(s+=Math.pow(on(a,e),-.5));return Math.log(1+n+r*s)}function Ps(t){return Math.max(1,Math.ceil(t/4))}function dn(t,e,r,n=new Date){if(t.length<=e)return t;if(!(r>0))return t.slice(0,e);let o=t.slice(0,Math.min(e,Ps(e))),i=t.slice(o.length).map((a,c)=>({item:a,i:c,score:Is(a,n,r)}));return i.sort((a,c)=>c.score-a.score||c.item.created_at_epoch-a.item.created_at_epoch||a.i-c.i),[...o,...i.slice(0,e-o.length).map(a=>a.item)].sort((a,c)=>c.created_at_epoch-a.created_at_epoch)}var fn=`
|
|
28
28
|
o.id,
|
|
29
29
|
o.memory_session_id,
|
|
30
30
|
s.content_session_id,
|
|
@@ -41,10 +41,10 @@ ${S.stack??""}
|
|
|
41
41
|
o.created_at,
|
|
42
42
|
o.created_at_epoch,
|
|
43
43
|
o.project
|
|
44
|
-
`,Lt=["project","merged_into_project"],ue=250;function En(t,e){let r=new Map;for(let n of t)for(let o of n)r.set(o.id,o);return[...r.values()].sort((n,o)=>o.created_at_epoch-n.created_at_epoch).slice(0,e)}function
|
|
44
|
+
`,Lt=["project","merged_into_project"],ue=250;function En(t,e){let r=new Map;for(let n of t)for(let o of n)r.set(o.id,o);return[...r.values()].sort((n,o)=>o.created_at_epoch-n.created_at_epoch).slice(0,e)}function _n(t,e,r){let n=[];for(let o of Lt)for(let i=0;i<e;i++)n.push(`SELECT * FROM (${r(`${t}.${o} COLLATE NOCASE = ?`)})`);return`
|
|
45
45
|
SELECT id FROM (${n.join(" UNION ")})
|
|
46
46
|
ORDER BY created_at_epoch DESC
|
|
47
|
-
LIMIT ?`}function
|
|
47
|
+
LIMIT ?`}function gn(t,e,r,n){let o=r.reinforcementAlpha??0,i=Sn(t,r,{limit:un(r.totalObservationCount,o),platformSource:n,projects:e,excludeSubagents:r.mainAgentOnly,withReinforcementDates:o>0});return dn(i,r.totalObservationCount,o)}function Sn(t,e,r){let n=Array.from(e.observationTypes),o=n.map(()=>"?").join(","),i=Array.from(e.observationConcepts),s=i.map(()=>"?").join(","),a=(r.projects??[]).filter(y=>y.trim().length>0);if(a.length>ue){let y=[];for(let P=0;P<a.length;P+=ue)y.push(Sn(t,e,{...r,projects:a.slice(P,P+ue)}));return En(y,r.limit)}let c=r.includeManualSaves?"substr(o.memory_session_id, 1, 7) = 'manual-' OR":"",l=r.excludeSubagents?`AND ${nn("o")}`:"",d=r.withReinforcementDates?`,
|
|
48
48
|
o.reinforcement_dates`:"",p=`(? IS NULL OR s.platform_source = ?)
|
|
49
49
|
${l}
|
|
50
50
|
AND (${c} (
|
|
@@ -61,7 +61,7 @@ ${S.stack??""}
|
|
|
61
61
|
WHERE ${p}
|
|
62
62
|
ORDER BY o.created_at_epoch DESC
|
|
63
63
|
LIMIT ?
|
|
64
|
-
`);try{return y.all(...f,r.limit)}finally{y.finalize()}}let E=
|
|
64
|
+
`);try{return y.all(...f,r.limit)}finally{y.finalize()}}let E=_n("o",a.length,y=>`
|
|
65
65
|
SELECT o.id, o.created_at_epoch
|
|
66
66
|
FROM observations o
|
|
67
67
|
LEFT JOIN sdk_sessions s ON o.memory_session_id = s.memory_session_id
|
|
@@ -74,7 +74,7 @@ ${S.stack??""}
|
|
|
74
74
|
JOIN observations o ON o.id = w.id
|
|
75
75
|
LEFT JOIN sdk_sessions s ON o.memory_session_id = s.memory_session_id
|
|
76
76
|
ORDER BY o.created_at_epoch DESC
|
|
77
|
-
`);try{return R.all(...S,r.limit)}finally{R.finalize()}}function kt(t,e,r,n){if(e.length===0)return[];let o=r.sessionCount+ae;if(e.length>ue){let l=[];for(let d=0;d<e.length;d+=ue)l.push(kt(t,e.slice(d,d+ue),r,n));return En(l,o)}let i=[n??null,n??null],s=
|
|
77
|
+
`);try{return R.all(...S,r.limit)}finally{R.finalize()}}function kt(t,e,r,n){if(e.length===0)return[];let o=r.sessionCount+ae;if(e.length>ue){let l=[];for(let d=0;d<e.length;d+=ue)l.push(kt(t,e.slice(d,d+ue),r,n));return En(l,o)}let i=[n??null,n??null],s=_n("ss",e.length,l=>`
|
|
78
78
|
SELECT ss.id, ss.created_at_epoch
|
|
79
79
|
FROM session_summaries ss
|
|
80
80
|
LEFT JOIN sdk_sessions s ON ss.memory_session_id = s.memory_session_id
|
|
@@ -99,7 +99,7 @@ ${S.stack??""}
|
|
|
99
99
|
LEFT JOIN sdk_sessions s ON ss.memory_session_id = s.memory_session_id
|
|
100
100
|
ORDER BY ss.created_at_epoch DESC
|
|
101
101
|
`);try{return c.all(...a,o)}finally{c.finalize()}}var mn=200;function xs(t){let e=0;for(let r=0;r<t.length;r++)e=(e<<5)-e+t.charCodeAt(r)|0;return Math.abs(e).toString(36)}function Ns(t){let e=t.replace(/[^a-zA-Z0-9]/g,"-");return e.length<=mn?e:`${e.slice(0,mn)}-${xs(t)}`}function Us(t){if(!/"type"\s*:\s*"assistant"/.test(t))return null;let e=JSON.parse(t);if(e.type==="assistant"&&e.message?.content&&Array.isArray(e.message.content)){let r="";for(let n of e.message.content)n.type==="text"&&(r+=n.text);if(r=r.replace(rn,"").trim(),r)return r}return null}function $s(t){for(let e=t.length-1;e>=0;e--)try{let r=Us(t[e]);if(r)return r}catch(r){r instanceof Error?u.debug("WORKER","Skipping malformed transcript line",{lineIndex:e},r):u.debug("WORKER","Skipping malformed transcript line",{lineIndex:e,error:String(r)});continue}return""}function Hs(t){try{if(!(0,Ge.existsSync)(t))return{assistantMessage:""};let e=(0,Ge.readFileSync)(t,"utf-8").trim();if(!e)return{assistantMessage:""};let r=e.split(`
|
|
102
|
-
`).filter(o=>o.trim());return{assistantMessage:$s(r)}}catch(e){return e instanceof Error?u.failure("WORKER","Failed to extract prior messages from transcript",{transcriptPath:t},e):u.warn("WORKER","Failed to extract prior messages from transcript",{transcriptPath:t,error:String(e)}),{assistantMessage:""}}}function hn(t,e,r,n){if(!e.showLastMessage||t.length===0)return{assistantMessage:""};let o=t.find(c=>c.memory_session_id!==r&&c.content_session_id!==r);if(!o)return{assistantMessage:""};let i=o.content_session_id??o.memory_session_id,s=Ns(n),a=pn.default.join(B,"projects",s,`${i}.jsonl`);return Hs(a)}function yn(t,e){let r=e[0]?.id;return t.map((n,o)=>{let i=o===0?null:e[o+1];return{...n,displayEpoch:i?i.created_at_epoch:n.created_at_epoch,displayTime:i?i.created_at:n.created_at,shouldShowLink:n.id!==r}})}function An(t,e){let r=[...t.map(n=>({type:"observation",data:n})),...e.map(n=>({type:"summary",data:n}))];return r.sort((n,o)=>{let i=n.type==="observation"?n.data.created_at_epoch:n.data.displayEpoch,s=o.type==="observation"?o.data.created_at_epoch:o.data.displayEpoch;return i-s}),r}function Tn(t,e){return new Set(t.slice(0,e).map(r=>r.id))}var It=oe(require("path"),1);
|
|
102
|
+
`).filter(o=>o.trim());return{assistantMessage:$s(r)}}catch(e){return e instanceof Error?u.failure("WORKER","Failed to extract prior messages from transcript",{transcriptPath:t},e):u.warn("WORKER","Failed to extract prior messages from transcript",{transcriptPath:t,error:String(e)}),{assistantMessage:""}}}function hn(t,e,r,n){if(!e.showLastMessage||t.length===0)return{assistantMessage:""};let o=t.find(c=>c.memory_session_id!==r&&c.content_session_id!==r);if(!o)return{assistantMessage:""};let i=o.content_session_id??o.memory_session_id,s=Ns(n),a=pn.default.join(B,"projects",s,`${i}.jsonl`);return Hs(a)}function yn(t,e){let r=e[0]?.id;return t.map((n,o)=>{let i=o===0?null:e[o+1];return{...n,displayEpoch:i?i.created_at_epoch:n.created_at_epoch,displayTime:i?i.created_at:n.created_at,shouldShowLink:n.id!==r}})}function An(t,e){let r=[...t.map(n=>({type:"observation",data:n})),...e.map(n=>({type:"summary",data:n}))];return r.sort((n,o)=>{let i=n.type==="observation"?n.data.created_at_epoch:n.data.displayEpoch,s=o.type==="observation"?o.data.created_at_epoch:o.data.displayEpoch;return i-s}),r}function Tn(t,e){return new Set(t.slice(0,e).map(r=>r.id))}var It=oe(require("path"),1);_();function Ye(t){if(!t)return[];try{let e=JSON.parse(t);return Array.isArray(e)?e.filter(r=>typeof r=="string"):[]}catch(e){return u.debug("PARSER","Failed to parse JSON array, using empty fallback",{preview:t?.substring(0,50)},e instanceof Error?e:new Error(String(e))),[]}}function Je(t,e){return Number.isNaN(t.getTime())?"Invalid Date":e(t)}function Pt(t){let e=t.getUTCHours(),r=e<12?"AM":"PM",n=t.getUTCMinutes().toString().padStart(2,"0");return`${e%12||12}:${n} ${r}`}function xt(t){return t.toISOString().slice(0,10)}function Ve(t,e){try{return t()}catch(r){return u.debug("PARSER","Locale date formatter unavailable, using ISO fallback",{},r instanceof Error?r:new Error(String(r))),e()}}function Nt(t){let e=new Date(t);return Ve(()=>e.toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0}),()=>Je(e,r=>`${xt(r)} ${Pt(r)}`))}function Ut(t){let e=new Date(t);return Ve(()=>e.toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}),()=>Je(e,Pt))}function Mn(t){let e=new Date(t);return Ve(()=>e.toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"}),()=>Je(e,xt))}function Y(t=new Date){return Ve(()=>{let e=t.toLocaleDateString("en-CA"),r=t.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}).toLowerCase().replace(" ",""),n=t.toLocaleTimeString("en-US",{timeZoneName:"short"}).split(" ").pop();return`${e} ${r} ${n}`},()=>Je(t,e=>`${xt(e)} ${Pt(e)} UTC`))}function Cn(t,e){return It.default.isAbsolute(t)?It.default.relative(e,t):t}function bn(t,e,r){let n=Ye(t);if(n.length>0)return Cn(n[0],e);if(r){let o=Ye(r);if(o.length>0)return Cn(o[0],e)}return"General"}var Fs=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function z(t,e){let r=String(t);return e.fetchByIdSupported===!1&&Fs.test(r)?r.slice(0,8):r}function On(){let t=w.getInstance();return`${t.getActiveMode().name} (${t.getActiveModeId()})`}function Rn(t,e=Y()){return[`# [${t}] recent context, ${e}`,`Mode: ${On()}`,""]}function wn(t=!0){let r=w.getInstance().getActiveMode().observation_types.map(o=>`${o.emoji}${o.id}`).join(" "),n=t?"Fetch details: get_observations([IDs]) | Search: mem-search skill":"Fetch details: observation_search by title (short refs are display-only)";return[`Legend: \u{1F3AF}session ${r}`,"Format: ID TIME TYPE TITLE",n,""]}function Dn(t,e){let r=[],n=[`${t.totalObservations} obs (${t.totalReadTokens.toLocaleString()}t read)`,`${t.totalDiscoveryTokens.toLocaleString()}t work`];return t.totalDiscoveryTokens>0&&(e.showSavingsAmount||e.showSavingsPercent)&&(e.showSavingsPercent?n.push(`${t.savingsPercent}% savings`):e.showSavingsAmount&&n.push(`${t.savings.toLocaleString()}t saved`)),r.push(`Stats: ${n.join(" | ")}`),r.push(""),r}function vn(t){return[`### ${t}`]}function Ln(t){return t.toLowerCase().replace(" am","a").replace(" pm","p")}function kn(t,e,r){let n=t.title||"Untitled",o=w.getInstance().getTypeIcon(t.type),i=e?Ln(e):'"';return`${z(t.id,r)} ${i} ${o} ${n}`}function In(t,e,r,n){let o=[],i=t.title||"Untitled",s=w.getInstance().getTypeIcon(t.type),a=e?Ln(e):'"',{readTokens:c,discoveryDisplay:l}=Ce(t,n),d=z(t.id,n);o.push(`**${d}** ${a} ${s} **${i}**`),r&&o.push(r);let p=[];return n.showReadTokens&&p.push(`~${c}t`),n.showWorkTokens&&p.push(l),p.length>0&&o.push(p.join(" ")),o.push(""),o}function Pn(t,e,r={}){return[`S${z(t.id,r)} ${t.request||"Session started"} (${e})`]}function de(t,e){return e?[`**${t}**: ${e}`,""]:[]}function xn(t){return t.assistantMessage?["","---","","**Previously**","",`A: ${t.assistantMessage}`,""]:[]}function Nn(t,e,r=!0){return["",`Access ${Math.round(t/1e3)}k tokens of past work via ${r?"get_observations([IDs]) or mem-search skill":"observation_search"}.`]}function Un(t,e=Y()){return`# [${t}] recent context, ${e}
|
|
103
103
|
Mode: ${On()}
|
|
104
104
|
|
|
105
105
|
No previous sessions found.`}function $n(){let t=w.getInstance();return`${t.getActiveMode().name} (${t.getActiveModeId()})`}function Hn(t,e=Y()){return["",`${m.bright}${m.cyan}[${t}] recent context, ${e}${m.reset}`,`${m.dim}Mode: ${$n()}${m.reset}`,`${m.gray}${"\u2500".repeat(60)}${m.reset}`,""]}function Fn(){let e=w.getInstance().getActiveMode().observation_types.map(r=>`${r.emoji} ${r.id}`).join(" | ");return[`${m.dim}Legend: session-request | ${e}${m.reset}`,""]}function Wn(){return[`${m.bright}Column Key${m.reset}`,`${m.dim} Read: Tokens to read this observation (cost to learn it now)${m.reset}`,`${m.dim} Work: Tokens spent on work that produced this record ( research, building, deciding)${m.reset}`,""]}function jn(t=!0){let e=t?[`${m.dim} - Fetch by ID: get_observations([IDs]) for observations visible in this index${m.reset}`,`${m.dim} - Search history: Use the mem-search skill for past decisions, bugs, and deeper research${m.reset}`]:[`${m.dim} - Search: observation_search by title or topic (short refs are display-only; server runtime has no fetch by ID)${m.reset}`];return[`${m.dim}Context Index: This semantic index (titles, types, files, tokens) is usually sufficient to understand past work.${m.reset}`,"",`${m.dim}When you need implementation details, rationale, or debugging context:${m.reset}`,...e,`${m.dim} - Trust this index over re-reading code for past decisions and learnings${m.reset}`,""]}function Bn(t,e){let r=[];if(r.push(`${m.bright}${m.cyan}Context Economics${m.reset}`),r.push(`${m.dim} Loading: ${t.totalObservations} observations (${t.totalReadTokens.toLocaleString()} tokens to read)${m.reset}`),r.push(`${m.dim} Work investment: ${t.totalDiscoveryTokens.toLocaleString()} tokens spent on research, building, and decisions${m.reset}`),t.totalDiscoveryTokens>0&&(e.showSavingsAmount||e.showSavingsPercent)){let n=" Your savings: ";e.showSavingsAmount&&e.showSavingsPercent?n+=`${t.savings.toLocaleString()} tokens (${t.savingsPercent}% reduction from reuse)`:e.showSavingsAmount?n+=`${t.savings.toLocaleString()} tokens`:n+=`${t.savingsPercent}% reduction from reuse`,r.push(`${m.green}${n}${m.reset}`)}return r.push(""),r}function Kn(t){return[`${m.bright}${m.cyan}${t}${m.reset}`,""]}function Gn(t){return[`${m.dim}${t}${m.reset}`]}function $t(t,e,r,n){let o=t.title||"Untitled",i=w.getInstance().getTypeIcon(t.type),{readTokens:s,discoveryTokens:a,workEmoji:c}=Ce(t,n),l=r?`${m.dim}${e}${m.reset}`:" ".repeat(e.length),d=n.showReadTokens&&s>0?`${m.dim}(~${s}t)${m.reset}`:"",p=n.showWorkTokens&&a>0?`${m.dim}(${c} ${a.toLocaleString()}t)${m.reset}`:"";return` ${m.dim}#${z(t.id,n)}${m.reset} ${l} ${i} ${o} ${d} ${p}`}function Ht(t,e,r,n,o){let i=[],s=t.title||"Untitled",a=w.getInstance().getTypeIcon(t.type),{readTokens:c,discoveryTokens:l,workEmoji:d}=Ce(t,o),p=r?`${m.dim}${e}${m.reset}`:" ".repeat(e.length),f=o.showReadTokens&&c>0?`${m.dim}(~${c}t)${m.reset}`:"",E=o.showWorkTokens&&l>0?`${m.dim}(${d} ${l.toLocaleString()}t)${m.reset}`:"";return i.push(` ${m.dim}#${z(t.id,o)}${m.reset} ${p} ${a} ${m.bright}${s}${m.reset}`),n&&i.push(` ${m.dim}${n}${m.reset}`),(f||E)&&i.push(` ${f} ${E}`),i.push(""),i}function Yn(t,e,r={}){let n=`${t.request||"Session started"} (${e})`;return[`${m.yellow}#S${z(t.id,r)}${m.reset} ${n}`,""]}function fe(t,e,r){return e?[`${r}${t}:${m.reset} ${e}`,""]:[]}function Jn(t){return t.assistantMessage?["","---","",`${m.bright}${m.magenta}Previously${m.reset}`,"",`${m.dim}A: ${t.assistantMessage}${m.reset}`,""]:[]}function Vn(t,e){let r=Math.round(t/1e3);return["",`${m.dim}Access ${r}k tokens of past research & decisions for just ${e.toLocaleString()}t. Use the claude-mem skill to access memories by ID.${m.reset}`]}function qn(t,e=Y()){return`
|
|
@@ -109,19 +109,19 @@ ${m.gray}${"\u2500".repeat(60)}${m.reset}
|
|
|
109
109
|
|
|
110
110
|
${m.dim}No previous sessions found for this project yet.${m.reset}
|
|
111
111
|
`}function Ws(t){return He().some(e=>e.name===t)?`${t} (environment)`:t}function Xn(t,e,r,n,o){let i=[],s=r.fetchByIdSupported!==!1,a=Ws(t);return n?i.push(...Hn(a,o)):i.push(...Rn(a,o)),n?i.push(...Fn()):i.push(...wn(s)),n&&(i.push(...Wn()),i.push(...jn(s))),We(r)&&(n?i.push(...Bn(e,r)):i.push(...Dn(e,r))),i}function zn(t){let e=new Map;for(let n of t){let o=n.type==="observation"?n.data.created_at:n.data.displayTime,i=Mn(o);e.has(i)||e.set(i,[]),e.get(i).push(n)}let r=Array.from(e.entries()).sort((n,o)=>{let i=new Date(n[0]).getTime(),s=new Date(o[0]).getTime();return i-s});return new Map(r)}function Qn(t,e){return e.fullObservationField==="narrative"?t.narrative:t.facts?Ye(t.facts).join(`
|
|
112
|
-
`):null}function js(t,e,r,n){let o=[];o.push(...vn(t));let i="";for(let s of e)if(s.type==="summary"){let a=s.data,c=Nt(a.displayTime);o.push(...Pn(a,c,n))}else{let a=s.data,c=Ut(a.created_at),d=c!==i?c:"";if(i=c,r.has(a.id)){let f=Qn(a,n);o.push(...In(a,d,f,n))}else o.push(kn(a,d,n))}return o}function Zn(t,e,r){let n=[];for(let[o,i]of zn(t))n.push(...js(o,i,e,r));return n}function eo(t,e,r,n){let o=[];for(let[i,s]of zn(t)){let a="";for(let c of s){if(c.type==="summary"){a="";let R=c.data;o.push({day:i,file:null,summary:!0,lines:Yn(R,Nt(R.displayTime),r)});continue}let l=c.data,d=Ut(l.created_at),p=d!==a;a=d;let f=bn(l.files_modified,n,l.files_read),E=Qn(l,r),S=e.has(l.id);o.push({day:i,file:f,summary:!1,lines:S?Ht(l,d,p,E,r):[$t(l,d,p,r)],linesWithTime:p?void 0:S?Ht(l,d,!0,E,r):[$t(l,d,!0,r)]})}}return o}function ze(t){let e=[],r="",n=null,o=!1;for(let i of t)i.day!==r&&(r&&e.push(""),e.push(...Kn(i.day)),r=i.day,n=null,o=!1),i.summary?n=null:i.file!==n&&(e.push(...Gn(i.file)),n=i.file),e.push(...!i.summary&&!o?i.linesWithTime??i.lines:i.lines),i.summary||(o=!0);return r&&e.push(""),e}function to(t,e,r){return!(!t.showLastSummary||!e||!!!(e.investigated||e.learned||e.completed||e.next_steps||e.notes)||r&&e.created_at_epoch<r.created_at_epoch)}function ro(t,e){let r=[];return e?(r.push(...fe("Investigated",t.investigated,m.blue)),r.push(...fe("Learned",t.learned,m.yellow)),r.push(...fe("Completed",t.completed,m.green)),r.push(...fe("Next Steps",t.next_steps,m.magenta)),r.push(...fe("Notes",t.notes??null,m.cyan))):(r.push(...de("Investigated",t.investigated)),r.push(...de("Learned",t.learned)),r.push(...de("Completed",t.completed)),r.push(...de("Next Steps",t.next_steps)),r.push(...de("Notes",t.notes??null))),r}function no(t,e){return e?Jn(t):xn(t)}function oo(t,e,r){return!We(e)||t.totalDiscoveryTokens<=0||t.savings<=0?[]:r?Vn(t.totalDiscoveryTokens,t.totalReadTokens):Nn(t.totalDiscoveryTokens,t.totalReadTokens,e.fetchByIdSupported!==!1)}var Q=require("fs"),Bt=require("path");T();T();var Qe=null;function me(){return Qe!==null||(Qe=b.loadFromFile(K)),Qe}function Ft(t,e){let r=(process.env.CLAUDE_MEM_PUBLIC_URL??e??"").trim();return r?r.replace(/\/+$/,""):`http://localhost:${t}`}function Wt(t){let e=(t??"").replace(/\s+/g," ").replace(/[\p{Cc}\p{Cf}]/gu,"").replace(/</g,"<").replace(/>/g,">").replace(/ {2,}/g," ").trim(),r=Array.from(e);return r.length>300?`${r.slice(0,299).join("").trimEnd()}\u2026`:e}function Bs(t){return t.hostname==="cmem.ai"||t.hostname==="openrouter.ai"?!0:t.hostname==="github.com"&&/^\/thedotmack\/claude-mem\/issues(\/|$)/.test(t.pathname)}function jt(t){let e=(t??"").trim();if(!URL.canParse(e))return null;let r=new URL(e);return r.protocol==="https:"&&!r.port&&!r.username&&!r.password&&Bs(r)&&r.href.length<=300?r.href:null}
|
|
112
|
+
`):null}function js(t,e,r,n){let o=[];o.push(...vn(t));let i="";for(let s of e)if(s.type==="summary"){let a=s.data,c=Nt(a.displayTime);o.push(...Pn(a,c,n))}else{let a=s.data,c=Ut(a.created_at),d=c!==i?c:"";if(i=c,r.has(a.id)){let f=Qn(a,n);o.push(...In(a,d,f,n))}else o.push(kn(a,d,n))}return o}function Zn(t,e,r){let n=[];for(let[o,i]of zn(t))n.push(...js(o,i,e,r));return n}function eo(t,e,r,n){let o=[];for(let[i,s]of zn(t)){let a="";for(let c of s){if(c.type==="summary"){a="";let R=c.data;o.push({day:i,file:null,summary:!0,lines:Yn(R,Nt(R.displayTime),r)});continue}let l=c.data,d=Ut(l.created_at),p=d!==a;a=d;let f=bn(l.files_modified,n,l.files_read),E=Qn(l,r),S=e.has(l.id);o.push({day:i,file:f,summary:!1,lines:S?Ht(l,d,p,E,r):[$t(l,d,p,r)],linesWithTime:p?void 0:S?Ht(l,d,!0,E,r):[$t(l,d,!0,r)]})}}return o}function ze(t){let e=[],r="",n=null,o=!1;for(let i of t)i.day!==r&&(r&&e.push(""),e.push(...Kn(i.day)),r=i.day,n=null,o=!1),i.summary?n=null:i.file!==n&&(e.push(...Gn(i.file)),n=i.file),e.push(...!i.summary&&!o?i.linesWithTime??i.lines:i.lines),i.summary||(o=!0);return r&&e.push(""),e}function to(t,e,r){return!(!t.showLastSummary||!e||!!!(e.investigated||e.learned||e.completed||e.next_steps||e.notes)||r&&e.created_at_epoch<r.created_at_epoch)}function ro(t,e){let r=[];return e?(r.push(...fe("Investigated",t.investigated,m.blue)),r.push(...fe("Learned",t.learned,m.yellow)),r.push(...fe("Completed",t.completed,m.green)),r.push(...fe("Next Steps",t.next_steps,m.magenta)),r.push(...fe("Notes",t.notes??null,m.cyan))):(r.push(...de("Investigated",t.investigated)),r.push(...de("Learned",t.learned)),r.push(...de("Completed",t.completed)),r.push(...de("Next Steps",t.next_steps)),r.push(...de("Notes",t.notes??null))),r}function no(t,e){return e?Jn(t):xn(t)}function oo(t,e,r){return!We(e)||t.totalDiscoveryTokens<=0||t.savings<=0?[]:r?Vn(t.totalDiscoveryTokens,t.totalReadTokens):Nn(t.totalDiscoveryTokens,t.totalReadTokens,e.fetchByIdSupported!==!1)}var Q=require("fs"),Bt=require("path");T();T();var Qe=null;function me(){return Qe!==null||(Qe=b.loadFromFile(K)),Qe}function Ft(t,e){let r=(process.env.CLAUDE_MEM_PUBLIC_URL??e??"").trim();return r?r.replace(/\/+$/,""):`http://localhost:${t}`}function Wt(t){let e=(t??"").replace(/\s+/g," ").replace(/[\p{Cc}\p{Cf}]/gu,"").replace(/</g,"<").replace(/>/g,">").replace(/ {2,}/g," ").trim(),r=Array.from(e);return r.length>300?`${r.slice(0,299).join("").trimEnd()}\u2026`:e}function Bs(t){return t.hostname==="cmem.ai"||t.hostname==="openrouter.ai"?!0:t.hostname==="github.com"&&/^\/thedotmack\/claude-mem\/issues(\/|$)/.test(t.pathname)}function jt(t){let e=(t??"").trim();if(!URL.canParse(e))return null;let r=new URL(e);return r.protocol==="https:"&&!r.port&&!r.username&&!r.password&&Bs(r)&&r.href.length<=300?r.href:null}_();var Gs="observer-health.json",Ys=3,Js=600,Vs={consecutiveFailures:0,failingSinceAt:null,lastErrorAt:null,lastErrorMessage:null,lastErrorProvider:null,lastSuccessAt:null,lastErrorCode:null,lastErrorAction:null,lastErrorUrl:null,lastErrorRequestId:null,quotaCooldown:null};function qs(){return(0,Bt.join)(A.dataDir(),Gs)}var Xs=/(["']?\b(?:api[_-]?key|apikey|access[_-]?token|auth[_-]?token|refresh[_-]?token|id[_-]?token|session[_-]?token|client[_-]?secret|secret[_-]?key|secret|password|passwd|pwd|authorization|auth|token|key)\b["']?\s*[=:]\s*)(["']?)([^\s"'&,;}\]]+)\2/gi;function Kt(t){return t.replace(/\bsk-[A-Za-z0-9_-]{8,}/g,"sk-\u2026").replace(/\bcm_pro_[A-Za-z0-9_-]{8,}/g,"cm_pro_\u2026").replace(/\b(Bearer|Basic|Digest|Token)\s+[^\s"']+/gi,"$1 \u2026").replace(Xs,(e,r,n,o)=>/^\d+$/.test(o)?e:`${r}${n}\u2026${n}`).slice(0,Js)}function ao(t=qs()){try{if(!(0,Q.existsSync)(t))return null;let e=JSON.parse((0,Q.readFileSync)(t,"utf-8"));return typeof e!="object"||e===null?null:{...Vs,...e}}catch(e){return u.warn("SESSION","Failed to read observer-health file",{filePath:t},e instanceof Error?e:new Error(String(e))),null}}function co(t){return t!==null&&(t.consecutiveFailures>=Ys||lo(t)||Zs(t))&&(t.lastErrorAt??0)>(t.lastSuccessAt??0)}function pe(t){let e=Math.max(1,Math.round(t/6e4));if(e<60)return`${e} minute${e===1?"":"s"}`;let r=Math.round(e/60);return r<48?`about ${r} hour${r===1?"":"s"}`:`about ${Math.round(r/24)} days`}function zs(){let t=me();return`${Ft(t.CLAUDE_MEM_WORKER_PORT,t.CLAUDE_MEM_PUBLIC_URL)}/restart`}function Gt(t){return t.lastErrorKind==="quota_exhausted"}function Re(t){return t.lastErrorKind==="quota_guard"}var Qs="Provider reported the inference allowance exhausted";function io(t){return Gt(t)&&t.lastErrorMessage===Qs}function lo(t){return t.lastErrorKind==="auth_invalid"}function Zs(t){return t.lastErrorKind==="setup_required"}var uo=30*6e4;function fo(t,e){let r=t.lastErrorAt;return r!==null&&e-r>=uo}function ea(t,e=Date.now()){return(Gt(t)||Re(t))&&fo(t,e)}function ta(t,e=Date.now()){return t.lastErrorCode==="deadline_exceeded"&&fo(t,e)}function mo(t,e=Date.now()){let r=t?.quotaCooldown;return r!=null&&typeof r.until=="number"&&r.until>e}function po(t,e=Date.now()){let r=t.quotaCooldown,n=r?.provider??"unknown provider",o=r?.until,i=o?`${new Date(o).toISOString()} (${pe(Math.max(0,o-e))} from now)`:"the next probe window",s=r?.window?` (${r.window})`:"";if(r?.servingProvider==="claude"){let l=r.window==="unavailable"?"is unavailable":r.window==="rate_limit"?"is rate limited or over capacity":`is in a quota cooldown${s}`;return`\u2139\uFE0F claude-mem's ${n} provider ${l}; memory is running on your Anthropic plan (Claude) meanwhile, and switches back after ${i}.`}if(r?.servingProvider)return`\u2139\uFE0F claude-mem's ${n} provider is in a quota cooldown${s}; memory capture continues on ${r.servingProvider} until it clears at ${i}.`;let a=we(r?.message)||null,c=Re(t);return["\u26A0\uFE0F Heads up: claude-mem is paused while a provider quota cooldown is active.","",c?`Memory capture is paused on ${n}${s} to preserve your Claude allowance, until ${i}.`:`The memory observer is waiting out a quota cooldown on ${n}${s} until ${i}.`,"",...a?[`${c?"Reason":"Latest signal"}: ${a}`,""]:[],"This is not a failure. Incoming observations stay queued in memory and are written","when the cooldown clears \u2014 the worker is intentionally not starting the generator",c?"so interactive work keeps the remaining allowance.":"so it does not keep sending requests the provider is refusing.","","Restarting will NOT help here: it does not replenish the allowance or clear the","persisted cooldown \u2014 so please leave the worker alone.","","(Assistant: tell the user that memory capture is paused for a quota cooldown","at the very start of your first reply. Do NOT restart the worker and do NOT","suggest restarting it.)"].join(`
|
|
113
113
|
`)}function we(t){return t?Wt(Kt(t)):""}function Ze(t,e){let r=jt(t.lastErrorUrl),n=Wt(t.lastErrorRequestId);return[`Latest error: ${we(t.lastErrorMessage)||"unknown"}`,...e?[`What to do: ${e}`]:[],...r?[`Link: ${r}`]:[],...n?[`Request id: ${n}`]:[]]}function so(t,e,r,n){let o=t.lastErrorProvider??"unknown provider",i=t.lastErrorAt?pe(e-t.lastErrorAt):"an unknown time",s=jt(t.lastErrorUrl);return[`\u2139\uFE0F claude-mem: the memory observer last failed with ${n.failedWith} on`,`${o}, ${i} ago. Nothing has re-tested it since \u2014 the health ledger only`,"updates on the next successful save, which happens after this message is written.","",`Last error: ${we(t.lastErrorMessage)||"unknown"}`,...r?[`${n.remedyLabel}: ${r}`]:[],...s?[`Link: ${s}`]:[],"",`${n.recovery}, so memory capture may already be working. If it is`,"not, the next failed save brings the full warning back.","","(Assistant: do not open your reply with this. Mention it only if the user asks why","something was not remembered, or if a later message reports a save failing.)"].join(`
|
|
114
114
|
`)}function Eo(t,e=Date.now()){let r=t.failingSinceAt??t.lastErrorAt,n=r?`for ${pe(e-r)} (since ${new Date(r).toISOString()})`:"for an unknown amount of time",o=t.lastErrorProvider??"unknown provider",i=t.consecutiveFailures,s=we(t.lastErrorAction)||null;if(ea(t,e)){let c=Re(t)||io(t);return so(t,e,s,c?{failedWith:"a usage-related pause",remedyLabel:"If it is still paused",recovery:"Usage pauses release on their own"}:{failedWith:"a spent allowance",remedyLabel:"If it is still spent",recovery:"Allowances reset on their own"})}if(ta(t,e))return so(t,e,s,{failedWith:"requests running past their deadline",remedyLabel:"If it is still slow",recovery:"A slow backend usually recovers on its own"});if(Re(t)||io(t)){let c=Re(t);return["\u26A0\uFE0F Heads up: claude-mem memory capture is paused.","",c?`Memory capture is paused to preserve your Claude allowance (${n}).`:`The memory observer has a usage-related pause on ${o} (${n}).`,"",c?`Reason: ${we(t.lastErrorMessage)||"Precautionary usage guard"}`:"This record cannot tell a precautionary pause from a provider rejection.","","Existing memories remain available; new memory generation is paused.",`After the ${uo/6e4}-minute cooldown, the next activity can trigger one retry.`,"Capture resumes when usage is below the guard thresholds and the provider accepts requests.",o==="claude"?"Check Claude Settings \u2192 Usage for the current usage and reset time.":`Check ${o} usage settings for the current allowance and reset time.`,"","Restarting does not replenish allowance or clear the persisted cooldown.","","(Assistant: tell the user about this pause at the start of your first reply.","Relay the reason accurately; do not call a precautionary pause provider exhaustion.","Do NOT restart the worker or change providers to bypass the pause.)"].join(`
|
|
115
115
|
`)}return Gt(t)?["\u26A0\uFE0F Heads up: claude-mem can't save memories right now.","",`The memory observer's allowance on ${o} is used up (since ${n.replace(/^for .*?\(since /,"").replace(/\)$/,"")}).`,"",...Ze(t,s),"","Until the allowance resets or you add capacity, nothing from this session \u2014 or any","other \u2014 will be remembered.","","Restarting will NOT help here: it does not replenish the allowance or clear the","persisted cooldown \u2014 so please leave the worker alone.",...s?[]:["Switch the observer to another provider in ~/.claude-mem/settings.json if you need","memory capture before the allowance resets."],"","(Assistant: tell the user about this outage at the very start of your first reply,","quoting the error above. Do NOT restart the worker and do NOT suggest restarting it.)"].join(`
|
|
116
116
|
`):t.lastErrorCode==="model_unavailable"?["\u26A0\uFE0F Heads up: claude-mem can't save memories right now.","",`The memory observer (provider: ${o}) has failed ${i} time${i===1?"":"s"} in a row ${n}: its configured model is no longer available.`,"",...Ze(t,s),"","Until the model is changed, nothing from this session \u2014 or any other \u2014 will be remembered.","","Restarting will NOT help here: after a restart the observer asks for the same model","and gets the same refusal.","","(Assistant: tell the user about this outage at the very start of your first reply,",'quoting the error and the "What to do" line above. Do NOT suggest restarting the worker.)'].join(`
|
|
117
117
|
`):lo(t)?["\u26A0\uFE0F Heads up: claude-mem can't save memories right now.","",`The memory observer's credentials have been refused by ${o} ${n}.`,"",...Ze(t,s),"","Until that's fixed, nothing from this session \u2014 or any other \u2014 will be remembered.","","Restarting will NOT help here: the provider refused the credentials, so nothing is broken to restart.",...s?[]:["Check the observer provider's API key in ~/.claude-mem/settings.json, or switch the","observer to another provider there."],"","(Assistant: tell the user about this outage at the very start of your first reply,","quoting the error above. Do NOT restart the worker and do NOT suggest restarting it.)"].join(`
|
|
118
118
|
`):["\u26A0\uFE0F Heads up: claude-mem can't save memories right now.","",`The memory observer (provider: ${o}) has failed ${i} time${i===1?"":"s"} in a row ${n}.`,"",...Ze(t,s),"","Until it's fixed, nothing from this session \u2014 or any other \u2014 will be remembered.","","Restarting the memory worker clears almost every outage. Do one of these:",` Click to restart: ${zs()}`," Or in a terminal: npx claude-mem restart","","Still failing after the restart? Run: npx claude-mem doctor",...s?[]:["If doctor comes back clean, check the observer provider's API key, spend limit, and base","URL in ~/.claude-mem/settings.json. The error above may include a management link."],"","(Assistant: tell the user about this outage at the very start of your first reply,","quoting the error above, and give them the restart link \u2014 let them press it rather","than restarting the worker yourself.)"].join(`
|
|
119
|
-
`)}T();
|
|
120
|
-
`)}
|
|
121
|
-
`)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);if(!n)continue;let o=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:o.length>0?o:null})}return e}async function Ca(){let t;try{t=(await Vt("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,@{Name='StartToken';Expression={$_.CreationDate.ToString('yyyyMMddHHmmss.ffffff')}} | ConvertTo-Csv -NoTypeInformation"],{timeout:3e4,windowsHide:!0,maxBuffer:33554432})).stdout}catch(r){return u.warn("PROCESS","Cannot enumerate the Windows process table \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),[]}let e=[];for(let r of t.split(/\r?\n/).slice(1)){let n=r.match(/^"(\d+)","(\d+)","(.*)"$/);if(!n)continue;let o=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:o.length>0?o:null})}return e}async function tt(t){let e=await ya(),r=new Map;for(let s of e){let a=r.get(s.ppid);a?a.push(s):r.set(s.ppid,[s])}let n=new Set([t]),o=[],i=s=>{for(let a of r.get(s)??[])n.has(a.pid)||(n.add(a.pid),i(a.pid),o.push({pid:a.pid,startToken:a.startToken}))};return i(t),o}var Oa=5e3,Ra=1e3,wa=A.supervisorRegistry(),Da=null;function D(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;return r==="EPERM"?!0:(u.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return u.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function nt(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!D(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function No(t){if(!t||!D(t.pid))return!1;if(!t.startToken)return!0;let e=J(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||u.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}var va={platform:process.platform,readCommandLine:t=>(0,De.readFileSync)(`/proc/${t}/cmdline`,"utf-8")};function Qt(t,e=va){if(!No(t))return!1;if(t.startToken||e.platform!=="linux")return!0;let r;try{r=e.readCommandLine(t.pid)}catch(o){return u.debug("SYSTEM","Could not read the command line of a token-less worker PID; trusting the live PID",{pid:t.pid,error:o instanceof Error?o.message:String(o)}),!0}let n=r.split("\0").some(o=>xo.default.basename(o)==="worker-service.cjs");return n||u.debug("SYSTEM","Token-less worker PID now belongs to another program (PID reused)",{pid:t.pid}),n}var zt=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(e=wa){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,!(0,De.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,De.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[o,i]of Object.entries(n))this.entries.set(o,i)}catch(r){r instanceof Error?u.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):u.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&u.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}retainSupersededEntry(e,r){let n=this.entries.get(e);if(!n||n.pid===r||!D(n.pid))return;let o=`${e}#superseded:${n.pid}`;this.entries.set(o,n);let i=this.runtimeProcesses.get(e);i&&(this.runtimeProcesses.set(o,i),this.runtimeProcesses.delete(e)),u.warn("SYSTEM","Registry id reused while the previous process was still alive; kept it for reaping",{id:e,supersededId:o,supersededPid:n.pid,incomingPid:r})}register(e,r,n){this.initialize(),this.retainSupersededEntry(e,r.pid),this.entries.set(e,r),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e,r){this.initialize();let n=e,o=this.entries.get(n);r!==void 0&&o?.pid!==r&&(n=`${e}#superseded:${r}`,o=this.entries.get(n),o?.pid!==r)||o&&(this.entries.delete(n),this.runtimeProcesses.delete(n),this.persist(),o?.type==="sdk"&&Xt())}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let n=Date.parse(e.startedAt),o=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(o)?0:o)})}getBySession(e){let r=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[n,o]of this.entries)D(o.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,o.type==="sdk"&&(r+=1));e>0&&this.persist();for(let n=0;n<r;n+=1)Xt();return e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;u.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:n,pids:r.map(a=>a.pid)});let o=r.filter(a=>D(a.pid)),i=new Map(o.map(a=>[a.pid,J(a.pid)]));for(let a of o)try{process.platform==="win32"?await j(a.pid,{expectedStartToken:i.get(a.pid)??null}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&u.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):u.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}await nt(o,Oa);let s=o.filter(a=>D(a.pid));for(let a of s){u.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});let c=i.get(a.pid)??null;if(!W(a.pid,c)){u.warn("SYSTEM","Skipping SIGKILL: session process PID was reused during the grace window",{pid:a.pid,sessionId:n});continue}try{process.platform==="win32"?await j(a.pid,{expectedStartToken:c}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(l){l instanceof Error?l.code!=="ESRCH"&&u.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},l):u.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(l)})}}if(s.length>0){let a=Date.now()+Ra;for(;Date.now()<a&&s.filter(l=>D(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let a of r)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of r)a.type==="sdk"&&Xt();return u.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:n,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};try{N(this.registryPath,e),this.persistDegraded=!1}catch(r){this.reportPersistFailure(r)}}reportPersistFailure(e){if(this.persistDegraded)return;this.persistDegraded=!0;let r=e instanceof Error?e:new Error(String(e));u.warn("SYSTEM","Failed to persist supervisor registry; keeping it in memory",{path:this.registryPath},r);try{Da?.({errorCategory:r.code??"unknown"})}catch{}}},qt=null;function ot(){return qt||(qt=new zt),qt}var Ld=180*1e3,La=[];function Xt(){let t=La.shift();t&&t.notify()}var ge=require("fs");g();T();var ka=A.workerPid();async function $o(t){let e=t.currentPid??process.pid,r=t.pidFilePath??ka,n=t.registry.getAll(),o=[...n].filter(c=>c.pid!==e).sort((c,l)=>Date.parse(l.startedAt)-Date.parse(c.startedAt)),i=new Map,s=new Map;for(let c of o){if(!D(c.pid)){t.registry.unregister(c.id);continue}s.set(c.id,J(c.pid)),i.set(c.id,await tt(c.pid));try{await Uo(c,"SIGTERM")}catch(l){l instanceof Error?u.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:c.pid,pgid:c.pgid,type:c.type},l):u.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(l)})}}await nt(o,5e3);let a=o.filter(c=>D(c.pid)||(i.get(c.id)??[]).some(l=>D(l.pid)));for(let c of a){let l=W(c.pid,s.get(c.id)??null);l||u.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:c.pid,type:c.type});try{l&&await Uo(c,"SIGKILL")}catch(d){d instanceof Error?u.debug("SYSTEM","Failed to force kill child process",{pid:c.pid,pgid:c.pgid,type:c.type},d):u.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(d)})}finally{Ia(i.get(c.id)??[],c.pid)}}await nt(a,1e3);for(let c of o)t.registry.unregister(c.id);for(let c of n.filter(l=>l.pid===e))t.registry.unregister(c.id);Ho(r,e),t.registry.pruneDeadEntries()}function Ho(t,e,r=!1){if(!(0,ge.existsSync)(t))return;let n=null;try{let s=JSON.parse((0,ge.readFileSync)(t,"utf-8"));n=typeof s.pid=="number"?s.pid:null}catch(s){u.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:s instanceof Error?s.message:String(s)});return}let o=e!==null&&n===e,i=n===null||!D(n);if(!o&&!(r&&i)){u.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:n,currentPid:e});return}try{(0,ge.rmSync)(t,{force:!0})}catch(s){s instanceof Error?u.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},s):u.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(s)})}}function Ia(t,e){for(let{pid:r,startToken:n}of t)if(!(r===e||!D(r))){if(!W(r,n)){u.debug("SYSTEM","Skipping reap: PID was recycled during the grace window",{pid:r,rootPid:e});continue}try{process.kill(r,"SIGKILL"),u.debug("SYSTEM","Reaped orphaned descendant during shutdown cascade",{pid:r,rootPid:e})}catch(o){let i=o instanceof Error?o.code:void 0;i!=="ESRCH"&&u.warn("SYSTEM","Failed to reap orphaned descendant during shutdown cascade",{pid:r,rootPid:e,errno:i})}}}async function Uo(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}if(e==="SIGKILL"){await j(r,{signalMode:"immediate"});return}try{process.kill(r,e)}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}return}await j(r)}g();var Fo=3e4,_e=null;function Pa(){let e=ot().pruneDeadEntries();e>0&&u.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function Wo(){_e===null&&(_e=setInterval(Pa,Fo),_e.unref(),u.debug("SYSTEM","Health checker started",{intervalMs:Fo}))}function jo(){_e!==null&&(clearInterval(_e),_e=null,u.debug("SYSTEM","Health checker stopped"))}var Bo=require("child_process"),Ko=require("util");g();var xa=(0,Ko.promisify)(Bo.execFile),Na=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/;function Ua(t){let e=[];for(let r of t.split(`
|
|
122
|
-
`)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);n&&e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),command:n[3].trim()})}return e}async function $a(){let t=await xa("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return Ua(t.stdout)}function Ha(t,e){let r=t.filter(s=>Na.test(s.command)&&s.pid!==e.selfPid),n=new Set(r.map(s=>s.pid)),o=r.filter(s=>!n.has(s.ppid)),i=o.filter(s=>s.ppid===e.selfPid?!1:s.ppid===1?!0:!e.isAlive(s.ppid));return{matched:r,roots:o,orphans:i}}async function Go(t={}){let e=t.platform??process.platform,r={matched:0,trees:0,orphans:0,killed:0,failed:0,unregistered:0,skipped:null};if(e==="win32")return r.skipped="windows",r;let n=t.readTable??$a,o=t.isAlive??D,i=t.killTree??(E=>j(E,{signalMode:"graceful"})),s=t.selfPid??process.pid,a;try{a=await n()}catch(E){return u.warn("PROCESS","Orphaned chroma-mcp sweep skipped: cannot read the process table",{error:E instanceof Error?E.message:String(E)}),r.skipped="unreadable",r}let{matched:c,roots:l,orphans:d}=Ha(a,{isAlive:o,selfPid:s});if(r.matched=c.length,r.trees=l.length,r.orphans=d.length,d.length===0)return u.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:r.matched,trees:r.trees}),r;u.warn("PROCESS","Reaping orphaned chroma-mcp trees left by dead workers",{orphans:d.length,roots:d.map(E=>E.pid)});let p=new Set,f=8;for(let E=0;E<d.length;E+=f){let S=d.slice(E,E+f);(await Promise.allSettled(S.map(y=>i(y.pid)))).forEach((y,P)=>{let x=S[P];y.status==="fulfilled"?(r.killed+=1,p.add(x.pid)):(r.failed+=1,u.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:x.pid,ppid:x.ppid,error:y.reason instanceof Error?y.reason.message:String(y.reason)}))})}if(t.registry)for(let E of t.registry.getAll())E.type==="chroma"&&p.has(E.pid)&&(t.registry.unregister(E.id),r.unregistered+=1);return u.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:r.orphans,killed:r.killed,failed:r.failed,unregistered:r.unregistered}),r}T();var Fa=A.workerPid(),Zt=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(),Jo({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,Go({registry:this.registry}).catch(r=>{u.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),Wo()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){u.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,u.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(o){o instanceof Error?u.error("SYSTEM","Error during shutdown",{},o):u.error("SYSTEM","Error during shutdown (non-Error)",{error:String(o)});try{await this.stop()}catch(i){i instanceof Error?u.debug("SYSTEM","Supervisor shutdown fallback failed",{},i):u.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(i)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{u.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}jo(),this.stopPromise=$o({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,r,n){this.registry.register(e,r,n)}unregisterProcess(e,r){this.registry.unregister(e,r)}getRegistry(){return this.registry}},zd=new Zt(ot());function Jo(t={}){let e=t.pidFilePath??Fa;if(!(0,ne.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,ne.readFileSync)(e,"utf-8"))}catch(o){return o instanceof Error?u.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},o):u.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(o)}),(0,ne.rmSync)(e,{force:!0}),"invalid"}return Qt(r)&&r?((t.logAlive??!0)&&u.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(t.removeStale===!1||(u.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,ne.rmSync)(e,{force:!0})),"stale")}Le();T();$();
|
|
123
|
-
`)}async function Xa(t,e={}){let r=Ja(e);try{return await fetch(t,r)}catch(n){throw zo()&&qa(t,e,n),n}}async function Qo(t,e={},r){try{return await Xa(t,{...e,signal:AbortSignal.timeout(r)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new Error(`Request timed out after ${r}ms`):n}}var za=1e3;var Qa=5e3,gp=Qa+za;var Za=G(U.API_REQUEST),ee=class extends Error{kind;status;cause;constructor(e,r,n={}){super(r),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)}},st=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=ec(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??Za}async startSession(e,r={}){let n=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",n,r)}async recordEvent(e){let r=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(e){if(!e.sessionId)throw new ee("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,r={}){let n={projectId:e.projectId};return e.query!==void 0&&(n.query=e.query),e.limit!==void 0&&(n.limit=e.limit),e.summaryLimit!==void 0&&(n.summaryLimit=e.summaryLimit),e.platformSource!==void 0&&(n.platformSource=it(e.platformSource)),e.folderProjects&&e.folderProjects.length>0&&(n.folderProjects=e.folderProjects),e.excludeSubagents!==void 0&&(n.excludeSubagents=e.excludeSubagents),this.request("POST","/v1/context",n,r)}async getJobStatus(e){if(!e)throw new ee("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,content:r,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.platformSource!==void 0?{platformSource:e.platformSource}:{},...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:it(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:it(e.platformSource)}:{},...e.metadata!==void 0?{metadata:vt(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:it(e.platformSource)}:{},...e.payload!==void 0?{payload:vt(e.payload)}:{}}}async request(e,r,n,o={}){if(!this.apiKey||!this.apiKey.trim())throw new ee("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let i=`${this.baseUrl}${r}`,s={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(s.body=JSON.stringify(n));let a=p=>{let f=p instanceof Error?p.message:String(p),E=/timed out|timeout/i.test(f)||p instanceof Error&&(p.name==="TimeoutError"||p.name==="AbortError");return new ee(E?"timeout":"transport",`Server ${e} ${r} failed: ${f}`,{cause:p})},c,l=o.timeoutMs??this.timeoutMs;try{c=await Qo(i,s,l)}catch(p){throw a(p)}if(!c.ok){let p=await c.text().catch(()=>"");throw new ee("http_error",`Server ${e} ${r} returned ${c.status}: ${tc(p,200)}`,{status:c.status})}let d;try{d=await c.text()}catch(p){throw a(p)}if(!d||d.length===0)return{};try{return JSON.parse(d)}catch(p){let f=p instanceof Error?p:new Error(String(p));throw new ee("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:f})}}};function ec(t){return t.replace(/\/+$/,"")}function it(t){return typeof t=="string"?Fe(t):null}function tc(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function rc(){let e=(me().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function nc(){let t=me(),e=(...s)=>{for(let a of s){let c=(a??"").trim();if(c.length>0)return c}return""},r=e(t.CLAUDE_MEM_SERVER_URL,t.CLAUDE_MEM_SERVER_BETA_URL),n=e(t.CLAUDE_MEM_SERVER_API_KEY,t.CLAUDE_MEM_SERVER_BETA_API_KEY),o=e(t.CLAUDE_MEM_SERVER_PROJECT_ID,t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!r)return u.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return u.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return u.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let i={serverBaseUrl:r,apiKey:n};return{runtime:"server",client:new st(i),projectId:o,serverBaseUrl:r}}function Zo(){if(rc()!=="server")return{runtime:"worker"};let t=nc();return t||{runtime:"worker"}}
|
|
124
|
-
`,1)[0]??"";return{id:O(t.id)??"",memory_session_id:O(M(t,"serverSessionId","memory_session_id"))??"",content_session_id:O(M(t,"contentSessionId","content_session_id"))??void 0,platform_source:r??"",type:O(M(t,"kind","type"))??"discovery",title:O(M(t,"title"))??i,subtitle:O(M(t,"subtitle")),narrative:O(M(t,"narrative"))??(o||null),facts:ct(M(t,"facts")),concepts:ct(M(t,"concepts")),files_read:ct(M(t,"files_read","filesRead")),files_modified:ct(M(t,"files_modified","filesModified")),discovery_tokens:null,created_at:new Date(n).toISOString(),created_at_epoch:n,project:O(M(t,"project"))??e}}function ic(t,e,r){let n=ti(t);return{id:O(t.id)??"",memory_session_id:O(M(t,"serverSessionId","memory_session_id"))??"",platform_source:r??"",request:O(M(t,"request")),investigated:O(M(t,"investigated")),learned:O(M(t,"learned")),completed:O(M(t,"completed")),next_steps:O(M(t,"next_steps","nextSteps")),notes:O(M(t,"notes")),created_at:new Date(n).toISOString(),created_at_epoch:n,project:O(M(t,"project"))??e}}var er=require("crypto");T();$();
|
|
119
|
+
`)}T();_();var Ao=require("crypto");var To=require("path");_();T();var go=require("child_process"),So=require("util");T();_();var Hu=(0,So.promisify)(go.execFile);function ho(t){let e=t?.trim();return _o(e?Er(e):B)}function _o(t){let e=t.replace(/[/\\]+$/,"");return e.length>0?e:t}function yo(t){let e=ho(t),r=t?.trim()?e!==pt:!!process.env.CLAUDE_CONFIG_DIR;return{configDir:e,explicitConfigDir:r}}function ra(t){if(!t.explicitConfigDir)return"default";let e=(0,Ao.createHash)("sha256").update(t.configDir.normalize("NFC")).digest("hex").slice(0,8);return`${(0,To.basename)(t.configDir)}#${e}`}function Co(){let t=b.loadFromFile(A.settings());return ra(yo(t.CLAUDE_MEM_CLAUDE_CONFIG_DIR))}var na=Co;function Mo(t){return t.provider!=="claude"||t.profile===na()}var td=30*6e4;var rd=5*6e4;var Z=require("fs"),Oo=require("path");T();_();var oa="sync-health.json",ia=900*1e3,sa=5,bo={invalid_token:"Cloud sync is paused: this device's sync token is no longer valid (connecting another machine can rotate it). Reconnect at https://cmem.ai (Connect), then restart claude-mem. Your local memories are safe.",subscription_inactive:"Cloud sync is paused: your CMEM Pro trial or subscription is not active. Renew at https://cmem.ai/pro and sync resumes on its own within the hour. Your local memories are safe."};function aa(){return(0,Oo.join)(A.dataDir(),oa)}function Ro(t=aa()){try{if(!(0,Z.existsSync)(t))return null;let e=JSON.parse((0,Z.readFileSync)(t,"utf-8"));if(!e||typeof e!="object"||Array.isArray(e))return null;let r=e;return r.state!=="ok"&&r.state!=="auth_paused"&&r.state!=="failing"?null:{state:r.state,code:typeof r.code=="string"?r.code:null,message:typeof r.message=="string"?r.message:null,consecutiveFailures:typeof r.consecutiveFailures=="number"?r.consecutiveFailures:0,failingSinceAt:typeof r.failingSinceAt=="number"?r.failingSinceAt:null,lastErrorAt:typeof r.lastErrorAt=="number"?r.lastErrorAt:null,lastSuccessAt:typeof r.lastSuccessAt=="number"?r.lastSuccessAt:null,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:0}}catch{return null}}function ca(t,e=Date.now()){return t?t.state==="auth_paused"?!0:t.state!=="failing"?!1:t.consecutiveFailures>=sa?!0:t.failingSinceAt!==null&&e-t.failingSinceAt>=ia:!1}function wo(t,e=Date.now()){if(!ca(t,e))return"";if(t.state==="auth_paused")return`\u26A0 ${t.code==="subscription_inactive"||t.code==="invalid_token"?bo[t.code]:t.message??bo.invalid_token}`;let r=t.failingSinceAt!==null?` for ${pe(e-t.failingSinceAt)}`:"",n=t.message?` Last error: ${Kt(t.message)}`:"";return[`\u26A0 Cloud sync has been failing${r} (${t.consecutiveFailures} attempt${t.consecutiveFailures===1?"":"s"}). New memories are saved locally and queued; they upload once the sync server accepts them.`+n,"Details: /api/sync/status on the claude-mem worker."].join(`
|
|
120
|
+
`)}_();_();T();var ne=require("fs");_();var la=new Set([".cmd",".bat"]),ua=new Set([".exe",".com"]),fd=new Set([...ua,...la]);var De=require("fs"),xo=oe(require("path"),1);_();$();var da=["CLAUDECODE_","CLAUDE_CODE_"],fa=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),ma=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"]),pa=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_TMPDIR","CLAUDE_CODE_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",...ma]);function Ee(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(pa.has(r)){e[r]=n;continue}fa.has(r)||da.some(o=>r.startsWith(o))||(e[r]=n)}return e}T();var Jt=require("child_process"),vo=require("fs");_();var Ea=5e3,Do=new Map,Yt=0;function Lo(t,e,r){if(r.status!==0)return null;if(typeof r.stdout!="string")return u.warn("SYSTEM","captureProcessStartToken: start-token probe returned no stdout",{pid:e,source:t,status:r.status}),null;let n=r.stdout.trim();return n.length>0?n:null}function _a(t){Yt+=1;let e=(0,Jt.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Ee(process.env),LC_ALL:"C",LANG:"C"}});return Lo("powershell-cim",t,e)}function ga(t,e=!1){if(!e){let n=Do.get(t);if(n&&(t===process.pid||Date.now()-n.capturedAtMs<Ea))return n.token}let r=null;try{r=_a(t)}catch(n){u.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:n instanceof Error?n.message:String(n)}),r=null}return(r!==null||t!==process.pid)&&Do.set(t,{token:r,capturedAtMs:Date.now()}),r}function ko(t,e){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux"){Yt+=1;try{let r=(0,vo.readFileSync)(`/proc/${t}/stat`,"utf-8"),n=r.lastIndexOf(") ");if(n<0)return null;let i=r.slice(n+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(r){return u.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}if(process.platform==="win32")return ga(t,e);Yt+=1;try{let r=(0,Jt.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Ee(process.env),LC_ALL:"C",LANG:"C"}});return Lo("ps-lstart",t,r)}catch(r){return u.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}function J(t){return ko(t,!1)}function W(t,e){if(e===null)return!0;let r=ko(t,!0);return r===null?!0:r===e}var Io=require("child_process"),rt=require("fs"),Po=require("util");_();var Vt=(0,Po.promisify)(Io.execFile),Sa=128,ha=/not found|no running instance|no tasks/i,et=class extends Error{pid;constructor(e,r,n){super(r,n),this.name="ProcessTreeKillError",this.pid=e}};async function j(t,e={}){let r=e.signalMode==="immediate",n=e.expectedStartToken!==void 0?e.expectedStartToken:J(t),o=()=>W(t,n);if(!o()){u.warn("PROCESS","Skipping tree-kill: root PID was reused since it was captured",{pid:t});return}if(u.debug("PROCESS",`Killing process tree rooted at PID ${t}`,{immediate:r}),process.platform==="win32"){try{await Vt("taskkill",["/PID",String(t),"/T","/F"],{timeout:5e3,windowsHide:!0})}catch(i){let s=i.code,a=String(i.stderr??""),c=i instanceof Error?i.message:String(i);if(s===Sa||ha.test(`${a} ${c}`)){u.debug("PROCESS","taskkill reported the process was already gone",{pid:t});return}throw new et(t,`taskkill failed for PID ${t} (exit ${String(s)}): ${a.trim()||c}`,{cause:i})}return}try{let i=r?"SIGKILL":"SIGTERM",s=await tt(t);for(let l of s){if(!W(l.pid,l.startToken)){u.debug("PROCESS",`Skipping ${i}: descendant PID was reused since enumeration`,{pid:l.pid,rootPid:t});continue}try{process.kill(l.pid,i)}catch{}}if(o())try{process.kill(t,i)}catch(l){let d=l instanceof Error?l:new Error(String(l)),p=d.code;p!=="ESRCH"&&u.debug("PROCESS",`Failed to ${i} PID ${t}`,{code:p},d)}else u.warn("PROCESS","Skipping root signal: PID was reused during descendant enumeration",{pid:t,signal:i});r||await new Promise(l=>setTimeout(l,500));let a=o()?await tt(t):[],c=new Map;for(let l of s)c.set(l.pid,l.startToken);for(let l of a)c.set(l.pid,l.startToken);for(let[l,d]of c){if(!W(l,d)){u.debug("PROCESS","Skipping SIGKILL: descendant PID was reused since the scan",{pid:l,rootPid:t});continue}try{process.kill(l,"SIGKILL")}catch{}}if(!r&&o())try{process.kill(t,"SIGKILL")}catch{}}catch(i){throw new et(t,`tree-kill failed for PID ${t}: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}async function ya(){return process.platform==="win32"?Ca():process.platform==="linux"?Aa():Ta()}function Aa(){let t=[],e;try{e=(0,rt.readdirSync)("/proc")}catch(r){return u.warn("PROCESS","Cannot read /proc \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),t}for(let r of e){if(!/^\d+$/.test(r))continue;let n;try{n=(0,rt.readFileSync)(`/proc/${r}/stat`,"utf-8")}catch{continue}let o=n.lastIndexOf(") ");if(o<0)continue;let i=n.slice(o+2).split(" "),s=Number.parseInt(i[1]??"",10),a=i[19];Number.isFinite(s)&&t.push({pid:Number.parseInt(r,10),ppid:s,startToken:a&&/^\d+$/.test(a)?a:null})}return t}async function Ta(){let t;try{t=(await Vt("ps",["-eo","pid=,ppid=,lstart="],{timeout:1e4,maxBuffer:33554432,env:{...process.env,LC_ALL:"C",LANG:"C"}})).stdout}catch(r){return u.warn("PROCESS","Cannot enumerate the process table \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),[]}let e=[];for(let r of t.split(`
|
|
121
|
+
`)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);if(!n)continue;let o=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:o.length>0?o:null})}return e}async function Ca(){let t;try{t=(await Vt("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,@{Name='StartToken';Expression={$_.CreationDate.ToString('yyyyMMddHHmmss.ffffff')}} | ConvertTo-Csv -NoTypeInformation"],{timeout:3e4,windowsHide:!0,maxBuffer:33554432})).stdout}catch(r){return u.warn("PROCESS","Cannot enumerate the Windows process table \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),[]}let e=[];for(let r of t.split(/\r?\n/).slice(1)){let n=r.match(/^"(\d+)","(\d+)","(.*)"$/);if(!n)continue;let o=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:o.length>0?o:null})}return e}async function tt(t){let e=await ya(),r=new Map;for(let s of e){let a=r.get(s.ppid);a?a.push(s):r.set(s.ppid,[s])}let n=new Set([t]),o=[],i=s=>{for(let a of r.get(s)??[])n.has(a.pid)||(n.add(a.pid),i(a.pid),o.push({pid:a.pid,startToken:a.startToken}))};return i(t),o}var Oa=5e3,Ra=1e3,wa=A.supervisorRegistry(),Da=null;function D(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;return r==="EPERM"?!0:(u.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return u.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function nt(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!D(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function No(t){if(!t||!D(t.pid))return!1;if(!t.startToken)return!0;let e=J(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||u.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}var va={platform:process.platform,readCommandLine:t=>(0,De.readFileSync)(`/proc/${t}/cmdline`,"utf-8")};function Qt(t,e=va){if(!No(t))return!1;if(t.startToken||e.platform!=="linux")return!0;let r;try{r=e.readCommandLine(t.pid)}catch(o){return u.debug("SYSTEM","Could not read the command line of a token-less worker PID; trusting the live PID",{pid:t.pid,error:o instanceof Error?o.message:String(o)}),!0}let n=r.split("\0").some(o=>xo.default.basename(o)==="worker-service.cjs");return n||u.debug("SYSTEM","Token-less worker PID now belongs to another program (PID reused)",{pid:t.pid}),n}var zt=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(e=wa){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,!(0,De.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,De.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[o,i]of Object.entries(n))this.entries.set(o,i)}catch(r){r instanceof Error?u.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):u.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&u.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}retainSupersededEntry(e,r){let n=this.entries.get(e);if(!n||n.pid===r||!D(n.pid))return;let o=`${e}#superseded:${n.pid}`;this.entries.set(o,n);let i=this.runtimeProcesses.get(e);i&&(this.runtimeProcesses.set(o,i),this.runtimeProcesses.delete(e)),u.warn("SYSTEM","Registry id reused while the previous process was still alive; kept it for reaping",{id:e,supersededId:o,supersededPid:n.pid,incomingPid:r})}register(e,r,n){this.initialize(),this.retainSupersededEntry(e,r.pid),this.entries.set(e,r),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e,r){this.initialize();let n=e,o=this.entries.get(n);r!==void 0&&o?.pid!==r&&(n=`${e}#superseded:${r}`,o=this.entries.get(n),o?.pid!==r)||o&&(this.entries.delete(n),this.runtimeProcesses.delete(n),this.persist(),o?.type==="sdk"&&Xt())}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let n=Date.parse(e.startedAt),o=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(o)?0:o)})}getBySession(e){let r=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[n,o]of this.entries)D(o.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,o.type==="sdk"&&(r+=1));e>0&&this.persist();for(let n=0;n<r;n+=1)Xt();return e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;u.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:n,pids:r.map(a=>a.pid)});let o=r.filter(a=>D(a.pid)),i=new Map(o.map(a=>[a.pid,J(a.pid)]));for(let a of o)try{process.platform==="win32"?await j(a.pid,{expectedStartToken:i.get(a.pid)??null}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&u.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):u.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}await nt(o,Oa);let s=o.filter(a=>D(a.pid));for(let a of s){u.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});let c=i.get(a.pid)??null;if(!W(a.pid,c)){u.warn("SYSTEM","Skipping SIGKILL: session process PID was reused during the grace window",{pid:a.pid,sessionId:n});continue}try{process.platform==="win32"?await j(a.pid,{expectedStartToken:c}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(l){l instanceof Error?l.code!=="ESRCH"&&u.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},l):u.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(l)})}}if(s.length>0){let a=Date.now()+Ra;for(;Date.now()<a&&s.filter(l=>D(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let a of r)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of r)a.type==="sdk"&&Xt();return u.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:n,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};try{N(this.registryPath,e),this.persistDegraded=!1}catch(r){this.reportPersistFailure(r)}}reportPersistFailure(e){if(this.persistDegraded)return;this.persistDegraded=!0;let r=e instanceof Error?e:new Error(String(e));u.warn("SYSTEM","Failed to persist supervisor registry; keeping it in memory",{path:this.registryPath},r);try{Da?.({errorCategory:r.code??"unknown"})}catch{}}},qt=null;function ot(){return qt||(qt=new zt),qt}var Ld=180*1e3,La=[];function Xt(){let t=La.shift();t&&t.notify()}var _e=require("fs");_();T();var ka=A.workerPid();async function $o(t){let e=t.currentPid??process.pid,r=t.pidFilePath??ka,n=t.registry.getAll(),o=[...n].filter(c=>c.pid!==e).sort((c,l)=>Date.parse(l.startedAt)-Date.parse(c.startedAt)),i=new Map,s=new Map;for(let c of o){if(!D(c.pid)){t.registry.unregister(c.id);continue}s.set(c.id,J(c.pid)),i.set(c.id,await tt(c.pid));try{await Uo(c,"SIGTERM")}catch(l){l instanceof Error?u.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:c.pid,pgid:c.pgid,type:c.type},l):u.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(l)})}}await nt(o,5e3);let a=o.filter(c=>D(c.pid)||(i.get(c.id)??[]).some(l=>D(l.pid)));for(let c of a){let l=W(c.pid,s.get(c.id)??null);l||u.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:c.pid,type:c.type});try{l&&await Uo(c,"SIGKILL")}catch(d){d instanceof Error?u.debug("SYSTEM","Failed to force kill child process",{pid:c.pid,pgid:c.pgid,type:c.type},d):u.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(d)})}finally{Ia(i.get(c.id)??[],c.pid)}}await nt(a,1e3);for(let c of o)t.registry.unregister(c.id);for(let c of n.filter(l=>l.pid===e))t.registry.unregister(c.id);Ho(r,e),t.registry.pruneDeadEntries()}function Ho(t,e,r=!1){if(!(0,_e.existsSync)(t))return;let n=null;try{let s=JSON.parse((0,_e.readFileSync)(t,"utf-8"));n=typeof s.pid=="number"?s.pid:null}catch(s){u.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:s instanceof Error?s.message:String(s)});return}let o=e!==null&&n===e,i=n===null||!D(n);if(!o&&!(r&&i)){u.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:n,currentPid:e});return}try{(0,_e.rmSync)(t,{force:!0})}catch(s){s instanceof Error?u.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},s):u.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(s)})}}function Ia(t,e){for(let{pid:r,startToken:n}of t)if(!(r===e||!D(r))){if(!W(r,n)){u.debug("SYSTEM","Skipping reap: PID was recycled during the grace window",{pid:r,rootPid:e});continue}try{process.kill(r,"SIGKILL"),u.debug("SYSTEM","Reaped orphaned descendant during shutdown cascade",{pid:r,rootPid:e})}catch(o){let i=o instanceof Error?o.code:void 0;i!=="ESRCH"&&u.warn("SYSTEM","Failed to reap orphaned descendant during shutdown cascade",{pid:r,rootPid:e,errno:i})}}}async function Uo(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}if(e==="SIGKILL"){await j(r,{signalMode:"immediate"});return}try{process.kill(r,e)}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}return}await j(r)}_();var Fo=3e4,ge=null;function Pa(){let e=ot().pruneDeadEntries();e>0&&u.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function Wo(){ge===null&&(ge=setInterval(Pa,Fo),ge.unref(),u.debug("SYSTEM","Health checker started",{intervalMs:Fo}))}function jo(){ge!==null&&(clearInterval(ge),ge=null,u.debug("SYSTEM","Health checker stopped"))}var Bo=require("child_process"),Ko=require("util");_();var xa=(0,Ko.promisify)(Bo.execFile),Na=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/;function Ua(t){let e=[];for(let r of t.split(`
|
|
122
|
+
`)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);n&&e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),command:n[3].trim()})}return e}async function $a(){let t=await xa("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return Ua(t.stdout)}function Ha(t,e){let r=t.filter(s=>Na.test(s.command)&&s.pid!==e.selfPid),n=new Set(r.map(s=>s.pid)),o=r.filter(s=>!n.has(s.ppid)),i=o.filter(s=>s.ppid===e.selfPid?!1:s.ppid===1?!0:!e.isAlive(s.ppid));return{matched:r,roots:o,orphans:i}}async function Go(t={}){let e=t.platform??process.platform,r={matched:0,trees:0,orphans:0,killed:0,failed:0,unregistered:0,skipped:null};if(e==="win32")return r.skipped="windows",r;let n=t.readTable??$a,o=t.isAlive??D,i=t.killTree??(E=>j(E,{signalMode:"graceful"})),s=t.selfPid??process.pid,a;try{a=await n()}catch(E){return u.warn("PROCESS","Orphaned chroma-mcp sweep skipped: cannot read the process table",{error:E instanceof Error?E.message:String(E)}),r.skipped="unreadable",r}let{matched:c,roots:l,orphans:d}=Ha(a,{isAlive:o,selfPid:s});if(r.matched=c.length,r.trees=l.length,r.orphans=d.length,d.length===0)return u.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:r.matched,trees:r.trees}),r;u.warn("PROCESS","Reaping orphaned chroma-mcp trees left by dead workers",{orphans:d.length,roots:d.map(E=>E.pid)});let p=new Set,f=8;for(let E=0;E<d.length;E+=f){let S=d.slice(E,E+f);(await Promise.allSettled(S.map(y=>i(y.pid)))).forEach((y,P)=>{let x=S[P];y.status==="fulfilled"?(r.killed+=1,p.add(x.pid)):(r.failed+=1,u.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:x.pid,ppid:x.ppid,error:y.reason instanceof Error?y.reason.message:String(y.reason)}))})}if(t.registry)for(let E of t.registry.getAll())E.type==="chroma"&&p.has(E.pid)&&(t.registry.unregister(E.id),r.unregistered+=1);return u.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:r.orphans,killed:r.killed,failed:r.failed,unregistered:r.unregistered}),r}T();var Fa=A.workerPid(),Zt=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(),Jo({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,Go({registry:this.registry}).catch(r=>{u.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),Wo()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){u.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,u.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(o){o instanceof Error?u.error("SYSTEM","Error during shutdown",{},o):u.error("SYSTEM","Error during shutdown (non-Error)",{error:String(o)});try{await this.stop()}catch(i){i instanceof Error?u.debug("SYSTEM","Supervisor shutdown fallback failed",{},i):u.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(i)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{u.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}jo(),this.stopPromise=$o({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,r,n){this.registry.register(e,r,n)}unregisterProcess(e,r){this.registry.unregister(e,r)}getRegistry(){return this.registry}},zd=new Zt(ot());function Jo(t={}){let e=t.pidFilePath??Fa;if(!(0,ne.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,ne.readFileSync)(e,"utf-8"))}catch(o){return o instanceof Error?u.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},o):u.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(o)}),(0,ne.rmSync)(e,{force:!0}),"invalid"}return Qt(r)&&r?((t.logAlive??!0)&&u.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(t.removeStale===!1||(u.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,ne.rmSync)(e,{force:!0})),"stale")}Le();T();$();_();_();var ff=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","stage","phase","install_method","interactive","provider_source","bun_version","uv_version","claude_code_version","trial_days","trial_variant","offer_surface","funnel_source","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","limit_window","overage_status","is_using_overage","resets_in_minutes","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_aborted_deadline_exceeded","outcomes_invalid_output","top_model","top_abort_reason","observed_model","observed_billing","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","skill_id","skill_source","skill_trigger","observations_created","total_observations_injected","total_tokens_saved_vs_naive","platform","agent_role","instruction_state","instruction_returned_count","instruction_disabled_count","instruction_excluded_count","instruction_missing_count","instruction_unknown_count","captured_prompt_count","captured_session_count","captured_tool_count","unidentified_tool_event_count","native_todo_count",...["captured","mcp"].flatMap(t=>["read","write"].flatMap(e=>[`${t}_${e}_count`,...["ok","error","excluded","disabled","unknown"].map(r=>`${t}_${e}_${r}_count`)]))]);_();_();_();_();T();var Jf=G(U.POWERSHELL_COMMAND);var Vf=A.dataDir(),qf=A.workerPid();_();T();_();T();_();var ja=9e4,Em=ja/3;var Vo=require("node:child_process");var qo=require("node:util");_();T();var wm=(0,qo.promisify)(Vo.execFile);var Ba=1500,Ka=1e3,Ga=5500,Dm=2*Ba+Ka+Ga;$();function Xo(t,e,r){let n=process.env[t];if(n){let o=parseInt(n,10);if(Number.isFinite(o)&&o>=r.min&&o<=r.max)return o;u.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max})}return e}var pp=Xo("CLAUDE_MEM_HEALTH_TIMEOUT_MS",G(U.HEALTH_CHECK),{min:500,max:3e5}),Ep=Xo("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",G(U.HOOK_READINESS_WAIT),{min:0,max:3e5});var _p={min:500,max:U.SESSION_INIT_REQUEST_MAX};function zo(t=process.env){let e=t.CLAUDE_MEM_FETCH_VERBOSE;if(e===void 0)return!1;let r=e.trim().toLowerCase();return r==="1"||r==="true"||r==="on"||r==="yes"}function Ja(t){return zo()?{...t,verbose:!0}:t}function Va(t){let e={},r=t;for(let n=0;r&&n<4;n++){let o=n===0?"error":`cause${n}`;if(r instanceof Error){let i=r;e[o]={name:r.name,message:r.message,...i.code!==void 0?{code:i.code}:{}},r=r.cause;continue}e[o]=String(r);break}return e}function qa(t,e,r){let n=typeof e.method=="string"?e.method:"GET",o=Va(r),i=JSON.stringify(o);u.warn("SYSTEM","Worker IPC fetch failed",{url:t,method:n},i),V(`[claude-mem] fetch verbose: ${n} ${t} ${i}
|
|
123
|
+
`)}async function Xa(t,e={}){let r=Ja(e);try{return await fetch(t,r)}catch(n){throw zo()&&qa(t,e,n),n}}async function Qo(t,e={},r){try{return await Xa(t,{...e,signal:AbortSignal.timeout(r)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new Error(`Request timed out after ${r}ms`):n}}var za=1e3;var Qa=5e3,gp=Qa+za;var Za=G(U.API_REQUEST),ee=class extends Error{kind;status;cause;constructor(e,r,n={}){super(r),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)}},st=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=ec(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??Za}async startSession(e,r={}){let n=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",n,r)}async recordEvent(e){let r=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(e){if(!e.sessionId)throw new ee("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,r={}){let n={projectId:e.projectId};return e.query!==void 0&&(n.query=e.query),e.limit!==void 0&&(n.limit=e.limit),e.summaryLimit!==void 0&&(n.summaryLimit=e.summaryLimit),e.platformSource!==void 0&&(n.platformSource=it(e.platformSource)),e.folderProjects&&e.folderProjects.length>0&&(n.folderProjects=e.folderProjects),e.excludeSubagents!==void 0&&(n.excludeSubagents=e.excludeSubagents),this.request("POST","/v1/context",n,r)}async getJobStatus(e){if(!e)throw new ee("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,content:r,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.platformSource!==void 0?{platformSource:e.platformSource}:{},...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:it(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:it(e.platformSource)}:{},...e.metadata!==void 0?{metadata:vt(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:it(e.platformSource)}:{},...e.payload!==void 0?{payload:vt(e.payload)}:{}}}async request(e,r,n,o={}){if(!this.apiKey||!this.apiKey.trim())throw new ee("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let i=`${this.baseUrl}${r}`,s={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(s.body=JSON.stringify(n));let a=p=>{let f=p instanceof Error?p.message:String(p),E=/timed out|timeout/i.test(f)||p instanceof Error&&(p.name==="TimeoutError"||p.name==="AbortError");return new ee(E?"timeout":"transport",`Server ${e} ${r} failed: ${f}`,{cause:p})},c,l=o.timeoutMs??this.timeoutMs;try{c=await Qo(i,s,l)}catch(p){throw a(p)}if(!c.ok){let p=await c.text().catch(()=>"");throw new ee("http_error",`Server ${e} ${r} returned ${c.status}: ${tc(p,200)}`,{status:c.status})}let d;try{d=await c.text()}catch(p){throw a(p)}if(!d||d.length===0)return{};try{return JSON.parse(d)}catch(p){let f=p instanceof Error?p:new Error(String(p));throw new ee("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:f})}}};function ec(t){return t.replace(/\/+$/,"")}function it(t){return typeof t=="string"?Fe(t):null}function tc(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function rc(){let e=(me().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function nc(){let t=me(),e=(...s)=>{for(let a of s){let c=(a??"").trim();if(c.length>0)return c}return""},r=e(t.CLAUDE_MEM_SERVER_URL,t.CLAUDE_MEM_SERVER_BETA_URL),n=e(t.CLAUDE_MEM_SERVER_API_KEY,t.CLAUDE_MEM_SERVER_BETA_API_KEY),o=e(t.CLAUDE_MEM_SERVER_PROJECT_ID,t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!r)return u.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return u.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return u.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let i={serverBaseUrl:r,apiKey:n};return{runtime:"server",client:new st(i),projectId:o,serverBaseUrl:r}}function Zo(){if(rc()!=="server")return{runtime:"worker"};let t=nc();return t||{runtime:"worker"}}_();async function ei(t,e){let{config:r,project:n,folderProjects:o,platformSource:i,timeoutMs:s}=e,a=r.totalObservationCount+r.sessionCount+ae,c=Math.max(1,Math.min(200,a));a>200&&u.debug("HOOK","Server context read capped at the route limit",{wanted:a,limit:200});let l;try{let f=await t.client.contextObservations({projectId:t.projectId,limit:c,...a<=200?{summaryLimit:r.sessionCount+ae}:{},folderProjects:o,excludeSubagents:r.mainAgentOnly,...i?{platformSource:i}:{}},s===void 0?{}:{timeoutMs:s});l=Array.isArray(f?.observations)?f.observations:[]}catch(f){return u.warn("HOOK","[server-fallback] session-start context unavailable from the server",{error:f instanceof Error?f.message:String(f)}),null}let d=l.filter(f=>f.kind==="summary");return{observations:l.filter(f=>f.kind!=="summary").slice(0,r.totalObservationCount).map(f=>oc(f,n,i)),summaries:d.slice(0,r.sessionCount+ae).map(f=>ic(f,n,i))}}function M(t,...e){let r=t.metadata??{};for(let n of e){if(t[n]!==void 0&&t[n]!==null)return t[n];if(r[n]!==void 0&&r[n]!==null)return r[n]}return null}function O(t){return typeof t=="string"?t:t==null?null:String(t)}function ct(t){if(t==null)return null;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return null}}function ti(t){return Number(M(t,"createdAtEpoch","created_at_epoch"))||Date.now()}function oc(t,e,r){let n=ti(t),o=O(t.content)??"",i=o.split(`
|
|
124
|
+
`,1)[0]??"";return{id:O(t.id)??"",memory_session_id:O(M(t,"serverSessionId","memory_session_id"))??"",content_session_id:O(M(t,"contentSessionId","content_session_id"))??void 0,platform_source:r??"",type:O(M(t,"kind","type"))??"discovery",title:O(M(t,"title"))??i,subtitle:O(M(t,"subtitle")),narrative:O(M(t,"narrative"))??(o||null),facts:ct(M(t,"facts")),concepts:ct(M(t,"concepts")),files_read:ct(M(t,"files_read","filesRead")),files_modified:ct(M(t,"files_modified","filesModified")),discovery_tokens:null,created_at:new Date(n).toISOString(),created_at_epoch:n,project:O(M(t,"project"))??e}}function ic(t,e,r){let n=ti(t);return{id:O(t.id)??"",memory_session_id:O(M(t,"serverSessionId","memory_session_id"))??"",platform_source:r??"",request:O(M(t,"request")),investigated:O(M(t,"investigated")),learned:O(M(t,"learned")),completed:O(M(t,"completed")),next_steps:O(M(t,"next_steps","nextSteps")),notes:O(M(t,"notes")),created_at:new Date(n).toISOString(),created_at_epoch:n,project:O(M(t,"project"))??e}}var er=require("crypto");T();$();_();var Hp=1440*60*1e3,sc=(0,er.randomBytes)(6).toString("hex");function ac(t){return`\u27E6CMEM_NOW_HEADER:${t}\u27E7`}var tr=ac(sc),cc=40,ri=Math.max(0,cc-tr.length);var uc=oi.default.join((0,ii.homedir)(),".claude","plugins","marketplaces","thedotmack","plugin",".install-version");function dc(){try{if(!(0,ut.existsSync)(Et))return null;let t=new si.Database(Et,{readonly:!0,create:!1});try{return t.run(`PRAGMA busy_timeout = ${$r}`),t}catch(e){throw t.close(),e}}catch(t){if(t instanceof Error&&t.code==="ERR_DLOPEN_FAILED"){try{(0,ut.unlinkSync)(uc)}catch(e){e instanceof Error?u.debug("WORKER","Marker file cleanup failed (may not exist)",{},e):u.debug("WORKER","Marker file cleanup failed (may not exist)",{error:String(e)})}return u.error("WORKER","Native module rebuild needed - restart Claude Code to auto-fix"),null}throw t}}function fc(t,e,r){return e?qn(t,r):Un(t,r)}function ni(t,e,r,n,o,i,s,a){let c=[],l=Rt(e);c.push(...Xn(t,l,n,s,a));let d=r.slice(0,n.sessionCount),p=yn(d,r),f=An(e,p),E=Tn(e,n.fullObservationCount),S=s?eo(f,E,n,o):void 0,R=c.join(`
|
|
125
125
|
`).length+1;c.push(...S?ze(S):Zn(f,E,n));let y=c.join(`
|
|
126
126
|
`).length,P=r[0],x=e[0];to(n,P,x)&&c.push(...ro(P,s));let I=c.join(`
|
|
127
127
|
`).length,dt=hn(e,n,i,o);c.push(...no(dt,s));let di=c.join(`
|
|
@@ -132,10 +132,10 @@ ${m.dim}No previous sessions found for this project yet.${m.reset}
|
|
|
132
132
|
|
|
133
133
|
${o}`:o),n?t?ai(n):n:""}function lt(t,e=!1){return t?.includeHealthWarning===!1?"":Ec(e)}function rr(t,e){return t?e?`${e}
|
|
134
134
|
|
|
135
|
-
${t}`:t:e}function
|
|
135
|
+
${t}`:t:e}function _c(t,e){let{text:r,timelineStart:n,timelineEnd:o,entries:i,summaryEnd:s,previousEnd:a}=typeof t=="string"?{text:t,timelineStart:0,timelineEnd:t.length,entries:void 0,summaryEnd:t.length,previousEnd:t.length}:t;if(r.length<=e)return r;let c=dt=>r.slice(0,n)+`${m.reset}
|
|
136
136
|
|
|
137
137
|
[Terminal preview truncated. The model received the full selected context; ${dt?"additional observations are not shown here.":"some presentation text is not shown here."}]
|
|
138
138
|
`,l=r.slice(a),d=r.slice(o,s),p=r.slice(s,a);if(!i)return(c(!1)+r.slice(n)).slice(0,e);let f=0,E=ze(i).join(`
|
|
139
139
|
`),S=c(!1),R=S.length+E.length+l.length<=e?S:c(!0);for(;f<i.length&&R.length+E.length+l.length>e;)f++,E=ze(i.slice(f)).join(`
|
|
140
|
-
`);let y=e-R.length-E.length-l.length,P=d.length<=y?d:"",x=y-P.length,I="";return p.length<=x?I=p:x>24&&(I=p.slice(0,x-1-m.reset.length)+"\u2026"+m.reset),R+E+P+I+l}function
|
|
140
|
+
`);let y=e-R.length-E.length-l.length,P=d.length<=y?d:"",x=y-P.length,I="";return p.length<=x?I=p:x>24&&(I=p.slice(0,x-1-m.reset.length)+"\u2026"+m.reset),R+E+P+I+l}function gc(t,e,r,n,o,i,s,a){let c=Yr(t,r,(p,f)=>rr(n,o(p,f)),i);c.reductions>0&&u.debug("HOOK","Trimmed context to fit the hook output limit",{reductions:c.reductions,observations:c.observationCount,sessions:c.config.sessionCount,chars:c.text.length,overBudget:c.overBudget});let l=t.slice(0,c.observationCount),d=c.text;if(a){let p=ai(n),f=p?p.length+2:0;d=rr(p,_c(a(l,c.config),i-f))}return{text:d,stats:pc(l,e.slice(0,c.config.sessionCount),s)}}function ci(t){let e=Gr();t?.includePriorMessage===!1&&(e.showLastMessage=!1);let r=t?.cwd??process.cwd(),n=t?.projects?.length?t.projects:Nr(r).allProjects,o=n[n.length-1];t?.full&&(e.totalObservationCount=999999,e.sessionCount=999999);let i=t?.platformSource?Fe(t.platformSource):void 0;return{config:e,cwd:r,projects:n,project:o,platformSource:i}}function li(t,e,r,n){let{observations:o,summaries:i}=t,{config:s,cwd:a,project:c}=n,l=e?.timePlaceholders?tr:Y(),d=e?.timePlaceholders?ri:0;return o.length===0&&i.length===0?{text:rr(lt(e,r),fc(c,r,l)),stats:null}:gc(o,i,s,lt(e),(p,f)=>ni(c,p,i,f,a,e?.session_id,!1,l).text,e?.full?Number.POSITIVE_INFINITY:1e4-(e?.reserveChars??0)-d,!!e?.full,r?(p,f)=>ni(c,p,i,f,a,e?.session_id,!0,l):void 0)}async function Sc(t,e,r){let n=ci(e);n.config.fetchByIdSupported=!1;let o=await ei(t,{config:n.config,project:n.project,folderProjects:n.projects,platformSource:n.platformSource,...r===void 0?{}:{timeoutMs:r}});return{scope:n,rows:o}}function hc(t,e,r){return t.rows?li(t.rows,e,r,t.scope):{text:lt(e,r),stats:null}}async function yc(t,e,r=!1){return hc(await Sc(t,e),e,r)}async function nr(t,e=!1){let r=Zo();if(r.runtime==="server")return yc(r,t,e);let n=ci(t),o=dc();if(!o)return{text:lt(t,e),stats:null};try{let i={db:o},s=Fr(o,n.projects.length>1?n.projects:[n.project]),a=gn(i,s,n.config,n.platformSource),c=kt(i,s,n.config,n.platformSource);return li({observations:a,summaries:c},t,e,n)}finally{o.close()}}async function ui(t,e=!1){return(await nr(t,e)).text}0&&(module.exports={generateContext,generateContextWithStats});
|
|
141
141
|
//# sourceMappingURL=context-generator.cjs.map
|