claude-mem 13.34.1 → 13.34.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -64,7 +64,7 @@ ${m.stack??""}
64
64
  `)}else go(p+`
65
65
  `)}debug(e,r,n,i){this.log(0,e,r,n,i)}info(e,r,n,i){this.log(1,e,r,n,i)}warn(e,r,n,i){this.log(2,e,r,n,i)}setErrorSink(e){hS=e}error(e,r,n,i){this.log(3,e,r,n,i),this.routeErrorToSink(r,n,i)}routeErrorToSink(e,r,n){try{if(!hS||!(n instanceof Error))return;hS(n)}catch{}}dataIn(e,r,n,i){this.info(e,`\u2192 ${r}`,n,i)}dataOut(e,r,n,i){this.info(e,`\u2190 ${r}`,n,i)}success(e,r,n,i){this.info(e,`\u2713 ${r}`,n,i)}failure(e,r,n,i){this.error(e,`\u2717 ${r}`,n,i)}},S=new gS});function Kf(t){return/^Bearer\s+(.+)$/i.exec(t.trim())?.[1]?.trim()||null}function Lf(t){let e=t.ip||t.socket.remoteAddress||"";return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"||e==="localhost"}function YK(t){let e=Nf(t.header("host")??"");return e==="127.0.0.1"||e==="localhost"||e==="::1"}function Nf(t){let e=t.trim().toLowerCase();if(e.startsWith("[")){let n=e.indexOf("]");return n===-1?e:e.slice(1,n)}let r=e.lastIndexOf(":");return r>-1&&/^\d+$/.test(e.slice(r+1))?e.slice(0,r):e}function qf(t){return!!(t.header("forwarded")||t.header("x-forwarded-for")||t.header("x-forwarded-host")||t.header("x-real-ip"))}var bS=R(()=>{"use strict"});function ooe(t=process.platform){return t==="win32"?8e3:5e3}function QK(t=process.platform){return Uf.SESSION_INIT_HOOK_CAP-ooe(t)}function XK(t){return process.platform==="win32"?Math.round(t*Uf.WINDOWS_MULTIPLIER):t}var Uf,ZK=R(()=>{"use strict";Uf={HEALTH_CHECK:3e3,API_REQUEST:3e4,SESSION_INIT_HOOK_CAP:15e3,SESSION_INIT_REQUEST:1e4,SESSION_INIT_REQUEST_MAX:14e3,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5}});function loe(t){try{return coe.has(new URL(t).protocol)}catch{return!1}}function uoe(t){tL!==t&&(tL=t,S.warn("SDK","CLAUDE_MEM_OPENROUTER_BASE_URL is not an http(s) URL; requests to it will fail until it is fixed",{baseUrl:t}))}function $f(t){let e=(t??"").trim();if(!e)return aoe;if(!loe(e)){uoe(e);let i=e.replace(eL,"");return i.toLowerCase().endsWith(Ff)?i:`${i}${Ff}`}let r=new URL(e),n=r.pathname.replace(eL,"");return r.pathname=n.toLowerCase().endsWith(Ff)?n:`${n}${Ff}`,r.href}function rL(t){try{return new URL(t).hostname.toLowerCase()==="openrouter.ai"}catch{return!1}}var aoe,Ff,coe,eL,tL,Jf=R(()=>{"use strict";oe();aoe="https://openrouter.ai/api/v1/chat/completions",Ff="/chat/completions",coe=new Set(["http:","https:"]),eL=/\/+$/;tL=null});function yoe(t){let e=t.CLAUDE_MEM_OPENROUTER_MODEL;if(typeof e!="string"||!hoe.has(e.trim()))return!1;let r=typeof t.CLAUDE_MEM_OPENROUTER_BASE_URL=="string"?t.CLAUDE_MEM_OPENROUTER_BASE_URL.trim():"";return r===""||rL(r)}function oL(t,e){return(0,ds.join)((0,ds.dirname)(t),`.${(0,ds.basename)(t)}.${e.markerTag}`)}function vS(t,e){try{(0,wo.writeFileSync)(oL(t,e),new Date().toISOString(),{encoding:"utf-8",mode:384})}catch{}}function goe(t){if(typeof t!="string")return null;let e=t.trim();if(e.length===0)return null;try{let r=new URL(e).hostname;if(r===poe||r===foe)return moe}catch{return null}return null}var wo,ds,cu,doe,poe,foe,moe,hoe,nL,iL,sL,xn,Za=R(()=>{"use strict";wo=require("fs"),ds=require("path"),cu=require("os");ZK();bo();Jf();Xa();doe="security_alert",poe="sync-hub.black-pond-afbb.workers.dev",foe="ziczmqtpmaxbornfghye.supabase.co",moe="https://sync.cmem.ai",hoe=new Set(["xiaomi/mimo-v2-flash:free"]);nL=18e4,iL=[{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"}];sL=new Set;xn=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_SESSION_START_INCLUDE_ALL_SOURCES:"false",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_ALLOWED_ORIGINS:"",CLAUDE_MEM_PUBLIC_URL:"",CLAUDE_MEM_API_TIMEOUT_MS:String(XK(Uf.API_REQUEST)),CLAUDE_MEM_SESSION_INIT_TIMEOUT_MS:String(QK()),CLAUDE_MEM_IDLE_EXIT_SEC:"0",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_SKIP_BASH_PATTERNS:"",CLAUDE_MEM_SKIP_SUBAGENT_OBSERVATIONS:"false",CLAUDE_MEM_SKIP_AGENT_TYPES:"",CLAUDE_MEM_CAPTURE_ADVISOR_CALLS:"false",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CODEX_MODEL:"",CLAUDE_MEM_CODEX_PATH:"codex",CLAUDE_MEM_CODEX_REASONING_EFFORT:"low",CLAUDE_MEM_CODEX_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_CODEX_OBSERVATION_BATCH_SIZE:"8",CLAUDE_MEM_CODEX_OBSERVATION_BATCH_MAX_CHARS:"32000",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_API_KEYS:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-flash-latest",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_API_KEYS:"",CLAUDE_MEM_OPENROUTER_MODEL:"cohere/north-mini-code:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_EXTRA_BODY:"",CLAUDE_MEM_OPENROUTER_REASONING_EFFORT:"",CLAUDE_MEM_OPENAI_COMPAT_PRESET:"",CLAUDE_MEM_OPENAI_COMPAT_API_KEY:"",CLAUDE_MEM_OPENAI_COMPAT_API_KEYS:"",CLAUDE_MEM_OPENAI_COMPAT_BASE_URL:"",CLAUDE_MEM_OPENAI_COMPAT_MODEL:"",CLAUDE_MEM_QUOTA_FALLBACK_PROVIDER:"",CLAUDE_MEM_QUOTA_FALLBACK_MODEL:"",CLAUDE_MEM_QUOTA_THRESHOLD_FIVE_HOUR:"0.95",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY:"0.93",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY_OPUS:"0.93",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY_SONNET:"0.92",CLAUDE_MEM_QUOTA_THRESHOLD_OVERAGE:"0.95",CLAUDE_MEM_DATA_DIR:(0,ds.join)((0,cu.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_CLAUDE_CONFIG_DIR:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES:"",CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:"",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_MAIN_AGENT_ONLY:"true",CLAUDE_MEM_REINFORCE_ALPHA:"0",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FILE_READ_GATE_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,ds.join)((0,cu.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_CODEX_SUBAGENT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_OBSERVER_MAX_CONVERSATION_CHARS:"400000",CLAUDE_MEM_OBSERVER_CONTEXT_WINDOW:"",CLAUDE_MEM_OBSERVER_MAX_OUTPUT_TOKENS:"4096",CLAUDE_MEM_OBSERVE_BARE_PROMPTS:"false",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_REDACT_ENABLED:"false",CLAUDE_MEM_REDACT_DISABLED_BUILTINS:"",CLAUDE_MEM_REDACT_CUSTOM_PATTERNS:"[]",CLAUDE_MEM_REDACT_LOG_MATCHES:"false",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_PROJECT_ENVIRONMENTS:"[]",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_CHROMA_MUTATION_TIMEOUT_MS:"600000",CLAUDE_MEM_CHROMA_MAX_PENDING_MUTATIONS:"5000",CLAUDE_MEM_CHROMA_EMBEDDING_FUNCTION:"default",CLAUDE_MEM_CLOUD_SYNC_TOKEN:"",CLAUDE_MEM_CLOUD_SYNC_USER_ID:"",CLAUDE_MEM_CLOUD_SYNC_HUB_URL:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_ID:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_NAME:(0,cu.hostname)(),CLAUDE_MEM_CLOUD_SYNC_WS:"true",CLAUDE_MEM_CLOUD_SYNC_CONTENT_BATCH_SIZE:"40",CLAUDE_MEM_CLOUD_SYNC_REQUEST_TIMEOUT_MS:"90000",CLAUDE_MEM_LLM_TIMEOUT_MS:String(nL),CLAUDE_MEM_FIELD_OPTIMIZE_TIMEOUT_MS:String(nL),CLAUDE_MEM_TV_TOKEN:"",CLAUDE_MEM_PRO_TRIAL_EMAIL:"",CLAUDE_MEM_PRO_TRIAL_AT:"",CLAUDE_MEM_PRO_TRIAL_STATE:"",CLAUDE_MEM_PRO_TRIAL_ENDS_AT:"",CLAUDE_MEM_PRO_PLAN:"",CLAUDE_MEM_PRO_FALLBACK_AT:"",CLAUDE_MEM_PRO_FALLBACK_MESSAGE:"",CLAUDE_MEM_PRO_FALLBACK_ACTION:"",CLAUDE_MEM_PRO_FALLBACK_URL:"",CLAUDE_MEM_PRO_MEMORY_KEY:"",CLAUDE_MEM_PRO_MEMORY_BASE_URL:"",CLAUDE_MEM_PRO_MEMORY_MODEL:"",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_WRAPUPS_ENABLED:"true",CLAUDE_MEM_TELEGRAM_OBSERVATION_ALERTS_ENABLED:"false",CLAUDE_MEM_TELEGRAM_WRAPUP_ROUTES:"{}",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert,sensitive",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_AWARENESS_ENABLED:"true",CLAUDE_MEM_GROK_BOT_AWARENESS_AGENT_IDS:"521e962d-2ec3-4488-bfbc-54d5209ce118,95601360-61f7-4fd9-bb3a-2c976b2b85c0",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_WEBHOOK_URL:"",CLAUDE_MEM_GROK_BOT_WEBHOOK_SECRET:"",CLAUDE_MEM_GROK_BOT_INJECT_ENABLED:"true",CLAUDE_MEM_GROK_BOT_INJECT_AGENT_IDS:"*",CLAUDE_MEM_GROK_BOT_INJECT_TIER:"episode",CLAUDE_MEM_GROK_BOT_INJECT_WINDOW:"80",CLAUDE_MEM_GROK_BOT_INJECT_FALLBACK:"house",CLAUDE_MEM_GROK_BOT_INJECT_PLATFORM_SOURCE:"",CLAUDE_MEM_GROK_BOT_INJECT_PROJECTS_BY_AGENT:"",CLAUDE_MEM_GROK_BOT_INJECT_MAX_LINE_CHARS:"160",CLAUDE_MEM_GROK_BOT_INJECT_DEBOUNCE_MS:"1500",CLAUDE_MEM_GROK_BOT_INJECT_STANDING_LINE:"",CLAUDE_MEM_CCS_ALIGN_ENABLED:"true",CLAUDE_MEM_CCS_ALIGN_VIEWER_IDS:"ccs-align",CLAUDE_MEM_CCS_ALIGN_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_CCS_ALIGN_PATCH_SHADOWS:"false",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:"",CLAUDE_MEM_DEDUP_ENABLED:"false",CLAUDE_MEM_DEDUP_COSINE_THRESHOLD:"0.80",CLAUDE_MEM_DEDUP_IDF_VETO_DF:"10",CLAUDE_MEM_DEDUP_MIN_SHARED_TOKENS:"2",CLAUDE_MEM_DEDUP_MIN_PROJECT_DOCS:"10",CLAUDE_MEM_DEDUP_MAX_SCAN:"2000",CLAUDE_MEM_DEDUP_MAX_BACKFILL_ROWS:"50000",CLAUDE_MEM_WORKER_AUTOSTART:"true",CLAUDE_MEM_PROJECT_NAME_SOURCE:"path"};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){let r=process.env[e]??this.DEFAULTS[e];return e==="CLAUDE_MEM_WORKER_HOST"?this.normalizeWorkerHost(r):r}static normalizeWorkerHost(e){return e==="localhost"?"127.0.0.1":e}static finalizeSettings(e,r){let n=r?this.applyEnvOverrides(e):e;return n.CLAUDE_MEM_WORKER_HOST=this.normalizeWorkerHost(n.CLAUDE_MEM_WORKER_HOST),n}static getInt(e){let r=this.get(e);return parseInt(r,10)}static applyEnvOverrides(e){let r={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(r[n]=process.env[n]);return r}static loadFromFile(e,r=!0){try{if(!(0,wo.existsSync)(e)){let d=this.getAllDefaults();try{_n(e,d,{mode:384});for(let p of iL)vS(e,p);console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(p){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,p instanceof Error?p.message:String(p))}return this.finalizeSettings(d,r)}let n=(0,wo.readFileSync)(e,"utf-8"),i=cS(n),s=Eo(i),o=s!==i,a=uS(i),c=o&&Object.keys(a).some(d=>d!=="env");if(o&&!c)try{_n(e,s,{mode:384}),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(d){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,d instanceof Error?d.message:String(d))}if(s.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES===doe){s={...s,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES};try{_n(e,c?{...a,env:s}:s,{mode:384}),console.warn("[SETTINGS] Migrated Telegram trigger types off the legacy default:",e)}catch(d){console.warn("[SETTINGS] Failed to migrate Telegram trigger types:",e,d instanceof Error?d.message:String(d))}}if(yoe(s)){let d=String(s.CLAUDE_MEM_OPENROUTER_MODEL).trim();s={...s,CLAUDE_MEM_OPENROUTER_MODEL:this.DEFAULTS.CLAUDE_MEM_OPENROUTER_MODEL};try{_n(e,c?{...a,env:s}:s,{mode:384}),console.warn(`[SETTINGS] Migrated OpenRouter model off the retired default ${d} to ${this.DEFAULTS.CLAUDE_MEM_OPENROUTER_MODEL}:`,e)}catch(p){console.warn("[SETTINGS] Failed to migrate the retired OpenRouter model:",e,p instanceof Error?p.message:String(p))}}let l=goe(s.CLAUDE_MEM_CLOUD_SYNC_HUB_URL);if(l!==null){s={...s,CLAUDE_MEM_CLOUD_SYNC_HUB_URL:l};try{_n(e,c?{...a,env:s}:s,{mode:384}),console.warn("[SETTINGS] Migrated cloud sync hub URL to",l,"from a retired hub host:",e)}catch(d){console.warn("[SETTINGS] Failed to migrate cloud sync hub URL:",e,d instanceof Error?d.message:String(d))}}for(let d of iL)if(!(0,wo.existsSync)(oL(e,d))){if(s[d.key]!==d.legacy){vS(e,d);continue}s={...s,[d.key]:this.DEFAULTS[d.key]};try{_n(e,c?{...a,env:s}:s,{mode:384}),vS(e,d),console.warn(`[SETTINGS] Migrated ${d.key} off the old ${d.legacy}ms default to ${this.DEFAULTS[d.key]}ms:`,e)}catch(p){let f=`${d.key}\0${e}`;sL.has(f)||(sL.add(f),console.warn(`[SETTINGS] Failed to migrate ${d.key}; using the new default in memory (reported once per process):`,e,p instanceof Error?p.message:String(p)))}}let u={...this.DEFAULTS};for(let d of Object.keys(this.DEFAULTS))s[d]!==void 0&&(u[d]=s[d]);return this.finalizeSettings(u,r)}catch(n){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,n instanceof Error?n.message:String(n));let i=this.getAllDefaults();return this.finalizeSettings(i,r)}}}});function Bf(t,e){if(!e.enabled||t.length===0)return{redacted:t,counts:{},oversize:!1};if(t.length>voe)return S.warn("REDACT","field exceeds the 1M-char redaction cap; replaced by an oversize marker",void 0,{inputLength:t.length}),{redacted:Eoe,counts:{oversize:1},oversize:!0};let r=new Set(e.disabledBuiltinPatterns??[]),n={},i=t,s=[];for(let a of e.customPatterns??[]){if(!a.name||a.name.length===0){S.warn("REDACT","custom pattern skipped: missing name",void 0,{pattern:a});continue}try{s.push({name:a.name,regex:new RegExp(a.regex,"g")})}catch(c){S.warn("REDACT","custom pattern skipped: invalid regex",{name:a.name},c instanceof Error?c:new Error(String(c)))}}let o=[...s,...boe];for(let a of o)r.has(a.name)||(a.regex.lastIndex=0,i=i.replace(a.regex,()=>(n[a.name]=(n[a.name]??0)+1,`<redacted type='${a.name}'/>`)));return e.logMatches&&Object.keys(n).length>0&&S.debug("REDACT","patterns matched",void 0,{counts:n}),{redacted:i,counts:n,oversize:!1}}function uL(t){return t.includes("<redacted type='")||t.includes("&lt;redacted type=")}function Soe(t){if(!t||t.trim()==="")return[];try{let e=JSON.parse(t);return Array.isArray(e)?e.filter(r=>r&&typeof r.name=="string"&&typeof r.regex=="string"):(S.warn("REDACT","CLAUDE_MEM_REDACT_CUSTOM_PATTERNS is not a JSON array, ignoring"),[])}catch(e){return S.warn("REDACT","failed to parse CLAUDE_MEM_REDACT_CUSTOM_PATTERNS as JSON",void 0,e instanceof Error?e:new Error(String(e))),[]}}function _oe(t){return{enabled:t.CLAUDE_MEM_REDACT_ENABLED==="true",disabledBuiltinPatterns:(t.CLAUDE_MEM_REDACT_DISABLED_BUILTINS??"").split(",").map(e=>e.trim()).filter(Boolean),customPatterns:Soe(t.CLAUDE_MEM_REDACT_CUSTOM_PATTERNS??"[]"),logMatches:t.CLAUDE_MEM_REDACT_LOG_MATCHES==="true"}}function Toe(t){if(!(0,Gf.existsSync)(t))return null;try{return(0,Gf.readFileSync)(t,"utf-8")}catch{return""}}function Aoe(t){if(t===null)return!1;try{let e=JSON.parse(aS(t));return e===null||typeof e!="object"||Array.isArray(e)}catch{return!0}}function koe(t,e,r){return process.env.CLAUDE_MEM_REDACT_ENABLED==="false"||!(uu?.enabled===!0||Ioe.test(e))?r:(cL||(cL=!0,S.warn("REDACT","settings.json could not be read; secret redaction stays on until it is repaired",{settingsPath:t,using:uu?.enabled?"the last configuration that loaded":"the built-in patterns"})),uu?.enabled?uu:woe)}function zf(t=So){let e=Date.now();if(lu&&e-aL<xoe)return lu;let r=xn.loadFromFile(t),n=_oe(r),i=n.enabled?null:Toe(t);return Aoe(i)?lu=koe(t,i,n):(lu=n,uu=n),aL=e,lu}function dL(t){return Bf(t,zf()).redacted}function pL(t,e=zf()){if(!e.enabled)return t;let r=n=>typeof n=="string"?Bf(n,e).redacted:Array.isArray(n)?n.map(r):n!==null&&typeof n=="object"?Object.fromEntries(Object.entries(n).map(([i,s])=>[i,r(s)])):n;return r(t)}var Gf,boe,voe,Eoe,lL,lu,aL,xoe,uu,cL,woe,Ioe,du=R(()=>{"use strict";Gf=require("fs");oe();Za();Rr();bo();boe=[{name:"aws_access_key",regex:/AKIA[0-9A-Z]{16}/g},{name:"aws_secret_key",regex:/(?<=AWS_SECRET_ACCESS_KEY\s*[=:]\s*['"]?)[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}],voe=1024*1024,Eoe="<redacted type='oversize'/>";lL=`If you see a "<redacted type='...'/>" marker, that field was a recognized secret pattern and was removed before storage. Treat it as a placeholder; do not infer the literal value or copy the marker itself into generated memory content.`;lu=null,aL=0,xoe=5e3,uu=null,cL=!1,woe={enabled:!0,disabledBuiltinPatterns:[],customPatterns:[],logMatches:!1},Ioe=/"CLAUDE_MEM_REDACT_ENABLED"\s*:\s*"true"/});function bL(){let t=[];t.push(ES.default.json({limit:"5mb"})),t.push((n,i,s)=>{let a=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(f=>n.path.endsWith(f)),c=n.path==="/api/logs";if(n.path.startsWith("/health")||n.path==="/"||a||c)return s();let l=Date.now(),u=`${n.method}-${Date.now()}`,d=Foe(n.method,n.path,n.body);S.debug("HTTP",`\u2192 ${n.method} ${n.path}`,{requestId:u},d);let p=i.send.bind(i);i.send=function(f){let m=Date.now()-l;return S.debug("HTTP",`\u2190 ${i.statusCode} ${n.path}`,{requestId:u,duration:`${m}ms`}),p(f)},s()});let e=_o(),r=yL.default.join(e,"plugin","ui");return t.push(ES.default.static(r)),t}function Roe(t){return t.startsWith("http://localhost:")||t.startsWith("http://127.0.0.1:")}function vL(t,e){if(!e)return!1;try{return new URL(t).host===e.trim().toLowerCase()}catch{return!1}}function Ooe(t,e,r){let n;try{n=new URL(t)}catch{return!1}if(n.protocol!=="http:"&&n.protocol!=="https:")return!1;if(r.allowedOrigins.includes(n.origin))return!0;if(!e)return!1;if(vL(t,e))return!0;let i;try{i=new URL(`${n.protocol}//${e.trim().toLowerCase()}`)}catch{return!1}return fL.has(n.hostname)&&fL.has(i.hostname)&&n.port===i.port}function EL(t){return(e,r,n)=>{let i=e.headers.origin;if(e.method!=="DELETE"||i===void 0||Ooe(i,e.headers.host,t)){n();return}S.warn("SECURITY","Refused a DELETE from a page other than the viewer",{origin:i,method:e.method,path:e.path}),r.status(403).json({error:"Forbidden",message:"Deletes are accepted only from the claude-mem viewer itself (or an origin in CLAUDE_MEM_ALLOWED_ORIGINS), not from other pages."})}}function Poe(t){let e=new Set(Coe),r=t.workerHost.trim().toLowerCase();r&&e.add(r);for(let n of t.allowedOrigins)try{e.add(new URL(n).hostname.toLowerCase())}catch{}return e}function Moe(t,e){if(!t)return!0;let r=Nf(t);return(0,gL.isIP)(r)!==0||r.endsWith(".localhost")?!0:e.has(r)}function SL(t){let e=Poe(t);return(r,n,i)=>{let s=r.headers.host;if(Moe(s,e)){i();return}let o=Nf(s??"");S.warn("SECURITY","Refused a request whose Host is not a trusted name (DNS rebinding check)",{host:o,method:r.method,path:r.path}),n.status(403).json({error:"Forbidden",message:`Host "${o}" is not trusted. To reach the worker by this name, add its origin (for example http://${s}) to CLAUDE_MEM_ALLOWED_ORIGINS and restart the worker.`})}}function _L(t){let e=new Set(t?.allowedOrigins??[]);return(r,n,i)=>{let s=r.headers.origin;if(s){if(!(Roe(s)||e.has(s.toLowerCase())||t!==void 0&&vL(s,r.headers.host))){n.status(403).json({error:"Forbidden",message:"CORS not allowed"});return}n.setHeader("Access-Control-Allow-Origin",s),n.setHeader("Vary","Origin")}if(r.method==="OPTIONS"){n.setHeader("Access-Control-Allow-Methods","GET,HEAD,POST,PUT,PATCH,DELETE"),n.setHeader("Access-Control-Allow-Headers","Content-Type,Authorization,X-Requested-With"),n.status(204).end();return}i()}}function Hf(t,e,r){let n=t.ip||t.connection.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){S.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:t.path,clientIp:n,method:t.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}r()}function Koe(t,e){let r=(0,ec.createHash)("sha256").update(t,"utf8").digest(),n=(0,ec.createHash)("sha256").update(e,"utf8").digest();if(r.length!==n.length)return!1;try{return(0,ec.timingSafeEqual)(r,n)}catch(i){let s=i instanceof Error?i:new Error(String(i));return S.warn("SECURITY","timing-safe secret comparison failed",{},s),!1}}function Loe(t){return joe.has(t.method.toUpperCase())?Doe.has(t.path)?!t.expectedToken||!t.presentedToken?{allow:!1,status:401,reason:"token"}:Koe(t.presentedToken,t.expectedToken)?{allow:!0}:{allow:!1,status:401,reason:"token"}:{allow:!1,status:404,reason:"path"}:{allow:!1,status:403,reason:"method"}}function qoe(t){let e=Date.now(),r=Io.get(t.clientIp);if(r&&e-r.windowStart>hL&&(r.count=0,r.windowStart=e),!r){if(Io.size>=mL){let n=null,i=1/0;for(let[s,o]of Io)e-o.windowStart>hL?Io.delete(s):o.windowStart<i&&(i=o.windowStart,n=s);n!==null&&Io.size>=mL&&Io.delete(n)}r={count:0,windowStart:e},Io.set(t.clientIp,r)}r.count+=1,r.count<=Noe?S.warn("SECURITY","Remote request denied",t):S.debug("SECURITY","Remote request denied",t)}function Uoe(t){let e=t.query?.token;if(Array.isArray(e)||typeof e!="string")return null;let r=e.trim();return r.length>0?r:null}function xL(t){return(e,r,n)=>{if(Lf(e)&&!qf(e)){n();return}let i=e.ip||e.socket.remoteAddress||"",s=Kf(e.header("authorization")??"")||e.header("x-api-key")?.trim()||Uoe(e)||null,o=Loe({method:e.method,path:e.path,presentedToken:s,expectedToken:t.getToken()});if(!o.allow){qoe({path:e.path,method:e.method,clientIp:i,reason:o.reason}),o.status===404?r.status(404).json({error:"Not found"}):o.status===403?r.status(403).json({error:"Forbidden",message:"Observation TV remote access is read-only"}):r.status(401).json({error:"Unauthorized",message:"Missing or invalid Observation TV token"});return}r.setHeader("Cache-Control","no-store"),n()}}function Foe(t,e,r){if(!r||Object.keys(r).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=r.tool_name||"?",i=r.tool_input;return`tool=${dL(S.formatTool(n,i))}`}return e.includes("/summarize")?"requesting summary":""}var ES,yL,gL,ec,fL,Coe,Doe,joe,Noe,mL,hL,Io,wL=R(()=>{"use strict";ES=Xe(Mf(),1),yL=Xe(require("path"),1),gL=require("net"),ec=require("crypto");Rr();bS();oe();du();fL=new Set(["localhost","127.0.0.1","[::1]"]);Coe=["localhost","host.docker.internal"];Doe=new Set(["/tv","/tv.html","/stream","/api/observations"]),joe=new Set(["GET","HEAD"]);Noe=10,mL=512,hL=6e4,Io=new Map});function IL(t,e,r,n){let i={error:t,message:e};return r&&(i.code=r),n&&(i.details=n),i}function AL(t,e){e.status(404).json(IL("NotFound",`Cannot ${t.method} ${t.path}`))}var tc,TL,kL=R(()=>{"use strict";oe();tc=class extends Error{constructor(r,n=500,i,s){super(r);this.statusCode=n;this.code=i;this.details=s;this.name="AppError"}statusCode;code;details};TL=(t,e,r,n)=>{let i=t instanceof tc?t.statusCode:500;S.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:t.message,code:t instanceof tc?t.code:void 0},t);let s=IL(t.name||"Error",t.message,t instanceof tc?t.code:void 0,t instanceof tc?t.details:void 0);r.status(i).json(s)}});var $oe,Joe,tKe,RL=R(()=>{"use strict";$oe=new Set([".cmd",".bat"]),Joe=new Set([".exe",".com"]),tKe=new Set([...Joe,...$oe])});function rc(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(Boe.has(r)){e[r]=n;continue}_S.has(r)||SS.some(i=>r.startsWith(i))||(e[r]=n)}return e}var SS,_S,Goe,Boe,pu=R(()=>{"use strict";SS=["CLAUDECODE_","CLAUDE_CODE_"],_S=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),Goe=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"]),Boe=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",...Goe])});function PL(t,e,r){if(r.status!==0)return null;if(typeof r.stdout!="string")return S.warn("SYSTEM","captureProcessStartToken: start-token probe returned no stdout",{pid:e,source:t,status:r.status}),null;let n=r.stdout.trim();return n.length>0?n:null}function Hoe(t){xS+=1;let e=(0,wS.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...rc(process.env),LC_ALL:"C",LANG:"C"}});return PL("powershell-cim",t,e)}function Voe(t,e=!1){if(!e){let n=OL.get(t);if(n&&(t===process.pid||Date.now()-n.capturedAtMs<zoe))return n.token}let r=null;try{r=Hoe(t)}catch(n){S.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:n instanceof Error?n.message:String(n)}),r=null}return(r!==null||t!==process.pid)&&OL.set(t,{token:r,capturedAtMs:Date.now()}),r}function ML(t,e){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux"){xS+=1;try{let r=(0,CL.readFileSync)(`/proc/${t}/stat`,"utf-8"),n=r.lastIndexOf(") ");if(n<0)return null;let s=r.slice(n+2).split(" ")[19];return s&&/^\d+$/.test(s)?s:null}catch(r){return S.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}if(process.platform==="win32")return Voe(t,e);xS+=1;try{let r=(0,wS.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...rc(process.env),LC_ALL:"C",LANG:"C"}});return PL("ps-lstart",t,r)}catch(r){return S.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}function Ai(t){return ML(t,!1)}function ki(t,e){if(e===null)return!0;let r=ML(t,!0);return r===null?!0:r===e}var wS,CL,zoe,OL,xS,IS=R(()=>{"use strict";wS=require("child_process"),CL=require("fs");oe();pu();zoe=5e3,OL=new Map,xS=0});async function Yn(t,e={}){let r=e.signalMode==="immediate",n=e.expectedStartToken!==void 0?e.expectedStartToken:Ai(t),i=()=>ki(t,n);if(!i()){S.warn("PROCESS","Skipping tree-kill: root PID was reused since it was captured",{pid:t});return}if(S.debug("PROCESS",`Killing process tree rooted at PID ${t}`,{immediate:r}),process.platform==="win32"){try{await TS("taskkill",["/PID",String(t),"/T","/F"],{timeout:5e3,windowsHide:!0})}catch(s){let o=s.code,a=String(s.stderr??""),c=s instanceof Error?s.message:String(s);if(o===Woe||Yoe.test(`${a} ${c}`)){S.debug("PROCESS","taskkill reported the process was already gone",{pid:t});return}throw new Vf(t,`taskkill failed for PID ${t} (exit ${String(o)}): ${a.trim()||c}`,{cause:s})}return}try{let s=r?"SIGKILL":"SIGTERM",o=await Wf(t);for(let l of o){if(!ki(l.pid,l.startToken)){S.debug("PROCESS",`Skipping ${s}: descendant PID was reused since enumeration`,{pid:l.pid,rootPid:t});continue}try{process.kill(l.pid,s)}catch{}}if(i())try{process.kill(t,s)}catch(l){let u=l instanceof Error?l:new Error(String(l)),d=u.code;d!=="ESRCH"&&S.debug("PROCESS",`Failed to ${s} PID ${t}`,{code:d},u)}else S.warn("PROCESS","Skipping root signal: PID was reused during descendant enumeration",{pid:t,signal:s});r||await new Promise(l=>setTimeout(l,500));let a=i()?await Wf(t):[],c=new Map;for(let l of o)c.set(l.pid,l.startToken);for(let l of a)c.set(l.pid,l.startToken);for(let[l,u]of c){if(!ki(l,u)){S.debug("PROCESS","Skipping SIGKILL: descendant PID was reused since the scan",{pid:l,rootPid:t});continue}try{process.kill(l,"SIGKILL")}catch{}}if(!r&&i())try{process.kill(t,"SIGKILL")}catch{}}catch(s){throw new Vf(t,`tree-kill failed for PID ${t}: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}async function Qoe(){return process.platform==="win32"?eae():process.platform==="linux"?Xoe():Zoe()}function Xoe(){let t=[],e;try{e=(0,Yf.readdirSync)("/proc")}catch(r){return S.warn("PROCESS","Cannot read /proc \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),t}for(let r of e){if(!/^\d+$/.test(r))continue;let n;try{n=(0,Yf.readFileSync)(`/proc/${r}/stat`,"utf-8")}catch{continue}let i=n.lastIndexOf(") ");if(i<0)continue;let s=n.slice(i+2).split(" "),o=Number.parseInt(s[1]??"",10),a=s[19];Number.isFinite(o)&&t.push({pid:Number.parseInt(r,10),ppid:o,startToken:a&&/^\d+$/.test(a)?a:null})}return t}async function Zoe(){let t;try{t=(await TS("ps",["-eo","pid=,ppid=,lstart="],{timeout:1e4,maxBuffer:33554432,env:{...process.env,LC_ALL:"C",LANG:"C"}})).stdout}catch(r){return S.warn("PROCESS","Cannot enumerate the process table \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),[]}let e=[];for(let r of t.split(`
