claude-mem 13.15.2 → 13.15.3

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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "13.15.2",
3
+ "version": "13.15.3",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "author": {
6
6
  "name": "Alex Newman",
@@ -98,7 +98,7 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
98
98
  ${m.stack??""}
99
99
  `)}else js(f+`
100
100
  `)}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){jb=e}error(e,r,i,n){this.log(3,e,r,i,n),this.routeErrorToSink(r,i,n)}routeErrorToSink(e,r,i){try{if(!jb||!(i instanceof Error))return;jb(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)}},x=new Mb});import{join as AA}from"path";import{mkdirSync as S3,writeFileSync as E3}from"fs";import{randomUUID as w3}from"crypto";function k3(t){let e=t.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function Nb(t,e){if(k3(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 RA(t,e){return Nb(t,e).enabled}function zl(){return AA(Rn(),KA)}function Ri(){let t;try{t=Ft(zl(),null)}catch(e){let r=e instanceof Error?e:new Error(String(e));return x.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 $s(t){let e=Rn();S3(e,{recursive:!0}),E3(AA(e,KA),JSON.stringify(t,null,2)+`
101
- `)}function Dd(){let t=Ri();if(t?.installId)return t.installId;let e=w3();return $s({installId:e,decidedAt:""}),e}var KA,jd=S(()=>{"use strict";it();_o();Me();KA="telemetry.json"});function I3(t,e){if(!(!t||typeof t!="object"))for(let r of Object.keys(t)){if(!x3.has(r))continue;let i=t[r];typeof i=="string"?e[r]=i.length>DA?i.slice(0,DA):i:(typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean")&&(e[r]=i)}}function jA(t){let e={};try{I3(t,e)}catch{}return e}var x3,DA,PA=S(()=>{"use strict";x3=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","install_method","interactive","bun_version","uv_version","claude_code_version","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","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_invalid_output","top_model","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","observations_created","total_observations_injected","total_tokens_saved_vs_naive"]),DA=200});import MA from"os";function NA(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||T3}function LA(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||C3}function UA(t){let e={};for(let r of O3)t[r]!==void 0&&(e[r]=t[r]);return e}function A3(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||MA.release().toLowerCase().includes("microsoft")}catch(t){let e=t instanceof Error?t:new Error(String(t));return x.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function $A(){return{version:_3,os:process.platform,os_version:MA.release(),is_wsl:A3(),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 _3,T3,C3,O3,JA=S(()=>{"use strict";Me();_3="13.15.2",T3="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",C3="https://us.i.posthog.com";O3=["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 br(t,e,r){try{if(!RA(process.env,Ri()))return;let i=jA({...$A(),...e??{}});if(r?.person?i.$set=UA(i):i.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:t,properties:i})+`
101
+ `)}function Dd(){let t=Ri();if(t?.installId)return t.installId;let e=w3();return $s({installId:e,decidedAt:""}),e}var KA,jd=S(()=>{"use strict";it();_o();Me();KA="telemetry.json"});function I3(t,e){if(!(!t||typeof t!="object"))for(let r of Object.keys(t)){if(!x3.has(r))continue;let i=t[r];typeof i=="string"?e[r]=i.length>DA?i.slice(0,DA):i:(typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean")&&(e[r]=i)}}function jA(t){let e={};try{I3(t,e)}catch{}return e}var x3,DA,PA=S(()=>{"use strict";x3=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","install_method","interactive","bun_version","uv_version","claude_code_version","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","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_invalid_output","top_model","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","observations_created","total_observations_injected","total_tokens_saved_vs_naive"]),DA=200});import MA from"os";function NA(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||T3}function LA(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||C3}function UA(t){let e={};for(let r of O3)t[r]!==void 0&&(e[r]=t[r]);return e}function A3(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||MA.release().toLowerCase().includes("microsoft")}catch(t){let e=t instanceof Error?t:new Error(String(t));return x.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function $A(){return{version:_3,os:process.platform,os_version:MA.release(),is_wsl:A3(),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 _3,T3,C3,O3,JA=S(()=>{"use strict";Me();_3="13.15.3",T3="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",C3="https://us.i.posthog.com";O3=["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 br(t,e,r){try{if(!RA(process.env,Ri()))return;let i=jA({...$A(),...e??{}});if(r?.person?i.$set=UA(i):i.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:t,properties:i})+`
102
102
  `);return}let n=NA(),o=new AbortController,s=setTimeout(()=>o.abort(),K3);try{await R3(n,t,i,o.signal)}finally{clearTimeout(s)}}catch{}}async function R3(t,e,r,i){await fetch(`${LA()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:t,event:e,distinct_id:Dd(),properties:r}),signal:i})}var K3,Pd=S(()=>{"use strict";jd();PA();JA();K3=2e3});import{spawn as D3,spawnSync as j3}from"node:child_process";import{extname as Lb}from"node:path";function Di(t,e,r){return D3(t,e??[],{windowsHide:!0,...r})}function M3(t){return`"${t.replace(/"/g,'""')}"`}function Md(t){if(process.platform!=="win32")return null;try{let e=j3("where",[t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0});if(e.status!==0||!e.stdout.trim())return null;let r=e.stdout.split(/\r?\n/).map(i=>i.trim()).filter(Boolean);return r.find(i=>qA.has(Lb(i).toLowerCase()))??r.find(i=>P3.has(Lb(i).toLowerCase()))??r[0]??null}catch{return null}}function Js(t,e,r,i=process.platform){let n={...i==="win32"?{windowsHide:!0}:{},...r};if(i==="win32"&&FA.has(Lb(t).toLowerCase())){let o=[t,...e].map(M3).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 FA,qA,P3,ji=S(()=>{"use strict";FA=new Set([".cmd",".bat"]),qA=new Set([".exe",".com"]),P3=new Set([...qA,...FA])});function Fs(t){return process.platform==="win32"?Math.round(t*ir.WINDOWS_MULTIPLIER):t}var ir,Gl=S(()=>{"use strict";ir={HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5}});var VA={};_e(VA,{SettingsDefaultsManager:()=>ze});import{readFileSync as N3,existsSync as L3}from"fs";import{join as zA}from"path";import{homedir as GA,hostname as U3}from"os";var $3,ze,Hr=S(()=>{"use strict";Gl();mn();$3="security_alert",ze=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_API_TIMEOUT_MS:String(Fs(ir.API_REQUEST)),CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-flash-latest",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_DATA_DIR:zA(GA(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",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_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_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_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:zA(GA(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_CHROMA_MAX_PENDING_MUTATIONS:"5000",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:U3(),CLAUDE_MEM_CLOUD_SYNC_WS:"true",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert,sensitive",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",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:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}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){try{if(!L3(e)){let a=this.getAllDefaults();try{ht(e,a),console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(l){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,l instanceof Error?l.message:String(l))}return r?this.applyEnvOverrides(a):a}let i=N3(e,"utf-8"),n=rr(i),o=n;if(n.env&&typeof n.env=="object"){o=n.env;try{ht(e,o),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(a){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,a instanceof Error?a.message:String(a))}}if(o.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES===$3){o={...o,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES};try{ht(e,o),console.warn("[SETTINGS] Migrated Telegram trigger types off the legacy default:",e)}catch(a){console.warn("[SETTINGS] Failed to migrate Telegram trigger types:",e,a instanceof Error?a.message:String(a))}}let s={...this.DEFAULTS};for(let a of Object.keys(this.DEFAULTS))o[a]!==void 0&&(s[a]=o[a]);return r?this.applyEnvOverrides(s):s}catch(i){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,i instanceof Error?i.message:String(i));let n=this.getAllDefaults();return r?this.applyEnvOverrides(n):n}}}});import{execFile as J3}from"child_process";import{promisify as F3}from"util";import{existsSync as qge,readFileSync as zge,writeFileSync as Gge,mkdirSync as Vge,unlinkSync as Bge}from"fs";import{userInfo as Zge}from"os";import{join as Yge}from"path";var ebe,BA=S(()=>{"use strict";it();Me();ebe=F3(J3)});import{existsSync as Ub,readFileSync as ZA,writeFileSync as q3,mkdirSync as z3,chmodSync as WA}from"fs";import{parseEnv as G3}from"util";function HA(){return process.env.CLAUDE_MEM_ENV_FILE??bt.envFile()}function XA(t){return G3(t)}function V3(t){let e=["# claude-mem credentials","# This file stores keys and gateway settings for the claude-mem memory agent","# Edit this file or use claude-mem settings to configure",""];for(let[r,i]of Object.entries(t))if(i){let n=/[\s#=]/.test(i);e.push(`${r}=${n?`"${i}"`:i}`)}return e.join(`
103
103
  `)+`
104
104
  `}function Vl(){let t=HA();if(!Ub(t))return{};try{let e=ZA(t,"utf-8"),r=XA(e),i={};for(let n of YA)r[n]&&(i[n]=r[n]);return i}catch(e){return x.warn("ENV","Failed to load .env file",{path:t},e instanceof Error?e:new Error(String(e))),{}}}function Bl(t){let e=HA(),r={};try{Ub(bt.dataDir())||z3(bt.dataDir(),{recursive:!0,mode:448}),WA(bt.dataDir(),448),r=Ub(e)?XA(ZA(e,"utf-8")):{}}catch(n){let o=n instanceof Error?n:new Error(String(n));throw x.error("ENV","Failed to set up env directory or read existing env",{},o),o}let i={...r};for(let n of YA){let o=t[n];o!==void 0&&(o?i[n]=o:delete i[n])}try{q3(e,V3(i),{encoding:"utf-8",mode:384}),WA(e,384)}catch(n){throw x.error("ENV","Failed to save .env file",{path:e},n instanceof Error?n:new Error(String(n))),n}}var YA,QA=S(()=>{"use strict";Me();it();BA();YA=["ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","GEMINI_API_KEY","OPENROUTER_API_KEY"]});function Ko(t=process.env){let e={};for(let[r,i]of Object.entries(t))if(i!==void 0){if(H3.has(r)){e[r]=i;continue}W3.has(r)||B3.some(n=>r.startsWith(n))||(e[r]=i)}return e}var B3,W3,Z3,H3,Nd=S(()=>{"use strict";B3=["CLAUDECODE_","CLAUDE_CODE_"],W3=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),Z3=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"]),H3=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_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",...Z3])});import{spawnSync as nK}from"child_process";import{existsSync as Y3,mkdirSync as eK,readFileSync as iK,writeFileSync as X3}from"fs";import tK from"path";function Yr(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:(x.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return x.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function Ld(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(i=>!Yr(i.pid)))return;await new Promise(i=>setTimeout(i,100))}}function nZ(t){let e=nK("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Ko(process.env),LC_ALL:"C",LANG:"C"}});if(e.status===0){let r=e.stdout.trim();return r.length>0?r:null}return null}function iZ(t){let e=rK.get(t);if(e&&Date.now()-e.capturedAtMs<rZ)return e.token;let r=null;try{r=nZ(t)}catch(i){x.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:i instanceof Error?i.message:String(i)}),r=null}return rK.set(t,{token:r,capturedAtMs:Date.now()}),r}function oK(t){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux")try{let e=iK(`/proc/${t}/stat`,"utf-8"),r=e.lastIndexOf(") ");if(r<0)return null;let n=e.slice(r+2).split(" ")[19];return n&&/^\d+$/.test(n)?n:null}catch(e){return x.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return iZ(t);try{let e=nK("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Ko(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let r=e.stdout.trim();return r.length>0?r:null}catch(e){return x.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}}function qb(t){if(!t||!Yr(t.pid))return!1;if(!t.startToken)return!0;let e=oK(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||x.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}function Ud(){return $b||($b=new Fb),$b}function Jb(){let t=oZ.shift();t&&t()}var Q3,eZ,tZ,rZ,rK,Fb,$b,oZ,qs=S(()=>{"use strict";ji();Me();Nd();it();Q3=5e3,eZ=1e3,tZ=bt.supervisorRegistry();rZ=5e3,rK=new Map;Fb=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=tZ){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,eK(tK.dirname(this.registryPath),{recursive:!0}),!Y3(this.registryPath)){this.persist();return}try{let i=JSON.parse(iK(this.registryPath,"utf-8")).processes??{};for(let[n,o]of Object.entries(i))this.entries.set(n,o)}catch(r){r instanceof Error?x.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):x.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&x.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,r,i){this.initialize(),this.entries.set(e,r),i&&this.runtimeProcesses.set(e,i),this.persist()}unregister(e){this.initialize();let r=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),r?.type==="sdk"&&Jb()}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)Yr(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)Jb();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;x.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:i,pids:r.map(s=>s.pid)});let n=r.filter(s=>Yr(s.pid));for(let s of n)try{typeof s.pgid=="number"&&process.platform!=="win32"?process.kill(-s.pgid,"SIGTERM"):process.kill(s.pid,"SIGTERM")}catch(a){a instanceof Error?a.code!=="ESRCH"&&x.debug("SYSTEM",`Failed to SIGTERM session process PID ${s.pid}`,{pid:s.pid,pgid:s.pgid},a):x.warn("SYSTEM",`Failed to SIGTERM session process PID ${s.pid} (non-Error)`,{pid:s.pid,pgid:s.pgid,error:String(a)})}await Ld(n,Q3);let o=n.filter(s=>Yr(s.pid));for(let s of o){x.warn("SYSTEM",`Session process PID ${s.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:s.pid,pgid:s.pgid,sessionId:i});try{typeof s.pgid=="number"&&process.platform!=="win32"?process.kill(-s.pgid,"SIGKILL"):process.kill(s.pid,"SIGKILL")}catch(a){a instanceof Error?a.code!=="ESRCH"&&x.debug("SYSTEM",`Failed to SIGKILL session process PID ${s.pid}`,{pid:s.pid,pgid:s.pgid},a):x.warn("SYSTEM",`Failed to SIGKILL session process PID ${s.pid} (non-Error)`,{pid:s.pid,pgid:s.pgid,error:String(a)})}}if(o.length>0){let s=Date.now()+eZ;for(;Date.now()<s&&o.filter(l=>Yr(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let s of r)this.entries.delete(s.id),this.runtimeProcesses.delete(s.id);this.persist();for(let s of r)s.type==="sdk"&&Jb();return x.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())};eK(tK.dirname(this.registryPath),{recursive:!0}),X3(this.registryPath,JSON.stringify(e,null,2))}},$b=null;oZ=[]});import{execFile as sZ}from"child_process";import{existsSync as aZ,readFileSync as lZ,rmSync as cZ}from"fs";import{promisify as uZ}from"util";async function aK(t){let e=t.currentPid??process.pid,r=t.pidFilePath??pZ,i=t.registry.getAll(),n=[...i].filter(s=>s.pid!==e).sort((s,a)=>Date.parse(a.startedAt)-Date.parse(s.startedAt));for(let s of n){if(!Yr(s.pid)){t.registry.unregister(s.id);continue}try{await sK(s,"SIGTERM")}catch(a){a instanceof Error?x.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:s.pid,pgid:s.pgid,type:s.type},a):x.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:s.pid,pgid:s.pgid,type:s.type,error:String(a)})}}await Ld(n,5e3);let o=n.filter(s=>Yr(s.pid));for(let s of o)try{await sK(s,"SIGKILL")}catch(a){a instanceof Error?x.debug("SYSTEM","Failed to force kill child process",{pid:s.pid,pgid:s.pgid,type:s.type},a):x.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:s.pid,pgid:s.pgid,type:s.type,error:String(a)})}await Ld(o,1e3);for(let s of n)t.registry.unregister(s.id);for(let s of i.filter(a=>a.pid===e))t.registry.unregister(s.id);lK(r,e),t.registry.pruneDeadEntries()}function lK(t,e,r=!1){if(!aZ(t))return;let i=null;try{let s=JSON.parse(lZ(t,"utf-8"));i=typeof s.pid=="number"?s.pid:null}catch(s){x.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||!Yr(i);if(!n&&!(r&&o)){x.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{cZ(t,{force:!0})}catch(s){s instanceof Error?x.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},s):x.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(s)})}}async function sK(t,e){let{pid:r,pgid:i}=t;if(process.platform!=="win32"){if(typeof i=="number")try{process.kill(-i,e);return}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}try{process.kill(r,e)}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}return}if(e==="SIGTERM"){try{process.kill(r,e)}catch(o){if(o instanceof Error&&o.code==="ESRCH")return;throw o}return}let n=["/PID",String(r),"/T"];e==="SIGKILL"&&n.push("/F"),await dZ("taskkill",n,{timeout:ir.POWERSHELL_COMMAND,windowsHide:!0})}var dZ,pZ,zb=S(()=>{"use strict";Me();Gl();qs();it();dZ=uZ(sZ),pZ=bt.workerPid()});function fZ(){let e=Ud().pruneDeadEntries();e>0&&x.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function uK(){zs===null&&(zs=setInterval(fZ,cK),zs.unref(),x.debug("SYSTEM","Health checker started",{intervalMs:cK}))}function dK(){zs!==null&&(clearInterval(zs),zs=null,x.debug("SYSTEM","Health checker stopped"))}var cK,zs,pK=S(()=>{"use strict";Me();qs();cK=3e4,zs=null});import{existsSync as mZ,readFileSync as hZ,rmSync as fK}from"fs";function Vb(){return gZ}function $d(t={}){let e=t.pidFilePath??yZ;if(!mZ(e))return"missing";let r=null;try{r=JSON.parse(hZ(e,"utf-8"))}catch(n){return n instanceof Error?x.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},n):x.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(n)}),fK(e,{force:!0}),"invalid"}return qb(r)&&r?((t.logAlive??!0)&&x.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(x.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),fK(e,{force:!0}),"stale")}var yZ,Gb,gZ,Jd=S(()=>{"use strict";Me();qs();zb();pK();it();yZ=bt.workerPid(),Gb=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(),$d({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,uK()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async i=>{if(this.shutdownInitiated){x.warn("SYSTEM",`Received ${i} but shutdown already in progress`);return}this.shutdownInitiated=!0,x.info("SYSTEM",`Received ${i}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(n){n instanceof Error?x.error("SYSTEM","Error during shutdown",{},n):x.error("SYSTEM","Error during shutdown (non-Error)",{error:String(n)});try{await this.stop()}catch(o){o instanceof Error?x.debug("SYSTEM","Supervisor shutdown fallback failed",{},o):x.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",()=>{x.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}dK(),this.stopPromise=aK({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){this.registry.unregister(e)}getRegistry(){return this.registry}},gZ=new Gb(Ud())});import{createHash as $be,randomUUID as Jbe}from"crypto";var mK=S(()=>{"use strict";Me()});import{randomUUID as Wbe}from"crypto";var hK=S(()=>{"use strict";Me();mK()});import Gs from"path";import{homedir as bZ}from"os";import{existsSync as Wb,writeFileSync as nve,readFileSync as ive,unlinkSync as ove,mkdirSync as sve,statSync as ave,utimesSync as vZ,copyFileSync as lve}from"fs";import{execSync as bK,spawnSync as uve}from"child_process";function gK(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function SZ(t,e){let r=e==="win32"?`where ${t}`:`which ${t}`,i;try{i=bK(r,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(o){return o instanceof Error?x.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},o):x.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},new Error(String(o))),null}return i.split(/\r?\n/).map(o=>o.trim()).find(o=>o.length>0)||null}function vK(t={}){let e=Object.keys(t).length===0;if(e&&Bb!==void 0)return Bb;let r=EZ(t);return e&&r!==null&&(Bb=r),r}function EZ(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(gK(r))return r;let i=t.env??process.env,n=t.homeDirectory??bZ(),o=t.pathExists??Wb,s=t.lookupInPath??SZ,a=e==="win32"?[i.BUN,i.BUN_PATH,Gs.join(n,".bun","bin","bun.exe"),Gs.join(n,".bun","bin","bun"),i.USERPROFILE?Gs.join(i.USERPROFILE,".bun","bin","bun.exe"):void 0,i.LOCALAPPDATA?Gs.join(i.LOCALAPPDATA,"bun","bun.exe"):void 0,i.LOCALAPPDATA?Gs.join(i.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[i.BUN,i.BUN_PATH,Gs.join(n,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun"];for(let l of a){let c=l?.trim();if(c&&(gK(c)&&o(c)||c.toLowerCase()==="bun"))return c}return s("bun",e)}function Vs(t){return process.platform==="win32"?Math.round(t*2):t}function wZ(t,e){let r=i=>i.replace(/'/g,"''");return`Start-Process -FilePath '${r(t)}' -ArgumentList @('"${r(e)}"','--daemon') -WindowStyle Hidden`}function SK(t,e,r={}){Vb().assertCanSpawn("worker daemon");let i=Ko({...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r}),n=vK();if(!n){x.error("SYSTEM","Bun runtime not found \u2014 install from https://bun.sh and ensure it is on PATH or set BUN env var. The worker daemon requires Bun because it uses bun:sqlite.");return}if(process.platform==="win32"){let u=wZ(n,t),d=Buffer.from(u,"utf16le").toString("base64");try{return bK(`powershell -NoProfile -EncodedCommand ${d}`,{stdio:"ignore",windowsHide:!0,env:i}),0}catch(f){let p=f instanceof Error?f:new Error(String(f));x.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:n},p);return}}let o="/usr/bin/setsid",s=Wb(o),c=Di(s?o:n,s?[n,t,"--daemon"]:[t,"--daemon"],{detached:!0,stdio:"ignore",env:i});if(c.pid!==void 0)return c.unref(),c.pid}function EK(){try{if(!Wb(yK))return;let t=new Date;vZ(yK,t,t)}catch{}}function Fd(){return $d({logAlive:!1})}var bve,yK,Bb,qd=S(()=>{"use strict";ji();Me();Nd();zb();Jd();hK();it();qs();bve=bt.dataDir(),yK=bt.workerPid()});import kZ from"net";function Zb(){return ze.loadFromFile(gt).CLAUDE_MEM_WORKER_HOST}function wK(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}async function xZ(t,e,r="GET"){let i=await fetch(`http://${wK(Zb())}:${t}${e}`,{method:r}),n="";try{n=await i.text()}catch{}return{ok:i.ok,statusCode:i.status,body:n}}async function kK(t){if(process.platform==="win32")try{let e=await fetch(`http://${wK(Zb())}:${t}/api/health`);if(e.ok)return!0;x.debug("SYSTEM","Windows health check returned non-ok; falling through to socket probe",{port:t,status:e.status})}catch(e){e instanceof Error?x.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:t,message:e.message}):x.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:t,error:String(e)})}return new Promise(e=>{let r=kZ.createServer(),i=Zb();r.once("error",n=>{n.code==="EADDRINUSE"?e(!0):e(!1)}),r.once("listening",()=>{r.close(()=>e(!1))}),r.listen(t,i)})}async function xK(t,e,r,i){let n=Date.now();for(;Date.now()-n<r;){try{if((await xZ(t,e)).ok)return!0}catch(o){o instanceof Error?x.debug("SYSTEM",i,{},o):x.debug("SYSTEM",i,{error:String(o)})}await new Promise(o=>setTimeout(o,500))}return!1}function Wl(t,e=3e4){return xK(t,"/api/health",e,"Service not ready yet, will retry")}function Zl(t,e=3e4){return xK(t,"/api/readiness",e,"Worker not ready yet, will retry")}var Hb=S(()=>{"use strict";Me();Hr();it()});import{dirname as IZ,join as _Z}from"path";import{mkdirSync as TZ,readFileSync as CZ,statSync as IK,unlinkSync as _K,writeFileSync as OZ}from"fs";function TK(){return _Z(Rn(),"spawn.lock")}function Yb(){let t=TK(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return TZ(IZ(t),{recursive:!0}),OZ(t,e,{flag:"wx"}),!0}catch(i){let n=i instanceof Error?i:new Error(String(i)),o=n.code;if(o!=="EEXIST")return x.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=IK(t).mtimeMs}catch{continue}if(Date.now()-s<=AZ)return!1;let a;try{a=IK(t).mtimeMs}catch{continue}if(a!==s)return!1;try{_K(t)}catch{return!1}}return!1}function Xb(){let t=TK();try{if(JSON.parse(CZ(t,"utf-8")).pid!==process.pid)return;_K(t)}catch{}}var AZ,Qb=S(()=>{"use strict";it();Me();AZ=9e4});import CK from"path";import{existsSync as ev,mkdirSync as KZ,writeFileSync as RZ,unlinkSync as DZ,statSync as jZ}from"fs";function tv(){return CK.join(ze.get("CLAUDE_MEM_DATA_DIR"),".worker-start-attempted")}function MZ(){if(process.platform!=="win32")return!1;let t=tv();if(!ev(t))return!1;try{let e=jZ(t).mtimeMs;return Date.now()-e<PZ}catch(e){return e instanceof Error?x.debug("SYSTEM","Could not stat worker spawn lock file",{},e):x.debug("SYSTEM","Could not stat worker spawn lock file",{error:String(e)}),!1}}function NZ(){if(process.platform==="win32")try{let t=tv();KZ(CK.dirname(t),{recursive:!0}),RZ(t,"","utf-8")}catch{}}function zd(){if(process.platform==="win32")try{let t=tv();ev(t)&&DZ(t)}catch{}}async function OK(t,e){if(!e)return x.error("SYSTEM","ensureWorkerStarted called with empty workerScriptPath \u2014 caller bug"),"dead";if(!ev(e))return x.error("SYSTEM","ensureWorkerStarted: worker script not found at expected path \u2014 likely a partial install or build artifact missing",{workerScriptPath:e}),"dead";if(Fd()==="alive"){if(x.info("SYSTEM","Worker PID file points to a live process, skipping duplicate spawn"),await Zl(t,Vs(ir.READINESS_WAIT)))return zd(),x.info("SYSTEM","Worker became ready while waiting on live PID"),"ready";let a=await Wl(t,1e3),l=Fd()==="alive";return!a&&!l?(x.error("SYSTEM","Live PID disappeared before readiness endpoint became available"),"dead"):(x.warn("SYSTEM","Live PID detected but worker did not become ready before timeout"),"warming")}if(await Wl(t,1e3)){zd();let s=await Zl(t,Vs(ir.READINESS_WAIT));return s||x.warn("SYSTEM","Worker is alive but readiness timed out \u2014 proceeding anyway"),x.info("SYSTEM","Worker already running and healthy"),s?"ready":"warming"}if(await kK(t)){if(x.info("SYSTEM","Port in use, waiting for worker to become healthy"),await Wl(t,Vs(ir.PORT_IN_USE_WAIT))){zd();let a=await Zl(t,Vs(ir.READINESS_WAIT));return x.info("SYSTEM","Worker is now healthy"),a?"ready":"warming"}return x.error("SYSTEM","Port in use but worker not responding to health checks"),"dead"}if(MZ())return x.warn("SYSTEM","Worker unavailable on Windows \u2014 skipping spawn (recent attempt failed within cooldown)"),"dead";let n=Yb(),o;try{if(n){if(x.info("SYSTEM","Starting worker daemon",{workerScriptPath:e}),NZ(),o=SK(e,t),o===void 0)return x.error("SYSTEM","Failed to spawn worker daemon"),"dead"}else x.info("SYSTEM","Another launcher holds the spawn lock \u2014 skipping duplicate spawn and waiting for its worker");if(!await Zl(t,Vs(ir.READINESS_WAIT))){let a=await Wl(t,1e3),l=Fd()==="alive",c=o!==void 0&&o>0&&Yr(o);return!a&&!l&&!c?(x.error("SYSTEM",n?"Worker exited before readiness endpoint became available":"Spawn-lock holder never produced a live worker before readiness timed out"),"dead"):(x.warn("SYSTEM",n?"Worker spawned but readiness endpoint not responding within window":"Spawn-lock holder's worker not ready within window"),"warming")}return zd(),EK(),x.info("SYSTEM",n?"Worker started successfully":"Worker is up (started by another launcher)"),"ready"}finally{n&&Xb()}}var PZ,AK=S(()=>{"use strict";Me();Gl();Hr();qd();Hb();Qb();qs();PZ=120*1e3});var KK=S(()=>{"use strict";Hr();it()});var RK=S(()=>{"use strict";Me();Jd()});var DK=S(()=>{"use strict";qd();Hb();RK()});import LZ from"path";import{readFileSync as nSe,existsSync as iSe,writeFileSync as oSe,renameSync as sSe,mkdirSync as aSe,readdirSync as lSe,statSync as cSe}from"fs";function PK(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;x.warn("SYSTEM",`Invalid ${t}, using default`,{value:i,min:r.min,max:r.max})}return e}async function $Z(t,e={},r){try{return await fetch(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 JZ(){return LZ.join(ze.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function rv(){return Bd!==null||(Bd=ze.loadFromFile(JZ())),Bd}function jK(t,e){if(!t)return null;let r=parseInt(t,10);return Number.isFinite(r)&&r>=e.min&&r<=e.max?r:null}function FZ(t,e,r){let i=process.env[t];if(i!==void 0){let s=jK(i,r);return s!==null?s:(x.warn("SYSTEM",`Invalid ${t}, using default`,{value:i,min:r.min,max:r.max}),e)}let n=rv()[t],o=jK(n,r);return o!==null?o:(x.warn("SYSTEM",`Invalid ${t} in settings.json, using default`,{value:n,min:r.min,max:r.max}),e)}function Hl(){if(Gd!==null)return Gd;let t=rv();return Gd=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),Gd}function Yl(){return Vd!==null||(Vd=rv().CLAUDE_MEM_WORKER_HOST),Vd}function qZ(){return Wd!==null||(Wd=FZ("CLAUDE_MEM_API_TIMEOUT_MS",Fs(ir.API_REQUEST),UZ)),Wd}function nv(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}function zZ(t){return`http://${nv(Yl())}:${Hl()}${t}`}function Zd(t,e={}){let r=e.method??"GET",i=e.timeoutMs??qZ(),n=zZ(t),o={method:r};return e.headers&&(o.headers=e.headers),e.body&&(o.body=e.body),i>0?$Z(n,o,i):fetch(n,o)}var wSe,kSe,UZ,Gd,Vd,Bd,Wd,Xl=S(()=>{"use strict";ji();Me();Gl();Hr();it();KK();Jd();gd();Pd();DK();qd();Qb();wSe=PK("CLAUDE_MEM_HEALTH_TIMEOUT_MS",Fs(ir.HEALTH_CHECK),{min:500,max:3e5}),kSe=PK("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",Fs(ir.HOOK_READINESS_WAIT),{min:0,max:3e5}),UZ={min:500,max:3e5};Gd=null,Vd=null,Bd=null,Wd=null});function Bs(t){return t instanceof Error?t.message:typeof t=="string"?t:t&&typeof t=="object"&&"message"in t?String(t.message):String(t??"")}function MK(t,e){for(let r of iv)if(r.match(t,e))return r;return iv[iv.length-1]}var GZ,VZ,iv,Hd=S(()=>{"use strict";GZ=t=>t.platform==="win32"?'Install Bun manually then re-run `npx claude-mem install`. Windows: `winget install Oven-sh.Bun` (or `powershell -c "irm bun.sh/install.ps1 | iex"`).':"Install Bun manually then re-run `npx claude-mem install`. macOS/Linux: `curl -fsSL https://bun.sh/install | bash` (or `brew install oven-sh/bun/bun`).",VZ=t=>t.platform==="win32"?'Install uv manually then re-run `npx claude-mem install`. Windows: `winget install astral-sh.uv` (or `powershell -c "irm https://astral.sh/uv/install.ps1 | iex"`).':"Install uv manually then re-run `npx claude-mem install`. macOS/Linux: `curl -LsSf https://astral.sh/uv/install.sh | sh` (or `brew install uv`).",iv=[{id:"bun-missing-after-install",severity:"ABORT",match:t=>{let e=Bs(t);return e.includes("Bun executable not found")||e.includes("Bun installation completed but binary not found")||e.includes("Failed to install Bun")},remediation:GZ},{id:"uv-missing-after-install",severity:"ABORT",match:t=>{let e=Bs(t);return e.includes("uv executable not found")||e.includes("uv installed but version probe failed")||e.includes("uv binary not found")||e.includes("Failed to install uv")},remediation:VZ},{id:"tree-sitter-eresolve",severity:"ABORT",match:t=>/\bERESOLVE\b/.test(Bs(t)),remediation:()=>"ERESOLVE peer-dependency conflict in marketplace deps that --legacy-peer-deps could not resolve. Open an issue at https://github.com/thedotmack/claude-mem/issues with the conflicting peer ranges shown above."},{id:"marketplace-dir-not-writable",severity:"ABORT",match:t=>/\b(EACCES|EPERM)\b/.test(Bs(t)),remediation:t=>`Cannot write to the claude-mem data/marketplace directory under ${t.dataDir}. Check filesystem permissions or set CLAUDE_MEM_DATA_DIR to a writable path, then re-run.`},{id:"plugin-json-corrupt",severity:"ABORT",match:(t,e)=>e.component==="plugin-json"&&/Unexpected token|JSON|parse/i.test(Bs(t)),remediation:()=>"Existing plugin.json is corrupt. Run `rm -rf ~/.claude/plugins/marketplaces/thedotmack` and re-run `npx claude-mem install`."},{id:"all-ides-failed",severity:"ABORT",match:(t,e)=>e.component==="all-ides",remediation:()=>"Every selected IDE integration failed. See the per-IDE errors above. Re-run with `--ide=<single>` to isolate the failure."},{id:"single-ide-failed",severity:"FAIL_LOUD_PER_IDE",match:(t,e)=>e.phase==="ide-install",remediation:()=>"Re-run `npx claude-mem install --ide=<name>` to retry just this IDE. The captured stderr is shown above."},{id:"path-update-failed",severity:"WARN_CONTINUE",match:(t,e)=>e.component==="path-update",remediation:()=>"Could not auto-update PATH in your shell config. Add the printed export line manually and restart your shell."},{id:"auto-memory-toggle-failed",severity:"WARN_CONTINUE",match:(t,e)=>e.component==="auto-memory",remediation:()=>'Could not disable Claude Code auto-memory. Add `"CLAUDE_CODE_DISABLE_AUTO_MEMORY": "1"` to the env block in ~/.claude/settings.json.'},{id:"version-probe-transient",severity:"WARN_CONTINUE",match:(t,e)=>e.component.endsWith("-version-probe"),remediation:()=>"Could not verify the tool version after install \u2014 the installation is likely OK. Re-run `npx claude-mem install` if features misbehave."},{id:"child-process-timeout",severity:"ABORT",match:t=>/timed out|ETIMEDOUT|SIGTERM|did not finish/i.test(Bs(t)),remediation:()=>"An install command did not finish in time. Check network connectivity. On a slow host, raise the budget with CLAUDE_MEM_INSTALL_TIMEOUT_MS and re-run."},{id:"unknown-install-error",severity:"ABORT",match:()=>!0,remediation:t=>`An unexpected installer error occurred. Capture ${t.dataDir}/last-install-error.json and open an issue at https://github.com/thedotmack/claude-mem/issues.`}]});import{mkdirSync as BZ,writeFileSync as WZ}from"fs";import{join as ZZ}from"path";function ov(){return{warnings:[],failedIDEs:[]}}function Ql(t){return t instanceof Error?t.message:typeof t=="string"?t:String(t??"")}function HZ(t,e,r,i){let n={severity:t.severity,categoryId:t.id,component:e.component,phase:e.phase,cause:Ql(e.cause),remediation:r,details:e.details??null,timestamp:new Date().toISOString()};try{BZ(i,{recursive:!0}),WZ(ZZ(i,"last-install-error.json"),JSON.stringify(n,null,2))}catch{}}function Gt(t,e,r){let i=Rn(),n=MK(e.cause,{component:e.component,phase:e.phase}),o=e.remediation??n.remediation({platform:process.platform,dataDir:i});switch(t){case"ABORT":throw HZ(n,e,o,i),new Ws(`${e.component} failed during ${e.phase}: ${Ql(e.cause)}`,{category:n,remediation:o,cause:e.cause});case"FAIL_LOUD_PER_IDE":{let s=e.ide??e.component;r.failedIDEs.includes(s)||r.failedIDEs.push(s),r.warnings.push({component:s,message:e.details?`${Ql(e.cause)}
@@ -3,7 +3,7 @@
3
3
  "name": "Claude-Mem (Persistent Memory)",
4
4
  "description": "OpenClaw plugin for Claude-Mem. Records observations from embedded runner sessions and streams them to messaging channels.",
5
5
  "kind": "memory",
6
- "version": "13.15.2",
6
+ "version": "13.15.3",
7
7
  "license": "Apache-2.0",
8
8
  "author": "thedotmack",
9
9
  "homepage": "https://claude-mem.ai",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "13.15.2",
3
+ "version": "13.15.3",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "keywords": [
6
6
  "claude",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "13.15.2",
3
+ "version": "13.15.3",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "author": {
6
6
  "name": "Alex Newman"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "13.15.2",
3
+ "version": "13.15.3",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "author": {
6
6
  "name": "Alex Newman",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem-plugin",
3
- "version": "13.15.2",
3
+ "version": "13.15.3",
4
4
  "private": true,
5
5
  "description": "Runtime dependencies for claude-mem bundled hooks",
6
6
  "type": "module",
@@ -222,7 +222,7 @@ ${f}`}let a=s.lineStart;for(let u=s.lineStart-1;u>=0;u--){let l=i[u].trim();if(l
222
222
  ${c}`}ce();var VP=new Set([".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".pyw",".go",".rs",".rb",".java",".cs",".cpp",".cc",".cxx",".c",".h",".hpp",".hh",".swift",".kt",".kts",".php",".vue",".svelte",".lua",".scala",".sc",".sh",".bash",".zsh",".hs",".zig",".css",".scss",".toml",".yml",".yaml",".sql",".md",".mdx"]),KP=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),GP=512*1024;async function*H_(t,e,r=20){if(r<=0)return;let n;try{n=await(0,qr.readdir)(t,{withFileTypes:!0})}catch(o){y.debug("WORKER",`walkDir: failed to read directory ${t}`,void 0,o instanceof Error?o:void 0);return}for(let o of n){if(o.name.startsWith(".")&&o.name!=="."||KP.has(o.name))continue;let s=(0,eo.join)(t,o.name);if(o.isDirectory())yield*H_(s,e,r-1);else if(o.isFile()){let i=o.name.slice(o.name.lastIndexOf("."));VP.has(i)&&(yield s)}}}async function JP(t){try{let e=await(0,qr.stat)(t);if(e.size>GP||e.size===0)return null;let r=await(0,qr.readFile)(t,"utf-8");return r.slice(0,1e3).includes("\0")?null:r}catch(e){return y.debug("WORKER",`safeReadFile: failed to read ${t}`,void 0,e instanceof Error?e:void 0),null}}async function W_(t,e,r={}){let n=r.maxResults||20,o=e.toLowerCase(),s=o.split(/[\s_\-./]+/).filter(g=>g.length>0),i=[];for await(let g of H_(t,t,20)){if(r.filePattern&&!(0,eo.relative)(t,g).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let S=await JP(g);S&&i.push({absolutePath:g,relativePath:(0,eo.relative)(t,g),content:S})}let a=q_(i),c=[],u=[],l=0;for(let[g,S]of a){l+=YP(S);let x=Ys(g.toLowerCase(),s)>0,b=[],$=(k,Se)=>{for(let K of k){let ct=0,Ne="",Pt=Ys(K.name.toLowerCase(),s);Pt>0&&(ct+=Pt*3,Ne="name match"),K.signature.toLowerCase().includes(o)&&(ct+=2,Ne=Ne?`${Ne} + signature`:"signature match"),K.jsdoc&&K.jsdoc.toLowerCase().includes(o)&&(ct+=1,Ne=Ne?`${Ne} + jsdoc`:"jsdoc match"),ct>0&&(x=!0,b.push({filePath:g,symbolName:Se?`${Se}.${K.name}`:K.name,kind:K.kind,signature:K.signature,jsdoc:K.jsdoc,lineStart:K.lineStart,lineEnd:K.lineEnd,matchReason:Ne})),K.children&&$(K.children,K.name)}};$(S.symbols),x&&(c.push(S),u.push(...b))}u.sort((g,S)=>{let v=Ys(g.symbolName.toLowerCase(),s);return Ys(S.symbolName.toLowerCase(),s)-v});let d=u.slice(0,n),p=new Set(d.map(g=>g.filePath)),f=c.filter(g=>p.has(g.filePath)).slice(0,n),m=f.reduce((g,S)=>g+S.foldedTokenEstimate,0);return{foldedFiles:f,matchingSymbols:d,totalFilesScanned:i.length,totalSymbolsFound:l,tokenEstimate:m}}function Ys(t,e){let r=0;for(let n of e)if(t===n)r+=10;else if(t.includes(n))r+=5;else{let o=0,s=0;for(let i of n){let a=t.indexOf(i,o);a!==-1&&(s++,o=a+1)}s===n.length&&(r+=1)}return r}function YP(t){let e=t.symbols.length;for(let r of t.symbols)r.children&&(e+=r.children.length);return e}function V_(t,e){let r=[];if(r.push(`\u{1F50D} Smart Search: "${e}"`),r.push(` Scanned ${t.totalFilesScanned} files, found ${t.totalSymbolsFound} symbols`),r.push(` ${t.matchingSymbols.length} matches across ${t.foldedFiles.length} files (~${t.tokenEstimate} tokens for folded view)`),r.push(""),t.matchingSymbols.length===0)return r.push(" No matching symbols found."),r.join(`
223
223
  `);r.push("\u2500\u2500 Matching Symbols \u2500\u2500"),r.push("");for(let n of t.matchingSymbols){if(r.push(` ${n.kind} ${n.symbolName} (${n.filePath}:${n.lineStart+1})`),r.push(` ${n.signature}`),n.jsdoc){let o=n.jsdoc.split(`
224
224
  `).find(s=>s.replace(/^[\s*/]+/,"").trim().length>0);o&&r.push(` \u{1F4AC} ${o.replace(/^[\s*/]+/,"").trim()}`)}r.push("")}r.push("\u2500\u2500 Folded File Views \u2500\u2500"),r.push("");for(let n of t.foldedFiles)r.push(Ur(n)),r.push("");return r.push("\u2500\u2500 Actions \u2500\u2500"),r.push(" To see full implementation: use smart_unfold with file path and symbol name"),r.join(`
225
- `)}var ju=require("node:fs/promises"),ei=require("node:fs"),at=require("node:path"),Q_=require("node:os"),ey=require("node:url");var K_="claude";function BP(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Bs(t){if(!t)return K_;let e=BP(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:K_}var XP=Ht(ye.API_REQUEST),Be=class extends Error{kind;status;cause;constructor(e,r,n={}){super(r),this.name="ServerClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},Xs=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=QP(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??XP}async startSession(e){let r=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",r)}async recordEvent(e){let r=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(e){if(!e.sessionId)throw new Be("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async getJobStatus(e){if(!e)throw new Be("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,type:n,narrative:r,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Nu(e.platformSource)}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:Nu(e.platformSource)}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:Nu(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,r,n){if(!this.apiKey||!this.apiKey.trim())throw new Be("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let o=`${this.baseUrl}${r}`,s={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(s.body=JSON.stringify(n));let i;try{i=await Pu(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new Be(l?"timeout":"transport",`Server ${e} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new Be("http_error",`Server ${e} ${r} returned ${i.status}: ${eT(c,200)}`,{status:i.status})}let a=await i.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(c){let u=c instanceof Error?c:new Error(String(c));throw new Be("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:u})}}};function G_(t){return t instanceof Be}function QP(t){return t.replace(/\/+$/,"")}function Nu(t){return typeof t=="string"?Bs(t):null}function eT(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}ce();function Qs(){let e=(Ds().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function J_(){let t=Ds(),e=(...i)=>{for(let a of i){let c=(a??"").trim();if(c.length>0)return c}return""},r=e(t.CLAUDE_MEM_SERVER_URL,t.CLAUDE_MEM_SERVER_BETA_URL),n=e(t.CLAUDE_MEM_SERVER_API_KEY,t.CLAUDE_MEM_SERVER_BETA_API_KEY),o=e(t.CLAUDE_MEM_SERVER_PROJECT_ID,t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!r)return y.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return y.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return y.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let s={serverBaseUrl:r,apiKey:n};return{runtime:"server",client:new Xs(s),projectId:o,serverBaseUrl:r}}ce();var Y_=["observation_add","observation_record_event","observation_search","observation_context","observation_generation_status","memory_add","memory_search","memory_context"],tT=new Set(Y_);function B_(t,e){return e==="server"?[...t]:(y.debug("SYSTEM","Filtering server-beta-only MCP tools from worker runtime advertisement",{runtime:e,hiddenToolCount:Y_.length}),t.filter(r=>!tT.has(r.name)))}var bT={},rT="13.15.2";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var ty=!1,ry=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,at.dirname)((0,ey.fileURLToPath)(bT.url))}catch(t){return ty=!0,y.warn("SYSTEM","mcp-server: failed to resolve module directory from import.meta.url, falling back to process.cwd()",void 0,t instanceof Error?t:new Error(String(t))),process.cwd()}})(),Lu=z_()??(0,at.resolve)(ry,"worker-service.cjs");function nT(){ty&&((0,ei.existsSync)(Lu)||y.error("SYSTEM","mcp-server: dirname resolution failed (both __dirname and import.meta.url are unavailable). Fell back to process.cwd() and the resolved WORKER_SCRIPT_PATH does not exist. This is the actual problem \u2014 the worker bundle is fine, but mcp-server cannot locate it. Worker auto-start will fail until the dirname-resolution path is fixed.",{workerScriptPath:Lu,mcpServerDir:ry}))}async function _t(t,e={}){y.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t});try{let r;if(e.body)r=await Ks(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e.body)});else{let n=new URLSearchParams;for(let[o,s]of Object.entries(e.query??{}))s!=null&&n.append(o,String(s));r=await Ks(`${t}?${n}`)}if(!r.ok){let n=await r.text();throw new Error(`Worker API error (${r.status}): ${n}`)}return y.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),e.text?{content:[{type:"text",text:await r.text()}]}:e.body?{content:[{type:"text",text:JSON.stringify(await r.json(),null,2)}]}:await r.json()}catch(r){return y.error("SYSTEM","\u2190 Worker API error",{endpoint:t},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function oT(){try{return(await Ks("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}function ny(){if(Qs()!=="server")return null;let e=J_();return e?{...e,available:!0}:{runtime:"server",available:!1,reason:"server runtime is selected but configuration is incomplete (missing url, api key, or project id)"}}function sT(t){return G_(t)?{content:[{type:"text",text:`Server error (${t.kind}${t.status?` ${t.status}`:""}): ${t.message}`}],isError:!0}:{content:[{type:"text",text:`Tool error: ${t instanceof Error?t.message:String(t)}`}],isError:!0}}function Zr(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function ro(t){let e=ny();if(!e)throw new Be("transport",`${t} requires CLAUDE_MEM_RUNTIME=server. Current runtime is "worker"; use the existing search/timeline/get_observations tools for worker-mode memory access.`);if(!e.available)throw new Be("missing_api_key",`${t}: ${e.reason}`);return e}function no(t,e){return async r=>{try{return await e(r)}catch(n){let o=n instanceof Error?n:new Error(String(n));return y.warn("SYSTEM",`${t} failed`,void 0,o),sT(n)}}}var iT=no("observation_add",async t=>{let e=ro("observation_add");if(typeof t?.content!="string"||t.content.trim().length===0)throw new Error('observation_add: "content" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,content:t.content,...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.kind!==void 0?{kind:t.kind}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}},o=await e.client.addObservation(n);return Zr(o)});function ri(t){return typeof t=="string"?Bs(t):null}var aT=no("observation_record_event",async t=>{let e=ro("observation_record_event");if(typeof t?.eventType!="string"||t.eventType.trim().length===0)throw new Error('observation_record_event: "eventType" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,sourceType:t.sourceType??"api",eventType:t.eventType,occurredAtEpoch:typeof t.occurredAtEpoch=="number"?t.occurredAtEpoch:Date.now(),...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.memorySessionId!==void 0?{memorySessionId:t.memorySessionId}:{},...t.platformSource!==void 0?{platformSource:ri(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{},...t.generate!==void 0?{generate:t.generate}:{}},o=await e.client.recordEvent(n);return Zr(o)}),cT=no("observation_search",async t=>{let e=ro("observation_search");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_search: "query" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:ri(t.platformSource)}:{}},o=await e.client.searchObservations(n);return Zr(o)}),uT=no("observation_context",async t=>{let e=ro("observation_context");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_context: "query" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:ri(t.platformSource)}:{}},o=await e.client.contextObservations(n);return Zr(o)});function lT(t){return Array.isArray(t.projects)?t.projects.map(e=>typeof e=="string"?e.trim():"").filter(Boolean):typeof t.projects=="string"?t.projects.split(",").map(e=>e.trim()).filter(Boolean):typeof t.project=="string"&&t.project.trim().length>0?[t.project.trim()]:[]}async function dT(t){let e=lT(t);return e.length===0?{content:[{type:"text",text:'session_start_context: "project" or "projects" is required'}],isError:!0}:_t("/api/context/inject",{query:{projects:e.join(","),...t.platformSource!==void 0?{platformSource:ri(t.platformSource)}:{},...t.full!==void 0?{full:t.full}:{},...t.colors!==void 0?{colors:t.colors}:{}},text:!0})}var pT=no("observation_generation_status",async t=>{let e=ro("observation_generation_status"),r=(t?.jobId??t?.job_id??"").trim();if(!r)throw new Error('observation_generation_status: "jobId" is required');let n=await e.client.getJobStatus(r);return Zr(n)});async function fT(){if(await oT())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),nT();try{let t=Ru(),e=await I_(t,Lu);return e==="dead"&&y.error("SYSTEM","Worker auto-start failed \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running. Check earlier log lines for the specific failure reason (Bun not found, missing worker bundle, port conflict, etc.)."),e!=="dead"}catch(t){return y.error("SYSTEM","Worker auto-start threw \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running.",void 0,t instanceof Error?t:new Error(String(t))),!1}}var oy=[{name:"important_workflow",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
225
+ `)}var ju=require("node:fs/promises"),ei=require("node:fs"),at=require("node:path"),Q_=require("node:os"),ey=require("node:url");var K_="claude";function BP(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Bs(t){if(!t)return K_;let e=BP(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:K_}var XP=Ht(ye.API_REQUEST),Be=class extends Error{kind;status;cause;constructor(e,r,n={}){super(r),this.name="ServerClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},Xs=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=QP(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??XP}async startSession(e){let r=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",r)}async recordEvent(e){let r=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(e){if(!e.sessionId)throw new Be("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async getJobStatus(e){if(!e)throw new Be("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,type:n,narrative:r,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Nu(e.platformSource)}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:Nu(e.platformSource)}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:Nu(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,r,n){if(!this.apiKey||!this.apiKey.trim())throw new Be("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let o=`${this.baseUrl}${r}`,s={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(s.body=JSON.stringify(n));let i;try{i=await Pu(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new Be(l?"timeout":"transport",`Server ${e} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new Be("http_error",`Server ${e} ${r} returned ${i.status}: ${eT(c,200)}`,{status:i.status})}let a=await i.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(c){let u=c instanceof Error?c:new Error(String(c));throw new Be("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:u})}}};function G_(t){return t instanceof Be}function QP(t){return t.replace(/\/+$/,"")}function Nu(t){return typeof t=="string"?Bs(t):null}function eT(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}ce();function Qs(){let e=(Ds().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function J_(){let t=Ds(),e=(...i)=>{for(let a of i){let c=(a??"").trim();if(c.length>0)return c}return""},r=e(t.CLAUDE_MEM_SERVER_URL,t.CLAUDE_MEM_SERVER_BETA_URL),n=e(t.CLAUDE_MEM_SERVER_API_KEY,t.CLAUDE_MEM_SERVER_BETA_API_KEY),o=e(t.CLAUDE_MEM_SERVER_PROJECT_ID,t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!r)return y.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return y.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return y.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let s={serverBaseUrl:r,apiKey:n};return{runtime:"server",client:new Xs(s),projectId:o,serverBaseUrl:r}}ce();var Y_=["observation_add","observation_record_event","observation_search","observation_context","observation_generation_status","memory_add","memory_search","memory_context"],tT=new Set(Y_);function B_(t,e){return e==="server"?[...t]:(y.debug("SYSTEM","Filtering server-beta-only MCP tools from worker runtime advertisement",{runtime:e,hiddenToolCount:Y_.length}),t.filter(r=>!tT.has(r.name)))}var bT={},rT="13.15.3";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var ty=!1,ry=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,at.dirname)((0,ey.fileURLToPath)(bT.url))}catch(t){return ty=!0,y.warn("SYSTEM","mcp-server: failed to resolve module directory from import.meta.url, falling back to process.cwd()",void 0,t instanceof Error?t:new Error(String(t))),process.cwd()}})(),Lu=z_()??(0,at.resolve)(ry,"worker-service.cjs");function nT(){ty&&((0,ei.existsSync)(Lu)||y.error("SYSTEM","mcp-server: dirname resolution failed (both __dirname and import.meta.url are unavailable). Fell back to process.cwd() and the resolved WORKER_SCRIPT_PATH does not exist. This is the actual problem \u2014 the worker bundle is fine, but mcp-server cannot locate it. Worker auto-start will fail until the dirname-resolution path is fixed.",{workerScriptPath:Lu,mcpServerDir:ry}))}async function _t(t,e={}){y.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t});try{let r;if(e.body)r=await Ks(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e.body)});else{let n=new URLSearchParams;for(let[o,s]of Object.entries(e.query??{}))s!=null&&n.append(o,String(s));r=await Ks(`${t}?${n}`)}if(!r.ok){let n=await r.text();throw new Error(`Worker API error (${r.status}): ${n}`)}return y.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),e.text?{content:[{type:"text",text:await r.text()}]}:e.body?{content:[{type:"text",text:JSON.stringify(await r.json(),null,2)}]}:await r.json()}catch(r){return y.error("SYSTEM","\u2190 Worker API error",{endpoint:t},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function oT(){try{return(await Ks("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}function ny(){if(Qs()!=="server")return null;let e=J_();return e?{...e,available:!0}:{runtime:"server",available:!1,reason:"server runtime is selected but configuration is incomplete (missing url, api key, or project id)"}}function sT(t){return G_(t)?{content:[{type:"text",text:`Server error (${t.kind}${t.status?` ${t.status}`:""}): ${t.message}`}],isError:!0}:{content:[{type:"text",text:`Tool error: ${t instanceof Error?t.message:String(t)}`}],isError:!0}}function Zr(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function ro(t){let e=ny();if(!e)throw new Be("transport",`${t} requires CLAUDE_MEM_RUNTIME=server. Current runtime is "worker"; use the existing search/timeline/get_observations tools for worker-mode memory access.`);if(!e.available)throw new Be("missing_api_key",`${t}: ${e.reason}`);return e}function no(t,e){return async r=>{try{return await e(r)}catch(n){let o=n instanceof Error?n:new Error(String(n));return y.warn("SYSTEM",`${t} failed`,void 0,o),sT(n)}}}var iT=no("observation_add",async t=>{let e=ro("observation_add");if(typeof t?.content!="string"||t.content.trim().length===0)throw new Error('observation_add: "content" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,content:t.content,...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.kind!==void 0?{kind:t.kind}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}},o=await e.client.addObservation(n);return Zr(o)});function ri(t){return typeof t=="string"?Bs(t):null}var aT=no("observation_record_event",async t=>{let e=ro("observation_record_event");if(typeof t?.eventType!="string"||t.eventType.trim().length===0)throw new Error('observation_record_event: "eventType" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,sourceType:t.sourceType??"api",eventType:t.eventType,occurredAtEpoch:typeof t.occurredAtEpoch=="number"?t.occurredAtEpoch:Date.now(),...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.memorySessionId!==void 0?{memorySessionId:t.memorySessionId}:{},...t.platformSource!==void 0?{platformSource:ri(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{},...t.generate!==void 0?{generate:t.generate}:{}},o=await e.client.recordEvent(n);return Zr(o)}),cT=no("observation_search",async t=>{let e=ro("observation_search");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_search: "query" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:ri(t.platformSource)}:{}},o=await e.client.searchObservations(n);return Zr(o)}),uT=no("observation_context",async t=>{let e=ro("observation_context");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_context: "query" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:ri(t.platformSource)}:{}},o=await e.client.contextObservations(n);return Zr(o)});function lT(t){return Array.isArray(t.projects)?t.projects.map(e=>typeof e=="string"?e.trim():"").filter(Boolean):typeof t.projects=="string"?t.projects.split(",").map(e=>e.trim()).filter(Boolean):typeof t.project=="string"&&t.project.trim().length>0?[t.project.trim()]:[]}async function dT(t){let e=lT(t);return e.length===0?{content:[{type:"text",text:'session_start_context: "project" or "projects" is required'}],isError:!0}:_t("/api/context/inject",{query:{projects:e.join(","),...t.platformSource!==void 0?{platformSource:ri(t.platformSource)}:{},...t.full!==void 0?{full:t.full}:{},...t.colors!==void 0?{colors:t.colors}:{}},text:!0})}var pT=no("observation_generation_status",async t=>{let e=ro("observation_generation_status"),r=(t?.jobId??t?.job_id??"").trim();if(!r)throw new Error('observation_generation_status: "jobId" is required');let n=await e.client.getJobStatus(r);return Zr(n)});async function fT(){if(await oT())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),nT();try{let t=Ru(),e=await I_(t,Lu);return e==="dead"&&y.error("SYSTEM","Worker auto-start failed \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running. Check earlier log lines for the specific failure reason (Bun not found, missing worker bundle, port conflict, etc.)."),e!=="dead"}catch(t){return y.error("SYSTEM","Worker auto-start threw \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running.",void 0,t instanceof Error?t:new Error(String(t))),!1}}var oy=[{name:"important_workflow",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
226
226
  1. search(query) \u2192 Get index with IDs (~50-100 tokens/result)
227
227
  2. timeline(anchor=ID) \u2192 Get context around interesting results
228
228
  3. get_observations([IDs]) \u2192 Fetch full details ONLY for filtered IDs