claude-mem 15.0.0 → 15.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/.qoder-plugin/plugin.json +1 -1
- package/README.md +1 -1
- package/dist/npx-cli/index.js +2 -2
- package/dsh/package.json +1 -1
- package/openclaw/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/.codex-plugin/plugin.json +1 -1
- package/plugin/.qoder-plugin/plugin.json +1 -1
- package/plugin/package.json +1 -1
- package/plugin/scripts/mcp-server.cjs +48 -48
- package/plugin/scripts/mcp-server.cjs.map +1 -1
- package/plugin/scripts/server-service.cjs +2 -2
- package/plugin/scripts/transcript-watcher.cjs +1 -1
- package/plugin/scripts/worker-service.cjs +390 -390
- package/plugin/scripts/worker-service.cjs.map +2 -2
- package/plugin/sqlite/SessionStore.js +136 -136
- package/plugin/sqlite/SessionStore.js.map +2 -2
package/README.md
CHANGED
|
@@ -59,7 +59,7 @@
|
|
|
59
59
|
<img src="https://img.shields.io/badge/License-Apache%202.0-blue.svg" alt="License">
|
|
60
60
|
</a>
|
|
61
61
|
<a href="package.json">
|
|
62
|
-
<img src="https://img.shields.io/badge/version-15.0.
|
|
62
|
+
<img src="https://img.shields.io/badge/version-15.0.1-green.svg" alt="Version">
|
|
63
63
|
</a>
|
|
64
64
|
<a href="package.json">
|
|
65
65
|
<img src="https://img.shields.io/badge/node-%3E%3D20.0.0-brightgreen.svg" alt="Node">
|
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){$w=e}error(e,r,i,n){this.log(3,e,r,i,n),this.routeErrorToSink(r,i,n)}routeErrorToSink(e,r,i){try{if(!$w||!(i instanceof Error))return;$w(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 Jw});function U1(t=process.env){let e=Number.parseInt(t.CLAUDE_MEM_WEDGED_WORKER_UPTIME_S??"",10);return Number.isFinite(e)&&e>=K1.min&&e<=K1.max?e:Qie}function $1(t=process.platform){return t==="win32"?8e3:5e3}function Bw(t=process.platform){return Nt.SESSION_INIT_HOOK_CAP-$1(t)}function _o(t){return process.platform==="win32"?Math.round(t*Nt.WINDOWS_MULTIPLIER):t}var Nt,Qie,K1,_a=v(()=>{"use strict";Nt={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},Qie=300,K1={min:60,max:86400}});var F1=v(()=>{"use strict"});function J1(t){try{return new URL(t).hostname.toLowerCase()==="openrouter.ai"}catch{return!1}}var B1=v(()=>{"use strict";he()});import{readFileSync as eoe,existsSync as z1,writeFileSync as toe}from"fs";import{basename as roe,dirname as noe,join as qw}from"path";import{homedir as q1,hostname as ioe}from"os";function uoe(t){return typeof t=="boolean"?String(t):t}function doe(t){let e=t.CLAUDE_MEM_OPENROUTER_MODEL;if(typeof e!="string"||!coe.has(e.trim()))return!1;let r=typeof t.CLAUDE_MEM_OPENROUTER_BASE_URL=="string"?t.CLAUDE_MEM_OPENROUTER_BASE_URL.trim():"";return r===""||J1(r)}function H1(t,e){return qw(noe(t),`.${roe(t)}.${e.markerTag}`)}function zw(t,e){try{toe(H1(t,e),new Date().toISOString(),{encoding:"utf-8",mode:384})}catch{}}function poe(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===soe||r===aoe)return loe}catch{return null}return null}var ooe,soe,aoe,loe,coe,G1,W1,V1,Te,gr=v(()=>{"use strict";_a();gt();B1();pi();ooe="security_alert",soe="sync-hub.black-pond-afbb.workers.dev",aoe="ziczmqtpmaxbornfghye.supabase.co",loe="https://sync.cmem.ai",coe=new Set(["xiaomi/mimo-v2-flash:free"]);G1=18e4,W1=[{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"}];V1=new Set;Te=class{static DEFAULTS={CLAUDE_MEM_MEMORY_SEARCH_HOOK_ENABLED:"true",CLAUDE_MEM_MEMORY_INSTRUCTIONS_ENABLED:"true",CLAUDE_MEM_MEMORY_WATCH_ROOTS:"",CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_SESSION_START_INCLUDE_ALL_SOURCES:"false",CLAUDE_MEM_CONTEXT_PROJECTS:"current",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_WORKER_INGEST_TOKEN:"",CLAUDE_MEM_WORKER_INGEST_MAX_BYTES:"5242880",CLAUDE_MEM_HOOK_SPOOL_TRANSPORT:"auto",CLAUDE_MEM_ALLOWED_ORIGINS:"",CLAUDE_MEM_PUBLIC_URL:"",CLAUDE_MEM_API_TIMEOUT_MS:String(_o(Nt.API_REQUEST)),CLAUDE_MEM_SESSION_INIT_TIMEOUT_MS:String(Bw()),CLAUDE_MEM_IDLE_EXIT_SEC:"0",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_SKIP_BASH_PATTERNS:"",CLAUDE_MEM_SKIP_SUBAGENT_OBSERVATIONS:"false",CLAUDE_MEM_SKIP_AGENT_TYPES:"",CLAUDE_MEM_CAPTURE_ADVISOR_CALLS:"false",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CODEX_MODEL:"",CLAUDE_MEM_CODEX_PATH:"codex",CLAUDE_MEM_CODEX_REASONING_EFFORT:"low",CLAUDE_MEM_CODEX_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_CODEX_OBSERVATION_BATCH_SIZE:"8",CLAUDE_MEM_CODEX_OBSERVATION_BATCH_MAX_CHARS:"32000",CLAUDE_MEM_CLAUDE_OBSERVATION_BATCH_SIZE:"1",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_API_KEYS:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-flash-latest",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_API_KEYS:"",CLAUDE_MEM_OPENROUTER_MODEL:"cohere/north-mini-code:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_TEMPERATURE:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_EXTRA_BODY:"",CLAUDE_MEM_OPENROUTER_REASONING_EFFORT:"",CLAUDE_MEM_OPENAI_COMPAT_PRESET:"",CLAUDE_MEM_OPENAI_COMPAT_API_KEY:"",CLAUDE_MEM_OPENAI_COMPAT_API_KEYS:"",CLAUDE_MEM_OPENAI_COMPAT_BASE_URL:"",CLAUDE_MEM_OPENAI_COMPAT_MODEL:"",CLAUDE_MEM_QUOTA_FALLBACK_PROVIDER:"claude",CLAUDE_MEM_QUOTA_FALLBACK_MODEL:"",CLAUDE_MEM_QUOTA_FALLBACK_AUTH_METHOD:"",CLAUDE_MEM_QUOTA_THRESHOLD_FIVE_HOUR:"0.95",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY:"0.93",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY_OPUS:"0.93",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY_SONNET:"0.92",CLAUDE_MEM_QUOTA_THRESHOLD_OVERAGE:"0.95",CLAUDE_MEM_DATA_DIR:qw(q1(),".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:qw(q1(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_CODEX_SUBAGENT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_OBSERVER_MAX_CONVERSATION_CHARS:"400000",CLAUDE_MEM_OBSERVER_THINKING:"disabled",CLAUDE_MEM_OBSERVER_CONTEXT_WINDOW:"",CLAUDE_MEM_OBSERVER_MAX_OUTPUT_TOKENS:"4096",CLAUDE_MEM_OBSERVE_BARE_PROMPTS:"false",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_REDACT_ENABLED:"false",CLAUDE_MEM_REDACT_DISABLED_BUILTINS:"",CLAUDE_MEM_REDACT_CUSTOM_PATTERNS:"[]",CLAUDE_MEM_REDACT_LOG_MATCHES:"false",CLAUDE_MEM_REDACT_GENERIC_ENABLED:"false",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_PROJECT_ENVIRONMENTS:"[]",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_SEMANTIC_INJECT_FORMAT:"narrative",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_CHROMA_MUTATION_TIMEOUT_MS:"600000",CLAUDE_MEM_CHROMA_MAX_PENDING_MUTATIONS:"5000",CLAUDE_MEM_CHROMA_EMBEDDING_FUNCTION:"default",CLAUDE_MEM_CHROMA_UVX_PATH:"",CLAUDE_MEM_SEARCH_RECENCY_DAYS:"90",CLAUDE_MEM_CLOUD_SYNC_TOKEN:"",CLAUDE_MEM_CLOUD_SYNC_USER_ID:"",CLAUDE_MEM_CLOUD_SYNC_HUB_URL:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_ID:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_NAME:ioe(),CLAUDE_MEM_CLOUD_SYNC_WS:"true",CLAUDE_MEM_CLOUD_SYNC_CONTENT_BATCH_SIZE:"40",CLAUDE_MEM_CLOUD_SYNC_REQUEST_TIMEOUT_MS:"90000",CLAUDE_MEM_TEAMBRAIN_URL:"",CLAUDE_MEM_TEAMBRAIN_TEAM_ID:"",CLAUDE_MEM_LLM_TIMEOUT_MS:String(G1),CLAUDE_MEM_FIELD_OPTIMIZE_TIMEOUT_MS:String(G1),CLAUDE_MEM_LLM_STREAM_IDLE_TIMEOUT_MS:"90000",CLAUDE_MEM_WORKER_HEARTBEAT_STALE_MS:"120000",CLAUDE_MEM_TV_TOKEN:"",CLAUDE_MEM_PRO_TRIAL_EMAIL:"",CLAUDE_MEM_PRO_TRIAL_AT:"",CLAUDE_MEM_PRO_TRIAL_STATE:"",CLAUDE_MEM_PRO_TRIAL_ENDS_AT:"",CLAUDE_MEM_PRO_PLAN:"",CLAUDE_MEM_PRO_FALLBACK_AT:"",CLAUDE_MEM_PRO_FALLBACK_MESSAGE:"",CLAUDE_MEM_PRO_FALLBACK_ACTION:"",CLAUDE_MEM_PRO_FALLBACK_URL:"",CLAUDE_MEM_PRO_MEMORY_KEY:"",CLAUDE_MEM_PRO_MEMORY_BASE_URL:"",CLAUDE_MEM_PRO_MEMORY_MODEL:"",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_WRAPUPS_ENABLED:"true",CLAUDE_MEM_TELEGRAM_OBSERVATION_ALERTS_ENABLED:"false",CLAUDE_MEM_TELEGRAM_WRAPUP_ROUTES:"{}",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert,sensitive",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_AWARENESS_ENABLED:"true",CLAUDE_MEM_GROK_BOT_AWARENESS_AGENT_IDS:"521e962d-2ec3-4488-bfbc-54d5209ce118,95601360-61f7-4fd9-bb3a-2c976b2b85c0",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_WEBHOOK_URL:"",CLAUDE_MEM_GROK_BOT_WEBHOOK_SECRET:"",CLAUDE_MEM_GROK_BOT_INJECT_ENABLED:"true",CLAUDE_MEM_GROK_BOT_INJECT_AGENT_IDS:"*",CLAUDE_MEM_GROK_BOT_INJECT_TIER:"episode",CLAUDE_MEM_GROK_BOT_INJECT_WINDOW:"80",CLAUDE_MEM_GROK_BOT_INJECT_FALLBACK:"house",CLAUDE_MEM_GROK_BOT_INJECT_PLATFORM_SOURCE:"",CLAUDE_MEM_GROK_BOT_INJECT_PROJECTS_BY_AGENT:"",CLAUDE_MEM_GROK_BOT_INJECT_MAX_LINE_CHARS:"160",CLAUDE_MEM_GROK_BOT_INJECT_DEBOUNCE_MS:"1500",CLAUDE_MEM_GROK_BOT_INJECT_STANDING_LINE:"",CLAUDE_MEM_CCS_ALIGN_ENABLED:"true",CLAUDE_MEM_CCS_ALIGN_VIEWER_IDS:"ccs-align",CLAUDE_MEM_CCS_ALIGN_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_CCS_ALIGN_PATCH_SHADOWS:"false",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:"",CLAUDE_MEM_DEDUP_ENABLED:"false",CLAUDE_MEM_DEDUP_COSINE_THRESHOLD:"0.80",CLAUDE_MEM_DEDUP_IDF_VETO_DF:"10",CLAUDE_MEM_DEDUP_MIN_SHARED_TOKENS:"2",CLAUDE_MEM_DEDUP_MIN_PROJECT_DOCS:"10",CLAUDE_MEM_DEDUP_MAX_SCAN:"2000",CLAUDE_MEM_DEDUP_MAX_BACKFILL_ROWS:"50000",CLAUDE_MEM_TOOL_USES_RETENTION_DAYS:"0",CLAUDE_MEM_WORKER_AUTOSTART:"true",CLAUDE_MEM_PROJECT_NAME_SOURCE:"path"};static getAllDefaults(){return{...this.DEFAULTS}}static get(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(!z1(e)){let p=this.getAllDefaults();if(!i.readOnly)try{Je(e,p,{mode:384});for(let f of W1)zw(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=eoe(e,"utf-8"),o=Rr(n),s=di(o),a=s!==o,l=Nw(o),c=a&&Object.keys(l).some(p=>p!=="env");if(a&&!c&&!i.readOnly)try{Je(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===ooe&&(s={...s,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES},!i.readOnly))try{Je(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(doe(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{Je(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=poe(s.CLAUDE_MEM_CLOUD_SYNC_HUB_URL);if(u!==null&&(s={...s,CLAUDE_MEM_CLOUD_SYNC_HUB_URL:u},!i.readOnly))try{Je(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 W1)if(!z1(H1(e,p))){if(s[p.key]!==p.legacy){i.readOnly||zw(e,p);continue}if(s={...s,[p.key]:this.DEFAULTS[p.key]},!i.readOnly)try{Je(e,c?{...l,env:s}:s,{mode:384}),zw(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}`;V1.has(m)||(V1.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]=uoe(s[p]));return this.finalizeSettings(d,r)}catch(n){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,n instanceof Error?n.message:String(n));let o=this.getAllDefaults();return this.finalizeSettings(o,r)}}}});function Gw(){return ih!==null||(ih=Te.loadFromFile(we)),ih}var ih,Ww=v(()=>{"use strict";gr();Oe();ih=null});function Zl(t){return(t.CLAUDE_MEM_WORKER_AUTOSTART??"true").trim().toLowerCase()==="false"}var oh=v(()=>{"use strict"});var Y1=v(()=>{"use strict"});function Fi(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}var Vw=v(()=>{"use strict"});import{spawn as foe,spawnSync as X1}from"node:child_process";import{existsSync as moe}from"node:fs";import{dirname as hoe,extname as sh,join as Q1}from"node:path";function fi(t,e,r){return foe(t,e??[],{...r,windowsHide:!0})}function yoe(t){return`"${t.replace(/"/g,'""')}"`}function Z1(t){return eK.has(sh(t).toLowerCase())}function boe(t=process.env){let e=t.SystemRoot||t.SYSTEMROOT||t.windir||t.WINDIR||"C:\\Windows";return Q1(e,"System32","where.exe")}function Yw(t){if(process.platform!=="win32")return[];try{let e=X1(boe(),[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=>moe(r))}catch{return[]}}function Soe(t,e){let r=t.find(Z1);if(r)return r;let i=t.find(n=>Hw.has(sh(n).toLowerCase()));if(i&&e){let n=e(i);if(n&&Z1(n))return n}return i??t.find(n=>goe.has(sh(n).toLowerCase()))??t[0]??null}function _oe(t,e,r=Eoe){if(!/[\\/]volta[\\/]bin[\\/]/i.test(e))return null;try{let i=r(Q1(hoe(e),"volta.exe"),["which",t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:voe,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 Jn(t){return Soe(Yw(t),e=>_oe(t,e))}function yr(t,e,r,i=process.platform){let n={...r,...i==="win32"?{windowsHide:!0}:{}};if(i==="win32"&&Hw.has(sh(t).toLowerCase())){let o=[t,...e].map(yoe).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 Hw,eK,goe,voe,Eoe,Zr=v(()=>{"use strict";Hw=new Set([".cmd",".bat"]),eK=new Set([".exe",".com"]),goe=new Set([...eK,...Hw]);voe=5e3,Eoe=(t,e,r)=>X1(t,e,r)});function or(t=process.env){let e={};for(let[r,i]of Object.entries(t))if(i!==void 0){if(xoe.has(r)){e[r]=i;continue}koe.has(r)||woe.some(n=>r.startsWith(n))||(e[r]=i)}return e}var woe,koe,Ioe,xoe,ss=v(()=>{"use strict";woe=["CLAUDECODE_","CLAUDE_CODE_"],koe=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),Ioe=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"]),xoe=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",...Ioe])});import{spawnSync as rK}from"child_process";import{readFileSync as Toe}from"fs";function nK(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 Coe(t){Zw+=1;let e=rK("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 nK("powershell-cim",t,e)}function Ooe(t,e=!1){if(!e){let i=tK.get(t);if(i&&(t===process.pid||Date.now()-i.capturedAtMs<Aoe))return i.token}let r=null;try{r=Coe(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)&&tK.set(t,{token:r,capturedAtMs:Date.now()}),r}function iK(t,e){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux"){Zw+=1;try{let r=Toe(`/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 Ooe(t,e);Zw+=1;try{let r=rK("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...or(process.env),LC_ALL:"C",LANG:"C"}});return nK("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 Ji(t){return iK(t,!1)}function mi(t,e){if(e===null)return!0;let r=iK(t,!0);return r===null?!0:r===e}var Aoe,tK,Zw,ah=v(()=>{"use strict";he();ss();Aoe=5e3,tK=new Map,Zw=0});import{execFile as Roe}from"child_process";import{readdirSync as Moe,readFileSync as Poe}from"fs";import{promisify as Doe}from"util";async function hi(t,e={}){let r=e.signalMode==="immediate",i=e.expectedStartToken!==void 0?e.expectedStartToken:Ji(t),n=()=>mi(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 Xw("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===Noe||joe.test(`${a} ${l}`)){b.debug("PROCESS","taskkill reported the process was already gone",{pid:t});return}throw new lh(t,`taskkill failed for PID ${t} (exit ${String(s)}): ${a.trim()||l}`,{cause:o})}return}try{let o=r?"SIGKILL":"SIGTERM",s=await ch(t);for(let c of s){if(!mi(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 ch(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(!mi(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 lh(t,`tree-kill failed for PID ${t}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}}async function Loe(){return process.platform==="win32"?$oe():process.platform==="linux"?Koe():Uoe()}function Koe(){let t=[],e;try{e=Moe("/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=Poe(`/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 Uoe(){let t;try{t=(await Xw("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 $oe(){let t;try{t=(await Xw("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 ch(t){let e=await Loe(),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 Xw,Noe,joe,lh,Xl=v(()=>{"use strict";he();ah();Xw=Doe(Roe),Noe=128,joe=/not found|no running instance|no tasks/i,lh=class extends Error{pid;constructor(e,r,i){super(r,i),this.name="ProcessTreeKillError",this.pid=e}}});import{existsSync as oK,readFileSync as rk}from"fs";import Joe 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 uh(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 sK(t){if(!t||!kt(t.pid))return!1;if(!t.startToken)return!0;let e=Ji(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 Ql(t,e=Woe){if(!sK(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=>Joe.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 Bi(t=Ke.workerPid()){if(!oK(t))return null;let e;try{e=JSON.parse(rk(t,"utf-8"))}catch{return null}return e!==null&&Ql(e)?e:null}function dh(){return Qw||(Qw=new tk),Qw}function ek(){let t=Voe.shift();t&&t.notify()}var Boe,zoe,qoe,Goe,Woe,tk,Qw,JUe,Voe,yn=v(()=>{"use strict";Zr();he();gt();ss();Oe();ah();Xl();Boe=5e3,zoe=1e3,qoe=Ke.supervisorRegistry(),Goe=null;Woe={platform:process.platform,readCommandLine:t=>rk(`/proc/${t}/cmdline`,"utf-8")};tk=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(e=qoe){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,!oK(this.registryPath)){this.persist();return}try{let i=JSON.parse(rk(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"&&ek())}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)ek();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,Ji(a.pid)]));for(let a of n)try{process.platform==="win32"?await hi(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 uh(n,Boe);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(!mi(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 hi(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()+zoe;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"&&ek();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{Je(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{Goe?.({errorCategory:r.code??"unknown"})}catch{}}},Qw=null;JUe=180*1e3,Voe=[]});import{existsSync as Hoe,readFileSync as Yoe,rmSync as Zoe}from"fs";async function lK(t){let e=t.currentPid??process.pid,r=t.pidFilePath??Xoe,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,Ji(l.pid)),o.set(l.id,await ch(l.pid));try{await aK(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 uh(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=mi(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 aK(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{Qoe(o.get(l.id)??[],l.pid)}}await uh(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);nk(r,e),t.registry.pruneDeadEntries()}function nk(t,e,r=!1){if(!Hoe(t))return;let i=null;try{let s=JSON.parse(Yoe(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{Zoe(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 Qoe(t,e){for(let{pid:r,startToken:i}of t)if(!(r===e||!kt(r))){if(!mi(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 aK(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 hi(r,{signalMode:"immediate"});return}try{process.kill(r,e)}catch(n){if((n instanceof Error?n.code:void 0)!=="ESRCH")throw n}return}await hi(r)}var Xoe,ik=v(()=>{"use strict";he();yn();Oe();Xl();Xoe=Ke.workerPid()});function ese(){let e=dh().pruneDeadEntries();e>0&&b.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function uK(){ec===null&&(ec=setInterval(ese,cK),ec.unref(),b.debug("SYSTEM","Health checker started",{intervalMs:cK}))}function dK(){ec!==null&&(clearInterval(ec),ec=null,b.debug("SYSTEM","Health checker stopped"))}var cK,ec,pK=v(()=>{"use strict";he();yn();cK=3e4,ec=null});import{execFile as tse}from"child_process";import{promisify as rse}from"util";function ose(t){let e=[];for(let r of t.split(`
|
|
15
15
|
`)){let i=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);i&&e.push({pid:Number.parseInt(i[1],10),ppid:Number.parseInt(i[2],10),command:i[3].trim()})}return e}async function ok(){let t=await nse("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return ose(t.stdout)}function sk(t,e){let r=t.filter(s=>ise.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 fK(t={}){let e=t.platform??process.platform,r={matched:0,trees:0,orphans:0,killed:0,failed:0,unregistered:0,skipped:null};if(e==="win32")return r.skipped="windows",r;let i=t.readTable??ok,n=t.isAlive??kt,o=t.killTree??(f=>hi(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}=sk(a,{isAlive:n,selfPid:s});if(r.matched=l.length,r.trees=c.length,r.orphans=u.length,u.length===0)return b.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:r.matched,trees:r.trees}),r;b.warn("PROCESS","Reaping orphaned chroma-mcp trees left by dead workers",{orphans:u.length,roots:u.map(f=>f.pid)});let d=new Set,p=8;for(let f=0;f<u.length;f+=p){let m=u.slice(f,f+p);(await Promise.allSettled(m.map(y=>o(y.pid)))).forEach((y,S)=>{let E=m[S];y.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:y.reason instanceof Error?y.reason.message:String(y.reason)}))})}if(t.registry)for(let f of t.registry.getAll())f.type==="chroma"&&d.has(f.pid)&&(t.registry.unregister(f.id),r.unregistered+=1);return b.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:r.orphans,killed:r.killed,failed:r.failed,unregistered:r.unregistered}),r}var nse,ise,ak=v(()=>{"use strict";he();Xl();yn();nse=rse(tse),ise=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/});import{existsSync as sse,readFileSync as ase,rmSync as mK}from"fs";function ck(){return cse}function uk(t={}){let e=t.pidFilePath??lse;if(!sse(e))return"missing";let r=null;try{r=JSON.parse(ase(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)}),mK(e,{force:!0}),"invalid"}return Ql(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}),mK(e,{force:!0})),"stale")}var lse,lk,cse,Cd=v(()=>{"use strict";he();yn();ik();pK();ak();Oe();yn();lse=Ke.workerPid(),lk=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(),uk({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,fK({registry:this.registry}).catch(r=>{b.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),uK()}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}dK(),this.stopPromise=lK({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}},cse=new lk(dh())});import{existsSync as use,readFileSync as dse}from"fs";function Yt(t,e){if(!use(t))return e;try{return Rr(dse(t,"utf-8"))}catch(r){throw new Error(`Corrupt JSON file, refusing to overwrite: ${t}: ${r instanceof Error?r.message:String(r)}`)}}var as=v(()=>{"use strict";gt()});import{join as hK}from"path";import{mkdirSync as pse,writeFileSync as fse}from"fs";import{randomUUID as mse}from"crypto";function hse(t){let e=t.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function dk(t,e){if(hse(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 yK(t,e){return dk(t,e).enabled}function Od(){return hK(gn(),gK)}function ls(){let t;try{t=Yt(Od(),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 tc(t){let e=gn();pse(e,{recursive:!0}),fse(hK(e,gK),JSON.stringify(t,null,2)+`
|
|
16
|
-
`)}function ph(){let t=ls();if(t?.installId)return t.installId;let e=mse();return tc({installId:e,decidedAt:""}),e}var gK,fh=v(()=>{"use strict";Oe();as();he();gK="telemetry.json"});import gse from"os";function yse(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>bK?e.slice(0,bK):e}catch{return""}}function bse(t){if(typeof t!="string"||t.length===0)return t??"";let e="";try{e=gse.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 vse(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 Ese(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${Bn}`):e.replace(/[?#].*$/,"").replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/@\s]+@/,`$1${Bn}@`))}function Sse(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\?[^\s"'()]*/g,"")}function _se(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)}${Bn}`})}function wse(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,Bn),e=e.replace(/\b[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\b/g,Bn),e=e.replace(/\b(?:sk|pk|rk|ak|phc|phx|ph|ghp|gho|ghs|xox[bpasr])[-_][A-Za-z0-9_-]{8,512}\b/gi,Bn),e=e.replace(/\bBearer\s+[A-Za-z0-9._-]{8,512}\b/gi,Bn),e=e.replace(/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g,Bn),e=e.replace(/\b[0-9a-fA-F]{24,4096}\b/g,Bn),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,Bn),e=e.replace(/\b(?=[A-Za-z0-9+/_-]{0,4096}\d)[A-Za-z0-9+/_-]{32,4096}={0,2}\b/g,Bn),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,Bn),e}function vK(t){let e=yse(t);return e.length===0?"":(e=bse(e),e=Ese(e),e=vse(e),e=Sse(e),e=_se(e),e=wse(e),e)}var bK,Bn,EK=v(()=>{"use strict";he();bK=8192,Bn="[REDACTED]"});function Ise(t,e){if(!(!t||typeof t!="object"))for(let r of Object.keys(t)){if(!kse.has(r))continue;let i=t[r];if(typeof i=="string"){let n=i.length>SK?i.slice(0,SK):i;e[r]=vK(n)}else(typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean")&&(e[r]=i)}}function _K(t){let e={};try{Ise(t,e)}catch{}return e}var kse,SK,wK=v(()=>{"use strict";EK();kse=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","stage","phase","install_method","interactive","provider_source","bun_version","uv_version","claude_code_version","trial_days","trial_variant","offer_surface","funnel_source","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","pre_latch_state","limit_window","overage_status","is_using_overage","resets_in_minutes","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_aborted_deadline_exceeded","outcomes_invalid_output","top_model","top_abort_reason","observed_model","observed_billing","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","skill_id","skill_source","skill_trigger","observations_created","total_observations_injected","total_tokens_saved_vs_naive","platform","agent_role","instruction_state","instruction_returned_count","instruction_disabled_count","instruction_excluded_count","instruction_missing_count","instruction_unknown_count","captured_prompt_count","captured_session_count","captured_tool_count","unidentified_tool_event_count","native_todo_count",...["captured","mcp"].flatMap(t=>["read","write"].flatMap(e=>[`${t}_${e}_count`,...["ok","error","excluded","disabled","unknown"].map(r=>`${t}_${e}_${r}_count`)]))]),SK=200});import kK from"os";function IK(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||Tse}function xK(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||Ase}function TK(t){let e={};for(let r of Cse)t[r]!==void 0&&(e[r]=t[r]);return e}function Ose(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||kK.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 AK(){return{version:xse,os:process.platform,os_version:kK.release(),is_wsl:Ose(),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 xse,Tse,Ase,Cse,CK=v(()=>{"use strict";he();xse="15.0.
|
|
16
|
+
`)}function ph(){let t=ls();if(t?.installId)return t.installId;let e=mse();return tc({installId:e,decidedAt:""}),e}var gK,fh=v(()=>{"use strict";Oe();as();he();gK="telemetry.json"});import gse from"os";function yse(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>bK?e.slice(0,bK):e}catch{return""}}function bse(t){if(typeof t!="string"||t.length===0)return t??"";let e="";try{e=gse.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 vse(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 Ese(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${Bn}`):e.replace(/[?#].*$/,"").replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/@\s]+@/,`$1${Bn}@`))}function Sse(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\?[^\s"'()]*/g,"")}function _se(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)}${Bn}`})}function wse(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,Bn),e=e.replace(/\b[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\b/g,Bn),e=e.replace(/\b(?:sk|pk|rk|ak|phc|phx|ph|ghp|gho|ghs|xox[bpasr])[-_][A-Za-z0-9_-]{8,512}\b/gi,Bn),e=e.replace(/\bBearer\s+[A-Za-z0-9._-]{8,512}\b/gi,Bn),e=e.replace(/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g,Bn),e=e.replace(/\b[0-9a-fA-F]{24,4096}\b/g,Bn),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,Bn),e=e.replace(/\b(?=[A-Za-z0-9+/_-]{0,4096}\d)[A-Za-z0-9+/_-]{32,4096}={0,2}\b/g,Bn),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,Bn),e}function vK(t){let e=yse(t);return e.length===0?"":(e=bse(e),e=Ese(e),e=vse(e),e=Sse(e),e=_se(e),e=wse(e),e)}var bK,Bn,EK=v(()=>{"use strict";he();bK=8192,Bn="[REDACTED]"});function Ise(t,e){if(!(!t||typeof t!="object"))for(let r of Object.keys(t)){if(!kse.has(r))continue;let i=t[r];if(typeof i=="string"){let n=i.length>SK?i.slice(0,SK):i;e[r]=vK(n)}else(typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean")&&(e[r]=i)}}function _K(t){let e={};try{Ise(t,e)}catch{}return e}var kse,SK,wK=v(()=>{"use strict";EK();kse=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","stage","phase","install_method","interactive","provider_source","bun_version","uv_version","claude_code_version","trial_days","trial_variant","offer_surface","funnel_source","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","pre_latch_state","limit_window","overage_status","is_using_overage","resets_in_minutes","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_aborted_deadline_exceeded","outcomes_invalid_output","top_model","top_abort_reason","observed_model","observed_billing","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","skill_id","skill_source","skill_trigger","observations_created","total_observations_injected","total_tokens_saved_vs_naive","platform","agent_role","instruction_state","instruction_returned_count","instruction_disabled_count","instruction_excluded_count","instruction_missing_count","instruction_unknown_count","captured_prompt_count","captured_session_count","captured_tool_count","unidentified_tool_event_count","native_todo_count",...["captured","mcp"].flatMap(t=>["read","write"].flatMap(e=>[`${t}_${e}_count`,...["ok","error","excluded","disabled","unknown"].map(r=>`${t}_${e}_${r}_count`)]))]),SK=200});import kK from"os";function IK(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||Tse}function xK(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||Ase}function TK(t){let e={};for(let r of Cse)t[r]!==void 0&&(e[r]=t[r]);return e}function Ose(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||kK.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 AK(){return{version:xse,os:process.platform,os_version:kK.release(),is_wsl:Ose(),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 xse,Tse,Ase,Cse,CK=v(()=>{"use strict";he();xse="15.0.1",Tse="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",Ase="https://us.i.posthog.com";Cse=["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 Mr(t,e,r){try{if(!yK(process.env,ls()))return;let i=_K({...AK(),...e??{}});if(r?.person?i.$set=TK(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=IK(),o=new AbortController,s=setTimeout(()=>o.abort(),Rse);try{await Mse(n,t,i,o.signal)}finally{clearTimeout(s)}}catch{}}async function Mse(t,e,r,i){await fetch(`${xK()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:t,event:e,distinct_id:ph(),properties:r}),signal:i})}var Rse,Rd=v(()=>{"use strict";fh();wK();CK();Rse=2e3});import{createHash as L$e,randomUUID as K$e}from"crypto";var OK=v(()=>{"use strict";he()});import{randomUUID as q$e}from"crypto";var RK=v(()=>{"use strict";he();OK()});import{statSync as Pse,readFileSync as Dse}from"fs";import wa from"path";function MK(t){let e=wa.join(t,".git"),r;try{r=Pse(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)}),Md}if(!r.isFile())return Md;let i;try{i=Dse(e,"utf-8").trim()}catch(l){return b.warn("GIT","Failed to read .git file",{error:l instanceof Error?l.message:String(l)}),Md}let n=i.match(/^gitdir:\s*(.+)$/);if(!n)return Md;let o=wa.resolve(wa.dirname(e),n[1]),s=o.match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(s){let l=s[1];return{isWorktree:!0,isSubmodule:!1,worktreeName:wa.basename(t),parentRepoPath:l,parentProjectName:wa.basename(l)}}let a=o.match(/^(.+)[/\\]\.git[/\\]modules[/\\](.+)$/);if(a){let l=a[1];return{isWorktree:!1,isSubmodule:!0,worktreeName:wa.basename(t),parentRepoPath:l,parentProjectName:wa.basename(l)}}return Md}var Md,PK=v(()=>{"use strict";he();Md={isWorktree:!1,isSubmodule:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null}});import{basename as NK}from"path";function DK(t){let e=hn(t.replace(/\\/g,"/"));e=e.replace(/\\/g,"/");let r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return r=r.replace(/(^|\/)\*\*(?=\/)/g,"$1<<<GLOBSTAR_DIR>>>").replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*").replace(/<<<GLOBSTAR_DIR>>>\//g,"(?:.*/)?"),new RegExp(`^${r}$`)}function jK(t,e,r){let i=DK(t);return i.test(e)||i.test(r)?!0:t.replace(/\\/g,"/").endsWith("/**")?DK(t.slice(0,-3)).test(e.replace(/\/+$/,"")):!1}function LK(t,e){if(!e.length)return!1;let r=t.replace(/\\/g,"/"),i=NK(r);for(let n of e){let o=n.trim();if(o)try{if(jK(o,r,i))return!0}catch(s){b.warn("PROJECT_NAME","Invalid glob pattern",{pattern:o,error:s instanceof Error?s.message:String(s)});continue}}return!1}function KK(t,e){if(!e||!e.trim())return!1;let r=t.replace(/\\/g,"/"),i=NK(r),n=e.split(",").map(o=>o.trim()).filter(Boolean);for(let o of n)try{if(jK(o,r,i))return!0}catch(s){b.warn("PROJECT_NAME","Invalid exclusion pattern",{pattern:o,error:s instanceof Error?s.message:String(s)});continue}return!1}var pk=v(()=>{"use strict";Ad();he()});import{realpathSync as Nse}from"fs";function UK(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 jse(t){try{return Nse(t)}catch{return t}}function fk(t,e){if(e.length===0)return null;let r=[...new Set([t,jse(t)])].flatMap(i=>[i,`${i.replace(/[\\/]+$/,"")}/`]);for(let i of e)if(r.some(n=>LK(n,i.patterns)))return i.name;return null}var $K=v(()=>{"use strict";pk();he()});import Xr from"path";import{existsSync as Lse,realpathSync as Kse,statSync as Use}from"fs";import{homedir as $se,tmpdir as Fse}from"os";import{execFileSync as BK}from"child_process";function zK(t){try{return BK("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 qK(t){try{return Kse(t)}catch{return t}}function zse(t,e){let r=Xr.relative(e,t);return r===""||!r.startsWith("..")&&!Xr.isAbsolute(r)}function qse(){return[$se(),Fse(),So].flatMap(t=>{let e=Xr.resolve(t);return[e,qK(e)]})}function GK(t){let e=qse(),r=Xr.resolve(t);if([Xr.resolve(So),qK(Xr.resolve(So))].some(n=>zse(r,n)))return null;for(let n=0;n<Bse;n++){if(e.includes(r))return null;let o=Xr.dirname(r);if(o===r)return null;if(Jse.some(s=>Lse(Xr.join(r,s))))return r;r=o}return null}function hk(t,e){let r=Xr.basename(e);if(r===""){if(process.platform==="win32"){let n=t.match(/^([A-Z]):\\/i);if(n){let s=`drive-${n[1].toUpperCase()}`;return b.info("PROJECT_NAME","Drive root detected",{cwd:t,projectName:s}),s}}return b.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:t}),gk}return r}function FK(){try{return Use(we).mtimeMs}catch{return-1}}function WK(){let t=FK();if(t===-1)return Te.getAllDefaults();if(mh&&mh.mtimeMs===t)return mh.settings;let e=Te.loadFromFile(we);return mh={mtimeMs:FK(),settings:e},e}function Wse(){let t=process.env[Gse]??WK().CLAUDE_MEM_PROJECT_NAME_SOURCE;return String(t??"path").trim().toLowerCase()==="git-remote"}function VK(){let t=process.env[Vse]??WK().CLAUDE_MEM_PROJECT_ENVIRONMENTS;return(!hh||hh.raw!==t)&&(hh={raw:t,environments:UK(t)}),hh.environments}function Hse(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 Yse(t){try{let e=BK("git",["remote","get-url","origin"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim();return Hse(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 HK(t){return Wse()?(mk.has(t)||mk.set(t,Yse(t)),mk.get(t)??null):null}function Zse(t,e=process.platform){if(!t||t.trim()==="")return b.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),gk;let r=hn(t,e),i=fk(r,VK());if(i)return i;let n=zK(r),o=n?HK(n):null;if(o)return o;let s=n??GK(r)??r;return hk(t,s)}function YK(t,e){return e===t?t:`${t}/${e}`}function Xse(t,e){if(!t.isSubmodule||!t.parentRepoPath)return null;let r=Xr.relative(t.parentRepoPath,e);return!r||r.startsWith("..")||Xr.isAbsolute(r)?null:r.split(Xr.sep).join("/")}function ka(t,e=process.platform){if(!t||t.trim()===""){let l=Zse(t,e);return{primary:l,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[l],keySource:"path"}}let r=hn(t,e),i=zK(r),n=Qse(t,r,i),o=i?HK(i):null,s=o?JK(n,o,"git-remote"):n,a=fk(r,VK());return a?JK(s,a,"environment"):s}function JK(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 Qse(t,e,r){let i=r?null:GK(e),n=hk(t,r??i??e),o=r??e,s=MK(o);if((s.isWorktree||s.isSubmodule)&&s.parentProjectName){let a=s.parentProjectName,l,c;return s.isSubmodule?(l=`${a}/${Xse(s,o)??n}`,c=n!==a?[n]:[]):(l=YK(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&&Xr.resolve(i)!==Xr.resolve(e)){let a=hk(t,e);if(a!==n&&a!==gk)return{primary:n,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[a,n],keySource:"path"}}return{primary:n,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[n],keySource:"path"}}var gk,Jse,Bse,Gse,mh,Vse,hh,mk,Pd=v(()=>{"use strict";Ad();Oe();gr();he();PK();$K();gk="unknown-project";Jse=[".claude-mem-project",".claude-mem.json"],Bse=64;Gse="CLAUDE_MEM_PROJECT_NAME_SOURCE",mh=null;Vse="CLAUDE_MEM_PROJECT_ENVIRONMENTS",hh=null;mk=new Map});import bn from"path";import{homedir as eae,tmpdir as _Fe}from"os";import{existsSync as gh,writeFileSync as kFe,readFileSync as tae,unlinkSync as IFe,mkdirSync as rae,statSync as xFe,utimesSync as nae,copyFileSync as TFe,realpathSync as iae}from"fs";import{execFileSync as oae,spawnSync as QK}from"child_process";function sae(t){return t===void 0?ZK:Math.max(1,Math.min(ZK,t))}function aae(t){try{return iae(t)}catch{return null}}function yk(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function lae(t,e){let r=e==="win32"?"where.exe":"which",i=[t],n;try{n=oae(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 Ek(t={}){let e=Object.keys(t).length===0;if(e&&bk!==void 0)return bk;let r=cae(t);return e&&r!==null&&(bk=r),r}function XK(t,e){let r=t?.trim();return r?e==="win32"?[bn.join(r,"bin","bun.exe"),bn.join(r,"bin","bun"),bn.join(r,"bun.exe")]:[bn.join(r,"bin","bun"),bn.join(r,"bun")]:[]}function cae(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(yk(r))return r;let i=t.env??process.env,n=t.homeDirectory??eae(),o=t.pathExists??gh,s=t.lookupInPath??lae,a=t.realpath??aae,l=e==="win32"?[i.BUN,i.BUN_PATH,...XK(i.BUN_INSTALL,e),bn.join(n,".bun","bin","bun.exe"),bn.join(n,".bun","bin","bun"),i.USERPROFILE?bn.join(i.USERPROFILE,".bun","bin","bun.exe"):void 0,i.LOCALAPPDATA?bn.join(i.LOCALAPPDATA,"bun","bun.exe"):void 0,i.LOCALAPPDATA?bn.join(i.LOCALAPPDATA,"bun","bin","bun.exe"):void 0,i.npm_config_prefix?bn.join(i.npm_config_prefix,"bun.exe"):void 0]:[i.BUN,i.BUN_PATH,...XK(i.BUN_INSTALL,e),bn.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?bn.join(i.npm_config_prefix,"bin","bun"):void 0];for(let d of l){let p=d?.trim();if(p&&(yk(p)&&o(p)||p.toLowerCase()==="bun"))return p}let c=s("bun",e)?.trim();if(!c||!yk(c))return null;let u=a(c)??c;return o(u)?u:null}function eU(){if(!gh(Ia))return null;try{return JSON.parse(tae(Ia,"utf-8"))}catch(t){return t instanceof Error?b.warn("SYSTEM","Failed to parse PID file",{path:Ia},t):b.warn("SYSTEM","Failed to parse PID file",{path:Ia},new Error(String(t))),null}}function tU(t){nk(Ia,t,!0)}function cs(t){return process.platform==="win32"?Math.round(t*2):t}function Sk(){let t=Ke.dataDir();return rae(t,{recursive:!0}),t}function uae(t,e,r=Sk()){let i=n=>n.replace(/'/g,"''");return`Start-Process -FilePath '${i(t)}' -ArgumentList @('"${i(e)}"','--daemon') -WorkingDirectory '${i(r)}' -WindowStyle Hidden`}function fae(t,e,r){return t?.code!=="ETIMEDOUT"?!1:e<r/2}function rU(t,e=cs(dae)){let r=Ek();if(!r)return;let i=()=>{let a=Date.now();try{return{result:QK(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||fae(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,pae).join(`
|
|
18
18
|
`)}function mae(t=process.env){let e=t.SystemRoot||t.SYSTEMROOT;return e?`${e}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`:"powershell.exe"}function hae(t,e,r=Sk()){return["-NoProfile","-WindowStyle","Hidden","-EncodedCommand",Buffer.from(uae(t,e,r),"utf16le").toString("base64")]}function nU(){return Dd}function iU(t,e,r,i=process.platform,n){if(Dd=void 0,i==="win32"){let u=mae(r),d=hae(t,e),p=sae(n);try{let f=QK(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));Dd=`${u} could not launch the worker: ${m.message}`,b.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:t,powershell:u},m);return}}let o="/usr/bin/setsid",s=gh(o),a=s?o:t,c=fi(a,s?[t,e,"--daemon"]:[e,"--daemon"],{detached:!0,stdio:"ignore",cwd:Sk(),env:r});if(c.on("error",u=>{b.error("SYSTEM",vk,{runtimePath:t,execPath:a},u)}),c.pid===void 0){Dd=`could not launch ${a}`;return}return c.unref(),c.pid}function oU(t,e,r={}){ck().assertCanSpawn("worker daemon");let i=or({...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r}),n=Ek();if(!n){b.error("SYSTEM",vk),Dd=vk;return}return iU(n,t,i)}function sU(){try{if(!gh(Ia))return;let t=new Date;nae(Ia,t,t)}catch{}}function Nd(t={}){return uk({logAlive:!1,removeStale:t.removeStale})}var ZK,UFe,Ia,vk,bk,dae,pae,Dd,yh=v(()=>{"use strict";Zr();he();ss();ik();Cd();RK();Pd();Oe();_a();yn();ZK=_o(Nt.POWERSHELL_COMMAND);UFe=Ke.dataDir(),Ia=Ke.workerPid(),vk="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.";dae=5e3,pae=8});function _k(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"&&gae.has(r.code)||_k(r.cause,e)?!0:Array.isArray(r.errors)&&r.errors.some(i=>_k(i,e))}function wo(t){return _k(t,new Set)?!0:t instanceof Error&&t.message.includes("ECONNREFUSED")}function aU(t){let e=t?.code;return e==="EACCES"||e==="EADDRNOTAVAIL"}var gae,bh,xa=v(()=>{"use strict";gae=new Set(["ECONNREFUSED","ConnectionRefused"]);bh="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 yae from"net";function wk(){return Te.loadFromFile(we).CLAUDE_MEM_WORKER_HOST}function lU(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}async function bae(t,e,r="GET",i=jd){let n=await fetch(`http://${lU(wk())}:${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 kk(t,e=jd){let r=Date.now()+e;if(process.platform==="win32")try{let n=await fetch(`http://${lU(wk())}:${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 cU(t,Math.max(1,r-Date.now()));return i==="occupied"||i==="indeterminate"}async function cU(t,e=jd){return(await Ik(t,e)).occupancy}function Ik(t,e=jd){return e<=0?Promise.resolve({occupancy:"indeterminate"}):new Promise(r=>{let i=!1,n=!1,o=!1,s;try{s=yae.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"}):aU(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,wk())}catch{try{s.close()}catch{}c({occupancy:"indeterminate"})}})}async function uU(t,e,r,i){let n=Date.now()+r;for(;Date.now()<n;){try{let s=n-Date.now();if((await bae(t,e,"GET",Math.min(jd,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 us(t,e=3e4){return uU(t,"/api/health",e,"Service not ready yet, will retry")}function rc(t,e=3e4){return uU(t,"/api/readiness",e,"Worker not ready yet, will retry")}var jd,Ld=v(()=>{"use strict";he();gr();Oe();xa();jd=5e3});var dU=v(()=>{"use strict";he();Cd()});var pU=v(()=>{"use strict";yh();Ld();dU()});import{dirname as vae,join as Eae}from"path";import{mkdirSync as Sae,readFileSync as vh,statSync as fU,unlinkSync as mU,utimesSync as _ae,writeFileSync as wae}from"fs";function Tk(){return Eae(gn(),"spawn.lock")}function xk(t){try{let e=JSON.parse(vh(t,"utf-8"));return typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0?null:e.pid}catch{return null}}function xae(t){if(t===null)return null;try{return process.kill(t,0),!0}catch(e){return e?.code==="EPERM"}}function Sh(){let t=Tk(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return Sae(vae(t),{recursive:!0}),wae(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=fU(t).mtimeMs}catch{continue}let a=xk(t),l=null;if(a===null)try{l=vh(t,"utf-8")}catch{continue}if(Date.now()-s<=Eh&&xae(a)!==!1)return!1;let u;try{u=fU(t).mtimeMs}catch{continue}if(u!==s)return!1;if(a!==null){if(xk(t)!==a)return!1}else try{if(vh(t,"utf-8")!==l)return!1}catch{continue}try{mU(t)}catch{return!1}}return!1}function _h(){let t=Tk();try{if(JSON.parse(vh(t,"utf-8")).pid!==process.pid)return;mU(t)}catch{}}async function Ak(t,e=kae){let r=Date.now()+t;for(;!Sh();){if(Date.now()>=r)return null;await new Promise(n=>setTimeout(n,Iae))}let i=setInterval(Tae,e);return i.unref(),()=>{clearInterval(i),_h()}}function Tae(){let t=Tk();try{if(xk(t)!==process.pid)return;let e=new Date;_ae(t,e,e)}catch{}}var Eh,kae,Iae,wh=v(()=>{"use strict";Oe();he();Eh=9e4,kae=Eh/3,Iae=250});import{execFile as Aae}from"node:child_process";import{readdirSync as cJe,readFileSync as Cae,statSync as uJe,promises as dJe}from"node:fs";import{promisify as Oae}from"node:util";function hU(t){return Rae.test(t.trim())}function Mae(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 Ih(t,e){return e===void 0?t:Math.max(1,Math.min(t,e))}async function Pae(t){try{let e=await kh("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name,CommandLine,@{Name='StartToken';Expression={$_.CreationDate.ToString('yyyyMMddHHmmss.ffffff')}} | ConvertTo-Json -Compress"],{timeout:Ih(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 Dae(t,e){try{let r=await kh("netstat",["-ano"],{timeout:Ih(15e3,e),windowsHide:!0,maxBuffer:16777216});return Kae(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 Nae(t,e){try{let r=await kh("lsof",["-nP",`-iTCP:${t}`,"-sTCP:LISTEN","-t"],{timeout:Ih(1e4,e),maxBuffer:1048576});return jae(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 jae(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 Lae(t,e){try{let i=(await kh("ps",["-p",String(t),"-o","command="],{timeout:Ih(5e3,e)})).stdout.trim();return i.length>0?i:null}catch{return null}}function Kae(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 $ae(t,e){let r=e.readOwnedWorker();if(r===null||r.port!==t)return null;let i=(u,d={})=>(b.info("PROCESS","Wedged-worker reclaim declined",{port:t,pid:r.pid,reason:u,...d}),{reclaimed:!1,reason:u,killedPids:[]}),n=(e.now()-Date.parse(r.startedAt))/1e3;if(!Number.isFinite(n)||n<e.minOwnerAgeSeconds)return i("owner-booting",{ageSeconds:n,minOwnerAgeSeconds:e.minOwnerAgeSeconds});for(let u=0;u<2;u++)if(u>0&&await e.sleep(vU),await e.probeHealth(t))return i("owner-responding");let o=await e.listOwners(t);if(o===null)return i("netstat-unreadable");if(!o.includes(r.pid))return b.info("PROCESS","Wedged-worker reclaim: our worker does not own the port \u2014 deferring to the ghost-listener check",{port:t,pid:r.pid,listeners:o}),null;let s=e.readHeartbeat();if(s!==null&&s.pid===r.pid){let u=e.now(),d=Math.max(0,u-s.beatAtMs),p=Math.max(0,u-s.lastResponseAtMs);if(d<e.heartbeatStaleMs){if(p<e.maxSilentProtectionMs)return i("owner-progressing",{heartbeatAgeMs:Math.round(d),sinceLastResponseMs:Math.round(p)});b.warn("PROCESS","Worker finished no response within the protection window despite a fresh liveness heartbeat",{port:t,pid:r.pid,sinceLastResponseMs:Math.round(p),maxSilentProtectionMs:e.maxSilentProtectionMs})}}let a=await e.readIdentity(r.pid),l=r.startToken!==void 0&&a.startToken!==null&&a.startToken!==r.startToken;if(l||a.cmdline===null||!Uae.test(a.cmdline))return i("owner-identity-mismatch",{tokenMismatch:l,hasCmdline:a.cmdline!==null});if(!e.hasKillBudget())return i("out-of-budget");b.warn("PROCESS","Reclaiming wedged worker: past its boot grace, silent on two health probes, and still holding the port",{port:t,pid:r.pid,ageSeconds:Math.round(n)});try{await e.killTree(r.pid,{expectedStartToken:a.startToken??r.startToken??void 0,signalMode:"graceful"})}catch(u){return b.error("PROCESS","Wedged-worker reclaim tree-kill failed",{port:t,pid:r.pid},u instanceof Error?u:new Error(String(u))),{reclaimed:!1,reason:"kill-failed",killedPids:[]}}let c=await e.listOwners(t);return c!==null&&c.length===0?(b.info("PROCESS","Wedged worker reclaimed \u2014 port is free again",{port:t,killedPids:[r.pid]}),{reclaimed:!0,killedPids:[r.pid]}):(b.warn("PROCESS","Wedged-worker reclaim killed the worker but the port is still bound",{port:t,pid:r.pid,stillOwnedBy:c}),{reclaimed:!1,reason:"still-bound",killedPids:[r.pid]})}async function Fae(t,e,r,i){let n=Ji(t),o=e?(await r(i))?.find(s=>s.pid===t)?.cmdline??null:await Lae(t,i);return mi(t,n)?{startToken:n,cmdline:o}:{startToken:null,cmdline:null}}async function Ok(t,e={}){let r=e.isWin32??(()=>process.platform==="win32"),i=e.now??Date.now,n=e.deadlineAt??null,o=W=>n!==null&&n-i()<W,s=()=>n===null?void 0:Math.max(1,n-i());if(o(gU))return b.info("PROCESS","Port reclaim skipped: not enough of the hook budget is left to finish one",{port:t,remainingMs:s(),neededMs:gU}),{reclaimed:!1,reason:"out-of-budget",killedPids:[]};let a=e.listOwners??((W,Q)=>r()?Dae(W,Q):Nae(W,Q)),l=W=>a(W,s()),c=e.readTable??Pae,u=()=>c(s()),d=e.killTree??((W,Q)=>hi(W,Q)),p=e.dataDir??(()=>Be),f=e.readIdentity??((W,Q)=>Fae(W,r(),c,Q)),m=await $ae(t,{listOwners:l,killTree:d,readOwnedWorker:e.readOwnedWorker??Bi,probeHealth:e.probeHealth??(W=>us(W,bU)),readIdentity:W=>f(W,s()),minOwnerAgeSeconds:e.minOwnerAgeSeconds??U1(),readHeartbeat:e.readHeartbeat??(()=>qae()),heartbeatStaleMs:e.heartbeatStaleMs??Bae(),maxSilentProtectionMs:e.maxSilentProtectionMs??zae,now:i,sleep:e.sleep??(W=>new Promise(Q=>setTimeout(Q,W))),hasKillBudget:()=>!o(Ck)});if(m!==null)return m;if(!r())return{reclaimed:!1,reason:"not-supported",killedPids:[]};let h=await l(t);if(h===null)return{reclaimed:!1,reason:"netstat-unreadable",killedPids:[]};if(h.length===0)return{reclaimed:!1,reason:"no-listener",killedPids:[]};let y=await u();if(y===null)return{reclaimed:!1,reason:"table-unreadable",killedPids:[]};if(h.filter(W=>kt(W)).length>0)return{reclaimed:!1,reason:"owner-alive",killedPids:[]};let E=new Map;for(let W of y){let Q=E.get(W.ppid);Q?Q.push(W):E.set(W.ppid,[W])}let T=new Map,O=new Set,N=W=>{for(let Q of E.get(W)??[])O.has(Q.pid)||(O.add(Q.pid),N(Q.pid),hU(Q.name)&&T.set(Q.pid,Q))};for(let W of h)N(W);let q=p();if(q)for(let W of y)T.has(W.pid)||hU(W.name)&&Mae(W.cmdline,q)&&T.set(W.pid,W);if(T.size===0)return b.info("PROCESS","Ghost listener owner is dead but no chroma-sidecar descendants found",{port:t,deadOwners:h,processTableRows:y.length,dataDir: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:[...T.values()].map(W=>({pid:W.pid,name:W.name}))});let B=[];for(let W of T.values()){if(o(Ck))return b.info("PROCESS","Ghost-listener reclaim stopped before a kill: the hook budget is spent",{port:t,killedPids:B}),{reclaimed:!1,reason:"out-of-budget",killedPids:B};try{await d(W.pid,{expectedStartToken:W.startToken,signalMode:"immediate"}),B.push(W.pid)}catch(Q){return b.error("PROCESS","Ghost-port reclaim tree-kill failed",{port:t,pid:W.pid},Q instanceof Error?Q:new Error(String(Q))),{reclaimed:!1,reason:"kill-failed",killedPids:B}}}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:B}),{reclaimed:!0,killedPids:B}):(b.warn("PROCESS","Ghost-port reclaim killed the sidecar chain but the port is still bound",{port:t,killedPids:B,stillOwnedBy:ie}),{reclaimed:!1,reason:"still-bound",killedPids:B})}function Bae(t=process.env,e=we){let r=t.CLAUDE_MEM_WORKER_HEARTBEAT_STALE_MS??Te.loadFromFile(e,!1,{readOnly:!0}).CLAUDE_MEM_WORKER_HEARTBEAT_STALE_MS,i=Number(r);return Number.isSafeInteger(i)&&i>=yU.min&&i<=yU.max?i:Jae}function qae(t=Ke.workerHeartbeat()){try{let e=JSON.parse(Cae(t,"utf8"));if(e&&Number.isSafeInteger(e.pid)&&Number.isFinite(e.beatAtMs)&&Number.isFinite(e.lastResponseAtMs))return{pid:e.pid,beatAtMs:e.beatAtMs,lastResponseAtMs:e.lastResponseAtMs}}catch{}return null}var kh,Rae,Uae,bU,vU,Ck,gU,Jae,yU,zae,Rk=v(()=>{"use strict";he();Xl();yn();Cd();Ld();ah();_a();Oe();gr();kh=Oae(Aae),Rae=/^(uv|uvx|python|chroma-mcp)(\.exe)?$/i;Uae=/worker-service/i,bU=1500,vU=1e3,Ck=5500,gU=2*bU+vU+Ck;Jae=12e4,yU={min:1e4,max:36e5};zae=6e5});import{existsSync as Gae,readFileSync as Wae,realpathSync as Vae}from"fs";import{createRequire as Hae}from"module";import Ta from"path";function EU(t){try{return Vae(t)}catch{return t}}function Zae(t,e){let r=Ta.relative(e,t);return r!==""&&!r.startsWith("..")&&!Ta.isAbsolute(r)}function Mk(t){let e;try{let n=JSON.parse(Wae(Ta.join(t,"package.json"),"utf-8"));e=Object.keys(n?.dependencies??{})}catch{return[]}if(e.length===0)return[];let r=Ta.join(t,"node_modules"),i=e.filter(n=>!Gae(Ta.join(r,...n.split("/"),"package.json")));if(e.includes("zod")&&!i.includes("zod")){let n=Hae(Ta.join(r,"noop.js")),o=EU(Ta.join(r,"zod"));for(let s of Yae)try{let a=n.resolve(s,{paths:[r]});Zae(EU(a),o)||i.push(s)}catch{i.push(s)}}return i}var Yae,SU=v(()=>{"use strict";Yae=["zod/v3","zod/v4","zod/v4-mini"]});import jt from"path";import{randomUUID as PJe}from"crypto";import{readFileSync as Xae,existsSync as Ah,writeFileSync as NJe,renameSync as jJe,mkdirSync as LJe,readdirSync as Qae,statSync as ele,unlinkSync as KJe}from"fs";function IU(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 xU(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 rle(t){return xU()?{...t,verbose:!0}:t}function nle(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 ile(t,e,r){let i=typeof e.method=="string"?e.method:"GET",n=nle(r),o=JSON.stringify(n);b.warn("SYSTEM","Worker IPC fetch failed",{url:t,method:i},o),ui(`[claude-mem] fetch verbose: ${i} ${t} ${o}
|
|
19
19
|
`)}async function Nk(t,e={}){let r=rle(e);try{return await fetch(t,r)}catch(i){throw xU()&&ile(t,e,i),i}}async function ole(t,e={},r){try{return await Nk(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 sle(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 ale(t,e,r){let i=sle(r,e.signal),n;try{n=await Nk(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 lle(t,e,r){let i=await ale(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 _U(){return jt.join(Te.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function jk(t={}){return t.readOnly?Te.loadFromFile(_U(),!0,t):(xh!==null||(xh=Te.loadFromFile(_U())),xh)}function wU(t,e){if(!t)return null;let r=parseInt(t,10);return Number.isFinite(r)&&r>=e.min&&r<=e.max?r:null}function cle(t,e,r){let i=process.env[t];if(i!==void 0){let s=wU(i,r);return s!==null?s:(b.warn("SYSTEM",`Invalid ${t}, using default`,{value:i,min:r.min,max:r.max}),e)}let n=jk()[t],o=wU(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 ko(t={}){if(!t.readOnly&&Pk!==null)return Pk;let e=parseInt(jk(t).CLAUDE_MEM_WORKER_PORT,10);return t.readOnly||(Pk=e),e}function Kd(t={}){if(!t.readOnly&&Dk!==null)return Dk;let e=jk(t).CLAUDE_MEM_WORKER_HOST;return t.readOnly||(Dk=e),e}function ule(){return Th!==null||(Th=cle("CLAUDE_MEM_API_TIMEOUT_MS",_o(Nt.API_REQUEST),tle)),Th}function Lk(t){return`http://${Fi(Kd())}:${ko()}${t}`}function gi(t,e={}){let r=e.method??"GET",i=Lk(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 lle(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??ule();return o>0?ole(i,n,o):Nk(i,n)}function TU(t){let e=Ah(jt.join(t,"plugin","scripts"))?jt.join(t,"plugin"):t;return jt.join(e,"scripts","worker-service.cjs")}function Kk(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 Uk(t=jt.join(jt.dirname(jt.dirname(Ht)),"cache","thedotmack","claude-mem")){try{return Qae(t).filter(e=>/^\d/.test(e)).map(e=>jt.join(t,e)).filter(e=>{try{if(!ele(e).isDirectory())return!1}catch{return!1}return!Ah(jt.join(e,".orphaned_at"))}).map(e=>({scriptPath:TU(e),version:jt.basename(e)}))}catch{return[]}}function kU(t){try{let e=JSON.parse(Xae(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 AU(){return{cacheRoot:jt.join(jt.dirname(jt.dirname(Ht)),"cache","thedotmack","claude-mem"),marketplaceRoot:Ht,cwd:process.cwd()}}function $k(t=AU()){let e=process.env.CLAUDE_MEM_WORKER_SCRIPT_PATH?.trim();if(e){if(Ah(e))return{scriptPath:e,version:null};b.debug("SYSTEM","Ignoring missing CLAUDE_MEM_WORKER_SCRIPT_PATH override",{override:e})}let r=[...Uk(t.cacheRoot),{scriptPath:TU(jt.join(t.marketplaceRoot,"plugin")),version:kU(jt.join(t.marketplaceRoot,"package.json"))},{scriptPath:jt.join(t.cwd,"plugin","scripts","worker-service.cjs"),version:kU(jt.join(t.cwd,"package.json"))}];return Fk(r)}function CU(t){return jt.dirname(jt.dirname(t))}function dle(t){return Mk(CU(t.scriptPath)).length===0}function Fk(t,e=dle){let r=t.filter(i=>Ah(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:Kk(i.version,n.version)),r.find(e)??r[0])}function nc(t=AU()){let e=$k(t);if(!e)return null;let r=CU(e.scriptPath);return{root:r,version:e.version,missingDependencies:Mk(r)}}var a2e,l2e,tle,c2e,Pk,Dk,xh,Th,ple,fle,u2e,yi=v(()=>{"use strict";he();_a();F1();gr();Oe();Ww();oh();Y1();Vw();Cd();Td();Rd();pU();Ld();xa();yh();wh();Rk();ss();Xl();gt();SU();Vw();a2e=IU("CLAUDE_MEM_HEALTH_TIMEOUT_MS",_o(Nt.HEALTH_CHECK),{min:500,max:3e5}),l2e=IU("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",_o(Nt.HOOK_READINESS_WAIT),{min:0,max:3e5}),tle={min:500,max:3e5},c2e={min:500,max:Nt.SESSION_INIT_REQUEST_MAX};Pk=null,Dk=null,xh=null,Th=null;ple=1e3,fle=5e3,u2e=fle+ple});import{existsSync as Jk,readFileSync as OU}from"fs";import{homedir as mle}from"os";import{dirname as hle,join as vn}from"path";import{fileURLToPath as gle}from"url";function Bk(){return process.env.CLAUDE_CONFIG_DIR||vn(mle(),".claude")}function br(){return vn(Bk(),"plugins","marketplaces","thedotmack")}function ds(){return vn(Bk(),"plugins")}function ic(){return vn(ds(),"known_marketplaces.json")}function ps(){return vn(ds(),"installed_plugins.json")}function fs(){return vn(Bk(),"settings.json")}function oc(){return vn(ds(),"cache","thedotmack","claude-mem")}function sc(t){return vn(oc(),t)}function Aa(){let t=gle(import.meta.url),e=vn(hle(t),"..","..");if(!Jk(vn(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 zk(){return vn(Aa(),"plugin")}function ms(){let t=vn(zk(),".claude-plugin","plugin.json");if(Jk(t))try{let r=JSON.parse(OU(t,"utf-8"));if(r.version)return r.version}catch{}let e=vn(Aa(),"package.json");if(Jk(e))try{let r=JSON.parse(OU(e,"utf-8"));if(r.version)return r.version}catch{}return"0.0.0"}function RU(){return nc()!==null}var St,bi=v(()=>{"use strict";gt();yi();as();St=process.platform==="win32"});var PU,DU,NU,jU=v(()=>{PU=(()=>{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}})(),DU=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,NU=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 yle,ble,LU,vle,KU,Ele,Sle,_le,UU,$U,FU=v(()=>{jU();yle=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,ble=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,LU=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,vle=/\t{1,1000}/y,KU=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"),Ele=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Sle=new RegExp("\\p{M}+","gu"),_le={limit:1/0,ellipsis:""},UU=(t,e={},r={})=>{let i=e.limit??1/0,n=e.ellipsis??"",o=e?.ellipsisWidth??(n?UU(n,_le,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=[[Ele,d],[yle,s],[ble,a],[vle,l],[KU,c],[LU,p]],m=0,h=0,y=t.length,S=0,E=!1,T=y,O=Math.max(0,i-o),N=0,q=0,B=0,ie=0;e:for(;;){if(q>N||h>=y&&h>m){let W=t.slice(N,q)||t.slice(m,h);S=0;for(let Q of W.replaceAll(Sle,"")){let Ae=Q.codePointAt(0)||0;if(DU(Ae)?ie=u:NU(Ae)?ie=p:ie=d,B+ie>O&&(T=Math.min(T,Math.max(N,m)+S)),B+ie>i){E=!0;break e}S+=Q.length,B+=ie}N=q=0}if(h>=y)break e;for(let W=0,Q=f.length;W<Q;W++){let[Ae,mn]=f[W];if(Ae.lastIndex=h,Ae.test(t)){if(S=Ae===LU?PU(t.slice(h,Ae.lastIndex)):Ae===KU?1:Ae.lastIndex-h,ie=S*mn,B+ie>O&&(T=Math.min(T,h+Math.floor((O-B)/mn))),B+ie>i){E=!0;break e}B+=ie,N=m,q=h,h=m=Ae.lastIndex;continue e}}h+=1}return{width:E?O:B,index:E?T:y,truncated:E,ellipsed:E&&i>=o}},$U=UU});var wle,kle,Pr,qk=v(()=>{FU();wle={limit:1/0,ellipsis:"",ellipsisWidth:0},kle=(t,e={})=>$U(t,wle,e).width,Pr=kle});function zi(t,e,r){return String(t).normalize().split(Cle).map(i=>Ale(i,e,r)).join(`
|
|
@@ -608,7 +608,7 @@ ${i.map(s=>zy(s,!1)).join(`
|
|
|
608
608
|
${i.map(s=>zy(s,!1)).join(`
|
|
609
609
|
`)}`),null)}function VW(t){let e=GI(t);return e||R.error("This install has not joined a TeamBrain team. Join one: npx claude-mem teambrain join <invite-link> (or start one: npx claude-mem teambrain start)"),e}function _A(t){try{return t()}catch(e){if(e instanceof Error&&String(e.code??"").startsWith("ERR_PARSE_ARGS"))return console.error(Tn("red",e.message)),console.error(Fy),null;throw e}}async function uSe(t){let e=_A(()=>vA({args:t,options:{share:{type:"string"},"share-all":{type:"boolean"}},allowPositionals:!0,strict:!0}));if(!e)return 1;let r=LW(e.positionals[0]);if(!r.ok)return R.error(r.error),1;let i=EA({share:e.values.share,shareAll:e.values["share-all"]===!0});if(!i.ok)return R.error(i.error),1;let n=By();if(n)return R.error(bA(n,"the join")),1;let o=await Wp({source:"teambrain_join",teamInvite:r.token});if(!o)return R.error(nSe()),1;R.info(`Sign in, then approve this device on the page to join the team: ${o.authorizationUrl}`),Ly(o,"Approving this device on the page, which names the team, joins it."),Jy?(await jy("Hit return to open it in your browser\u2026"),Vc(o.authorizationUrl)):R.info("AGENT: show this link to the user. This command waits until they approve this device.");let s=await Vp(o,"teambrain_join",ZEe);if(!s||s.kind!=="ready")return 1;let a=By();if(a)return R.error(bA(a,"the join")),1;let l=tSe(),c=Gy(),u=UW([l.CLAUDE_MEM_CLOUD_SYNC_USER_ID,c.CLAUDE_MEM_CLOUD_SYNC_USER_ID],s.userId);if(u)return R.error(u),1;let d=$W(s.teambrainUrl);if(!d.ok)return R.error(d.error),1;let p={teambrainUrl:d.url,syncToken:s.setupToken,syncUserId:s.userId,teamId:s.team?.id??""},f=s.team,m=null;if(!f){let E=await WW(p,void 0);if(!E)return 1;f=E.team,m=E.team,p.teamId=f.id}let h=rSe(c,s),y=JW(FW(s,l,{teambrainUrl:p.teambrainUrl,teamId:f.id}));if(y)return R.error(`${y}. ${f.name} counts you as a member, but this install did not save the connection; fix the file and run the join again.`),1;R.success(`Joined ${f.name}. Your memory stays private; you choose what the team sees.`);let S=i.choice??(Jy?await zW(f.name,m):null);if(S){if(!await qW(p,f,S))return 1}else R.info("Not sharing any projects yet. Choose them with: npx claude-mem teambrain share");return h&&await GW(!0),R.info("Your next session starts with the team brief, and agents can use the team_search tool. Check anytime: npx claude-mem teambrain status"),0}async function dSe(t){let e=_A(()=>vA({args:t,options:{share:{type:"string"},"share-all":{type:"boolean"},team:{type:"string"}},allowPositionals:!1,strict:!0}));if(!e)return 1;let r=EA({share:e.values.share,shareAll:e.values["share-all"]===!0});if(!r.ok)return R.error(r.error),1;if(!r.choice&&!Jy)return R.error("Without a terminal, name what to share: npx claude-mem teambrain share --share <a,b> (or --share-all)"),1;let i=VW(Gy());if(!i)return 1;let n=await WW(i,e.values.team);if(!n)return 1;let o=r.choice??await zW(n.team.name,n.team);return o?await qW(i,n.team,o)?0:1:(R.info("Nothing changed."),0)}async function pSe(){let t=GI(Gy());if(!t)return console.log(`${Tn("bold","TeamBrain:")} not joined on this install`),console.log(` Start a team: ${Tn("cyan","npx claude-mem teambrain start")}`),console.log(` Join a team: ${Tn("cyan","npx claude-mem teambrain join <invite-link>")}`),0;console.log(`${Tn("bold","TeamBrain:")} ${Rt(t.teambrainUrl)}`);let e=await rp(t,Xc);if(!e.ok)return console.error(Tn("red",`Could not read your teams: ${e.reason}`)),1;if(e.value.length===0)return console.log(" This account is not in a team. Join one: npx claude-mem teambrain join <invite-link>"),0;for(let r of e.value)console.log(zy(r,r.id===t.teamId));return console.log(Tn("dim","Change what you share: npx claude-mem teambrain share")),0}async function fSe(t,e,r){let i=!t.teamId||t.teamId===e,n=await rp(t,Xc),o=l=>{let c=JW(l);return c&&R.error(`${c}. The team was left on cmem.ai, but this install still points at it; fix the file and run leave again.`),!c};if(!n.ok)return R.warn(`Could not read which teams this account is still in: ${n.reason}`),i?o(yA)?(R.info("Cleared CLAUDE_MEM_TEAMBRAIN_URL and CLAUDE_MEM_TEAMBRAIN_TEAM_ID on this install. Cloud sync settings were not changed. To use another team you are in, join it again with its invite link."),0):1:(R.info("Nothing on this install changed: it stays connected to its own team. Cloud sync settings were not changed."),0);let s=n.value;if(s.length>0){if(i){if(!o({CLAUDE_MEM_TEAMBRAIN_TEAM_ID:s[0].id}))return 1;R.info(`This install now uses ${s[0].name}.`)}return R.info(`Still in: ${s.map(l=>l.name).join(", ")}. Cloud sync settings were not changed.`),0}let a=r.CLAUDE_MEM_PRO_PLAN.trim()==="teambrain_seat";return o(a?{...yA,...eSe}:yA)?(R.info("This account is in no team now, so TeamBrain is off on this install (CLAUDE_MEM_TEAMBRAIN_URL and CLAUDE_MEM_TEAMBRAIN_TEAM_ID cleared)."),a?(R.info("Cloud sync is off for this install too: a TeamBrain seat was its only sync access (CLAUDE_MEM_CLOUD_SYNC_* cleared). Your memory stays on this machine."),await GW(!1),0):(R.info("Cloud sync settings were not changed."),0)):1}async function mSe(t){let e=_A(()=>vA({args:t,options:{},allowPositionals:!0,strict:!0}));if(!e)return 1;let r=By();if(r)return R.error(bA(r,"leave")),1;let i=Gy(),n=VW(i);if(!n)return 1;let o=await rp(n,Xc);o.ok||R.warn(`Could not read your teams before leaving: ${o.reason}`);let s=o.ok?o.value:null,a=e.positionals[0]?.trim()??"",l=a||n.teamId||(s?.length===1?s[0].id:"");if(!l)return R.error(o.ok?"Name the team to leave: npx claude-mem teambrain leave <team-id> (see npx claude-mem teambrain status)":"Name the team to leave: npx claude-mem teambrain leave <team-id>"),1;let c=s?.find(d=>d.id===l),u=c?.name??`team ${Rt(l)}`;if(s&&!c){if(a)return R.error(`This account is not in team ${Rt(l)}.${s.length>0?` Its teams:
|
|
610
610
|
${s.map(d=>zy(d,!1)).join(`
|
|
611
|
-
`)}`:""}`),1;R.info(`This account is no longer in ${u}; removing it from this install.`)}else{if(Jy){let p=await vi({message:`Leave ${u}? TeamBrain removes what you shared with it.`,initialValue:!1});if(xt(p)||!p)return R.info("Still in the team. Nothing changed."),0}let d=await YF(n,l,Xc);if(!d.ok)return R.error(`Could not leave ${u}: ${d.reason}`),1;R.success(`Left ${u}.`)}return fSe(n,l,i)}function hSe(){let t=ZF(qi()),e=!process.stdout.isTTY||!!process.env.CI||!!(process.env.SSH_CONNECTION||process.env.SSH_TTY)||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY;return console.log(`Create your team's TeamBrain: ${Tn("cyan",t)}`),e?console.log("Open that link in a browser to continue."):Vc(t),0}async function gSe(t=[]){let e=t[0]?.toLowerCase()??"status";if(t.slice(1).some(r=>r==="--help"||r==="-h"))return console.log(Fy),0;switch(e){case"join":return uSe(t.slice(1));case"start":return hSe();case"status":return pSe();case"share":return dSe(t.slice(1));case"leave":return mSe(t.slice(1));case"help":case"--help":case"-h":return console.log(Fy),0;default:return console.error(Tn("red",`Unknown teambrain command: ${Rt(e)}`)),console.error(Fy),1}}var ZEe,Jy,Xc,qy,DW,XEe,QEe,gA,NW,eSe,yA,Fy,YW=v(()=>{"use strict";zd();gt();ep();xa();Oe();Qd();gr();pi();PW();HI();yi();he();Pd();Hp();ZEe="15.0.
|
|
611
|
+
`)}`:""}`),1;R.info(`This account is no longer in ${u}; removing it from this install.`)}else{if(Jy){let p=await vi({message:`Leave ${u}? TeamBrain removes what you shared with it.`,initialValue:!1});if(xt(p)||!p)return R.info("Still in the team. Nothing changed."),0}let d=await YF(n,l,Xc);if(!d.ok)return R.error(`Could not leave ${u}: ${d.reason}`),1;R.success(`Left ${u}.`)}return fSe(n,l,i)}function hSe(){let t=ZF(qi()),e=!process.stdout.isTTY||!!process.env.CI||!!(process.env.SSH_CONNECTION||process.env.SSH_TTY)||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY;return console.log(`Create your team's TeamBrain: ${Tn("cyan",t)}`),e?console.log("Open that link in a browser to continue."):Vc(t),0}async function gSe(t=[]){let e=t[0]?.toLowerCase()??"status";if(t.slice(1).some(r=>r==="--help"||r==="-h"))return console.log(Fy),0;switch(e){case"join":return uSe(t.slice(1));case"start":return hSe();case"status":return pSe();case"share":return dSe(t.slice(1));case"leave":return mSe(t.slice(1));case"help":case"--help":case"-h":return console.log(Fy),0;default:return console.error(Tn("red",`Unknown teambrain command: ${Rt(e)}`)),console.error(Fy),1}}var ZEe,Jy,Xc,qy,DW,XEe,QEe,gA,NW,eSe,yA,Fy,YW=v(()=>{"use strict";zd();gt();ep();xa();Oe();Qd();gr();pi();PW();HI();yi();he();Pd();Hp();ZEe="15.0.1",Jy=process.stdin.isTTY===!0,Xc=15e3,qy=5e3,DW=3e4,XEe=1e3,QEe=40,gA="__teambrain_all_projects__",NW=/^[A-Za-z0-9_-]{16,128}$/,eSe={CLAUDE_MEM_CLOUD_SYNC_TOKEN:"",CLAUDE_MEM_CLOUD_SYNC_USER_ID:"",CLAUDE_MEM_CLOUD_SYNC_HUB_URL:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_ID:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_NAME:"",CLAUDE_MEM_PRO_PLAN:""},yA={CLAUDE_MEM_TEAMBRAIN_URL:"",CLAUDE_MEM_TEAMBRAIN_TEAM_ID:""},Fy=[`Usage: ${Tn("bold","npx claude-mem teambrain <command>")}`," join <invite-link> Join a team: sign in, approve this device on the page, then choose which projects to share"," (without a terminal: --share <a,b> or --share-all)"," start Create a team on cmem.ai (opens the browser)"," status Show your teams and what this install shares (the default)"," share Choose again which projects you share (--share <a,b>, --share-all, --team <id>)"," leave [team-id] Leave a team; TeamBrain removes what you shared with it"].join(`
|
|
612
612
|
`)});function ySe(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function bSe(t){if(!t)return ZW;let e=ySe(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e.includes("kimi")?"kimi":e==="pi-mono"?"pi":e==="agy"||e==="antigravity"||e.startsWith("antigravity-")?"antigravity-cli":e:ZW}function to(t){return typeof t!="string"?null:bSe(t)}var ZW,Wy=v(()=>{"use strict";ZW="claude"});import{existsSync as vSe,readFileSync as ESe}from"fs";function wA(t){return new RegExp(`${t}${SSe}`,"gi")}function XW(t){return`(?<=${t}${Hy}${rf}[=:]${rf}${Hy})`}function kA(t,e){if(!e.enabled||t.length===0)return{redacted:t,counts:{},oversize:!1};if(t.length>kSe)return b.warn("REDACT","field exceeds the 1M-char redaction cap; replaced by an oversize marker",void 0,{inputLength:t.length}),{redacted:ISe,counts:{oversize:1},oversize:!0};let r=new Set(e.disabledBuiltinPatterns??[]),i={},n=t,o=[];for(let a of e.customPatterns??[]){if(!a.name||a.name.length===0){b.warn("REDACT","custom pattern skipped: missing name",void 0,{pattern:a});continue}try{o.push({name:a.name,regex:new RegExp(a.regex,"g")})}catch(l){b.warn("REDACT","custom pattern skipped: invalid regex",{name:a.name},l instanceof Error?l:new Error(String(l)))}}let s=[...o,..._Se,...e.genericEnabled?wSe:[]];for(let a of s)r.has(a.name)||(a.regex.lastIndex=0,n=n.replace(a.regex,()=>(i[a.name]=(i[a.name]??0)+1,`<redacted type='${a.name}'/>`)));return e.logMatches&&Object.keys(i).length>0&&b.debug("REDACT","patterns matched",void 0,{counts:i}),{redacted:n,counts:i,oversize:!1}}function xSe(t){if(!t||t.trim()==="")return[];try{let e=JSON.parse(t);return Array.isArray(e)?e.filter(r=>r&&typeof r.name=="string"&&typeof r.regex=="string"):(b.warn("REDACT","CLAUDE_MEM_REDACT_CUSTOM_PATTERNS is not a JSON array, ignoring"),[])}catch(e){return b.warn("REDACT","failed to parse CLAUDE_MEM_REDACT_CUSTOM_PATTERNS as JSON",void 0,e instanceof Error?e:new Error(String(e))),[]}}function TSe(t){return{enabled:t.CLAUDE_MEM_REDACT_ENABLED==="true",disabledBuiltinPatterns:(t.CLAUDE_MEM_REDACT_DISABLED_BUILTINS??"").split(",").map(e=>e.trim()).filter(Boolean),customPatterns:xSe(t.CLAUDE_MEM_REDACT_CUSTOM_PATTERNS??"[]"),logMatches:t.CLAUDE_MEM_REDACT_LOG_MATCHES==="true",genericEnabled:t.CLAUDE_MEM_REDACT_GENERIC_ENABLED==="true"}}function RSe(t){if(!vSe(t))return null;try{return ESe(t,"utf-8")}catch{return""}}function MSe(t){if(t===null)return!1;try{let e=JSON.parse(os(t));return e===null||typeof e!="object"||Array.isArray(e)}catch{return!0}}function PSe(t,e,r){return process.env.CLAUDE_MEM_REDACT_ENABLED==="false"||!(tf?.enabled===!0||OSe.test(e))?r:(e6||(e6=!0,b.warn("REDACT","settings.json could not be read; secret redaction stays on until it is repaired",{settingsPath:t,using:tf?.enabled?"the last configuration that loaded":"the built-in patterns"})),tf?.enabled?tf:CSe)}function IA(t=we){let e=Date.now();if(ef&&e-QW<ASe)return ef;let r=Te.loadFromFile(t),i=TSe(r),n=i.enabled?null:RSe(t);return MSe(n)?ef=PSe(t,n,i):(ef=i,tf=i),QW=e,ef}function jSe(t,e,r){if(!r.genericEnabled)return null;let i=DSe.exec(t);if(!i)return null;let n=i[1].toLowerCase().startsWith("passw")?"generic_password":"generic_token";return r.disabledBuiltinPatterns?.includes(n)||!NSe.test(e)||!/[A-Za-z]/.test(e)?null:`<redacted type='${n}'/>`}function t6(t,e=IA()){if(!e.enabled)return t;let r=(i,n)=>{if(typeof i=="string"){let o=kA(i,e);return n===void 0||Object.keys(o.counts).length>0?o.redacted:jSe(n,i,e)??o.redacted}return Array.isArray(i)?i.map(o=>r(o)):i!==null&&typeof i=="object"?Object.fromEntries(Object.entries(i).map(([o,s])=>[o,r(s,o)])):i};return r(t)}var Vy,SSe,Hy,rf,_Se,wSe,kSe,ISe,ef,QW,ASe,tf,e6,CSe,OSe,DSe,NSe,xA=v(()=>{"use strict";he();gr();Oe();gt();Vy=String.raw`[A-Za-z0-9_.\-+/=~@#$%^*!?]`,SSe=`(?=${Vy}{8})${Vy}*[A-Za-z]${Vy}*`,Hy=String.raw`(?:\\{0,3}["'])?`,rf=String.raw`\s{0,8}`;_Se=[{name:"aws_access_key",regex:/AKIA[0-9A-Z]{16}/g},{name:"aws_secret_key",regex:/(?<=AWS_SECRET_ACCESS_KEY\s{0,8}[=:]\s{0,8}['"]?)[A-Za-z0-9/+=]{40}/g},{name:"github_pat",regex:/\bgh[oprsu]_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{82}\b/g},{name:"openai_key",regex:/\bsk-(?!ant-)[A-Za-z0-9_-]{20,}(?!\w)/g},{name:"anthropic_key",regex:/\bsk-ant-[A-Za-z0-9_-]{20,}(?!\w)/g},{name:"slack_token",regex:/\bxox[baprs]-[A-Za-z0-9-]{10,}(?!\w)/g},{name:"jwt",regex:/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+(?!\w)/g},{name:"private_key_pem",regex:/-----BEGIN (?:RSA |DSA |EC |OPENSSH |PGP )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |DSA |EC |OPENSSH |PGP )?PRIVATE KEY-----/g},{name:"stripe_key",regex:/\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]{24,}\b/g},{name:"google_api_key",regex:/\bAIza[0-9A-Za-z_-]{35}(?!\w)/g},{name:"claude_mem_key",regex:/\bcmem_[A-Za-z0-9_-]{32,}|\bcm_pro_[A-Za-z0-9_-]{8,}/g}],wSe=[{name:"generic_password",regex:wA(XW(String.raw`\b(?:\w*_?(?:password|passwd)|\w+_pwd)`))},{name:"generic_token",regex:wA(XW(String.raw`\b\w*_(?:token|secret|api_key)`))},{name:"bearer_token",regex:wA(`(?<=\\bAuthorization${Hy}${rf}:${rf}${Hy}Bearer${rf})`)}],kSe=1024*1024,ISe="<redacted type='oversize'/>";ef=null,QW=0,ASe=5e3,tf=null,e6=!1,CSe={enabled:!0,disabledBuiltinPatterns:[],customPatterns:[],logMatches:!1},OSe=/"CLAUDE_MEM_REDACT_ENABLED"\s*:\s*"true"/;DSe=/(?:^|_)(password|passwd|secret|token|api_key)$/i,NSe=new RegExp(`^${Vy}{8,}$`)});function KSe(t){let e=Object.fromEntries(o6.map(u=>[u,0]));if(!t.includes("<"))return{text:t,counts:e,total:0};let r=t.length,i=new Int32Array(r+1);i[r]=r;for(let u=r-1;u>=0;u--)i[u]=t.charCodeAt(u)===62?u:i[u+1];let n=new Map,o=[],s=0,a=0;for(;a<r;){if(t.charCodeAt(a)!==60){a+=1;continue}n6.lastIndex=a;let u=n6.exec(t);if(u){let p=u[1],f=n.get(p),m=f&&f.head<f.items.length?f.items[f.head]:void 0;m&&a>=m.attrEnd&&(f.head+=1,o.push([m.start,a+u[0].length]),e[p]+=1,s+=1),a+=u[0].length;continue}r6.lastIndex=a;let d=r6.exec(t);if(d&&LSe.has(d[1])){let p=d[1],f=a+d[0].length,m={start:a,attrEnd:i[f]},h=n.get(p);h?h.items.push(m):n.set(p,{items:[m],head:0}),a=f;continue}a+=1}o.sort((u,d)=>u[0]-d[0]);let l="",c=0;for(let[u,d]of o)u>c&&(l+=t.slice(c,u)),d>c&&(c=d);return l+=t.slice(c),{text:l,counts:e,total:s}}function USe(t,{text:e,counts:r,total:i}){return i>i6&&b.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:i,maxAllowed:i6,contentLength:t.length}),{stripped:kA(e.trim(),IA()).redacted,counts:r}}function nf(t){let e=r=>{if(typeof r=="string"){let i=KSe(r);return i.total>0?USe(r,i).stripped:r}return Array.isArray(r)?r.map(e):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).map(([i,n])=>[i,e(n)])):r};return e(t)}var o6,LSe,r6,n6,i6,$Se,q3e,G3e,TA=v(()=>{"use strict";he();xA();o6=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],LSe=new Set(o6),r6=/<([A-Za-z_][A-Za-z0-9_-]*)/y,n6=/<\/([A-Za-z_][A-Za-z0-9_-]*)\s*>/y;i6=100;$Se=["task-notification"],q3e=new RegExp(`^\\s*<(${$Se.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),G3e=256*1024});function s6(t){let e=to(t.platformSource),r=e?[e]:[];return t.sourceEventId?`agent_event:v1:${xi([t.teamId,t.projectId,t.sourceAdapter,...r,t.sourceEventId])}`:`agent_event:v1:${xi([t.teamId,t.projectId,t.sourceAdapter,...r,t.contentSessionId??t.serverSessionId??null,t.eventType,new Date(t.occurredAt).toISOString(),Bp(t.payload??{})])}`}function AA(t){return{id:t.id,projectId:t.project_id,teamId:t.team_id,serverSessionId:t.server_session_id,sourceAdapter:t.source_adapter,sourceEventId:t.source_event_id,idempotencyKey:t.idempotency_key,eventType:t.event_type,platformSource:t.platform_source,payload:t.payload,metadata:Ot(t.metadata),occurredAtEpoch:Qe(t.occurred_at),receivedAtEpoch:Qe(t.received_at),createdAtEpoch:Qe(t.created_at)}}var of,CA=v(()=>{"use strict";jo();Wy();xA();TA();of=class{constructor(e){this.client=e}client;async create(e){await Ii(this.client,e.projectId,e.teamId),e.serverSessionId&&await No(this.client,e.serverSessionId,e.projectId,e.teamId);let r=s6(e),i=to(e.platformSource),n=await ve(this.client,`
|
|
613
613
|
INSERT INTO agent_events (
|
|
614
614
|
id, project_id, team_id, server_session_id, source_adapter,
|
package/dsh/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "Claude-Mem (Persistent Memory)",
|
|
4
4
|
"description": "OpenClaw plugin for Claude-Mem. Records observations from embedded runner sessions and streams them to messaging channels.",
|
|
5
5
|
"kind": "memory",
|
|
6
|
-
"version": "15.0.
|
|
6
|
+
"version": "15.0.1",
|
|
7
7
|
"license": "Apache-2.0",
|
|
8
8
|
"author": "thedotmack",
|
|
9
9
|
"homepage": "https://claude-mem.ai",
|
package/package.json
CHANGED