66
66
  `)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);if(!n)continue;let i=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:i.length>0?i:null})}return e}async function eae(){let t;try{t=(await TS("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,@{Name='StartToken';Expression={$_.CreationDate.ToString('yyyyMMddHHmmss.ffffff')}} | ConvertTo-Csv -NoTypeInformation"],{timeout:3e4,windowsHide:!0,maxBuffer:33554432})).stdout}catch(r){return S.warn("PROCESS","Cannot enumerate the Windows process table \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),[]}let e=[];for(let r of t.split(/\r?\n/).slice(1)){let n=r.match(/^"(\d+)","(\d+)","(.*)"$/);if(!n)continue;let i=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:i.length>0?i:null})}return e}async function Wf(t){let e=await Qoe(),r=new Map;for(let o of e){let a=r.get(o.ppid);a?a.push(o):r.set(o.ppid,[o])}let n=new Set([t]),i=[],s=o=>{for(let a of r.get(o)??[])n.has(a.pid)||(n.add(a.pid),s(a.pid),i.push({pid:a.pid,startToken:a.startToken}))};return s(t),i}var DL,Yf,jL,TS,Woe,Yoe,Vf,fu=R(()=>{"use strict";DL=require("child_process"),Yf=require("fs"),jL=require("util");oe();IS();TS=(0,jL.promisify)(DL.execFile),Woe=128,Yoe=/not found|no running instance|no tasks/i,Vf=class extends Error{pid;constructor(e,r,n){super(r,n),this.name="ProcessTreeKillError",this.pid=e}}});function Et(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;return r==="EPERM"?!0:(S.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return S.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function Qf(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!Et(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function To(t){if(!t||!Et(t.pid))return!1;if(!t.startToken)return!0;let e=Ai(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||S.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}function LL(t,e=sae){if(!To(t))return!1;if(t.startToken||e.platform!=="linux")return!0;let r;try{r=e.readCommandLine(t.pid)}catch(i){return S.debug("SYSTEM","Could not read the command line of a token-less worker PID; trusting the live PID",{pid:t.pid,error:i instanceof Error?i.message:String(i)}),!0}let n=r.split("\0").some(i=>KL.default.basename(i)==="worker-service.cjs");return n||S.debug("SYSTEM","Token-less worker PID now belongs to another program (PID reused)",{pid:t.pid}),n}function Xf(){return AS||(AS=new RS),AS}function kS(){let t=oae.shift();t&&t.notify()}var mu,KL,tae,rae,nae,iae,sae,RS,AS,_Ke,oae,ps=R(()=>{"use strict";RL();mu=require("fs"),KL=Xe(require("path"),1);oe();bo();pu();Rr();IS();fu();tae=5e3,rae=1e3,nae=je.supervisorRegistry(),iae=null;sae={platform:process.platform,readCommandLine:t=>(0,mu.readFileSync)(`/proc/${t}/cmdline`,"utf-8")};RS=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(e=nae){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,!(0,mu.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,mu.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[i,s]of Object.entries(n))this.entries.set(i,s)}catch(r){r instanceof Error?S.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):S.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&S.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}retainSupersededEntry(e,r){let n=this.entries.get(e);if(!n||n.pid===r||!Et(n.pid))return;let i=`${e}#superseded:${n.pid}`;this.entries.set(i,n);let s=this.runtimeProcesses.get(e);s&&(this.runtimeProcesses.set(i,s),this.runtimeProcesses.delete(e)),S.warn("SYSTEM","Registry id reused while the previous process was still alive; kept it for reaping",{id:e,supersededId:i,supersededPid:n.pid,incomingPid:r})}register(e,r,n){this.initialize(),this.retainSupersededEntry(e,r.pid),this.entries.set(e,r),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e,r){this.initialize();let n=e,i=this.entries.get(n);r!==void 0&&i?.pid!==r&&(n=`${e}#superseded:${r}`,i=this.entries.get(n),i?.pid!==r)||i&&(this.entries.delete(n),this.runtimeProcesses.delete(n),this.persist(),i?.type==="sdk"&&kS())}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let n=Date.parse(e.startedAt),i=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(i)?0:i)})}getBySession(e){let r=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[n,i]of this.entries)Et(i.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,i.type==="sdk"&&(r+=1));e>0&&this.persist();for(let n=0;n<r;n+=1)kS();return e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;S.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:n,pids:r.map(a=>a.pid)});let i=r.filter(a=>Et(a.pid)),s=new Map(i.map(a=>[a.pid,Ai(a.pid)]));for(let a of i)try{process.platform==="win32"?await Yn(a.pid,{expectedStartToken:s.get(a.pid)??null}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&S.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):S.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}await Qf(i,tae);let o=i.filter(a=>Et(a.pid));for(let a of o){S.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});let c=s.get(a.pid)??null;if(!ki(a.pid,c)){S.warn("SYSTEM","Skipping SIGKILL: session process PID was reused during the grace window",{pid:a.pid,sessionId:n});continue}try{process.platform==="win32"?await Yn(a.pid,{expectedStartToken:c}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(l){l instanceof Error?l.code!=="ESRCH"&&S.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},l):S.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(l)})}}if(o.length>0){let a=Date.now()+rae;for(;Date.now()<a&&o.filter(l=>Et(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let a of r)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of r)a.type==="sdk"&&kS();return S.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:n,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};try{_n(this.registryPath,e),this.persistDegraded=!1}catch(r){this.reportPersistFailure(r)}}reportPersistFailure(e){if(this.persistDegraded)return;this.persistDegraded=!0;let r=e instanceof Error?e:new Error(String(e));S.warn("SYSTEM","Failed to persist supervisor registry; keeping it in memory",{path:this.registryPath},r);try{iae?.({errorCategory:r.code??"unknown"})}catch{}}},AS=null;_Ke=180*1e3,oae=[]});async function qL(t){let e=t.currentPid??process.pid,r=t.pidFilePath??aae,n=t.registry.getAll(),i=[...n].filter(c=>c.pid!==e).sort((c,l)=>Date.parse(l.startedAt)-Date.parse(c.startedAt)),s=new Map,o=new Map;for(let c of i){if(!Et(c.pid)){t.registry.unregister(c.id);continue}o.set(c.id,Ai(c.pid)),s.set(c.id,await Wf(c.pid));try{await NL(c,"SIGTERM")}catch(l){l instanceof Error?S.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:c.pid,pgid:c.pgid,type:c.type},l):S.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(l)})}}await Qf(i,5e3);let a=i.filter(c=>Et(c.pid)||(s.get(c.id)??[]).some(l=>Et(l.pid)));for(let c of a){let l=ki(c.pid,o.get(c.id)??null);l||S.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:c.pid,type:c.type});try{l&&await NL(c,"SIGKILL")}catch(u){u instanceof Error?S.debug("SYSTEM","Failed to force kill child process",{pid:c.pid,pgid:c.pgid,type:c.type},u):S.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(u)})}finally{lae(s.get(c.id)??[],c.pid)}}await Qf(a,1e3);for(let c of i)t.registry.unregister(c.id);for(let c of n.filter(l=>l.pid===e))t.registry.unregister(c.id);cae(r,e),t.registry.pruneDeadEntries()}function cae(t,e,r=!1){if(!(0,nc.existsSync)(t))return;let n=null;try{let o=JSON.parse((0,nc.readFileSync)(t,"utf-8"));n=typeof o.pid=="number"?o.pid:null}catch(o){S.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:o instanceof Error?o.message:String(o)});return}let i=e!==null&&n===e,s=n===null||!Et(n);if(!i&&!(r&&s)){S.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:n,currentPid:e});return}try{(0,nc.rmSync)(t,{force:!0})}catch(o){o instanceof Error?S.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},o):S.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(o)})}}function lae(t,e){for(let{pid:r,startToken:n}of t)if(!(r===e||!Et(r))){if(!ki(r,n)){S.debug("SYSTEM","Skipping reap: PID was recycled during the grace window",{pid:r,rootPid:e});continue}try{process.kill(r,"SIGKILL"),S.debug("SYSTEM","Reaped orphaned descendant during shutdown cascade",{pid:r,rootPid:e})}catch(i){let s=i instanceof Error?i.code:void 0;s!=="ESRCH"&&S.warn("SYSTEM","Failed to reap orphaned descendant during shutdown cascade",{pid:r,rootPid:e,errno:s})}}}async function NL(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}if(e==="SIGKILL"){await Yn(r,{signalMode:"immediate"});return}try{process.kill(r,e)}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}return}await Yn(r)}var nc,aae,UL=R(()=>{"use strict";nc=require("fs");oe();ps();Rr();fu();aae=je.workerPid()});function uae(){let e=Xf().pruneDeadEntries();e>0&&S.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function $L(){ic===null&&(ic=setInterval(uae,FL),ic.unref(),S.debug("SYSTEM","Health checker started",{intervalMs:FL}))}function JL(){ic!==null&&(clearInterval(ic),ic=null,S.debug("SYSTEM","Health checker stopped"))}var FL,ic,GL=R(()=>{"use strict";oe();ps();FL=3e4,ic=null});function fae(t){let e=[];for(let r of t.split(`
