claude-mem 13.34.1 → 13.34.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/README.md +1 -1
- package/dist/npx-cli/index.js +1 -1
- package/dsh/package.json +1 -1
- package/openclaw/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/.codex-plugin/plugin.json +1 -1
- package/plugin/package.json +1 -1
- package/plugin/scripts/mcp-server.cjs +2 -2
- package/plugin/scripts/server-service.cjs +2 -2
- package/plugin/scripts/transcript-watcher.cjs +1 -1
- package/plugin/scripts/worker-service.cjs +331 -335
- package/plugin/scripts/worker-service.cjs.map +3 -3
|
@@ -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,v}if(m[0]===RC)return t.onActivity?.(),null;f(m.length),a+=m.length;let h=n.decode(m),_=h.indexOf(":"),S=_===-1?h:h.slice(0,_),E=_===-1?"":h.slice(_+1);return E.startsWith(" ")&&(E=E.slice(1)),S==="event"?c=E:S==="data"?(l??=[]).push(E):S==="id"&&(u=E),null};for await(let m of xC(e)){let h=[],_=0;for(let S=0;S<m.length;S++){let E=m[S];if(i&&(i=!1,E===PE)){_=S+1;continue}if(E!==TE&&E!==PE)continue;o.push(m.subarray(_,S));let y=AC(o,s+(S-_));o=[],s=0;let v=p(y);v&&h.push(v),i=E===TE,_=S+1}if(_<m.length){let S=m.slice(_);o.push(S),s+=S.length,f(s)}for(let S of h)t.terminalEventNames?.includes(S.event)&&(d=!0),yield S}if(t.terminalEventNames&&t.terminalEventNames.length>0&&!d)throw new md(t.terminalEventNames)}var Wr=require("fs"),yr=require("path"),Qo=require("os");rr();Y();function RE(e){try{return new URL(e).hostname.toLowerCase()==="openrouter.ai"}catch{return!1}}fs();var MC="security_alert",OC="sync-hub.black-pond-afbb.workers.dev",CC="ziczmqtpmaxbornfghye.supabase.co",$C="https://sync.cmem.ai",IC=new Set(["xiaomi/mimo-v2-flash:free"]);function DC(e){let t=e.CLAUDE_MEM_OPENROUTER_MODEL;if(typeof t!="string"||!IC.has(t.trim()))return!1;let r=typeof e.CLAUDE_MEM_OPENROUTER_BASE_URL=="string"?e.CLAUDE_MEM_OPENROUTER_BASE_URL.trim():"";return r===""||RE(r)}var xE=18e4,AE=[{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 OE(e,t){return(0,yr.join)((0,yr.dirname)(e),`.${(0,yr.basename)(e)}.${t.markerTag}`)}function gd(e,t){try{(0,Wr.writeFileSync)(OE(e,t),new Date().toISOString(),{encoding:"utf-8",mode:384})}catch{}}var ME=new Set;function NC(e){if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;try{let r=new URL(t).hostname;if(r===OC||r===CC)return $C}catch{return null}return null}var Me=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(Lt(ye.API_REQUEST)),CLAUDE_MEM_SESSION_INIT_TIMEOUT_MS:String(fd()),CLAUDE_MEM_IDLE_EXIT_SEC:"0",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_SKIP_BASH_PATTERNS:"",CLAUDE_MEM_SKIP_SUBAGENT_OBSERVATIONS:"false",CLAUDE_MEM_SKIP_AGENT_TYPES:"",CLAUDE_MEM_CAPTURE_ADVISOR_CALLS:"false",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CODEX_MODEL:"",CLAUDE_MEM_CODEX_PATH:"codex",CLAUDE_MEM_CODEX_REASONING_EFFORT:"low",CLAUDE_MEM_CODEX_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_CODEX_OBSERVATION_BATCH_SIZE:"8",CLAUDE_MEM_CODEX_OBSERVATION_BATCH_MAX_CHARS:"32000",CLAUDE_MEM_CLAUDE_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_QUOTA_THRESHOLD_FIVE_HOUR:"0.95",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY:"0.93",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY_OPUS:"0.93",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY_SONNET:"0.92",CLAUDE_MEM_QUOTA_THRESHOLD_OVERAGE:"0.95",CLAUDE_MEM_DATA_DIR:(0,yr.join)((0,Qo.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_FILE_READ_GATE_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,yr.join)((0,Qo.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,Qo.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(xE),CLAUDE_MEM_FIELD_OPTIMIZE_TIMEOUT_MS:String(xE),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,Wr.existsSync)(t)){let d=this.getAllDefaults();try{St(t,d,{mode:384});for(let f of AE)gd(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,Wr.readFileSync)(t,"utf-8"),o=Fn(n),s=Jr(o),i=s!==o,a=Tf(o),c=i&&Object.keys(a).some(d=>d!=="env");if(i&&!c)try{St(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===MC){s={...s,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES};try{St(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(DC(s)){let d=String(s.CLAUDE_MEM_OPENROUTER_MODEL).trim();s={...s,CLAUDE_MEM_OPENROUTER_MODEL:this.DEFAULTS.CLAUDE_MEM_OPENROUTER_MODEL};try{St(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=NC(s.CLAUDE_MEM_CLOUD_SYNC_HUB_URL);if(u!==null){s={...s,CLAUDE_MEM_CLOUD_SYNC_HUB_URL:u};try{St(t,c?{...a,env:s}:s,{mode:384}),console.warn("[SETTINGS] Migrated cloud sync hub URL to",u,"from a retired hub 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 AE)if(!(0,Wr.existsSync)(OE(t,d))){if(s[d.key]!==d.legacy){gd(t,d);continue}s={...s,[d.key]:this.DEFAULTS[d.key]};try{St(t,c?{...a,env:s}:s,{mode:384}),gd(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}`;ME.has(p)||(ME.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)}}};Ke();Ke();var oa=null;function sa(){return oa!==null||(oa=Me.loadFromFile(Pr)),oa}function _d(e){return(e.CLAUDE_MEM_WORKER_AUTOSTART??"true").trim().toLowerCase()==="false"}function yd(e){return e.startsWith("[")&&e.endsWith("]")?e:e.includes(":")?`[${e}]`:e}var Hr=require("fs");Y();var Sd=require("node:child_process");function Ed(e,t,r){return(0,Sd.spawn)(e,t??[],{...r,windowsHide:!0})}var LC=new Set([".cmd",".bat"]),zC=new Set([".exe",".com"]),MW=new Set([...zC,...LC]);var Zr=require("fs"),zE=nt(require("path"),1);Y();rr();var UC=["CLAUDECODE_","CLAUDE_CODE_"],jC=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),FC=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"]),qC=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",...FC]);function Sr(e=process.env){let t={};for(let[r,n]of Object.entries(e))if(n!==void 0){if(qC.has(r)){t[r]=n;continue}jC.has(r)||UC.some(o=>r.startsWith(o))||(t[r]=n)}return t}Ke();var wd=require("child_process"),$E=require("fs");Y();var WC=5e3,CE=new Map,bd=0;function IE(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 ZC(e){bd+=1;let t=(0,wd.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:{...Sr(process.env),LC_ALL:"C",LANG:"C"}});return IE("powershell-cim",e,t)}function HC(e,t=!1){if(!t){let n=CE.get(e);if(n&&(e===process.pid||Date.now()-n.capturedAtMs<WC))return n.token}let r=null;try{r=ZC(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)&&CE.set(e,{token:r,capturedAtMs:Date.now()}),r}function DE(e,t){if(!Number.isInteger(e)||e<=0)return null;if(process.platform==="linux"){bd+=1;try{let r=(0,$E.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 HC(e,t);bd+=1;try{let r=(0,wd.spawnSync)("ps",["-p",String(e),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Sr(process.env),LC_ALL:"C",LANG:"C"}});return IE("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 zt(e){return DE(e,!1)}function At(e,t){if(t===null)return!0;let r=DE(e,!0);return r===null?!0:r===t}var NE=require("child_process"),ca=require("fs"),LE=require("util");Y();var vd=(0,LE.promisify)(NE.execFile),BC=128,KC=/not found|no running instance|no tasks/i,ia=class extends Error{pid;constructor(t,r,n){super(r,n),this.name="ProcessTreeKillError",this.pid=t}};async function Mt(e,t={}){let r=t.signalMode==="immediate",n=t.expectedStartToken!==void 0?t.expectedStartToken:zt(e),o=()=>At(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 vd("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===BC||KC.test(`${a} ${c}`)){g.debug("PROCESS","taskkill reported the process was already gone",{pid:e});return}throw new ia(e,`taskkill failed for PID ${e} (exit ${String(i)}): ${a.trim()||c}`,{cause:s})}return}try{let s=r?"SIGKILL":"SIGTERM",i=await aa(e);for(let u of i){if(!At(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 aa(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(!At(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 ia(e,`tree-kill failed for PID ${e}: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}async function GC(){return process.platform==="win32"?JC():process.platform==="linux"?VC():YC()}function VC(){let e=[],t;try{t=(0,ca.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,ca.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 YC(){let e;try{e=(await vd("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 JC(){let e;try{e=(await vd("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 aa(e){let t=await GC(),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 XC=5e3,QC=1e3,e$=Be.supervisorRegistry(),t$=null;function be(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 ua(e,t){let r=Date.now()+t;for(;Date.now()<r;){if(e.every(n=>!be(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function UE(e){if(!e||!be(e.pid))return!1;if(!e.startToken)return!0;let t=zt(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 r$={platform:process.platform,readCommandLine:e=>(0,Zr.readFileSync)(`/proc/${e}/cmdline`,"utf-8")};function la(e,t=r$){if(!UE(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=>zE.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 da(e=Be.workerPid()){if(!(0,Zr.existsSync)(e))return null;let t;try{t=JSON.parse((0,Zr.readFileSync)(e,"utf-8"))}catch{return null}return t!==null&&la(t)?t:null}var Pd=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(t=e$){this.registryPath=t}initialize(){if(this.initialized)return;if(this.initialized=!0,!(0,Zr.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Zr.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||!be(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"&&Td())}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)be(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)Td();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=>be(a.pid)),s=new Map(o.map(a=>[a.pid,zt(a.pid)]));for(let a of o)try{process.platform==="win32"?await Mt(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 ua(o,XC);let i=o.filter(a=>be(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(!At(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 Mt(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()+QC;for(;Date.now()<a&&i.filter(u=>be(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"&&Td();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{St(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{t$?.({errorCategory:r.code??"unknown"})}catch{}}},kd=null;function fa(){return kd||(kd=new Pd),kd}var YW=180*1e3,n$=[];function Td(){let e=n$.shift();e&&e.notify()}var Mn=require("fs");Y();Ke();var o$=Be.workerPid();async function FE(e){let t=e.currentPid??process.pid,r=e.pidFilePath??o$,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(!be(c.pid)){e.registry.unregister(c.id);continue}i.set(c.id,zt(c.pid)),s.set(c.id,await aa(c.pid));try{await jE(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 ua(o,5e3);let a=o.filter(c=>be(c.pid)||(s.get(c.id)??[]).some(u=>be(u.pid)));for(let c of a){let u=At(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 jE(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{s$(s.get(c.id)??[],c.pid)}}await ua(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);Rd(r,t),e.registry.pruneDeadEntries()}function Rd(e,t,r=!1){if(!(0,Mn.existsSync)(e))return;let n=null;try{let i=JSON.parse((0,Mn.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||!be(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,Mn.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 s$(e,t){for(let{pid:r,startToken:n}of e)if(!(r===t||!be(r))){if(!At(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 jE(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 Mt(r,{signalMode:"immediate"});return}try{process.kill(r,t)}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}return}await Mt(r)}Y();var qE=3e4,On=null;function i$(){let t=fa().pruneDeadEntries();t>0&&g.info("SYSTEM",`Health check: pruned ${t} dead process(es) from registry`)}function WE(){On===null&&(On=setInterval(i$,qE),On.unref(),g.debug("SYSTEM","Health checker started",{intervalMs:qE}))}function ZE(){On!==null&&(clearInterval(On),On=null,g.debug("SYSTEM","Health checker stopped"))}var HE=require("child_process"),BE=require("util");Y();var a$=(0,BE.promisify)(HE.execFile),c$=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/;function u$(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 l$(){let e=await a$("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return u$(e.stdout)}function d$(e,t){let r=e.filter(i=>c$.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 KE(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??l$,o=e.isAlive??be,s=e.killTree??(p=>Mt(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}=d$(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((_,S)=>{let E=m[S];_.status==="fulfilled"?(r.killed+=1,d.add(E.pid)):(r.failed+=1,g.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:E.pid,ppid:E.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}Ke();var f$=Be.workerPid(),xd=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(),Md({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,KE({registry:this.registry}).catch(r=>{g.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),WE()}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}ZE(),this.stopPromise=FE({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}},p$=new xd(fa());function Ad(){return p$}function Md(e={}){let t=e.pidFilePath??f$;if(!(0,Hr.existsSync)(t))return"missing";let r=null;try{r=JSON.parse((0,Hr.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,Hr.rmSync)(t,{force:!0}),"invalid"}return la(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,Hr.rmSync)(t,{force:!0})),"stale")}ds();var Od=require("path"),ma=require("fs"),VE=require("crypto");Ke();var pa=require("fs");rr();function GE(e,t){if(!(0,pa.existsSync)(e))return t;try{return Fn((0,pa.readFileSync)(e,"utf-8"))}catch(r){throw new Error(`Corrupt JSON file, refusing to overwrite: ${e}: ${r instanceof Error?r.message:String(r)}`)}}Y();var YE="telemetry.json";function m$(e){let t=e.DO_NOT_TRACK;return t===void 0||t===""?!1:t!=="0"&&t!=="false"}function h$(e,t){if(m$(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 JE(e,t){return h$(e,t).enabled}function g$(){return(0,Od.join)(qt(),YE)}function Cd(){let e;try{e=GE(g$(),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 _$(e){let t=qt();(0,ma.mkdirSync)(t,{recursive:!0}),(0,ma.writeFileSync)((0,Od.join)(t,YE),JSON.stringify(e,null,2)+`
|
|
84
|
-
`)}function XE(){let e=Cd();if(e?.installId)return e.installId;let t=(0,VE.randomUUID)();return _$({installId:t,decidedAt:""}),t}var eb=nt(require("os"),1);Y();var QE=8192,gt="[REDACTED]";function y$(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>QE?t.slice(0,QE):t}catch{return""}}function S$(e){if(typeof e!="string"||e.length===0)return e??"";let t="";try{t=eb.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 E$(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 b$(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${gt}`):t.replace(/[?#].*$/,"").replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/@\s]+@/,`$1${gt}@`))}function w$(e){return typeof e!="string"||e.length===0?e??"":e.replace(/\?[^\s"'()]*/g,"")}function v$(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)}${gt}`})}function k$(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,gt),t=t.replace(/\b[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\b/g,gt),t=t.replace(/\b(?:sk|pk|rk|ak|phc|phx|ph|ghp|gho|ghs|xox[bpasr])[-_][A-Za-z0-9_-]{8,512}\b/gi,gt),t=t.replace(/\bBearer\s+[A-Za-z0-9._-]{8,512}\b/gi,gt),t=t.replace(/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g,gt),t=t.replace(/\b[0-9a-fA-F]{24,4096}\b/g,gt),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,gt),t=t.replace(/\b(?=[A-Za-z0-9+/_-]{0,4096}\d)[A-Za-z0-9+/_-]{32,4096}={0,2}\b/g,gt),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,gt),t}function tb(e){let t=y$(e);return t.length===0?"":(t=S$(t),t=b$(t),t=E$(t),t=w$(t),t=v$(t),t=k$(t),t)}var T$=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"]),rb=200;function P$(e,t){if(!(!e||typeof e!="object"))for(let r of Object.keys(e)){if(!T$.has(r))continue;let n=e[r];if(typeof n=="string"){let o=n.length>rb?n.slice(0,rb):n;t[r]=tb(o)}else(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(t[r]=n)}}function nb(e){let t={};try{P$(e,t)}catch{}return t}var $d=nt(require("os"),1);Y();var R$="13.34.
|
|
84
|
+
`)}function XE(){let e=Cd();if(e?.installId)return e.installId;let t=(0,VE.randomUUID)();return _$({installId:t,decidedAt:""}),t}var eb=nt(require("os"),1);Y();var QE=8192,gt="[REDACTED]";function y$(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>QE?t.slice(0,QE):t}catch{return""}}function S$(e){if(typeof e!="string"||e.length===0)return e??"";let t="";try{t=eb.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 E$(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 b$(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${gt}`):t.replace(/[?#].*$/,"").replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/@\s]+@/,`$1${gt}@`))}function w$(e){return typeof e!="string"||e.length===0?e??"":e.replace(/\?[^\s"'()]*/g,"")}function v$(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)}${gt}`})}function k$(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,gt),t=t.replace(/\b[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\b/g,gt),t=t.replace(/\b(?:sk|pk|rk|ak|phc|phx|ph|ghp|gho|ghs|xox[bpasr])[-_][A-Za-z0-9_-]{8,512}\b/gi,gt),t=t.replace(/\bBearer\s+[A-Za-z0-9._-]{8,512}\b/gi,gt),t=t.replace(/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g,gt),t=t.replace(/\b[0-9a-fA-F]{24,4096}\b/g,gt),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,gt),t=t.replace(/\b(?=[A-Za-z0-9+/_-]{0,4096}\d)[A-Za-z0-9+/_-]{32,4096}={0,2}\b/g,gt),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,gt),t}function tb(e){let t=y$(e);return t.length===0?"":(t=S$(t),t=b$(t),t=E$(t),t=w$(t),t=v$(t),t=k$(t),t)}var T$=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"]),rb=200;function P$(e,t){if(!(!e||typeof e!="object"))for(let r of Object.keys(e)){if(!T$.has(r))continue;let n=e[r];if(typeof n=="string"){let o=n.length>rb?n.slice(0,rb):n;t[r]=tb(o)}else(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(t[r]=n)}}function nb(e){let t={};try{P$(e,t)}catch{}return t}var $d=nt(require("os"),1);Y();var R$="13.34.2",x$="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",A$="https://us.i.posthog.com";function ob(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||x$}function sb(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||A$}var M$=["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 ib(e){let t={};for(let r of M$)e[r]!==void 0&&(t[r]=e[r]);return t}function O$(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||$d.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 ab(){return{version:R$,os:process.platform,os_version:$d.default.release(),is_wsl:O$(),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 C$=2e3;async function Id(e,t,r){try{if(!JE(process.env,Cd()))return;let n=nb({...ab(),...t??{}});if(r?.person?n.$set=ib(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=ob(),s=new AbortController,i=setTimeout(()=>s.abort(),C$);try{await $$(o,e,n,s.signal)}finally{clearTimeout(i)}}catch{}}async function $$(e,t,r,n){await fetch(`${sb()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:e,event:t,distinct_id:XE(),properties:r}),signal:n})}var tt=nt(require("path"),1),qd=require("os"),Oe=require("fs"),ts=require("child_process");Y();Y();Y();var We=nt(require("path"),1),Cn=require("fs"),ya=require("os"),zd=require("child_process");Wn();Ke();Y();var ha=require("fs"),Er=nt(require("path"),1);Y();var es={isWorktree:!1,isSubmodule:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function cb(e){let t=Er.default.join(e,".git"),r;try{r=(0,ha.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)}),es}if(!r.isFile())return es;let n;try{n=(0,ha.readFileSync)(t,"utf-8").trim()}catch(c){return g.warn("GIT","Failed to read .git file",{error:c instanceof Error?c.message:String(c)}),es}let o=n.match(/^gitdir:\s*(.+)$/);if(!o)return es;let s=Er.default.resolve(Er.default.dirname(t),o[1]),i=s.match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(i){let c=i[1];return{isWorktree:!0,isSubmodule:!1,worktreeName:Er.default.basename(e),parentRepoPath:c,parentProjectName:Er.default.basename(c)}}let a=s.match(/^(.+)[/\\]\.git[/\\]modules[/\\](.+)$/);if(a){let c=a[1];return{isWorktree:!1,isSubmodule:!0,worktreeName:Er.default.basename(e),parentRepoPath:c,parentProjectName:Er.default.basename(c)}}return es}var db=require("fs");var ub=require("path");Wn();Y();function I$(e){let t=Ft(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 lb(e,t){if(!t.length)return!1;let r=e.replace(/\\/g,"/"),n=(0,ub.basename)(r);for(let o of t){let s=o.trim();if(s)try{let i=I$(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}Y();function fb(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 D$(e){try{return(0,db.realpathSync)(e)}catch{return e}}function Dd(e,t){if(t.length===0)return null;let r=[...new Set([e,D$(e)])].flatMap(n=>[n,`${n.replace(/[\\/]+$/,"")}/`]);for(let n of t)if(r.some(o=>lb(o,n.patterns)))return n.name;return null}var Ud="unknown-project";function hb(e){try{return(0,zd.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 N$=[".claude-mem-project",".claude-mem.json"],L$=64;function gb(e){try{return(0,Cn.realpathSync)(e)}catch{return e}}function z$(e,t){let r=We.default.relative(t,e);return r===""||!r.startsWith("..")&&!We.default.isAbsolute(r)}function U$(){return[(0,ya.homedir)(),(0,ya.tmpdir)(),Zn].flatMap(e=>{let t=We.default.resolve(e);return[t,gb(t)]})}function _b(e){let t=U$(),r=We.default.resolve(e);if([We.default.resolve(Zn),gb(We.default.resolve(Zn))].some(o=>z$(r,o)))return null;for(let o=0;o<L$;o++){if(t.includes(r))return null;let s=We.default.dirname(r);if(s===r)return null;if(N$.some(i=>(0,Cn.existsSync)(We.default.join(r,i))))return r;r=s}return null}function Ld(e,t){let r=We.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}),Ud}return r}var j$="CLAUDE_MEM_PROJECT_NAME_SOURCE",ga=null;function pb(){try{return(0,Cn.statSync)(Pr).mtimeMs}catch{return-1}}function yb(){let e=pb();if(e===-1)return Me.getAllDefaults();if(ga&&ga.mtimeMs===e)return ga.settings;let t=Me.loadFromFile(Pr);return ga={mtimeMs:pb(),settings:t},t}function F$(){let e=process.env[j$]??yb().CLAUDE_MEM_PROJECT_NAME_SOURCE;return String(e??"path").trim().toLowerCase()==="git-remote"}var q$="CLAUDE_MEM_PROJECT_ENVIRONMENTS",_a=null;function Sb(){let e=process.env[q$]??yb().CLAUDE_MEM_PROJECT_ENVIRONMENTS;return(!_a||_a.raw!==e)&&(_a={raw:e,environments:fb(e)}),_a.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 Z$(e){try{let t=(0,zd.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 Nd=new Map;function Eb(e){return F$()?(Nd.has(e)||Nd.set(e,Z$(e)),Nd.get(e)??null):null}function H$(e,t=process.platform){if(!e||e.trim()==="")return g.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:e}),Ud;let r=Ft(e,t),n=Dd(r,Sb());if(n)return n;let o=hb(r),s=o?Eb(o):null;if(s)return s;let i=o??_b(r)??r;return Ld(e,i)}function bb(e,t){return t===e?e:`${e}/${t}`}function B$(e,t){if(!e.isSubmodule||!e.parentRepoPath)return null;let r=We.default.relative(e.parentRepoPath,t);return!r||r.startsWith("..")||We.default.isAbsolute(r)?null:r.split(We.default.sep).join("/")}function wb(e,t=process.platform){if(!e||e.trim()===""){let c=H$(e,t);return{primary:c,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[c],keySource:"path"}}let r=Ft(e,t),n=hb(r),o=K$(e,r,n),s=n?Eb(n):null,i=s?mb(o,s,"git-remote"):o,a=Dd(r,Sb());return a?mb(i,a,"environment"):i}function mb(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 K$(e,t,r){let n=r?null:_b(t),o=Ld(e,r??n??t),s=r??t,i=cb(s);if((i.isWorktree||i.isSubmodule)&&i.parentProjectName){let a=i.parentProjectName,c,u;return i.isSubmodule?(c=`${a}/${B$(i,s)??o}`,u=o!==a?[o]:[]):(c=bb(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&&We.default.resolve(n)!==We.default.resolve(t)){let a=Ld(e,t);if(a!==o&&a!==Ud)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"}}Ke();var vb=Lt(ye.POWERSHELL_COMMAND);function G$(e){return e===void 0?vb:Math.max(1,Math.min(vb,e))}var h2=Be.dataDir(),Br=Be.workerPid(),Tb="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 V$(e){try{return(0,Oe.realpathSync)(e)}catch{return null}}function jd(e){return e?/(^|[\\/])bun(\.exe)?$/i.test(e.trim()):!1}function Y$(e,t){let r=t==="win32"?"where.exe":"which",n=[e],o;try{o=(0,ts.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 Fd;function Wd(e={}){let t=Object.keys(e).length===0;if(t&&Fd!==void 0)return Fd;let r=J$(e);return t&&r!==null&&(Fd=r),r}function kb(e,t){let r=e?.trim();return r?t==="win32"?[tt.default.join(r,"bin","bun.exe"),tt.default.join(r,"bin","bun"),tt.default.join(r,"bun.exe")]:[tt.default.join(r,"bin","bun"),tt.default.join(r,"bun")]:[]}function J$(e){let t=e.platform??process.platform,r=e.execPath??process.execPath;if(jd(r))return r;let n=e.env??process.env,o=e.homeDirectory??(0,qd.homedir)(),s=e.pathExists??Oe.existsSync,i=e.lookupInPath??Y$,a=e.realpath??V$,c=t==="win32"?[n.BUN,n.BUN_PATH,...kb(n.BUN_INSTALL,t),tt.default.join(o,".bun","bin","bun.exe"),tt.default.join(o,".bun","bin","bun"),n.USERPROFILE?tt.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?tt.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?tt.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0,n.npm_config_prefix?tt.default.join(n.npm_config_prefix,"bun.exe"):void 0]:[n.BUN,n.BUN_PATH,...kb(n.BUN_INSTALL,t),tt.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?tt.default.join(n.npm_config_prefix,"bin","bun"):void 0];for(let d of c){let f=d?.trim();if(f&&(jd(f)&&s(f)||f.toLowerCase()==="bun"))return f}let u=i("bun",t)?.trim();if(!u||!jd(u))return null;let l=a(u)??u;return s(l)?l:null}function Pb(){if(!(0,Oe.existsSync)(Br))return null;try{return JSON.parse((0,Oe.readFileSync)(Br,"utf-8"))}catch(e){return e instanceof Error?g.warn("SYSTEM","Failed to parse PID file",{path:Br},e):g.warn("SYSTEM","Failed to parse PID file",{path:Br},new Error(String(e))),null}}function Rb(e){Rd(Br,e,!0)}function br(e){return process.platform==="win32"?Math.round(e*2):e}function Zd(){let e=Be.dataDir();return(0,Oe.mkdirSync)(e,{recursive:!0}),e}function X$(e,t,r=Zd()){let n=o=>o.replace(/'/g,"''");return`Start-Process -FilePath '${n(e)}' -ArgumentList @('"${n(t)}"','--daemon') -WorkingDirectory '${n(r)}' -WindowStyle Hidden`}var Q$=5e3,eI=8;function tI(e,t,r){return e?.code!=="ETIMEDOUT"?!1:t<r/2}function xb(e,t=br(Q$)){let r=Wd();if(!r)return;let n=()=>{let a=Date.now();try{return{result:(0,ts.spawnSync)(r,[e,"status"],{encoding:"utf-8",timeout:t,windowsHide:!0,env:Sr({...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||tI(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,eI).join(`
|
|
86
86
|
`)}function rI(e=process.env){let t=e.SystemRoot||e.SYSTEMROOT;return t?`${t}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`:"powershell.exe"}function nI(e,t,r=Zd()){return["-NoProfile","-WindowStyle","Hidden","-EncodedCommand",Buffer.from(X$(e,t,r),"utf16le").toString("base64")]}function Ab(e,t,r,n=process.platform,o){if(n==="win32"){let l=rI(r),d=nI(e,t),f=G$(o);try{let p=(0,ts.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,Oe.existsSync)(s),a=i?s:e,u=Ed(a,i?[e,t,"--daemon"]:[t,"--daemon"],{detached:!0,stdio:"ignore",cwd:Zd(),env:r});if(u.on("error",l=>{g.error("SYSTEM",Tb,{runtimePath:e,execPath:a},l)}),u.pid!==void 0)return u.unref(),u.pid}function Mb(e,t,r={}){Ad().assertCanSpawn("worker daemon");let n=Sr({...process.env,CLAUDE_MEM_WORKER_PORT:String(t),...r}),o=Wd();if(!o){g.error("SYSTEM",Tb);return}return Ab(o,e,n)}function Ob(){try{if(!(0,Oe.existsSync)(Br))return;let e=new Date;(0,Oe.utimesSync)(Br,e,e)}catch{}}function rs(e={}){return Md({logAlive:!1,removeStale:e.removeStale})}var $b=nt(require("net"),1);Y();Ke();var oI=new Set(["ECONNREFUSED","ConnectionRefused"]);function Hd(e,t){if(!e||typeof e!="object"||t.has(e))return!1;t.add(e);let r=e;return typeof r.code=="string"&&oI.has(r.code)||Hd(r.cause,t)?!0:Array.isArray(r.errors)&&r.errors.some(n=>Hd(n,t))}function Bd(e){return Hd(e,new Set)?!0:e instanceof Error&&e.message.includes("ECONNREFUSED")}function Cb(e){let t=e?.code;return t==="EACCES"||t==="EADDRNOTAVAIL"}var Sa="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 Kd(){return Me.loadFromFile(Pr).CLAUDE_MEM_WORKER_HOST}function Ib(e){return e.startsWith("[")&&e.endsWith("]")?e:e.includes(":")?`[${e}]`:e}var ns=5e3;async function sI(e,t,r="GET",n=ns){let o=await fetch(`http://${Ib(Kd())}:${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 Gd(e,t=ns){let r=Date.now()+t;if(process.platform==="win32")try{let o=await fetch(`http://${Ib(Kd())}:${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 Db(e,Math.max(1,r-Date.now()));return n==="occupied"||n==="indeterminate"}async function Db(e,t=ns){return(await Vd(e,t)).occupancy}function Vd(e,t=ns){return t<=0?Promise.resolve({occupancy:"indeterminate"}):new Promise(r=>{let n=!1,o=!1,s=!1,i;try{i=$b.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"}):Cb(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,Kd())}catch{try{i.close()}catch{}u({occupancy:"indeterminate"})}})}async function Nb(e,t,r,n){let o=Date.now()+r;for(;Date.now()<o;){try{let i=o-Date.now();if((await sI(e,t,"GET",Math.min(ns,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 wr(e,t=3e4){return Nb(e,"/api/health",t,"Service not ready yet, will retry")}function $n(e,t=3e4){return Nb(e,"/api/readiness",t,"Worker not ready yet, will retry")}Y();var Ea=require("path"),Le=require("fs");Ke();Y();var zb=9e4,$2=zb/3;function Ub(){return(0,Ea.join)(qt(),"spawn.lock")}function Lb(e){try{let t=JSON.parse((0,Le.readFileSync)(e,"utf-8"));return typeof t.pid!="number"||!Number.isInteger(t.pid)||t.pid<=0?null:t.pid}catch{return null}}function iI(e){if(e===null)return null;try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}function Yd(){let e=Ub(),t=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return(0,Le.mkdirSync)((0,Ea.dirname)(e),{recursive:!0}),(0,Le.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,Le.statSync)(e).mtimeMs}catch{continue}let a=Lb(e),c=null;if(a===null)try{c=(0,Le.readFileSync)(e,"utf-8")}catch{continue}if(Date.now()-i<=zb&&iI(a)!==!1)return!1;let l;try{l=(0,Le.statSync)(e).mtimeMs}catch{continue}if(l!==i)return!1;if(a!==null){if(Lb(e)!==a)return!1}else try{if((0,Le.readFileSync)(e,"utf-8")!==c)return!1}catch{continue}try{(0,Le.unlinkSync)(e)}catch{return!1}}return!1}function Jd(){let e=Ub();try{if(JSON.parse((0,Le.readFileSync)(e,"utf-8")).pid!==process.pid)return;(0,Le.unlinkSync)(e)}catch{}}var qb=require("node:child_process"),Wb=require("node:util");Y();Ke();var ba=(0,Wb.promisify)(qb.execFile),aI=/^(uv|uvx|python|chroma-mcp)(\.exe)?$/i;function jb(e){return aI.test(e.trim())}function cI(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 wa(e,t){return t===void 0?e:Math.max(1,Math.min(e,t))}async function uI(e){try{let t=await ba("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:wa(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 lI(e,t){try{let r=await ba("netstat",["-ano"],{timeout:wa(15e3,t),windowsHide:!0,maxBuffer:16777216});return mI(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 dI(e,t){try{let r=await ba("lsof",["-nP",`-iTCP:${e}`,"-sTCP:LISTEN","-t"],{timeout:wa(1e4,t),maxBuffer:1048576});return fI(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 fI(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 pI(e,t){try{let n=(await ba("ps",["-p",String(e),"-o","command="],{timeout:wa(5e3,t)})).stdout.trim();return n.length>0?n:null}catch{return null}}function mI(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 hI=/worker-service/i,Zb=1500,Hb=1e3,Xd=5500,Fb=2*Zb+Hb+Xd;async function gI(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(Hb),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||!hI.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 _I(e,t,r,n){let o=zt(e),s=t?(await r(n))?.find(i=>i.pid===e)?.cmdline??null:await pI(e,n);return At(e,o)?{startToken:o,cmdline:s}:{startToken:null,cmdline:null}}async function Qd(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(Fb))return g.info("PROCESS","Port reclaim skipped: not enough of the hook budget is left to finish one",{port:e,remainingMs:i(),neededMs:Fb}),{reclaimed:!1,reason:"out-of-budget",killedPids:[]};let a=t.listOwners??((R,C)=>r()?lI(R,C):dI(R,C)),c=R=>a(R,i()),u=t.readTable??uI,l=()=>u(i()),d=t.killTree??((R,C)=>Mt(R,C)),f=t.dataDir??(()=>he),p=t.readIdentity??((R,C)=>_I(R,r(),u,C)),m=await gI(e,{listOwners:c,killTree:d,readOwnedWorker:t.readOwnedWorker??da,probeHealth:t.probeHealth??(R=>wr(R,Zb)),readIdentity:R=>p(R,i()),minOwnerAgeSeconds:t.minOwnerAgeSeconds??kE(),now:n,sleep:t.sleep??(R=>new Promise(C=>setTimeout(C,R))),hasKillBudget:()=>!s(Xd)});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=>be(R)).length>0)return{reclaimed:!1,reason:"owner-alive",killedPids:[]};let E=new Map;for(let R of _){let C=E.get(R.ppid);C?C.push(R):E.set(R.ppid,[R])}let y=new Map,v=new Set,k=R=>{for(let C of E.get(R)??[])v.has(C.pid)||(v.add(C.pid),k(C.pid),jb(C.name)&&y.set(C.pid,C))};for(let R of h)k(R);let T=f();if(T)for(let R of _)y.has(R.pid)||jb(R.name)&&cI(R.cmdline,T)&&y.set(R.pid,R);if(y.size===0)return g.info("PROCESS","Ghost listener owner is dead but no chroma-sidecar descendants found",{port:e,deadOwners:h,processTableRows:_.length,dataDir:T??"(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:[...y.values()].map(R=>({pid:R.pid,name:R.name}))});let P=[];for(let R of y.values()){if(s(Xd))return g.info("PROCESS","Ghost-listener reclaim stopped before a kill: the hook budget is spent",{port:e,killedPids:P}),{reclaimed:!1,reason:"out-of-budget",killedPids:P};try{await d(R.pid,{expectedStartToken:R.startToken,signalMode:"immediate"}),P.push(R.pid)}catch(C){return g.error("PROCESS","Ghost-port reclaim tree-kill failed",{port:e,pid:R.pid},C instanceof Error?C:new Error(String(C))),{reclaimed:!1,reason:"kill-failed",killedPids:P}}}let D=await c(e);return D!==null&&D.length===0?(g.info("PROCESS","Ghost listener reclaimed \u2014 port is free again",{port:e,killedPids:P}),{reclaimed:!0,killedPids:P}):(g.warn("PROCESS","Ghost-port reclaim killed the sidecar chain but the port is still bound",{port:e,killedPids:P,stillOwnedBy:D}),{reclaimed:!1,reason:"still-bound",killedPids:P})}rr();var In=require("fs"),Kb=require("module"),vr=nt(require("path"),1),yI=["zod/v3","zod/v4","zod/v4-mini"];function Bb(e){try{return(0,In.realpathSync)(e)}catch{return e}}function SI(e,t){let r=vr.default.relative(t,e);return r!==""&&!r.startsWith("..")&&!vr.default.isAbsolute(r)}function Gb(e){let t;try{let o=JSON.parse((0,In.readFileSync)(vr.default.join(e,"package.json"),"utf-8"));t=Object.keys(o?.dependencies??{})}catch{return[]}if(t.length===0)return[];let r=vr.default.join(e,"node_modules"),n=t.filter(o=>!(0,In.existsSync)(vr.default.join(r,...o.split("/"),"package.json")));if(t.includes("zod")&&!n.includes("zod")){let o=(0,Kb.createRequire)(vr.default.join(r,"noop.js")),s=Bb(vr.default.join(r,"zod"));for(let i of yI)try{let a=o.resolve(i,{paths:[r]});SI(Bb(a),s)||n.push(i)}catch{n.push(i)}}return n}function Jb(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 gH=Jb("CLAUDE_MEM_HEALTH_TIMEOUT_MS",Lt(ye.HEALTH_CHECK),{min:500,max:3e5}),_H=Jb("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",Lt(ye.HOOK_READINESS_WAIT),{min:0,max:3e5});var EI={min:500,max:3e5},yH={min:500,max:ye.SESSION_INIT_REQUEST_MAX};function Xb(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 bI(e){return Xb()?{...e,verbose:!0}:e}function wI(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 vI(e,t,r){let n=typeof t.method=="string"?t.method:"GET",o=wI(r),s=JSON.stringify(o);g.warn("SYSTEM","Worker IPC fetch failed",{url:e,method:n},s),tr(`[claude-mem] fetch verbose: ${n} ${e} ${s}
|
|
87
87
|
`)}async function ef(e,t={}){let r=bI(t);try{return await fetch(e,r)}catch(n){throw Xb()&&vI(e,t,n),n}}async function tf(e,t={},r){try{return await ef(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 kI(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 rf(e,t,r){let n=kI(r,t.signal),o;try{o=await ef(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 TI(e,t,r){let n=await rf(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 va=null,ka=null,Ta=null,Pa=null;function PI(){return Se.default.join(Me.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function nf(){return Ta!==null||(Ta=Me.loadFromFile(PI())),Ta}function Vb(e,t){if(!e)return null;let r=parseInt(e,10);return Number.isFinite(r)&&r>=t.min&&r<=t.max?r:null}function RI(e,t,r){let n=process.env[e];if(n!==void 0){let i=Vb(n,r);return i!==null?i:(g.warn("SYSTEM",`Invalid ${e}, using default`,{value:n,min:r.min,max:r.max}),t)}let o=nf()[e],s=Vb(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 of(){if(va!==null)return va;let e=nf();return va=parseInt(e.CLAUDE_MEM_WORKER_PORT,10),va}function xI(){return ka!==null||(ka=nf().CLAUDE_MEM_WORKER_HOST),ka}function AI(){return Pa!==null||(Pa=RI("CLAUDE_MEM_API_TIMEOUT_MS",Lt(ye.API_REQUEST),EI)),Pa}function sf(e){return`http://${yd(xI())}:${of()}${e}`}function Ra(e,t={}){let r=t.method??"GET",n=sf(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 TI(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?tf(n,o,s):ef(n,o)}function Qb(e){let t=(0,Ze.existsSync)(Se.default.join(e,"plugin","scripts"))?Se.default.join(e,"plugin"):e;return Se.default.join(t,"scripts","worker-service.cjs")}function MI(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 OI(e=Se.default.join(Se.default.dirname(Se.default.dirname(ps)),"cache","thedotmack","claude-mem")){try{return(0,Ze.readdirSync)(e).filter(t=>/^\d/.test(t)).map(t=>Se.default.join(e,t)).filter(t=>{try{if(!(0,Ze.statSync)(t).isDirectory())return!1}catch{return!1}return!(0,Ze.existsSync)(Se.default.join(t,".orphaned_at"))}).map(t=>({scriptPath:Qb(t),version:Se.default.basename(t)}))}catch{return[]}}function Yb(e){try{let t=JSON.parse((0,Ze.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 CI(){return{cacheRoot:Se.default.join(Se.default.dirname(Se.default.dirname(ps)),"cache","thedotmack","claude-mem"),marketplaceRoot:ps,cwd:process.cwd()}}function $I(e=CI()){let t=process.env.CLAUDE_MEM_WORKER_SCRIPT_PATH?.trim();if(t){if((0,Ze.existsSync)(t))return{scriptPath:t,version:null};g.debug("SYSTEM","Ignoring missing CLAUDE_MEM_WORKER_SCRIPT_PATH override",{override:t})}let r=[...OI(e.cacheRoot),{scriptPath:Qb(Se.default.join(e.marketplaceRoot,"plugin")),version:Yb(Se.default.join(e.marketplaceRoot,"package.json"))},{scriptPath:Se.default.join(e.cwd,"plugin","scripts","worker-service.cjs"),version:Yb(Se.default.join(e.cwd,"package.json"))}];return NI(r)}function II(e){return Se.default.dirname(Se.default.dirname(e))}function DI(e){return Gb(II(e.scriptPath)).length===0}function NI(e,t=DI){let r=e.filter(n=>(0,Ze.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:MI(n.version,o.version)),r.find(t)??r[0])}function ew(){return $I()?.scriptPath??null}var LI=1e3;var zI=5e3,SH=zI+LI;var Kr=nt(require("path"),1),we=require("fs");Y();var nw=120*1e3;function af(){return Kr.default.join(Me.get("CLAUDE_MEM_DATA_DIR"),".worker-start-attempted")}function UI(){if(process.platform!=="win32")return null;let e=af();if(!(0,we.existsSync)(e))return null;try{let t=(0,we.statSync)(e).mtimeMs;return Date.now()-t>=nw?null:(0,we.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 tw(e){if(process.platform==="win32")try{let t=af();(0,we.mkdirSync)(Kr.default.dirname(t),{recursive:!0}),(0,we.writeFileSync)(t,e,"utf-8")}catch{}}function os(){if(process.platform==="win32")try{let e=af();(0,we.existsSync)(e)&&(0,we.unlinkSync)(e)}catch{}}async function rw(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(`
|
|
@@ -280,7 +280,7 @@ ${l}`}).join(`
|
|
|
280
280
|
${c}`}Y();var iD=new Set([".js",".jsx",".ts",".tsx",".mjs",".cjs",".mts",".cts",".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"]),aD=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),cD=512*1024;async function*vw(e,t,r=20){if(r<=0)return;let n;try{n=await(0,zn.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!=="."||aD.has(o.name))continue;let s=(0,er.join)(e,o.name);if(o.isDirectory())yield*vw(s,t,r-1);else if(o.isFile()){let i=o.name.slice(o.name.lastIndexOf("."));iD.has(i.toLowerCase())&&(yield s)}}}async function uD(e){try{let t=await(0,zn.stat)(e);if(t.size>cD||t.size===0)return null;let r=await(0,zn.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 kw(e,t,r={}){let n=r.maxResults||20,o=t.toLowerCase(),s=o.split(/[\s_\-./]+/).filter(E=>E.length>0),i=[];for await(let E of vw(e,e,20)){if(r.filePattern&&!(0,er.relative)(e,E).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let y=await uD(E);y&&i.push({absolutePath:E,relativePath:(0,er.relative)(e,E),content:y})}let a=Sw(i),c=[],u=[],l=new Map,d=0;for(let[E,y]of a){d+=dD(y);let k=Ut(E.toLowerCase(),s)>0,T=[],P=(D,R)=>{for(let C of D){let X=Ma(C.name,R,y.language,C.kind);if(C.kind==="namespace"){P(C.children??[],X);continue}let ue=0,ze="",Vr=X.includes("#")?X.lastIndexOf("#"):X.lastIndexOf("."),jt=X.slice(0,Vr+1).toLowerCase(),ls=y.language==="ruby"&&C.kind==="method"&&Vr>=0&&o.startsWith(jt)&&o.length>jt.length?Ut(X.toLowerCase(),[o]):0,ee=y.language==="ruby"&&/[#.]/.test(o),Ce=ee?C.kind==="method"?ls:Ut(X.toLowerCase(),[o]):Ut(C.name.toLowerCase(),s),jn=y.language==="go"&&C.kind==="method"?lD(X.toLowerCase(),o,s):Ce||(X.toLowerCase()===o?10:0);jn>0&&(ue+=jn*3,ze="name match");let Tr=!ee||Ce>0;if(Tr&&C.signature.toLowerCase().includes(o)&&(ue+=2,ze=ze?`${ze} + signature`:"signature match"),Tr&&C.jsdoc&&C.jsdoc.toLowerCase().includes(o)&&(ue+=1,ze=ze?`${ze} + jsdoc`:"jsdoc match"),ue>0){k=!0;let bf={filePath:E,symbolName:X,kind:C.kind,signature:C.signature,jsdoc:C.jsdoc,lineStart:C.lineStart,lineEnd:C.lineEnd,matchReason:ze};T.push(bf),l.set(bf,ue)}C.children&&P(C.children,X)}};P(y.symbols),k&&(c.push(y),u.push(...T))}let f=E=>Ut(E.symbolName.toLowerCase(),s);u.sort((E,y)=>l.get(y)-l.get(E)||f(y)-f(E));let p=u.slice(0,n),m=new Set(p.map(E=>E.filePath)),h=c.filter(E=>m.has(E.filePath)).slice(0,n),_=h.reduce((E,y)=>E+y.foldedTokenEstimate,0),S=s.length===0?[]:[...a.values()].filter(E=>{let y=E.filePath.toLowerCase();return!m.has(E.filePath)&&s.every(v=>y.includes(v))}).map(E=>({file:E,nameScore:Ut((0,er.basename)(E.filePath,(0,er.extname)(E.filePath)).toLowerCase(),s)})).sort((E,y)=>y.nameScore-E.nameScore).slice(0,n).map(({file:E})=>({filePath:E.filePath,language:E.language,totalLines:E.totalLines,foldedTokenEstimate:E.foldedTokenEstimate}));return{foldedFiles:h,matchingSymbols:p,matchingFiles:S,totalFilesScanned:i.length,totalSymbolsFound:d,tokenEstimate:_}}function lD(e,t,r){let n=e.slice(e.lastIndexOf(".")+1);if(!t.includes("."))return Ut(n,r);let o=t.slice(t.lastIndexOf(".")+1);if(!o)return e.startsWith(t)?20:0;let s=Ut(n,[o]);return s===0?0:e===t?s+20:s+(e.startsWith(t)?10:0)}function dD(e){let t=r=>r.reduce((n,o)=>n+1+(o.children?t(o.children):0),0);return t(e.symbols)}function Tw(e,t){let r=[],n=(o,s,i="s")=>`${o} ${s}${o===1?"":i}`;if(r.push(`\u{1F50D} Smart Search: "${t}"`),r.push(` Scanned ${e.totalFilesScanned} files, found ${e.totalSymbolsFound} symbols`),r.push(` ${n(e.matchingSymbols.length,"symbol match","es")}; ${n(e.foldedFiles.length,"matched file")} (~${e.tokenEstimate} tokens for folded view); ${n(e.matchingFiles.length,"file")} matched by path only`),r.push(""),e.matchingSymbols.length===0&&e.matchingFiles.length===0)return r.push(" No matching symbols or files found."),r.join(`
|
|
281
281
|
`);e.matchingSymbols.length>0&&(r.push("\u2500\u2500 Matching Symbols \u2500\u2500"),r.push(""));for(let o of e.matchingSymbols){if(r.push(` ${o.kind} ${o.symbolName} (${o.filePath}:${o.lineStart+1})`),r.push(` ${o.signature}`),o.jsdoc){let s=o.jsdoc.split(`
|
|
282
282
|
`).find(i=>i.replace(/^[\s*/]+/,"").trim().length>0);s&&r.push(` \u{1F4AC} ${s.replace(/^[\s*/]+/,"").trim()}`)}r.push("")}e.foldedFiles.length>0&&(r.push("\u2500\u2500 Folded File Views \u2500\u2500"),r.push(""));for(let o of e.foldedFiles)r.push(Ln(o)),r.push("");if(e.matchingFiles.length>0){r.push("\u2500\u2500 Matching Files \u2500\u2500"),r.push("");for(let o of e.matchingFiles)r.push(` ${o.filePath} (${o.language}, ${o.totalLines} lines, ~${o.foldedTokenEstimate} tokens folded) \u2014 smart_outline to expand`);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(`
|
|
283
|
-
`)}var gf=require("node:fs/promises"),_f=require("node:os"),Gr=require("node:path");function fD(e){return e==="~"?(0,_f.homedir)():e.startsWith("~/")||e.startsWith("~\\")?(0,Gr.join)((0,_f.homedir)(),e.slice(2)):e}async function Oa(e,t=process.cwd()){if(typeof e!="string"||e.trim().length===0)throw new Error("file_path is required");let r=await(0,gf.realpath)((0,Gr.resolve)(t)),n=(0,Gr.resolve)(r,fD(e)),o;try{o=await(0,gf.realpath)(n)}catch{o=n}if(o!==r&&!o.startsWith(r+Gr.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 yf=require("node:fs/promises"),Da=require("node:fs"),kr=require("node:path"),Lw=require("node:os"),zw=require("node:url");var Pw="claude";function pD(e){return e.trim().toLowerCase().replace(/\s+/g,"-")}function Ca(e){if(!e)return Pw;let t=pD(e);return t?t==="transcript"||t.includes("codex")?"codex":t.includes("cursor")?"cursor":t.includes("claude")?"claude":t.includes("kimi")?"kimi":t==="pi-mono"?"pi":t==="agy"||t==="antigravity"||t.startsWith("antigravity-")?"antigravity-cli":t:Pw}var mD=Lt(ye.API_REQUEST),yt=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)}},Ia=class{baseUrl;apiKey;timeoutMs;constructor(t){this.baseUrl=hD(t.serverBaseUrl),this.apiKey=t.apiKey,this.timeoutMs=t.timeoutMs??mD}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 yt("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=$a(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 yt("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:$a(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:$a(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:$a(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{}}}async request(t,r,n,o={}){if(!this.apiKey||!this.apiKey.trim())throw new yt("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 tf(s,i,c)}catch(l){let d=l instanceof Error?l.message:String(l),f=/timed out|timeout/i.test(d);throw new yt(f?"timeout":"transport",`Server ${t} ${r} failed: ${d}`,{cause:l})}if(!a.ok){let l=await a.text().catch(()=>"");throw new yt("http_error",`Server ${t} ${r} returned ${a.status}: ${gD(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 yt("invalid_response",`Server ${t} ${r} returned non-JSON response`,{cause:d})}}};function Rw(e){return e instanceof yt}function hD(e){return e.replace(/\/+$/,"")}function $a(e){return typeof e=="string"?Ca(e):null}function gD(e,t){return e.length<=t?e:`${e.slice(0,t)}\u2026`}Y();function ss(){let t=(sa().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return t==="server"||t==="server-beta"?"server":"worker"}function xw(){let e=sa(),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 Ia(s),projectId:o,serverBaseUrl:r}}Y();var Aw=["observation_add","observation_record_event","observation_search","observation_context","observation_generation_status","memory_add","memory_search","memory_context"],_D=new Set(Aw);function Mw(e,t){return t==="server"?[...e]:(g.debug("SYSTEM","Filtering server-beta-only MCP tools from worker runtime advertisement",{runtime:t,hiddenToolCount:Aw.length}),e.filter(r=>!_D.has(r.name)))}function Ow(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 yD=3e4,SD=15*6e4,ED={idleTimeoutMs:yD,absoluteCapMs:SD},bD=["result","error"];async function Cw(e){let t=new TextDecoder,r="";for await(let n of e)r+=t.decode(n,{stream:!0});return r+t.decode()}async function $w(e,t,r=ED){let n=await rf(sf(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 Cw(n.chunks)}`);if(!(n.headers.get("content-type")??"").includes("text/event-stream"))return JSON.parse(await Cw(n.chunks));for await(let s of hd(n.chunks,{terminalEventNames:bD})){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`)}async function Iw(e,t){try{return await e()}catch(r){if(!Bd(r)||!await t())throw r;return await e()}}var WD={},wD="13.34.1";console.log=(...e)=>{g.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:e})};var Dw=null;function vD(){return Dw??=wb(process.cwd()),Dw}var Uw=!1,jw=(()=>{if(typeof __CM_DIRNAME__<"u")return __CM_DIRNAME__;try{return(0,kr.dirname)((0,zw.fileURLToPath)(WD.url))}catch(e){return Uw=!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()}})(),Sf=ew()??(0,kr.resolve)(jw,"worker-service.cjs");function kD(){Uw&&((0,Da.existsSync)(Sf)||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:Sf,mcpServerDir:jw}))}async function ct(e,t={}){g.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:e});try{return await Iw(()=>TD(e,t),PD)}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(e,t){if(t.streamCorpusProgress&&t.body){let n=await $w(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 Ra(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 Ra(`${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()}async function PD(){return ss()==="server"?!1:qw()}async function RD(){try{return(await Ra("/api/health")).ok}catch(e){return g.debug("SYSTEM","Worker health check failed",{},e instanceof Error?e:new Error(String(e))),!1}}function Fw(){if(ss()!=="server")return null;let t=xw();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 xD(e){return Rw(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 Un(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function as(e){let t=Fw();if(!t)throw new yt("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 yt("missing_api_key",`${e}: ${t.reason}`);return t}function cs(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),xD(n)}}}var AD=cs("observation_add",async e=>{let t=as("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 Un(o)});function La(e){return typeof e=="string"?Ca(e):null}var MD=cs("observation_record_event",async e=>{let t=as("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:La(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{},...e.generate!==void 0?{generate:e.generate}:{}},o=await t.client.recordEvent(n);return Un(o)}),OD=cs("observation_search",async e=>{let t=as("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:La(e.platformSource)}:{}},o=await t.client.searchObservations(n);return Un(o)}),CD=cs("observation_context",async e=>{let t=as("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:La(e.platformSource)}:{}},s=await t.client.contextObservations(o);return Un(s)});function $D(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 ID(e){let t=$D(e);return t.length===0?{content:[{type:"text",text:'session_start_context: "project" or "projects" is required'}],isError:!0}:ct("/api/context/inject",{query:{projects:t.join(","),...e.platformSource!==void 0?{platformSource:La(e.platformSource)}:{},...e.full!==void 0?{full:e.full}:{},...e.colors!==void 0?{colors:e.colors}:{}},text:!0})}var DD=cs("observation_generation_status",async e=>{let t=as("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 Un(n)});async function qw(){if(await RD())return!0;g.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),kD();try{let e=of(),t=await ow(e,Sf);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 rt={readOnlyHint:!0},Ww=[{name:"important_workflow",description:`LAYERED WORKFLOW (ALWAYS FOLLOW):
|
|
283
|
+
`)}var gf=require("node:fs/promises"),_f=require("node:os"),Gr=require("node:path");function fD(e){return e==="~"?(0,_f.homedir)():e.startsWith("~/")||e.startsWith("~\\")?(0,Gr.join)((0,_f.homedir)(),e.slice(2)):e}async function Oa(e,t=process.cwd()){if(typeof e!="string"||e.trim().length===0)throw new Error("file_path is required");let r=await(0,gf.realpath)((0,Gr.resolve)(t)),n=(0,Gr.resolve)(r,fD(e)),o;try{o=await(0,gf.realpath)(n)}catch{o=n}if(o!==r&&!o.startsWith(r+Gr.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 yf=require("node:fs/promises"),Da=require("node:fs"),kr=require("node:path"),Lw=require("node:os"),zw=require("node:url");var Pw="claude";function pD(e){return e.trim().toLowerCase().replace(/\s+/g,"-")}function Ca(e){if(!e)return Pw;let t=pD(e);return t?t==="transcript"||t.includes("codex")?"codex":t.includes("cursor")?"cursor":t.includes("claude")?"claude":t.includes("kimi")?"kimi":t==="pi-mono"?"pi":t==="agy"||t==="antigravity"||t.startsWith("antigravity-")?"antigravity-cli":t:Pw}var mD=Lt(ye.API_REQUEST),yt=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)}},Ia=class{baseUrl;apiKey;timeoutMs;constructor(t){this.baseUrl=hD(t.serverBaseUrl),this.apiKey=t.apiKey,this.timeoutMs=t.timeoutMs??mD}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 yt("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=$a(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 yt("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:$a(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:$a(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:$a(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{}}}async request(t,r,n,o={}){if(!this.apiKey||!this.apiKey.trim())throw new yt("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 tf(s,i,c)}catch(l){let d=l instanceof Error?l.message:String(l),f=/timed out|timeout/i.test(d);throw new yt(f?"timeout":"transport",`Server ${t} ${r} failed: ${d}`,{cause:l})}if(!a.ok){let l=await a.text().catch(()=>"");throw new yt("http_error",`Server ${t} ${r} returned ${a.status}: ${gD(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 yt("invalid_response",`Server ${t} ${r} returned non-JSON response`,{cause:d})}}};function Rw(e){return e instanceof yt}function hD(e){return e.replace(/\/+$/,"")}function $a(e){return typeof e=="string"?Ca(e):null}function gD(e,t){return e.length<=t?e:`${e.slice(0,t)}\u2026`}Y();function ss(){let t=(sa().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return t==="server"||t==="server-beta"?"server":"worker"}function xw(){let e=sa(),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 Ia(s),projectId:o,serverBaseUrl:r}}Y();var Aw=["observation_add","observation_record_event","observation_search","observation_context","observation_generation_status","memory_add","memory_search","memory_context"],_D=new Set(Aw);function Mw(e,t){return t==="server"?[...e]:(g.debug("SYSTEM","Filtering server-beta-only MCP tools from worker runtime advertisement",{runtime:t,hiddenToolCount:Aw.length}),e.filter(r=>!_D.has(r.name)))}function Ow(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 yD=3e4,SD=15*6e4,ED={idleTimeoutMs:yD,absoluteCapMs:SD},bD=["result","error"];async function Cw(e){let t=new TextDecoder,r="";for await(let n of e)r+=t.decode(n,{stream:!0});return r+t.decode()}async function $w(e,t,r=ED){let n=await rf(sf(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 Cw(n.chunks)}`);if(!(n.headers.get("content-type")??"").includes("text/event-stream"))return JSON.parse(await Cw(n.chunks));for await(let s of hd(n.chunks,{terminalEventNames:bD})){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`)}async function Iw(e,t){try{return await e()}catch(r){if(!Bd(r)||!await t())throw r;return await e()}}var WD={},wD="13.34.2";console.log=(...e)=>{g.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:e})};var Dw=null;function vD(){return Dw??=wb(process.cwd()),Dw}var Uw=!1,jw=(()=>{if(typeof __CM_DIRNAME__<"u")return __CM_DIRNAME__;try{return(0,kr.dirname)((0,zw.fileURLToPath)(WD.url))}catch(e){return Uw=!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()}})(),Sf=ew()??(0,kr.resolve)(jw,"worker-service.cjs");function kD(){Uw&&((0,Da.existsSync)(Sf)||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:Sf,mcpServerDir:jw}))}async function ct(e,t={}){g.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:e});try{return await Iw(()=>TD(e,t),PD)}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(e,t){if(t.streamCorpusProgress&&t.body){let n=await $w(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 Ra(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 Ra(`${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()}async function PD(){return ss()==="server"?!1:qw()}async function RD(){try{return(await Ra("/api/health")).ok}catch(e){return g.debug("SYSTEM","Worker health check failed",{},e instanceof Error?e:new Error(String(e))),!1}}function Fw(){if(ss()!=="server")return null;let t=xw();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 xD(e){return Rw(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 Un(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function as(e){let t=Fw();if(!t)throw new yt("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 yt("missing_api_key",`${e}: ${t.reason}`);return t}function cs(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),xD(n)}}}var AD=cs("observation_add",async e=>{let t=as("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 Un(o)});function La(e){return typeof e=="string"?Ca(e):null}var MD=cs("observation_record_event",async e=>{let t=as("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:La(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{},...e.generate!==void 0?{generate:e.generate}:{}},o=await t.client.recordEvent(n);return Un(o)}),OD=cs("observation_search",async e=>{let t=as("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:La(e.platformSource)}:{}},o=await t.client.searchObservations(n);return Un(o)}),CD=cs("observation_context",async e=>{let t=as("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:La(e.platformSource)}:{}},s=await t.client.contextObservations(o);return Un(s)});function $D(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 ID(e){let t=$D(e);return t.length===0?{content:[{type:"text",text:'session_start_context: "project" or "projects" is required'}],isError:!0}:ct("/api/context/inject",{query:{projects:t.join(","),...e.platformSource!==void 0?{platformSource:La(e.platformSource)}:{},...e.full!==void 0?{full:e.full}:{},...e.colors!==void 0?{colors:e.colors}:{}},text:!0})}var DD=cs("observation_generation_status",async e=>{let t=as("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 Un(n)});async function qw(){if(await RD())return!0;g.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),kD();try{let e=of(),t=await ow(e,Sf);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 rt={readOnlyHint:!0},Ww=[{name:"important_workflow",description:`LAYERED WORKFLOW (ALWAYS FOLLOW):
|
|
284
284
|
1. search(query) \u2192 Get index with IDs (~50-100 tokens/result)
|
|
285
285
|
2. timeline(anchor=ID) \u2192 Get context around interesting results
|
|
286
286
|
3. get_observations([IDs]) \u2192 Fetch full details ONLY for filtered IDs
|