claude-mem 13.30.0 → 13.31.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/README.md +1 -1
- package/dist/npx-cli/index.js +1 -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/hooks/hooks.json +6 -1
- package/plugin/package.json +1 -1
- package/plugin/scripts/context-generator.cjs +72 -55
- package/plugin/scripts/context-generator.cjs.map +2 -2
- package/plugin/scripts/mcp-server.cjs +39 -37
- package/plugin/scripts/mcp-server.cjs.map +2 -2
- package/plugin/scripts/server-service.cjs +3 -3
- package/plugin/scripts/server-service.cjs.map +1 -1
- package/plugin/scripts/transcript-watcher.cjs +2 -2
- package/plugin/scripts/transcript-watcher.cjs.map +1 -1
- package/plugin/scripts/worker-service.cjs +384 -367
- package/plugin/scripts/worker-service.cjs.map +2 -2
- package/plugin/skills/version-bump/SKILL.md +28 -19
- package/plugin/sqlite/SessionStore.js +65 -65
- package/plugin/sqlite/SessionStore.js.map +1 -1
- package/plugin/ui/viewer-bundle.js +12 -12
|
@@ -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
|
|
4
|
-
`);let m=(0,_.readlinkSync)(t);n=(0,x.resolve)((0,x.dirname)(t),m)}}catch(p){let d=p.code;if(d!=="ENOENT"&&d!=="ENOTDIR")throw p}
|
|
5
|
-
`,"utf-8"),s=r.mode;if(s===void 0)try{s=(0,_.statSync)(n).mode&511}catch{}let u;try{u=s!==void 0?(0,_.openSync)(a,"w",s):(0,_.openSync)(a,"w");let p=0;for(;p<c.length;){let d=(0,_.writeSync)(u,c,p,c.length-p);if(d===0)throw new Error(`writeSync stalled at ${p}/${c.length} bytes`);p+=d}if((0,_.fsyncSync)(u),(0,_.closeSync)(u),u=void 0,(0,_.renameSync)(a,n),!
|
|
6
|
-
`)}finally{if(d!==void 0)try{(0,_.closeSync)(d)}catch{}}}}catch(p){if(u!==void 0)try{(0,_.closeSync)(u)}catch{}try{(0,_.unlinkSync)(a)}catch{}throw p}}var _,
|
|
3
|
+
"use strict";var Po=Object.create;var Te=Object.defineProperty;var xo=Object.getOwnPropertyDescriptor;var No=Object.getOwnPropertyNames;var Uo=Object.getPrototypeOf,$o=Object.prototype.hasOwnProperty;var Q=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(n){throw r=[n],n}};var Fo=(t,e)=>{for(var r in e)Te(t,r,{get:e[r],enumerable:!0})},Bt=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of No(e))!$o.call(t,o)&&o!==r&&Te(t,o,{get:()=>e[o],enumerable:!(n=xo(e,o))||n.enumerable});return t};var ne=(t,e,r)=>(r=t!=null?Po(Uo(t)):{},Bt(e||!t||!t.__esModule?Te(r,"default",{value:t,enumerable:!0}):r,t)),Ho=t=>Bt(Te({},"__esModule",{value:!0}),t);function jo(t){return(Wo??process.stderr.write.bind(process.stderr))(t)}function Y(t){jo(t)}var Wo,ya,Ce=Q(()=>{"use strict";Wo=null;ya=Promise.resolve()});function Yt(t){return t.replace(/^\uFEFF/,"")}function be(t){return JSON.parse(Yt(t))}function de(t){return be((0,_.readFileSync)(t,"utf-8"))}function Ko(t){(0,_.existsSync)(t)||(0,_.mkdirSync)(t,{recursive:!0})}function L(t,e,r={}){let n=t;try{if((0,_.lstatSync)(t).isSymbolicLink())try{n=(0,_.realpathSync)(t)}catch(p){let d=p instanceof Error?p:new Error(String(p));Y(`claude-mem: realpathSync failed for ${t}, resolving symlink manually: ${d.message}
|
|
4
|
+
`);let m=(0,_.readlinkSync)(t);n=(0,x.resolve)((0,x.dirname)(t),m)}}catch(p){let d=p.code;if(d!=="ENOENT"&&d!=="ENOTDIR")throw p}Ko((0,x.dirname)(n));let o=(0,x.dirname)(n),i=(0,x.basename)(n),a=(0,x.join)(o,`.${i}.${process.pid}.${(0,Kt.randomBytes)(6).toString("hex")}.tmp`),c=Buffer.from(JSON.stringify(e,null,2)+`
|
|
5
|
+
`,"utf-8"),s=r.mode;if(s===void 0)try{s=(0,_.statSync)(n).mode&511}catch{}let u;try{u=s!==void 0?(0,_.openSync)(a,"w",s):(0,_.openSync)(a,"w");let p=0;for(;p<c.length;){let d=(0,_.writeSync)(u,c,p,c.length-p);if(d===0)throw new Error(`writeSync stalled at ${p}/${c.length} bytes`);p+=d}if((0,_.fsyncSync)(u),(0,_.closeSync)(u),u=void 0,(0,_.renameSync)(a,n),!Bo){let d;try{d=(0,_.openSync)(o,"r"),(0,_.fsyncSync)(d)}catch(m){let g=m instanceof Error?m:new Error(String(m));Y(`claude-mem: directory fsync failed for ${o}: ${g.message}
|
|
6
|
+
`)}finally{if(d!==void 0)try{(0,_.closeSync)(d)}catch{}}}}catch(p){if(u!==void 0)try{(0,_.closeSync)(u)}catch{}try{(0,_.unlinkSync)(a)}catch{}throw p}}var _,Kt,x,Bo,N=Q(()=>{"use strict";_=require("fs"),Kt=require("crypto"),x=require("path");Ce();Bo=process.platform==="win32"});function Gt(t){let e=t.env;return Yo(e)&&Object.keys(e).some(r=>r.startsWith("CLAUDE_MEM_"))?"nested":"flat"}function oe(t){return Gt(t)==="nested"?t.env:t}function Jt(t){return Gt(t)!=="nested"?t:Object.fromEntries(Object.entries(t).filter(([e])=>!e.startsWith("CLAUDE_MEM_")))}var Yo,Me=Q(()=>{"use strict";N();Yo=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)});function U(t,e=process.platform,r=(0,qt.homedir)()){return typeof t!="string"||t.length===0?t:t==="~"?r:t.startsWith("~/")||e==="win32"&&t.startsWith("~\\")?(0,Vt.join)(r,t.slice(2)):t}var qt,Vt,fe=Q(()=>{"use strict";qt=require("os"),Vt=require("path")});function Go(){return typeof __CM_DIRNAME__<"u"?__CM_DIRNAME__:(0,S.dirname)((0,Xt.fileURLToPath)(Xo.url))}function pe(){if(process.env.CLAUDE_MEM_DATA_DIR)return U(process.env.CLAUDE_MEM_DATA_DIR);let t=(0,S.join)((0,we.homedir)(),".claude-mem"),e=(0,S.join)(t,"settings.json");try{if((0,rt.existsSync)(e)){let r=de(e);if(r===null||typeof r!="object"||Array.isArray(r))return t;let n=oe(r);if(typeof n.CLAUDE_MEM_DATA_DIR=="string"&&n.CLAUDE_MEM_DATA_DIR)return U(n.CLAUDE_MEM_DATA_DIR)}}catch{}return t}function Zt(){return(0,S.join)(Jo,"..")}function er(t,e=(0,we.homedir)(),r=process.platform){return U(t,r,e)}var S,we,rt,Xt,Xo,Jo,A,nt,H,qo,Vo,Z,zt,ot,Qt,Ia,h,y=Q(()=>{"use strict";S=require("path"),we=require("os"),rt=require("fs"),Xt=require("url");N();Me();fe();fe();Xo={};Jo=Go();A=pe(),nt=(0,S.join)((0,we.homedir)(),".claude"),H=process.env.CLAUDE_CONFIG_DIR||nt,qo=(0,S.join)(H,"plugins","marketplaces","thedotmack"),Vo=(0,S.join)(A,"logs"),Z=(0,S.join)(A,"settings.json"),zt="claude-mem.db",ot=(0,S.join)(A,zt),Qt=(0,S.join)(A,"observer-sessions"),Ia=(0,S.basename)(Qt);h={dataDir:()=>A,workerPid:()=>(0,S.join)(A,"worker.pid"),serverPid:()=>(0,S.join)(A,".server-beta.pid"),serverPort:()=>(0,S.join)(A,".server-beta.port"),serverRuntime:()=>(0,S.join)(A,".server-beta.runtime.json"),settings:()=>(0,S.join)(A,"settings.json"),database:()=>(0,S.join)(A,zt),chroma:()=>(0,S.join)(A,"chroma"),combinedCerts:()=>(0,S.join)(A,"combined_certs.pem"),transcriptsConfig:()=>(0,S.join)(A,"transcript-watch.json"),transcriptsState:()=>(0,S.join)(A,"transcript-watch-state.json"),corpora:()=>(0,S.join)(A,"corpora"),supervisorRegistry:()=>(0,S.join)(A,"supervisor.json"),envFile:()=>(0,S.join)(A,".env"),logsDir:()=>Vo}});var ee,tr,st,it,at,l,E=Q(()=>{"use strict";ee=require("fs"),tr=require("path");y();Ce();N();Me();st=(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))(st||{}),it=null,at=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;logFileDate=null;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){let e=new Date().toISOString().split("T")[0];if(!(this.logFileInitialized&&this.logFileDate===e)){this.logFileInitialized=!0,this.logFileDate=e;try{let r=h.logsDir();(0,ee.existsSync)(r)||(0,ee.mkdirSync)(r,{recursive:!0}),this.logFilePath=(0,tr.join)(r,`claude-mem-${e}.log`)}catch(r){console.error("[LOGGER] Failed to initialize log file:",r instanceof Error?r.message:String(r)),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let e=h.settings();if((0,ee.existsSync)(e)){let n=(oe(de(e)).CLAUDE_MEM_LOG_LEVEL||"INFO").toString().toUpperCase();this.level=st[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=(a,c)=>{if(typeof a=="bigint")return`${a}n`;if(a===null||typeof a!="object")return a;let s=a.toJSON,u=typeof s=="function"?s.call(a):a;if(typeof u=="bigint")return`${u}n`;if(u===null||typeof u!="object")return u;if(o.has(u))return"[Circular]";if(c>=n)return Array.isArray(u)?"[Array]":"[Object]";o.add(u);try{if(Array.isArray(u))return u.map(d=>i(d,c+1));let p={};for(let d of Object.keys(u))try{p[d]=i(u[d],c+1)}catch{p[d]="[unreadable]"}return p}finally{o.delete(u)}};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
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(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"),a=String(e.getMinutes()).padStart(2,"0"),c=String(e.getSeconds()).padStart(2,"0"),s=String(e.getMilliseconds()).padStart(3,"0");return`${r}-${n}-${o} ${i}:${a}:${c}.${s}`}log(e,r,n,o,i){if(e<this.getLevel())return;this.ensureLogFileInitialized();let a=this.formatTimestamp(new Date),c=st[e].padEnd(5),s=r.padEnd(6),u="";o?.correlationId?u=`[${o.correlationId}] `:o?.sessionId&&(u=`[session-${o.sessionId}] `);let p="";i!=null&&(i instanceof Error?p=this.getLevel()===0?`
|
|
8
8
|
${i.message}
|
|
9
9
|
${i.stack}`:` ${i.message}`:this.getLevel()===0&&typeof i=="object"?p=`
|
|
10
|
-
`+this.safeStringify(i,2):p=" "+this.formatData(i));let d="";if(o){let{sessionId:g,memorySessionId:
|
|
11
|
-
`,"utf8")}catch(g){let
|
|
12
|
-
${
|
|
13
|
-
`)}else
|
|
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){it=e}error(e,r,n,o){this.log(3,e,r,n,o),this.routeErrorToSink(r,n,o)}routeErrorToSink(e,r,n){try{if(!it||!(n instanceof Error))return;it(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)}},l=new at});var Ei,Ar,Tr=Q(()=>{"use strict";Ei=require("bun:sqlite");E();Ar=5e3});var Ea={};No(Ea,{generateContext:()=>vo,generateContextWithStats:()=>Wt});module.exports=Uo(Ea);var Co=ne(require("path"),1),bo=require("os"),et=require("fs"),Mo=require("bun:sqlite");y();E();var O=ne(require("path"),1),ie=require("fs"),De=require("os"),pt=require("child_process");fe();y();var te=require("fs"),Y=require("path"),me=require("os");var L={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 qo(t=process.platform){return t==="win32"?8e3:5e3}function ct(t=process.platform){return L.SESSION_INIT_HOOK_CAP-qo(t)}function W(t){return process.platform==="win32"?Math.round(t*L.WINDOWS_MULTIPLIER):t}N();E();function tr(t){try{return new URL(t).hostname.toLowerCase()==="openrouter.ai"}catch{return!1}}Me();var Vo="security_alert",Xo="sync-hub.black-pond-afbb.workers.dev",zo="https://sync.cmem.ai",Qo=new Set(["xiaomi/mimo-v2-flash:free"]);function Zo(t){let e=t.CLAUDE_MEM_OPENROUTER_MODEL;if(typeof e!="string"||!Qo.has(e.trim()))return!1;let r=typeof t.CLAUDE_MEM_OPENROUTER_BASE_URL=="string"?t.CLAUDE_MEM_OPENROUTER_BASE_URL.trim():"";return r===""||tr(r)}var rr=18e4,nr=[{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 ir(t,e){return(0,Y.join)((0,Y.dirname)(t),`.${(0,Y.basename)(t)}.${e.markerTag}`)}function lt(t,e){try{(0,te.writeFileSync)(ir(t,e),new Date().toISOString(),{encoding:"utf-8",mode:384})}catch{}}var or=new Set;function ei(t){if(typeof t!="string")return null;let e=t.trim();if(e.length===0)return null;try{if(new URL(e).hostname===Xo)return zo}catch{return null}return null}var R=class{static DEFAULTS={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_ALLOWED_ORIGINS:"",CLAUDE_MEM_PUBLIC_URL:"",CLAUDE_MEM_API_TIMEOUT_MS:String(W(L.API_REQUEST)),CLAUDE_MEM_SESSION_INIT_TIMEOUT_MS:String(ct()),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_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_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_MEM_QUOTA_FALLBACK_MODEL:"",CLAUDE_MEM_DATA_DIR:(0,Y.join)((0,me.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_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_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,Y.join)((0,me.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_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_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_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_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,me.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_LLM_TIMEOUT_MS:String(rr),CLAUDE_MEM_FIELD_OPTIMIZE_TIMEOUT_MS:String(rr),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_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){try{if(!(0,te.existsSync)(e)){let d=this.getAllDefaults();try{I(e,d,{mode:384});for(let m of nr)lt(e,m);console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(m){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,m instanceof Error?m.message:String(m))}return this.finalizeSettings(d,r)}let n=(0,te.readFileSync)(e,"utf-8"),o=be(n),i=oe(o),a=i!==o,c=Yt(o),s=a&&Object.keys(c).some(d=>d!=="env");if(a&&!s)try{I(e,i,{mode:384}),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(d){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,d instanceof Error?d.message:String(d))}if(i.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES===Vo){i={...i,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES};try{I(e,s?{...c,env:i}:i,{mode:384}),console.warn("[SETTINGS] Migrated Telegram trigger types off the legacy default:",e)}catch(d){console.warn("[SETTINGS] Failed to migrate Telegram trigger types:",e,d instanceof Error?d.message:String(d))}}if(Zo(i)){let d=String(i.CLAUDE_MEM_OPENROUTER_MODEL).trim();i={...i,CLAUDE_MEM_OPENROUTER_MODEL:this.DEFAULTS.CLAUDE_MEM_OPENROUTER_MODEL};try{I(e,s?{...c,env:i}:i,{mode:384}),console.warn(`[SETTINGS] Migrated OpenRouter model off the retired default ${d} to ${this.DEFAULTS.CLAUDE_MEM_OPENROUTER_MODEL}:`,e)}catch(m){console.warn("[SETTINGS] Failed to migrate the retired OpenRouter model:",e,m instanceof Error?m.message:String(m))}}let u=ei(i.CLAUDE_MEM_CLOUD_SYNC_HUB_URL);if(u!==null){i={...i,CLAUDE_MEM_CLOUD_SYNC_HUB_URL:u};try{I(e,s?{...c,env:i}:i,{mode:384}),console.warn("[SETTINGS] Migrated cloud sync hub URL off the legacy workers.dev host:",e)}catch(d){console.warn("[SETTINGS] Failed to migrate cloud sync hub URL:",e,d instanceof Error?d.message:String(d))}}for(let d of nr)if(!(0,te.existsSync)(ir(e,d))){if(i[d.key]!==d.legacy){lt(e,d);continue}i={...i,[d.key]:this.DEFAULTS[d.key]};try{I(e,s?{...c,env:i}:i,{mode:384}),lt(e,d),console.warn(`[SETTINGS] Migrated ${d.key} off the old ${d.legacy}ms default to ${this.DEFAULTS[d.key]}ms:`,e)}catch(m){let g=`${d.key}\0${e}`;or.has(g)||(or.add(g),console.warn(`[SETTINGS] Failed to migrate ${d.key}; using the new default in memory (reported once per process):`,e,m instanceof Error?m.message:String(m)))}}let p={...this.DEFAULTS};for(let d of Object.keys(this.DEFAULTS))i[d]!==void 0&&(p[d]=i[d]);return this.finalizeSettings(p,r)}catch(n){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,n instanceof Error?n.message:String(n));let o=this.getAllDefaults();return this.finalizeSettings(o,r)}}};E();var Re=require("fs"),J=ne(require("path"),1);E();var ge={isWorktree:!1,isSubmodule:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function sr(t){let e=J.default.join(t,".git"),r;try{r=(0,Re.statSync)(e)}catch(s){return s instanceof Error&&s.code!=="ENOENT"&&l.warn("GIT","Unexpected error checking .git",{error:s instanceof Error?s.message:String(s)}),ge}if(!r.isFile())return ge;let n;try{n=(0,Re.readFileSync)(e,"utf-8").trim()}catch(s){return l.warn("GIT","Failed to read .git file",{error:s instanceof Error?s.message:String(s)}),ge}let o=n.match(/^gitdir:\s*(.+)$/);if(!o)return ge;let i=J.default.resolve(J.default.dirname(e),o[1]),a=i.match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(a){let s=a[1];return{isWorktree:!0,isSubmodule:!1,worktreeName:J.default.basename(t),parentRepoPath:s,parentProjectName:J.default.basename(s)}}let c=i.match(/^(.+)[/\\]\.git[/\\]modules[/\\](.+)$/);if(c){let s=c[1];return{isWorktree:!1,isSubmodule:!0,worktreeName:J.default.basename(t),parentRepoPath:s,parentProjectName:J.default.basename(s)}}return ge}var lr=require("fs");var ar=require("path");fe();E();function ti(t){let e=U(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 cr(t,e){if(!e.length)return!1;let r=t.replace(/\\/g,"/"),n=(0,ar.basename)(r);for(let o of e){let i=o.trim();if(i)try{let a=ti(i);if(a.test(r)||a.test(n))return!0}catch(a){l.warn("PROJECT_NAME","Invalid glob pattern",{pattern:i,error:a instanceof Error?a.message:String(a)});continue}}return!1}E();function ur(t){let e=t;if(typeof e=="string"){if(!e.trim())return[];try{e=JSON.parse(e)}catch(n){return l.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&&l.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(a=>typeof a=="string"&&a.trim()!==""):[];if(!o||i.length===0){l.warn("PROJECT_NAME","Ignoring a project environment without a name or patterns",{name:o});continue}r.push({name:o,patterns:i})}return r}function ri(t){try{return(0,lr.realpathSync)(t)}catch{return t}}function ut(t,e){if(e.length===0)return null;let r=[...new Set([t,ri(t)])].flatMap(n=>[n,`${n.replace(/[\\/]+$/,"")}/`]);for(let n of e)if(r.some(o=>cr(o,n.patterns)))return n.name;return null}var mt="unknown-project";function pr(t){try{return(0,pt.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 l.debug("PROJECT_NAME","git rev-parse failed, falling back to non-git root",{dir:t},r),null}}var ni=[".claude-mem-project",".claude-mem.json"],oi=64;function mr(t){try{return(0,ie.realpathSync)(t)}catch{return t}}function ii(t,e){let r=O.default.relative(e,t);return r===""||!r.startsWith("..")&&!O.default.isAbsolute(r)}function si(){return[(0,De.homedir)(),(0,De.tmpdir)(),H].flatMap(t=>{let e=O.default.resolve(t);return[e,mr(e)]})}function gr(t){let e=si(),r=O.default.resolve(t);if([O.default.resolve(H),mr(O.default.resolve(H))].some(o=>ii(r,o)))return null;for(let o=0;o<oi;o++){if(e.includes(r))return null;let i=O.default.dirname(r);if(i===r)return null;if(ni.some(a=>(0,ie.existsSync)(O.default.join(r,a))))return r;r=i}return null}function ft(t,e){let r=O.default.basename(e);if(r===""){if(process.platform==="win32"){let o=t.match(/^([A-Z]):\\/i);if(o){let a=`drive-${o[1].toUpperCase()}`;return l.info("PROJECT_NAME","Drive root detected",{cwd:t,projectName:a}),a}}return l.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:t}),mt}return r}var ai="CLAUDE_MEM_PROJECT_NAME_SOURCE",Oe=null;function dr(){try{return(0,ie.statSync)(Z).mtimeMs}catch{return-1}}function Er(){let t=dr();if(t===-1)return R.getAllDefaults();if(Oe&&Oe.mtimeMs===t)return Oe.settings;let e=R.loadFromFile(Z);return Oe={mtimeMs:dr(),settings:e},e}function ci(){let t=process.env[ai]??Er().CLAUDE_MEM_PROJECT_NAME_SOURCE;return String(t??"path").trim().toLowerCase()==="git-remote"}var li="CLAUDE_MEM_PROJECT_ENVIRONMENTS",ve=null;function ke(){let t=process.env[li]??Er().CLAUDE_MEM_PROJECT_ENVIRONMENTS;return(!ve||ve.raw!==t)&&(ve={raw:t,environments:ur(t)}),ve.environments}function ui(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]+:(?!\/\/)(.+)$/),a=o?.[1]??i?.[1];if(!a)return null;let c=a.split("/").filter(s=>s&&s!=="_git");return c.length>=2?c.slice(-2).join("/"):c.length===1?c[0]:null}function di(t){try{let e=(0,pt.execFileSync)("git",["remote","get-url","origin"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim();return ui(e)}catch(e){let r=e instanceof Error?e:new Error(String(e));return l.debug("PROJECT_NAME","No usable origin remote, keeping the path-based name",{repoRoot:t},r),null}}var dt=new Map;function _r(t){return ci()?(dt.has(t)||dt.set(t,di(t)),dt.get(t)??null):null}function fi(t,e=process.platform){if(!t||t.trim()==="")return l.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),mt;let r=U(t,e),n=ut(r,ke());if(n)return n;let o=pr(r),i=o?_r(o):null;if(i)return i;let a=o??gr(r)??r;return ft(t,a)}function Sr(t,e){return e===t?t:`${t}/${e}`}function pi(t,e){if(!t.isSubmodule||!t.parentRepoPath)return null;let r=O.default.relative(t.parentRepoPath,e);return!r||r.startsWith("..")||O.default.isAbsolute(r)?null:r.split(O.default.sep).join("/")}function hr(t,e=process.platform){if(!t||t.trim()===""){let s=fi(t,e);return{primary:s,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[s],keySource:"path"}}let r=U(t,e),n=pr(r),o=mi(t,r,n),i=n?_r(n):null,a=i?fr(o,i,"git-remote"):o,c=ut(r,ke());return c?fr(a,c,"environment"):a}function fr(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 mi(t,e,r){let n=r?null:gr(e),o=ft(t,r??n??e),i=r??e,a=sr(i);if((a.isWorktree||a.isSubmodule)&&a.parentProjectName){let c=a.parentProjectName,s,u;return a.isSubmodule?(s=`${c}/${pi(a,i)??o}`,u=o!==c?[o]:[]):(s=Sr(c,o),u=s===c?[`${c}/${o}`]:[]),{primary:s,parent:c,isWorktree:a.isWorktree,isSubmodule:a.isSubmodule,allProjects:[...new Set([c,...u,s])].filter(p=>p!==s).concat(s),keySource:"path"}}if(n&&O.default.resolve(n)!==O.default.resolve(e)){let c=ft(t,e);if(c!==o&&c!==mt)return{primary:o,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[c,o],keySource:"path"}}return{primary:o,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[o],keySource:"path"}}var yr="claude";function gi(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Ie(t){if(!t)return yr;let e=gi(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e.includes("kimi")?"kimi":e==="agy"||e==="antigravity"||e.startsWith("antigravity-")?"antigravity-cli":e:yr}Tr();function _i(t){let e=t.projects?.length?t.projects:t.project?[t.project]:[];return[...new Set(e.map(r=>r.trim()).filter(Boolean))]}function Cr(t,e){let r=_i({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})`,`SELECT project FROM observations WHERE project COLLATE NOCASE IN (${n})`,`SELECT merged_into_project FROM observations WHERE merged_into_project COLLATE NOCASE IN (${n})`,`SELECT project FROM session_summaries WHERE project COLLATE NOCASE IN (${n})`,`SELECT merged_into_project FROM session_summaries WHERE merged_into_project COLLATE NOCASE IN (${n})`,`SELECT project FROM observations WHERE merged_into_project COLLATE NOCASE IN (${n})`,`SELECT project FROM session_summaries WHERE merged_into_project COLLATE NOCASE IN (${n})`],i=t.prepare(o.join(" UNION ")).all(...o.flatMap(()=>r));return[...new Set([...r,...i.map(a=>a.key)])]}var f={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"},br=4,Ee=1;y();var Le=require("fs"),_e=require("path");E();y();var Si=/^[a-z0-9]+(?:-[a-z0-9]+)*(?:--[a-z0-9]+(?:-[a-z0-9]+)*)?$/,b=class t{static instance=null;activeMode=null;activeModeId=null;modeDirs;constructor(){let e=Qt(),r=[...process.env.CLAUDE_MEM_MODES_DIR?[process.env.CLAUDE_MEM_MODES_DIR]:[],(0,_e.join)(h.dataDir(),"modes"),(0,_e.join)(e,"modes"),(0,_e.join)(e,"..","plugin","modes")];this.modeDirs=[...new Set(r)]}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],a=e[o];this.isPlainObject(i)&&this.isPlainObject(a)?n[o]=this.deepMerge(a,i):n[o]=i}return n}loadModeFile(e){if(!Si.test(e))throw new Error(`Invalid mode ID: ${e}`);let r=this.modeDirs.map(o=>(0,_e.join)(o,`${e}.json`)).find(o=>(0,Le.existsSync)(o));if(!r)throw new Error(`Mode file not found: ${e}.json (searched: ${this.modeDirs.join(", ")})`);let n=(0,Le.readFileSync)(r,"utf-8");return JSON.parse(n)}loadMode(e){let r=this.parseInheritance(e);if(!r.hasParent)try{let s=this.loadModeFile(e);return this.activeMode=s,this.activeModeId=e,l.debug("SYSTEM",`Loaded mode: ${s.name} (${e})`,void 0,{types:s.observation_types.map(u=>u.id),concepts:s.observation_concepts.map(u=>u.id)}),s}catch(s){if(s instanceof Error?l.warn("WORKER",`Mode file not found: ${e}, falling back to 'code'`,{message:s.message}):l.warn("WORKER",`Mode file not found: ${e}, falling back to 'code'`,{error:String(s)}),e==="code")throw new Error("Critical: code.json mode file missing");return this.loadMode("code")}let{parentId:n,overrideId:o}=r,i;try{i=this.loadMode(n)}catch(s){s instanceof Error?l.warn("WORKER",`Parent mode '${n}' not found for ${e}, falling back to 'code'`,{message:s.message}):l.warn("WORKER",`Parent mode '${n}' not found for ${e}, falling back to 'code'`,{error:String(s)}),i=this.loadMode("code")}let a;try{a=this.loadModeFile(o),l.debug("SYSTEM",`Loaded override file: ${o} for parent ${n}`)}catch(s){return s instanceof Error?l.warn("WORKER",`Override file '${o}' not found, using parent mode '${n}' only`,{message:s.message}):l.warn("WORKER",`Override file '${o}' not found, using parent mode '${n}' only`,{error:String(s)}),this.activeMode=i,i}if(!a)return l.warn("SYSTEM",`Invalid override file: ${o}, using parent mode '${n}' only`),this.activeMode=i,i;let c=this.deepMerge(i,a);return this.activeMode=c,this.activeModeId=e,l.debug("SYSTEM",`Loaded mode with inheritance: ${c.name} (${e} = ${n} + ${o})`,void 0,{parent:n,override:o,types:c.observation_types.map(s=>s.id),concepts:c.observation_concepts.map(s=>s.id)}),c}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}"}};E();function hi(t){let e=Number(t);return Number.isFinite(e)&&e>0?e:0}function yi(t){let e=(t??"").split(",").map(r=>r.trim()).filter(r=>r!=="");return e.length>0?e:null}function Mr(t,e,r){let n=yi(e);if(!n)return new Set(r);let o=n.filter(a=>r.includes(a)),i=n.filter(a=>!r.includes(a));return i.length>0&&l.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 wr(){let t=h.settings(),e=R.loadFromFile(t),r=b.getInstance().getActiveMode(),n=Mr("CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES",e.CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES,r.observation_types.map(i=>i.id)),o=Mr("CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS",e.CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS,r.observation_concepts.map(i=>i.id));return{totalObservationCount:parseInt(e.CLAUDE_MEM_CONTEXT_OBSERVATIONS,10),fullObservationCount:parseInt(e.CLAUDE_MEM_CONTEXT_FULL_COUNT,10),sessionCount:parseInt(e.CLAUDE_MEM_CONTEXT_SESSION_COUNT,10),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:hi(e.CLAUDE_MEM_REINFORCE_ALPHA)}}function Ai(t,e){return t.fullObservationCount>0?{config:{...t,fullObservationCount:0},observationCount:e}:t.showLastSummary?{config:{...t,showLastSummary:!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 Rr(t,e,r,n=1e4){let o=e,i=t.length,a=r(t,o),c=0;for(;a.length>n;){let s=Ai(o,i);if(!s)return{text:a,config:o,observationCount:i,reductions:c,overBudget:!0};o=s.config,i=s.observationCount,a=r(t.slice(0,i),o),c++}return{text:a,config:o,observationCount:i,reductions:c,overBudget:!1}}function Or(t){let e=(t.title?.length||0)+(t.subtitle?.length||0)+(t.narrative?.length||0)+JSON.stringify(t.facts||[]).length;return Math.ceil(e/br)}function gt(t){let e=t.length,r=t.reduce((a,c)=>a+Or(c),0),n=t.reduce((a,c)=>a+(c.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 Ti(t){return b.getInstance().getWorkEmoji(t)}function Se(t,e){let r=Or(t),n=t.discovery_tokens||0,o=Ti(t.type),i=n>0?`${o} ${n.toLocaleString()}`:"-";return{readTokens:r,discoveryTokens:n,discoveryDisplay:i,workEmoji:o}}function Pe(t){return t.showReadTokens||t.showWorkTokens||t.showSavingsAmount||t.showSavingsPercent}var Ur=ne(require("path"),1),xe=require("fs");E();E();E();y();N();var vc=1024*1024;var Ci=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],xc=new RegExp(`<(${Ci.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g"),vr=/<system-reminder>[\s\S]*?<\/system-reminder>/g;var bi=["task-notification"],Nc=new RegExp(`^\\s*<(${bi.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),Uc=256*1024;y();function Dr(t){return`(COALESCE(${t}.agent_id, '') = '' OR COALESCE(${t}.agent_type, '') = '')`}function kr(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 Ir(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[]}}var Mi=864e5,wi=5,Lr=500;function xr(t,e){return!(e>0)||t>=Lr?t:Math.min(Lr,Math.max(t,t*wi))}function Ri(t,e){let r=Math.max(1,Math.floor((e.getTime()-t)/Mi));return Math.pow(r,-.5)}function Oi(t,e,r){let n=Ri(t.created_at_epoch,e),o=Ir(t.reinforcement_dates),i=0;for(let a=1;a<o.length;a++)i+=Math.pow(kr(o[a],e),-.5);return Math.log(1+n+r*i)}function vi(t){return Math.max(1,Math.ceil(t/4))}function Nr(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,vi(e))),i=t.slice(o.length).map((c,s)=>({item:c,i:s,score:Oi(c,n,r)}));return i.sort((c,s)=>s.score-c.score||s.item.created_at_epoch-c.item.created_at_epoch||c.i-s.i),[...o,...i.slice(0,e-o.length).map(c=>c.item)].sort((c,s)=>s.created_at_epoch-c.created_at_epoch)}var Di=`
|
|
10
|
+
`+this.safeStringify(i,2):p=" "+this.formatData(i));let d="";if(o){let{sessionId:g,memorySessionId:T,correlationId:b,...D}=o;Object.keys(D).length>0&&(d=` {${Object.entries(D).map(([I,k])=>typeof k!="object"||k===null||k instanceof Error||k instanceof Date?`${I}=${k}`:`${I}=${Array.isArray(k)?this.safeStringify(k):this.formatData(k)}`).join(", ")}}`)}let m=`[${a}] [${c}] [${s}] ${u}${n}${d}${p}`;if(this.logFilePath)try{(0,ee.appendFileSync)(this.logFilePath,m+`
|
|
11
|
+
`,"utf8")}catch(g){let T=g instanceof Error?g:new Error(String(g));Y(`[LOGGER] Failed to write to log file: ${T.message}
|
|
12
|
+
${T.stack??""}
|
|
13
|
+
`)}else Y(m+`
|
|
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){it=e}error(e,r,n,o){this.log(3,e,r,n,o),this.routeErrorToSink(r,n,o)}routeErrorToSink(e,r,n){try{if(!it||!(n instanceof Error))return;it(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)}},l=new at});var hi,Tr,Cr=Q(()=>{"use strict";hi=require("bun:sqlite");E();Tr=5e3});var Sa={};Fo(Sa,{generateContext:()=>Io,generateContextWithStats:()=>jt});module.exports=Ho(Sa);var wo=ne(require("path"),1),Ro=require("os"),et=require("fs"),Oo=require("bun:sqlite");y();E();var v=ne(require("path"),1),ie=require("fs"),De=require("os"),pt=require("child_process");fe();y();var te=require("fs"),G=require("path"),me=require("os");var P={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 zo(t=process.platform){return t==="win32"?8e3:5e3}function ct(t=process.platform){return P.SESSION_INIT_HOOK_CAP-zo(t)}function W(t){return process.platform==="win32"?Math.round(t*P.WINDOWS_MULTIPLIER):t}N();E();function rr(t){try{return new URL(t).hostname.toLowerCase()==="openrouter.ai"}catch{return!1}}Me();var Qo="security_alert",Zo="sync-hub.black-pond-afbb.workers.dev",ei="https://sync.cmem.ai",ti=new Set(["xiaomi/mimo-v2-flash:free"]);function ri(t){let e=t.CLAUDE_MEM_OPENROUTER_MODEL;if(typeof e!="string"||!ti.has(e.trim()))return!1;let r=typeof t.CLAUDE_MEM_OPENROUTER_BASE_URL=="string"?t.CLAUDE_MEM_OPENROUTER_BASE_URL.trim():"";return r===""||rr(r)}var nr=18e4,or=[{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 sr(t,e){return(0,G.join)((0,G.dirname)(t),`.${(0,G.basename)(t)}.${e.markerTag}`)}function lt(t,e){try{(0,te.writeFileSync)(sr(t,e),new Date().toISOString(),{encoding:"utf-8",mode:384})}catch{}}var ir=new Set;function ni(t){if(typeof t!="string")return null;let e=t.trim();if(e.length===0)return null;try{if(new URL(e).hostname===Zo)return ei}catch{return null}return null}var O=class{static DEFAULTS={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_ALLOWED_ORIGINS:"",CLAUDE_MEM_PUBLIC_URL:"",CLAUDE_MEM_API_TIMEOUT_MS:String(W(P.API_REQUEST)),CLAUDE_MEM_SESSION_INIT_TIMEOUT_MS:String(ct()),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_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_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_MEM_QUOTA_FALLBACK_MODEL:"",CLAUDE_MEM_DATA_DIR:(0,G.join)((0,me.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_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_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,G.join)((0,me.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_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_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_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_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,me.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_LLM_TIMEOUT_MS:String(nr),CLAUDE_MEM_FIELD_OPTIMIZE_TIMEOUT_MS:String(nr),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_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){try{if(!(0,te.existsSync)(e)){let d=this.getAllDefaults();try{L(e,d,{mode:384});for(let m of or)lt(e,m);console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(m){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,m instanceof Error?m.message:String(m))}return this.finalizeSettings(d,r)}let n=(0,te.readFileSync)(e,"utf-8"),o=be(n),i=oe(o),a=i!==o,c=Jt(o),s=a&&Object.keys(c).some(d=>d!=="env");if(a&&!s)try{L(e,i,{mode:384}),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(d){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,d instanceof Error?d.message:String(d))}if(i.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES===Qo){i={...i,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES};try{L(e,s?{...c,env:i}:i,{mode:384}),console.warn("[SETTINGS] Migrated Telegram trigger types off the legacy default:",e)}catch(d){console.warn("[SETTINGS] Failed to migrate Telegram trigger types:",e,d instanceof Error?d.message:String(d))}}if(ri(i)){let d=String(i.CLAUDE_MEM_OPENROUTER_MODEL).trim();i={...i,CLAUDE_MEM_OPENROUTER_MODEL:this.DEFAULTS.CLAUDE_MEM_OPENROUTER_MODEL};try{L(e,s?{...c,env:i}:i,{mode:384}),console.warn(`[SETTINGS] Migrated OpenRouter model off the retired default ${d} to ${this.DEFAULTS.CLAUDE_MEM_OPENROUTER_MODEL}:`,e)}catch(m){console.warn("[SETTINGS] Failed to migrate the retired OpenRouter model:",e,m instanceof Error?m.message:String(m))}}let u=ni(i.CLAUDE_MEM_CLOUD_SYNC_HUB_URL);if(u!==null){i={...i,CLAUDE_MEM_CLOUD_SYNC_HUB_URL:u};try{L(e,s?{...c,env:i}:i,{mode:384}),console.warn("[SETTINGS] Migrated cloud sync hub URL off the legacy workers.dev host:",e)}catch(d){console.warn("[SETTINGS] Failed to migrate cloud sync hub URL:",e,d instanceof Error?d.message:String(d))}}for(let d of or)if(!(0,te.existsSync)(sr(e,d))){if(i[d.key]!==d.legacy){lt(e,d);continue}i={...i,[d.key]:this.DEFAULTS[d.key]};try{L(e,s?{...c,env:i}:i,{mode:384}),lt(e,d),console.warn(`[SETTINGS] Migrated ${d.key} off the old ${d.legacy}ms default to ${this.DEFAULTS[d.key]}ms:`,e)}catch(m){let g=`${d.key}\0${e}`;ir.has(g)||(ir.add(g),console.warn(`[SETTINGS] Failed to migrate ${d.key}; using the new default in memory (reported once per process):`,e,m instanceof Error?m.message:String(m)))}}let p={...this.DEFAULTS};for(let d of Object.keys(this.DEFAULTS))i[d]!==void 0&&(p[d]=i[d]);return this.finalizeSettings(p,r)}catch(n){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,n instanceof Error?n.message:String(n));let o=this.getAllDefaults();return this.finalizeSettings(o,r)}}};E();var Re=require("fs"),J=ne(require("path"),1);E();var ge={isWorktree:!1,isSubmodule:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function ar(t){let e=J.default.join(t,".git"),r;try{r=(0,Re.statSync)(e)}catch(s){return s instanceof Error&&s.code!=="ENOENT"&&l.warn("GIT","Unexpected error checking .git",{error:s instanceof Error?s.message:String(s)}),ge}if(!r.isFile())return ge;let n;try{n=(0,Re.readFileSync)(e,"utf-8").trim()}catch(s){return l.warn("GIT","Failed to read .git file",{error:s instanceof Error?s.message:String(s)}),ge}let o=n.match(/^gitdir:\s*(.+)$/);if(!o)return ge;let i=J.default.resolve(J.default.dirname(e),o[1]),a=i.match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(a){let s=a[1];return{isWorktree:!0,isSubmodule:!1,worktreeName:J.default.basename(t),parentRepoPath:s,parentProjectName:J.default.basename(s)}}let c=i.match(/^(.+)[/\\]\.git[/\\]modules[/\\](.+)$/);if(c){let s=c[1];return{isWorktree:!1,isSubmodule:!0,worktreeName:J.default.basename(t),parentRepoPath:s,parentProjectName:J.default.basename(s)}}return ge}var ur=require("fs");var cr=require("path");fe();E();function oi(t){let e=U(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 lr(t,e){if(!e.length)return!1;let r=t.replace(/\\/g,"/"),n=(0,cr.basename)(r);for(let o of e){let i=o.trim();if(i)try{let a=oi(i);if(a.test(r)||a.test(n))return!0}catch(a){l.warn("PROJECT_NAME","Invalid glob pattern",{pattern:i,error:a instanceof Error?a.message:String(a)});continue}}return!1}E();function dr(t){let e=t;if(typeof e=="string"){if(!e.trim())return[];try{e=JSON.parse(e)}catch(n){return l.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&&l.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(a=>typeof a=="string"&&a.trim()!==""):[];if(!o||i.length===0){l.warn("PROJECT_NAME","Ignoring a project environment without a name or patterns",{name:o});continue}r.push({name:o,patterns:i})}return r}function ii(t){try{return(0,ur.realpathSync)(t)}catch{return t}}function ut(t,e){if(e.length===0)return null;let r=[...new Set([t,ii(t)])].flatMap(n=>[n,`${n.replace(/[\\/]+$/,"")}/`]);for(let n of e)if(r.some(o=>lr(o,n.patterns)))return n.name;return null}var mt="unknown-project";function mr(t){try{return(0,pt.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 l.debug("PROJECT_NAME","git rev-parse failed, falling back to non-git root",{dir:t},r),null}}var si=[".claude-mem-project",".claude-mem.json"],ai=64;function gr(t){try{return(0,ie.realpathSync)(t)}catch{return t}}function ci(t,e){let r=v.default.relative(e,t);return r===""||!r.startsWith("..")&&!v.default.isAbsolute(r)}function li(){return[(0,De.homedir)(),(0,De.tmpdir)(),H].flatMap(t=>{let e=v.default.resolve(t);return[e,gr(e)]})}function Er(t){let e=li(),r=v.default.resolve(t);if([v.default.resolve(H),gr(v.default.resolve(H))].some(o=>ci(r,o)))return null;for(let o=0;o<ai;o++){if(e.includes(r))return null;let i=v.default.dirname(r);if(i===r)return null;if(si.some(a=>(0,ie.existsSync)(v.default.join(r,a))))return r;r=i}return null}function ft(t,e){let r=v.default.basename(e);if(r===""){if(process.platform==="win32"){let o=t.match(/^([A-Z]):\\/i);if(o){let a=`drive-${o[1].toUpperCase()}`;return l.info("PROJECT_NAME","Drive root detected",{cwd:t,projectName:a}),a}}return l.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:t}),mt}return r}var ui="CLAUDE_MEM_PROJECT_NAME_SOURCE",Oe=null;function fr(){try{return(0,ie.statSync)(Z).mtimeMs}catch{return-1}}function _r(){let t=fr();if(t===-1)return O.getAllDefaults();if(Oe&&Oe.mtimeMs===t)return Oe.settings;let e=O.loadFromFile(Z);return Oe={mtimeMs:fr(),settings:e},e}function di(){let t=process.env[ui]??_r().CLAUDE_MEM_PROJECT_NAME_SOURCE;return String(t??"path").trim().toLowerCase()==="git-remote"}var fi="CLAUDE_MEM_PROJECT_ENVIRONMENTS",ve=null;function ke(){let t=process.env[fi]??_r().CLAUDE_MEM_PROJECT_ENVIRONMENTS;return(!ve||ve.raw!==t)&&(ve={raw:t,environments:dr(t)}),ve.environments}function pi(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]+:(?!\/\/)(.+)$/),a=o?.[1]??i?.[1];if(!a)return null;let c=a.split("/").filter(s=>s&&s!=="_git");return c.length>=2?c.slice(-2).join("/"):c.length===1?c[0]:null}function mi(t){try{let e=(0,pt.execFileSync)("git",["remote","get-url","origin"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim();return pi(e)}catch(e){let r=e instanceof Error?e:new Error(String(e));return l.debug("PROJECT_NAME","No usable origin remote, keeping the path-based name",{repoRoot:t},r),null}}var dt=new Map;function Sr(t){return di()?(dt.has(t)||dt.set(t,mi(t)),dt.get(t)??null):null}function gi(t,e=process.platform){if(!t||t.trim()==="")return l.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),mt;let r=U(t,e),n=ut(r,ke());if(n)return n;let o=mr(r),i=o?Sr(o):null;if(i)return i;let a=o??Er(r)??r;return ft(t,a)}function hr(t,e){return e===t?t:`${t}/${e}`}function Ei(t,e){if(!t.isSubmodule||!t.parentRepoPath)return null;let r=v.default.relative(t.parentRepoPath,e);return!r||r.startsWith("..")||v.default.isAbsolute(r)?null:r.split(v.default.sep).join("/")}function yr(t,e=process.platform){if(!t||t.trim()===""){let s=gi(t,e);return{primary:s,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[s],keySource:"path"}}let r=U(t,e),n=mr(r),o=_i(t,r,n),i=n?Sr(n):null,a=i?pr(o,i,"git-remote"):o,c=ut(r,ke());return c?pr(a,c,"environment"):a}function pr(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 _i(t,e,r){let n=r?null:Er(e),o=ft(t,r??n??e),i=r??e,a=ar(i);if((a.isWorktree||a.isSubmodule)&&a.parentProjectName){let c=a.parentProjectName,s,u;return a.isSubmodule?(s=`${c}/${Ei(a,i)??o}`,u=o!==c?[o]:[]):(s=hr(c,o),u=s===c?[`${c}/${o}`]:[]),{primary:s,parent:c,isWorktree:a.isWorktree,isSubmodule:a.isSubmodule,allProjects:[...new Set([c,...u,s])].filter(p=>p!==s).concat(s),keySource:"path"}}if(n&&v.default.resolve(n)!==v.default.resolve(e)){let c=ft(t,e);if(c!==o&&c!==mt)return{primary:o,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[c,o],keySource:"path"}}return{primary:o,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[o],keySource:"path"}}var Ar="claude";function Si(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Ie(t){if(!t)return Ar;let e=Si(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e.includes("kimi")?"kimi":e==="agy"||e==="antigravity"||e.startsWith("antigravity-")?"antigravity-cli":e:Ar}Cr();function yi(t){let e=t.projects?.length?t.projects:t.project?[t.project]:[];return[...new Set(e.map(r=>r.trim()).filter(Boolean))]}function br(t,e){let r=yi({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})`,`SELECT project FROM observations WHERE project COLLATE NOCASE IN (${n})`,`SELECT merged_into_project FROM observations WHERE merged_into_project COLLATE NOCASE IN (${n})`,`SELECT project FROM session_summaries WHERE project COLLATE NOCASE IN (${n})`,`SELECT merged_into_project FROM session_summaries WHERE merged_into_project COLLATE NOCASE IN (${n})`,`SELECT project FROM observations WHERE merged_into_project COLLATE NOCASE IN (${n})`,`SELECT project FROM session_summaries WHERE merged_into_project COLLATE NOCASE IN (${n})`],i=t.prepare(o.join(" UNION ")).all(...o.flatMap(()=>r));return[...new Set([...r,...i.map(a=>a.key)])]}var f={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"},Mr=4,Ee=1;y();var Le=require("fs"),_e=require("path");E();y();var Ai=/^[a-z0-9]+(?:-[a-z0-9]+)*(?:--[a-z0-9]+(?:-[a-z0-9]+)*)?$/,M=class t{static instance=null;activeMode=null;activeModeId=null;modeDirs;constructor(){let e=Zt(),r=[...process.env.CLAUDE_MEM_MODES_DIR?[process.env.CLAUDE_MEM_MODES_DIR]:[],(0,_e.join)(h.dataDir(),"modes"),(0,_e.join)(e,"modes"),(0,_e.join)(e,"..","plugin","modes")];this.modeDirs=[...new Set(r)]}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],a=e[o];this.isPlainObject(i)&&this.isPlainObject(a)?n[o]=this.deepMerge(a,i):n[o]=i}return n}loadModeFile(e){if(!Ai.test(e))throw new Error(`Invalid mode ID: ${e}`);let r=this.modeDirs.map(o=>(0,_e.join)(o,`${e}.json`)).find(o=>(0,Le.existsSync)(o));if(!r)throw new Error(`Mode file not found: ${e}.json (searched: ${this.modeDirs.join(", ")})`);let n=(0,Le.readFileSync)(r,"utf-8");return JSON.parse(n)}loadMode(e){let r=this.parseInheritance(e);if(!r.hasParent)try{let s=this.loadModeFile(e);return this.activeMode=s,this.activeModeId=e,l.debug("SYSTEM",`Loaded mode: ${s.name} (${e})`,void 0,{types:s.observation_types.map(u=>u.id),concepts:s.observation_concepts.map(u=>u.id)}),s}catch(s){if(s instanceof Error?l.warn("WORKER",`Mode file not found: ${e}, falling back to 'code'`,{message:s.message}):l.warn("WORKER",`Mode file not found: ${e}, falling back to 'code'`,{error:String(s)}),e==="code")throw new Error("Critical: code.json mode file missing");return this.loadMode("code")}let{parentId:n,overrideId:o}=r,i;try{i=this.loadMode(n)}catch(s){s instanceof Error?l.warn("WORKER",`Parent mode '${n}' not found for ${e}, falling back to 'code'`,{message:s.message}):l.warn("WORKER",`Parent mode '${n}' not found for ${e}, falling back to 'code'`,{error:String(s)}),i=this.loadMode("code")}let a;try{a=this.loadModeFile(o),l.debug("SYSTEM",`Loaded override file: ${o} for parent ${n}`)}catch(s){return s instanceof Error?l.warn("WORKER",`Override file '${o}' not found, using parent mode '${n}' only`,{message:s.message}):l.warn("WORKER",`Override file '${o}' not found, using parent mode '${n}' only`,{error:String(s)}),this.activeMode=i,i}if(!a)return l.warn("SYSTEM",`Invalid override file: ${o}, using parent mode '${n}' only`),this.activeMode=i,i;let c=this.deepMerge(i,a);return this.activeMode=c,this.activeModeId=e,l.debug("SYSTEM",`Loaded mode with inheritance: ${c.name} (${e} = ${n} + ${o})`,void 0,{parent:n,override:o,types:c.observation_types.map(s=>s.id),concepts:c.observation_concepts.map(s=>s.id)}),c}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}"}};E();function Ti(t){let e=Number(t);return Number.isFinite(e)&&e>0?e:0}function Ci(t){let e=(t??"").split(",").map(r=>r.trim()).filter(r=>r!=="");return e.length>0?e:null}function wr(t,e,r){let n=Ci(e);if(!n)return new Set(r);let o=n.filter(a=>r.includes(a)),i=n.filter(a=>!r.includes(a));return i.length>0&&l.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 Rr(){let t=h.settings(),e=O.loadFromFile(t),r=M.getInstance().getActiveMode(),n=wr("CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES",e.CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES,r.observation_types.map(i=>i.id)),o=wr("CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS",e.CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS,r.observation_concepts.map(i=>i.id));return{totalObservationCount:parseInt(e.CLAUDE_MEM_CONTEXT_OBSERVATIONS,10),fullObservationCount:parseInt(e.CLAUDE_MEM_CONTEXT_FULL_COUNT,10),sessionCount:parseInt(e.CLAUDE_MEM_CONTEXT_SESSION_COUNT,10),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:Ti(e.CLAUDE_MEM_REINFORCE_ALPHA)}}function bi(t,e){return t.fullObservationCount>0?{config:{...t,fullObservationCount:0},observationCount:e}:t.showLastSummary?{config:{...t,showLastSummary:!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 Or(t,e,r,n=1e4){let o=e,i=t.length,a=r(t,o),c=0;for(;a.length>n;){let s=bi(o,i);if(!s)return{text:a,config:o,observationCount:i,reductions:c,overBudget:!0};o=s.config,i=s.observationCount,a=r(t.slice(0,i),o),c++}return{text:a,config:o,observationCount:i,reductions:c,overBudget:!1}}function vr(t){let e=(t.title?.length||0)+(t.subtitle?.length||0)+(t.narrative?.length||0)+JSON.stringify(t.facts||[]).length;return Math.ceil(e/Mr)}function gt(t){let e=t.length,r=t.reduce((a,c)=>a+vr(c),0),n=t.reduce((a,c)=>a+(c.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 Mi(t){return M.getInstance().getWorkEmoji(t)}function Se(t,e){let r=vr(t),n=t.discovery_tokens||0,o=Mi(t.type),i=n>0?`${o} ${n.toLocaleString()}`:"-";return{readTokens:r,discoveryTokens:n,discoveryDisplay:i,workEmoji:o}}function Pe(t){return t.showReadTokens||t.showWorkTokens||t.showSavingsAmount||t.showSavingsPercent}var Fr=ne(require("path"),1),xe=require("fs");E();E();E();y();N();var kc=1024*1024;var wi=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],Uc=new RegExp(`<(${wi.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g"),Dr=/<system-reminder>[\s\S]*?<\/system-reminder>/g;var Ri=["task-notification"],$c=new RegExp(`^\\s*<(${Ri.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),Fc=256*1024;y();function kr(t){return`(COALESCE(${t}.agent_id, '') = '' OR COALESCE(${t}.agent_type, '') = '')`}function Ir(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 Lr(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[]}}var Oi=864e5,vi=5,Pr=500;function Nr(t,e){return!(e>0)||t>=Pr?t:Math.min(Pr,Math.max(t,t*vi))}function Di(t,e){let r=Math.max(1,Math.floor((e.getTime()-t)/Oi));return Math.pow(r,-.5)}function ki(t,e,r){let n=Di(t.created_at_epoch,e),o=Lr(t.reinforcement_dates),i=0;for(let a=1;a<o.length;a++)i+=Math.pow(Ir(o[a],e),-.5);return Math.log(1+n+r*i)}function Ii(t){return Math.max(1,Math.ceil(t/4))}function Ur(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,Ii(e))),i=t.slice(o.length).map((c,s)=>({item:c,i:s,score:ki(c,n,r)}));return i.sort((c,s)=>s.score-c.score||s.item.created_at_epoch-c.item.created_at_epoch||c.i-s.i),[...o,...i.slice(0,e-o.length).map(c=>c.item)].sort((c,s)=>s.created_at_epoch-c.created_at_epoch)}var $r=`
|
|
15
15
|
o.id,
|
|
16
16
|
o.memory_session_id,
|
|
17
17
|
COALESCE(s.platform_source, 'claude') as platform_source,
|
|
@@ -27,26 +27,46 @@ ${C.stack??""}
|
|
|
27
27
|
o.created_at,
|
|
28
28
|
o.created_at_epoch,
|
|
29
29
|
o.project
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
WHERE (? IS NULL OR s.platform_source = ?)
|
|
38
|
-
${s}
|
|
39
|
-
${p}
|
|
40
|
-
AND (${u} (
|
|
30
|
+
`,Et=["project","merged_into_project"];function Hr(t,e,r){let n=[];for(let o of Et)for(let i=0;i<e;i++)n.push(`SELECT * FROM (${r(`${t}.${o} COLLATE NOCASE = ?`)})`);return`
|
|
31
|
+
SELECT id FROM (${n.join(" UNION ")})
|
|
32
|
+
ORDER BY created_at_epoch DESC
|
|
33
|
+
LIMIT ?`}function Wr(t,e,r,n){let o=r.reinforcementAlpha??0,i=Li(t,r,{limit:Nr(r.totalObservationCount,o),platformSource:n,projects:e,excludeSubagents:r.mainAgentOnly,withReinforcementDates:o>0});return Ur(i,r.totalObservationCount,o)}function Li(t,e,r){let n=Array.from(e.observationTypes),o=n.map(()=>"?").join(","),i=Array.from(e.observationConcepts),a=i.map(()=>"?").join(","),c=(r.projects??[]).filter(b=>b.trim().length>0),s=r.includeManualSaves?"substr(o.memory_session_id, 1, 7) = 'manual-' OR":"",u=r.excludeSubagents?`AND ${kr("o")}`:"",p=r.withReinforcementDates?`,
|
|
34
|
+
o.reinforcement_dates`:"",d=`(? IS NULL OR s.platform_source = ?)
|
|
35
|
+
${u}
|
|
36
|
+
AND (${s} (
|
|
41
37
|
type IN (${o})
|
|
42
38
|
AND EXISTS (
|
|
43
39
|
SELECT 1 FROM json_each(o.concepts)
|
|
44
40
|
WHERE value IN (${a})
|
|
45
41
|
)
|
|
46
|
-
))
|
|
42
|
+
))`,m=[r.platformSource??null,r.platformSource??null,...n,...i];if(c.length===0)return t.db.prepare(`
|
|
43
|
+
SELECT
|
|
44
|
+
${$r}${p}
|
|
45
|
+
FROM observations o
|
|
46
|
+
LEFT JOIN sdk_sessions s ON o.memory_session_id = s.memory_session_id
|
|
47
|
+
WHERE ${d}
|
|
48
|
+
ORDER BY o.created_at_epoch DESC
|
|
49
|
+
LIMIT ?
|
|
50
|
+
`).all(...m,r.limit);let g=Hr("o",c.length,b=>`
|
|
51
|
+
SELECT o.id, o.created_at_epoch
|
|
52
|
+
FROM observations o
|
|
53
|
+
LEFT JOIN sdk_sessions s ON o.memory_session_id = s.memory_session_id
|
|
54
|
+
WHERE ${b} AND ${d}
|
|
55
|
+
ORDER BY o.created_at_epoch DESC
|
|
56
|
+
LIMIT ?`),T=Et.flatMap(()=>c.flatMap(b=>[b,...m,r.limit]));return t.db.prepare(`
|
|
57
|
+
SELECT
|
|
58
|
+
${$r}${p}
|
|
59
|
+
FROM (${g}) w
|
|
60
|
+
JOIN observations o ON o.id = w.id
|
|
61
|
+
LEFT JOIN sdk_sessions s ON o.memory_session_id = s.memory_session_id
|
|
47
62
|
ORDER BY o.created_at_epoch DESC
|
|
48
|
-
|
|
49
|
-
|
|
63
|
+
`).all(...T,r.limit)}function jr(t,e,r,n){if(e.length===0)return[];let o=r.sessionCount+Ee,i=[n??null,n??null],a=Hr("ss",e.length,s=>`
|
|
64
|
+
SELECT ss.id, ss.created_at_epoch
|
|
65
|
+
FROM session_summaries ss
|
|
66
|
+
LEFT JOIN sdk_sessions s ON ss.memory_session_id = s.memory_session_id
|
|
67
|
+
WHERE ${s} AND (? IS NULL OR s.platform_source = ?)
|
|
68
|
+
ORDER BY ss.created_at_epoch DESC
|
|
69
|
+
LIMIT ?`),c=Et.flatMap(()=>e.flatMap(s=>[s,...i,o]));return t.db.prepare(`
|
|
50
70
|
SELECT
|
|
51
71
|
ss.id,
|
|
52
72
|
ss.memory_session_id,
|
|
@@ -59,50 +79,47 @@ ${C.stack??""}
|
|
|
59
79
|
ss.created_at,
|
|
60
80
|
ss.created_at_epoch,
|
|
61
81
|
ss.project
|
|
62
|
-
FROM
|
|
82
|
+
FROM (${a}) w
|
|
83
|
+
JOIN session_summaries ss ON ss.id = w.id
|
|
63
84
|
LEFT JOIN sdk_sessions s ON ss.memory_session_id = s.memory_session_id
|
|
64
|
-
WHERE (ss.project COLLATE NOCASE IN (${o})
|
|
65
|
-
OR ss.merged_into_project COLLATE NOCASE IN (${o}))
|
|
66
|
-
AND (? IS NULL OR s.platform_source = ?)
|
|
67
85
|
ORDER BY ss.created_at_epoch DESC
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
Mode: ${Jr()}
|
|
86
|
+
`).all(...c,o)}function Pi(t){return t.replace(/[/.]/g,"-")}function xi(t){if(!t.includes('"type":"assistant"'))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(Dr,"").trim(),r)return r}return null}function Ni(t){for(let e=t.length-1;e>=0;e--)try{let r=xi(t[e]);if(r)return r}catch(r){r instanceof Error?l.debug("WORKER","Skipping malformed transcript line",{lineIndex:e},r):l.debug("WORKER","Skipping malformed transcript line",{lineIndex:e,error:String(r)});continue}return""}function Ui(t){try{if(!(0,xe.existsSync)(t))return{assistantMessage:""};let e=(0,xe.readFileSync)(t,"utf-8").trim();if(!e)return{assistantMessage:""};let r=e.split(`
|
|
87
|
+
`).filter(o=>o.trim());return{assistantMessage:Ni(r)}}catch(e){return e instanceof Error?l.failure("WORKER","Failed to extract prior messages from transcript",{transcriptPath:t},e):l.warn("WORKER","Failed to extract prior messages from transcript",{transcriptPath:t,error:String(e)}),{assistantMessage:""}}}function Br(t,e,r,n){if(!e.showLastMessage||t.length===0)return{assistantMessage:""};let o=t.find(s=>s.memory_session_id!==r);if(!o)return{assistantMessage:""};let i=o.memory_session_id,a=Pi(n),c=Fr.default.join(H,"projects",a,`${i}.jsonl`);return Ui(c)}function Kr(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 Yr(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,a=o.type==="observation"?o.data.created_at_epoch:o.data.displayEpoch;return i-a}),r}function Gr(t,e){return new Set(t.slice(0,e).map(r=>r.id))}var _t=ne(require("path"),1);E();function Ne(t){if(!t)return[];try{let e=JSON.parse(t);return Array.isArray(e)?e:[]}catch(e){return l.debug("PARSER","Failed to parse JSON array, using empty fallback",{preview:t?.substring(0,50)},e instanceof Error?e:new Error(String(e))),[]}}function Ue(t,e){return Number.isNaN(t.getTime())?"Invalid Date":e(t)}function St(t){let e=t.getUTCHours(),r=e<12?"AM":"PM",n=t.getUTCMinutes().toString().padStart(2,"0");return`${e%12||12}:${n} ${r}`}function ht(t){return t.toISOString().slice(0,10)}function $e(t,e){try{return t()}catch(r){return l.debug("PARSER","Locale date formatter unavailable, using ISO fallback",{},r instanceof Error?r:new Error(String(r))),e()}}function yt(t){let e=new Date(t);return $e(()=>e.toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0}),()=>Ue(e,r=>`${ht(r)} ${St(r)}`))}function At(t){let e=new Date(t);return $e(()=>e.toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}),()=>Ue(e,St))}function qr(t){let e=new Date(t);return $e(()=>e.toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"}),()=>Ue(e,ht))}function j(t=new Date){return $e(()=>{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}`},()=>Ue(t,e=>`${ht(e)} ${St(e)} UTC`))}function Jr(t,e){return _t.default.isAbsolute(t)?_t.default.relative(e,t):t}function Vr(t,e,r){let n=Ne(t);if(n.length>0)return Jr(n[0],e);if(r){let o=Ne(r);if(o.length>0)return Jr(o[0],e)}return"General"}var $i=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function q(t,e){let r=String(t);return e.fetchByIdSupported===!1&&$i.test(r)?r.slice(0,8):r}function Xr(){let t=M.getInstance();return`${t.getActiveMode().name} (${t.getActiveModeId()})`}function zr(t,e=j()){return[`# [${t}] recent context, ${e}`,`Mode: ${Xr()}`,""]}function Qr(t=!0){let r=M.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 Zr(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 en(t){return[`### ${t}`]}function tn(t){return t.toLowerCase().replace(" am","a").replace(" pm","p")}function rn(t,e,r){let n=t.title||"Untitled",o=M.getInstance().getTypeIcon(t.type),i=e?tn(e):'"';return`${q(t.id,r)} ${i} ${o} ${n}`}function nn(t,e,r,n){let o=[],i=t.title||"Untitled",a=M.getInstance().getTypeIcon(t.type),c=e?tn(e):'"',{readTokens:s,discoveryDisplay:u}=Se(t,n),p=q(t.id,n);o.push(`**${p}** ${c} ${a} **${i}**`),r&&o.push(r);let d=[];return n.showReadTokens&&d.push(`~${s}t`),n.showWorkTokens&&d.push(u),d.length>0&&o.push(d.join(" ")),o.push(""),o}function on(t,e,r={}){return[`S${q(t.id,r)} ${t.request||"Session started"} (${e})`]}function he(t,e){return e?[`**${t}**: ${e}`,""]:[]}function sn(t){return t.assistantMessage?["","---","","**Previously**","",`A: ${t.assistantMessage}`,""]:[]}function an(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 cn(t,e=j()){return`# [${t}] recent context, ${e}
|
|
88
|
+
Mode: ${Xr()}
|
|
72
89
|
|
|
73
|
-
No previous sessions found.`}function
|
|
90
|
+
No previous sessions found.`}function ln(){let t=M.getInstance();return`${t.getActiveMode().name} (${t.getActiveModeId()})`}function un(t,e=j()){return["",`${f.bright}${f.cyan}[${t}] recent context, ${e}${f.reset}`,`${f.dim}Mode: ${ln()}${f.reset}`,`${f.gray}${"\u2500".repeat(60)}${f.reset}`,""]}function dn(){let e=M.getInstance().getActiveMode().observation_types.map(r=>`${r.emoji} ${r.id}`).join(" | ");return[`${f.dim}Legend: session-request | ${e}${f.reset}`,""]}function fn(){return[`${f.bright}Column Key${f.reset}`,`${f.dim} Read: Tokens to read this observation (cost to learn it now)${f.reset}`,`${f.dim} Work: Tokens spent on work that produced this record ( research, building, deciding)${f.reset}`,""]}function pn(t=!0){let e=t?[`${f.dim} - Fetch by ID: get_observations([IDs]) for observations visible in this index${f.reset}`,`${f.dim} - Search history: Use the mem-search skill for past decisions, bugs, and deeper research${f.reset}`]:[`${f.dim} - Search: observation_search by title or topic (short refs are display-only; server runtime has no fetch by ID)${f.reset}`];return[`${f.dim}Context Index: This semantic index (titles, types, files, tokens) is usually sufficient to understand past work.${f.reset}`,"",`${f.dim}When you need implementation details, rationale, or debugging context:${f.reset}`,...e,`${f.dim} - Trust this index over re-reading code for past decisions and learnings${f.reset}`,""]}function mn(t,e){let r=[];if(r.push(`${f.bright}${f.cyan}Context Economics${f.reset}`),r.push(`${f.dim} Loading: ${t.totalObservations} observations (${t.totalReadTokens.toLocaleString()} tokens to read)${f.reset}`),r.push(`${f.dim} Work investment: ${t.totalDiscoveryTokens.toLocaleString()} tokens spent on research, building, and decisions${f.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(`${f.green}${n}${f.reset}`)}return r.push(""),r}function gn(t){return[`${f.bright}${f.cyan}${t}${f.reset}`,""]}function En(t){return[`${f.dim}${t}${f.reset}`]}function Tt(t,e,r,n){let o=t.title||"Untitled",i=M.getInstance().getTypeIcon(t.type),{readTokens:a,discoveryTokens:c,workEmoji:s}=Se(t,n),u=r?`${f.dim}${e}${f.reset}`:" ".repeat(e.length),p=n.showReadTokens&&a>0?`${f.dim}(~${a}t)${f.reset}`:"",d=n.showWorkTokens&&c>0?`${f.dim}(${s} ${c.toLocaleString()}t)${f.reset}`:"";return` ${f.dim}#${q(t.id,n)}${f.reset} ${u} ${i} ${o} ${p} ${d}`}function Ct(t,e,r,n,o){let i=[],a=t.title||"Untitled",c=M.getInstance().getTypeIcon(t.type),{readTokens:s,discoveryTokens:u,workEmoji:p}=Se(t,o),d=r?`${f.dim}${e}${f.reset}`:" ".repeat(e.length),m=o.showReadTokens&&s>0?`${f.dim}(~${s}t)${f.reset}`:"",g=o.showWorkTokens&&u>0?`${f.dim}(${p} ${u.toLocaleString()}t)${f.reset}`:"";return i.push(` ${f.dim}#${q(t.id,o)}${f.reset} ${d} ${c} ${f.bright}${a}${f.reset}`),n&&i.push(` ${f.dim}${n}${f.reset}`),(m||g)&&i.push(` ${m} ${g}`),i.push(""),i}function _n(t,e,r={}){let n=`${t.request||"Session started"} (${e})`;return[`${f.yellow}#S${q(t.id,r)}${f.reset} ${n}`,""]}function ye(t,e,r){return e?[`${r}${t}:${f.reset} ${e}`,""]:[]}function Sn(t){return t.assistantMessage?["","---","",`${f.bright}${f.magenta}Previously${f.reset}`,"",`${f.dim}A: ${t.assistantMessage}${f.reset}`,""]:[]}function hn(t,e){let r=Math.round(t/1e3);return["",`${f.dim}Access ${r}k tokens of past research & decisions for just ${e.toLocaleString()}t. Use the claude-mem skill to access memories by ID.${f.reset}`]}function yn(t,e=j()){return`
|
|
74
91
|
${f.bright}${f.cyan}[${t}] recent context, ${e}${f.reset}
|
|
75
|
-
${f.dim}Mode: ${
|
|
92
|
+
${f.dim}Mode: ${ln()}${f.reset}
|
|
76
93
|
${f.gray}${"\u2500".repeat(60)}${f.reset}
|
|
77
94
|
|
|
78
95
|
${f.dim}No previous sessions found for this project yet.${f.reset}
|
|
79
|
-
`}function
|
|
80
|
-
`):null}function
|
|
81
|
-
`)}function Ke(t){return t?
|
|
82
|
-
`)}function
|
|
96
|
+
`}function Fi(t){return ke().some(e=>e.name===t)?`${t} (environment)`:t}function An(t,e,r,n,o){let i=[],a=r.fetchByIdSupported!==!1,c=Fi(t);return n?i.push(...un(c,o)):i.push(...zr(c,o)),n?i.push(...dn()):i.push(...Qr(a)),n&&(i.push(...fn()),i.push(...pn(a))),Pe(r)&&(n?i.push(...mn(e,r)):i.push(...Zr(e,r))),i}function Tn(t){let e=new Map;for(let n of t){let o=n.type==="observation"?n.data.created_at:n.data.displayTime,i=qr(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(),a=new Date(o[0]).getTime();return i-a});return new Map(r)}function Cn(t,e){return e.fullObservationField==="narrative"?t.narrative:t.facts?Ne(t.facts).join(`
|
|
97
|
+
`):null}function Hi(t,e,r,n){let o=[];o.push(...en(t));let i="";for(let a of e)if(a.type==="summary"){let c=a.data,s=yt(c.displayTime);o.push(...on(c,s,n))}else{let c=a.data,s=At(c.created_at),p=s!==i?s:"";if(i=s,r.has(c.id)){let m=Cn(c,n);o.push(...nn(c,p,m,n))}else o.push(rn(c,p,n))}return o}function bn(t,e,r){let n=[];for(let[o,i]of Tn(t))n.push(...Hi(o,i,e,r));return n}function Mn(t,e,r,n){let o=[];for(let[i,a]of Tn(t)){let c="";for(let s of a){if(s.type==="summary"){c="";let b=s.data;o.push({day:i,file:null,summary:!0,lines:_n(b,yt(b.displayTime),r)});continue}let u=s.data,p=At(u.created_at),d=p!==c;c=p;let m=Vr(u.files_modified,n,u.files_read),g=Cn(u,r),T=e.has(u.id);o.push({day:i,file:m,summary:!1,lines:T?Ct(u,p,d,g,r):[Tt(u,p,d,r)],linesWithTime:d?void 0:T?Ct(u,p,!0,g,r):[Tt(u,p,!0,r)]})}}return o}function We(t){let e=[],r="",n=null,o=!1;for(let i of t)i.day!==r&&(r&&e.push(""),e.push(...gn(i.day)),r=i.day,n=null,o=!1),i.summary?n=null:i.file!==n&&(e.push(...En(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 wn(t,e,r){return!(!t.showLastSummary||!e||!!!(e.investigated||e.learned||e.completed||e.next_steps)||r&&e.created_at_epoch<r.created_at_epoch)}function Rn(t,e){let r=[];return e?(r.push(...ye("Investigated",t.investigated,f.blue)),r.push(...ye("Learned",t.learned,f.yellow)),r.push(...ye("Completed",t.completed,f.green)),r.push(...ye("Next Steps",t.next_steps,f.magenta))):(r.push(...he("Investigated",t.investigated)),r.push(...he("Learned",t.learned)),r.push(...he("Completed",t.completed)),r.push(...he("Next Steps",t.next_steps))),r}function On(t,e){return e?Sn(t):sn(t)}function vn(t,e,r){return!Pe(e)||t.totalDiscoveryTokens<=0||t.savings<=0?[]:r?hn(t.totalDiscoveryTokens,t.totalReadTokens):an(t.totalDiscoveryTokens,t.totalReadTokens,e.fetchByIdSupported!==!1)}var V=require("fs"),Rt=require("path");y();y();var je=null;function se(){return je!==null||(je=O.loadFromFile(Z)),je}function bt(t,e){let r=(process.env.CLAUDE_MEM_PUBLIC_URL??e??"").trim();return r?r.replace(/\/+$/,""):`http://localhost:${t}`}function Mt(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 Wi(t){return t.hostname==="cmem.ai"||t.hostname==="openrouter.ai"?!0:t.hostname==="github.com"&&/^\/thedotmack\/claude-mem\/issues(\/|$)/.test(t.pathname)}function wt(t){try{let e=new URL((t??"").trim());if(e.protocol==="https:"&&!e.port&&!e.username&&!e.password&&Wi(e)&&e.href.length<=300)return e.href}catch{}return null}E();var Bi="observer-health.json",Ki=3,Yi=600,Gi={consecutiveFailures:0,failingSinceAt:null,lastErrorAt:null,lastErrorMessage:null,lastErrorProvider:null,lastSuccessAt:null,lastErrorCode:null,lastErrorAction:null,lastErrorUrl:null,lastErrorRequestId:null,quotaCooldown:null};function Ji(){return(0,Rt.join)(h.dataDir(),Bi)}var qi=/(["']?\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 Ot(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(qi,(e,r,n,o)=>/^\d+$/.test(o)?e:`${r}${n}\u2026${n}`).slice(0,Yi)}function kn(t=Ji()){try{if(!(0,V.existsSync)(t))return null;let e=JSON.parse((0,V.readFileSync)(t,"utf-8"));return typeof e!="object"||e===null?null:{...Gi,...e}}catch(e){return l.warn("SESSION","Failed to read observer-health file",{filePath:t},e instanceof Error?e:new Error(String(e))),null}}function In(t){return t!==null&&(t.consecutiveFailures>=Ki||Pn(t)||Xi(t))&&(t.lastErrorAt??0)>(t.lastSuccessAt??0)}function ae(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 Vi(){let t=se();return`${bt(t.CLAUDE_MEM_WORKER_PORT,t.CLAUDE_MEM_PUBLIC_URL)}/restart`}function Ln(t){return t.lastErrorKind==="quota_exhausted"}function Pn(t){return t.lastErrorKind==="auth_invalid"}function Xi(t){return t.lastErrorKind==="setup_required"}var zi=30*6e4;function xn(t,e){let r=t.lastErrorAt;return r!==null&&e-r>=zi}function Qi(t,e=Date.now()){return Ln(t)&&xn(t,e)}function Zi(t,e=Date.now()){return t.lastErrorCode==="deadline_exceeded"&&xn(t,e)}function Nn(t,e=Date.now()){let r=t?.quotaCooldown;return r!=null&&typeof r.until=="number"&&r.until>e}function Un(t,e=Date.now()){let r=t.quotaCooldown,n=r?.provider??"unknown provider",o=r?.until,i=o?`${new Date(o).toISOString()} (${ae(Math.max(0,o-e))} from now)`:"the next probe window",a=r?.window?` (${r.window})`:"";if(r?.servingProvider)return`\u2139\uFE0F claude-mem's ${n} provider is in a quota cooldown${a}; memory capture continues on ${r.servingProvider} until it clears at ${i}.`;let c=Ke(r?.message)||null;return["\u26A0\uFE0F Heads up: claude-mem is paused while a provider quota cooldown is active.","",`The memory observer is waiting out a quota cooldown on ${n}${a} until ${i}.`,"",...c?[`Latest signal: ${c}`,""]:[],"This is not a failure. Incoming observations stay queued and will be written","when the cooldown clears \u2014 the worker is intentionally not starting the","generator so it does not keep spending a spent allowance.","","Restarting will NOT help here, and it clears the backoff that is currently keeping","claude-mem from hammering the provider \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(`
|
|
98
|
+
`)}function Ke(t){return t?Mt(Ot(t)):""}function Be(t,e){let r=wt(t.lastErrorUrl),n=Mt(t.lastErrorRequestId);return[`Latest error: ${Ke(t.lastErrorMessage)||"unknown"}`,...e?[`What to do: ${e}`]:[],...r?[`Link: ${r}`]:[],...n?[`Request id: ${n}`]:[]]}function Dn(t,e,r,n){let o=t.lastErrorProvider??"unknown provider",i=t.lastErrorAt?ae(e-t.lastErrorAt):"an unknown time",a=wt(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: ${Ke(t.lastErrorMessage)||"unknown"}`,...r?[`${n.remedyLabel}: ${r}`]:[],...a?[`Link: ${a}`]:[],"",`${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(`
|
|
99
|
+
`)}function $n(t,e=Date.now()){let r=t.failingSinceAt??t.lastErrorAt,n=r?`for ${ae(e-r)} (since ${new Date(r).toISOString()})`:"for an unknown amount of time",o=t.lastErrorProvider??"unknown provider",i=t.consecutiveFailures,a=Ke(t.lastErrorAction)||null;return Qi(t,e)?Dn(t,e,a,{failedWith:"a spent allowance",remedyLabel:"If it is still spent",recovery:"Allowances reset on their own"}):Zi(t,e)?Dn(t,e,a,{failedWith:"requests running past their deadline",remedyLabel:"If it is still slow",recovery:"A slow backend usually recovers on its own"}):Ln(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(/\)$/,"")}).`,"",...Be(t,a),"","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, and it clears the backoff that is currently keeping","claude-mem from hammering the provider \u2014 so please leave the worker alone.",...a?[]:["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(`
|
|
83
100
|
`):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.`,"",...Be(t,a),"","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(`
|
|
84
|
-
`):
|
|
85
|
-
`):["\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}.`,"",...Be(t,a),"","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: ${
|
|
86
|
-
`)}y();E();var
|
|
87
|
-
`)}E();E();y();var re=require("fs");E();var
|
|
88
|
-
`)){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 ys(){let t;try{t=(await Dt("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 l.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 Ye(t){let e=await _s(),r=new Map;for(let a of e){let c=r.get(a.ppid);c?c.push(a):r.set(a.ppid,[a])}let n=new Set([t]),o=[],i=a=>{for(let c of r.get(a)??[])n.has(c.pid)||(n.add(c.pid),i(c.pid),o.push({pid:c.pid,startToken:c.startToken}))};return i(t),o}var Ts=5e3,Cs=1e3,bs=h.supervisorRegistry(),Ms=null;function M(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:(l.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return l.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function qe(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!M(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function to(t){if(!t||!M(t.pid))return!1;if(!t.startToken)return!0;let e=B(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||l.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}var ws={platform:process.platform,readCommandLine:t=>(0,Ae.readFileSync)(`/proc/${t}/cmdline`,"utf-8")};function Pt(t,e=ws){if(!to(t))return!1;if(t.startToken||e.platform!=="linux")return!0;let r;try{r=e.readCommandLine(t.pid)}catch(o){return l.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=>eo.default.basename(o)==="worker-service.cjs");return n||l.debug("SYSTEM","Token-less worker PID now belongs to another program (PID reused)",{pid:t.pid}),n}var Lt=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(e=bs){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,!(0,Ae.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Ae.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[o,i]of Object.entries(n))this.entries.set(o,i)}catch(r){r instanceof Error?l.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):l.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&l.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||!M(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)),l.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"&&It())}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)M(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)It();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;l.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:n,pids:r.map(c=>c.pid)});let o=r.filter(c=>M(c.pid)),i=new Map(o.map(c=>[c.pid,B(c.pid)]));for(let c of o)try{process.platform==="win32"?await F(c.pid,{expectedStartToken:i.get(c.pid)??null}):typeof c.pgid=="number"?process.kill(-c.pgid,"SIGTERM"):process.kill(c.pid,"SIGTERM")}catch(s){s instanceof Error?s.code!=="ESRCH"&&l.debug("SYSTEM",`Failed to SIGTERM session process PID ${c.pid}`,{pid:c.pid,pgid:c.pgid},s):l.warn("SYSTEM",`Failed to SIGTERM session process PID ${c.pid} (non-Error)`,{pid:c.pid,pgid:c.pgid,error:String(s)})}await qe(o,Ts);let a=o.filter(c=>M(c.pid));for(let c of a){l.warn("SYSTEM",`Session process PID ${c.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:c.pid,pgid:c.pgid,sessionId:n});let s=i.get(c.pid)??null;if(!$(c.pid,s)){l.warn("SYSTEM","Skipping SIGKILL: session process PID was reused during the grace window",{pid:c.pid,sessionId:n});continue}try{process.platform==="win32"?await F(c.pid,{expectedStartToken:s}):typeof c.pgid=="number"?process.kill(-c.pgid,"SIGKILL"):process.kill(c.pid,"SIGKILL")}catch(u){u instanceof Error?u.code!=="ESRCH"&&l.debug("SYSTEM",`Failed to SIGKILL session process PID ${c.pid}`,{pid:c.pid,pgid:c.pgid},u):l.warn("SYSTEM",`Failed to SIGKILL session process PID ${c.pid} (non-Error)`,{pid:c.pid,pgid:c.pgid,error:String(u)})}}if(a.length>0){let c=Date.now()+Cs;for(;Date.now()<c&&a.filter(u=>M(u.pid)).length!==0;)await new Promise(u=>setTimeout(u,100))}for(let c of r)this.entries.delete(c.id),this.runtimeProcesses.delete(c.id);this.persist();for(let c of r)c.type==="sdk"&&It();return l.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{I(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));l.warn("SYSTEM","Failed to persist supervisor registry; keeping it in memory",{path:this.registryPath},r);try{Ms?.({errorCategory:r.code??"unknown"})}catch{}}},kt=null;function Ve(){return kt||(kt=new Lt),kt}var Mu=180*1e3,Rs=[];function It(){let t=Rs.shift();t&&t.notify()}var le=require("fs");E();y();var Os=h.workerPid();async function no(t){let e=t.currentPid??process.pid,r=t.pidFilePath??Os,n=t.registry.getAll(),o=[...n].filter(s=>s.pid!==e).sort((s,u)=>Date.parse(u.startedAt)-Date.parse(s.startedAt)),i=new Map,a=new Map;for(let s of o){if(!M(s.pid)){t.registry.unregister(s.id);continue}a.set(s.id,B(s.pid)),i.set(s.id,await Ye(s.pid));try{await ro(s,"SIGTERM")}catch(u){u instanceof Error?l.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:s.pid,pgid:s.pgid,type:s.type},u):l.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:s.pid,pgid:s.pgid,type:s.type,error:String(u)})}}await qe(o,5e3);let c=o.filter(s=>M(s.pid)||(i.get(s.id)??[]).some(u=>M(u.pid)));for(let s of c){let u=$(s.pid,a.get(s.id)??null);u||l.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:s.pid,type:s.type});try{u&&await ro(s,"SIGKILL")}catch(p){p instanceof Error?l.debug("SYSTEM","Failed to force kill child process",{pid:s.pid,pgid:s.pgid,type:s.type},p):l.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:s.pid,pgid:s.pgid,type:s.type,error:String(p)})}finally{vs(i.get(s.id)??[],s.pid)}}await qe(c,1e3);for(let s of o)t.registry.unregister(s.id);for(let s of n.filter(u=>u.pid===e))t.registry.unregister(s.id);oo(r,e),t.registry.pruneDeadEntries()}function oo(t,e,r=!1){if(!(0,le.existsSync)(t))return;let n=null;try{let a=JSON.parse((0,le.readFileSync)(t,"utf-8"));n=typeof a.pid=="number"?a.pid:null}catch(a){l.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:a instanceof Error?a.message:String(a)});return}let o=e!==null&&n===e,i=n===null||!M(n);if(!o&&!(r&&i)){l.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,le.rmSync)(t,{force:!0})}catch(a){a instanceof Error?l.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},a):l.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(a)})}}function vs(t,e){for(let{pid:r,startToken:n}of t)if(!(r===e||!M(r))){if(!$(r,n)){l.debug("SYSTEM","Skipping reap: PID was recycled during the grace window",{pid:r,rootPid:e});continue}try{process.kill(r,"SIGKILL"),l.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"&&l.warn("SYSTEM","Failed to reap orphaned descendant during shutdown cascade",{pid:r,rootPid:e,errno:i})}}}async function ro(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 F(r,{signalMode:"immediate"});return}try{process.kill(r,e)}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}return}await F(r)}E();var io=3e4,ue=null;function Ds(){let e=Ve().pruneDeadEntries();e>0&&l.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function so(){ue===null&&(ue=setInterval(Ds,io),ue.unref(),l.debug("SYSTEM","Health checker started",{intervalMs:io}))}function ao(){ue!==null&&(clearInterval(ue),ue=null,l.debug("SYSTEM","Health checker stopped"))}var co=require("child_process"),lo=require("util");E();var ks=(0,lo.promisify)(co.execFile),Is=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/;function Ls(t){let e=[];for(let r of t.split(`
|
|
89
|
-
`)){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
|
|
90
|
-
`)}async function
|
|
91
|
-
`,1)[0]??"";return{id:
|
|
92
|
-
`).length+1;s.push(...
|
|
93
|
-
`).length,K=r[0],
|
|
94
|
-
`).length,tt=
|
|
95
|
-
`).length;return s.push(...
|
|
96
|
-
`).trimEnd(),timelineStart:
|
|
101
|
+
`):Pn(t)?["\u26A0\uFE0F Heads up: claude-mem can't save memories right now.","",`The memory observer's credentials have been refused by ${o} ${n}.`,"",...Be(t,a),"","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.",...a?[]:["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(`
|
|
102
|
+
`):["\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}.`,"",...Be(t,a),"","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: ${Vi()}`," Or in a terminal: npx claude-mem restart","","Still failing after the restart? Run: npx claude-mem doctor",...a?[]:["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(`
|
|
103
|
+
`)}y();E();var Bn=require("crypto");var Kn=require("path");E();y();var Hn=require("child_process"),Wn=require("util");y();E();var xl=(0,Wn.promisify)(Hn.execFile);function es(t){let e=t?.trim();return Fn(e?er(e):H)}function Fn(t){let e=t.replace(/[/\\]+$/,"");return e.length>0?e:t}function jn(t){let e=es(t),r=t?.trim()?e!==nt:!!process.env.CLAUDE_CONFIG_DIR;return{configDir:e,explicitConfigDir:r}}function ts(t){if(!t.explicitConfigDir)return"default";let e=(0,Bn.createHash)("sha256").update(t.configDir.normalize("NFC")).digest("hex").slice(0,8);return`${(0,Kn.basename)(t.configDir)}#${e}`}function Yn(){let t=O.loadFromFile(h.settings());return ts(jn(t.CLAUDE_MEM_CLAUDE_CONFIG_DIR))}var rs=Yn;function Gn(t){return t.provider!=="claude"||t.profile===rs()}var zl=30*6e4;var Ql=5*6e4;var X=require("fs"),qn=require("path");y();E();var ns="sync-health.json",os=900*1e3,is=5,Jn={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 ss(){return(0,qn.join)(h.dataDir(),ns)}function Vn(t=ss()){try{if(!(0,X.existsSync)(t))return null;let e=JSON.parse((0,X.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 as(t,e=Date.now()){return t?t.state==="auth_paused"?!0:t.state!=="failing"?!1:t.consecutiveFailures>=is?!0:t.failingSinceAt!==null&&e-t.failingSinceAt>=os:!1}function Xn(t,e=Date.now()){if(!as(t,e))return"";if(t.state==="auth_paused")return`\u26A0 ${t.code==="subscription_inactive"||t.code==="invalid_token"?Jn[t.code]:t.message??Jn.invalid_token}`;let r=t.failingSinceAt!==null?` for ${ae(e-t.failingSinceAt)}`:"",n=t.message?` Last error: ${Ot(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(`
|
|
104
|
+
`)}E();E();y();var re=require("fs");E();var cs=new Set([".cmd",".bat"]),ls=new Set([".exe",".com"]),au=new Set([...ls,...cs]);var Ae=require("fs"),no=ne(require("path"),1);E();N();var us=["CLAUDECODE_","CLAUDE_CODE_"],ds=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),fs=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"]),ps=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",...fs]);function ce(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(ps.has(r)){e[r]=n;continue}ds.has(r)||us.some(o=>r.startsWith(o))||(e[r]=n)}return e}y();var Dt=require("child_process"),Qn=require("fs");E();var ms=5e3,zn=new Map,vt=0;function Zn(t,e,r){if(r.status!==0)return null;if(typeof r.stdout!="string")return l.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 gs(t){vt+=1;let e=(0,Dt.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:{...ce(process.env),LC_ALL:"C",LANG:"C"}});return Zn("powershell-cim",t,e)}function Es(t,e=!1){if(!e){let n=zn.get(t);if(n&&(t===process.pid||Date.now()-n.capturedAtMs<ms))return n.token}let r=null;try{r=gs(t)}catch(n){l.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)&&zn.set(t,{token:r,capturedAtMs:Date.now()}),r}function eo(t,e){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux"){vt+=1;try{let r=(0,Qn.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 l.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}if(process.platform==="win32")return Es(t,e);vt+=1;try{let r=(0,Dt.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...ce(process.env),LC_ALL:"C",LANG:"C"}});return Zn("ps-lstart",t,r)}catch(r){return l.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}function B(t){return eo(t,!1)}function $(t,e){if(e===null)return!0;let r=eo(t,!0);return r===null?!0:r===e}var to=require("child_process"),Je=require("fs"),ro=require("util");E();var kt=(0,ro.promisify)(to.execFile),_s=128,Ss=/not found|no running instance|no tasks/i,Ye=class extends Error{pid;constructor(e,r,n){super(r,n),this.name="ProcessTreeKillError",this.pid=e}};async function F(t,e={}){let r=e.signalMode==="immediate",n=e.expectedStartToken!==void 0?e.expectedStartToken:B(t),o=()=>$(t,n);if(!o()){l.warn("PROCESS","Skipping tree-kill: root PID was reused since it was captured",{pid:t});return}if(l.debug("PROCESS",`Killing process tree rooted at PID ${t}`,{immediate:r}),process.platform==="win32"){try{await kt("taskkill",["/PID",String(t),"/T","/F"],{timeout:5e3,windowsHide:!0})}catch(i){let a=i.code,c=String(i.stderr??""),s=i instanceof Error?i.message:String(i);if(a===_s||Ss.test(`${c} ${s}`)){l.debug("PROCESS","taskkill reported the process was already gone",{pid:t});return}throw new Ye(t,`taskkill failed for PID ${t} (exit ${String(a)}): ${c.trim()||s}`,{cause:i})}return}try{let i=r?"SIGKILL":"SIGTERM",a=await Ge(t);for(let u of a){if(!$(u.pid,u.startToken)){l.debug("PROCESS",`Skipping ${i}: descendant PID was reused since enumeration`,{pid:u.pid,rootPid:t});continue}try{process.kill(u.pid,i)}catch{}}if(o())try{process.kill(t,i)}catch(u){let p=u instanceof Error?u:new Error(String(u)),d=p.code;d!=="ESRCH"&&l.debug("PROCESS",`Failed to ${i} PID ${t}`,{code:d},p)}else l.warn("PROCESS","Skipping root signal: PID was reused during descendant enumeration",{pid:t,signal:i});r||await new Promise(u=>setTimeout(u,500));let c=o()?await Ge(t):[],s=new Map;for(let u of a)s.set(u.pid,u.startToken);for(let u of c)s.set(u.pid,u.startToken);for(let[u,p]of s){if(!$(u,p)){l.debug("PROCESS","Skipping SIGKILL: descendant PID was reused since the scan",{pid:u,rootPid:t});continue}try{process.kill(u,"SIGKILL")}catch{}}if(!r&&o())try{process.kill(t,"SIGKILL")}catch{}}catch(i){throw new Ye(t,`tree-kill failed for PID ${t}: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}async function hs(){return process.platform==="win32"?Ts():process.platform==="linux"?ys():As()}function ys(){let t=[],e;try{e=(0,Je.readdirSync)("/proc")}catch(r){return l.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,Je.readFileSync)(`/proc/${r}/stat`,"utf-8")}catch{continue}let o=n.lastIndexOf(") ");if(o<0)continue;let i=n.slice(o+2).split(" "),a=Number.parseInt(i[1]??"",10),c=i[19];Number.isFinite(a)&&t.push({pid:Number.parseInt(r,10),ppid:a,startToken:c&&/^\d+$/.test(c)?c:null})}return t}async function As(){let t;try{t=(await kt("ps",["-eo","pid=,ppid=,lstart="],{timeout:1e4,maxBuffer:33554432,env:{...process.env,LC_ALL:"C",LANG:"C"}})).stdout}catch(r){return l.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(`
|
|
105
|
+
`)){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 Ts(){let t;try{t=(await kt("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 l.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 Ge(t){let e=await hs(),r=new Map;for(let a of e){let c=r.get(a.ppid);c?c.push(a):r.set(a.ppid,[a])}let n=new Set([t]),o=[],i=a=>{for(let c of r.get(a)??[])n.has(c.pid)||(n.add(c.pid),i(c.pid),o.push({pid:c.pid,startToken:c.startToken}))};return i(t),o}var bs=5e3,Ms=1e3,ws=h.supervisorRegistry(),Rs=null;function w(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:(l.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return l.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function qe(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!w(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function oo(t){if(!t||!w(t.pid))return!1;if(!t.startToken)return!0;let e=B(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||l.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}var Os={platform:process.platform,readCommandLine:t=>(0,Ae.readFileSync)(`/proc/${t}/cmdline`,"utf-8")};function xt(t,e=Os){if(!oo(t))return!1;if(t.startToken||e.platform!=="linux")return!0;let r;try{r=e.readCommandLine(t.pid)}catch(o){return l.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=>no.default.basename(o)==="worker-service.cjs");return n||l.debug("SYSTEM","Token-less worker PID now belongs to another program (PID reused)",{pid:t.pid}),n}var Pt=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(e=ws){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,!(0,Ae.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Ae.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[o,i]of Object.entries(n))this.entries.set(o,i)}catch(r){r instanceof Error?l.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):l.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&l.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||!w(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)),l.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"&&Lt())}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)w(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)Lt();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;l.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:n,pids:r.map(c=>c.pid)});let o=r.filter(c=>w(c.pid)),i=new Map(o.map(c=>[c.pid,B(c.pid)]));for(let c of o)try{process.platform==="win32"?await F(c.pid,{expectedStartToken:i.get(c.pid)??null}):typeof c.pgid=="number"?process.kill(-c.pgid,"SIGTERM"):process.kill(c.pid,"SIGTERM")}catch(s){s instanceof Error?s.code!=="ESRCH"&&l.debug("SYSTEM",`Failed to SIGTERM session process PID ${c.pid}`,{pid:c.pid,pgid:c.pgid},s):l.warn("SYSTEM",`Failed to SIGTERM session process PID ${c.pid} (non-Error)`,{pid:c.pid,pgid:c.pgid,error:String(s)})}await qe(o,bs);let a=o.filter(c=>w(c.pid));for(let c of a){l.warn("SYSTEM",`Session process PID ${c.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:c.pid,pgid:c.pgid,sessionId:n});let s=i.get(c.pid)??null;if(!$(c.pid,s)){l.warn("SYSTEM","Skipping SIGKILL: session process PID was reused during the grace window",{pid:c.pid,sessionId:n});continue}try{process.platform==="win32"?await F(c.pid,{expectedStartToken:s}):typeof c.pgid=="number"?process.kill(-c.pgid,"SIGKILL"):process.kill(c.pid,"SIGKILL")}catch(u){u instanceof Error?u.code!=="ESRCH"&&l.debug("SYSTEM",`Failed to SIGKILL session process PID ${c.pid}`,{pid:c.pid,pgid:c.pgid},u):l.warn("SYSTEM",`Failed to SIGKILL session process PID ${c.pid} (non-Error)`,{pid:c.pid,pgid:c.pgid,error:String(u)})}}if(a.length>0){let c=Date.now()+Ms;for(;Date.now()<c&&a.filter(u=>w(u.pid)).length!==0;)await new Promise(u=>setTimeout(u,100))}for(let c of r)this.entries.delete(c.id),this.runtimeProcesses.delete(c.id);this.persist();for(let c of r)c.type==="sdk"&&Lt();return l.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{L(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));l.warn("SYSTEM","Failed to persist supervisor registry; keeping it in memory",{path:this.registryPath},r);try{Rs?.({errorCategory:r.code??"unknown"})}catch{}}},It=null;function Ve(){return It||(It=new Pt),It}var Ru=180*1e3,vs=[];function Lt(){let t=vs.shift();t&&t.notify()}var le=require("fs");E();y();var Ds=h.workerPid();async function so(t){let e=t.currentPid??process.pid,r=t.pidFilePath??Ds,n=t.registry.getAll(),o=[...n].filter(s=>s.pid!==e).sort((s,u)=>Date.parse(u.startedAt)-Date.parse(s.startedAt)),i=new Map,a=new Map;for(let s of o){if(!w(s.pid)){t.registry.unregister(s.id);continue}a.set(s.id,B(s.pid)),i.set(s.id,await Ge(s.pid));try{await io(s,"SIGTERM")}catch(u){u instanceof Error?l.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:s.pid,pgid:s.pgid,type:s.type},u):l.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:s.pid,pgid:s.pgid,type:s.type,error:String(u)})}}await qe(o,5e3);let c=o.filter(s=>w(s.pid)||(i.get(s.id)??[]).some(u=>w(u.pid)));for(let s of c){let u=$(s.pid,a.get(s.id)??null);u||l.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:s.pid,type:s.type});try{u&&await io(s,"SIGKILL")}catch(p){p instanceof Error?l.debug("SYSTEM","Failed to force kill child process",{pid:s.pid,pgid:s.pgid,type:s.type},p):l.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:s.pid,pgid:s.pgid,type:s.type,error:String(p)})}finally{ks(i.get(s.id)??[],s.pid)}}await qe(c,1e3);for(let s of o)t.registry.unregister(s.id);for(let s of n.filter(u=>u.pid===e))t.registry.unregister(s.id);ao(r,e),t.registry.pruneDeadEntries()}function ao(t,e,r=!1){if(!(0,le.existsSync)(t))return;let n=null;try{let a=JSON.parse((0,le.readFileSync)(t,"utf-8"));n=typeof a.pid=="number"?a.pid:null}catch(a){l.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:a instanceof Error?a.message:String(a)});return}let o=e!==null&&n===e,i=n===null||!w(n);if(!o&&!(r&&i)){l.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,le.rmSync)(t,{force:!0})}catch(a){a instanceof Error?l.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},a):l.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(a)})}}function ks(t,e){for(let{pid:r,startToken:n}of t)if(!(r===e||!w(r))){if(!$(r,n)){l.debug("SYSTEM","Skipping reap: PID was recycled during the grace window",{pid:r,rootPid:e});continue}try{process.kill(r,"SIGKILL"),l.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"&&l.warn("SYSTEM","Failed to reap orphaned descendant during shutdown cascade",{pid:r,rootPid:e,errno:i})}}}async function io(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 F(r,{signalMode:"immediate"});return}try{process.kill(r,e)}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}return}await F(r)}E();var co=3e4,ue=null;function Is(){let e=Ve().pruneDeadEntries();e>0&&l.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function lo(){ue===null&&(ue=setInterval(Is,co),ue.unref(),l.debug("SYSTEM","Health checker started",{intervalMs:co}))}function uo(){ue!==null&&(clearInterval(ue),ue=null,l.debug("SYSTEM","Health checker stopped"))}var fo=require("child_process"),po=require("util");E();var Ls=(0,po.promisify)(fo.execFile),Ps=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/;function xs(t){let e=[];for(let r of t.split(`
|
|
106
|
+
`)){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 Ns(){let t=await Ls("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return xs(t.stdout)}function Us(t,e){let r=t.filter(a=>Ps.test(a.command)&&a.pid!==e.selfPid),n=new Set(r.map(a=>a.pid)),o=r.filter(a=>!n.has(a.ppid)),i=o.filter(a=>a.ppid===e.selfPid?!1:a.ppid===1?!0:!e.isAlive(a.ppid));return{matched:r,roots:o,orphans:i}}async function mo(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??Ns,o=t.isAlive??w,i=t.killTree??(g=>F(g,{signalMode:"graceful"})),a=t.selfPid??process.pid,c;try{c=await n()}catch(g){return l.warn("PROCESS","Orphaned chroma-mcp sweep skipped: cannot read the process table",{error:g instanceof Error?g.message:String(g)}),r.skipped="unreadable",r}let{matched:s,roots:u,orphans:p}=Us(c,{isAlive:o,selfPid:a});if(r.matched=s.length,r.trees=u.length,r.orphans=p.length,p.length===0)return l.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:r.matched,trees:r.trees}),r;l.warn("PROCESS","Reaping orphaned chroma-mcp trees left by dead workers",{orphans:p.length,roots:p.map(g=>g.pid)});let d=new Set,m=8;for(let g=0;g<p.length;g+=m){let T=p.slice(g,g+m);(await Promise.allSettled(T.map(D=>i(D.pid)))).forEach((D,K)=>{let I=T[K];D.status==="fulfilled"?(r.killed+=1,d.add(I.pid)):(r.failed+=1,l.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:I.pid,ppid:I.ppid,error:D.reason instanceof Error?D.reason.message:String(D.reason)}))})}if(t.registry)for(let g of t.registry.getAll())g.type==="chroma"&&d.has(g.pid)&&(t.registry.unregister(g.id),r.unregistered+=1);return l.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:r.orphans,killed:r.killed,failed:r.failed,unregistered:r.unregistered}),r}y();var $s=h.workerPid(),Nt=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(),Ut({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,mo({registry:this.registry}).catch(r=>{l.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),lo()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){l.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,l.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(o){o instanceof Error?l.error("SYSTEM","Error during shutdown",{},o):l.error("SYSTEM","Error during shutdown (non-Error)",{error:String(o)});try{await this.stop()}catch(i){i instanceof Error?l.debug("SYSTEM","Supervisor shutdown fallback failed",{},i):l.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",()=>{l.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}uo(),this.stopPromise=so({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}},Ju=new Nt(Ve());function Ut(t={}){let e=t.pidFilePath??$s;if(!(0,re.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,re.readFileSync)(e,"utf-8"))}catch(o){return o instanceof Error?l.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},o):l.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(o)}),(0,re.rmSync)(e,{force:!0}),"invalid"}return xt(r)&&r?((t.logAlive??!0)&&l.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(t.removeStale===!1||(l.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,re.rmSync)(e,{force:!0})),"stale")}Ce();y();N();E();E();E();E();E();E();y();var Wd=W(P.POWERSHELL_COMMAND);var jd=h.dataDir(),Bd=h.workerPid();E();y();E();y();E();var Hs=9e4,uf=Hs/3;var Eo=require("node:child_process"),_o=require("node:util");E();y();var Tf=(0,_o.promisify)(Eo.execFile);var Ws=1500,js=1e3,Bs=5500,Cf=2*Ws+js+Bs;N();function So(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;l.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max})}return e}var ap=So("CLAUDE_MEM_HEALTH_TIMEOUT_MS",W(P.HEALTH_CHECK),{min:500,max:3e5}),cp=So("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",W(P.HOOK_READINESS_WAIT),{min:0,max:3e5});var lp={min:500,max:P.SESSION_INIT_REQUEST_MAX};function ho(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 Ks(t){return ho()?{...t,verbose:!0}:t}function Ys(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 Gs(t,e,r){let n=typeof e.method=="string"?e.method:"GET",o=Ys(r),i=JSON.stringify(o);l.warn("SYSTEM","Worker IPC fetch failed",{url:t,method:n},i),Y(`[claude-mem] fetch verbose: ${n} ${t} ${i}
|
|
107
|
+
`)}async function Js(t,e={}){let r=Ks(e);try{return await fetch(t,r)}catch(n){throw ho()&&Gs(t,e,n),n}}async function yo(t,e={},r){try{return await Js(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 qs=1e3;var Vs=5e3,up=Vs+qs;var Xs=W(P.API_REQUEST),z=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)}},ze=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=zs(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??Xs}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 z("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.platformSource!==void 0&&(n.platformSource=Xe(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 z("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:Xe(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:Xe(e.platformSource)}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:Xe(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,r,n,o={}){if(!this.apiKey||!this.apiKey.trim())throw new z("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let i=`${this.baseUrl}${r}`,a={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(a.body=JSON.stringify(n));let c,s=o.timeoutMs??this.timeoutMs;try{c=await yo(i,a,s)}catch(p){let d=p instanceof Error?p.message:String(p),m=/timed out|timeout/i.test(d);throw new z(m?"timeout":"transport",`Server ${e} ${r} failed: ${d}`,{cause:p})}if(!c.ok){let p=await c.text().catch(()=>"");throw new z("http_error",`Server ${e} ${r} returned ${c.status}: ${Qs(p,200)}`,{status:c.status})}let u=await c.text();if(!u||u.length===0)return{};try{return JSON.parse(u)}catch(p){let d=p instanceof Error?p:new Error(String(p));throw new z("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:d})}}};function zs(t){return t.replace(/\/+$/,"")}function Xe(t){return typeof t=="string"?Ie(t):null}function Qs(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Zs(){let e=(se().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function ea(){let t=se(),e=(...a)=>{for(let c of a){let s=(c??"").trim();if(s.length>0)return s}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 l.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return l.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return l.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let i={serverBaseUrl:r,apiKey:n};return{runtime:"server",client:new ze(i),projectId:o,serverBaseUrl:r}}function Ao(){if(Zs()!=="server")return{runtime:"worker"};let t=ea();return t||{runtime:"worker"}}E();async function To(t,e){let{config:r,project:n,folderProjects:o,platformSource:i,timeoutMs:a}=e,c=r.totalObservationCount+r.sessionCount+Ee,s=Math.max(1,Math.min(200,c));c>200&&l.debug("HOOK","Server context read capped at the route limit",{wanted:c,limit:200});let u;try{let m=await t.client.contextObservations({projectId:t.projectId,limit:s,folderProjects:o,excludeSubagents:r.mainAgentOnly,...i?{platformSource:i}:{}},a===void 0?{}:{timeoutMs:a});u=Array.isArray(m?.observations)?m.observations:[]}catch(m){return l.warn("HOOK","[server-fallback] session-start context unavailable from the server",{error:m instanceof Error?m.message:String(m)}),null}let p=u.filter(m=>m.kind==="summary");return{observations:u.filter(m=>m.kind!=="summary").slice(0,r.totalObservationCount).map(m=>ta(m,n,i)),summaries:p.slice(0,r.sessionCount+Ee).map(m=>ra(m,n,i))}}function C(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 R(t){return typeof t=="string"?t:t==null?null:String(t)}function Qe(t){if(t==null)return null;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return null}}function Co(t){return Number(C(t,"createdAtEpoch","created_at_epoch"))||Date.now()}function ta(t,e,r){let n=Co(t),o=R(t.content)??"",i=o.split(`
|
|
108
|
+
`,1)[0]??"";return{id:R(t.id)??"",memory_session_id:R(C(t,"serverSessionId","memory_session_id"))??"",platform_source:r??"",type:R(C(t,"kind","type"))??"discovery",title:R(C(t,"title"))??i,subtitle:R(C(t,"subtitle")),narrative:R(C(t,"narrative"))??(o||null),facts:Qe(C(t,"facts")),concepts:Qe(C(t,"concepts")),files_read:Qe(C(t,"files_read","filesRead")),files_modified:Qe(C(t,"files_modified","filesModified")),discovery_tokens:null,created_at:new Date(n).toISOString(),created_at_epoch:n,project:R(C(t,"project"))??e}}function ra(t,e,r){let n=Co(t);return{id:R(t.id)??"",memory_session_id:R(C(t,"serverSessionId","memory_session_id"))??"",platform_source:r??"",request:R(C(t,"request")),investigated:R(C(t,"investigated")),learned:R(C(t,"learned")),completed:R(C(t,"completed")),next_steps:R(C(t,"next_steps","nextSteps")),created_at:new Date(n).toISOString(),created_at_epoch:n,project:R(C(t,"project"))??e}}var Ft=require("crypto");y();N();E();var Dp=1440*60*1e3,na=(0,Ft.randomBytes)(6).toString("hex");function oa(t){return`\u27E6CMEM_NOW_HEADER:${t}\u27E7`}var Ht=oa(na),ia=40,bo=Math.max(0,ia-Ht.length);var aa=wo.default.join((0,Ro.homedir)(),".claude","plugins","marketplaces","thedotmack","plugin",".install-version");function ca(){try{if(!(0,et.existsSync)(ot))return null;let t=new Oo.Database(ot,{readonly:!0,create:!1});try{return t.run(`PRAGMA busy_timeout = ${Tr}`),t}catch(e){throw t.close(),e}}catch(t){if(t instanceof Error&&t.code==="ERR_DLOPEN_FAILED"){try{(0,et.unlinkSync)(aa)}catch(e){e instanceof Error?l.debug("WORKER","Marker file cleanup failed (may not exist)",{},e):l.debug("WORKER","Marker file cleanup failed (may not exist)",{error:String(e)})}return l.error("WORKER","Native module rebuild needed - restart Claude Code to auto-fix"),null}throw t}}function la(t,e,r){return e?yn(t,r):cn(t,r)}function Mo(t,e,r,n,o,i,a,c){let s=[],u=gt(e);s.push(...An(t,u,n,a,c));let p=r.slice(0,n.sessionCount),d=Kr(p,r),m=Yr(e,d),g=Gr(e,n.fullObservationCount),T=a?Mn(m,g,n,o):void 0,b=s.join(`
|
|
109
|
+
`).length+1;s.push(...T?We(T):bn(m,g,n));let D=s.join(`
|
|
110
|
+
`).length,K=r[0],I=e[0];wn(n,K,I)&&s.push(...Rn(K,a));let k=s.join(`
|
|
111
|
+
`).length,tt=Br(e,n,i,o);s.push(...On(tt,a));let Lo=s.join(`
|
|
112
|
+
`).length;return s.push(...vn(u,n,a)),{text:s.join(`
|
|
113
|
+
`).trimEnd(),timelineStart:b,timelineEnd:D,entries:T,summaryEnd:k,previousEnd:Lo}}var ua=new Set(["bugfix","discovery","decision","refactor"]);function da(t,e,r){let n=gt(t),o={bugfix:0,discovery:0,decision:0,refactor:0,other:0},i=new Set,a=Number.POSITIVE_INFINITY;for(let s of t){let u=ua.has(s.type)?s.type:"other";o[u]++,s.memory_session_id&&i.add(s.memory_session_id),s.created_at_epoch&&s.created_at_epoch<a&&(a=s.created_at_epoch)}let c=Number.isFinite(a)?Math.max(0,Math.floor((Date.now()-a)/864e5)):0;return{observation_count:t.length,session_count:i.size,timeline_depth_days:c,has_session_summary:e.length>0,obs_type_bugfix:o.bugfix,obs_type_discovery:o.discovery,obs_type_decision:o.decision,obs_type_refactor:o.refactor,obs_type_other:o.other,tokens_injected:n.totalReadTokens,tokens_saved_vs_naive:n.savings,search_strategy:r?"full":"timeline"}}function vo(t){return t.split(`
|
|
97
114
|
`).map(e=>e.trim()?`${f.red}${e}${f.reset}`:e).join(`
|
|
98
|
-
`)}function
|
|
115
|
+
`)}function fa(t=!1){let e=kn(),r=e?.quotaCooldown,n=null;In(e)?n=$n(e):Nn(e)&&r&&Gn(r)&&(n=Un(e));let o=Xn(Vn());return o&&(n=n?`${n}
|
|
99
116
|
|
|
100
|
-
${o}`:o),n?t?
|
|
117
|
+
${o}`:o),n?t?vo(n):n:""}function Ze(t,e=!1){return t?.includeHealthWarning===!1?"":fa(e)}function Wt(t,e){return t?e?`${e}
|
|
101
118
|
|
|
102
|
-
${t}`:t:e}function
|
|
119
|
+
${t}`:t:e}function pa(t,e){let{text:r,timelineStart:n,timelineEnd:o,entries:i,summaryEnd:a,previousEnd:c}=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 s=tt=>r.slice(0,n)+`${f.reset}
|
|
103
120
|
|
|
104
121
|
[Terminal preview truncated. The model received the full selected context; ${tt?"additional observations are not shown here.":"some presentation text is not shown here."}]
|
|
105
122
|
`,u=r.slice(c),p=r.slice(o,a),d=r.slice(a,c);if(!i)return(s(!1)+r.slice(n)).slice(0,e);let m=0,g=We(i).join(`
|
|
106
|
-
`),
|
|
107
|
-
`);let
|
|
123
|
+
`),T=s(!1),b=T.length+g.length+u.length<=e?T:s(!0);for(;m<i.length&&b.length+g.length+u.length>e;)m++,g=We(i.slice(m)).join(`
|
|
124
|
+
`);let D=e-b.length-g.length-u.length,K=p.length<=D?p:"",I=D-K.length,k="";return d.length<=I?k=d:I>24&&(k=d.slice(0,I-1-f.reset.length)+"\u2026"+f.reset),b+g+K+k+u}function ma(t,e,r,n,o,i,a,c){let s=Or(t,r,(d,m)=>Wt(n,o(d,m)),i);s.reductions>0&&l.debug("HOOK","Trimmed context to fit the hook output limit",{reductions:s.reductions,observations:s.observationCount,sessions:s.config.sessionCount,chars:s.text.length,overBudget:s.overBudget});let u=t.slice(0,s.observationCount),p=s.text;if(c){let d=vo(n),m=d?d.length+2:0;p=Wt(d,pa(c(u,s.config),i-m))}return{text:p,stats:da(u,e.slice(0,s.config.sessionCount),a)}}function Do(t){let e=Rr(),r=t?.cwd??process.cwd(),n=yr(r),o=t?.projects?.length?t.projects:n.allProjects,i=o[o.length-1]??n.primary;t?.full&&(e.totalObservationCount=999999,e.sessionCount=999999);let a=t?.platformSource?Ie(t.platformSource):void 0;return{config:e,cwd:r,projects:o,project:i,platformSource:a}}function ko(t,e,r,n){let{observations:o,summaries:i}=t,{config:a,cwd:c,project:s}=n,u=e?.timePlaceholders?Ht:j(),p=e?.timePlaceholders?bo:0;return o.length===0&&i.length===0?{text:Wt(Ze(e,r),la(s,r,u)),stats:null}:ma(o,i,a,Ze(e),(d,m)=>Mo(s,d,i,m,c,e?.session_id,!1,u).text,e?.full?Number.POSITIVE_INFINITY:1e4-(e?.reserveChars??0)-p,!!e?.full,r?(d,m)=>Mo(s,d,i,m,c,e?.session_id,!0,u):void 0)}async function ga(t,e,r){let n=Do(e);n.config.fetchByIdSupported=!1;let o=await To(t,{config:n.config,project:n.project,folderProjects:n.projects,platformSource:n.platformSource,...r===void 0?{}:{timeoutMs:r}});return{scope:n,rows:o}}function Ea(t,e,r){return t.rows?ko(t.rows,e,r,t.scope):{text:Ze(e,r),stats:null}}async function _a(t,e,r=!1){return Ea(await ga(t,e),e,r)}async function jt(t,e=!1){let r=Ao();if(r.runtime==="server")return _a(r,t,e);let n=Do(t),o=ca();if(!o)return{text:Ze(t,e),stats:null};try{let i={db:o},a=br(o,n.projects.length>1?n.projects:[n.project]),c=Wr(i,a,n.config,n.platformSource),s=jr(i,a,n.config,n.platformSource);return ko({observations:c,summaries:s},t,e,n)}finally{o.close()}}async function Io(t,e=!1){return(await jt(t,e)).text}0&&(module.exports={generateContext,generateContextWithStats});
|
|
108
125
|
//# sourceMappingURL=context-generator.cjs.map
|