claude-mem 15.8.0 → 15.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,7 +9,7 @@
9
9
  "plugins": [
10
10
  {
11
11
  "name": "claude-mem",
12
- "version": "15.8.0",
12
+ "version": "15.8.1",
13
13
  "source": "./plugin",
14
14
  "description": "Persistent memory system for Claude Code - context compression across sessions"
15
15
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "15.8.0",
3
+ "version": "15.8.1",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "author": {
6
6
  "name": "Alex Newman"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "15.8.0",
3
+ "version": "15.8.1",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "author": {
6
6
  "name": "Alex Newman",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "15.8.0",
3
+ "version": "15.8.1",
4
4
  "description": "Persistent memory and context compression for Qoder sessions.",
5
5
  "author": {
6
6
  "name": "Alex Newman",
package/README.md CHANGED
@@ -59,7 +59,7 @@
59
59
  <img src="https://img.shields.io/badge/License-Apache%202.0-blue.svg" alt="License">
60
60
  </a>
61
61
  <a href="package.json">
62
- <img src="https://img.shields.io/badge/version-15.8.0-green.svg" alt="Version">
62
+ <img src="https://img.shields.io/badge/version-15.8.1-green.svg" alt="Version">
63
63
  </a>
64
64
  <a href="package.json">
65
65
  <img src="https://img.shields.io/badge/node-%3E%3D20.0.0-brightgreen.svg" alt="Node">
@@ -440,7 +440,6 @@ See the [LICENSE](LICENSE) file for full details. See [docs/license.md](docs/lic
440
440
  and [docs/ip-boundary.md](docs/ip-boundary.md) for licensing scope and the
441
441
  open/commercial boundary.
442
442
 
443
- **Note on Ragtime**: The `ragtime/` directory is licensed under the **Apache License 2.0**. See [ragtime/LICENSE](ragtime/LICENSE) for details.
444
443
 
445
444
  ---
446
445
 
@@ -13,7 +13,7 @@ ${m.stack??""}
13
13
  `)}debug(e,r,i,n){this.log(0,e,r,i,n)}info(e,r,i,n){this.log(1,e,r,i,n)}warn(e,r,i,n){this.log(2,e,r,i,n)}setErrorSink(e){bk=e}error(e,r,i,n){this.log(3,e,r,i,n),this.routeErrorToSink(r,i,n)}routeErrorToSink(e,r,i){try{if(!bk||!(i instanceof Error))return;bk(i)}catch{}}dataIn(e,r,i,n){this.info(e,`\u2192 ${r}`,i,n)}dataOut(e,r,i,n){this.info(e,`\u2190 ${r}`,i,n)}success(e,r,i,n){this.info(e,`\u2713 ${r}`,i,n)}failure(e,r,i,n){this.error(e,`\u2717 ${r}`,i,n)}},b=new Ek});function GK(t=process.env){let e=Number.parseInt(t.CLAUDE_MEM_WEDGED_WORKER_UPTIME_S??"",10);return Number.isFinite(e)&&e>=WK.min&&e<=WK.max?e:nae}function VK(t=process.platform){return t==="win32"?8e3:5e3}function Sk(t=process.platform){return $t.SESSION_INIT_HOOK_CAP-VK(t)}function Ao(t){return process.platform==="win32"?Math.round(t*$t.WINDOWS_MULTIPLIER):t}var $t,nae,WK,Aa=v(()=>{"use strict";$t={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},nae=300,WK={min:60,max:86400}});var HK=v(()=>{"use strict"});function YK(t){try{return new URL(t).hostname.toLowerCase()==="openrouter.ai"}catch{return!1}}var ZK=v(()=>{"use strict";me()});import{readFileSync as r$,existsSync as wk,writeFileSync as iae}from"fs";import{basename as oae,dirname as n$,join as Vd}from"path";import{homedir as XK,hostname as sae}from"os";import{parseEnv as aae}from"util";function fae(t){return typeof t=="boolean"?String(t):t}function hae(t){let e=process.env.CLAUDE_MEM_ENV_FILE??Vd(n$(t),".env");try{return wk(e)?!!aae(Wi(r$(e,"utf-8"))).ANTHROPIC_BASE_URL:!1}catch{return!0}}function gae(t,e){let r=t.CLAUDE_MEM_MODEL;return typeof r!="string"||!mae.has(r.trim())?!1:(typeof t.CLAUDE_MEM_CLAUDE_AUTH_METHOD=="string"?t.CLAUDE_MEM_CLAUDE_AUTH_METHOD.trim():"")!=="gateway"&&!hae(e)}function yae(t){let e=t.CLAUDE_MEM_OPENROUTER_MODEL;if(typeof e!="string"||!pae.has(e.trim()))return!1;let r=typeof t.CLAUDE_MEM_OPENROUTER_BASE_URL=="string"?t.CLAUDE_MEM_OPENROUTER_BASE_URL.trim():"";return r===""||YK(r)}function i$(t,e){return Vd(n$(t),`.${oae(t)}.${e.markerTag}`)}function _k(t,e){try{iae(i$(t,e),new Date().toISOString(),{encoding:"utf-8",mode:384})}catch{}}function bae(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===cae||r===uae)return dae}catch{return null}return null}var lae,cae,uae,dae,pae,mae,QK,e$,t$,he,Ut=v(()=>{"use strict";Aa();ct();ZK();qn();dc();lae="security_alert",cae="sync-hub.black-pond-afbb.workers.dev",uae="ziczmqtpmaxbornfghye.supabase.co",dae="https://sync.cmem.ai",pae=new Set(["xiaomi/mimo-v2-flash:free"]);mae=new Set(["claude-haiku-4-5-20251001","claude-haiku-4-5"]);QK=18e4,e$=[{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"}];t$=new Set;he=class{static DEFAULTS={CLAUDE_MEM_MEMORY_SEARCH_HOOK_ENABLED:"true",CLAUDE_MEM_MEMORY_INSTRUCTIONS_ENABLED:"true",CLAUDE_MEM_MEMORY_WATCH_ROOTS:"",CLAUDE_MEM_MODEL:"haiku",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_SESSION_START_INCLUDE_ALL_SOURCES:"false",CLAUDE_MEM_CONTEXT_PROJECTS:"current",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_WORKER_INGEST_TOKEN:"",CLAUDE_MEM_WORKER_INGEST_MAX_BYTES:"5242880",CLAUDE_MEM_HOOK_SPOOL_TRANSPORT:"auto",CLAUDE_MEM_ALLOWED_ORIGINS:"",CLAUDE_MEM_PUBLIC_URL:"",CLAUDE_MEM_API_TIMEOUT_MS:String(Ao($t.API_REQUEST)),CLAUDE_MEM_SESSION_INIT_TIMEOUT_MS:String(Sk()),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_DELIVERABLES_ENABLED:"true",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_MEDIA_CAPTURE_ENABLED:"false",CLAUDE_MEM_MEDIA_INFERENCE_ENABLED:"false",CLAUDE_MEM_CODEX_MODEL:"",CLAUDE_MEM_CODEX_PATH:"codex",CLAUDE_MEM_CODEX_REASONING_EFFORT:"low",CLAUDE_MEM_CODEX_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_CODEX_OBSERVATION_BATCH_SIZE:"8",CLAUDE_MEM_CODEX_OBSERVATION_BATCH_MAX_CHARS:"32000",CLAUDE_MEM_CLAUDE_OBSERVATION_BATCH_SIZE:"1",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_API_KEYS:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-flash-latest",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_API_KEYS:"",CLAUDE_MEM_OPENROUTER_MODEL:"cohere/north-mini-code:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_TEMPERATURE:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_EXTRA_BODY:"",CLAUDE_MEM_OPENROUTER_REASONING_EFFORT:"",CLAUDE_MEM_OPENAI_COMPAT_PRESET:"",CLAUDE_MEM_OPENAI_COMPAT_API_KEY:"",CLAUDE_MEM_OPENAI_COMPAT_API_KEYS:"",CLAUDE_MEM_OPENAI_COMPAT_BASE_URL:"",CLAUDE_MEM_OPENAI_COMPAT_MODEL:"",CLAUDE_MEM_OPENAI_COMPAT_REASONING:"",CLAUDE_MEM_OPENAI_COMPAT_OBSERVATION_BATCH_SIZE:"1",CLAUDE_MEM_QUOTA_FALLBACK_PROVIDER:"claude",CLAUDE_MEM_QUOTA_FALLBACK_MODEL:"",CLAUDE_MEM_QUOTA_FALLBACK_AUTH_METHOD:"",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:Vd(XK(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_CLAUDE_CONFIG_DIR:"",CLAUDE_MEM_OBSERVER_CLAUDE_CONFIG_DIR:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES:"",CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:"",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_MAIN_AGENT_ONLY:"true",CLAUDE_MEM_REINFORCE_ALPHA:"0",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_WORK_STATE_ENABLED:"true",CLAUDE_MEM_FILE_READ_GATE_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:Vd(XK(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_CODEX_SUBAGENT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_OBSERVER_MAX_CONVERSATION_CHARS:"400000",CLAUDE_MEM_OBSERVER_THINKING:"disabled",CLAUDE_MEM_OBSERVER_CONTEXT_WINDOW:"",CLAUDE_MEM_OBSERVER_MAX_OUTPUT_TOKENS:"4096",CLAUDE_MEM_OBSERVE_BARE_PROMPTS:"false",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_REDACT_ENABLED:"false",CLAUDE_MEM_REDACT_DISABLED_BUILTINS:"",CLAUDE_MEM_REDACT_CUSTOM_PATTERNS:"[]",CLAUDE_MEM_REDACT_LOG_MATCHES:"false",CLAUDE_MEM_REDACT_GENERIC_ENABLED:"false",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_PROJECT_ENVIRONMENTS:"[]",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_SEMANTIC_INJECT_FORMAT:"narrative",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_CHROMA_MUTATION_TIMEOUT_MS:"600000",CLAUDE_MEM_CHROMA_MAX_PENDING_MUTATIONS:"5000",CLAUDE_MEM_CHROMA_EMBEDDING_FUNCTION:"default",CLAUDE_MEM_SERVER_VECTOR_SEARCH:"auto",CLAUDE_MEM_EMBEDDING_BACKFILL_THREADS:"",CLAUDE_MEM_EMBEDDING_MODEL:"all-MiniLM-L6-v2",CLAUDE_MEM_CHROMA_UVX_PATH:"",CLAUDE_MEM_SEARCH_RECENCY_DAYS:"90",CLAUDE_MEM_CLOUD_SYNC_TOKEN:"",CLAUDE_MEM_CLOUD_SYNC_USER_ID:"",CLAUDE_MEM_CLOUD_SYNC_HUB_URL:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_ID:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_NAME:sae(),CLAUDE_MEM_CLOUD_SYNC_WS:"true",CLAUDE_MEM_CLOUD_SYNC_KEEP_PULLING:"false",CLAUDE_MEM_CLOUD_SYNC_CONTENT_BATCH_SIZE:"40",CLAUDE_MEM_CLOUD_SYNC_REQUEST_TIMEOUT_MS:"90000",CLAUDE_MEM_TEAMBRAIN_URL:"",CLAUDE_MEM_TEAMBRAIN_TEAM_ID:"",CLAUDE_MEM_LLM_TIMEOUT_MS:String(QK),CLAUDE_MEM_FIELD_OPTIMIZE_TIMEOUT_MS:String(QK),CLAUDE_MEM_LLM_STREAM_IDLE_TIMEOUT_MS:"90000",CLAUDE_MEM_WORKER_HEARTBEAT_STALE_MS:"120000",CLAUDE_MEM_TV_TOKEN:"",CLAUDE_MEM_PRO_TRIAL_EMAIL:"",CLAUDE_MEM_PRO_TRIAL_AT:"",CLAUDE_MEM_PRO_TRIAL_STATE:"",CLAUDE_MEM_PRO_TRIAL_ENDS_AT:"",CLAUDE_MEM_PRO_PLAN:"",CLAUDE_MEM_PRO_FALLBACK_AT:"",CLAUDE_MEM_PRO_FALLBACK_MESSAGE:"",CLAUDE_MEM_PRO_FALLBACK_ACTION:"",CLAUDE_MEM_PRO_FALLBACK_URL:"",CLAUDE_MEM_PRO_MEMORY_KEY:"",CLAUDE_MEM_PRO_MEMORY_BASE_URL:"",CLAUDE_MEM_PRO_MEMORY_MODEL:"",CLAUDE_MEM_WORK_VIEW_AUTO_REFRESH:"true",CLAUDE_MEM_WORK_VIEW_COPY_PROVIDER:"",CLAUDE_MEM_WORK_VIEW_COPY_MODEL:"",CLAUDE_MEM_BACKUP_ENABLED:"false",CLAUDE_MEM_BACKUP_INTERVAL_HOURS:"24",CLAUDE_MEM_BACKUP_RETAIN_COUNT:"7",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_NOTION_ENABLED:"false",CLAUDE_MEM_NOTION_TOKEN:"",CLAUDE_MEM_NOTION_DATABASE_ID:"",CLAUDE_MEM_NOTION_AUTO_CREATE_PROPERTIES:"true",CLAUDE_MEM_GROK_BOT_INJECT_ENABLED:"true",CLAUDE_MEM_GROK_BOT_INJECT_AGENT_IDS:"*",CLAUDE_MEM_GROK_BOT_INJECT_TIER:"episode",CLAUDE_MEM_GROK_BOT_INJECT_WINDOW:"80",CLAUDE_MEM_GROK_BOT_INJECT_FALLBACK:"house",CLAUDE_MEM_GROK_BOT_INJECT_PLATFORM_SOURCE:"",CLAUDE_MEM_GROK_BOT_INJECT_PROJECTS_BY_AGENT:"",CLAUDE_MEM_GROK_BOT_INJECT_MAX_LINE_CHARS:"160",CLAUDE_MEM_GROK_BOT_INJECT_DEBOUNCE_MS:"1500",CLAUDE_MEM_GROK_BOT_INJECT_STANDING_LINE:"",CLAUDE_MEM_CCS_ALIGN_ENABLED:"true",CLAUDE_MEM_CCS_ALIGN_VIEWER_IDS:"ccs-align",CLAUDE_MEM_CCS_ALIGN_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_CCS_ALIGN_PATCH_SHADOWS:"false",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:"",CLAUDE_MEM_DEDUP_ENABLED:"false",CLAUDE_MEM_DEDUP_COSINE_THRESHOLD:"0.80",CLAUDE_MEM_DEDUP_IDF_VETO_DF:"10",CLAUDE_MEM_DEDUP_MIN_SHARED_TOKENS:"2",CLAUDE_MEM_DEDUP_MIN_PROJECT_DOCS:"10",CLAUDE_MEM_DEDUP_MAX_SCAN:"2000",CLAUDE_MEM_DEDUP_MAX_BACKFILL_ROWS:"50000",CLAUDE_MEM_TOOL_USES_RETENTION_DAYS:"0",CLAUDE_MEM_LOG_RETENTION_DAYS:"30",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):e==="CLAUDE_MEM_DATA_DIR"?kr(r):r}static normalizeWorkerHost(e){return e==="localhost"?"127.0.0.1":e}static finalizeSettings(e,r){let i=r?this.applyEnvOverrides(e):e;i.CLAUDE_MEM_WORKER_HOST=this.normalizeWorkerHost(i.CLAUDE_MEM_WORKER_HOST);let n=i.CLAUDE_MEM_DATA_DIR?.trim();return n&&i.CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH===this.DEFAULTS.CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH&&(i.CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH=Vd(kr(n),"transcript-watch.json")),i}static getInt(e){let r=this.get(e);return parseInt(r,10)}static applyEnvOverrides(e){let r={...e};for(let i of Object.keys(this.DEFAULTS))process.env[i]!==void 0&&(r[i]=process.env[i]);return r}static loadFromFile(e,r=!0,i={}){try{if(!wk(e)){let p=this.getAllDefaults();if(!i.readOnly)try{Ke(e,p,{mode:384});for(let f of e$)_k(e,f);console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(f){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,f instanceof Error?f.message:String(f))}return this.finalizeSettings(p,r)}let n=r$(e,"utf-8"),o=wr(n),s=vn(o),a=s!==o,l=fk(o),c=a&&Object.keys(l).some(p=>p!=="env");if(a&&!c&&!i.readOnly)try{Ke(e,s,{mode:384}),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(p){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,p instanceof Error?p.message:String(p))}if(s.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES===lae&&(s={...s,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES},!i.readOnly))try{Ke(e,c?{...l,env:s}:s,{mode:384}),console.warn("[SETTINGS] Migrated Telegram trigger types off the legacy default:",e)}catch(p){console.warn("[SETTINGS] Failed to migrate Telegram trigger types:",e,p instanceof Error?p.message:String(p))}if(gae(s,e)){let p=String(s.CLAUDE_MEM_MODEL).trim();if(s={...s,CLAUDE_MEM_MODEL:this.DEFAULTS.CLAUDE_MEM_MODEL},!i.readOnly)try{Ke(e,c?{...l,env:s}:s,{mode:384}),console.warn(`[SETTINGS] Migrated Claude model off the pinned ${p} to ${this.DEFAULTS.CLAUDE_MEM_MODEL}:`,e)}catch(f){console.warn("[SETTINGS] Failed to migrate the pinned Claude model:",e,f instanceof Error?f.message:String(f))}}if(yae(s)){let p=String(s.CLAUDE_MEM_OPENROUTER_MODEL).trim();if(s={...s,CLAUDE_MEM_OPENROUTER_MODEL:this.DEFAULTS.CLAUDE_MEM_OPENROUTER_MODEL},!i.readOnly)try{Ke(e,c?{...l,env:s}:s,{mode:384}),console.warn(`[SETTINGS] Migrated OpenRouter model off the retired default ${p} to ${this.DEFAULTS.CLAUDE_MEM_OPENROUTER_MODEL}:`,e)}catch(f){console.warn("[SETTINGS] Failed to migrate the retired OpenRouter model:",e,f instanceof Error?f.message:String(f))}}let u=bae(s.CLAUDE_MEM_CLOUD_SYNC_HUB_URL);if(u!==null&&(s={...s,CLAUDE_MEM_CLOUD_SYNC_HUB_URL:u},!i.readOnly))try{Ke(e,c?{...l,env:s}:s,{mode:384}),console.warn("[SETTINGS] Migrated cloud sync hub URL to",u,"from a retired hub host:",e)}catch(p){console.warn("[SETTINGS] Failed to migrate cloud sync hub URL:",e,p instanceof Error?p.message:String(p))}for(let p of e$)if(!wk(i$(e,p))){if(s[p.key]!==p.legacy){i.readOnly||_k(e,p);continue}if(s={...s,[p.key]:this.DEFAULTS[p.key]},!i.readOnly)try{Ke(e,c?{...l,env:s}:s,{mode:384}),_k(e,p),console.warn(`[SETTINGS] Migrated ${p.key} off the old ${p.legacy}ms default to ${this.DEFAULTS[p.key]}ms:`,e)}catch(f){let m=`${p.key}\0${e}`;t$.has(m)||(t$.add(m),console.warn(`[SETTINGS] Failed to migrate ${p.key}; using the new default in memory (reported once per process):`,e,f instanceof Error?f.message:String(f)))}}let d={...this.DEFAULTS};for(let p of Object.keys(this.DEFAULTS))s[p]!==void 0&&(d[p]=fae(s[p]));return this.finalizeSettings(d,r)}catch(n){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,n instanceof Error?n.message:String(n));let o=this.getAllDefaults();return this.finalizeSettings(o,r)}}}});function kk(){return vh!==null||(vh=he.loadFromFile(fe)),vh}var vh,Ik=v(()=>{"use strict";Ut();we();vh=null});function fc(t){return(t.CLAUDE_MEM_WORKER_AUTOSTART??"true").trim().toLowerCase()==="false"}var Eh=v(()=>{"use strict"});var o$=v(()=>{"use strict"});function Wn(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}var xk=v(()=>{"use strict"});var Sh,s$=v(()=>{"use strict";Sh=class extends Error{timeoutMs;constructor(e){super(`Request timed out after ${e}ms`),this.name="WorkerRequestTimeoutError",this.timeoutMs=e}}});import{spawn as vae,spawnSync as l$}from"node:child_process";import{existsSync as Eae}from"node:fs";import{dirname as c$,extname as _h,join as u$,win32 as Sae}from"node:path";function vi(t,e,r){return vae(t,e??[],{...r,windowsHide:!0})}function wae(t){return`"${t.replace(/"/g,'""')}"`}function a$(t){return d$.has(_h(t).toLowerCase())}function kae(t=process.env){let e=t.SystemRoot||t.SYSTEMROOT||t.windir||t.WINDIR||"C:\\Windows";return u$(e,"System32","where.exe")}function Iae(t,e=process.cwd()){let i=/^[a-zA-Z]:[\\/]|\\\\/.test(t)?Sae.dirname(t):c$(t),n=o=>o.replace(/[\\/]+/g,"/").replace(/\/+$/,"").toLowerCase();return n(i)===n(e)}function cs(t,e=process.cwd()){if(process.platform!=="win32")return[];try{let r=l$(kae(),[t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0});return r.status!==0||!r.stdout.trim()?[]:r.stdout.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).filter(i=>!Iae(i,e)).filter(i=>Eae(i))}catch{return[]}}function Aae(t,e){let r=t.find(a$);if(r)return r;let i=t.find(n=>Tk.has(_h(n).toLowerCase()));if(i&&e){let n=e(i);if(n&&a$(n))return n}return i??t.find(n=>_ae.has(_h(n).toLowerCase()))??t[0]??null}function Cae(t,e,r=Tae){if(!/[\\/]volta[\\/]bin[\\/]/i.test(e))return null;try{let i=r(u$(c$(e),"volta.exe"),["which",t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:xae,windowsHide:!0});return i.status!==0||!i.stdout.trim()?null:i.stdout.split(/\r?\n/).map(n=>n.trim()).find(Boolean)??null}catch{return null}}function Gn(t){return Aae(cs(t),e=>Cae(t,e))}function Oae(t,e,r=process.platform){if(r==="win32"&&Tk.has(_h(t).toLowerCase())){let i=[t,...e].map(wae).join(" ");return{command:process.env.ComSpec??"cmd.exe",args:["/d","/s","/c",`"${i}"`],windowsVerbatimArguments:!0}}return{command:t,args:[...e],windowsVerbatimArguments:!1}}function Ir(t,e,r,i=process.platform){let n={...r,...i==="win32"?{windowsHide:!0}:{}},o=Oae(t,e,i);return{command:o.command,args:o.args,options:o.windowsVerbatimArguments?{...n,windowsVerbatimArguments:!0}:n}}var Tk,d$,_ae,xae,Tae,Jr=v(()=>{"use strict";Tk=new Set([".cmd",".bat"]),d$=new Set([".exe",".com"]),_ae=new Set([...d$,...Tk]);xae=5e3,Tae=(t,e,r)=>l$(t,e,r)});function ur(t=process.env){let e={};for(let[r,i]of Object.entries(t))if(i!==void 0){if(Dae.has(r)){e[r]=i;continue}Mae.has(r)||Rae.some(n=>r.startsWith(n))||(e[r]=i)}return e}var Rae,Mae,Pae,Dae,us=v(()=>{"use strict";Rae=["CLAUDECODE_","CLAUDE_CODE_"],Mae=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),Pae=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"]),Dae=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",...Pae])});import{spawnSync as f$}from"child_process";import{readFileSync as Nae}from"fs";function m$(t,e,r){if(r.status!==0)return null;if(typeof r.stdout!="string")return b.warn("SYSTEM","captureProcessStartToken: start-token probe returned no stdout",{pid:e,source:t,status:r.status}),null;let i=r.stdout.trim();return i.length>0?i:null}function jae(t){Ak+=1;let e=f$("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...ur(process.env),LC_ALL:"C",LANG:"C"}});return m$("powershell-cim",t,e)}function Kae(t,e=!1){if(!e){let i=p$.get(t);if(i&&(t===process.pid||Date.now()-i.capturedAtMs<Lae))return i.token}let r=null;try{r=jae(t)}catch(i){b.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:i instanceof Error?i.message:String(i)}),r=null}return(r!==null||t!==process.pid)&&p$.set(t,{token:r,capturedAtMs:Date.now()}),r}function h$(t,e){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux"){Ak+=1;try{let r=Nae(`/proc/${t}/stat`,"utf-8"),i=r.lastIndexOf(") ");if(i<0)return null;let o=r.slice(i+2).split(" ")[19];return o&&/^\d+$/.test(o)?o:null}catch(r){return b.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}if(process.platform==="win32")return Kae(t,e);Ak+=1;try{let r=f$("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...ur(process.env),LC_ALL:"C",LANG:"C"}});return m$("ps-lstart",t,r)}catch(r){return b.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}function Vi(t){return h$(t,!1)}function Ei(t,e){if(e===null)return!0;let r=h$(t,!0);return r===null?!0:r===e}var Lae,p$,Ak,wh=v(()=>{"use strict";me();us();Lae=5e3,p$=new Map,Ak=0});import{execFile as $ae}from"child_process";import{readdirSync as Uae,readFileSync as Fae}from"fs";import{promisify as Jae}from"util";async function Gae(t,e){let r=Date.now()+e,i=n=>{try{return process.kill(n,0),!0}catch(o){return o.code==="EPERM"}};for(;t.some(i);){let n=r-Date.now();if(n<=0)return;await new Promise(o=>setTimeout(o,Math.min(Wae,n)))}}async function Si(t,e={}){let r=e.signalMode==="immediate",i=e.expectedStartToken!==void 0?e.expectedStartToken:Vi(t),n=()=>Ei(t,i);if(!n()){b.warn("PROCESS","Skipping tree-kill: root PID was reused since it was captured",{pid:t});return}if(b.debug("PROCESS",`Killing process tree rooted at PID ${t}`,{immediate:r}),process.platform==="win32"){try{await Ck("taskkill",["/PID",String(t),"/T","/F"],{timeout:5e3,windowsHide:!0})}catch(o){let s=o.code,a=String(o.stderr??""),l=o instanceof Error?o.message:String(o);if(s===Bae||zae.test(`${a} ${l}`)){b.debug("PROCESS","taskkill reported the process was already gone",{pid:t});return}throw new kh(t,`taskkill failed for PID ${t} (exit ${String(s)}): ${a.trim()||l}`,{cause:o})}return}try{let o=r?"SIGKILL":"SIGTERM",s=await Ih(t);for(let c of s){if(!Ei(c.pid,c.startToken)){b.debug("PROCESS",`Skipping ${o}: descendant PID was reused since enumeration`,{pid:c.pid,rootPid:t});continue}try{process.kill(c.pid,o)}catch{}}if(n())try{process.kill(t,o)}catch(c){let u=c instanceof Error?c:new Error(String(c)),d=u.code;d!=="ESRCH"&&b.debug("PROCESS",`Failed to ${o} PID ${t}`,{code:d},u)}else b.warn("PROCESS","Skipping root signal: PID was reused during descendant enumeration",{pid:t,signal:o});r||await Gae([t,...s.map(c=>c.pid)],qae);let a=n()?await Ih(t):[],l=new Map;for(let c of s)l.set(c.pid,c.startToken);for(let c of a)l.set(c.pid,c.startToken);for(let[c,u]of l){if(!Ei(c,u)){b.debug("PROCESS","Skipping SIGKILL: descendant PID was reused since the scan",{pid:c,rootPid:t});continue}try{process.kill(c,"SIGKILL")}catch{}}if(!r&&n())try{process.kill(t,"SIGKILL")}catch{}}catch(o){throw new kh(t,`tree-kill failed for PID ${t}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}}async function Vae(){return process.platform==="win32"?Zae():process.platform==="linux"?Hae():Yae()}function Hae(){let t=[],e;try{e=Uae("/proc")}catch(r){return b.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 i;try{i=Fae(`/proc/${r}/stat`,"utf-8")}catch{continue}let n=i.lastIndexOf(") ");if(n<0)continue;let o=i.slice(n+2).split(" "),s=Number.parseInt(o[1]??"",10),a=o[19];Number.isFinite(s)&&t.push({pid:Number.parseInt(r,10),ppid:s,startToken:a&&/^\d+$/.test(a)?a:null})}return t}async function Yae(){let t;try{t=(await Ck("ps",["-eo","pid=,ppid=,lstart="],{timeout:1e4,maxBuffer:33554432,env:{...process.env,LC_ALL:"C",LANG:"C"}})).stdout}catch(r){return b.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(`
14
14
  `)){let i=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);if(!i)continue;let n=i[3].trim();e.push({pid:Number.parseInt(i[1],10),ppid:Number.parseInt(i[2],10),startToken:n.length>0?n:null})}return e}async function Zae(){let t;try{t=(await Ck("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 b.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 i=r.match(/^"(\d+)","(\d+)","(.*)"$/);if(!i)continue;let n=i[3].trim();e.push({pid:Number.parseInt(i[1],10),ppid:Number.parseInt(i[2],10),startToken:n.length>0?n:null})}return e}async function Ih(t){let e=await Vae(),r=new Map;for(let s of e){let a=r.get(s.ppid);a?a.push(s):r.set(s.ppid,[s])}let i=new Set([t]),n=[],o=s=>{for(let a of r.get(s)??[])i.has(a.pid)||(i.add(a.pid),o(a.pid),n.push({pid:a.pid,startToken:a.startToken}))};return o(t),n}var Ck,Bae,zae,qae,Wae,kh,mc=v(()=>{"use strict";me();wh();Ck=Jae($ae),Bae=128,zae=/not found|no running instance|no tasks/i,qae=500,Wae=10;kh=class extends Error{pid;constructor(e,r,i){super(r,i),this.name="ProcessTreeKillError",this.pid=e}}});import{existsSync as g$,readFileSync as Pk}from"fs";import Qae from"path";function xt(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:(b.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return b.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function xh(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(i=>!xt(i.pid)))return;await new Promise(i=>setTimeout(i,100))}}function y$(t){if(!t||!xt(t.pid))return!1;if(!t.startToken)return!0;let e=Vi(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||b.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}function hc(t,e=ile){if(!y$(t))return!1;if(t.startToken||e.platform!=="linux")return!0;let r;try{r=e.readCommandLine(t.pid)}catch(n){return b.debug("SYSTEM","Could not read the command line of a token-less worker PID; trusting the live PID",{pid:t.pid,error:n instanceof Error?n.message:String(n)}),!0}let i=r.split("\0").some(n=>Qae.basename(n)==="worker-service.cjs");return i||b.debug("SYSTEM","Token-less worker PID now belongs to another program (PID reused)",{pid:t.pid}),i}function Hi(t=Me.workerPid()){if(!g$(t))return null;let e;try{e=JSON.parse(Pk(t,"utf-8"))}catch{return null}return e!==null&&hc(e)?e:null}function Th(){return Ok||(Ok=new Mk),Ok}function Rk(){let t=ole.shift();t&&t.notify()}var ele,tle,rle,nle,ile,Mk,Ok,h2e,ole,En=v(()=>{"use strict";Jr();me();ct();us();we();wh();mc();ele=5e3,tle=1e3,rle=Me.supervisorRegistry(),nle=null;ile={platform:process.platform,readCommandLine:t=>Pk(`/proc/${t}/cmdline`,"utf-8")};Mk=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(e=rle){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,!g$(this.registryPath)){this.persist();return}try{let i=JSON.parse(Pk(this.registryPath,"utf-8")).processes??{};for(let[n,o]of Object.entries(i))this.entries.set(n,o)}catch(r){r instanceof Error?b.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):b.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&b.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}retainSupersededEntry(e,r){let i=this.entries.get(e);if(!i||i.pid===r||!xt(i.pid))return;let n=`${e}#superseded:${i.pid}`;this.entries.set(n,i);let o=this.runtimeProcesses.get(e);o&&(this.runtimeProcesses.set(n,o),this.runtimeProcesses.delete(e)),b.warn("SYSTEM","Registry id reused while the previous process was still alive; kept it for reaping",{id:e,supersededId:n,supersededPid:i.pid,incomingPid:r})}register(e,r,i){this.initialize(),this.retainSupersededEntry(e,r.pid),this.entries.set(e,r),i&&this.runtimeProcesses.set(e,i),this.persist()}unregister(e,r){this.initialize();let i=e,n=this.entries.get(i);r!==void 0&&n?.pid!==r&&(i=`${e}#superseded:${r}`,n=this.entries.get(i),n?.pid!==r)||n&&(this.entries.delete(i),this.runtimeProcesses.delete(i),this.persist(),n?.type==="sdk"&&Rk())}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 i=Date.parse(e.startedAt),n=Date.parse(r.startedAt);return(Number.isNaN(i)?0:i)-(Number.isNaN(n)?0:n)})}getBySession(e){let r=String(e);return this.getAll().filter(i=>i.sessionId!==void 0&&String(i.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[i,n]of this.entries)xt(n.pid)||(this.entries.delete(i),this.runtimeProcesses.delete(i),e+=1,n.type==="sdk"&&(r+=1));e>0&&this.persist();for(let i=0;i<r;i+=1)Rk();return e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let i=typeof e=="number"?e:Number(e)||void 0;b.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:i,pids:r.map(a=>a.pid)});let n=r.filter(a=>xt(a.pid)),o=new Map(n.map(a=>[a.pid,Vi(a.pid)]));for(let a of n)try{process.platform==="win32"?await Si(a.pid,{expectedStartToken:o.get(a.pid)??null}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(l){l instanceof Error?l.code!=="ESRCH"&&b.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},l):b.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(l)})}await xh(n,ele);let s=n.filter(a=>xt(a.pid));for(let a of s){b.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:i});let l=o.get(a.pid)??null;if(!Ei(a.pid,l)){b.warn("SYSTEM","Skipping SIGKILL: session process PID was reused during the grace window",{pid:a.pid,sessionId:i});continue}try{process.platform==="win32"?await Si(a.pid,{expectedStartToken:l}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(c){c instanceof Error?c.code!=="ESRCH"&&b.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):b.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}}if(s.length>0){let a=Date.now()+tle;for(;Date.now()<a&&s.filter(c=>xt(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,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"&&Rk();return b.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:i,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};try{Ke(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));b.warn("SYSTEM","Failed to persist supervisor registry; keeping it in memory",{path:this.registryPath},r);try{nle?.({errorCategory:r.code??"unknown"})}catch{}}},Ok=null;h2e=180*1e3,ole=[]});import{existsSync as sle,readFileSync as ale,rmSync as lle}from"fs";async function v$(t){let e=t.currentPid??process.pid,r=t.pidFilePath??cle,i=t.registry.getAll(),n=[...i].filter(l=>l.pid!==e).sort((l,c)=>Date.parse(c.startedAt)-Date.parse(l.startedAt)),o=new Map,s=new Map;for(let l of n){if(!xt(l.pid)){t.registry.unregister(l.id);continue}s.set(l.id,Vi(l.pid)),o.set(l.id,await Ih(l.pid));try{await b$(l,"SIGTERM")}catch(c){c instanceof Error?b.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:l.pid,pgid:l.pgid,type:l.type},c):b.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:l.pid,pgid:l.pgid,type:l.type,error:String(c)})}}await xh(n,5e3);let a=n.filter(l=>xt(l.pid)||(o.get(l.id)??[]).some(c=>xt(c.pid)));for(let l of a){let c=Ei(l.pid,s.get(l.id)??null);c||b.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:l.pid,type:l.type});try{c&&await b$(l,"SIGKILL")}catch(u){u instanceof Error?b.debug("SYSTEM","Failed to force kill child process",{pid:l.pid,pgid:l.pgid,type:l.type},u):b.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:l.pid,pgid:l.pgid,type:l.type,error:String(u)})}finally{ule(o.get(l.id)??[],l.pid)}}await xh(a,1e3);for(let l of n)t.registry.unregister(l.id);for(let l of i.filter(c=>c.pid===e))t.registry.unregister(l.id);Dk(r,e),t.registry.pruneDeadEntries()}function Dk(t,e,r=!1){if(!sle(t))return;let i=null;try{let s=JSON.parse(ale(t,"utf-8"));i=typeof s.pid=="number"?s.pid:null}catch(s){b.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:s instanceof Error?s.message:String(s)});return}let n=e!==null&&i===e,o=i===null||!xt(i);if(!n&&!(r&&o)){b.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:i,currentPid:e});return}try{lle(t,{force:!0})}catch(s){s instanceof Error?b.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},s):b.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(s)})}}function ule(t,e){for(let{pid:r,startToken:i}of t)if(!(r===e||!xt(r))){if(!Ei(r,i)){b.debug("SYSTEM","Skipping reap: PID was recycled during the grace window",{pid:r,rootPid:e});continue}try{process.kill(r,"SIGKILL"),b.debug("SYSTEM","Reaped orphaned descendant during shutdown cascade",{pid:r,rootPid:e})}catch(n){let o=n instanceof Error?n.code:void 0;o!=="ESRCH"&&b.warn("SYSTEM","Failed to reap orphaned descendant during shutdown cascade",{pid:r,rootPid:e,errno:o})}}}async function b$(t,e){let{pid:r,pgid:i}=t;if(process.platform!=="win32"){if(typeof i=="number")try{process.kill(-i,e);return}catch(n){if((n instanceof Error?n.code:void 0)!=="ESRCH")throw n}if(e==="SIGKILL"){await Si(r,{signalMode:"immediate"});return}try{process.kill(r,e)}catch(n){if((n instanceof Error?n.code:void 0)!=="ESRCH")throw n}return}await Si(r)}var cle,Nk=v(()=>{"use strict";me();En();we();mc();cle=Me.workerPid()});function dle(){let e=Th().pruneDeadEntries();e>0&&b.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function S$(){gc===null&&(gc=setInterval(dle,E$),gc.unref(),b.debug("SYSTEM","Health checker started",{intervalMs:E$}))}function _$(){gc!==null&&(clearInterval(gc),gc=null,b.debug("SYSTEM","Health checker stopped"))}var E$,gc,w$=v(()=>{"use strict";me();En();E$=3e4,gc=null});import{execFile as ple}from"child_process";import{promisify as fle}from"util";function gle(t){let e=[];for(let r of t.split(`
15
15
  `)){let i=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);i&&e.push({pid:Number.parseInt(i[1],10),ppid:Number.parseInt(i[2],10),command:i[3].trim()})}return e}async function Lk(){let t=await mle("ps",["-e","-o","pid=","-o","ppid=","-o","args="],{timeout:1e4,maxBuffer:33554432});return gle(t.stdout)}function jk(t,e){let r=t.filter(s=>hle.test(s.command)&&s.pid!==e.selfPid),i=new Set(r.map(s=>s.pid)),n=r.filter(s=>!i.has(s.ppid)),o=n.filter(s=>s.ppid===e.selfPid?!1:s.ppid===1?!0:!e.isAlive(s.ppid));return{matched:r,roots:n,orphans:o}}async function k$(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 i=t.readTable??Lk,n=t.isAlive??xt,o=t.killTree??(f=>Si(f,{signalMode:"graceful"})),s=t.selfPid??process.pid,a;try{a=await i()}catch(f){return b.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:l,roots:c,orphans:u}=jk(a,{isAlive:n,selfPid:s});if(r.matched=l.length,r.trees=c.length,r.orphans=u.length,u.length===0)return b.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:r.matched,trees:r.trees}),r;b.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(y=>o(y.pid)))).forEach((y,E)=>{let S=m[E];y.status==="fulfilled"?(r.killed+=1,d.add(S.pid)):(r.failed+=1,b.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:S.pid,ppid:S.ppid,error:y.reason instanceof Error?y.reason.message:String(y.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 b.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:r.orphans,killed:r.killed,failed:r.failed,unregistered:r.unregistered}),r}var mle,hle,Kk=v(()=>{"use strict";me();mc();En();mle=fle(ple),hle=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/});import{existsSync as yle,readFileSync as ble,rmSync as I$}from"fs";function Uk(){return Ele}function Fk(t={}){let e=t.pidFilePath??vle;if(!yle(e))return"missing";let r=null;try{r=JSON.parse(ble(e,"utf-8"))}catch(n){return n instanceof Error?b.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},n):b.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(n)}),I$(e,{force:!0}),"invalid"}return hc(r)&&r?((t.logAlive??!0)&&b.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(t.removeStale===!1||(b.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),I$(e,{force:!0})),"stale")}var vle,$k,Ele,Hd=v(()=>{"use strict";me();En();Nk();w$();Kk();we();En();vle=Me.workerPid(),$k=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(),Fk({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,k$({registry:this.registry}).catch(r=>{b.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),S$()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async i=>{if(this.shutdownInitiated){b.warn("SYSTEM",`Received ${i} but shutdown already in progress`);return}this.shutdownInitiated=!0,b.info("SYSTEM",`Received ${i}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(n){n instanceof Error?b.error("SYSTEM","Error during shutdown",{},n):b.error("SYSTEM","Error during shutdown (non-Error)",{error:String(n)});try{await this.stop()}catch(o){o instanceof Error?b.debug("SYSTEM","Supervisor shutdown fallback failed",{},o):b.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(o)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{b.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}_$(),this.stopPromise=v$({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,i){this.registry.register(e,r,i)}unregisterProcess(e,r){this.registry.unregister(e,r)}getRegistry(){return this.registry}},Ele=new $k(Th())});import{existsSync as Sle,readFileSync as _le}from"fs";function tr(t,e){if(!Sle(t))return e;try{return wr(_le(t,"utf-8"))}catch(r){throw new Error(`Corrupt JSON file, refusing to overwrite: ${t}: ${r instanceof Error?r.message:String(r)}`)}}var ds=v(()=>{"use strict";ct()});import{join as x$}from"path";import{mkdirSync as wle,writeFileSync as kle}from"fs";import{randomUUID as Ile}from"crypto";function xle(t){let e=t.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function Jk(t,e){if(xle(t))return{enabled:!1,source:"DO_NOT_TRACK"};let r=t.CLAUDE_MEM_TELEMETRY?.toLowerCase();return r==="0"||r==="false"||r==="off"?{enabled:!1,source:"env"}:r==="1"||r==="true"||r==="on"?{enabled:!0,source:"env"}:e?.enabled===!0?{enabled:!0,source:"config"}:e?.enabled===!1?{enabled:!1,source:"config"}:{enabled:!0,source:"default"}}function A$(t,e){return Jk(t,e).enabled}function Yd(){return x$(Qt(),T$)}function ps(){let t;try{t=tr(Yd(),null)}catch(e){let r=e instanceof Error?e:new Error(String(e));return b.warn("SYSTEM","Telemetry: corrupt telemetry.json; treating as no recorded consent",void 0,r),null}return!t||typeof t!="object"||typeof t.installId!="string"||t.enabled!==void 0&&typeof t.enabled!="boolean"?null:{enabled:t.enabled,installId:t.installId,decidedAt:typeof t.decidedAt=="string"?t.decidedAt:""}}function yc(t){let e=Qt();wle(e,{recursive:!0}),kle(x$(e,T$),JSON.stringify(t,null,2)+`
16
- `)}function Ah(){let t=ps();if(t?.installId)return t.installId;let e=Ile();return yc({installId:e,decidedAt:""}),e}var T$,Ch=v(()=>{"use strict";we();ds();me();T$="telemetry.json"});import Tle from"os";function Ale(t){try{if(typeof t!="string"){if(t==null)return"";try{t=String(t)}catch(r){let i=r instanceof Error?r:new Error(String(r));return b.warn("SYSTEM","error-scrub: String() coercion of non-string input failed",void 0,i),""}}let e=t;return e.length>C$?e.slice(0,C$):e}catch{return""}}function Cle(t){if(typeof t!="string"||t.length===0)return t??"";let e="";try{e=Tle.homedir()||""}catch(i){let n=i instanceof Error?i:new Error(String(i));b.warn("SYSTEM","error-scrub: os.homedir() failed; skipping home-dir redaction",void 0,n),e=""}if(!e)return t;let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");try{return t.replace(new RegExp(r,"g"),"~")}catch(i){let n=i instanceof Error?i:new Error(String(i));return b.warn("SYSTEM","error-scrub: home-dir RegExp replace failed; using split/join fallback",void 0,n),t.split(e).join("~")}}function Ole(t){return typeof t!="string"||t.length===0?t??"":t.replace(/(?<![~\w])\/(?:[^\s/:"'()]+\/)+([^\s/:"'()]+)/g,"$1").replace(/[A-Za-z]:\\(?:[^\s\\:"'()]+\\)*([^\s\\:"'()]+)/g,"$1").replace(/\\\\[^\s\\:"'()]+(?:\\[^\s\\:"'()]+)*\\([^\s\\:"'()]+)/g,"$1")}function Rle(t){return typeof t!="string"||t.length===0?t??"":t.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${Vn}`):e.replace(/[?#].*$/,"").replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/@\s]+@/,`$1${Vn}@`))}function Mle(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\?[^\s"'()]*/g,"")}function Ple(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\b(?:access[_-]?token|api[_-]?key|auth(?:orization)?|secret|password|passwd|jwt|session[_-]?id|token)=[^\s"'&]+/gi,e=>{let r=e.indexOf("=");return`${e.slice(0,r+1)}${Vn}`})}function Dle(t){if(typeof t!="string"||t.length===0)return t??"";let e=t;return e=e.replace(/[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}/g,Vn),e=e.replace(/\b[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\b/g,Vn),e=e.replace(/\b(?:sk|pk|rk|ak|phc|phx|ph|ghp|gho|ghs|xox[bpasr])[-_][A-Za-z0-9_-]{8,512}\b/gi,Vn),e=e.replace(/\bBearer\s+[A-Za-z0-9._-]{8,512}\b/gi,Vn),e=e.replace(/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g,Vn),e=e.replace(/\b[0-9a-fA-F]{24,4096}\b/g,Vn),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,Vn),e=e.replace(/\b(?=[A-Za-z0-9+/_-]{0,4096}\d)[A-Za-z0-9+/_-]{32,4096}={0,2}\b/g,Vn),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,Vn),e}function O$(t){let e=Ale(t);return e.length===0?"":(e=Cle(e),e=Rle(e),e=Ole(e),e=Mle(e),e=Ple(e),e=Dle(e),e)}var C$,Vn,R$=v(()=>{"use strict";me();C$=8192,Vn="[REDACTED]"});function Lle(t,e){if(!(!t||typeof t!="object"))for(let r of Object.keys(t)){if(!Nle.has(r))continue;let i=t[r];if(typeof i=="string"){let n=i.length>M$?i.slice(0,M$):i;e[r]=O$(n)}else(typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean")&&(e[r]=i)}}function P$(t){let e={};try{Lle(t,e)}catch{}return e}var Nle,M$,D$=v(()=>{"use strict";R$();Nle=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","pre_latch_state","limit_window","overage_status","is_using_overage","resets_in_minutes","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_aborted_deadline_exceeded","outcomes_invalid_output","top_model","top_abort_reason","observed_model","observed_billing","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","skill_id","skill_source","skill_trigger","observations_created","total_observations_injected","total_tokens_saved_vs_naive","platform","agent_role","instruction_state","instruction_returned_count","instruction_disabled_count","instruction_excluded_count","instruction_missing_count","instruction_unknown_count","captured_prompt_count","captured_session_count","captured_tool_count","unidentified_tool_event_count","native_todo_count",...["captured","mcp"].flatMap(t=>["read","write"].flatMap(e=>[`${t}_${e}_count`,...["ok","error","excluded","disabled","unknown"].map(r=>`${t}_${e}_${r}_count`)])),"view","previous_view"]),M$=200});import N$ from"os";function L$(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||Kle}function j$(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||$le}function K$(t){let e={};for(let r of Ule)t[r]!==void 0&&(e[r]=t[r]);return e}function Fle(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||N$.release().toLowerCase().includes("microsoft")}catch(t){let e=t instanceof Error?t:new Error(String(t));return b.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function $$(){return{version:jle,os:process.platform,os_version:N$.release(),is_wsl:Fle(),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 jle,Kle,$le,Ule,U$=v(()=>{"use strict";me();jle="15.8.0",Kle="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",$le="https://us.i.posthog.com";Ule=["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"]});async function xr(t,e,r){try{if(!A$(process.env,ps()))return;let i=P$({...$$(),...e??{}});if(r?.person?i.$set=K$(i):i.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:t,properties:i})+`
16
+ `)}function Ah(){let t=ps();if(t?.installId)return t.installId;let e=Ile();return yc({installId:e,decidedAt:""}),e}var T$,Ch=v(()=>{"use strict";we();ds();me();T$="telemetry.json"});import Tle from"os";function Ale(t){try{if(typeof t!="string"){if(t==null)return"";try{t=String(t)}catch(r){let i=r instanceof Error?r:new Error(String(r));return b.warn("SYSTEM","error-scrub: String() coercion of non-string input failed",void 0,i),""}}let e=t;return e.length>C$?e.slice(0,C$):e}catch{return""}}function Cle(t){if(typeof t!="string"||t.length===0)return t??"";let e="";try{e=Tle.homedir()||""}catch(i){let n=i instanceof Error?i:new Error(String(i));b.warn("SYSTEM","error-scrub: os.homedir() failed; skipping home-dir redaction",void 0,n),e=""}if(!e)return t;let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");try{return t.replace(new RegExp(r,"g"),"~")}catch(i){let n=i instanceof Error?i:new Error(String(i));return b.warn("SYSTEM","error-scrub: home-dir RegExp replace failed; using split/join fallback",void 0,n),t.split(e).join("~")}}function Ole(t){return typeof t!="string"||t.length===0?t??"":t.replace(/(?<![~\w])\/(?:[^\s/:"'()]+\/)+([^\s/:"'()]+)/g,"$1").replace(/[A-Za-z]:\\(?:[^\s\\:"'()]+\\)*([^\s\\:"'()]+)/g,"$1").replace(/\\\\[^\s\\:"'()]+(?:\\[^\s\\:"'()]+)*\\([^\s\\:"'()]+)/g,"$1")}function Rle(t){return typeof t!="string"||t.length===0?t??"":t.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${Vn}`):e.replace(/[?#].*$/,"").replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/@\s]+@/,`$1${Vn}@`))}function Mle(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\?[^\s"'()]*/g,"")}function Ple(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\b(?:access[_-]?token|api[_-]?key|auth(?:orization)?|secret|password|passwd|jwt|session[_-]?id|token)=[^\s"'&]+/gi,e=>{let r=e.indexOf("=");return`${e.slice(0,r+1)}${Vn}`})}function Dle(t){if(typeof t!="string"||t.length===0)return t??"";let e=t;return e=e.replace(/[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}/g,Vn),e=e.replace(/\b[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\b/g,Vn),e=e.replace(/\b(?:sk|pk|rk|ak|phc|phx|ph|ghp|gho|ghs|xox[bpasr])[-_][A-Za-z0-9_-]{8,512}\b/gi,Vn),e=e.replace(/\bBearer\s+[A-Za-z0-9._-]{8,512}\b/gi,Vn),e=e.replace(/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g,Vn),e=e.replace(/\b[0-9a-fA-F]{24,4096}\b/g,Vn),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,Vn),e=e.replace(/\b(?=[A-Za-z0-9+/_-]{0,4096}\d)[A-Za-z0-9+/_-]{32,4096}={0,2}\b/g,Vn),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,Vn),e}function O$(t){let e=Ale(t);return e.length===0?"":(e=Cle(e),e=Rle(e),e=Ole(e),e=Mle(e),e=Ple(e),e=Dle(e),e)}var C$,Vn,R$=v(()=>{"use strict";me();C$=8192,Vn="[REDACTED]"});function Lle(t,e){if(!(!t||typeof t!="object"))for(let r of Object.keys(t)){if(!Nle.has(r))continue;let i=t[r];if(typeof i=="string"){let n=i.length>M$?i.slice(0,M$):i;e[r]=O$(n)}else(typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean")&&(e[r]=i)}}function P$(t){let e={};try{Lle(t,e)}catch{}return e}var Nle,M$,D$=v(()=>{"use strict";R$();Nle=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","pre_latch_state","limit_window","overage_status","is_using_overage","resets_in_minutes","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_aborted_deadline_exceeded","outcomes_invalid_output","top_model","top_abort_reason","observed_model","observed_billing","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","skill_id","skill_source","skill_trigger","observations_created","total_observations_injected","total_tokens_saved_vs_naive","platform","agent_role","instruction_state","instruction_returned_count","instruction_disabled_count","instruction_excluded_count","instruction_missing_count","instruction_unknown_count","captured_prompt_count","captured_session_count","captured_tool_count","unidentified_tool_event_count","native_todo_count",...["captured","mcp"].flatMap(t=>["read","write"].flatMap(e=>[`${t}_${e}_count`,...["ok","error","excluded","disabled","unknown"].map(r=>`${t}_${e}_${r}_count`)])),"view","previous_view"]),M$=200});import N$ from"os";function L$(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||Kle}function j$(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||$le}function K$(t){let e={};for(let r of Ule)t[r]!==void 0&&(e[r]=t[r]);return e}function Fle(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||N$.release().toLowerCase().includes("microsoft")}catch(t){let e=t instanceof Error?t:new Error(String(t));return b.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function $$(){return{version:jle,os:process.platform,os_version:N$.release(),is_wsl:Fle(),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 jle,Kle,$le,Ule,U$=v(()=>{"use strict";me();jle="15.8.1",Kle="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",$le="https://us.i.posthog.com";Ule=["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"]});async function xr(t,e,r){try{if(!A$(process.env,ps()))return;let i=P$({...$$(),...e??{}});if(r?.person?i.$set=K$(i):i.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:t,properties:i})+`
17
17
  `);return}let n=L$(),o=new AbortController,s=setTimeout(()=>o.abort(),Jle);try{await Ble(n,t,i,o.signal)}finally{clearTimeout(s)}}catch{}}async function Ble(t,e,r,i){await fetch(`${j$()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:t,event:e,distinct_id:Ah(),properties:r}),signal:i})}var Jle,Zd=v(()=>{"use strict";Ch();D$();U$();Jle=2e3});var cBe,F$=v(()=>{"use strict";cBe=Object.freeze({maxImagesPerEvent:4,maxSourceBytes:3145728,maxCanonicalBytes:3145728,maxPixels:24e6,maxDimension:8192,conversionTimeoutSeconds:5,maxConcurrentConversions:1,maxDerivativeBytes:262144,maxDerivativeDimension:1536,maxInlineEncodedBytes:4194304,maxObservationRefs:32,maxLabelChars:64,maxManifestBytes:8192,maxProvenanceBytes:8192,maxSourceLocatorChars:4096,maxGatewayImageBytes:1048576,maxUploadBodyBytes:3211264,ownerQuotaBytes:268435456})});import{createHash as hBe,randomUUID as gBe}from"crypto";var J$=v(()=>{"use strict";me();F$()});import{randomUUID as kBe}from"crypto";var B$=v(()=>{"use strict";me();J$()});import{existsSync as zle,statSync as qle,readFileSync as Wle}from"fs";import Hn from"path";function z$(t){let e=Hn.join(t,".git"),r;try{r=qle(e)}catch(c){return c instanceof Error&&c.code!=="ENOENT"&&b.warn("GIT","Unexpected error checking .git",{error:c instanceof Error?c.message:String(c)}),Xd}if(!r.isFile())return Xd;let i;try{i=Wle(e,"utf-8").trim()}catch(c){return b.warn("GIT","Failed to read .git file",{error:c instanceof Error?c.message:String(c)}),Xd}let n=i.match(/^gitdir:\s*(.+)$/);if(!n)return Xd;let o=Hn.resolve(Hn.dirname(e),n[1]),s=o.match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(s){let c=s[1];return{isWorktree:!0,isSubmodule:!1,worktreeName:Hn.basename(t),parentRepoPath:c,parentProjectName:Hn.basename(c)}}let a=o.match(/^(.+)[/\\]\.git[/\\]modules[/\\](.+)$/);if(a){let c=a[1];return{isWorktree:!1,isSubmodule:!0,worktreeName:Hn.basename(t),parentRepoPath:c,parentProjectName:Hn.basename(c)}}let l=o.match(/^(.+)[/\\]worktrees[/\\]([^/\\]+)$/);if(l&&zle(Hn.join(o,"commondir"))){let c=l[1],u=Gle(c);if(u)return{isWorktree:!0,isSubmodule:!1,worktreeName:Hn.basename(t),parentRepoPath:c,parentProjectName:u}}return Xd}function Gle(t){let e=Hn.basename(t).replace(/\.git$/,"");return e&&!e.startsWith(".")?e:Hn.basename(Hn.dirname(t))||null}var Xd,q$=v(()=>{"use strict";me();Xd={isWorktree:!1,isSubmodule:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null}});import{basename as G$}from"path";function W$(t){let e=kr(t.replace(/\\/g,"/"));e=e.replace(/\\/g,"/");let r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return r=r.replace(/(^|\/)\*\*(?=\/)/g,"$1<<<GLOBSTAR_DIR>>>").replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*").replace(/<<<GLOBSTAR_DIR>>>\//g,"(?:.*/)?"),new RegExp(`^${r}$`)}function V$(t,e,r){let i=W$(t);return i.test(e)||i.test(r)?!0:t.replace(/\\/g,"/").endsWith("/**")?W$(t.slice(0,-3)).test(e.replace(/\/+$/,"")):!1}function H$(t,e){if(!e.length)return!1;let r=t.replace(/\\/g,"/"),i=G$(r);for(let n of e){let o=n.trim();if(o)try{if(V$(o,r,i))return!0}catch(s){b.warn("PROJECT_NAME","Invalid glob pattern",{pattern:o,error:s instanceof Error?s.message:String(s)});continue}}return!1}function Y$(t,e){if(!e||!e.trim())return!1;let r=t.replace(/\\/g,"/"),i=G$(r),n=e.split(",").map(o=>o.trim()).filter(Boolean);for(let o of n)try{if(V$(o,r,i))return!0}catch(s){b.warn("PROJECT_NAME","Invalid exclusion pattern",{pattern:o,error:s instanceof Error?s.message:String(s)});continue}return!1}var Bk=v(()=>{"use strict";dc();me()});import{realpathSync as Vle}from"fs";function Z$(t){let e=t;if(typeof e=="string"){if(!e.trim())return[];try{e=JSON.parse(e)}catch(i){return b.warn("PROJECT_NAME","CLAUDE_MEM_PROJECT_ENVIRONMENTS is not valid JSON; ignoring it",{error:i instanceof Error?i.message:String(i)}),[]}}if(!Array.isArray(e))return e!=null&&b.warn("PROJECT_NAME","CLAUDE_MEM_PROJECT_ENVIRONMENTS must be an array; ignoring it",{}),[];let r=[];for(let i of e){let n=typeof i?.name=="string"?i.name.trim():"",o=Array.isArray(i?.patterns)?i.patterns.filter(s=>typeof s=="string"&&s.trim()!==""):[];if(!n||o.length===0){b.warn("PROJECT_NAME","Ignoring a project environment without a name or patterns",{name:n});continue}if("inherit"in i){let s=i.inherit;if(!Array.isArray(s)||s.some(a=>typeof a!="string"||!a.trim()||a.includes(",")))throw new Error(`CLAUDE_MEM_PROJECT_ENVIRONMENTS: inherit for "${n}" must be an array of non-empty project names without commas`);r.push({name:n,patterns:o,inherit:[...new Set(s.map(a=>a.trim()))]})}else r.push({name:n,patterns:o})}return r}function Hle(t){try{return Vle(t)}catch{return t}}function zk(t,e){if(e.length===0)return null;let r=[...new Set([t,Hle(t)])].flatMap(i=>[i,`${i.replace(/[\\/]+$/,"")}/`]);for(let i of e)if(r.some(n=>H$(n,i.patterns)))return i;return null}var X$=v(()=>{"use strict";Bk();me()});import on from"path";import{existsSync as Yle,realpathSync as Zle,statSync as Xle}from"fs";import{homedir as Qle,tmpdir as ece}from"os";import{execFileSync as tU}from"child_process";function rU(t){try{return tU("git",["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim()||null}catch(e){let r=e instanceof Error?e:new Error(String(e));return b.debug("PROJECT_NAME","git rev-parse failed, falling back to non-git root",{dir:t},r),null}}function nU(t){try{return Zle(t)}catch{return t}}function nce(t,e){let r=on.relative(e,t);return r===""||!r.startsWith("..")&&!on.isAbsolute(r)}function ice(){return[Qle(),ece(),To].flatMap(t=>{let e=on.resolve(t);return[e,nU(e)]})}function iU(t){let e=ice(),r=on.resolve(t);if([on.resolve(To),nU(on.resolve(To))].some(n=>nce(r,n)))return null;for(let n=0;n<rce;n++){if(e.includes(r))return null;let o=on.dirname(r);if(o===r)return null;if(tce.some(s=>Yle(on.join(r,s))))return r;r=o}return null}function Wk(t,e){let r=on.basename(e);if(r===""){if(process.platform==="win32"){let n=t.match(/^([A-Z]):\\/i);if(n){let s=`drive-${n[1].toUpperCase()}`;return b.info("PROJECT_NAME","Drive root detected",{cwd:t,projectName:s}),s}}return b.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:t}),Gk}return r}function Q$(){try{return Xle(fe).mtimeMs}catch{return-1}}function oU(){let t=Q$();if(t===-1)return he.getAllDefaults();if(Oh&&Oh.mtimeMs===t)return Oh.settings;let e=he.loadFromFile(fe);return Oh={mtimeMs:Q$(),settings:e},e}function sce(){let t=process.env[oce]??oU().CLAUDE_MEM_PROJECT_NAME_SOURCE;return String(t??"path").trim().toLowerCase()==="git-remote"}function sU(){let t=process.env[ace]??oU().CLAUDE_MEM_PROJECT_ENVIRONMENTS;return(!Rh||Rh.raw!==t)&&(Rh={raw:t,environments:Z$(t)}),Rh.environments}function lce(t){let e=(t??"").trim();if(!e||/^file:/i.test(e)||e.startsWith("/")||e.startsWith(".")||e.startsWith("~")||e.startsWith("\\\\")||/^[a-z]:[\\/]/i.test(e))return null;let i=e.replace(/\/+$/,"").replace(/\.git$/i,""),n=i.match(/^[a-z][a-z0-9+.-]*:\/\/[^/]+\/(.+)$/i),o=n?null:i.match(/^(?:[^/@\s]+@)?[^:/\s]+:(?!\/\/)(.+)$/),s=n?.[1]??o?.[1];if(!s)return null;let a=s.split("/").filter(l=>l&&l!=="_git");return a.length>=2?a.slice(-2).join("/"):a.length===1?a[0]:null}function cce(t){try{let e=tU("git",["remote","get-url","origin"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim();return lce(e)}catch(e){let r=e instanceof Error?e:new Error(String(e));return b.debug("PROJECT_NAME","No usable origin remote, keeping the path-based name",{repoRoot:t},r),null}}function aU(t){return sce()?(qk.has(t)||qk.set(t,cce(t)),qk.get(t)??null):null}function uce(t,e=process.platform){if(!t||t.trim()==="")return b.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),Gk;let r=kr(t,e),i=zk(r,sU());if(i)return i.name;let n=rU(r),o=n?aU(n):null;if(o)return o;let s=n??iU(r)??r;return Wk(t,s)}function lU(t,e){return e===t?t:`${t}/${e}`}function dce(t,e){if(!t.isSubmodule||!t.parentRepoPath)return null;let r=on.relative(t.parentRepoPath,e);return!r||r.startsWith("..")||on.isAbsolute(r)?null:r.split(on.sep).join("/")}function Ca(t,e=process.platform){if(!t||t.trim()===""){let l=uce(t,e);return{primary:l,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[l],keySource:"path"}}let r=kr(t,e),i=rU(r),n=pce(t,r,i),o=i?aU(i):null,s=o?eU(n,o,"git-remote"):n,a=zk(r,sU());return a?eU(s,a.name,"environment",a.inherit):s}function eU(t,e,r,i=t.allProjects){return{primary:e,parent:null,isWorktree:t.isWorktree,isSubmodule:t.isSubmodule,allProjects:[...new Set(i.filter(n=>n!==e)),e],keySource:r}}function pce(t,e,r){let i=r?null:iU(e),n=Wk(t,r??i??e),o=r??e,s=z$(o);if((s.isWorktree||s.isSubmodule)&&s.parentProjectName){let a=s.parentProjectName,l,c;return s.isSubmodule?(l=`${a}/${dce(s,o)??n}`,c=n!==a?[n]:[]):(l=lU(a,n),c=l===a?[`${a}/${n}`]:[]),{primary:l,parent:a,isWorktree:s.isWorktree,isSubmodule:s.isSubmodule,allProjects:[...new Set([a,...c,l])].filter(u=>u!==l).concat(l),keySource:"path"}}if(i&&on.resolve(i)!==on.resolve(e)){let a=Wk(t,e);if(a!==n&&a!==Gk)return{primary:n,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[a,n],keySource:"path"}}return{primary:n,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[n],keySource:"path"}}var Gk,tce,rce,oce,Oh,ace,Rh,qk,Qd=v(()=>{"use strict";dc();we();Ut();me();q$();X$();Gk="unknown-project";tce=[".claude-mem-project",".claude-mem.json"],rce=64;oce="CLAUDE_MEM_PROJECT_NAME_SOURCE",Oh=null;ace="CLAUDE_MEM_PROJECT_ENVIRONMENTS",Rh=null;qk=new Map});import Sn from"path";import{homedir as fce,tmpdir as tze}from"os";import{existsSync as Mh,writeFileSync as nze,readFileSync as mce,unlinkSync as ize,mkdirSync as hce,statSync as oze,utimesSync as gce,copyFileSync as sze,realpathSync as yce}from"fs";import{execFileSync as bce,spawnSync as dU}from"child_process";function vce(t){return t===void 0?cU:Math.max(1,Math.min(cU,t))}function Ece(t){try{return yce(t)}catch{return null}}function Vk(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function Sce(t,e){let r=e==="win32"?"where.exe":"which",i=[t],n;try{n=bce(r,i,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(s){return s instanceof Error?b.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r,args:i},s):b.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r,args:i},new Error(String(s))),null}return n.split(/\r?\n/).map(s=>s.trim()).find(s=>s.length>0)||null}function Zk(t={}){let e=Object.keys(t).length===0;if(e&&Hk!==void 0)return Hk;let r=_ce(t);return e&&r!==null&&(Hk=r),r}function uU(t,e){let r=t?.trim();return r?e==="win32"?[Sn.join(r,"bin","bun.exe"),Sn.join(r,"bin","bun"),Sn.join(r,"bun.exe")]:[Sn.join(r,"bin","bun"),Sn.join(r,"bun")]:[]}function _ce(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(Vk(r))return r;let i=t.env??process.env,n=t.homeDirectory??fce(),o=t.pathExists??Mh,s=t.lookupInPath??Sce,a=t.realpath??Ece,l=e==="win32"?[i.BUN,i.BUN_PATH,...uU(i.BUN_INSTALL,e),Sn.join(n,".bun","bin","bun.exe"),Sn.join(n,".bun","bin","bun"),i.USERPROFILE?Sn.join(i.USERPROFILE,".bun","bin","bun.exe"):void 0,i.LOCALAPPDATA?Sn.join(i.LOCALAPPDATA,"bun","bun.exe"):void 0,i.LOCALAPPDATA?Sn.join(i.LOCALAPPDATA,"bun","bin","bun.exe"):void 0,i.npm_config_prefix?Sn.join(i.npm_config_prefix,"bun.exe"):void 0]:[i.BUN,i.BUN_PATH,...uU(i.BUN_INSTALL,e),Sn.join(n,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun",i.npm_config_prefix?Sn.join(i.npm_config_prefix,"bin","bun"):void 0];for(let d of l){let p=d?.trim();if(p&&(Vk(p)&&o(p)||p.toLowerCase()==="bun"))return p}let c=s("bun",e)?.trim();if(!c||!Vk(c))return null;let u=a(c)??c;return o(u)?u:null}function pU(){if(!Mh(Oa))return null;try{return JSON.parse(mce(Oa,"utf-8"))}catch(t){return t instanceof Error?b.warn("SYSTEM","Failed to parse PID file",{path:Oa},t):b.warn("SYSTEM","Failed to parse PID file",{path:Oa},new Error(String(t))),null}}function fU(t){Dk(Oa,t,!0)}function fs(t){return process.platform==="win32"?Math.round(t*2):t}function Xk(){let t=Me.dataDir();return hce(t,{recursive:!0}),t}function wce(t,e,r=Xk()){let i=n=>n.replace(/'/g,"''");return`Start-Process -FilePath '${i(t)}' -ArgumentList @('"${i(e)}"','--daemon') -WorkingDirectory '${i(r)}' -WindowStyle Hidden`}function xce(t,e,r){return t?.code!=="ETIMEDOUT"?!1:e<r/2}function mU(t,e=fs(kce)){let r=Zk();if(!r)return;let i=()=>{let a=Date.now();try{return{result:dU(r,[t,"status"],{encoding:"utf-8",timeout:e,windowsHide:!0,env:ur({...process.env})}),elapsedMs:Date.now()-a}}catch(l){let c=l instanceof Error?l:new Error(String(l));b.debug("SYSTEM","Worker boot probe could not be launched",{scriptPath:t},c);return}},n=i();if(n===void 0||xce(n.result.error,n.elapsedMs,e)&&(b.debug("SYSTEM","Worker boot probe timed out before it could run \u2014 retrying once",{scriptPath:t,elapsedMs:n.elapsedMs,timeoutMs:e}),n=i(),n===void 0))return;let{result:o}=n;if(o.error||o.status===0)return;let s=`${o.stdout??""}${o.stderr??""}`.trim();if(s)return s.split(/\r?\n/).slice(0,Ice).join(`
18
18
  `)}function Tce(t=process.env){let e=t.SystemRoot||t.SYSTEMROOT;return e?`${e}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`:"powershell.exe"}function Ace(t,e,r=Xk()){return["-NoProfile","-WindowStyle","Hidden","-EncodedCommand",Buffer.from(wce(t,e,r),"utf16le").toString("base64")]}function hU(){return ep}function gU(t,e,r,i=process.platform,n){if(ep=void 0,i==="win32"){let u=Tce(r),d=Ace(t,e),p=vce(n);try{let f=dU(u,d,{stdio:"ignore",windowsHide:!0,env:r,timeout:p,killSignal:"SIGTERM"});if(f.error)throw f.error;if(f.signal)throw new Error(`powershell Start-Process killed by signal=${f.signal} after ${p}ms`);if(f.status!==0)throw new Error(`powershell Start-Process exited ${f.status??"null"}`);return 0}catch(f){let m=f instanceof Error?f:new Error(String(f));ep=`${u} could not launch the worker: ${m.message}`,b.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:t,powershell:u},m);return}}let o="/usr/bin/setsid",s=Mh(o),a=s?o:t,c=vi(a,s?[t,e,"--daemon"]:[e,"--daemon"],{detached:!0,stdio:"ignore",cwd:Xk(),env:r});if(c.on("error",u=>{b.error("SYSTEM",Yk,{runtimePath:t,execPath:a},u)}),c.pid===void 0){ep=`could not launch ${a}`;return}return c.unref(),c.pid}function yU(t,e,r={}){Uk().assertCanSpawn("worker daemon");let i=ur({...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r}),n=Zk();if(!n){b.error("SYSTEM",Yk),ep=Yk;return}return gU(n,t,i)}function bU(){try{if(!Mh(Oa))return;let t=new Date;gce(Oa,t,t)}catch{}}function tp(t={}){return Fk({logAlive:!1,removeStale:t.removeStale})}var cU,bze,Oa,Yk,Hk,kce,Ice,ep,Ph=v(()=>{"use strict";Jr();me();us();Nk();Hd();B$();Qd();we();Aa();En();cU=Ao($t.POWERSHELL_COMMAND);bze=Me.dataDir(),Oa=Me.workerPid(),Yk="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.";kce=5e3,Ice=8});function Qk(t,e){if(!t||typeof t!="object"||e.has(t))return!1;if(e.add(t),t instanceof Error&&t.message.includes("ECONNREFUSED"))return!0;let r=t;return typeof r.code=="string"&&Cce.has(r.code)||Qk(r.cause,e)?!0:Array.isArray(r.errors)&&r.errors.some(i=>Qk(i,e))}function Co(t){return Qk(t,new Set)?!0:t instanceof Error&&t.message.includes("ECONNREFUSED")}function vU(t){let e=t?.code;return e==="EACCES"||e==="EADDRNOTAVAIL"}var Cce,Dh,Ra=v(()=>{"use strict";Cce=new Set(["ECONNREFUSED","ConnectionRefused"]);Dh="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"});import Oce from"net";function eI(){return he.loadFromFile(fe).CLAUDE_MEM_WORKER_HOST}function EU(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}async function Rce(t,e,r="GET",i=rp){let n=await fetch(`http://${EU(eI())}:${t}${e}`,{method:r,signal:AbortSignal.timeout(Math.max(1,i))}),o="";try{o=await n.text()}catch{}return{ok:n.ok,statusCode:n.status,body:o}}async function tI(t,e=rp){let r=Date.now()+e;if(process.platform==="win32")try{let n=await fetch(`http://${EU(eI())}:${t}/api/health`,{signal:AbortSignal.timeout(Math.max(1,r-Date.now()))});if(n.ok)return!0;b.debug("SYSTEM","Windows health check returned non-ok; falling through to socket probe",{port:t,status:n.status})}catch(n){n instanceof Error?b.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:t,message:n.message}):b.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:t,error:String(n)})}let i=await SU(t,Math.max(1,r-Date.now()));return i==="occupied"||i==="indeterminate"}async function SU(t,e=rp){return(await rI(t,e)).occupancy}function rI(t,e=rp){return e<=0?Promise.resolve({occupancy:"indeterminate"}):new Promise(r=>{let i=!1,n=!1,o=!1,s;try{s=Oce.createServer()}catch{r({occupancy:"indeterminate"});return}let a=u=>{if(o){u?.();return}o=!0;try{s.close(u)}catch(d){u?.(d instanceof Error?d:new Error(String(d)))}},l=setTimeout(()=>{if(n)a();else try{s.close()}catch{}c({occupancy:"indeterminate"})},e),c=u=>{i||(i=!0,clearTimeout(l),r(u))};s.once("error",u=>{if(n)a();else try{s.close()}catch{}u.code==="EADDRINUSE"?c({occupancy:"occupied"}):vU(u)?c({occupancy:"unbindable",bindErrorCode:u.code}):c({occupancy:"indeterminate"})}),s.once("listening",()=>{if(n=!0,i){a();return}try{a(u=>c({occupancy:u?"indeterminate":"free"}))}catch{c({occupancy:"indeterminate"})}});try{s.listen(t,eI())}catch{try{s.close()}catch{}c({occupancy:"indeterminate"})}})}async function _U(t,e,r,i){let n=Date.now()+r;for(;Date.now()<n;){try{let s=n-Date.now();if((await Rce(t,e,"GET",Math.min(rp,s))).ok)return!0}catch(s){s instanceof Error?b.debug("SYSTEM",i,{},s):b.debug("SYSTEM",i,{error:String(s)})}let o=Math.min(500,n-Date.now());o>0&&await new Promise(s=>setTimeout(s,o))}return!1}function ms(t,e=3e4){return _U(t,"/api/health",e,"Service not ready yet, will retry")}function bc(t,e=3e4){return _U(t,"/api/readiness",e,"Worker not ready yet, will retry")}var rp,np=v(()=>{"use strict";me();Ut();we();Ra();rp=5e3});var wU=v(()=>{"use strict";me();Hd()});var kU=v(()=>{"use strict";Ph();np();wU()});import{dirname as Mce,join as Pce}from"path";import{mkdirSync as Dce,readFileSync as Nh,statSync as IU,unlinkSync as xU,utimesSync as Nce,writeFileSync as Lce}from"fs";function iI(){return Pce(Qt(),"spawn.lock")}function nI(t){try{let e=JSON.parse(Nh(t,"utf-8"));return typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0?null:e.pid}catch{return null}}function $ce(t){if(t===null)return null;try{return process.kill(t,0),!0}catch(e){return e?.code==="EPERM"}}function jh(){let t=iI(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return Dce(Mce(t),{recursive:!0}),Lce(t,e,{flag:"wx"}),!0}catch(i){let n=i instanceof Error?i:new Error(String(i)),o=n.code;if(o!=="EEXIST")return b.warn("SYSTEM","Spawn lock write failed for a non-contention reason; failing open (spawning unlocked)",{lockPath:t,code:o},n),!0;if(r>0)return!1;let s;try{s=IU(t).mtimeMs}catch{continue}let a=nI(t),l=null;if(a===null)try{l=Nh(t,"utf-8")}catch{continue}if(Date.now()-s<=Lh&&$ce(a)!==!1)return!1;let u;try{u=IU(t).mtimeMs}catch{continue}if(u!==s)return!1;if(a!==null){if(nI(t)!==a)return!1}else try{if(Nh(t,"utf-8")!==l)return!1}catch{continue}try{xU(t)}catch{return!1}}return!1}function Kh(){let t=iI();try{if(JSON.parse(Nh(t,"utf-8")).pid!==process.pid)return;xU(t)}catch{}}async function oI(t,e=jce){let r=Date.now()+t;for(;!jh();){if(Date.now()>=r)return null;await new Promise(n=>setTimeout(n,Kce))}let i=setInterval(Uce,e);return i.unref(),()=>{clearInterval(i),Kh()}}function Uce(){let t=iI();try{if(nI(t)!==process.pid)return;let e=new Date;Nce(t,e,e)}catch{}}var Lh,jce,Kce,$h=v(()=>{"use strict";we();me();Lh=9e4,jce=Lh/3,Kce=250});import{execFile as Fce}from"node:child_process";import{readdirSync as TU,readFileSync as aI,readlinkSync as Jce,statSync as Jze,promises as Bze}from"node:fs";import{promisify as Bce}from"node:util";function AU(t){return zce.test(t.trim())}function qce(t,e){if(!t)return!1;let r=t.toLowerCase().replace(/\\/g,"/"),i=r.indexOf("--data-dir");if(i<0)return!1;let n=r.slice(i+10).trim();if(n.startsWith('"')){let s=n.indexOf('"',1);n=s<0?n.slice(1):n.slice(1,s)}let o=e.toLowerCase().replace(/\\/g,"/");return n===o||n.startsWith(o)&&n[o.length]==="/"}function Fh(t,e){return e===void 0?t:Math.max(1,Math.min(t,e))}async function Wce(t){try{let e=await Uh("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:Fh(3e4,t),windowsHide:!0,maxBuffer:33554432}),r=JSON.parse(e.stdout),i=Array.isArray(r)?r:r===null?[]:[r],n=[];for(let o of i){let s=typeof o.Name=="string"?o.Name.trim():"";if(!s)continue;let a=typeof o.ProcessId=="number"?o.ProcessId:Number.parseInt(String(o.ProcessId),10),l=typeof o.ParentProcessId=="number"?o.ParentProcessId:Number.parseInt(String(o.ParentProcessId),10);!Number.isInteger(a)||!Number.isInteger(l)||n.push({pid:a,ppid:l,name:s,cmdline:typeof o.CommandLine=="string"?o.CommandLine:null,startToken:typeof o.StartToken=="string"&&o.StartToken.length>0?o.StartToken:null})}return n}catch(e){return b.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 Gce(t,e){try{let r=await Uh("netstat",["-ano"],{timeout:Fh(15e3,e),windowsHide:!0,maxBuffer:16777216});return Qce(r.stdout,t)}catch(r){return b.warn("PROCESS","netstat failed \u2014 ghost-port reclaim disabled for this attempt",{port:t,error:r instanceof Error?r.message:String(r)}),null}}async function Vce(t,e){try{let r=await Uh("lsof",["-nP",`-iTCP:${t}`,"-sTCP:LISTEN","-t"],{timeout:Fh(1e4,e),maxBuffer:1048576});return Hce(r.stdout)}catch(r){let i=r;return i.code===1&&typeof i.stdout=="string"&&i.stdout.trim()===""?[]:(b.warn("PROCESS","lsof failed \u2014 cannot verify the worker port owner",{port:t,error:r instanceof Error?r.message:String(r)}),null)}}function Hce(t){let e=new Set;for(let r of t.split(/\r?\n/)){let i=Number.parseInt(r.trim(),10);Number.isInteger(i)&&i>0&&e.add(i)}return[...e]}function Yce(t){let e=new Set,r=!1;for(let n of["/proc/net/tcp","/proc/net/tcp6"]){let o;try{o=aI(n,"utf-8")}catch{continue}r=!0;for(let s of Zce(o,t))e.add(s)}if(!r)return b.warn("PROCESS","Cannot read /proc/net/tcp, so the worker port owner cannot be verified",{port:t}),null;if(e.size===0)return[];let i=new Set;for(let n of TU("/proc")){if(!/^\d+$/.test(n))continue;let o;try{o=TU(`/proc/${n}/fd`)}catch{continue}for(let s of o){let a;try{a=Jce(`/proc/${n}/fd/${s}`)}catch{continue}let l=/^socket:\[(\d+)\]$/.exec(a);if(l&&e.has(l[1])){i.add(Number.parseInt(n,10));break}}}return[...i]}function Zce(t,e){let r=e.toString(16).toUpperCase().padStart(4,"0"),i=[];for(let n of t.split(/\r?\n/).slice(1)){let o=n.trim().split(/\s+/);if(o.length<10)continue;o[1].split(":").pop()?.toUpperCase()===r&&o[3]==="0A"&&o[9]!=="0"&&i.push(o[9])}return i}async function Xce(t,e){if(process.platform==="linux")try{return aI(`/proc/${t}/cmdline`,"utf-8").split("\0").filter(Boolean).join(" ")||null}catch{return null}try{let i=(await Uh("ps",["-p",String(t),"-o","command="],{timeout:Fh(5e3,e)})).stdout.trim();return i.length>0?i:null}catch{return null}}function Qce(t,e){let r=new Set,i=`:${e}`;for(let n of t.split(/\r?\n/)){let o=n.trim();if(!/^TCP\b/i.test(o))continue;let s=o.split(/\s+/);if(!s[1]?.endsWith(i)||s[3]!=="LISTENING")continue;let l=Number.parseInt(s[4]??"",10);Number.isInteger(l)&&l>0&&r.add(l)}return[...r]}async function tue(t,e){let r=e.readOwnedWorker();if(r===null||r.port!==t)return null;let i=(u,d={})=>(b.info("PROCESS","Wedged-worker reclaim declined",{port:t,pid:r.pid,reason:u,...d}),{reclaimed:!1,reason:u,killedPids:[]}),n=(e.now()-Date.parse(r.startedAt))/1e3;if(!Number.isFinite(n)||n<e.minOwnerAgeSeconds)return i("owner-booting",{ageSeconds:n,minOwnerAgeSeconds:e.minOwnerAgeSeconds});for(let u=0;u<2;u++)if(u>0&&await e.sleep(MU),await e.probeHealth(t))return i("owner-responding");let o=await e.listOwners(t);if(o===null)return i("netstat-unreadable");if(!o.includes(r.pid))return b.info("PROCESS","Wedged-worker reclaim: our worker does not own the port \u2014 deferring to the ghost-listener check",{port:t,pid:r.pid,listeners:o}),null;let s=e.readHeartbeat();if(s!==null&&s.pid===r.pid){let u=e.now(),d=Math.max(0,u-s.beatAtMs),p=Math.max(0,u-s.lastResponseAtMs);if(d<e.heartbeatStaleMs){if(p<e.maxSilentProtectionMs)return i("owner-progressing",{heartbeatAgeMs:Math.round(d),sinceLastResponseMs:Math.round(p)});b.warn("PROCESS","Worker finished no response within the protection window despite a fresh liveness heartbeat",{port:t,pid:r.pid,sinceLastResponseMs:Math.round(p),maxSilentProtectionMs:e.maxSilentProtectionMs})}}let a=await e.readIdentity(r.pid),l=r.startToken!==void 0&&a.startToken!==null&&a.startToken!==r.startToken;if(l||a.cmdline===null||!eue.test(a.cmdline))return i("owner-identity-mismatch",{tokenMismatch:l,hasCmdline:a.cmdline!==null});if(!e.hasKillBudget())return i("out-of-budget");b.warn("PROCESS","Reclaiming wedged worker: past its boot grace, silent on two health probes, and still holding the port",{port:t,pid:r.pid,ageSeconds:Math.round(n)});try{await e.killTree(r.pid,{expectedStartToken:a.startToken??r.startToken??void 0,signalMode:"graceful"})}catch(u){return b.error("PROCESS","Wedged-worker reclaim tree-kill failed",{port:t,pid:r.pid},u instanceof Error?u:new Error(String(u))),{reclaimed:!1,reason:"kill-failed",killedPids:[]}}let c=await e.listOwners(t);return c!==null&&c.length===0?(b.info("PROCESS","Wedged worker reclaimed \u2014 port is free again",{port:t,killedPids:[r.pid]}),{reclaimed:!0,killedPids:[r.pid]}):(b.warn("PROCESS","Wedged-worker reclaim killed the worker but the port is still bound",{port:t,pid:r.pid,stillOwnedBy:c}),{reclaimed:!1,reason:"still-bound",killedPids:[r.pid]})}async function rue(t,e,r,i){let n=Vi(t),o=e?(await r(i))?.find(s=>s.pid===t)?.cmdline??null:await Xce(t,i);return Ei(t,n)?{startToken:n,cmdline:o}:{startToken:null,cmdline:null}}async function lI(t,e={}){let r=e.isWin32??(()=>process.platform==="win32"),i=e.now??Date.now,n=e.deadlineAt??null,o=U=>n!==null&&n-i()<U,s=()=>n===null?void 0:Math.max(1,n-i());if(o(CU))return b.info("PROCESS","Port reclaim skipped: not enough of the hook budget is left to finish one",{port:t,remainingMs:s(),neededMs:CU}),{reclaimed:!1,reason:"out-of-budget",killedPids:[]};let a=e.listOwners??((U,X)=>r()?Gce(U,X):process.platform==="linux"?Promise.resolve(Yce(U)):Vce(U,X)),l=U=>a(U,s()),c=e.readTable??Wce,u=()=>c(s()),d=e.killTree??((U,X)=>Si(U,X)),p=e.dataDir??(()=>Fe),f=e.readIdentity??((U,X)=>rue(U,r(),c,X)),m=await tue(t,{listOwners:l,killTree:d,readOwnedWorker:e.readOwnedWorker??Hi,probeHealth:e.probeHealth??(U=>ms(U,RU)),readIdentity:U=>f(U,s()),minOwnerAgeSeconds:e.minOwnerAgeSeconds??GK(),readHeartbeat:e.readHeartbeat??(()=>sue()),heartbeatStaleMs:e.heartbeatStaleMs??iue(),maxSilentProtectionMs:e.maxSilentProtectionMs??oue,now:i,sleep:e.sleep??(U=>new Promise(X=>setTimeout(X,U))),hasKillBudget:()=>!o(sI)});if(m!==null)return m;if(!r())return{reclaimed:!1,reason:"not-supported",killedPids:[]};let h=await l(t);if(h===null)return{reclaimed:!1,reason:"netstat-unreadable",killedPids:[]};if(h.length===0)return{reclaimed:!1,reason:"no-listener",killedPids:[]};let y=await u();if(y===null)return{reclaimed:!1,reason:"table-unreadable",killedPids:[]};if(h.filter(U=>xt(U)).length>0)return{reclaimed:!1,reason:"owner-alive",killedPids:[]};let S=new Map;for(let U of y){let X=S.get(U.ppid);X?X.push(U):S.set(U.ppid,[U])}let I=new Map,C=new Set,R=U=>{for(let X of S.get(U)??[])C.has(X.pid)||(C.add(X.pid),R(X.pid),AU(X.name)&&I.set(X.pid,X))};for(let U of h)R(U);let z=p();if(z)for(let U of y)I.has(U.pid)||AU(U.name)&&qce(U.cmdline,z)&&I.set(U.pid,U);if(I.size===0)return b.info("PROCESS","Ghost listener owner is dead but no chroma-sidecar descendants found",{port:t,deadOwners:h,processTableRows:y.length,dataDir:z??"(unresolved)"}),{reclaimed:!1,reason:"no-chroma-descendants",killedPids:[]};b.warn("PROCESS","Reclaiming ghost listener: killing dead worker's surviving chroma sidecar chain",{port:t,deadOwners:h,targets:[...I.values()].map(U=>({pid:U.pid,name:U.name}))});let Z=[];for(let U of I.values()){if(o(sI))return b.info("PROCESS","Ghost-listener reclaim stopped before a kill: the hook budget is spent",{port:t,killedPids:Z}),{reclaimed:!1,reason:"out-of-budget",killedPids:Z};try{await d(U.pid,{expectedStartToken:U.startToken,signalMode:"immediate"}),Z.push(U.pid)}catch(X){return b.error("PROCESS","Ghost-port reclaim tree-kill failed",{port:t,pid:U.pid},X instanceof Error?X:new Error(String(X))),{reclaimed:!1,reason:"kill-failed",killedPids:Z}}}let G=await l(t);return G!==null&&G.length===0?(b.info("PROCESS","Ghost listener reclaimed \u2014 port is free again",{port:t,killedPids:Z}),{reclaimed:!0,killedPids:Z}):(b.warn("PROCESS","Ghost-port reclaim killed the sidecar chain but the port is still bound",{port:t,killedPids:Z,stillOwnedBy:G}),{reclaimed:!1,reason:"still-bound",killedPids:Z})}function iue(t=process.env,e=fe){let r=t.CLAUDE_MEM_WORKER_HEARTBEAT_STALE_MS??he.loadFromFile(e,!1,{readOnly:!0}).CLAUDE_MEM_WORKER_HEARTBEAT_STALE_MS,i=Number(r);return Number.isSafeInteger(i)&&i>=OU.min&&i<=OU.max?i:nue}function sue(t=Me.workerHeartbeat()){try{let e=JSON.parse(aI(t,"utf8"));if(e&&Number.isSafeInteger(e.pid)&&Number.isFinite(e.beatAtMs)&&Number.isFinite(e.lastResponseAtMs))return{pid:e.pid,beatAtMs:e.beatAtMs,lastResponseAtMs:e.lastResponseAtMs}}catch{}return null}var Uh,zce,eue,RU,MU,sI,CU,nue,OU,oue,cI=v(()=>{"use strict";me();mc();En();Hd();np();wh();Aa();we();Ut();Uh=Bce(Fce),zce=/^(uv|uvx|python|chroma-mcp)(\.exe)?$/i;eue=/worker-service/i,RU=1500,MU=1e3,sI=5500,CU=2*RU+MU+sI;nue=12e4,OU={min:1e4,max:36e5};oue=6e5});import{existsSync as aue,readFileSync as lue,realpathSync as cue}from"fs";import{createRequire as uue}from"module";import Ma from"path";function PU(t){try{return cue(t)}catch{return t}}function pue(t,e){let r=Ma.relative(e,t);return r!==""&&!r.startsWith("..")&&!Ma.isAbsolute(r)}function uI(t){let e;try{let n=JSON.parse(lue(Ma.join(t,"package.json"),"utf-8"));e=Object.keys(n?.dependencies??{})}catch{return[]}if(e.length===0)return[];let r=Ma.join(t,"node_modules"),i=e.filter(n=>!aue(Ma.join(r,...n.split("/"),"package.json")));if(e.includes("zod")&&!i.includes("zod")){let n=uue(Ma.join(r,"noop.js")),o=PU(Ma.join(r,"zod"));for(let s of due)try{let a=n.resolve(s,{paths:[r]});pue(PU(a),o)||i.push(s)}catch{i.push(s)}}return i}var due,DU=v(()=>{"use strict";due=["zod/v3","zod/v4","zod/v4-mini"]});import yt from"path";import{randomUUID as dqe}from"crypto";import{fileURLToPath as fue}from"url";import{readFileSync as mue,existsSync as zh,writeFileSync as mqe,renameSync as hqe,mkdirSync as gqe,readdirSync as hue,realpathSync as NU,statSync as gue,unlinkSync as yqe}from"fs";function $U(t,e,r){let i=process.env[t];if(i){let n=parseInt(i,10);if(Number.isFinite(n)&&n>=r.min&&n<=r.max)return n;b.warn("SYSTEM",`Invalid ${t}, using default`,{value:i,min:r.min,max:r.max})}return e}function UU(t=process.env){let e=t.CLAUDE_MEM_FETCH_VERBOSE;if(e===void 0)return!1;let r=e.trim().toLowerCase();return r==="1"||r==="true"||r==="on"||r==="yes"}function bue(t){return UU()?{...t,verbose:!0}:t}function vue(t){let e={},r=t;for(let i=0;r&&i<4;i++){let n=i===0?"error":`cause${i}`;if(r instanceof Error){let o=r;e[n]={name:r.name,message:r.message,...o.code!==void 0?{code:o.code}:{}},r=r.cause;continue}e[n]=String(r);break}return e}function Eue(t,e,r){let i=typeof e.method=="string"?e.method:"GET",n=vue(r),o=JSON.stringify(n);b.warn("SYSTEM","Worker IPC fetch failed",{url:t,method:i},o),bi(`[claude-mem] fetch verbose: ${i} ${t} ${o}
19
19
  `)}async function fI(t,e={}){let r=bue(e);try{return await fetch(t,r)}catch(i){throw UU()&&Eue(t,e,i),i}}async function Sue(t,e={},r){try{return await fI(t,{...e,signal:AbortSignal.timeout(r)})}catch(i){throw i instanceof DOMException&&i.name==="TimeoutError"?new Sh(r):i}}function _ue(t,e){let r=new AbortController,i=null,n=null,o=null,s=!1,a=()=>{n!==null&&(clearTimeout(n),n=null)},l=()=>{s=!0,a(),o!==null&&(clearTimeout(o),o=null)},c=d=>{s||(i=d,l(),r.abort(d))},u=()=>{s||(a(),n=setTimeout(()=>c(new Error(`Request timed out after ${t.idleTimeoutMs}ms idle`)),t.idleTimeoutMs))};if(t.absoluteCapMs!==void 0&&t.absoluteCapMs>0){let d=t.absoluteCapMs;o=setTimeout(()=>c(new Error(`Request timed out after ${d}ms`)),d)}return u(),{signal:e?AbortSignal.any([e,r.signal]):r.signal,touch:u,pause:a,dispose:l,translate:d=>i??d}}async function wue(t,e,r){let i=_ue(r,e.signal),n;try{n=await fI(t,{...e,signal:i.signal})}catch(c){throw i.dispose(),i.translate(c)}i.touch();let o=n.body,s=o?o.getReader():null,a=!1;async function*l(){if(!s){a=!0,i.dispose();return}try{for(;;){i.touch();let c;try{c=await s.read()}catch(u){throw a=!0,i.translate(u)}if(c.done){a=!0;return}i.pause(),r.onChunk?.(c.value),yield c.value}}finally{i.dispose(),a||await s.cancel()}}return{status:n.status,statusText:n.statusText,ok:n.ok,headers:n.headers,chunks:l(),cancel:async()=>{i.dispose(),s&&!a&&(a=!0,await s.cancel())}}}async function kue(t,e,r){let i=await wue(t,e,r),n=new TextDecoder,o="";for await(let s of i.chunks)o+=n.decode(s,{stream:!0});return o+=n.decode(),{status:i.status,statusText:i.statusText,ok:i.ok,headers:i.headers,text:o}}function LU(){return yt.join(he.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function mI(t={}){return t.readOnly?he.loadFromFile(LU(),!0,t):(Jh!==null||(Jh=he.loadFromFile(LU())),Jh)}function jU(t,e){if(!t)return null;let r=parseInt(t,10);return Number.isFinite(r)&&r>=e.min&&r<=e.max?r:null}function Iue(t,e,r){let i=process.env[t];if(i!==void 0){let s=jU(i,r);return s!==null?s:(b.warn("SYSTEM",`Invalid ${t}, using default`,{value:i,min:r.min,max:r.max}),e)}let n=mI()[t],o=jU(n,r);return o!==null?o:(b.warn("SYSTEM",`Invalid ${t} in settings.json, using default`,{value:n,min:r.min,max:r.max}),e)}function _i(t={}){if(!t.readOnly&&dI!==null)return dI;let e=parseInt(mI(t).CLAUDE_MEM_WORKER_PORT,10);return t.readOnly||(dI=e),e}function Pa(t={}){if(!t.readOnly&&pI!==null)return pI;let e=mI(t).CLAUDE_MEM_WORKER_HOST;return t.readOnly||(pI=e),e}function xue(){return Bh!==null||(Bh=Iue("CLAUDE_MEM_API_TIMEOUT_MS",Ao($t.API_REQUEST),yue)),Bh}function hI(t){return`http://${Wn(Pa())}:${_i()}${t}`}function wi(t,e={}){let r=e.method??"GET",i=hI(t),n={method:r};if(e.headers&&(n.headers=e.headers),e.body&&(n.body=e.body),e.idleTimeoutMs!==void 0&&e.idleTimeoutMs>0)return kue(i,n,{idleTimeoutMs:e.idleTimeoutMs,absoluteCapMs:e.timeoutMs}).then(s=>new Response(s.text.length>0?s.text:null,{status:s.status,statusText:s.statusText,headers:s.headers}));let o=e.timeoutMs??xue();return o>0?Sue(i,n,o):fI(i,n)}function FU(t){let e=zh(yt.join(t,"plugin","scripts"))?yt.join(t,"plugin"):t;return yt.join(e,"scripts","worker-service.cjs")}function gI(t,e){let r=d=>{let p=d.split("-")[0].split(".");return[parseInt(p[0],10)||0,parseInt(p[1],10)||0,parseInt(p[2],10)||0]},[i,n,o]=r(t),[s,a,l]=r(e);if(s!==i)return s-i;if(a!==n)return a-n;if(l!==o)return l-o;let c=t.includes("-")?1:0,u=e.includes("-")?1:0;return c!==u?c-u:t<e?1:t>e?-1:0}function yI(t=yt.join(yt.dirname(yt.dirname(er)),"cache","thedotmack","claude-mem")){try{return hue(t).filter(e=>/^\d/.test(e)).map(e=>yt.join(t,e)).filter(e=>{try{if(!gue(e).isDirectory())return!1}catch{return!1}return!zh(yt.join(e,".orphaned_at"))}).map(e=>({scriptPath:FU(e),version:yt.basename(e)}))}catch{return[]}}function KU(t){try{let e=JSON.parse(mue(t,"utf-8"));return typeof e.version=="string"?e.version:null}catch(e){let r=e.code;return r!=="ENOENT"&&b.debug("SYSTEM","Could not read package version for worker resolution",{packageJsonPath:t,code:r}),null}}function JU(){return{cacheRoot:yt.join(yt.dirname(yt.dirname(er)),"cache","thedotmack","claude-mem"),marketplaceRoot:er,cwd:process.cwd()}}function Tue(){return typeof __filename<"u"?__filename:fue(import.meta.url)}function Cue(t,e=Tue()){let r,i;try{r=yt.dirname(NU(e)),i=NU(t)}catch(o){return b.debug("SYSTEM","Ignoring the cwd worker script: could not resolve the running module or cwd",{cwd:t,moduleFile:e,code:o.code}),!1}let n=Aue.some(o=>{let s=yt.relative(yt.join(i,o),r);return!s.startsWith("..")&&!yt.isAbsolute(s)});return n||b.debug("SYSTEM","Ignoring the cwd worker script: the running module is not this checkout's own code",{cwd:i,moduleDir:r}),n}function bI(t=JU()){let e=process.env.CLAUDE_MEM_WORKER_SCRIPT_PATH?.trim();if(e){if(zh(e))return{scriptPath:e,version:null};b.debug("SYSTEM","Ignoring missing CLAUDE_MEM_WORKER_SCRIPT_PATH override",{override:e})}let r=[...yI(t.cacheRoot),{scriptPath:FU(yt.join(t.marketplaceRoot,"plugin")),version:KU(yt.join(t.marketplaceRoot,"package.json"))},...Cue(t.cwd,t.runningModuleFile)?[{scriptPath:yt.join(t.cwd,"plugin","scripts","worker-service.cjs"),version:KU(yt.join(t.cwd,"package.json"))}]:[]];return vI(r)}function BU(t){return yt.dirname(yt.dirname(t))}function Oue(t){return uI(BU(t.scriptPath)).length===0}function vI(t,e=Oue){let r=t.filter(i=>zh(i.scriptPath));return r.length===0?null:(r.sort((i,n)=>i.version===null&&n.version===null?0:i.version===null?1:n.version===null?-1:gI(i.version,n.version)),r.find(e)??r[0])}function vc(t=JU()){let e=bI(t);if(!e)return null;let r=BU(e.scriptPath);return{root:r,version:e.version,missingDependencies:uI(r)}}var Fqe,Jqe,yue,Bqe,dI,pI,Jh,Bh,Aue,Rue,Mue,zqe,Yn=v(()=>{"use strict";me();Aa();HK();Ut();we();Ik();Eh();o$();xk();s$();Hd();Gd();Zd();kU();np();Ra();Ph();$h();cI();us();mc();ct();DU();xk();Fqe=$U("CLAUDE_MEM_HEALTH_TIMEOUT_MS",Ao($t.HEALTH_CHECK),{min:500,max:3e5}),Jqe=$U("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",Ao($t.HOOK_READINESS_WAIT),{min:0,max:3e5}),yue={min:500,max:3e5},Bqe={min:500,max:$t.SESSION_INIT_REQUEST_MAX};dI=null,pI=null,Jh=null,Bh=null;Aue=["plugin","src","dist"];Rue=1e3,Mue=5e3,zqe=Mue+Rue});import{existsSync as EI,readFileSync as zU}from"fs";import{homedir as Pue}from"os";import{dirname as Due,join as _n}from"path";import{fileURLToPath as Nue}from"url";function SI(){return process.env.CLAUDE_CONFIG_DIR||_n(Pue(),".claude")}function dr(){return _n(SI(),"plugins","marketplaces","thedotmack")}function hs(){return _n(SI(),"plugins")}function Ec(){return _n(hs(),"known_marketplaces.json")}function gs(){return _n(hs(),"installed_plugins.json")}function ys(){return _n(SI(),"settings.json")}function Sc(){return _n(hs(),"cache","thedotmack","claude-mem")}function Da(t){return _n(Sc(),t)}function Na(){let t=Nue(import.meta.url),e=_n(Due(t),"..","..");if(!EI(_n(e,"package.json")))throw new Error(`npmPackageRootDirectory: expected package.json at ${e}. Bundle structure may have changed \u2014 update the path walk.`);return e}function _I(){return _n(Na(),"plugin")}function bs(){let t=_n(_I(),".claude-plugin","plugin.json");if(EI(t))try{let r=JSON.parse(zU(t,"utf-8"));if(r.version)return r.version}catch{}let e=_n(Na(),"package.json");if(EI(e))try{let r=JSON.parse(zU(e,"utf-8"));if(r.version)return r.version}catch{}return"0.0.0"}function qU(){return vc()!==null}var wt,ki=v(()=>{"use strict";ct();Yn();ds();wt=process.platform==="win32"});var GU,VU,HU,YU=v(()=>{GU=(()=>{let t=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return e=>{let r=0;for(t.lastIndex=0;t.test(e);)r+=1;return e.length-r}})(),VU=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,HU=t=>t===8987||t===9001||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t>=131072&&t<=196605||t>=196608&&t<=262141});var Lue,jue,ZU,Kue,XU,$ue,Uue,Fue,QU,eF,tF=v(()=>{YU();Lue=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,jue=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,ZU=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,Kue=/\t{1,1000}/y,XU=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),$ue=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Uue=new RegExp("\\p{M}+","gu"),Fue={limit:1/0,ellipsis:""},QU=(t,e={},r={})=>{let i=e.limit??1/0,n=e.ellipsis??"",o=e?.ellipsisWidth??(n?QU(n,Fue,r).width:0),s=0,a=r.controlWidth??0,l=r.tabWidth??8,c=r.emojiWidth??2,u=2,d=r.regularWidth??1,p=r.wideWidth??u,f=[[$ue,d],[Lue,s],[jue,a],[Kue,l],[XU,c],[ZU,p]],m=0,h=0,y=t.length,E=0,S=!1,I=y,C=Math.max(0,i-o),R=0,z=0,Z=0,G=0;e:for(;;){if(z>R||h>=y&&h>m){let U=t.slice(R,z)||t.slice(m,h);E=0;for(let X of U.replaceAll(Uue,"")){let xe=X.codePointAt(0)||0;if(VU(xe)?G=u:HU(xe)?G=p:G=d,Z+G>C&&(I=Math.min(I,Math.max(R,m)+E)),Z+G>i){S=!0;break e}E+=X.length,Z+=G}R=z=0}if(h>=y)break e;for(let U=0,X=f.length;U<X;U++){let[xe,Ur]=f[U];if(xe.lastIndex=h,xe.test(t)){if(E=xe===ZU?GU(t.slice(h,xe.lastIndex)):xe===XU?1:xe.lastIndex-h,G=E*Ur,Z+G>C&&(I=Math.min(I,h+Math.floor((C-Z)/Ur))),Z+G>i){S=!0;break e}Z+=G,R=m,z=h,h=m=xe.lastIndex;continue e}}h+=1}return{width:S?C:Z,index:S?I:y,truncated:S,ellipsed:S&&i>=o}},eF=QU});var Jue,Bue,Br,wI=v(()=>{tF();Jue={limit:1/0,ellipsis:"",ellipsisWidth:0},Bue=(t,e={})=>eF(t,Jue,e).width,Br=Bue});function Yi(t,e,r){return String(t).normalize().split(Vue).map(i=>Gue(i,e,r)).join(`
@@ -871,7 +871,7 @@ CREATE INDEX IF NOT EXISTS idx_observation_embeddings_scope
871
871
  INNER JOIN team_members ON team_members.team_id = teams.id
872
872
  WHERE teams.id = $1 AND team_members.user_id = $2
873
873
  `,[e.id,e.userId]);return r?uV(r):null}}});var FA={};be(FA,{HOOK_API_KEY_SCOPES:()=>mV,bootstrapServerApiKey:()=>hV,createRawApiKey:()=>yV,hashApiKey:()=>bV,persistServerSettings:()=>h_e,readServerKeyRotationState:()=>g_e,revokeServerApiKey:()=>gV,rotateServerApiKey:()=>m_e});import{randomBytes as f_e}from"crypto";async function hV(t={}){let e=t.closePool??t.pool===void 0,r=t.pool??UA();try{await Xy(r);let i=await y_e(r),n=await b_e(r,i),o=yV(),s=bV(o),a=OT(o),l=new nl(r),c=await l.createApiKey({keyHash:s,keyPrefix:a,teamId:i,projectId:n,actorId:fV,scopes:[...mV]});return await l.createAuditLog({teamId:i,projectId:n,actorId:fV,apiKeyId:c.id,action:"api_key.create",resourceType:"api_key",resourceId:c.id,details:{source:"server-bootstrap"}}),{rawKey:o,apiKeyId:c.id,teamId:i,projectId:n}}finally{e&&await r.end().catch(()=>{})}}async function gV(t,e){let r=e===void 0,i=e??UA();try{await i.query("UPDATE api_keys SET revoked_at = now() WHERE id = $1 AND revoked_at IS NULL",[t])}finally{r&&await i.end().catch(()=>{})}}async function m_e(t={}){let e=t.pool===void 0,r=t.pool??UA();try{let i=await hV({pool:r,closePool:!1}),n=t.beforeRevoke===void 0;try{t.beforeRevoke&&(await t.beforeRevoke(i),n=!0),t.previousApiKeyId&&await r.query("UPDATE api_keys SET revoked_at = now() WHERE id = $1 AND revoked_at IS NULL",[t.previousApiKeyId])}catch(o){throw n||await gV(i.apiKeyId,r).catch(()=>{}),o}return i}finally{e&&await r.end().catch(()=>{})}}function h_e(t,e){let r={CLAUDE_MEM_SERVER_API_KEY:e.apiKey,CLAUDE_MEM_SERVER_PROJECT_ID:e.projectId};e.serverBaseUrl&&(r.CLAUDE_MEM_SERVER_URL=e.serverBaseUrl),e.previousApiKeyId&&(r.CLAUDE_MEM_SERVER_PREVIOUS_API_KEY_ID=e.previousApiKeyId);let i=Gi(t,r,{},n=>{e.previousApiKeyId||delete n.CLAUDE_MEM_SERVER_PREVIOUS_API_KEY_ID});return i.status==="refused"?(b.warn("HOOK","Could not persist server settings; leaving existing credentials unchanged.",{settingsPath:t},i.error instanceof Error?i.error:void 0),!1):!0}function g_e(t){let e=r=>typeof r=="string"&&r.length>0?r:null;return{pendingRevocationKeyId:e(t?.CLAUDE_MEM_SERVER_PREVIOUS_API_KEY_ID),currentApiKey:e(t?.CLAUDE_MEM_SERVER_API_KEY??t?.CLAUDE_MEM_SERVER_BETA_API_KEY),currentProjectId:e(t?.CLAUDE_MEM_SERVER_PROJECT_ID??t?.CLAUDE_MEM_SERVER_BETA_PROJECT_ID)}}function yV(){return`cmem_${f_e(32).toString("base64url")}`}function bV(t){return TT(t)}async function y_e(t){let e=await t.query("SELECT id FROM teams WHERE name = $1 LIMIT 1",[dV]);return e.rows[0]?e.rows[0].id:(await new ol(t).create({name:dV,metadata:{source:"local-hook-bootstrap"}})).id}async function b_e(t,e){let r=await t.query("SELECT id FROM projects WHERE team_id = $1 AND name = $2 LIMIT 1",[e,pV]);return r.rows[0]?r.rows[0].id:(await new il(t).create({teamId:e,name:pV,metadata:{source:"local-hook-bootstrap"}})).id}function UA(){let t=ou({requireDatabaseUrl:!0});if(!t)throw new Error("Cannot bootstrap server API key: CLAUDE_MEM_SERVER_DATABASE_URL is not set.");return sf(t)}var dV,pV,fV,mV,JA=v(()=>{"use strict";RT();me();qn();lu();of();Yy();lf();Qy();eb();dV="local-hook-team",pV="local-hook-project",fV="system:local-hook-bootstrap",mV=Object.freeze(["memories:read","memories:write"])});var cb={};be(cb,{activateBrowserEnrollment:()=>VV,buildInstallerOAuthStartBody:()=>BV,buildSyncConnectionSettings:()=>ob,buildTrialReadySettings:()=>ZA,claudeCodeInstallCommand:()=>OV,completeCmemTrialPairing:()=>XA,completeInstallerOAuthLogin:()=>WV,disableClaudeAutoMemory:()=>AV,joinFailedMessage:()=>qV,lastOAuthStartErrorMessage:()=>fu,lastOAuthStartFailure:()=>pu,log:()=>M,makeIDETask:()=>CV,mergeSettings:()=>zt,noteDeviceCode:()=>ab,offerDeferredLogin:()=>GV,openBrowser:()=>$s,overwriteWithWorkerStopped:()=>HV,parseInstallerOAuthStartBody:()=>UV,parseTrialReadyBody:()=>zV,promptProvider:()=>VA,providerNeedsAccount:()=>nb,requireWorkerStopped:()=>lb,runInstallCommand:()=>Y_e,runRepairCommand:()=>Q_e,setInstallerSignupContext:()=>JV,shouldSkipWorkerAutostart:()=>XV,startInstallerOAuthPairing:()=>mu,validateNonInteractiveProvider:()=>YV,waitForInstallerPairing:()=>uf,waitForReturnToOpenBrowser:()=>sb,workerShutdownFailure:()=>HA,writeTrimmedMarketplaceManifest:()=>PV,writeTrimmedMarketplacePackageJson:()=>DV});import{styleText as J}from"node:util";import{randomUUID as v_e}from"crypto";import{spawnSync as BA}from"child_process";import{cpSync as kV,existsSync as ni,readFileSync as ib,rmSync as IV,writeFileSync as xV}from"fs";import{homedir as E_e,hostname as YA}from"os";import{join as hr}from"path";function Pt(t){return he.loadFromFile(fe)[t]}function TV(){let e=(process.env.npm_config_user_agent??"").split("/")[0]?.trim().toLowerCase();return e==="npm"||e==="bun"||e==="pnpm"||e==="yarn"?e:process.versions.bun?"bun":"unknown"}async function du(t){if(Ae)await tg(t);else for(let e of t){let r=await e.task(i=>console.log(` ${i}`));console.log(` ${r}`)}}function tb(t,e){if(t(e),!Ae)return()=>{};let r=Date.now(),i=setInterval(()=>{let n=Math.round((Date.now()-r)/1e3);t(`${e} ${J("dim",`(${n}s \u2014 still working)`)}`)},1e3);return()=>clearInterval(i)}async function Mr(t){if(!Ae)return{result:await t(),output:""};let e="",r=(...n)=>{e+=n.map(o=>typeof o=="string"?o:String(o)).join(" ")+`
874
- `},i={log:console.log,error:console.error,warn:console.warn};console.log=r,console.error=r,console.warn=r;try{return{result:await t(),output:e}}finally{console.log=i.log,console.error=i.error,console.warn=i.warn}}function __e(){let t=tr(Ec(),{});t.thedotmack={source:{source:"github",repo:"thedotmack/claude-mem"},installLocation:dr(),lastUpdated:new Date().toISOString(),autoUpdate:!0},uc(hs()),Ke(Ec(),t)}function w_e(t){let e=tr(gs(),{});e.version||(e.version=2),e.plugins||(e.plugins={});let r=Da(t),i=new Date().toISOString();e.plugins["claude-mem@thedotmack"]=[{scope:"user",installPath:r,version:t,installedAt:i,lastUpdated:i}],Ke(gs(),e)}function k_e(){let t=tr(ys(),{});t.enabledPlugins||(t.enabledPlugins={}),t.enabledPlugins["claude-mem@thedotmack"]=!0,Ke(ys(),t)}function AV(){let t=tr(ys(),{}),e=t.env&&typeof t.env=="object"?t.env:{};return e.CLAUDE_CODE_DISABLE_AUTO_MEMORY==="1"?!1:(t.env={...e,CLAUDE_CODE_DISABLE_AUTO_MEMORY:"1"},Ke(ys(),t),!0)}async function I_e(t,e){if(!t.includes("claude-code"))return"not-applicable";if(e.disableAutoMemory)return"disable";if(!Ae)return"leave-enabled";let r=await eg({message:"Disable Claude Code auto-memory?",options:[{value:"leave-enabled",label:"Leave enabled",hint:"Recommended; keeps Claude Code native memory visible on startup."},{value:"disable",label:"Disable auto-memory",hint:"Only if you explicitly want claude-mem to replace native startup memory."}],initialValue:"leave-enabled"});return(At(r)||typeof r=="symbol")&&(Mt("Installation cancelled."),process.exit(0)),r}function CV(t,e,r){let i=(n,o)=>{Xe("FAIL_LOUD_PER_IDE",{component:n,ide:t,phase:"ide-install",cause:new Error(n),details:o&&o.trim().length>0?o.trim().slice(0,4e3):void 0},e)};switch(t){case"claude-code":return{title:"Claude Code: registering plugin",task:async()=>`Claude Code: plugin registered ${J("green","OK")}`};case"cursor":return{title:"Cursor: installing hooks + MCP",task:async n=>{n("Loading Cursor installer\u2026");let{installCursorHooks:o,configureCursorMcp:s}=await Promise.resolve().then(()=>(Iz(),kz));n("Installing Cursor hooks\u2026");let{result:a,output:l}=await Mr(()=>o("user"));if(a!==0)return i("Cursor: hook installation failed",l),`Cursor: hook installation failed ${J("red","FAIL")}`;n("Configuring Cursor MCP\u2026");let{result:c}=await Mr(async()=>s("user"));return c===0?`Cursor: hooks + MCP installed ${J("green","OK")}`:`Cursor: hooks installed; MCP setup failed \u2014 run \`npx claude-mem mcp\` ${J("yellow","!")}`}};case"grok-bot":return{title:"Grok Bot: installing transcript watch",task:async n=>{n("Configuring Grok Bot transcript watch\u2026");let{installGrokBotIntegration:o}=await Promise.resolve().then(()=>(jz(),Lz)),{result:s,output:a}=await Mr(async()=>o());return s!==0?(i("Grok Bot: transcript watch installation failed",a),`Grok Bot: transcript watch installation failed ${J("red","FAIL")}`):`Grok Bot: transcript watch installed ${J("green","OK")}`}};case"kimi":return{title:"Kimi Code: installing hooks + MCP",task:async n=>{n("Loading Kimi installer\u2026");let{installKimiHooks:o,configureKimiMcp:s}=await Promise.resolve().then(()=>(ly(),ay));n("Installing Kimi hooks\u2026");let{result:a,output:l}=await Mr(async()=>o());if(a!==0)return i("Kimi Code: hook installation failed",l),`Kimi Code: hook installation failed ${J("red","FAIL")}`;n("Configuring Kimi MCP\u2026");let{result:c}=await Mr(async()=>s());return c===0?`Kimi Code: hooks + MCP installed ${J("green","OK")}`:`Kimi Code: hooks installed; MCP setup failed \u2014 run \`npx claude-mem kimi install\` ${J("yellow","!")}`}};case"opencode":return{title:"OpenCode: installing plugin",task:async n=>{n("Loading OpenCode installer\u2026");let{installOpenCodeIntegration:o,getOpenCodeAgentsMdPath:s,OPENCODE_MCP_REGISTRATION_INCOMPLETE:a,OPENCODE_OLD_CONTEXT_BLOCK_LEFT:l}=await Promise.resolve().then(()=>(Gx(),Wx));n("Installing OpenCode plugin\u2026");let{result:c,output:u}=await Mr(()=>o());return c===a?(Xe("WARN_CONTINUE",{component:"opencode",phase:"ide-install",cause:new Error("OpenCode plugin installed, but MCP registration is incomplete (mcp-server.cjs not found)."),remediation:"Restore the plugin build, then re-run `npx claude-mem install --ide=opencode` to register the MCP server.",details:u},e),`OpenCode: plugin installed; MCP registration incomplete ${J("yellow","!")}`):c===l?(Xe("WARN_CONTINUE",{component:"opencode",phase:"ide-install",cause:new Error(`OpenCode plugin installed, but the old claude-mem memory block in ${s()} could not be removed; OpenCode shows it in every project.`),remediation:"Delete the <claude-mem-context> block from that file (or fix its permissions and re-run `npx claude-mem install --ide=opencode`).",details:u},e),`OpenCode: plugin installed; old AGENTS.md memory block left in place ${J("yellow","!")}`):c!==0?(i("OpenCode: plugin installation failed",u),`OpenCode: plugin installation failed ${J("red","FAIL")}`):`OpenCode: plugin installed ${J("green","OK")}`}};case"hermes":return{title:"Hermes Agent: installing memory provider",task:async n=>{n("Loading Hermes installer\u2026");let{installHermesIntegration:o}=await Promise.resolve().then(()=>(Gg(),hx));n("Installing the memory provider plugin\u2026");let{result:s,output:a}=await Mr(async()=>o());return s!==0?(i("Hermes Agent: memory provider installation failed",a),`Hermes Agent: memory provider installation failed ${J("red","FAIL")}`):`Hermes Agent: memory provider installed ${J("green","OK")}`}};case"pi":return{title:"Pi: installing memory extension",task:async()=>{let{installPiExtension:n}=await Promise.resolve().then(()=>(py(),dy)),{result:o,output:s}=await Mr(async()=>n());return o!==0?(i("Pi: memory extension installation failed",s),"Pi: extension installation failed"):"Pi: extension files installed; automatic capture is unverified. Pi 0.79.6 provides manual recall only. Check your Pi version and update Pi if needed: https://github.com/thedotmack/claude-mem/blob/main/docs/pi-native-capture.md"}};case"dsh":return{title:"DeepSeek Harness: installing native memory",task:async()=>{let{installDeepSeekHarness:n}=await Promise.resolve().then(()=>(Xx(),Zx)),{result:o,output:s}=await Mr(()=>n(r));return o===2?(Xe("WARN_CONTINUE",{component:"dsh",phase:"ide-install",cause:new Error("DeepSeek Harness plugin installed, but transcript capture is incomplete."),remediation:"Check the transcript config and CLAUDE_MEM_TRANSCRIPTS_ENABLED, then re-run npx claude-mem install --ide dsh --dsh-profile "+(r??"web")+".",details:s},e),"DeepSeek Harness: plugin installed; transcript setup incomplete"):o!==0?(i("DeepSeek Harness: native memory installation failed",s),"DeepSeek Harness: installation failed"):"DeepSeek Harness: native memory installed"}};case"omp":return{title:"OMP: installing hooks",task:async n=>{n("Loading OMP installer\u2026");let{installOmpHooks:o}=await Promise.resolve().then(()=>(rT(),tT));n("Installing OMP hooks\u2026");let{result:s,output:a}=await Mr(()=>o());return s!==0?(i("OMP: hook installation failed",a),`OMP: hook installation failed ${J("red","FAIL")}`):`OMP: hooks installed ${J("green","OK")}`}};case"windsurf":return{title:"Windsurf: installing hooks",task:async n=>{n("Loading Windsurf installer\u2026");let{installWindsurfHooks:o}=await Promise.resolve().then(()=>(sT(),oT));n("Installing Windsurf hooks\u2026");let{result:s,output:a}=await Mr(()=>o());return s!==0?(i("Windsurf: hook installation failed",a),`Windsurf: hook installation failed ${J("red","FAIL")}`):`Windsurf: hooks installed ${J("green","OK")}`}};case"openclaw":return{title:"OpenClaw: installing plugin",task:async n=>{n("Loading OpenClaw installer\u2026");let{installOpenClawIntegration:o}=await Promise.resolve().then(()=>(dT(),uT));n("Copying plugin files\u2026");let{result:s,output:a}=await Mr(()=>o());return s!==0?(i("OpenClaw: plugin installation failed",a),`OpenClaw: plugin installation failed ${J("red","FAIL")}`):`OpenClaw: plugin installed ${J("green","OK")}`}};case"t3code":return{title:"T3 Code: registering native provider plugins",task:async n=>{n("Installing hooks and MCP for T3 Code providers\u2026");let{installT3Code:o}=await Promise.resolve().then(()=>(Ap(),zg)),{result:s,output:a}=await Mr(()=>o(dr()));return s!==0?(i("T3 Code: integration setup failed",a),`T3 Code: integration setup failed ${J("red","FAIL")}`):`T3 Code: native provider plugins registered ${J("green","OK")}`}};case"codex-cli":return{title:"Codex CLI: registering hooks marketplace",task:async n=>{n("Loading Codex CLI installer\u2026");let{installCodexCli:o}=await Promise.resolve().then(()=>($g(),ix));n("Registering native Codex hooks\u2026");let{result:s,output:a}=await Mr(()=>o(dr()));return s!==0?(i("Codex CLI: integration setup failed",a),`Codex CLI: integration setup failed ${J("red","FAIL")}`):`Codex CLI: hooks marketplace registered ${J("green","OK")}`}};case"antigravity":return{title:"Antigravity: installing hooks + MCP",task:async n=>{n("Loading Antigravity CLI installer\u2026");let{installAntigravityCliHooks:o}=await Promise.resolve().then(()=>(xy(),Iy));n("Installing Antigravity hooks + MCP\u2026");let{result:s,output:a}=await Mr(()=>o());return s!==0?(i("Antigravity: hooks + MCP installation failed",a),`Antigravity: hooks + MCP installation failed ${J("red","FAIL")}`):`Antigravity: hooks + MCP installed ${J("green","OK")}`}};case"copilot-cli":case"goose":case"roo-code":case"warp":{let s=Vg().find(a=>a.id===t)?.label??t;return{title:`${s}: installing MCP integration`,task:async a=>{a("Loading MCP installer\u2026");let{MCP_IDE_INSTALLERS:l}=await Promise.resolve().then(()=>(Sy(),bT)),c=l[t];if(!c)return`${s}: MCP installer not found ${J("yellow","!")}`;a(`Configuring ${s} MCP\u2026`);let{result:u,output:d}=await Mr(()=>c());return u!==0?(i(`${s}: MCP integration failed`,d),`${s}: MCP integration failed ${J("red","FAIL")}`):`${s}: MCP integration installed ${J("green","OK")}`}}}default:return null}}async function vV(t,e,r){let i=[];for(let n of t){let o=CV(n,e,r);o&&i.push(o)}return i.length>0&&await du(i),t.length>0&&e.failedIDEs.length===t.length&&Xe("ABORT",{component:"all-ides",phase:"ide-install",cause:new Error(`All ${t.length} selected IDE integrations failed.`)},e),e.failedIDEs}function x_e(){ni(hr(E_e(),".local","bin","claude"))&&xx({purposeLabel:"Claude Code",logger:M})}function OV(t=wt){return t?'powershell -ExecutionPolicy ByPass -c "irm https://claude.ai/install.ps1 | iex"':"set -o pipefail; curl -fsSL https://claude.ai/install.sh | bash"}async function T_e(){let t=OV(),e=wt?process.env.ComSpec??"cmd.exe":"/bin/bash",r=Ae?$a():null;return r?.start("Installing Claude Code (this can take a few minutes \u2014 downloading the native build)\u2026"),new Promise(i=>{let n="",o=vi(t,[],{shell:e,stdio:r?["inherit","pipe","pipe"]:"inherit"});o.stdout?.on("data",s=>{n+=s.toString()}),o.stderr?.on("data",s=>{n+=s.toString()}),o.on("error",s=>{r?.error("Claude Code install failed"),n&&process.stderr.write(n),M.error(`Claude Code install failed: ${s.message}`),M.info("You can install it manually later: https://claude.ai/install.sh"),i(!1)}),o.on("exit",s=>{if(s!==0){r?.error("Claude Code install failed"),n&&process.stderr.write(n),M.error(`Claude Code install failed (exit ${s??"unknown"})`),M.info("You can install it manually later: https://claude.ai/install.sh"),i(!1);return}if(r?.stop("Claude Code installed"),!wt)try{x_e()}catch(a){M.warn(`Could not auto-apply PATH setup: ${a instanceof Error?a.message:String(a)}`)}i(!0)})})}async function RV(){let t=Vg();t.filter(s=>s.detected).length===0&&M.warn("No supported IDEs detected \u2014 pick the one(s) you plan to use.");let r=t.map(s=>{let a=s.detected?" [detected]":"";return{value:s.id,label:s.label,hint:`${s.hint}${a}`}}),i=KB(t),n=await lp({message:"Which agents do you use?",options:r,initialValues:i,required:!0});At(n)&&(Mt("Installation cancelled."),process.exit(0));let o=n;if(o.includes("claude-code")&&!t.find(s=>s.id==="claude-code")?.detected){let s=await Ii({message:"Install Claude Code now?",initialValue:!0});if(At(s)&&(Mt("Installation cancelled."),process.exit(0)),s&&!await T_e())return M.warn("Claude Code installation failed. Choose an agent again, or decline the host installation to set it up later."),RV()}return o}function MV(){let t=dr(),e=Na(),r=CF(e);uc(t);let i=[".agents",".claude-plugin",".codex-plugin",".cursor-plugin","claude-mem-cursor","claude-mem-grok-bot","plugin","package-lock.json","openclaw","omp","hermes","pi","dsh","dist","README.md","CHANGELOG.md"];for(let n of i){let o=hr(e,n),s=hr(t,n);ni(o)&&(ni(s)&&IV(s,{recursive:!0,force:!0}),kV(o,s,{recursive:!0,force:!0}))}_c(t,r),DV(e,t),PV(t)}function PV(t){let e=hr(t,".claude-plugin","marketplace.json");if(!ni(e))return;let r=JSON.parse(ib(e,"utf-8"));if(!Array.isArray(r.plugins))return;let i=r.plugins.filter(n=>{let o=n?.source;return typeof o!="string"||!o.startsWith(".")||ni(hr(t,o))});i.length!==r.plugins.length&&xV(e,`${JSON.stringify({...r,plugins:i},null,2)}
874
+ `},i={log:console.log,error:console.error,warn:console.warn};console.log=r,console.error=r,console.warn=r;try{return{result:await t(),output:e}}finally{console.log=i.log,console.error=i.error,console.warn=i.warn}}function __e(){let t=tr(Ec(),{});t.thedotmack={source:{source:"github",repo:"thedotmack/claude-mem"},installLocation:dr(),lastUpdated:new Date().toISOString(),autoUpdate:!0},uc(hs()),Ke(Ec(),t)}function w_e(t){let e=tr(gs(),{});e.version||(e.version=2),e.plugins||(e.plugins={});let r=Da(t),i=new Date().toISOString();e.plugins["claude-mem@thedotmack"]=[{scope:"user",installPath:r,version:t,installedAt:i,lastUpdated:i}],Ke(gs(),e)}function k_e(){let t=tr(ys(),{});t.enabledPlugins||(t.enabledPlugins={}),t.enabledPlugins["claude-mem@thedotmack"]=!0,Ke(ys(),t)}function AV(){let t=tr(ys(),{}),e=t.env&&typeof t.env=="object"?t.env:{};return e.CLAUDE_CODE_DISABLE_AUTO_MEMORY==="1"?!1:(t.env={...e,CLAUDE_CODE_DISABLE_AUTO_MEMORY:"1"},Ke(ys(),t),!0)}async function I_e(t,e){if(!t.includes("claude-code"))return"not-applicable";if(e.disableAutoMemory)return"disable";if(!Ae)return"leave-enabled";let r=await eg({message:"Disable Claude Code auto-memory?",options:[{value:"leave-enabled",label:"Leave enabled",hint:"Recommended; keeps Claude Code native memory visible on startup."},{value:"disable",label:"Disable auto-memory",hint:"Only if you explicitly want claude-mem to replace native startup memory."}],initialValue:"leave-enabled"});return(At(r)||typeof r=="symbol")&&(Mt("Installation cancelled."),process.exit(0)),r}function CV(t,e,r){let i=(n,o)=>{Xe("FAIL_LOUD_PER_IDE",{component:n,ide:t,phase:"ide-install",cause:new Error(n),details:o&&o.trim().length>0?o.trim().slice(0,4e3):void 0},e)};switch(t){case"claude-code":return{title:"Claude Code: registering plugin",task:async()=>`Claude Code: plugin registered ${J("green","OK")}`};case"cursor":return{title:"Cursor: installing hooks + MCP",task:async n=>{n("Loading Cursor installer\u2026");let{installCursorHooks:o,configureCursorMcp:s}=await Promise.resolve().then(()=>(Iz(),kz));n("Installing Cursor hooks\u2026");let{result:a,output:l}=await Mr(()=>o("user"));if(a!==0)return i("Cursor: hook installation failed",l),`Cursor: hook installation failed ${J("red","FAIL")}`;n("Configuring Cursor MCP\u2026");let{result:c}=await Mr(async()=>s("user"));return c===0?`Cursor: hooks + MCP installed ${J("green","OK")}`:`Cursor: hooks installed; MCP setup failed \u2014 run \`npx claude-mem mcp\` ${J("yellow","!")}`}};case"grok-bot":return{title:"Grok Bot: installing transcript watch",task:async n=>{n("Configuring Grok Bot transcript watch\u2026");let{installGrokBotIntegration:o}=await Promise.resolve().then(()=>(jz(),Lz)),{result:s,output:a}=await Mr(async()=>o());return s!==0?(i("Grok Bot: transcript watch installation failed",a),`Grok Bot: transcript watch installation failed ${J("red","FAIL")}`):`Grok Bot: transcript watch installed ${J("green","OK")}`}};case"kimi":return{title:"Kimi Code: installing hooks + MCP",task:async n=>{n("Loading Kimi installer\u2026");let{installKimiHooks:o,configureKimiMcp:s}=await Promise.resolve().then(()=>(ly(),ay));n("Installing Kimi hooks\u2026");let{result:a,output:l}=await Mr(async()=>o());if(a!==0)return i("Kimi Code: hook installation failed",l),`Kimi Code: hook installation failed ${J("red","FAIL")}`;n("Configuring Kimi MCP\u2026");let{result:c}=await Mr(async()=>s());return c===0?`Kimi Code: hooks + MCP installed ${J("green","OK")}`:`Kimi Code: hooks installed; MCP setup failed \u2014 run \`npx claude-mem kimi install\` ${J("yellow","!")}`}};case"opencode":return{title:"OpenCode: installing plugin",task:async n=>{n("Loading OpenCode installer\u2026");let{installOpenCodeIntegration:o,getOpenCodeAgentsMdPath:s,OPENCODE_MCP_REGISTRATION_INCOMPLETE:a,OPENCODE_OLD_CONTEXT_BLOCK_LEFT:l}=await Promise.resolve().then(()=>(Gx(),Wx));n("Installing OpenCode plugin\u2026");let{result:c,output:u}=await Mr(()=>o());return c===a?(Xe("WARN_CONTINUE",{component:"opencode",phase:"ide-install",cause:new Error("OpenCode plugin installed, but MCP registration is incomplete (mcp-server.cjs not found)."),remediation:"Restore the plugin build, then re-run `npx claude-mem install --ide=opencode` to register the MCP server.",details:u},e),`OpenCode: plugin installed; MCP registration incomplete ${J("yellow","!")}`):c===l?(Xe("WARN_CONTINUE",{component:"opencode",phase:"ide-install",cause:new Error(`OpenCode plugin installed, but the old claude-mem memory block in ${s()} could not be removed; OpenCode shows it in every project.`),remediation:"Delete the <claude-mem-context> block from that file (or fix its permissions and re-run `npx claude-mem install --ide=opencode`).",details:u},e),`OpenCode: plugin installed; old AGENTS.md memory block left in place ${J("yellow","!")}`):c!==0?(i("OpenCode: plugin installation failed",u),`OpenCode: plugin installation failed ${J("red","FAIL")}`):`OpenCode: plugin installed ${J("green","OK")}`}};case"hermes":return{title:"Hermes Agent: installing memory provider",task:async n=>{n("Loading Hermes installer\u2026");let{installHermesIntegration:o}=await Promise.resolve().then(()=>(Gg(),hx));n("Installing the memory provider plugin\u2026");let{result:s,output:a}=await Mr(async()=>o());return s!==0?(i("Hermes Agent: memory provider installation failed",a),`Hermes Agent: memory provider installation failed ${J("red","FAIL")}`):`Hermes Agent: memory provider installed ${J("green","OK")}`}};case"pi":return{title:"Pi: installing memory extension",task:async()=>{let{installPiExtension:n}=await Promise.resolve().then(()=>(py(),dy)),{result:o,output:s}=await Mr(async()=>n());return o!==0?(i("Pi: memory extension installation failed",s),"Pi: extension installation failed"):"Pi: extension files installed; automatic capture is unverified. Pi 0.79.6 provides manual recall only. Check your Pi version and update Pi if needed: https://github.com/thedotmack/claude-mem/blob/main/docs/pi-native-capture.md"}};case"dsh":return{title:"DeepSeek Harness: installing native memory",task:async()=>{let{installDeepSeekHarness:n}=await Promise.resolve().then(()=>(Xx(),Zx)),{result:o,output:s}=await Mr(()=>n(r));return o===2?(Xe("WARN_CONTINUE",{component:"dsh",phase:"ide-install",cause:new Error("DeepSeek Harness plugin installed, but transcript capture is incomplete."),remediation:"Check the transcript config and CLAUDE_MEM_TRANSCRIPTS_ENABLED, then re-run npx claude-mem install --ide dsh --dsh-profile "+(r??"web")+".",details:s},e),"DeepSeek Harness: plugin installed; transcript setup incomplete"):o!==0?(i("DeepSeek Harness: native memory installation failed",s),"DeepSeek Harness: installation failed"):"DeepSeek Harness: native memory installed"}};case"omp":return{title:"OMP: installing hooks",task:async n=>{n("Loading OMP installer\u2026");let{installOmpHooks:o}=await Promise.resolve().then(()=>(rT(),tT));n("Installing OMP hooks\u2026");let{result:s,output:a}=await Mr(()=>o());return s!==0?(i("OMP: hook installation failed",a),`OMP: hook installation failed ${J("red","FAIL")}`):`OMP: hooks installed ${J("green","OK")}`}};case"windsurf":return{title:"Windsurf: installing hooks",task:async n=>{n("Loading Windsurf installer\u2026");let{installWindsurfHooks:o}=await Promise.resolve().then(()=>(sT(),oT));n("Installing Windsurf hooks\u2026");let{result:s,output:a}=await Mr(()=>o());return s!==0?(i("Windsurf: hook installation failed",a),`Windsurf: hook installation failed ${J("red","FAIL")}`):`Windsurf: hooks installed ${J("green","OK")}`}};case"openclaw":return{title:"OpenClaw: installing plugin",task:async n=>{n("Loading OpenClaw installer\u2026");let{installOpenClawIntegration:o}=await Promise.resolve().then(()=>(dT(),uT));n("Copying plugin files\u2026");let{result:s,output:a}=await Mr(()=>o());return s!==0?(i("OpenClaw: plugin installation failed",a),`OpenClaw: plugin installation failed ${J("red","FAIL")}`):`OpenClaw: plugin installed ${J("green","OK")}`}};case"t3code":return{title:"T3 Code: registering native provider plugins",task:async n=>{n("Installing hooks and MCP for T3 Code providers\u2026");let{installT3Code:o}=await Promise.resolve().then(()=>(Ap(),zg)),{result:s,output:a}=await Mr(()=>o(dr()));return s!==0?(i("T3 Code: integration setup failed",a),`T3 Code: integration setup failed ${J("red","FAIL")}`):`T3 Code: native provider plugins registered ${J("green","OK")}`}};case"codex-cli":return{title:"Codex CLI: registering hooks marketplace",task:async n=>{n("Loading Codex CLI installer\u2026");let{installCodexCli:o}=await Promise.resolve().then(()=>($g(),ix));n("Registering native Codex hooks\u2026");let{result:s,output:a}=await Mr(()=>o(dr()));return s!==0?(i("Codex CLI: integration setup failed",a),`Codex CLI: integration setup failed ${J("red","FAIL")}`):`Codex CLI: hooks marketplace registered ${J("green","OK")}`}};case"antigravity":return{title:"Antigravity: installing hooks + MCP",task:async n=>{n("Loading Antigravity CLI installer\u2026");let{installAntigravityCliHooks:o}=await Promise.resolve().then(()=>(xy(),Iy));n("Installing Antigravity hooks + MCP\u2026");let{result:s,output:a}=await Mr(()=>o());return s!==0?(i("Antigravity: hooks + MCP installation failed",a),`Antigravity: hooks + MCP installation failed ${J("red","FAIL")}`):`Antigravity: hooks + MCP installed ${J("green","OK")}`}};case"copilot-cli":case"goose":case"roo-code":case"warp":{let s=Vg().find(a=>a.id===t)?.label??t;return{title:`${s}: installing MCP integration`,task:async a=>{a("Loading MCP installer\u2026");let{MCP_IDE_INSTALLERS:l}=await Promise.resolve().then(()=>(Sy(),bT)),c=l[t];if(!c)return`${s}: MCP installer not found ${J("yellow","!")}`;a(`Configuring ${s} MCP\u2026`);let{result:u,output:d}=await Mr(()=>c());return u!==0?(i(`${s}: MCP integration failed`,d),`${s}: MCP integration failed ${J("red","FAIL")}`):`${s}: MCP integration installed ${J("green","OK")}`}}}default:return null}}async function vV(t,e,r){let i=[];for(let n of t){let o=CV(n,e,r);o&&i.push(o)}return i.length>0&&await du(i),t.length>0&&e.failedIDEs.length===t.length&&Xe("ABORT",{component:"all-ides",phase:"ide-install",cause:new Error(`All ${t.length} selected IDE integrations failed.`)},e),e.failedIDEs}function x_e(){ni(hr(E_e(),".local","bin","claude"))&&xx({purposeLabel:"Claude Code",logger:M})}function OV(t=wt){return t?'powershell -ExecutionPolicy ByPass -c "irm https://claude.ai/install.ps1 | iex"':"set -o pipefail; curl -fsSL https://claude.ai/install.sh | bash"}async function T_e(){let t=OV(),e=wt?process.env.ComSpec??"cmd.exe":"/bin/bash",r=Ae?$a():null;return r?.start("Installing Claude Code (this can take a few minutes \u2014 downloading the native build)\u2026"),new Promise(i=>{let n="",o=vi(t,[],{shell:e,stdio:r?["inherit","pipe","pipe"]:"inherit"});o.stdout?.on("data",s=>{n+=s.toString()}),o.stderr?.on("data",s=>{n+=s.toString()}),o.on("error",s=>{r?.error("Claude Code install failed"),n&&process.stderr.write(n),M.error(`Claude Code install failed: ${s.message}`),M.info("You can install it manually later: https://claude.ai/install.sh"),i(!1)}),o.on("exit",s=>{if(s!==0){r?.error("Claude Code install failed"),n&&process.stderr.write(n),M.error(`Claude Code install failed (exit ${s??"unknown"})`),M.info("You can install it manually later: https://claude.ai/install.sh"),i(!1);return}if(r?.stop("Claude Code installed"),!wt)try{x_e()}catch(a){M.warn(`Could not auto-apply PATH setup: ${a instanceof Error?a.message:String(a)}`)}i(!0)})})}async function RV(){let t=Vg();t.filter(s=>s.detected).length===0&&M.warn("No supported IDEs detected \u2014 pick the one(s) you plan to use.");let r=t.map(s=>{let a=s.detected?" [detected]":"";return{value:s.id,label:s.label,hint:`${s.hint}${a}`}}),i=KB(t),n=await lp({message:"Which agents do you use?",options:r,initialValues:i,required:!0});At(n)&&(Mt("Installation cancelled."),process.exit(0));let o=n;if(o.includes("claude-code")&&!t.find(s=>s.id==="claude-code")?.detected){let s=await Ii({message:"Install Claude Code now?",initialValue:!0});if(At(s)&&(Mt("Installation cancelled."),process.exit(0)),s&&!await T_e())return M.warn("Claude Code installation failed. Choose an agent again, or decline the host installation to set it up later."),RV()}return o}function MV(){let t=dr(),e=Na(),r=CF(e);uc(t);let i=[".agents",".claude-plugin",".codex-plugin",".cursor-plugin","claude-mem-cursor","claude-mem-grok-bot","plugin","package-lock.json","openclaw","omp","hermes","pi","dsh","dist","README.md"];for(let n of i){let o=hr(e,n),s=hr(t,n);ni(o)&&(ni(s)&&IV(s,{recursive:!0,force:!0}),kV(o,s,{recursive:!0,force:!0}))}_c(t,r),DV(e,t),PV(t)}function PV(t){let e=hr(t,".claude-plugin","marketplace.json");if(!ni(e))return;let r=JSON.parse(ib(e,"utf-8"));if(!Array.isArray(r.plugins))return;let i=r.plugins.filter(n=>{let o=n?.source;return typeof o!="string"||!o.startsWith(".")||ni(hr(t,o))});i.length!==r.plugins.length&&xV(e,`${JSON.stringify({...r,plugins:i},null,2)}
875
875
  `)}function DV(t,e){let r=hr(t,"package.json");if(!ni(r))return;let i=JSON.parse(ib(r,"utf-8"));delete i.devDependencies,delete i.trustedDependencies,xV(hr(e,"package.json"),`${JSON.stringify(i,null,2)}
876
876
  `)}async function NV(t){let e=_I(),r=Da(t);IV(r,{recursive:!0,force:!0}),uc(r),kV(e,r,{recursive:!0,force:!0});try{let i=await Cg({additionalProtectedVersions:[t]});i.retainedForLiveWorker?M.info("Skipped cache prune: a worker is running but its version could not be read; retaining all versions."):i.removed.length>0&&M.info(`Pruned ${i.removed.length} stale plugin cache version(s): ${i.removed.join(", ")}`);for(let n of i.failed)M.warn(`Could not prune cache version ${n.version}: ${n.reason}`)}catch(i){M.warn(`Skipped cache prune: ${i instanceof Error?i.message:String(i)}`)}}function LV(t,e,r,i){xc(t,e,r,i),xc(hr(t,"plugin"),e,r,i)}async function jV(t){let e=dr(),r=hr(e,"package.json");if(!ni(r))return;let i=["install","--omit=dev","--ignore-scripts"],n=await E0(e,i);if(n.code===0)return;if(n.timedOut&&Xe("ABORT",{component:"marketplace-npm-install",phase:"marketplace-deps",cause:new Error("npm install timed out"),details:n.stderr.slice(0,4e3)},t),!FJ(n.stderr)){let s=BJ(n.stderr);Xe("ABORT",{component:"marketplace-npm-install",phase:"marketplace-deps",cause:new Error(`npm install failed (exit ${n.code})${s?`: ${s}`:""}`),details:n.stderr.slice(0,4e3)},t)}M.warn("npm reported an ERESOLVE peer-dependency conflict in marketplace deps; retrying once with --legacy-peer-deps."),M.warn(JJ(n.stderr));let o=await E0(e,[...i,"--legacy-peer-deps"]);if(o.code===0){t.warnings.push({component:"marketplace-npm-install",message:"tree-sitter peer-dep ERESOLVE was resolved with the --legacy-peer-deps fallback. Benign for the marketplace install; re-evaluate when tree-sitter peer ranges change.",remediation:"No action required."});return}Xe("ABORT",{component:"marketplace-npm-install",phase:"marketplace-deps",cause:new Error(`npm install --legacy-peer-deps still failed (exit ${o.code}): ERESOLVE`),details:o.stderr.slice(0,4e3)},t)}function zt(t,e=fe){let r=Gi(e,t,{},void 0,{quarantineCorrupt:!0});if(r.status==="refused"){let i=r.error instanceof Error?r.error.message:String(r.error);return M.error(r.quarantinedTo?`Failed to write settings to ${e}: ${i}. Its unreadable previous contents are in ${r.quarantinedTo}.`:`Failed to write settings to ${e}: ${i}`),!1}return r.quarantinedTo&&M.warn(`${e} could not be read, so it was moved to ${r.quarantinedTo} and a fresh settings file was started. Copy back any settings you still need from it.`),!0}function WA(){try{return Sp(fe)??{}}catch{return{}}}function A_e(){try{let t=Sp(fe)?.CLAUDE_MEM_CLAUDE_AUTH_METHOD;return t==="subscription"||t==="api-key"||t==="gateway"?t:void 0}catch{return}}function KV(){let t=A_e();if(t)return t;let e=JI();return e.ANTHROPIC_BASE_URL?.trim()?"gateway":e.ANTHROPIC_API_KEY?.trim()?"api-key":"subscription"}function GA(t,e){e==="server"&&t.some(r=>r==="pi"||r==="dsh")&&(M.error("Pi and DeepSeek Harness currently require --runtime worker."),process.exit(1))}async function O_e(t,e){if(t.runtime!==void 0){let i=gp(t.runtime);return i===null&&(M.error(`Unknown --runtime: ${t.runtime}. Allowed: worker, server`),process.exit(1)),GA(e,i),i==="server"?(await R_e(t),"server"):(zt({CLAUDE_MEM_RUNTIME:"worker"}),"worker")}if(!Ae)return zt({CLAUDE_MEM_RUNTIME:"worker"}),"worker";let r=await eg({message:"Which runtime should claude-mem start after install?",options:[{value:"worker",label:"Worker",hint:"stable compatibility path"},{value:"server",label:"Server (beta)",hint:"REST V1, API keys, team-ready storage"}],initialValue:"worker"});return(At(r)||typeof r=="symbol")&&(Mt("Installation cancelled."),process.exit(0)),GA(e,r),zt({CLAUDE_MEM_RUNTIME:r}),r==="server"&&await $V(),r}async function R_e(t){let e=(t.serverUrl??"").trim()||C_e;zt({CLAUDE_MEM_RUNTIME:"server",CLAUDE_MEM_SERVER_URL:e}),M.info(`Server runtime selected. Bring up the bundled stack with \`docker compose up -d postgres valkey claude-mem-server claude-mem-worker\` (pg + redis/valkey). The server listens at ${e}.`),M.info(`IDE MCP config target for the server runtime: http ${e.replace(/\/+$/,"")}/mcp`),await $V()}async function $V(){if(!process.env.CLAUDE_MEM_SERVER_DATABASE_URL){M.warn("Skipping local hook API key bootstrap: CLAUDE_MEM_SERVER_DATABASE_URL is not set. Run `npx claude-mem server keys rotate` after configuring Postgres to provision a key.");return}try{await M_e()}catch(t){M.warn(`Failed to bootstrap server API key: ${t instanceof Error?t.message:String(t)}. Hooks will fall back to the worker until you run \`npx claude-mem server keys rotate\`.`)}}async function M_e(){let{bootstrapServerApiKey:t,revokeServerApiKey:e,persistServerSettings:r}=await Promise.resolve().then(()=>(JA(),FA)),i=await t();if(r(fe,{apiKey:i.rawKey,projectId:i.projectId})){M.info(`Provisioned local hook API key (project=${i.projectId.slice(0,8)}\u2026). Settings saved with mode 0600.`);return}await e(i.apiKeyId).catch(o=>{M.warn(`Could not revoke the unpersisted server API key: ${o instanceof Error?o.message:String(o)}`)}),M.warn("Server API key was provisioned but settings.json could not be updated. Repair or restore ~/.claude-mem/settings.json and rerun the installer.")}function $s(t){try{process.platform==="darwin"?BA("open",[t],{stdio:"ignore"}):process.platform==="win32"?BA("cmd",["/c","start","",t],{stdio:"ignore"}):BA("xdg-open",[t],{stdio:"ignore"})}catch{}}async function VA(t,e,r){let i=Pt("CLAUDE_MEM_PROVIDER")||"claude",n=WA(),o=E=>{let S=E??KV();zt({CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:S})&&M.info("Saved Claude Agent SDK configuration to ~/.claude-mem/settings.json")},s=()=>{zt(r2(n))||(Mt("Could not save the local Anthropic Max configuration."),process.exit(1)),LF({ANTHROPIC_API_KEY:"",ANTHROPIC_BASE_URL:"",ANTHROPIC_AUTH_TOKEN:""}),M.info("Disabled cloud sync and saved local Anthropic Max configuration."),M.info("Configured claude-mem to use your logged-in Claude SDK account.")};if(t.providerSource==="persisted"&&t.provider)return t.provider;let a;if(t.provider)a=t.provider;else{if(!Ae)throw new Error("Non-interactive provider validation did not run.");t.providerSource="prompt";let E=VJ();for(;;){let S=await lp({message:GJ,options:[{value:"cmem",label:E.cmem,hint:E.cmemHint},{value:"claude",label:E.claude,hint:E.claudeHint}],initialValues:["cmem"],required:!0});if((At(S)||!Array.isArray(S))&&(Mt("Installation cancelled."),process.exit(1)),S.length===1){a=S[0];break}M.warn("Select exactly one provider.")}}if(a==="cmem"){if(!e)throw new Error("CMEM Pro requires a signed-in claude-mem account.");let E=await XA(e,r);if(E||(Mt("CMEM Pro setup was not completed. Run npx claude-mem install to try again."),process.exit(1)),!E.memory)return M.warn(`This account syncs through a TeamBrain seat, which does not include CMEM Pro's observer. Memory keeps its current provider (${i}). CMEM Pro: ${wg("installer")}`),i;let S=k0(E.memory,n);return S||(Mt("CMEM Pro did not return memory credentials. Run npx claude-mem install to try again."),process.exit(1)),zt(I0(S))||(Mt("Could not save the CMEM Pro configuration."),process.exit(1)),S.clearFallback&&Ig(),M.info("CMEM Pro configured with your signed-in memory key."),"openrouter"}if(a==="claude")return s(),"claude";if(a==="codex"){let E=t.model?.trim();if(t.model!==void 0&&!E)throw new Error("Codex model must not be empty. Omit --model to keep the current Codex model setting.");return zt({CLAUDE_MEM_PROVIDER:"codex",...E?{CLAUDE_MEM_CODEX_MODEL:E}:{}})||(Mt("Could not save the Codex provider configuration."),process.exit(1)),M.info("Configured Codex subscription provider. Run `codex login` before starting the worker."),"codex"}if(a==="host"){let E=t.ide==="grok-bot"?"grok-bot":"cursor";return zt(t2(E,n))||(Mt("Could not save the host observer configuration."),process.exit(1)),M.info(`Configured host observer for ${E}.`),"openrouter"}if(a==="openai-compatible")throw new Error("The openai-compatible provider is configured in ~/.claude-mem/settings.json, not by the installer.");let l=a==="gemini"?"Gemini":"OpenRouter",c=a==="gemini"?"CLAUDE_MEM_GEMINI_API_KEY":"CLAUDE_MEM_OPENROUTER_API_KEY",u=Pt(c),d=a==="openrouter"?String(Pt("CLAUDE_MEM_OPENROUTER_BASE_URL")??""):"",p=a==="openrouter"&&Oo(d);if(u&&u.trim().length>0&&!p)return zt({CLAUDE_MEM_PROVIDER:a})&&M.info(`Saved provider=${a} to ~/.claude-mem/settings.json`),a;if(!Ae)throw new Error(`Non-interactive ${l} configuration is missing a personal API key.`);let f=await IF({message:`Paste your ${l} API key:`,mask:"*",validate:E=>!E||E.trim().length===0?"API key required":void 0});if(At(f))return M.warn("API key prompt cancelled \u2014 falling back to Claude provider."),o(),"claude";let m=String(f).trim(),h=a==="openrouter"?n2(m,WA(),he.getAllDefaults().CLAUDE_MEM_OPENROUTER_MODEL):{CLAUDE_MEM_PROVIDER:a,[c]:m};return zt(h)&&M.info(`Saved provider=${a} to ~/.claude-mem/settings.json`),a}async function EV(t,e=Ae){let r=new Set(["haiku","sonnet","opus","claude-haiku-4-5-20251001","claude-sonnet-5","claude-opus-4-8"]),i=KV()==="gateway";if(t.model&&!i){if(!r.has(t.model))throw new Error(`Unknown Claude model: ${t.model}. Allowed: ${[...r].join(", ")}`);zt({CLAUDE_MEM_MODEL:t.model})&&M.info(`Saved Claude model=${t.model} to ~/.claude-mem/settings.json`);return}if(t.model&&i){zt({CLAUDE_MEM_MODEL:t.model})&&M.info(`Saved gateway model=${t.model} to ~/.claude-mem/settings.json`);return}if(!e)return;let n=Pt("CLAUDE_MEM_MODEL");if(i){let u=await xF({message:"Which model should the gateway use?",placeholder:"haiku",defaultValue:n||"haiku",validate:f=>!f||f.trim().length===0?"Model required":void 0});At(u)&&(Mt("Installation cancelled."),process.exit(0));let d=String(u).trim();zt({CLAUDE_MEM_MODEL:d})&&M.info(`Saved gateway model=${d} to ~/.claude-mem/settings.json`);return}let o=r.has(n)?n:"haiku",s=[{value:"haiku",label:"Haiku, newest version (recommended \u2014 fast, cheap, great for compression)"},{value:"sonnet",label:"Sonnet, newest version (balanced quality and cost)"},{value:"opus",label:"Opus, newest version (highest quality, slowest)"}];s.some(u=>u.value===o)||s.push({value:o,label:`${o} (your saved pin; never updates)`});let a=await eg({message:`Which Claude model should claude-mem use to compress observations?
877
877
  This runs whenever you and Claude touch a file \u2014 keep it cheap and fast.`,options:s,initialValue:o});At(a)&&(Mt("Installation cancelled."),process.exit(0));let l=a;zt({CLAUDE_MEM_MODEL:l})&&M.info(`Saved Claude model=${l} to ~/.claude-mem/settings.json`)}function Pr(t){return typeof t=="string"&&t.trim().length>0?t.trim():null}function zA(t,e){let r=Pr(t);if(!r)return null;try{let i=new URL(r),n=new URL(xg).origin;return i.origin!==n||i.pathname!==e||i.username||i.password||i.hash?null:i}catch{return null}}function SV(t,e){let r=[...t.searchParams.entries()],i=Object.entries(e);return r.length===i.length&&i.every(([n,o])=>t.searchParams.get(n)===o)}function $_e(t,e){if([...t.searchParams.entries()].length!==2||t.searchParams.get("pairing")!==e)return!1;let i=t.searchParams.get("trial");if(i===null||!/^[0-9]{1,3}$/.test(i))return!1;let n=Number(i);return n>=1&&n<=365}function UV(t){if(!t||typeof t!="object")return null;let e=t,r=Pr(e.pairing_id),i=Pr(e.secret),n=Pr(e.user_code),o=zA(e.authorization_url,"/login"),s=zA(e.checkout_url,"/api/pro/trial/claim");if(!r||!/^[0-9a-f]{32}$/.test(r)||!i||!/^[0-9a-f]{48}$/.test(i)||!n||!/^[A-HJ-KM-NP-TV-Z2-9]{4}-[A-HJ-KM-NP-TV-Z2-9]{4}$/.test(n)||!o||!s)return null;let a=new URL(xg).origin,l=o.searchParams.get("next");if(!l||!l.startsWith("/")||l.startsWith("//")||!SV(o,{next:l}))return null;let c=zA(`${a}${l}`,"/api/pro/trial/claim");if(!c||!SV(c,{pairing:r,login_only:"1"})||!$_e(s,r))return null;let u=typeof e.poll_interval=="number"&&Number.isFinite(e.poll_interval)&&e.poll_interval>0?Math.min(Math.max(e.poll_interval,1),30):K_e,d=typeof e.expires_in=="number"&&Number.isFinite(e.expires_in)&&e.expires_in>0?Date.now()+Math.min(e.expires_in*1e3,j_e):void 0;return{pairingId:r,secret:i,userCode:n,authorizationUrl:o.toString(),checkoutUrl:s.toString(),pollIntervalMs:u*1e3,...d!==void 0?{expiresAt:d}:{}}}function pu(){return sl}function fu(){return rb}function JV(t){FV={...t}}function BV(t,e,r={},i){return{source:t,device_name:e,...r.installState?{install_state:r.installState}:{},...r.usageSummary?{usage_summary:r.usageSummary}:{},...i?{team_invite:i}:{}}}async function mu(t={}){let e=t.source??"npx-installer";sl=null,rb=null;let r;try{r=_2(S2())}catch(o){return sl="credentials",rb=o instanceof Error?o.message:String(o),null}let i=new AbortController,n=setTimeout(()=>i.abort(),t.timeoutMs??P_e);try{let o=await fetch(xg,{method:"POST",headers:{"Content-Type":"application/json",...r},body:JSON.stringify(BV(e,YA(),FV,t.teamInvite)),signal:i.signal});if(!o.ok){sl="http_error";try{let l=await o.json();l&&typeof l=="object"&&(rb=Pr(l.message))}catch(l){if(l instanceof Error&&l.name==="AbortError")throw l}return null}let s;try{s=await o.json()}catch(l){return sl=l instanceof Error&&l.name==="AbortError"?"timeout":"bad_body",null}let a=UV(s);return a||(sl="bad_body"),a}catch(o){return sl=o instanceof Error&&o.name==="AbortError"?"timeout":"network",null}finally{clearTimeout(n)}}function ob(t,e=YA()){return{CLAUDE_MEM_CLOUD_SYNC_TOKEN:t.setupToken,CLAUDE_MEM_CLOUD_SYNC_USER_ID:t.userId,CLAUDE_MEM_CLOUD_SYNC_HUB_URL:t.hubUrl,CLAUDE_MEM_CLOUD_SYNC_DEVICE_ID:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_NAME:e}}function ZA(t,e=YA()){let r=ob(t,e);return t.memory?{...r,CLAUDE_MEM_PRO_TRIAL_STATE:"active",CLAUDE_MEM_PRO_TRIAL_ENDS_AT:t.trialEndsAt??"",CLAUDE_MEM_PRO_PLAN:t.plan,CLAUDE_MEM_PRO_MEMORY_KEY:t.memory.memoryKey,CLAUDE_MEM_PRO_MEMORY_BASE_URL:t.memory.memoryBaseUrl,CLAUDE_MEM_PRO_MEMORY_MODEL:t.memory.memoryModel,CLAUDE_MEM_PRO_FALLBACK_AT:""}:r}function zV(t){if(!t||typeof t!="object")return null;let e=t,r=Pr(e.user_id),i=Pr(e.setup_token),n=Pr(e.hub_url);if(e.status!=="ready"||!r||!i||!n)return null;let o=Pr(e.memory_key);return{userId:r,setupToken:i,hubUrl:n,memory:o?{memoryKey:o,memoryBaseUrl:Pr(e.memory_base_url)??Tg,memoryModel:Pr(e.memory_model)??Oc}:null,plan:e.plan==="trial"||e.plan==="pro"||e.plan==="none"||e.plan==="teambrain_seat"?e.plan:"trial",trialEndsAt:Pr(e.trial?.ends_at),team:C0(e.team),teambrainUrl:Pr(e.teambrain_url)}}function qV(t){let e=kn(t.message)||U_e[t.reason]||"cmem.ai refused the join.",r=kn(t.reason);return`Could not join the team: ${e}${r&&r!=="unknown"?` (${r})`:""}`}async function F_e(t){let e=new AbortController,r=setTimeout(()=>e.abort(),N_e);try{let i=await fetch(HJ,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pairing_id:t.pairingId,secret:t.secret}),signal:e.signal}),n=await i.json().catch(()=>({}));if(n.status==="join_failed")return{kind:"join_failed",reason:Pr(n.reason)??"unknown",message:Pr(n.error)};if(i.status===404||i.status===410)return{kind:"gone"};if(i.status===202)return{kind:"pending",stage:n.stage==="awaiting_checkout"||n.stage==="awaiting_approval"?n.stage:"awaiting_login"};if(i.ok&&n.status==="authenticated"){let o=Pr(n.user_id);return o?{kind:"authenticated",userId:o}:{kind:"unreachable"}}if(i.ok){let o=zV(n);return o?{kind:"ready",...o}:{kind:"unreachable"}}return{kind:"unreachable"}}catch{return{kind:"unreachable"}}finally{clearTimeout(r)}}function J_e(t,e){return new Promise(r=>{let i=Date.now(),n=setInterval(()=>{(e()||Date.now()-i>=t)&&(clearInterval(n),r())},250)})}async function uf(t,e,r){let i=Date.now(),n=e==="teambrain_join"?"Run npx claude-mem teambrain join again":"Run the installer again",o={awaiting_login:e==="teambrain_join"?"Waiting for you to sign in in the browser\u2026":"Waiting for OAuth login in the browser\u2026",awaiting_checkout:e==="login"?"Waiting for the browser to finish signing you in\u2026":e==="teambrain_join"?"Waiting for the browser to finish joining the team\u2026":"Waiting for CMEM Pro setup in the browser\u2026",awaiting_approval:e==="teambrain_join"?`Approve this device on the page (code ${t.userCode}) to join the team\u2026`:`Enter code ${t.userCode} in the browser to approve this device\u2026`},s=e==="enrollment"?"awaiting_checkout":"awaiting_login";M.info(o[s]);let a=!1,l=f=>{(typeof f=="string"?f.includes(""):f.includes(3))&&(a=!0)},c=()=>{a=!0},u=process.stdin.isTTY===!0,d=process.stdin.isRaw===!0,p=!1;u&&(process.stdin.on("data",l),d||(process.stdin.setRawMode(!0),p=!0),process.stdin.resume()),process.on("SIGINT",c);try{let f=0,m=t.expiresAt??i+L_e;for(;Date.now()<m;){if(a)return null;let h=await F_e(t);if(a)return null;if(h.kind==="authenticated"&&e==="login"||h.kind==="ready")return h;if(h.kind==="join_failed")return M.error(qV(h)),null;if(h.kind==="gone")return M.error(`This browser authorization expired. ${n}.`),null;if(h.kind==="unreachable"){if(f+=1,f>=3)return M.error(`cmem.ai is not responding. ${n} when it is reachable.`),null}else f=0,h.kind==="pending"&&h.stage!==s&&(s=h.stage,M.info(o[s]));await J_e(t.pollIntervalMs,()=>a)}return e!=="teambrain_join"&&await xr("installer_oauth_timeout",{version:r,phase:e,duration_ms:Date.now()-i}),M.error(`Browser authorization timed out. ${n}.`),null}finally{process.off("SIGINT",c),u&&(process.stdin.off("data",l),p&&process.stdin.setRawMode(!1),process.stdin.pause())}}async function WV(t,e){let r=await uf(t,"login",e);if(!r)return!1;if(r.kind==="ready"){if(!zt(ZA(r)))return!1;t.delivered=r}return M.success("OAuth login complete."),await xr("installer_oauth_completed",{version:e}),r.kind==="authenticated"||r.kind==="ready"}async function sb(t){!Ae||process.stdin.isTTY!==!0||(M.info(t),await new Promise(e=>{let r=process.stdin.isRaw===!0,i=!1,n=()=>{process.stdin.off("data",o),i&&process.stdin.setRawMode(!1),process.stdin.pause(),e()},o=s=>{let a=typeof s=="string"?s:s.toString("utf8");(a.includes("\r")||a.includes(`
@@ -912,7 +912,7 @@ ${i.map(s=>yb(s,!1)).join(`
912
912
  ${i.map(s=>yb(s,!1)).join(`
913
913
  `)}`),null)}function z6(t){let e=T0(t);return e||M.error("This install has not joined a TeamBrain team. Join one: npx claude-mem teambrain join <invite-link> (or start one: npx claude-mem teambrain start)"),e}function _C(t){try{return t()}catch(e){if(e instanceof Error&&String(e.code??"").startsWith("ERR_PARSE_ARGS"))return console.error(On("red",e.message)),console.error(mb),null;throw e}}async function dke(t){let e=_C(()=>vC({args:t,options:{share:{type:"string"},"share-all":{type:"boolean"}},allowPositionals:!0,strict:!0}));if(!e)return 1;let r=P6(e.positionals[0]);if(!r.ok)return M.error(r.error),1;let i=EC({share:e.values.share,shareAll:e.values["share-all"]===!0});if(!i.ok)return M.error(i.error),1;let n=gb();if(n)return M.error(bC(n,"the join")),1;let o=await mu({source:"teambrain_join",teamInvite:r.token});if(!o)return M.error(ike()),1;M.info(`Sign in, then approve this device on the page to join the team: ${o.authorizationUrl}`),ab(o,"Approving this device on the page, which names the team, joins it."),hb?(await sb("Hit return to open it in your browser\u2026"),$s(o.authorizationUrl)):M.info("AGENT: show this link to the user. This command waits until they approve this device.");let s=await uf(o,"teambrain_join",Xwe);if(!s||s.kind!=="ready")return 1;let a=gb();if(a)return M.error(bC(a,"the join")),1;let l=rke(),c=vb(),u=N6([l.CLAUDE_MEM_CLOUD_SYNC_USER_ID,c.CLAUDE_MEM_CLOUD_SYNC_USER_ID],s.userId);if(u)return M.error(u),1;let d=L6(s.teambrainUrl);if(!d.ok)return M.error(d.error),1;let p={teambrainUrl:d.url,syncToken:s.setupToken,syncUserId:s.userId,teamId:s.team?.id??""},f=s.team,m=null;if(!f){let S=await B6(p,void 0);if(!S)return 1;f=S.team,m=S.team,p.teamId=f.id}let h=nke(c,s),y=K6(j6(s,l,{teambrainUrl:p.teambrainUrl,teamId:f.id}));if(y)return M.error(`${y}. ${f.name} counts you as a member, but this install did not save the connection; fix the file and run the join again.`),1;M.success(`Joined ${f.name}. Your memory stays private; you choose what the team sees.`);let E=i.choice??(hb?await U6(f.name,m):null);if(E){if(!await F6(p,f,E))return 1}else M.info("Not sharing any projects yet. Choose them with: npx claude-mem teambrain share");return h&&await J6(!0),M.info("Your next session starts with the team brief, and agents can use the team_search tool. Check anytime: npx claude-mem teambrain status"),0}async function pke(t){let e=_C(()=>vC({args:t,options:{share:{type:"string"},"share-all":{type:"boolean"},team:{type:"string"}},allowPositionals:!1,strict:!0}));if(!e)return 1;let r=EC({share:e.values.share,shareAll:e.values["share-all"]===!0});if(!r.ok)return M.error(r.error),1;if(!r.choice&&!hb)return M.error("Without a terminal, name what to share: npx claude-mem teambrain share --share <a,b> (or --share-all)"),1;let i=z6(vb());if(!i)return 1;let n=await B6(i,e.values.team);if(!n)return 1;let o=r.choice??await U6(n.team.name,n.team);return o?await F6(i,n.team,o)?0:1:(M.info("Nothing changed."),0)}async function fke(){let t=T0(vb());if(!t)return console.log(`${On("bold","TeamBrain:")} not joined on this install`),console.log(` Start a team: ${On("cyan","npx claude-mem teambrain start")}`),console.log(` Join a team: ${On("cyan","npx claude-mem teambrain join <invite-link>")}`),0;console.log(`${On("bold","TeamBrain:")} ${Nt(t.teambrainUrl)}`);let e=await vp(t,bu);if(!e.ok)return console.error(On("red",`Could not read your teams: ${e.reason}`)),1;if(e.value.length===0)return console.log(" This account is not in a team. Join one: npx claude-mem teambrain join <invite-link>"),0;for(let r of e.value)console.log(yb(r,r.id===t.teamId));return console.log(On("dim","Change what you share: npx claude-mem teambrain share")),0}async function mke(t,e,r){let i=!t.teamId||t.teamId===e,n=await vp(t,bu),o=l=>{let c=K6(l);return c&&M.error(`${c}. The team was left on cmem.ai, but this install still points at it; fix the file and run leave again.`),!c};if(!n.ok)return M.warn(`Could not read which teams this account is still in: ${n.reason}`),i?o(yC)?(M.info("Cleared CLAUDE_MEM_TEAMBRAIN_URL and CLAUDE_MEM_TEAMBRAIN_TEAM_ID on this install. Cloud sync settings were not changed. To use another team you are in, join it again with its invite link."),0):1:(M.info("Nothing on this install changed: it stays connected to its own team. Cloud sync settings were not changed."),0);let s=n.value;if(s.length>0){if(i){if(!o({CLAUDE_MEM_TEAMBRAIN_TEAM_ID:s[0].id}))return 1;M.info(`This install now uses ${s[0].name}.`)}return M.info(`Still in: ${s.map(l=>l.name).join(", ")}. Cloud sync settings were not changed.`),0}let a=r.CLAUDE_MEM_PRO_PLAN.trim()==="teambrain_seat";return o(a?{...yC,...tke}:yC)?(M.info("This account is in no team now, so TeamBrain is off on this install (CLAUDE_MEM_TEAMBRAIN_URL and CLAUDE_MEM_TEAMBRAIN_TEAM_ID cleared)."),a?(M.info("Cloud sync is off for this install too: a TeamBrain seat was its only sync access (CLAUDE_MEM_CLOUD_SYNC_* cleared). Your memory stays on this machine."),await J6(!1),0):(M.info("Cloud sync settings were not changed."),0)):1}async function hke(t){let e=_C(()=>vC({args:t,options:{},allowPositionals:!0,strict:!0}));if(!e)return 1;let r=gb();if(r)return M.error(bC(r,"leave")),1;let i=vb(),n=z6(i);if(!n)return 1;let o=await vp(n,bu);o.ok||M.warn(`Could not read your teams before leaving: ${o.reason}`);let s=o.ok?o.value:null,a=e.positionals[0]?.trim()??"",l=a||n.teamId||(s?.length===1?s[0].id:"");if(!l)return M.error(o.ok?"Name the team to leave: npx claude-mem teambrain leave <team-id> (see npx claude-mem teambrain status)":"Name the team to leave: npx claude-mem teambrain leave <team-id>"),1;let c=s?.find(d=>d.id===l),u=c?.name??`team ${Nt(l)}`;if(s&&!c){if(a)return M.error(`This account is not in team ${Nt(l)}.${s.length>0?` Its teams:
914
914
  ${s.map(d=>yb(d,!1)).join(`
915
- `)}`:""}`),1;M.info(`This account is no longer in ${u}; removing it from this install.`)}else{if(hb){let p=await Ii({message:`Leave ${u}? TeamBrain removes what you shared with it.`,initialValue:!1});if(At(p)||!p)return M.info("Still in the team. Nothing changed."),0}let d=await u2(n,l,bu);if(!d.ok)return M.error(`Could not leave ${u}: ${d.reason}`),1;M.success(`Left ${u}.`)}return mke(n,l,i)}function gke(){let t=d2(Zi()),e=!process.stdout.isTTY||!!process.env.CI||!!(process.env.SSH_CONNECTION||process.env.SSH_TTY)||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY;return console.log(`Create your team's TeamBrain: ${On("cyan",t)}`),e?console.log("Open that link in a browser to continue."):$s(t),0}async function yke(t=[]){let e=t[0]?.toLowerCase()??"status";if(t.slice(1).some(r=>r==="--help"||r==="-h"))return console.log(mb),0;switch(e){case"join":return dke(t.slice(1));case"start":return gke();case"status":return fke();case"share":return pke(t.slice(1));case"leave":return hke(t.slice(1));case"help":case"--help":case"-h":return console.log(mb),0;default:return console.error(On("red",`Unknown teambrain command: ${Nt(e)}`)),console.error(mb),1}}var Xwe,hb,bu,bb,O6,Qwe,eke,gC,R6,tke,yC,mb,W6=v(()=>{"use strict";cp();ct();Cc();Ra();we();yp();Ut();qn();C6();O0();Yn();me();Qd();df();Xwe="15.8.0",hb=process.stdin.isTTY===!0,bu=15e3,bb=5e3,O6=3e4,Qwe=1e3,eke=40,gC="__teambrain_all_projects__",R6=/^[A-Za-z0-9_-]{16,128}$/,tke={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:"",CLAUDE_MEM_PRO_PLAN:""},yC={CLAUDE_MEM_TEAMBRAIN_URL:"",CLAUDE_MEM_TEAMBRAIN_TEAM_ID:""},mb=[`Usage: ${On("bold","npx claude-mem teambrain <command>")}`," join <invite-link> Join a team: sign in, approve this device on the page, then choose which projects to share"," (without a terminal: --share <a,b> or --share-all)"," start Create a team on cmem.ai (opens the browser)"," status Show your teams and what this install shares (the default)"," share Choose again which projects you share (--share <a,b>, --share-all, --team <id>)"," leave [team-id] Leave a team; TeamBrain removes what you shared with it"].join(`
915
+ `)}`:""}`),1;M.info(`This account is no longer in ${u}; removing it from this install.`)}else{if(hb){let p=await Ii({message:`Leave ${u}? TeamBrain removes what you shared with it.`,initialValue:!1});if(At(p)||!p)return M.info("Still in the team. Nothing changed."),0}let d=await u2(n,l,bu);if(!d.ok)return M.error(`Could not leave ${u}: ${d.reason}`),1;M.success(`Left ${u}.`)}return mke(n,l,i)}function gke(){let t=d2(Zi()),e=!process.stdout.isTTY||!!process.env.CI||!!(process.env.SSH_CONNECTION||process.env.SSH_TTY)||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY;return console.log(`Create your team's TeamBrain: ${On("cyan",t)}`),e?console.log("Open that link in a browser to continue."):$s(t),0}async function yke(t=[]){let e=t[0]?.toLowerCase()??"status";if(t.slice(1).some(r=>r==="--help"||r==="-h"))return console.log(mb),0;switch(e){case"join":return dke(t.slice(1));case"start":return gke();case"status":return fke();case"share":return pke(t.slice(1));case"leave":return hke(t.slice(1));case"help":case"--help":case"-h":return console.log(mb),0;default:return console.error(On("red",`Unknown teambrain command: ${Nt(e)}`)),console.error(mb),1}}var Xwe,hb,bu,bb,O6,Qwe,eke,gC,R6,tke,yC,mb,W6=v(()=>{"use strict";cp();ct();Cc();Ra();we();yp();Ut();qn();C6();O0();Yn();me();Qd();df();Xwe="15.8.1",hb=process.stdin.isTTY===!0,bu=15e3,bb=5e3,O6=3e4,Qwe=1e3,eke=40,gC="__teambrain_all_projects__",R6=/^[A-Za-z0-9_-]{16,128}$/,tke={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:"",CLAUDE_MEM_PRO_PLAN:""},yC={CLAUDE_MEM_TEAMBRAIN_URL:"",CLAUDE_MEM_TEAMBRAIN_TEAM_ID:""},mb=[`Usage: ${On("bold","npx claude-mem teambrain <command>")}`," join <invite-link> Join a team: sign in, approve this device on the page, then choose which projects to share"," (without a terminal: --share <a,b> or --share-all)"," start Create a team on cmem.ai (opens the browser)"," status Show your teams and what this install shares (the default)"," share Choose again which projects you share (--share <a,b>, --share-all, --team <id>)"," leave [team-id] Leave a team; TeamBrain removes what you shared with it"].join(`
916
916
  `)});function bke(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function vke(t){if(!t)return G6;let e=bke(t);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:G6}function ao(t){return typeof t!="string"?null:vke(t)}var G6,Eb=v(()=>{"use strict";G6="claude"});import{existsSync as Eke,readFileSync as Ske}from"fs";function V6(t){return new RegExp(`${t}${pl}`,"gi")}function wb(t){return`(?<=${t}${fl}${Bo}[=:]${Bo}${fl})`}function kC(t,e){if(!e.enabled||t.length===0)return{redacted:t,counts:{},oversize:!1};if(t.length>Ake)return b.warn("REDACT","field exceeds the 1M-char redaction cap; replaced by an oversize marker",void 0,{inputLength:t.length}),{redacted:Cke,counts:{oversize:1},oversize:!0};let r=new Set(e.disabledBuiltinPatterns??[]),i={},n=t,o=[];for(let a of e.customPatterns??[]){if(!a.name||a.name.length===0){b.warn("REDACT","custom pattern skipped: missing name",void 0,{pattern:a});continue}try{o.push({name:a.name,regex:new RegExp(a.regex,"g")})}catch(l){b.warn("REDACT","custom pattern skipped: invalid regex",{name:a.name},l instanceof Error?l:new Error(String(l)))}}let s=[...o,...xke,...e.genericEnabled?Tke:[]];for(let a of s)r.has(a.name)||(a.regex.lastIndex=0,n=n.replace(a.regex,()=>(i[a.name]=(i[a.name]??0)+1,`<redacted type='${a.name}'/>`)));return e.logMatches&&Object.keys(i).length>0&&b.debug("REDACT","patterns matched",void 0,{counts:i}),{redacted:n,counts:i,oversize:!1}}function Oke(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"):(b.warn("REDACT","CLAUDE_MEM_REDACT_CUSTOM_PATTERNS is not a JSON array, ignoring"),[])}catch(e){return b.warn("REDACT","failed to parse CLAUDE_MEM_REDACT_CUSTOM_PATTERNS as JSON",void 0,e instanceof Error?e:new Error(String(e))),[]}}function Rke(t){return{enabled:t.CLAUDE_MEM_REDACT_ENABLED==="true",disabledBuiltinPatterns:(t.CLAUDE_MEM_REDACT_DISABLED_BUILTINS??"").split(",").map(e=>e.trim()).filter(Boolean),customPatterns:Oke(t.CLAUDE_MEM_REDACT_CUSTOM_PATTERNS??"[]"),logMatches:t.CLAUDE_MEM_REDACT_LOG_MATCHES==="true",genericEnabled:t.CLAUDE_MEM_REDACT_GENERIC_ENABLED==="true"}}function Nke(t){if(!Eke(t))return null;try{return Ske(t,"utf-8")}catch{return""}}function Lke(t){if(t===null)return!1;try{let e=JSON.parse(Wi(t));return e===null||typeof e!="object"||Array.isArray(e)}catch{return!0}}function jke(t,e,r){return process.env.CLAUDE_MEM_REDACT_ENABLED==="false"||!(hf?.enabled===!0||Dke.test(e))?r:(Y6||(Y6=!0,b.warn("REDACT","settings.json could not be read; secret redaction stays on until it is repaired",{settingsPath:t,using:hf?.enabled?"the last configuration that loaded":"the built-in patterns"})),hf?.enabled?hf:Pke)}function IC(t=fe){let e=Date.now();if(mf&&e-H6<Mke)return mf;let r=he.loadFromFile(t),i=Rke(r),n=i.enabled?null:Nke(t);return Lke(n)?mf=jke(t,n,i):(mf=i,hf=i),H6=e,mf}function Fke(t,e,r){if(!r.genericEnabled)return null;let i=Kke.test(t)?"generic_password":$ke.test(t)?"generic_token":null;return!i||r.disabledBuiltinPatterns?.includes(i)||!Uke.test(e)||!/[A-Za-z]/.test(e)?null:`<redacted type='${i}'/>`}function zke(t,e,r){if(!r.genericEnabled||r.disabledBuiltinPatterns?.includes("bearer_token")||!Jke.test(t))return null;let i=Bke.exec(e);return i?`${i[1]}<redacted type='bearer_token'/>${e.slice(i[0].length)}`:null}function Gke(t,e,r){return r.disabledBuiltinPatterns?.includes("aws_session_token")||!qke.test(t)||!Wke.test(e)?null:"<redacted type='aws_session_token'/>"}function Yke(t,e,r){return r.disabledBuiltinPatterns?.includes("aws_secret_key")||!Vke.test(t)||!Hke.test(e)?null:"<redacted type='aws_secret_key'/>"}function Z6(t,e=IC()){if(!e.enabled)return t;let r=(i,n)=>{if(typeof i=="string"){let o=kC(i,e);return n===void 0||Object.keys(o.counts).length>0?o.redacted:Gke(n,i,e)??Yke(n,i,e)??zke(n,i,e)??Fke(n,i,e)??o.redacted}return Array.isArray(i)?i.map(o=>r(o)):i!==null&&typeof i=="object"?Object.fromEntries(Object.entries(i).map(([o,s])=>[o,r(s,o)])):i};return r(t)}var gf,pl,fl,Bo,Sb,_b,wC,_ke,wke,kke,Ike,xke,Tke,Ake,Cke,mf,H6,Mke,hf,Y6,Pke,Dke,Kke,$ke,Uke,Jke,Bke,qke,Wke,Vke,Hke,xC=v(()=>{"use strict";me();Ut();we();ct();gf=String.raw`[A-Za-z0-9_.\-+/=~@#$%^*!?]`,pl=`(?=${gf}{8})${gf}*[A-Za-z]${gf}*`,fl=String.raw`(?:\\{0,3}["'])?`,Bo=String.raw`\s{0,8}`;Sb=String.raw`(?:token|secret|api_key)`,_b=String.raw`\\{0,3}["']`,wC=String.raw`(?<!\\)"`,_ke=String.raw`(?:^|[\s?&]|\\[nrt]|${wC})`,wke=String.raw`(?:^|\n|\\n|${wC})[ \t]{0,8}(?:-[ \t]{1,8})?`,kke=String.raw`(?:${_b})?[ \t]{0,8}(?:$|\r?\n|\\{1,3}[rn]|#|${wC})`,Ike=new RegExp([`${wb(String.raw`\b\w*_${Sb}`)}${pl}`,`(?<=${_b}${Sb}${_b}${Bo}:${Bo}${_b})${pl}`,`(?<=${_ke}${Sb}=${fl})${pl}(?!\\(|${gf})`,String.raw`(?<=--(?:token|secret|api[-_]key)(?:=|[ \t]{1,8})${fl})${pl}`,`(?<=${wke}${Sb}:[ \\t]{1,8}${fl})${pl}(?=${kke})`].join("|"),"gi"),xke=[{name:"url_credentials",regex:/(?<=\b[a-z][a-z0-9+.-]*:\/\/[^\s:\/@'"<>]*:)(?![${<])[^\s\/@'"<>]+(?=@)/gi},{name:"aws_access_key",regex:/(?:AKIA|ASIA)[0-9A-Z]{16}/g},{name:"aws_secret_key",regex:new RegExp(`${wb(String.raw`(?:aws_secret_access_key|\bSecretAccessKey)`)}[A-Za-z0-9/+=]{40}`,"gi")},{name:"aws_session_token",regex:new RegExp(`${wb(String.raw`\b(?:aws_session_token|SessionToken)`)}[A-Za-z0-9/+=]{100,}`,"gi")},{name:"github_pat",regex:/\bgh[oprsu]_[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,}(?!\w)/g},{name:"anthropic_key",regex:/\bsk-ant-[A-Za-z0-9_-]{20,}(?!\w)/g},{name:"slack_token",regex:/\b(?:xox[abeprs]|xapp)-[A-Za-z0-9-]{10,}(?!\w)/g},{name:"jwt",regex:/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+(?!\w)/g},{name:"private_key_pem",regex:/-----BEGIN (?:RSA |DSA |EC |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY(?: BLOCK)?-----[\s\S]*?-----END (?:RSA |DSA |EC |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY(?: BLOCK)?-----/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}(?!\w)/g},{name:"gitlab_token",regex:/\bglpat-[A-Za-z0-9_-]{20,}(?:\.[A-Za-z0-9_-]+)*(?!\w)/g},{name:"huggingface_token",regex:/\bhf_[A-Za-z0-9]{30,}\b/g},{name:"npm_token",regex:/\bnpm_[A-Za-z0-9]{36}\b/g},{name:"claude_mem_key",regex:/\bcmem_[A-Za-z0-9_-]{32,}|\bcm_pro_[A-Za-z0-9_-]{8,}/g}],Tke=[{name:"generic_password",regex:V6(wb(String.raw`\b(?:\w*_?(?:password|passwd)|\w+_pwd)`))},{name:"generic_token",regex:Ike},{name:"bearer_token",regex:V6(`(?<=\\bAuthorization${fl}${Bo}:${Bo}${fl}Bearer${Bo})`)}],Ake=1024*1024,Cke="<redacted type='oversize'/>";mf=null,H6=0,Mke=5e3,hf=null,Y6=!1,Pke={enabled:!0,disabledBuiltinPatterns:[],customPatterns:[],logMatches:!1},Dke=/"CLAUDE_MEM_REDACT_ENABLED"\s*:\s*"true"/;Kke=/(?:password|passwd)$|\w_pwd$/i,$ke=/(?:^|_)(?:secret|token|api_key)$/i,Uke=new RegExp(`^${gf}{8,}$`);Jke=/^authorization$/i,Bke=new RegExp(`^(${Bo}Bearer${Bo})${pl}`,"i");qke=/^(?:aws_session_token|SessionToken)$/i,Wke=/^[A-Za-z0-9/+=]{100,}$/;Vke=/^(?:aws_secret_access_key|SecretAccessKey)$/i,Hke=/^[A-Za-z0-9/+=]{40}$/});function Xke(t){let e=Object.fromEntries(t4.map(u=>[u,0]));if(!t.includes("<"))return{text:t,counts:e,total:0};let r=t.length,i=new Int32Array(r+1);i[r]=r;for(let u=r-1;u>=0;u--)i[u]=t.charCodeAt(u)===62?u:i[u+1];let n=new Map,o=[],s=0,a=0;for(;a<r;){if(t.charCodeAt(a)!==60){a+=1;continue}Q6.lastIndex=a;let u=Q6.exec(t);if(u){let p=u[1],f=n.get(p),m=f&&f.head<f.items.length?f.items[f.head]:void 0;m&&a>=m.attrEnd&&(f.head+=1,o.push([m.start,a+u[0].length]),e[p]+=1,s+=1),a+=u[0].length;continue}X6.lastIndex=a;let d=X6.exec(t);if(d&&Zke.has(d[1])){let p=d[1],f=a+d[0].length,m={start:a,attrEnd:i[f]},h=n.get(p);h?h.items.push(m):n.set(p,{items:[m],head:0}),a=f;continue}a+=1}o.sort((u,d)=>u[0]-d[0]);let l="",c=0;for(let[u,d]of o)u>c&&(l+=t.slice(c,u)),d>c&&(c=d);return l+=t.slice(c),{text:l,counts:e,total:s}}function Qke(t,{text:e,counts:r,total:i}){return i>e4&&b.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:i,maxAllowed:e4,contentLength:t.length}),{stripped:kC(e.trim(),IC()).redacted,counts:r}}function yf(t){let e=r=>{if(typeof r=="string"){let i=Xke(r);return i.total>0?Qke(r,i).stripped:r}return Array.isArray(r)?r.map(e):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).map(([i,n])=>[i,e(n)])):r};return e(t)}var t4,Zke,X6,Q6,e4,eIe,dXe,pXe,TC=v(()=>{"use strict";me();xC();t4=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],Zke=new Set(t4),X6=/<([A-Za-z_][A-Za-z0-9_-]*)/y,Q6=/<\/([A-Za-z_][A-Za-z0-9_-]*)\s*>/y;e4=100;eIe=["task-notification"],dXe=new RegExp(`^\\s*<(${eIe.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),pXe=256*1024});function r4(t){let e=ao(t.platformSource),r=e?[e]:[];return t.sourceEventId?`agent_event:v1:${Mi([t.teamId,t.projectId,t.sourceAdapter,...r,t.sourceEventId])}`:`agent_event:v1:${Mi([t.teamId,t.projectId,t.sourceAdapter,...r,t.contentSessionId??t.serverSessionId??null,t.eventType,new Date(t.occurredAt).toISOString(),af(t.payload??{})])}`}function AC(t){return{id:t.id,projectId:t.project_id,teamId:t.team_id,serverSessionId:t.server_session_id,sourceAdapter:t.source_adapter,sourceEventId:t.source_event_id,idempotencyKey:t.idempotency_key,eventType:t.event_type,platformSource:t.platform_source,payload:t.payload,metadata:Ot(t.metadata),occurredAtEpoch:Qe(t.occurred_at),receivedAtEpoch:Qe(t.received_at),createdAtEpoch:Qe(t.created_at)}}var bf,CC=v(()=>{"use strict";so();Eb();xC();TC();bf=class{constructor(e){this.client=e}client;async create(e){await Ri(this.client,e.projectId,e.teamId),e.serverSessionId&&await Uo(this.client,e.serverSessionId,e.projectId,e.teamId);let r=r4(e),i=ao(e.platformSource),n=await Se(this.client,`
917
917
  INSERT INTO agent_events (
918
918
  id, project_id, team_id, server_session_id, source_adapter,
package/dsh/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@claude-mem/dsh",
3
- "version": "15.8.0",
3
+ "version": "15.8.1",
4
4
  "private": true,
5
5
  "description": "First-party DeepSeek Harness memory integration, based on Bleed00/dsh-claude-mem",
6
6
  "type": "module",
@@ -3,7 +3,7 @@
3
3
  "name": "Claude-Mem (Persistent Memory)",
4
4
  "description": "OpenClaw plugin for Claude-Mem. Records observations from embedded runner sessions and streams them to messaging channels.",
5
5
  "kind": "memory",
6
- "version": "15.8.0",
6
+ "version": "15.8.1",
7
7
  "license": "Apache-2.0",
8
8
  "author": "thedotmack",
9
9
  "homepage": "https://claude-mem.ai",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "15.8.0",
3
+ "version": "15.8.1",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "keywords": [
6
6
  "claude",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "15.8.0",
3
+ "version": "15.8.1",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "author": {
6
6
  "name": "Alex Newman"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "15.8.0",
3
+ "version": "15.8.1",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "author": {
6
6
  "name": "Alex Newman",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "15.8.0",
3
+ "version": "15.8.1",
4
4
  "description": "Persistent memory and context compression for Qoder sessions.",
5
5
  "author": {
6
6
  "name": "Alex Newman",