claude-mem 13.22.0 → 13.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.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/mcp-server.cjs +1 -1
- package/plugin/scripts/server-service.cjs +108 -108
- package/plugin/scripts/transcript-watcher.cjs +1 -1
- package/plugin/scripts/worker-service.cjs +215 -215
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 ei(f+`
|
|
100
100
|
`)}debug(e,r,i,n){this.log(0,e,r,i,n)}info(e,r,i,n){this.log(1,e,r,i,n)}warn(e,r,i,n){this.log(2,e,r,i,n)}setErrorSink(e){Jb=e}error(e,r,i,n){this.log(3,e,r,i,n),this.routeErrorToSink(r,i,n)}routeErrorToSink(e,r,i){try{if(!Jb||!(i instanceof Error))return;Jb(i)}catch{}}dataIn(e,r,i,n){this.info(e,`\u2192 ${r}`,i,n)}dataOut(e,r,i,n){this.info(e,`\u2190 ${r}`,i,n)}success(e,r,i,n){this.info(e,`\u2713 ${r}`,i,n)}failure(e,r,i,n){this.error(e,`\u2717 ${r}`,i,n)}},E=new qb});import{join as zA}from"path";import{mkdirSync as X3,writeFileSync as Q3}from"fs";import{randomUUID as eZ}from"crypto";function tZ(t){let e=t.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function zb(t,e){if(tZ(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 BA(t,e){return zb(t,e).enabled}function Zl(){return zA(Rn(),GA)}function Pi(){let t;try{t=Gt(Zl(),null)}catch(e){let r=e instanceof Error?e:new Error(String(e));return E.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 qs(t){let e=Rn();X3(e,{recursive:!0}),Q3(zA(e,GA),JSON.stringify(t,null,2)+`
|
|
101
|
-
`)}function Dd(){let t=Pi();if(t?.installId)return t.installId;let e=eZ();return qs({installId:e,decidedAt:""}),e}var GA,Pd=S(()=>{"use strict";Xe();Oo();Re();GA="telemetry.json"});function nZ(t,e){if(!(!t||typeof t!="object"))for(let r of Object.keys(t)){if(!rZ.has(r))continue;let i=t[r];typeof i=="string"?e[r]=i.length>VA?i.slice(0,VA):i:(typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean")&&(e[r]=i)}}function WA(t){let e={};try{nZ(t,e)}catch{}return e}var rZ,VA,ZA=S(()=>{"use strict";rZ=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","stage","install_method","interactive","bun_version","uv_version","claude_code_version","trial_days","trial_variant","offer_surface","funnel_source","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","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","observed_model","observed_billing","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","observations_created","total_observations_injected","total_tokens_saved_vs_naive"]),VA=200});import YA from"os";function HA(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||oZ}function XA(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||sZ}function QA(t){let e={};for(let r of aZ)t[r]!==void 0&&(e[r]=t[r]);return e}function lZ(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||YA.release().toLowerCase().includes("microsoft")}catch(t){let e=t instanceof Error?t:new Error(String(t));return E.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function eR(){return{version:iZ,os:process.platform,os_version:YA.release(),is_wsl:lZ(),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 iZ,oZ,sZ,aZ,tR=S(()=>{"use strict";Re();iZ="13.
|
|
101
|
+
`)}function Dd(){let t=Pi();if(t?.installId)return t.installId;let e=eZ();return qs({installId:e,decidedAt:""}),e}var GA,Pd=S(()=>{"use strict";Xe();Oo();Re();GA="telemetry.json"});function nZ(t,e){if(!(!t||typeof t!="object"))for(let r of Object.keys(t)){if(!rZ.has(r))continue;let i=t[r];typeof i=="string"?e[r]=i.length>VA?i.slice(0,VA):i:(typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean")&&(e[r]=i)}}function WA(t){let e={};try{nZ(t,e)}catch{}return e}var rZ,VA,ZA=S(()=>{"use strict";rZ=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","stage","install_method","interactive","bun_version","uv_version","claude_code_version","trial_days","trial_variant","offer_surface","funnel_source","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","limit_window","overage_status","is_using_overage","resets_in_minutes","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_invalid_output","top_model","observed_model","observed_billing","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","observations_created","total_observations_injected","total_tokens_saved_vs_naive"]),VA=200});import YA from"os";function HA(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||oZ}function XA(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||sZ}function QA(t){let e={};for(let r of aZ)t[r]!==void 0&&(e[r]=t[r]);return e}function lZ(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||YA.release().toLowerCase().includes("microsoft")}catch(t){let e=t instanceof Error?t:new Error(String(t));return E.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function eR(){return{version:iZ,os:process.platform,os_version:YA.release(),is_wsl:lZ(),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 iZ,oZ,sZ,aZ,tR=S(()=>{"use strict";Re();iZ="13.23.0",oZ="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",sZ="https://us.i.posthog.com";aZ=["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 Kn(t,e,r){try{if(!BA(process.env,Pi()))return;let i=WA({...eR(),...e??{}});if(r?.person?i.$set=QA(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=HA(),o=new AbortController,s=setTimeout(()=>o.abort(),cZ);try{await uZ(n,t,i,o.signal)}finally{clearTimeout(s)}}catch{}}async function uZ(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:Dd(),properties:r}),signal:i})}var cZ,jd=S(()=>{"use strict";Pd();ZA();tR();cZ=2e3});import{spawn as dZ,spawnSync as pZ}from"node:child_process";import{extname as Gb}from"node:path";function ji(t,e,r){return dZ(t,e??[],{windowsHide:!0,...r})}function mZ(t){return`"${t.replace(/"/g,'""')}"`}function Bb(t){if(process.platform!=="win32")return[];try{let e=pZ("where",[t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0});return e.status!==0||!e.stdout.trim()?[]:e.stdout.split(/\r?\n/).map(r=>r.trim()).filter(Boolean)}catch{return[]}}function Md(t){let e=Bb(t);return e.find(r=>nR.has(Gb(r).toLowerCase()))??e.find(r=>fZ.has(Gb(r).toLowerCase()))??e[0]??null}function zs(t,e,r,i=process.platform){let n={...i==="win32"?{windowsHide:!0}:{},...r};if(i==="win32"&&rR.has(Gb(t).toLowerCase())){let o=[t,...e].map(mZ).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 rR,nR,fZ,ri=S(()=>{"use strict";rR=new Set([".cmd",".bat"]),nR=new Set([".exe",".com"]),fZ=new Set([...nR,...rR])});function Gs(t){return process.platform==="win32"?Math.round(t*Or.WINDOWS_MULTIPLIER):t}var Or,Nd=S(()=>{"use strict";Or={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 sR={};Te(sR,{SettingsDefaultsManager:()=>Ue});import{readFileSync as hZ,existsSync as yZ}from"fs";import{join as iR}from"path";import{homedir as oR,hostname as gZ}from"os";var bZ,Ue,Hr=S(()=>{"use strict";Nd();Wr();bZ="security_alert",Ue=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(Gs(Or.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:iR(oR(),".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:iR(oR(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_OBSERVER_MAX_CONVERSATION_CHARS:"400000",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:gZ(),CLAUDE_MEM_CLOUD_SYNC_WS:"true",CLAUDE_MEM_PRO_TRIAL_EMAIL:"",CLAUDE_MEM_PRO_TRIAL_AT:"",CLAUDE_MEM_PRO_TRIAL_STATE:"",CLAUDE_MEM_PRO_TRIAL_ENDS_AT:"",CLAUDE_MEM_PRO_PLAN:"",CLAUDE_MEM_PRO_FALLBACK_AT:"",CLAUDE_MEM_PRO_MEMORY_KEY:"",CLAUDE_MEM_PRO_MEMORY_BASE_URL:"",CLAUDE_MEM_PRO_MEMORY_MODEL:"",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_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(!yZ(e)){let c=this.getAllDefaults();try{lt(e,c),console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(u){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,u instanceof Error?u.message:String(u))}return r?this.applyEnvOverrides(c):c}let i=hZ(e,"utf-8"),n=Nt(i),o=n,s=n.env&&typeof n.env=="object"&&!Array.isArray(n.env),a=s&&Object.keys(n).some(c=>c!=="env");if(s&&(o=n.env,!a))try{lt(e,o),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(o.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES===bZ){o={...o,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES};try{lt(e,a?{...n,env:o}:o),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 l={...this.DEFAULTS};for(let c of Object.keys(this.DEFAULTS))o[c]!==void 0&&(l[c]=o[c]);return r?this.applyEnvOverrides(l):l}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 vZ}from"child_process";import{promisify as SZ}from"util";import{existsSync as Wbe,readFileSync as Zbe,writeFileSync as Ybe,mkdirSync as Hbe,unlinkSync as Xbe}from"fs";import{userInfo as eve}from"os";import{join as rve}from"path";var ove,aR=S(()=>{"use strict";Xe();Re();ove=SZ(vZ)});import{existsSync as Vb,readFileSync as cR,writeFileSync as EZ,mkdirSync as wZ,chmodSync as lR}from"fs";import{parseEnv as kZ}from"util";function uR(){return process.env.CLAUDE_MEM_ENV_FILE??dt.envFile()}function pR(t){return kZ(t)}function xZ(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 fR(){let t=uR();if(!Vb(t))return{};try{let e=cR(t,"utf-8"),r=pR(e),i={};for(let n of dR)r[n]&&(i[n]=r[n]);return i}catch(e){return E.warn("ENV","Failed to load .env file",{path:t},e instanceof Error?e:new Error(String(e))),{}}}function mR(t){let e=uR(),r={};try{Vb(dt.dataDir())||wZ(dt.dataDir(),{recursive:!0,mode:448}),lR(dt.dataDir(),448),r=Vb(e)?pR(cR(e,"utf-8")):{}}catch(n){let o=n instanceof Error?n:new Error(String(n));throw E.error("ENV","Failed to set up env directory or read existing env",{},o),o}let i={...r};for(let n of dR){let o=t[n];o!==void 0&&(o?i[n]=o:delete i[n])}try{EZ(e,xZ(i),{encoding:"utf-8",mode:384}),lR(e,384)}catch(n){throw E.error("ENV","Failed to save .env file",{path:e},n instanceof Error?n:new Error(String(n))),n}}var dR,hR=S(()=>{"use strict";Re();Xe();aR();dR=["ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","GEMINI_API_KEY","OPENROUTER_API_KEY"]});function Mi(t=process.env){let e={};for(let[r,i]of Object.entries(t))if(i!==void 0){if(CZ.has(r)){e[r]=i;continue}_Z.has(r)||IZ.some(n=>r.startsWith(n))||(e[r]=i)}return e}var IZ,_Z,TZ,CZ,Yl=S(()=>{"use strict";IZ=["CLAUDECODE_","CLAUDE_CODE_"],_Z=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),TZ=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"]),CZ=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",...TZ])});import{spawnSync as gR}from"child_process";import{readFileSync as OZ}from"fs";function RZ(t){Wb+=1;let e=gR("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Mi(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 KZ(t,e=!1){if(!e){let i=yR.get(t);if(i&&Date.now()-i.capturedAtMs<AZ)return i.token}let r=null;try{r=RZ(t)}catch(i){E.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:i instanceof Error?i.message:String(i)}),r=null}return yR.set(t,{token:r,capturedAtMs:Date.now()}),r}function bR(t,e){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux"){Wb+=1;try{let r=OZ(`/proc/${t}/stat`,"utf-8"),i=r.lastIndexOf(") ");if(i<0)return null;let o=r.slice(i+2).split(" ")[19];return o&&/^\d+$/.test(o)?o:null}catch(r){return E.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}if(process.platform==="win32")return KZ(t,e);Wb+=1;try{let r=gR("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Mi(process.env),LC_ALL:"C",LANG:"C"}});if(r.status!==0)return null;let i=r.stdout.trim();return i.length>0?i:null}catch(r){return E.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}function Ni(t){return bR(t,!1)}function ni(t,e){if(e===null)return!0;let r=bR(t,!0);return r===null?!0:r===e}var AZ,yR,Wb,Zb=S(()=>{"use strict";Re();Yl();AZ=5e3,yR=new Map,Wb=0});import{execFile as DZ}from"child_process";import{readdirSync as PZ,readFileSync as jZ}from"fs";import{promisify as MZ}from"util";async function Po(t,e={}){let r=e.signalMode==="immediate",i=e.expectedStartToken!==void 0?e.expectedStartToken:Ni(t),n=()=>ni(t,i);if(!n()){E.warn("PROCESS","Skipping tree-kill: root PID was reused since it was captured",{pid:t});return}if(E.debug("PROCESS",`Killing process tree rooted at PID ${t}`,{immediate:r}),process.platform==="win32"){try{await Yb("taskkill",["/PID",String(t),"/T","/F"],{timeout:5e3,windowsHide:!0})}catch(o){let s=o.code,a=String(o.stderr??""),l=o instanceof Error?o.message:String(o);if(s===NZ||LZ.test(`${a} ${l}`)){E.debug("PROCESS","taskkill reported the process was already gone",{pid:t});return}throw new Ld(t,`taskkill failed for PID ${t} (exit ${String(s)}): ${a.trim()||l}`,{cause:o})}return}try{let o=r?"SIGKILL":"SIGTERM",s=await Ud(t);for(let c of s){if(!ni(c.pid,c.startToken)){E.debug("PROCESS",`Skipping ${o}: descendant PID was reused since enumeration`,{pid:c.pid,rootPid:t});continue}try{process.kill(c.pid,o)}catch{}}if(n())try{process.kill(t,o)}catch(c){let u=c instanceof Error?c:new Error(String(c)),d=u.code;d!=="ESRCH"&&E.debug("PROCESS",`Failed to ${o} PID ${t}`,{code:d},u)}else E.warn("PROCESS","Skipping root signal: PID was reused during descendant enumeration",{pid:t,signal:o});r||await new Promise(c=>setTimeout(c,500));let a=n()?await Ud(t):[],l=new Map;for(let c of s)l.set(c.pid,c.startToken);for(let c of a)l.set(c.pid,c.startToken);for(let[c,u]of l){if(!ni(c,u)){E.debug("PROCESS","Skipping SIGKILL: descendant PID was reused since the scan",{pid:c,rootPid:t});continue}try{process.kill(c,"SIGKILL")}catch{}}if(!r&&n())try{process.kill(t,"SIGKILL")}catch{}}catch(o){throw new Ld(t,`tree-kill failed for PID ${t}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}}async function UZ(){return process.platform==="win32"?FZ():process.platform==="linux"?$Z():JZ()}function $Z(){let t=[],e;try{e=PZ("/proc")}catch(r){return E.warn("PROCESS","Cannot read /proc \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),t}for(let r of e){if(!/^\d+$/.test(r))continue;let i;try{i=jZ(`/proc/${r}/stat`,"utf-8")}catch{continue}let n=i.lastIndexOf(") ");if(n<0)continue;let o=i.slice(n+2).split(" "),s=Number.parseInt(o[1]??"",10),a=o[19];Number.isFinite(s)&&t.push({pid:Number.parseInt(r,10),ppid:s,startToken:a&&/^\d+$/.test(a)?a:null})}return t}async function JZ(){let t;try{t=(await Yb("ps",["-eo","pid=,ppid=,lstart="],{timeout:1e4,maxBuffer:33554432,env:{...process.env,LC_ALL:"C",LANG:"C"}})).stdout}catch(r){return E.warn("PROCESS","Cannot enumerate the process table \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),[]}let e=[];for(let r of t.split(`
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "Claude-Mem (Persistent Memory)",
|
|
4
4
|
"description": "OpenClaw plugin for Claude-Mem. Records observations from embedded runner sessions and streams them to messaging channels.",
|
|
5
5
|
"kind": "memory",
|
|
6
|
-
"version": "13.
|
|
6
|
+
"version": "13.23.0",
|
|
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
|
@@ -223,7 +223,7 @@ ${f}`}let a=s.lineStart;for(let u=s.lineStart-1;u>=0;u--){let l=i[u].trim();if(l
|
|
|
223
223
|
${c}`}ie();var dT=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"]),pT=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),fT=512*1024;async function*ry(t,e,r=20){if(r<=0)return;let n;try{n=await(0,Wr.readdir)(t,{withFileTypes:!0})}catch(o){h.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!=="."||pT.has(o.name))continue;let s=(0,ro.join)(t,o.name);if(o.isDirectory())yield*ry(s,e,r-1);else if(o.isFile()){let i=o.name.slice(o.name.lastIndexOf("."));dT.has(i)&&(yield s)}}}async function mT(t){try{let e=await(0,Wr.stat)(t);if(e.size>fT||e.size===0)return null;let r=await(0,Wr.readFile)(t,"utf-8");return r.slice(0,1e3).includes("\0")?null:r}catch(e){return h.debug("WORKER",`safeReadFile: failed to read ${t}`,void 0,e instanceof Error?e:void 0),null}}async function ny(t,e,r={}){let n=r.maxResults||20,o=e.toLowerCase(),s=o.split(/[\s_\-./]+/).filter(_=>_.length>0),i=[];for await(let _ of ry(t,t,20)){if(r.filePattern&&!(0,ro.relative)(t,_).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let S=await mT(_);S&&i.push({absolutePath:_,relativePath:(0,ro.relative)(t,_),content:S})}let a=Q_(i),c=[],u=[],l=0;for(let[_,S]of a){l+=hT(S);let x=ri(_.toLowerCase(),s)>0,b=[],$=(k,ye)=>{for(let K of k){let ct=0,Le="",Tt=ri(K.name.toLowerCase(),s);Tt>0&&(ct+=Tt*3,Le="name match"),K.signature.toLowerCase().includes(o)&&(ct+=2,Le=Le?`${Le} + signature`:"signature match"),K.jsdoc&&K.jsdoc.toLowerCase().includes(o)&&(ct+=1,Le=Le?`${Le} + jsdoc`:"jsdoc match"),ct>0&&(x=!0,b.push({filePath:_,symbolName:ye?`${ye}.${K.name}`:K.name,kind:K.kind,signature:K.signature,jsdoc:K.jsdoc,lineStart:K.lineStart,lineEnd:K.lineEnd,matchReason:Le})),K.children&&$(K.children,K.name)}};$(S.symbols),x&&(c.push(S),u.push(...b))}u.sort((_,S)=>{let v=ri(_.symbolName.toLowerCase(),s);return ri(S.symbolName.toLowerCase(),s)-v});let d=u.slice(0,n),p=new Set(d.map(_=>_.filePath)),f=c.filter(_=>p.has(_.filePath)).slice(0,n),m=f.reduce((_,S)=>_+S.foldedTokenEstimate,0);return{foldedFiles:f,matchingSymbols:d,totalFilesScanned:i.length,totalSymbolsFound:l,tokenEstimate:m}}function ri(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 hT(t){let e=t.symbols.length;for(let r of t.symbols)r.children&&(e+=r.children.length);return e}function oy(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(`
|
|
224
224
|
`);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(`
|
|
225
225
|
`).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(Hr(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(`
|
|
226
|
-
`)}var Yu=require("node:fs/promises"),ii=require("node:fs"),at=require("node:path"),dy=require("node:os"),py=require("node:url");var sy="claude";function gT(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function ni(t){if(!t)return sy;let e=gT(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:sy}var _T=Wt($e.API_REQUEST),Je=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)}},oi=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=yT(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??_T}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 Je("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 Je("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:Ku(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:Ku(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:Ku(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,r,n){if(!this.apiKey||!this.apiKey.trim())throw new Je("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 Nu(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new Je(l?"timeout":"transport",`Server ${e} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new Je("http_error",`Server ${e} ${r} returned ${i.status}: ${ST(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 Je("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:u})}}};function iy(t){return t instanceof Je}function yT(t){return t.replace(/\/+$/,"")}function Ku(t){return typeof t=="string"?ni(t):null}function ST(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}ie();function si(){let e=(Ls().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function ay(){let t=Ls(),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 h.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return h.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return h.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let s={serverBaseUrl:r,apiKey:n};return{runtime:"server",client:new oi(s),projectId:o,serverBaseUrl:r}}ie();var cy=["observation_add","observation_record_event","observation_search","observation_context","observation_generation_status","memory_add","memory_search","memory_context"],vT=new Set(cy);function uy(t,e){return e==="server"?[...t]:(h.debug("SYSTEM","Filtering server-beta-only MCP tools from worker runtime advertisement",{runtime:e,hiddenToolCount:cy.length}),t.filter(r=>!vT.has(r.name)))}var UT={},bT="13.22.0";console.log=(...t)=>{h.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var fy=!1,my=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,at.dirname)((0,py.fileURLToPath)(UT.url))}catch(t){return fy=!0,h.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()}})(),Gu=F_()??(0,at.resolve)(my,"worker-service.cjs");function ET(){fy&&((0,ii.existsSync)(Gu)||h.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:Gu,mcpServerDir:my}))}async function gt(t,e={}){h.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t});try{let r;if(e.body)r=await Xs(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 Xs(`${t}?${n}`)}if(!r.ok){let n=await r.text();throw new Error(`Worker API error (${r.status}): ${n}`)}return h.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 h.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 wT(){try{return(await Xs("/api/health")).ok}catch(t){return h.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}function hy(){if(si()!=="server")return null;let e=ay();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 kT(t){return iy(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 Vr(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function oo(t){let e=hy();if(!e)throw new Je("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 Je("missing_api_key",`${t}: ${e.reason}`);return e}function so(t,e){return async r=>{try{return await e(r)}catch(n){let o=n instanceof Error?n:new Error(String(n));return h.warn("SYSTEM",`${t} failed`,void 0,o),kT(n)}}}var xT=so("observation_add",async t=>{let e=oo("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 Vr(o)});function ci(t){return typeof t=="string"?ni(t):null}var $T=so("observation_record_event",async t=>{let e=oo("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:ci(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{},...t.generate!==void 0?{generate:t.generate}:{}},o=await e.client.recordEvent(n);return Vr(o)}),PT=so("observation_search",async t=>{let e=oo("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:ci(t.platformSource)}:{}},o=await e.client.searchObservations(n);return Vr(o)}),TT=so("observation_context",async t=>{let e=oo("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:ci(t.platformSource)}:{}},o=await e.client.contextObservations(n);return Vr(o)});function RT(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 zT(t){let e=RT(t);return e.length===0?{content:[{type:"text",text:'session_start_context: "project" or "projects" is required'}],isError:!0}:gt("/api/context/inject",{query:{projects:e.join(","),...t.platformSource!==void 0?{platformSource:ci(t.platformSource)}:{},...t.full!==void 0?{full:t.full}:{},...t.colors!==void 0?{colors:t.colors}:{}},text:!0})}var IT=so("observation_generation_status",async t=>{let e=oo("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 Vr(n)});async function OT(){if(await wT())return!0;h.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),ET();try{let t=ju(),e=await Z_(t,Gu);return e==="dead"&&h.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 h.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 gy=[{name:"important_workflow",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
|
|
226
|
+
`)}var Yu=require("node:fs/promises"),ii=require("node:fs"),at=require("node:path"),dy=require("node:os"),py=require("node:url");var sy="claude";function gT(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function ni(t){if(!t)return sy;let e=gT(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:sy}var _T=Wt($e.API_REQUEST),Je=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)}},oi=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=yT(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??_T}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 Je("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 Je("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:Ku(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:Ku(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:Ku(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,r,n){if(!this.apiKey||!this.apiKey.trim())throw new Je("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 Nu(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new Je(l?"timeout":"transport",`Server ${e} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new Je("http_error",`Server ${e} ${r} returned ${i.status}: ${ST(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 Je("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:u})}}};function iy(t){return t instanceof Je}function yT(t){return t.replace(/\/+$/,"")}function Ku(t){return typeof t=="string"?ni(t):null}function ST(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}ie();function si(){let e=(Ls().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function ay(){let t=Ls(),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 h.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return h.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return h.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let s={serverBaseUrl:r,apiKey:n};return{runtime:"server",client:new oi(s),projectId:o,serverBaseUrl:r}}ie();var cy=["observation_add","observation_record_event","observation_search","observation_context","observation_generation_status","memory_add","memory_search","memory_context"],vT=new Set(cy);function uy(t,e){return e==="server"?[...t]:(h.debug("SYSTEM","Filtering server-beta-only MCP tools from worker runtime advertisement",{runtime:e,hiddenToolCount:cy.length}),t.filter(r=>!vT.has(r.name)))}var UT={},bT="13.23.0";console.log=(...t)=>{h.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var fy=!1,my=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,at.dirname)((0,py.fileURLToPath)(UT.url))}catch(t){return fy=!0,h.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()}})(),Gu=F_()??(0,at.resolve)(my,"worker-service.cjs");function ET(){fy&&((0,ii.existsSync)(Gu)||h.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:Gu,mcpServerDir:my}))}async function gt(t,e={}){h.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t});try{let r;if(e.body)r=await Xs(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 Xs(`${t}?${n}`)}if(!r.ok){let n=await r.text();throw new Error(`Worker API error (${r.status}): ${n}`)}return h.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 h.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 wT(){try{return(await Xs("/api/health")).ok}catch(t){return h.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}function hy(){if(si()!=="server")return null;let e=ay();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 kT(t){return iy(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 Vr(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function oo(t){let e=hy();if(!e)throw new Je("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 Je("missing_api_key",`${t}: ${e.reason}`);return e}function so(t,e){return async r=>{try{return await e(r)}catch(n){let o=n instanceof Error?n:new Error(String(n));return h.warn("SYSTEM",`${t} failed`,void 0,o),kT(n)}}}var xT=so("observation_add",async t=>{let e=oo("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 Vr(o)});function ci(t){return typeof t=="string"?ni(t):null}var $T=so("observation_record_event",async t=>{let e=oo("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:ci(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{},...t.generate!==void 0?{generate:t.generate}:{}},o=await e.client.recordEvent(n);return Vr(o)}),PT=so("observation_search",async t=>{let e=oo("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:ci(t.platformSource)}:{}},o=await e.client.searchObservations(n);return Vr(o)}),TT=so("observation_context",async t=>{let e=oo("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:ci(t.platformSource)}:{}},o=await e.client.contextObservations(n);return Vr(o)});function RT(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 zT(t){let e=RT(t);return e.length===0?{content:[{type:"text",text:'session_start_context: "project" or "projects" is required'}],isError:!0}:gt("/api/context/inject",{query:{projects:e.join(","),...t.platformSource!==void 0?{platformSource:ci(t.platformSource)}:{},...t.full!==void 0?{full:t.full}:{},...t.colors!==void 0?{colors:t.colors}:{}},text:!0})}var IT=so("observation_generation_status",async t=>{let e=oo("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 Vr(n)});async function OT(){if(await wT())return!0;h.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),ET();try{let t=ju(),e=await Z_(t,Gu);return e==="dead"&&h.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 h.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 gy=[{name:"important_workflow",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
|
|
227
227
|
1. search(query) \u2192 Get index with IDs (~50-100 tokens/result)
|
|
228
228
|
2. timeline(anchor=ID) \u2192 Get context around interesting results
|
|
229
229
|
3. get_observations([IDs]) \u2192 Fetch full details ONLY for filtered IDs
|