claude-mem 13.30.0 → 13.30.1

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.
@@ -81,7 +81,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
81
81
  `),...u!==void 0?{id:u}:{}}:null;return c=null,u=void 0,l=null,a=0,A}if(m[0]===aC)return t.onActivity?.(),null;f(m.length),a+=m.length;let h=n.decode(m),_=h.indexOf(":"),y=_===-1?h:h.slice(0,_),b=_===-1?"":h.slice(_+1);return b.startsWith(" ")&&(b=b.slice(1)),y==="event"?c=b:y==="data"?(l??=[]).push(b):y==="id"&&(u=b),null};for await(let m of cC(e)){let h=[],_=0;for(let y=0;y<m.length;y++){let b=m[y];if(i&&(i=!1,b===uE)){_=y+1;continue}if(b!==cE&&b!==uE)continue;o.push(m.subarray(_,y));let w=uC(o,s+(y-_));o=[],s=0;let A=p(w);A&&h.push(A),i=b===cE,_=y+1}if(_<m.length){let y=m.slice(_);o.push(y),s+=y.length,f(s)}for(let y of h)t.terminalEventNames?.includes(y.event)&&(d=!0),yield y}if(t.terminalEventNames&&t.terminalEventNames.length>0&&!d)throw new nd(t.terminalEventNames)}var Cr=require("fs"),cr=require("path"),Uo=require("os");Bt();V();function lE(e){try{return new URL(e).hostname.toLowerCase()==="openrouter.ai"}catch{return!1}}Qo();var lC="security_alert",dC="sync-hub.black-pond-afbb.workers.dev",fC="https://sync.cmem.ai",pC=new Set(["xiaomi/mimo-v2-flash:free"]);function mC(e){let t=e.CLAUDE_MEM_OPENROUTER_MODEL;if(typeof t!="string"||!pC.has(t.trim()))return!1;let r=typeof e.CLAUDE_MEM_OPENROUTER_BASE_URL=="string"?e.CLAUDE_MEM_OPENROUTER_BASE_URL.trim():"";return r===""||lE(r)}var dE=18e4,fE=[{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 mE(e,t){return(0,cr.join)((0,cr.dirname)(e),`.${(0,cr.basename)(e)}.${t.markerTag}`)}function sd(e,t){try{(0,Cr.writeFileSync)(mE(e,t),new Date().toISOString(),{encoding:"utf-8",mode:384})}catch{}}var pE=new Set;function hC(e){if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;try{if(new URL(t).hostname===dC)return fC}catch{return null}return null}var Te=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(Ot(pe.API_REQUEST)),CLAUDE_MEM_SESSION_INIT_TIMEOUT_MS:String(td()),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,cr.join)((0,Uo.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,cr.join)((0,Uo.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,Uo.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(dE),CLAUDE_MEM_FIELD_OPTIMIZE_TIMEOUT_MS:String(dE),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(t){let r=process.env[t]??this.DEFAULTS[t];return t==="CLAUDE_MEM_WORKER_HOST"?this.normalizeWorkerHost(r):r}static normalizeWorkerHost(t){return t==="localhost"?"127.0.0.1":t}static finalizeSettings(t,r){let n=r?this.applyEnvOverrides(t):t;return n.CLAUDE_MEM_WORKER_HOST=this.normalizeWorkerHost(n.CLAUDE_MEM_WORKER_HOST),n}static getInt(t){let r=this.get(t);return parseInt(r,10)}static applyEnvOverrides(t){let r={...t};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(r[n]=process.env[n]);return r}static loadFromFile(t,r=!0){try{if(!(0,Cr.existsSync)(t)){let d=this.getAllDefaults();try{pt(t,d,{mode:384});for(let f of fE)sd(t,f);console.warn("[SETTINGS] Created settings file with defaults:",t)}catch(f){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",t,f instanceof Error?f.message:String(f))}return this.finalizeSettings(d,r)}let n=(0,Cr.readFileSync)(t,"utf-8"),o=xn(n),s=jr(o),i=s!==o,a=cf(o),c=i&&Object.keys(a).some(d=>d!=="env");if(i&&!c)try{pt(t,s,{mode:384}),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",t)}catch(d){console.warn("[SETTINGS] Failed to auto-migrate settings file:",t,d instanceof Error?d.message:String(d))}if(s.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES===lC){s={...s,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES};try{pt(t,c?{...a,env:s}:s,{mode:384}),console.warn("[SETTINGS] Migrated Telegram trigger types off the legacy default:",t)}catch(d){console.warn("[SETTINGS] Failed to migrate Telegram trigger types:",t,d instanceof Error?d.message:String(d))}}if(mC(s)){let d=String(s.CLAUDE_MEM_OPENROUTER_MODEL).trim();s={...s,CLAUDE_MEM_OPENROUTER_MODEL:this.DEFAULTS.CLAUDE_MEM_OPENROUTER_MODEL};try{pt(t,c?{...a,env:s}:s,{mode:384}),console.warn(`[SETTINGS] Migrated OpenRouter model off the retired default ${d} to ${this.DEFAULTS.CLAUDE_MEM_OPENROUTER_MODEL}:`,t)}catch(f){console.warn("[SETTINGS] Failed to migrate the retired OpenRouter model:",t,f instanceof Error?f.message:String(f))}}let u=hC(s.CLAUDE_MEM_CLOUD_SYNC_HUB_URL);if(u!==null){s={...s,CLAUDE_MEM_CLOUD_SYNC_HUB_URL:u};try{pt(t,c?{...a,env:s}:s,{mode:384}),console.warn("[SETTINGS] Migrated cloud sync hub URL off the legacy workers.dev host:",t)}catch(d){console.warn("[SETTINGS] Failed to migrate cloud sync hub URL:",t,d instanceof Error?d.message:String(d))}}for(let d of fE)if(!(0,Cr.existsSync)(mE(t,d))){if(s[d.key]!==d.legacy){sd(t,d);continue}s={...s,[d.key]:this.DEFAULTS[d.key]};try{pt(t,c?{...a,env:s}:s,{mode:384}),sd(t,d),console.warn(`[SETTINGS] Migrated ${d.key} off the old ${d.legacy}ms default to ${this.DEFAULTS[d.key]}ms:`,t)}catch(f){let p=`${d.key}\0${t}`;pE.has(p)||(pE.add(p),console.warn(`[SETTINGS] Failed to migrate ${d.key}; using the new default in memory (reported once per process):`,t,f instanceof Error?f.message:String(f)))}}let l={...this.DEFAULTS};for(let d of Object.keys(this.DEFAULTS))s[d]!==void 0&&(l[d]=s[d]);return this.finalizeSettings(l,r)}catch(n){console.warn("[SETTINGS] Failed to load settings, using defaults:",t,n instanceof Error?n.message:String(n));let o=this.getAllDefaults();return this.finalizeSettings(o,r)}}};qe();qe();var Hi=null;function Bi(){return Hi!==null||(Hi=Te.loadFromFile(hr)),Hi}function id(e){return(e.CLAUDE_MEM_WORKER_AUTOSTART??"true").trim().toLowerCase()==="false"}var Ir=require("fs");V();var ad=require("node:child_process");function cd(e,t,r){return(0,ad.spawn)(e,t??[],{...r,windowsHide:!0})}var gC=new Set([".cmd",".bat"]),_C=new Set([".exe",".com"]),oZ=new Set([..._C,...gC]);var $r=require("fs"),bE=Je(require("path"),1);V();Bt();var yC=["CLAUDECODE_","CLAUDE_CODE_"],SC=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),EC=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"]),bC=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",...EC]);function ur(e=process.env){let t={};for(let[r,n]of Object.entries(e))if(n!==void 0){if(bC.has(r)){t[r]=n;continue}SC.has(r)||yC.some(o=>r.startsWith(o))||(t[r]=n)}return t}qe();var ld=require("child_process"),gE=require("fs");V();var wC=5e3,hE=new Map,ud=0;function _E(e,t,r){if(r.status!==0)return null;if(typeof r.stdout!="string")return g.warn("SYSTEM","captureProcessStartToken: start-token probe returned no stdout",{pid:t,source:e,status:r.status}),null;let n=r.stdout.trim();return n.length>0?n:null}function vC(e){ud+=1;let t=(0,ld.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${e}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...ur(process.env),LC_ALL:"C",LANG:"C"}});return _E("powershell-cim",e,t)}function kC(e,t=!1){if(!t){let n=hE.get(e);if(n&&(e===process.pid||Date.now()-n.capturedAtMs<wC))return n.token}let r=null;try{r=vC(e)}catch(n){g.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:e,error:n instanceof Error?n.message:String(n)}),r=null}return(r!==null||e!==process.pid)&&hE.set(e,{token:r,capturedAtMs:Date.now()}),r}function yE(e,t){if(!Number.isInteger(e)||e<=0)return null;if(process.platform==="linux"){ud+=1;try{let r=(0,gE.readFileSync)(`/proc/${e}/stat`,"utf-8"),n=r.lastIndexOf(") ");if(n<0)return null;let s=r.slice(n+2).split(" ")[19];return s&&/^\d+$/.test(s)?s:null}catch(r){return g.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:e,error:r instanceof Error?r.message:String(r)}),null}}if(process.platform==="win32")return kC(e,t);ud+=1;try{let r=(0,ld.spawnSync)("ps",["-p",String(e),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...ur(process.env),LC_ALL:"C",LANG:"C"}});return _E("ps-lstart",e,r)}catch(r){return g.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:e,error:r instanceof Error?r.message:String(r)}),null}}function Ct(e){return yE(e,!1)}function vt(e,t){if(t===null)return!0;let r=yE(e,!0);return r===null?!0:r===t}var SE=require("child_process"),Vi=require("fs"),EE=require("util");V();var dd=(0,EE.promisify)(SE.execFile),TC=128,PC=/not found|no running instance|no tasks/i,Ki=class extends Error{pid;constructor(t,r,n){super(r,n),this.name="ProcessTreeKillError",this.pid=t}};async function kt(e,t={}){let r=t.signalMode==="immediate",n=t.expectedStartToken!==void 0?t.expectedStartToken:Ct(e),o=()=>vt(e,n);if(!o()){g.warn("PROCESS","Skipping tree-kill: root PID was reused since it was captured",{pid:e});return}if(g.debug("PROCESS",`Killing process tree rooted at PID ${e}`,{immediate:r}),process.platform==="win32"){try{await dd("taskkill",["/PID",String(e),"/T","/F"],{timeout:5e3,windowsHide:!0})}catch(s){let i=s.code,a=String(s.stderr??""),c=s instanceof Error?s.message:String(s);if(i===TC||PC.test(`${a} ${c}`)){g.debug("PROCESS","taskkill reported the process was already gone",{pid:e});return}throw new Ki(e,`taskkill failed for PID ${e} (exit ${String(i)}): ${a.trim()||c}`,{cause:s})}return}try{let s=r?"SIGKILL":"SIGTERM",i=await Gi(e);for(let u of i){if(!vt(u.pid,u.startToken)){g.debug("PROCESS",`Skipping ${s}: descendant PID was reused since enumeration`,{pid:u.pid,rootPid:e});continue}try{process.kill(u.pid,s)}catch{}}if(o())try{process.kill(e,s)}catch(u){let l=u instanceof Error?u:new Error(String(u)),d=l.code;d!=="ESRCH"&&g.debug("PROCESS",`Failed to ${s} PID ${e}`,{code:d},l)}else g.warn("PROCESS","Skipping root signal: PID was reused during descendant enumeration",{pid:e,signal:s});r||await new Promise(u=>setTimeout(u,500));let a=o()?await Gi(e):[],c=new Map;for(let u of i)c.set(u.pid,u.startToken);for(let u of a)c.set(u.pid,u.startToken);for(let[u,l]of c){if(!vt(u,l)){g.debug("PROCESS","Skipping SIGKILL: descendant PID was reused since the scan",{pid:u,rootPid:e});continue}try{process.kill(u,"SIGKILL")}catch{}}if(!r&&o())try{process.kill(e,"SIGKILL")}catch{}}catch(s){throw new Ki(e,`tree-kill failed for PID ${e}: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}async function xC(){return process.platform==="win32"?MC():process.platform==="linux"?RC():AC()}function RC(){let e=[],t;try{t=(0,Vi.readdirSync)("/proc")}catch(r){return g.warn("PROCESS","Cannot read /proc \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),e}for(let r of t){if(!/^\d+$/.test(r))continue;let n;try{n=(0,Vi.readFileSync)(`/proc/${r}/stat`,"utf-8")}catch{continue}let o=n.lastIndexOf(") ");if(o<0)continue;let s=n.slice(o+2).split(" "),i=Number.parseInt(s[1]??"",10),a=s[19];Number.isFinite(i)&&e.push({pid:Number.parseInt(r,10),ppid:i,startToken:a&&/^\d+$/.test(a)?a:null})}return e}async function AC(){let e;try{e=(await dd("ps",["-eo","pid=,ppid=,lstart="],{timeout:1e4,maxBuffer:33554432,env:{...process.env,LC_ALL:"C",LANG:"C"}})).stdout}catch(r){return g.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 t=[];for(let r of e.split(`
82
82
  `)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);if(!n)continue;let o=n[3].trim();t.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:o.length>0?o:null})}return t}async function MC(){let e;try{e=(await dd("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 g.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 t=[];for(let r of e.split(/\r?\n/).slice(1)){let n=r.match(/^"(\d+)","(\d+)","(.*)"$/);if(!n)continue;let o=n[3].trim();t.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:o.length>0?o:null})}return t}async function Gi(e){let t=await xC(),r=new Map;for(let i of t){let a=r.get(i.ppid);a?a.push(i):r.set(i.ppid,[i])}let n=new Set([e]),o=[],s=i=>{for(let a of r.get(i)??[])n.has(a.pid)||(n.add(a.pid),s(a.pid),o.push({pid:a.pid,startToken:a.startToken}))};return s(e),o}var OC=5e3,CC=1e3,$C=Fe.supervisorRegistry(),IC=null;function ge(e){if(!Number.isInteger(e)||e<0||e===0)return!1;try{return process.kill(e,0),!0}catch(t){if(t instanceof Error){let r=t.code;return r==="EPERM"?!0:(g.debug("SYSTEM","PID check failed",{pid:e,code:r}),!1)}return g.warn("SYSTEM","PID check threw non-Error",{pid:e,error:String(t)}),!1}}async function Yi(e,t){let r=Date.now()+t;for(;Date.now()<r;){if(e.every(n=>!ge(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function wE(e){if(!e||!ge(e.pid))return!1;if(!e.startToken)return!0;let t=Ct(e.pid);if(t===null)return!0;let r=t===e.startToken;return r||g.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:e.pid,stored:e.startToken,current:t}),r}var DC={platform:process.platform,readCommandLine:e=>(0,$r.readFileSync)(`/proc/${e}/cmdline`,"utf-8")};function Ji(e,t=DC){if(!wE(e))return!1;if(e.startToken||t.platform!=="linux")return!0;let r;try{r=t.readCommandLine(e.pid)}catch(o){return g.debug("SYSTEM","Could not read the command line of a token-less worker PID; trusting the live PID",{pid:e.pid,error:o instanceof Error?o.message:String(o)}),!0}let n=r.split("\0").some(o=>bE.default.basename(o)==="worker-service.cjs");return n||g.debug("SYSTEM","Token-less worker PID now belongs to another program (PID reused)",{pid:e.pid}),n}function Xi(e=Fe.workerPid()){if(!(0,$r.existsSync)(e))return null;let t;try{t=JSON.parse((0,$r.readFileSync)(e,"utf-8"))}catch{return null}return t!==null&&Ji(t)?t:null}var md=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(t=$C){this.registryPath=t}initialize(){if(this.initialized)return;if(this.initialized=!0,!(0,$r.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,$r.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[o,s]of Object.entries(n))this.entries.set(o,s)}catch(r){r instanceof Error?g.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):g.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let t=this.pruneDeadEntries();t>0&&g.info("SYSTEM","Removed dead processes from supervisor registry",{removed:t}),this.persist()}retainSupersededEntry(t,r){let n=this.entries.get(t);if(!n||n.pid===r||!ge(n.pid))return;let o=`${t}#superseded:${n.pid}`;this.entries.set(o,n);let s=this.runtimeProcesses.get(t);s&&(this.runtimeProcesses.set(o,s),this.runtimeProcesses.delete(t)),g.warn("SYSTEM","Registry id reused while the previous process was still alive; kept it for reaping",{id:t,supersededId:o,supersededPid:n.pid,incomingPid:r})}register(t,r,n){this.initialize(),this.retainSupersededEntry(t,r.pid),this.entries.set(t,r),n&&this.runtimeProcesses.set(t,n),this.persist()}unregister(t,r){this.initialize();let n=t,o=this.entries.get(n);r!==void 0&&o?.pid!==r&&(n=`${t}#superseded:${r}`,o=this.entries.get(n),o?.pid!==r)||o&&(this.entries.delete(n),this.runtimeProcesses.delete(n),this.persist(),o?.type==="sdk"&&pd())}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([t,r])=>({id:t,...r})).sort((t,r)=>{let n=Date.parse(t.startedAt),o=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(o)?0:o)})}getBySession(t){let r=String(t);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===r)}getRuntimeProcess(t){return this.runtimeProcesses.get(t)}pruneDeadEntries(){this.initialize();let t=0,r=0;for(let[n,o]of this.entries)ge(o.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),t+=1,o.type==="sdk"&&(r+=1));t>0&&this.persist();for(let n=0;n<r;n+=1)pd();return t}async reapSession(t){this.initialize();let r=this.getBySession(t);if(r.length===0)return 0;let n=typeof t=="number"?t:Number(t)||void 0;g.info("SYSTEM",`Reaping ${r.length} process(es) for session ${t}`,{sessionId:n,pids:r.map(a=>a.pid)});let o=r.filter(a=>ge(a.pid)),s=new Map(o.map(a=>[a.pid,Ct(a.pid)]));for(let a of o)try{process.platform==="win32"?await kt(a.pid,{expectedStartToken:s.get(a.pid)??null}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&g.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):g.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}await Yi(o,OC);let i=o.filter(a=>ge(a.pid));for(let a of i){g.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});let c=s.get(a.pid)??null;if(!vt(a.pid,c)){g.warn("SYSTEM","Skipping SIGKILL: session process PID was reused during the grace window",{pid:a.pid,sessionId:n});continue}try{process.platform==="win32"?await kt(a.pid,{expectedStartToken:c}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(u){u instanceof Error?u.code!=="ESRCH"&&g.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},u):g.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(u)})}}if(i.length>0){let a=Date.now()+CC;for(;Date.now()<a&&i.filter(u=>ge(u.pid)).length!==0;)await new Promise(u=>setTimeout(u,100))}for(let a of r)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of r)a.type==="sdk"&&pd();return g.info("SYSTEM",`Reaped ${r.length} process(es) for session ${t}`,{sessionId:n,reaped:r.length}),r.length}persist(){let t={processes:Object.fromEntries(this.entries.entries())};try{pt(this.registryPath,t),this.persistDegraded=!1}catch(r){this.reportPersistFailure(r)}}reportPersistFailure(t){if(this.persistDegraded)return;this.persistDegraded=!0;let r=t instanceof Error?t:new Error(String(t));g.warn("SYSTEM","Failed to persist supervisor registry; keeping it in memory",{path:this.registryPath},r);try{IC?.({errorCategory:r.code??"unknown"})}catch{}}},fd=null;function Qi(){return fd||(fd=new md),fd}var kZ=180*1e3,NC=[];function pd(){let e=NC.shift();e&&e.notify()}var Sn=require("fs");V();qe();var LC=Fe.workerPid();async function kE(e){let t=e.currentPid??process.pid,r=e.pidFilePath??LC,n=e.registry.getAll(),o=[...n].filter(c=>c.pid!==t).sort((c,u)=>Date.parse(u.startedAt)-Date.parse(c.startedAt)),s=new Map,i=new Map;for(let c of o){if(!ge(c.pid)){e.registry.unregister(c.id);continue}i.set(c.id,Ct(c.pid)),s.set(c.id,await Gi(c.pid));try{await vE(c,"SIGTERM")}catch(u){u instanceof Error?g.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:c.pid,pgid:c.pgid,type:c.type},u):g.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(u)})}}await Yi(o,5e3);let a=o.filter(c=>ge(c.pid)||(s.get(c.id)??[]).some(u=>ge(u.pid)));for(let c of a){let u=vt(c.pid,i.get(c.id)??null);u||g.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:c.pid,type:c.type});try{u&&await vE(c,"SIGKILL")}catch(l){l instanceof Error?g.debug("SYSTEM","Failed to force kill child process",{pid:c.pid,pgid:c.pgid,type:c.type},l):g.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(l)})}finally{zC(s.get(c.id)??[],c.pid)}}await Yi(a,1e3);for(let c of o)e.registry.unregister(c.id);for(let c of n.filter(u=>u.pid===t))e.registry.unregister(c.id);hd(r,t),e.registry.pruneDeadEntries()}function hd(e,t,r=!1){if(!(0,Sn.existsSync)(e))return;let n=null;try{let i=JSON.parse((0,Sn.readFileSync)(e,"utf-8"));n=typeof i.pid=="number"?i.pid:null}catch(i){g.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:e,error:i instanceof Error?i.message:String(i)});return}let o=t!==null&&n===t,s=n===null||!ge(n);if(!o&&!(r&&s)){g.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:e,recordedPid:n,currentPid:t});return}try{(0,Sn.rmSync)(e,{force:!0})}catch(i){i instanceof Error?g.debug("SYSTEM","Failed to remove PID file",{pidFilePath:e},i):g.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:e,error:String(i)})}}function zC(e,t){for(let{pid:r,startToken:n}of e)if(!(r===t||!ge(r))){if(!vt(r,n)){g.debug("SYSTEM","Skipping reap: PID was recycled during the grace window",{pid:r,rootPid:t});continue}try{process.kill(r,"SIGKILL"),g.debug("SYSTEM","Reaped orphaned descendant during shutdown cascade",{pid:r,rootPid:t})}catch(o){let s=o instanceof Error?o.code:void 0;s!=="ESRCH"&&g.warn("SYSTEM","Failed to reap orphaned descendant during shutdown cascade",{pid:r,rootPid:t,errno:s})}}}async function vE(e,t){let{pid:r,pgid:n}=e;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,t);return}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}if(t==="SIGKILL"){await kt(r,{signalMode:"immediate"});return}try{process.kill(r,t)}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}return}await kt(r)}V();var TE=3e4,En=null;function UC(){let t=Qi().pruneDeadEntries();t>0&&g.info("SYSTEM",`Health check: pruned ${t} dead process(es) from registry`)}function PE(){En===null&&(En=setInterval(UC,TE),En.unref(),g.debug("SYSTEM","Health checker started",{intervalMs:TE}))}function xE(){En!==null&&(clearInterval(En),En=null,g.debug("SYSTEM","Health checker stopped"))}var RE=require("child_process"),AE=require("util");V();var jC=(0,AE.promisify)(RE.execFile),FC=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/;function qC(e){let t=[];for(let r of e.split(`
83
83
  `)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);n&&t.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),command:n[3].trim()})}return t}async function ZC(){let e=await jC("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return qC(e.stdout)}function WC(e,t){let r=e.filter(i=>FC.test(i.command)&&i.pid!==t.selfPid),n=new Set(r.map(i=>i.pid)),o=r.filter(i=>!n.has(i.ppid)),s=o.filter(i=>i.ppid===t.selfPid?!1:i.ppid===1?!0:!t.isAlive(i.ppid));return{matched:r,roots:o,orphans:s}}async function ME(e={}){let t=e.platform??process.platform,r={matched:0,trees:0,orphans:0,killed:0,failed:0,unregistered:0,skipped:null};if(t==="win32")return r.skipped="windows",r;let n=e.readTable??ZC,o=e.isAlive??ge,s=e.killTree??(p=>kt(p,{signalMode:"graceful"})),i=e.selfPid??process.pid,a;try{a=await n()}catch(p){return g.warn("PROCESS","Orphaned chroma-mcp sweep skipped: cannot read the process table",{error:p instanceof Error?p.message:String(p)}),r.skipped="unreadable",r}let{matched:c,roots:u,orphans:l}=WC(a,{isAlive:o,selfPid:i});if(r.matched=c.length,r.trees=u.length,r.orphans=l.length,l.length===0)return g.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:r.matched,trees:r.trees}),r;g.warn("PROCESS","Reaping orphaned chroma-mcp trees left by dead workers",{orphans:l.length,roots:l.map(p=>p.pid)});let d=new Set,f=8;for(let p=0;p<l.length;p+=f){let m=l.slice(p,p+f);(await Promise.allSettled(m.map(_=>s(_.pid)))).forEach((_,y)=>{let b=m[y];_.status==="fulfilled"?(r.killed+=1,d.add(b.pid)):(r.failed+=1,g.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:b.pid,ppid:b.ppid,error:_.reason instanceof Error?_.reason.message:String(_.reason)}))})}if(e.registry)for(let p of e.registry.getAll())p.type==="chroma"&&d.has(p.pid)&&(e.registry.unregister(p.id),r.unregistered+=1);return g.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:r.orphans,killed:r.killed,failed:r.failed,unregistered:r.unregistered}),r}qe();var HC=Fe.workerPid(),gd=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(t){this.registry=t}async start(){if(this.started)return;if(this.registry.initialize(),ea({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,ME({registry:this.registry}).catch(r=>{g.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),PE()}configureSignalHandlers(t){if(this.shutdownHandler=t,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){g.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,g.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(o){o instanceof Error?g.error("SYSTEM","Error during shutdown",{},o):g.error("SYSTEM","Error during shutdown (non-Error)",{error:String(o)});try{await this.stop()}catch(s){s instanceof Error?g.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):g.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(s)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{g.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}xE(),this.stopPromise=kE({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(t){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${t}`)}registerProcess(t,r,n){this.registry.register(t,r,n)}unregisterProcess(t,r){this.registry.unregister(t,r)}getRegistry(){return this.registry}},BC=new gd(Qi());function _d(){return BC}function ea(e={}){let t=e.pidFilePath??HC;if(!(0,Ir.existsSync)(t))return"missing";let r=null;try{r=JSON.parse((0,Ir.readFileSync)(t,"utf-8"))}catch(o){return o instanceof Error?g.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:t},o):g.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:t,error:String(o)}),(0,Ir.rmSync)(t,{force:!0}),"invalid"}return Ji(r)&&r?((e.logAlive??!0)&&g.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(e.removeStale===!1||(g.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,Ir.rmSync)(t,{force:!0})),"stale")}Xo();var yd=require("path"),ra=require("fs"),CE=require("crypto");qe();var ta=require("fs");Bt();function OE(e,t){if(!(0,ta.existsSync)(e))return t;try{return xn((0,ta.readFileSync)(e,"utf-8"))}catch(r){throw new Error(`Corrupt JSON file, refusing to overwrite: ${e}: ${r instanceof Error?r.message:String(r)}`)}}V();var $E="telemetry.json";function KC(e){let t=e.DO_NOT_TRACK;return t===void 0||t===""?!1:t!=="0"&&t!=="false"}function GC(e,t){if(KC(e))return{enabled:!1,source:"DO_NOT_TRACK"};let r=e.CLAUDE_MEM_TELEMETRY?.toLowerCase();return r==="0"||r==="false"||r==="off"?{enabled:!1,source:"env"}:r==="1"||r==="true"||r==="on"?{enabled:!0,source:"env"}:t?.enabled===!0?{enabled:!0,source:"config"}:t?.enabled===!1?{enabled:!1,source:"config"}:{enabled:!0,source:"default"}}function IE(e,t){return GC(e,t).enabled}function VC(){return(0,yd.join)(It(),$E)}function Sd(){let e;try{e=OE(VC(),null)}catch(t){let r=t instanceof Error?t:new Error(String(t));return g.warn("SYSTEM","Telemetry: corrupt telemetry.json; treating as no recorded consent",void 0,r),null}return!e||typeof e!="object"||typeof e.installId!="string"||e.enabled!==void 0&&typeof e.enabled!="boolean"?null:{enabled:e.enabled,installId:e.installId,decidedAt:typeof e.decidedAt=="string"?e.decidedAt:""}}function YC(e){let t=It();(0,ra.mkdirSync)(t,{recursive:!0}),(0,ra.writeFileSync)((0,yd.join)(t,$E),JSON.stringify(e,null,2)+`
84
- `)}function DE(){let e=Sd();if(e?.installId)return e.installId;let t=(0,CE.randomUUID)();return YC({installId:t,decidedAt:""}),t}var LE=Je(require("os"),1);V();var NE=8192,lt="[REDACTED]";function JC(e){try{if(typeof e!="string"){if(e==null)return"";try{e=String(e)}catch(r){let n=r instanceof Error?r:new Error(String(r));return g.warn("SYSTEM","error-scrub: String() coercion of non-string input failed",void 0,n),""}}let t=e;return t.length>NE?t.slice(0,NE):t}catch{return""}}function XC(e){if(typeof e!="string"||e.length===0)return e??"";let t="";try{t=LE.default.homedir()||""}catch(n){let o=n instanceof Error?n:new Error(String(n));g.warn("SYSTEM","error-scrub: os.homedir() failed; skipping home-dir redaction",void 0,o),t=""}if(!t)return e;let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");try{return e.replace(new RegExp(r,"g"),"~")}catch(n){let o=n instanceof Error?n:new Error(String(n));return g.warn("SYSTEM","error-scrub: home-dir RegExp replace failed; using split/join fallback",void 0,o),e.split(t).join("~")}}function QC(e){return typeof e!="string"||e.length===0?e??"":e.replace(/(?<![~\w])\/(?:[^\s/:"'()]+\/)+([^\s/:"'()]+)/g,"$1").replace(/[A-Za-z]:\\(?:[^\s\\:"'()]+\\)*([^\s\\:"'()]+)/g,"$1").replace(/\\\\[^\s\\:"'()]+(?:\\[^\s\\:"'()]+)*\\([^\s\\:"'()]+)/g,"$1")}function e$(e){return typeof e!="string"||e.length===0?e??"":e.replace(/\b[A-Za-z][A-Za-z0-9+.-]*:\/\/[^\s"'()]+/g,t=>/^https?:\/\/hooks\.slack\.com\/services\//i.test(t)?t.replace(/^(https?:\/\/hooks\.slack\.com\/services\/)[^\s"'()]+/i,`$1${lt}`):t.replace(/[?#].*$/,"").replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/@\s]+@/,`$1${lt}@`))}function t$(e){return typeof e!="string"||e.length===0?e??"":e.replace(/\?[^\s"'()]*/g,"")}function r$(e){return typeof e!="string"||e.length===0?e??"":e.replace(/\b(?:access[_-]?token|api[_-]?key|auth(?:orization)?|secret|password|passwd|jwt|session[_-]?id|token)=[^\s"'&]+/gi,t=>{let r=t.indexOf("=");return`${t.slice(0,r+1)}${lt}`})}function n$(e){if(typeof e!="string"||e.length===0)return e??"";let t=e;return t=t.replace(/[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}/g,lt),t=t.replace(/\b[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\b/g,lt),t=t.replace(/\b(?:sk|pk|rk|ak|phc|phx|ph|ghp|gho|ghs|xox[bpasr])[-_][A-Za-z0-9_-]{8,512}\b/gi,lt),t=t.replace(/\bBearer\s+[A-Za-z0-9._-]{8,512}\b/gi,lt),t=t.replace(/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g,lt),t=t.replace(/\b[0-9a-fA-F]{24,4096}\b/g,lt),t=t.replace(/\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/g,lt),t=t.replace(/\b(?=[A-Za-z0-9+/_-]{0,4096}\d)[A-Za-z0-9+/_-]{32,4096}={0,2}\b/g,lt),t=t.replace(/\b(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}\b/g,lt),t}function zE(e){let t=JC(e);return t.length===0?"":(t=XC(t),t=e$(t),t=QC(t),t=t$(t),t=r$(t),t=n$(t),t)}var o$=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","stage","phase","install_method","interactive","provider_source","bun_version","uv_version","claude_code_version","trial_days","trial_variant","offer_surface","funnel_source","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","limit_window","overage_status","is_using_overage","resets_in_minutes","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_aborted_deadline_exceeded","outcomes_invalid_output","top_model","top_abort_reason","observed_model","observed_billing","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","skill_id","skill_source","skill_trigger","observations_created","total_observations_injected","total_tokens_saved_vs_naive"]),UE=200;function s$(e,t){if(!(!e||typeof e!="object"))for(let r of Object.keys(e)){if(!o$.has(r))continue;let n=e[r];if(typeof n=="string"){let o=n.length>UE?n.slice(0,UE):n;t[r]=zE(o)}else(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(t[r]=n)}}function jE(e){let t={};try{s$(e,t)}catch{}return t}var Ed=Je(require("os"),1);V();var i$="13.30.0",a$="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",c$="https://us.i.posthog.com";function FE(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||a$}function qE(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||c$}var u$=["version","os","os_version","is_wsl","arch","runtime","locale","ide","provider","runtime_mode","install_method","claude_code_version","first_active_date","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs"];function ZE(e){let t={};for(let r of u$)e[r]!==void 0&&(t[r]=e[r]);return t}function l$(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||Ed.default.release().toLowerCase().includes("microsoft")}catch(e){let t=e instanceof Error?e:new Error(String(e));return g.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,t),!1}}function WE(){return{version:i$,os:process.platform,os_version:Ed.default.release(),is_wsl:l$(),arch:process.arch,runtime:process.versions.bun?"bun":"node",runtime_version:process.versions.bun??process.versions.node,node_version:process.versions.node,is_ci:!!process.env.CI,locale:Intl.DateTimeFormat().resolvedOptions().locale}}var d$=2e3;async function bd(e,t,r){try{if(!IE(process.env,Sd()))return;let n=jE({...WE(),...t??{}});if(r?.person?n.$set=ZE(n):n.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:e,properties:n})+`
84
+ `)}function DE(){let e=Sd();if(e?.installId)return e.installId;let t=(0,CE.randomUUID)();return YC({installId:t,decidedAt:""}),t}var LE=Je(require("os"),1);V();var NE=8192,lt="[REDACTED]";function JC(e){try{if(typeof e!="string"){if(e==null)return"";try{e=String(e)}catch(r){let n=r instanceof Error?r:new Error(String(r));return g.warn("SYSTEM","error-scrub: String() coercion of non-string input failed",void 0,n),""}}let t=e;return t.length>NE?t.slice(0,NE):t}catch{return""}}function XC(e){if(typeof e!="string"||e.length===0)return e??"";let t="";try{t=LE.default.homedir()||""}catch(n){let o=n instanceof Error?n:new Error(String(n));g.warn("SYSTEM","error-scrub: os.homedir() failed; skipping home-dir redaction",void 0,o),t=""}if(!t)return e;let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");try{return e.replace(new RegExp(r,"g"),"~")}catch(n){let o=n instanceof Error?n:new Error(String(n));return g.warn("SYSTEM","error-scrub: home-dir RegExp replace failed; using split/join fallback",void 0,o),e.split(t).join("~")}}function QC(e){return typeof e!="string"||e.length===0?e??"":e.replace(/(?<![~\w])\/(?:[^\s/:"'()]+\/)+([^\s/:"'()]+)/g,"$1").replace(/[A-Za-z]:\\(?:[^\s\\:"'()]+\\)*([^\s\\:"'()]+)/g,"$1").replace(/\\\\[^\s\\:"'()]+(?:\\[^\s\\:"'()]+)*\\([^\s\\:"'()]+)/g,"$1")}function e$(e){return typeof e!="string"||e.length===0?e??"":e.replace(/\b[A-Za-z][A-Za-z0-9+.-]*:\/\/[^\s"'()]+/g,t=>/^https?:\/\/hooks\.slack\.com\/services\//i.test(t)?t.replace(/^(https?:\/\/hooks\.slack\.com\/services\/)[^\s"'()]+/i,`$1${lt}`):t.replace(/[?#].*$/,"").replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/@\s]+@/,`$1${lt}@`))}function t$(e){return typeof e!="string"||e.length===0?e??"":e.replace(/\?[^\s"'()]*/g,"")}function r$(e){return typeof e!="string"||e.length===0?e??"":e.replace(/\b(?:access[_-]?token|api[_-]?key|auth(?:orization)?|secret|password|passwd|jwt|session[_-]?id|token)=[^\s"'&]+/gi,t=>{let r=t.indexOf("=");return`${t.slice(0,r+1)}${lt}`})}function n$(e){if(typeof e!="string"||e.length===0)return e??"";let t=e;return t=t.replace(/[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}/g,lt),t=t.replace(/\b[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\b/g,lt),t=t.replace(/\b(?:sk|pk|rk|ak|phc|phx|ph|ghp|gho|ghs|xox[bpasr])[-_][A-Za-z0-9_-]{8,512}\b/gi,lt),t=t.replace(/\bBearer\s+[A-Za-z0-9._-]{8,512}\b/gi,lt),t=t.replace(/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g,lt),t=t.replace(/\b[0-9a-fA-F]{24,4096}\b/g,lt),t=t.replace(/\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/g,lt),t=t.replace(/\b(?=[A-Za-z0-9+/_-]{0,4096}\d)[A-Za-z0-9+/_-]{32,4096}={0,2}\b/g,lt),t=t.replace(/\b(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}\b/g,lt),t}function zE(e){let t=JC(e);return t.length===0?"":(t=XC(t),t=e$(t),t=QC(t),t=t$(t),t=r$(t),t=n$(t),t)}var o$=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","stage","phase","install_method","interactive","provider_source","bun_version","uv_version","claude_code_version","trial_days","trial_variant","offer_surface","funnel_source","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","limit_window","overage_status","is_using_overage","resets_in_minutes","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_aborted_deadline_exceeded","outcomes_invalid_output","top_model","top_abort_reason","observed_model","observed_billing","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","skill_id","skill_source","skill_trigger","observations_created","total_observations_injected","total_tokens_saved_vs_naive"]),UE=200;function s$(e,t){if(!(!e||typeof e!="object"))for(let r of Object.keys(e)){if(!o$.has(r))continue;let n=e[r];if(typeof n=="string"){let o=n.length>UE?n.slice(0,UE):n;t[r]=zE(o)}else(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(t[r]=n)}}function jE(e){let t={};try{s$(e,t)}catch{}return t}var Ed=Je(require("os"),1);V();var i$="13.30.1",a$="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",c$="https://us.i.posthog.com";function FE(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||a$}function qE(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||c$}var u$=["version","os","os_version","is_wsl","arch","runtime","locale","ide","provider","runtime_mode","install_method","claude_code_version","first_active_date","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs"];function ZE(e){let t={};for(let r of u$)e[r]!==void 0&&(t[r]=e[r]);return t}function l$(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||Ed.default.release().toLowerCase().includes("microsoft")}catch(e){let t=e instanceof Error?e:new Error(String(e));return g.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,t),!1}}function WE(){return{version:i$,os:process.platform,os_version:Ed.default.release(),is_wsl:l$(),arch:process.arch,runtime:process.versions.bun?"bun":"node",runtime_version:process.versions.bun??process.versions.node,node_version:process.versions.node,is_ci:!!process.env.CI,locale:Intl.DateTimeFormat().resolvedOptions().locale}}var d$=2e3;async function bd(e,t,r){try{if(!IE(process.env,Sd()))return;let n=jE({...WE(),...t??{}});if(r?.person?n.$set=ZE(n):n.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:e,properties:n})+`
85
85
  `);return}let o=FE(),s=new AbortController,i=setTimeout(()=>s.abort(),d$);try{await f$(o,e,n,s.signal)}finally{clearTimeout(i)}}catch{}}async function f$(e,t,r,n){await fetch(`${qE()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:e,event:t,distinct_id:DE(),properties:r}),signal:n})}var Ye=Je(require("path"),1),Ad=require("os"),Pe=require("fs"),Fo=require("child_process");V();V();V();var ze=Je(require("path"),1),bn=require("fs"),ia=require("os"),Td=require("child_process");An();qe();V();var na=require("fs"),lr=Je(require("path"),1);V();var jo={isWorktree:!1,isSubmodule:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function HE(e){let t=lr.default.join(e,".git"),r;try{r=(0,na.statSync)(t)}catch(c){return c instanceof Error&&c.code!=="ENOENT"&&g.warn("GIT","Unexpected error checking .git",{error:c instanceof Error?c.message:String(c)}),jo}if(!r.isFile())return jo;let n;try{n=(0,na.readFileSync)(t,"utf-8").trim()}catch(c){return g.warn("GIT","Failed to read .git file",{error:c instanceof Error?c.message:String(c)}),jo}let o=n.match(/^gitdir:\s*(.+)$/);if(!o)return jo;let s=lr.default.resolve(lr.default.dirname(t),o[1]),i=s.match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(i){let c=i[1];return{isWorktree:!0,isSubmodule:!1,worktreeName:lr.default.basename(e),parentRepoPath:c,parentProjectName:lr.default.basename(c)}}let a=s.match(/^(.+)[/\\]\.git[/\\]modules[/\\](.+)$/);if(a){let c=a[1];return{isWorktree:!1,isSubmodule:!0,worktreeName:lr.default.basename(e),parentRepoPath:c,parentProjectName:lr.default.basename(c)}}return jo}var GE=require("fs");var BE=require("path");An();V();function p$(e){let t=$t(e.replace(/\\/g,"/"));t=t.replace(/\\/g,"/");let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&");return r=r.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${r}$`)}function KE(e,t){if(!t.length)return!1;let r=e.replace(/\\/g,"/"),n=(0,BE.basename)(r);for(let o of t){let s=o.trim();if(s)try{let i=p$(s);if(i.test(r)||i.test(n))return!0}catch(i){g.warn("PROJECT_NAME","Invalid glob pattern",{pattern:s,error:i instanceof Error?i.message:String(i)});continue}}return!1}V();function VE(e){let t=e;if(typeof t=="string"){if(!t.trim())return[];try{t=JSON.parse(t)}catch(n){return g.warn("PROJECT_NAME","CLAUDE_MEM_PROJECT_ENVIRONMENTS is not valid JSON; ignoring it",{error:n instanceof Error?n.message:String(n)}),[]}}if(!Array.isArray(t))return t!=null&&g.warn("PROJECT_NAME","CLAUDE_MEM_PROJECT_ENVIRONMENTS must be an array; ignoring it",{}),[];let r=[];for(let n of t){let o=typeof n?.name=="string"?n.name.trim():"",s=Array.isArray(n?.patterns)?n.patterns.filter(i=>typeof i=="string"&&i.trim()!==""):[];if(!o||s.length===0){g.warn("PROJECT_NAME","Ignoring a project environment without a name or patterns",{name:o});continue}r.push({name:o,patterns:s})}return r}function m$(e){try{return(0,GE.realpathSync)(e)}catch{return e}}function wd(e,t){if(t.length===0)return null;let r=[...new Set([e,m$(e)])].flatMap(n=>[n,`${n.replace(/[\\/]+$/,"")}/`]);for(let n of t)if(r.some(o=>KE(o,n.patterns)))return n.name;return null}var Pd="unknown-project";function XE(e){try{return(0,Td.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim()||null}catch(t){let r=t instanceof Error?t:new Error(String(t));return g.debug("PROJECT_NAME","git rev-parse failed, falling back to non-git root",{dir:e},r),null}}var h$=[".claude-mem-project",".claude-mem.json"],g$=64;function QE(e){try{return(0,bn.realpathSync)(e)}catch{return e}}function _$(e,t){let r=ze.default.relative(t,e);return r===""||!r.startsWith("..")&&!ze.default.isAbsolute(r)}function y$(){return[(0,ia.homedir)(),(0,ia.tmpdir)(),Mn].flatMap(e=>{let t=ze.default.resolve(e);return[t,QE(t)]})}function eb(e){let t=y$(),r=ze.default.resolve(e);if([ze.default.resolve(Mn),QE(ze.default.resolve(Mn))].some(o=>_$(r,o)))return null;for(let o=0;o<g$;o++){if(t.includes(r))return null;let s=ze.default.dirname(r);if(s===r)return null;if(h$.some(i=>(0,bn.existsSync)(ze.default.join(r,i))))return r;r=s}return null}function kd(e,t){let r=ze.default.basename(t);if(r===""){if(process.platform==="win32"){let o=e.match(/^([A-Z]):\\/i);if(o){let i=`drive-${o[1].toUpperCase()}`;return g.info("PROJECT_NAME","Drive root detected",{cwd:e,projectName:i}),i}}return g.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:e}),Pd}return r}var S$="CLAUDE_MEM_PROJECT_NAME_SOURCE",oa=null;function YE(){try{return(0,bn.statSync)(hr).mtimeMs}catch{return-1}}function tb(){let e=YE();if(e===-1)return Te.getAllDefaults();if(oa&&oa.mtimeMs===e)return oa.settings;let t=Te.loadFromFile(hr);return oa={mtimeMs:YE(),settings:t},t}function E$(){let e=process.env[S$]??tb().CLAUDE_MEM_PROJECT_NAME_SOURCE;return String(e??"path").trim().toLowerCase()==="git-remote"}var b$="CLAUDE_MEM_PROJECT_ENVIRONMENTS",sa=null;function rb(){let e=process.env[b$]??tb().CLAUDE_MEM_PROJECT_ENVIRONMENTS;return(!sa||sa.raw!==e)&&(sa={raw:e,environments:VE(e)}),sa.environments}function w$(e){let t=(e??"").trim();if(!t||/^file:/i.test(t)||t.startsWith("/")||t.startsWith(".")||t.startsWith("~")||t.startsWith("\\\\")||/^[a-z]:[\\/]/i.test(t))return null;let n=t.replace(/\/+$/,"").replace(/\.git$/i,""),o=n.match(/^[a-z][a-z0-9+.-]*:\/\/[^/]+\/(.+)$/i),s=o?null:n.match(/^(?:[^/@\s]+@)?[^:/\s]+:(?!\/\/)(.+)$/),i=o?.[1]??s?.[1];if(!i)return null;let a=i.split("/").filter(c=>c&&c!=="_git");return a.length>=2?a.slice(-2).join("/"):a.length===1?a[0]:null}function v$(e){try{let t=(0,Td.execFileSync)("git",["remote","get-url","origin"],{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim();return w$(t)}catch(t){let r=t instanceof Error?t:new Error(String(t));return g.debug("PROJECT_NAME","No usable origin remote, keeping the path-based name",{repoRoot:e},r),null}}var vd=new Map;function nb(e){return E$()?(vd.has(e)||vd.set(e,v$(e)),vd.get(e)??null):null}function k$(e,t=process.platform){if(!e||e.trim()==="")return g.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:e}),Pd;let r=$t(e,t),n=wd(r,rb());if(n)return n;let o=XE(r),s=o?nb(o):null;if(s)return s;let i=o??eb(r)??r;return kd(e,i)}function ob(e,t){return t===e?e:`${e}/${t}`}function T$(e,t){if(!e.isSubmodule||!e.parentRepoPath)return null;let r=ze.default.relative(e.parentRepoPath,t);return!r||r.startsWith("..")||ze.default.isAbsolute(r)?null:r.split(ze.default.sep).join("/")}function sb(e,t=process.platform){if(!e||e.trim()===""){let c=k$(e,t);return{primary:c,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[c],keySource:"path"}}let r=$t(e,t),n=XE(r),o=P$(e,r,n),s=n?nb(n):null,i=s?JE(o,s,"git-remote"):o,a=wd(r,rb());return a?JE(i,a,"environment"):i}function JE(e,t,r){return{primary:t,parent:null,isWorktree:e.isWorktree,isSubmodule:e.isSubmodule,allProjects:[...e.allProjects.filter(n=>n!==t),t],keySource:r}}function P$(e,t,r){let n=r?null:eb(t),o=kd(e,r??n??t),s=r??t,i=HE(s);if((i.isWorktree||i.isSubmodule)&&i.parentProjectName){let a=i.parentProjectName,c,u;return i.isSubmodule?(c=`${a}/${T$(i,s)??o}`,u=o!==a?[o]:[]):(c=ob(a,o),u=c===a?[`${a}/${o}`]:[]),{primary:c,parent:a,isWorktree:i.isWorktree,isSubmodule:i.isSubmodule,allProjects:[...new Set([a,...u,c])].filter(l=>l!==c).concat(c),keySource:"path"}}if(n&&ze.default.resolve(n)!==ze.default.resolve(t)){let a=kd(e,t);if(a!==o&&a!==Pd)return{primary:o,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[a,o],keySource:"path"}}return{primary:o,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[o],keySource:"path"}}qe();var ib=Ot(pe.POWERSHELL_COMMAND);function x$(e){return e===void 0?ib:Math.max(1,Math.min(ib,e))}var ZW=Fe.dataDir(),Dr=Fe.workerPid(),cb="Bun runtime not found \u2014 install from https://bun.sh and ensure it is on PATH, under ~/.bun/bin, or set BUN / BUN_PATH / BUN_INSTALL. The worker daemon requires Bun because it uses bun:sqlite.";function R$(e){try{return(0,Pe.realpathSync)(e)}catch{return null}}function xd(e){return e?/(^|[\\/])bun(\.exe)?$/i.test(e.trim()):!1}function A$(e,t){let r=t==="win32"?"where.exe":"which",n=[e],o;try{o=(0,Fo.execFileSync)(r,n,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(i){return i instanceof Error?g.debug("SYSTEM",`Binary lookup failed for ${e}`,{command:r,args:n},i):g.debug("SYSTEM",`Binary lookup failed for ${e}`,{command:r,args:n},new Error(String(i))),null}return o.split(/\r?\n/).map(i=>i.trim()).find(i=>i.length>0)||null}var Rd;function Md(e={}){let t=Object.keys(e).length===0;if(t&&Rd!==void 0)return Rd;let r=M$(e);return t&&r!==null&&(Rd=r),r}function ab(e,t){let r=e?.trim();return r?t==="win32"?[Ye.default.join(r,"bin","bun.exe"),Ye.default.join(r,"bin","bun"),Ye.default.join(r,"bun.exe")]:[Ye.default.join(r,"bin","bun"),Ye.default.join(r,"bun")]:[]}function M$(e){let t=e.platform??process.platform,r=e.execPath??process.execPath;if(xd(r))return r;let n=e.env??process.env,o=e.homeDirectory??(0,Ad.homedir)(),s=e.pathExists??Pe.existsSync,i=e.lookupInPath??A$,a=e.realpath??R$,c=t==="win32"?[n.BUN,n.BUN_PATH,...ab(n.BUN_INSTALL,t),Ye.default.join(o,".bun","bin","bun.exe"),Ye.default.join(o,".bun","bin","bun"),n.USERPROFILE?Ye.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?Ye.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?Ye.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0,n.npm_config_prefix?Ye.default.join(n.npm_config_prefix,"bun.exe"):void 0]:[n.BUN,n.BUN_PATH,...ab(n.BUN_INSTALL,t),Ye.default.join(o,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun",n.npm_config_prefix?Ye.default.join(n.npm_config_prefix,"bin","bun"):void 0];for(let d of c){let f=d?.trim();if(f&&(xd(f)&&s(f)||f.toLowerCase()==="bun"))return f}let u=i("bun",t)?.trim();if(!u||!xd(u))return null;let l=a(u)??u;return s(l)?l:null}function ub(){if(!(0,Pe.existsSync)(Dr))return null;try{return JSON.parse((0,Pe.readFileSync)(Dr,"utf-8"))}catch(e){return e instanceof Error?g.warn("SYSTEM","Failed to parse PID file",{path:Dr},e):g.warn("SYSTEM","Failed to parse PID file",{path:Dr},new Error(String(e))),null}}function lb(e){hd(Dr,e,!0)}function dr(e){return process.platform==="win32"?Math.round(e*2):e}function Od(){let e=Fe.dataDir();return(0,Pe.mkdirSync)(e,{recursive:!0}),e}function O$(e,t,r=Od()){let n=o=>o.replace(/'/g,"''");return`Start-Process -FilePath '${n(e)}' -ArgumentList @('"${n(t)}"','--daemon') -WorkingDirectory '${n(r)}' -WindowStyle Hidden`}var C$=5e3,$$=8;function I$(e,t,r){return e?.code!=="ETIMEDOUT"?!1:t<r/2}function db(e,t=dr(C$)){let r=Md();if(!r)return;let n=()=>{let a=Date.now();try{return{result:(0,Fo.spawnSync)(r,[e,"status"],{encoding:"utf-8",timeout:t,windowsHide:!0,env:ur({...process.env})}),elapsedMs:Date.now()-a}}catch(c){let u=c instanceof Error?c:new Error(String(c));g.debug("SYSTEM","Worker boot probe could not be launched",{scriptPath:e},u);return}},o=n();if(o===void 0||I$(o.result.error,o.elapsedMs,t)&&(g.debug("SYSTEM","Worker boot probe timed out before it could run \u2014 retrying once",{scriptPath:e,elapsedMs:o.elapsedMs,timeoutMs:t}),o=n(),o===void 0))return;let{result:s}=o;if(s.error||s.status===0)return;let i=`${s.stdout??""}${s.stderr??""}`.trim();if(i)return i.split(/\r?\n/).slice(0,$$).join(`
86
86
  `)}function D$(e=process.env){let t=e.SystemRoot||e.SYSTEMROOT;return t?`${t}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`:"powershell.exe"}function N$(e,t,r=Od()){return["-NoProfile","-WindowStyle","Hidden","-EncodedCommand",Buffer.from(O$(e,t,r),"utf16le").toString("base64")]}function fb(e,t,r,n=process.platform,o){if(n==="win32"){let l=D$(r),d=N$(e,t),f=x$(o);try{let p=(0,Fo.spawnSync)(l,d,{stdio:"ignore",windowsHide:!0,env:r,timeout:f,killSignal:"SIGTERM"});if(p.error)throw p.error;if(p.signal)throw new Error(`powershell Start-Process killed by signal=${p.signal} after ${f}ms`);if(p.status!==0)throw new Error(`powershell Start-Process exited ${p.status??"null"}`);return 0}catch(p){let m=p instanceof Error?p:new Error(String(p));g.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:e,powershell:l},m);return}}let s="/usr/bin/setsid",i=(0,Pe.existsSync)(s),a=i?s:e,u=cd(a,i?[e,t,"--daemon"]:[t,"--daemon"],{detached:!0,stdio:"ignore",cwd:Od(),env:r});if(u.on("error",l=>{g.error("SYSTEM",cb,{runtimePath:e,execPath:a},l)}),u.pid!==void 0)return u.unref(),u.pid}function pb(e,t,r={}){_d().assertCanSpawn("worker daemon");let n=ur({...process.env,CLAUDE_MEM_WORKER_PORT:String(t),...r}),o=Md();if(!o){g.error("SYSTEM",cb);return}return fb(o,e,n)}function mb(){try{if(!(0,Pe.existsSync)(Dr))return;let e=new Date;(0,Pe.utimesSync)(Dr,e,e)}catch{}}function qo(e={}){return ea({logAlive:!1,removeStale:e.removeStale})}var gb=Je(require("net"),1);V();qe();function hb(e){let t=e?.code;return t==="EACCES"||t==="EADDRNOTAVAIL"}var aa="Set CLAUDE_MEM_WORKER_PORT to a port between 1024 and 65535 and CLAUDE_MEM_WORKER_HOST to an address of this machine (127.0.0.1 by default) in claude-mem settings";function Cd(){return Te.loadFromFile(hr).CLAUDE_MEM_WORKER_HOST}function _b(e){return e.startsWith("[")&&e.endsWith("]")?e:e.includes(":")?`[${e}]`:e}var Zo=5e3;async function L$(e,t,r="GET",n=Zo){let o=await fetch(`http://${_b(Cd())}:${e}${t}`,{method:r,signal:AbortSignal.timeout(Math.max(1,n))}),s="";try{s=await o.text()}catch{}return{ok:o.ok,statusCode:o.status,body:s}}async function $d(e,t=Zo){let r=Date.now()+t;if(process.platform==="win32")try{let o=await fetch(`http://${_b(Cd())}:${e}/api/health`,{signal:AbortSignal.timeout(Math.max(1,r-Date.now()))});if(o.ok)return!0;g.debug("SYSTEM","Windows health check returned non-ok; falling through to socket probe",{port:e,status:o.status})}catch(o){o instanceof Error?g.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:e,message:o.message}):g.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:e,error:String(o)})}let n=await yb(e,Math.max(1,r-Date.now()));return n==="occupied"||n==="indeterminate"}async function yb(e,t=Zo){return(await Id(e,t)).occupancy}function Id(e,t=Zo){return t<=0?Promise.resolve({occupancy:"indeterminate"}):new Promise(r=>{let n=!1,o=!1,s=!1,i;try{i=gb.default.createServer()}catch{r({occupancy:"indeterminate"});return}let a=l=>{if(s){l?.();return}s=!0;try{i.close(l)}catch(d){l?.(d instanceof Error?d:new Error(String(d)))}},c=setTimeout(()=>{if(o)a();else try{i.close()}catch{}u({occupancy:"indeterminate"})},t),u=l=>{n||(n=!0,clearTimeout(c),r(l))};i.once("error",l=>{if(o)a();else try{i.close()}catch{}l.code==="EADDRINUSE"?u({occupancy:"occupied"}):hb(l)?u({occupancy:"unbindable",bindErrorCode:l.code}):u({occupancy:"indeterminate"})}),i.once("listening",()=>{if(o=!0,n){a();return}try{a(l=>u({occupancy:l?"indeterminate":"free"}))}catch{u({occupancy:"indeterminate"})}});try{i.listen(e,Cd())}catch{try{i.close()}catch{}u({occupancy:"indeterminate"})}})}async function Sb(e,t,r,n){let o=Date.now()+r;for(;Date.now()<o;){try{let i=o-Date.now();if((await L$(e,t,"GET",Math.min(Zo,i))).ok)return!0}catch(i){i instanceof Error?g.debug("SYSTEM",n,{},i):g.debug("SYSTEM",n,{error:String(i)})}let s=Math.min(500,o-Date.now());s>0&&await new Promise(i=>setTimeout(i,s))}return!1}function fr(e,t=3e4){return Sb(e,"/api/health",t,"Service not ready yet, will retry")}function wn(e,t=3e4){return Sb(e,"/api/readiness",t,"Worker not ready yet, will retry")}V();var ca=require("path"),$e=require("fs");qe();V();var bb=9e4,c2=bb/3;function wb(){return(0,ca.join)(It(),"spawn.lock")}function Eb(e){try{let t=JSON.parse((0,$e.readFileSync)(e,"utf-8"));return typeof t.pid!="number"||!Number.isInteger(t.pid)||t.pid<=0?null:t.pid}catch{return null}}function z$(e){if(e===null)return null;try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}function Dd(){let e=wb(),t=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return(0,$e.mkdirSync)((0,ca.dirname)(e),{recursive:!0}),(0,$e.writeFileSync)(e,t,{flag:"wx"}),!0}catch(n){let o=n instanceof Error?n:new Error(String(n)),s=o.code;if(s!=="EEXIST")return g.warn("SYSTEM","Spawn lock write failed for a non-contention reason; failing open (spawning unlocked)",{lockPath:e,code:s},o),!0;if(r>0)return!1;let i;try{i=(0,$e.statSync)(e).mtimeMs}catch{continue}let a=Eb(e),c=null;if(a===null)try{c=(0,$e.readFileSync)(e,"utf-8")}catch{continue}if(Date.now()-i<=bb&&z$(a)!==!1)return!1;let l;try{l=(0,$e.statSync)(e).mtimeMs}catch{continue}if(l!==i)return!1;if(a!==null){if(Eb(e)!==a)return!1}else try{if((0,$e.readFileSync)(e,"utf-8")!==c)return!1}catch{continue}try{(0,$e.unlinkSync)(e)}catch{return!1}}return!1}function Nd(){let e=wb();try{if(JSON.parse((0,$e.readFileSync)(e,"utf-8")).pid!==process.pid)return;(0,$e.unlinkSync)(e)}catch{}}var Tb=require("node:child_process"),Pb=require("node:util");V();qe();var ua=(0,Pb.promisify)(Tb.execFile),U$=/^(uv|uvx|python|chroma-mcp)(\.exe)?$/i;function vb(e){return U$.test(e.trim())}function j$(e,t){if(!e)return!1;let r=e.toLowerCase().replace(/\\/g,"/"),n=r.indexOf("--data-dir");if(n<0)return!1;let o=r.slice(n+10).trim();if(o.startsWith('"')){let i=o.indexOf('"',1);o=i<0?o.slice(1):o.slice(1,i)}let s=t.toLowerCase().replace(/\\/g,"/");return o===s||o.startsWith(s)&&o[s.length]==="/"}function la(e,t){return t===void 0?e:Math.max(1,Math.min(e,t))}async function F$(e){try{let t=await ua("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name,CommandLine,@{Name='StartToken';Expression={$_.CreationDate.ToString('yyyyMMddHHmmss.ffffff')}} | ConvertTo-Json -Compress"],{timeout:la(3e4,e),windowsHide:!0,maxBuffer:33554432}),r=JSON.parse(t.stdout),n=Array.isArray(r)?r:r===null?[]:[r],o=[];for(let s of n){let i=typeof s.Name=="string"?s.Name.trim():"";if(!i)continue;let a=typeof s.ProcessId=="number"?s.ProcessId:Number.parseInt(String(s.ProcessId),10),c=typeof s.ParentProcessId=="number"?s.ParentProcessId:Number.parseInt(String(s.ParentProcessId),10);!Number.isInteger(a)||!Number.isInteger(c)||o.push({pid:a,ppid:c,name:i,cmdline:typeof s.CommandLine=="string"?s.CommandLine:null,startToken:typeof s.StartToken=="string"&&s.StartToken.length>0?s.StartToken:null})}return o}catch(t){return g.warn("PROCESS","Cannot enumerate the Windows process table with names \u2014 ghost-port reclaim disabled",{error:t instanceof Error?t.message:String(t)}),null}}async function q$(e,t){try{let r=await ua("netstat",["-ano"],{timeout:la(15e3,t),windowsHide:!0,maxBuffer:16777216});return B$(r.stdout,e)}catch(r){return g.warn("PROCESS","netstat failed \u2014 ghost-port reclaim disabled for this attempt",{port:e,error:r instanceof Error?r.message:String(r)}),null}}async function Z$(e,t){try{let r=await ua("lsof",["-nP",`-iTCP:${e}`,"-sTCP:LISTEN","-t"],{timeout:la(1e4,t),maxBuffer:1048576});return W$(r.stdout)}catch(r){let n=r;return n.code===1&&typeof n.stdout=="string"&&n.stdout.trim()===""?[]:(g.warn("PROCESS","lsof failed \u2014 cannot verify the worker port owner",{port:e,error:r instanceof Error?r.message:String(r)}),null)}}function W$(e){let t=new Set;for(let r of e.split(/\r?\n/)){let n=Number.parseInt(r.trim(),10);Number.isInteger(n)&&n>0&&t.add(n)}return[...t]}async function H$(e,t){try{let n=(await ua("ps",["-p",String(e),"-o","command="],{timeout:la(5e3,t)})).stdout.trim();return n.length>0?n:null}catch{return null}}function B$(e,t){let r=new Set,n=`:${t}`;for(let o of e.split(/\r?\n/)){let s=o.trim();if(!/^TCP\b/i.test(s))continue;let i=s.split(/\s+/);if(!i[1]?.endsWith(n)||i[3]!=="LISTENING")continue;let c=Number.parseInt(i[4]??"",10);Number.isInteger(c)&&c>0&&r.add(c)}return[...r]}var K$=/worker-service/i,xb=1500,Rb=1e3,Ld=5500,kb=2*xb+Rb+Ld;async function G$(e,t){let r=t.readOwnedWorker();if(r===null||r.port!==e)return null;let n=(u,l={})=>(g.info("PROCESS","Wedged-worker reclaim declined",{port:e,pid:r.pid,reason:u,...l}),{reclaimed:!1,reason:u,killedPids:[]}),o=(t.now()-Date.parse(r.startedAt))/1e3;if(!Number.isFinite(o)||o<t.minOwnerAgeSeconds)return n("owner-booting",{ageSeconds:o,minOwnerAgeSeconds:t.minOwnerAgeSeconds});for(let u=0;u<2;u++)if(u>0&&await t.sleep(Rb),await t.probeHealth(e))return n("owner-responding");let s=await t.listOwners(e);if(s===null)return n("netstat-unreadable");if(!s.includes(r.pid))return g.info("PROCESS","Wedged-worker reclaim: our worker does not own the port \u2014 deferring to the ghost-listener check",{port:e,pid:r.pid,listeners:s}),null;let i=await t.readIdentity(r.pid),a=r.startToken!==void 0&&i.startToken!==null&&i.startToken!==r.startToken;if(a||i.cmdline===null||!K$.test(i.cmdline))return n("owner-identity-mismatch",{tokenMismatch:a,hasCmdline:i.cmdline!==null});if(!t.hasKillBudget())return n("out-of-budget");g.warn("PROCESS","Reclaiming wedged worker: past its boot grace, silent on two health probes, and still holding the port",{port:e,pid:r.pid,ageSeconds:Math.round(o)});try{await t.killTree(r.pid,{expectedStartToken:i.startToken??r.startToken??void 0,signalMode:"graceful"})}catch(u){return g.error("PROCESS","Wedged-worker reclaim tree-kill failed",{port:e,pid:r.pid},u instanceof Error?u:new Error(String(u))),{reclaimed:!1,reason:"kill-failed",killedPids:[]}}let c=await t.listOwners(e);return c!==null&&c.length===0?(g.info("PROCESS","Wedged worker reclaimed \u2014 port is free again",{port:e,killedPids:[r.pid]}),{reclaimed:!0,killedPids:[r.pid]}):(g.warn("PROCESS","Wedged-worker reclaim killed the worker but the port is still bound",{port:e,pid:r.pid,stillOwnedBy:c}),{reclaimed:!1,reason:"still-bound",killedPids:[r.pid]})}async function V$(e,t,r,n){let o=Ct(e),s=t?(await r(n))?.find(i=>i.pid===e)?.cmdline??null:await H$(e,n);return vt(e,o)?{startToken:o,cmdline:s}:{startToken:null,cmdline:null}}async function zd(e,t={}){let r=t.isWin32??(()=>process.platform==="win32"),n=t.now??Date.now,o=t.deadlineAt??null,s=R=>o!==null&&o-n()<R,i=()=>o===null?void 0:Math.max(1,o-n());if(s(kb))return g.info("PROCESS","Port reclaim skipped: not enough of the hook budget is left to finish one",{port:e,remainingMs:i(),neededMs:kb}),{reclaimed:!1,reason:"out-of-budget",killedPids:[]};let a=t.listOwners??((R,F)=>r()?q$(R,F):Z$(R,F)),c=R=>a(R,i()),u=t.readTable??F$,l=()=>u(i()),d=t.killTree??((R,F)=>kt(R,F)),f=t.dataDir??(()=>le),p=t.readIdentity??((R,F)=>V$(R,r(),u,F)),m=await G$(e,{listOwners:c,killTree:d,readOwnedWorker:t.readOwnedWorker??Xi,probeHealth:t.probeHealth??(R=>fr(R,xb)),readIdentity:R=>p(R,i()),minOwnerAgeSeconds:t.minOwnerAgeSeconds??aE(),now:n,sleep:t.sleep??(R=>new Promise(F=>setTimeout(F,R))),hasKillBudget:()=>!s(Ld)});if(m!==null)return m;if(!r())return{reclaimed:!1,reason:"not-supported",killedPids:[]};let h=await c(e);if(h===null)return{reclaimed:!1,reason:"netstat-unreadable",killedPids:[]};if(h.length===0)return{reclaimed:!1,reason:"no-listener",killedPids:[]};let _=await l();if(_===null)return{reclaimed:!1,reason:"table-unreadable",killedPids:[]};if(h.filter(R=>ge(R)).length>0)return{reclaimed:!1,reason:"owner-alive",killedPids:[]};let b=new Map;for(let R of _){let F=b.get(R.ppid);F?F.push(R):b.set(R.ppid,[R])}let w=new Map,A=new Set,k=R=>{for(let F of b.get(R)??[])A.has(F.pid)||(A.add(F.pid),k(F.pid),vb(F.name)&&w.set(F.pid,F))};for(let R of h)k(R);let D=f();if(D)for(let R of _)w.has(R.pid)||vb(R.name)&&j$(R.cmdline,D)&&w.set(R.pid,R);if(w.size===0)return g.info("PROCESS","Ghost listener owner is dead but no chroma-sidecar descendants found",{port:e,deadOwners:h,processTableRows:_.length,dataDir:D??"(unresolved)"}),{reclaimed:!1,reason:"no-chroma-descendants",killedPids:[]};g.warn("PROCESS","Reclaiming ghost listener: killing dead worker's surviving chroma sidecar chain",{port:e,deadOwners:h,targets:[...w.values()].map(R=>({pid:R.pid,name:R.name}))});let $=[];for(let R of w.values()){if(s(Ld))return g.info("PROCESS","Ghost-listener reclaim stopped before a kill: the hook budget is spent",{port:e,killedPids:$}),{reclaimed:!1,reason:"out-of-budget",killedPids:$};try{await d(R.pid,{expectedStartToken:R.startToken,signalMode:"immediate"}),$.push(R.pid)}catch(F){return g.error("PROCESS","Ghost-port reclaim tree-kill failed",{port:e,pid:R.pid},F instanceof Error?F:new Error(String(F))),{reclaimed:!1,reason:"kill-failed",killedPids:$}}}let Re=await c(e);return Re!==null&&Re.length===0?(g.info("PROCESS","Ghost listener reclaimed \u2014 port is free again",{port:e,killedPids:$}),{reclaimed:!0,killedPids:$}):(g.warn("PROCESS","Ghost-port reclaim killed the sidecar chain but the port is still bound",{port:e,killedPids:$,stillOwnedBy:Re}),{reclaimed:!1,reason:"still-bound",killedPids:$})}Bt();var vn=require("fs"),Mb=require("module"),pr=Je(require("path"),1),Y$=["zod/v3","zod/v4","zod/v4-mini"];function Ab(e){try{return(0,vn.realpathSync)(e)}catch{return e}}function J$(e,t){let r=pr.default.relative(t,e);return r!==""&&!r.startsWith("..")&&!pr.default.isAbsolute(r)}function Ob(e){let t;try{let o=JSON.parse((0,vn.readFileSync)(pr.default.join(e,"package.json"),"utf-8"));t=Object.keys(o?.dependencies??{})}catch{return[]}if(t.length===0)return[];let r=pr.default.join(e,"node_modules"),n=t.filter(o=>!(0,vn.existsSync)(pr.default.join(r,...o.split("/"),"package.json")));if(t.includes("zod")&&!n.includes("zod")){let o=(0,Mb.createRequire)(pr.default.join(r,"noop.js")),s=Ab(pr.default.join(r,"zod"));for(let i of Y$)try{let a=o.resolve(i,{paths:[r]});J$(Ab(a),s)||n.push(i)}catch{n.push(i)}}return n}function Ib(e,t,r){let n=process.env[e];if(n){let o=parseInt(n,10);if(Number.isFinite(o)&&o>=r.min&&o<=r.max)return o;g.warn("SYSTEM",`Invalid ${e}, using default`,{value:n,min:r.min,max:r.max})}return t}var W2=Ib("CLAUDE_MEM_HEALTH_TIMEOUT_MS",Ot(pe.HEALTH_CHECK),{min:500,max:3e5}),H2=Ib("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",Ot(pe.HOOK_READINESS_WAIT),{min:0,max:3e5});var X$={min:500,max:3e5},B2={min:500,max:pe.SESSION_INIT_REQUEST_MAX};function Db(e=process.env){let t=e.CLAUDE_MEM_FETCH_VERBOSE;if(t===void 0)return!1;let r=t.trim().toLowerCase();return r==="1"||r==="true"||r==="on"||r==="yes"}function Q$(e){return Db()?{...e,verbose:!0}:e}function eI(e){let t={},r=e;for(let n=0;r&&n<4;n++){let o=n===0?"error":`cause${n}`;if(r instanceof Error){let s=r;t[o]={name:r.name,message:r.message,...s.code!==void 0?{code:s.code}:{}},r=r.cause;continue}t[o]=String(r);break}return t}function tI(e,t,r){let n=typeof t.method=="string"?t.method:"GET",o=eI(r),s=JSON.stringify(o);g.warn("SYSTEM","Worker IPC fetch failed",{url:e,method:n},s),Ht(`[claude-mem] fetch verbose: ${n} ${e} ${s}
87
87
  `)}async function Ud(e,t={}){let r=Q$(t);try{return await fetch(e,r)}catch(n){throw Db()&&tI(e,t,n),n}}async function jd(e,t={},r){try{return await Ud(e,{...t,signal:AbortSignal.timeout(r)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new Error(`Request timed out after ${r}ms`):n}}function rI(e,t){let r=new AbortController,n=null,o=null,s=null,i=!1,a=()=>{o!==null&&(clearTimeout(o),o=null)},c=()=>{i=!0,a(),s!==null&&(clearTimeout(s),s=null)},u=d=>{i||(n=d,c(),r.abort(d))},l=()=>{i||(a(),o=setTimeout(()=>u(new Error(`Request timed out after ${e.idleTimeoutMs}ms idle`)),e.idleTimeoutMs))};if(e.absoluteCapMs!==void 0&&e.absoluteCapMs>0){let d=e.absoluteCapMs;s=setTimeout(()=>u(new Error(`Request timed out after ${d}ms`)),d)}return l(),{signal:t?AbortSignal.any([t,r.signal]):r.signal,touch:l,pause:a,dispose:c,translate:d=>n??d}}async function Fd(e,t,r){let n=rI(r,t.signal),o;try{o=await Ud(e,{...t,signal:n.signal})}catch(u){throw n.dispose(),n.translate(u)}n.touch();let s=o.body,i=s?s.getReader():null,a=!1;async function*c(){if(!i){a=!0,n.dispose();return}try{for(;;){n.touch();let u;try{u=await i.read()}catch(l){throw a=!0,n.translate(l)}if(u.done){a=!0;return}n.pause(),r.onChunk?.(u.value),yield u.value}}finally{n.dispose(),a||await i.cancel()}}return{status:o.status,statusText:o.statusText,ok:o.ok,headers:o.headers,chunks:c(),cancel:async()=>{n.dispose(),i&&!a&&(a=!0,await i.cancel())}}}async function nI(e,t,r){let n=await Fd(e,t,r),o=new TextDecoder,s="";for await(let i of n.chunks)s+=o.decode(i,{stream:!0});return s+=o.decode(),{status:n.status,statusText:n.statusText,ok:n.ok,headers:n.headers,text:s}}var da=null,fa=null,pa=null,ma=null;function oI(){return me.default.join(Te.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function qd(){return pa!==null||(pa=Te.loadFromFile(oI())),pa}function Cb(e,t){if(!e)return null;let r=parseInt(e,10);return Number.isFinite(r)&&r>=t.min&&r<=t.max?r:null}function sI(e,t,r){let n=process.env[e];if(n!==void 0){let i=Cb(n,r);return i!==null?i:(g.warn("SYSTEM",`Invalid ${e}, using default`,{value:n,min:r.min,max:r.max}),t)}let o=qd()[e],s=Cb(o,r);return s!==null?s:(g.warn("SYSTEM",`Invalid ${e} in settings.json, using default`,{value:o,min:r.min,max:r.max}),t)}function Zd(){if(da!==null)return da;let e=qd();return da=parseInt(e.CLAUDE_MEM_WORKER_PORT,10),da}function iI(){return fa!==null||(fa=qd().CLAUDE_MEM_WORKER_HOST),fa}function aI(){return ma!==null||(ma=sI("CLAUDE_MEM_API_TIMEOUT_MS",Ot(pe.API_REQUEST),X$)),ma}function cI(e){return e.startsWith("[")&&e.endsWith("]")?e:e.includes(":")?`[${e}]`:e}function Wd(e){return`http://${cI(iI())}:${Zd()}${e}`}function ha(e,t={}){let r=t.method??"GET",n=Wd(e),o={method:r};if(t.headers&&(o.headers=t.headers),t.body&&(o.body=t.body),t.idleTimeoutMs!==void 0&&t.idleTimeoutMs>0)return nI(n,o,{idleTimeoutMs:t.idleTimeoutMs,absoluteCapMs:t.timeoutMs}).then(i=>new Response(i.text.length>0?i.text:null,{status:i.status,statusText:i.statusText,headers:i.headers}));let s=t.timeoutMs??aI();return s>0?jd(n,o,s):Ud(n,o)}function Nb(e){let t=(0,Ue.existsSync)(me.default.join(e,"plugin","scripts"))?me.default.join(e,"plugin"):e;return me.default.join(t,"scripts","worker-service.cjs")}function uI(e,t){let r=d=>{let f=d.split("-")[0].split(".");return[parseInt(f[0],10)||0,parseInt(f[1],10)||0,parseInt(f[2],10)||0]},[n,o,s]=r(e),[i,a,c]=r(t);if(i!==n)return i-n;if(a!==o)return a-o;if(c!==s)return c-s;let u=e.includes("-")?1:0,l=t.includes("-")?1:0;return u!==l?u-l:e<t?1:e>t?-1:0}function lI(e=me.default.join(me.default.dirname(me.default.dirname(es)),"cache","thedotmack","claude-mem")){try{return(0,Ue.readdirSync)(e).filter(t=>/^\d/.test(t)).map(t=>me.default.join(e,t)).filter(t=>{try{if(!(0,Ue.statSync)(t).isDirectory())return!1}catch{return!1}return!(0,Ue.existsSync)(me.default.join(t,".orphaned_at"))}).map(t=>({scriptPath:Nb(t),version:me.default.basename(t)}))}catch{return[]}}function $b(e){try{let t=JSON.parse((0,Ue.readFileSync)(e,"utf-8"));return typeof t.version=="string"?t.version:null}catch(t){let r=t.code;return r!=="ENOENT"&&g.debug("SYSTEM","Could not read package version for worker resolution",{packageJsonPath:e,code:r}),null}}function dI(){return{cacheRoot:me.default.join(me.default.dirname(me.default.dirname(es)),"cache","thedotmack","claude-mem"),marketplaceRoot:es,cwd:process.cwd()}}function fI(e=dI()){let t=process.env.CLAUDE_MEM_WORKER_SCRIPT_PATH?.trim();if(t){if((0,Ue.existsSync)(t))return{scriptPath:t,version:null};g.debug("SYSTEM","Ignoring missing CLAUDE_MEM_WORKER_SCRIPT_PATH override",{override:t})}let r=[...lI(e.cacheRoot),{scriptPath:Nb(me.default.join(e.marketplaceRoot,"plugin")),version:$b(me.default.join(e.marketplaceRoot,"package.json"))},{scriptPath:me.default.join(e.cwd,"plugin","scripts","worker-service.cjs"),version:$b(me.default.join(e.cwd,"package.json"))}];return hI(r)}function pI(e){return me.default.dirname(me.default.dirname(e))}function mI(e){return Ob(pI(e.scriptPath)).length===0}function hI(e,t=mI){let r=e.filter(n=>(0,Ue.existsSync)(n.scriptPath));return r.length===0?null:(r.sort((n,o)=>n.version===null&&o.version===null?0:n.version===null?1:o.version===null?-1:uI(n.version,o.version)),r.find(t)??r[0])}function Lb(){return fI()?.scriptPath??null}var gI=1e3;var _I=5e3,K2=_I+gI;var Nr=Je(require("path"),1),_e=require("fs");V();var jb=120*1e3;function Hd(){return Nr.default.join(Te.get("CLAUDE_MEM_DATA_DIR"),".worker-start-attempted")}function yI(){if(process.platform!=="win32")return null;let e=Hd();if(!(0,_e.existsSync)(e))return null;try{let t=(0,_e.statSync)(e).mtimeMs;return Date.now()-t>=jb?null:(0,_e.readFileSync)(e,"utf-8")}catch(t){return t instanceof Error?g.debug("SYSTEM","Could not read worker spawn cooldown marker",{},t):g.debug("SYSTEM","Could not read worker spawn cooldown marker",{error:String(t)}),null}}function zb(e){if(process.platform==="win32")try{let t=Hd();(0,_e.mkdirSync)(Nr.default.dirname(t),{recursive:!0}),(0,_e.writeFileSync)(t,e,"utf-8")}catch{}}function Wo(){if(process.platform==="win32")try{let e=Hd();(0,_e.existsSync)(e)&&(0,_e.unlinkSync)(e)}catch{}}async function Ub(e,t,r,n=r?"boot_crash":"unreachable_after_boot"){let o=n==="port_unbindable",s=[o?`[worker-spawner] worker port ${e} cannot be bound, so no worker was spawned`:`[worker-spawner] worker is dead and unreachable on port ${e} after boot \u2014 issue #3557`,` spawned pid: ${t??"n/a"}`,` platform: ${process.platform}`,` timestamp: ${new Date().toISOString()}`,...r?[o?" bind failure:":" boot failure (reproduced):",...r.split(`
@@ -229,7 +229,7 @@ ${p}`}let a=s.lineStart;for(let u=s.lineStart-1;u>=0;u--){let l=i[u].trim();if(l
229
229
  ${c}`}V();var LI=new Set([".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".pyw",".go",".rs",".rb",".java",".cs",".cpp",".cc",".cxx",".c",".h",".hpp",".hh",".swift",".kt",".kts",".php",".vue",".svelte",".lua",".scala",".sc",".sh",".bash",".zsh",".hs",".zig",".css",".scss",".toml",".yml",".yaml",".sql",".md",".mdx"]),zI=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),UI=512*1024;async function*ow(e,t,r=20){if(r<=0)return;let n;try{n=await(0,Tn.readdir)(e,{withFileTypes:!0})}catch(o){g.debug("WORKER",`walkDir: failed to read directory ${e}`,void 0,o instanceof Error?o:void 0);return}for(let o of n){if(o.name.startsWith(".")&&o.name!=="."||zI.has(o.name))continue;let s=(0,Ho.join)(e,o.name);if(o.isDirectory())yield*ow(s,t,r-1);else if(o.isFile()){let i=o.name.slice(o.name.lastIndexOf("."));LI.has(i)&&(yield s)}}}async function jI(e){try{let t=await(0,Tn.stat)(e);if(t.size>UI||t.size===0)return null;let r=await(0,Tn.readFile)(e,"utf-8");return r.slice(0,1e3).includes("\0")?null:r}catch(t){return g.debug("WORKER",`safeReadFile: failed to read ${e}`,void 0,t instanceof Error?t:void 0),null}}async function sw(e,t,r={}){let n=r.maxResults||20,o=t.toLowerCase(),s=o.split(/[\s_\-./]+/).filter(h=>h.length>0),i=[];for await(let h of ow(e,e,20)){if(r.filePattern&&!(0,Ho.relative)(e,h).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let _=await jI(h);_&&i.push({absolutePath:h,relativePath:(0,Ho.relative)(e,h),content:_})}let a=tw(i),c=[],u=[],l=0;for(let[h,_]of a){l+=FI(_);let b=ya(h.toLowerCase(),s)>0,w=[],A=(k,D)=>{for(let $ of k){let Re=0,R="",F=ya($.name.toLowerCase(),s);F>0&&(Re+=F*3,R="name match"),$.signature.toLowerCase().includes(o)&&(Re+=2,R=R?`${R} + signature`:"signature match"),$.jsdoc&&$.jsdoc.toLowerCase().includes(o)&&(Re+=1,R=R?`${R} + jsdoc`:"jsdoc match"),Re>0&&(b=!0,w.push({filePath:h,symbolName:D?`${D}.${$.name}`:$.name,kind:$.kind,signature:$.signature,jsdoc:$.jsdoc,lineStart:$.lineStart,lineEnd:$.lineEnd,matchReason:R})),$.children&&A($.children,$.name)}};A(_.symbols),b&&(c.push(_),u.push(...w))}u.sort((h,_)=>{let y=ya(h.symbolName.toLowerCase(),s);return ya(_.symbolName.toLowerCase(),s)-y});let d=u.slice(0,n),f=new Set(d.map(h=>h.filePath)),p=c.filter(h=>f.has(h.filePath)).slice(0,n),m=p.reduce((h,_)=>h+_.foldedTokenEstimate,0);return{foldedFiles:p,matchingSymbols:d,totalFilesScanned:i.length,totalSymbolsFound:l,tokenEstimate:m}}function ya(e,t){let r=0;for(let n of t)if(e===n)r+=10;else if(e.includes(n))r+=5;else{let o=0,s=0;for(let i of n){let a=e.indexOf(i,o);a!==-1&&(s++,o=a+1)}s===n.length&&(r+=1)}return r}function FI(e){let t=e.symbols.length;for(let r of e.symbols)r.children&&(t+=r.children.length);return t}function iw(e,t){let r=[];if(r.push(`\u{1F50D} Smart Search: "${t}"`),r.push(` Scanned ${e.totalFilesScanned} files, found ${e.totalSymbolsFound} symbols`),r.push(` ${e.matchingSymbols.length} matches across ${e.foldedFiles.length} files (~${e.tokenEstimate} tokens for folded view)`),r.push(""),e.matchingSymbols.length===0)return r.push(" No matching symbols found."),r.join(`
230
230
  `);r.push("\u2500\u2500 Matching Symbols \u2500\u2500"),r.push("");for(let n of e.matchingSymbols){if(r.push(` ${n.kind} ${n.symbolName} (${n.filePath}:${n.lineStart+1})`),r.push(` ${n.signature}`),n.jsdoc){let o=n.jsdoc.split(`
231
231
  `).find(s=>s.replace(/^[\s*/]+/,"").trim().length>0);o&&r.push(` \u{1F4AC} ${o.replace(/^[\s*/]+/,"").trim()}`)}r.push("")}r.push("\u2500\u2500 Folded File Views \u2500\u2500"),r.push("");for(let n of e.foldedFiles)r.push(kn(n)),r.push("");return r.push("\u2500\u2500 Actions \u2500\u2500"),r.push(" To see full implementation: use smart_unfold with file path and symbol name"),r.join(`
232
- `)}var Qd=require("node:fs/promises"),ef=require("node:os"),Lr=require("node:path");function qI(e){return e==="~"?(0,ef.homedir)():e.startsWith("~/")||e.startsWith("~\\")?(0,Lr.join)((0,ef.homedir)(),e.slice(2)):e}async function Sa(e,t=process.cwd()){if(typeof e!="string"||e.trim().length===0)throw new Error("file_path is required");let r=await(0,Qd.realpath)((0,Lr.resolve)(t)),n=(0,Lr.resolve)(r,qI(e.trim())),o;try{o=await(0,Qd.realpath)(n)}catch{o=n}if(o!==r&&!o.startsWith(r+Lr.sep))throw new Error(`Access denied: "${e}" resolves outside the workspace (${r}). MCP file tools can only read files within the current project.`);return o}var tf=require("node:fs/promises"),ka=require("node:fs"),mr=require("node:path"),_w=require("node:os"),yw=require("node:url");var aw="claude";function ZI(e){return e.trim().toLowerCase().replace(/\s+/g,"-")}function Ea(e){if(!e)return aw;let t=ZI(e);return t?t==="transcript"||t.includes("codex")?"codex":t.includes("cursor")?"cursor":t.includes("claude")?"claude":t.includes("kimi")?"kimi":t==="agy"||t==="antigravity"||t.startsWith("antigravity-")?"antigravity-cli":t:aw}var WI=Ot(pe.API_REQUEST),ft=class extends Error{kind;status;cause;constructor(t,r,n={}){super(r),this.name="ServerClientError",this.kind=t,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)}},wa=class{baseUrl;apiKey;timeoutMs;constructor(t){this.baseUrl=HI(t.serverBaseUrl),this.apiKey=t.apiKey,this.timeoutMs=t.timeoutMs??WI}async startSession(t,r={}){let n=this.buildStartSessionPayload(t);return this.request("POST","/v1/sessions/start",n,r)}async recordEvent(t){let r=this.buildEventPayload(t),n=t.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(t){if(!t.sessionId)throw new ft("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(t.sessionId)}/end`,{})}async addObservation(t){return this.request("POST","/v1/memories",this.buildAddObservationPayload(t))}async searchObservations(t){return this.request("POST","/v1/search",this.buildSearchPayload(t))}async contextObservations(t,r={}){let n={projectId:t.projectId};return t.query!==void 0&&(n.query=t.query),t.limit!==void 0&&(n.limit=t.limit),t.platformSource!==void 0&&(n.platformSource=ba(t.platformSource)),t.folderProjects&&t.folderProjects.length>0&&(n.folderProjects=t.folderProjects),t.excludeSubagents!==void 0&&(n.excludeSubagents=t.excludeSubagents),this.request("POST","/v1/context",n,r)}async getJobStatus(t){if(!t)throw new ft("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(t)}`)}buildAddObservationPayload(t){let r=t.content,n=t.kind??"manual",o=typeof t.metadata?.title=="string"?t.metadata.title:void 0;return{projectId:t.projectId,kind:n,content:r,...o?{title:o}:{},...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.platformSource!==void 0?{platformSource:t.platformSource}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}}}buildSearchPayload(t){return{projectId:t.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:ba(t.platformSource)}:{}}}buildStartSessionPayload(t){return{projectId:t.projectId,...t.externalSessionId!==void 0?{externalSessionId:t.externalSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.agentId!==void 0?{agentId:t.agentId}:{},...t.agentType!==void 0?{agentType:t.agentType}:{},...t.platformSource!==void 0?{platformSource:ba(t.platformSource)}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}}}buildEventPayload(t){return{projectId:t.projectId,sourceType:t.sourceType,eventType:t.eventType,occurredAtEpoch:t.occurredAtEpoch,...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.memorySessionId!==void 0?{memorySessionId:t.memorySessionId}:{},...t.platformSource!==void 0?{platformSource:ba(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{}}}async request(t,r,n,o={}){if(!this.apiKey||!this.apiKey.trim())throw new ft("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let s=`${this.baseUrl}${r}`,i={method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(i.body=JSON.stringify(n));let a,c=o.timeoutMs??this.timeoutMs;try{a=await jd(s,i,c)}catch(l){let d=l instanceof Error?l.message:String(l),f=/timed out|timeout/i.test(d);throw new ft(f?"timeout":"transport",`Server ${t} ${r} failed: ${d}`,{cause:l})}if(!a.ok){let l=await a.text().catch(()=>"");throw new ft("http_error",`Server ${t} ${r} returned ${a.status}: ${BI(l,200)}`,{status:a.status})}let u=await a.text();if(!u||u.length===0)return{};try{return JSON.parse(u)}catch(l){let d=l instanceof Error?l:new Error(String(l));throw new ft("invalid_response",`Server ${t} ${r} returned non-JSON response`,{cause:d})}}};function cw(e){return e instanceof ft}function HI(e){return e.replace(/\/+$/,"")}function ba(e){return typeof e=="string"?Ea(e):null}function BI(e,t){return e.length<=t?e:`${e.slice(0,t)}\u2026`}V();function va(){let t=(Bi().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return t==="server"||t==="server-beta"?"server":"worker"}function uw(){let e=Bi(),t=(...i)=>{for(let a of i){let c=(a??"").trim();if(c.length>0)return c}return""},r=t(e.CLAUDE_MEM_SERVER_URL,e.CLAUDE_MEM_SERVER_BETA_URL),n=t(e.CLAUDE_MEM_SERVER_API_KEY,e.CLAUDE_MEM_SERVER_BETA_API_KEY),o=t(e.CLAUDE_MEM_SERVER_PROJECT_ID,e.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!r)return g.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return g.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return g.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let s={serverBaseUrl:r,apiKey:n};return{runtime:"server",client:new wa(s),projectId:o,serverBaseUrl:r}}V();var lw=["observation_add","observation_record_event","observation_search","observation_context","observation_generation_status","memory_add","memory_search","memory_context"],KI=new Set(lw);function dw(e,t){return t==="server"?[...e]:(g.debug("SYSTEM","Filtering server-beta-only MCP tools from worker runtime advertisement",{runtime:t,hiddenToolCount:lw.length}),e.filter(r=>!KI.has(r.name)))}function fw(e,t){if(e.projects!==void 0||typeof e.project!="string")return e;let r=e.project.trim();return!r||r.toLowerCase()!==t.primary.toLowerCase()||t.allProjects.length<2?e:{...e,projects:t.allProjects.join(",")}}var GI=3e4,VI=15*6e4,YI={idleTimeoutMs:GI,absoluteCapMs:VI},JI=["result","error"];async function pw(e){let t=new TextDecoder,r="";for await(let n of e)r+=t.decode(n,{stream:!0});return r+t.decode()}async function mw(e,t,r=YI){let n=await Fd(Wd(e),{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream"},body:JSON.stringify(t)},{idleTimeoutMs:r.idleTimeoutMs,absoluteCapMs:r.absoluteCapMs});if(!n.ok)throw new Error(`Worker API error (${n.status}): ${await pw(n.chunks)}`);if(!(n.headers.get("content-type")??"").includes("text/event-stream"))return JSON.parse(await pw(n.chunks));for await(let s of od(n.chunks,{terminalEventNames:JI})){if(s.event==="result")return JSON.parse(s.data);if(s.event==="error"){let{status:i,...a}=JSON.parse(s.data);throw new Error(`Worker API error (${i}): ${JSON.stringify(a)}`)}}throw new Error(`Corpus stream for ${e} ended without a terminal event`)}var yD={},XI="13.30.0";console.log=(...e)=>{g.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:e})};var hw=null;function QI(){return hw??=sb(process.cwd()),hw}var Sw=!1,Ew=(()=>{if(typeof __CM_DIRNAME__<"u")return __CM_DIRNAME__;try{return(0,mr.dirname)((0,yw.fileURLToPath)(yD.url))}catch(e){return Sw=!0,g.warn("SYSTEM","mcp-server: failed to resolve module directory from import.meta.url, falling back to process.cwd()",void 0,e instanceof Error?e:new Error(String(e))),process.cwd()}})(),rf=Lb()??(0,mr.resolve)(Ew,"worker-service.cjs");function eD(){Sw&&((0,ka.existsSync)(rf)||g.error("SYSTEM","mcp-server: dirname resolution failed (both __dirname and import.meta.url are unavailable). Fell back to process.cwd() and the resolved WORKER_SCRIPT_PATH does not exist. This is the actual problem \u2014 the worker bundle is fine, but mcp-server cannot locate it. Worker auto-start will fail until the dirname-resolution path is fixed.",{workerScriptPath:rf,mcpServerDir:Ew}))}async function rt(e,t={}){g.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:e});try{if(t.streamCorpusProgress&&t.body){let n=await mw(e,t.body);return g.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:e}),{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}let r;if(t.body)r=await ha(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t.body)});else{let n=new URLSearchParams;for(let[o,s]of Object.entries(t.query??{}))s!=null&&n.append(o,String(s));r=await ha(`${e}?${n}`)}if(!r.ok){let n=await r.text();throw new Error(`Worker API error (${r.status}): ${n}`)}return g.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:e}),t.text?{content:[{type:"text",text:await r.text()}]}:t.body?{content:[{type:"text",text:JSON.stringify(await r.json(),null,2)}]}:await r.json()}catch(r){return g.error("SYSTEM","\u2190 Worker API error",{endpoint:e},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function tD(){try{return(await ha("/api/health")).ok}catch(e){return g.debug("SYSTEM","Worker health check failed",{},e instanceof Error?e:new Error(String(e))),!1}}function bw(){if(va()!=="server")return null;let t=uw();return t?{...t,available:!0}:{runtime:"server",available:!1,reason:"server runtime is selected but configuration is incomplete (missing url, api key, or project id)"}}function rD(e){return cw(e)?{content:[{type:"text",text:`Server error (${e.kind}${e.status?` ${e.status}`:""}): ${e.message}`}],isError:!0}:{content:[{type:"text",text:`Tool error: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}function Pn(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function Ko(e){let t=bw();if(!t)throw new ft("transport",`${e} requires CLAUDE_MEM_RUNTIME=server. Current runtime is "worker"; use the existing search/timeline/get_observations tools for worker-mode memory access.`);if(!t.available)throw new ft("missing_api_key",`${e}: ${t.reason}`);return t}function Go(e,t){return async r=>{try{return await t(r)}catch(n){let o=n instanceof Error?n:new Error(String(n));return g.warn("SYSTEM",`${e} failed`,void 0,o),rD(n)}}}var nD=Go("observation_add",async e=>{let t=Ko("observation_add");if(typeof e?.content!="string"||e.content.trim().length===0)throw new Error('observation_add: "content" is required');let n={projectId:e.projectId&&e.projectId.trim().length>0?e.projectId:t.projectId,content:e.content,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.platformSource!==void 0?{platformSource:e.platformSource}:{},...e.kind!==void 0?{kind:e.kind}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}},o=await t.client.addObservation(n);return Pn(o)});function Pa(e){return typeof e=="string"?Ea(e):null}var oD=Go("observation_record_event",async e=>{let t=Ko("observation_record_event");if(typeof e?.eventType!="string"||e.eventType.trim().length===0)throw new Error('observation_record_event: "eventType" is required');let n={projectId:e.projectId&&e.projectId.trim().length>0?e.projectId:t.projectId,sourceType:e.sourceType??"api",eventType:e.eventType,occurredAtEpoch:typeof e.occurredAtEpoch=="number"?e.occurredAtEpoch:Date.now(),...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:Pa(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{},...e.generate!==void 0?{generate:e.generate}:{}},o=await t.client.recordEvent(n);return Pn(o)}),sD=Go("observation_search",async e=>{let t=Ko("observation_search");if(typeof e?.query!="string"||e.query.trim().length===0)throw new Error('observation_search: "query" is required');let n={projectId:e.projectId&&e.projectId.trim().length>0?e.projectId:t.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Pa(e.platformSource)}:{}},o=await t.client.searchObservations(n);return Pn(o)}),iD=Go("observation_context",async e=>{let t=Ko("observation_context"),r=typeof e?.query=="string"&&e.query.trim().length>0,o={projectId:e.projectId&&e.projectId.trim().length>0?e.projectId:t.projectId,...r?{query:e.query}:{},...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Pa(e.platformSource)}:{}},s=await t.client.contextObservations(o);return Pn(s)});function aD(e){return Array.isArray(e.projects)?e.projects.map(t=>typeof t=="string"?t.trim():"").filter(Boolean):typeof e.projects=="string"?e.projects.split(",").map(t=>t.trim()).filter(Boolean):typeof e.project=="string"&&e.project.trim().length>0?[e.project.trim()]:[]}async function cD(e){let t=aD(e);return t.length===0?{content:[{type:"text",text:'session_start_context: "project" or "projects" is required'}],isError:!0}:rt("/api/context/inject",{query:{projects:t.join(","),...e.platformSource!==void 0?{platformSource:Pa(e.platformSource)}:{},...e.full!==void 0?{full:e.full}:{},...e.colors!==void 0?{colors:e.colors}:{}},text:!0})}var uD=Go("observation_generation_status",async e=>{let t=Ko("observation_generation_status"),r=(e?.jobId??e?.job_id??"").trim();if(!r)throw new Error('observation_generation_status: "jobId" is required');let n=await t.client.getJobStatus(r);return Pn(n)});async function lD(){if(await tD())return!0;g.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),eD();try{let e=Zd(),t=await Fb(e,rf);return t==="dead"&&g.error("SYSTEM","Worker auto-start failed \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running. Check earlier log lines for the specific failure reason (Bun not found, missing worker bundle, port conflict, etc.)."),t!=="dead"}catch(e){return g.error("SYSTEM","Worker auto-start threw \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running.",void 0,e instanceof Error?e:new Error(String(e))),!1}}var ww=[{name:"important_workflow",description:`LAYERED WORKFLOW (ALWAYS FOLLOW):
232
+ `)}var Qd=require("node:fs/promises"),ef=require("node:os"),Lr=require("node:path");function qI(e){return e==="~"?(0,ef.homedir)():e.startsWith("~/")||e.startsWith("~\\")?(0,Lr.join)((0,ef.homedir)(),e.slice(2)):e}async function Sa(e,t=process.cwd()){if(typeof e!="string"||e.trim().length===0)throw new Error("file_path is required");let r=await(0,Qd.realpath)((0,Lr.resolve)(t)),n=(0,Lr.resolve)(r,qI(e.trim())),o;try{o=await(0,Qd.realpath)(n)}catch{o=n}if(o!==r&&!o.startsWith(r+Lr.sep))throw new Error(`Access denied: "${e}" resolves outside the workspace (${r}). MCP file tools can only read files within the current project.`);return o}var tf=require("node:fs/promises"),ka=require("node:fs"),mr=require("node:path"),_w=require("node:os"),yw=require("node:url");var aw="claude";function ZI(e){return e.trim().toLowerCase().replace(/\s+/g,"-")}function Ea(e){if(!e)return aw;let t=ZI(e);return t?t==="transcript"||t.includes("codex")?"codex":t.includes("cursor")?"cursor":t.includes("claude")?"claude":t.includes("kimi")?"kimi":t==="agy"||t==="antigravity"||t.startsWith("antigravity-")?"antigravity-cli":t:aw}var WI=Ot(pe.API_REQUEST),ft=class extends Error{kind;status;cause;constructor(t,r,n={}){super(r),this.name="ServerClientError",this.kind=t,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)}},wa=class{baseUrl;apiKey;timeoutMs;constructor(t){this.baseUrl=HI(t.serverBaseUrl),this.apiKey=t.apiKey,this.timeoutMs=t.timeoutMs??WI}async startSession(t,r={}){let n=this.buildStartSessionPayload(t);return this.request("POST","/v1/sessions/start",n,r)}async recordEvent(t){let r=this.buildEventPayload(t),n=t.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(t){if(!t.sessionId)throw new ft("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(t.sessionId)}/end`,{})}async addObservation(t){return this.request("POST","/v1/memories",this.buildAddObservationPayload(t))}async searchObservations(t){return this.request("POST","/v1/search",this.buildSearchPayload(t))}async contextObservations(t,r={}){let n={projectId:t.projectId};return t.query!==void 0&&(n.query=t.query),t.limit!==void 0&&(n.limit=t.limit),t.platformSource!==void 0&&(n.platformSource=ba(t.platformSource)),t.folderProjects&&t.folderProjects.length>0&&(n.folderProjects=t.folderProjects),t.excludeSubagents!==void 0&&(n.excludeSubagents=t.excludeSubagents),this.request("POST","/v1/context",n,r)}async getJobStatus(t){if(!t)throw new ft("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(t)}`)}buildAddObservationPayload(t){let r=t.content,n=t.kind??"manual",o=typeof t.metadata?.title=="string"?t.metadata.title:void 0;return{projectId:t.projectId,kind:n,content:r,...o?{title:o}:{},...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.platformSource!==void 0?{platformSource:t.platformSource}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}}}buildSearchPayload(t){return{projectId:t.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:ba(t.platformSource)}:{}}}buildStartSessionPayload(t){return{projectId:t.projectId,...t.externalSessionId!==void 0?{externalSessionId:t.externalSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.agentId!==void 0?{agentId:t.agentId}:{},...t.agentType!==void 0?{agentType:t.agentType}:{},...t.platformSource!==void 0?{platformSource:ba(t.platformSource)}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}}}buildEventPayload(t){return{projectId:t.projectId,sourceType:t.sourceType,eventType:t.eventType,occurredAtEpoch:t.occurredAtEpoch,...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.memorySessionId!==void 0?{memorySessionId:t.memorySessionId}:{},...t.platformSource!==void 0?{platformSource:ba(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{}}}async request(t,r,n,o={}){if(!this.apiKey||!this.apiKey.trim())throw new ft("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let s=`${this.baseUrl}${r}`,i={method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(i.body=JSON.stringify(n));let a,c=o.timeoutMs??this.timeoutMs;try{a=await jd(s,i,c)}catch(l){let d=l instanceof Error?l.message:String(l),f=/timed out|timeout/i.test(d);throw new ft(f?"timeout":"transport",`Server ${t} ${r} failed: ${d}`,{cause:l})}if(!a.ok){let l=await a.text().catch(()=>"");throw new ft("http_error",`Server ${t} ${r} returned ${a.status}: ${BI(l,200)}`,{status:a.status})}let u=await a.text();if(!u||u.length===0)return{};try{return JSON.parse(u)}catch(l){let d=l instanceof Error?l:new Error(String(l));throw new ft("invalid_response",`Server ${t} ${r} returned non-JSON response`,{cause:d})}}};function cw(e){return e instanceof ft}function HI(e){return e.replace(/\/+$/,"")}function ba(e){return typeof e=="string"?Ea(e):null}function BI(e,t){return e.length<=t?e:`${e.slice(0,t)}\u2026`}V();function va(){let t=(Bi().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return t==="server"||t==="server-beta"?"server":"worker"}function uw(){let e=Bi(),t=(...i)=>{for(let a of i){let c=(a??"").trim();if(c.length>0)return c}return""},r=t(e.CLAUDE_MEM_SERVER_URL,e.CLAUDE_MEM_SERVER_BETA_URL),n=t(e.CLAUDE_MEM_SERVER_API_KEY,e.CLAUDE_MEM_SERVER_BETA_API_KEY),o=t(e.CLAUDE_MEM_SERVER_PROJECT_ID,e.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!r)return g.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return g.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return g.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let s={serverBaseUrl:r,apiKey:n};return{runtime:"server",client:new wa(s),projectId:o,serverBaseUrl:r}}V();var lw=["observation_add","observation_record_event","observation_search","observation_context","observation_generation_status","memory_add","memory_search","memory_context"],KI=new Set(lw);function dw(e,t){return t==="server"?[...e]:(g.debug("SYSTEM","Filtering server-beta-only MCP tools from worker runtime advertisement",{runtime:t,hiddenToolCount:lw.length}),e.filter(r=>!KI.has(r.name)))}function fw(e,t){if(e.projects!==void 0||typeof e.project!="string")return e;let r=e.project.trim();return!r||r.toLowerCase()!==t.primary.toLowerCase()||t.allProjects.length<2?e:{...e,projects:t.allProjects.join(",")}}var GI=3e4,VI=15*6e4,YI={idleTimeoutMs:GI,absoluteCapMs:VI},JI=["result","error"];async function pw(e){let t=new TextDecoder,r="";for await(let n of e)r+=t.decode(n,{stream:!0});return r+t.decode()}async function mw(e,t,r=YI){let n=await Fd(Wd(e),{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream"},body:JSON.stringify(t)},{idleTimeoutMs:r.idleTimeoutMs,absoluteCapMs:r.absoluteCapMs});if(!n.ok)throw new Error(`Worker API error (${n.status}): ${await pw(n.chunks)}`);if(!(n.headers.get("content-type")??"").includes("text/event-stream"))return JSON.parse(await pw(n.chunks));for await(let s of od(n.chunks,{terminalEventNames:JI})){if(s.event==="result")return JSON.parse(s.data);if(s.event==="error"){let{status:i,...a}=JSON.parse(s.data);throw new Error(`Worker API error (${i}): ${JSON.stringify(a)}`)}}throw new Error(`Corpus stream for ${e} ended without a terminal event`)}var yD={},XI="13.30.1";console.log=(...e)=>{g.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:e})};var hw=null;function QI(){return hw??=sb(process.cwd()),hw}var Sw=!1,Ew=(()=>{if(typeof __CM_DIRNAME__<"u")return __CM_DIRNAME__;try{return(0,mr.dirname)((0,yw.fileURLToPath)(yD.url))}catch(e){return Sw=!0,g.warn("SYSTEM","mcp-server: failed to resolve module directory from import.meta.url, falling back to process.cwd()",void 0,e instanceof Error?e:new Error(String(e))),process.cwd()}})(),rf=Lb()??(0,mr.resolve)(Ew,"worker-service.cjs");function eD(){Sw&&((0,ka.existsSync)(rf)||g.error("SYSTEM","mcp-server: dirname resolution failed (both __dirname and import.meta.url are unavailable). Fell back to process.cwd() and the resolved WORKER_SCRIPT_PATH does not exist. This is the actual problem \u2014 the worker bundle is fine, but mcp-server cannot locate it. Worker auto-start will fail until the dirname-resolution path is fixed.",{workerScriptPath:rf,mcpServerDir:Ew}))}async function rt(e,t={}){g.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:e});try{if(t.streamCorpusProgress&&t.body){let n=await mw(e,t.body);return g.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:e}),{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}let r;if(t.body)r=await ha(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t.body)});else{let n=new URLSearchParams;for(let[o,s]of Object.entries(t.query??{}))s!=null&&n.append(o,String(s));r=await ha(`${e}?${n}`)}if(!r.ok){let n=await r.text();throw new Error(`Worker API error (${r.status}): ${n}`)}return g.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:e}),t.text?{content:[{type:"text",text:await r.text()}]}:t.body?{content:[{type:"text",text:JSON.stringify(await r.json(),null,2)}]}:await r.json()}catch(r){return g.error("SYSTEM","\u2190 Worker API error",{endpoint:e},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function tD(){try{return(await ha("/api/health")).ok}catch(e){return g.debug("SYSTEM","Worker health check failed",{},e instanceof Error?e:new Error(String(e))),!1}}function bw(){if(va()!=="server")return null;let t=uw();return t?{...t,available:!0}:{runtime:"server",available:!1,reason:"server runtime is selected but configuration is incomplete (missing url, api key, or project id)"}}function rD(e){return cw(e)?{content:[{type:"text",text:`Server error (${e.kind}${e.status?` ${e.status}`:""}): ${e.message}`}],isError:!0}:{content:[{type:"text",text:`Tool error: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}function Pn(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function Ko(e){let t=bw();if(!t)throw new ft("transport",`${e} requires CLAUDE_MEM_RUNTIME=server. Current runtime is "worker"; use the existing search/timeline/get_observations tools for worker-mode memory access.`);if(!t.available)throw new ft("missing_api_key",`${e}: ${t.reason}`);return t}function Go(e,t){return async r=>{try{return await t(r)}catch(n){let o=n instanceof Error?n:new Error(String(n));return g.warn("SYSTEM",`${e} failed`,void 0,o),rD(n)}}}var nD=Go("observation_add",async e=>{let t=Ko("observation_add");if(typeof e?.content!="string"||e.content.trim().length===0)throw new Error('observation_add: "content" is required');let n={projectId:e.projectId&&e.projectId.trim().length>0?e.projectId:t.projectId,content:e.content,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.platformSource!==void 0?{platformSource:e.platformSource}:{},...e.kind!==void 0?{kind:e.kind}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}},o=await t.client.addObservation(n);return Pn(o)});function Pa(e){return typeof e=="string"?Ea(e):null}var oD=Go("observation_record_event",async e=>{let t=Ko("observation_record_event");if(typeof e?.eventType!="string"||e.eventType.trim().length===0)throw new Error('observation_record_event: "eventType" is required');let n={projectId:e.projectId&&e.projectId.trim().length>0?e.projectId:t.projectId,sourceType:e.sourceType??"api",eventType:e.eventType,occurredAtEpoch:typeof e.occurredAtEpoch=="number"?e.occurredAtEpoch:Date.now(),...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:Pa(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{},...e.generate!==void 0?{generate:e.generate}:{}},o=await t.client.recordEvent(n);return Pn(o)}),sD=Go("observation_search",async e=>{let t=Ko("observation_search");if(typeof e?.query!="string"||e.query.trim().length===0)throw new Error('observation_search: "query" is required');let n={projectId:e.projectId&&e.projectId.trim().length>0?e.projectId:t.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Pa(e.platformSource)}:{}},o=await t.client.searchObservations(n);return Pn(o)}),iD=Go("observation_context",async e=>{let t=Ko("observation_context"),r=typeof e?.query=="string"&&e.query.trim().length>0,o={projectId:e.projectId&&e.projectId.trim().length>0?e.projectId:t.projectId,...r?{query:e.query}:{},...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Pa(e.platformSource)}:{}},s=await t.client.contextObservations(o);return Pn(s)});function aD(e){return Array.isArray(e.projects)?e.projects.map(t=>typeof t=="string"?t.trim():"").filter(Boolean):typeof e.projects=="string"?e.projects.split(",").map(t=>t.trim()).filter(Boolean):typeof e.project=="string"&&e.project.trim().length>0?[e.project.trim()]:[]}async function cD(e){let t=aD(e);return t.length===0?{content:[{type:"text",text:'session_start_context: "project" or "projects" is required'}],isError:!0}:rt("/api/context/inject",{query:{projects:t.join(","),...e.platformSource!==void 0?{platformSource:Pa(e.platformSource)}:{},...e.full!==void 0?{full:e.full}:{},...e.colors!==void 0?{colors:e.colors}:{}},text:!0})}var uD=Go("observation_generation_status",async e=>{let t=Ko("observation_generation_status"),r=(e?.jobId??e?.job_id??"").trim();if(!r)throw new Error('observation_generation_status: "jobId" is required');let n=await t.client.getJobStatus(r);return Pn(n)});async function lD(){if(await tD())return!0;g.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),eD();try{let e=Zd(),t=await Fb(e,rf);return t==="dead"&&g.error("SYSTEM","Worker auto-start failed \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running. Check earlier log lines for the specific failure reason (Bun not found, missing worker bundle, port conflict, etc.)."),t!=="dead"}catch(e){return g.error("SYSTEM","Worker auto-start threw \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running.",void 0,e instanceof Error?e:new Error(String(e))),!1}}var ww=[{name:"important_workflow",description:`LAYERED WORKFLOW (ALWAYS FOLLOW):
233
233
  1. search(query) \u2192 Get index with IDs (~50-100 tokens/result)
234
234
  2. timeline(anchor=ID) \u2192 Get context around interesting results
235
235
  3. get_observations([IDs]) \u2192 Fetch full details ONLY for filtered IDs