67
- `)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);n&&e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),command:n[3].trim()})}return e}async function mae(){let t=await dae("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return fae(t.stdout)}function hae(t,e){let r=t.filter(o=>pae.test(o.command)&&o.pid!==e.selfPid),n=new Set(r.map(o=>o.pid)),i=r.filter(o=>!n.has(o.ppid)),s=i.filter(o=>o.ppid===e.selfPid?!1:o.ppid===1?!0:!e.isAlive(o.ppid));return{matched:r,roots:i,orphans:s}}async function HL(t={}){let e=t.platform??process.platform,r={matched:0,trees:0,orphans:0,killed:0,failed:0,unregistered:0,skipped:null};if(e==="win32")return r.skipped="windows",r;let n=t.readTable??mae,i=t.isAlive??Et,s=t.killTree??(f=>Yn(f,{signalMode:"graceful"})),o=t.selfPid??process.pid,a;try{a=await n()}catch(f){return S.warn("PROCESS","Orphaned chroma-mcp sweep skipped: cannot read the process table",{error:f instanceof Error?f.message:String(f)}),r.skipped="unreadable",r}let{matched:c,roots:l,orphans:u}=hae(a,{isAlive:i,selfPid:o});if(r.matched=c.length,r.trees=l.length,r.orphans=u.length,u.length===0)return S.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:r.matched,trees:r.trees}),r;S.warn("PROCESS","Reaping orphaned chroma-mcp trees left by dead workers",{orphans:u.length,roots:u.map(f=>f.pid)});let d=new Set,p=8;for(let f=0;f<u.length;f+=p){let m=u.slice(f,f+p);(await Promise.allSettled(m.map(b=>s(b.pid)))).forEach((b,v)=>{let E=m[v];b.status==="fulfilled"?(r.killed+=1,d.add(E.pid)):(r.failed+=1,S.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:E.pid,ppid:E.ppid,error:b.reason instanceof Error?b.reason.message:String(b.reason)}))})}if(t.registry)for(let f of t.registry.getAll())f.type==="chroma"&&d.has(f.pid)&&(t.registry.unregister(f.id),r.unregistered+=1);return S.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:r.orphans,killed:r.killed,failed:r.failed,unregistered:r.unregistered}),r}var BL,zL,dae,pae,VL=R(()=>{"use strict";BL=require("child_process"),zL=require("util");oe();fu();ps();dae=(0,zL.promisify)(BL.execFile),pae=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/});function WL(){return gae}function bae(t={}){let e=t.pidFilePath??yae;if(!(0,Ao.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,Ao.readFileSync)(e,"utf-8"))}catch(i){return i instanceof Error?S.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},i):S.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(i)}),(0,Ao.rmSync)(e,{force:!0}),"invalid"}return LL(r)&&r?((t.logAlive??!0)&&S.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(t.removeStale===!1||(S.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,Ao.rmSync)(e,{force:!0})),"stale")}var Ao,yae,OS,gae,YL=R(()=>{"use strict";Ao=require("fs");oe();ps();UL();GL();VL();Rr();ps();yae=je.workerPid(),OS=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),bae({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,HL({registry:this.registry}).catch(r=>{S.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),$L()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){S.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,S.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){i instanceof Error?S.error("SYSTEM","Error during shutdown",{},i):S.error("SYSTEM","Error during shutdown (non-Error)",{error:String(i)});try{await this.stop()}catch(s){s instanceof Error?S.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):S.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(s)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{S.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}JL(),this.stopPromise=qL({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,n){this.registry.register(e,r,n)}unregisterProcess(e,r){this.registry.unregister(e,r)}getRegistry(){return this.registry}},gae=new OS(Xf())});function CS(t,e,r){t.on("finish",async()=>{try{await r()}finally{process.exit(0)}}),t.json(e)}var QL=R(()=>{"use strict"});function PS(t,e=Date.now){return Math.max(0,Math.floor((e()-t)/1e3))}var XL=R(()=>{"use strict"});var ZL=R(()=>{"use strict"});function MS(){let t=Array.from(vae.values()).map(e=>({...e})).sort((e,r)=>e.dependency.localeCompare(r.dependency));return{degraded:t.length>0,statuses:t}}var YKe,vae,eN=R(()=>{"use strict";ZL();YKe=5*6e4,vae=new Map});function DS(t,e){return ko(t)===ko(e)}function tN(t,e){let r=ko(t);return r!==void 0&&r>e}function Sae(t){let e=new Map;if(!t||typeof t!="object")return e;for(let r of Eae){let n=t[r];if(!n||typeof n!="object")continue;let{utilization:i,resetsAt:s}=n,o={};typeof i=="number"&&Number.isFinite(i)&&(o.utilization=i),typeof s=="number"&&Number.isFinite(s)&&(o.resetsAt=ko(s)),(o.utilization!==void 0||o.resetsAt!==void 0)&&e.set(r,o)}return e}function _ae(t,e){return e.status!=="rejected"?!1:!t||t.status!=="rejected"?!0:t.resetsAt!==e.resetsAt}function ko(t){if(!(typeof t!="number"||!Number.isFinite(t)))return t<1e12?t*1e3:t}function xae(t,e){return e!==void 0&&t.profile!==void 0&&t.profile!==e}var Eae,jS,rN,tLe,nN=R(()=>{"use strict";Za();Rr();oe();Eae=["five_hour","seven_day"],jS=class{entries=new Map;rejections=new Map;set(e){if(!e||typeof e!="object")return!1;let{unifiedWindows:r,...n}=e,i=e.rateLimitType??"default",s=this.rejections.get(i),o=Date.now(),a=Sae(r);for(let[d,p]of a){if(d===i)continue;let f=this.entries.get(d),m=f&&!xae(f,e.profile)?f:void 0,h=tN(m?.resetsAt,o)?m?.resetsAt:void 0,b=p.resetsAt??h,v=p.utilization===void 0&&m?.status==="rejected"&&DS(b,m.resetsAt)&&tN(b,o);this.entries.set(d,{rateLimitType:d,...p,resetsAt:b,...v?{status:"rejected"}:{},...e.profile!==void 0?{profile:e.profile}:{},observedAt:o});let E=this.rejections.get(d);E&&p.resetsAt!==void 0&&!DS(p.resetsAt,E.resetsAt)&&this.rejections.delete(d)}let c=e.rateLimitType?a.get(e.rateLimitType):void 0,l={...n,utilization:e.utilization??c?.utilization,resetsAt:ko(e.resetsAt)??c?.resetsAt,overageResetsAt:ko(e.overageResetsAt),observedAt:o};this.entries.set(i,l);let u=_ae(s,l);return l.status==="rejected"?this.rejections.set(i,l):(e.status!==void 0||s&&l.resetsAt!==void 0&&!DS(l.resetsAt,s.resetsAt))&&this.rejections.delete(i),u}get(e){return e?this.entries.get(e):this.entries.get("default")}getMostRecentByWindow(e=Date.now()){let r=n=>{let i=this.entries.get(n);if(!i)return;let s=ko(i.resetsAt);return s!==void 0&&s<=e?{...i,expired:!0}:i};return{five_hour:r("five_hour"),seven_day:r("seven_day"),seven_day_opus:r("seven_day_opus"),seven_day_sonnet:r("seven_day_sonnet"),seven_day_overage_included:r("seven_day_overage_included"),overage:r("overage")}}get size(){return this.entries.size}};rN=new jS;tLe=900*1e3});function Tae(){try{let{dlopen:t,FFIType:e,ptr:r,suffix:n}=require("bun:ffi"),i=t(`kernel32.${n}`,{SetHandleInformation:{args:[e.ptr,e.u32,e.u32],returns:e.i32}}),s=t(`ws2_32.${n}`,{getsockname:{args:[e.u64,e.ptr,e.ptr],returns:e.i32},ntohs:{args:[e.u16],returns:e.u16}});return{setHandleInformation:i.symbols.SetHandleInformation,getsockname:s.symbols.getsockname,ntohs:s.symbols.ntohs,ptr:r}}catch{return null}}function Aae(t){let e=t.address();return!e||typeof e=="string"?null:e.port}function kae(t,e,r){let i=t._handle?.fd;if(typeof i=="number"&&i>0)return i;let s=new Uint8Array(28),o=new Int32Array([16]);for(let a=4;a<Iae;a+=4){if(o[0]=16,s.fill(0),r.getsockname(a,r.ptr(s),r.ptr(o))!==0)continue;if(r.ntohs(s[2]|s[3]<<8)===e)return a}return null}function iN(t){if(process.platform!=="win32")return!1;let e=Aae(t);if(e===null||e<=0)return S.debug("SYSTEM","Windows listen socket inherit clear skipped: no bound port"),!1;let r=Tae();if(!r)return S.warn("SYSTEM","Windows listen socket inherit clear skipped: bun:ffi unavailable"),!1;let n=kae(t,e,r);if(n===null)return S.warn("SYSTEM","Windows listen socket inherit clear skipped: listen handle not found",{port:e}),!1;try{return r.setHandleInformation(n,wae,0)?(S.debug("SYSTEM","Cleared HANDLE_FLAG_INHERIT on Windows listen socket",{port:e,socketHandle:n}),!0):(S.warn("SYSTEM","SetHandleInformation failed to clear HANDLE_FLAG_INHERIT on listen socket",{port:e,socketHandle:n}),!1)}catch(i){let s=i instanceof Error?i:new Error(String(i));return S.warn("SYSTEM","Failed to clear Windows listen socket inherit flag",{port:e,socketHandle:n},s),!1}}var wae,Iae,sN=R(()=>{"use strict";oe();wae=1,Iae=16384});var oN,aN=R(()=>{"use strict";oN=["ready","failed"]});function Cae(){if(LS)return LS.text;let t;try{t=US.readFileSync(KS,"utf-8"),S.debug("SYSTEM","Cached SKILL.md on first request",{path:KS,bytes:Buffer.byteLength(t,"utf-8")})}catch(e){S.debug("SYSTEM","SKILL.md not present, /api/instructions will 404 for topic queries",{path:KS,message:e instanceof Error?e.message:String(e)}),t=null}return LS={text:t},t}function Pae(){if(NS)return NS;let t=new Map;for(let e of oS){let r=hu.default.join(Oae,`${e}.md`);try{t.set(e,US.readFileSync(r,"utf-8"))}catch(n){S.debug("SYSTEM","Operation instruction file not present",{path:r,message:n instanceof Error?n.message:String(n)})}}return t.size>0&&S.debug("SYSTEM","Cached operation instruction files on first request",{count:t.size,operations:Array.from(t.keys())}),NS=t,t}function Mae(t){t.setHeader("X-Content-Type-Options","nosniff"),t.setHeader("X-Frame-Options","DENY"),t.setHeader("X-DNS-Prefetch-Control","off"),t.setHeader("Referrer-Policy","no-referrer"),t.setHeader("Cross-Origin-Opener-Policy","same-origin"),t.setHeader("Cross-Origin-Resource-Policy","same-origin"),t.setHeader("Origin-Agent-Cluster","?1"),t.removeHeader("X-Powered-By")}var cN,lN,US,hu,Rae,uN,Oae,KS,LS,NS,qS,Zf,dN=R(()=>{"use strict";cN=Xe(Mf(),1),lN=Xe(require("http"),1),US=Xe(require("fs"),1),hu=Xe(require("path"),1);FK();oe();wL();kL();YL();ps();pu();QL();XL();eN();nN();sN();aN();Rae=2e3,uN=hu.default.resolve(__CM_DIRNAME__,"../skills/mem-search"),Oae=hu.default.join(uN,"operations"),KS=hu.default.join(uN,"SKILL.md");qS="13.34.1";Zf=class{app;server=null;lastRequestAt=null;inFlightRequests=0;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,cN.default)(),this.app.disable("x-powered-by"),this.setupRemoteReadOnlyGuard(),this.setupSecurityHeaders(),this.setupCors(),this.setupPreBodyParserRoutes(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}getLastRequestAt(){return this.lastRequestAt}getInFlightRequestCount(){return this.inFlightRequests}trackRequestActivity(e){this.lastRequestAt=Date.now(),this.inFlightRequests++;let r=e.socket,n=!1,i=()=>{n||(n=!0,e.off("finish",i),e.off("close",i),r?.off("close",i),this.inFlightRequests--,this.lastRequestAt=Date.now())};e.on("finish",i),e.on("close",i),r?.on("close",i)}async listen(e,r){return new Promise((n,i)=>{let s=lN.default.createServer(this.app),o=c=>{s.off("listening",a),i(c)},a=()=>{s.off("error",o),this.server=s,iN(s),S.info("SYSTEM","HTTP server started",{host:r,port:e,pid:process.pid}),n()};s.once("error",o),s.once("listening",a),s.listen(e,r)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{this.server.close(n=>n?r(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,S.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(AL),this.app.use(TL)}setupMiddleware(){this.app.use((r,n,i)=>{this.trackRequestActivity(n),i()}),bL().forEach(r=>this.app.use(r))}setupRemoteReadOnlyGuard(){this.options.remoteReadOnly&&this.app.use(xL(this.options.remoteReadOnly))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,r,n)=>{Mae(r),n()})}setupCors(){this.options.originPolicy&&(this.app.use(SL(this.options.originPolicy)),this.app.use(EL(this.options.originPolicy))),this.app.use(_L(this.options.originPolicy))}setupPreBodyParserRoutes(){this.options.preBodyParserRoutes?.forEach(e=>e.setupRoutes(this.app))}handleReadyStream(e,r){r.setHeader("Content-Type","text/event-stream"),r.setHeader("Cache-Control","no-cache"),r.setHeader("Connection","keep-alive"),r.flushHeaders();let n=this.options.initPhaseSource,i=()=>n?n.getInitPhase():{phase:this.options.getInitializationComplete()?"ready":"starting"},s=!1,o=null,a=null,c=null,l=e.socket,u=()=>{s=!0,c!==null&&(clearInterval(c),c=null),a!==null&&(a(),a=null),r.off("close",u),l.off("close",u)},d=p=>{if(s||p.phase===o)return;o=p.phase;let f={phase:p.phase,...p.message!==void 0?{message:p.message}:{},version:qS,pid:process.pid};r.write(`event: phase
67
+ `)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);n&&e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),command:n[3].trim()})}return e}async function mae(){let t=await dae("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return fae(t.stdout)}function hae(t,e){let r=t.filter(o=>pae.test(o.command)&&o.pid!==e.selfPid),n=new Set(r.map(o=>o.pid)),i=r.filter(o=>!n.has(o.ppid)),s=i.filter(o=>o.ppid===e.selfPid?!1:o.ppid===1?!0:!e.isAlive(o.ppid));return{matched:r,roots:i,orphans:s}}async function HL(t={}){let e=t.platform??process.platform,r={matched:0,trees:0,orphans:0,killed:0,failed:0,unregistered:0,skipped:null};if(e==="win32")return r.skipped="windows",r;let n=t.readTable??mae,i=t.isAlive??Et,s=t.killTree??(f=>Yn(f,{signalMode:"graceful"})),o=t.selfPid??process.pid,a;try{a=await n()}catch(f){return S.warn("PROCESS","Orphaned chroma-mcp sweep skipped: cannot read the process table",{error:f instanceof Error?f.message:String(f)}),r.skipped="unreadable",r}let{matched:c,roots:l,orphans:u}=hae(a,{isAlive:i,selfPid:o});if(r.matched=c.length,r.trees=l.length,r.orphans=u.length,u.length===0)return S.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:r.matched,trees:r.trees}),r;S.warn("PROCESS","Reaping orphaned chroma-mcp trees left by dead workers",{orphans:u.length,roots:u.map(f=>f.pid)});let d=new Set,p=8;for(let f=0;f<u.length;f+=p){let m=u.slice(f,f+p);(await Promise.allSettled(m.map(b=>s(b.pid)))).forEach((b,v)=>{let E=m[v];b.status==="fulfilled"?(r.killed+=1,d.add(E.pid)):(r.failed+=1,S.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:E.pid,ppid:E.ppid,error:b.reason instanceof Error?b.reason.message:String(b.reason)}))})}if(t.registry)for(let f of t.registry.getAll())f.type==="chroma"&&d.has(f.pid)&&(t.registry.unregister(f.id),r.unregistered+=1);return S.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:r.orphans,killed:r.killed,failed:r.failed,unregistered:r.unregistered}),r}var BL,zL,dae,pae,VL=R(()=>{"use strict";BL=require("child_process"),zL=require("util");oe();fu();ps();dae=(0,zL.promisify)(BL.execFile),pae=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/});function WL(){return gae}function bae(t={}){let e=t.pidFilePath??yae;if(!(0,Ao.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,Ao.readFileSync)(e,"utf-8"))}catch(i){return i instanceof Error?S.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},i):S.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(i)}),(0,Ao.rmSync)(e,{force:!0}),"invalid"}return LL(r)&&r?((t.logAlive??!0)&&S.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(t.removeStale===!1||(S.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,Ao.rmSync)(e,{force:!0})),"stale")}var Ao,yae,OS,gae,YL=R(()=>{"use strict";Ao=require("fs");oe();ps();UL();GL();VL();Rr();ps();yae=je.workerPid(),OS=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),bae({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,HL({registry:this.registry}).catch(r=>{S.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),$L()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){S.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,S.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){i instanceof Error?S.error("SYSTEM","Error during shutdown",{},i):S.error("SYSTEM","Error during shutdown (non-Error)",{error:String(i)});try{await this.stop()}catch(s){s instanceof Error?S.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):S.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(s)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{S.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}JL(),this.stopPromise=qL({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,n){this.registry.register(e,r,n)}unregisterProcess(e,r){this.registry.unregister(e,r)}getRegistry(){return this.registry}},gae=new OS(Xf())});function CS(t,e,r){t.on("finish",async()=>{try{await r()}finally{process.exit(0)}}),t.json(e)}var QL=R(()=>{"use strict"});function PS(t,e=Date.now){return Math.max(0,Math.floor((e()-t)/1e3))}var XL=R(()=>{"use strict"});var ZL=R(()=>{"use strict"});function MS(){let t=Array.from(vae.values()).map(e=>({...e})).sort((e,r)=>e.dependency.localeCompare(r.dependency));return{degraded:t.length>0,statuses:t}}var YKe,vae,eN=R(()=>{"use strict";ZL();YKe=5*6e4,vae=new Map});function DS(t,e){return ko(t)===ko(e)}function tN(t,e){let r=ko(t);return r!==void 0&&r>e}function Sae(t){let e=new Map;if(!t||typeof t!="object")return e;for(let r of Eae){let n=t[r];if(!n||typeof n!="object")continue;let{utilization:i,resetsAt:s}=n,o={};typeof i=="number"&&Number.isFinite(i)&&(o.utilization=i),typeof s=="number"&&Number.isFinite(s)&&(o.resetsAt=ko(s)),(o.utilization!==void 0||o.resetsAt!==void 0)&&e.set(r,o)}return e}function _ae(t,e){return e.status!=="rejected"?!1:!t||t.status!=="rejected"?!0:t.resetsAt!==e.resetsAt}function ko(t){if(!(typeof t!="number"||!Number.isFinite(t)))return t<1e12?t*1e3:t}function xae(t,e){return e!==void 0&&t.profile!==void 0&&t.profile!==e}var Eae,jS,rN,tLe,nN=R(()=>{"use strict";Za();Rr();oe();Eae=["five_hour","seven_day"],jS=class{entries=new Map;rejections=new Map;set(e){if(!e||typeof e!="object")return!1;let{unifiedWindows:r,...n}=e,i=e.rateLimitType??"default",s=this.rejections.get(i),o=Date.now(),a=Sae(r);for(let[d,p]of a){if(d===i)continue;let f=this.entries.get(d),m=f&&!xae(f,e.profile)?f:void 0,h=tN(m?.resetsAt,o)?m?.resetsAt:void 0,b=p.resetsAt??h,v=p.utilization===void 0&&m?.status==="rejected"&&DS(b,m.resetsAt)&&tN(b,o);this.entries.set(d,{rateLimitType:d,...p,resetsAt:b,...v?{status:"rejected"}:{},...e.profile!==void 0?{profile:e.profile}:{},observedAt:o});let E=this.rejections.get(d);E&&p.resetsAt!==void 0&&!DS(p.resetsAt,E.resetsAt)&&this.rejections.delete(d)}let c=e.rateLimitType?a.get(e.rateLimitType):void 0,l={...n,utilization:e.utilization??c?.utilization,resetsAt:ko(e.resetsAt)??c?.resetsAt,overageResetsAt:ko(e.overageResetsAt),observedAt:o};this.entries.set(i,l);let u=_ae(s,l);return l.status==="rejected"?this.rejections.set(i,l):(e.status!==void 0||s&&l.resetsAt!==void 0&&!DS(l.resetsAt,s.resetsAt))&&this.rejections.delete(i),u}get(e){return e?this.entries.get(e):this.entries.get("default")}getMostRecentByWindow(e=Date.now()){let r=n=>{let i=this.entries.get(n);if(!i)return;let s=ko(i.resetsAt);return s!==void 0&&s<=e?{...i,expired:!0}:i};return{five_hour:r("five_hour"),seven_day:r("seven_day"),seven_day_opus:r("seven_day_opus"),seven_day_sonnet:r("seven_day_sonnet"),seven_day_overage_included:r("seven_day_overage_included"),overage:r("overage")}}get size(){return this.entries.size}};rN=new jS;tLe=900*1e3});function Tae(){try{let{dlopen:t,FFIType:e,ptr:r,suffix:n}=require("bun:ffi"),i=t(`kernel32.${n}`,{SetHandleInformation:{args:[e.ptr,e.u32,e.u32],returns:e.i32}}),s=t(`ws2_32.${n}`,{getsockname:{args:[e.u64,e.ptr,e.ptr],returns:e.i32},ntohs:{args:[e.u16],returns:e.u16}});return{setHandleInformation:i.symbols.SetHandleInformation,getsockname:s.symbols.getsockname,ntohs:s.symbols.ntohs,ptr:r}}catch{return null}}function Aae(t){let e=t.address();return!e||typeof e=="string"?null:e.port}function kae(t,e,r){let i=t._handle?.fd;if(typeof i=="number"&&i>0)return i;let s=new Uint8Array(28),o=new Int32Array([16]);for(let a=4;a<Iae;a+=4){if(o[0]=16,s.fill(0),r.getsockname(a,r.ptr(s),r.ptr(o))!==0)continue;if(r.ntohs(s[2]|s[3]<<8)===e)return a}return null}function iN(t){if(process.platform!=="win32")return!1;let e=Aae(t);if(e===null||e<=0)return S.debug("SYSTEM","Windows listen socket inherit clear skipped: no bound port"),!1;let r=Tae();if(!r)return S.warn("SYSTEM","Windows listen socket inherit clear skipped: bun:ffi unavailable"),!1;let n=kae(t,e,r);if(n===null)return S.warn("SYSTEM","Windows listen socket inherit clear skipped: listen handle not found",{port:e}),!1;try{return r.setHandleInformation(n,wae,0)?(S.debug("SYSTEM","Cleared HANDLE_FLAG_INHERIT on Windows listen socket",{port:e,socketHandle:n}),!0):(S.warn("SYSTEM","SetHandleInformation failed to clear HANDLE_FLAG_INHERIT on listen socket",{port:e,socketHandle:n}),!1)}catch(i){let s=i instanceof Error?i:new Error(String(i));return S.warn("SYSTEM","Failed to clear Windows listen socket inherit flag",{port:e,socketHandle:n},s),!1}}var wae,Iae,sN=R(()=>{"use strict";oe();wae=1,Iae=16384});var oN,aN=R(()=>{"use strict";oN=["ready","failed"]});function Cae(){if(LS)return LS.text;let t;try{t=US.readFileSync(KS,"utf-8"),S.debug("SYSTEM","Cached SKILL.md on first request",{path:KS,bytes:Buffer.byteLength(t,"utf-8")})}catch(e){S.debug("SYSTEM","SKILL.md not present, /api/instructions will 404 for topic queries",{path:KS,message:e instanceof Error?e.message:String(e)}),t=null}return LS={text:t},t}function Pae(){if(NS)return NS;let t=new Map;for(let e of oS){let r=hu.default.join(Oae,`${e}.md`);try{t.set(e,US.readFileSync(r,"utf-8"))}catch(n){S.debug("SYSTEM","Operation instruction file not present",{path:r,message:n instanceof Error?n.message:String(n)})}}return t.size>0&&S.debug("SYSTEM","Cached operation instruction files on first request",{count:t.size,operations:Array.from(t.keys())}),NS=t,t}function Mae(t){t.setHeader("X-Content-Type-Options","nosniff"),t.setHeader("X-Frame-Options","DENY"),t.setHeader("X-DNS-Prefetch-Control","off"),t.setHeader("Referrer-Policy","no-referrer"),t.setHeader("Cross-Origin-Opener-Policy","same-origin"),t.setHeader("Cross-Origin-Resource-Policy","same-origin"),t.setHeader("Origin-Agent-Cluster","?1"),t.removeHeader("X-Powered-By")}var cN,lN,US,hu,Rae,uN,Oae,KS,LS,NS,qS,Zf,dN=R(()=>{"use strict";cN=Xe(Mf(),1),lN=Xe(require("http"),1),US=Xe(require("fs"),1),hu=Xe(require("path"),1);FK();oe();wL();kL();YL();ps();pu();QL();XL();eN();nN();sN();aN();Rae=2e3,uN=hu.default.resolve(__CM_DIRNAME__,"../skills/mem-search"),Oae=hu.default.join(uN,"operations"),KS=hu.default.join(uN,"SKILL.md");qS="13.34.2";Zf=class{app;server=null;lastRequestAt=null;inFlightRequests=0;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,cN.default)(),this.app.disable("x-powered-by"),this.setupRemoteReadOnlyGuard(),this.setupSecurityHeaders(),this.setupCors(),this.setupPreBodyParserRoutes(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}getLastRequestAt(){return this.lastRequestAt}getInFlightRequestCount(){return this.inFlightRequests}trackRequestActivity(e){this.lastRequestAt=Date.now(),this.inFlightRequests++;let r=e.socket,n=!1,i=()=>{n||(n=!0,e.off("finish",i),e.off("close",i),r?.off("close",i),this.inFlightRequests--,this.lastRequestAt=Date.now())};e.on("finish",i),e.on("close",i),r?.on("close",i)}async listen(e,r){return new Promise((n,i)=>{let s=lN.default.createServer(this.app),o=c=>{s.off("listening",a),i(c)},a=()=>{s.off("error",o),this.server=s,iN(s),S.info("SYSTEM","HTTP server started",{host:r,port:e,pid:process.pid}),n()};s.once("error",o),s.once("listening",a),s.listen(e,r)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{this.server.close(n=>n?r(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,S.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(AL),this.app.use(TL)}setupMiddleware(){this.app.use((r,n,i)=>{this.trackRequestActivity(n),i()}),bL().forEach(r=>this.app.use(r))}setupRemoteReadOnlyGuard(){this.options.remoteReadOnly&&this.app.use(xL(this.options.remoteReadOnly))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,r,n)=>{Mae(r),n()})}setupCors(){this.options.originPolicy&&(this.app.use(SL(this.options.originPolicy)),this.app.use(EL(this.options.originPolicy))),this.app.use(_L(this.options.originPolicy))}setupPreBodyParserRoutes(){this.options.preBodyParserRoutes?.forEach(e=>e.setupRoutes(this.app))}handleReadyStream(e,r){r.setHeader("Content-Type","text/event-stream"),r.setHeader("Cache-Control","no-cache"),r.setHeader("Connection","keep-alive"),r.flushHeaders();let n=this.options.initPhaseSource,i=()=>n?n.getInitPhase():{phase:this.options.getInitializationComplete()?"ready":"starting"},s=!1,o=null,a=null,c=null,l=e.socket,u=()=>{s=!0,c!==null&&(clearInterval(c),c=null),a!==null&&(a(),a=null),r.off("close",u),l.off("close",u)},d=p=>{if(s||p.phase===o)return;o=p.phase;let f={phase:p.phase,...p.message!==void 0?{message:p.message}:{},version:qS,pid:process.pid};r.write(`event: phase
68
68
  data: ${JSON.stringify(f)}
69
69
 
70
70
  `),oN.includes(p.phase)&&(u(),r.end())};r.on("close",u),l.on("close",u),n&&(a=n.subscribeInitPhase(d)),d(i()),!s&&(c=setInterval(()=>{s||(r.write(`: ping
@@ -390,7 +390,7 @@ data:
390
390
  LIMIT $4)
391
391
  )
392
392
  ORDER BY e.occurred_at ASC, e.id ASC
