claude-mem 13.38.0 → 13.39.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/hooks/codex-hooks.json +12 -0
- 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 +26 -26
- package/plugin/scripts/transcript-watcher.cjs.map +3 -3
- package/plugin/scripts/worker-service.cjs +433 -433
- package/plugin/scripts/worker-service.cjs.map +3 -3
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-13.
|
|
62
|
+
<img src="https://img.shields.io/badge/version-13.39.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){D_=e}error(e,r,i,n){this.log(3,e,r,i,n),this.routeErrorToSink(r,i,n)}routeErrorToSink(e,r,i){try{if(!D_||!(i instanceof Error))return;D_(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 M_});function zK(t=process.env){let e=Number.parseInt(t.CLAUDE_MEM_WEDGED_WORKER_UPTIME_S??"",10);return Number.isFinite(e)&&e>=JK.min&&e<=JK.max?e:Rte}function qK(t=process.platform){return t==="win32"?8e3:5e3}function N_(t=process.platform){return Mt.SESSION_INIT_HOOK_CAP-qK(t)}function lo(t){return process.platform==="win32"?Math.round(t*Mt.WINDOWS_MULTIPLIER):t}var Mt,Rte,JK,na=v(()=>{"use strict";Mt={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},Rte=300,JK={min:60,max:86400}});var BK=v(()=>{"use strict"});function GK(t){try{return new URL(t).hostname.toLowerCase()==="openrouter.ai"}catch{return!1}}var WK=v(()=>{"use strict";ge()});import{readFileSync as Dte,existsSync as VK,writeFileSync as Pte}from"fs";import{basename as Mte,dirname as Nte,join as j_}from"path";import{homedir as HK,hostname as Kte}from"os";function Jte(t){return typeof t=="boolean"?String(t):t}function zte(t){let e=t.CLAUDE_MEM_OPENROUTER_MODEL;if(typeof e!="string"||!Fte.has(e.trim()))return!1;let r=typeof t.CLAUDE_MEM_OPENROUTER_BASE_URL=="string"?t.CLAUDE_MEM_OPENROUTER_BASE_URL.trim():"";return r===""||GK(r)}function QK(t,e){return j_(Nte(t),`.${Mte(t)}.${e.markerTag}`)}function K_(t,e){try{Pte(QK(t,e),new Date().toISOString(),{encoding:"utf-8",mode:384})}catch{}}function qte(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===Lte||r===Ute)return $te}catch{return null}return null}var jte,Lte,Ute,$te,Fte,YK,ZK,XK,Ne,qr=v(()=>{"use strict";na();Pt();WK();Ci();jte="security_alert",Lte="sync-hub.black-pond-afbb.workers.dev",Ute="ziczmqtpmaxbornfghye.supabase.co",$te="https://sync.cmem.ai",Fte=new Set(["xiaomi/mimo-v2-flash:free"]);YK=18e4,ZK=[{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"}];XK=new Set;Ne=class{static DEFAULTS={CLAUDE_MEM_MEMORY_SEARCH_HOOK_ENABLED:"true",CLAUDE_MEM_MEMORY_INSTRUCTIONS_ENABLED:"true",CLAUDE_MEM_MEMORY_WATCH_ROOTS:"",CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_SESSION_START_INCLUDE_ALL_SOURCES:"false",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_ALLOWED_ORIGINS:"",CLAUDE_MEM_PUBLIC_URL:"",CLAUDE_MEM_API_TIMEOUT_MS:String(lo(Mt.API_REQUEST)),CLAUDE_MEM_SESSION_INIT_TIMEOUT_MS:String(N_()),CLAUDE_MEM_IDLE_EXIT_SEC:"0",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_SKIP_BASH_PATTERNS:"",CLAUDE_MEM_SKIP_SUBAGENT_OBSERVATIONS:"false",CLAUDE_MEM_SKIP_AGENT_TYPES:"",CLAUDE_MEM_CAPTURE_ADVISOR_CALLS:"false",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CODEX_MODEL:"",CLAUDE_MEM_CODEX_PATH:"codex",CLAUDE_MEM_CODEX_REASONING_EFFORT:"low",CLAUDE_MEM_CODEX_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_CODEX_OBSERVATION_BATCH_SIZE:"8",CLAUDE_MEM_CODEX_OBSERVATION_BATCH_MAX_CHARS:"32000",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_API_KEYS:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-flash-latest",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_API_KEYS:"",CLAUDE_MEM_OPENROUTER_MODEL:"cohere/north-mini-code:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_TEMPERATURE:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_EXTRA_BODY:"",CLAUDE_MEM_OPENROUTER_REASONING_EFFORT:"",CLAUDE_MEM_OPENAI_COMPAT_PRESET:"",CLAUDE_MEM_OPENAI_COMPAT_API_KEY:"",CLAUDE_MEM_OPENAI_COMPAT_API_KEYS:"",CLAUDE_MEM_OPENAI_COMPAT_BASE_URL:"",CLAUDE_MEM_OPENAI_COMPAT_MODEL:"",CLAUDE_MEM_QUOTA_FALLBACK_PROVIDER:"claude",CLAUDE_MEM_QUOTA_FALLBACK_MODEL:"",CLAUDE_MEM_QUOTA_THRESHOLD_FIVE_HOUR:"0.95",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY:"0.93",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY_OPUS:"0.93",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY_SONNET:"0.92",CLAUDE_MEM_QUOTA_THRESHOLD_OVERAGE:"0.95",CLAUDE_MEM_DATA_DIR:j_(HK(),".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:j_(HK(),".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_EXCLUDED_PROJECTS:"",CLAUDE_MEM_PROJECT_ENVIRONMENTS:"[]",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_SEMANTIC_INJECT_FORMAT:"narrative",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_CHROMA_MUTATION_TIMEOUT_MS:"600000",CLAUDE_MEM_CHROMA_MAX_PENDING_MUTATIONS:"5000",CLAUDE_MEM_CHROMA_EMBEDDING_FUNCTION:"default",CLAUDE_MEM_CHROMA_UVX_PATH:"",CLAUDE_MEM_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:Kte(),CLAUDE_MEM_CLOUD_SYNC_WS:"true",CLAUDE_MEM_CLOUD_SYNC_CONTENT_BATCH_SIZE:"40",CLAUDE_MEM_CLOUD_SYNC_REQUEST_TIMEOUT_MS:"90000",CLAUDE_MEM_LLM_TIMEOUT_MS:String(YK),CLAUDE_MEM_FIELD_OPTIMIZE_TIMEOUT_MS:String(YK),CLAUDE_MEM_LLM_STREAM_IDLE_TIMEOUT_MS:"90000",CLAUDE_MEM_TV_TOKEN:"",CLAUDE_MEM_PRO_TRIAL_EMAIL:"",CLAUDE_MEM_PRO_TRIAL_AT:"",CLAUDE_MEM_PRO_TRIAL_STATE:"",CLAUDE_MEM_PRO_TRIAL_ENDS_AT:"",CLAUDE_MEM_PRO_PLAN:"",CLAUDE_MEM_PRO_FALLBACK_AT:"",CLAUDE_MEM_PRO_FALLBACK_MESSAGE:"",CLAUDE_MEM_PRO_FALLBACK_ACTION:"",CLAUDE_MEM_PRO_FALLBACK_URL:"",CLAUDE_MEM_PRO_MEMORY_KEY:"",CLAUDE_MEM_PRO_MEMORY_BASE_URL:"",CLAUDE_MEM_PRO_MEMORY_MODEL:"",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_WRAPUPS_ENABLED:"true",CLAUDE_MEM_TELEGRAM_OBSERVATION_ALERTS_ENABLED:"false",CLAUDE_MEM_TELEGRAM_WRAPUP_ROUTES:"{}",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert,sensitive",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_AWARENESS_ENABLED:"true",CLAUDE_MEM_GROK_BOT_AWARENESS_AGENT_IDS:"521e962d-2ec3-4488-bfbc-54d5209ce118,95601360-61f7-4fd9-bb3a-2c976b2b85c0",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_WEBHOOK_URL:"",CLAUDE_MEM_GROK_BOT_WEBHOOK_SECRET:"",CLAUDE_MEM_GROK_BOT_INJECT_ENABLED:"true",CLAUDE_MEM_GROK_BOT_INJECT_AGENT_IDS:"*",CLAUDE_MEM_GROK_BOT_INJECT_TIER:"episode",CLAUDE_MEM_GROK_BOT_INJECT_WINDOW:"80",CLAUDE_MEM_GROK_BOT_INJECT_FALLBACK:"house",CLAUDE_MEM_GROK_BOT_INJECT_PLATFORM_SOURCE:"",CLAUDE_MEM_GROK_BOT_INJECT_PROJECTS_BY_AGENT:"",CLAUDE_MEM_GROK_BOT_INJECT_MAX_LINE_CHARS:"160",CLAUDE_MEM_GROK_BOT_INJECT_DEBOUNCE_MS:"1500",CLAUDE_MEM_GROK_BOT_INJECT_STANDING_LINE:"",CLAUDE_MEM_CCS_ALIGN_ENABLED:"true",CLAUDE_MEM_CCS_ALIGN_VIEWER_IDS:"ccs-align",CLAUDE_MEM_CCS_ALIGN_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_CCS_ALIGN_PATCH_SHADOWS:"false",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:"",CLAUDE_MEM_DEDUP_ENABLED:"false",CLAUDE_MEM_DEDUP_COSINE_THRESHOLD:"0.80",CLAUDE_MEM_DEDUP_IDF_VETO_DF:"10",CLAUDE_MEM_DEDUP_MIN_SHARED_TOKENS:"2",CLAUDE_MEM_DEDUP_MIN_PROJECT_DOCS:"10",CLAUDE_MEM_DEDUP_MAX_SCAN:"2000",CLAUDE_MEM_DEDUP_MAX_BACKFILL_ROWS:"50000",CLAUDE_MEM_TOOL_USES_RETENTION_DAYS:"0",CLAUDE_MEM_WORKER_AUTOSTART:"true",CLAUDE_MEM_PROJECT_NAME_SOURCE:"path"};static getAllDefaults(){return{...this.DEFAULTS}}static get(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;return i.CLAUDE_MEM_WORKER_HOST=this.normalizeWorkerHost(i.CLAUDE_MEM_WORKER_HOST),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(!VK(e)){let p=this.getAllDefaults();if(!i.readOnly)try{Fe(e,p,{mode:384});for(let f of ZK)K_(e,f);console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(f){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,f instanceof Error?f.message:String(f))}return this.finalizeSettings(p,r)}let n=Dte(e,"utf-8"),o=Dn(n),s=oi(o),a=s!==o,l=T_(o),c=a&&Object.keys(l).some(p=>p!=="env");if(a&&!c&&!i.readOnly)try{Fe(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===jte&&(s={...s,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES},!i.readOnly))try{Fe(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(zte(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{Fe(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=qte(s.CLAUDE_MEM_CLOUD_SYNC_HUB_URL);if(u!==null&&(s={...s,CLAUDE_MEM_CLOUD_SYNC_HUB_URL:u},!i.readOnly))try{Fe(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 ZK)if(!VK(QK(e,p))){if(s[p.key]!==p.legacy){i.readOnly||K_(e,p);continue}if(s={...s,[p.key]:this.DEFAULTS[p.key]},!i.readOnly)try{Fe(e,c?{...l,env:s}:s,{mode:384}),K_(e,p),console.warn(`[SETTINGS] Migrated ${p.key} off the old ${p.legacy}ms default to ${this.DEFAULTS[p.key]}ms:`,e)}catch(f){let m=`${p.key}\0${e}`;XK.has(m)||(XK.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]=Jte(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)}}}});var ej=v(()=>{"use strict";qr();Me()});function ed(t){return(t.CLAUDE_MEM_WORKER_AUTOSTART??"true").trim().toLowerCase()==="false"}var hm=v(()=>{"use strict"});var tj=v(()=>{"use strict"});function Ai(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}var L_=v(()=>{"use strict"});import{spawn as Bte,spawnSync as nj}from"node:child_process";import{existsSync as Gte}from"node:fs";import{dirname as Wte,extname as ym,join as ij}from"node:path";function si(t,e,r){return Bte(t,e??[],{...r,windowsHide:!0})}function Hte(t){return`"${t.replace(/"/g,'""')}"`}function rj(t){return oj.has(ym(t).toLowerCase())}function Yte(t=process.env){let e=t.SystemRoot||t.SYSTEMROOT||t.windir||t.WINDIR||"C:\\Windows";return ij(e,"System32","where.exe")}function $_(t){if(process.platform!=="win32")return[];try{let e=nj(Yte(),[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=>Gte(r))}catch{return[]}}function Qte(t,e){let r=t.find(rj);if(r)return r;let i=t.find(n=>U_.has(ym(n).toLowerCase()));if(i&&e){let n=e(i);if(n&&rj(n))return n}return i??t.find(n=>Vte.has(ym(n).toLowerCase()))??t[0]??null}function ere(t,e,r=Xte){if(!/[\\/]volta[\\/]bin[\\/]/i.test(e))return null;try{let i=r(ij(Wte(e),"volta.exe"),["which",t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:Zte,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 Pn(t){return Qte($_(t),e=>ere(t,e))}function Br(t,e,r,i=process.platform){let n={...r,...i==="win32"?{windowsHide:!0}:{}};if(i==="win32"&&U_.has(ym(t).toLowerCase())){let o=[t,...e].map(Hte).join(" ");return{command:process.env.ComSpec??"cmd.exe",args:["/d","/s","/c",`"${o}"`],options:{...n,windowsVerbatimArguments:!0}}}return{command:t,args:[...e],options:n}}var U_,oj,Vte,Zte,Xte,Gr=v(()=>{"use strict";U_=new Set([".cmd",".bat"]),oj=new Set([".exe",".com"]),Vte=new Set([...oj,...U_]);Zte=5e3,Xte=(t,e,r)=>nj(t,e,r)});function or(t=process.env){let e={};for(let[r,i]of Object.entries(t))if(i!==void 0){if(ire.has(r)){e[r]=i;continue}rre.has(r)||tre.some(n=>r.startsWith(n))||(e[r]=i)}return e}var tre,rre,nre,ire,zo=v(()=>{"use strict";tre=["CLAUDECODE_","CLAUDE_CODE_"],rre=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),nre=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"]),ire=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",...nre])});import{spawnSync as aj}from"child_process";import{readFileSync as ore}from"fs";function lj(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 are(t){F_+=1;let e=aj("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...or(process.env),LC_ALL:"C",LANG:"C"}});return lj("powershell-cim",t,e)}function lre(t,e=!1){if(!e){let i=sj.get(t);if(i&&(t===process.pid||Date.now()-i.capturedAtMs<sre))return i.token}let r=null;try{r=are(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)&&sj.set(t,{token:r,capturedAtMs:Date.now()}),r}function cj(t,e){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux"){F_+=1;try{let r=ore(`/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 lre(t,e);F_+=1;try{let r=aj("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...or(process.env),LC_ALL:"C",LANG:"C"}});return lj("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 Oi(t){return cj(t,!1)}function ai(t,e){if(e===null)return!0;let r=cj(t,!0);return r===null?!0:r===e}var sre,sj,F_,gm=v(()=>{"use strict";ge();zo();sre=5e3,sj=new Map,F_=0});import{execFile as cre}from"child_process";import{readdirSync as ure,readFileSync as dre}from"fs";import{promisify as pre}from"util";async function li(t,e={}){let r=e.signalMode==="immediate",i=e.expectedStartToken!==void 0?e.expectedStartToken:Oi(t),n=()=>ai(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 J_("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===fre||mre.test(`${a} ${l}`)){b.debug("PROCESS","taskkill reported the process was already gone",{pid:t});return}throw new bm(t,`taskkill failed for PID ${t} (exit ${String(s)}): ${a.trim()||l}`,{cause:o})}return}try{let o=r?"SIGKILL":"SIGTERM",s=await vm(t);for(let c of s){if(!ai(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 new Promise(c=>setTimeout(c,500));let a=n()?await vm(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(!ai(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 bm(t,`tree-kill failed for PID ${t}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}}async function hre(){return process.platform==="win32"?bre():process.platform==="linux"?yre():gre()}function yre(){let t=[],e;try{e=ure("/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=dre(`/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 gre(){let t;try{t=(await J_("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 bre(){let t;try{t=(await J_("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 vm(t){let e=await hre(),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 J_,fre,mre,bm,Ol=v(()=>{"use strict";ge();gm();J_=pre(cre),fre=128,mre=/not found|no running instance|no tasks/i,bm=class extends Error{pid;constructor(e,r,i){super(r,i),this.name="ProcessTreeKillError",this.pid=e}}});import{existsSync as uj,readFileSync as G_}from"fs";import Ere from"path";function kt(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 Em(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(i=>!kt(i.pid)))return;await new Promise(i=>setTimeout(i,100))}}function dj(t){if(!t||!kt(t.pid))return!1;if(!t.startToken)return!0;let e=Oi(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 Rl(t,e=Ire){if(!dj(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=>Ere.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 Ri(t=Je.workerPid()){if(!uj(t))return null;let e;try{e=JSON.parse(G_(t,"utf-8"))}catch{return null}return e!==null&&Rl(e)?e:null}function Sm(){return z_||(z_=new B_),z_}function q_(){let t=xre.shift();t&&t.notify()}var Sre,_re,wre,kre,Ire,B_,z_,RNe,xre,dn=v(()=>{"use strict";Gr();ge();Pt();zo();Me();gm();Ol();Sre=5e3,_re=1e3,wre=Je.supervisorRegistry(),kre=null;Ire={platform:process.platform,readCommandLine:t=>G_(`/proc/${t}/cmdline`,"utf-8")};B_=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(e=wre){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,!uj(this.registryPath)){this.persist();return}try{let i=JSON.parse(G_(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||!kt(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"&&q_())}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)kt(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)q_();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=>kt(a.pid)),o=new Map(n.map(a=>[a.pid,Oi(a.pid)]));for(let a of n)try{process.platform==="win32"?await li(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 Em(n,Sre);let s=n.filter(a=>kt(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(!ai(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 li(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()+_re;for(;Date.now()<a&&s.filter(c=>kt(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"&&q_();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{Fe(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{kre?.({errorCategory:r.code??"unknown"})}catch{}}},z_=null;RNe=180*1e3,xre=[]});import{existsSync as Tre,readFileSync as Cre,rmSync as Are}from"fs";async function fj(t){let e=t.currentPid??process.pid,r=t.pidFilePath??Ore,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(!kt(l.pid)){t.registry.unregister(l.id);continue}s.set(l.id,Oi(l.pid)),o.set(l.id,await vm(l.pid));try{await pj(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 Em(n,5e3);let a=n.filter(l=>kt(l.pid)||(o.get(l.id)??[]).some(c=>kt(c.pid)));for(let l of a){let c=ai(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 pj(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{Rre(o.get(l.id)??[],l.pid)}}await Em(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);W_(r,e),t.registry.pruneDeadEntries()}function W_(t,e,r=!1){if(!Tre(t))return;let i=null;try{let s=JSON.parse(Cre(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||!kt(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{Are(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 Rre(t,e){for(let{pid:r,startToken:i}of t)if(!(r===e||!kt(r))){if(!ai(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 pj(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 li(r,{signalMode:"immediate"});return}try{process.kill(r,e)}catch(n){if((n instanceof Error?n.code:void 0)!=="ESRCH")throw n}return}await li(r)}var Ore,V_=v(()=>{"use strict";ge();dn();Me();Ol();Ore=Je.workerPid()});function Dre(){let e=Sm().pruneDeadEntries();e>0&&b.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function hj(){Dl===null&&(Dl=setInterval(Dre,mj),Dl.unref(),b.debug("SYSTEM","Health checker started",{intervalMs:mj}))}function yj(){Dl!==null&&(clearInterval(Dl),Dl=null,b.debug("SYSTEM","Health checker stopped"))}var mj,Dl,gj=v(()=>{"use strict";ge();dn();mj=3e4,Dl=null});import{execFile as Pre}from"child_process";import{promisify as Mre}from"util";function jre(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 H_(){let t=await Nre("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return jre(t.stdout)}function Y_(t,e){let r=t.filter(s=>Kre.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 bj(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??H_,n=t.isAlive??kt,o=t.killTree??(f=>li(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}=Y_(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(g=>o(g.pid)))).forEach((g,S)=>{let E=m[S];g.status==="fulfilled"?(r.killed+=1,d.add(E.pid)):(r.failed+=1,b.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:E.pid,ppid:E.ppid,error:g.reason instanceof Error?g.reason.message:String(g.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 Nre,Kre,Z_=v(()=>{"use strict";ge();Ol();dn();Nre=Mre(Pre),Kre=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/});import{existsSync as Lre,readFileSync as Ure,rmSync as vj}from"fs";function Q_(){return Fre}function ew(t={}){let e=t.pidFilePath??$re;if(!Lre(e))return"missing";let r=null;try{r=JSON.parse(Ure(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)}),vj(e,{force:!0}),"invalid"}return Rl(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}),vj(e,{force:!0})),"stale")}var $re,X_,Fre,td=v(()=>{"use strict";ge();dn();V_();gj();Z_();Me();dn();$re=Je.workerPid(),X_=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(),ew({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,bj({registry:this.registry}).catch(r=>{b.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),hj()}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}yj(),this.stopPromise=fj({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}},Fre=new X_(Sm())});import{existsSync as Jre,readFileSync as zre}from"fs";function Ht(t,e){if(!Jre(t))return e;try{return Dn(zre(t,"utf-8"))}catch(r){throw new Error(`Corrupt JSON file, refusing to overwrite: ${t}: ${r instanceof Error?r.message:String(r)}`)}}var qo=v(()=>{"use strict";Pt()});import{join as Ej}from"path";import{mkdirSync as qre,writeFileSync as Bre}from"fs";import{randomUUID as Gre}from"crypto";function Wre(t){let e=t.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function tw(t,e){if(Wre(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 _j(t,e){return tw(t,e).enabled}function rd(){return Ej(un(),Sj)}function Bo(){let t;try{t=Ht(rd(),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 Pl(t){let e=un();qre(e,{recursive:!0}),Bre(Ej(e,Sj),JSON.stringify(t,null,2)+`
|
|
16
|
-
`)}function _m(){let t=Bo();if(t?.installId)return t.installId;let e=Gre();return Pl({installId:e,decidedAt:""}),e}var Sj,wm=v(()=>{"use strict";Me();qo();ge();Sj="telemetry.json"});import Vre from"os";function Hre(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>wj?e.slice(0,wj):e}catch{return""}}function Yre(t){if(typeof t!="string"||t.length===0)return t??"";let e="";try{e=Vre.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 Zre(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 Xre(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${Mn}`):e.replace(/[?#].*$/,"").replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/@\s]+@/,`$1${Mn}@`))}function Qre(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\?[^\s"'()]*/g,"")}function ene(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)}${Mn}`})}function tne(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,Mn),e=e.replace(/\b[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\b/g,Mn),e=e.replace(/\b(?:sk|pk|rk|ak|phc|phx|ph|ghp|gho|ghs|xox[bpasr])[-_][A-Za-z0-9_-]{8,512}\b/gi,Mn),e=e.replace(/\bBearer\s+[A-Za-z0-9._-]{8,512}\b/gi,Mn),e=e.replace(/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g,Mn),e=e.replace(/\b[0-9a-fA-F]{24,4096}\b/g,Mn),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,Mn),e=e.replace(/\b(?=[A-Za-z0-9+/_-]{0,4096}\d)[A-Za-z0-9+/_-]{32,4096}={0,2}\b/g,Mn),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,Mn),e}function kj(t){let e=Hre(t);return e.length===0?"":(e=Yre(e),e=Xre(e),e=Zre(e),e=Qre(e),e=ene(e),e=tne(e),e)}var wj,Mn,Ij=v(()=>{"use strict";ge();wj=8192,Mn="[REDACTED]"});function nne(t,e){if(!(!t||typeof t!="object"))for(let r of Object.keys(t)){if(!rne.has(r))continue;let i=t[r];if(typeof i=="string"){let n=i.length>xj?i.slice(0,xj):i;e[r]=kj(n)}else(typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean")&&(e[r]=i)}}function Tj(t){let e={};try{nne(t,e)}catch{}return e}var rne,xj,Cj=v(()=>{"use strict";Ij();rne=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","stage","phase","install_method","interactive","provider_source","bun_version","uv_version","claude_code_version","trial_days","trial_variant","offer_surface","funnel_source","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","limit_window","overage_status","is_using_overage","resets_in_minutes","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_aborted_deadline_exceeded","outcomes_invalid_output","top_model","top_abort_reason","observed_model","observed_billing","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","skill_id","skill_source","skill_trigger","observations_created","total_observations_injected","total_tokens_saved_vs_naive"]),xj=200});import Aj from"os";function Oj(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||one}function Rj(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||sne}function Dj(t){let e={};for(let r of ane)t[r]!==void 0&&(e[r]=t[r]);return e}function lne(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||Aj.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 Pj(){return{version:ine,os:process.platform,os_version:Aj.release(),is_wsl:lne(),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 ine,one,sne,ane,Mj=v(()=>{"use strict";ge();ine="13.
|
|
16
|
+
`)}function _m(){let t=Bo();if(t?.installId)return t.installId;let e=Gre();return Pl({installId:e,decidedAt:""}),e}var Sj,wm=v(()=>{"use strict";Me();qo();ge();Sj="telemetry.json"});import Vre from"os";function Hre(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>wj?e.slice(0,wj):e}catch{return""}}function Yre(t){if(typeof t!="string"||t.length===0)return t??"";let e="";try{e=Vre.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 Zre(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 Xre(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${Mn}`):e.replace(/[?#].*$/,"").replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/@\s]+@/,`$1${Mn}@`))}function Qre(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\?[^\s"'()]*/g,"")}function ene(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)}${Mn}`})}function tne(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,Mn),e=e.replace(/\b[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\b/g,Mn),e=e.replace(/\b(?:sk|pk|rk|ak|phc|phx|ph|ghp|gho|ghs|xox[bpasr])[-_][A-Za-z0-9_-]{8,512}\b/gi,Mn),e=e.replace(/\bBearer\s+[A-Za-z0-9._-]{8,512}\b/gi,Mn),e=e.replace(/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g,Mn),e=e.replace(/\b[0-9a-fA-F]{24,4096}\b/g,Mn),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,Mn),e=e.replace(/\b(?=[A-Za-z0-9+/_-]{0,4096}\d)[A-Za-z0-9+/_-]{32,4096}={0,2}\b/g,Mn),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,Mn),e}function kj(t){let e=Hre(t);return e.length===0?"":(e=Yre(e),e=Xre(e),e=Zre(e),e=Qre(e),e=ene(e),e=tne(e),e)}var wj,Mn,Ij=v(()=>{"use strict";ge();wj=8192,Mn="[REDACTED]"});function nne(t,e){if(!(!t||typeof t!="object"))for(let r of Object.keys(t)){if(!rne.has(r))continue;let i=t[r];if(typeof i=="string"){let n=i.length>xj?i.slice(0,xj):i;e[r]=kj(n)}else(typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean")&&(e[r]=i)}}function Tj(t){let e={};try{nne(t,e)}catch{}return e}var rne,xj,Cj=v(()=>{"use strict";Ij();rne=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","stage","phase","install_method","interactive","provider_source","bun_version","uv_version","claude_code_version","trial_days","trial_variant","offer_surface","funnel_source","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","limit_window","overage_status","is_using_overage","resets_in_minutes","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_aborted_deadline_exceeded","outcomes_invalid_output","top_model","top_abort_reason","observed_model","observed_billing","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","skill_id","skill_source","skill_trigger","observations_created","total_observations_injected","total_tokens_saved_vs_naive"]),xj=200});import Aj from"os";function Oj(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||one}function Rj(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||sne}function Dj(t){let e={};for(let r of ane)t[r]!==void 0&&(e[r]=t[r]);return e}function lne(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||Aj.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 Pj(){return{version:ine,os:process.platform,os_version:Aj.release(),is_wsl:lne(),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 ine,one,sne,ane,Mj=v(()=>{"use strict";ge();ine="13.39.0",one="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",sne="https://us.i.posthog.com";ane=["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(!_j(process.env,Bo()))return;let i=Tj({...Pj(),...e??{}});if(r?.person?i.$set=Dj(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=Oj(),o=new AbortController,s=setTimeout(()=>o.abort(),cne);try{await une(n,t,i,o.signal)}finally{clearTimeout(s)}}catch{}}async function une(t,e,r,i){await fetch(`${Rj()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:t,event:e,distinct_id:_m(),properties:r}),signal:i})}var cne,nd=v(()=>{"use strict";wm();Cj();Mj();cne=2e3});import{createHash as xKe,randomUUID as TKe}from"crypto";var Nj=v(()=>{"use strict";ge()});import{randomUUID as MKe}from"crypto";var Kj=v(()=>{"use strict";ge();Nj()});import{statSync as dne,readFileSync as pne}from"fs";import ia from"path";function jj(t){let e=ia.join(t,".git"),r;try{r=dne(e)}catch(l){return l instanceof Error&&l.code!=="ENOENT"&&b.warn("GIT","Unexpected error checking .git",{error:l instanceof Error?l.message:String(l)}),id}if(!r.isFile())return id;let i;try{i=pne(e,"utf-8").trim()}catch(l){return b.warn("GIT","Failed to read .git file",{error:l instanceof Error?l.message:String(l)}),id}let n=i.match(/^gitdir:\s*(.+)$/);if(!n)return id;let o=ia.resolve(ia.dirname(e),n[1]),s=o.match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(s){let l=s[1];return{isWorktree:!0,isSubmodule:!1,worktreeName:ia.basename(t),parentRepoPath:l,parentProjectName:ia.basename(l)}}let a=o.match(/^(.+)[/\\]\.git[/\\]modules[/\\](.+)$/);if(a){let l=a[1];return{isWorktree:!1,isSubmodule:!0,worktreeName:ia.basename(t),parentRepoPath:l,parentProjectName:ia.basename(l)}}return id}var id,Lj=v(()=>{"use strict";ge();id={isWorktree:!1,isSubmodule:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null}});import{basename as fne}from"path";function mne(t){let e=cn(t.replace(/\\/g,"/"));e=e.replace(/\\/g,"/");let r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return r=r.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${r}$`)}function Uj(t,e){if(!e.length)return!1;let r=t.replace(/\\/g,"/"),i=fne(r);for(let n of e){let o=n.trim();if(o)try{let s=mne(o);if(s.test(r)||s.test(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}var $j=v(()=>{"use strict";Qu();ge()});import{realpathSync as hne}from"fs";function Fj(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 yne(t){try{return hne(t)}catch{return t}}function rw(t,e){if(e.length===0)return null;let r=[...new Set([t,yne(t)])].flatMap(i=>[i,`${i.replace(/[\\/]+$/,"")}/`]);for(let i of e)if(r.some(n=>Uj(n,i.patterns)))return i.name;return null}var Jj=v(()=>{"use strict";$j();ge()});import Wr from"path";import{existsSync as gne,realpathSync as bne,statSync as vne}from"fs";import{homedir as Ene,tmpdir as Sne}from"os";import{execFileSync as Bj}from"child_process";function Gj(t){try{return Bj("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 Wj(t){try{return bne(t)}catch{return t}}function kne(t,e){let r=Wr.relative(e,t);return r===""||!r.startsWith("..")&&!Wr.isAbsolute(r)}function Ine(){return[Ene(),Sne(),ra].flatMap(t=>{let e=Wr.resolve(t);return[e,Wj(e)]})}function Vj(t){let e=Ine(),r=Wr.resolve(t);if([Wr.resolve(ra),Wj(Wr.resolve(ra))].some(n=>kne(r,n)))return null;for(let n=0;n<wne;n++){if(e.includes(r))return null;let o=Wr.dirname(r);if(o===r)return null;if(_ne.some(s=>gne(Wr.join(r,s))))return r;r=o}return null}function iw(t,e){let r=Wr.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}),ow}return r}function zj(){try{return vne(Le).mtimeMs}catch{return-1}}function Hj(){let t=zj();if(t===-1)return Ne.getAllDefaults();if(km&&km.mtimeMs===t)return km.settings;let e=Ne.loadFromFile(Le);return km={mtimeMs:zj(),settings:e},e}function Tne(){let t=process.env[xne]??Hj().CLAUDE_MEM_PROJECT_NAME_SOURCE;return String(t??"path").trim().toLowerCase()==="git-remote"}function Yj(){let t=process.env[Cne]??Hj().CLAUDE_MEM_PROJECT_ENVIRONMENTS;return(!Im||Im.raw!==t)&&(Im={raw:t,environments:Fj(t)}),Im.environments}function Ane(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 One(t){try{let e=Bj("git",["remote","get-url","origin"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim();return Ane(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 Zj(t){return Tne()?(nw.has(t)||nw.set(t,One(t)),nw.get(t)??null):null}function Rne(t,e=process.platform){if(!t||t.trim()==="")return b.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),ow;let r=cn(t,e),i=rw(r,Yj());if(i)return i;let n=Gj(r),o=n?Zj(n):null;if(o)return o;let s=n??Vj(r)??r;return iw(t,s)}function Xj(t,e){return e===t?t:`${t}/${e}`}function Dne(t,e){if(!t.isSubmodule||!t.parentRepoPath)return null;let r=Wr.relative(t.parentRepoPath,e);return!r||r.startsWith("..")||Wr.isAbsolute(r)?null:r.split(Wr.sep).join("/")}function od(t,e=process.platform){if(!t||t.trim()===""){let l=Rne(t,e);return{primary:l,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[l],keySource:"path"}}let r=cn(t,e),i=Gj(r),n=Pne(t,r,i),o=i?Zj(i):null,s=o?qj(n,o,"git-remote"):n,a=rw(r,Yj());return a?qj(s,a,"environment"):s}function qj(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 Pne(t,e,r){let i=r?null:Vj(e),n=iw(t,r??i??e),o=r??e,s=jj(o);if((s.isWorktree||s.isSubmodule)&&s.parentProjectName){let a=s.parentProjectName,l,c;return s.isSubmodule?(l=`${a}/${Dne(s,o)??n}`,c=n!==a?[n]:[]):(l=Xj(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&&Wr.resolve(i)!==Wr.resolve(e)){let a=iw(t,e);if(a!==n&&a!==ow)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 ow,_ne,wne,xne,km,Cne,Im,nw,xm=v(()=>{"use strict";Qu();Me();qr();ge();Lj();Jj();ow="unknown-project";_ne=[".claude-mem-project",".claude-mem.json"],wne=64;xne="CLAUDE_MEM_PROJECT_NAME_SOURCE",km=null;Cne="CLAUDE_MEM_PROJECT_ENVIRONMENTS",Im=null;nw=new Map});import pn from"path";import{homedir as Mne,tmpdir as dje}from"os";import{existsSync as Tm,writeFileSync as fje,readFileSync as Nne,unlinkSync as mje,mkdirSync as Kne,statSync as hje,utimesSync as jne,copyFileSync as yje,realpathSync as Lne}from"fs";import{execFileSync as Une,spawnSync as t1}from"child_process";function $ne(t){return t===void 0?Qj:Math.max(1,Math.min(Qj,t))}function Fne(t){try{return Lne(t)}catch{return null}}function sw(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function Jne(t,e){let r=e==="win32"?"where.exe":"which",i=[t],n;try{n=Une(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 lw(t={}){let e=Object.keys(t).length===0;if(e&&aw!==void 0)return aw;let r=zne(t);return e&&r!==null&&(aw=r),r}function e1(t,e){let r=t?.trim();return r?e==="win32"?[pn.join(r,"bin","bun.exe"),pn.join(r,"bin","bun"),pn.join(r,"bun.exe")]:[pn.join(r,"bin","bun"),pn.join(r,"bun")]:[]}function zne(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(sw(r))return r;let i=t.env??process.env,n=t.homeDirectory??Mne(),o=t.pathExists??Tm,s=t.lookupInPath??Jne,a=t.realpath??Fne,l=e==="win32"?[i.BUN,i.BUN_PATH,...e1(i.BUN_INSTALL,e),pn.join(n,".bun","bin","bun.exe"),pn.join(n,".bun","bin","bun"),i.USERPROFILE?pn.join(i.USERPROFILE,".bun","bin","bun.exe"):void 0,i.LOCALAPPDATA?pn.join(i.LOCALAPPDATA,"bun","bun.exe"):void 0,i.LOCALAPPDATA?pn.join(i.LOCALAPPDATA,"bun","bin","bun.exe"):void 0,i.npm_config_prefix?pn.join(i.npm_config_prefix,"bun.exe"):void 0]:[i.BUN,i.BUN_PATH,...e1(i.BUN_INSTALL,e),pn.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?pn.join(i.npm_config_prefix,"bin","bun"):void 0];for(let d of l){let p=d?.trim();if(p&&(sw(p)&&o(p)||p.toLowerCase()==="bun"))return p}let c=s("bun",e)?.trim();if(!c||!sw(c))return null;let u=a(c)??c;return o(u)?u:null}function n1(){if(!Tm(oa))return null;try{return JSON.parse(Nne(oa,"utf-8"))}catch(t){return t instanceof Error?b.warn("SYSTEM","Failed to parse PID file",{path:oa},t):b.warn("SYSTEM","Failed to parse PID file",{path:oa},new Error(String(t))),null}}function i1(t){W_(oa,t,!0)}function Go(t){return process.platform==="win32"?Math.round(t*2):t}function cw(){let t=Je.dataDir();return Kne(t,{recursive:!0}),t}function qne(t,e,r=cw()){let i=n=>n.replace(/'/g,"''");return`Start-Process -FilePath '${i(t)}' -ArgumentList @('"${i(e)}"','--daemon') -WorkingDirectory '${i(r)}' -WindowStyle Hidden`}function Wne(t,e,r){return t?.code!=="ETIMEDOUT"?!1:e<r/2}function o1(t,e=Go(Bne)){let r=lw();if(!r)return;let i=()=>{let a=Date.now();try{return{result:t1(r,[t,"status"],{encoding:"utf-8",timeout:e,windowsHide:!0,env:or({...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||Wne(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,Gne).join(`
|
|
18
18
|
`)}function Vne(t=process.env){let e=t.SystemRoot||t.SYSTEMROOT;return e?`${e}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`:"powershell.exe"}function Hne(t,e,r=cw()){return["-NoProfile","-WindowStyle","Hidden","-EncodedCommand",Buffer.from(qne(t,e,r),"utf16le").toString("base64")]}function s1(t,e,r,i=process.platform,n){if(i==="win32"){let u=Vne(r),d=Hne(t,e),p=$ne(n);try{let f=t1(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));b.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:t,powershell:u},m);return}}let o="/usr/bin/setsid",s=Tm(o),a=s?o:t,c=si(a,s?[t,e,"--daemon"]:[e,"--daemon"],{detached:!0,stdio:"ignore",cwd:cw(),env:r});if(c.on("error",u=>{b.error("SYSTEM",r1,{runtimePath:t,execPath:a},u)}),c.pid!==void 0)return c.unref(),c.pid}function a1(t,e,r={}){Q_().assertCanSpawn("worker daemon");let i=or({...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r}),n=lw();if(!n){b.error("SYSTEM",r1);return}return s1(n,t,i)}function l1(){try{if(!Tm(oa))return;let t=new Date;jne(oa,t,t)}catch{}}function sd(t={}){return ew({logAlive:!1,removeStale:t.removeStale})}var Qj,Cje,oa,r1,aw,Bne,Gne,Cm=v(()=>{"use strict";Gr();ge();zo();V_();td();Kj();xm();Me();na();dn();Qj=lo(Mt.POWERSHELL_COMMAND);Cje=Je.dataDir(),oa=Je.workerPid(),r1="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.";Bne=5e3,Gne=8});function uw(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"&&Yne.has(r.code)||uw(r.cause,e)?!0:Array.isArray(r.errors)&&r.errors.some(i=>uw(i,e))}function Ml(t){return uw(t,new Set)?!0:t instanceof Error&&t.message.includes("ECONNREFUSED")}function c1(t){let e=t?.code;return e==="EACCES"||e==="EADDRNOTAVAIL"}var Yne,Am,Nl=v(()=>{"use strict";Yne=new Set(["ECONNREFUSED","ConnectionRefused"]);Am="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 Zne from"net";function dw(){return Ne.loadFromFile(Le).CLAUDE_MEM_WORKER_HOST}function u1(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}async function Xne(t,e,r="GET",i=ad){let n=await fetch(`http://${u1(dw())}:${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 pw(t,e=ad){let r=Date.now()+e;if(process.platform==="win32")try{let n=await fetch(`http://${u1(dw())}:${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 d1(t,Math.max(1,r-Date.now()));return i==="occupied"||i==="indeterminate"}async function d1(t,e=ad){return(await fw(t,e)).occupancy}function fw(t,e=ad){return e<=0?Promise.resolve({occupancy:"indeterminate"}):new Promise(r=>{let i=!1,n=!1,o=!1,s;try{s=Zne.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"}):c1(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,dw())}catch{try{s.close()}catch{}c({occupancy:"indeterminate"})}})}async function p1(t,e,r,i){let n=Date.now()+r;for(;Date.now()<n;){try{let s=n-Date.now();if((await Xne(t,e,"GET",Math.min(ad,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 Wo(t,e=3e4){return p1(t,"/api/health",e,"Service not ready yet, will retry")}function Kl(t,e=3e4){return p1(t,"/api/readiness",e,"Worker not ready yet, will retry")}var ad,ld=v(()=>{"use strict";ge();qr();Me();Nl();ad=5e3});var f1=v(()=>{"use strict";ge();td()});var m1=v(()=>{"use strict";Cm();ld();f1()});import{dirname as Qne,join as eie}from"path";import{mkdirSync as tie,readFileSync as Om,statSync as h1,unlinkSync as y1,utimesSync as rie,writeFileSync as nie}from"fs";function hw(){return eie(un(),"spawn.lock")}function mw(t){try{let e=JSON.parse(Om(t,"utf-8"));return typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0?null:e.pid}catch{return null}}function sie(t){if(t===null)return null;try{return process.kill(t,0),!0}catch(e){return e?.code==="EPERM"}}function Dm(){let t=hw(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return tie(Qne(t),{recursive:!0}),nie(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=h1(t).mtimeMs}catch{continue}let a=mw(t),l=null;if(a===null)try{l=Om(t,"utf-8")}catch{continue}if(Date.now()-s<=Rm&&sie(a)!==!1)return!1;let u;try{u=h1(t).mtimeMs}catch{continue}if(u!==s)return!1;if(a!==null){if(mw(t)!==a)return!1}else try{if(Om(t,"utf-8")!==l)return!1}catch{continue}try{y1(t)}catch{return!1}}return!1}function Pm(){let t=hw();try{if(JSON.parse(Om(t,"utf-8")).pid!==process.pid)return;y1(t)}catch{}}async function yw(t,e=iie){let r=Date.now()+t;for(;!Dm();){if(Date.now()>=r)return null;await new Promise(n=>setTimeout(n,oie))}let i=setInterval(aie,e);return i.unref(),()=>{clearInterval(i),Pm()}}function aie(){let t=hw();try{if(mw(t)!==process.pid)return;let e=new Date;rie(t,e,e)}catch{}}var Rm,iie,oie,Mm=v(()=>{"use strict";Me();ge();Rm=9e4,iie=Rm/3,oie=250});import{execFile as lie}from"node:child_process";import{promisify as cie}from"node:util";function g1(t){return uie.test(t.trim())}function die(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 Km(t,e){return e===void 0?t:Math.max(1,Math.min(t,e))}async function pie(t){try{let e=await Nm("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:Km(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 fie(t,e){try{let r=await Nm("netstat",["-ano"],{timeout:Km(15e3,e),windowsHide:!0,maxBuffer:16777216});return gie(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 mie(t,e){try{let r=await Nm("lsof",["-nP",`-iTCP:${t}`,"-sTCP:LISTEN","-t"],{timeout:Km(1e4,e),maxBuffer:1048576});return hie(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 hie(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]}async function yie(t,e){try{let i=(await Nm("ps",["-p",String(t),"-o","command="],{timeout:Km(5e3,e)})).stdout.trim();return i.length>0?i:null}catch{return null}}function gie(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 vie(t,e){let r=e.readOwnedWorker();if(r===null||r.port!==t)return null;let i=(c,u={})=>(b.info("PROCESS","Wedged-worker reclaim declined",{port:t,pid:r.pid,reason:c,...u}),{reclaimed:!1,reason:c,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 c=0;c<2;c++)if(c>0&&await e.sleep(E1),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=await e.readIdentity(r.pid),a=r.startToken!==void 0&&s.startToken!==null&&s.startToken!==r.startToken;if(a||s.cmdline===null||!bie.test(s.cmdline))return i("owner-identity-mismatch",{tokenMismatch:a,hasCmdline:s.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:s.startToken??r.startToken??void 0,signalMode:"graceful"})}catch(c){return b.error("PROCESS","Wedged-worker reclaim tree-kill failed",{port:t,pid:r.pid},c instanceof Error?c:new Error(String(c))),{reclaimed:!1,reason:"kill-failed",killedPids:[]}}let l=await e.listOwners(t);return l!==null&&l.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:l}),{reclaimed:!1,reason:"still-bound",killedPids:[r.pid]})}async function Eie(t,e,r,i){let n=Oi(t),o=e?(await r(i))?.find(s=>s.pid===t)?.cmdline??null:await yie(t,i);return ai(t,n)?{startToken:n,cmdline:o}:{startToken:null,cmdline:null}}async function bw(t,e={}){let r=e.isWin32??(()=>process.platform==="win32"),i=e.now??Date.now,n=e.deadlineAt??null,o=G=>n!==null&&n-i()<G,s=()=>n===null?void 0:Math.max(1,n-i());if(o(b1))return b.info("PROCESS","Port reclaim skipped: not enough of the hook budget is left to finish one",{port:t,remainingMs:s(),neededMs:b1}),{reclaimed:!1,reason:"out-of-budget",killedPids:[]};let a=e.listOwners??((G,Q)=>r()?fie(G,Q):mie(G,Q)),l=G=>a(G,s()),c=e.readTable??pie,u=()=>c(s()),d=e.killTree??((G,Q)=>li(G,Q)),p=e.dataDir??(()=>We),f=e.readIdentity??((G,Q)=>Eie(G,r(),c,Q)),m=await vie(t,{listOwners:l,killTree:d,readOwnedWorker:e.readOwnedWorker??Ri,probeHealth:e.probeHealth??(G=>Wo(G,v1)),readIdentity:G=>f(G,s()),minOwnerAgeSeconds:e.minOwnerAgeSeconds??zK(),now:i,sleep:e.sleep??(G=>new Promise(Q=>setTimeout(Q,G))),hasKillBudget:()=>!o(gw)});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 g=await u();if(g===null)return{reclaimed:!1,reason:"table-unreadable",killedPids:[]};if(h.filter(G=>kt(G)).length>0)return{reclaimed:!1,reason:"owner-alive",killedPids:[]};let E=new Map;for(let G of g){let Q=E.get(G.ppid);Q?Q.push(G):E.set(G.ppid,[G])}let x=new Map,O=new Set,M=G=>{for(let Q of E.get(G)??[])O.has(Q.pid)||(O.add(Q.pid),M(Q.pid),g1(Q.name)&&x.set(Q.pid,Q))};for(let G of h)M(G);let q=p();if(q)for(let G of g)x.has(G.pid)||g1(G.name)&&die(G.cmdline,q)&&x.set(G.pid,G);if(x.size===0)return b.info("PROCESS","Ghost listener owner is dead but no chroma-sidecar descendants found",{port:t,deadOwners:h,processTableRows:g.length,dataDir:q??"(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:[...x.values()].map(G=>({pid:G.pid,name:G.name}))});let F=[];for(let G of x.values()){if(o(gw))return b.info("PROCESS","Ghost-listener reclaim stopped before a kill: the hook budget is spent",{port:t,killedPids:F}),{reclaimed:!1,reason:"out-of-budget",killedPids:F};try{await d(G.pid,{expectedStartToken:G.startToken,signalMode:"immediate"}),F.push(G.pid)}catch(Q){return b.error("PROCESS","Ghost-port reclaim tree-kill failed",{port:t,pid:G.pid},Q instanceof Error?Q:new Error(String(Q))),{reclaimed:!1,reason:"kill-failed",killedPids:F}}}let ie=await l(t);return ie!==null&&ie.length===0?(b.info("PROCESS","Ghost listener reclaimed \u2014 port is free again",{port:t,killedPids:F}),{reclaimed:!0,killedPids:F}):(b.warn("PROCESS","Ghost-port reclaim killed the sidecar chain but the port is still bound",{port:t,killedPids:F,stillOwnedBy:ie}),{reclaimed:!1,reason:"still-bound",killedPids:F})}var Nm,uie,bie,v1,E1,gw,b1,vw=v(()=>{"use strict";ge();Ol();dn();td();ld();gm();na();Me();Nm=cie(lie),uie=/^(uv|uvx|python|chroma-mcp)(\.exe)?$/i;bie=/worker-service/i,v1=1500,E1=1e3,gw=5500,b1=2*v1+E1+gw});import{existsSync as Sie,readFileSync as _ie,realpathSync as wie}from"fs";import{createRequire as kie}from"module";import sa from"path";function S1(t){try{return wie(t)}catch{return t}}function xie(t,e){let r=sa.relative(e,t);return r!==""&&!r.startsWith("..")&&!sa.isAbsolute(r)}function Ew(t){let e;try{let n=JSON.parse(_ie(sa.join(t,"package.json"),"utf-8"));e=Object.keys(n?.dependencies??{})}catch{return[]}if(e.length===0)return[];let r=sa.join(t,"node_modules"),i=e.filter(n=>!Sie(sa.join(r,...n.split("/"),"package.json")));if(e.includes("zod")&&!i.includes("zod")){let n=kie(sa.join(r,"noop.js")),o=S1(sa.join(r,"zod"));for(let s of Iie)try{let a=n.resolve(s,{paths:[r]});xie(S1(a),o)||i.push(s)}catch{i.push(s)}}return i}var Iie,_1=v(()=>{"use strict";Iie=["zod/v3","zod/v4","zod/v4-mini"]});import Nt from"path";import{randomUUID as b1e}from"crypto";import{readFileSync as Tie,existsSync as Um,writeFileSync as E1e,renameSync as S1e,mkdirSync as _1e,readdirSync as Cie,statSync as Aie,unlinkSync as w1e}from"fs";function x1(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 T1(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 Rie(t){return T1()?{...t,verbose:!0}:t}function Die(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 Pie(t,e,r){let i=typeof e.method=="string"?e.method:"GET",n=Die(r),o=JSON.stringify(n);b.warn("SYSTEM","Worker IPC fetch failed",{url:t,method:i},o),ii(`[claude-mem] fetch verbose: ${i} ${t} ${o}
|
|
19
19
|
`)}async function ww(t,e={}){let r=Rie(e);try{return await fetch(t,r)}catch(i){throw T1()&&Pie(t,e,i),i}}async function Mie(t,e={},r){try{return await ww(t,{...e,signal:AbortSignal.timeout(r)})}catch(i){throw i instanceof DOMException&&i.name==="TimeoutError"?new Error(`Request timed out after ${r}ms`):i}}function Nie(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 Kie(t,e,r){let i=Nie(r,e.signal),n;try{n=await ww(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 jie(t,e,r){let i=await Kie(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 w1(){return Nt.join(Ne.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function kw(t={}){return t.readOnly?Ne.loadFromFile(w1(),!0,t):(jm!==null||(jm=Ne.loadFromFile(w1())),jm)}function k1(t,e){if(!t)return null;let r=parseInt(t,10);return Number.isFinite(r)&&r>=e.min&&r<=e.max?r:null}function Lie(t,e,r){let i=process.env[t];if(i!==void 0){let s=k1(i,r);return s!==null?s:(b.warn("SYSTEM",`Invalid ${t}, using default`,{value:i,min:r.min,max:r.max}),e)}let n=kw()[t],o=k1(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 co(t={}){if(!t.readOnly&&Sw!==null)return Sw;let e=parseInt(kw(t).CLAUDE_MEM_WORKER_PORT,10);return t.readOnly||(Sw=e),e}function cd(t={}){if(!t.readOnly&&_w!==null)return _w;let e=kw(t).CLAUDE_MEM_WORKER_HOST;return t.readOnly||(_w=e),e}function Uie(){return Lm!==null||(Lm=Lie("CLAUDE_MEM_API_TIMEOUT_MS",lo(Mt.API_REQUEST),Oie)),Lm}function Iw(t){return`http://${Ai(cd())}:${co()}${t}`}function jl(t,e={}){let r=e.method??"GET",i=Iw(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 jie(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??Uie();return o>0?Mie(i,n,o):ww(i,n)}function C1(t){let e=Um(Nt.join(t,"plugin","scripts"))?Nt.join(t,"plugin"):t;return Nt.join(e,"scripts","worker-service.cjs")}function xw(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 Tw(t=Nt.join(Nt.dirname(Nt.dirname(zr)),"cache","thedotmack","claude-mem")){try{return Cie(t).filter(e=>/^\d/.test(e)).map(e=>Nt.join(t,e)).filter(e=>{try{if(!Aie(e).isDirectory())return!1}catch{return!1}return!Um(Nt.join(e,".orphaned_at"))}).map(e=>({scriptPath:C1(e),version:Nt.basename(e)}))}catch{return[]}}function I1(t){try{let e=JSON.parse(Tie(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 A1(){return{cacheRoot:Nt.join(Nt.dirname(Nt.dirname(zr)),"cache","thedotmack","claude-mem"),marketplaceRoot:zr,cwd:process.cwd()}}function Cw(t=A1()){let e=process.env.CLAUDE_MEM_WORKER_SCRIPT_PATH?.trim();if(e){if(Um(e))return{scriptPath:e,version:null};b.debug("SYSTEM","Ignoring missing CLAUDE_MEM_WORKER_SCRIPT_PATH override",{override:e})}let r=[...Tw(t.cacheRoot),{scriptPath:C1(Nt.join(t.marketplaceRoot,"plugin")),version:I1(Nt.join(t.marketplaceRoot,"package.json"))},{scriptPath:Nt.join(t.cwd,"plugin","scripts","worker-service.cjs"),version:I1(Nt.join(t.cwd,"package.json"))}];return Aw(r)}function O1(t){return Nt.dirname(Nt.dirname(t))}function $ie(t){return Ew(O1(t.scriptPath)).length===0}function Aw(t,e=$ie){let r=t.filter(i=>Um(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:xw(i.version,n.version)),r.find(e)??r[0])}function Ll(t=A1()){let e=Cw(t);if(!e)return null;let r=O1(e.scriptPath);return{root:r,version:e.version,missingDependencies:Ew(r)}}var G1e,W1e,Oie,V1e,Sw,_w,jm,Lm,Fie,Jie,H1e,Di=v(()=>{"use strict";ge();na();BK();qr();Me();ej();hm();tj();L_();td();Xu();nd();m1();ld();Nl();Cm();Mm();vw();zo();Ol();Pt();_1();L_();G1e=x1("CLAUDE_MEM_HEALTH_TIMEOUT_MS",lo(Mt.HEALTH_CHECK),{min:500,max:3e5}),W1e=x1("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",lo(Mt.HOOK_READINESS_WAIT),{min:0,max:3e5}),Oie={min:500,max:3e5},V1e={min:500,max:Mt.SESSION_INIT_REQUEST_MAX};Sw=null,_w=null,jm=null,Lm=null;Fie=1e3,Jie=5e3,H1e=Jie+Fie});import{existsSync as Ow,readFileSync as R1}from"fs";import{homedir as zie}from"os";import{dirname as qie,join as fn}from"path";import{fileURLToPath as Bie}from"url";function Rw(){return process.env.CLAUDE_CONFIG_DIR||fn(zie(),".claude")}function yr(){return fn(Rw(),"plugins","marketplaces","thedotmack")}function aa(){return fn(Rw(),"plugins")}function Ul(){return fn(aa(),"known_marketplaces.json")}function Vo(){return fn(aa(),"installed_plugins.json")}function Ho(){return fn(Rw(),"settings.json")}function $l(){return fn(aa(),"cache","thedotmack","claude-mem")}function Fl(t){return fn($l(),t)}function la(){let t=Bie(import.meta.url),e=fn(qie(t),"..","..");if(!Ow(fn(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 Dw(){return fn(la(),"plugin")}function Yo(){let t=fn(Dw(),".claude-plugin","plugin.json");if(Ow(t))try{let r=JSON.parse(R1(t,"utf-8"));if(r.version)return r.version}catch{}let e=fn(la(),"package.json");if(Ow(e))try{let r=JSON.parse(R1(e,"utf-8"));if(r.version)return r.version}catch{}return"0.0.0"}function D1(){return Ll()!==null}var vt,ci=v(()=>{"use strict";Pt();Di();qo();vt=process.platform==="win32"});var M1,N1,K1,j1=v(()=>{M1=(()=>{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}})(),N1=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,K1=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 Gie,Wie,L1,Vie,U1,Hie,Yie,Zie,$1,F1,J1=v(()=>{j1();Gie=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Wie=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,L1=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,Vie=/\t{1,1000}/y,U1=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"),Hie=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Yie=new RegExp("\\p{M}+","gu"),Zie={limit:1/0,ellipsis:""},$1=(t,e={},r={})=>{let i=e.limit??1/0,n=e.ellipsis??"",o=e?.ellipsisWidth??(n?$1(n,Zie,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=[[Hie,d],[Gie,s],[Wie,a],[Vie,l],[U1,c],[L1,p]],m=0,h=0,g=t.length,S=0,E=!1,x=g,O=Math.max(0,i-o),M=0,q=0,F=0,ie=0;e:for(;;){if(q>M||h>=g&&h>m){let G=t.slice(M,q)||t.slice(m,h);S=0;for(let Q of G.replaceAll(Yie,"")){let Ce=Q.codePointAt(0)||0;if(N1(Ce)?ie=u:K1(Ce)?ie=p:ie=d,F+ie>O&&(x=Math.min(x,Math.max(M,m)+S)),F+ie>i){E=!0;break e}S+=Q.length,F+=ie}M=q=0}if(h>=g)break e;for(let G=0,Q=f.length;G<Q;G++){let[Ce,wt]=f[G];if(Ce.lastIndex=h,Ce.test(t)){if(S=Ce===L1?M1(t.slice(h,Ce.lastIndex)):Ce===U1?1:Ce.lastIndex-h,ie=S*wt,F+ie>O&&(x=Math.min(x,h+Math.floor((O-F)/wt))),F+ie>i){E=!0;break e}F+=ie,M=m,q=h,h=m=Ce.lastIndex;continue e}}h+=1}return{width:E?O:F,index:E?x:g,truncated:E,ellipsed:E&&i>=o}},F1=$1});var Xie,Qie,xr,Pw=v(()=>{J1();Xie={limit:1/0,ellipsis:"",ellipsisWidth:0},Qie=(t,e={})=>F1(t,Xie,e).width,xr=Qie});function Pi(t,e,r){return String(t).normalize().split(ioe).map(i=>noe(i,e,r)).join(`
|
|
@@ -202,7 +202,7 @@ Plugin source: ${e}
|
|
|
202
202
|
|
|
203
203
|
Next steps:
|
|
204
204
|
1. Open Codex CLI in your project
|
|
205
|
-
2. Review and trust the
|
|
205
|
+
2. Review and trust the six claude-mem hooks when Codex prompts you
|
|
206
206
|
3. Restart sessions opened before trusting the hooks
|
|
207
207
|
|
|
208
208
|
For a fresh setup, the supported entry point is:
|
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": "13.
|
|
6
|
+
"version": "13.39.0",
|
|
7
7
|
"license": "Apache-2.0",
|
|
8
8
|
"author": "thedotmack",
|
|
9
9
|
"homepage": "https://claude-mem.ai",
|
package/package.json
CHANGED
|
@@ -62,6 +62,18 @@
|
|
|
62
62
|
}
|
|
63
63
|
]
|
|
64
64
|
}
|
|
65
|
+
],
|
|
66
|
+
"PostCompact": [
|
|
67
|
+
{
|
|
68
|
+
"hooks": [
|
|
69
|
+
{
|
|
70
|
+
"type": "command",
|
|
71
|
+
"command": "_HP=$(printenv PATH 2>/dev/null || true); if [ -z \"$_HP\" ] && [ -n \"${SHELL:-}\" ]; then _HP=$(\"$SHELL\" -lc 'printf %s \"$PATH\"' 2>/dev/null || true); fi; _HP=$(printf '%s' \"$_HP\" | tr ' ' ':'); export PATH=\"${_HP:+$_HP:}$PATH\"; _C=\"${CLAUDE_CONFIG_DIR:-$HOME/.claude}\"; _E=\"${CLAUDE_PLUGIN_ROOT:-${PLUGIN_ROOT:-}}\"; _P=; if [ -n \"$_E\" ]; then _R=\"${_E%/}\"; [ -d \"$_R/plugin/scripts\" ] && _Q=\"$_R/plugin\" || _Q=\"$_R\"; [ -f \"$_Q/scripts/bun-runner.js\" ] && [ -f \"$_Q/scripts/worker-service.cjs\" ] && _P=\"$_Q\"; fi; if [ -z \"$_P\" ]; then _F=; _P=$({ for _V in \"$_C/plugins/cache/thedotmack/claude-mem\"/[0-9]*/; do [ -d \"$_V\" ] || continue; [ -e \"${_V}.orphaned_at\" ] && continue; _B=${_V%/}; _B=${_B##*/}; case \"$_B\" in (*-*) _G=0;; (*) _G=1;; esac; _N=${_B%%-*}; _M1=${_N%%.*}; case \"$_N\" in (*.*) _T=${_N#*.};; (*) _T=0;; esac; _M2=${_T%%.*}; case \"$_T\" in (*.*) _U=${_T#*.};; (*) _U=0;; esac; _M3=${_U%%.*}; _M1=${_M1%%[!0-9]*}; _M2=${_M2%%[!0-9]*}; _M3=${_M3%%[!0-9]*}; printf '%08d%08d%08d%d %s\\n' \"${_M1:-0}\" \"${_M2:-0}\" \"${_M3:-0}\" \"$_G\" \"$_V\"; done 2>/dev/null | sort -r | sed 's/^[^ ]* //'; printf '%s\\n' \"$_C/plugins/marketplaces/thedotmack/plugin\"; } | while IFS= read -r _R; do _R=\"${_R%/}\"; [ -d \"$_R/plugin/scripts\" ] && _Q=\"$_R/plugin\" || _Q=\"$_R\"; [ -f \"$_Q/scripts/bun-runner.js\" ] && [ -f \"$_Q/scripts/worker-service.cjs\" ] && [ -z \"$_F\" ] && { _F=1; printf '%s\\n' \"$_Q\"; }; done); fi; [ -n \"$_P\" ] || { echo \"claude-mem: plugin scripts not found\" >&2; exit 1; }; command -v cygpath >/dev/null 2>&1 && { _W=$(cygpath -w \"$_P\" 2>/dev/null); [ -n \"$_W\" ] && _P=\"$_W\"; }; CLAUDE_MEM_CODEX_HOOK=1 node \"$_P/scripts/bun-runner.js\" \"$_P/scripts/worker-service.cjs\" hook codex post-compact",
|
|
72
|
+
"timeout": 20,
|
|
73
|
+
"commandWindows": "node -e \"const fs=require('fs'),p=require('path'),o=require('os'),c=require('child_process');const h=o.homedir();const C=process.env.CLAUDE_CONFIG_DIR||p.join(h,'.claude');const roots=[];for(const v of [process.env.CLAUDE_PLUGIN_ROOT,process.env.PLUGIN_ROOT])if(v)roots.push(v);const cache=p.join(C,'plugins','cache','thedotmack','claude-mem');const S=n=>{const q=n.split('-')[0].split('.');return[parseInt(q[0],10)||0,parseInt(q[1],10)||0,parseInt(q[2],10)||0]};const W=(a,b)=>{const x=S(a),y=S(b);return(y[0]-x[0])||(y[1]-x[1])||(y[2]-x[2])||((a.indexOf('-')<0?0:1)-(b.indexOf('-')<0?0:1))||(a<b?1:a>b?-1:0)};try{roots.push(...fs.readdirSync(cache).filter(n=>{const ch=n.charAt(0);return ch>='0'&&ch<='9'}).map(n=>p.join(cache,n)).filter(r=>{try{return fs.statSync(r).isDirectory()&&!fs.existsSync(p.join(r,'.orphaned_at'))}catch{return false}}).sort((a,b)=>W(p.basename(a),p.basename(b))))}catch{}roots.push(p.join(C,'plugins','marketplaces','thedotmack','plugin'));let R=null;for(const k of roots){const r=fs.existsSync(p.join(k,'plugin','scripts'))?p.join(k,'plugin'):k;if(fs.existsSync(p.join(r,'scripts','bun-runner.js'))&&fs.existsSync(p.join(r,'scripts','worker-service.cjs'))){R=r;break}}if(!R){process.stderr.write('claude-mem: plugin scripts not found\\n');process.exit(1)}const env={...process.env,CLAUDE_MEM_CODEX_HOOK:'1'};const workerArgs=['hook','codex','post-compact'];const args=[p.join(R,'scripts','bun-runner.js'),p.join(R,'scripts','worker-service.cjs'),...workerArgs];const res=c.spawnSync(process.execPath,args,{stdio:'inherit',env});if(res.error){process.stderr.write(String(res.error.message||res.error)+'\\n');process.exit(1)}process.exit(res.status==null?0:res.status)\""
|
|
74
|
+
}
|
|
75
|
+
]
|
|
76
|
+
}
|
|
65
77
|
]
|
|
66
78
|
}
|
|
67
79
|
}
|