claude-mem 15.5.0 → 15.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/.qoder-plugin/plugin.json +1 -1
- package/README.md +1 -1
- package/dist/npx-cli/index.js +2 -2
- package/dsh/package.json +1 -1
- package/openclaw/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/.codex-plugin/plugin.json +1 -1
- package/plugin/.qoder-plugin/plugin.json +1 -1
- package/plugin/package.json +1 -1
- package/plugin/scripts/mcp-server.cjs +2 -2
- package/plugin/scripts/server-service.cjs +2 -2
- package/plugin/scripts/transcript-watcher.cjs +20 -20
- package/plugin/scripts/worker-service.cjs +346 -346
- package/plugin/scripts/worker-service.cjs.map +2 -2
- package/plugin/ui/work-view/assets/index-DLew0mNr.js +89 -0
- package/plugin/ui/work-view/assets/{setup-page-julZevIR.js → setup-page-CQrNfTDX.js} +2 -2
- package/plugin/ui/work-view/assets/{setup-sample-CziYgQNA.js → setup-sample-opUnQkqx.js} +1 -1
- package/plugin/ui/work-view/index.html +1 -1
- package/plugin/ui/work-view/assets/index-CpKMegdC.js +0 -84
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.
|
|
62
|
+
<img src="https://img.shields.io/badge/version-15.6.0-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">
|
package/dist/npx-cli/index.js
CHANGED
|
@@ -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){pk=e}error(e,r,i,n){this.log(3,e,r,i,n),this.routeErrorToSink(r,i,n)}routeErrorToSink(e,r,i){try{if(!pk||!(i instanceof Error))return;pk(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 mk});function CK(t=process.env){let e=Number.parseInt(t.CLAUDE_MEM_WEDGED_WORKER_UPTIME_S??"",10);return Number.isFinite(e)&&e>=AK.min&&e<=AK.max?e:Ase}function OK(t=process.platform){return t==="win32"?8e3:5e3}function hk(t=process.platform){return Kt.SESSION_INIT_HOOK_CAP-OK(t)}function To(t){return process.platform==="win32"?Math.round(t*Kt.WINDOWS_MULTIPLIER):t}var Kt,Ase,AK,Ta=v(()=>{"use strict";Kt={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},Ase=300,AK={min:60,max:86400}});var RK=v(()=>{"use strict"});function MK(t){try{return new URL(t).hostname.toLowerCase()==="openrouter.ai"}catch{return!1}}var PK=v(()=>{"use strict";ye()});import{readFileSync as Cse,existsSync as DK,writeFileSync as Ose}from"fs";import{basename as Rse,dirname as Mse,join as gh}from"path";import{homedir as NK,hostname as Pse}from"os";function $se(t){return typeof t=="boolean"?String(t):t}function Use(t){let e=t.CLAUDE_MEM_OPENROUTER_MODEL;if(typeof e!="string"||!Kse.has(e.trim()))return!1;let r=typeof t.CLAUDE_MEM_OPENROUTER_BASE_URL=="string"?t.CLAUDE_MEM_OPENROUTER_BASE_URL.trim():"";return r===""||MK(r)}function $K(t,e){return gh(Mse(t),`.${Rse(t)}.${e.markerTag}`)}function gk(t,e){try{Ose($K(t,e),new Date().toISOString(),{encoding:"utf-8",mode:384})}catch{}}function Fse(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===Nse||r===Lse)return jse}catch{return null}return null}var Dse,Nse,Lse,jse,Kse,LK,jK,KK,me,$t=v(()=>{"use strict";Ta();ct();PK();qn();uc();Dse="security_alert",Nse="sync-hub.black-pond-afbb.workers.dev",Lse="ziczmqtpmaxbornfghye.supabase.co",jse="https://sync.cmem.ai",Kse=new Set(["xiaomi/mimo-v2-flash:free"]);LK=18e4,jK=[{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"}];KK=new Set;me=class{static DEFAULTS={CLAUDE_MEM_MEMORY_SEARCH_HOOK_ENABLED:"true",CLAUDE_MEM_MEMORY_INSTRUCTIONS_ENABLED:"true",CLAUDE_MEM_MEMORY_WATCH_ROOTS:"",CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_SESSION_START_INCLUDE_ALL_SOURCES:"false",CLAUDE_MEM_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(To(Kt.API_REQUEST)),CLAUDE_MEM_SESSION_INIT_TIMEOUT_MS:String(hk()),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_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:gh(NK(),".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:gh(NK(),".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:Pse(),CLAUDE_MEM_CLOUD_SYNC_WS:"true",CLAUDE_MEM_CLOUD_SYNC_CONTENT_BATCH_SIZE:"40",CLAUDE_MEM_CLOUD_SYNC_REQUEST_TIMEOUT_MS:"90000",CLAUDE_MEM_TEAMBRAIN_URL:"",CLAUDE_MEM_TEAMBRAIN_TEAM_ID:"",CLAUDE_MEM_LLM_TIMEOUT_MS:String(LK),CLAUDE_MEM_FIELD_OPTIMIZE_TIMEOUT_MS:String(LK),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_WORKER_AUTOSTART:"true",CLAUDE_MEM_PROJECT_NAME_SOURCE:"path"};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){let r=process.env[e]??this.DEFAULTS[e];return e==="CLAUDE_MEM_WORKER_HOST"?this.normalizeWorkerHost(r):r}static normalizeWorkerHost(e){return e==="localhost"?"127.0.0.1":e}static finalizeSettings(e,r){let 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=gh(Fr(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(!DK(e)){let p=this.getAllDefaults();if(!i.readOnly)try{Ue(e,p,{mode:384});for(let f of jK)gk(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=Cse(e,"utf-8"),o=wr(n),s=vn(o),a=s!==o,l=ak(o),c=a&&Object.keys(l).some(p=>p!=="env");if(a&&!c&&!i.readOnly)try{Ue(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===Dse&&(s={...s,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES},!i.readOnly))try{Ue(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(Use(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{Ue(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=Fse(s.CLAUDE_MEM_CLOUD_SYNC_HUB_URL);if(u!==null&&(s={...s,CLAUDE_MEM_CLOUD_SYNC_HUB_URL:u},!i.readOnly))try{Ue(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 jK)if(!DK($K(e,p))){if(s[p.key]!==p.legacy){i.readOnly||gk(e,p);continue}if(s={...s,[p.key]:this.DEFAULTS[p.key]},!i.readOnly)try{Ue(e,c?{...l,env:s}:s,{mode:384}),gk(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}`;KK.has(m)||(KK.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]=$se(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 yk(){return yh!==null||(yh=me.loadFromFile(fe)),yh}var yh,bk=v(()=>{"use strict";$t();_e();yh=null});function pc(t){return(t.CLAUDE_MEM_WORKER_AUTOSTART??"true").trim().toLowerCase()==="false"}var bh=v(()=>{"use strict"});var UK=v(()=>{"use strict"});function Wn(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}var vk=v(()=>{"use strict"});var vh,FK=v(()=>{"use strict";vh=class extends Error{timeoutMs;constructor(e){super(`Request timed out after ${e}ms`),this.name="WorkerRequestTimeoutError",this.timeoutMs=e}}});import{spawn as Jse,spawnSync as BK}from"node:child_process";import{existsSync as Bse}from"node:fs";import{dirname as zse,extname as Eh,join as zK}from"node:path";function vi(t,e,r){return Jse(t,e??[],{...r,windowsHide:!0})}function Wse(t){return`"${t.replace(/"/g,'""')}"`}function JK(t){return qK.has(Eh(t).toLowerCase())}function Gse(t=process.env){let e=t.SystemRoot||t.SYSTEMROOT||t.windir||t.WINDIR||"C:\\Windows";return zK(e,"System32","where.exe")}function Sk(t){if(process.platform!=="win32")return[];try{let e=BK(Gse(),[t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0});return e.status!==0||!e.stdout.trim()?[]:e.stdout.split(/\r?\n/).map(r=>r.trim()).filter(Boolean).filter(r=>Bse(r))}catch{return[]}}function Yse(t,e){let r=t.find(JK);if(r)return r;let i=t.find(n=>Ek.has(Eh(n).toLowerCase()));if(i&&e){let n=e(i);if(n&&JK(n))return n}return i??t.find(n=>qse.has(Eh(n).toLowerCase()))??t[0]??null}function Zse(t,e,r=Hse){if(!/[\\/]volta[\\/]bin[\\/]/i.test(e))return null;try{let i=r(zK(zse(e),"volta.exe"),["which",t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:Vse,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 Yse(Sk(t),e=>Zse(t,e))}function Xse(t,e,r=process.platform){if(r==="win32"&&Ek.has(Eh(t).toLowerCase())){let i=[t,...e].map(Wse).join(" ");return{command:process.env.ComSpec??"cmd.exe",args:["/d","/s","/c",`"${i}"`],windowsVerbatimArguments:!0}}return{command:t,args:[...e],windowsVerbatimArguments:!1}}function kr(t,e,r,i=process.platform){let n={...r,...i==="win32"?{windowsHide:!0}:{}},o=Xse(t,e,i);return{command:o.command,args:o.args,options:o.windowsVerbatimArguments?{...n,windowsVerbatimArguments:!0}:n}}var Ek,qK,qse,Vse,Hse,nn=v(()=>{"use strict";Ek=new Set([".cmd",".bat"]),qK=new Set([".exe",".com"]),qse=new Set([...qK,...Ek]);Vse=5e3,Hse=(t,e,r)=>BK(t,e,r)});function ur(t=process.env){let e={};for(let[r,i]of Object.entries(t))if(i!==void 0){if(rae.has(r)){e[r]=i;continue}eae.has(r)||Qse.some(n=>r.startsWith(n))||(e[r]=i)}return e}var Qse,eae,tae,rae,cs=v(()=>{"use strict";Qse=["CLAUDECODE_","CLAUDE_CODE_"],eae=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),tae=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"]),rae=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",...tae])});import{spawnSync as GK}from"child_process";import{readFileSync as nae}from"fs";function VK(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 oae(t){_k+=1;let e=GK("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 VK("powershell-cim",t,e)}function sae(t,e=!1){if(!e){let i=WK.get(t);if(i&&(t===process.pid||Date.now()-i.capturedAtMs<iae))return i.token}let r=null;try{r=oae(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)&&WK.set(t,{token:r,capturedAtMs:Date.now()}),r}function HK(t,e){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux"){_k+=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 sae(t,e);_k+=1;try{let r=GK("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...ur(process.env),LC_ALL:"C",LANG:"C"}});return VK("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 Gi(t){return HK(t,!1)}function Ei(t,e){if(e===null)return!0;let r=HK(t,!0);return r===null?!0:r===e}var iae,WK,_k,Sh=v(()=>{"use strict";ye();cs();iae=5e3,WK=new Map,_k=0});import{execFile as aae}from"child_process";import{readdirSync as lae,readFileSync as cae}from"fs";import{promisify as uae}from"util";async function hae(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(mae,n)))}}async function Si(t,e={}){let r=e.signalMode==="immediate",i=e.expectedStartToken!==void 0?e.expectedStartToken:Gi(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 wk("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===dae||pae.test(`${a} ${l}`)){b.debug("PROCESS","taskkill reported the process was already gone",{pid:t});return}throw new _h(t,`taskkill failed for PID ${t} (exit ${String(s)}): ${a.trim()||l}`,{cause:o})}return}try{let o=r?"SIGKILL":"SIGTERM",s=await wh(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 hae([t,...s.map(c=>c.pid)],fae);let a=n()?await wh(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 _h(t,`tree-kill failed for PID ${t}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}}async function gae(){return process.platform==="win32"?vae():process.platform==="linux"?yae():bae()}function yae(){let t=[],e;try{e=lae("/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=cae(`/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 bae(){let t;try{t=(await wk("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 vae(){let t;try{t=(await wk("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 wh(t){let e=await gae(),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 wk,dae,pae,fae,mae,_h,fc=v(()=>{"use strict";ye();Sh();wk=uae(aae),dae=128,pae=/not found|no running instance|no tasks/i,fae=500,mae=10;_h=class extends Error{pid;constructor(e,r,i){super(r,i),this.name="ProcessTreeKillError",this.pid=e}}});import{existsSync as YK,readFileSync as Tk}from"fs";import Sae from"path";function It(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 kh(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(i=>!It(i.pid)))return;await new Promise(i=>setTimeout(i,100))}}function ZK(t){if(!t||!It(t.pid))return!1;if(!t.startToken)return!0;let e=Gi(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 mc(t,e=xae){if(!ZK(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=>Sae.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 Vi(t=Me.workerPid()){if(!YK(t))return null;let e;try{e=JSON.parse(Tk(t,"utf-8"))}catch{return null}return e!==null&&mc(e)?e:null}function Ih(){return kk||(kk=new xk),kk}function Ik(){let t=Tae.shift();t&&t.notify()}var _ae,wae,kae,Iae,xae,xk,kk,xJe,Tae,En=v(()=>{"use strict";nn();ye();ct();cs();_e();Sh();fc();_ae=5e3,wae=1e3,kae=Me.supervisorRegistry(),Iae=null;xae={platform:process.platform,readCommandLine:t=>Tk(`/proc/${t}/cmdline`,"utf-8")};xk=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(e=kae){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,!YK(this.registryPath)){this.persist();return}try{let i=JSON.parse(Tk(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||!It(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"&&Ik())}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)It(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)Ik();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=>It(a.pid)),o=new Map(n.map(a=>[a.pid,Gi(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 kh(n,_ae);let s=n.filter(a=>It(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()+wae;for(;Date.now()<a&&s.filter(c=>It(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"&&Ik();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{Ue(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{Iae?.({errorCategory:r.code??"unknown"})}catch{}}},kk=null;xJe=180*1e3,Tae=[]});import{existsSync as Aae,readFileSync as Cae,rmSync as Oae}from"fs";async function QK(t){let e=t.currentPid??process.pid,r=t.pidFilePath??Rae,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(!It(l.pid)){t.registry.unregister(l.id);continue}s.set(l.id,Gi(l.pid)),o.set(l.id,await wh(l.pid));try{await XK(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 kh(n,5e3);let a=n.filter(l=>It(l.pid)||(o.get(l.id)??[]).some(c=>It(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 XK(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{Mae(o.get(l.id)??[],l.pid)}}await kh(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);Ak(r,e),t.registry.pruneDeadEntries()}function Ak(t,e,r=!1){if(!Aae(t))return;let i=null;try{let s=JSON.parse(Cae(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||!It(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{Oae(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 Mae(t,e){for(let{pid:r,startToken:i}of t)if(!(r===e||!It(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 XK(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 Rae,Ck=v(()=>{"use strict";ye();En();_e();fc();Rae=Me.workerPid()});function Pae(){let e=Ih().pruneDeadEntries();e>0&&b.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function t$(){hc===null&&(hc=setInterval(Pae,e$),hc.unref(),b.debug("SYSTEM","Health checker started",{intervalMs:e$}))}function r$(){hc!==null&&(clearInterval(hc),hc=null,b.debug("SYSTEM","Health checker stopped"))}var e$,hc,n$=v(()=>{"use strict";ye();En();e$=3e4,hc=null});import{execFile as Dae}from"child_process";import{promisify as Nae}from"util";function Kae(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 Ok(){let t=await Lae("ps",["-e","-o","pid=","-o","ppid=","-o","args="],{timeout:1e4,maxBuffer:33554432});return Kae(t.stdout)}function Rk(t,e){let r=t.filter(s=>jae.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 i$(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??Ok,n=t.isAlive??It,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}=Rk(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 Lae,jae,Mk=v(()=>{"use strict";ye();fc();En();Lae=Nae(Dae),jae=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/});import{existsSync as $ae,readFileSync as Uae,rmSync as o$}from"fs";function Dk(){return Jae}function Nk(t={}){let e=t.pidFilePath??Fae;if(!$ae(e))return"missing";let r=null;try{r=JSON.parse(Uae(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)}),o$(e,{force:!0}),"invalid"}return mc(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}),o$(e,{force:!0})),"stale")}var Fae,Pk,Jae,qd=v(()=>{"use strict";ye();En();Ck();n$();Mk();_e();En();Fae=Me.workerPid(),Pk=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(),Nk({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,i$({registry:this.registry}).catch(r=>{b.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),t$()}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}r$(),this.stopPromise=QK({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}},Jae=new Pk(Ih())});import{existsSync as Bae,readFileSync as zae}from"fs";function tr(t,e){if(!Bae(t))return e;try{return wr(zae(t,"utf-8"))}catch(r){throw new Error(`Corrupt JSON file, refusing to overwrite: ${t}: ${r instanceof Error?r.message:String(r)}`)}}var us=v(()=>{"use strict";ct()});import{join as s$}from"path";import{mkdirSync as qae,writeFileSync as Wae}from"fs";import{randomUUID as Gae}from"crypto";function Vae(t){let e=t.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function Lk(t,e){if(Vae(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 l$(t,e){return Lk(t,e).enabled}function Wd(){return s$(Qt(),a$)}function ds(){let t;try{t=tr(Wd(),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 gc(t){let e=Qt();qae(e,{recursive:!0}),Wae(s$(e,a$),JSON.stringify(t,null,2)+`
|
|
16
|
-
`)}function xh(){let t=ds();if(t?.installId)return t.installId;let e=Gae();return gc({installId:e,decidedAt:""}),e}var a$,Th=v(()=>{"use strict";_e();us();ye();a$="telemetry.json"});import Hae from"os";function Yae(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 Zae(t){if(typeof t!="string"||t.length===0)return t??"";let e="";try{e=Hae.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 Xae(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 Qae(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 ele(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\?[^\s"'()]*/g,"")}function tle(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 rle(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 u$(t){let e=Yae(t);return e.length===0?"":(e=Zae(e),e=Qae(e),e=Xae(e),e=ele(e),e=tle(e),e=rle(e),e)}var c$,Vn,d$=v(()=>{"use strict";ye();c$=8192,Vn="[REDACTED]"});function ile(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>p$?i.slice(0,p$):i;e[r]=u$(n)}else(typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean")&&(e[r]=i)}}function f$(t){let e={};try{ile(t,e)}catch{}return e}var nle,p$,m$=v(()=>{"use strict";d$();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"]),p$=200});import h$ from"os";function g$(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||sle}function y$(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||ale}function b$(t){let e={};for(let r of lle)t[r]!==void 0&&(e[r]=t[r]);return e}function cle(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||h$.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 v$(){return{version:ole,os:process.platform,os_version:h$.release(),is_wsl:cle(),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 ole,sle,ale,lle,E$=v(()=>{"use strict";ye();ole="15.
|
|
16
|
+
`)}function xh(){let t=ds();if(t?.installId)return t.installId;let e=Gae();return gc({installId:e,decidedAt:""}),e}var a$,Th=v(()=>{"use strict";_e();us();ye();a$="telemetry.json"});import Hae from"os";function Yae(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 Zae(t){if(typeof t!="string"||t.length===0)return t??"";let e="";try{e=Hae.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 Xae(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 Qae(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 ele(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\?[^\s"'()]*/g,"")}function tle(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 rle(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 u$(t){let e=Yae(t);return e.length===0?"":(e=Zae(e),e=Qae(e),e=Xae(e),e=ele(e),e=tle(e),e=rle(e),e)}var c$,Vn,d$=v(()=>{"use strict";ye();c$=8192,Vn="[REDACTED]"});function ile(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>p$?i.slice(0,p$):i;e[r]=u$(n)}else(typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean")&&(e[r]=i)}}function f$(t){let e={};try{ile(t,e)}catch{}return e}var nle,p$,m$=v(()=>{"use strict";d$();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"]),p$=200});import h$ from"os";function g$(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||sle}function y$(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||ale}function b$(t){let e={};for(let r of lle)t[r]!==void 0&&(e[r]=t[r]);return e}function cle(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||h$.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 v$(){return{version:ole,os:process.platform,os_version:h$.release(),is_wsl:cle(),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 ole,sle,ale,lle,E$=v(()=>{"use strict";ye();ole="15.6.0",sle="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",ale="https://us.i.posthog.com";lle=["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 Ir(t,e,r){try{if(!l$(process.env,ds()))return;let i=f$({...v$(),...e??{}});if(r?.person?i.$set=b$(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=g$(),o=new AbortController,s=setTimeout(()=>o.abort(),ule);try{await dle(n,t,i,o.signal)}finally{clearTimeout(s)}}catch{}}async function dle(t,e,r,i){await fetch(`${y$()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:t,event:e,distinct_id:xh(),properties:r}),signal:i})}var ule,Gd=v(()=>{"use strict";Th();m$();E$();ule=2e3});import{createHash as S2e,randomUUID as _2e}from"crypto";var S$=v(()=>{"use strict";ye()});import{randomUUID as C2e}from"crypto";var _$=v(()=>{"use strict";ye();S$()});import{existsSync as ple,statSync as fle,readFileSync as mle}from"fs";import Hn from"path";function w$(t){let e=Hn.join(t,".git"),r;try{r=fle(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)}),Vd}if(!r.isFile())return Vd;let i;try{i=mle(e,"utf-8").trim()}catch(c){return b.warn("GIT","Failed to read .git file",{error:c instanceof Error?c.message:String(c)}),Vd}let n=i.match(/^gitdir:\s*(.+)$/);if(!n)return Vd;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&&ple(Hn.join(o,"commondir"))){let c=l[1],u=hle(c);if(u)return{isWorktree:!0,isSubmodule:!1,worktreeName:Hn.basename(t),parentRepoPath:c,parentProjectName:u}}return Vd}function hle(t){let e=Hn.basename(t).replace(/\.git$/,"");return e&&!e.startsWith(".")?e:Hn.basename(Hn.dirname(t))||null}var Vd,k$=v(()=>{"use strict";ye();Vd={isWorktree:!1,isSubmodule:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null}});import{basename as x$}from"path";function I$(t){let e=Fr(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 T$(t,e,r){let i=I$(t);return i.test(e)||i.test(r)?!0:t.replace(/\\/g,"/").endsWith("/**")?I$(t.slice(0,-3)).test(e.replace(/\/+$/,"")):!1}function A$(t,e){if(!e.length)return!1;let r=t.replace(/\\/g,"/"),i=x$(r);for(let n of e){let o=n.trim();if(o)try{if(T$(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 C$(t,e){if(!e||!e.trim())return!1;let r=t.replace(/\\/g,"/"),i=x$(r),n=e.split(",").map(o=>o.trim()).filter(Boolean);for(let o of n)try{if(T$(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 jk=v(()=>{"use strict";uc();ye()});import{realpathSync as gle}from"fs";function O$(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}r.push({name:n,patterns:o})}return r}function yle(t){try{return gle(t)}catch{return t}}function Kk(t,e){if(e.length===0)return null;let r=[...new Set([t,yle(t)])].flatMap(i=>[i,`${i.replace(/[\\/]+$/,"")}/`]);for(let i of e)if(r.some(n=>A$(n,i.patterns)))return i.name;return null}var R$=v(()=>{"use strict";jk();ye()});import on from"path";import{existsSync as ble,realpathSync as vle,statSync as Ele}from"fs";import{homedir as Sle,tmpdir as _le}from"os";import{execFileSync as D$}from"child_process";function N$(t){try{return D$("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 L$(t){try{return vle(t)}catch{return t}}function Ile(t,e){let r=on.relative(e,t);return r===""||!r.startsWith("..")&&!on.isAbsolute(r)}function xle(){return[Sle(),_le(),xo].flatMap(t=>{let e=on.resolve(t);return[e,L$(e)]})}function j$(t){let e=xle(),r=on.resolve(t);if([on.resolve(xo),L$(on.resolve(xo))].some(n=>Ile(r,n)))return null;for(let n=0;n<kle;n++){if(e.includes(r))return null;let o=on.dirname(r);if(o===r)return null;if(wle.some(s=>ble(on.join(r,s))))return r;r=o}return null}function Uk(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}),Fk}return r}function M$(){try{return Ele(fe).mtimeMs}catch{return-1}}function K$(){let t=M$();if(t===-1)return me.getAllDefaults();if(Ah&&Ah.mtimeMs===t)return Ah.settings;let e=me.loadFromFile(fe);return Ah={mtimeMs:M$(),settings:e},e}function Ale(){let t=process.env[Tle]??K$().CLAUDE_MEM_PROJECT_NAME_SOURCE;return String(t??"path").trim().toLowerCase()==="git-remote"}function $$(){let t=process.env[Cle]??K$().CLAUDE_MEM_PROJECT_ENVIRONMENTS;return(!Ch||Ch.raw!==t)&&(Ch={raw:t,environments:O$(t)}),Ch.environments}function Ole(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 Rle(t){try{let e=D$("git",["remote","get-url","origin"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim();return Ole(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 U$(t){return Ale()?($k.has(t)||$k.set(t,Rle(t)),$k.get(t)??null):null}function Mle(t,e=process.platform){if(!t||t.trim()==="")return b.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),Fk;let r=Fr(t,e),i=Kk(r,$$());if(i)return i;let n=N$(r),o=n?U$(n):null;if(o)return o;let s=n??j$(r)??r;return Uk(t,s)}function F$(t,e){return e===t?t:`${t}/${e}`}function Ple(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 Aa(t,e=process.platform){if(!t||t.trim()===""){let l=Mle(t,e);return{primary:l,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[l],keySource:"path"}}let r=Fr(t,e),i=N$(r),n=Dle(t,r,i),o=i?U$(i):null,s=o?P$(n,o,"git-remote"):n,a=Kk(r,$$());return a?P$(s,a,"environment"):s}function P$(t,e,r){return{primary:e,parent:null,isWorktree:t.isWorktree,isSubmodule:t.isSubmodule,allProjects:[...t.allProjects.filter(i=>i!==e),e],keySource:r}}function Dle(t,e,r){let i=r?null:j$(e),n=Uk(t,r??i??e),o=r??e,s=w$(o);if((s.isWorktree||s.isSubmodule)&&s.parentProjectName){let a=s.parentProjectName,l,c;return s.isSubmodule?(l=`${a}/${Ple(s,o)??n}`,c=n!==a?[n]:[]):(l=F$(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=Uk(t,e);if(a!==n&&a!==Fk)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 Fk,wle,kle,Tle,Ah,Cle,Ch,$k,Hd=v(()=>{"use strict";uc();_e();$t();ye();k$();R$();Fk="unknown-project";wle=[".claude-mem-project",".claude-mem.json"],kle=64;Tle="CLAUDE_MEM_PROJECT_NAME_SOURCE",Ah=null;Cle="CLAUDE_MEM_PROJECT_ENVIRONMENTS",Ch=null;$k=new Map});import Sn from"path";import{homedir as Nle,tmpdir as sBe}from"os";import{existsSync as Oh,writeFileSync as lBe,readFileSync as Lle,unlinkSync as cBe,mkdirSync as jle,statSync as uBe,utimesSync as Kle,copyFileSync as dBe,realpathSync as $le}from"fs";import{execFileSync as Ule,spawnSync as z$}from"child_process";function Fle(t){return t===void 0?J$:Math.max(1,Math.min(J$,t))}function Jle(t){try{return $le(t)}catch{return null}}function Jk(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function Ble(t,e){let r=e==="win32"?"where.exe":"which",i=[t],n;try{n=Ule(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 qk(t={}){let e=Object.keys(t).length===0;if(e&&Bk!==void 0)return Bk;let r=zle(t);return e&&r!==null&&(Bk=r),r}function B$(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 zle(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(Jk(r))return r;let i=t.env??process.env,n=t.homeDirectory??Nle(),o=t.pathExists??Oh,s=t.lookupInPath??Ble,a=t.realpath??Jle,l=e==="win32"?[i.BUN,i.BUN_PATH,...B$(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,...B$(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&&(Jk(p)&&o(p)||p.toLowerCase()==="bun"))return p}let c=s("bun",e)?.trim();if(!c||!Jk(c))return null;let u=a(c)??c;return o(u)?u:null}function q$(){if(!Oh(Ca))return null;try{return JSON.parse(Lle(Ca,"utf-8"))}catch(t){return t instanceof Error?b.warn("SYSTEM","Failed to parse PID file",{path:Ca},t):b.warn("SYSTEM","Failed to parse PID file",{path:Ca},new Error(String(t))),null}}function W$(t){Ak(Ca,t,!0)}function ps(t){return process.platform==="win32"?Math.round(t*2):t}function Wk(){let t=Me.dataDir();return jle(t,{recursive:!0}),t}function qle(t,e,r=Wk()){let i=n=>n.replace(/'/g,"''");return`Start-Process -FilePath '${i(t)}' -ArgumentList @('"${i(e)}"','--daemon') -WorkingDirectory '${i(r)}' -WindowStyle Hidden`}function Vle(t,e,r){return t?.code!=="ETIMEDOUT"?!1:e<r/2}function G$(t,e=ps(Wle)){let r=qk();if(!r)return;let i=()=>{let a=Date.now();try{return{result:z$(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||Vle(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,Gle).join(`
|
|
18
18
|
`)}function Hle(t=process.env){let e=t.SystemRoot||t.SYSTEMROOT;return e?`${e}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`:"powershell.exe"}function Yle(t,e,r=Wk()){return["-NoProfile","-WindowStyle","Hidden","-EncodedCommand",Buffer.from(qle(t,e,r),"utf16le").toString("base64")]}function V$(){return Yd}function H$(t,e,r,i=process.platform,n){if(Yd=void 0,i==="win32"){let u=Hle(r),d=Yle(t,e),p=Fle(n);try{let f=z$(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));Yd=`${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=Oh(o),a=s?o:t,c=vi(a,s?[t,e,"--daemon"]:[e,"--daemon"],{detached:!0,stdio:"ignore",cwd:Wk(),env:r});if(c.on("error",u=>{b.error("SYSTEM",zk,{runtimePath:t,execPath:a},u)}),c.pid===void 0){Yd=`could not launch ${a}`;return}return c.unref(),c.pid}function Y$(t,e,r={}){Dk().assertCanSpawn("worker daemon");let i=ur({...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r}),n=qk();if(!n){b.error("SYSTEM",zk),Yd=zk;return}return H$(n,t,i)}function Z$(){try{if(!Oh(Ca))return;let t=new Date;Kle(Ca,t,t)}catch{}}function Zd(t={}){return Nk({logAlive:!1,removeStale:t.removeStale})}var J$,wBe,Ca,zk,Bk,Wle,Gle,Yd,Rh=v(()=>{"use strict";nn();ye();cs();Ck();qd();_$();Hd();_e();Ta();En();J$=To(Kt.POWERSHELL_COMMAND);wBe=Me.dataDir(),Ca=Me.workerPid(),zk="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.";Wle=5e3,Gle=8});function Gk(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"&&Zle.has(r.code)||Gk(r.cause,e)?!0:Array.isArray(r.errors)&&r.errors.some(i=>Gk(i,e))}function Ao(t){return Gk(t,new Set)?!0:t instanceof Error&&t.message.includes("ECONNREFUSED")}function X$(t){let e=t?.code;return e==="EACCES"||e==="EADDRNOTAVAIL"}var Zle,Mh,Oa=v(()=>{"use strict";Zle=new Set(["ECONNREFUSED","ConnectionRefused"]);Mh="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 Xle from"net";function Vk(){return me.loadFromFile(fe).CLAUDE_MEM_WORKER_HOST}function Q$(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}async function Qle(t,e,r="GET",i=Xd){let n=await fetch(`http://${Q$(Vk())}:${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 Hk(t,e=Xd){let r=Date.now()+e;if(process.platform==="win32")try{let n=await fetch(`http://${Q$(Vk())}:${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 eU(t,Math.max(1,r-Date.now()));return i==="occupied"||i==="indeterminate"}async function eU(t,e=Xd){return(await Yk(t,e)).occupancy}function Yk(t,e=Xd){return e<=0?Promise.resolve({occupancy:"indeterminate"}):new Promise(r=>{let i=!1,n=!1,o=!1,s;try{s=Xle.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"}):X$(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,Vk())}catch{try{s.close()}catch{}c({occupancy:"indeterminate"})}})}async function tU(t,e,r,i){let n=Date.now()+r;for(;Date.now()<n;){try{let s=n-Date.now();if((await Qle(t,e,"GET",Math.min(Xd,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 fs(t,e=3e4){return tU(t,"/api/health",e,"Service not ready yet, will retry")}function yc(t,e=3e4){return tU(t,"/api/readiness",e,"Worker not ready yet, will retry")}var Xd,Qd=v(()=>{"use strict";ye();$t();_e();Oa();Xd=5e3});var rU=v(()=>{"use strict";ye();qd()});var nU=v(()=>{"use strict";Rh();Qd();rU()});import{dirname as ece,join as tce}from"path";import{mkdirSync as rce,readFileSync as Ph,statSync as iU,unlinkSync as oU,utimesSync as nce,writeFileSync as ice}from"fs";function Xk(){return tce(Qt(),"spawn.lock")}function Zk(t){try{let e=JSON.parse(Ph(t,"utf-8"));return typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0?null:e.pid}catch{return null}}function ace(t){if(t===null)return null;try{return process.kill(t,0),!0}catch(e){return e?.code==="EPERM"}}function Nh(){let t=Xk(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return rce(ece(t),{recursive:!0}),ice(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=Zk(t),l=null;if(a===null)try{l=Ph(t,"utf-8")}catch{continue}if(Date.now()-s<=Dh&&ace(a)!==!1)return!1;let u;try{u=iU(t).mtimeMs}catch{continue}if(u!==s)return!1;if(a!==null){if(Zk(t)!==a)return!1}else try{if(Ph(t,"utf-8")!==l)return!1}catch{continue}try{oU(t)}catch{return!1}}return!1}function Lh(){let t=Xk();try{if(JSON.parse(Ph(t,"utf-8")).pid!==process.pid)return;oU(t)}catch{}}async function Qk(t,e=oce){let r=Date.now()+t;for(;!Nh();){if(Date.now()>=r)return null;await new Promise(n=>setTimeout(n,sce))}let i=setInterval(lce,e);return i.unref(),()=>{clearInterval(i),Lh()}}function lce(){let t=Xk();try{if(Zk(t)!==process.pid)return;let e=new Date;nce(t,e,e)}catch{}}var Dh,oce,sce,jh=v(()=>{"use strict";_e();ye();Dh=9e4,oce=Dh/3,sce=250});import{execFile as cce}from"node:child_process";import{readdirSync as sU,readFileSync as tI,readlinkSync as uce,statSync as GBe,promises as VBe}from"node:fs";import{promisify as dce}from"node:util";function aU(t){return pce.test(t.trim())}function fce(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 $h(t,e){return e===void 0?t:Math.max(1,Math.min(t,e))}async function mce(t){try{let e=await Kh("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:$h(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 hce(t,e){try{let r=await Kh("netstat",["-ano"],{timeout:$h(15e3,e),windowsHide:!0,maxBuffer:16777216});return Sce(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 gce(t,e){try{let r=await Kh("lsof",["-nP",`-iTCP:${t}`,"-sTCP:LISTEN","-t"],{timeout:$h(1e4,e),maxBuffer:1048576});return yce(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 yce(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 bce(t){let e=new Set,r=!1;for(let n of["/proc/net/tcp","/proc/net/tcp6"]){let o;try{o=tI(n,"utf-8")}catch{continue}r=!0;for(let s of vce(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 sU("/proc")){if(!/^\d+$/.test(n))continue;let o;try{o=sU(`/proc/${n}/fd`)}catch{continue}for(let s of o){let a;try{a=uce(`/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 vce(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 Ece(t,e){if(process.platform==="linux")try{return tI(`/proc/${t}/cmdline`,"utf-8").split("\0").filter(Boolean).join(" ")||null}catch{return null}try{let i=(await Kh("ps",["-p",String(t),"-o","command="],{timeout:$h(5e3,e)})).stdout.trim();return i.length>0?i:null}catch{return null}}function Sce(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 wce(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(dU),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||!_ce.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 kce(t,e,r,i){let n=Gi(t),o=e?(await r(i))?.find(s=>s.pid===t)?.cmdline??null:await Ece(t,i);return Ei(t,n)?{startToken:n,cmdline:o}:{startToken:null,cmdline:null}}async function rI(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(lU))return b.info("PROCESS","Port reclaim skipped: not enough of the hook budget is left to finish one",{port:t,remainingMs:s(),neededMs:lU}),{reclaimed:!1,reason:"out-of-budget",killedPids:[]};let a=e.listOwners??((U,X)=>r()?hce(U,X):process.platform==="linux"?Promise.resolve(bce(U)):gce(U,X)),l=U=>a(U,s()),c=e.readTable??mce,u=()=>c(s()),d=e.killTree??((U,X)=>Si(U,X)),p=e.dataDir??(()=>Fe),f=e.readIdentity??((U,X)=>kce(U,r(),c,X)),m=await wce(t,{listOwners:l,killTree:d,readOwnedWorker:e.readOwnedWorker??Vi,probeHealth:e.probeHealth??(U=>fs(U,uU)),readIdentity:U=>f(U,s()),minOwnerAgeSeconds:e.minOwnerAgeSeconds??CK(),readHeartbeat:e.readHeartbeat??(()=>Ace()),heartbeatStaleMs:e.heartbeatStaleMs??xce(),maxSilentProtectionMs:e.maxSilentProtectionMs??Tce,now:i,sleep:e.sleep??(U=>new Promise(X=>setTimeout(X,U))),hasKillBudget:()=>!o(eI)});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=>It(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)&&fce(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(eI))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 xce(t=process.env,e=fe){let r=t.CLAUDE_MEM_WORKER_HEARTBEAT_STALE_MS??me.loadFromFile(e,!1,{readOnly:!0}).CLAUDE_MEM_WORKER_HEARTBEAT_STALE_MS,i=Number(r);return Number.isSafeInteger(i)&&i>=cU.min&&i<=cU.max?i:Ice}function Ace(t=Me.workerHeartbeat()){try{let e=JSON.parse(tI(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 Kh,pce,_ce,uU,dU,eI,lU,Ice,cU,Tce,nI=v(()=>{"use strict";ye();fc();En();qd();Qd();Sh();Ta();_e();$t();Kh=dce(cce),pce=/^(uv|uvx|python|chroma-mcp)(\.exe)?$/i;_ce=/worker-service/i,uU=1500,dU=1e3,eI=5500,lU=2*uU+dU+eI;Ice=12e4,cU={min:1e4,max:36e5};Tce=6e5});import{existsSync as Cce,readFileSync as Oce,realpathSync as Rce}from"fs";import{createRequire as Mce}from"module";import Ra from"path";function pU(t){try{return Rce(t)}catch{return t}}function Dce(t,e){let r=Ra.relative(e,t);return r!==""&&!r.startsWith("..")&&!Ra.isAbsolute(r)}function iI(t){let e;try{let n=JSON.parse(Oce(Ra.join(t,"package.json"),"utf-8"));e=Object.keys(n?.dependencies??{})}catch{return[]}if(e.length===0)return[];let r=Ra.join(t,"node_modules"),i=e.filter(n=>!Cce(Ra.join(r,...n.split("/"),"package.json")));if(e.includes("zod")&&!i.includes("zod")){let n=Mce(Ra.join(r,"noop.js")),o=pU(Ra.join(r,"zod"));for(let s of Pce)try{let a=n.resolve(s,{paths:[r]});Dce(pU(a),o)||i.push(s)}catch{i.push(s)}}return i}var Pce,fU=v(()=>{"use strict";Pce=["zod/v3","zod/v4","zod/v4-mini"]});import Ut from"path";import{randomUUID as gze}from"crypto";import{readFileSync as Nce,existsSync as Jh,writeFileSync as bze,renameSync as vze,mkdirSync as Eze,readdirSync as Lce,statSync as jce,unlinkSync as Sze}from"fs";function yU(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 bU(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 $ce(t){return bU()?{...t,verbose:!0}:t}function Uce(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 Fce(t,e,r){let i=typeof e.method=="string"?e.method:"GET",n=Uce(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 aI(t,e={}){let r=$ce(e);try{return await fetch(t,r)}catch(i){throw bU()&&Fce(t,e,i),i}}async function Jce(t,e={},r){try{return await aI(t,{...e,signal:AbortSignal.timeout(r)})}catch(i){throw i instanceof DOMException&&i.name==="TimeoutError"?new vh(r):i}}function Bce(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 zce(t,e,r){let i=Bce(r,e.signal),n;try{n=await aI(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 qce(t,e,r){let i=await zce(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 mU(){return Ut.join(me.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function lI(t={}){return t.readOnly?me.loadFromFile(mU(),!0,t):(Uh!==null||(Uh=me.loadFromFile(mU())),Uh)}function hU(t,e){if(!t)return null;let r=parseInt(t,10);return Number.isFinite(r)&&r>=e.min&&r<=e.max?r:null}function Wce(t,e,r){let i=process.env[t];if(i!==void 0){let s=hU(i,r);return s!==null?s:(b.warn("SYSTEM",`Invalid ${t}, using default`,{value:i,min:r.min,max:r.max}),e)}let n=lI()[t],o=hU(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&&oI!==null)return oI;let e=parseInt(lI(t).CLAUDE_MEM_WORKER_PORT,10);return t.readOnly||(oI=e),e}function Ma(t={}){if(!t.readOnly&&sI!==null)return sI;let e=lI(t).CLAUDE_MEM_WORKER_HOST;return t.readOnly||(sI=e),e}function Gce(){return Fh!==null||(Fh=Wce("CLAUDE_MEM_API_TIMEOUT_MS",To(Kt.API_REQUEST),Kce)),Fh}function cI(t){return`http://${Wn(Ma())}:${_i()}${t}`}function wi(t,e={}){let r=e.method??"GET",i=cI(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 qce(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??Gce();return o>0?Jce(i,n,o):aI(i,n)}function vU(t){let e=Jh(Ut.join(t,"plugin","scripts"))?Ut.join(t,"plugin"):t;return Ut.join(e,"scripts","worker-service.cjs")}function uI(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 dI(t=Ut.join(Ut.dirname(Ut.dirname(er)),"cache","thedotmack","claude-mem")){try{return Lce(t).filter(e=>/^\d/.test(e)).map(e=>Ut.join(t,e)).filter(e=>{try{if(!jce(e).isDirectory())return!1}catch{return!1}return!Jh(Ut.join(e,".orphaned_at"))}).map(e=>({scriptPath:vU(e),version:Ut.basename(e)}))}catch{return[]}}function gU(t){try{let e=JSON.parse(Nce(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 EU(){return{cacheRoot:Ut.join(Ut.dirname(Ut.dirname(er)),"cache","thedotmack","claude-mem"),marketplaceRoot:er,cwd:process.cwd()}}function pI(t=EU()){let e=process.env.CLAUDE_MEM_WORKER_SCRIPT_PATH?.trim();if(e){if(Jh(e))return{scriptPath:e,version:null};b.debug("SYSTEM","Ignoring missing CLAUDE_MEM_WORKER_SCRIPT_PATH override",{override:e})}let r=[...dI(t.cacheRoot),{scriptPath:vU(Ut.join(t.marketplaceRoot,"plugin")),version:gU(Ut.join(t.marketplaceRoot,"package.json"))},{scriptPath:Ut.join(t.cwd,"plugin","scripts","worker-service.cjs"),version:gU(Ut.join(t.cwd,"package.json"))}];return fI(r)}function SU(t){return Ut.dirname(Ut.dirname(t))}function Vce(t){return iI(SU(t.scriptPath)).length===0}function fI(t,e=Vce){let r=t.filter(i=>Jh(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:uI(i.version,n.version)),r.find(e)??r[0])}function bc(t=EU()){let e=pI(t);if(!e)return null;let r=SU(e.scriptPath);return{root:r,version:e.version,missingDependencies:iI(r)}}var qze,Wze,Kce,Gze,oI,sI,Uh,Fh,Hce,Yce,Vze,Yn=v(()=>{"use strict";ye();Ta();RK();$t();_e();bk();bh();UK();vk();FK();qd();zd();Gd();nU();Qd();Oa();Rh();jh();nI();cs();fc();ct();fU();vk();qze=yU("CLAUDE_MEM_HEALTH_TIMEOUT_MS",To(Kt.HEALTH_CHECK),{min:500,max:3e5}),Wze=yU("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",To(Kt.HOOK_READINESS_WAIT),{min:0,max:3e5}),Kce={min:500,max:3e5},Gze={min:500,max:Kt.SESSION_INIT_REQUEST_MAX};oI=null,sI=null,Uh=null,Fh=null;Hce=1e3,Yce=5e3,Vze=Yce+Hce});import{existsSync as mI,readFileSync as _U}from"fs";import{homedir as Zce}from"os";import{dirname as Xce,join as _n}from"path";import{fileURLToPath as Qce}from"url";function hI(){return process.env.CLAUDE_CONFIG_DIR||_n(Zce(),".claude")}function dr(){return _n(hI(),"plugins","marketplaces","thedotmack")}function ms(){return _n(hI(),"plugins")}function vc(){return _n(ms(),"known_marketplaces.json")}function hs(){return _n(ms(),"installed_plugins.json")}function gs(){return _n(hI(),"settings.json")}function Ec(){return _n(ms(),"cache","thedotmack","claude-mem")}function Pa(t){return _n(Ec(),t)}function Da(){let t=Qce(import.meta.url),e=_n(Xce(t),"..","..");if(!mI(_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 gI(){return _n(Da(),"plugin")}function ys(){let t=_n(gI(),".claude-plugin","plugin.json");if(mI(t))try{let r=JSON.parse(_U(t,"utf-8"));if(r.version)return r.version}catch{}let e=_n(Da(),"package.json");if(mI(e))try{let r=JSON.parse(_U(e,"utf-8"));if(r.version)return r.version}catch{}return"0.0.0"}function wU(){return bc()!==null}var _t,ki=v(()=>{"use strict";ct();Yn();us();_t=process.platform==="win32"});var IU,xU,TU,AU=v(()=>{IU=(()=>{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}})(),xU=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,TU=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 eue,tue,CU,rue,OU,nue,iue,oue,RU,MU,PU=v(()=>{AU();eue=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,tue=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,CU=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,rue=/\t{1,1000}/y,OU=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"),nue=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,iue=new RegExp("\\p{M}+","gu"),oue={limit:1/0,ellipsis:""},RU=(t,e={},r={})=>{let i=e.limit??1/0,n=e.ellipsis??"",o=e?.ellipsisWidth??(n?RU(n,oue,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=[[nue,d],[eue,s],[tue,a],[rue,l],[OU,c],[CU,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(iue,"")){let xe=X.codePointAt(0)||0;if(xU(xe)?G=u:TU(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,$r]=f[U];if(xe.lastIndex=h,xe.test(t)){if(E=xe===CU?IU(t.slice(h,xe.lastIndex)):xe===OU?1:xe.lastIndex-h,G=E*$r,Z+G>C&&(I=Math.min(I,h+Math.floor((C-Z)/$r))),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}},MU=RU});var sue,aue,Jr,yI=v(()=>{PU();sue={limit:1/0,ellipsis:"",ellipsisWidth:0},aue=(t,e={})=>MU(t,sue,e).width,Jr=aue});function Hi(t,e,r){return String(t).normalize().split(pue).map(i=>due(i,e,r)).join(`
|
|
@@ -610,7 +610,7 @@ ${i.map(s=>ub(s,!1)).join(`
|
|
|
610
610
|
${i.map(s=>ub(s,!1)).join(`
|
|
611
611
|
`)}`),null)}function p6(t){let e=S0(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 nC(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(ab),null;throw e}}async function hwe(t){let e=nC(()=>eC({args:t,options:{share:{type:"string"},"share-all":{type:"boolean"}},allowPositionals:!0,strict:!0}));if(!e)return 1;let r=t6(e.positionals[0]);if(!r.ok)return M.error(r.error),1;let i=tC({share:e.values.share,shareAll:e.values["share-all"]===!0});if(!i.ok)return M.error(i.error),1;let n=cb();if(n)return M.error(QA(n,"the join")),1;let o=await du({source:"teambrain_join",teamInvite:r.token});if(!o)return M.error(lwe()),1;M.info(`Sign in, then approve this device on the page to join the team: ${o.authorizationUrl}`),eb(o,"Approving this device on the page, which names the team, joins it."),lb?(await Qy("Hit return to open it in your browser\u2026"),Ks(o.authorizationUrl)):M.info("AGENT: show this link to the user. This command waits until they approve this device.");let s=await of(o,"teambrain_join",rwe);if(!s||s.kind!=="ready")return 1;let a=cb();if(a)return M.error(QA(a,"the join")),1;let l=swe(),c=pb(),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=i6(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 d6(p,void 0);if(!S)return 1;f=S.team,m=S.team,p.teamId=f.id}let h=awe(c,s),y=s6(o6(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??(lb?await l6(f.name,m):null);if(E){if(!await c6(p,f,E))return 1}else M.info("Not sharing any projects yet. Choose them with: npx claude-mem teambrain share");return h&&await u6(!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 gwe(t){let e=nC(()=>eC({args:t,options:{share:{type:"string"},"share-all":{type:"boolean"},team:{type:"string"}},allowPositionals:!1,strict:!0}));if(!e)return 1;let r=tC({share:e.values.share,shareAll:e.values["share-all"]===!0});if(!r.ok)return M.error(r.error),1;if(!r.choice&&!lb)return M.error("Without a terminal, name what to share: npx claude-mem teambrain share --share <a,b> (or --share-all)"),1;let i=p6(pb());if(!i)return 1;let n=await d6(i,e.values.team);if(!n)return 1;let o=r.choice??await l6(n.team.name,n.team);return o?await c6(i,n.team,o)?0:1:(M.info("Nothing changed."),0)}async function ywe(){let t=S0(pb());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:")} ${Dt(t.teambrainUrl)}`);let e=await hp(t,hu);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(ub(r,r.id===t.teamId));return console.log(On("dim","Change what you share: npx claude-mem teambrain share")),0}async function bwe(t,e,r){let i=!t.teamId||t.teamId===e,n=await hp(t,hu),o=l=>{let c=s6(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(XA)?(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?{...XA,...owe}:XA)?(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 u6(!1),0):(M.info("Cloud sync settings were not changed."),0)):1}async function vwe(t){let e=nC(()=>eC({args:t,options:{},allowPositionals:!0,strict:!0}));if(!e)return 1;let r=cb();if(r)return M.error(QA(r,"leave")),1;let i=pb(),n=p6(i);if(!n)return 1;let o=await hp(n,hu);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 ${Dt(l)}`;if(s&&!c){if(a)return M.error(`This account is not in team ${Dt(l)}.${s.length>0?` Its teams:
|
|
612
612
|
${s.map(d=>ub(d,!1)).join(`
|
|
613
|
-
`)}`:""}`),1;M.info(`This account is no longer in ${u}; removing it from this install.`)}else{if(lb){let p=await Ii({message:`Leave ${u}? TeamBrain removes what you shared with it.`,initialValue:!1});if(Tt(p)||!p)return M.info("Still in the team. Nothing changed."),0}let d=await JJ(n,l,hu);if(!d.ok)return M.error(`Could not leave ${u}: ${d.reason}`),1;M.success(`Left ${u}.`)}return bwe(n,l,i)}function Ewe(){let t=BJ(Yi()),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."):Ks(t),0}async function Swe(t=[]){let e=t[0]?.toLowerCase()??"status";if(t.slice(1).some(r=>r==="--help"||r==="-h"))return console.log(ab),0;switch(e){case"join":return hwe(t.slice(1));case"start":return Ewe();case"status":return ywe();case"share":return gwe(t.slice(1));case"leave":return vwe(t.slice(1));case"help":case"--help":case"-h":return console.log(ab),0;default:return console.error(On("red",`Unknown teambrain command: ${Dt(e)}`)),console.error(ab),1}}var rwe,lb,hu,db,XV,nwe,iwe,ZA,QV,owe,XA,ab,m6=v(()=>{"use strict";op();ct();Ac();Oa();_e();fp();$t();qn();ZV();k0();Yn();ye();Hd();sf();rwe="15.
|
|
613
|
+
`)}`:""}`),1;M.info(`This account is no longer in ${u}; removing it from this install.`)}else{if(lb){let p=await Ii({message:`Leave ${u}? TeamBrain removes what you shared with it.`,initialValue:!1});if(Tt(p)||!p)return M.info("Still in the team. Nothing changed."),0}let d=await JJ(n,l,hu);if(!d.ok)return M.error(`Could not leave ${u}: ${d.reason}`),1;M.success(`Left ${u}.`)}return bwe(n,l,i)}function Ewe(){let t=BJ(Yi()),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."):Ks(t),0}async function Swe(t=[]){let e=t[0]?.toLowerCase()??"status";if(t.slice(1).some(r=>r==="--help"||r==="-h"))return console.log(ab),0;switch(e){case"join":return hwe(t.slice(1));case"start":return Ewe();case"status":return ywe();case"share":return gwe(t.slice(1));case"leave":return vwe(t.slice(1));case"help":case"--help":case"-h":return console.log(ab),0;default:return console.error(On("red",`Unknown teambrain command: ${Dt(e)}`)),console.error(ab),1}}var rwe,lb,hu,db,XV,nwe,iwe,ZA,QV,owe,XA,ab,m6=v(()=>{"use strict";op();ct();Ac();Oa();_e();fp();$t();qn();ZV();k0();Yn();ye();Hd();sf();rwe="15.6.0",lb=process.stdin.isTTY===!0,hu=15e3,db=5e3,XV=3e4,nwe=1e3,iwe=40,ZA="__teambrain_all_projects__",QV=/^[A-Za-z0-9_-]{16,128}$/,owe={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:""},XA={CLAUDE_MEM_TEAMBRAIN_URL:"",CLAUDE_MEM_TEAMBRAIN_TEAM_ID:""},ab=[`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(`
|
|
614
614
|
`)});function _we(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function wwe(t){if(!t)return h6;let e=_we(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:h6}function so(t){return typeof t!="string"?null:wwe(t)}var h6,fb=v(()=>{"use strict";h6="claude"});import{existsSync as kwe,readFileSync as Iwe}from"fs";function g6(t){return new RegExp(`${t}${dl}`,"gi")}function gb(t){return`(?<=${t}${pl}${Jo}[=:]${Jo}${pl})`}function oC(t,e){if(!e.enabled||t.length===0)return{redacted:t,counts:{},oversize:!1};if(t.length>Mwe)return b.warn("REDACT","field exceeds the 1M-char redaction cap; replaced by an oversize marker",void 0,{inputLength:t.length}),{redacted:Pwe,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,...Owe,...e.genericEnabled?Rwe:[]];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 Dwe(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 Nwe(t){return{enabled:t.CLAUDE_MEM_REDACT_ENABLED==="true",disabledBuiltinPatterns:(t.CLAUDE_MEM_REDACT_DISABLED_BUILTINS??"").split(",").map(e=>e.trim()).filter(Boolean),customPatterns:Dwe(t.CLAUDE_MEM_REDACT_CUSTOM_PATTERNS??"[]"),logMatches:t.CLAUDE_MEM_REDACT_LOG_MATCHES==="true",genericEnabled:t.CLAUDE_MEM_REDACT_GENERIC_ENABLED==="true"}}function $we(t){if(!kwe(t))return null;try{return Iwe(t,"utf-8")}catch{return""}}function Uwe(t){if(t===null)return!1;try{let e=JSON.parse(ls(t));return e===null||typeof e!="object"||Array.isArray(e)}catch{return!0}}function Fwe(t,e,r){return process.env.CLAUDE_MEM_REDACT_ENABLED==="false"||!(uf?.enabled===!0||Kwe.test(e))?r:(b6||(b6=!0,b.warn("REDACT","settings.json could not be read; secret redaction stays on until it is repaired",{settingsPath:t,using:uf?.enabled?"the last configuration that loaded":"the built-in patterns"})),uf?.enabled?uf:jwe)}function sC(t=fe){let e=Date.now();if(cf&&e-y6<Lwe)return cf;let r=me.loadFromFile(t),i=Nwe(r),n=i.enabled?null:$we(t);return Uwe(n)?cf=Fwe(t,n,i):(cf=i,uf=i),y6=e,cf}function qwe(t,e,r){if(!r.genericEnabled)return null;let i=Jwe.test(t)?"generic_password":Bwe.test(t)?"generic_token":null;return!i||r.disabledBuiltinPatterns?.includes(i)||!zwe.test(e)||!/[A-Za-z]/.test(e)?null:`<redacted type='${i}'/>`}function Vwe(t,e,r){if(!r.genericEnabled||r.disabledBuiltinPatterns?.includes("bearer_token")||!Wwe.test(t))return null;let i=Gwe.exec(e);return i?`${i[1]}<redacted type='bearer_token'/>${e.slice(i[0].length)}`:null}function Zwe(t,e,r){return r.disabledBuiltinPatterns?.includes("aws_session_token")||!Hwe.test(t)||!Ywe.test(e)?null:"<redacted type='aws_session_token'/>"}function eke(t,e,r){return r.disabledBuiltinPatterns?.includes("aws_secret_key")||!Xwe.test(t)||!Qwe.test(e)?null:"<redacted type='aws_secret_key'/>"}function v6(t,e=sC()){if(!e.enabled)return t;let r=(i,n)=>{if(typeof i=="string"){let o=oC(i,e);return n===void 0||Object.keys(o.counts).length>0?o.redacted:Zwe(n,i,e)??eke(n,i,e)??Vwe(n,i,e)??qwe(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 df,dl,pl,Jo,mb,hb,iC,xwe,Twe,Awe,Cwe,Owe,Rwe,Mwe,Pwe,cf,y6,Lwe,uf,b6,jwe,Kwe,Jwe,Bwe,zwe,Wwe,Gwe,Hwe,Ywe,Xwe,Qwe,aC=v(()=>{"use strict";ye();$t();_e();ct();df=String.raw`[A-Za-z0-9_.\-+/=~@#$%^*!?]`,dl=`(?=${df}{8})${df}*[A-Za-z]${df}*`,pl=String.raw`(?:\\{0,3}["'])?`,Jo=String.raw`\s{0,8}`;mb=String.raw`(?:token|secret|api_key)`,hb=String.raw`\\{0,3}["']`,iC=String.raw`(?<!\\)"`,xwe=String.raw`(?:^|[\s?&]|\\[nrt]|${iC})`,Twe=String.raw`(?:^|\n|\\n|${iC})[ \t]{0,8}(?:-[ \t]{1,8})?`,Awe=String.raw`(?:${hb})?[ \t]{0,8}(?:$|\r?\n|\\{1,3}[rn]|#|${iC})`,Cwe=new RegExp([`${gb(String.raw`\b\w*_${mb}`)}${dl}`,`(?<=${hb}${mb}${hb}${Jo}:${Jo}${hb})${dl}`,`(?<=${xwe}${mb}=${pl})${dl}(?!\\(|${df})`,String.raw`(?<=--(?:token|secret|api[-_]key)(?:=|[ \t]{1,8})${pl})${dl}`,`(?<=${Twe}${mb}:[ \\t]{1,8}${pl})${dl}(?=${Awe})`].join("|"),"gi"),Owe=[{name:"aws_access_key",regex:/(?:AKIA|ASIA)[0-9A-Z]{16}/g},{name:"aws_secret_key",regex:new RegExp(`${gb(String.raw`(?:aws_secret_access_key|\bSecretAccessKey)`)}[A-Za-z0-9/+=]{40}`,"gi")},{name:"aws_session_token",regex:new RegExp(`${gb(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:"claude_mem_key",regex:/\bcmem_[A-Za-z0-9_-]{32,}|\bcm_pro_[A-Za-z0-9_-]{8,}/g}],Rwe=[{name:"generic_password",regex:g6(gb(String.raw`\b(?:\w*_?(?:password|passwd)|\w+_pwd)`))},{name:"generic_token",regex:Cwe},{name:"bearer_token",regex:g6(`(?<=\\bAuthorization${pl}${Jo}:${Jo}${pl}Bearer${Jo})`)}],Mwe=1024*1024,Pwe="<redacted type='oversize'/>";cf=null,y6=0,Lwe=5e3,uf=null,b6=!1,jwe={enabled:!0,disabledBuiltinPatterns:[],customPatterns:[],logMatches:!1},Kwe=/"CLAUDE_MEM_REDACT_ENABLED"\s*:\s*"true"/;Jwe=/(?:password|passwd)$|\w_pwd$/i,Bwe=/(?:^|_)(?:secret|token|api_key)$/i,zwe=new RegExp(`^${df}{8,}$`);Wwe=/^authorization$/i,Gwe=new RegExp(`^(${Jo}Bearer${Jo})${dl}`,"i");Hwe=/^(?:aws_session_token|SessionToken)$/i,Ywe=/^[A-Za-z0-9/+=]{100,}$/;Xwe=/^(?:aws_secret_access_key|SecretAccessKey)$/i,Qwe=/^[A-Za-z0-9/+=]{40}$/});function rke(t){let e=Object.fromEntries(w6.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}S6.lastIndex=a;let u=S6.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}E6.lastIndex=a;let d=E6.exec(t);if(d&&tke.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 nke(t,{text:e,counts:r,total:i}){return i>_6&&b.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:i,maxAllowed:_6,contentLength:t.length}),{stripped:oC(e.trim(),sC()).redacted,counts:r}}function pf(t){let e=r=>{if(typeof r=="string"){let i=rke(r);return i.total>0?nke(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 w6,tke,E6,S6,_6,ike,c8e,u8e,lC=v(()=>{"use strict";ye();aC();w6=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],tke=new Set(w6),E6=/<([A-Za-z_][A-Za-z0-9_-]*)/y,S6=/<\/([A-Za-z_][A-Za-z0-9_-]*)\s*>/y;_6=100;ike=["task-notification"],c8e=new RegExp(`^\\s*<(${ike.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),u8e=256*1024});function k6(t){let e=so(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(),rf(t.payload??{})])}`}function cC(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:Ct(t.metadata),occurredAtEpoch:Qe(t.occurred_at),receivedAtEpoch:Qe(t.received_at),createdAtEpoch:Qe(t.created_at)}}var ff,uC=v(()=>{"use strict";oo();fb();aC();lC();ff=class{constructor(e){this.client=e}client;async create(e){await Ri(this.client,e.projectId,e.teamId),e.serverSessionId&&await $o(this.client,e.serverSessionId,e.projectId,e.teamId);let r=k6(e),i=so(e.platformSource),n=await we(this.client,`
|
|
615
615
|
INSERT INTO agent_events (
|
|
616
616
|
id, project_id, team_id, server_session_id, source_adapter,
|
package/dsh/package.json
CHANGED
|
@@ -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.
|
|
6
|
+
"version": "15.6.0",
|
|
7
7
|
"license": "Apache-2.0",
|
|
8
8
|
"author": "thedotmack",
|
|
9
9
|
"homepage": "https://claude-mem.ai",
|
package/package.json
CHANGED