393
- `,[e.serverSessionId,e.projectId,e.teamId,r])).rows.map(S0e)}}});function U$(t){let e=w0e.safeParse(t);if(!e.success)throw new _d(e.error.issues);return e.data}var tr,Gc,N$,q$,_0e,x0e,w0e,_d,zh=R(()=>{"use strict";tr=require("zod"),Gc={event:"server_beta_generate_event",summary:"server_beta_generate_summary"},N$={event:"evt",summary:"sum"},q$=tr.z.object({team_id:tr.z.string().min(1,"team_id is required"),project_id:tr.z.string().min(1,"project_id is required"),source_type:tr.z.enum(["agent_event","session_summary","observation_reindex"]),source_id:tr.z.string().min(1,"source_id is required"),generation_job_id:tr.z.string().min(1,"generation_job_id is required"),api_key_id:tr.z.string().min(1).nullable(),actor_id:tr.z.string().min(1).nullable(),source_adapter:tr.z.string().min(1,"source_adapter is required"),request_id:tr.z.string().min(1).nullable().optional()}),_0e=q$.extend({kind:tr.z.literal("event"),agent_event_id:tr.z.string().min(1)}),x0e=q$.extend({kind:tr.z.literal("summary"),server_session_id:tr.z.string().min(1)}),w0e=tr.z.discriminatedUnion("kind",[_0e,x0e]),_d=class extends Error{issues;constructor(e){super(`invalid server generation job payload: ${e.map(r=>r.message).join("; ")}`),this.issues=e}}});function Bc(t){let e=N$[t.kind],r=JSON.stringify({kind:t.kind,team_id:t.team_id,project_id:t.project_id,source_type:t.source_type,source_id:t.source_id}),n=(0,F$.createHash)("sha256").update(r).digest("hex");return`${e}_${n}`}var F$,a1=R(()=>{"use strict";F$=require("crypto");zh()});function $$(t){return{kind:"event",team_id:t.event.teamId,project_id:t.event.projectId,source_type:"agent_event",source_id:t.event.id,generation_job_id:t.outboxId,agent_event_id:t.event.id,api_key_id:t.apiKeyId,actor_id:t.actorId,source_adapter:t.sourceAdapter??t.event.sourceAdapter??"api",request_id:t.requestId}}var J$,Hh,G$=R(()=>{"use strict";oc();ms();Ko();oe();a1();Tn();J$="observation_generate_for_event",Hh=class{constructor(e){this.options=e}options;async ingestOne(e,r={}){let n=r.generate??!0,i=r.source??"http_post_v1_events",s=await kn(this.options.pool,async a=>{let l=await new Zr(a).create(e);if(!n)return{event:l,outbox:null};let u=new dt(a),d=new Wt(a),p=et(),f=$$({outboxId:p,event:l,apiKeyId:r.apiKeyId??null,actorId:r.actorId??null,sourceAdapter:r.sourceAdapter??null,requestId:r.requestId??null}),m=await u.create({id:p,projectId:l.projectId,teamId:l.teamId,sourceType:"agent_event",sourceId:l.id,agentEventId:l.id,serverSessionId:l.serverSessionId,jobType:J$,bullmqJobId:Bc({kind:"event",team_id:l.teamId,project_id:l.projectId,source_type:"agent_event",source_id:l.id}),payload:f});return await d.append({generationJobId:m.id,projectId:m.projectId,teamId:m.teamId,eventType:"queued",statusAfter:m.status,attempt:m.attempts,details:{source:i}}),{event:l,outbox:m}}),o="skipped";return s.outbox&&(o=await this.publishEventJob(s.event,s.outbox)),{event:s.event,outbox:s.outbox,enqueueState:o}}async ingestBatch(e,r={}){let n=r.generate??!0,i=r.source??"http_post_v1_events_batch",s=await kn(this.options.pool,async o=>{let a=new Zr(o),c=new dt(o),l=new Wt(o),u=[];for(let d of e){let p=await a.create(d);if(!n){u.push({event:p,outbox:null});continue}let f=et(),m=$$({outboxId:f,event:p,apiKeyId:r.apiKeyId??null,actorId:r.actorId??null,sourceAdapter:r.sourceAdapter??null,requestId:r.requestId??null}),h=await c.create({id:f,projectId:p.projectId,teamId:p.teamId,sourceType:"agent_event",sourceId:p.id,agentEventId:p.id,serverSessionId:p.serverSessionId,jobType:J$,bullmqJobId:Bc({kind:"event",team_id:p.teamId,project_id:p.projectId,source_type:"agent_event",source_id:p.id}),payload:m});await l.append({generationJobId:h.id,projectId:h.projectId,teamId:h.teamId,eventType:"queued",statusAfter:h.status,attempt:h.attempts,details:{source:i}}),u.push({event:p,outbox:h})}return u});return Promise.all(s.map(async({event:o,outbox:a})=>{let c=a?await this.publishEventJob(o,a):"skipped";return{event:o,outbox:a,enqueueState:c}}))}async publishEventJob(e,r){let n=this.options.resolveEventQueue();if(!n)return"queued_only";let i=r.bullmqJobId??Bc({kind:"event",team_id:e.teamId,project_id:e.projectId,source_type:"agent_event",source_id:e.id});try{return await n.add(i,r.payload),"enqueued"}catch(s){return S.warn("SYSTEM","failed to publish event generation job to BullMQ",{outboxId:r.id,error:s instanceof Error?s.message:String(s)}),"queued_only"}}}});function c1(t){return Bc({kind:"summary",team_id:t.teamId,project_id:t.projectId,source_type:"session_summary",source_id:t.serverSessionId})}function l1(t){return{kind:"summary",team_id:t.teamId,project_id:t.projectId,source_type:"session_summary",source_id:t.serverSessionId,generation_job_id:t.generationJobId,server_session_id:t.serverSessionId,api_key_id:t.apiKeyId??null,actor_id:t.actorId??null,source_adapter:t.sourceAdapter??"api",request_id:t.requestId??null}}var B$=R(()=>{"use strict";a1()});var I0e,Vh,z$=R(()=>{"use strict";ms();Ko();Ps();oe();B$();Tn();I0e="observation_generate_session_summary",Vh=class{constructor(e){this.options=e}options;async end(e){let r=e.source??"http_post_v1_sessions_end",n=await kn(this.options.pool,async s=>{let a=await new Gt(s).endSession({id:e.sessionId,projectId:e.projectId,teamId:e.teamId});if(!a)return{session:null,outbox:null};let c=new dt(s),l=new Wt(s),u=et(),d=l1({serverSessionId:a.id,teamId:a.teamId,projectId:a.projectId,generationJobId:u,apiKeyId:e.apiKeyId??null,actorId:e.actorId??null,sourceAdapter:e.sourceAdapter??null}),p=await c.create({id:u,projectId:a.projectId,teamId:a.teamId,sourceType:"session_summary",sourceId:a.id,serverSessionId:a.id,jobType:I0e,bullmqJobId:c1({serverSessionId:a.id,teamId:a.teamId,projectId:a.projectId}),payload:d});return await l.append({generationJobId:p.id,projectId:p.projectId,teamId:p.teamId,eventType:"queued",statusAfter:p.status,attempt:p.attempts,details:{source:r}}),{session:a,outbox:p}});if(!n.session||!n.outbox)return{session:n.session,outbox:null,enqueueState:"skipped"};let i=await this.publishSummaryJob(n.session.id,n.outbox,e);return{session:n.session,outbox:n.outbox,enqueueState:i}}async publishSummaryJob(e,r,n){let i=this.options.resolveSummaryQueue();if(!i)return"queued_only";let s=r.bullmqJobId??c1({serverSessionId:e,teamId:r.teamId,projectId:r.projectId}),o=l1({serverSessionId:e,teamId:r.teamId,projectId:r.projectId,generationJobId:r.id,apiKeyId:n.apiKeyId??null,actorId:n.actorId??null,sourceAdapter:n.sourceAdapter??null});try{return await i.add(s,o),"enqueued"}catch(a){return S.warn("SYSTEM","failed to publish summary generation job to BullMQ",{outboxId:r.id,error:a instanceof Error?a.message:String(a)}),"queued_only"}}}});var H$=R(()=>{"use strict"});function V$(t){return`${(process.env.CLAUDE_MEM_PUBLIC_URL??`${t.protocol}://${t.get("host")??"localhost"}`).replace(/\/+$/,"")}/v1/mcp`}function W$(t,e){return`claude mcp add --transport http claude-mem ${t} --header "Authorization: Bearer ${e}"`}async function X$(t,e,r=r3,n=C0e){if(Q$.includes(e.status))return{job:e,timedOut:!1};let i=Date.now()+r,s=e;for(;Date.now()<i;){await new Promise(a=>setTimeout(a,n));let o=await t.getByIdForScope({id:e.id,projectId:e.projectId,teamId:e.teamId});if(!o)return{job:s,timedOut:!1};if(s=o,Q$.includes(o.status))return{job:o,timedOut:!1}}return{job:s,timedOut:!0}}function M0e(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&n3.has(e)?e:null,n=typeof t.query.source_type=="string"?t.query.source_type.trim():"",i=n&&P0e.has(n)?n:null,s=Yh(t.query.limit,i3,1,s3),o=Yh(t.query.offset,0,0,Number.MAX_SAFE_INTEGER),a=typeof t.query.since=="string"?t.query.since.trim():"",c=null;if(a){let l=new Date(a);Number.isNaN(l.getTime())||(c=l)}return{status:r,sourceType:i,limit:s,offset:o,since:c}}function Z$(t){if(!t||typeof t!="object")return 0;let e=t.retried_count;return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function e3(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&n3.has(e)?e:null,n=Yh(t.query.limit,i3,1,s3),i=Yh(t.query.offset,0,0,Number.MAX_SAFE_INTEGER);return{status:r,limit:n,offset:i}}function Yh(t,e,r,n){if(typeof t!="string")return e;let i=Number.parseInt(t,10);return Number.isFinite(i)?Math.max(r,Math.min(n,i)):e}function u1(t,e={}){let r={id:t.id,projectId:t.project_id,teamId:t.team_id,sourceType:t.source_type,sourceId:t.source_id,status:t.status,attempts:t.attempts,maxAttempts:t.max_attempts,createdAtEpoch:new Date(t.created_at).getTime(),completedAtEpoch:t.completed_at?new Date(t.completed_at).getTime():null,failedAtEpoch:t.failed_at?new Date(t.failed_at).getTime():null,lastError:t.last_error&&typeof t.last_error=="object"?t.last_error:null};return e.includePayload&&t.payload&&typeof t.payload=="object"&&(r.payload=t.payload),r}function D0e(t){let e={"event.received":"agent_event","event.batch_received":"agent_event","event.write":"agent_event","event.batch_write":"agent_event","session.write":"server_session","session.end":"server_session","memory.write":"observation","observation.read":"observation","observation.search":"observation","observation.context":"observation","observation.generated":"observation","session_summary.generated":"observation","generation_job.queued":"observation_generation_job","generation_job.enqueued":"observation_generation_job","generation_job.processing":"observation_generation_job","generation_job.completed":"observation_generation_job","generation_job.failed":"observation_generation_job","generation_job.scope_violation":"observation_generation_job","generation_job.revoked_key":"observation_generation_job","generation_job.retried_by_operator":"observation_generation_job","generation_job.cancelled_by_operator":"observation_generation_job","generation_job.stalled":"observation_generation_job"};return e[t]?e[t]:t.split(".")[0]??"unknown"}function j0e(t,e){let r=t.authContext?.projectId??null;if(!(t.authContext?.teamId??null))return{status:403,body:{error:"Forbidden",message:"API key is not bound to a team"}};if(!r)return null;for(let i of e)if(i.projectId!==r)return{status:403,body:{error:"Forbidden",message:"API key is scoped to a different project"}};return null}function xd(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,externalSessionId:t.externalSessionId,contentSessionId:t.contentSessionId,agentId:t.agentId,agentType:t.agentType,platformSource:t.platformSource,generationStatus:t.generationStatus,metadata:t.metadata,startedAtEpoch:t.startedAtEpoch,endedAtEpoch:t.endedAtEpoch,lastGeneratedAtEpoch:t.lastGeneratedAtEpoch,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function wd(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,serverSessionId:t.serverSessionId,sourceAdapter:t.sourceAdapter,sourceEventId:t.sourceEventId,eventType:t.eventType,platformSource:t.platformSource,payload:t.payload,metadata:t.metadata,occurredAtEpoch:t.occurredAtEpoch,receivedAtEpoch:t.receivedAtEpoch,createdAtEpoch:t.createdAtEpoch}}function zc(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,serverSessionId:t.serverSessionId,...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},kind:t.kind,content:t.content,metadata:t.metadata,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function K0e(t){return{id:t.id,projectId:t.project_id,teamId:t.team_id,serverSessionId:t.server_session_id,kind:t.kind,content:t.content,metadata:t.metadata&&typeof t.metadata=="object"?t.metadata:{},generationKey:t.generation_key,createdByJobId:t.created_by_job_id,createdAtEpoch:new Date(t.created_at).getTime(),updatedAtEpoch:new Date(t.updated_at).getTime(),source:{id:t.source_id_pk,sourceType:t.source_type,sourceId:t.source_id,generationJobId:t.generation_job_id,createdAtEpoch:new Date(t.source_created_at).getTime()}}}function d1(t,e){return{id:t.id,status:t.status,bullmqJobId:t.bullmqJobId,sourceType:t.sourceType,sourceId:t.sourceId,transport:e,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function t3(t,e){return{id:t.id,status:t.status,transport:e,bullmqJobId:t.bullmqJobId,sourceType:t.sourceType,sourceId:t.sourceId,attempts:t.attempts,maxAttempts:t.maxAttempts,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function p1(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,sourceType:t.sourceType,sourceId:t.sourceId,agentEventId:t.agentEventId,serverSessionId:t.serverSessionId,jobType:t.jobType,status:t.status,bullmqJobId:t.bullmqJobId,attempts:t.attempts,maxAttempts:t.maxAttempts,nextAttemptAtEpoch:t.nextAttemptAtEpoch,completedAtEpoch:t.completedAtEpoch,failedAtEpoch:t.failedAtEpoch,cancelledAtEpoch:t.cancelledAtEpoch,lastError:t.lastError,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}var ne,Qh,R0e,O0e,Y$,r3,C0e,Q$,Wh,P0e,n3,i3,s3,o3=R(()=>{"use strict";ne=require("zod");pN();oc();ms();Oi();bu();ac();oe();rm();W_();g2();mU();P$();D$();K$();Qo();Qh=require("node:crypto");Ps();G$();z$();Ro();H$();R0e="api",O0e="13.34.1";Y$=ne.z.object({generate:ne.z.union([ne.z.literal("true"),ne.z.literal("false")]).optional(),wait:ne.z.union([ne.z.literal("true"),ne.z.literal("false")]).optional()}),r3=3e4,C0e=100,Q$=["completed","failed","cancelled"];Wh=class{constructor(e){this.options=e;this.ingestEvents=new Hh({pool:e.pool,resolveEventQueue:()=>this.resolveQueue("event")}),this.endSession=new Vh({pool:e.pool,resolveSummaryQueue:()=>this.resolveQueue("summary")})}options;ingestEvents;endSession;getIngestEventsService(){return this.ingestEvents}getEndSessionService(){return this.endSession}setupRoutes(e){e.use("/v1",y2());let r=Co(this.options.pool,{authMode:this.options.authMode,allowLocalDevBypass:this.options.allowLocalDevBypass,requiredScopes:["memories:write"]}),n=Co(this.options.pool,{authMode:this.options.authMode,allowLocalDevBypass:this.options.allowLocalDevBypass,requiredScopes:["memories:read"]}),i=[],s=Number(process.env.CLAUDE_MEM_RATE_LIMIT_PER_MIN??"0");s>0&&i.push(M$(this.options.pool,{windowSec:60,max:s}));let o=Number(process.env.CLAUDE_MEM_MONTHLY_REQUEST_CAP??"0");o>0&&i.push(o1(this.options.pool,{kind:"request",cap:o})),process.env.CLAUDE_MEM_USAGE_METERING==="1"&&i.push(j$(this.options.pool));let a=[...i],c=Number(process.env.CLAUDE_MEM_MONTHLY_TOKEN_CAP??"0");c>0&&a.push(o1(this.options.pool,{kind:"tokens",cap:c}));let l=[r,...a],u=[n,...i];e.get("/v1/usage",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let h=new Date(Date.UTC(new Date().getUTCFullYear(),new Date().getUTCMonth(),1)),b=await new jr(this.options.pool).summarize({teamId:m,since:h});f.status(200).json({since:h.toISOString(),usage:b})})),e.post("/v1/keys",l,this.handleCreate(ne.z.object({label:ne.z.string().max(120).optional(),expiresInDays:ne.z.number().int().positive().max(365).optional()}),async(p,f,m)=>{let h=this.requireTeamId(p,f);if(!h)return;let b=`cm_${(0,Qh.randomBytes)(24).toString("hex")}`,v=(0,Qh.createHash)("sha256").update(b).digest("hex"),E=m.expiresInDays?new Date(Date.now()+m.expiresInDays*864e5):null,_=await new Lt(this.options.pool).createApiKey({keyHash:v,teamId:h,projectId:p.authContext?.projectId??null,actorId:p.authContext?.apiKeyId??"api",scopes:["memories:read"],expiresAt:E});m.label;let I=V$(p);f.status(201).json({id:_.id,apiKey:b,scopes:["memories:read"],expiresAt:E?.toISOString()??null,mcpUrl:I,connectCommand:W$(I,b)})})),e.get("/v1/connect",u,this.asyncHandler(async(p,f)=>{if(!this.requireTeamId(p,f))return;let h=V$(p);f.status(200).json({mcpUrl:h,connectCommand:W$(h,"<YOUR_API_KEY>"),hint:"POST /v1/keys (write scope) to mint a read-only key for this link."})})),e.post("/v1/events",l,this.asyncHandler(async(p,f)=>{let m=Y$.safeParse(p.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let h=m.data.generate!=="false",b=m.data.wait==="true",v=FS.safeParse(p.body);if(!v.success){f.status(400).json({error:"ValidationError",issues:v.error.issues});return}let E=v.data,_=this.requireTeamId(p,f);if(!_||!this.ensureProjectAllowed(p,f,E.projectId))return;let I=this.toAgentEventInput(E,_);await this.applyContentSessionLinks([I],[p.body],_);let w,O=null,K="skipped",Q={generate:h,source:"http_post_v1_events",apiKeyId:p.authContext?.apiKeyId??null,actorId:await this.resolveActorId(p),sourceAdapter:I.sourceAdapter,requestId:p.requestId??null};try{let N=await this.ingestEvents.ingestOne(I,Q);w=N.event,O=N.outbox,K=N.enqueueState}catch(N){let $=N instanceof Error?N:new Error(String(N));S.warn("SYSTEM","event.write ingest failed",{requestId:p.requestId??null},$),this.handleDbError($,f,"event.write");return}if(await this.auditWrite(p,"event.received",w.id,w.projectId,{sourceAdapter:w.sourceAdapter,sourceEventId:w.sourceEventId,eventType:w.eventType,serverSessionId:w.serverSessionId,generationJobId:O?.id??null}),b){let N=O,$=!1;if(O){let te=new dt(this.options.pool),ze=await X$(te,O);N=ze.job,$=ze.timedOut}f.status(201).json({event:wd(w),generationJob:N?t3(N,K):null,...$?{waitTimedOut:!0}:{}});return}f.status(201).json({event:wd(w),...O?{generationJob:d1(O,K)}:{}})})),e.post("/v1/events/batch",l,this.asyncHandler(async(p,f)=>{let m=Y$.safeParse(p.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let h=m.data.generate!=="false",b=m.data.wait==="true",E=ne.z.array(FS).min(1).max(500).safeParse(p.body);if(!E.success){f.status(400).json({error:"ValidationError",issues:E.error.issues});return}let _=this.requireTeamId(p,f);if(!_)return;let I=j0e(p,E.data);if(I){f.status(I.status).json(I.body);return}let w=E.data.map(N=>this.toAgentEventInput(N,_));await this.applyContentSessionLinks(w,Array.isArray(p.body)?p.body:E.data,_);let O=[],K=[],Q={generate:h,source:"http_post_v1_events_batch",apiKeyId:p.authContext?.apiKeyId??null,actorId:await this.resolveActorId(p),sourceAdapter:null,requestId:p.requestId??null};try{let N=await this.ingestEvents.ingestBatch(w,Q);O=N.map(({event:$,outbox:te})=>({event:$,outbox:te})),K=N.map(({enqueueState:$})=>$)}catch(N){let $=N instanceof Error?N:new Error(String(N));S.warn("SYSTEM","event.batch_write ingest failed",{requestId:p.requestId??null},$),this.handleDbError($,f,"event.batch_write");return}if(await this.auditWrite(p,"event.batch_received",null,null,{eventCount:O.length,generationJobIds:O.map(({outbox:N})=>N?.id??null).filter(Boolean)}),b){let N=new dt(this.options.pool),$=Date.now()+r3,te=[];for(let A of O){if(!A.outbox){te.push({event:A.event,outbox:null,timedOut:!1});continue}let D=Math.max(0,$-Date.now()),M=await X$(N,A.outbox,D);te.push({event:A.event,outbox:M.job,timedOut:M.timedOut})}let ze=te.some(A=>A.timedOut);f.status(201).json({events:te.map(({event:A,outbox:D,timedOut:M},C)=>({event:wd(A),generationJob:D?t3(D,K[C]):null,...M?{waitTimedOut:!0}:{}})),...ze?{waitTimedOut:!0}:{}});return}f.status(201).json({events:O.map(({event:N,outbox:$},te)=>({event:wd(N),...$?{generationJob:d1($,K[te])}:{}}))})})),e.get("/v1/events/:id",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let h=this.routeParam(p.params.id),b=new Zr(this.options.pool),v=await this.loadScopedById(p,f,{id:h,teamId:m,table:"agent_events",notFound:"Event not found",load:E=>b.getByIdForScope({id:h,projectId:E,teamId:m})});v&&f.json({event:wd(v)})})),e.get("/v1/events/:id/observations",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let h=this.routeParam(p.params.id),v=(await this.options.pool.query("SELECT id, project_id FROM agent_events WHERE id = $1 AND team_id = $2",[h,m])).rows[0];if(!v){f.status(404).json({error:"NotFound",message:"Event not found"});return}if(!this.ensureProjectAllowed(p,f,v.project_id))return;let E=await this.options.pool.query(`
393
+ `,[e.serverSessionId,e.projectId,e.teamId,r])).rows.map(S0e)}}});function U$(t){let e=w0e.safeParse(t);if(!e.success)throw new _d(e.error.issues);return e.data}var tr,Gc,N$,q$,_0e,x0e,w0e,_d,zh=R(()=>{"use strict";tr=require("zod"),Gc={event:"server_beta_generate_event",summary:"server_beta_generate_summary"},N$={event:"evt",summary:"sum"},q$=tr.z.object({team_id:tr.z.string().min(1,"team_id is required"),project_id:tr.z.string().min(1,"project_id is required"),source_type:tr.z.enum(["agent_event","session_summary","observation_reindex"]),source_id:tr.z.string().min(1,"source_id is required"),generation_job_id:tr.z.string().min(1,"generation_job_id is required"),api_key_id:tr.z.string().min(1).nullable(),actor_id:tr.z.string().min(1).nullable(),source_adapter:tr.z.string().min(1,"source_adapter is required"),request_id:tr.z.string().min(1).nullable().optional()}),_0e=q$.extend({kind:tr.z.literal("event"),agent_event_id:tr.z.string().min(1)}),x0e=q$.extend({kind:tr.z.literal("summary"),server_session_id:tr.z.string().min(1)}),w0e=tr.z.discriminatedUnion("kind",[_0e,x0e]),_d=class extends Error{issues;constructor(e){super(`invalid server generation job payload: ${e.map(r=>r.message).join("; ")}`),this.issues=e}}});function Bc(t){let e=N$[t.kind],r=JSON.stringify({kind:t.kind,team_id:t.team_id,project_id:t.project_id,source_type:t.source_type,source_id:t.source_id}),n=(0,F$.createHash)("sha256").update(r).digest("hex");return`${e}_${n}`}var F$,a1=R(()=>{"use strict";F$=require("crypto");zh()});function $$(t){return{kind:"event",team_id:t.event.teamId,project_id:t.event.projectId,source_type:"agent_event",source_id:t.event.id,generation_job_id:t.outboxId,agent_event_id:t.event.id,api_key_id:t.apiKeyId,actor_id:t.actorId,source_adapter:t.sourceAdapter??t.event.sourceAdapter??"api",request_id:t.requestId}}var J$,Hh,G$=R(()=>{"use strict";oc();ms();Ko();oe();a1();Tn();J$="observation_generate_for_event",Hh=class{constructor(e){this.options=e}options;async ingestOne(e,r={}){let n=r.generate??!0,i=r.source??"http_post_v1_events",s=await kn(this.options.pool,async a=>{let l=await new Zr(a).create(e);if(!n)return{event:l,outbox:null};let u=new dt(a),d=new Wt(a),p=et(),f=$$({outboxId:p,event:l,apiKeyId:r.apiKeyId??null,actorId:r.actorId??null,sourceAdapter:r.sourceAdapter??null,requestId:r.requestId??null}),m=await u.create({id:p,projectId:l.projectId,teamId:l.teamId,sourceType:"agent_event",sourceId:l.id,agentEventId:l.id,serverSessionId:l.serverSessionId,jobType:J$,bullmqJobId:Bc({kind:"event",team_id:l.teamId,project_id:l.projectId,source_type:"agent_event",source_id:l.id}),payload:f});return await d.append({generationJobId:m.id,projectId:m.projectId,teamId:m.teamId,eventType:"queued",statusAfter:m.status,attempt:m.attempts,details:{source:i}}),{event:l,outbox:m}}),o="skipped";return s.outbox&&(o=await this.publishEventJob(s.event,s.outbox)),{event:s.event,outbox:s.outbox,enqueueState:o}}async ingestBatch(e,r={}){let n=r.generate??!0,i=r.source??"http_post_v1_events_batch",s=await kn(this.options.pool,async o=>{let a=new Zr(o),c=new dt(o),l=new Wt(o),u=[];for(let d of e){let p=await a.create(d);if(!n){u.push({event:p,outbox:null});continue}let f=et(),m=$$({outboxId:f,event:p,apiKeyId:r.apiKeyId??null,actorId:r.actorId??null,sourceAdapter:r.sourceAdapter??null,requestId:r.requestId??null}),h=await c.create({id:f,projectId:p.projectId,teamId:p.teamId,sourceType:"agent_event",sourceId:p.id,agentEventId:p.id,serverSessionId:p.serverSessionId,jobType:J$,bullmqJobId:Bc({kind:"event",team_id:p.teamId,project_id:p.projectId,source_type:"agent_event",source_id:p.id}),payload:m});await l.append({generationJobId:h.id,projectId:h.projectId,teamId:h.teamId,eventType:"queued",statusAfter:h.status,attempt:h.attempts,details:{source:i}}),u.push({event:p,outbox:h})}return u});return Promise.all(s.map(async({event:o,outbox:a})=>{let c=a?await this.publishEventJob(o,a):"skipped";return{event:o,outbox:a,enqueueState:c}}))}async publishEventJob(e,r){let n=this.options.resolveEventQueue();if(!n)return"queued_only";let i=r.bullmqJobId??Bc({kind:"event",team_id:e.teamId,project_id:e.projectId,source_type:"agent_event",source_id:e.id});try{return await n.add(i,r.payload),"enqueued"}catch(s){return S.warn("SYSTEM","failed to publish event generation job to BullMQ",{outboxId:r.id,error:s instanceof Error?s.message:String(s)}),"queued_only"}}}});function c1(t){return Bc({kind:"summary",team_id:t.teamId,project_id:t.projectId,source_type:"session_summary",source_id:t.serverSessionId})}function l1(t){return{kind:"summary",team_id:t.teamId,project_id:t.projectId,source_type:"session_summary",source_id:t.serverSessionId,generation_job_id:t.generationJobId,server_session_id:t.serverSessionId,api_key_id:t.apiKeyId??null,actor_id:t.actorId??null,source_adapter:t.sourceAdapter??"api",request_id:t.requestId??null}}var B$=R(()=>{"use strict";a1()});var I0e,Vh,z$=R(()=>{"use strict";ms();Ko();Ps();oe();B$();Tn();I0e="observation_generate_session_summary",Vh=class{constructor(e){this.options=e}options;async end(e){let r=e.source??"http_post_v1_sessions_end",n=await kn(this.options.pool,async s=>{let a=await new Gt(s).endSession({id:e.sessionId,projectId:e.projectId,teamId:e.teamId});if(!a)return{session:null,outbox:null};let c=new dt(s),l=new Wt(s),u=et(),d=l1({serverSessionId:a.id,teamId:a.teamId,projectId:a.projectId,generationJobId:u,apiKeyId:e.apiKeyId??null,actorId:e.actorId??null,sourceAdapter:e.sourceAdapter??null}),p=await c.create({id:u,projectId:a.projectId,teamId:a.teamId,sourceType:"session_summary",sourceId:a.id,serverSessionId:a.id,jobType:I0e,bullmqJobId:c1({serverSessionId:a.id,teamId:a.teamId,projectId:a.projectId}),payload:d});return await l.append({generationJobId:p.id,projectId:p.projectId,teamId:p.teamId,eventType:"queued",statusAfter:p.status,attempt:p.attempts,details:{source:r}}),{session:a,outbox:p}});if(!n.session||!n.outbox)return{session:n.session,outbox:null,enqueueState:"skipped"};let i=await this.publishSummaryJob(n.session.id,n.outbox,e);return{session:n.session,outbox:n.outbox,enqueueState:i}}async publishSummaryJob(e,r,n){let i=this.options.resolveSummaryQueue();if(!i)return"queued_only";let s=r.bullmqJobId??c1({serverSessionId:e,teamId:r.teamId,projectId:r.projectId}),o=l1({serverSessionId:e,teamId:r.teamId,projectId:r.projectId,generationJobId:r.id,apiKeyId:n.apiKeyId??null,actorId:n.actorId??null,sourceAdapter:n.sourceAdapter??null});try{return await i.add(s,o),"enqueued"}catch(a){return S.warn("SYSTEM","failed to publish summary generation job to BullMQ",{outboxId:r.id,error:a instanceof Error?a.message:String(a)}),"queued_only"}}}});var H$=R(()=>{"use strict"});function V$(t){return`${(process.env.CLAUDE_MEM_PUBLIC_URL??`${t.protocol}://${t.get("host")??"localhost"}`).replace(/\/+$/,"")}/v1/mcp`}function W$(t,e){return`claude mcp add --transport http claude-mem ${t} --header "Authorization: Bearer ${e}"`}async function X$(t,e,r=r3,n=C0e){if(Q$.includes(e.status))return{job:e,timedOut:!1};let i=Date.now()+r,s=e;for(;Date.now()<i;){await new Promise(a=>setTimeout(a,n));let o=await t.getByIdForScope({id:e.id,projectId:e.projectId,teamId:e.teamId});if(!o)return{job:s,timedOut:!1};if(s=o,Q$.includes(o.status))return{job:o,timedOut:!1}}return{job:s,timedOut:!0}}function M0e(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&n3.has(e)?e:null,n=typeof t.query.source_type=="string"?t.query.source_type.trim():"",i=n&&P0e.has(n)?n:null,s=Yh(t.query.limit,i3,1,s3),o=Yh(t.query.offset,0,0,Number.MAX_SAFE_INTEGER),a=typeof t.query.since=="string"?t.query.since.trim():"",c=null;if(a){let l=new Date(a);Number.isNaN(l.getTime())||(c=l)}return{status:r,sourceType:i,limit:s,offset:o,since:c}}function Z$(t){if(!t||typeof t!="object")return 0;let e=t.retried_count;return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function e3(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&n3.has(e)?e:null,n=Yh(t.query.limit,i3,1,s3),i=Yh(t.query.offset,0,0,Number.MAX_SAFE_INTEGER);return{status:r,limit:n,offset:i}}function Yh(t,e,r,n){if(typeof t!="string")return e;let i=Number.parseInt(t,10);return Number.isFinite(i)?Math.max(r,Math.min(n,i)):e}function u1(t,e={}){let r={id:t.id,projectId:t.project_id,teamId:t.team_id,sourceType:t.source_type,sourceId:t.source_id,status:t.status,attempts:t.attempts,maxAttempts:t.max_attempts,createdAtEpoch:new Date(t.created_at).getTime(),completedAtEpoch:t.completed_at?new Date(t.completed_at).getTime():null,failedAtEpoch:t.failed_at?new Date(t.failed_at).getTime():null,lastError:t.last_error&&typeof t.last_error=="object"?t.last_error:null};return e.includePayload&&t.payload&&typeof t.payload=="object"&&(r.payload=t.payload),r}function D0e(t){let e={"event.received":"agent_event","event.batch_received":"agent_event","event.write":"agent_event","event.batch_write":"agent_event","session.write":"server_session","session.end":"server_session","memory.write":"observation","observation.read":"observation","observation.search":"observation","observation.context":"observation","observation.generated":"observation","session_summary.generated":"observation","generation_job.queued":"observation_generation_job","generation_job.enqueued":"observation_generation_job","generation_job.processing":"observation_generation_job","generation_job.completed":"observation_generation_job","generation_job.failed":"observation_generation_job","generation_job.scope_violation":"observation_generation_job","generation_job.revoked_key":"observation_generation_job","generation_job.retried_by_operator":"observation_generation_job","generation_job.cancelled_by_operator":"observation_generation_job","generation_job.stalled":"observation_generation_job"};return e[t]?e[t]:t.split(".")[0]??"unknown"}function j0e(t,e){let r=t.authContext?.projectId??null;if(!(t.authContext?.teamId??null))return{status:403,body:{error:"Forbidden",message:"API key is not bound to a team"}};if(!r)return null;for(let i of e)if(i.projectId!==r)return{status:403,body:{error:"Forbidden",message:"API key is scoped to a different project"}};return null}function xd(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,externalSessionId:t.externalSessionId,contentSessionId:t.contentSessionId,agentId:t.agentId,agentType:t.agentType,platformSource:t.platformSource,generationStatus:t.generationStatus,metadata:t.metadata,startedAtEpoch:t.startedAtEpoch,endedAtEpoch:t.endedAtEpoch,lastGeneratedAtEpoch:t.lastGeneratedAtEpoch,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function wd(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,serverSessionId:t.serverSessionId,sourceAdapter:t.sourceAdapter,sourceEventId:t.sourceEventId,eventType:t.eventType,platformSource:t.platformSource,payload:t.payload,metadata:t.metadata,occurredAtEpoch:t.occurredAtEpoch,receivedAtEpoch:t.receivedAtEpoch,createdAtEpoch:t.createdAtEpoch}}function zc(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,serverSessionId:t.serverSessionId,...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},kind:t.kind,content:t.content,metadata:t.metadata,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function K0e(t){return{id:t.id,projectId:t.project_id,teamId:t.team_id,serverSessionId:t.server_session_id,kind:t.kind,content:t.content,metadata:t.metadata&&typeof t.metadata=="object"?t.metadata:{},generationKey:t.generation_key,createdByJobId:t.created_by_job_id,createdAtEpoch:new Date(t.created_at).getTime(),updatedAtEpoch:new Date(t.updated_at).getTime(),source:{id:t.source_id_pk,sourceType:t.source_type,sourceId:t.source_id,generationJobId:t.generation_job_id,createdAtEpoch:new Date(t.source_created_at).getTime()}}}function d1(t,e){return{id:t.id,status:t.status,bullmqJobId:t.bullmqJobId,sourceType:t.sourceType,sourceId:t.sourceId,transport:e,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function t3(t,e){return{id:t.id,status:t.status,transport:e,bullmqJobId:t.bullmqJobId,sourceType:t.sourceType,sourceId:t.sourceId,attempts:t.attempts,maxAttempts:t.maxAttempts,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function p1(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,sourceType:t.sourceType,sourceId:t.sourceId,agentEventId:t.agentEventId,serverSessionId:t.serverSessionId,jobType:t.jobType,status:t.status,bullmqJobId:t.bullmqJobId,attempts:t.attempts,maxAttempts:t.maxAttempts,nextAttemptAtEpoch:t.nextAttemptAtEpoch,completedAtEpoch:t.completedAtEpoch,failedAtEpoch:t.failedAtEpoch,cancelledAtEpoch:t.cancelledAtEpoch,lastError:t.lastError,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}var ne,Qh,R0e,O0e,Y$,r3,C0e,Q$,Wh,P0e,n3,i3,s3,o3=R(()=>{"use strict";ne=require("zod");pN();oc();ms();Oi();bu();ac();oe();rm();W_();g2();mU();P$();D$();K$();Qo();Qh=require("node:crypto");Ps();G$();z$();Ro();H$();R0e="api",O0e="13.34.2";Y$=ne.z.object({generate:ne.z.union([ne.z.literal("true"),ne.z.literal("false")]).optional(),wait:ne.z.union([ne.z.literal("true"),ne.z.literal("false")]).optional()}),r3=3e4,C0e=100,Q$=["completed","failed","cancelled"];Wh=class{constructor(e){this.options=e;this.ingestEvents=new Hh({pool:e.pool,resolveEventQueue:()=>this.resolveQueue("event")}),this.endSession=new Vh({pool:e.pool,resolveSummaryQueue:()=>this.resolveQueue("summary")})}options;ingestEvents;endSession;getIngestEventsService(){return this.ingestEvents}getEndSessionService(){return this.endSession}setupRoutes(e){e.use("/v1",y2());let r=Co(this.options.pool,{authMode:this.options.authMode,allowLocalDevBypass:this.options.allowLocalDevBypass,requiredScopes:["memories:write"]}),n=Co(this.options.pool,{authMode:this.options.authMode,allowLocalDevBypass:this.options.allowLocalDevBypass,requiredScopes:["memories:read"]}),i=[],s=Number(process.env.CLAUDE_MEM_RATE_LIMIT_PER_MIN??"0");s>0&&i.push(M$(this.options.pool,{windowSec:60,max:s}));let o=Number(process.env.CLAUDE_MEM_MONTHLY_REQUEST_CAP??"0");o>0&&i.push(o1(this.options.pool,{kind:"request",cap:o})),process.env.CLAUDE_MEM_USAGE_METERING==="1"&&i.push(j$(this.options.pool));let a=[...i],c=Number(process.env.CLAUDE_MEM_MONTHLY_TOKEN_CAP??"0");c>0&&a.push(o1(this.options.pool,{kind:"tokens",cap:c}));let l=[r,...a],u=[n,...i];e.get("/v1/usage",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let h=new Date(Date.UTC(new Date().getUTCFullYear(),new Date().getUTCMonth(),1)),b=await new jr(this.options.pool).summarize({teamId:m,since:h});f.status(200).json({since:h.toISOString(),usage:b})})),e.post("/v1/keys",l,this.handleCreate(ne.z.object({label:ne.z.string().max(120).optional(),expiresInDays:ne.z.number().int().positive().max(365).optional()}),async(p,f,m)=>{let h=this.requireTeamId(p,f);if(!h)return;let b=`cm_${(0,Qh.randomBytes)(24).toString("hex")}`,v=(0,Qh.createHash)("sha256").update(b).digest("hex"),E=m.expiresInDays?new Date(Date.now()+m.expiresInDays*864e5):null,_=await new Lt(this.options.pool).createApiKey({keyHash:v,teamId:h,projectId:p.authContext?.projectId??null,actorId:p.authContext?.apiKeyId??"api",scopes:["memories:read"],expiresAt:E});m.label;let I=V$(p);f.status(201).json({id:_.id,apiKey:b,scopes:["memories:read"],expiresAt:E?.toISOString()??null,mcpUrl:I,connectCommand:W$(I,b)})})),e.get("/v1/connect",u,this.asyncHandler(async(p,f)=>{if(!this.requireTeamId(p,f))return;let h=V$(p);f.status(200).json({mcpUrl:h,connectCommand:W$(h,"<YOUR_API_KEY>"),hint:"POST /v1/keys (write scope) to mint a read-only key for this link."})})),e.post("/v1/events",l,this.asyncHandler(async(p,f)=>{let m=Y$.safeParse(p.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let h=m.data.generate!=="false",b=m.data.wait==="true",v=FS.safeParse(p.body);if(!v.success){f.status(400).json({error:"ValidationError",issues:v.error.issues});return}let E=v.data,_=this.requireTeamId(p,f);if(!_||!this.ensureProjectAllowed(p,f,E.projectId))return;let I=this.toAgentEventInput(E,_);await this.applyContentSessionLinks([I],[p.body],_);let w,O=null,K="skipped",Q={generate:h,source:"http_post_v1_events",apiKeyId:p.authContext?.apiKeyId??null,actorId:await this.resolveActorId(p),sourceAdapter:I.sourceAdapter,requestId:p.requestId??null};try{let N=await this.ingestEvents.ingestOne(I,Q);w=N.event,O=N.outbox,K=N.enqueueState}catch(N){let $=N instanceof Error?N:new Error(String(N));S.warn("SYSTEM","event.write ingest failed",{requestId:p.requestId??null},$),this.handleDbError($,f,"event.write");return}if(await this.auditWrite(p,"event.received",w.id,w.projectId,{sourceAdapter:w.sourceAdapter,sourceEventId:w.sourceEventId,eventType:w.eventType,serverSessionId:w.serverSessionId,generationJobId:O?.id??null}),b){let N=O,$=!1;if(O){let te=new dt(this.options.pool),ze=await X$(te,O);N=ze.job,$=ze.timedOut}f.status(201).json({event:wd(w),generationJob:N?t3(N,K):null,...$?{waitTimedOut:!0}:{}});return}f.status(201).json({event:wd(w),...O?{generationJob:d1(O,K)}:{}})})),e.post("/v1/events/batch",l,this.asyncHandler(async(p,f)=>{let m=Y$.safeParse(p.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let h=m.data.generate!=="false",b=m.data.wait==="true",E=ne.z.array(FS).min(1).max(500).safeParse(p.body);if(!E.success){f.status(400).json({error:"ValidationError",issues:E.error.issues});return}let _=this.requireTeamId(p,f);if(!_)return;let I=j0e(p,E.data);if(I){f.status(I.status).json(I.body);return}let w=E.data.map(N=>this.toAgentEventInput(N,_));await this.applyContentSessionLinks(w,Array.isArray(p.body)?p.body:E.data,_);let O=[],K=[],Q={generate:h,source:"http_post_v1_events_batch",apiKeyId:p.authContext?.apiKeyId??null,actorId:await this.resolveActorId(p),sourceAdapter:null,requestId:p.requestId??null};try{let N=await this.ingestEvents.ingestBatch(w,Q);O=N.map(({event:$,outbox:te})=>({event:$,outbox:te})),K=N.map(({enqueueState:$})=>$)}catch(N){let $=N instanceof Error?N:new Error(String(N));S.warn("SYSTEM","event.batch_write ingest failed",{requestId:p.requestId??null},$),this.handleDbError($,f,"event.batch_write");return}if(await this.auditWrite(p,"event.batch_received",null,null,{eventCount:O.length,generationJobIds:O.map(({outbox:N})=>N?.id??null).filter(Boolean)}),b){let N=new dt(this.options.pool),$=Date.now()+r3,te=[];for(let A of O){if(!A.outbox){te.push({event:A.event,outbox:null,timedOut:!1});continue}let D=Math.max(0,$-Date.now()),M=await X$(N,A.outbox,D);te.push({event:A.event,outbox:M.job,timedOut:M.timedOut})}let ze=te.some(A=>A.timedOut);f.status(201).json({events:te.map(({event:A,outbox:D,timedOut:M},C)=>({event:wd(A),generationJob:D?t3(D,K[C]):null,...M?{waitTimedOut:!0}:{}})),...ze?{waitTimedOut:!0}:{}});return}f.status(201).json({events:O.map(({event:N,outbox:$},te)=>({event:wd(N),...$?{generationJob:d1($,K[te])}:{}}))})})),e.get("/v1/events/:id",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let h=this.routeParam(p.params.id),b=new Zr(this.options.pool),v=await this.loadScopedById(p,f,{id:h,teamId:m,table:"agent_events",notFound:"Event not found",load:E=>b.getByIdForScope({id:h,projectId:E,teamId:m})});v&&f.json({event:wd(v)})})),e.get("/v1/events/:id/observations",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let h=this.routeParam(p.params.id),v=(await this.options.pool.query("SELECT id, project_id FROM agent_events WHERE id = $1 AND team_id = $2",[h,m])).rows[0];if(!v){f.status(404).json({error:"NotFound",message:"Event not found"});return}if(!this.ensureProjectAllowed(p,f,v.project_id))return;let E=await this.options.pool.query(`
394
394
  SELECT o.id, o.project_id, o.team_id, o.server_session_id, o.kind, o.content,
