claude-mem 13.13.0 → 13.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.codex-plugin/plugin.json +1 -1
- package/dist/npx-cli/index.js +1 -1
- package/openclaw/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/.codex-plugin/plugin.json +1 -1
- package/plugin/package.json +1 -1
- package/plugin/scripts/context-generator.cjs +23 -21
- package/plugin/scripts/mcp-server.cjs +1 -1
- package/plugin/scripts/server-service.cjs +50 -50
- package/plugin/scripts/transcript-watcher.cjs +1 -1
- package/plugin/scripts/worker-service.cjs +220 -218
- package/plugin/skills/mode-creator/SKILL.md +162 -0
- package/plugin/skills/mode-creator/evals/evals.json +23 -0
- package/plugin/skills/mode-creator/references/mode-authoring.md +96 -0
- package/plugin/skills/mode-creator/references/telegram.md +45 -0
- package/plugin/skills/mode-creator/scripts/configure-telegram.mjs +218 -0
- package/plugin/skills/mode-creator/scripts/install-mode.mjs +264 -0
package/dist/npx-cli/index.js
CHANGED
|
@@ -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.13.
|
|
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.13.1",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 y3,Fe,Vr=S(()=>{"use strict";Fl();un();y3="security_alert",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_CHROMA_MAX_PENDING_MUTATIONS:"5000",CLAUDE_MEM_CLOUD_SYNC_TOKEN:"",CLAUDE_MEM_CLOUD_SYNC_USER_ID:"",CLAUDE_MEM_CLOUD_SYNC_HUB_URL:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_ID:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_NAME: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,sensitive",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let r=this.get(e);return parseInt(r,10)}static applyEnvOverrides(e){let r={...e};for(let i of Object.keys(this.DEFAULTS))process.env[i]!==void 0&&(r[i]=process.env[i]);return r}static loadFromFile(e,r=!0){try{if(!m3(e)){let a=this.getAllDefaults();try{mt(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{mt(e,o),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(a){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,a instanceof Error?a.message:String(a))}}if(o.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES===y3){o={...o,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES};try{mt(e,o),console.warn("[SETTINGS] Migrated Telegram trigger types off the legacy default:",e)}catch(a){console.warn("[SETTINGS] Failed to migrate Telegram trigger types:",e,a instanceof Error?a.message:String(a))}}let s={...this.DEFAULTS};for(let a of Object.keys(this.DEFAULTS))o[a]!==void 0&&(s[a]=o[a]);return r?this.applyEnvOverrides(s):s}catch(i){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,i instanceof Error?i.message:String(i));let n=this.getAllDefaults();return r?this.applyEnvOverrides(n):n}}}});import{execFile as g3}from"child_process";import{promisify as b3}from"util";import{existsSync as uge,readFileSync as dge,writeFileSync as pge,mkdirSync as fge,unlinkSync as mge}from"fs";import{userInfo as yge}from"os";import{join as bge}from"path";var Ege,RA=S(()=>{"use strict";nt();Me();Ege=b3(g3)});import{existsSync as Rb,readFileSync as jA,writeFileSync as v3,mkdirSync as S3,chmodSync as DA}from"fs";import{parseEnv as E3}from"util";function PA(){return process.env.CLAUDE_MEM_ENV_FILE??gt.envFile()}function NA(t){return E3(t)}function w3(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(gt.dataDir())||S3(gt.dataDir(),{recursive:!0,mode:448}),DA(gt.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{v3(e,w3(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(_3.has(r)){e[r]=i;continue}I3.has(r)||x3.some(n=>r.startsWith(n))||(e[r]=i)}return e}var x3,I3,k3,_3,Dd=S(()=>{"use strict";x3=["CLAUDECODE_","CLAUDE_CODE_"],I3=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),k3=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"]),_3=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",...k3])});import{spawnSync as FA}from"child_process";import{existsSync as T3,mkdirSync as UA,readFileSync as qA,writeFileSync as C3}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 D3(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 j3(t){let e=JA.get(t);if(e&&Date.now()-e.capturedAtMs<R3)return e.token;let r=null;try{r=D3(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 j3(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=P3.shift();t&&t()}var O3,A3,K3,R3,JA,Pb,Db,P3,$s=S(()=>{"use strict";Ai();Me();Dd();nt();O3=5e3,A3=1e3,K3=gt.supervisorRegistry();R3=5e3,JA=new Map;Pb=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=K3){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,UA($A.dirname(this.registryPath),{recursive:!0}),!T3(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,O3);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()+A3;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}),C3(this.registryPath,JSON.stringify(e,null,2))}},Db=null;P3=[]});import{execFile as M3}from"child_process";import{existsSync as N3,readFileSync as L3,rmSync as U3}from"fs";import{promisify as $3}from"util";async function VA(t){let e=t.currentPid??process.pid,r=t.pidFilePath??F3,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(!N3(t))return;let i=null;try{let s=JSON.parse(L3(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{U3(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 J3("taskkill",n,{timeout:nr.POWERSHELL_COMMAND,windowsHide:!0})}var J3,F3,Nb=S(()=>{"use strict";Me();Fl();$s();nt();J3=$3(M3),F3=gt.workerPid()});function q3(){let e=Pd().pruneDeadEntries();e>0&&I.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function ZA(){Js===null&&(Js=setInterval(q3,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 z3,readFileSync as G3,rmSync as XA}from"fs";function Ub(){return B3}function Md(t={}){let e=t.pidFilePath??V3;if(!z3(e))return"missing";let r=null;try{r=JSON.parse(G3(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 V3,Lb,B3,Nd=S(()=>{"use strict";Me();$s();Nb();YA();nt();V3=gt.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}},B3=new Lb(Pd())});import{createHash as abe,randomUUID as lbe}from"crypto";var QA=S(()=>{"use strict";Me()});import{randomUUID as hbe}from"crypto";var eK=S(()=>{"use strict";Me();QA()});import Fs from"path";import{homedir as W3}from"os";import{existsSync as Jb,writeFileSync as Ibe,readFileSync as kbe,unlinkSync as _be,mkdirSync as Tbe,statSync as Cbe,utimesSync as Z3,copyFileSync as Obe}from"fs";import{execSync as nK,spawnSync as Kbe}from"child_process";function rK(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function H3(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=Y3(t);return e&&r!==null&&($b=r),r}function Y3(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??W3(),o=t.pathExists??Jb,s=t.lookupInPath??H3,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 X3(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=X3(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;Z3(tK,t,t)}catch{}}function Ld(){return Md({logAlive:!1})}var Ube,tK,$b,Ud=S(()=>{"use strict";Ai();Me();Dd();Nb();Nd();eK();nt();$s();Ube=gt.dataDir(),tK=gt.workerPid()});import Q3 from"net";function Fb(){return Fe.loadFromFile(yt).CLAUDE_MEM_WORKER_HOST}function aK(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}async function eZ(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=Q3.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 eZ(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 tZ,join as rZ}from"path";import{mkdirSync as nZ,readFileSync as iZ,statSync as uK,unlinkSync as dK,writeFileSync as oZ}from"fs";function pK(){return rZ(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 nZ(tZ(t),{recursive:!0}),oZ(t,e,{flag:"wx"}),!0}catch(i){let n=i instanceof Error?i:new Error(String(i)),o=n.code;if(o!=="EEXIST")return 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<=sZ)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(iZ(t,"utf-8")).pid!==process.pid)return;dK(t)}catch{}}var sZ,Vb=S(()=>{"use strict";nt();Me();sZ=9e4});import fK from"path";import{existsSync as Bb,mkdirSync as aZ,writeFileSync as lZ,unlinkSync as cZ,statSync as uZ}from"fs";function Wb(){return fK.join(Fe.get("CLAUDE_MEM_DATA_DIR"),".worker-start-attempted")}function pZ(){if(process.platform!=="win32")return!1;let t=Wb();if(!Bb(t))return!1;try{let e=uZ(t).mtimeMs;return Date.now()-e<dZ}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 fZ(){if(process.platform==="win32")try{let t=Wb();aZ(fK.dirname(t),{recursive:!0}),lZ(t,"","utf-8")}catch{}}function $d(){if(process.platform==="win32")try{let t=Wb();Bb(t)&&cZ(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(pZ())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}),fZ(),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 dZ,hK=S(()=>{"use strict";Me();Fl();Vr();Ud();qb();Vb();$s();dZ=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 mZ from"path";import{readFileSync as Ive,existsSync as kve,writeFileSync as _ve,renameSync as Tve,mkdirSync as Cve,readdirSync as Ove,statSync as Ave}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 yZ(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 gZ(){return mZ.join(Fe.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function Zb(){return qd!==null||(qd=Fe.loadFromFile(gZ())),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 bZ(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 vZ(){return zd!==null||(zd=bZ("CLAUDE_MEM_API_TIMEOUT_MS",Us(nr.API_REQUEST),hZ)),zd}function Hb(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}function SZ(t){return`http://${Hb(Wl())}:${Bl()}${t}`}function Gd(t,e={}){let r=e.method??"GET",i=e.timeoutMs??vZ(),n=SZ(t),o={method:r};return e.headers&&(o.headers=e.headers),e.body&&(o.body=e.body),i>0?yZ(n,o,i):fetch(n,o)}var qve,zve,hZ,Jd,Fd,qd,zd,Zl=S(()=>{"use strict";Ai();Me();Fl();Vr();nt();yK();Nd();fd();Kd();bK();Ud();Vb();qve=SK("CLAUDE_MEM_HEALTH_TIMEOUT_MS",Us(nr.HEALTH_CHECK),{min:500,max:3e5}),zve=SK("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",Us(nr.HOOK_READINESS_WAIT),{min:0,max:3e5}),hZ={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 EZ,wZ,Yb,Vd=S(()=>{"use strict";EZ=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`).",wZ=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:EZ},{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:wZ},{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 xZ,writeFileSync as IZ}from"fs";import{join as kZ}from"path";function Xb(){return{warnings:[],failedIDEs:[]}}function Hl(t){return t instanceof Error?t.message:typeof t=="string"?t:String(t??"")}function _Z(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{xZ(i,{recursive:!0}),IZ(kZ(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 _Z(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.13.
|
|
6
|
+
"version": "13.13.1",
|
|
7
7
|
"license": "Apache-2.0",
|
|
8
8
|
"author": "thedotmack",
|
|
9
9
|
"homepage": "https://claude-mem.ai",
|
package/package.json
CHANGED
package/plugin/package.json
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`);let
|
|
3
|
-
`,"utf-8"),c;try{c=(0,m.statSync)(r).mode&511}catch{}let
|
|
4
|
-
`)}finally{if(E!==void 0)try{(0,m.closeSync)(E)}catch{}}}}catch(l){if(
|
|
5
|
-
${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let r=Object.keys(e);return r.length===0?"{}":r.length<=3?JSON.stringify(e):`{${r.length} keys: ${r.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,r){if(!r)return e;let n=r;if(typeof r=="string")try{n=JSON.parse(r)}catch{n=r}if(e==="Bash"&&n.command)return`${e}(${n.command})`;if(n.file_path)return`${e}(${n.file_path})`;if(n.notebook_path)return`${e}(${n.notebook_path})`;if(e==="Glob"&&n.pattern)return`${e}(${n.pattern})`;if(e==="Grep"&&n.pattern)return`${e}(${n.pattern})`;if(n.url)return`${e}(${n.url})`;if(n.query)return`${e}(${n.query})`;if(e==="Task"){if(n.subagent_type)return`${e}(${n.subagent_type})`;if(n.description)return`${e}(${n.description})`}return e==="Skill"&&n.skill?`${e}(${n.skill})`:e==="LSP"&&n.operation?`${e}(${n.operation})`:e}formatTimestamp(e){let r=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0"),s=String(e.getHours()).padStart(2,"0"),u=String(e.getMinutes()).padStart(2,"0"),c=String(e.getSeconds()).padStart(2,"0"),
|
|
1
|
+
"use strict";var ht=Object.create;var k=Object.defineProperty;var Rt=Object.getOwnPropertyDescriptor;var It=Object.getOwnPropertyNames;var Ut=Object.getPrototypeOf,vt=Object.prototype.hasOwnProperty;var bt=(t,e)=>{for(var r in e)k(t,r,{get:e[r],enumerable:!0})},ce=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of It(e))!vt.call(t,o)&&o!==r&&k(t,o,{get:()=>e[o],enumerable:!(n=Rt(e,o))||n.enumerable});return t};var h=(t,e,r)=>(r=t!=null?ht(Ut(t)):{},ce(e||!t||!t.__esModule?k(r,"default",{value:t,enumerable:!0}):r,t)),Nt=t=>ce(k({},"__esModule",{value:!0}),t);var mr={};bt(mr,{generateContext:()=>Lt,generateContextWithStats:()=>se});module.exports=Nt(mr);var Ct=h(require("path"),1),At=require("os"),X=require("fs"),Dt=require("bun:sqlite");var g=require("path"),R=require("os"),I=require("fs"),le=require("url");var m=require("fs"),ue=require("crypto"),T=require("path");var xt=null;function $t(t){return(xt??process.stderr.write.bind(process.stderr))(t)}function L(t){$t(t)}var kt=process.platform==="win32";function Pt(t){return t.replace(/^\uFEFF/,"")}function O(t){return JSON.parse(Pt(t))}function wt(t){(0,m.existsSync)(t)||(0,m.mkdirSync)(t,{recursive:!0})}function P(t,e){let r=t;try{if((0,m.lstatSync)(t).isSymbolicLink())try{r=(0,m.realpathSync)(t)}catch(l){let E=l instanceof Error?l:new Error(String(l));L(`claude-mem: realpathSync failed for ${t}, resolving symlink manually: ${E.message}
|
|
2
|
+
`);let d=(0,m.readlinkSync)(t);r=(0,T.resolve)((0,T.dirname)(t),d)}}catch(l){let E=l.code;if(E!=="ENOENT"&&E!=="ENOTDIR")throw l}wt((0,T.dirname)(r));let n=(0,T.dirname)(r),o=(0,T.basename)(r),s=(0,T.join)(n,`.${o}.${process.pid}.${(0,ue.randomBytes)(6).toString("hex")}.tmp`),u=Buffer.from(JSON.stringify(e,null,2)+`
|
|
3
|
+
`,"utf-8"),c;try{c=(0,m.statSync)(r).mode&511}catch{}let a;try{a=c!==void 0?(0,m.openSync)(s,"w",c):(0,m.openSync)(s,"w");let l=0;for(;l<u.length;){let E=(0,m.writeSync)(a,u,l,u.length-l);if(E===0)throw new Error(`writeSync stalled at ${l}/${u.length} bytes`);l+=E}if((0,m.fsyncSync)(a),(0,m.closeSync)(a),a=void 0,(0,m.renameSync)(s,r),!kt){let E;try{E=(0,m.openSync)(n,"r"),(0,m.fsyncSync)(E)}catch(d){let p=d instanceof Error?d:new Error(String(d));L(`claude-mem: directory fsync failed for ${n}: ${p.message}
|
|
4
|
+
`)}finally{if(E!==void 0)try{(0,m.closeSync)(E)}catch{}}}}catch(l){if(a!==void 0)try{(0,m.closeSync)(a)}catch{}try{(0,m.unlinkSync)(s)}catch{}throw l}}var Bt={};function Ht(){return typeof __dirname<"u"?__dirname:(0,g.dirname)((0,le.fileURLToPath)(Bt.url))}var Ft=Ht();function Ee(t){return typeof t!="string"||t.length===0?t:t==="~"?(0,R.homedir)():t.startsWith("~/")?(0,g.join)((0,R.homedir)(),t.slice(2)):t}function jt(){if(process.env.CLAUDE_MEM_DATA_DIR)return Ee(process.env.CLAUDE_MEM_DATA_DIR);let t=(0,g.join)((0,R.homedir)(),".claude-mem"),e=(0,g.join)(t,"settings.json");try{if((0,I.existsSync)(e)){let r=O((0,I.readFileSync)(e,"utf-8")),n=r.env??r;if(n.CLAUDE_MEM_DATA_DIR)return Ee(n.CLAUDE_MEM_DATA_DIR)}}catch{}return t}var f=jt(),J=process.env.CLAUDE_CONFIG_DIR||(0,g.join)((0,R.homedir)(),".claude"),Cr=(0,g.join)(J,"plugins","marketplaces","thedotmack"),Wt=(0,g.join)(f,"logs"),Ar=(0,g.join)(f,"settings.json"),V=(0,g.join)(f,"claude-mem.db"),Gt=(0,g.join)(f,"observer-sessions"),Dr=(0,g.basename)(Gt);function _e(){return(0,g.join)(Ft,"..")}var D={dataDir:()=>f,workerPid:()=>(0,g.join)(f,"worker.pid"),serverPid:()=>(0,g.join)(f,".server-beta.pid"),serverPort:()=>(0,g.join)(f,".server-beta.port"),serverRuntime:()=>(0,g.join)(f,".server-beta.runtime.json"),settings:()=>(0,g.join)(f,"settings.json"),database:()=>(0,g.join)(f,"claude-mem.db"),chroma:()=>(0,g.join)(f,"chroma"),combinedCerts:()=>(0,g.join)(f,"combined_certs.pem"),transcriptsConfig:()=>(0,g.join)(f,"transcript-watch.json"),transcriptsState:()=>(0,g.join)(f,"transcript-watch-state.json"),corpora:()=>(0,g.join)(f,"corpora"),supervisorRegistry:()=>(0,g.join)(f,"supervisor.json"),envFile:()=>(0,g.join)(f,".env"),logsDir:()=>Wt};var C=require("fs"),me=require("path");var z=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.WARN=2]="WARN",s[s.ERROR=3]="ERROR",s[s.SILENT=4]="SILENT",s))(z||{}),q=null,Q=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){if(!this.logFileInitialized){this.logFileInitialized=!0;try{let e=D.logsDir();(0,C.existsSync)(e)||(0,C.mkdirSync)(e,{recursive:!0});let r=new Date().toISOString().split("T")[0];this.logFilePath=(0,me.join)(e,`claude-mem-${r}.log`)}catch(e){console.error("[LOGGER] Failed to initialize log file:",e instanceof Error?e.message:String(e)),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let e=D.settings();if((0,C.existsSync)(e)){let r=(0,C.readFileSync)(e,"utf-8"),o=(O(r).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=z[o]??1}else this.level=1}catch(e){console.error("[LOGGER] Failed to load log level from settings:",e instanceof Error?e.message:String(e)),this.level=1}return this.level}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.getLevel()===0?`${e.message}
|
|
5
|
+
${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let r=Object.keys(e);return r.length===0?"{}":r.length<=3?JSON.stringify(e):`{${r.length} keys: ${r.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,r){if(!r)return e;let n=r;if(typeof r=="string")try{n=JSON.parse(r)}catch{n=r}if(e==="Bash"&&n.command)return`${e}(${n.command})`;if(n.file_path)return`${e}(${n.file_path})`;if(n.notebook_path)return`${e}(${n.notebook_path})`;if(e==="Glob"&&n.pattern)return`${e}(${n.pattern})`;if(e==="Grep"&&n.pattern)return`${e}(${n.pattern})`;if(n.url)return`${e}(${n.url})`;if(n.query)return`${e}(${n.query})`;if(e==="Task"){if(n.subagent_type)return`${e}(${n.subagent_type})`;if(n.description)return`${e}(${n.description})`}return e==="Skill"&&n.skill?`${e}(${n.skill})`:e==="LSP"&&n.operation?`${e}(${n.operation})`:e}formatTimestamp(e){let r=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0"),s=String(e.getHours()).padStart(2,"0"),u=String(e.getMinutes()).padStart(2,"0"),c=String(e.getSeconds()).padStart(2,"0"),a=String(e.getMilliseconds()).padStart(3,"0");return`${r}-${n}-${o} ${s}:${u}:${c}.${a}`}log(e,r,n,o,s){if(e<this.getLevel())return;this.ensureLogFileInitialized();let u=this.formatTimestamp(new Date),c=z[e].padEnd(5),a=r.padEnd(6),l="";o?.correlationId?l=`[${o.correlationId}] `:o?.sessionId&&(l=`[session-${o.sessionId}] `);let E="";if(s!=null)if(s instanceof Error)E=this.getLevel()===0?`
|
|
6
6
|
${s.message}
|
|
7
7
|
${s.stack}`:` ${s.message}`;else if(this.getLevel()===0&&typeof s=="object")try{E=`
|
|
8
|
-
`+JSON.stringify(s,null,2)}catch{E=" "+this.formatData(s)}else E=" "+this.formatData(s);let
|
|
9
|
-
`,"utf8")}catch(S){let A=S instanceof Error?S:new Error(String(S));
|
|
8
|
+
`+JSON.stringify(s,null,2)}catch{E=" "+this.formatData(s)}else E=" "+this.formatData(s);let d="";if(o){let{sessionId:S,memorySessionId:A,correlationId:ie,...ae}=o;Object.keys(ae).length>0&&(d=` {${Object.entries(ae).map(([Ot,yt])=>`${Ot}=${yt}`).join(", ")}}`)}let p=`[${u}] [${c}] [${a}] ${l}${n}${d}${E}`;if(this.logFilePath)try{(0,C.appendFileSync)(this.logFilePath,p+`
|
|
9
|
+
`,"utf8")}catch(S){let A=S instanceof Error?S:new Error(String(S));L(`[LOGGER] Failed to write to log file: ${A.message}
|
|
10
10
|
${A.stack??""}
|
|
11
|
-
`)}else
|
|
12
|
-
`)}debug(e,r,n,o){this.log(0,e,r,n,o)}info(e,r,n,o){this.log(1,e,r,n,o)}warn(e,r,n,o){this.log(2,e,r,n,o)}setErrorSink(e){q=e}error(e,r,n,o){this.log(3,e,r,n,o),this.routeErrorToSink(r,n,o)}routeErrorToSink(e,r,n){try{if(!q||!(n instanceof Error))return;q(n)}catch{}}dataIn(e,r,n,o){this.info(e,`\u2192 ${r}`,n,o)}dataOut(e,r,n,o){this.info(e,`\u2190 ${r}`,n,o)}success(e,r,n,o){this.info(e,`\u2713 ${r}`,n,o)}failure(e,r,n,o){this.error(e,`\u2717 ${r}`,n,o)}},_=new Q;var pe=require("os"),de=y(require("path"),1),fe=require("child_process");var w=require("fs"),O=y(require("path"),1);var I={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function ge(t){let e=O.default.join(t,".git"),r;try{r=(0,w.statSync)(e)}catch(E){return E instanceof Error&&E.code!=="ENOENT"&&_.warn("GIT","Unexpected error checking .git",{error:E instanceof Error?E.message:String(E)}),I}if(!r.isFile())return I;let n;try{n=(0,w.readFileSync)(e,"utf-8").trim()}catch(E){return _.warn("GIT","Failed to read .git file",{error:E instanceof Error?E.message:String(E)}),I}let o=n.match(/^gitdir:\s*(.+)$/);if(!o)return I;let u=O.default.resolve(O.default.dirname(e),o[1]).match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!u)return I;let c=u[1],i=O.default.basename(t),l=O.default.basename(c);return{isWorktree:!0,worktreeName:i,parentRepoPath:c,parentProjectName:l}}function Me(t){return t==="~"||t.startsWith("~/")?t.replace(/^~/,(0,pe.homedir)()):t}function Se(t){try{return(0,fe.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim()||null}catch(e){let r=e instanceof Error?e:new Error(String(e));return _.debug("PROJECT_NAME","git rev-parse failed, falling back to basename",{dir:t},r),null}}function Gt(t){if(!t||t.trim()==="")return _.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),"unknown-project";let e=Me(t),n=Se(e)??e,o=de.default.basename(n);if(o===""){if(process.platform==="win32"){let u=t.match(/^([A-Z]):\\/i);if(u){let i=`drive-${u[1].toUpperCase()}`;return _.info("PROJECT_NAME","Drive root detected",{cwd:t,projectName:i}),i}}return _.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:t}),"unknown-project"}return o}function Te(t){let e=Gt(t);if(!t)return{primary:e,parent:null,isWorktree:!1,allProjects:[e]};let r=Me(t),n=ge(Se(r)??r);if(n.isWorktree&&n.parentProjectName){let o=`${n.parentProjectName}/${e}`;return{primary:o,parent:n.parentProjectName,isWorktree:!0,allProjects:[n.parentProjectName,o]}}return{primary:e,parent:null,isWorktree:!1,allProjects:[e]}}var Ce="claude";function Bt(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Ae(t){if(!t)return Ce;let e=Bt(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:Ce}var Kt=require("bun:sqlite");var De=5e3;var F=require("fs"),ee=require("path"),b=require("os");var Z={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};function Le(t){return process.platform==="win32"?Math.round(t*Z.WINDOWS_MULTIPLIER):t}var Yt="security_alert",H=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(Le(Z.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:(0,ee.join)((0,b.homedir)(),".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:(0,ee.join)((0,b.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_CHROMA_MAX_PENDING_MUTATIONS:"5000",CLAUDE_MEM_CLOUD_SYNC_TOKEN:"",CLAUDE_MEM_CLOUD_SYNC_USER_ID:"",CLAUDE_MEM_CLOUD_SYNC_HUB_URL:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_ID:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_NAME:(0,b.hostname)(),CLAUDE_MEM_CLOUD_SYNC_WS:"true",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert,sensitive",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let r=this.get(e);return parseInt(r,10)}static applyEnvOverrides(e){let r={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(r[n]=process.env[n]);return r}static loadFromFile(e,r=!0){try{if(!(0,F.existsSync)(e)){let c=this.getAllDefaults();try{P(e,c),console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(i){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,i instanceof Error?i.message:String(i))}return r?this.applyEnvOverrides(c):c}let n=(0,F.readFileSync)(e,"utf-8"),o=L(n),s=o;if(o.env&&typeof o.env=="object"){s=o.env;try{P(e,s),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(c){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,c instanceof Error?c.message:String(c))}}if(s.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES===Yt){s={...s,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES};try{P(e,s),console.warn("[SETTINGS] Migrated Telegram trigger types off the legacy default:",e)}catch(c){console.warn("[SETTINGS] Failed to migrate Telegram trigger types:",e,c instanceof Error?c.message:String(c))}}let u={...this.DEFAULTS};for(let c of Object.keys(this.DEFAULTS))s[c]!==void 0&&(u[c]=s[c]);return r?this.applyEnvOverrides(u):u}catch(n){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,n instanceof Error?n.message:String(n));let o=this.getAllDefaults();return r?this.applyEnvOverrides(o):o}}};var v=require("fs"),W=require("path");var M=class t{static instance=null;activeMode=null;modesDir;constructor(){let e=_e(),r=[...process.env.CLAUDE_MEM_MODES_DIR?[process.env.CLAUDE_MEM_MODES_DIR]:[],(0,W.join)(e,"modes"),(0,W.join)(e,"..","plugin","modes")],n=r.find(o=>(0,v.existsSync)(o));this.modesDir=n||r[0]}static getInstance(){return t.instance||(t.instance=new t),t.instance}parseInheritance(e){let r=e.split("--");if(r.length===1)return{hasParent:!1,parentId:"",overrideId:""};if(r.length>2)throw new Error(`Invalid mode inheritance: ${e}. Only one level of inheritance supported (parent--override)`);return{hasParent:!0,parentId:r[0],overrideId:e}}isPlainObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}deepMerge(e,r){let n={...e};for(let o in r){let s=r[o],u=e[o];this.isPlainObject(s)&&this.isPlainObject(u)?n[o]=this.deepMerge(u,s):n[o]=s}return n}loadModeFile(e){let r=(0,W.join)(this.modesDir,`${e}.json`);if(!(0,v.existsSync)(r))throw new Error(`Mode file not found: ${r}`);let n=(0,v.readFileSync)(r,"utf-8");return JSON.parse(n)}loadMode(e){let r=this.parseInheritance(e);if(!r.hasParent)try{let i=this.loadModeFile(e);return this.activeMode=i,_.debug("SYSTEM",`Loaded mode: ${i.name} (${e})`,void 0,{types:i.observation_types.map(l=>l.id),concepts:i.observation_concepts.map(l=>l.id)}),i}catch(i){if(i instanceof Error?_.warn("WORKER",`Mode file not found: ${e}, falling back to 'code'`,{message:i.message}):_.warn("WORKER",`Mode file not found: ${e}, falling back to 'code'`,{error:String(i)}),e==="code")throw new Error("Critical: code.json mode file missing");return this.loadMode("code")}let{parentId:n,overrideId:o}=r,s;try{s=this.loadMode(n)}catch(i){i instanceof Error?_.warn("WORKER",`Parent mode '${n}' not found for ${e}, falling back to 'code'`,{message:i.message}):_.warn("WORKER",`Parent mode '${n}' not found for ${e}, falling back to 'code'`,{error:String(i)}),s=this.loadMode("code")}let u;try{u=this.loadModeFile(o),_.debug("SYSTEM",`Loaded override file: ${o} for parent ${n}`)}catch(i){return i instanceof Error?_.warn("WORKER",`Override file '${o}' not found, using parent mode '${n}' only`,{message:i.message}):_.warn("WORKER",`Override file '${o}' not found, using parent mode '${n}' only`,{error:String(i)}),this.activeMode=s,s}if(!u)return _.warn("SYSTEM",`Invalid override file: ${o}, using parent mode '${n}' only`),this.activeMode=s,s;let c=this.deepMerge(s,u);return this.activeMode=c,_.debug("SYSTEM",`Loaded mode with inheritance: ${c.name} (${e} = ${n} + ${o})`,void 0,{parent:n,override:o,types:c.observation_types.map(i=>i.id),concepts:c.observation_concepts.map(i=>i.id)}),c}getActiveMode(){if(!this.activeMode)throw new Error("No mode loaded. Call loadMode() first.");return this.activeMode}getObservationTypes(){return this.getActiveMode().observation_types}getTypeIcon(e){return this.getObservationTypes().find(n=>n.id===e)?.emoji||"\u{1F4DD}"}getWorkEmoji(e){return this.getObservationTypes().find(n=>n.id===e)?.work_emoji||"\u{1F4DD}"}};function Oe(){let t=U.settings(),e=H.loadFromFile(t),r=M.getInstance().getActiveMode(),n=new Set(r.observation_types.map(s=>s.id)),o=new Set(r.observation_concepts.map(s=>s.id));return{totalObservationCount:parseInt(e.CLAUDE_MEM_CONTEXT_OBSERVATIONS,10),fullObservationCount:parseInt(e.CLAUDE_MEM_CONTEXT_FULL_COUNT,10),sessionCount:parseInt(e.CLAUDE_MEM_CONTEXT_SESSION_COUNT,10),showReadTokens:e.CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS==="true",showWorkTokens:e.CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS==="true",showSavingsAmount:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT==="true",showSavingsPercent:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT==="true",observationTypes:n,observationConcepts:o,fullObservationField:e.CLAUDE_MEM_CONTEXT_FULL_FIELD,showLastSummary:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY==="true",showLastMessage:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE==="true"}}var a={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",cyan:"\x1B[36m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",gray:"\x1B[90m",red:"\x1B[31m"},ye=4,he=1;function Re(t){let e=(t.title?.length||0)+(t.subtitle?.length||0)+(t.narrative?.length||0)+JSON.stringify(t.facts||[]).length;return Math.ceil(e/ye)}function te(t){let e=t.length,r=t.reduce((u,c)=>u+Re(c),0),n=t.reduce((u,c)=>u+(c.discovery_tokens||0),0),o=n-r,s=n>0?Math.round(o/n*100):0;return{totalObservations:e,totalReadTokens:r,totalDiscoveryTokens:n,savings:o,savingsPercent:s}}function Xt(t){return M.getInstance().getWorkEmoji(t)}function N(t,e){let r=Re(t),n=t.discovery_tokens||0,o=Xt(t.type),s=n>0?`${o} ${n.toLocaleString()}`:"-";return{readTokens:r,discoveryTokens:n,discoveryDisplay:s,workEmoji:o}}function j(t){return t.showReadTokens||t.showWorkTokens||t.showSavingsAmount||t.showSavingsPercent}var Ie=y(require("path"),1),G=require("fs");var Jt=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],qr=new RegExp(`<(${Jt.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g"),Ue=/<system-reminder>[\s\S]*?<\/system-reminder>/g;var Vt=["task-notification"],zr=new RegExp(`^\\s*<(${Vt.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),Qr=256*1024;function be(t,e,r,n){let o=Array.from(r.observationTypes),s=o.map(()=>"?").join(","),u=Array.from(r.observationConcepts),c=u.map(()=>"?").join(","),i=e.map(()=>"?").join(",");return t.db.prepare(`
|
|
11
|
+
`)}else L(p+`
|
|
12
|
+
`)}debug(e,r,n,o){this.log(0,e,r,n,o)}info(e,r,n,o){this.log(1,e,r,n,o)}warn(e,r,n,o){this.log(2,e,r,n,o)}setErrorSink(e){q=e}error(e,r,n,o){this.log(3,e,r,n,o),this.routeErrorToSink(r,n,o)}routeErrorToSink(e,r,n){try{if(!q||!(n instanceof Error))return;q(n)}catch{}}dataIn(e,r,n,o){this.info(e,`\u2192 ${r}`,n,o)}dataOut(e,r,n,o){this.info(e,`\u2190 ${r}`,n,o)}success(e,r,n,o){this.info(e,`\u2713 ${r}`,n,o)}failure(e,r,n,o){this.error(e,`\u2717 ${r}`,n,o)}},_=new Q;var de=require("os"),pe=h(require("path"),1),fe=require("child_process");var w=require("fs"),y=h(require("path"),1);var U={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function ge(t){let e=y.default.join(t,".git"),r;try{r=(0,w.statSync)(e)}catch(E){return E instanceof Error&&E.code!=="ENOENT"&&_.warn("GIT","Unexpected error checking .git",{error:E instanceof Error?E.message:String(E)}),U}if(!r.isFile())return U;let n;try{n=(0,w.readFileSync)(e,"utf-8").trim()}catch(E){return _.warn("GIT","Failed to read .git file",{error:E instanceof Error?E.message:String(E)}),U}let o=n.match(/^gitdir:\s*(.+)$/);if(!o)return U;let u=y.default.resolve(y.default.dirname(e),o[1]).match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!u)return U;let c=u[1],a=y.default.basename(t),l=y.default.basename(c);return{isWorktree:!0,worktreeName:a,parentRepoPath:c,parentProjectName:l}}function Me(t){return t==="~"||t.startsWith("~/")?t.replace(/^~/,(0,de.homedir)()):t}function Se(t){try{return(0,fe.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim()||null}catch(e){let r=e instanceof Error?e:new Error(String(e));return _.debug("PROJECT_NAME","git rev-parse failed, falling back to basename",{dir:t},r),null}}function Kt(t){if(!t||t.trim()==="")return _.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),"unknown-project";let e=Me(t),n=Se(e)??e,o=pe.default.basename(n);if(o===""){if(process.platform==="win32"){let u=t.match(/^([A-Z]):\\/i);if(u){let a=`drive-${u[1].toUpperCase()}`;return _.info("PROJECT_NAME","Drive root detected",{cwd:t,projectName:a}),a}}return _.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:t}),"unknown-project"}return o}function Te(t){let e=Kt(t);if(!t)return{primary:e,parent:null,isWorktree:!1,allProjects:[e]};let r=Me(t),n=ge(Se(r)??r);if(n.isWorktree&&n.parentProjectName){let o=`${n.parentProjectName}/${e}`;return{primary:o,parent:n.parentProjectName,isWorktree:!0,allProjects:[n.parentProjectName,o]}}return{primary:e,parent:null,isWorktree:!1,allProjects:[e]}}var Ce="claude";function Yt(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Ae(t){if(!t)return Ce;let e=Yt(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:Ce}var Xt=require("bun:sqlite");var De=5e3;var F=require("fs"),ee=require("path"),v=require("os");var Z={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};function Le(t){return process.platform==="win32"?Math.round(t*Z.WINDOWS_MULTIPLIER):t}var Jt="security_alert",H=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(Le(Z.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:(0,ee.join)((0,v.homedir)(),".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:(0,ee.join)((0,v.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_CHROMA_MAX_PENDING_MUTATIONS:"5000",CLAUDE_MEM_CLOUD_SYNC_TOKEN:"",CLAUDE_MEM_CLOUD_SYNC_USER_ID:"",CLAUDE_MEM_CLOUD_SYNC_HUB_URL:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_ID:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_NAME:(0,v.hostname)(),CLAUDE_MEM_CLOUD_SYNC_WS:"true",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert,sensitive",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let r=this.get(e);return parseInt(r,10)}static applyEnvOverrides(e){let r={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(r[n]=process.env[n]);return r}static loadFromFile(e,r=!0){try{if(!(0,F.existsSync)(e)){let c=this.getAllDefaults();try{P(e,c),console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(a){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,a instanceof Error?a.message:String(a))}return r?this.applyEnvOverrides(c):c}let n=(0,F.readFileSync)(e,"utf-8"),o=O(n),s=o;if(o.env&&typeof o.env=="object"){s=o.env;try{P(e,s),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(c){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,c instanceof Error?c.message:String(c))}}if(s.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES===Jt){s={...s,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES};try{P(e,s),console.warn("[SETTINGS] Migrated Telegram trigger types off the legacy default:",e)}catch(c){console.warn("[SETTINGS] Failed to migrate Telegram trigger types:",e,c instanceof Error?c.message:String(c))}}let u={...this.DEFAULTS};for(let c of Object.keys(this.DEFAULTS))s[c]!==void 0&&(u[c]=s[c]);return r?this.applyEnvOverrides(u):u}catch(n){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,n instanceof Error?n.message:String(n));let o=this.getAllDefaults();return r?this.applyEnvOverrides(o):o}}};var j=require("fs"),b=require("path");var Vt=/^[a-z0-9]+(?:-[a-z0-9]+)*(?:--[a-z0-9]+(?:-[a-z0-9]+)*)?$/,M=class t{static instance=null;activeMode=null;activeModeId=null;modeDirs;constructor(){let e=_e(),r=[...process.env.CLAUDE_MEM_MODES_DIR?[process.env.CLAUDE_MEM_MODES_DIR]:[],(0,b.join)(D.dataDir(),"modes"),(0,b.join)(e,"modes"),(0,b.join)(e,"..","plugin","modes")];this.modeDirs=[...new Set(r)]}static getInstance(){return t.instance||(t.instance=new t),t.instance}parseInheritance(e){let r=e.split("--");if(r.length===1)return{hasParent:!1,parentId:"",overrideId:""};if(r.length>2)throw new Error(`Invalid mode inheritance: ${e}. Only one level of inheritance supported (parent--override)`);return{hasParent:!0,parentId:r[0],overrideId:e}}isPlainObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}deepMerge(e,r){let n={...e};for(let o in r){let s=r[o],u=e[o];this.isPlainObject(s)&&this.isPlainObject(u)?n[o]=this.deepMerge(u,s):n[o]=s}return n}loadModeFile(e){if(!Vt.test(e))throw new Error(`Invalid mode ID: ${e}`);let r=this.modeDirs.map(o=>(0,b.join)(o,`${e}.json`)).find(o=>(0,j.existsSync)(o));if(!r)throw new Error(`Mode file not found: ${e}.json (searched: ${this.modeDirs.join(", ")})`);let n=(0,j.readFileSync)(r,"utf-8");return JSON.parse(n)}loadMode(e){let r=this.parseInheritance(e);if(!r.hasParent)try{let a=this.loadModeFile(e);return this.activeMode=a,this.activeModeId=e,_.debug("SYSTEM",`Loaded mode: ${a.name} (${e})`,void 0,{types:a.observation_types.map(l=>l.id),concepts:a.observation_concepts.map(l=>l.id)}),a}catch(a){if(a instanceof Error?_.warn("WORKER",`Mode file not found: ${e}, falling back to 'code'`,{message:a.message}):_.warn("WORKER",`Mode file not found: ${e}, falling back to 'code'`,{error:String(a)}),e==="code")throw new Error("Critical: code.json mode file missing");return this.loadMode("code")}let{parentId:n,overrideId:o}=r,s;try{s=this.loadMode(n)}catch(a){a instanceof Error?_.warn("WORKER",`Parent mode '${n}' not found for ${e}, falling back to 'code'`,{message:a.message}):_.warn("WORKER",`Parent mode '${n}' not found for ${e}, falling back to 'code'`,{error:String(a)}),s=this.loadMode("code")}let u;try{u=this.loadModeFile(o),_.debug("SYSTEM",`Loaded override file: ${o} for parent ${n}`)}catch(a){return a instanceof Error?_.warn("WORKER",`Override file '${o}' not found, using parent mode '${n}' only`,{message:a.message}):_.warn("WORKER",`Override file '${o}' not found, using parent mode '${n}' only`,{error:String(a)}),this.activeMode=s,s}if(!u)return _.warn("SYSTEM",`Invalid override file: ${o}, using parent mode '${n}' only`),this.activeMode=s,s;let c=this.deepMerge(s,u);return this.activeMode=c,this.activeModeId=e,_.debug("SYSTEM",`Loaded mode with inheritance: ${c.name} (${e} = ${n} + ${o})`,void 0,{parent:n,override:o,types:c.observation_types.map(a=>a.id),concepts:c.observation_concepts.map(a=>a.id)}),c}getActiveMode(){if(!this.activeMode)throw new Error("No mode loaded. Call loadMode() first.");return this.activeMode}getActiveModeId(){if(!this.activeModeId)throw new Error("No mode loaded. Call loadMode() first.");return this.activeModeId}getObservationTypes(){return this.getActiveMode().observation_types}getTypeIcon(e){return this.getObservationTypes().find(n=>n.id===e)?.emoji||"\u{1F4DD}"}getWorkEmoji(e){return this.getObservationTypes().find(n=>n.id===e)?.work_emoji||"\u{1F4DD}"}};function Oe(){let t=D.settings(),e=H.loadFromFile(t),r=M.getInstance().getActiveMode(),n=new Set(r.observation_types.map(s=>s.id)),o=new Set(r.observation_concepts.map(s=>s.id));return{totalObservationCount:parseInt(e.CLAUDE_MEM_CONTEXT_OBSERVATIONS,10),fullObservationCount:parseInt(e.CLAUDE_MEM_CONTEXT_FULL_COUNT,10),sessionCount:parseInt(e.CLAUDE_MEM_CONTEXT_SESSION_COUNT,10),showReadTokens:e.CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS==="true",showWorkTokens:e.CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS==="true",showSavingsAmount:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT==="true",showSavingsPercent:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT==="true",observationTypes:n,observationConcepts:o,fullObservationField:e.CLAUDE_MEM_CONTEXT_FULL_FIELD,showLastSummary:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY==="true",showLastMessage:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE==="true"}}var i={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",cyan:"\x1B[36m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",gray:"\x1B[90m",red:"\x1B[31m"},ye=4,he=1;function Re(t){let e=(t.title?.length||0)+(t.subtitle?.length||0)+(t.narrative?.length||0)+JSON.stringify(t.facts||[]).length;return Math.ceil(e/ye)}function te(t){let e=t.length,r=t.reduce((u,c)=>u+Re(c),0),n=t.reduce((u,c)=>u+(c.discovery_tokens||0),0),o=n-r,s=n>0?Math.round(o/n*100):0;return{totalObservations:e,totalReadTokens:r,totalDiscoveryTokens:n,savings:o,savingsPercent:s}}function qt(t){return M.getInstance().getWorkEmoji(t)}function N(t,e){let r=Re(t),n=t.discovery_tokens||0,o=qt(t.type),s=n>0?`${o} ${n.toLocaleString()}`:"-";return{readTokens:r,discoveryTokens:n,discoveryDisplay:s,workEmoji:o}}function W(t){return t.showReadTokens||t.showWorkTokens||t.showSavingsAmount||t.showSavingsPercent}var Ue=h(require("path"),1),G=require("fs");var zt=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],Zr=new RegExp(`<(${zt.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g"),Ie=/<system-reminder>[\s\S]*?<\/system-reminder>/g;var Qt=["task-notification"],en=new RegExp(`^\\s*<(${Qt.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),tn=256*1024;function ve(t,e,r,n){let o=Array.from(r.observationTypes),s=o.map(()=>"?").join(","),u=Array.from(r.observationConcepts),c=u.map(()=>"?").join(","),a=e.map(()=>"?").join(",");return t.db.prepare(`
|
|
13
13
|
SELECT
|
|
14
14
|
o.id,
|
|
15
15
|
o.memory_session_id,
|
|
@@ -28,8 +28,8 @@ ${A.stack??""}
|
|
|
28
28
|
o.project
|
|
29
29
|
FROM observations o
|
|
30
30
|
LEFT JOIN sdk_sessions s ON o.memory_session_id = s.memory_session_id
|
|
31
|
-
WHERE (o.project IN (${
|
|
32
|
-
OR o.merged_into_project IN (${
|
|
31
|
+
WHERE (o.project IN (${a})
|
|
32
|
+
OR o.merged_into_project IN (${a}))
|
|
33
33
|
AND (? IS NULL OR s.platform_source = ?)
|
|
34
34
|
AND type IN (${s})
|
|
35
35
|
AND EXISTS (
|
|
@@ -38,7 +38,7 @@ ${A.stack??""}
|
|
|
38
38
|
)
|
|
39
39
|
ORDER BY o.created_at_epoch DESC
|
|
40
40
|
LIMIT ?
|
|
41
|
-
`).all(...e,...e,n??null,n??null,...o,...u,r.totalObservationCount)}function
|
|
41
|
+
`).all(...e,...e,n??null,n??null,...o,...u,r.totalObservationCount)}function be(t,e,r,n){let o=e.map(()=>"?").join(",");return t.db.prepare(`
|
|
42
42
|
SELECT
|
|
43
43
|
ss.id,
|
|
44
44
|
ss.memory_session_id,
|
|
@@ -58,14 +58,16 @@ ${A.stack??""}
|
|
|
58
58
|
AND (? IS NULL OR s.platform_source = ?)
|
|
59
59
|
ORDER BY ss.created_at_epoch DESC
|
|
60
60
|
LIMIT ?
|
|
61
|
-
`).all(...e,...e,n??null,n??null,r.sessionCount+he)}function
|
|
62
|
-
`).filter(o=>o.trim());return{assistantMessage:
|
|
61
|
+
`).all(...e,...e,n??null,n??null,r.sessionCount+he)}function Zt(t){return t.replace(/[/.]/g,"-")}function er(t){if(!t.includes('"type":"assistant"'))return null;let e=JSON.parse(t);if(e.type==="assistant"&&e.message?.content&&Array.isArray(e.message.content)){let r="";for(let n of e.message.content)n.type==="text"&&(r+=n.text);if(r=r.replace(Ie,"").trim(),r)return r}return null}function tr(t){for(let e=t.length-1;e>=0;e--)try{let r=er(t[e]);if(r)return r}catch(r){r instanceof Error?_.debug("WORKER","Skipping malformed transcript line",{lineIndex:e},r):_.debug("WORKER","Skipping malformed transcript line",{lineIndex:e,error:String(r)});continue}return""}function rr(t){try{if(!(0,G.existsSync)(t))return{assistantMessage:""};let e=(0,G.readFileSync)(t,"utf-8").trim();if(!e)return{assistantMessage:""};let r=e.split(`
|
|
62
|
+
`).filter(o=>o.trim());return{assistantMessage:tr(r)}}catch(e){return e instanceof Error?_.failure("WORKER","Failed to extract prior messages from transcript",{transcriptPath:t},e):_.warn("WORKER","Failed to extract prior messages from transcript",{transcriptPath:t,error:String(e)}),{assistantMessage:""}}}function Ne(t,e,r,n){if(!e.showLastMessage||t.length===0)return{assistantMessage:""};let o=t.find(a=>a.memory_session_id!==r);if(!o)return{assistantMessage:""};let s=o.memory_session_id,u=Zt(n),c=Ue.default.join(J,"projects",u,`${s}.jsonl`);return rr(c)}function xe(t,e){let r=e[0]?.id;return t.map((n,o)=>{let s=o===0?null:e[o+1];return{...n,displayEpoch:s?s.created_at_epoch:n.created_at_epoch,displayTime:s?s.created_at:n.created_at,shouldShowLink:n.id!==r}})}function $e(t,e){let r=[...t.map(n=>({type:"observation",data:n})),...e.map(n=>({type:"summary",data:n}))];return r.sort((n,o)=>{let s=n.type==="observation"?n.data.created_at_epoch:n.data.displayEpoch,u=o.type==="observation"?o.data.created_at_epoch:o.data.displayEpoch;return s-u}),r}function ke(t,e){return new Set(t.slice(0,e).map(r=>r.id))}function Pe(){let t=new Date,e=t.toLocaleDateString("en-CA"),r=t.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}).toLowerCase().replace(" ",""),n=t.toLocaleTimeString("en-US",{timeZoneName:"short"}).split(" ").pop();return`${e} ${r} ${n}`}function we(){let t=M.getInstance();return`${t.getActiveMode().name} (${t.getActiveModeId()})`}function He(t){return[`# [${t}] recent context, ${Pe()}`,`Mode: ${we()}`,""]}function Fe(){return[`Legend: \u{1F3AF}session ${M.getInstance().getActiveMode().observation_types.map(r=>`${r.emoji}${r.id}`).join(" ")}`,"Format: ID TIME TYPE TITLE","Fetch details: get_observations([IDs]) | Search: mem-search skill",""]}function je(t,e){let r=[],n=[`${t.totalObservations} obs (${t.totalReadTokens.toLocaleString()}t read)`,`${t.totalDiscoveryTokens.toLocaleString()}t work`];return t.totalDiscoveryTokens>0&&(e.showSavingsAmount||e.showSavingsPercent)&&(e.showSavingsPercent?n.push(`${t.savingsPercent}% savings`):e.showSavingsAmount&&n.push(`${t.savings.toLocaleString()}t saved`)),r.push(`Stats: ${n.join(" | ")}`),r.push(""),r}function We(t){return[`### ${t}`]}function Ge(t){return t.toLowerCase().replace(" am","a").replace(" pm","p")}function Be(t,e,r){let n=t.title||"Untitled",o=M.getInstance().getTypeIcon(t.type),s=e?Ge(e):'"';return`${t.id} ${s} ${o} ${n}`}function Ke(t,e,r,n){let o=[],s=t.title||"Untitled",u=M.getInstance().getTypeIcon(t.type),c=e?Ge(e):'"',{readTokens:a,discoveryDisplay:l}=N(t,n);o.push(`**${t.id}** ${c} ${u} **${s}**`),r&&o.push(r);let E=[];return n.showReadTokens&&E.push(`~${a}t`),n.showWorkTokens&&E.push(l),E.length>0&&o.push(E.join(" ")),o.push(""),o}function Ye(t,e){return[`S${t.id} ${t.request||"Session started"} (${e})`]}function x(t,e){return e?[`**${t}**: ${e}`,""]:[]}function Xe(t){return t.assistantMessage?["","---","","**Previously**","",`A: ${t.assistantMessage}`,""]:[]}function Je(t,e){return["",`Access ${Math.round(t/1e3)}k tokens of past work via get_observations([IDs]) or mem-search skill.`]}function Ve(t){return`# [${t}] recent context, ${Pe()}
|
|
63
|
+
Mode: ${we()}
|
|
63
64
|
|
|
64
|
-
No previous sessions found.`}function
|
|
65
|
-
${
|
|
66
|
-
${
|
|
65
|
+
No previous sessions found.`}function qe(){let t=new Date,e=t.toLocaleDateString("en-CA"),r=t.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}).toLowerCase().replace(" ",""),n=t.toLocaleTimeString("en-US",{timeZoneName:"short"}).split(" ").pop();return`${e} ${r} ${n}`}function ze(){let t=M.getInstance();return`${t.getActiveMode().name} (${t.getActiveModeId()})`}function Qe(t){return["",`${i.bright}${i.cyan}[${t}] recent context, ${qe()}${i.reset}`,`${i.dim}Mode: ${ze()}${i.reset}`,`${i.gray}${"\u2500".repeat(60)}${i.reset}`,""]}function Ze(){let e=M.getInstance().getActiveMode().observation_types.map(r=>`${r.emoji} ${r.id}`).join(" | ");return[`${i.dim}Legend: session-request | ${e}${i.reset}`,""]}function et(){return[`${i.bright}Column Key${i.reset}`,`${i.dim} Read: Tokens to read this observation (cost to learn it now)${i.reset}`,`${i.dim} Work: Tokens spent on work that produced this record ( research, building, deciding)${i.reset}`,""]}function tt(){return[`${i.dim}Context Index: This semantic index (titles, types, files, tokens) is usually sufficient to understand past work.${i.reset}`,"",`${i.dim}When you need implementation details, rationale, or debugging context:${i.reset}`,`${i.dim} - Fetch by ID: get_observations([IDs]) for observations visible in this index${i.reset}`,`${i.dim} - Search history: Use the mem-search skill for past decisions, bugs, and deeper research${i.reset}`,`${i.dim} - Trust this index over re-reading code for past decisions and learnings${i.reset}`,""]}function rt(t,e){let r=[];if(r.push(`${i.bright}${i.cyan}Context Economics${i.reset}`),r.push(`${i.dim} Loading: ${t.totalObservations} observations (${t.totalReadTokens.toLocaleString()} tokens to read)${i.reset}`),r.push(`${i.dim} Work investment: ${t.totalDiscoveryTokens.toLocaleString()} tokens spent on research, building, and decisions${i.reset}`),t.totalDiscoveryTokens>0&&(e.showSavingsAmount||e.showSavingsPercent)){let n=" Your savings: ";e.showSavingsAmount&&e.showSavingsPercent?n+=`${t.savings.toLocaleString()} tokens (${t.savingsPercent}% reduction from reuse)`:e.showSavingsAmount?n+=`${t.savings.toLocaleString()} tokens`:n+=`${t.savingsPercent}% reduction from reuse`,r.push(`${i.green}${n}${i.reset}`)}return r.push(""),r}function nt(t){return[`${i.bright}${i.cyan}${t}${i.reset}`,""]}function ot(t){return[`${i.dim}${t}${i.reset}`]}function st(t,e,r,n){let o=t.title||"Untitled",s=M.getInstance().getTypeIcon(t.type),{readTokens:u,discoveryTokens:c,workEmoji:a}=N(t,n),l=r?`${i.dim}${e}${i.reset}`:" ".repeat(e.length),E=n.showReadTokens&&u>0?`${i.dim}(~${u}t)${i.reset}`:"",d=n.showWorkTokens&&c>0?`${i.dim}(${a} ${c.toLocaleString()}t)${i.reset}`:"";return` ${i.dim}#${t.id}${i.reset} ${l} ${s} ${o} ${E} ${d}`}function it(t,e,r,n,o){let s=[],u=t.title||"Untitled",c=M.getInstance().getTypeIcon(t.type),{readTokens:a,discoveryTokens:l,workEmoji:E}=N(t,o),d=r?`${i.dim}${e}${i.reset}`:" ".repeat(e.length),p=o.showReadTokens&&a>0?`${i.dim}(~${a}t)${i.reset}`:"",S=o.showWorkTokens&&l>0?`${i.dim}(${E} ${l.toLocaleString()}t)${i.reset}`:"";return s.push(` ${i.dim}#${t.id}${i.reset} ${d} ${c} ${i.bright}${u}${i.reset}`),n&&s.push(` ${i.dim}${n}${i.reset}`),(p||S)&&s.push(` ${p} ${S}`),s.push(""),s}function at(t,e){let r=`${t.request||"Session started"} (${e})`;return[`${i.yellow}#S${t.id}${i.reset} ${r}`,""]}function $(t,e,r){return e?[`${r}${t}:${i.reset} ${e}`,""]:[]}function ct(t){return t.assistantMessage?["","---","",`${i.bright}${i.magenta}Previously${i.reset}`,"",`${i.dim}A: ${t.assistantMessage}${i.reset}`,""]:[]}function ut(t,e){let r=Math.round(t/1e3);return["",`${i.dim}Access ${r}k tokens of past research & decisions for just ${e.toLocaleString()}t. Use the claude-mem skill to access memories by ID.${i.reset}`]}function Et(t){return`
|
|
66
|
+
${i.bright}${i.cyan}[${t}] recent context, ${qe()}${i.reset}
|
|
67
|
+
${i.dim}Mode: ${ze()}${i.reset}
|
|
68
|
+
${i.gray}${"\u2500".repeat(60)}${i.reset}
|
|
67
69
|
|
|
68
|
-
${
|
|
69
|
-
`}function
|
|
70
|
-
`):null}function
|
|
71
|
-
`).trimEnd()}var
|
|
70
|
+
${i.dim}No previous sessions found for this project yet.${i.reset}
|
|
71
|
+
`}function lt(t,e,r,n){let o=[];return n?o.push(...Qe(t)):o.push(...He(t)),n?o.push(...Ze()):o.push(...Fe()),n&&(o.push(...et()),o.push(...tt())),W(r)&&(n?o.push(...rt(e,r)):o.push(...je(e,r))),o}var re=h(require("path"),1);function Y(t){if(!t)return[];try{let e=JSON.parse(t);return Array.isArray(e)?e:[]}catch(e){return _.debug("PARSER","Failed to parse JSON array, using empty fallback",{preview:t?.substring(0,50)},e instanceof Error?e:new Error(String(e))),[]}}function ne(t){return new Date(t).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}function oe(t){return new Date(t).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function mt(t){return new Date(t).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})}function _t(t,e){return re.default.isAbsolute(t)?re.default.relative(e,t):t}function gt(t,e,r){let n=Y(t);if(n.length>0)return _t(n[0],e);if(r){let o=Y(r);if(o.length>0)return _t(o[0],e)}return"General"}function nr(t){let e=new Map;for(let n of t){let o=n.type==="observation"?n.data.created_at:n.data.displayTime,s=mt(o);e.has(s)||e.set(s,[]),e.get(s).push(n)}let r=Array.from(e.entries()).sort((n,o)=>{let s=new Date(n[0]).getTime(),u=new Date(o[0]).getTime();return s-u});return new Map(r)}function dt(t,e){return e.fullObservationField==="narrative"?t.narrative:t.facts?Y(t.facts).join(`
|
|
72
|
+
`):null}function or(t,e,r,n){let o=[];o.push(...We(t));let s="";for(let u of e)if(u.type==="summary"){let c=u.data,a=ne(c.displayTime);o.push(...Ye(c,a))}else{let c=u.data,a=oe(c.created_at),E=a!==s?a:"";if(s=a,r.has(c.id)){let p=dt(c,n);o.push(...Ke(c,E,p,n))}else o.push(Be(c,E,n))}return o}function sr(t,e,r,n,o){let s=[];s.push(...nt(t));let u=null,c="";for(let a of e)if(a.type==="summary"){u=null,c="";let l=a.data,E=ne(l.displayTime);s.push(...at(l,E))}else{let l=a.data,E=gt(l.files_modified,o,l.files_read),d=oe(l.created_at),p=d!==c;c=d;let S=r.has(l.id);if(E!==u&&(s.push(...ot(E)),u=E),S){let A=dt(l,n);s.push(...it(l,d,p,A,n))}else s.push(st(l,d,p,n))}return s.push(""),s}function ir(t,e,r,n,o,s){return s?sr(t,e,r,n,o):or(t,e,r,n)}function pt(t,e,r,n,o){let s=[],u=nr(t);for(let[c,a]of u)s.push(...ir(c,a,e,r,n,o));return s}function ft(t,e,r){return!(!t.showLastSummary||!e||!!!(e.investigated||e.learned||e.completed||e.next_steps)||r&&e.created_at_epoch<=r.created_at_epoch)}function Mt(t,e){let r=[];return e?(r.push(...$("Investigated",t.investigated,i.blue)),r.push(...$("Learned",t.learned,i.yellow)),r.push(...$("Completed",t.completed,i.green)),r.push(...$("Next Steps",t.next_steps,i.magenta))):(r.push(...x("Investigated",t.investigated)),r.push(...x("Learned",t.learned)),r.push(...x("Completed",t.completed)),r.push(...x("Next Steps",t.next_steps))),r}function St(t,e){return e?ct(t):Xe(t)}function Tt(t,e,r){return!W(e)||t.totalDiscoveryTokens<=0||t.savings<=0?[]:r?ut(t.totalDiscoveryTokens,t.totalReadTokens):Je(t.totalDiscoveryTokens,t.totalReadTokens)}var ar=Ct.default.join((0,At.homedir)(),".claude","plugins","marketplaces","thedotmack","plugin",".install-version");function cr(){try{if(!(0,X.existsSync)(V))return null;let t=new Dt.Database(V,{readonly:!0,create:!1});try{return t.run(`PRAGMA busy_timeout = ${De}`),t}catch(e){throw t.close(),e}}catch(t){if(t instanceof Error&&t.code==="ERR_DLOPEN_FAILED"){try{(0,X.unlinkSync)(ar)}catch(e){e instanceof Error?_.debug("WORKER","Marker file cleanup failed (may not exist)",{},e):_.debug("WORKER","Marker file cleanup failed (may not exist)",{error:String(e)})}return _.error("WORKER","Native module rebuild needed - restart Claude Code to auto-fix"),null}throw t}}function ur(t,e){return e?Et(t):Ve(t)}function Er(t,e,r,n,o,s,u){let c=[],a=te(e);c.push(...lt(t,a,n,u));let l=r.slice(0,n.sessionCount),E=xe(l,r),d=$e(e,E),p=ke(e,n.fullObservationCount);c.push(...pt(d,p,n,o,u));let S=r[0],A=e[0];ft(n,S,A)&&c.push(...Mt(S,u));let ie=Ne(e,n,s,o);return c.push(...St(ie,u)),c.push(...Tt(a,n,u)),c.join(`
|
|
73
|
+
`).trimEnd()}var lr=new Set(["bugfix","discovery","decision","refactor"]);function _r(t,e,r){let n=te(t),o={bugfix:0,discovery:0,decision:0,refactor:0,other:0},s=new Set,u=Number.POSITIVE_INFINITY;for(let a of t){let l=lr.has(a.type)?a.type:"other";o[l]++,a.memory_session_id&&s.add(a.memory_session_id),a.created_at_epoch&&a.created_at_epoch<u&&(u=a.created_at_epoch)}let c=Number.isFinite(u)?Math.max(0,Math.floor((Date.now()-u)/864e5)):0;return{observation_count:t.length,session_count:s.size,timeline_depth_days:c,has_session_summary:e.length>0,obs_type_bugfix:o.bugfix,obs_type_discovery:o.discovery,obs_type_decision:o.decision,obs_type_refactor:o.refactor,obs_type_other:o.other,tokens_injected:n.totalReadTokens,tokens_saved_vs_naive:n.savings,search_strategy:r?"full":"timeline"}}async function se(t,e=!1){let r=Oe(),n=t?.cwd??process.cwd(),o=Te(n),s=t?.projects?.length?t.projects:o.allProjects,u=s[s.length-1]??o.primary;t?.full&&(r.totalObservationCount=999999,r.sessionCount=999999);let c=cr();if(!c)return{text:"",stats:null};try{let a={db:c},l=t?.platformSource?Ae(t.platformSource):void 0,E=s.length>1?s:[u],d=ve(a,E,r,l),p=be(a,E,r,l);return d.length===0&&p.length===0?{text:ur(u,e),stats:null}:{text:Er(u,d,p,r,n,t?.session_id,e),stats:_r(d,p,!!t?.full)}}finally{c.close()}}async function Lt(t,e=!1){return(await se(t,e)).text}0&&(module.exports={generateContext,generateContextWithStats});
|
|
@@ -222,7 +222,7 @@ ${f}`}let a=s.lineStart;for(let u=s.lineStart-1;u>=0;u--){let l=i[u].trim();if(l
|
|
|
222
222
|
${c}`}ce();var VP=new Set([".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".pyw",".go",".rs",".rb",".java",".cs",".cpp",".cc",".cxx",".c",".h",".hpp",".hh",".swift",".kt",".kts",".php",".vue",".svelte",".lua",".scala",".sc",".sh",".bash",".zsh",".hs",".zig",".css",".scss",".toml",".yml",".yaml",".sql",".md",".mdx"]),KP=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),GP=512*1024;async function*H_(t,e,r=20){if(r<=0)return;let n;try{n=await(0,qr.readdir)(t,{withFileTypes:!0})}catch(o){y.debug("WORKER",`walkDir: failed to read directory ${t}`,void 0,o instanceof Error?o:void 0);return}for(let o of n){if(o.name.startsWith(".")&&o.name!=="."||KP.has(o.name))continue;let s=(0,eo.join)(t,o.name);if(o.isDirectory())yield*H_(s,e,r-1);else if(o.isFile()){let i=o.name.slice(o.name.lastIndexOf("."));VP.has(i)&&(yield s)}}}async function JP(t){try{let e=await(0,qr.stat)(t);if(e.size>GP||e.size===0)return null;let r=await(0,qr.readFile)(t,"utf-8");return r.slice(0,1e3).includes("\0")?null:r}catch(e){return y.debug("WORKER",`safeReadFile: failed to read ${t}`,void 0,e instanceof Error?e:void 0),null}}async function W_(t,e,r={}){let n=r.maxResults||20,o=e.toLowerCase(),s=o.split(/[\s_\-./]+/).filter(g=>g.length>0),i=[];for await(let g of H_(t,t,20)){if(r.filePattern&&!(0,eo.relative)(t,g).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let S=await JP(g);S&&i.push({absolutePath:g,relativePath:(0,eo.relative)(t,g),content:S})}let a=q_(i),c=[],u=[],l=0;for(let[g,S]of a){l+=YP(S);let x=Ys(g.toLowerCase(),s)>0,b=[],$=(k,Se)=>{for(let K of k){let ct=0,Ne="",Pt=Ys(K.name.toLowerCase(),s);Pt>0&&(ct+=Pt*3,Ne="name match"),K.signature.toLowerCase().includes(o)&&(ct+=2,Ne=Ne?`${Ne} + signature`:"signature match"),K.jsdoc&&K.jsdoc.toLowerCase().includes(o)&&(ct+=1,Ne=Ne?`${Ne} + jsdoc`:"jsdoc match"),ct>0&&(x=!0,b.push({filePath:g,symbolName:Se?`${Se}.${K.name}`:K.name,kind:K.kind,signature:K.signature,jsdoc:K.jsdoc,lineStart:K.lineStart,lineEnd:K.lineEnd,matchReason:Ne})),K.children&&$(K.children,K.name)}};$(S.symbols),x&&(c.push(S),u.push(...b))}u.sort((g,S)=>{let v=Ys(g.symbolName.toLowerCase(),s);return Ys(S.symbolName.toLowerCase(),s)-v});let d=u.slice(0,n),p=new Set(d.map(g=>g.filePath)),f=c.filter(g=>p.has(g.filePath)).slice(0,n),m=f.reduce((g,S)=>g+S.foldedTokenEstimate,0);return{foldedFiles:f,matchingSymbols:d,totalFilesScanned:i.length,totalSymbolsFound:l,tokenEstimate:m}}function Ys(t,e){let r=0;for(let n of e)if(t===n)r+=10;else if(t.includes(n))r+=5;else{let o=0,s=0;for(let i of n){let a=t.indexOf(i,o);a!==-1&&(s++,o=a+1)}s===n.length&&(r+=1)}return r}function YP(t){let e=t.symbols.length;for(let r of t.symbols)r.children&&(e+=r.children.length);return e}function V_(t,e){let r=[];if(r.push(`\u{1F50D} Smart Search: "${e}"`),r.push(` Scanned ${t.totalFilesScanned} files, found ${t.totalSymbolsFound} symbols`),r.push(` ${t.matchingSymbols.length} matches across ${t.foldedFiles.length} files (~${t.tokenEstimate} tokens for folded view)`),r.push(""),t.matchingSymbols.length===0)return r.push(" No matching symbols found."),r.join(`
|
|
223
223
|
`);r.push("\u2500\u2500 Matching Symbols \u2500\u2500"),r.push("");for(let n of t.matchingSymbols){if(r.push(` ${n.kind} ${n.symbolName} (${n.filePath}:${n.lineStart+1})`),r.push(` ${n.signature}`),n.jsdoc){let o=n.jsdoc.split(`
|
|
224
224
|
`).find(s=>s.replace(/^[\s*/]+/,"").trim().length>0);o&&r.push(` \u{1F4AC} ${o.replace(/^[\s*/]+/,"").trim()}`)}r.push("")}r.push("\u2500\u2500 Folded File Views \u2500\u2500"),r.push("");for(let n of t.foldedFiles)r.push(Ur(n)),r.push("");return r.push("\u2500\u2500 Actions \u2500\u2500"),r.push(" To see full implementation: use smart_unfold with file path and symbol name"),r.join(`
|
|
225
|
-
`)}var ju=require("node:fs/promises"),ei=require("node:fs"),at=require("node:path"),Q_=require("node:os"),ey=require("node:url");var K_="claude";function BP(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Bs(t){if(!t)return K_;let e=BP(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:K_}var XP=Ht(ye.API_REQUEST),Be=class extends Error{kind;status;cause;constructor(e,r,n={}){super(r),this.name="ServerClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},Xs=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=QP(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??XP}async startSession(e){let r=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",r)}async recordEvent(e){let r=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(e){if(!e.sessionId)throw new Be("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async getJobStatus(e){if(!e)throw new Be("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,type:n,narrative:r,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Nu(e.platformSource)}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:Nu(e.platformSource)}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:Nu(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,r,n){if(!this.apiKey||!this.apiKey.trim())throw new Be("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let o=`${this.baseUrl}${r}`,s={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(s.body=JSON.stringify(n));let i;try{i=await Pu(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new Be(l?"timeout":"transport",`Server ${e} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new Be("http_error",`Server ${e} ${r} returned ${i.status}: ${eT(c,200)}`,{status:i.status})}let a=await i.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(c){let u=c instanceof Error?c:new Error(String(c));throw new Be("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:u})}}};function G_(t){return t instanceof Be}function QP(t){return t.replace(/\/+$/,"")}function Nu(t){return typeof t=="string"?Bs(t):null}function eT(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}ce();function Qs(){let e=(Ds().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function J_(){let t=Ds(),e=(...i)=>{for(let a of i){let c=(a??"").trim();if(c.length>0)return c}return""},r=e(t.CLAUDE_MEM_SERVER_URL,t.CLAUDE_MEM_SERVER_BETA_URL),n=e(t.CLAUDE_MEM_SERVER_API_KEY,t.CLAUDE_MEM_SERVER_BETA_API_KEY),o=e(t.CLAUDE_MEM_SERVER_PROJECT_ID,t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!r)return y.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return y.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return y.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let s={serverBaseUrl:r,apiKey:n};return{runtime:"server",client:new Xs(s),projectId:o,serverBaseUrl:r}}ce();var Y_=["observation_add","observation_record_event","observation_search","observation_context","observation_generation_status","memory_add","memory_search","memory_context"],tT=new Set(Y_);function B_(t,e){return e==="server"?[...t]:(y.debug("SYSTEM","Filtering server-beta-only MCP tools from worker runtime advertisement",{runtime:e,hiddenToolCount:Y_.length}),t.filter(r=>!tT.has(r.name)))}var bT={},rT="13.13.0";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var ty=!1,ry=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,at.dirname)((0,ey.fileURLToPath)(bT.url))}catch(t){return ty=!0,y.warn("SYSTEM","mcp-server: failed to resolve module directory from import.meta.url, falling back to process.cwd()",void 0,t instanceof Error?t:new Error(String(t))),process.cwd()}})(),Lu=z_()??(0,at.resolve)(ry,"worker-service.cjs");function nT(){ty&&((0,ei.existsSync)(Lu)||y.error("SYSTEM","mcp-server: dirname resolution failed (both __dirname and import.meta.url are unavailable). Fell back to process.cwd() and the resolved WORKER_SCRIPT_PATH does not exist. This is the actual problem \u2014 the worker bundle is fine, but mcp-server cannot locate it. Worker auto-start will fail until the dirname-resolution path is fixed.",{workerScriptPath:Lu,mcpServerDir:ry}))}async function _t(t,e={}){y.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t});try{let r;if(e.body)r=await Ks(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e.body)});else{let n=new URLSearchParams;for(let[o,s]of Object.entries(e.query??{}))s!=null&&n.append(o,String(s));r=await Ks(`${t}?${n}`)}if(!r.ok){let n=await r.text();throw new Error(`Worker API error (${r.status}): ${n}`)}return y.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),e.text?{content:[{type:"text",text:await r.text()}]}:e.body?{content:[{type:"text",text:JSON.stringify(await r.json(),null,2)}]}:await r.json()}catch(r){return y.error("SYSTEM","\u2190 Worker API error",{endpoint:t},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function oT(){try{return(await Ks("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}function ny(){if(Qs()!=="server")return null;let e=J_();return e?{...e,available:!0}:{runtime:"server",available:!1,reason:"server runtime is selected but configuration is incomplete (missing url, api key, or project id)"}}function sT(t){return G_(t)?{content:[{type:"text",text:`Server error (${t.kind}${t.status?` ${t.status}`:""}): ${t.message}`}],isError:!0}:{content:[{type:"text",text:`Tool error: ${t instanceof Error?t.message:String(t)}`}],isError:!0}}function Zr(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function ro(t){let e=ny();if(!e)throw new Be("transport",`${t} requires CLAUDE_MEM_RUNTIME=server. Current runtime is "worker"; use the existing search/timeline/get_observations tools for worker-mode memory access.`);if(!e.available)throw new Be("missing_api_key",`${t}: ${e.reason}`);return e}function no(t,e){return async r=>{try{return await e(r)}catch(n){let o=n instanceof Error?n:new Error(String(n));return y.warn("SYSTEM",`${t} failed`,void 0,o),sT(n)}}}var iT=no("observation_add",async t=>{let e=ro("observation_add");if(typeof t?.content!="string"||t.content.trim().length===0)throw new Error('observation_add: "content" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,content:t.content,...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.kind!==void 0?{kind:t.kind}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}},o=await e.client.addObservation(n);return Zr(o)});function ri(t){return typeof t=="string"?Bs(t):null}var aT=no("observation_record_event",async t=>{let e=ro("observation_record_event");if(typeof t?.eventType!="string"||t.eventType.trim().length===0)throw new Error('observation_record_event: "eventType" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,sourceType:t.sourceType??"api",eventType:t.eventType,occurredAtEpoch:typeof t.occurredAtEpoch=="number"?t.occurredAtEpoch:Date.now(),...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.memorySessionId!==void 0?{memorySessionId:t.memorySessionId}:{},...t.platformSource!==void 0?{platformSource:ri(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{},...t.generate!==void 0?{generate:t.generate}:{}},o=await e.client.recordEvent(n);return Zr(o)}),cT=no("observation_search",async t=>{let e=ro("observation_search");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_search: "query" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:ri(t.platformSource)}:{}},o=await e.client.searchObservations(n);return Zr(o)}),uT=no("observation_context",async t=>{let e=ro("observation_context");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_context: "query" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:ri(t.platformSource)}:{}},o=await e.client.contextObservations(n);return Zr(o)});function lT(t){return Array.isArray(t.projects)?t.projects.map(e=>typeof e=="string"?e.trim():"").filter(Boolean):typeof t.projects=="string"?t.projects.split(",").map(e=>e.trim()).filter(Boolean):typeof t.project=="string"&&t.project.trim().length>0?[t.project.trim()]:[]}async function dT(t){let e=lT(t);return e.length===0?{content:[{type:"text",text:'session_start_context: "project" or "projects" is required'}],isError:!0}:_t("/api/context/inject",{query:{projects:e.join(","),...t.platformSource!==void 0?{platformSource:ri(t.platformSource)}:{},...t.full!==void 0?{full:t.full}:{},...t.colors!==void 0?{colors:t.colors}:{}},text:!0})}var pT=no("observation_generation_status",async t=>{let e=ro("observation_generation_status"),r=(t?.jobId??t?.job_id??"").trim();if(!r)throw new Error('observation_generation_status: "jobId" is required');let n=await e.client.getJobStatus(r);return Zr(n)});async function fT(){if(await oT())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),nT();try{let t=Ru(),e=await I_(t,Lu);return e==="dead"&&y.error("SYSTEM","Worker auto-start failed \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running. Check earlier log lines for the specific failure reason (Bun not found, missing worker bundle, port conflict, etc.)."),e!=="dead"}catch(t){return y.error("SYSTEM","Worker auto-start threw \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running.",void 0,t instanceof Error?t:new Error(String(t))),!1}}var oy=[{name:"important_workflow",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
|
|
225
|
+
`)}var ju=require("node:fs/promises"),ei=require("node:fs"),at=require("node:path"),Q_=require("node:os"),ey=require("node:url");var K_="claude";function BP(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Bs(t){if(!t)return K_;let e=BP(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:K_}var XP=Ht(ye.API_REQUEST),Be=class extends Error{kind;status;cause;constructor(e,r,n={}){super(r),this.name="ServerClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},Xs=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=QP(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??XP}async startSession(e){let r=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",r)}async recordEvent(e){let r=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(e){if(!e.sessionId)throw new Be("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async getJobStatus(e){if(!e)throw new Be("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,type:n,narrative:r,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Nu(e.platformSource)}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:Nu(e.platformSource)}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:Nu(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,r,n){if(!this.apiKey||!this.apiKey.trim())throw new Be("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let o=`${this.baseUrl}${r}`,s={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(s.body=JSON.stringify(n));let i;try{i=await Pu(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new Be(l?"timeout":"transport",`Server ${e} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new Be("http_error",`Server ${e} ${r} returned ${i.status}: ${eT(c,200)}`,{status:i.status})}let a=await i.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(c){let u=c instanceof Error?c:new Error(String(c));throw new Be("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:u})}}};function G_(t){return t instanceof Be}function QP(t){return t.replace(/\/+$/,"")}function Nu(t){return typeof t=="string"?Bs(t):null}function eT(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}ce();function Qs(){let e=(Ds().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function J_(){let t=Ds(),e=(...i)=>{for(let a of i){let c=(a??"").trim();if(c.length>0)return c}return""},r=e(t.CLAUDE_MEM_SERVER_URL,t.CLAUDE_MEM_SERVER_BETA_URL),n=e(t.CLAUDE_MEM_SERVER_API_KEY,t.CLAUDE_MEM_SERVER_BETA_API_KEY),o=e(t.CLAUDE_MEM_SERVER_PROJECT_ID,t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!r)return y.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return y.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return y.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let s={serverBaseUrl:r,apiKey:n};return{runtime:"server",client:new Xs(s),projectId:o,serverBaseUrl:r}}ce();var Y_=["observation_add","observation_record_event","observation_search","observation_context","observation_generation_status","memory_add","memory_search","memory_context"],tT=new Set(Y_);function B_(t,e){return e==="server"?[...t]:(y.debug("SYSTEM","Filtering server-beta-only MCP tools from worker runtime advertisement",{runtime:e,hiddenToolCount:Y_.length}),t.filter(r=>!tT.has(r.name)))}var bT={},rT="13.13.1";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var ty=!1,ry=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,at.dirname)((0,ey.fileURLToPath)(bT.url))}catch(t){return ty=!0,y.warn("SYSTEM","mcp-server: failed to resolve module directory from import.meta.url, falling back to process.cwd()",void 0,t instanceof Error?t:new Error(String(t))),process.cwd()}})(),Lu=z_()??(0,at.resolve)(ry,"worker-service.cjs");function nT(){ty&&((0,ei.existsSync)(Lu)||y.error("SYSTEM","mcp-server: dirname resolution failed (both __dirname and import.meta.url are unavailable). Fell back to process.cwd() and the resolved WORKER_SCRIPT_PATH does not exist. This is the actual problem \u2014 the worker bundle is fine, but mcp-server cannot locate it. Worker auto-start will fail until the dirname-resolution path is fixed.",{workerScriptPath:Lu,mcpServerDir:ry}))}async function _t(t,e={}){y.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t});try{let r;if(e.body)r=await Ks(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e.body)});else{let n=new URLSearchParams;for(let[o,s]of Object.entries(e.query??{}))s!=null&&n.append(o,String(s));r=await Ks(`${t}?${n}`)}if(!r.ok){let n=await r.text();throw new Error(`Worker API error (${r.status}): ${n}`)}return y.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),e.text?{content:[{type:"text",text:await r.text()}]}:e.body?{content:[{type:"text",text:JSON.stringify(await r.json(),null,2)}]}:await r.json()}catch(r){return y.error("SYSTEM","\u2190 Worker API error",{endpoint:t},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function oT(){try{return(await Ks("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}function ny(){if(Qs()!=="server")return null;let e=J_();return e?{...e,available:!0}:{runtime:"server",available:!1,reason:"server runtime is selected but configuration is incomplete (missing url, api key, or project id)"}}function sT(t){return G_(t)?{content:[{type:"text",text:`Server error (${t.kind}${t.status?` ${t.status}`:""}): ${t.message}`}],isError:!0}:{content:[{type:"text",text:`Tool error: ${t instanceof Error?t.message:String(t)}`}],isError:!0}}function Zr(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function ro(t){let e=ny();if(!e)throw new Be("transport",`${t} requires CLAUDE_MEM_RUNTIME=server. Current runtime is "worker"; use the existing search/timeline/get_observations tools for worker-mode memory access.`);if(!e.available)throw new Be("missing_api_key",`${t}: ${e.reason}`);return e}function no(t,e){return async r=>{try{return await e(r)}catch(n){let o=n instanceof Error?n:new Error(String(n));return y.warn("SYSTEM",`${t} failed`,void 0,o),sT(n)}}}var iT=no("observation_add",async t=>{let e=ro("observation_add");if(typeof t?.content!="string"||t.content.trim().length===0)throw new Error('observation_add: "content" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,content:t.content,...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.kind!==void 0?{kind:t.kind}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}},o=await e.client.addObservation(n);return Zr(o)});function ri(t){return typeof t=="string"?Bs(t):null}var aT=no("observation_record_event",async t=>{let e=ro("observation_record_event");if(typeof t?.eventType!="string"||t.eventType.trim().length===0)throw new Error('observation_record_event: "eventType" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,sourceType:t.sourceType??"api",eventType:t.eventType,occurredAtEpoch:typeof t.occurredAtEpoch=="number"?t.occurredAtEpoch:Date.now(),...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.memorySessionId!==void 0?{memorySessionId:t.memorySessionId}:{},...t.platformSource!==void 0?{platformSource:ri(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{},...t.generate!==void 0?{generate:t.generate}:{}},o=await e.client.recordEvent(n);return Zr(o)}),cT=no("observation_search",async t=>{let e=ro("observation_search");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_search: "query" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:ri(t.platformSource)}:{}},o=await e.client.searchObservations(n);return Zr(o)}),uT=no("observation_context",async t=>{let e=ro("observation_context");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_context: "query" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:ri(t.platformSource)}:{}},o=await e.client.contextObservations(n);return Zr(o)});function lT(t){return Array.isArray(t.projects)?t.projects.map(e=>typeof e=="string"?e.trim():"").filter(Boolean):typeof t.projects=="string"?t.projects.split(",").map(e=>e.trim()).filter(Boolean):typeof t.project=="string"&&t.project.trim().length>0?[t.project.trim()]:[]}async function dT(t){let e=lT(t);return e.length===0?{content:[{type:"text",text:'session_start_context: "project" or "projects" is required'}],isError:!0}:_t("/api/context/inject",{query:{projects:e.join(","),...t.platformSource!==void 0?{platformSource:ri(t.platformSource)}:{},...t.full!==void 0?{full:t.full}:{},...t.colors!==void 0?{colors:t.colors}:{}},text:!0})}var pT=no("observation_generation_status",async t=>{let e=ro("observation_generation_status"),r=(t?.jobId??t?.job_id??"").trim();if(!r)throw new Error('observation_generation_status: "jobId" is required');let n=await e.client.getJobStatus(r);return Zr(n)});async function fT(){if(await oT())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),nT();try{let t=Ru(),e=await I_(t,Lu);return e==="dead"&&y.error("SYSTEM","Worker auto-start failed \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running. Check earlier log lines for the specific failure reason (Bun not found, missing worker bundle, port conflict, etc.)."),e!=="dead"}catch(t){return y.error("SYSTEM","Worker auto-start threw \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running.",void 0,t instanceof Error?t:new Error(String(t))),!1}}var oy=[{name:"important_workflow",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
|
|
226
226
|
1. search(query) \u2192 Get index with IDs (~50-100 tokens/result)
|
|
227
227
|
2. timeline(anchor=ID) \u2192 Get context around interesting results
|
|
228
228
|
3. get_observations([IDs]) \u2192 Fetch full details ONLY for filtered IDs
|