claude-mem 14.0.0 → 14.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/.qoder-plugin/plugin.json +1 -1
- package/README.md +1 -1
- package/dist/npx-cli/index.js +2 -2
- package/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/.qoder-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 +248 -248
- package/plugin/scripts/worker-service.cjs.map +2 -2
|
@@ -23,7 +23,7 @@ ${p.stack??""}
|
|
|
23
23
|
`),...u!==void 0?{id:u}:{}}:null;return c=null,u=void 0,l=null,a=0,w}if(p[0]===x0)return t.onActivity?.(),null;m(p.length),a+=p.length;let g=o.decode(p),_=g.indexOf(":"),E=_===-1?g:g.slice(0,_),v=_===-1?"":g.slice(_+1);return v.startsWith(" ")&&(v=v.slice(1)),E==="event"?c=v:E==="data"?(l??=[]).push(v):E==="id"&&(u=v),null};for await(let p of I0(e)){let g=0;for(let _=0;_<p.length;_++){let E=p[_];if(s&&(s=!1,E===NS)){g=_+1;continue}if(E!==DS&&E!==NS)continue;r.push(p.subarray(g,_));let v=T0(r,i+(_-g));r=[],i=0;let y=f(v);y&&(t.terminalEventNames?.includes(y.event)&&(d=!0),yield y),s=E===DS,g=_+1}if(g<p.length){let _=p.slice(g);r.push(_),i+=_.length,m(i)}}if(t.terminalEventNames&&t.terminalEventNames.length>0&&!d)throw new tf(t.terminalEventNames)}var kn=require("fs"),Hr=require("path"),Li=require("os");er();G();function LS(e){try{return new URL(e).hostname.toLowerCase()==="openrouter.ai"}catch{return!1}}Za();var A0="security_alert",O0="sync-hub.black-pond-afbb.workers.dev",P0="ziczmqtpmaxbornfghye.supabase.co",R0="https://sync.cmem.ai",C0=new Set(["xiaomi/mimo-v2-flash:free"]);function M0(e){return typeof e=="boolean"?String(e):e}function D0(e){let t=e.CLAUDE_MEM_OPENROUTER_MODEL;if(typeof t!="string"||!C0.has(t.trim()))return!1;let n=typeof e.CLAUDE_MEM_OPENROUTER_BASE_URL=="string"?e.CLAUDE_MEM_OPENROUTER_BASE_URL.trim():"";return n===""||LS(n)}var zS=18e4,US=[{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 FS(e,t){return(0,Hr.join)((0,Hr.dirname)(e),`.${(0,Hr.basename)(e)}.${t.markerTag}`)}function nf(e,t){try{(0,kn.writeFileSync)(FS(e,t),new Date().toISOString(),{encoding:"utf-8",mode:384})}catch{}}var jS=new Set;function N0(e){if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;try{let n=new URL(t).hostname;if(n===O0||n===P0)return R0}catch{return null}return null}var Oe=class{static DEFAULTS={CLAUDE_MEM_MEMORY_SEARCH_HOOK_ENABLED:"true",CLAUDE_MEM_MEMORY_INSTRUCTIONS_ENABLED:"true",CLAUDE_MEM_MEMORY_WATCH_ROOTS:"",CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_SESSION_START_INCLUDE_ALL_SOURCES:"false",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_WORKER_INGEST_TOKEN:"",CLAUDE_MEM_HOOK_SPOOL_TRANSPORT:"auto",CLAUDE_MEM_ALLOWED_ORIGINS:"",CLAUDE_MEM_PUBLIC_URL:"",CLAUDE_MEM_API_TIMEOUT_MS:String(pr(De.API_REQUEST)),CLAUDE_MEM_SESSION_INIT_TIMEOUT_MS:String(Qd()),CLAUDE_MEM_IDLE_EXIT_SEC:"0",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_SKIP_BASH_PATTERNS:"",CLAUDE_MEM_SKIP_SUBAGENT_OBSERVATIONS:"false",CLAUDE_MEM_SKIP_AGENT_TYPES:"",CLAUDE_MEM_CAPTURE_ADVISOR_CALLS:"false",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CODEX_MODEL:"",CLAUDE_MEM_CODEX_PATH:"codex",CLAUDE_MEM_CODEX_REASONING_EFFORT:"low",CLAUDE_MEM_CODEX_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_CODEX_OBSERVATION_BATCH_SIZE:"8",CLAUDE_MEM_CODEX_OBSERVATION_BATCH_MAX_CHARS:"32000",CLAUDE_MEM_CLAUDE_OBSERVATION_BATCH_SIZE:"1",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_API_KEYS:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-flash-latest",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_API_KEYS:"",CLAUDE_MEM_OPENROUTER_MODEL:"cohere/north-mini-code:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_TEMPERATURE:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_EXTRA_BODY:"",CLAUDE_MEM_OPENROUTER_REASONING_EFFORT:"",CLAUDE_MEM_OPENAI_COMPAT_PRESET:"",CLAUDE_MEM_OPENAI_COMPAT_API_KEY:"",CLAUDE_MEM_OPENAI_COMPAT_API_KEYS:"",CLAUDE_MEM_OPENAI_COMPAT_BASE_URL:"",CLAUDE_MEM_OPENAI_COMPAT_MODEL:"",CLAUDE_MEM_QUOTA_FALLBACK_PROVIDER:"claude",CLAUDE_MEM_QUOTA_FALLBACK_MODEL:"",CLAUDE_MEM_QUOTA_THRESHOLD_FIVE_HOUR:"0.95",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY:"0.93",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY_OPUS:"0.93",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY_SONNET:"0.92",CLAUDE_MEM_QUOTA_THRESHOLD_OVERAGE:"0.95",CLAUDE_MEM_DATA_DIR:(0,Hr.join)((0,Li.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_CLAUDE_CONFIG_DIR:"",CLAUDE_MEM_OBSERVER_CLAUDE_CONFIG_DIR:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES:"",CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:"",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_MAIN_AGENT_ONLY:"true",CLAUDE_MEM_REINFORCE_ALPHA:"0",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_WORK_STATE_ENABLED:"true",CLAUDE_MEM_FILE_READ_GATE_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,Hr.join)((0,Li.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_CODEX_SUBAGENT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_OBSERVER_MAX_CONVERSATION_CHARS:"400000",CLAUDE_MEM_OBSERVER_THINKING:"disabled",CLAUDE_MEM_OBSERVER_CONTEXT_WINDOW:"",CLAUDE_MEM_OBSERVER_MAX_OUTPUT_TOKENS:"4096",CLAUDE_MEM_OBSERVE_BARE_PROMPTS:"false",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_REDACT_ENABLED:"false",CLAUDE_MEM_REDACT_DISABLED_BUILTINS:"",CLAUDE_MEM_REDACT_CUSTOM_PATTERNS:"[]",CLAUDE_MEM_REDACT_LOG_MATCHES:"false",CLAUDE_MEM_REDACT_GENERIC_ENABLED:"false",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_PROJECT_ENVIRONMENTS:"[]",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_SEMANTIC_INJECT_FORMAT:"narrative",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_CHROMA_MUTATION_TIMEOUT_MS:"600000",CLAUDE_MEM_CHROMA_MAX_PENDING_MUTATIONS:"5000",CLAUDE_MEM_CHROMA_EMBEDDING_FUNCTION:"default",CLAUDE_MEM_CHROMA_UVX_PATH:"",CLAUDE_MEM_SEARCH_RECENCY_DAYS:"90",CLAUDE_MEM_CLOUD_SYNC_TOKEN:"",CLAUDE_MEM_CLOUD_SYNC_USER_ID:"",CLAUDE_MEM_CLOUD_SYNC_HUB_URL:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_ID:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_NAME:(0,Li.hostname)(),CLAUDE_MEM_CLOUD_SYNC_WS:"true",CLAUDE_MEM_CLOUD_SYNC_CONTENT_BATCH_SIZE:"40",CLAUDE_MEM_CLOUD_SYNC_REQUEST_TIMEOUT_MS:"90000",CLAUDE_MEM_TEAMBRAIN_URL:"",CLAUDE_MEM_TEAMBRAIN_TEAM_ID:"",CLAUDE_MEM_LLM_TIMEOUT_MS:String(zS),CLAUDE_MEM_FIELD_OPTIMIZE_TIMEOUT_MS:String(zS),CLAUDE_MEM_LLM_STREAM_IDLE_TIMEOUT_MS:"90000",CLAUDE_MEM_WORKER_HEARTBEAT_STALE_MS:"120000",CLAUDE_MEM_TV_TOKEN:"",CLAUDE_MEM_PRO_TRIAL_EMAIL:"",CLAUDE_MEM_PRO_TRIAL_AT:"",CLAUDE_MEM_PRO_TRIAL_STATE:"",CLAUDE_MEM_PRO_TRIAL_ENDS_AT:"",CLAUDE_MEM_PRO_PLAN:"",CLAUDE_MEM_PRO_FALLBACK_AT:"",CLAUDE_MEM_PRO_FALLBACK_MESSAGE:"",CLAUDE_MEM_PRO_FALLBACK_ACTION:"",CLAUDE_MEM_PRO_FALLBACK_URL:"",CLAUDE_MEM_PRO_MEMORY_KEY:"",CLAUDE_MEM_PRO_MEMORY_BASE_URL:"",CLAUDE_MEM_PRO_MEMORY_MODEL:"",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_WRAPUPS_ENABLED:"true",CLAUDE_MEM_TELEGRAM_OBSERVATION_ALERTS_ENABLED:"false",CLAUDE_MEM_TELEGRAM_WRAPUP_ROUTES:"{}",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert,sensitive",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_AWARENESS_ENABLED:"true",CLAUDE_MEM_GROK_BOT_AWARENESS_AGENT_IDS:"521e962d-2ec3-4488-bfbc-54d5209ce118,95601360-61f7-4fd9-bb3a-2c976b2b85c0",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_WEBHOOK_URL:"",CLAUDE_MEM_GROK_BOT_WEBHOOK_SECRET:"",CLAUDE_MEM_GROK_BOT_INJECT_ENABLED:"true",CLAUDE_MEM_GROK_BOT_INJECT_AGENT_IDS:"*",CLAUDE_MEM_GROK_BOT_INJECT_TIER:"episode",CLAUDE_MEM_GROK_BOT_INJECT_WINDOW:"80",CLAUDE_MEM_GROK_BOT_INJECT_FALLBACK:"house",CLAUDE_MEM_GROK_BOT_INJECT_PLATFORM_SOURCE:"",CLAUDE_MEM_GROK_BOT_INJECT_PROJECTS_BY_AGENT:"",CLAUDE_MEM_GROK_BOT_INJECT_MAX_LINE_CHARS:"160",CLAUDE_MEM_GROK_BOT_INJECT_DEBOUNCE_MS:"1500",CLAUDE_MEM_GROK_BOT_INJECT_STANDING_LINE:"",CLAUDE_MEM_CCS_ALIGN_ENABLED:"true",CLAUDE_MEM_CCS_ALIGN_VIEWER_IDS:"ccs-align",CLAUDE_MEM_CCS_ALIGN_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_CCS_ALIGN_PATCH_SHADOWS:"false",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:"",CLAUDE_MEM_DEDUP_ENABLED:"false",CLAUDE_MEM_DEDUP_COSINE_THRESHOLD:"0.80",CLAUDE_MEM_DEDUP_IDF_VETO_DF:"10",CLAUDE_MEM_DEDUP_MIN_SHARED_TOKENS:"2",CLAUDE_MEM_DEDUP_MIN_PROJECT_DOCS:"10",CLAUDE_MEM_DEDUP_MAX_SCAN:"2000",CLAUDE_MEM_DEDUP_MAX_BACKFILL_ROWS:"50000",CLAUDE_MEM_TOOL_USES_RETENTION_DAYS:"0",CLAUDE_MEM_WORKER_AUTOSTART:"true",CLAUDE_MEM_PROJECT_NAME_SOURCE:"path"};static getAllDefaults(){return{...this.DEFAULTS}}static get(t){let n=process.env[t]??this.DEFAULTS[t];return t==="CLAUDE_MEM_WORKER_HOST"?this.normalizeWorkerHost(n):n}static normalizeWorkerHost(t){return t==="localhost"?"127.0.0.1":t}static finalizeSettings(t,n){let o=n?this.applyEnvOverrides(t):t;return o.CLAUDE_MEM_WORKER_HOST=this.normalizeWorkerHost(o.CLAUDE_MEM_WORKER_HOST),o}static getInt(t){let n=this.get(t);return parseInt(n,10)}static applyEnvOverrides(t){let n={...t};for(let o of Object.keys(this.DEFAULTS))process.env[o]!==void 0&&(n[o]=process.env[o]);return n}static loadFromFile(t,n=!0,o={}){try{if(!(0,kn.existsSync)(t)){let m=this.getAllDefaults();if(!o.readOnly)try{ft(t,m,{mode:384});for(let f of US)nf(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(m,n)}let r=(0,kn.readFileSync)(t,"utf-8"),i=Ci(r),s=uo(i),a=s!==i,c=bS(i),u=a&&Object.keys(c).some(m=>m!=="env");if(a&&!u&&!o.readOnly)try{ft(t,s,{mode:384}),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",t)}catch(m){console.warn("[SETTINGS] Failed to auto-migrate settings file:",t,m instanceof Error?m.message:String(m))}if(s.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES===A0&&(s={...s,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES},!o.readOnly))try{ft(t,u?{...c,env:s}:s,{mode:384}),console.warn("[SETTINGS] Migrated Telegram trigger types off the legacy default:",t)}catch(m){console.warn("[SETTINGS] Failed to migrate Telegram trigger types:",t,m instanceof Error?m.message:String(m))}if(D0(s)){let m=String(s.CLAUDE_MEM_OPENROUTER_MODEL).trim();if(s={...s,CLAUDE_MEM_OPENROUTER_MODEL:this.DEFAULTS.CLAUDE_MEM_OPENROUTER_MODEL},!o.readOnly)try{ft(t,u?{...c,env:s}:s,{mode:384}),console.warn(`[SETTINGS] Migrated OpenRouter model off the retired default ${m} 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 l=N0(s.CLAUDE_MEM_CLOUD_SYNC_HUB_URL);if(l!==null&&(s={...s,CLAUDE_MEM_CLOUD_SYNC_HUB_URL:l},!o.readOnly))try{ft(t,u?{...c,env:s}:s,{mode:384}),console.warn("[SETTINGS] Migrated cloud sync hub URL to",l,"from a retired hub host:",t)}catch(m){console.warn("[SETTINGS] Failed to migrate cloud sync hub URL:",t,m instanceof Error?m.message:String(m))}for(let m of US)if(!(0,kn.existsSync)(FS(t,m))){if(s[m.key]!==m.legacy){o.readOnly||nf(t,m);continue}if(s={...s,[m.key]:this.DEFAULTS[m.key]},!o.readOnly)try{ft(t,u?{...c,env:s}:s,{mode:384}),nf(t,m),console.warn(`[SETTINGS] Migrated ${m.key} off the old ${m.legacy}ms default to ${this.DEFAULTS[m.key]}ms:`,t)}catch(f){let p=`${m.key}\0${t}`;jS.has(p)||(jS.add(p),console.warn(`[SETTINGS] Failed to migrate ${m.key}; using the new default in memory (reported once per process):`,t,f instanceof Error?f.message:String(f)))}}let d={...this.DEFAULTS};for(let m of Object.keys(this.DEFAULTS))s[m]!==void 0&&(d[m]=M0(s[m]));return this.finalizeSettings(d,n)}catch(r){console.warn("[SETTINGS] Failed to load settings, using defaults:",t,r instanceof Error?r.message:String(r));let i=this.getAllDefaults();return this.finalizeSettings(i,n)}}};Me();Me();var Ja=null;function Ft(){return Ja!==null||(Ja=Oe.loadFromFile(tr)),Ja}function of(e){return(e.CLAUDE_MEM_WORKER_AUTOSTART??"true").trim().toLowerCase()==="false"}function zi(e){return e.startsWith("[")&&e.endsWith("]")?e:e.includes(":")?`[${e}]`:e}var In=require("fs");G();var sf=require("node:child_process");function af(e,t,n){return(0,sf.spawn)(e,t??[],{...n,windowsHide:!0})}var L0=new Set([".cmd",".bat"]),z0=new Set([".exe",".com"]),aH=new Set([...z0,...L0]);var xn=require("fs"),KS=Nt(require("path"),1);G();er();var U0=["CLAUDECODE_","CLAUDE_CODE_"],j0=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),F0=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"]),q0=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",...F0]);function gr(e=process.env){let t={};for(let[n,o]of Object.entries(e))if(o!==void 0){if(q0.has(n)){t[n]=o;continue}j0.has(n)||U0.some(r=>n.startsWith(r))||(t[n]=o)}return t}Me();var uf=require("child_process"),WS=require("fs");G();var W0=5e3,qS=new Map,cf=0;function BS(e,t,n){if(n.status!==0)return null;if(typeof n.stdout!="string")return h.warn("SYSTEM","captureProcessStartToken: start-token probe returned no stdout",{pid:t,source:e,status:n.status}),null;let o=n.stdout.trim();return o.length>0?o:null}function B0(e){cf+=1;let t=(0,uf.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:{...gr(process.env),LC_ALL:"C",LANG:"C"}});return BS("powershell-cim",e,t)}function H0(e,t=!1){if(!t){let o=qS.get(e);if(o&&(e===process.pid||Date.now()-o.capturedAtMs<W0))return o.token}let n=null;try{n=B0(e)}catch(o){h.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:e,error:o instanceof Error?o.message:String(o)}),n=null}return(n!==null||e!==process.pid)&&qS.set(e,{token:n,capturedAtMs:Date.now()}),n}function HS(e,t){if(!Number.isInteger(e)||e<=0)return null;if(process.platform==="linux"){cf+=1;try{let n=(0,WS.readFileSync)(`/proc/${e}/stat`,"utf-8"),o=n.lastIndexOf(") ");if(o<0)return null;let i=n.slice(o+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(n){return h.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:e,error:n instanceof Error?n.message:String(n)}),null}}if(process.platform==="win32")return H0(e,t);cf+=1;try{let n=(0,uf.spawnSync)("ps",["-p",String(e),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...gr(process.env),LC_ALL:"C",LANG:"C"}});return BS("ps-lstart",e,n)}catch(n){return h.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:e,error:n instanceof Error?n.message:String(n)}),null}}function hr(e){return HS(e,!1)}function rr(e,t){if(t===null)return!0;let n=HS(e,!0);return n===null?!0:n===t}var ZS=require("child_process"),Qa=require("fs"),VS=require("util");G();var lf=(0,VS.promisify)(ZS.execFile),Z0=128,V0=/not found|no running instance|no tasks/i,Ya=class extends Error{pid;constructor(t,n,o){super(n,o),this.name="ProcessTreeKillError",this.pid=t}};async function nr(e,t={}){let n=t.signalMode==="immediate",o=t.expectedStartToken!==void 0?t.expectedStartToken:hr(e),r=()=>rr(e,o);if(!r()){h.warn("PROCESS","Skipping tree-kill: root PID was reused since it was captured",{pid:e});return}if(h.debug("PROCESS",`Killing process tree rooted at PID ${e}`,{immediate:n}),process.platform==="win32"){try{await lf("taskkill",["/PID",String(e),"/T","/F"],{timeout:5e3,windowsHide:!0})}catch(i){let s=i.code,a=String(i.stderr??""),c=i instanceof Error?i.message:String(i);if(s===Z0||V0.test(`${a} ${c}`)){h.debug("PROCESS","taskkill reported the process was already gone",{pid:e});return}throw new Ya(e,`taskkill failed for PID ${e} (exit ${String(s)}): ${a.trim()||c}`,{cause:i})}return}try{let i=n?"SIGKILL":"SIGTERM",s=await Xa(e);for(let u of s){if(!rr(u.pid,u.startToken)){h.debug("PROCESS",`Skipping ${i}: descendant PID was reused since enumeration`,{pid:u.pid,rootPid:e});continue}try{process.kill(u.pid,i)}catch{}}if(r())try{process.kill(e,i)}catch(u){let l=u instanceof Error?u:new Error(String(u)),d=l.code;d!=="ESRCH"&&h.debug("PROCESS",`Failed to ${i} PID ${e}`,{code:d},l)}else h.warn("PROCESS","Skipping root signal: PID was reused during descendant enumeration",{pid:e,signal:i});n||await new Promise(u=>setTimeout(u,500));let a=r()?await Xa(e):[],c=new Map;for(let u of s)c.set(u.pid,u.startToken);for(let u of a)c.set(u.pid,u.startToken);for(let[u,l]of c){if(!rr(u,l)){h.debug("PROCESS","Skipping SIGKILL: descendant PID was reused since the scan",{pid:u,rootPid:e});continue}try{process.kill(u,"SIGKILL")}catch{}}if(!n&&r())try{process.kill(e,"SIGKILL")}catch{}}catch(i){throw new Ya(e,`tree-kill failed for PID ${e}: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}async function K0(){return process.platform==="win32"?Y0():process.platform==="linux"?G0():J0()}function G0(){let e=[],t;try{t=(0,Qa.readdirSync)("/proc")}catch(n){return h.warn("PROCESS","Cannot read /proc \u2014 tree-kill degrades to a single-PID kill",{error:n instanceof Error?n.message:String(n)}),e}for(let n of t){if(!/^\d+$/.test(n))continue;let o;try{o=(0,Qa.readFileSync)(`/proc/${n}/stat`,"utf-8")}catch{continue}let r=o.lastIndexOf(") ");if(r<0)continue;let i=o.slice(r+2).split(" "),s=Number.parseInt(i[1]??"",10),a=i[19];Number.isFinite(s)&&e.push({pid:Number.parseInt(n,10),ppid:s,startToken:a&&/^\d+$/.test(a)?a:null})}return e}async function J0(){let e;try{e=(await lf("ps",["-eo","pid=,ppid=,lstart="],{timeout:1e4,maxBuffer:33554432,env:{...process.env,LC_ALL:"C",LANG:"C"}})).stdout}catch(n){return h.warn("PROCESS","Cannot enumerate the process table \u2014 tree-kill degrades to a single-PID kill",{error:n instanceof Error?n.message:String(n)}),[]}let t=[];for(let n of e.split(`
|
|
24
24
|
`)){let o=n.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);if(!o)continue;let r=o[3].trim();t.push({pid:Number.parseInt(o[1],10),ppid:Number.parseInt(o[2],10),startToken:r.length>0?r:null})}return t}async function Y0(){let e;try{e=(await lf("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(n){return h.warn("PROCESS","Cannot enumerate the Windows process table \u2014 tree-kill degrades to a single-PID kill",{error:n instanceof Error?n.message:String(n)}),[]}let t=[];for(let n of e.split(/\r?\n/).slice(1)){let o=n.match(/^"(\d+)","(\d+)","(.*)"$/);if(!o)continue;let r=o[3].trim();t.push({pid:Number.parseInt(o[1],10),ppid:Number.parseInt(o[2],10),startToken:r.length>0?r:null})}return t}async function Xa(e){let t=await K0(),n=new Map;for(let s of t){let a=n.get(s.ppid);a?a.push(s):n.set(s.ppid,[s])}let o=new Set([e]),r=[],i=s=>{for(let a of n.get(s)??[])o.has(a.pid)||(o.add(a.pid),i(a.pid),r.push({pid:a.pid,startToken:a.startToken}))};return i(e),r}var Q0=5e3,eR=1e3,tR=qe.supervisorRegistry(),rR=null;function Le(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 n=t.code;return n==="EPERM"?!0:(h.debug("SYSTEM","PID check failed",{pid:e,code:n}),!1)}return h.warn("SYSTEM","PID check threw non-Error",{pid:e,error:String(t)}),!1}}async function ec(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(e.every(o=>!Le(o.pid)))return;await new Promise(o=>setTimeout(o,100))}}function GS(e){if(!e||!Le(e.pid))return!1;if(!e.startToken)return!0;let t=hr(e.pid);if(t===null)return!0;let n=t===e.startToken;return n||h.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:e.pid,stored:e.startToken,current:t}),n}var nR={platform:process.platform,readCommandLine:e=>(0,xn.readFileSync)(`/proc/${e}/cmdline`,"utf-8")};function tc(e,t=nR){if(!GS(e))return!1;if(e.startToken||t.platform!=="linux")return!0;let n;try{n=t.readCommandLine(e.pid)}catch(r){return h.debug("SYSTEM","Could not read the command line of a token-less worker PID; trusting the live PID",{pid:e.pid,error:r instanceof Error?r.message:String(r)}),!0}let o=n.split("\0").some(r=>KS.default.basename(r)==="worker-service.cjs");return o||h.debug("SYSTEM","Token-less worker PID now belongs to another program (PID reused)",{pid:e.pid}),o}function rc(e=qe.workerPid()){if(!(0,xn.existsSync)(e))return null;let t;try{t=JSON.parse((0,xn.readFileSync)(e,"utf-8"))}catch{return null}return t!==null&&tc(t)?t:null}var mf=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(t=tR){this.registryPath=t}initialize(){if(this.initialized)return;if(this.initialized=!0,!(0,xn.existsSync)(this.registryPath)){this.persist();return}try{let o=JSON.parse((0,xn.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[r,i]of Object.entries(o))this.entries.set(r,i)}catch(n){n instanceof Error?h.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},n):h.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(n)}),this.entries.clear()}let t=this.pruneDeadEntries();t>0&&h.info("SYSTEM","Removed dead processes from supervisor registry",{removed:t}),this.persist()}retainSupersededEntry(t,n){let o=this.entries.get(t);if(!o||o.pid===n||!Le(o.pid))return;let r=`${t}#superseded:${o.pid}`;this.entries.set(r,o);let i=this.runtimeProcesses.get(t);i&&(this.runtimeProcesses.set(r,i),this.runtimeProcesses.delete(t)),h.warn("SYSTEM","Registry id reused while the previous process was still alive; kept it for reaping",{id:t,supersededId:r,supersededPid:o.pid,incomingPid:n})}register(t,n,o){this.initialize(),this.retainSupersededEntry(t,n.pid),this.entries.set(t,n),o&&this.runtimeProcesses.set(t,o),this.persist()}unregister(t,n){this.initialize();let o=t,r=this.entries.get(o);n!==void 0&&r?.pid!==n&&(o=`${t}#superseded:${n}`,r=this.entries.get(o),r?.pid!==n)||r&&(this.entries.delete(o),this.runtimeProcesses.delete(o),this.persist(),r?.type==="sdk"&&ff())}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([t,n])=>({id:t,...n})).sort((t,n)=>{let o=Date.parse(t.startedAt),r=Date.parse(n.startedAt);return(Number.isNaN(o)?0:o)-(Number.isNaN(r)?0:r)})}getBySession(t){let n=String(t);return this.getAll().filter(o=>o.sessionId!==void 0&&String(o.sessionId)===n)}getRuntimeProcess(t){return this.runtimeProcesses.get(t)}pruneDeadEntries(){this.initialize();let t=0,n=0;for(let[o,r]of this.entries)Le(r.pid)||(this.entries.delete(o),this.runtimeProcesses.delete(o),t+=1,r.type==="sdk"&&(n+=1));t>0&&this.persist();for(let o=0;o<n;o+=1)ff();return t}async reapSession(t){this.initialize();let n=this.getBySession(t);if(n.length===0)return 0;let o=typeof t=="number"?t:Number(t)||void 0;h.info("SYSTEM",`Reaping ${n.length} process(es) for session ${t}`,{sessionId:o,pids:n.map(a=>a.pid)});let r=n.filter(a=>Le(a.pid)),i=new Map(r.map(a=>[a.pid,hr(a.pid)]));for(let a of r)try{process.platform==="win32"?await nr(a.pid,{expectedStartToken:i.get(a.pid)??null}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&h.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):h.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}await ec(r,Q0);let s=r.filter(a=>Le(a.pid));for(let a of s){h.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:o});let c=i.get(a.pid)??null;if(!rr(a.pid,c)){h.warn("SYSTEM","Skipping SIGKILL: session process PID was reused during the grace window",{pid:a.pid,sessionId:o});continue}try{process.platform==="win32"?await nr(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"&&h.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},u):h.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(u)})}}if(s.length>0){let a=Date.now()+eR;for(;Date.now()<a&&s.filter(u=>Le(u.pid)).length!==0;)await new Promise(u=>setTimeout(u,100))}for(let a of n)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of n)a.type==="sdk"&&ff();return h.info("SYSTEM",`Reaped ${n.length} process(es) for session ${t}`,{sessionId:o,reaped:n.length}),n.length}persist(){let t={processes:Object.fromEntries(this.entries.entries())};try{ft(this.registryPath,t),this.persistDegraded=!1}catch(n){this.reportPersistFailure(n)}}reportPersistFailure(t){if(this.persistDegraded)return;this.persistDegraded=!0;let n=t instanceof Error?t:new Error(String(t));h.warn("SYSTEM","Failed to persist supervisor registry; keeping it in memory",{path:this.registryPath},n);try{rR?.({errorCategory:n.code??"unknown"})}catch{}}},df=null;function nc(){return df||(df=new mf),df}var xH=180*1e3,oR=[];function ff(){let e=oR.shift();e&&e.notify()}var mo=require("fs");G();Me();var iR=qe.workerPid();async function YS(e){let t=e.currentPid??process.pid,n=e.pidFilePath??iR,o=e.registry.getAll(),r=[...o].filter(c=>c.pid!==t).sort((c,u)=>Date.parse(u.startedAt)-Date.parse(c.startedAt)),i=new Map,s=new Map;for(let c of r){if(!Le(c.pid)){e.registry.unregister(c.id);continue}s.set(c.id,hr(c.pid)),i.set(c.id,await Xa(c.pid));try{await JS(c,"SIGTERM")}catch(u){u instanceof Error?h.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:c.pid,pgid:c.pgid,type:c.type},u):h.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(u)})}}await ec(r,5e3);let a=r.filter(c=>Le(c.pid)||(i.get(c.id)??[]).some(u=>Le(u.pid)));for(let c of a){let u=rr(c.pid,s.get(c.id)??null);u||h.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:c.pid,type:c.type});try{u&&await JS(c,"SIGKILL")}catch(l){l instanceof Error?h.debug("SYSTEM","Failed to force kill child process",{pid:c.pid,pgid:c.pgid,type:c.type},l):h.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(l)})}finally{sR(i.get(c.id)??[],c.pid)}}await ec(a,1e3);for(let c of r)e.registry.unregister(c.id);for(let c of o.filter(u=>u.pid===t))e.registry.unregister(c.id);pf(n,t),e.registry.pruneDeadEntries()}function pf(e,t,n=!1){if(!(0,mo.existsSync)(e))return;let o=null;try{let s=JSON.parse((0,mo.readFileSync)(e,"utf-8"));o=typeof s.pid=="number"?s.pid:null}catch(s){h.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:e,error:s instanceof Error?s.message:String(s)});return}let r=t!==null&&o===t,i=o===null||!Le(o);if(!r&&!(n&&i)){h.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:e,recordedPid:o,currentPid:t});return}try{(0,mo.rmSync)(e,{force:!0})}catch(s){s instanceof Error?h.debug("SYSTEM","Failed to remove PID file",{pidFilePath:e},s):h.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:e,error:String(s)})}}function sR(e,t){for(let{pid:n,startToken:o}of e)if(!(n===t||!Le(n))){if(!rr(n,o)){h.debug("SYSTEM","Skipping reap: PID was recycled during the grace window",{pid:n,rootPid:t});continue}try{process.kill(n,"SIGKILL"),h.debug("SYSTEM","Reaped orphaned descendant during shutdown cascade",{pid:n,rootPid:t})}catch(r){let i=r instanceof Error?r.code:void 0;i!=="ESRCH"&&h.warn("SYSTEM","Failed to reap orphaned descendant during shutdown cascade",{pid:n,rootPid:t,errno:i})}}}async function JS(e,t){let{pid:n,pgid:o}=e;if(process.platform!=="win32"){if(typeof o=="number")try{process.kill(-o,t);return}catch(r){if((r instanceof Error?r.code:void 0)!=="ESRCH")throw r}if(t==="SIGKILL"){await nr(n,{signalMode:"immediate"});return}try{process.kill(n,t)}catch(r){if((r instanceof Error?r.code:void 0)!=="ESRCH")throw r}return}await nr(n)}G();var XS=3e4,po=null;function aR(){let t=nc().pruneDeadEntries();t>0&&h.info("SYSTEM",`Health check: pruned ${t} dead process(es) from registry`)}function QS(){po===null&&(po=setInterval(aR,XS),po.unref(),h.debug("SYSTEM","Health checker started",{intervalMs:XS}))}function eE(){po!==null&&(clearInterval(po),po=null,h.debug("SYSTEM","Health checker stopped"))}var tE=require("child_process"),rE=require("util");G();var cR=(0,rE.promisify)(tE.execFile),uR=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/;function lR(e){let t=[];for(let n of e.split(`
|
|
25
25
|
`)){let o=n.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);o&&t.push({pid:Number.parseInt(o[1],10),ppid:Number.parseInt(o[2],10),command:o[3].trim()})}return t}async function dR(){let e=await cR("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return lR(e.stdout)}function fR(e,t){let n=e.filter(s=>uR.test(s.command)&&s.pid!==t.selfPid),o=new Set(n.map(s=>s.pid)),r=n.filter(s=>!o.has(s.ppid)),i=r.filter(s=>s.ppid===t.selfPid?!1:s.ppid===1?!0:!t.isAlive(s.ppid));return{matched:n,roots:r,orphans:i}}async function nE(e={}){let t=e.platform??process.platform,n={matched:0,trees:0,orphans:0,killed:0,failed:0,unregistered:0,skipped:null};if(t==="win32")return n.skipped="windows",n;let o=e.readTable??dR,r=e.isAlive??Le,i=e.killTree??(f=>nr(f,{signalMode:"graceful"})),s=e.selfPid??process.pid,a;try{a=await o()}catch(f){return h.warn("PROCESS","Orphaned chroma-mcp sweep skipped: cannot read the process table",{error:f instanceof Error?f.message:String(f)}),n.skipped="unreadable",n}let{matched:c,roots:u,orphans:l}=fR(a,{isAlive:r,selfPid:s});if(n.matched=c.length,n.trees=u.length,n.orphans=l.length,l.length===0)return h.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:n.matched,trees:n.trees}),n;h.warn("PROCESS","Reaping orphaned chroma-mcp trees left by dead workers",{orphans:l.length,roots:l.map(f=>f.pid)});let d=new Set,m=8;for(let f=0;f<l.length;f+=m){let p=l.slice(f,f+m);(await Promise.allSettled(p.map(_=>i(_.pid)))).forEach((_,E)=>{let v=p[E];_.status==="fulfilled"?(n.killed+=1,d.add(v.pid)):(n.failed+=1,h.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:v.pid,ppid:v.ppid,error:_.reason instanceof Error?_.reason.message:String(_.reason)}))})}if(e.registry)for(let f of e.registry.getAll())f.type==="chroma"&&d.has(f.pid)&&(e.registry.unregister(f.id),n.unregistered+=1);return h.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:n.orphans,killed:n.killed,failed:n.failed,unregistered:n.unregistered}),n}Me();var mR=qe.workerPid(),gf=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(),_f({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,nE({registry:this.registry}).catch(n=>{h.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:n instanceof Error?n.message:String(n)})}),QS()}configureSignalHandlers(t){if(this.shutdownHandler=t,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let n=async o=>{if(this.shutdownInitiated){h.warn("SYSTEM",`Received ${o} but shutdown already in progress`);return}this.shutdownInitiated=!0,h.info("SYSTEM",`Received ${o}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(r){r instanceof Error?h.error("SYSTEM","Error during shutdown",{},r):h.error("SYSTEM","Error during shutdown (non-Error)",{error:String(r)});try{await this.stop()}catch(i){i instanceof Error?h.debug("SYSTEM","Supervisor shutdown fallback failed",{},i):h.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(i)})}}process.exit(0)};process.on("SIGTERM",()=>{n("SIGTERM")}),process.on("SIGINT",()=>{n("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{h.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{n("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}eE(),this.stopPromise=YS({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,n,o){this.registry.register(t,n,o)}unregisterProcess(t,n){this.registry.unregister(t,n)}getRegistry(){return this.registry}},pR=new gf(nc());function hf(){return pR}function _f(e={}){let t=e.pidFilePath??mR;if(!(0,In.existsSync)(t))return"missing";let n=null;try{n=JSON.parse((0,In.readFileSync)(t,"utf-8"))}catch(r){return r instanceof Error?h.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:t},r):h.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:t,error:String(r)}),(0,In.rmSync)(t,{force:!0}),"invalid"}return tc(n)&&n?((e.logAlive??!0)&&h.info("SYSTEM","Worker already running (PID alive)",{existingPid:n.pid,existingPort:n.port,startedAt:n.startedAt}),"alive"):(e.removeStale===!1||(h.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:n?.pid,port:n?.port,startedAt:n?.startedAt}),(0,In.rmSync)(t,{force:!0})),"stale")}Ha();var yf=require("path"),ic=require("fs"),iE=require("crypto");Me();var oc=require("fs");er();function oE(e,t){if(!(0,oc.existsSync)(e))return t;try{return Ci((0,oc.readFileSync)(e,"utf-8"))}catch(n){throw new Error(`Corrupt JSON file, refusing to overwrite: ${e}: ${n instanceof Error?n.message:String(n)}`)}}G();var sE="telemetry.json";function gR(e){let t=e.DO_NOT_TRACK;return t===void 0||t===""?!1:t!=="0"&&t!=="false"}function hR(e,t){if(gR(e))return{enabled:!1,source:"DO_NOT_TRACK"};let n=e.CLAUDE_MEM_TELEMETRY?.toLowerCase();return n==="0"||n==="false"||n==="off"?{enabled:!1,source:"env"}:n==="1"||n==="true"||n==="on"?{enabled:!0,source:"env"}:t?.enabled===!0?{enabled:!0,source:"config"}:t?.enabled===!1?{enabled:!1,source:"config"}:{enabled:!0,source:"default"}}function sc(e,t){return hR(e,t).enabled}function _R(){return(0,yf.join)($t(),sE)}function Ui(){let e;try{e=oE(_R(),null)}catch(t){let n=t instanceof Error?t:new Error(String(t));return h.warn("SYSTEM","Telemetry: corrupt telemetry.json; treating as no recorded consent",void 0,n),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 yR(e){let t=$t();(0,ic.mkdirSync)(t,{recursive:!0}),(0,ic.writeFileSync)((0,yf.join)(t,sE),JSON.stringify(e,null,2)+`
|
|
26
|
-
`)}function aE(){let e=Ui();if(e?.installId)return e.installId;let t=(0,iE.randomUUID)();return yR({installId:t,decidedAt:""}),t}var uE=Nt(require("os"),1);G();var cE=8192,qt="[REDACTED]";function vR(e){try{if(typeof e!="string"){if(e==null)return"";try{e=String(e)}catch(n){let o=n instanceof Error?n:new Error(String(n));return h.warn("SYSTEM","error-scrub: String() coercion of non-string input failed",void 0,o),""}}let t=e;return t.length>cE?t.slice(0,cE):t}catch{return""}}function bR(e){if(typeof e!="string"||e.length===0)return e??"";let t="";try{t=uE.default.homedir()||""}catch(o){let r=o instanceof Error?o:new Error(String(o));h.warn("SYSTEM","error-scrub: os.homedir() failed; skipping home-dir redaction",void 0,r),t=""}if(!t)return e;let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");try{return e.replace(new RegExp(n,"g"),"~")}catch(o){let r=o instanceof Error?o:new Error(String(o));return h.warn("SYSTEM","error-scrub: home-dir RegExp replace failed; using split/join fallback",void 0,r),e.split(t).join("~")}}function SR(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 ER(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${qt}`):t.replace(/[?#].*$/,"").replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/@\s]+@/,`$1${qt}@`))}function wR(e){return typeof e!="string"||e.length===0?e??"":e.replace(/\?[^\s"'()]*/g,"")}function $R(e){return typeof e!="string"||e.length===0?e??"":e.replace(/\b(?:access[_-]?token|api[_-]?key|auth(?:orization)?|secret|password|passwd|jwt|session[_-]?id|token)=[^\s"'&]+/gi,t=>{let n=t.indexOf("=");return`${t.slice(0,n+1)}${qt}`})}function kR(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,qt),t=t.replace(/\b[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\b/g,qt),t=t.replace(/\b(?:sk|pk|rk|ak|phc|phx|ph|ghp|gho|ghs|xox[bpasr])[-_][A-Za-z0-9_-]{8,512}\b/gi,qt),t=t.replace(/\bBearer\s+[A-Za-z0-9._-]{8,512}\b/gi,qt),t=t.replace(/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g,qt),t=t.replace(/\b[0-9a-fA-F]{24,4096}\b/g,qt),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,qt),t=t.replace(/\b(?=[A-Za-z0-9+/_-]{0,4096}\d)[A-Za-z0-9+/_-]{32,4096}={0,2}\b/g,qt),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,qt),t}function lE(e){let t=vR(e);return t.length===0?"":(t=bR(t),t=ER(t),t=SR(t),t=wR(t),t=$R(t),t=kR(t),t)}var xR=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","stage","phase","install_method","interactive","provider_source","bun_version","uv_version","claude_code_version","trial_days","trial_variant","offer_surface","funnel_source","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","limit_window","overage_status","is_using_overage","resets_in_minutes","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_aborted_deadline_exceeded","outcomes_invalid_output","top_model","top_abort_reason","observed_model","observed_billing","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","skill_id","skill_source","skill_trigger","observations_created","total_observations_injected","total_tokens_saved_vs_naive","platform","agent_role","instruction_state","instruction_returned_count","instruction_disabled_count","instruction_excluded_count","instruction_missing_count","instruction_unknown_count","captured_prompt_count","captured_session_count","captured_tool_count","unidentified_tool_event_count","native_todo_count",...["captured","mcp"].flatMap(e=>["read","write"].flatMap(t=>[`${e}_${t}_count`,...["ok","error","excluded","disabled","unknown"].map(n=>`${e}_${t}_${n}_count`)]))]),dE=200;function IR(e,t){if(!(!e||typeof e!="object"))for(let n of Object.keys(e)){if(!xR.has(n))continue;let o=e[n];if(typeof o=="string"){let r=o.length>dE?o.slice(0,dE):o;t[n]=lE(r)}else(typeof o=="number"&&Number.isFinite(o)||typeof o=="boolean")&&(t[n]=o)}}function fE(e){let t={};try{IR(e,t)}catch{}return t}var vf=Nt(require("os"),1);G();var TR="14.0.
|
|
26
|
+
`)}function aE(){let e=Ui();if(e?.installId)return e.installId;let t=(0,iE.randomUUID)();return yR({installId:t,decidedAt:""}),t}var uE=Nt(require("os"),1);G();var cE=8192,qt="[REDACTED]";function vR(e){try{if(typeof e!="string"){if(e==null)return"";try{e=String(e)}catch(n){let o=n instanceof Error?n:new Error(String(n));return h.warn("SYSTEM","error-scrub: String() coercion of non-string input failed",void 0,o),""}}let t=e;return t.length>cE?t.slice(0,cE):t}catch{return""}}function bR(e){if(typeof e!="string"||e.length===0)return e??"";let t="";try{t=uE.default.homedir()||""}catch(o){let r=o instanceof Error?o:new Error(String(o));h.warn("SYSTEM","error-scrub: os.homedir() failed; skipping home-dir redaction",void 0,r),t=""}if(!t)return e;let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");try{return e.replace(new RegExp(n,"g"),"~")}catch(o){let r=o instanceof Error?o:new Error(String(o));return h.warn("SYSTEM","error-scrub: home-dir RegExp replace failed; using split/join fallback",void 0,r),e.split(t).join("~")}}function SR(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 ER(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${qt}`):t.replace(/[?#].*$/,"").replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/@\s]+@/,`$1${qt}@`))}function wR(e){return typeof e!="string"||e.length===0?e??"":e.replace(/\?[^\s"'()]*/g,"")}function $R(e){return typeof e!="string"||e.length===0?e??"":e.replace(/\b(?:access[_-]?token|api[_-]?key|auth(?:orization)?|secret|password|passwd|jwt|session[_-]?id|token)=[^\s"'&]+/gi,t=>{let n=t.indexOf("=");return`${t.slice(0,n+1)}${qt}`})}function kR(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,qt),t=t.replace(/\b[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\b/g,qt),t=t.replace(/\b(?:sk|pk|rk|ak|phc|phx|ph|ghp|gho|ghs|xox[bpasr])[-_][A-Za-z0-9_-]{8,512}\b/gi,qt),t=t.replace(/\bBearer\s+[A-Za-z0-9._-]{8,512}\b/gi,qt),t=t.replace(/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g,qt),t=t.replace(/\b[0-9a-fA-F]{24,4096}\b/g,qt),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,qt),t=t.replace(/\b(?=[A-Za-z0-9+/_-]{0,4096}\d)[A-Za-z0-9+/_-]{32,4096}={0,2}\b/g,qt),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,qt),t}function lE(e){let t=vR(e);return t.length===0?"":(t=bR(t),t=ER(t),t=SR(t),t=wR(t),t=$R(t),t=kR(t),t)}var xR=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","stage","phase","install_method","interactive","provider_source","bun_version","uv_version","claude_code_version","trial_days","trial_variant","offer_surface","funnel_source","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","limit_window","overage_status","is_using_overage","resets_in_minutes","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_aborted_deadline_exceeded","outcomes_invalid_output","top_model","top_abort_reason","observed_model","observed_billing","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","skill_id","skill_source","skill_trigger","observations_created","total_observations_injected","total_tokens_saved_vs_naive","platform","agent_role","instruction_state","instruction_returned_count","instruction_disabled_count","instruction_excluded_count","instruction_missing_count","instruction_unknown_count","captured_prompt_count","captured_session_count","captured_tool_count","unidentified_tool_event_count","native_todo_count",...["captured","mcp"].flatMap(e=>["read","write"].flatMap(t=>[`${e}_${t}_count`,...["ok","error","excluded","disabled","unknown"].map(n=>`${e}_${t}_${n}_count`)]))]),dE=200;function IR(e,t){if(!(!e||typeof e!="object"))for(let n of Object.keys(e)){if(!xR.has(n))continue;let o=e[n];if(typeof o=="string"){let r=o.length>dE?o.slice(0,dE):o;t[n]=lE(r)}else(typeof o=="number"&&Number.isFinite(o)||typeof o=="boolean")&&(t[n]=o)}}function fE(e){let t={};try{IR(e,t)}catch{}return t}var vf=Nt(require("os"),1);G();var TR="14.0.1",AR="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",OR="https://us.i.posthog.com";function mE(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||AR}function pE(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||OR}var PR=["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 gE(e){let t={};for(let n of PR)e[n]!==void 0&&(t[n]=e[n]);return t}function RR(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||vf.default.release().toLowerCase().includes("microsoft")}catch(e){let t=e instanceof Error?e:new Error(String(e));return h.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,t),!1}}function hE(){return{version:TR,os:process.platform,os_version:vf.default.release(),is_wsl:RR(),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 CR=2e3;async function bf(e,t,n){try{if(!sc(process.env,Ui()))return;let o=fE({...hE(),...t??{}});if(n?.person?o.$set=gE(o):o.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:e,properties:o})+`
|
|
27
27
|
`);return}let r=mE(),i=new AbortController,s=setTimeout(()=>i.abort(),CR);try{await MR(r,e,o,i.signal)}finally{clearTimeout(s)}}catch{}}async function MR(e,t,n,o){await fetch(`${pE()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:e,event:t,distinct_id:aE(),properties:n}),signal:o})}var kt=Nt(require("path"),1),Tf=require("os"),He=require("fs"),Fi=require("child_process");G();G();G();var pt=Nt(require("path"),1),go=require("fs"),lc=require("os"),$f=require("child_process");Di();Me();G();var ac=require("fs"),Zr=Nt(require("path"),1);G();var ji={isWorktree:!1,isSubmodule:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function _E(e){let t=Zr.default.join(e,".git"),n;try{n=(0,ac.statSync)(t)}catch(c){return c instanceof Error&&c.code!=="ENOENT"&&h.warn("GIT","Unexpected error checking .git",{error:c instanceof Error?c.message:String(c)}),ji}if(!n.isFile())return ji;let o;try{o=(0,ac.readFileSync)(t,"utf-8").trim()}catch(c){return h.warn("GIT","Failed to read .git file",{error:c instanceof Error?c.message:String(c)}),ji}let r=o.match(/^gitdir:\s*(.+)$/);if(!r)return ji;let i=Zr.default.resolve(Zr.default.dirname(t),r[1]),s=i.match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(s){let c=s[1];return{isWorktree:!0,isSubmodule:!1,worktreeName:Zr.default.basename(e),parentRepoPath:c,parentProjectName:Zr.default.basename(c)}}let a=i.match(/^(.+)[/\\]\.git[/\\]modules[/\\](.+)$/);if(a){let c=a[1];return{isWorktree:!1,isSubmodule:!0,worktreeName:Zr.default.basename(e),parentRepoPath:c,parentProjectName:Zr.default.basename(c)}}return ji}var SE=require("fs");var vE=require("path");Di();G();function yE(e){let t=Ar(e.replace(/\\/g,"/"));t=t.replace(/\\/g,"/");let n=t.replace(/[.+^${}()|[\]\\]/g,"\\$&");return n=n.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${n}$`)}function DR(e,t,n){let o=yE(e);return o.test(t)||o.test(n)?!0:e.replace(/\\/g,"/").endsWith("/**")?yE(e.slice(0,-3)).test(t.replace(/\/+$/,"")):!1}function bE(e,t){if(!t.length)return!1;let n=e.replace(/\\/g,"/"),o=(0,vE.basename)(n);for(let r of t){let i=r.trim();if(i)try{if(DR(i,n,o))return!0}catch(s){h.warn("PROJECT_NAME","Invalid glob pattern",{pattern:i,error:s instanceof Error?s.message:String(s)});continue}}return!1}G();function EE(e){let t=e;if(typeof t=="string"){if(!t.trim())return[];try{t=JSON.parse(t)}catch(o){return h.warn("PROJECT_NAME","CLAUDE_MEM_PROJECT_ENVIRONMENTS is not valid JSON; ignoring it",{error:o instanceof Error?o.message:String(o)}),[]}}if(!Array.isArray(t))return t!=null&&h.warn("PROJECT_NAME","CLAUDE_MEM_PROJECT_ENVIRONMENTS must be an array; ignoring it",{}),[];let n=[];for(let o of t){let r=typeof o?.name=="string"?o.name.trim():"",i=Array.isArray(o?.patterns)?o.patterns.filter(s=>typeof s=="string"&&s.trim()!==""):[];if(!r||i.length===0){h.warn("PROJECT_NAME","Ignoring a project environment without a name or patterns",{name:r});continue}n.push({name:r,patterns:i})}return n}function NR(e){try{return(0,SE.realpathSync)(e)}catch{return e}}function Sf(e,t){if(t.length===0)return null;let n=[...new Set([e,NR(e)])].flatMap(o=>[o,`${o.replace(/[\\/]+$/,"")}/`]);for(let o of t)if(n.some(r=>bE(r,o.patterns)))return o.name;return null}var kf="unknown-project";function kE(e){try{return(0,$f.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim()||null}catch(t){let n=t instanceof Error?t:new Error(String(t));return h.debug("PROJECT_NAME","git rev-parse failed, falling back to non-git root",{dir:e},n),null}}var LR=[".claude-mem-project",".claude-mem.json"],zR=64;function xE(e){try{return(0,go.realpathSync)(e)}catch{return e}}function UR(e,t){let n=pt.default.relative(t,e);return n===""||!n.startsWith("..")&&!pt.default.isAbsolute(n)}function jR(){return[(0,lc.homedir)(),(0,lc.tmpdir)(),Ni].flatMap(e=>{let t=pt.default.resolve(e);return[t,xE(t)]})}function IE(e){let t=jR(),n=pt.default.resolve(e);if([pt.default.resolve(Ni),xE(pt.default.resolve(Ni))].some(r=>UR(n,r)))return null;for(let r=0;r<zR;r++){if(t.includes(n))return null;let i=pt.default.dirname(n);if(i===n)return null;if(LR.some(s=>(0,go.existsSync)(pt.default.join(n,s))))return n;n=i}return null}function wf(e,t){let n=pt.default.basename(t);if(n===""){if(process.platform==="win32"){let r=e.match(/^([A-Z]):\\/i);if(r){let s=`drive-${r[1].toUpperCase()}`;return h.info("PROJECT_NAME","Drive root detected",{cwd:e,projectName:s}),s}}return h.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:e}),kf}return n}var FR="CLAUDE_MEM_PROJECT_NAME_SOURCE",cc=null;function wE(){try{return(0,go.statSync)(tr).mtimeMs}catch{return-1}}function TE(){let e=wE();if(e===-1)return Oe.getAllDefaults();if(cc&&cc.mtimeMs===e)return cc.settings;let t=Oe.loadFromFile(tr);return cc={mtimeMs:wE(),settings:t},t}function qR(){let e=process.env[FR]??TE().CLAUDE_MEM_PROJECT_NAME_SOURCE;return String(e??"path").trim().toLowerCase()==="git-remote"}var WR="CLAUDE_MEM_PROJECT_ENVIRONMENTS",uc=null;function AE(){let e=process.env[WR]??TE().CLAUDE_MEM_PROJECT_ENVIRONMENTS;return(!uc||uc.raw!==e)&&(uc={raw:e,environments:EE(e)}),uc.environments}function BR(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 o=t.replace(/\/+$/,"").replace(/\.git$/i,""),r=o.match(/^[a-z][a-z0-9+.-]*:\/\/[^/]+\/(.+)$/i),i=r?null:o.match(/^(?:[^/@\s]+@)?[^:/\s]+:(?!\/\/)(.+)$/),s=r?.[1]??i?.[1];if(!s)return null;let a=s.split("/").filter(c=>c&&c!=="_git");return a.length>=2?a.slice(-2).join("/"):a.length===1?a[0]:null}function HR(e){try{let t=(0,$f.execFileSync)("git",["remote","get-url","origin"],{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim();return BR(t)}catch(t){let n=t instanceof Error?t:new Error(String(t));return h.debug("PROJECT_NAME","No usable origin remote, keeping the path-based name",{repoRoot:e},n),null}}var Ef=new Map;function OE(e){return qR()?(Ef.has(e)||Ef.set(e,HR(e)),Ef.get(e)??null):null}function ZR(e,t=process.platform){if(!e||e.trim()==="")return h.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:e}),kf;let n=Ar(e,t),o=Sf(n,AE());if(o)return o;let r=kE(n),i=r?OE(r):null;if(i)return i;let s=r??IE(n)??n;return wf(e,s)}function PE(e,t){return t===e?e:`${e}/${t}`}function VR(e,t){if(!e.isSubmodule||!e.parentRepoPath)return null;let n=pt.default.relative(e.parentRepoPath,t);return!n||n.startsWith("..")||pt.default.isAbsolute(n)?null:n.split(pt.default.sep).join("/")}function RE(e,t=process.platform){if(!e||e.trim()===""){let c=ZR(e,t);return{primary:c,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[c],keySource:"path"}}let n=Ar(e,t),o=kE(n),r=KR(e,n,o),i=o?OE(o):null,s=i?$E(r,i,"git-remote"):r,a=Sf(n,AE());return a?$E(s,a,"environment"):s}function $E(e,t,n){return{primary:t,parent:null,isWorktree:e.isWorktree,isSubmodule:e.isSubmodule,allProjects:[...e.allProjects.filter(o=>o!==t),t],keySource:n}}function KR(e,t,n){let o=n?null:IE(t),r=wf(e,n??o??t),i=n??t,s=_E(i);if((s.isWorktree||s.isSubmodule)&&s.parentProjectName){let a=s.parentProjectName,c,u;return s.isSubmodule?(c=`${a}/${VR(s,i)??r}`,u=r!==a?[r]:[]):(c=PE(a,r),u=c===a?[`${a}/${r}`]:[]),{primary:c,parent:a,isWorktree:s.isWorktree,isSubmodule:s.isSubmodule,allProjects:[...new Set([a,...u,c])].filter(l=>l!==c).concat(c),keySource:"path"}}if(o&&pt.default.resolve(o)!==pt.default.resolve(t)){let a=wf(e,t);if(a!==r&&a!==kf)return{primary:r,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[a,r],keySource:"path"}}return{primary:r,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[r],keySource:"path"}}Me();var CE=pr(De.POWERSHELL_COMMAND);function GR(e){return e===void 0?CE:Math.max(1,Math.min(CE,e))}var HZ=qe.dataDir(),Tn=qe.workerPid(),DE="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 JR(e){try{return(0,He.realpathSync)(e)}catch{return null}}function xf(e){return e?/(^|[\\/])bun(\.exe)?$/i.test(e.trim()):!1}function YR(e,t){let n=t==="win32"?"where.exe":"which",o=[e],r;try{r=(0,Fi.execFileSync)(n,o,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(s){return s instanceof Error?h.debug("SYSTEM",`Binary lookup failed for ${e}`,{command:n,args:o},s):h.debug("SYSTEM",`Binary lookup failed for ${e}`,{command:n,args:o},new Error(String(s))),null}return r.split(/\r?\n/).map(s=>s.trim()).find(s=>s.length>0)||null}var If;function Af(e={}){let t=Object.keys(e).length===0;if(t&&If!==void 0)return If;let n=XR(e);return t&&n!==null&&(If=n),n}function ME(e,t){let n=e?.trim();return n?t==="win32"?[kt.default.join(n,"bin","bun.exe"),kt.default.join(n,"bin","bun"),kt.default.join(n,"bun.exe")]:[kt.default.join(n,"bin","bun"),kt.default.join(n,"bun")]:[]}function XR(e){let t=e.platform??process.platform,n=e.execPath??process.execPath;if(xf(n))return n;let o=e.env??process.env,r=e.homeDirectory??(0,Tf.homedir)(),i=e.pathExists??He.existsSync,s=e.lookupInPath??YR,a=e.realpath??JR,c=t==="win32"?[o.BUN,o.BUN_PATH,...ME(o.BUN_INSTALL,t),kt.default.join(r,".bun","bin","bun.exe"),kt.default.join(r,".bun","bin","bun"),o.USERPROFILE?kt.default.join(o.USERPROFILE,".bun","bin","bun.exe"):void 0,o.LOCALAPPDATA?kt.default.join(o.LOCALAPPDATA,"bun","bun.exe"):void 0,o.LOCALAPPDATA?kt.default.join(o.LOCALAPPDATA,"bun","bin","bun.exe"):void 0,o.npm_config_prefix?kt.default.join(o.npm_config_prefix,"bun.exe"):void 0]:[o.BUN,o.BUN_PATH,...ME(o.BUN_INSTALL,t),kt.default.join(r,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun",o.npm_config_prefix?kt.default.join(o.npm_config_prefix,"bin","bun"):void 0];for(let d of c){let m=d?.trim();if(m&&(xf(m)&&i(m)||m.toLowerCase()==="bun"))return m}let u=s("bun",t)?.trim();if(!u||!xf(u))return null;let l=a(u)??u;return i(l)?l:null}function NE(){if(!(0,He.existsSync)(Tn))return null;try{return JSON.parse((0,He.readFileSync)(Tn,"utf-8"))}catch(e){return e instanceof Error?h.warn("SYSTEM","Failed to parse PID file",{path:Tn},e):h.warn("SYSTEM","Failed to parse PID file",{path:Tn},new Error(String(e))),null}}function LE(e){pf(Tn,e,!0)}function Vr(e){return process.platform==="win32"?Math.round(e*2):e}function Of(){let e=qe.dataDir();return(0,He.mkdirSync)(e,{recursive:!0}),e}function QR(e,t,n=Of()){let o=r=>r.replace(/'/g,"''");return`Start-Process -FilePath '${o(e)}' -ArgumentList @('"${o(t)}"','--daemon') -WorkingDirectory '${o(n)}' -WindowStyle Hidden`}var eC=5e3,tC=8;function rC(e,t,n){return e?.code!=="ETIMEDOUT"?!1:t<n/2}function zE(e,t=Vr(eC)){let n=Af();if(!n)return;let o=()=>{let a=Date.now();try{return{result:(0,Fi.spawnSync)(n,[e,"status"],{encoding:"utf-8",timeout:t,windowsHide:!0,env:gr({...process.env})}),elapsedMs:Date.now()-a}}catch(c){let u=c instanceof Error?c:new Error(String(c));h.debug("SYSTEM","Worker boot probe could not be launched",{scriptPath:e},u);return}},r=o();if(r===void 0||rC(r.result.error,r.elapsedMs,t)&&(h.debug("SYSTEM","Worker boot probe timed out before it could run \u2014 retrying once",{scriptPath:e,elapsedMs:r.elapsedMs,timeoutMs:t}),r=o(),r===void 0))return;let{result:i}=r;if(i.error||i.status===0)return;let s=`${i.stdout??""}${i.stderr??""}`.trim();if(s)return s.split(/\r?\n/).slice(0,tC).join(`
|
|
28
28
|
`)}function nC(e=process.env){let t=e.SystemRoot||e.SYSTEMROOT;return t?`${t}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`:"powershell.exe"}function oC(e,t,n=Of()){return["-NoProfile","-WindowStyle","Hidden","-EncodedCommand",Buffer.from(QR(e,t,n),"utf16le").toString("base64")]}function UE(e,t,n,o=process.platform,r){if(o==="win32"){let l=nC(n),d=oC(e,t),m=GR(r);try{let f=(0,Fi.spawnSync)(l,d,{stdio:"ignore",windowsHide:!0,env:n,timeout:m,killSignal:"SIGTERM"});if(f.error)throw f.error;if(f.signal)throw new Error(`powershell Start-Process killed by signal=${f.signal} after ${m}ms`);if(f.status!==0)throw new Error(`powershell Start-Process exited ${f.status??"null"}`);return 0}catch(f){let p=f instanceof Error?f:new Error(String(f));h.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:e,powershell:l},p);return}}let i="/usr/bin/setsid",s=(0,He.existsSync)(i),a=s?i:e,u=af(a,s?[e,t,"--daemon"]:[t,"--daemon"],{detached:!0,stdio:"ignore",cwd:Of(),env:n});if(u.on("error",l=>{h.error("SYSTEM",DE,{runtimePath:e,execPath:a},l)}),u.pid!==void 0)return u.unref(),u.pid}function jE(e,t,n={}){hf().assertCanSpawn("worker daemon");let o=gr({...process.env,CLAUDE_MEM_WORKER_PORT:String(t),...n}),r=Af();if(!r){h.error("SYSTEM",DE);return}return UE(r,e,o)}function FE(){try{if(!(0,He.existsSync)(Tn))return;let e=new Date;(0,He.utimesSync)(Tn,e,e)}catch{}}function qi(e={}){return _f({logAlive:!1,removeStale:e.removeStale})}var WE=Nt(require("net"),1);G();Me();var iC=new Set(["ECONNREFUSED","ConnectionRefused"]);function Pf(e,t){if(!e||typeof e!="object"||t.has(e))return!1;if(t.add(e),e instanceof Error&&e.message.includes("ECONNREFUSED"))return!0;let n=e;return typeof n.code=="string"&&iC.has(n.code)||Pf(n.cause,t)?!0:Array.isArray(n.errors)&&n.errors.some(o=>Pf(o,t))}function Rf(e){return Pf(e,new Set)?!0:e instanceof Error&&e.message.includes("ECONNREFUSED")}function qE(e){let t=e?.code;return t==="EACCES"||t==="EADDRNOTAVAIL"}var dc="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 Cf(){return Oe.loadFromFile(tr).CLAUDE_MEM_WORKER_HOST}function BE(e){return e.startsWith("[")&&e.endsWith("]")?e:e.includes(":")?`[${e}]`:e}var Wi=5e3;async function sC(e,t,n="GET",o=Wi){let r=await fetch(`http://${BE(Cf())}:${e}${t}`,{method:n,signal:AbortSignal.timeout(Math.max(1,o))}),i="";try{i=await r.text()}catch{}return{ok:r.ok,statusCode:r.status,body:i}}async function Mf(e,t=Wi){let n=Date.now()+t;if(process.platform==="win32")try{let r=await fetch(`http://${BE(Cf())}:${e}/api/health`,{signal:AbortSignal.timeout(Math.max(1,n-Date.now()))});if(r.ok)return!0;h.debug("SYSTEM","Windows health check returned non-ok; falling through to socket probe",{port:e,status:r.status})}catch(r){r instanceof Error?h.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:e,message:r.message}):h.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:e,error:String(r)})}let o=await HE(e,Math.max(1,n-Date.now()));return o==="occupied"||o==="indeterminate"}async function HE(e,t=Wi){return(await Df(e,t)).occupancy}function Df(e,t=Wi){return t<=0?Promise.resolve({occupancy:"indeterminate"}):new Promise(n=>{let o=!1,r=!1,i=!1,s;try{s=WE.default.createServer()}catch{n({occupancy:"indeterminate"});return}let a=l=>{if(i){l?.();return}i=!0;try{s.close(l)}catch(d){l?.(d instanceof Error?d:new Error(String(d)))}},c=setTimeout(()=>{if(r)a();else try{s.close()}catch{}u({occupancy:"indeterminate"})},t),u=l=>{o||(o=!0,clearTimeout(c),n(l))};s.once("error",l=>{if(r)a();else try{s.close()}catch{}l.code==="EADDRINUSE"?u({occupancy:"occupied"}):qE(l)?u({occupancy:"unbindable",bindErrorCode:l.code}):u({occupancy:"indeterminate"})}),s.once("listening",()=>{if(r=!0,o){a();return}try{a(l=>u({occupancy:l?"indeterminate":"free"}))}catch{u({occupancy:"indeterminate"})}});try{s.listen(e,Cf())}catch{try{s.close()}catch{}u({occupancy:"indeterminate"})}})}async function ZE(e,t,n,o){let r=Date.now()+n;for(;Date.now()<r;){try{let s=r-Date.now();if((await sC(e,t,"GET",Math.min(Wi,s))).ok)return!0}catch(s){s instanceof Error?h.debug("SYSTEM",o,{},s):h.debug("SYSTEM",o,{error:String(s)})}let i=Math.min(500,r-Date.now());i>0&&await new Promise(s=>setTimeout(s,i))}return!1}function Kr(e,t=3e4){return ZE(e,"/api/health",t,"Service not ready yet, will retry")}function ho(e,t=3e4){return ZE(e,"/api/readiness",t,"Worker not ready yet, will retry")}G();var fc=require("path"),nt=require("fs");Me();G();var KE=9e4,uV=KE/3;function GE(){return(0,fc.join)($t(),"spawn.lock")}function VE(e){try{let t=JSON.parse((0,nt.readFileSync)(e,"utf-8"));return typeof t.pid!="number"||!Number.isInteger(t.pid)||t.pid<=0?null:t.pid}catch{return null}}function aC(e){if(e===null)return null;try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}function Nf(){let e=GE(),t=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let n=0;n<2;n++)try{return(0,nt.mkdirSync)((0,fc.dirname)(e),{recursive:!0}),(0,nt.writeFileSync)(e,t,{flag:"wx"}),!0}catch(o){let r=o instanceof Error?o:new Error(String(o)),i=r.code;if(i!=="EEXIST")return h.warn("SYSTEM","Spawn lock write failed for a non-contention reason; failing open (spawning unlocked)",{lockPath:e,code:i},r),!0;if(n>0)return!1;let s;try{s=(0,nt.statSync)(e).mtimeMs}catch{continue}let a=VE(e),c=null;if(a===null)try{c=(0,nt.readFileSync)(e,"utf-8")}catch{continue}if(Date.now()-s<=KE&&aC(a)!==!1)return!1;let l;try{l=(0,nt.statSync)(e).mtimeMs}catch{continue}if(l!==s)return!1;if(a!==null){if(VE(e)!==a)return!1}else try{if((0,nt.readFileSync)(e,"utf-8")!==c)return!1}catch{continue}try{(0,nt.unlinkSync)(e)}catch{return!1}}return!1}function Lf(){let e=GE();try{if(JSON.parse((0,nt.readFileSync)(e,"utf-8")).pid!==process.pid)return;(0,nt.unlinkSync)(e)}catch{}}var QE=require("node:child_process"),Bi=require("node:fs"),ew=require("node:util");G();Me();var mc=(0,ew.promisify)(QE.execFile),cC=/^(uv|uvx|python|chroma-mcp)(\.exe)?$/i;function JE(e){return cC.test(e.trim())}function uC(e,t){if(!e)return!1;let n=e.toLowerCase().replace(/\\/g,"/"),o=n.indexOf("--data-dir");if(o<0)return!1;let r=n.slice(o+10).trim();if(r.startsWith('"')){let s=r.indexOf('"',1);r=s<0?r.slice(1):r.slice(1,s)}let i=t.toLowerCase().replace(/\\/g,"/");return r===i||r.startsWith(i)&&r[i.length]==="/"}function pc(e,t){return t===void 0?e:Math.max(1,Math.min(e,t))}async function lC(e){try{let t=await mc("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:pc(3e4,e),windowsHide:!0,maxBuffer:33554432}),n=JSON.parse(t.stdout),o=Array.isArray(n)?n:n===null?[]:[n],r=[];for(let i of o){let s=typeof i.Name=="string"?i.Name.trim():"";if(!s)continue;let a=typeof i.ProcessId=="number"?i.ProcessId:Number.parseInt(String(i.ProcessId),10),c=typeof i.ParentProcessId=="number"?i.ParentProcessId:Number.parseInt(String(i.ParentProcessId),10);!Number.isInteger(a)||!Number.isInteger(c)||r.push({pid:a,ppid:c,name:s,cmdline:typeof i.CommandLine=="string"?i.CommandLine:null,startToken:typeof i.StartToken=="string"&&i.StartToken.length>0?i.StartToken:null})}return r}catch(t){return h.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 dC(e,t){try{let n=await mc("netstat",["-ano"],{timeout:pc(15e3,t),windowsHide:!0,maxBuffer:16777216});return gC(n.stdout,e)}catch(n){return h.warn("PROCESS","netstat failed \u2014 ghost-port reclaim disabled for this attempt",{port:e,error:n instanceof Error?n.message:String(n)}),null}}async function fC(e,t){try{let n=await mc("lsof",["-nP",`-iTCP:${e}`,"-sTCP:LISTEN","-t"],{timeout:pc(1e4,t),maxBuffer:1048576});return mC(n.stdout)}catch(n){let o=n;return o.code===1&&typeof o.stdout=="string"&&o.stdout.trim()===""?[]:(h.warn("PROCESS","lsof failed \u2014 cannot verify the worker port owner",{port:e,error:n instanceof Error?n.message:String(n)}),null)}}function mC(e){let t=new Set;for(let n of e.split(/\r?\n/)){let o=Number.parseInt(n.trim(),10);Number.isInteger(o)&&o>0&&t.add(o)}return[...t]}async function pC(e,t){try{let o=(await mc("ps",["-p",String(e),"-o","command="],{timeout:pc(5e3,t)})).stdout.trim();return o.length>0?o:null}catch{return null}}function gC(e,t){let n=new Set,o=`:${t}`;for(let r of e.split(/\r?\n/)){let i=r.trim();if(!/^TCP\b/i.test(i))continue;let s=i.split(/\s+/);if(!s[1]?.endsWith(o)||s[3]!=="LISTENING")continue;let c=Number.parseInt(s[4]??"",10);Number.isInteger(c)&&c>0&&n.add(c)}return[...n]}var hC=/worker-service/i,tw=1500,rw=1e3,zf=5500,YE=2*tw+rw+zf;async function _C(e,t){let n=t.readOwnedWorker();if(n===null||n.port!==e)return null;let o=(l,d={})=>(h.info("PROCESS","Wedged-worker reclaim declined",{port:e,pid:n.pid,reason:l,...d}),{reclaimed:!1,reason:l,killedPids:[]}),r=(t.now()-Date.parse(n.startedAt))/1e3;if(!Number.isFinite(r)||r<t.minOwnerAgeSeconds)return o("owner-booting",{ageSeconds:r,minOwnerAgeSeconds:t.minOwnerAgeSeconds});for(let l=0;l<2;l++)if(l>0&&await t.sleep(rw),await t.probeHealth(e))return o("owner-responding");let i=await t.listOwners(e);if(i===null)return o("netstat-unreadable");if(!i.includes(n.pid))return h.info("PROCESS","Wedged-worker reclaim: our worker does not own the port \u2014 deferring to the ghost-listener check",{port:e,pid:n.pid,listeners:i}),null;let s=t.readHeartbeat();if(s!==null&&s.pid===n.pid){let l=t.now(),d=Math.max(0,l-s.beatAtMs),m=Math.max(0,l-s.lastResponseAtMs);if(d<t.heartbeatStaleMs){if(m<t.maxSilentProtectionMs)return o("owner-progressing",{heartbeatAgeMs:Math.round(d),sinceLastResponseMs:Math.round(m)});h.warn("PROCESS","Worker finished no response within the protection window despite a fresh liveness heartbeat",{port:e,pid:n.pid,sinceLastResponseMs:Math.round(m),maxSilentProtectionMs:t.maxSilentProtectionMs})}}let a=await t.readIdentity(n.pid),c=n.startToken!==void 0&&a.startToken!==null&&a.startToken!==n.startToken;if(c||a.cmdline===null||!hC.test(a.cmdline))return o("owner-identity-mismatch",{tokenMismatch:c,hasCmdline:a.cmdline!==null});if(!t.hasKillBudget())return o("out-of-budget");h.warn("PROCESS","Reclaiming wedged worker: past its boot grace, silent on two health probes, and still holding the port",{port:e,pid:n.pid,ageSeconds:Math.round(r)});try{await t.killTree(n.pid,{expectedStartToken:a.startToken??n.startToken??void 0,signalMode:"graceful"})}catch(l){return h.error("PROCESS","Wedged-worker reclaim tree-kill failed",{port:e,pid:n.pid},l instanceof Error?l:new Error(String(l))),{reclaimed:!1,reason:"kill-failed",killedPids:[]}}let u=await t.listOwners(e);return u!==null&&u.length===0?(h.info("PROCESS","Wedged worker reclaimed \u2014 port is free again",{port:e,killedPids:[n.pid]}),{reclaimed:!0,killedPids:[n.pid]}):(h.warn("PROCESS","Wedged-worker reclaim killed the worker but the port is still bound",{port:e,pid:n.pid,stillOwnedBy:u}),{reclaimed:!1,reason:"still-bound",killedPids:[n.pid]})}async function yC(e,t,n,o){let r=hr(e),i=t?(await n(o))?.find(s=>s.pid===e)?.cmdline??null:await pC(e,o);return rr(e,r)?{startToken:r,cmdline:i}:{startToken:null,cmdline:null}}async function Uf(e,t={}){let n=t.isWin32??(()=>process.platform==="win32"),o=t.now??Date.now,r=t.deadlineAt??null,i=R=>r!==null&&r-o()<R,s=()=>r===null?void 0:Math.max(1,r-o());if(i(YE))return h.info("PROCESS","Port reclaim skipped: not enough of the hook budget is left to finish one",{port:e,remainingMs:s(),neededMs:YE}),{reclaimed:!1,reason:"out-of-budget",killedPids:[]};let a=t.listOwners??((R,z)=>n()?dC(R,z):fC(R,z)),c=R=>a(R,s()),u=t.readTable??lC,l=()=>u(s()),d=t.killTree??((R,z)=>nr(R,z)),m=t.dataDir??(()=>Ae),f=t.readIdentity??((R,z)=>yC(R,n(),u,z)),p=await _C(e,{listOwners:c,killTree:d,readOwnedWorker:t.readOwnedWorker??rc,probeHealth:t.probeHealth??(R=>Kr(R,tw)),readIdentity:R=>f(R,s()),minOwnerAgeSeconds:t.minOwnerAgeSeconds??MS(),readHeartbeat:t.readHeartbeat??(()=>EC()),heartbeatStaleMs:t.heartbeatStaleMs??bC(),maxSilentProtectionMs:t.maxSilentProtectionMs??SC,now:o,sleep:t.sleep??(R=>new Promise(z=>setTimeout(z,R))),hasKillBudget:()=>!i(zf)});if(p!==null)return p;if(!n())return{reclaimed:!1,reason:"not-supported",killedPids:[]};let g=await c(e);if(g===null)return{reclaimed:!1,reason:"netstat-unreadable",killedPids:[]};if(g.length===0)return{reclaimed:!1,reason:"no-listener",killedPids:[]};let _=await l();if(_===null)return{reclaimed:!1,reason:"table-unreadable",killedPids:[]};if(g.filter(R=>Le(R)).length>0)return{reclaimed:!1,reason:"owner-alive",killedPids:[]};let v=new Map;for(let R of _){let z=v.get(R.ppid);z?z.push(R):v.set(R.ppid,[R])}let y=new Map,w=new Set,k=R=>{for(let z of v.get(R)??[])w.has(z.pid)||(w.add(z.pid),k(z.pid),JE(z.name)&&y.set(z.pid,z))};for(let R of g)k(R);let A=m();if(A)for(let R of _)y.has(R.pid)||JE(R.name)&&uC(R.cmdline,A)&&y.set(R.pid,R);if(y.size===0)return h.info("PROCESS","Ghost listener owner is dead but no chroma-sidecar descendants found",{port:e,deadOwners:g,processTableRows:_.length,dataDir:A??"(unresolved)"}),{reclaimed:!1,reason:"no-chroma-descendants",killedPids:[]};h.warn("PROCESS","Reclaiming ghost listener: killing dead worker's surviving chroma sidecar chain",{port:e,deadOwners:g,targets:[...y.values()].map(R=>({pid:R.pid,name:R.name}))});let P=[];for(let R of y.values()){if(i(zf))return h.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(z){return h.error("PROCESS","Ghost-port reclaim tree-kill failed",{port:e,pid:R.pid},z instanceof Error?z:new Error(String(z))),{reclaimed:!1,reason:"kill-failed",killedPids:P}}}let j=await c(e);return j!==null&&j.length===0?(h.info("PROCESS","Ghost listener reclaimed \u2014 port is free again",{port:e,killedPids:P}),{reclaimed:!0,killedPids:P}):(h.warn("PROCESS","Ghost-port reclaim killed the sidecar chain but the port is still bound",{port:e,killedPids:P,stillOwnedBy:j}),{reclaimed:!1,reason:"still-bound",killedPids:P})}var vC=12e4,XE={min:1e4,max:36e5};function bC(e=process.env,t=tr){let n=e.CLAUDE_MEM_WORKER_HEARTBEAT_STALE_MS??Oe.loadFromFile(t,!1,{readOnly:!0}).CLAUDE_MEM_WORKER_HEARTBEAT_STALE_MS,o=Number(n);return Number.isSafeInteger(o)&&o>=XE.min&&o<=XE.max?o:vC}var SC=6e5;function EC(e=qe.workerHeartbeat()){try{let t=JSON.parse((0,Bi.readFileSync)(e,"utf8"));if(t&&Number.isSafeInteger(t.pid)&&Number.isFinite(t.beatAtMs)&&Number.isFinite(t.lastResponseAtMs))return{pid:t.pid,beatAtMs:t.beatAtMs,lastResponseAtMs:t.lastResponseAtMs}}catch{}return null}er();var _o=require("fs"),ow=require("module"),Gr=Nt(require("path"),1),wC=["zod/v3","zod/v4","zod/v4-mini"];function nw(e){try{return(0,_o.realpathSync)(e)}catch{return e}}function $C(e,t){let n=Gr.default.relative(t,e);return n!==""&&!n.startsWith("..")&&!Gr.default.isAbsolute(n)}function iw(e){let t;try{let r=JSON.parse((0,_o.readFileSync)(Gr.default.join(e,"package.json"),"utf-8"));t=Object.keys(r?.dependencies??{})}catch{return[]}if(t.length===0)return[];let n=Gr.default.join(e,"node_modules"),o=t.filter(r=>!(0,_o.existsSync)(Gr.default.join(n,...r.split("/"),"package.json")));if(t.includes("zod")&&!o.includes("zod")){let r=(0,ow.createRequire)(Gr.default.join(n,"noop.js")),i=nw(Gr.default.join(n,"zod"));for(let s of wC)try{let a=r.resolve(s,{paths:[n]});$C(nw(a),i)||o.push(s)}catch{o.push(s)}}return o}function uw(e,t,n){let o=process.env[e];if(o){let r=parseInt(o,10);if(Number.isFinite(r)&&r>=n.min&&r<=n.max)return r;h.warn("SYSTEM",`Invalid ${e}, using default`,{value:o,min:n.min,max:n.max})}return t}var ZV=uw("CLAUDE_MEM_HEALTH_TIMEOUT_MS",pr(De.HEALTH_CHECK),{min:500,max:3e5}),VV=uw("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",pr(De.HOOK_READINESS_WAIT),{min:0,max:3e5});var xC={min:500,max:3e5},KV={min:500,max:De.SESSION_INIT_REQUEST_MAX};function lw(e=process.env){let t=e.CLAUDE_MEM_FETCH_VERBOSE;if(t===void 0)return!1;let n=t.trim().toLowerCase();return n==="1"||n==="true"||n==="on"||n==="yes"}function IC(e){return lw()?{...e,verbose:!0}:e}function TC(e){let t={},n=e;for(let o=0;n&&o<4;o++){let r=o===0?"error":`cause${o}`;if(n instanceof Error){let i=n;t[r]={name:n.name,message:n.message,...i.code!==void 0?{code:i.code}:{}},n=n.cause;continue}t[r]=String(n);break}return t}function AC(e,t,n){let o=typeof t.method=="string"?t.method:"GET",r=TC(n),i=JSON.stringify(r);h.warn("SYSTEM","Worker IPC fetch failed",{url:e,method:o},i),Br(`[claude-mem] fetch verbose: ${o} ${e} ${i}
|
|
29
29
|
`)}async function qf(e,t={}){let n=IC(t);try{return await fetch(e,n)}catch(o){throw lw()&&AC(e,t,o),o}}async function Wf(e,t={},n){try{return await qf(e,{...t,signal:AbortSignal.timeout(n)})}catch(o){throw o instanceof DOMException&&o.name==="TimeoutError"?new Error(`Request timed out after ${n}ms`):o}}function OC(e,t){let n=new AbortController,o=null,r=null,i=null,s=!1,a=()=>{r!==null&&(clearTimeout(r),r=null)},c=()=>{s=!0,a(),i!==null&&(clearTimeout(i),i=null)},u=d=>{s||(o=d,c(),n.abort(d))},l=()=>{s||(a(),r=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;i=setTimeout(()=>u(new Error(`Request timed out after ${d}ms`)),d)}return l(),{signal:t?AbortSignal.any([t,n.signal]):n.signal,touch:l,pause:a,dispose:c,translate:d=>o??d}}async function Bf(e,t,n){let o=OC(n,t.signal),r;try{r=await qf(e,{...t,signal:o.signal})}catch(u){throw o.dispose(),o.translate(u)}o.touch();let i=r.body,s=i?i.getReader():null,a=!1;async function*c(){if(!s){a=!0,o.dispose();return}try{for(;;){o.touch();let u;try{u=await s.read()}catch(l){throw a=!0,o.translate(l)}if(u.done){a=!0;return}o.pause(),n.onChunk?.(u.value),yield u.value}}finally{o.dispose(),a||await s.cancel()}}return{status:r.status,statusText:r.statusText,ok:r.ok,headers:r.headers,chunks:c(),cancel:async()=>{o.dispose(),s&&!a&&(a=!0,await s.cancel())}}}async function PC(e,t,n){let o=await Bf(e,t,n),r=new TextDecoder,i="";for await(let s of o.chunks)i+=r.decode(s,{stream:!0});return i+=r.decode(),{status:o.status,statusText:o.statusText,ok:o.ok,headers:o.headers,text:i}}var jf=null,Ff=null,gc=null,hc=null;function sw(){return Ne.default.join(Oe.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function Hf(e={}){return e.readOnly?Oe.loadFromFile(sw(),!0,e):(gc!==null||(gc=Oe.loadFromFile(sw())),gc)}function aw(e,t){if(!e)return null;let n=parseInt(e,10);return Number.isFinite(n)&&n>=t.min&&n<=t.max?n:null}function RC(e,t,n){let o=process.env[e];if(o!==void 0){let s=aw(o,n);return s!==null?s:(h.warn("SYSTEM",`Invalid ${e}, using default`,{value:o,min:n.min,max:n.max}),t)}let r=Hf()[e],i=aw(r,n);return i!==null?i:(h.warn("SYSTEM",`Invalid ${e} in settings.json, using default`,{value:r,min:n.min,max:n.max}),t)}function Zf(e={}){if(!e.readOnly&&jf!==null)return jf;let t=parseInt(Hf(e).CLAUDE_MEM_WORKER_PORT,10);return e.readOnly||(jf=t),t}function Vf(e={}){if(!e.readOnly&&Ff!==null)return Ff;let t=Hf(e).CLAUDE_MEM_WORKER_HOST;return e.readOnly||(Ff=t),t}function CC(){return hc!==null||(hc=RC("CLAUDE_MEM_API_TIMEOUT_MS",pr(De.API_REQUEST),xC)),hc}function Kf(e){return`http://${zi(Vf())}:${Zf()}${e}`}function An(e,t={}){let n=t.method??"GET",o=Kf(e),r={method:n};if(t.headers&&(r.headers=t.headers),t.body&&(r.body=t.body),t.idleTimeoutMs!==void 0&&t.idleTimeoutMs>0)return PC(o,r,{idleTimeoutMs:t.idleTimeoutMs,absoluteCapMs:t.timeoutMs}).then(s=>new Response(s.text.length>0?s.text:null,{status:s.status,statusText:s.statusText,headers:s.headers}));let i=t.timeoutMs??CC();return i>0?Wf(o,r,i):qf(o,r)}function dw(e){let t=(0,gt.existsSync)(Ne.default.join(e,"plugin","scripts"))?Ne.default.join(e,"plugin"):e;return Ne.default.join(t,"scripts","worker-service.cjs")}function MC(e,t){let n=d=>{let m=d.split("-")[0].split(".");return[parseInt(m[0],10)||0,parseInt(m[1],10)||0,parseInt(m[2],10)||0]},[o,r,i]=n(e),[s,a,c]=n(t);if(s!==o)return s-o;if(a!==r)return a-r;if(c!==i)return c-i;let u=e.includes("-")?1:0,l=t.includes("-")?1:0;return u!==l?u-l:e<t?1:e>t?-1:0}function DC(e=Ne.default.join(Ne.default.dirname(Ne.default.dirname(Va)),"cache","thedotmack","claude-mem")){try{return(0,gt.readdirSync)(e).filter(t=>/^\d/.test(t)).map(t=>Ne.default.join(e,t)).filter(t=>{try{if(!(0,gt.statSync)(t).isDirectory())return!1}catch{return!1}return!(0,gt.existsSync)(Ne.default.join(t,".orphaned_at"))}).map(t=>({scriptPath:dw(t),version:Ne.default.basename(t)}))}catch{return[]}}function cw(e){try{let t=JSON.parse((0,gt.readFileSync)(e,"utf-8"));return typeof t.version=="string"?t.version:null}catch(t){let n=t.code;return n!=="ENOENT"&&h.debug("SYSTEM","Could not read package version for worker resolution",{packageJsonPath:e,code:n}),null}}function NC(){return{cacheRoot:Ne.default.join(Ne.default.dirname(Ne.default.dirname(Va)),"cache","thedotmack","claude-mem"),marketplaceRoot:Va,cwd:process.cwd()}}function LC(e=NC()){let t=process.env.CLAUDE_MEM_WORKER_SCRIPT_PATH?.trim();if(t){if((0,gt.existsSync)(t))return{scriptPath:t,version:null};h.debug("SYSTEM","Ignoring missing CLAUDE_MEM_WORKER_SCRIPT_PATH override",{override:t})}let n=[...DC(e.cacheRoot),{scriptPath:dw(Ne.default.join(e.marketplaceRoot,"plugin")),version:cw(Ne.default.join(e.marketplaceRoot,"package.json"))},{scriptPath:Ne.default.join(e.cwd,"plugin","scripts","worker-service.cjs"),version:cw(Ne.default.join(e.cwd,"package.json"))}];return jC(n)}function zC(e){return Ne.default.dirname(Ne.default.dirname(e))}function UC(e){return iw(zC(e.scriptPath)).length===0}function jC(e,t=UC){let n=e.filter(o=>(0,gt.existsSync)(o.scriptPath));return n.length===0?null:(n.sort((o,r)=>o.version===null&&r.version===null?0:o.version===null?1:r.version===null?-1:MC(o.version,r.version)),n.find(t)??n[0])}function _c(){return LC()?.scriptPath??null}var FC=1e3;var qC=5e3,GV=qC+FC;var kI=require("child_process"),xI=require("fs");Me();G();G();var bc=require("fs");G();Me();er();var yc=String.raw`[A-Za-z0-9_.\-+/=~@#$%^*!?]`,WC=`(?=${yc}{8})${yc}*[A-Za-z]${yc}*`,vc=String.raw`(?:\\{0,3}["'])?`,Vi=String.raw`\s{0,8}`;function Gf(e){return new RegExp(`${e}${WC}`,"gi")}function fw(e){return`(?<=${e}${vc}${Vi}[=:]${Vi}${vc})`}var BC=[{name:"aws_access_key",regex:/AKIA[0-9A-Z]{16}/g},{name:"aws_secret_key",regex:/(?<=AWS_SECRET_ACCESS_KEY\s{0,8}[=:]\s{0,8}['"]?)[A-Za-z0-9/+=]{40}/g},{name:"github_pat",regex:/\bgh[oprs]_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{82}\b/g},{name:"openai_key",regex:/\bsk-(?!ant-)[A-Za-z0-9_-]{20,}\b/g},{name:"anthropic_key",regex:/\bsk-ant-[A-Za-z0-9_-]{20,}\b/g},{name:"slack_token",regex:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g},{name:"jwt",regex:/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g},{name:"private_key_pem",regex:/-----BEGIN (?:RSA |DSA |EC |OPENSSH |PGP )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |DSA |EC |OPENSSH |PGP )?PRIVATE KEY-----/g},{name:"stripe_key",regex:/\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]{24,}\b/g},{name:"google_api_key",regex:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:"claude_mem_key",regex:/\bcmem_[A-Za-z0-9_-]{32,}|\bcm_pro_[A-Za-z0-9_-]{8,}/g}],HC=[{name:"generic_password",regex:Gf(fw(String.raw`\b(?:\w*_?(?:password|passwd)|\w+_pwd)`))},{name:"generic_token",regex:Gf(fw(String.raw`\b\w*_(?:token|secret|api_key)`))},{name:"bearer_token",regex:Gf(`(?<=\\bAuthorization${vc}${Vi}:${Vi}${vc}Bearer${Vi})`)}],ZC=1024*1024,VC="<redacted type='oversize'/>";function gw(e,t){if(!t.enabled||e.length===0)return{redacted:e,counts:{},oversize:!1};if(e.length>ZC)return h.warn("REDACT","field exceeds the 1M-char redaction cap; replaced by an oversize marker",void 0,{inputLength:e.length}),{redacted:VC,counts:{oversize:1},oversize:!0};let n=new Set(t.disabledBuiltinPatterns??[]),o={},r=e,i=[];for(let a of t.customPatterns??[]){if(!a.name||a.name.length===0){h.warn("REDACT","custom pattern skipped: missing name",void 0,{pattern:a});continue}try{i.push({name:a.name,regex:new RegExp(a.regex,"g")})}catch(c){h.warn("REDACT","custom pattern skipped: invalid regex",{name:a.name},c instanceof Error?c:new Error(String(c)))}}let s=[...i,...BC,...t.genericEnabled?HC:[]];for(let a of s)n.has(a.name)||(a.regex.lastIndex=0,r=r.replace(a.regex,()=>(o[a.name]=(o[a.name]??0)+1,`<redacted type='${a.name}'/>`)));return t.logMatches&&Object.keys(o).length>0&&h.debug("REDACT","patterns matched",void 0,{counts:o}),{redacted:r,counts:o,oversize:!1}}function KC(e){if(!e||e.trim()==="")return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>n&&typeof n.name=="string"&&typeof n.regex=="string"):(h.warn("REDACT","CLAUDE_MEM_REDACT_CUSTOM_PATTERNS is not a JSON array, ignoring"),[])}catch(t){return h.warn("REDACT","failed to parse CLAUDE_MEM_REDACT_CUSTOM_PATTERNS as JSON",void 0,t instanceof Error?t:new Error(String(t))),[]}}function GC(e){return{enabled:e.CLAUDE_MEM_REDACT_ENABLED==="true",disabledBuiltinPatterns:(e.CLAUDE_MEM_REDACT_DISABLED_BUILTINS??"").split(",").map(t=>t.trim()).filter(Boolean),customPatterns:KC(e.CLAUDE_MEM_REDACT_CUSTOM_PATTERNS??"[]"),logMatches:e.CLAUDE_MEM_REDACT_LOG_MATCHES==="true",genericEnabled:e.CLAUDE_MEM_REDACT_GENERIC_ENABLED==="true"}}var Hi=null,mw=0,JC=5e3,Zi=null,pw=!1,YC={enabled:!0,disabledBuiltinPatterns:[],customPatterns:[],logMatches:!1},XC=/"CLAUDE_MEM_REDACT_ENABLED"\s*:\s*"true"/;function QC(e){if(!(0,bc.existsSync)(e))return null;try{return(0,bc.readFileSync)(e,"utf-8")}catch{return""}}function eM(e){if(e===null)return!1;try{let t=JSON.parse(Hd(e));return t===null||typeof t!="object"||Array.isArray(t)}catch{return!0}}function tM(e,t,n){return process.env.CLAUDE_MEM_REDACT_ENABLED==="false"||!(Zi?.enabled===!0||XC.test(t))?n:(pw||(pw=!0,h.warn("REDACT","settings.json could not be read; secret redaction stays on until it is repaired",{settingsPath:e,using:Zi?.enabled?"the last configuration that loaded":"the built-in patterns"})),Zi?.enabled?Zi:YC)}function hw(e=tr){let t=Date.now();if(Hi&&t-mw<JC)return Hi;let n=Oe.loadFromFile(e),o=GC(n),r=o.enabled?null:QC(e);return eM(r)?Hi=tM(e,r,o):(Hi=o,Zi=o),mw=t,Hi}var rK=new RegExp(`^${yc}{8,}$`);var Jf=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],rM=new Set(Jf),_w=/<([A-Za-z_][A-Za-z0-9_-]*)/y,yw=/<\/([A-Za-z_][A-Za-z0-9_-]*)\s*>/y;function nM(e){let t=Object.fromEntries(Jf.map(l=>[l,0]));if(!e.includes("<"))return{text:e,counts:t,total:0};let n=e.length,o=new Int32Array(n+1);o[n]=n;for(let l=n-1;l>=0;l--)o[l]=e.charCodeAt(l)===62?l:o[l+1];let r=new Map,i=[],s=0,a=0;for(;a<n;){if(e.charCodeAt(a)!==60){a+=1;continue}yw.lastIndex=a;let l=yw.exec(e);if(l){let m=l[1],f=r.get(m),p=f&&f.head<f.items.length?f.items[f.head]:void 0;p&&a>=p.attrEnd&&(f.head+=1,i.push([p.start,a+l[0].length]),t[m]+=1,s+=1),a+=l[0].length;continue}_w.lastIndex=a;let d=_w.exec(e);if(d&&rM.has(d[1])){let m=d[1],f=a+d[0].length,p={start:a,attrEnd:o[f]},g=r.get(m);g?g.items.push(p):r.set(m,{items:[p],head:0}),a=f;continue}a+=1}i.sort((l,d)=>l[0]-d[0]);let c="",u=0;for(let[l,d]of i)l>u&&(c+=e.slice(u,l)),d>u&&(u=d);return c+=e.slice(u),{text:c,counts:t,total:s}}var vw=100;function oM(e){let{text:t,counts:n,total:o}=nM(e);return o>vw&&h.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:o,maxAllowed:vw,contentLength:e.length}),{stripped:gw(t.trim(),hw()).redacted,counts:n}}function iM(e){return oM(e).stripped}var sM=new RegExp(`<(${Jf.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`);function Yf(e){let t=n=>typeof n=="string"?sM.test(n)?iM(n):n:Array.isArray(n)?n.map(t):n!==null&&typeof n=="object"?Object.fromEntries(Object.entries(n).map(([o,r])=>[o,t(r)])):n;return t(e)}var aM=["task-notification"],sK=new RegExp(`^\\s*<(${aM.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),aK=256*1024;var cM=pr(De.API_REQUEST),Wt=class extends Error{kind;status;cause;constructor(t,n,o={}){super(n),this.name="ServerClientError",this.kind=t,this.status=o.status??null,this.cause=o.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)}},Ec=class{baseUrl;apiKey;timeoutMs;constructor(t){this.baseUrl=uM(t.serverBaseUrl),this.apiKey=t.apiKey,this.timeoutMs=t.timeoutMs??cM}async startSession(t,n={}){let o=this.buildStartSessionPayload(t);return this.request("POST","/v1/sessions/start",o,n)}async recordEvent(t){let n=this.buildEventPayload(t),o=t.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",o,n)}async endSession(t){if(!t.sessionId)throw new Wt("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,n={}){let o={projectId:t.projectId};return t.query!==void 0&&(o.query=t.query),t.limit!==void 0&&(o.limit=t.limit),t.summaryLimit!==void 0&&(o.summaryLimit=t.summaryLimit),t.platformSource!==void 0&&(o.platformSource=Sc(t.platformSource)),t.folderProjects&&t.folderProjects.length>0&&(o.folderProjects=t.folderProjects),t.excludeSubagents!==void 0&&(o.excludeSubagents=t.excludeSubagents),this.request("POST","/v1/context",o,n)}async getJobStatus(t){if(!t)throw new Wt("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(t)}`)}buildAddObservationPayload(t){let n=t.content,o=t.kind??"manual",r=typeof t.metadata?.title=="string"?t.metadata.title:void 0;return{projectId:t.projectId,kind:o,content:n,...r?{title:r}:{},...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:Sc(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:Sc(t.platformSource)}:{},...t.metadata!==void 0?{metadata:Yf(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:Sc(t.platformSource)}:{},...t.payload!==void 0?{payload:Yf(t.payload)}:{}}}async request(t,n,o,r={}){if(!this.apiKey||!this.apiKey.trim())throw new Wt("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let i=`${this.baseUrl}${n}`,s={method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};o!==void 0&&(s.body=JSON.stringify(o));let a=d=>{let m=d instanceof Error?d.message:String(d),f=/timed out|timeout/i.test(m)||d instanceof Error&&(d.name==="TimeoutError"||d.name==="AbortError");return new Wt(f?"timeout":"transport",`Server ${t} ${n} failed: ${m}`,{cause:d})},c,u=r.timeoutMs??this.timeoutMs;try{c=await Wf(i,s,u)}catch(d){throw a(d)}if(!c.ok){let d=await c.text().catch(()=>"");throw new Wt("http_error",`Server ${t} ${n} returned ${c.status}: ${lM(d,200)}`,{status:c.status})}let l;try{l=await c.text()}catch(d){throw a(d)}if(!l||l.length===0)return{};try{return JSON.parse(l)}catch(d){let m=d instanceof Error?d:new Error(String(d));throw new Wt("invalid_response",`Server ${t} ${n} returned non-JSON response`,{cause:m})}}};function Xf(e){return e instanceof Wt}function uM(e){return e.replace(/\/+$/,"")}function Sc(e){return typeof e=="string"?mr(e):null}function lM(e,t){return e.length<=t?e:`${e.slice(0,t)}\u2026`}function Jr(){let t=(Ft().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return t==="server"||t==="server-beta"?"server":"worker"}function bw(){let e=Ft(),t=(...s)=>{for(let a of s){let c=(a??"").trim();if(c.length>0)return c}return""},n=t(e.CLAUDE_MEM_SERVER_URL,e.CLAUDE_MEM_SERVER_BETA_URL),o=t(e.CLAUDE_MEM_SERVER_API_KEY,e.CLAUDE_MEM_SERVER_BETA_API_KEY),r=t(e.CLAUDE_MEM_SERVER_PROJECT_ID,e.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!n)return h.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!o)return h.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!r)return h.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let i={serverBaseUrl:n,apiKey:o};return{runtime:"server",client:new Ec(i),projectId:r,serverBaseUrl:n}}var ee={};Tr(ee,{$brand:()=>fm,$input:()=>Ug,$output:()=>zg,INVALID:()=>yt,NEVER:()=>dm,TimePrecision:()=>Yg,ZodAny:()=>D_,ZodArray:()=>U_,ZodBase64:()=>_l,ZodBase64URL:()=>yl,ZodBigInt:()=>ni,ZodBigIntFormat:()=>Sl,ZodBoolean:()=>ri,ZodCIDRv4:()=>gl,ZodCIDRv6:()=>hl,ZodCUID:()=>cl,ZodCUID2:()=>ul,ZodCatch:()=>oy,ZodCodec:()=>qs,ZodCompileAsyncError:()=>ir,ZodCompileUnsupportedError:()=>Q,ZodCreditCard:()=>O_,ZodCustom:()=>Ws,ZodCustomStringFormat:()=>Bn,ZodDate:()=>Ns,ZodDefault:()=>X_,ZodDiscriminatedUnion:()=>F_,ZodE164:()=>vl,ZodEmail:()=>ol,ZodEmoji:()=>sl,ZodEnum:()=>Qo,ZodError:()=>vz,ZodExactOptional:()=>$l,ZodFile:()=>K_,ZodFirstPartyTypeKind:()=>yy,ZodFunction:()=>py,ZodGUID:()=>il,ZodIBAN:()=>P_,ZodIPv4:()=>ml,ZodIPv6:()=>pl,ZodISODate:()=>cn,ZodISODateTime:()=>an,ZodISODuration:()=>ln,ZodISOTime:()=>un,ZodInstanceOf:()=>_y,ZodIntersection:()=>q_,ZodIssueCode:()=>Ez,ZodJWT:()=>bl,ZodKSUID:()=>fl,ZodLazy:()=>dy,ZodLiteral:()=>V_,ZodMAC:()=>A_,ZodMap:()=>H_,ZodNaN:()=>sy,ZodNanoID:()=>al,ZodNever:()=>L_,ZodNonOptional:()=>kl,ZodNull:()=>M_,ZodNullable:()=>Y_,ZodNumber:()=>ti,ZodNumberFormat:()=>Hn,ZodObject:()=>Ls,ZodOptional:()=>js,ZodPipe:()=>Fs,ZodPrefault:()=>ey,ZodPreprocess:()=>ay,ZodPromise:()=>my,ZodReadonly:()=>cy,ZodRealError:()=>Ot,ZodRecord:()=>Xo,ZodSet:()=>Z_,ZodString:()=>ei,ZodStringFormat:()=>pe,ZodSuccess:()=>ny,ZodSymbol:()=>R_,ZodTemplateLiteral:()=>ly,ZodTransform:()=>G_,ZodTuple:()=>W_,ZodType:()=>H,ZodULID:()=>ll,ZodURL:()=>Ms,ZodUUID:()=>br,ZodUndefined:()=>C_,ZodUnion:()=>zs,ZodUnknown:()=>N_,ZodVoid:()=>z_,ZodXID:()=>dl,ZodXor:()=>j_,_ZodString:()=>nl,_default:()=>Q_,_function:()=>oI,any:()=>Ux,array:()=>J,base64:()=>vx,base64url:()=>bx,bigint:()=>Mx,boolean:()=>Re,catch:()=>iy,check:()=>iI,cidrv4:()=>_x,cidrv6:()=>yx,clone:()=>ce,codec:()=>eI,coerce:()=>by,compile:()=>Wg,config:()=>Pe,core:()=>Mr,creditCard:()=>Ex,cuid:()=>ux,cuid2:()=>lx,currencyCode:()=>Tx,custom:()=>xl,date:()=>Fx,decode:()=>E_,decodeAsync:()=>$_,deepPartial:()=>_I,describe:()=>sI,discriminatedUnion:()=>Us,e164:()=>Sx,email:()=>Qk,emoji:()=>ax,encode:()=>S_,encodeAsync:()=>w_,endsWith:()=>Fo,enum:()=>Ge,exactOptional:()=>J_,file:()=>Jx,flattenError:()=>os,float32:()=>Ox,float64:()=>Px,formatError:()=>is,fromJSONSchema:()=>gI,function:()=>oI,getDiscriminatedOption:()=>fg,getErrorMap:()=>$z,globalRegistry:()=>Ve,gt:()=>yr,gte:()=>Ut,guid:()=>ex,hash:()=>Ax,hex:()=>Ix,hostname:()=>xx,httpUrl:()=>sx,iban:()=>wx,includes:()=>Uo,input:()=>vI,instanceof:()=>cI,int:()=>tl,int32:()=>Rx,int64:()=>Dx,intersection:()=>oi,invertCodec:()=>tI,ipv4:()=>px,ipv6:()=>hx,iso:()=>Zn,json:()=>lI,jwt:()=>$x,keyof:()=>qx,ksuid:()=>mx,lazy:()=>fy,length:()=>Fn,literal:()=>N,locales:()=>ks,looseObject:()=>Ke,looseRecord:()=>Zx,lowercase:()=>Lo,lt:()=>_r,lte:()=>zt,mac:()=>gx,map:()=>Vx,maxLength:()=>jn,maxSize:()=>rn,memoizer:()=>ws,meta:()=>aI,mime:()=>Wo,minLength:()=>Cr,minSize:()=>vr,multipleOf:()=>tn,nan:()=>Qx,nanoid:()=>cx,nativeEnum:()=>Gx,negative:()=>Bu,never:()=>El,nonnegative:()=>Zu,nonoptional:()=>ry,nonpositive:()=>Hu,normalize:()=>Bo,null:()=>Ds,nullable:()=>Cs,nullish:()=>Yx,number:()=>ie,object:()=>D,optional:()=>me,output:()=>bI,overwrite:()=>sr,parse:()=>__,parseAsync:()=>y_,partialRecord:()=>Hx,pipe:()=>rl,positive:()=>Wu,prefault:()=>ty,preprocess:()=>Bs,prettifyError:()=>_m,promise:()=>nI,properties:()=>qo,property:()=>Vu,readonly:()=>uy,record:()=>ge,refine:()=>gy,regex:()=>No,regexes:()=>Zt,registry:()=>yu,safeDecode:()=>x_,safeDecodeAsync:()=>T_,safeEncode:()=>k_,safeEncodeAsync:()=>I_,safeParse:()=>v_,safeParseAsync:()=>b_,set:()=>Kx,setErrorMap:()=>wz,size:()=>Un,slugify:()=>Ko,startsWith:()=>jo,strictObject:()=>Wx,string:()=>$,stringFormat:()=>kx,stringbool:()=>uI,success:()=>Xx,superRefine:()=>hy,symbol:()=>Lx,templateLiteral:()=>rI,toJSONSchema:()=>Yu,toLowerCase:()=>Zo,toUpperCase:()=>Vo,toZod:()=>Ki,transform:()=>wl,treeifyError:()=>hm,trim:()=>Ho,tuple:()=>B_,uint32:()=>Cx,uint64:()=>Nx,ulid:()=>dx,undefined:()=>zx,union:()=>de,unknown:()=>ye,uppercase:()=>zo,url:()=>ix,util:()=>x,uuid:()=>tx,uuidv4:()=>rx,uuidv6:()=>nx,uuidv7:()=>ox,validate:()=>Ao,validateAsync:()=>Oo,void:()=>jx,withParser:()=>vu,xid:()=>fx,xor:()=>Bx});var Mr={};Tr(Mr,{$ZodAny:()=>ng,$ZodArray:()=>ug,$ZodAsyncError:()=>Tt,$ZodBase64:()=>Hp,$ZodBase64URL:()=>Zp,$ZodBigInt:()=>ou,$ZodBigIntFormat:()=>Qp,$ZodBoolean:()=>_s,$ZodCIDRv4:()=>Wp,$ZodCIDRv6:()=>Bp,$ZodCUID:()=>Pp,$ZodCUID2:()=>Rp,$ZodCatch:()=>Tg,$ZodCheck:()=>_e,$ZodCheckBigIntFormat:()=>op,$ZodCheckEndsWith:()=>hp,$ZodCheckGreaterThan:()=>qc,$ZodCheckIncludes:()=>pp,$ZodCheckLengthEquals:()=>lp,$ZodCheckLessThan:()=>Fc,$ZodCheckLowerCase:()=>fp,$ZodCheckMaxLength:()=>cp,$ZodCheckMaxSize:()=>ip,$ZodCheckMimeType:()=>vp,$ZodCheckMinLength:()=>up,$ZodCheckMinSize:()=>sp,$ZodCheckMultipleOf:()=>rp,$ZodCheckNumberFormat:()=>np,$ZodCheckOverwrite:()=>bp,$ZodCheckProperties:()=>yp,$ZodCheckProperty:()=>_p,$ZodCheckRegex:()=>dp,$ZodCheckSizeEquals:()=>ap,$ZodCheckStartsWith:()=>gp,$ZodCheckStringFormat:()=>Po,$ZodCheckUpperCase:()=>mp,$ZodCodec:()=>vs,$ZodCreditCard:()=>Kp,$ZodCustom:()=>Dg,$ZodCustomStringFormat:()=>Yp,$ZodCyclicError:()=>du,$ZodDate:()=>ag,$ZodDefault:()=>$g,$ZodDiscriminatedUnion:()=>mg,$ZodE164:()=>Vp,$ZodEmail:()=>kp,$ZodEmoji:()=>Ap,$ZodEncodeError:()=>Qr,$ZodEnum:()=>yg,$ZodError:()=>gm,$ZodExactOptional:()=>Eg,$ZodFile:()=>bg,$ZodFunction:()=>Cg,$ZodGUID:()=>wp,$ZodIBAN:()=>Gp,$ZodIPv4:()=>jp,$ZodIPv6:()=>Fp,$ZodISODate:()=>Lp,$ZodISODateTime:()=>Np,$ZodISODuration:()=>Up,$ZodISOTime:()=>zp,$ZodIntersection:()=>pg,$ZodJWT:()=>Jp,$ZodKSUID:()=>Dp,$ZodLazy:()=>bs,$ZodLiteral:()=>vg,$ZodMAC:()=>qp,$ZodMap:()=>hg,$ZodNaN:()=>Ag,$ZodNanoID:()=>Op,$ZodNever:()=>ig,$ZodNonOptional:()=>xg,$ZodNull:()=>rg,$ZodNullable:()=>wg,$ZodNumber:()=>nu,$ZodNumberFormat:()=>Xp,$ZodObject:()=>u$,$ZodObjectJIT:()=>lg,$ZodOptional:()=>su,$ZodPipe:()=>au,$ZodPrefault:()=>kg,$ZodPreprocess:()=>Og,$ZodPromise:()=>Mg,$ZodReadonly:()=>Pg,$ZodRealError:()=>At,$ZodRecord:()=>gg,$ZodRegistry:()=>_u,$ZodSet:()=>_g,$ZodString:()=>Dn,$ZodStringFormat:()=>ue,$ZodSuccess:()=>Ig,$ZodSymbol:()=>eg,$ZodTemplateLiteral:()=>Rg,$ZodTransform:()=>Sg,$ZodTuple:()=>iu,$ZodType:()=>q,$ZodULID:()=>Cp,$ZodURL:()=>Tp,$ZodUUID:()=>$p,$ZodUndefined:()=>tg,$ZodUnion:()=>ys,$ZodUnknown:()=>og,$ZodVoid:()=>sg,$ZodXID:()=>Mp,$ZodXor:()=>dg,$brand:()=>fm,$constructor:()=>b,$input:()=>Ug,$output:()=>zg,Doc:()=>Mn,INVALID:()=>yt,JSONSchema:()=>Jk,JSONSchemaGenerator:()=>Xu,NEVER:()=>dm,TimePrecision:()=>Yg,URL_BAD_FORMAT:()=>xp,URL_UNPARSEABLE:()=>fs,ZodCompileAsyncError:()=>ir,ZodCompileUnsupportedError:()=>Q,_any:()=>ph,_array:()=>Sh,_base64:()=>Uu,_base64url:()=>ju,_bigint:()=>ah,_boolean:()=>ih,_catch:()=>az,_check:()=>Mk,_cidrv4:()=>Lu,_cidrv6:()=>zu,_coercedBigint:()=>ch,_coercedBoolean:()=>sh,_coercedDate:()=>vh,_coercedNumber:()=>Qg,_coercedString:()=>Vg,_creditCard:()=>Gg,_cuid:()=>Ou,_cuid2:()=>Pu,_custom:()=>wh,_date:()=>yh,_decode:()=>Oc,_decodeAsync:()=>Rc,_default:()=>oz,_discriminatedUnion:()=>ZL,_e164:()=>Fu,_email:()=>Eu,_emoji:()=>Tu,_encode:()=>Ac,_encodeAsync:()=>Pc,_endsWith:()=>Fo,_enum:()=>XL,_file:()=>Eh,_float32:()=>th,_float64:()=>rh,_gt:()=>yr,_gte:()=>Ut,_guid:()=>wu,_iban:()=>Jg,_includes:()=>Uo,_int:()=>eh,_int32:()=>nh,_int64:()=>uh,_intersection:()=>VL,_ipv4:()=>Du,_ipv6:()=>Nu,_isoDate:()=>Ts,_isoDateTime:()=>Is,_isoDuration:()=>Os,_isoTime:()=>As,_jwt:()=>qu,_ksuid:()=>Mu,_lazy:()=>dz,_length:()=>Fn,_literal:()=>ez,_lowercase:()=>Lo,_lt:()=>_r,_lte:()=>zt,_mac:()=>Kg,_map:()=>JL,_max:()=>zt,_maxLength:()=>jn,_maxSize:()=>rn,_mime:()=>Wo,_min:()=>Ut,_minLength:()=>Cr,_minSize:()=>vr,_multipleOf:()=>tn,_nan:()=>bh,_nanoid:()=>Au,_nativeEnum:()=>QL,_negative:()=>Bu,_never:()=>hh,_nonnegative:()=>Zu,_nonoptional:()=>iz,_nonpositive:()=>Hu,_normalize:()=>Bo,_null:()=>mh,_nullable:()=>nz,_number:()=>Xg,_optional:()=>rz,_overwrite:()=>sr,_parse:()=>ko,_parseAsync:()=>xo,_pipe:()=>cz,_positive:()=>Wu,_promise:()=>fz,_properties:()=>qo,_property:()=>Vu,_readonly:()=>uz,_record:()=>GL,_refine:()=>$h,_regex:()=>No,_safeDecode:()=>Mc,_safeDecodeAsync:()=>Nc,_safeEncode:()=>Cc,_safeEncodeAsync:()=>Dc,_safeParse:()=>Io,_safeParseAsync:()=>To,_set:()=>YL,_size:()=>Un,_slugify:()=>Ko,_startsWith:()=>jo,_string:()=>Zg,_stringFormat:()=>qn,_stringbool:()=>Th,_success:()=>sz,_superRefine:()=>kh,_symbol:()=>dh,_templateLiteral:()=>lz,_toLowerCase:()=>Zo,_toUpperCase:()=>Vo,_transform:()=>tz,_trim:()=>Ho,_tuple:()=>KL,_uint32:()=>oh,_uint64:()=>lh,_ulid:()=>Ru,_undefined:()=>fh,_union:()=>BL,_unknown:()=>gh,_uppercase:()=>zo,_url:()=>xs,_uuid:()=>$u,_uuidv4:()=>ku,_uuidv6:()=>xu,_uuidv7:()=>Iu,_void:()=>_h,_xid:()=>Cu,_xor:()=>HL,base64Charset:()=>Xc,base64urlCharset:()=>hs,canParseURL:()=>Ip,clone:()=>ce,compile:()=>Wg,compileFn:()=>bu,config:()=>Pe,createStandardJSONSchemaMethod:()=>Go,createToJSONSchemaMethod:()=>Oh,decode:()=>Mw,decodeAsync:()=>Nw,describe:()=>xh,encode:()=>Cw,encodeAsync:()=>Dw,extractDefs:()=>on,finalize:()=>sn,flattenError:()=>os,formatError:()=>is,getDiscriminatedOption:()=>fg,globalConfig:()=>We,globalRegistry:()=>Ve,handleUnrepresentable:()=>ze,initializeContext:()=>nn,isBackEdge:()=>mu,isRecursiveSchema:()=>fu,isValidBase64:()=>gs,isValidBase64URL:()=>Qc,isValidCIDRv6:()=>Yc,isValidCreditCard:()=>eu,isValidIBAN:()=>tu,isValidIPv6:()=>ps,isValidJWT:()=>ru,locales:()=>ks,memoizer:()=>ws,mergeValues:()=>Ro,meta:()=>Ih,parse:()=>ss,parseAsync:()=>as,parseURLObject:()=>s$,prettifyError:()=>_m,process:()=>le,processSchema:()=>le,regexes:()=>Zt,registry:()=>yu,safeDecode:()=>zw,safeDecodeAsync:()=>jw,safeEncode:()=>Lw,safeEncodeAsync:()=>Uw,safeParse:()=>Tc,safeParseAsync:()=>ym,standardProps:()=>Vc,stripTabAndNewline:()=>ms,toDotPath:()=>Pw,toJSONSchema:()=>Yu,toZod:()=>Ki,treeifyError:()=>hm,urlHostnameOk:()=>Gc,urlProtocolOk:()=>Jc,util:()=>x,validate:()=>Ao,validateAsync:()=>Oo,validateURL:()=>Kc,version:()=>Sp,withParser:()=>vu});var x={};Tr(x,{BIGINT_FORMAT_RANGES:()=>Qi,CONSTANT_CATCH:()=>xc,Class:()=>tm,NUMBER_FORMAT_RANGES:()=>Xi,aborted:()=>_t,allowsEval:()=>om,assert:()=>gM,assertEqual:()=>dM,assertIs:()=>mM,assertNever:()=>pM,assertNotEqual:()=>fM,assignProp:()=>Ze,attachSchema:()=>es,base64ToUint8Array:()=>kw,base64urlToUint8Array:()=>MM,cached:()=>So,captureStackTrace:()=>$c,cleanEnum:()=>CM,cleanRegex:()=>Pr,clone:()=>ce,cloneDef:()=>yM,codePointLength:()=>Rn,constantCatch:()=>um,createTransparentProxy:()=>$M,defineLazy:()=>rm,defineLazyInternal:()=>Z,derived:()=>zM,esc:()=>ht,escapeRegex:()=>Ht,explicitlyAborted:()=>am,extend:()=>IM,finalizeIssue:()=>It,floatSafeRemainder:()=>Gi,getElementAtPath:()=>vM,getEnumValues:()=>vo,getLengthableOrigin:()=>rs,getParsedType:()=>wM,getSizableOrigin:()=>ts,hexToUint8Array:()=>NM,hide:()=>ns,installLazyProp:()=>qM,isObject:()=>Pn,isPlainObject:()=>Bt,issue:()=>$o,joinValues:()=>S,jsonStringifyReplacer:()=>bo,members:()=>cm,merge:()=>AM,mergeDefs:()=>or,normalizeParams:()=>O,nullish:()=>wc,numKeys:()=>EM,objectClone:()=>hM,omit:()=>xM,optionalKeys:()=>sm,own:()=>Xr,parsedType:()=>T,partial:()=>OM,pick:()=>kM,prefixIssues:()=>xt,primitiveTypes:()=>im,promiseAllObject:()=>bM,propertyKeyTypes:()=>Yi,randomString:()=>SM,rawShape:()=>Eo,required:()=>PM,safeExtend:()=>TM,shallowClone:()=>Ji,sizeCaps:()=>wo,slugify:()=>nm,stringifyPrimitive:()=>I,toZod:()=>Ki,uint8ArrayToBase64:()=>xw,uint8ArrayToBase64url:()=>DM,uint8ArrayToHex:()=>LM,unwrapMessage:()=>yo});function dM(e){return e}function fM(e){return e}function Ki(){return e=>e}function mM(e){}function pM(e){throw new Error("Unexpected value in exhaustive check")}function gM(e){}function vo(e){let t=Object.values(e).filter(o=>typeof o=="number");return Object.entries(e).filter(([o,r])=>t.indexOf(+o)===-1).map(([o,r])=>r)}function S(e,t="|"){return e.map(n=>I(n)).join(t)}function bo(e,t){return typeof t=="bigint"?t.toString():t}var em=class{constructor(t){this._getter=t,this._value=void 0}get value(){let t=this._getter;return t!==void 0&&(this._value=t(),this._getter=void 0),this._value}};function So(e){return new em(e)}function wc(e){return e==null}function Pr(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Gi(e,t){let n=e/t,o=Math.round(n),r=4*Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-o)<r?0:n-o}var Sw=Symbol("evaluating");function rm(e,t,n){let o;Object.defineProperty(e,t,{get(){if(o!==Sw)return o===void 0&&(o=Sw,o=n()),o},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function hM(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function Ze(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Eo(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function Or(e){return Eo(e._zod.def)??e._zod.def.shape}function Ew(e,t,n){Object.defineProperty(e,t,{get(){let o=n();return Ze(this,t,o),o},enumerable:!0,configurable:!0})}function ww(e,t,n){t in e?Ze(e,t,n):e[t]=n}function On(e,t,n,o){let r=Or(t);for(let i of n){let s=Object.getOwnPropertyDescriptor(r,i);s.enumerable&&(s.get?Ew(e,i,()=>{let a=t._zod.def.shape[i];return o?o(a,i):a}):ww(e,i,o?o(s.value,i):s.value))}}function _M(e,t){for(let n of Reflect.ownKeys(t)){let o=Object.getOwnPropertyDescriptor(t,n);o.enumerable&&(o.get?Ew(e,n,()=>t[n]):ww(e,n,o.value))}}function or(...e){let t={};for(let n of e){let o=Object.getOwnPropertyDescriptors(n);Object.assign(t,o)}return Object.defineProperties({},t)}function yM(e){return or(e._zod.def)}function vM(e,t){return t?t.reduce((n,o)=>n?.[o],e):e}function bM(e){let t=Object.keys(e),n=t.map(o=>e[o]);return Promise.all(n).then(o=>{let r={};for(let i=0;i<t.length;i++)r[t[i]]=o[i];return r})}function SM(e=10){let t="abcdefghijklmnopqrstuvwxyz",n="";for(let o=0;o<e;o++)n+=t[Math.floor(Math.random()*t.length)];return n}function ht(e){return JSON.stringify(e)}function nm(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var $c="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Pn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var om=So(()=>{if(We.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function Bt(e){if(Pn(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let n=t.prototype;return!(Pn(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Ji(e){return Bt(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function EM(e){let t=0;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}var wM=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},Yi=new Set(["string","number","symbol"]),im=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Ht(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ce(e,t,n){let o=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(o._zod.parent=e),o}function O(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function $M(e){let t;return new Proxy({},{get(n,o,r){return t??(t=e()),Reflect.get(t,o,r)},set(n,o,r,i){return t??(t=e()),Reflect.set(t,o,r,i)},has(n,o){return t??(t=e()),Reflect.has(t,o)},deleteProperty(n,o){return t??(t=e()),Reflect.deleteProperty(t,o)},ownKeys(n){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(n,o){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,o)},defineProperty(n,o,r){return t??(t=e()),Reflect.defineProperty(t,o,r)}})}function I(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function sm(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}var Xi={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Qi={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function kM(e,t){let n=e._zod.def,o=n.checks;if(o&&o.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let i={};return On(i,e,kc(e,t)),ce(e,or(n,{shape:i,checks:[]}))}function kc(e,t){let n=Or(e),o=[];for(let r of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,r)?.enumerable)throw new Error(`Unrecognized key: "${String(r)}"`);t[r]&&o.push(r)}return o}function xM(e,t){let n=e._zod.def,o=n.checks;if(o&&o.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let i=new Set(kc(e,t)),s={};return On(s,e,Reflect.ownKeys(Or(e)).filter(a=>!i.has(a))),ce(e,or(n,{shape:s,checks:[]}))}function IM(e,t){if(!Bt(t))throw new Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let r=Or(e);for(let i of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(r,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return ce(e,or(e._zod.def,{shape:$w(e,t)}))}function $w(e,t){let n={};return On(n,e,Reflect.ownKeys(Or(e))),_M(n,t),n}function TM(e,t){if(!Bt(t))throw new Error("Invalid input to safeExtend: expected a plain object");return ce(e,or(e._zod.def,{shape:$w(e,t)}))}function AM(e,t){if(!t?._zod?.def)throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n={};On(n,e,Reflect.ownKeys(Or(e))),On(n,t,Reflect.ownKeys(Or(t)));let o=or(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return ce(e,o)}function OM(e,t,n,o="partial"){let i=t._zod.def.checks;if(i&&i.length>0)throw new Error(`.${o}() cannot be used on object schemas containing refinements`);let a=n?new Set(kc(t,n)):void 0,c={};return On(c,t,Reflect.ownKeys(Or(t)),e&&((u,l)=>a&&!a.has(l)?u:new e({type:"optional",innerType:u}))),ce(t,or(t._zod.def,{shape:c,checks:[]}))}function PM(e,t,n){let o=n?new Set(kc(t,n)):void 0,r={};return On(r,t,Reflect.ownKeys(Or(t)),(i,s)=>o&&!o.has(s)?i:new e({type:"nonoptional",innerType:i})),ce(t,or(t._zod.def,{shape:r}))}function _t(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function am(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function xt(e,t){return t.map(n=>{var o;return(o=n).path??(o.path=[]),n.path.unshift(e),n})}function yo(e){return typeof e=="string"?e:e?.message}function wo(e){let t=[];for(let n of e??[]){let o=n._zod.def;if(!/_(length|size)$|_equals$/.test(o.check))break;let r=o.maximum??o.length??o.size;r>=0&&t.push([r,n])}return t}function es(e,t,n){var o;for(let r=t;r<e.length;r++)(o=e[r]).schema??(o.schema=n)}function It(e,t,n){var o;let r=e.inst?._zod?.traits;r?.has("$ZodType")&&(r.has("$ZodCheck")?(o=e).schema??(o.schema=e.inst):e.schema=e.inst);let i=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,s=e.message?e.message:yo(e.inst?._zod.def?.error?.(e))??yo(i?.(e))??yo(t?.error?.(e))??yo(n.customError?.(e))??yo(n.localeError?.(e))??"Invalid input",a={};for(let c of Object.keys(e))c==="inst"||c==="schema"||c==="continue"||c==="input"||c==="__proto__"||(a[c]=e[c]);return a.path??(a.path=[]),a.message=s,t?.reportInput&&(a.input=e.input),a}function ts(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}var RM=/[\uD800-\uDBFF]/;function Rn(e){let t=e.length;if(!RM.test(e))return t;let n=t;for(let o=0;o<t-1;o++)(e.charCodeAt(o)&64512)===55296&&(e.charCodeAt(o+1)&64512)===56320&&(n--,o++);return n}function rs(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function T(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function $o(...e){let[t,n,o]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:o}:{...t}}function CM(e){return Object.entries(e).filter(([t,n])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function kw(e){let t=atob(e),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n}function xw(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function MM(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-t.length%4)%4);return kw(t+n)}function DM(e){return xw(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function NM(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let n=new Uint8Array(t.length/2);for(let o=0;o<t.length;o+=2)n[o/2]=Number.parseInt(t.slice(o,o+2),16);return n}function LM(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var tm=class{constructor(...t){}};function cm(e,t){for(let n in t){let o=Object.getOwnPropertyDescriptor(t,n);o.get?Object.defineProperty(e,n,{...o,enumerable:!1}):UM(e,n,o.value)}}function Xr(e,t,n,o=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:o,value:n}),n}function ns(e,t,n){return Xr(e,t,n,!1)}function zM(e,t){for(let n in e){let o=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return Xr(this,n,o(this))},set(r){Xr(this,n,r)}})}return t}function UM(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:Xr(this,t,n.bind(this))},set(o){Xr(this,t,o)}})}function jM(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}var Qf,Yr=!1,FM={configurable:!0,get(){Yr=!0}};function Z(e,t,n){let o=Object.getPrototypeOf(e._zod);if(t in o&&Qf!==e._zod){Qf=void 0;return}Qf=e._zod,Object.defineProperty(o,t,{configurable:!0,get(){Object.defineProperty(this,t,FM);let r=Yr;Yr=!1;try{let i=n(this);return Yr?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:i}),Yr=Yr||r,i}catch(i){throw delete this[t],Yr=Yr||r,i}},set(r){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r})}})}function qM(e,t,n,o){let r=jM(e,t);r&&Object.defineProperty(r,t,{configurable:!0,get(){let i={configurable:!0,writable:!0,enumerable:o,value:void 0};return Object.defineProperty(this,t,i),i.value=n(this),Object.defineProperty(this,t,i),i.value},set(i){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:o,value:i})}})}var xc="~constantCatch";function um(e){let t=()=>e;return t[xc]=!0,t}var Iw,dm=Object.freeze({status:"aborted"}),lm={value:void 0,enumerable:!1},Tw="captureStackTrace"in Error?Error:null;function WM(e){let t=Tw;if(t){let n=t.stackTraceLimit;if(typeof n=="number"){try{t.stackTraceLimit=0}catch{return Tw=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function b(e,t,n,o){let r={};function i(m){this.def=m,this.constr=d,this.traits=new Set}i.prototype=r;let s=n,a=s&&new WeakSet;function c(m,f){if(m._zod){if(m._zod.traits.has(e))return}else{lm.value=new i(f);try{Object.defineProperty(m,"_zod",lm)}finally{lm.value=void 0}}if(m._zod.traits.add(e),t(m,f),a){let g=Object.getPrototypeOf(m),_=m._zod.constr.prototype,E=g;for(;E&&E!==_;)E=Object.getPrototypeOf(E);let v=E??g;a.has(v)||(a.add(v),cm(v,s))}let p=d.prototype;for(let g in p)Object.prototype.hasOwnProperty.call(p,g)&&(g in m||(m[g]=p[g].bind(m)))}let u=o?.Parent??Object;class l extends u{}Object.defineProperty(l,"name",{value:e});function d(m){let f=o?.Parent?WM(l):this;c(f,m);let p=f._zod.deferred;if(p){for(let _ of p)_();f._zod.deferred=void 0}let g=globalThis.__zod_globalConfig?.postProcessor;return g&&g(f),f}return Object.defineProperty(d,"init",{value:c}),Object.defineProperty(d,Symbol.hasInstance,{value:m=>o?.Parent&&m instanceof o.Parent?!0:m?._zod?.traits?.has(e)}),Object.defineProperty(d,"name",{value:e}),d}var fm=Symbol("zod_brand"),Tt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Qr=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}};(Iw=globalThis).__zod_globalConfig??(Iw.__zod_globalConfig={});var We=globalThis.__zod_globalConfig;function Pe(e){return e&&Object.assign(We,e),We}function BM(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,bo,2)),e.message}function HM(e){this._zod.message=e}var ZM={get:BM,set:HM,enumerable:!0,configurable:!0},pm={value:void 0,enumerable:!1},Aw=new WeakSet([Object.prototype,Error.prototype]),Ow=(e,t)=>{e.name="$ZodError",pm.value=t,Object.defineProperty(e,"issues",pm),pm.value=void 0,Object.defineProperty(e,"message",ZM);let n=Object.getPrototypeOf(e);Aw.has(n)||(Aw.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let o=()=>this.message;return Object.defineProperty(this,"toString",{value:o,configurable:!0,writable:!0}),o},set(o){Object.defineProperty(this,"toString",{value:o,configurable:!0,writable:!0})}}))},gm=b("$ZodError",Ow),At=b("$ZodError",Ow,void 0,{Parent:Error});function VM(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||(t==="__proto__"?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function os(e,t=n=>n.message){let n={},o=[];for(let r of e.issues)r.path.length>0?VM(n,r.path[0],()=>[]).push(t(r)):o.push(t(r));return{formErrors:o,fieldErrors:n}}function is(e,t=n=>n.message){let n={_errors:[]},o=(r,i=[])=>{for(let s of r.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>o({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")o({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")o({issues:s.issues},[...i,...s.path]);else{let a=[...i,...s.path];if(a.length===0)n._errors.push(t(s));else{let c=n,u=0;for(;u<a.length;){let l=a[u],d=u===a.length-1;if(l==="_errors"){d&&c._errors.push(t(s)),u++;continue}Object.prototype.hasOwnProperty.call(c,l)||Object.defineProperty(c,l,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let m=c[l];d&&m._errors.push(t(s)),c=m,u++}}}};return o(e),n}function hm(e,t=n=>n.message){let n={errors:[]},o=(r,i=[])=>{var s;for(let a of r.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(c=>o({issues:c},[...i,...a.path]));else if(a.code==="invalid_key")o({issues:a.issues},[...i,...a.path]);else if(a.code==="invalid_element")o({issues:a.issues},[...i,...a.path]);else{let c=[...i,...a.path];if(c.length===0){n.errors.push(t(a));continue}let u=n,l=0;for(;l<c.length;){let d=c[l],m=l===c.length-1;typeof d=="string"?(u.properties??(u.properties={}),Object.prototype.hasOwnProperty.call(u.properties,d)||Object.defineProperty(u.properties,d,{value:{errors:[]},enumerable:!0,writable:!0,configurable:!0}),u=u.properties[d]):(u.items??(u.items=[]),(s=u.items)[d]??(s[d]={errors:[]}),u=u.items[d]),m&&u.errors.push(t(a)),l++}}};return o(e),n}function Pw(e){let t=[],n=e.map(o=>typeof o=="object"?o.key:o);for(let o of n)typeof o=="number"?t.push(`[${o}]`):typeof o=="symbol"?t.push(`[${JSON.stringify(String(o))}]`):/[^\w$]/.test(o)?t.push(`[${JSON.stringify(o)}]`):(t.length&&t.push("."),t.push(o));return t.join("")}function _m(e){let t=[],n=[...e.issues].sort((o,r)=>(o.path??[]).length-(r.path??[]).length);for(let o of n)t.push(`\u2716 ${o.message}`),o.path?.length&&t.push(` \u2192 at ${Pw(o.path)}`);return t.join(`
|
|
@@ -332,7 +332,7 @@ ${typeof n.answer=="string"?n.answer:"No answer returned."}`;break}return En(o)}
|
|
|
332
332
|
`),n.isError===!0):(h.debug("SYSTEM","Omitted unsupported MCP response content",{purpose:e}),En("The tool returned no readable text.",n.isError===!0))}return Wr(e,t)}function LP(e){let t=/^Worker API error \((\d+)\): ([\s\S]*)$/.exec(e);if(!t)return"The worker could not complete this request. Retry after checking the worker connection.";let n=Be(lS(t[2])),o=[n.error,n.fix].filter(r=>typeof r=="string").map(r=>Te(r,"",400)).filter(Boolean);return`Worker request failed (HTTP ${t[1]}).${o.length?`
|
|
333
333
|
${o.join(`
|
|
334
334
|
`)}`:`
|
|
335
|
-
Check the arguments and retry.`}`}function zP(e,t){return e==="missing_api_key"?"The server connection is incomplete. Configure its URL, API key and project before retrying.":e==="timeout"?"The server request timed out. Retry the request.":e==="invalid_response"?"The server returned an unreadable response. Retry or check the server connection.":e==="http_error"?`Server request failed${t?` (HTTP ${t})`:""}. `+(t===401||t===403?"Check the connection and project permissions.":"Check the arguments and retry."):"The server could not be reached. Check the server connection and retry."}var gB={},JW="14.0.0";console.log=(...e)=>{h.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:e})};var UP=null;function jd(){return UP??=RE(process.cwd()),UP}function fS(){let e=sP();return e.present&&!e.loadable?`the installed tree-sitter CLI cannot run on this system${e.reason?` (${e.reason})`:""}: this is a broken-install/environment issue, not an unsupported language`:null}var BP=!1,HP=(()=>{if(typeof __CM_DIRNAME__<"u")return __CM_DIRNAME__;try{return(0,wn.dirname)((0,WP.fileURLToPath)(gB.url))}catch(e){return BP=!0,h.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()}})(),pS=_c()??(0,wn.resolve)(HP,"worker-service.cjs");function YW(){BP&&((0,Fd.existsSync)(pS)||h.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:pS,mcpServerDir:HP}))}function jP(e,t){return e==="/api/memory/save"?"save":e==="/api/observations/batch"?"observations":e==="/api/tool-uses/batch"?"tool-uses":e==="/api/corpus"?t?"corpus-build":"corpus-list":/\/corpus\/[^/]+\/(?:prime|reprime)$/.test(e)?"corpus-prime":/\/corpus\/[^/]+\/rebuild$/.test(e)?"corpus-build":/\/corpus\/[^/]+\/query$/.test(e)?"corpus-query":e==="/api/search"?"search":"context"}async function ut(e,t={}){h.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:e});try{return await sS(()=>XW(e,t),ZP)}catch(n){return h.error("SYSTEM","\u2190 Worker API error",{endpoint:e},n instanceof Error?n:new Error(String(n))),En(LP(n instanceof Error?n.message:""),!0)}}async function XW(e,t){if(t.streamCorpusProgress&&t.body){let o=await RP(e,t.body);return h.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:e}),dS(jP(e,!0),o)}let n;if(t.body)n=await An(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t.body)});else{let o=new URLSearchParams;for(let[r,i]of Object.entries(t.query??{}))i!=null&&o.append(r,String(i));n=await An(`${e}?${o}`)}if(!n.ok){let o=await n.text();throw new Error(`Worker API error (${n.status}): ${o}`)}return h.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:e}),t.text?En(await n.text()):dS(jP(e,!!t.body),await n.json())}async function ZP(){return Jr()==="server"?!1:KP()}async function QW(){try{return(await An("/api/health")).ok}catch(e){return h.debug("SYSTEM","Worker health check failed",{},e instanceof Error?e:new Error(String(e))),!1}}function VP(){if(Jr()!=="server")return null;let t=bw();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 eB(e){if(Xf(e)){let t=e.kind==="transport"&&e.message.includes(" requires CLAUDE_MEM_RUNTIME=server.")?e.message:zP(e.kind,e.status);return{content:En(t).content,isError:!0}}return{content:[{type:"text",text:`Tool error: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}function Fa(e){let t=VP();if(!t)throw new Wt("transport",`${e} requires CLAUDE_MEM_RUNTIME=server. Current runtime is "worker"; use mem_search for worker-mode memory access.`);if(!t.available)throw new Wt("missing_api_key",`${e}: ${t.reason}`);return t}function qa(e,t){return async n=>{try{return await t(n)}catch(o){return Xf(o)?h.warn("SYSTEM",`${e} failed`,{errorKind:o.kind,status:o.status}):h.warn("SYSTEM",`${e} failed`,void 0,o instanceof Error?o:new Error(String(o))),eB(o)}}}var tB=qa("observation_add",async e=>{let t=Fa("observation_add");if(typeof e?.content!="string"||e.content.trim().length===0)throw new Error('observation_add: "content" is required');let o={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}:{}},r=await t.client.addObservation(o);return Wr("observation-add",r)});function Wd(e){return typeof e=="string"?mr(e):null}var rB=qa("observation_record_event",async e=>{let t=Fa("observation_record_event");if(typeof e?.eventType!="string"||e.eventType.trim().length===0)throw new Error('observation_record_event: "eventType" is required');let o={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:Wd(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{},...e.generate!==void 0?{generate:e.generate}:{}},r=await t.client.recordEvent(o);return Wr("event",r)}),nB=qa("observation_search",async e=>{let t=Fa("observation_search");if(typeof e?.query!="string"||e.query.trim().length===0)throw new Error('observation_search: "query" is required');let o={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:Wd(e.platformSource)}:{}},r=await t.client.searchObservations(o);return Wr("server-search",r)}),oB=qa("observation_context",async e=>{let t=Fa("observation_context"),n=typeof e?.query=="string"&&e.query.trim().length>0,r={projectId:e.projectId&&e.projectId.trim().length>0?e.projectId:t.projectId,...n?{query:e.query}:{},...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Wd(e.platformSource)}:{}},i=await t.client.contextObservations(r);return Wr("context",i)});function iB(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 sB(e){let t=iB(e);return t.length===0?{content:[{type:"text",text:'session_start_context: "project" or "projects" is required'}],isError:!0}:ut("/api/context/inject",{query:{projects:t.join(","),...e.platformSource!==void 0?{platformSource:Wd(e.platformSource)}:{},...e.full!==void 0?{full:e.full}:{},...e.colors!==void 0?{colors:e.colors}:{}},text:!0})}var aB=qa("observation_generation_status",async e=>{let t=Fa("observation_generation_status"),n=(e?.jobId??e?.job_id??"").trim();if(!n)throw new Error('observation_generation_status: "jobId" is required');let o=await t.client.getJobStatus(n);return Wr("job",o)});async function KP(){if(await QW())return!0;h.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),YW();try{let e=Zf(),t=await tP(e,pS);return t==="dead"&&h.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 h.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 tt={readOnlyHint:!0},GP=[{name:"mem_search",description:"Search memory through enforced progressive disclosure. Guided mode returns readable mem-search step 1 of 3 (index), a short continuation for step 2 (context), then step 3 (selected details). Follow the next-call instructions and choose only IDs shown in the previous result. Auto mode completes the same bounded pipeline in one call. Use this tool for every memory search.",inputSchema:{type:"object",properties:{mode:{type:"string",enum:["guided","auto"],description:"Guided by default; auto completes index, context and filtered details in one call."},query:{type:"string",description:"Search query; required for a new search, up to 500 characters."},project:{type:"string",description:"Optional project filter."},limit:{type:"integer",minimum:1,maximum:20,description:"Index result count, default 20."},maxDetails:{type:"integer",minimum:1,maximum:5,description:"Maximum full details, default 3."},depthBefore:{type:"integer",minimum:0,maximum:3,description:"Context rows before each selected anchor, default 2."},depthAfter:{type:"integer",minimum:0,maximum:3,description:"Context rows after each selected anchor, default 2."},continuation:{type:"string",minLength:27,maxLength:27,pattern:"^ms_[A-Za-z0-9_-]{24}$",description:"Short opaque continuation from the previous mem_search response."},selectedIds:{type:"array",items:{type:["string","number"]},description:"Only relevant IDs from the previous response."}},additionalProperties:!1},annotations:tt,handler:async e=>{try{if(Jr()==="server")throw new Ua("unsupported_runtime","Use the hosted claude-mem MCP connection for server memory, or select worker runtime for local mem_search.");let t=jd(),n={...iS(e??{},t),searchScope:t.allProjects.join(",")},o=await sS(()=>An("/api/mem-search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),ZP);if(!o.ok)throw new Error(`Worker API error (${o.status})`);let r=await o.json();return{content:r.content.filter(i=>i.type==="text"&&typeof i.text=="string").map(i=>({type:"text",text:i.text})),...r.isError?{isError:!0}:{}}}catch(t){return CP(t)}}},{name:"save_memory",description:"Save an explicit durable note, decision, correction or handoff into worker-mode claude-mem. Use this for your own note taking after searching with mem_search for duplicates. Include project when the note belongs to a specific project. Server runtime uses observation_add to write to the selected server.",inputSchema:{type:"object",properties:{text:{type:"string",description:"Durable memory text."},title:{type:"string",description:"Concise searchable title."},project:{type:"string",description:"Project receiving the note; defaults to the active checkout."},metadata:{type:"object",additionalProperties:!0,description:"Optional provenance or source metadata."}},required:["text"],additionalProperties:!1},handler:async e=>Jr()==="server"?En("save_memory requires worker runtime. To save a note in the selected server, use observation_add with content and optional projectId.",!0):ut("/api/memory/save",{body:{...e,project:e?.project||jd().primary}})},{name:"important_workflow",description:`Use mem_search for all memory search. Guided mode enforces index -> context -> selected details with short opaque continuations. Auto mode performs the same bounded pipeline. Legacy layered workflow:
|
|
335
|
+
Check the arguments and retry.`}`}function zP(e,t){return e==="missing_api_key"?"The server connection is incomplete. Configure its URL, API key and project before retrying.":e==="timeout"?"The server request timed out. Retry the request.":e==="invalid_response"?"The server returned an unreadable response. Retry or check the server connection.":e==="http_error"?`Server request failed${t?` (HTTP ${t})`:""}. `+(t===401||t===403?"Check the connection and project permissions.":"Check the arguments and retry."):"The server could not be reached. Check the server connection and retry."}var gB={},JW="14.0.1";console.log=(...e)=>{h.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:e})};var UP=null;function jd(){return UP??=RE(process.cwd()),UP}function fS(){let e=sP();return e.present&&!e.loadable?`the installed tree-sitter CLI cannot run on this system${e.reason?` (${e.reason})`:""}: this is a broken-install/environment issue, not an unsupported language`:null}var BP=!1,HP=(()=>{if(typeof __CM_DIRNAME__<"u")return __CM_DIRNAME__;try{return(0,wn.dirname)((0,WP.fileURLToPath)(gB.url))}catch(e){return BP=!0,h.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()}})(),pS=_c()??(0,wn.resolve)(HP,"worker-service.cjs");function YW(){BP&&((0,Fd.existsSync)(pS)||h.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:pS,mcpServerDir:HP}))}function jP(e,t){return e==="/api/memory/save"?"save":e==="/api/observations/batch"?"observations":e==="/api/tool-uses/batch"?"tool-uses":e==="/api/corpus"?t?"corpus-build":"corpus-list":/\/corpus\/[^/]+\/(?:prime|reprime)$/.test(e)?"corpus-prime":/\/corpus\/[^/]+\/rebuild$/.test(e)?"corpus-build":/\/corpus\/[^/]+\/query$/.test(e)?"corpus-query":e==="/api/search"?"search":"context"}async function ut(e,t={}){h.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:e});try{return await sS(()=>XW(e,t),ZP)}catch(n){return h.error("SYSTEM","\u2190 Worker API error",{endpoint:e},n instanceof Error?n:new Error(String(n))),En(LP(n instanceof Error?n.message:""),!0)}}async function XW(e,t){if(t.streamCorpusProgress&&t.body){let o=await RP(e,t.body);return h.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:e}),dS(jP(e,!0),o)}let n;if(t.body)n=await An(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t.body)});else{let o=new URLSearchParams;for(let[r,i]of Object.entries(t.query??{}))i!=null&&o.append(r,String(i));n=await An(`${e}?${o}`)}if(!n.ok){let o=await n.text();throw new Error(`Worker API error (${n.status}): ${o}`)}return h.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:e}),t.text?En(await n.text()):dS(jP(e,!!t.body),await n.json())}async function ZP(){return Jr()==="server"?!1:KP()}async function QW(){try{return(await An("/api/health")).ok}catch(e){return h.debug("SYSTEM","Worker health check failed",{},e instanceof Error?e:new Error(String(e))),!1}}function VP(){if(Jr()!=="server")return null;let t=bw();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 eB(e){if(Xf(e)){let t=e.kind==="transport"&&e.message.includes(" requires CLAUDE_MEM_RUNTIME=server.")?e.message:zP(e.kind,e.status);return{content:En(t).content,isError:!0}}return{content:[{type:"text",text:`Tool error: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}function Fa(e){let t=VP();if(!t)throw new Wt("transport",`${e} requires CLAUDE_MEM_RUNTIME=server. Current runtime is "worker"; use mem_search for worker-mode memory access.`);if(!t.available)throw new Wt("missing_api_key",`${e}: ${t.reason}`);return t}function qa(e,t){return async n=>{try{return await t(n)}catch(o){return Xf(o)?h.warn("SYSTEM",`${e} failed`,{errorKind:o.kind,status:o.status}):h.warn("SYSTEM",`${e} failed`,void 0,o instanceof Error?o:new Error(String(o))),eB(o)}}}var tB=qa("observation_add",async e=>{let t=Fa("observation_add");if(typeof e?.content!="string"||e.content.trim().length===0)throw new Error('observation_add: "content" is required');let o={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}:{}},r=await t.client.addObservation(o);return Wr("observation-add",r)});function Wd(e){return typeof e=="string"?mr(e):null}var rB=qa("observation_record_event",async e=>{let t=Fa("observation_record_event");if(typeof e?.eventType!="string"||e.eventType.trim().length===0)throw new Error('observation_record_event: "eventType" is required');let o={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:Wd(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{},...e.generate!==void 0?{generate:e.generate}:{}},r=await t.client.recordEvent(o);return Wr("event",r)}),nB=qa("observation_search",async e=>{let t=Fa("observation_search");if(typeof e?.query!="string"||e.query.trim().length===0)throw new Error('observation_search: "query" is required');let o={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:Wd(e.platformSource)}:{}},r=await t.client.searchObservations(o);return Wr("server-search",r)}),oB=qa("observation_context",async e=>{let t=Fa("observation_context"),n=typeof e?.query=="string"&&e.query.trim().length>0,r={projectId:e.projectId&&e.projectId.trim().length>0?e.projectId:t.projectId,...n?{query:e.query}:{},...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Wd(e.platformSource)}:{}},i=await t.client.contextObservations(r);return Wr("context",i)});function iB(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 sB(e){let t=iB(e);return t.length===0?{content:[{type:"text",text:'session_start_context: "project" or "projects" is required'}],isError:!0}:ut("/api/context/inject",{query:{projects:t.join(","),...e.platformSource!==void 0?{platformSource:Wd(e.platformSource)}:{},...e.full!==void 0?{full:e.full}:{},...e.colors!==void 0?{colors:e.colors}:{}},text:!0})}var aB=qa("observation_generation_status",async e=>{let t=Fa("observation_generation_status"),n=(e?.jobId??e?.job_id??"").trim();if(!n)throw new Error('observation_generation_status: "jobId" is required');let o=await t.client.getJobStatus(n);return Wr("job",o)});async function KP(){if(await QW())return!0;h.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),YW();try{let e=Zf(),t=await tP(e,pS);return t==="dead"&&h.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 h.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 tt={readOnlyHint:!0},GP=[{name:"mem_search",description:"Search memory through enforced progressive disclosure. Guided mode returns readable mem-search step 1 of 3 (index), a short continuation for step 2 (context), then step 3 (selected details). Follow the next-call instructions and choose only IDs shown in the previous result. Auto mode completes the same bounded pipeline in one call. Use this tool for every memory search.",inputSchema:{type:"object",properties:{mode:{type:"string",enum:["guided","auto"],description:"Guided by default; auto completes index, context and filtered details in one call."},query:{type:"string",description:"Search query; required for a new search, up to 500 characters."},project:{type:"string",description:"Optional project filter."},limit:{type:"integer",minimum:1,maximum:20,description:"Index result count, default 20."},maxDetails:{type:"integer",minimum:1,maximum:5,description:"Maximum full details, default 3."},depthBefore:{type:"integer",minimum:0,maximum:3,description:"Context rows before each selected anchor, default 2."},depthAfter:{type:"integer",minimum:0,maximum:3,description:"Context rows after each selected anchor, default 2."},continuation:{type:"string",minLength:27,maxLength:27,pattern:"^ms_[A-Za-z0-9_-]{24}$",description:"Short opaque continuation from the previous mem_search response."},selectedIds:{type:"array",items:{type:["string","number"]},description:"Only relevant IDs from the previous response."}},additionalProperties:!1},annotations:tt,handler:async e=>{try{if(Jr()==="server")throw new Ua("unsupported_runtime","Use the hosted claude-mem MCP connection for server memory, or select worker runtime for local mem_search.");let t=jd(),n={...iS(e??{},t),searchScope:t.allProjects.join(",")},o=await sS(()=>An("/api/mem-search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),ZP);if(!o.ok)throw new Error(`Worker API error (${o.status})`);let r=await o.json();return{content:r.content.filter(i=>i.type==="text"&&typeof i.text=="string").map(i=>({type:"text",text:i.text})),...r.isError?{isError:!0}:{}}}catch(t){return CP(t)}}},{name:"save_memory",description:"Save an explicit durable note, decision, correction or handoff into worker-mode claude-mem. Use this for your own note taking after searching with mem_search for duplicates. Include project when the note belongs to a specific project. Server runtime uses observation_add to write to the selected server.",inputSchema:{type:"object",properties:{text:{type:"string",description:"Durable memory text."},title:{type:"string",description:"Concise searchable title."},project:{type:"string",description:"Project receiving the note; defaults to the active checkout."},metadata:{type:"object",additionalProperties:!0,description:"Optional provenance or source metadata."}},required:["text"],additionalProperties:!1},handler:async e=>Jr()==="server"?En("save_memory requires worker runtime. To save a note in the selected server, use observation_add with content and optional projectId.",!0):ut("/api/memory/save",{body:{...e,project:e?.project||jd().primary}})},{name:"important_workflow",description:`Use mem_search for all memory search. Guided mode enforces index -> context -> selected details with short opaque continuations. Auto mode performs the same bounded pipeline. Legacy layered workflow:
|
|
336
336
|
1. search(query) \u2192 Get index with IDs (~50-100 tokens/result)
|
|
337
337
|
2. timeline(anchor=ID) \u2192 Get context around interesting results
|
|
338
338
|
3. get_observations([IDs]) \u2192 Fetch full details ONLY for filtered IDs
|