395
395
  o.metadata, o.generation_key, o.created_by_job_id, o.created_at, o.updated_at,
396
396
  os.id AS source_id_pk, os.source_type, os.source_id, os.generation_job_id, os.created_at AS source_created_at
@@ -17,7 +17,7 @@ ${m.stack??""}
17
17
  `)){let n=t.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);if(!n)continue;let s=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:s.length>0?s:null})}return e}async function Xp(){let r;try{r=(await fi("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(t){return f.warn("PROCESS","Cannot enumerate the Windows process table \u2014 tree-kill degrades to a single-PID kill",{error:t instanceof Error?t.message:String(t)}),[]}let e=[];for(let t of r.split(/\r?\n/).slice(1)){let n=t.match(/^"(\d+)","(\d+)","(.*)"$/);if(!n)continue;let s=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:s.length>0?s:null})}return e}async function rn(r){let e=await Yp(),t=new Map;for(let o of e){let a=t.get(o.ppid);a?a.push(o):t.set(o.ppid,[o])}let n=new Set([r]),s=[],i=o=>{for(let a of t.get(o)??[])n.has(a.pid)||(n.add(a.pid),i(a.pid),s.push({pid:a.pid,startToken:a.startToken}))};return i(r),s}var Qp=5e3,Zp=1e3,eg=$.supervisorRegistry(),tg=null;function z(r){if(!Number.isInteger(r)||r<0||r===0)return!1;try{return process.kill(r,0),!0}catch(e){if(e instanceof Error){let t=e.code;return t==="EPERM"?!0:(f.debug("SYSTEM","PID check failed",{pid:r,code:t}),!1)}return f.warn("SYSTEM","PID check threw non-Error",{pid:r,error:String(e)}),!1}}async function sn(r,e){let t=Date.now()+e;for(;Date.now()<t;){if(r.every(n=>!z(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function rc(r){if(!r||!z(r.pid))return!1;if(!r.startToken)return!0;let e=Me(r.pid);if(e===null)return!0;let t=e===r.startToken;return t||f.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:r.pid,stored:r.startToken,current:e}),t}var rg={platform:process.platform,readCommandLine:r=>(0,ot.readFileSync)(`/proc/${r}/cmdline`,"utf-8")};function on(r,e=rg){if(!rc(r))return!1;if(r.startToken||e.platform!=="linux")return!0;let t;try{t=e.readCommandLine(r.pid)}catch(s){return f.debug("SYSTEM","Could not read the command line of a token-less worker PID; trusting the live PID",{pid:r.pid,error:s instanceof Error?s.message:String(s)}),!0}let n=t.split("\0").some(s=>tc.default.basename(s)==="worker-service.cjs");return n||f.debug("SYSTEM","Token-less worker PID now belongs to another program (PID reused)",{pid:r.pid}),n}function ze(r=$.workerPid()){if(!(0,ot.existsSync)(r))return null;let e;try{e=JSON.parse((0,ot.readFileSync)(r,"utf-8"))}catch{return null}return e!==null&&on(e)?e:null}var mi=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(e=eg){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,!(0,ot.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,ot.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[s,i]of Object.entries(n))this.entries.set(s,i)}catch(t){t instanceof Error?f.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},t):f.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(t)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&f.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}retainSupersededEntry(e,t){let n=this.entries.get(e);if(!n||n.pid===t||!z(n.pid))return;let s=`${e}#superseded:${n.pid}`;this.entries.set(s,n);let i=this.runtimeProcesses.get(e);i&&(this.runtimeProcesses.set(s,i),this.runtimeProcesses.delete(e)),f.warn("SYSTEM","Registry id reused while the previous process was still alive; kept it for reaping",{id:e,supersededId:s,supersededPid:n.pid,incomingPid:t})}register(e,t,n){this.initialize(),this.retainSupersededEntry(e,t.pid),this.entries.set(e,t),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e,t){this.initialize();let n=e,s=this.entries.get(n);t!==void 0&&s?.pid!==t&&(n=`${e}#superseded:${t}`,s=this.entries.get(n),s?.pid!==t)||s&&(this.entries.delete(n),this.runtimeProcesses.delete(n),this.persist(),s?.type==="sdk"&&gi())}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,t])=>({id:e,...t})).sort((e,t)=>{let n=Date.parse(e.startedAt),s=Date.parse(t.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(s)?0:s)})}getBySession(e){let t=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===t)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,t=0;for(let[n,s]of this.entries)z(s.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,s.type==="sdk"&&(t+=1));e>0&&this.persist();for(let n=0;n<t;n+=1)gi();return e}async reapSession(e){this.initialize();let t=this.getBySession(e);if(t.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;f.info("SYSTEM",`Reaping ${t.length} process(es) for session ${e}`,{sessionId:n,pids:t.map(a=>a.pid)});let s=t.filter(a=>z(a.pid)),i=new Map(s.map(a=>[a.pid,Me(a.pid)]));for(let a of s)try{process.platform==="win32"?await ue(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"&&f.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):f.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}await sn(s,Qp);let o=s.filter(a=>z(a.pid));for(let a of o){f.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});let c=i.get(a.pid)??null;if(!ye(a.pid,c)){f.warn("SYSTEM","Skipping SIGKILL: session process PID was reused during the grace window",{pid:a.pid,sessionId:n});continue}try{process.platform==="win32"?await ue(a.pid,{expectedStartToken:c}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(l){l instanceof Error?l.code!=="ESRCH"&&f.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},l):f.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(l)})}}if(o.length>0){let a=Date.now()+Zp;for(;Date.now()<a&&o.filter(l=>z(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let a of t)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of t)a.type==="sdk"&&gi();return f.info("SYSTEM",`Reaped ${t.length} process(es) for session ${e}`,{sessionId:n,reaped:t.length}),t.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};try{H(this.registryPath,e),this.persistDegraded=!1}catch(t){this.reportPersistFailure(t)}}reportPersistFailure(e){if(this.persistDegraded)return;this.persistDegraded=!0;let t=e instanceof Error?e:new Error(String(e));f.warn("SYSTEM","Failed to persist supervisor registry; keeping it in memory",{path:this.registryPath},t);try{tg?.({errorCategory:t.code??"unknown"})}catch{}}},pi=null;function an(){return pi||(pi=new mi),pi}var mw=180*1e3,ng=[];function gi(){let r=ng.shift();r&&r.notify()}var Rt=require("fs");C();U();var sg=$.workerPid();async function sc(r){let e=r.currentPid??process.pid,t=r.pidFilePath??sg,n=r.registry.getAll(),s=[...n].filter(c=>c.pid!==e).sort((c,l)=>Date.parse(l.startedAt)-Date.parse(c.startedAt)),i=new Map,o=new Map;for(let c of s){if(!z(c.pid)){r.registry.unregister(c.id);continue}o.set(c.id,Me(c.pid)),i.set(c.id,await rn(c.pid));try{await nc(c,"SIGTERM")}catch(l){l instanceof Error?f.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:c.pid,pgid:c.pgid,type:c.type},l):f.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(l)})}}await sn(s,5e3);let a=s.filter(c=>z(c.pid)||(i.get(c.id)??[]).some(l=>z(l.pid)));for(let c of a){let l=ye(c.pid,o.get(c.id)??null);l||f.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:c.pid,type:c.type});try{l&&await nc(c,"SIGKILL")}catch(u){u instanceof Error?f.debug("SYSTEM","Failed to force kill child process",{pid:c.pid,pgid:c.pgid,type:c.type},u):f.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(u)})}finally{ig(i.get(c.id)??[],c.pid)}}await sn(a,1e3);for(let c of s)r.registry.unregister(c.id);for(let c of n.filter(l=>l.pid===e))r.registry.unregister(c.id);ic(t,e),r.registry.pruneDeadEntries()}function ic(r,e,t=!1){if(!(0,Rt.existsSync)(r))return;let n=null;try{let o=JSON.parse((0,Rt.readFileSync)(r,"utf-8"));n=typeof o.pid=="number"?o.pid:null}catch(o){f.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:r,error:o instanceof Error?o.message:String(o)});return}let s=e!==null&&n===e,i=n===null||!z(n);if(!s&&!(t&&i)){f.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:r,recordedPid:n,currentPid:e});return}try{(0,Rt.rmSync)(r,{force:!0})}catch(o){o instanceof Error?f.debug("SYSTEM","Failed to remove PID file",{pidFilePath:r},o):f.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:r,error:String(o)})}}function ig(r,e){for(let{pid:t,startToken:n}of r)if(!(t===e||!z(t))){if(!ye(t,n)){f.debug("SYSTEM","Skipping reap: PID was recycled during the grace window",{pid:t,rootPid:e});continue}try{process.kill(t,"SIGKILL"),f.debug("SYSTEM","Reaped orphaned descendant during shutdown cascade",{pid:t,rootPid:e})}catch(s){let i=s instanceof Error?s.code:void 0;i!=="ESRCH"&&f.warn("SYSTEM","Failed to reap orphaned descendant during shutdown cascade",{pid:t,rootPid:e,errno:i})}}}async function nc(r,e){let{pid:t,pgid:n}=r;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}if(e==="SIGKILL"){await ue(t,{signalMode:"immediate"});return}try{process.kill(t,e)}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}return}await ue(t)}C();var oc=3e4,Mt=null;function og(){let e=an().pruneDeadEntries();e>0&&f.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function ac(){Mt===null&&(Mt=setInterval(og,oc),Mt.unref(),f.debug("SYSTEM","Health checker started",{intervalMs:oc}))}function cc(){Mt!==null&&(clearInterval(Mt),Mt=null,f.debug("SYSTEM","Health checker stopped"))}var lc=require("child_process"),uc=require("util");C();var ag=(0,uc.promisify)(lc.execFile),cg=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/;function lg(r){let e=[];for(let t of r.split(`
18
18
  `)){let n=t.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);n&&e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),command:n[3].trim()})}return e}async function ug(){let r=await ag("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return lg(r.stdout)}function dg(r,e){let t=r.filter(o=>cg.test(o.command)&&o.pid!==e.selfPid),n=new Set(t.map(o=>o.pid)),s=t.filter(o=>!n.has(o.ppid)),i=s.filter(o=>o.ppid===e.selfPid?!1:o.ppid===1?!0:!e.isAlive(o.ppid));return{matched:t,roots:s,orphans:i}}async function dc(r={}){let e=r.platform??process.platform,t={matched:0,trees:0,orphans:0,killed:0,failed:0,unregistered:0,skipped:null};if(e==="win32")return t.skipped="windows",t;let n=r.readTable??ug,s=r.isAlive??z,i=r.killTree??(g=>ue(g,{signalMode:"graceful"})),o=r.selfPid??process.pid,a;try{a=await n()}catch(g){return f.warn("PROCESS","Orphaned chroma-mcp sweep skipped: cannot read the process table",{error:g instanceof Error?g.message:String(g)}),t.skipped="unreadable",t}let{matched:c,roots:l,orphans:u}=dg(a,{isAlive:s,selfPid:o});if(t.matched=c.length,t.trees=l.length,t.orphans=u.length,u.length===0)return f.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:t.matched,trees:t.trees}),t;f.warn("PROCESS","Reaping orphaned chroma-mcp trees left by dead workers",{orphans:u.length,roots:u.map(g=>g.pid)});let d=new Set,p=8;for(let g=0;g<u.length;g+=p){let m=u.slice(g,g+p);(await Promise.allSettled(m.map(E=>i(E.pid)))).forEach((E,_)=>{let b=m[_];E.status==="fulfilled"?(t.killed+=1,d.add(b.pid)):(t.failed+=1,f.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:b.pid,ppid:b.ppid,error:E.reason instanceof Error?E.reason.message:String(E.reason)}))})}if(r.registry)for(let g of r.registry.getAll())g.type==="chroma"&&d.has(g.pid)&&(r.registry.unregister(g.id),t.unregistered+=1);return f.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:t.orphans,killed:t.killed,failed:t.failed,unregistered:t.unregistered}),t}U();var fg=$.workerPid(),hi=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),fc({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,dc({registry:this.registry}).catch(t=>{f.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:t instanceof Error?t.message:String(t)})}),ac()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let t=async n=>{if(this.shutdownInitiated){f.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,f.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(s){s instanceof Error?f.error("SYSTEM","Error during shutdown",{},s):f.error("SYSTEM","Error during shutdown (non-Error)",{error:String(s)});try{await this.stop()}catch(i){i instanceof Error?f.debug("SYSTEM","Supervisor shutdown fallback failed",{},i):f.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(i)})}}process.exit(0)};process.on("SIGTERM",()=>{t("SIGTERM")}),process.on("SIGINT",()=>{t("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{f.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{t("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}cc(),this.stopPromise=sc({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,t,n){this.registry.register(e,t,n)}unregisterProcess(e,t){this.registry.unregister(e,t)}getRegistry(){return this.registry}},Lw=new hi(an());function fc(r={}){let e=r.pidFilePath??fg;if(!(0,at.existsSync)(e))return"missing";let t=null;try{t=JSON.parse((0,at.readFileSync)(e,"utf-8"))}catch(s){return s instanceof Error?f.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},s):f.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(s)}),(0,at.rmSync)(e,{force:!0}),"invalid"}return on(t)&&t?((r.logAlive??!0)&&f.info("SYSTEM","Worker already running (PID alive)",{existingPid:t.pid,existingPort:t.port,startedAt:t.startedAt}),"alive"):(r.removeStale===!1||(f.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:t?.pid,port:t?.port,startedAt:t?.startedAt}),(0,at.rmSync)(e,{force:!0})),"stale")}zr();var _i=require("path"),ln=require("fs"),gc=require("crypto");U();var cn=require("fs");ce();function pc(r,e){if(!(0,cn.existsSync)(r))return e;try{return zt((0,cn.readFileSync)(r,"utf-8"))}catch(t){throw new Error(`Corrupt JSON file, refusing to overwrite: ${r}: ${t instanceof Error?t.message:String(t)}`)}}C();var mc="telemetry.json";function pg(r){let e=r.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function gg(r,e){if(pg(r))return{enabled:!1,source:"DO_NOT_TRACK"};let t=r.CLAUDE_MEM_TELEMETRY?.toLowerCase();return t==="0"||t==="false"||t==="off"?{enabled:!1,source:"env"}:t==="1"||t==="true"||t==="on"?{enabled:!0,source:"env"}:e?.enabled===!0?{enabled:!0,source:"config"}:e?.enabled===!1?{enabled:!1,source:"config"}:{enabled:!0,source:"default"}}function un(r,e){return gg(r,e).enabled}function hc(r){let e=r.CLAUDE_MEM_TELEMETRY_ERRORS?.toLowerCase();return!(e==="0"||e==="false"||e==="off")}function mg(){return(0,_i.join)(se(),mc)}function Zt(){let r;try{r=pc(mg(),null)}catch(e){let t=e instanceof Error?e:new Error(String(e));return f.warn("SYSTEM","Telemetry: corrupt telemetry.json; treating as no recorded consent",void 0,t),null}return!r||typeof r!="object"||typeof r.installId!="string"||r.enabled!==void 0&&typeof r.enabled!="boolean"?null:{enabled:r.enabled,installId:r.installId,decidedAt:typeof r.decidedAt=="string"?r.decidedAt:""}}function hg(r){let e=se();(0,ln.mkdirSync)(e,{recursive:!0}),(0,ln.writeFileSync)((0,_i.join)(e,mc),JSON.stringify(r,null,2)+`
19
19
  `)}function dn(){let r=Zt();if(r?.installId)return r.installId;let e=(0,gc.randomUUID)();return hg({installId:e,decidedAt:""}),e}var Sc=Ee(require("os"),1);C();var _c=500;var Ec=8192,de="[REDACTED]";function yc(r){try{if(typeof r!="string"){if(r==null)return"";try{r=String(r)}catch(t){let n=t instanceof Error?t:new Error(String(t));return f.warn("SYSTEM","error-scrub: String() coercion of non-string input failed",void 0,n),""}}let e=r;return e.length>Ec?e.slice(0,Ec):e}catch{return""}}function Ei(r){if(typeof r!="string"||r.length===0)return r??"";let e="";try{e=Sc.default.homedir()||""}catch(n){let s=n instanceof Error?n:new Error(String(n));f.warn("SYSTEM","error-scrub: os.homedir() failed; skipping home-dir redaction",void 0,s),e=""}if(!e)return r;let t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");try{return r.replace(new RegExp(t,"g"),"~")}catch(n){let s=n instanceof Error?n:new Error(String(n));return f.warn("SYSTEM","error-scrub: home-dir RegExp replace failed; using split/join fallback",void 0,s),r.split(e).join("~")}}function Si(r){return typeof r!="string"||r.length===0?r??"":r.replace(/(?<![~\w])\/(?:[^\s/:"'()]+\/)+([^\s/:"'()]+)/g,"$1").replace(/[A-Za-z]:\\(?:[^\s\\:"'()]+\\)*([^\s\\:"'()]+)/g,"$1").replace(/\\\\[^\s\\:"'()]+(?:\\[^\s\\:"'()]+)*\\([^\s\\:"'()]+)/g,"$1")}function _g(r){return typeof r!="string"||r.length===0?r??"":r.replace(/\b[A-Za-z][A-Za-z0-9+.-]*:\/\/[^\s"'()]+/g,e=>/^https?:\/\/hooks\.slack\.com\/services\//i.test(e)?e.replace(/^(https?:\/\/hooks\.slack\.com\/services\/)[^\s"'()]+/i,`$1${de}`):e.replace(/[?#].*$/,"").replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/@\s]+@/,`$1${de}@`))}function Eg(r){return typeof r!="string"||r.length===0?r??"":r.replace(/\?[^\s"'()]*/g,"")}function Sg(r){return typeof r!="string"||r.length===0?r??"":r.replace(/\b(?:access[_-]?token|api[_-]?key|auth(?:orization)?|secret|password|passwd|jwt|session[_-]?id|token)=[^\s"'&]+/gi,e=>{let t=e.indexOf("=");return`${e.slice(0,t+1)}${de}`})}function yg(r){if(typeof r!="string"||r.length===0)return r??"";let e=r;return e=e.replace(/[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}/g,de),e=e.replace(/\b[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\b/g,de),e=e.replace(/\b(?:sk|pk|rk|ak|phc|phx|ph|ghp|gho|ghs|xox[bpasr])[-_][A-Za-z0-9_-]{8,512}\b/gi,de),e=e.replace(/\bBearer\s+[A-Za-z0-9._-]{8,512}\b/gi,de),e=e.replace(/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g,de),e=e.replace(/\b[0-9a-fA-F]{24,4096}\b/g,de),e=e.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,de),e=e.replace(/\b(?=[A-Za-z0-9+/_-]{0,4096}\d)[A-Za-z0-9+/_-]{32,4096}={0,2}\b/g,de),e=e.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,de),e}function bg(r){return typeof r!="string"||r.length===0?r??"":r.replace(/[ \t\f\v]+/g," ").replace(/ *\n */g,`
