claude-mem 13.12.3 → 13.12.4

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.12.3",
3
+ "version": "13.12.4",
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 Os(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){Tb=e}error(e,r,i,n){this.log(3,e,r,i,n),this.routeErrorToSink(r,i,n)}routeErrorToSink(e,r,i){try{if(!Tb||!(i instanceof Error))return;Tb(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)}},I=new Ob});import{join as hA}from"path";import{mkdirSync as HW,writeFileSync as YW}from"fs";import{randomUUID as XW}from"crypto";function QW(t){let e=t.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function Ab(t,e){if(QW(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 gA(t,e){return Ab(t,e).enabled}function Jl(){return hA(Cn(),yA)}function Ci(){let t;try{t=Ft(Jl(),null)}catch(e){let r=e instanceof Error?e:new Error(String(e));return I.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 Ms(t){let e=Cn();HW(e,{recursive:!0}),YW(hA(e,yA),JSON.stringify(t,null,2)+`
101
- `)}function Od(){let t=Ci();if(t?.installId)return t.installId;let e=XW();return Ms({installId:e,decidedAt:""}),e}var yA,Ad=S(()=>{"use strict";nt();wo();Me();yA="telemetry.json"});function t3(t,e){if(!(!t||typeof t!="object"))for(let r of Object.keys(t)){if(!e3.has(r))continue;let i=t[r];typeof i=="string"?e[r]=i.length>bA?i.slice(0,bA):i:(typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean")&&(e[r]=i)}}function vA(t){let e={};try{t3(t,e)}catch{}return e}var e3,bA,SA=S(()=>{"use strict";e3=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","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"]),bA=200});import EA from"os";function wA(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||n3}function xA(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||i3}function IA(t){let e={};for(let r of o3)t[r]!==void 0&&(e[r]=t[r]);return e}function s3(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||EA.release().toLowerCase().includes("microsoft")}catch(t){let e=t instanceof Error?t:new Error(String(t));return I.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function kA(){return{version:r3,os:process.platform,os_version:EA.release(),is_wsl:s3(),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 r3,n3,i3,o3,_A=S(()=>{"use strict";Me();r3="13.12.3",n3="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",i3="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 Ns(t,e,r){try{if(!gA(process.env,Ci()))return;let i=vA({...kA(),...e??{}});if(r?.person?i.$set=IA(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 Od(){let t=Ci();if(t?.installId)return t.installId;let e=XW();return Ms({installId:e,decidedAt:""}),e}var yA,Ad=S(()=>{"use strict";nt();wo();Me();yA="telemetry.json"});function t3(t,e){if(!(!t||typeof t!="object"))for(let r of Object.keys(t)){if(!e3.has(r))continue;let i=t[r];typeof i=="string"?e[r]=i.length>bA?i.slice(0,bA):i:(typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean")&&(e[r]=i)}}function vA(t){let e={};try{t3(t,e)}catch{}return e}var e3,bA,SA=S(()=>{"use strict";e3=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","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"]),bA=200});import EA from"os";function wA(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||n3}function xA(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||i3}function IA(t){let e={};for(let r of o3)t[r]!==void 0&&(e[r]=t[r]);return e}function s3(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||EA.release().toLowerCase().includes("microsoft")}catch(t){let e=t instanceof Error?t:new Error(String(t));return I.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function kA(){return{version:r3,os:process.platform,os_version:EA.release(),is_wsl:s3(),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 r3,n3,i3,o3,_A=S(()=>{"use strict";Me();r3="13.12.4",n3="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",i3="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 Ns(t,e,r){try{if(!gA(process.env,Ci()))return;let i=vA({...kA(),...e??{}});if(r?.person?i.$set=IA(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=wA(),o=new AbortController,s=setTimeout(()=>o.abort(),a3);try{await l3(n,t,i,o.signal)}finally{clearTimeout(s)}}catch{}}async function l3(t,e,r,i){await fetch(`${xA()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:t,event:e,distinct_id:Od(),properties:r}),signal:i})}var a3,Kd=S(()=>{"use strict";Ad();SA();_A();a3=2e3});import{spawn as c3,spawnSync as u3}from"node:child_process";import{extname as Kb}from"node:path";function Oi(t,e,r){return c3(t,e??[],{windowsHide:!0,...r})}function p3(t){return`"${t.replace(/"/g,'""')}"`}function Rd(t){if(process.platform!=="win32")return null;try{let e=u3("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=>CA.has(Kb(i).toLowerCase()))??r.find(i=>d3.has(Kb(i).toLowerCase()))??r[0]??null}catch{return null}}function Ls(t,e,r,i=process.platform){let n={...i==="win32"?{windowsHide:!0}:{},...r};if(i==="win32"&&TA.has(Kb(t).toLowerCase())){let o=[t,...e].map(p3).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 TA,CA,d3,Ai=S(()=>{"use strict";TA=new Set([".cmd",".bat"]),CA=new Set([".exe",".com"]),d3=new Set([...CA,...TA])});function Us(t){return process.platform==="win32"?Math.round(t*nr.WINDOWS_MULTIPLIER):t}var nr,Fl=S(()=>{"use strict";nr={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 KA={};Ce(KA,{SettingsDefaultsManager:()=>Fe});import{readFileSync as f3,existsSync as m3}from"fs";import{join as OA}from"path";import{homedir as AA,hostname as h3}from"os";var Fe,Vr=S(()=>{"use strict";Fl();un();Fe=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(Us(nr.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:OA(AA(),".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:OA(AA(),".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_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:h3(),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",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(!m3(e)){let a=this.getAllDefaults();try{wt(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=f3(e,"utf-8"),n=er(i),o=n;if(n.env&&typeof n.env=="object"){o=n.env;try{wt(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))}}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 y3}from"child_process";import{promisify as g3}from"util";import{existsSync as cge,readFileSync as uge,writeFileSync as dge,mkdirSync as pge,unlinkSync as fge}from"fs";import{userInfo as hge}from"os";import{join as gge}from"path";var Sge,RA=S(()=>{"use strict";nt();Me();Sge=g3(y3)});import{existsSync as Rb,readFileSync as jA,writeFileSync as b3,mkdirSync as v3,chmodSync as DA}from"fs";import{parseEnv as S3}from"util";function PA(){return process.env.CLAUDE_MEM_ENV_FILE??yt.envFile()}function NA(t){return S3(t)}function E3(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 ql(){let t=PA();if(!Rb(t))return{};try{let e=jA(t,"utf-8"),r=NA(e),i={};for(let n of MA)r[n]&&(i[n]=r[n]);return i}catch(e){return I.warn("ENV","Failed to load .env file",{path:t},e instanceof Error?e:new Error(String(e))),{}}}function zl(t){let e=PA(),r={};try{Rb(yt.dataDir())||v3(yt.dataDir(),{recursive:!0,mode:448}),DA(yt.dataDir(),448),r=Rb(e)?NA(jA(e,"utf-8")):{}}catch(n){let o=n instanceof Error?n:new Error(String(n));throw I.error("ENV","Failed to set up env directory or read existing env",{},o),o}let i={...r};for(let n of MA){let o=t[n];o!==void 0&&(o?i[n]=o:delete i[n])}try{b3(e,E3(i),{encoding:"utf-8",mode:384}),DA(e,384)}catch(n){throw I.error("ENV","Failed to save .env file",{path:e},n instanceof Error?n:new Error(String(n))),n}}var MA,LA=S(()=>{"use strict";Me();nt();RA();MA=["ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","GEMINI_API_KEY","OPENROUTER_API_KEY"]});function To(t=process.env){let e={};for(let[r,i]of Object.entries(t))if(i!==void 0){if(k3.has(r)){e[r]=i;continue}x3.has(r)||w3.some(n=>r.startsWith(n))||(e[r]=i)}return e}var w3,x3,I3,k3,Dd=S(()=>{"use strict";w3=["CLAUDECODE_","CLAUDE_CODE_"],x3=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),I3=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"]),k3=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",...I3])});import{spawnSync as FA}from"child_process";import{existsSync as _3,mkdirSync as UA,readFileSync as qA,writeFileSync as T3}from"fs";import $A from"path";function Br(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:(I.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return I.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function jd(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(i=>!Br(i.pid)))return;await new Promise(i=>setTimeout(i,100))}}function R3(t){let e=FA("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...To(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 D3(t){let e=JA.get(t);if(e&&Date.now()-e.capturedAtMs<K3)return e.token;let r=null;try{r=R3(t)}catch(i){I.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:i instanceof Error?i.message:String(i)}),r=null}return JA.set(t,{token:r,capturedAtMs:Date.now()}),r}function zA(t){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux")try{let e=qA(`/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 I.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return D3(t);try{let e=FA("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...To(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 I.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}}function Mb(t){if(!t||!Br(t.pid))return!1;if(!t.startToken)return!0;let e=zA(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||I.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}function Pd(){return Db||(Db=new Pb),Db}function jb(){let t=j3.shift();t&&t()}var C3,O3,A3,K3,JA,Pb,Db,j3,$s=S(()=>{"use strict";Ai();Me();Dd();nt();C3=5e3,O3=1e3,A3=yt.supervisorRegistry();K3=5e3,JA=new Map;Pb=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=A3){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,UA($A.dirname(this.registryPath),{recursive:!0}),!_3(this.registryPath)){this.persist();return}try{let i=JSON.parse(qA(this.registryPath,"utf-8")).processes??{};for(let[n,o]of Object.entries(i))this.entries.set(n,o)}catch(r){r instanceof Error?I.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):I.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&I.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)Br(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;I.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:i,pids:r.map(s=>s.pid)});let n=r.filter(s=>Br(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"&&I.debug("SYSTEM",`Failed to SIGTERM session process PID ${s.pid}`,{pid:s.pid,pgid:s.pgid},a):I.warn("SYSTEM",`Failed to SIGTERM session process PID ${s.pid} (non-Error)`,{pid:s.pid,pgid:s.pgid,error:String(a)})}await jd(n,C3);let o=n.filter(s=>Br(s.pid));for(let s of o){I.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"&&I.debug("SYSTEM",`Failed to SIGKILL session process PID ${s.pid}`,{pid:s.pid,pgid:s.pgid},a):I.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()+O3;for(;Date.now()<s&&o.filter(l=>Br(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 I.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())};UA($A.dirname(this.registryPath),{recursive:!0}),T3(this.registryPath,JSON.stringify(e,null,2))}},Db=null;j3=[]});import{execFile as P3}from"child_process";import{existsSync as M3,readFileSync as N3,rmSync as L3}from"fs";import{promisify as U3}from"util";async function VA(t){let e=t.currentPid??process.pid,r=t.pidFilePath??J3,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(!Br(s.pid)){t.registry.unregister(s.id);continue}try{await GA(s,"SIGTERM")}catch(a){a instanceof Error?I.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:s.pid,pgid:s.pgid,type:s.type},a):I.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:s.pid,pgid:s.pgid,type:s.type,error:String(a)})}}await jd(n,5e3);let o=n.filter(s=>Br(s.pid));for(let s of o)try{await GA(s,"SIGKILL")}catch(a){a instanceof Error?I.debug("SYSTEM","Failed to force kill child process",{pid:s.pid,pgid:s.pgid,type:s.type},a):I.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:s.pid,pgid:s.pgid,type:s.type,error:String(a)})}await jd(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);BA(r,e),t.registry.pruneDeadEntries()}function BA(t,e,r=!1){if(!M3(t))return;let i=null;try{let s=JSON.parse(N3(t,"utf-8"));i=typeof s.pid=="number"?s.pid:null}catch(s){I.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||!Br(i);if(!n&&!(r&&o)){I.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{L3(t,{force:!0})}catch(s){s instanceof Error?I.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},s):I.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(s)})}}async function GA(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 $3("taskkill",n,{timeout:nr.POWERSHELL_COMMAND,windowsHide:!0})}var $3,J3,Nb=S(()=>{"use strict";Me();Fl();$s();nt();$3=U3(P3),J3=yt.workerPid()});function F3(){let e=Pd().pruneDeadEntries();e>0&&I.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function ZA(){Js===null&&(Js=setInterval(F3,WA),Js.unref(),I.debug("SYSTEM","Health checker started",{intervalMs:WA}))}function HA(){Js!==null&&(clearInterval(Js),Js=null,I.debug("SYSTEM","Health checker stopped"))}var WA,Js,YA=S(()=>{"use strict";Me();$s();WA=3e4,Js=null});import{existsSync as q3,readFileSync as z3,rmSync as XA}from"fs";function Ub(){return V3}function Md(t={}){let e=t.pidFilePath??G3;if(!q3(e))return"missing";let r=null;try{r=JSON.parse(z3(e,"utf-8"))}catch(n){return n instanceof Error?I.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},n):I.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(n)}),XA(e,{force:!0}),"invalid"}return Mb(r)&&r?((t.logAlive??!0)&&I.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(I.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),XA(e,{force:!0}),"stale")}var G3,Lb,V3,Nd=S(()=>{"use strict";Me();$s();Nb();YA();nt();G3=yt.workerPid(),Lb=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(),Md({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,ZA()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async i=>{if(this.shutdownInitiated){I.warn("SYSTEM",`Received ${i} but shutdown already in progress`);return}this.shutdownInitiated=!0,I.info("SYSTEM",`Received ${i}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(n){n instanceof Error?I.error("SYSTEM","Error during shutdown",{},n):I.error("SYSTEM","Error during shutdown (non-Error)",{error:String(n)});try{await this.stop()}catch(o){o instanceof Error?I.debug("SYSTEM","Supervisor shutdown fallback failed",{},o):I.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",()=>{I.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}HA(),this.stopPromise=VA({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}},V3=new Lb(Pd())});import{createHash as sbe,randomUUID as abe}from"crypto";var QA=S(()=>{"use strict";Me()});import{randomUUID as mbe}from"crypto";var eK=S(()=>{"use strict";Me();QA()});import Fs from"path";import{homedir as B3}from"os";import{existsSync as Jb,writeFileSync as xbe,readFileSync as Ibe,unlinkSync as kbe,mkdirSync as _be,statSync as Tbe,utimesSync as W3,copyFileSync as Cbe}from"fs";import{execSync as nK,spawnSync as Abe}from"child_process";function rK(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function Z3(t,e){let r=e==="win32"?`where ${t}`:`which ${t}`,i;try{i=nK(r,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(o){return o instanceof Error?I.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},o):I.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 iK(t={}){let e=Object.keys(t).length===0;if(e&&$b!==void 0)return $b;let r=H3(t);return e&&r!==null&&($b=r),r}function H3(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(rK(r))return r;let i=t.env??process.env,n=t.homeDirectory??B3(),o=t.pathExists??Jb,s=t.lookupInPath??Z3,a=e==="win32"?[i.BUN,i.BUN_PATH,Fs.join(n,".bun","bin","bun.exe"),Fs.join(n,".bun","bin","bun"),i.USERPROFILE?Fs.join(i.USERPROFILE,".bun","bin","bun.exe"):void 0,i.LOCALAPPDATA?Fs.join(i.LOCALAPPDATA,"bun","bun.exe"):void 0,i.LOCALAPPDATA?Fs.join(i.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[i.BUN,i.BUN_PATH,Fs.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&&(rK(c)&&o(c)||c.toLowerCase()==="bun"))return c}return s("bun",e)}function qs(t){return process.platform==="win32"?Math.round(t*2):t}function Y3(t,e){let r=i=>i.replace(/'/g,"''");return`Start-Process -FilePath '${r(t)}' -ArgumentList @('"${r(e)}"','--daemon') -WindowStyle Hidden`}function oK(t,e,r={}){Ub().assertCanSpawn("worker daemon");let i=To({...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r}),n=iK();if(!n){I.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=Y3(n,t),d=Buffer.from(u,"utf16le").toString("base64");try{return nK(`powershell -NoProfile -EncodedCommand ${d}`,{stdio:"ignore",windowsHide:!0,env:i}),0}catch(f){let p=f instanceof Error?f:new Error(String(f));I.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:n},p);return}}let o="/usr/bin/setsid",s=Jb(o),c=Oi(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 sK(){try{if(!Jb(tK))return;let t=new Date;W3(tK,t,t)}catch{}}function Ld(){return Md({logAlive:!1})}var Lbe,tK,$b,Ud=S(()=>{"use strict";Ai();Me();Dd();Nb();Nd();eK();nt();$s();Lbe=yt.dataDir(),tK=yt.workerPid()});import X3 from"net";function Fb(){return Fe.loadFromFile(ht).CLAUDE_MEM_WORKER_HOST}function aK(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}async function Q3(t,e,r="GET"){let i=await fetch(`http://${aK(Fb())}:${t}${e}`,{method:r}),n="";try{n=await i.text()}catch{}return{ok:i.ok,statusCode:i.status,body:n}}async function lK(t){if(process.platform==="win32")try{let e=await fetch(`http://${aK(Fb())}:${t}/api/health`);if(e.ok)return!0;I.debug("SYSTEM","Windows health check returned non-ok; falling through to socket probe",{port:t,status:e.status})}catch(e){e instanceof Error?I.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:t,message:e.message}):I.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:t,error:String(e)})}return new Promise(e=>{let r=X3.createServer(),i=Fb();r.once("error",n=>{n.code==="EADDRINUSE"?e(!0):e(!1)}),r.once("listening",()=>{r.close(()=>e(!1))}),r.listen(t,i)})}async function cK(t,e,r,i){let n=Date.now();for(;Date.now()-n<r;){try{if((await Q3(t,e)).ok)return!0}catch(o){o instanceof Error?I.debug("SYSTEM",i,{},o):I.debug("SYSTEM",i,{error:String(o)})}await new Promise(o=>setTimeout(o,500))}return!1}function Gl(t,e=3e4){return cK(t,"/api/health",e,"Service not ready yet, will retry")}function Vl(t,e=3e4){return cK(t,"/api/readiness",e,"Worker not ready yet, will retry")}var qb=S(()=>{"use strict";Me();Vr();nt()});import{dirname as eZ,join as tZ}from"path";import{mkdirSync as rZ,readFileSync as nZ,statSync as uK,unlinkSync as dK,writeFileSync as iZ}from"fs";function pK(){return tZ(Cn(),"spawn.lock")}function zb(){let t=pK(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return rZ(eZ(t),{recursive:!0}),iZ(t,e,{flag:"wx"}),!0}catch(i){let n=i instanceof Error?i:new Error(String(i)),o=n.code;if(o!=="EEXIST")return I.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=uK(t).mtimeMs}catch{continue}if(Date.now()-s<=oZ)return!1;let a;try{a=uK(t).mtimeMs}catch{continue}if(a!==s)return!1;try{dK(t)}catch{return!1}}return!1}function Gb(){let t=pK();try{if(JSON.parse(nZ(t,"utf-8")).pid!==process.pid)return;dK(t)}catch{}}var oZ,Vb=S(()=>{"use strict";nt();Me();oZ=9e4});import fK from"path";import{existsSync as Bb,mkdirSync as sZ,writeFileSync as aZ,unlinkSync as lZ,statSync as cZ}from"fs";function Wb(){return fK.join(Fe.get("CLAUDE_MEM_DATA_DIR"),".worker-start-attempted")}function dZ(){if(process.platform!=="win32")return!1;let t=Wb();if(!Bb(t))return!1;try{let e=cZ(t).mtimeMs;return Date.now()-e<uZ}catch(e){return e instanceof Error?I.debug("SYSTEM","Could not stat worker spawn lock file",{},e):I.debug("SYSTEM","Could not stat worker spawn lock file",{error:String(e)}),!1}}function pZ(){if(process.platform==="win32")try{let t=Wb();sZ(fK.dirname(t),{recursive:!0}),aZ(t,"","utf-8")}catch{}}function $d(){if(process.platform==="win32")try{let t=Wb();Bb(t)&&lZ(t)}catch{}}async function mK(t,e){if(!e)return I.error("SYSTEM","ensureWorkerStarted called with empty workerScriptPath \u2014 caller bug"),"dead";if(!Bb(e))return I.error("SYSTEM","ensureWorkerStarted: worker script not found at expected path \u2014 likely a partial install or build artifact missing",{workerScriptPath:e}),"dead";if(Ld()==="alive"){if(I.info("SYSTEM","Worker PID file points to a live process, skipping duplicate spawn"),await Vl(t,qs(nr.READINESS_WAIT)))return $d(),I.info("SYSTEM","Worker became ready while waiting on live PID"),"ready";let a=await Gl(t,1e3),l=Ld()==="alive";return!a&&!l?(I.error("SYSTEM","Live PID disappeared before readiness endpoint became available"),"dead"):(I.warn("SYSTEM","Live PID detected but worker did not become ready before timeout"),"warming")}if(await Gl(t,1e3)){$d();let s=await Vl(t,qs(nr.READINESS_WAIT));return s||I.warn("SYSTEM","Worker is alive but readiness timed out \u2014 proceeding anyway"),I.info("SYSTEM","Worker already running and healthy"),s?"ready":"warming"}if(await lK(t)){if(I.info("SYSTEM","Port in use, waiting for worker to become healthy"),await Gl(t,qs(nr.PORT_IN_USE_WAIT))){$d();let a=await Vl(t,qs(nr.READINESS_WAIT));return I.info("SYSTEM","Worker is now healthy"),a?"ready":"warming"}return I.error("SYSTEM","Port in use but worker not responding to health checks"),"dead"}if(dZ())return I.warn("SYSTEM","Worker unavailable on Windows \u2014 skipping spawn (recent attempt failed within cooldown)"),"dead";let n=zb(),o;try{if(n){if(I.info("SYSTEM","Starting worker daemon",{workerScriptPath:e}),pZ(),o=oK(e,t),o===void 0)return I.error("SYSTEM","Failed to spawn worker daemon"),"dead"}else I.info("SYSTEM","Another launcher holds the spawn lock \u2014 skipping duplicate spawn and waiting for its worker");if(!await Vl(t,qs(nr.READINESS_WAIT))){let a=await Gl(t,1e3),l=Ld()==="alive",c=o!==void 0&&o>0&&Br(o);return!a&&!l&&!c?(I.error("SYSTEM",n?"Worker exited before readiness endpoint became available":"Spawn-lock holder never produced a live worker before readiness timed out"),"dead"):(I.warn("SYSTEM",n?"Worker spawned but readiness endpoint not responding within window":"Spawn-lock holder's worker not ready within window"),"warming")}return $d(),sK(),I.info("SYSTEM",n?"Worker started successfully":"Worker is up (started by another launcher)"),"ready"}finally{n&&Gb()}}var uZ,hK=S(()=>{"use strict";Me();Fl();Vr();Ud();qb();Vb();$s();uZ=120*1e3});var yK=S(()=>{"use strict";Vr();nt()});var gK=S(()=>{"use strict";Me();Nd()});var bK=S(()=>{"use strict";Ud();qb();gK()});import fZ from"path";import{readFileSync as xve,existsSync as Ive,writeFileSync as kve,renameSync as _ve,mkdirSync as Tve,readdirSync as Cve,statSync as Ove}from"fs";function SK(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;I.warn("SYSTEM",`Invalid ${t}, using default`,{value:i,min:r.min,max:r.max})}return e}async function hZ(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 yZ(){return fZ.join(Fe.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function Zb(){return qd!==null||(qd=Fe.loadFromFile(yZ())),qd}function vK(t,e){if(!t)return null;let r=parseInt(t,10);return Number.isFinite(r)&&r>=e.min&&r<=e.max?r:null}function gZ(t,e,r){let i=process.env[t];if(i!==void 0){let s=vK(i,r);return s!==null?s:(I.warn("SYSTEM",`Invalid ${t}, using default`,{value:i,min:r.min,max:r.max}),e)}let n=Zb()[t],o=vK(n,r);return o!==null?o:(I.warn("SYSTEM",`Invalid ${t} in settings.json, using default`,{value:n,min:r.min,max:r.max}),e)}function Bl(){if(Jd!==null)return Jd;let t=Zb();return Jd=parseInt(t.CLAUDE_MEM_WORKER_PORT,10),Jd}function Wl(){return Fd!==null||(Fd=Zb().CLAUDE_MEM_WORKER_HOST),Fd}function bZ(){return zd!==null||(zd=gZ("CLAUDE_MEM_API_TIMEOUT_MS",Us(nr.API_REQUEST),mZ)),zd}function Hb(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}function vZ(t){return`http://${Hb(Wl())}:${Bl()}${t}`}function Gd(t,e={}){let r=e.method??"GET",i=e.timeoutMs??bZ(),n=vZ(t),o={method:r};return e.headers&&(o.headers=e.headers),e.body&&(o.body=e.body),i>0?hZ(n,o,i):fetch(n,o)}var Fve,qve,mZ,Jd,Fd,qd,zd,Zl=S(()=>{"use strict";Ai();Me();Fl();Vr();nt();yK();Nd();fd();Kd();bK();Ud();Vb();Fve=SK("CLAUDE_MEM_HEALTH_TIMEOUT_MS",Us(nr.HEALTH_CHECK),{min:500,max:3e5}),qve=SK("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",Us(nr.HOOK_READINESS_WAIT),{min:0,max:3e5}),mZ={min:500,max:3e5};Jd=null,Fd=null,qd=null,zd=null});function zs(t){return t instanceof Error?t.message:typeof t=="string"?t:t&&typeof t=="object"&&"message"in t?String(t.message):String(t??"")}function EK(t,e){for(let r of Yb)if(r.match(t,e))return r;return Yb[Yb.length-1]}var SZ,EZ,Yb,Vd=S(()=>{"use strict";SZ=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`).",EZ=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`).",Yb=[{id:"bun-missing-after-install",severity:"ABORT",match:t=>{let e=zs(t);return e.includes("Bun executable not found")||e.includes("Bun installation completed but binary not found")||e.includes("Failed to install Bun")},remediation:SZ},{id:"uv-missing-after-install",severity:"ABORT",match:t=>{let e=zs(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:EZ},{id:"tree-sitter-eresolve",severity:"ABORT",match:t=>/\bERESOLVE\b/.test(zs(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(zs(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(zs(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(zs(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 wZ,writeFileSync as xZ}from"fs";import{join as IZ}from"path";function Xb(){return{warnings:[],failedIDEs:[]}}function Hl(t){return t instanceof Error?t.message:typeof t=="string"?t:String(t??"")}function kZ(t,e,r,i){let n={severity:t.severity,categoryId:t.id,component:e.component,phase:e.phase,cause:Hl(e.cause),remediation:r,details:e.details??null,timestamp:new Date().toISOString()};try{wZ(i,{recursive:!0}),xZ(IZ(i,"last-install-error.json"),JSON.stringify(n,null,2))}catch{}}function zt(t,e,r){let i=Cn(),n=EK(e.cause,{component:e.component,phase:e.phase}),o=e.remediation??n.remediation({platform:process.platform,dataDir:i});switch(t){case"ABORT":throw kZ(n,e,o,i),new Gs(`${e.component} failed during ${e.phase}: ${Hl(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?`${Hl(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.12.3",
6
+ "version": "13.12.4",
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.12.3",
3
+ "version": "13.12.4",
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.12.3",
3
+ "version": "13.12.4",
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.12.3",
3
+ "version": "13.12.4",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "author": {
6
6
  "name": "Alex Newman",
@@ -104,7 +104,7 @@
104
104
  "recording_focus": "WHAT TO RECORD\n--------------\nFocus on durable technical signal:\n- What the system NOW DOES differently (new capabilities)\n- What shipped to users/production (features, fixes, configs, docs)\n- Changes in technical domains (auth, data, UI, infra, DevOps, docs)\n- Concrete debugging or investigative findings from logs, traces, queue state, database rows, and code-path inspection\n\nUse verbs like: implemented, fixed, deployed, configured, migrated, optimized, added, refactored, discovered, confirmed, traced\n\n✅ GOOD EXAMPLES (describes what was built or learned):\n- \"Authentication now supports OAuth2 with PKCE flow\"\n- \"Deployment pipeline runs canary releases with auto-rollback\"\n- \"Database indexes optimized for common query patterns\"\n- \"Observation queue for claude-mem session timed out waiting for an agent pool slot\"\n- \"Fallback processing abandoned pending messages after Gemini and OpenRouter returned 404\"\n\n❌ BAD EXAMPLES (describes observation process - DO NOT DO THIS):\n- \"Analyzed authentication implementation and stored findings\"\n- \"Tracked deployment steps and logged outcomes\"\n- \"Monitored database performance and recorded metrics\"",
105
105
  "skip_guidance": "WHEN TO SKIP\n------------\nSkip routine operations:\n- Empty status checks\n- Package installations with no errors\n- Simple file listings with no follow-on finding\n- Repetitive operations you've already documented\n- File related research that comes back empty or not found\n\nIf skipping, return an empty response only. Do not explain the skip in prose.",
106
106
  "type_guidance": "**type**: MUST be EXACTLY one of these 6 options (no other values allowed):\n - bugfix: something was broken, now fixed\n - feature: new capability or functionality added\n - refactor: code restructured, behavior unchanged\n - change: generic modification (docs, config, misc)\n - discovery: learning about existing system\n - decision: architectural/design choice with rationale",
107
- "concept_guidance": "**concepts**: 2-5 knowledge-type categories. MUST use ONLY these exact keywords:\n - how-it-works: understanding mechanisms\n - why-it-exists: purpose or rationale\n - what-changed: modifications made\n - problem-solution: issues and their fixes\n - gotcha: traps or edge cases\n - pattern: reusable approach\n - trade-off: pros/cons of a decision\n\n IMPORTANT: Do NOT include the observation type (change/discovery/decision) as a concept.\n Types and concepts are separate dimensions.",
107
+ "concept_guidance": "**concepts**: 2-5 knowledge-type categories. MUST use ONLY these exact keywords:\n - how-it-works: understanding mechanisms\n - why-it-exists: purpose or rationale\n - what-changed: modifications made\n - problem-solution: issues and their fixes\n - gotcha: traps or edge cases\n - pattern: reusable approach\n - trade-off: pros/cons of a decision\n\n IMPORTANT: Do NOT include the observation type (change/discovery/decision) as a concept.\n Types and concepts are separate dimensions.\n\n OUTPUT RULE: Each <concept> element must contain ONLY the bare keyword (e.g. <concept>gotcha</concept>) - never a description, sentence, or colon.",
108
108
  "field_guidance": "**facts**: Concise, self-contained statements\nEach fact is ONE piece of information\n No pronouns - each fact must stand alone\n Include specific details: filenames, functions, values\n\n**files**: All files touched (full paths from project root)",
109
109
  "output_format_header": "OUTPUT FORMAT\n-------------\nOutput observations using this XML structure:",
110
110
  "format_examples": "",
@@ -85,7 +85,7 @@
85
85
  "recording_focus": "WHAT TO RECORD\n--------------\nFocus on investigative elements:\n- New entities discovered (people, organizations, email addresses)\n- Relationships between entities (who contacted whom, organizational ties)\n- Timeline events (when things happened, communication sequences)\n- Evidence supporting or refuting fraud patterns\n- Anomalies or red flags detected\n\nCRITICAL OBSERVATION GRANULARITY:\n- Break up the information into multiple observations as necessary\n- Create AT LEAST 1 observation per tool use\n- When a single tool use returns rich information (like reading an email), create multiple smaller, focused observations rather than one large observation\n- Each observation should be atomic and semantically focused on ONE investigative element\n- Example: One email might yield 3-5 observations (entity discovery, timeline event, relationship, evidence, anomaly)\n\nUse verbs like: identified, discovered, revealed, detected, corroborated, confirmed\n\n✅ GOOD EXAMPLES (describes what was discovered):\n- \"John Smith <john@example.com> sent 15 emails requesting wire transfers\"\n- \"Timeline reveals communication pattern between suspicious accounts\"\n- \"Email headers show spoofed sender domain\"\n\n❌ BAD EXAMPLES (describes observation process - DO NOT DO THIS):\n- \"Analyzed email headers and recorded findings\"\n- \"Tracked communication patterns and logged results\"\n- \"Monitored entity relationships and stored data\"",
86
86
  "skip_guidance": "WHEN TO SKIP\n------------\nSkip routine operations:\n- Empty searches with no results\n- Simple file listings\n- Repetitive operations you've already documented\n- If email research comes back as empty or not found\n- **No output necessary if skipping.**",
87
87
  "type_guidance": "**type**: MUST be EXACTLY one of these options:\n - entity: new person, organization, or email address identified\n - relationship: connection between entities discovered\n - timeline-event: time-stamped event in communication sequence\n - evidence: supporting documentation or proof discovered\n - anomaly: suspicious pattern or irregularity detected\n - conclusion: investigative finding or determination",
88
- "concept_guidance": "**concepts**: 2-5 knowledge-type categories. MUST use ONLY these exact keywords:\n - who: people and organizations involved\n - when: timing and sequence of events\n - what-happened: events and communications\n - motive: intent or purpose behind actions\n - red-flag: warning signs of fraud or deception\n - corroboration: evidence supporting a claim",
88
+ "concept_guidance": "**concepts**: 2-5 knowledge-type categories. MUST use ONLY these exact keywords:\n - who: people and organizations involved\n - when: timing and sequence of events\n - what-happened: events and communications\n - motive: intent or purpose behind actions\n - red-flag: warning signs of fraud or deception\n - corroboration: evidence supporting a claim\n\n OUTPUT RULE: Each <concept> element must contain ONLY the bare keyword (e.g. <concept>red-flag</concept>) - never a description, sentence, or colon.",
89
89
  "field_guidance": "**facts**: Concise, self-contained statements about entities and events\n Each fact is ONE piece of information\n No pronouns - each fact must stand alone\n ALWAYS use \"Full Name <email@address.com>\" format for people\n Include specific details: timestamps, email addresses, relationships\n\n**files**: All email files, documents, or evidence files examined (full paths)",
90
90
  "output_format_header": "OUTPUT FORMAT\n-------------\nOutput observations using this XML structure:",
91
91
  "format_examples": "**Entity Format Examples:**\nWhen recording people, ALWAYS use: \"Full Name <email@address.com>\"\n\n<observation>\n <type>entity</type>\n <title>John Smith <john.smith@example.com> identified as sender</title>\n <facts>\n <fact>John Smith <john.smith@example.com> sent 15 emails to Jane Doe <jane@corp.com></fact>\n <fact>Email address john.smith@example.com registered to Acme Corp</fact>\n </facts>\n <narrative>John Smith <john.smith@example.com> appears frequently in the email chain...</narrative>\n</observation>",
@@ -85,7 +85,7 @@
85
85
  "recording_focus": "WHAT TO RECORD\n--------------\nFocus on legal knowledge and exam-ready insights:\n- Case holdings distilled to 2-3 sentences (key facts + holding + rule)\n- Legal tests, elements, and standards extracted from cases or statutes\n- Issue-spotting triggers: what fact patterns signal which legal issues\n- Professor's framing, emphasis, or analytical approach to a doctrine\n- Arguments and counter-arguments worked through\n- Connections across cases or doctrines that reveal underlying principles\n\nUse verbs like: held, established, synthesized, identified, distinguished, analyzed, revealed, connected\n\n✅ GOOD EXAMPLES (describes what was learned about the law):\n- \"Palsgraf established proximate cause requires the harm be foreseeable to the defendant at the time of conduct\"\n- \"Prof frames consideration doctrine around the bargain theory, not benefit-detriment — exam answers should reflect this\"\n- \"When fact pattern shows concurrent causation, issue-spot both but-for AND substantial factor tests\"\n\n❌ BAD EXAMPLES (describes observation process - DO NOT DO THIS):\n- \"Analyzed the case and recorded findings about proximate cause\"\n- \"Tracked professor's comments and stored the framework\"\n- \"Monitored discussion of consideration and noted the approach\"",
86
86
  "skip_guidance": "WHEN TO SKIP\n------------\nSkip these — not worth recording:\n- Full case briefs (only record the 2-3 sentence distilled version with the rule)\n- Re-reading the same case or passage without new insight\n- Definitions of basic terms the student already knows\n- Routine case brief formatting with no analytical content\n- Simple fact summaries that don't extract a rule or pattern\n- Procedural history details not relevant to the legal rule\n- **No output necessary if skipping.**",
87
87
  "type_guidance": "**type**: MUST be EXACTLY one of these 6 options (no other values allowed):\n - case-holding: case brief (2-3 sentences: key facts + holding) with extracted legal rule\n - issue-pattern: exam trigger or fact pattern that signals a legal issue to spot\n - prof-framework: professor's analytical lens, emphasis, or approach to a topic or doctrine\n - doctrine-rule: legal test, standard, or doctrine synthesized from cases, statutes, or restatements\n - argument-structure: legal argument or counter-argument worked through with analytical steps\n - cross-case-connection: insight linking multiple cases, doctrines, or topics that reveals a deeper principle",
88
- "concept_guidance": "**concepts**: 2-5 knowledge-type categories. MUST use ONLY these exact keywords:\n - exam-relevant: flagged by professor or likely to appear on exams\n - minority-position: dissent, minority rule, or alternative jurisdictional approach\n - gotcha: subtle nuance, counterintuitive result, or common mistake\n - unsettled-law: circuit split, open question, or evolving area\n - policy-rationale: normative or policy argument underlying a rule\n - course-theme: connects to the overarching narrative or theory of the course\n\n IMPORTANT: Do NOT include the observation type (case-holding/issue-pattern/etc.) as a concept.\n Types and concepts are separate dimensions.",
88
+ "concept_guidance": "**concepts**: 2-5 knowledge-type categories. MUST use ONLY these exact keywords:\n - exam-relevant: flagged by professor or likely to appear on exams\n - minority-position: dissent, minority rule, or alternative jurisdictional approach\n - gotcha: subtle nuance, counterintuitive result, or common mistake\n - unsettled-law: circuit split, open question, or evolving area\n - policy-rationale: normative or policy argument underlying a rule\n - course-theme: connects to the overarching narrative or theory of the course\n\n IMPORTANT: Do NOT include the observation type (case-holding/issue-pattern/etc.) as a concept.\n Types and concepts are separate dimensions.\n\n OUTPUT RULE: Each <concept> element must contain ONLY the bare keyword (e.g. <concept>gotcha</concept>) - never a description, sentence, or colon.",
89
89
  "field_guidance": "**facts**: Concise, self-contained statements\nEach fact is ONE piece of information\n No pronouns - each fact must stand alone\n Include specific details: case names, rule elements, test names, jurisdiction\n\n**files**: All files or documents read (full paths from project root)",
90
90
  "output_format_header": "OUTPUT FORMAT\n-------------\nOutput observations using this XML structure:",
91
91
  "format_examples": "",
@@ -90,7 +90,7 @@
90
90
  "recording_focus": "WHAT TO RECORD\n--------------\nFocus on trading signals and market behavior:\n- Pump detection: token symbol, U/m, signal tier, price gains across timeframes, buy pressure, pool size\n- Dump detection: activity collapse, negative gains, sell pressure\n- Signal transitions: FLAT→WATCH→RISING→STRONG or reverse\n- Multi-wave pumps: tokens that pump, die, then pump again\n- Market conditions: how many STRONG/RISING tokens, overall activity level\n- Algorithm quality: false positives, tokens that shouldn't be ranked high, filter gaps\n- Buy pressure ratios: buyPressure5m relative to pool liquidity (high ratio = potential whale)\n\nALWAYS INCLUDE SPECIFIC NUMBERS:\n- U/m value and signal tier\n- Price gains (1m%, 2m%, 3m%, 4m%, 5m%)\n- Buy pressure dollar amount\n- Pool liquidity\n- Token age and discovery time\n\n✅ GOOD EXAMPLES:\n- \"MEMEMAN hit 58 U/m STRONG with +82.3% 3m gain, $2.5K buy pressure on $7K pool, discovered 5 minutes ago\"\n- \"Market in deep lull: no STRONG/RISING tokens, all FLAT at 1-9 U/m, only noise-level shuffling\"\n- \"思念熊 appeared for 8th time — repeat pumper cycling FLAT→WATCH→RISING then collapsing within 3 checks\"\n\n❌ BAD EXAMPLES:\n- \"Observed token activity and recorded findings\"\n- \"Monitored market conditions and logged results\"",
91
91
  "skip_guidance": "WHEN TO SKIP\n------------\nSkip these:\n- Routine checks with no notable changes from previous observation\n- Tokens at 1-2 U/m with 0% gains (background noise)\n- Repeat observations of the same token at the same signal tier with no meaningful metric change\n- Code file reads or edits (these are algorithm changes, not token observations)\n- **No output necessary if skipping.**",
92
92
  "type_guidance": "**type**: MUST be EXACTLY one of these 6 options (no other values allowed):\n - pump-detected: rapid price increase with high trading activity\n - dump-detected: rapid price decline, sell pressure, or activity collapse\n - signal-change: token transitioning between signal tiers (FLAT/WATCH/RISING/STRONG)\n - token-profile: notable token characteristics, patterns, or repeat behavior\n - market-condition: broad market state (lull, heating up, multiple pumps)\n - algorithm-insight: observation about sorting behavior, ranking quality, or filter gaps",
93
- "concept_guidance": "**concepts**: 2-5 knowledge-type categories. MUST use ONLY these exact keywords:\n - early-detection: token caught before or during initial pump\n - lifecycle: full pump-hold-dump cycle or multi-wave pattern\n - false-signal: token ranked high but not actually pumping\n - whale-activity: large buy pressure relative to pool size\n - repeat-pumper: token cycling through multiple pump-dump waves\n - dead-cat-bounce: brief recovery tricking the ranking\n - sustained-momentum: high activity and gains over 5+ minutes\n\n IMPORTANT: Do NOT include the observation type as a concept.\n Types and concepts are separate dimensions.",
93
+ "concept_guidance": "**concepts**: 2-5 knowledge-type categories. MUST use ONLY these exact keywords:\n - early-detection: token caught before or during initial pump\n - lifecycle: full pump-hold-dump cycle or multi-wave pattern\n - false-signal: token ranked high but not actually pumping\n - whale-activity: large buy pressure relative to pool size\n - repeat-pumper: token cycling through multiple pump-dump waves\n - dead-cat-bounce: brief recovery tricking the ranking\n - sustained-momentum: high activity and gains over 5+ minutes\n\n IMPORTANT: Do NOT include the observation type as a concept.\n Types and concepts are separate dimensions.\n\n OUTPUT RULE: Each <concept> element must contain ONLY the bare keyword (e.g. <concept>whale-activity</concept>) - never a description, sentence, or colon.",
94
94
  "field_guidance": "**facts**: Concise, self-contained statements about token activity\nEach fact is ONE piece of information\n No pronouns - each fact must stand alone\n ALWAYS include: token symbol, U/m, signal tier, specific gain percentages, buy pressure, pool size\n Include timing: when discovered, how long at current tier, which check number\n\n**files**: Leave empty for token observations (no files involved)",
95
95
  "output_format_header": "OUTPUT FORMAT\n-------------\nOutput observations using this XML structure:",
96
96
  "format_examples": "**Token Observation Examples:**\n\n<observation>\n <type>pump-detected</type>\n <title>SIMULAT Reaches RISING at 36 U/m With +45.5% 3m Gain</title>\n <subtitle>6-day-old token building sustained momentum over 5 consecutive checks since discovery at 6 U/m</subtitle>\n <facts>\n <fact>SIMULAT reached 36 U/m RISING signal tier at 10:33 PM</fact>\n <fact>SIMULAT price gains: +15.3% 1m, +33.9% 2m, +45.5% 3m</fact>\n <fact>SIMULAT buy pressure $4.8K on $4K pool (1.2:1 pressure-to-pool ratio)</fact>\n <fact>SIMULAT first detected at 6 U/m FLAT, promoted through WATCH to RISING over 4 minutes</fact>\n </facts>\n <narrative>SIMULAT demonstrated the ideal early-detection pattern for the activity-first algorithm. First appearing at 6 U/m with +15% 1m gain, it steadily built activity through WATCH to RISING over 4 minutes. The 1.2:1 buy-pressure-to-pool ratio suggests concentrated buying interest. This token was surfaced 4 minutes before its biggest price move.</narrative>\n <concepts><concept>early-detection</concept><concept>sustained-momentum</concept></concepts>\n <files></files>\n</observation>",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem-plugin",
3
- "version": "13.12.3",
3
+ "version": "13.12.4",
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 WP=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"]),VP=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),KP=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!=="."||VP.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("."));WP.has(i)&&(yield s)}}}async function JP(t){try{let e=await(0,qr.stat)(t);if(e.size>KP||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+=BP(S);let x=Bs(g.toLowerCase(),s)>0,b=[],$=(k,Se)=>{for(let K of k){let ct=0,Ne="",Pt=Bs(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=Bs(g.symbolName.toLowerCase(),s);return Bs(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 Bs(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 BP(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"),Qs=require("node:fs"),at=require("node:path"),Q_=require("node:os"),ey=require("node:url");var K_="claude";function YP(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Ys(t){if(!t)return K_;let e=YP(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:K_}var GP=Ht(ye.API_REQUEST),Ge=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)}},Gs=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=XP(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??GP}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 Ge("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 Ge("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 Ge("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 Ge(l?"timeout":"transport",`Server ${e} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new Ge("http_error",`Server ${e} ${r} returned ${i.status}: ${QP(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 Ge("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:u})}}};function J_(t){return t instanceof Ge}function XP(t){return t.replace(/\/+$/,"")}function Nu(t){return typeof t=="string"?Ys(t):null}function QP(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}ce();function Xs(){let e=(Ms().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function B_(){let t=Ms(),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 Gs(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"],eT=new Set(Y_);function G_(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=>!eT.has(r.name)))}var vT={},tT="13.12.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)(vT.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 rT(){ty&&((0,Qs.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 Vs(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 Vs(`${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 nT(){try{return(await Vs("/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(Xs()!=="server")return null;let e=B_();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 oT(t){return J_(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 Ge("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 Ge("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),oT(n)}}}var sT=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 ti(t){return typeof t=="string"?Ys(t):null}var iT=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:ti(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)}),aT=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:ti(t.platformSource)}:{}},o=await e.client.searchObservations(n);return Zr(o)}),cT=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:ti(t.platformSource)}:{}},o=await e.client.contextObservations(n);return Zr(o)});function uT(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 lT(t){let e=uT(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:ti(t.platformSource)}:{},...t.full!==void 0?{full:t.full}:{},...t.colors!==void 0?{colors:t.colors}:{}},text:!0})}var dT=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 pT(){if(await nT())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),rT();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"),Qs=require("node:fs"),at=require("node:path"),Q_=require("node:os"),ey=require("node:url");var K_="claude";function YP(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Ys(t){if(!t)return K_;let e=YP(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:K_}var GP=Ht(ye.API_REQUEST),Ge=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)}},Gs=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=XP(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??GP}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 Ge("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 Ge("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 Ge("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 Ge(l?"timeout":"transport",`Server ${e} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new Ge("http_error",`Server ${e} ${r} returned ${i.status}: ${QP(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 Ge("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:u})}}};function J_(t){return t instanceof Ge}function XP(t){return t.replace(/\/+$/,"")}function Nu(t){return typeof t=="string"?Ys(t):null}function QP(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}ce();function Xs(){let e=(Ms().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function B_(){let t=Ms(),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 Gs(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"],eT=new Set(Y_);function G_(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=>!eT.has(r.name)))}var vT={},tT="13.12.4";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)(vT.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 rT(){ty&&((0,Qs.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 Vs(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 Vs(`${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 nT(){try{return(await Vs("/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(Xs()!=="server")return null;let e=B_();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 oT(t){return J_(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 Ge("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 Ge("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),oT(n)}}}var sT=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 ti(t){return typeof t=="string"?Ys(t):null}var iT=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:ti(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)}),aT=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:ti(t.platformSource)}:{}},o=await e.client.searchObservations(n);return Zr(o)}),cT=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:ti(t.platformSource)}:{}},o=await e.client.contextObservations(n);return Zr(o)});function uT(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 lT(t){let e=uT(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:ti(t.platformSource)}:{},...t.full!==void 0?{full:t.full}:{},...t.colors!==void 0?{colors:t.colors}:{}},text:!0})}var dT=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 pT(){if(await nT())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),rT();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