20
- `).trim()}function yi(r){let e=yc(r);return e.length===0?"":(e=Ei(e),e=_g(e),e=Si(e),e=Eg(e),e=Sg(e),e=yg(e),e)}function bc(r){try{let e=bg(yi(yc(r)));return e.length>_c?e.slice(0,_c):e}catch(e){let t=e instanceof Error?e:new Error(String(e));return f.warn("SYSTEM","error-scrub: message scrub failed; emitting empty message",void 0,t),""}}function wc(r){return(typeof r=="string"?r:"").replace(/\[REDACTED\]/g,"\xA7").replace(/'[^']*'/g,"'\xA7'").replace(/"[^"]*"/g,'"\xA7"').replace(/\b\d+\b/g,"\xA7").replace(/[ \t]+/g," ").trim().slice(0,200)}var wg=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"]),Tc=200;function Tg(r,e){if(!(!r||typeof r!="object"))for(let t of Object.keys(r)){if(!wg.has(t))continue;let n=r[t];if(typeof n=="string"){let s=n.length>Tc?n.slice(0,Tc):n;e[t]=yi(s)}else(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(e[t]=n)}}function fn(r){let e={};try{Tg(r,e)}catch{}return e}var bi=Ee(require("os"),1);C();var Ag="13.34.1",vg="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",Rg="https://us.i.posthog.com";function pn(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||vg}function gn(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||Rg}var Mg=["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 mn(r){let e={};for(let t of Mg)r[t]!==void 0&&(e[t]=r[t]);return e}function Cg(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||bi.default.release().toLowerCase().includes("microsoft")}catch(r){let e=r instanceof Error?r:new Error(String(r));return f.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function hn(){return{version:Ag,os:process.platform,os_version:bi.default.release(),is_wsl:Cg(),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 Pg=2e3;async function Ac(r,e,t){try{if(!un(process.env,Zt()))return;let n=fn({...hn(),...e??{}});if(t?.person?n.$set=mn(n):n.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:r,properties:n})+`
20
+ `).trim()}function yi(r){let e=yc(r);return e.length===0?"":(e=Ei(e),e=_g(e),e=Si(e),e=Eg(e),e=Sg(e),e=yg(e),e)}function bc(r){try{let e=bg(yi(yc(r)));return e.length>_c?e.slice(0,_c):e}catch(e){let t=e instanceof Error?e:new Error(String(e));return f.warn("SYSTEM","error-scrub: message scrub failed; emitting empty message",void 0,t),""}}function wc(r){return(typeof r=="string"?r:"").replace(/\[REDACTED\]/g,"\xA7").replace(/'[^']*'/g,"'\xA7'").replace(/"[^"]*"/g,'"\xA7"').replace(/\b\d+\b/g,"\xA7").replace(/[ \t]+/g," ").trim().slice(0,200)}var wg=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"]),Tc=200;function Tg(r,e){if(!(!r||typeof r!="object"))for(let t of Object.keys(r)){if(!wg.has(t))continue;let n=r[t];if(typeof n=="string"){let s=n.length>Tc?n.slice(0,Tc):n;e[t]=yi(s)}else(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(e[t]=n)}}function fn(r){let e={};try{Tg(r,e)}catch{}return e}var bi=Ee(require("os"),1);C();var Ag="13.34.2",vg="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",Rg="https://us.i.posthog.com";function pn(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||vg}function gn(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||Rg}var Mg=["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 mn(r){let e={};for(let t of Mg)r[t]!==void 0&&(e[t]=r[t]);return e}function Cg(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||bi.default.release().toLowerCase().includes("microsoft")}catch(r){let e=r instanceof Error?r:new Error(String(r));return f.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function hn(){return{version:Ag,os:process.platform,os_version:bi.default.release(),is_wsl:Cg(),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 Pg=2e3;async function Ac(r,e,t){try{if(!un(process.env,Zt()))return;let n=fn({...hn(),...e??{}});if(t?.person?n.$set=mn(n):n.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:r,properties:n})+`
21
21
  `);return}let s=pn(),i=new AbortController,o=setTimeout(()=>i.abort(),Pg);try{await Ig(s,r,n,i.signal)}finally{clearTimeout(o)}}catch{}}async function Ig(r,e,t,n){await fetch(`${gn()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:r,event:e,distinct_id:dn(),properties:t}),signal:n})}var re=Ee(require("path"),1),Oi=require("os"),oe=require("fs"),wn=require("child_process");C();C();C();var Q=Ee(require("path"),1),Ct=require("fs"),bn=require("os"),Mi=require("child_process");Vt();U();C();var _n=require("fs"),Ve=Ee(require("path"),1);C();var er={isWorktree:!1,isSubmodule:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function vc(r){let e=Ve.default.join(r,".git"),t;try{t=(0,_n.statSync)(e)}catch(c){return c instanceof Error&&c.code!=="ENOENT"&&f.warn("GIT","Unexpected error checking .git",{error:c instanceof Error?c.message:String(c)}),er}if(!t.isFile())return er;let n;try{n=(0,_n.readFileSync)(e,"utf-8").trim()}catch(c){return f.warn("GIT","Failed to read .git file",{error:c instanceof Error?c.message:String(c)}),er}let s=n.match(/^gitdir:\s*(.+)$/);if(!s)return er;let i=Ve.default.resolve(Ve.default.dirname(e),s[1]),o=i.match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(o){let c=o[1];return{isWorktree:!0,isSubmodule:!1,worktreeName:Ve.default.basename(r),parentRepoPath:c,parentProjectName:Ve.default.basename(c)}}let a=i.match(/^(.+)[/\\]\.git[/\\]modules[/\\](.+)$/);if(a){let c=a[1];return{isWorktree:!1,isSubmodule:!0,worktreeName:Ve.default.basename(r),parentRepoPath:c,parentProjectName:Ve.default.basename(c)}}return er}var Mc=require("fs");var wi=require("path");Vt();C();function Rc(r){let e=ve(r.replace(/\\/g,"/"));e=e.replace(/\\/g,"/");let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return t=t.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${t}$`)}function Ti(r,e){if(!e.length)return!1;let t=r.replace(/\\/g,"/"),n=(0,wi.basename)(t);for(let s of e){let i=s.trim();if(i)try{let o=Rc(i);if(o.test(t)||o.test(n))return!0}catch(o){f.warn("PROJECT_NAME","Invalid glob pattern",{pattern:i,error:o instanceof Error?o.message:String(o)});continue}}return!1}function En(r,e){if(!e||!e.trim())return!1;let t=r.replace(/\\/g,"/"),n=(0,wi.basename)(t),s=e.split(",").map(i=>i.trim()).filter(Boolean);for(let i of s)try{let o=Rc(i);if(o.test(t)||o.test(n))return!0}catch(o){f.warn("PROJECT_NAME","Invalid exclusion pattern",{pattern:i,error:o instanceof Error?o.message:String(o)});continue}return!1}C();function Cc(r){let e=r;if(typeof e=="string"){if(!e.trim())return[];try{e=JSON.parse(e)}catch(n){return f.warn("PROJECT_NAME","CLAUDE_MEM_PROJECT_ENVIRONMENTS is not valid JSON; ignoring it",{error:n instanceof Error?n.message:String(n)}),[]}}if(!Array.isArray(e))return e!=null&&f.warn("PROJECT_NAME","CLAUDE_MEM_PROJECT_ENVIRONMENTS must be an array; ignoring it",{}),[];let t=[];for(let n of e){let s=typeof n?.name=="string"?n.name.trim():"",i=Array.isArray(n?.patterns)?n.patterns.filter(o=>typeof o=="string"&&o.trim()!==""):[];if(!s||i.length===0){f.warn("PROJECT_NAME","Ignoring a project environment without a name or patterns",{name:s});continue}t.push({name:s,patterns:i})}return t}function Og(r){try{return(0,Mc.realpathSync)(r)}catch{return r}}function Ai(r,e){if(e.length===0)return null;let t=[...new Set([r,Og(r)])].flatMap(n=>[n,`${n.replace(/[\\/]+$/,"")}/`]);for(let n of e)if(t.some(s=>Ti(s,n.patterns)))return n.name;return null}var Ci="unknown-project";function Oc(r){try{return(0,Mi.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:r,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim()||null}catch(e){let t=e instanceof Error?e:new Error(String(e));return f.debug("PROJECT_NAME","git rev-parse failed, falling back to non-git root",{dir:r},t),null}}var kg=[".claude-mem-project",".claude-mem.json"],Dg=64;function kc(r){try{return(0,Ct.realpathSync)(r)}catch{return r}}function xg(r,e){let t=Q.default.relative(e,r);return t===""||!t.startsWith("..")&&!Q.default.isAbsolute(t)}function Lg(){return[(0,bn.homedir)(),(0,bn.tmpdir)(),rt].flatMap(r=>{let e=Q.default.resolve(r);return[e,kc(e)]})}function Dc(r){let e=Lg(),t=Q.default.resolve(r);if([Q.default.resolve(rt),kc(Q.default.resolve(rt))].some(s=>xg(t,s)))return null;for(let s=0;s<Dg;s++){if(e.includes(t))return null;let i=Q.default.dirname(t);if(i===t)return null;if(kg.some(o=>(0,Ct.existsSync)(Q.default.join(t,o))))return t;t=i}return null}function Ri(r,e){let t=Q.default.basename(e);if(t===""){if(process.platform==="win32"){let s=r.match(/^([A-Z]):\\/i);if(s){let o=`drive-${s[1].toUpperCase()}`;return f.info("PROJECT_NAME","Drive root detected",{cwd:r,projectName:o}),o}}return f.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:r}),Ci}return t}var Fg="CLAUDE_MEM_PROJECT_NAME_SOURCE",Sn=null;function Pc(){try{return(0,Ct.statSync)(ie).mtimeMs}catch{return-1}}function xc(){let r=Pc();if(r===-1)return B.getAllDefaults();if(Sn&&Sn.mtimeMs===r)return Sn.settings;let e=B.loadFromFile(ie);return Sn={mtimeMs:Pc(),settings:e},e}function Ng(){let r=process.env[Fg]??xc().CLAUDE_MEM_PROJECT_NAME_SOURCE;return String(r??"path").trim().toLowerCase()==="git-remote"}var Ug="CLAUDE_MEM_PROJECT_ENVIRONMENTS",yn=null;function Lc(){let r=process.env[Ug]??xc().CLAUDE_MEM_PROJECT_ENVIRONMENTS;return(!yn||yn.raw!==r)&&(yn={raw:r,environments:Cc(r)}),yn.environments}function $g(r){let e=(r??"").trim();if(!e||/^file:/i.test(e)||e.startsWith("/")||e.startsWith(".")||e.startsWith("~")||e.startsWith("\\\\")||/^[a-z]:[\\/]/i.test(e))return null;let n=e.replace(/\/+$/,"").replace(/\.git$/i,""),s=n.match(/^[a-z][a-z0-9+.-]*:\/\/[^/]+\/(.+)$/i),i=s?null:n.match(/^(?:[^/@\s]+@)?[^:/\s]+:(?!\/\/)(.+)$/),o=s?.[1]??i?.[1];if(!o)return null;let a=o.split("/").filter(c=>c&&c!=="_git");return a.length>=2?a.slice(-2).join("/"):a.length===1?a[0]:null}function Bg(r){try{let e=(0,Mi.execFileSync)("git",["remote","get-url","origin"],{cwd:r,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim();return $g(e)}catch(e){let t=e instanceof Error?e:new Error(String(e));return f.debug("PROJECT_NAME","No usable origin remote, keeping the path-based name",{repoRoot:r},t),null}}var vi=new Map;function Fc(r){return Ng()?(vi.has(r)||vi.set(r,Bg(r)),vi.get(r)??null):null}function Wg(r,e=process.platform){if(!r||r.trim()==="")return f.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:r}),Ci;let t=ve(r,e),n=Ai(t,Lc());if(n)return n;let s=Oc(t),i=s?Fc(s):null;if(i)return i;let o=s??Dc(t)??t;return Ri(r,o)}function Nc(r,e){return e===r?r:`${r}/${e}`}function jg(r,e){if(!r.isSubmodule||!r.parentRepoPath)return null;let t=Q.default.relative(r.parentRepoPath,e);return!t||t.startsWith("..")||Q.default.isAbsolute(t)?null:t.split(Q.default.sep).join("/")}function ct(r,e=process.platform){if(!r||r.trim()===""){let c=Wg(r,e);return{primary:c,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[c],keySource:"path"}}let t=ve(r,e),n=Oc(t),s=Hg(r,t,n),i=n?Fc(n):null,o=i?Ic(s,i,"git-remote"):s,a=Ai(t,Lc());return a?Ic(o,a,"environment"):o}function Ic(r,e,t){return{primary:e,parent:null,isWorktree:r.isWorktree,isSubmodule:r.isSubmodule,allProjects:[...r.allProjects.filter(n=>n!==e),e],keySource:t}}function Hg(r,e,t){let n=t?null:Dc(e),s=Ri(r,t??n??e),i=t??e,o=vc(i);if((o.isWorktree||o.isSubmodule)&&o.parentProjectName){let a=o.parentProjectName,c,l;return o.isSubmodule?(c=`${a}/${jg(o,i)??s}`,l=s!==a?[s]:[]):(c=Nc(a,s),l=c===a?[`${a}/${s}`]:[]),{primary:c,parent:a,isWorktree:o.isWorktree,isSubmodule:o.isSubmodule,allProjects:[...new Set([a,...l,c])].filter(u=>u!==c).concat(c),keySource:"path"}}if(n&&Q.default.resolve(n)!==Q.default.resolve(e)){let a=Ri(r,e);if(a!==s&&a!==Ci)return{primary:s,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[a,s],keySource:"path"}}return{primary:s,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[s],keySource:"path"}}U();var Uc=Re(Y.POWERSHELL_COMMAND);function Gg(r){return r===void 0?Uc:Math.max(1,Math.min(Uc,r))}var LT=$.dataDir(),FT=$.workerPid(),zg="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 Vg(r){try{return(0,oe.realpathSync)(r)}catch{return null}}function Pi(r){return r?/(^|[\\/])bun(\.exe)?$/i.test(r.trim()):!1}function Yg(r,e){let t=e==="win32"?"where.exe":"which",n=[r],s;try{s=(0,wn.execFileSync)(t,n,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(o){return o instanceof Error?f.debug("SYSTEM",`Binary lookup failed for ${r}`,{command:t,args:n},o):f.debug("SYSTEM",`Binary lookup failed for ${r}`,{command:t,args:n},new Error(String(o))),null}return s.split(/\r?\n/).map(o=>o.trim()).find(o=>o.length>0)||null}var Ii;function ki(r={}){let e=Object.keys(r).length===0;if(e&&Ii!==void 0)return Ii;let t=qg(r);return e&&t!==null&&(Ii=t),t}function $c(r,e){let t=r?.trim();return t?e==="win32"?[re.default.join(t,"bin","bun.exe"),re.default.join(t,"bin","bun"),re.default.join(t,"bun.exe")]:[re.default.join(t,"bin","bun"),re.default.join(t,"bun")]:[]}function qg(r){let e=r.platform??process.platform,t=r.execPath??process.execPath;if(Pi(t))return t;let n=r.env??process.env,s=r.homeDirectory??(0,Oi.homedir)(),i=r.pathExists??oe.existsSync,o=r.lookupInPath??Yg,a=r.realpath??Vg,c=e==="win32"?[n.BUN,n.BUN_PATH,...$c(n.BUN_INSTALL,e),re.default.join(s,".bun","bin","bun.exe"),re.default.join(s,".bun","bin","bun"),n.USERPROFILE?re.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?re.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?re.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0,n.npm_config_prefix?re.default.join(n.npm_config_prefix,"bun.exe"):void 0]:[n.BUN,n.BUN_PATH,...$c(n.BUN_INSTALL,e),re.default.join(s,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun",n.npm_config_prefix?re.default.join(n.npm_config_prefix,"bin","bun"):void 0];for(let d of c){let p=d?.trim();if(p&&(Pi(p)&&i(p)||p.toLowerCase()==="bun"))return p}let l=o("bun",e)?.trim();if(!l||!Pi(l))return null;let u=a(l)??l;return i(u)?u:null}function Di(){let r=$.dataDir();return(0,oe.mkdirSync)(r,{recursive:!0}),r}function Jg(r,e,t=Di()){let n=s=>s.replace(/'/g,"''");return`Start-Process -FilePath '${n(r)}' -ArgumentList @('"${n(e)}"','--daemon') -WorkingDirectory '${n(t)}' -WindowStyle Hidden`}function Xg(r=process.env){let e=r.SystemRoot||r.SYSTEMROOT;return e?`${e}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`:"powershell.exe"}function Qg(r,e,t=Di()){return["-NoProfile","-WindowStyle","Hidden","-EncodedCommand",Buffer.from(Jg(r,e,t),"utf16le").toString("base64")]}function xi(r,e,t,n=process.platform,s){if(n==="win32"){let u=Xg(t),d=Qg(r,e),p=Gg(s);try{let g=(0,wn.spawnSync)(u,d,{stdio:"ignore",windowsHide:!0,env:t,timeout:p,killSignal:"SIGTERM"});if(g.error)throw g.error;if(g.signal)throw new Error(`powershell Start-Process killed by signal=${g.signal} after ${p}ms`);if(g.status!==0)throw new Error(`powershell Start-Process exited ${g.status??"null"}`);return 0}catch(g){let m=g instanceof Error?g:new Error(String(g));f.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:r,powershell:u},m);return}}let i="/usr/bin/setsid",o=(0,oe.existsSync)(i),a=o?i:r,l=li(a,o?[r,e,"--daemon"]:[e,"--daemon"],{detached:!0,stdio:"ignore",cwd:Di(),env:t});if(l.on("error",u=>{f.error("SYSTEM",zg,{runtimePath:r,execPath:a},u)}),l.pid!==void 0)return l.unref(),l.pid}var Wc=Ee(require("net"),1);C();U();function Bc(r){let e=r?.code;return e==="EACCES"||e==="EADDRNOTAVAIL"}var Li="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 Fi(){return B.loadFromFile(ie).CLAUDE_MEM_WORKER_HOST}function jc(r){return r.startsWith("[")&&r.endsWith("]")?r:r.includes(":")?`[${r}]`:r}var lt=5e3;async function Hc(r,e,t="GET",n=lt){let s=await fetch(`http://${jc(Fi())}:${r}${e}`,{method:t,signal:AbortSignal.timeout(Math.max(1,n))}),i="";try{i=await s.text()}catch{}return{ok:s.ok,statusCode:s.status,body:i}}async function Kc(r,e=lt){let t=Date.now()+e;if(process.platform==="win32")try{let s=await fetch(`http://${jc(Fi())}:${r}/api/health`,{signal:AbortSignal.timeout(Math.max(1,t-Date.now()))});if(s.ok)return!0;f.debug("SYSTEM","Windows health check returned non-ok; falling through to socket probe",{port:r,status:s.status})}catch(s){s instanceof Error?f.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:r,message:s.message}):f.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:r,error:String(s)})}let n=await Tn(r,Math.max(1,t-Date.now()));return n==="occupied"||n==="indeterminate"}async function Tn(r,e=lt){return(await Zg(r,e)).occupancy}function Zg(r,e=lt){return e<=0?Promise.resolve({occupancy:"indeterminate"}):new Promise(t=>{let n=!1,s=!1,i=!1,o;try{o=Wc.default.createServer()}catch{t({occupancy:"indeterminate"});return}let a=u=>{if(i){u?.();return}i=!0;try{o.close(u)}catch(d){u?.(d instanceof Error?d:new Error(String(d)))}},c=setTimeout(()=>{if(s)a();else try{o.close()}catch{}l({occupancy:"indeterminate"})},e),l=u=>{n||(n=!0,clearTimeout(c),t(u))};o.once("error",u=>{if(s)a();else try{o.close()}catch{}u.code==="EADDRINUSE"?l({occupancy:"occupied"}):Bc(u)?l({occupancy:"unbindable",bindErrorCode:u.code}):l({occupancy:"indeterminate"})}),o.once("listening",()=>{if(s=!0,n){a();return}try{a(u=>l({occupancy:u?"indeterminate":"free"}))}catch{l({occupancy:"indeterminate"})}});try{o.listen(r,Fi())}catch{try{o.close()}catch{}l({occupancy:"indeterminate"})}})}async function em(r,e,t,n){let s=Date.now()+t;for(;Date.now()<s;){try{let o=s-Date.now();if((await Hc(r,e,"GET",Math.min(lt,o))).ok)return!0}catch(o){o instanceof Error?f.debug("SYSTEM",n,{},o):f.debug("SYSTEM",n,{error:String(o)})}let i=Math.min(500,s-Date.now());i>0&&await new Promise(o=>setTimeout(o,i))}return!1}function Gc(r,e=3e4){return em(r,"/api/health",e,"Service not ready yet, will retry")}async function tm(r,e=lt){try{let t=await Hc(r,"/api/health","GET",e);return t.ok?JSON.parse(t.body).version:null}catch{return f.debug("SYSTEM","Could not fetch worker version",{}),null}}async function zc(r,e,t=lt){let n=e??"unknown",s=await tm(r,t);return!s||n==="unknown"?{matches:!0,pluginVersion:n,workerVersion:s}:{matches:n===s,pluginVersion:n,workerVersion:s}}C();var An=require("path"),q=require("fs");U();C();var Yc=9e4,tA=Yc/3;function qc(){return(0,An.join)(se(),"spawn.lock")}function Vc(r){try{let e=JSON.parse((0,q.readFileSync)(r,"utf-8"));return typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0?null:e.pid}catch{return null}}function rm(r){if(r===null)return null;try{return process.kill(r,0),!0}catch(e){return e?.code==="EPERM"}}function Ni(){let r=qc(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let t=0;t<2;t++)try{return(0,q.mkdirSync)((0,An.dirname)(r),{recursive:!0}),(0,q.writeFileSync)(r,e,{flag:"wx"}),!0}catch(n){let s=n instanceof Error?n:new Error(String(n)),i=s.code;if(i!=="EEXIST")return f.warn("SYSTEM","Spawn lock write failed for a non-contention reason; failing open (spawning unlocked)",{lockPath:r,code:i},s),!0;if(t>0)return!1;let o;try{o=(0,q.statSync)(r).mtimeMs}catch{continue}let a=Vc(r),c=null;if(a===null)try{c=(0,q.readFileSync)(r,"utf-8")}catch{continue}if(Date.now()-o<=Yc&&rm(a)!==!1)return!1;let u;try{u=(0,q.statSync)(r).mtimeMs}catch{continue}if(u!==o)return!1;if(a!==null){if(Vc(r)!==a)return!1}else try{if((0,q.readFileSync)(r,"utf-8")!==c)return!1}catch{continue}try{(0,q.unlinkSync)(r)}catch{return!1}}return!1}function Ui(){let r=qc();try{if(JSON.parse((0,q.readFileSync)(r,"utf-8")).pid!==process.pid)return;(0,q.unlinkSync)(r)}catch{}}var Qc=require("node:child_process"),Zc=require("node:util");C();U();var vn=(0,Zc.promisify)(Qc.execFile),nm=/^(uv|uvx|python|chroma-mcp)(\.exe)?$/i;function Jc(r){return nm.test(r.trim())}function sm(r,e){if(!r)return!1;let t=r.toLowerCase().replace(/\\/g,"/"),n=t.indexOf("--data-dir");if(n<0)return!1;let s=t.slice(n+10).trim();if(s.startsWith('"')){let o=s.indexOf('"',1);s=o<0?s.slice(1):s.slice(1,o)}let i=e.toLowerCase().replace(/\\/g,"/");return s===i||s.startsWith(i)&&s[i.length]==="/"}function Rn(r,e){return e===void 0?r:Math.max(1,Math.min(r,e))}async function im(r){try{let e=await vn("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:Rn(3e4,r),windowsHide:!0,maxBuffer:33554432}),t=JSON.parse(e.stdout),n=Array.isArray(t)?t:t===null?[]:[t],s=[];for(let i of n){let o=typeof i.Name=="string"?i.Name.trim():"";if(!o)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)||s.push({pid:a,ppid:c,name:o,cmdline:typeof i.CommandLine=="string"?i.CommandLine:null,startToken:typeof i.StartToken=="string"&&i.StartToken.length>0?i.StartToken:null})}return s}catch(e){return f.warn("PROCESS","Cannot enumerate the Windows process table with names \u2014 ghost-port reclaim disabled",{error:e instanceof Error?e.message:String(e)}),null}}async function om(r,e){try{let t=await vn("netstat",["-ano"],{timeout:Rn(15e3,e),windowsHide:!0,maxBuffer:16777216});return um(t.stdout,r)}catch(t){return f.warn("PROCESS","netstat failed \u2014 ghost-port reclaim disabled for this attempt",{port:r,error:t instanceof Error?t.message:String(t)}),null}}async function am(r,e){try{let t=await vn("lsof",["-nP",`-iTCP:${r}`,"-sTCP:LISTEN","-t"],{timeout:Rn(1e4,e),maxBuffer:1048576});return cm(t.stdout)}catch(t){let n=t;return n.code===1&&typeof n.stdout=="string"&&n.stdout.trim()===""?[]:(f.warn("PROCESS","lsof failed \u2014 cannot verify the worker port owner",{port:r,error:t instanceof Error?t.message:String(t)}),null)}}function cm(r){let e=new Set;for(let t of r.split(/\r?\n/)){let n=Number.parseInt(t.trim(),10);Number.isInteger(n)&&n>0&&e.add(n)}return[...e]}async function lm(r,e){try{let n=(await vn("ps",["-p",String(r),"-o","command="],{timeout:Rn(5e3,e)})).stdout.trim();return n.length>0?n:null}catch{return null}}function um(r,e){let t=new Set,n=`:${e}`;for(let s of r.split(/\r?\n/)){let i=s.trim();if(!/^TCP\b/i.test(i))continue;let o=i.split(/\s+/);if(!o[1]?.endsWith(n)||o[3]!=="LISTENING")continue;let c=Number.parseInt(o[4]??"",10);Number.isInteger(c)&&c>0&&t.add(c)}return[...t]}var dm=/worker-service/i,el=1500,tl=1e3,$i=5500,Xc=2*el+tl+$i;async function fm(r,e){let t=e.readOwnedWorker();if(t===null||t.port!==r)return null;let n=(l,u={})=>(f.info("PROCESS","Wedged-worker reclaim declined",{port:r,pid:t.pid,reason:l,...u}),{reclaimed:!1,reason:l,killedPids:[]}),s=(e.now()-Date.parse(t.startedAt))/1e3;if(!Number.isFinite(s)||s<e.minOwnerAgeSeconds)return n("owner-booting",{ageSeconds:s,minOwnerAgeSeconds:e.minOwnerAgeSeconds});for(let l=0;l<2;l++)if(l>0&&await e.sleep(tl),await e.probeHealth(r))return n("owner-responding");let i=await e.listOwners(r);if(i===null)return n("netstat-unreadable");if(!i.includes(t.pid))return f.info("PROCESS","Wedged-worker reclaim: our worker does not own the port \u2014 deferring to the ghost-listener check",{port:r,pid:t.pid,listeners:i}),null;let o=await e.readIdentity(t.pid),a=t.startToken!==void 0&&o.startToken!==null&&o.startToken!==t.startToken;if(a||o.cmdline===null||!dm.test(o.cmdline))return n("owner-identity-mismatch",{tokenMismatch:a,hasCmdline:o.cmdline!==null});if(!e.hasKillBudget())return n("out-of-budget");f.warn("PROCESS","Reclaiming wedged worker: past its boot grace, silent on two health probes, and still holding the port",{port:r,pid:t.pid,ageSeconds:Math.round(s)});try{await e.killTree(t.pid,{expectedStartToken:o.startToken??t.startToken??void 0,signalMode:"graceful"})}catch(l){return f.error("PROCESS","Wedged-worker reclaim tree-kill failed",{port:r,pid:t.pid},l instanceof Error?l:new Error(String(l))),{reclaimed:!1,reason:"kill-failed",killedPids:[]}}let c=await e.listOwners(r);return c!==null&&c.length===0?(f.info("PROCESS","Wedged worker reclaimed \u2014 port is free again",{port:r,killedPids:[t.pid]}),{reclaimed:!0,killedPids:[t.pid]}):(f.warn("PROCESS","Wedged-worker reclaim killed the worker but the port is still bound",{port:r,pid:t.pid,stillOwnedBy:c}),{reclaimed:!1,reason:"still-bound",killedPids:[t.pid]})}async function pm(r,e,t,n){let s=Me(r),i=e?(await t(n))?.find(o=>o.pid===r)?.cmdline??null:await lm(r,n);return ye(r,s)?{startToken:s,cmdline:i}:{startToken:null,cmdline:null}}async function rl(r,e={}){let t=e.isWin32??(()=>process.platform==="win32"),n=e.now??Date.now,s=e.deadlineAt??null,i=S=>s!==null&&s-n()<S,o=()=>s===null?void 0:Math.max(1,s-n());if(i(Xc))return f.info("PROCESS","Port reclaim skipped: not enough of the hook budget is left to finish one",{port:r,remainingMs:o(),neededMs:Xc}),{reclaimed:!1,reason:"out-of-budget",killedPids:[]};let a=e.listOwners??((S,I)=>t()?om(S,I):am(S,I)),c=S=>a(S,o()),l=e.readTable??im,u=()=>l(o()),d=e.killTree??((S,I)=>ue(S,I)),p=e.dataDir??(()=>F),g=e.readIdentity??((S,I)=>pm(S,t(),l,I)),m=await fm(r,{listOwners:c,killTree:d,readOwnedWorker:e.readOwnedWorker??ze,probeHealth:e.probeHealth??(S=>Gc(S,el)),readIdentity:S=>g(S,o()),minOwnerAgeSeconds:e.minOwnerAgeSeconds??Ma(),now:n,sleep:e.sleep??(S=>new Promise(I=>setTimeout(I,S))),hasKillBudget:()=>!i($i)});if(m!==null)return m;if(!t())return{reclaimed:!1,reason:"not-supported",killedPids:[]};let h=await c(r);if(h===null)return{reclaimed:!1,reason:"netstat-unreadable",killedPids:[]};if(h.length===0)return{reclaimed:!1,reason:"no-listener",killedPids:[]};let E=await u();if(E===null)return{reclaimed:!1,reason:"table-unreadable",killedPids:[]};if(h.filter(S=>z(S)).length>0)return{reclaimed:!1,reason:"owner-alive",killedPids:[]};let b=new Map;for(let S of E){let I=b.get(S.ppid);I?I.push(S):b.set(S.ppid,[S])}let w=new Map,T=new Set,M=S=>{for(let I of b.get(S)??[])T.has(I.pid)||(T.add(I.pid),M(I.pid),Jc(I.name)&&w.set(I.pid,I))};for(let S of h)M(S);let R=p();if(R)for(let S of E)w.has(S.pid)||Jc(S.name)&&sm(S.cmdline,R)&&w.set(S.pid,S);if(w.size===0)return f.info("PROCESS","Ghost listener owner is dead but no chroma-sidecar descendants found",{port:r,deadOwners:h,processTableRows:E.length,dataDir:R??"(unresolved)"}),{reclaimed:!1,reason:"no-chroma-descendants",killedPids:[]};f.warn("PROCESS","Reclaiming ghost listener: killing dead worker's surviving chroma sidecar chain",{port:r,deadOwners:h,targets:[...w.values()].map(S=>({pid:S.pid,name:S.name}))});let y=[];for(let S of w.values()){if(i($i))return f.info("PROCESS","Ghost-listener reclaim stopped before a kill: the hook budget is spent",{port:r,killedPids:y}),{reclaimed:!1,reason:"out-of-budget",killedPids:y};try{await d(S.pid,{expectedStartToken:S.startToken,signalMode:"immediate"}),y.push(S.pid)}catch(I){return f.error("PROCESS","Ghost-port reclaim tree-kill failed",{port:r,pid:S.pid},I instanceof Error?I:new Error(String(I))),{reclaimed:!1,reason:"kill-failed",killedPids:y}}}let A=await c(r);return A!==null&&A.length===0?(f.info("PROCESS","Ghost listener reclaimed \u2014 port is free again",{port:r,killedPids:y}),{reclaimed:!0,killedPids:y}):(f.warn("PROCESS","Ghost-port reclaim killed the sidecar chain but the port is still bound",{port:r,killedPids:y,stillOwnedBy:A}),{reclaimed:!1,reason:"still-bound",killedPids:y})}ce();var Pt=require("fs"),sl=require("module"),Ye=Ee(require("path"),1),gm=["zod/v3","zod/v4","zod/v4-mini"];function nl(r){try{return(0,Pt.realpathSync)(r)}catch{return r}}function mm(r,e){let t=Ye.default.relative(e,r);return t!==""&&!t.startsWith("..")&&!Ye.default.isAbsolute(t)}function il(r){let e;try{let s=JSON.parse((0,Pt.readFileSync)(Ye.default.join(r,"package.json"),"utf-8"));e=Object.keys(s?.dependencies??{})}catch{return[]}if(e.length===0)return[];let t=Ye.default.join(r,"node_modules"),n=e.filter(s=>!(0,Pt.existsSync)(Ye.default.join(t,...s.split("/"),"package.json")));if(e.includes("zod")&&!n.includes("zod")){let s=(0,sl.createRequire)(Ye.default.join(t,"noop.js")),i=nl(Ye.default.join(t,"zod"));for(let o of gm)try{let a=s.resolve(o,{paths:[t]});mm(nl(a),i)||n.push(o)}catch{n.push(o)}}return n}function _l(r,e,t){let n=process.env[r];if(n){let s=parseInt(n,10);if(Number.isFinite(s)&&s>=t.min&&s<=t.max)return s;f.warn("SYSTEM",`Invalid ${r}, using default`,{value:n,min:t.min,max:t.max})}return e}var ft=_l("CLAUDE_MEM_HEALTH_TIMEOUT_MS",Re(Y.HEALTH_CHECK),{min:500,max:3e5}),tr=_l("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",Re(Y.HOOK_READINESS_WAIT),{min:0,max:3e5}),hm=5e3,_m={min:500,max:3e5},Em={min:500,max:Y.SESSION_INIT_REQUEST_MAX},ji=100;function El(r=process.env){let e=r.CLAUDE_MEM_FETCH_VERBOSE;if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="on"||t==="yes"}function Sm(r){return El()?{...r,verbose:!0}:r}function ym(r){let e={},t=r;for(let n=0;t&&n<4;n++){let s=n===0?"error":`cause${n}`;if(t instanceof Error){let i=t;e[s]={name:t.name,message:t.message,...i.code!==void 0?{code:i.code}:{}},t=t.cause;continue}e[s]=String(t);break}return e}function bm(r,e,t){let n=typeof e.method=="string"?e.method:"GET",s=ym(t),i=JSON.stringify(s);f.warn("SYSTEM","Worker IPC fetch failed",{url:r,method:n},i),Le(`[claude-mem] fetch verbose: ${n} ${r} ${i}
22
22
  `)}async function Hi(r,e={}){let t=Sm(e);try{return await fetch(r,t)}catch(n){throw El()&&bm(r,e,n),n}}async function Ki(r,e={},t){try{return await Hi(r,{...e,signal:AbortSignal.timeout(t)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new Error(`Request timed out after ${t}ms`):n}}function wm(r,e){let t=new AbortController,n=null,s=null,i=null,o=!1,a=()=>{s!==null&&(clearTimeout(s),s=null)},c=()=>{o=!0,a(),i!==null&&(clearTimeout(i),i=null)},l=d=>{o||(n=d,c(),t.abort(d))},u=()=>{o||(a(),s=setTimeout(()=>l(new Error(`Request timed out after ${r.idleTimeoutMs}ms idle`)),r.idleTimeoutMs))};if(r.absoluteCapMs!==void 0&&r.absoluteCapMs>0){let d=r.absoluteCapMs;i=setTimeout(()=>l(new Error(`Request timed out after ${d}ms`)),d)}return u(),{signal:e?AbortSignal.any([e,t.signal]):t.signal,touch:u,pause:a,dispose:c,translate:d=>n??d}}async function Sl(r,e,t){let n=wm(t,e.signal),s;try{s=await Hi(r,{...e,signal:n.signal})}catch(l){throw n.dispose(),n.translate(l)}n.touch();let i=s.body,o=i?i.getReader():null,a=!1;async function*c(){if(!o){a=!0,n.dispose();return}try{for(;;){n.touch();let l;try{l=await o.read()}catch(u){throw a=!0,n.translate(u)}if(l.done){a=!0;return}n.pause(),t.onChunk?.(l.value),yield l.value}}finally{n.dispose(),a||await o.cancel()}}return{status:s.status,statusText:s.statusText,ok:s.ok,headers:s.headers,chunks:c(),cancel:async()=>{n.dispose(),o&&!a&&(a=!0,await o.cancel())}}}async function Tm(r,e,t){let n=await Sl(r,e,t),s=new TextDecoder,i="";for await(let o of n.chunks)i+=s.decode(o,{stream:!0});return i+=s.decode(),{status:n.status,statusText:n.statusText,ok:n.ok,headers:n.headers,text:i}}var Mn=null,Cn=null,Pn=null,In=null,On=null;function Am(){return D.default.join(B.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function Gi(){return Pn!==null||(Pn=B.loadFromFile(Am())),Pn}function ol(r,e){if(!r)return null;let t=parseInt(r,10);return Number.isFinite(t)&&t>=e.min&&t<=e.max?t:null}function yl(r,e,t){let n=process.env[r];if(n!==void 0){let o=ol(n,t);return o!==null?o:(f.warn("SYSTEM",`Invalid ${r}, using default`,{value:n,min:t.min,max:t.max}),e)}let s=Gi()[r],i=ol(s,t);return i!==null?i:(f.warn("SYSTEM",`Invalid ${r} in settings.json, using default`,{value:s,min:t.min,max:t.max}),e)}function fe(){if(Mn!==null)return Mn;let r=Gi();return Mn=parseInt(r.CLAUDE_MEM_WORKER_PORT,10),Mn}function zi(){return Cn!==null||(Cn=Gi().CLAUDE_MEM_WORKER_HOST),Cn}function vm(){return In!==null||(In=yl("CLAUDE_MEM_API_TIMEOUT_MS",Re(Y.API_REQUEST),_m)),In}function bl(){return On!==null||(On=Math.min(yl("CLAUDE_MEM_SESSION_INIT_TIMEOUT_MS",Yt(),Em),Ca())),On}function Vi(r){return r===null?null:Math.max(0,r-Date.now())}function Dn(r){let e=Vi(r);return e!==null&&e<ji}function qe(r,e){let t=Vi(e);return t===null?r:Math.max(1,Math.min(r,t))}function wl(r){return`http://${ai(zi())}:${fe()}${r}`}function Ce(r,e={}){let t=e.method??"GET",n=wl(r),s={method:t};if(e.headers&&(s.headers=e.headers),e.body&&(s.body=e.body),e.idleTimeoutMs!==void 0&&e.idleTimeoutMs>0)return Tm(n,s,{idleTimeoutMs:e.idleTimeoutMs,absoluteCapMs:e.timeoutMs}).then(o=>new Response(o.text.length>0?o.text:null,{status:o.status,statusText:o.statusText,headers:o.headers}));let i=e.timeoutMs??vm();return i>0?Ki(n,s,i):Hi(n,s)}async function Rm(r){return(await Ce("/api/health",{timeoutMs:r})).ok}async function al(r=ft){return(await Ce("/api/readiness",{timeoutMs:r})).ok}function Tl(r){let e=(0,P.existsSync)(D.default.join(r,"plugin","scripts"))?D.default.join(r,"plugin"):r;return D.default.join(e,"scripts","worker-service.cjs")}function Mm(r,e){let t=d=>{let p=d.split("-")[0].split(".");return[parseInt(p[0],10)||0,parseInt(p[1],10)||0,parseInt(p[2],10)||0]},[n,s,i]=t(r),[o,a,c]=t(e);if(o!==n)return o-n;if(a!==s)return a-s;if(c!==i)return c-i;let l=r.includes("-")?1:0,u=e.includes("-")?1:0;return l!==u?l-u:r<e?1:r>e?-1:0}function Cm(r=D.default.join(D.default.dirname(D.default.dirname(At)),"cache","thedotmack","claude-mem")){try{return(0,P.readdirSync)(r).filter(e=>/^\d/.test(e)).map(e=>D.default.join(r,e)).filter(e=>{try{if(!(0,P.statSync)(e).isDirectory())return!1}catch{return!1}return!(0,P.existsSync)(D.default.join(e,".orphaned_at"))}).map(e=>({scriptPath:Tl(e),version:D.default.basename(e)}))}catch{return[]}}function cl(r){try{let e=JSON.parse((0,P.readFileSync)(r,"utf-8"));return typeof e.version=="string"?e.version:null}catch(e){let t=e.code;return t!=="ENOENT"&&f.debug("SYSTEM","Could not read package version for worker resolution",{packageJsonPath:r,code:t}),null}}function Pm(){return{cacheRoot:D.default.join(D.default.dirname(D.default.dirname(At)),"cache","thedotmack","claude-mem"),marketplaceRoot:At,cwd:process.cwd()}}function Yi(r=Pm()){let e=process.env.CLAUDE_MEM_WORKER_SCRIPT_PATH?.trim();if(e){if((0,P.existsSync)(e))return{scriptPath:e,version:null};f.debug("SYSTEM","Ignoring missing CLAUDE_MEM_WORKER_SCRIPT_PATH override",{override:e})}let t=[...Cm(r.cacheRoot),{scriptPath:Tl(D.default.join(r.marketplaceRoot,"plugin")),version:cl(D.default.join(r.marketplaceRoot,"package.json"))},{scriptPath:D.default.join(r.cwd,"plugin","scripts","worker-service.cjs"),version:cl(D.default.join(r.cwd,"package.json"))}];return km(t)}function Im(r){return D.default.dirname(D.default.dirname(r))}function Om(r){return il(Im(r.scriptPath)).length===0}function km(r,e=Om){let t=r.filter(n=>(0,P.existsSync)(n.scriptPath));return t.length===0?null:(t.sort((n,s)=>n.version===null&&s.version===null?0:n.version===null?1:s.version===null?-1:Mm(n.version,s.version)),t.find(e)??t[0])}function Dm(){return Yi()?.scriptPath??null}async function xm(r){let e=r.deadlineAt??null,t=r.backoffMs;for(let n=1;n<=r.attempts;n++){if(Dn(e))return!1;if(await kl(e??Number.POSITIVE_INFINITY))return!0;n<r.attempts&&(await new Promise(s=>setTimeout(s,qe(t,e))),t*=2)}return!1}function ll(r){return r instanceof Error&&/^Request timed out after \d+ms idle$/.test(r.message)}function ul(r){return r instanceof Error&&/^Request timed out after \d+ms$/.test(r.message)}async function Lm(r){let e;try{e=await Sl(wl("/api/ready"),{method:"GET"},{idleTimeoutMs:hm,absoluteCapMs:Math.max(1,r)})}catch(i){return ll(i)?{outcome:"unresponsive",detail:"no response headers within the idle window"}:ul(i)?{outcome:"still_booting",detail:"budget spent before response headers"}:(f.debug("SYSTEM","Worker /api/ready connection failed",{error:i instanceof Error?i.message:String(i)}),{outcome:"not_running"})}let t=()=>e.cancel().catch(i=>{f.debug("SYSTEM","Releasing the /api/ready body failed",{error:i instanceof Error?i.message:String(i)})}),n=e.headers?.get("content-type")??"";if(!e.ok||!n.includes("text/event-stream"))return xn(),await t(),{outcome:"unsupported"};let s=null;try{for await(let i of Ya(e.chunks)){if(i.event!=="phase")continue;let o=JSON.parse(i.data);if(s=typeof o.phase=="string"?o.phase:null,s==="ready")return xn(),await t(),{outcome:"ready"};if(s==="failed")return await t(),{outcome:"failed",detail:typeof o.message=="string"?o.message:"unknown init failure"}}}catch(i){return ul(i)?(xn(),{outcome:"still_booting",detail:`last phase ${s??"none"}`}):ll(i)?{outcome:"unresponsive",detail:`silent past the idle window after response headers (last phase ${s??"none"})`}:{outcome:"wedged",detail:`stream error: ${i instanceof Error?i.message:String(i)} (last phase ${s??"none"})`}}return{outcome:"wedged",detail:`stream closed before ready/failed (last phase ${s??"none"})`}}async function Fm(r){if(r<=0)try{return await al()?{outcome:"ready"}:{outcome:"still_booting"}}catch(t){return f.debug("SYSTEM","Worker readiness check threw",{},t instanceof Error?t:new Error(String(t))),{outcome:"still_booting"}}let e=Date.now();do{let t=r-(Date.now()-e);try{if(await al(Math.max(1,Math.min(ft,t))))return{outcome:"ready"}}catch(s){f.debug("SYSTEM","Worker readiness check threw",{error:s instanceof Error?s.message:String(s)})}let n=r-(Date.now()-e);if(n<=0)break;await new Promise(s=>setTimeout(s,Math.min(250,n)))}while(Date.now()-e<r);return{outcome:"still_booting",detail:"legacy /api/readiness never reported ready"}}async function It(r=tr){let e=r>0?r:ft,t=await Lm(e);return t.outcome==="ready"&&Hm(),t.outcome!=="unsupported"?t:(f.debug("SYSTEM","Worker has no /api/ready stream; falling back to /api/readiness"),Fm(r))}async function Nm(r=ft){try{let t=await(await Ce("/api/health",{timeoutMs:r})).json();return typeof t.version=="string"?t.version:null}catch(e){let t=e instanceof Error?e:new Error(String(e));return f.debug("SYSTEM","Worker health-version fetch failed",{},t),null}}async function Um(r=5e3){let e=Date.now()+r;for(;;){let t=e-Date.now();if(t<=0)return!1;if(await Tn(fe(),Math.min(1e3,t))==="free")return!0;let n=Math.min(200,e-Date.now());n>0&&await new Promise(s=>setTimeout(s,n))}}function Al(r,e){if(!r)return null;try{let t=(0,P.statSync)(r.scriptPath);return JSON.stringify([r.scriptPath,e,t.size,t.mtimeMs,t.ctimeMs])}catch{return null}}function vl(){return D.default.join(se(),"worker-version-recycle.json")}function $m(r,e){if(r===null||e===null)return!1;try{let t=JSON.parse((0,P.readFileSync)(vl(),"utf-8"));return t?.buildKey===r&&t?.workerVersion===e}catch{return!1}}async function dl(r,e=null,t=ft){let n=await Nm(t);if(n!==null&&n!==r){if(e!==null)try{H(vl(),{buildKey:e,workerVersion:n})}catch(s){f.warn("SYSTEM","Could not persist the failed worker version recycle",{error:s instanceof Error?s.message:String(s)})}f.warn("SYSTEM","Worker is ready but still reports a stale version; rebuild or reinstall the worker bundle before retrying",{pluginVersion:r,workerVersion:n})}}var Rl=3e4;function qi(){return D.default.join(se(),"worker-unresponsive.json")}function Bm(){try{let r=JSON.parse((0,P.readFileSync)(qi(),"utf-8"));return typeof r?.pid!="number"||typeof r?.firstUnresponsiveAtEpochMs!="number"?null:{pid:r.pid,firstUnresponsiveAtEpochMs:r.firstUnresponsiveAtEpochMs}}catch{return null}}function xn(){let r=qi();if((0,P.existsSync)(r))try{(0,P.unlinkSync)(r)}catch(e){f.debug("SYSTEM","Could not clear the unresponsive-worker record",{error:e instanceof Error?e.message:String(e)})}}function Wm(r=Date.now()){let e=ze()?.pid??null;if(e===null)return!1;let t=Bm();if(t!==null&&t.pid===e)return r-t.firstUnresponsiveAtEpochMs>=Rl;try{H(qi(),{pid:e,firstUnresponsiveAtEpochMs:r})}catch(n){f.warn("SYSTEM","Could not persist the unresponsive-worker record",{error:n instanceof Error?n.message:String(n)})}return!1}function Ji(){return D.default.join(se(),"worker-never-ready-recycle.json")}function jm(){try{let r=JSON.parse((0,P.readFileSync)(Ji(),"utf-8"));return typeof r?.buildKey!="string"||typeof r?.failureMessage!="string"?null:{buildKey:r.buildKey,failureMessage:r.failureMessage,refusalLogged:r.refusalLogged===!0}}catch{return null}}function Ml(r){try{H(Ji(),r)}catch(e){f.warn("SYSTEM","Could not persist the never-ready worker recycle",{error:e instanceof Error?e.message:String(e)})}}function Hm(){let r=Ji();if((0,P.existsSync)(r))try{(0,P.unlinkSync)(r)}catch(e){f.debug("SYSTEM","Could not clear the never-ready worker recycle record",{error:e instanceof Error?e.message:String(e)})}}function Cl(r){return Al(r,r?.version??"unknown")??"unresolved-worker-bundle"}function Pl(r){return r.outcome==="failed"?r.detail??"unknown init failure":r.outcome}function Il(r,e){if(r.outcome==="unresponsive"&&!Wm())return f.warn("SYSTEM","Worker went silent on /api/ready; skipping this hook without killing it",{detail:r.detail,wedgedAfterMs:Rl}),!1;let t=Pl(r),n=jm();return n!==null&&n.buildKey===e&&n.failureMessage===t?(n.refusalLogged?f.debug("SYSTEM","Never-ready worker recycle already refused for this bundle and failure",{failureMessage:t}):(f.error("SYSTEM","Worker keeps failing to start the same way after a recycle; not recycling again. Run `npx claude-mem doctor` and check the worker logs",{outcome:r.outcome,failureMessage:t,logsDir:D.default.join(se(),"logs")}),Ml({...n,refusalLogged:!0})),!1):!0}function Ol(r,e){Ml({buildKey:e,failureMessage:Pl(r)}),xn()}async function kl(r=Number.POSITIVE_INFINITY){let e=r-Date.now();if(e<=0)return!1;let t;try{t=await Rm(Math.min(ft,e))}catch(n){return f.debug("SYSTEM","Worker health check threw",{error:n instanceof Error?n.message:String(n)}),!1}return t}async function Dl(r,e){let t=ze();if(t===null||t.port!==fe())return f.error("SYSTEM","Stale worker is serving the port but the PID file does not identify it; kill the claude-mem worker process manually",{port:fe(),pidFilePid:t?.pid??null,pidFilePort:t?.port??null}),!1;if(e("stale-worker recycle"))return!1;try{await ue(t.pid,{signalMode:"immediate"})}catch(n){return f.error("SYSTEM","Could not kill stale worker",{pid:t.pid,port:t.port},n instanceof Error?n:new Error(String(n))),!1}return await Um(qe(5e3,r))?!0:(e("stale port release")||(dt=fe(),f.error("SYSTEM","Stale worker port still open after SIGKILL; skipping spawn this hook event",{pid:t.pid,port:fe(),fix:Fn})),!1)}async function Ln(r){let e=r===void 0?null:Date.now()+r,t=h=>Dn(e)?(f.warn("SYSTEM","Worker check ran out of the hook budget; skipping the rest this hook event",{step:h,budgetMs:r}),!0):!1,n=()=>e===null?void 0:qe(ft,e),s=Math.min(Date.now()+5e3,e??Number.POSITIVE_INFINITY),i=Yi(),o=null,a=null,c=!1,l=null,u=null,d=en(le());if(t("health probe"))return!1;if(await kl(s)){if(t("version probe"))return!1;let{matches:h,pluginVersion:E,workerVersion:_}=await zc(fe(),i?.version??null,n());if(E!=="unknown"&&(o=E),h){if(t("readiness wait"))return!1;let b=await It(qe(tr,e));if(b.outcome==="ready")return o!==null&&!Dn(e)&&await dl(o,null,n()),!0;if(b.outcome==="still_booting"||b.outcome==="not_running")return f.warn("SYSTEM","Worker is healthy but not ready yet; skipping hook API call",{outcome:b.outcome,detail:b.detail}),!1;if(d)return f.warn("SYSTEM","Worker will never become ready; CLAUDE_MEM_WORKER_AUTOSTART=false, so leaving it to whatever manages it",{outcome:b.outcome,detail:b.detail}),!1;if(u=Cl(i),!Il(b,u))return!1;l=b,f.info("SYSTEM","Worker will never become ready \u2014 recycling wedged worker",{outcome:b.outcome,detail:b.detail,version:_})}else{if(d)return f.warn("SYSTEM","Worker version differs from the installed plugin; CLAUDE_MEM_WORKER_AUTOSTART=false, so using it as is",{pluginVersion:E,workerVersion:_}),t("readiness wait")?!1:(await It(qe(tr,e))).outcome==="ready";if(a=Al(i,E),$m(a,_))return f.warn("SYSTEM","Skipping repeated worker recycle: the unchanged bundle still reports a stale version; rebuild or reinstall it",{pluginVersion:E,workerVersion:_,scriptPath:i?.scriptPath}),t("readiness wait")?!1:(await It(qe(tr,e))).outcome==="ready";f.info("SYSTEM","Worker version mismatch \u2014 killing stale worker",{pluginVersion:E,workerVersion:_})}if(!await Dl(e,t))return!1;l!==null&&u!==null&&Ol(l,u),c=!0}if(d)return f.debug("SYSTEM","Worker not running and CLAUDE_MEM_WORKER_AUTOSTART=false \u2014 not lazy-spawning"),!1;let p=i?.scriptPath??null;if(t("lazy spawn"))return!1;let g=Ni();try{if(g){if(!c&&!await Km(s,e))return!1;let E=ki();if(!E)return f.warn("SYSTEM","Cannot lazy-spawn worker: Bun runtime not found (PATH, BUN / BUN_PATH / BUN_INSTALL, or ~/.bun/bin)"),!1;if(!p)return f.warn("SYSTEM","Cannot lazy-spawn worker: worker-service.cjs not found in plugin/scripts"),!1;f.info("SYSTEM","Worker not running \u2014 lazy-spawning",{runtimePath:E,scriptPath:p});try{if(xi(E,p,Ge({...process.env,CLAUDE_MEM_WORKER_PORT:String(fe())}),process.platform,Vi(e)??void 0)===void 0)return!1}catch(_){return _ instanceof Error?f.error("SYSTEM","Lazy-spawn of worker failed",{runtimePath:E,scriptPath:p},_):f.error("SYSTEM","Lazy-spawn of worker failed (non-Error)",{runtimePath:E,scriptPath:p,error:String(_)}),!1}}else f.info("SYSTEM","Another launcher holds the spawn lock \u2014 skipping lazy-spawn and waiting for its worker");if(!await xm({attempts:6,backoffMs:500,deadlineAt:e}))return t("cold-boot port wait")||(f.warn("SYSTEM",g?"Worker port did not open after lazy-spawn within the cold-boot wait (~15s)":"Spawn-lock holder's worker port did not open within the cold-boot wait (~15s)"),ze()===null&&await Kc(fe(),e===null?void 0:qe(5e3,e))&&(dt=fe(),f.error("SYSTEM","Worker port is occupied by an unreachable process that no PID file claims (likely an orphaned OS socket); every lazy-spawn on this port will be silently refused",{port:dt,fix:Fn}))),!1}finally{g&&Ui()}if(t("readiness wait"))return!1;let m=await It(qe(tr,e));return m.outcome!=="ready"?(f.warn("SYSTEM","Worker lazy-spawned but did not become ready before hook readiness timeout",{outcome:m.outcome,detail:m.detail}),!1):(o!==null&&!Dn(e)&&await dl(o,a,n()),!0)}var Fn="Set CLAUDE_MEM_WORKER_PORT to a different port in claude-mem settings, or reboot to release the stuck port",dt=null,Wi=null;async function Km(r,e){let t=fe(),n=r-Date.now();if(n<=0)return!1;let s=await Tn(t,n);if(s==="free")return!0;if(s==="unbindable")return Wi=t,f.error("SYSTEM","Worker port cannot be bound (EACCES or EADDRNOTAVAIL) \u2014 skipping lazy-spawn",{port:t,host:zi(),fix:Li}),!1;if(s==="indeterminate")return f.warn("SYSTEM","Worker port state could not be determined in time \u2014 skipping lazy-spawn",{port:t}),!1;let i=await rl(t,{deadlineAt:e});return i.reclaimed?(f.info("SYSTEM","Reclaimed the worker port before lazy-spawn",{port:t,killedPids:i.killedPids}),!0):(ze()===null&&(dt=t),f.warn("SYSTEM","Worker port is held by a listener that does not answer health \u2014 skipping lazy-spawn",{port:t,reclaimReason:i.reason,...dt===t?{fix:Fn}:{}}),!1)}var kn=null;async function Gm(r){return kn!==null||(kn=await Ln(r)),kn}async function zm(r){let e=Date.now()+r,t=()=>e-Date.now(),n=l=>t()>=ji?!1:(f.debug("SYSTEM","Bounded worker startup ran out of budget",{step:l,budgetMs:r}),!0),s=await It(Math.max(1,t()));if(s.outcome==="ready")return!0;if(s.outcome==="still_booting")return f.warn("SYSTEM","Worker is still booting; bounded startup budget spent, skipping this call",{detail:s.detail,budgetMs:r}),!1;if(!!en(le()))return fl(e);let o=ki(),a=Dm();if(!o||!a)return!1;if(s.outcome==="failed"||s.outcome==="wedged"||s.outcome==="unresponsive"){let l=Cl(Yi());if(!Il(s,l)||(f.info("SYSTEM","Worker will never become ready \u2014 recycling wedged worker",{outcome:s.outcome,detail:s.detail}),!await Dl(e,n)))return!1;Ol(s,l)}let c=Ni();try{return c&&xi(o,a,Ge({...process.env,CLAUDE_MEM_WORKER_PORT:String(fe())}),process.platform,Math.max(1,t()))===void 0?!1:await fl(e)}catch(l){return f.debug("SYSTEM","Bounded worker startup failed",{error:l instanceof Error?l.message:String(l)}),!1}finally{c&&Ui()}}async function fl(r){for(;r-Date.now()>0;){let e=await It(Math.max(1,r-Date.now()));if(e.outcome==="ready")return!0;if(e.outcome!=="not_running")return f.debug("SYSTEM","Bounded worker startup did not reach ready",{outcome:e.outcome,detail:e.detail}),!1;let t=Math.min(100,r-Date.now());t>0&&await new Promise(n=>setTimeout(n,t))}return!1}var Vm=3,xl=20,Ll=1e3,Ym=10,Fl=5e3,qm=Fl+Ll;function Nn(){return D.default.join(F,"state")}function Nl(){return D.default.join(Nn(),"hook-failures.json")}function Ul(){return D.default.join(Nn(),"hook-failures.lock")}async function Xi(r=Ll){let e=Nn(),t=Ul(),n=(0,hl.randomUUID)(),s=JSON.stringify({pid:process.pid,token:n}),i=Date.now()+r;for(;Date.now()<=i;)try{return(0,P.mkdirSync)(e,{recursive:!0}),(0,P.writeFileSync)(t,s,{flag:"wx"}),n}catch(o){let a=o instanceof Error?o:new Error(String(o)),c=a.code;if(c!=="EEXIST")return f.warn("SYSTEM","Hook-failure lock unavailable; skipping failure-state update",{lockPath:t,code:c},a),null;let l;try{l=(0,P.statSync)(t).mtimeMs}catch{continue}if(Date.now()-l>Fl){let u;try{u=(0,P.statSync)(t).mtimeMs}catch{continue}if(u===l)try{(0,P.unlinkSync)(t);continue}catch{}}await new Promise(u=>setTimeout(u,Ym))}return f.warn("SYSTEM","Timed out waiting for hook-failure lock; skipping failure-state update",{lockPath:t,waitMs:r}),null}function Qi(r){let e=Ul();try{if(JSON.parse((0,P.readFileSync)(e,"utf-8")).token!==r)return;(0,P.unlinkSync)(e)}catch{}}function Jm(r){let e=JSON.parse(r);return{consecutiveFailures:typeof e.consecutiveFailures=="number"&&Number.isFinite(e.consecutiveFailures)?Math.max(0,Math.floor(e.consecutiveFailures)):0,lastFailureAt:typeof e.lastFailureAt=="number"&&Number.isFinite(e.lastFailureAt)?e.lastFailureAt:0,thresholdTripped:e.thresholdTripped===!0,notifiedSessionIds:Array.isArray(e.notifiedSessionIds)?e.notifiedSessionIds.filter(t=>typeof t=="string").slice(-xl):void 0}}function rr(){try{return Jm((0,P.readFileSync)(Nl(),"utf-8"))}catch{return{consecutiveFailures:0,lastFailureAt:0,thresholdTripped:!1}}}function Zi(r){let e=Nn(),t=Nl(),n=`${t}.tmp`;try{return(0,P.existsSync)(e)||(0,P.mkdirSync)(e,{recursive:!0}),(0,P.writeFileSync)(n,JSON.stringify(r),"utf-8"),(0,P.renameSync)(n,t),!0}catch(s){return f.debug("SYSTEM","Failed to persist hook-failure counter",{error:s instanceof Error?s.message:String(s)}),!1}}function Xm(){try{let e=le().CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD,t=parseInt(e,10);if(Number.isFinite(t)&&t>=1)return t}catch{}return Vm}var pl=null;function $l(r){let e=Wi!==null?`The worker cannot bind port ${Wi} on ${zi()}: the system refuses it (EACCES or EADDRNOTAVAIL). ${Li}.`:dt!==null?`Port ${dt} is held by an unreachable process that no PID file claims, so the worker cannot bind it. ${Fn}.`:"Run `npx claude-mem restart`; if it keeps failing, run `npx claude-mem doctor`.";return`claude-mem worker unreachable for ${r} consecutive hooks \u2014 memory features are degraded, but your prompts are not blocked. ${e}`}var Qm=!1,gl=!1;async function Bi(){if(Qm){if(gl)return rr().consecutiveFailures;gl=!0}let r=await Xi();if(r===null)return rr().consecutiveFailures;let e,t=!1;try{let n=rr();e={consecutiveFailures:n.consecutiveFailures+1,lastFailureAt:Date.now(),thresholdTripped:n.thresholdTripped,notifiedSessionIds:n.notifiedSessionIds};let s=Xm();t=e.consecutiveFailures>=s&&!e.thresholdTripped,t&&(e.thresholdTripped=!0);let i=Zi(e);t=t&&i}finally{Qi(r)}return t&&(await Ac("hook_failed",{...pl!==null?{hook_type:pl}:{},error_mode:"worker_unavailable",consecutive_failures:e.consecutiveFailures,threshold_tripped:!0}),Le(`${$l(e.consecutiveFailures)}
23
23
  `)),e.consecutiveFailures}async function Bl(r){if(!r)return null;let e=await Xi();if(e===null)return null;try{let t=rr(),n=t.notifiedSessionIds??[];return!t.thresholdTripped||n.includes(r)?null:Zi({...t,notifiedSessionIds:[...n,r].slice(-xl)})?$l(t.consecutiveFailures):null}finally{Qi(e)}}async function ml(){let r=await Xi(qm);if(r!==null)try{let e=rr();if(e.consecutiveFailures===0&&!e.thresholdTripped)return;Zi({consecutiveFailures:0,lastFailureAt:0,thresholdTripped:!1})}finally{Qi(r)}}var ut=Symbol.for("claude-mem/worker-fallback");function Wl(r){return typeof r=="object"&&r!==null&&r[ut]===!0}async function jl(r,e,t,n={}){let s=Date.now(),i=n.workerStartupTimeoutMs!==void 0;if(!(i?await zm(n.workerStartupTimeoutMs):await Gm(n.timeoutMs)))return en(le())?{continue:!0,reason:"worker_autostart_disabled",[ut]:!0}:(i||await Bi(),{continue:!0,reason:"worker_unreachable",[ut]:!0});let a={method:e};if(t!==void 0&&(a.headers={"Content-Type":"application/json"},a.body=JSON.stringify(t)),n.timeoutMs!==void 0){let u=i?n.timeoutMs:n.timeoutMs-(Date.now()-s);if(u<ji)return f.debug("SYSTEM","Hook budget spent before the worker request; skipping it",{url:r}),i||await Bi(),{continue:!0,reason:"worker_budget_exhausted",[ut]:!0};a.timeoutMs=u}let c;try{c=await Ce(r,a)}catch(u){if(!i)throw u;return f.debug("SYSTEM","Worker unavailable for best-effort hook call",{error:u instanceof Error?u.message:String(u)}),{continue:!0,reason:"worker_unreachable",[ut]:!0}}if(!c.ok){let u=await c.text().catch(()=>"");if(await ml(),c.status===429||c.status>=500)return f.warn("SYSTEM",`Worker API ${e} ${r} returned ${c.status}; skipping hook API call`,{body:u.substring(0,200)}),{continue:!0,reason:`worker_api_${c.status}`,[ut]:!0};let d=u;try{d=JSON.parse(u)}catch{}return d}let l;try{l=await c.text()}catch(u){return f.debug("SYSTEM","Worker response body could not be read; treating the worker as unreachable",{error:u instanceof Error?u.message:String(u)}),i||await Bi(),{continue:!0,reason:"worker_body_read_failed",[ut]:!0}}if(await ml(),l.length!==0)try{return JSON.parse(l)}catch{return l}}C();var Pe=require("path");U();var Zm="plugins",eh="cache",th="thedotmack",rh="claude-mem",nh="plugin",sh=(0,Pe.join)(rt,Zm,eh,th,rh),ih=(0,Pe.join)(At,nh);function eo(r,e){let t=(0,Pe.normalize)(r),n=(0,Pe.normalize)(e);if(t===n)return!0;let s=(0,Pe.relative)(n,t);return s.length>0&&!s.startsWith("..")&&!(0,Pe.isAbsolute)(s)}function Un(r){if(process.env.CLAUDE_MEM_INTERNAL==="1")return!1;if(!r)return!0;if(eo(r,qr)||eo(r,sh)||eo(r,ih))return!1;let e=le();return!En(r,e.CLAUDE_MEM_EXCLUDED_PROJECTS)}var Hl="claude";function oh(r){return r.trim().toLowerCase().replace(/\s+/g,"-")}function Z(r){if(!r)return Hl;let e=oh(r);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e.includes("kimi")?"kimi":e==="pi-mono"?"pi":e==="agy"||e==="antigravity"||e.startsWith("antigravity-")?"antigravity-cli":e:Hl}C();var $n=require("fs");C();U();ce();var ah=[{name:"aws_access_key",regex:/AKIA[0-9A-Z]{16}/g},{name:"aws_secret_key",regex:/(?<=AWS_SECRET_ACCESS_KEY\s*[=:]\s*['"]?)[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}],ch=1024*1024,lh="<redacted type='oversize'/>";function zl(r,e){if(!e.enabled||r.length===0)return{redacted:r,counts:{},oversize:!1};if(r.length>ch)return f.warn("REDACT","field exceeds the 1M-char redaction cap; replaced by an oversize marker",void 0,{inputLength:r.length}),{redacted:lh,counts:{oversize:1},oversize:!0};let t=new Set(e.disabledBuiltinPatterns??[]),n={},s=r,i=[];for(let a of e.customPatterns??[]){if(!a.name||a.name.length===0){f.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){f.warn("REDACT","custom pattern skipped: invalid regex",{name:a.name},c instanceof Error?c:new Error(String(c)))}}let o=[...i,...ah];for(let a of o)t.has(a.name)||(a.regex.lastIndex=0,s=s.replace(a.regex,()=>(n[a.name]=(n[a.name]??0)+1,`<redacted type='${a.name}'/>`)));return e.logMatches&&Object.keys(n).length>0&&f.debug("REDACT","patterns matched",void 0,{counts:n}),{redacted:s,counts:n,oversize:!1}}function uh(r){if(!r||r.trim()==="")return[];try{let e=JSON.parse(r);return Array.isArray(e)?e.filter(t=>t&&typeof t.name=="string"&&typeof t.regex=="string"):(f.warn("REDACT","CLAUDE_MEM_REDACT_CUSTOM_PATTERNS is not a JSON array, ignoring"),[])}catch(e){return f.warn("REDACT","failed to parse CLAUDE_MEM_REDACT_CUSTOM_PATTERNS as JSON",void 0,e instanceof Error?e:new Error(String(e))),[]}}function dh(r){return{enabled:r.CLAUDE_MEM_REDACT_ENABLED==="true",disabledBuiltinPatterns:(r.CLAUDE_MEM_REDACT_DISABLED_BUILTINS??"").split(",").map(e=>e.trim()).filter(Boolean),customPatterns:uh(r.CLAUDE_MEM_REDACT_CUSTOM_PATTERNS??"[]"),logMatches:r.CLAUDE_MEM_REDACT_LOG_MATCHES==="true"}}var nr=null,Kl=0,fh=5e3,sr=null,Gl=!1,ph={enabled:!0,disabledBuiltinPatterns:[],customPatterns:[],logMatches:!1},gh=/"CLAUDE_MEM_REDACT_ENABLED"\s*:\s*"true"/;function mh(r){if(!(0,$n.existsSync)(r))return null;try{return(0,$n.readFileSync)(r,"utf-8")}catch{return""}}function hh(r){if(r===null)return!1;try{let e=JSON.parse(Js(r));return e===null||typeof e!="object"||Array.isArray(e)}catch{return!0}}function _h(r,e,t){return process.env.CLAUDE_MEM_REDACT_ENABLED==="false"||!(sr?.enabled===!0||gh.test(e))?t:(Gl||(Gl=!0,f.warn("REDACT","settings.json could not be read; secret redaction stays on until it is repaired",{settingsPath:r,using:sr?.enabled?"the last configuration that loaded":"the built-in patterns"})),sr?.enabled?sr:ph)}function Vl(r=ie){let e=Date.now();if(nr&&e-Kl<fh)return nr;let t=B.loadFromFile(r),n=dh(t),s=n.enabled?null:mh(r);return hh(s)?nr=_h(r,s,n):(nr=n,sr=n),Kl=e,nr}var Jl=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],Yl=new RegExp(`<(${Jl.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g");var ql=100;function Eh(r){let e=Object.fromEntries(Jl.map(i=>[i,0]));Yl.lastIndex=0;let t=0,n=r.replace(Yl,(i,o)=>(e[o]=(e[o]??0)+1,t+=1,""));return t>ql&&f.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:t,maxAllowed:ql,contentLength:r.length}),{stripped:zl(n.trim(),Vl()).redacted,counts:e}}function to(r){return Eh(r).stripped}var Sh=["task-notification"],yh=new RegExp(`^\\s*<(${Sh.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),bh=256*1024;function Xl(r){return!r||r.length>bh?!1:yh.test(r)}var wh=[/^You are a helpful assistant\. You will be presented with a user prompt, and your job is to provide a short title/,/^## Memory Writing Agent: Phase 2 \(Consolidation\)/,/^# Overview\r?\n(?:\r?\n)?Generate 0 to 3 hyperpersonalized suggestions/];function Ql(r){let e=r.trimStart();return wh.some(t=>t.test(e))}C();var Th=Re(Y.API_REQUEST),Ue=class extends Error{kind;status;cause;constructor(e,t,n={}){super(t),this.name="ServerClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},Wn=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=Ah(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??Th}async startSession(e,t={}){let n=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",n,t)}async recordEvent(e){let t=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,t)}async endSession(e){if(!e.sessionId)throw new Ue("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e,t={}){let n={projectId:e.projectId};return e.query!==void 0&&(n.query=e.query),e.limit!==void 0&&(n.limit=e.limit),e.platformSource!==void 0&&(n.platformSource=Bn(e.platformSource)),e.folderProjects&&e.folderProjects.length>0&&(n.folderProjects=e.folderProjects),e.excludeSubagents!==void 0&&(n.excludeSubagents=e.excludeSubagents),this.request("POST","/v1/context",n,t)}async getJobStatus(e){if(!e)throw new Ue("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let t=e.content,n=e.kind??"manual",s=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,content:t,...s?{title:s}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.platformSource!==void 0?{platformSource:e.platformSource}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Bn(e.platformSource)}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:Bn(e.platformSource)}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:Bn(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,t,n,s={}){if(!this.apiKey||!this.apiKey.trim())throw new Ue("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let i=`${this.baseUrl}${t}`,o={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(o.body=JSON.stringify(n));let a,c=s.timeoutMs??this.timeoutMs;try{a=await Ki(i,o,c)}catch(u){let d=u instanceof Error?u.message:String(u),p=/timed out|timeout/i.test(d);throw new Ue(p?"timeout":"transport",`Server ${e} ${t} failed: ${d}`,{cause:u})}if(!a.ok){let u=await a.text().catch(()=>"");throw new Ue("http_error",`Server ${e} ${t} returned ${a.status}: ${vh(u,200)}`,{status:a.status})}let l=await a.text();if(!l||l.length===0)return{};try{return JSON.parse(l)}catch(u){let d=u instanceof Error?u:new Error(String(u));throw new Ue("invalid_response",`Server ${e} ${t} returned non-JSON response`,{cause:d})}}};function Zl(r){return r instanceof Ue}function Ah(r){return r.replace(/\/+$/,"")}function Bn(r){return typeof r=="string"?Z(r):null}function vh(r,e){return r.length<=e?r:`${r.slice(0,e)}\u2026`}function Rh(){let e=(le().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function Mh(){let r=le(),e=(...o)=>{for(let a of o){let c=(a??"").trim();if(c.length>0)return c}return""},t=e(r.CLAUDE_MEM_SERVER_URL,r.CLAUDE_MEM_SERVER_BETA_URL),n=e(r.CLAUDE_MEM_SERVER_API_KEY,r.CLAUDE_MEM_SERVER_BETA_API_KEY),s=e(r.CLAUDE_MEM_SERVER_PROJECT_ID,r.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!t)return f.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return f.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!s)return f.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let i={serverBaseUrl:t,apiKey:n};return{runtime:"server",client:new Wn(i),projectId:s,serverBaseUrl:t}}function eu(){if(Rh()!=="server")return{runtime:"worker"};let r=Mh();return r||{runtime:"worker"}}function tu(r,e){f.warn("HOOK",`[server-fallback] reason=${r}`,e??{})}var Ch={executeWithWorkerFallback:jl,getSessionInitRequestTimeoutMs:bl,isWorkerFallback:Wl,consumeWorkerOutageNotice:Bl,loadFromFileOnce:le,resolveRuntimeContext:eu,logServerFallback:tu,shouldTrackProject:Un,readHookEnvironment:()=>process.env},be=Ch,Ph=2,ro=500,Ih=2e3;var jn=class extends Error{constructor(t){super(`session-init did not record the prompt (${t})`);this.reason=t;this.name="SessionPromptNotRecordedError"}reason};function su(r){return Dh.run(r,!0)}var Oh=r=>r?r.replace(/\\/g,"/").includes("/.qwen/"):!1,kh=(r,e=process.env)=>r?e.QWEN_PROJECT_DIR?!0:Oh(r):!1,Dh={async run(r,e){let{sessionId:t,prompt:n,submittedPrompt:s}=r,i=r.cwd??process.cwd();if(!t)return f.warn("HOOK","session-init: No sessionId provided, skipping (Codex CLI or unknown platform)"),{continue:!0,suppressOutput:!0,exitCode:He.SUCCESS};if(!be.shouldTrackProject(i))return f.info("HOOK","Project excluded from tracking",{cwd:i}),{continue:!0,suppressOutput:!0};if(n&&Xl(n))return f.debug("HOOK","session-init: skipping internal protocol payload",{preview:n.slice(0,80)}),{continue:!0,suppressOutput:!0};if(n&&Z(r.platform)==="codex"&&Ql(n))return f.debug("HOOK","session-init: skipping a Codex internal helper prompt",{reason:"internal_system_prompt",preview:n.slice(0,80)}),{continue:!0,suppressOutput:!0};if(s===null)return f.debug("HOOK","session-init: host reported no user-submitted text; not storing a prompt",{sessionId:t}),{continue:!0,suppressOutput:!0};if(s===void 0&&!n?.trim()&&kh(r.transcriptPath,be.readHookEnvironment()))return f.debug("HOOK","session-init: Qwen send carried no submitted_prompt and no prompt text; not storing a prompt",{sessionId:t}),{continue:!0,suppressOutput:!0};let o=s??n,a=!o||!o.trim()?"[media prompt]":o,c=ct(i),l=c.primary,u=Z(r.platform),d=be.loadFromFileOnce(),p=String(d.CLAUDE_MEM_SEMANTIC_INJECT).toLowerCase()==="true",g=be.resolveRuntimeContext(),m=Date.now(),h=be.getSessionInitRequestTimeoutMs();if(g.runtime==="server")try{return await xh(g,r,t,u,l,a,Math.max(ro,Math.floor(h/Ph))),{continue:!0,suppressOutput:!0}}catch(M){if(Zl(M)&&M.isFallbackEligible())be.logServerFallback(M.kind,{status:M.status,message:M.message,route:"/v1/sessions/start"});else return f.error("HOOK","Server session-start failed (non-recoverable)",{error:M instanceof Error?M.message:String(M)}),{continue:!0,suppressOutput:!0,exitCode:He.SUCCESS}}f.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:t,project:l});let E=ru(m,h);if(E<ro){if(f.warn("HOOK","session-init: skipping the worker call because the prompt budget is spent",{contentSessionId:t,project:l,remainingMs:E}),e)throw new jn("budget_exhausted");return{continue:!0,suppressOutput:!0,exitCode:He.SUCCESS}}let _=await be.executeWithWorkerFallback("/api/sessions/init","POST",{contentSessionId:t,project:l,prompt:a,platformSource:u,cwd:i,projectKeySource:c.keySource},nu(u,E));if(be.isWorkerFallback(_)){if(e)throw new jn("reason"in _?_.reason:"worker_fallback");let M=await be.consumeWorkerOutageNotice(t);return{continue:!0,suppressOutput:!0,exitCode:He.SUCCESS,...M?{systemMessage:M}:{}}}if(typeof _?.sessionDbId!="number")return f.failure("HOOK","Session initialization returned malformed response",{contentSessionId:t,project:l}),{continue:!0,suppressOutput:!0,exitCode:He.SUCCESS};let b=_.sessionDbId,w=_.promptNumber;if(f.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:b,promptNumber:w,skipped:_.skipped,contextInjected:_.contextInjected}),f.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${t} | prompt#=${w} | sessionDbId=${b}`),_.skipped&&_.reason==="private")return f.info("HOOK",`INIT_COMPLETE | sessionDbId=${b} | promptNumber=${w} | skipped=true | reason=private`,{sessionId:b}),{continue:!0,suppressOutput:!0};let T="";if(p&&a&&a.length>=20&&a!=="[media prompt]"){let M=d.CLAUDE_MEM_SEMANTIC_INJECT_LIMIT||"5",R=ru(m,h);if(R<ro)f.warn("HOOK","session-init: skipping semantic injection because the prompt budget is spent",{contentSessionId:t,project:l,remainingMs:R});else{let y=await be.executeWithWorkerFallback("/api/context/semantic","POST",{q:a,project:l,projects:c.allProjects,limit:M,platformSource:u},nu(u,R));!be.isWorkerFallback(y)&&y?.context&&(f.debug("HOOK",`Semantic injection: ${y.count} observations for prompt`,{sessionId:b,count:y.count}),T=y.context)}}return f.info("HOOK",`INIT_COMPLETE | sessionDbId=${b} | promptNumber=${w} | project=${l}`,{sessionId:b}),T?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:T}}:{continue:!0,suppressOutput:!0}}};async function xh(r,e,t,n,s,i,o){await r.client.startSession({projectId:r.projectId,externalSessionId:t,contentSessionId:t,agentId:e.agentId??null,agentType:e.agentType??null,platformSource:n,metadata:{project:s,prompt:i}},{timeoutMs:o}),f.info("HOOK","session-init: server session started",{contentSessionId:t,project:s})}function ru(r,e){return Math.max(0,e-(Date.now()-r))}function nu(r,e){return r==="codex"?{workerStartupTimeoutMs:Y.POST_SPAWN_WAIT,timeoutMs:Math.min(Ih,e)}:{timeoutMs:e}}var io=require("crypto"),K=require("fs"),Ie=require("path");ce();U();C();var Lh=["observation","file_edit","summarize","session_end","advisor_calls"],Fh=/^[a-z_]+-[A-Za-z0-9_-]+\.json$/,au=/^[A-Za-z0-9_-]{1,128}$/,Nh="corrupt",Uh="expired",iu=10080*60*1e3;function $h(){return(0,Ie.join)(se(),"state","hook-spool")}function oo(r){if(r===null||typeof r!="object")return JSON.stringify(r)??"null";if(Array.isArray(r))return`[${r.map(oo).join(",")}]`;let e=r;return`{${Object.keys(e).filter(n=>e[n]!==void 0).sort().map(n=>`${JSON.stringify(n)}:${oo(e[n])}`).join(",")}}`}function Bh(r,e){let t=e.toolUseId;return typeof t=="string"&&au.test(t)?`${(0,io.createHash)("sha256").update(e.contentSessionId).update("\0").update(Z(e.platformSource)).digest("hex")}-${t}`:(0,io.createHash)("sha256").update(r).update("\0").update(e.contentSessionId).update("\0").update(oo(e)).digest("hex")}function ou(r){return typeof r=="string"&&r.length>0}function no(r){let e;try{e=JSON.parse(r)}catch(i){return{corruptReason:`invalid JSON: ${i instanceof Error?i.message:String(i)}`}}if(e===null||typeof e!="object")return{corruptReason:"not an object"};let t=e;if(!Lh.includes(t.kind))return{corruptReason:`unknown kind ${JSON.stringify(t.kind)}`};if(typeof t.enqueuedAtEpochMs!="number"||!Number.isFinite(t.enqueuedAtEpochMs))return{corruptReason:"missing enqueuedAtEpochMs"};let n=t.payload;if(n===null||typeof n!="object"||!ou(n.contentSessionId))return{corruptReason:"payload missing contentSessionId"};let s=t.kind;return(s==="observation"||s==="file_edit")&&!ou(n.toolName)?{corruptReason:"observation payload missing toolName"}:s==="summarize"&&typeof n.lastAssistantMessage!="string"?{corruptReason:"summarize payload missing lastAssistantMessage"}:s==="advisor_calls"&&(!Array.isArray(n.calls)||n.calls.length===0)?{corruptReason:"advisor_calls payload has no calls"}:{kind:s,payload:{...n,platformSource:Z(n.platformSource)},enqueuedAtEpochMs:t.enqueuedAtEpochMs}}var so=0;function Wh(){return so=Math.max(Date.now(),so+1),so}var Hn=class{constructor(e=$h()){this.directory=e}directory;get corruptDirectory(){return(0,Ie.join)(this.directory,Nh)}get expiredDirectory(){return(0,Ie.join)(this.directory,Uh)}enqueue(e,t,n){let s={...t,platformSource:Z(t.platformSource)},i=(0,Ie.join)(this.directory,`${e}-${Bh(e,s)}.json`),o=s.toolUseId;if(typeof o=="string"&&au.test(o)){let c=(0,Ie.join)(this.directory,`${e}-${o}.json`);try{let l=no((0,K.readFileSync)(c,"utf8"));!("corruptReason"in l)&&l.kind===e&&l.payload.contentSessionId===s.contentSessionId&&l.payload.platformSource===s.platformSource&&(i=c)}catch{}}let a=this.existingEnqueuedAt(i)??n??Wh();return H(i,{kind:e,payload:s,enqueuedAtEpochMs:a}),i}entries(){return this.readEntries().files.map(e=>e.entry)}async drain(e,t){let{files:n,quarantined:s}=this.readEntries(),i=0,o=0,a=0;t?.pruneConsumedBefore(Date.now()-iu);let c=new Set;for(let l of n){let u=l.filename.replace(/\.json$/,"");if(t?.isConsumed(u)){f.info("HOOK","Hook spool entry was already handed to ingest before a restart; removing it without ingesting again",{kind:l.entry.kind,contentSessionId:l.entry.payload.contentSessionId,file:l.filename}),this.unlinkEntry(l)?(t.clearConsumed(u),i++):o++;continue}let d=JSON.stringify([l.entry.payload.contentSessionId,l.entry.payload.platformSource]);if((l.entry.kind==="summarize"||l.entry.kind==="session_end")&&c.has(d)){o++;continue}let p=!1,g=()=>{if(!p){p=!0;try{t?.markConsumed(u,Date.now())}catch(h){f.error("HOOK","Could not record a hook spool hand-off marker; a crash before the file is removed would ingest it twice",{kind:l.entry.kind,contentSessionId:l.entry.payload.contentSessionId,file:l.filename},h instanceof Error?h:new Error(String(h)))}}},m;try{m=await e(l.entry,g)}catch(h){f.warn("HOOK",p?"Hook spool entry failed after ingest accepted it; removing it (a retry would send it twice)":"Hook spool entry failed to ingest; keeping it for the next drain",{kind:l.entry.kind,contentSessionId:l.entry.payload.contentSessionId,file:l.filename},h instanceof Error?h:new Error(String(h))),m=!1}if(p&&(m=!0),!m){this.expireIfPastRetryWindow(l)?a++:((l.entry.kind==="observation"||l.entry.kind==="file_edit")&&c.add(d),o++);continue}this.unlinkEntry(l)?(t?.clearConsumed(u),i++):o++}return{drained:i,retained:o,quarantined:s,expired:a}}unlinkEntry(e){try{return(0,K.unlinkSync)(e.path),!0}catch(t){return t.code==="ENOENT"?!0:(f.warn("HOOK","Hook spool entry was ingested but could not be removed",{kind:e.entry.kind,file:e.filename},t instanceof Error?t:new Error(String(t))),!1)}}expireIfPastRetryWindow(e){let t=Date.now()-e.entry.enqueuedAtEpochMs;if(t<=iu)return!1;let n={kind:e.entry.kind,contentSessionId:e.entry.payload.contentSessionId,ageHours:Math.round(t/36e5),file:e.filename,expiredDirectory:this.expiredDirectory};try{(0,K.mkdirSync)(this.expiredDirectory,{recursive:!0}),(0,K.renameSync)(e.path,(0,Ie.join)(this.expiredDirectory,e.filename))}catch(s){return f.error("HOOK","Hook spool entry is past its retry window but could not be moved to expired/; keeping it",n,s instanceof Error?s:new Error(String(s))),!1}return f.error("HOOK","Hook spool entry was never accepted within its retry window; moved to expired/",n),!0}existingEnqueuedAt(e){if(!(0,K.existsSync)(e))return null;try{let t=no((0,K.readFileSync)(e,"utf-8"));return"corruptReason"in t?null:t.enqueuedAtEpochMs}catch(t){return f.debug("HOOK","Could not read existing hook spool entry; writing a fresh one",{entryPath:e},t instanceof Error?t:new Error(String(t))),null}}quarantine(e,t){let n=(0,Ie.join)(this.directory,e);try{return(0,K.mkdirSync)(this.corruptDirectory,{recursive:!0}),(0,K.renameSync)(n,(0,Ie.join)(this.corruptDirectory,e)),f.error("HOOK","Quarantined corrupt hook spool entry",{file:e,reason:t,corruptDirectory:this.corruptDirectory}),!0}catch(s){return f.error("HOOK","Corrupt hook spool entry could not be quarantined; leaving it in place",{file:e,reason:t},s instanceof Error?s:new Error(String(s))),!1}}readEntries(){if(!(0,K.existsSync)(this.directory))return{files:[],quarantined:0};let e;try{e=(0,K.readdirSync)(this.directory).filter(s=>Fh.test(s))}catch(s){return f.warn("HOOK","Could not list hook spool entries",{directory:this.directory},s instanceof Error?s:new Error(String(s))),{files:[],quarantined:0}}let t=[],n=0;for(let s of e){let i=(0,Ie.join)(this.directory,s),o;try{o=(0,K.readFileSync)(i,"utf-8")}catch(c){c.code!=="ENOENT"&&f.warn("HOOK","Could not read hook spool entry; will retry",{file:s},c instanceof Error?c:new Error(String(c)));continue}let a=no(o);if("corruptReason"in a){this.quarantine(s,a.corruptReason)&&n++;continue}t.push({entry:a,path:i,filename:s})}return t.sort((s,i)=>s.entry.enqueuedAtEpochMs-i.entry.enqueuedAtEpochMs||s.filename.localeCompare(i.filename)),{files:t,quarantined:n}}};C();var jh=250,cu=new Set,ir=null;function Hh(){if(ir)return ir;let r=(async()=>{try{await(await Ce("/api/spool/nudge",{method:"POST",timeoutMs:jh})).body?.cancel()}catch(e){f.debug("HOOK","Hook spool nudge not delivered (worker will pick the entry up on its own)",{error:e instanceof Error?e.message:String(e)})}})();return ir=r,cu.add(r),r.finally(()=>{cu.delete(r),ir===r&&(ir=null)}),r}function or(r,e){let t=new Hn().enqueue(r,e);return f.debug("HOOK","Hook event spooled for the worker",{kind:r,entryPath:t}),Hh(),t}C();var lu={async execute(r){let{sessionId:e,cwd:t,filePath:n,edits:s}=r,i=Z(r.platform);if(!n)throw new Error("fileEditHandler requires filePath");if(f.dataIn("HOOK",`FileEdit: ${n}`,{editCount:s?.length??0}),!t)throw new Error(`Missing cwd in FileEdit hook input for session ${e}, file ${n}`);return Un(t)?(or("file_edit",{contentSessionId:e,platformSource:i,toolName:"write_file",toolInput:{filePath:n,edits:s},toolResponse:{success:!0},cwd:t}),f.debug("HOOK","File edit observation spooled",{filePath:n}),{continue:!0,suppressOutput:!0}):(f.debug("HOOK","Project excluded from tracking, skipping file edit observation",{cwd:t,filePath:n}),{continue:!0,suppressOutput:!0,exitCode:He.SUCCESS})}};U();C();var we=require("fs"),Gn=require("path");C();C();U();var ar="<claude-mem-context>",Kn="</claude-mem-context>";function uu(r){let e=r.indexOf(ar);if(e===-1)return null;let t=r.indexOf(Kn,e+ar.length);return t===-1?null:{start:r.lastIndexOf(ar,t),end:t+Kn.length}}var zv=$.settings();function du(r,e){let t=`${ar}