claude-mem 13.21.1 → 13.22.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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "13.21.1",
3
+ "version": "13.22.0",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "author": {
6
6
  "name": "Alex Newman",
@@ -98,7 +98,7 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
98
98
  ${m.stack??""}
99
99
  `)}else 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","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.21.1",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})+`
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.22.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(`
@@ -470,7 +470,7 @@ See https://www.postgresql.org/docs/current/libpq-ssl.html for libpq SSL mode de
470
470
  `}
471
471
  # Added by claude-mem installer for Claude Code
472
472
  ${l}
473
- `;a7(o,c+d,"utf-8"),Z.success(`Added Claude Code to PATH in ${o}`)}catch(u){Z.warn(`Could not update ${o}: ${u instanceof Error?u.message:String(u)}`),Z.info(`Run manually: echo '${l}' >> ${o}`);return}process.env.PATH=`${e}:${i}`}async function g7(){let t=rt?'powershell -ExecutionPolicy ByPass -c "irm https://claude.ai/install.ps1 | iex"':"curl -fsSL https://claude.ai/install.sh | bash",e=rt?process.env.ComSpec??"cmd.exe":"/bin/bash",r=Ee?Fs():null;return r?.start("Installing Claude Code (this can take a few minutes \u2014 downloading the native build)\u2026"),new Promise(i=>{let n="",o=ji(t,[],{shell:e,stdio:r?["inherit","pipe","pipe"]:"inherit"});o.stdout?.on("data",s=>{n+=s.toString()}),o.stderr?.on("data",s=>{n+=s.toString()}),o.on("error",s=>{r?.error("Claude Code install failed"),n&&process.stderr.write(n),Z.error(`Claude Code install failed: ${s.message}`),Z.info("You can install it manually later: https://claude.ai/install.sh"),i(!1)}),o.on("exit",s=>{if(s!==0){r?.error("Claude Code install failed"),n&&process.stderr.write(n),Z.error(`Claude Code install failed (exit ${s??"unknown"})`),Z.info("You can install it manually later: https://claude.ai/install.sh"),i(!1);return}if(r?.stop("Claude Code installed"),!rt)try{y7()}catch(a){Z.warn(`Could not auto-apply PATH setup: ${a instanceof Error?a.message:String(a)}`)}i(!0)})})}async function b7(){let t=cc(),e=t.find(o=>o.id==="claude-code");if(e&&!e.detected){Z.warn("Claude Code is not installed. Claude-mem works best in Claude Code, but also works with the IDEs below.");let o=await Wl({message:"Install Claude Code now?",options:[{value:"install",label:"Yes \u2014 install Claude Code (recommended)"},{value:"skip",label:"No \u2014 pick another IDE below"},{value:"cancel",label:"Cancel installation"}],initialValue:"install"});(At(o)||o==="cancel")&&(Rt("Installation cancelled."),process.exit(0)),o==="install"&&await g7()&&(t=cc())}t.filter(o=>o.detected).length===0&&Z.warn("No supported IDEs detected \u2014 pick the one(s) you plan to use.");let i=t.map(o=>{let s=o.detected?" [detected]":"";return{value:o.id,label:o.label,hint:`${o.hint}${s}`}}),n=await Lb({message:"Which IDEs do you use?",options:i,initialValues:[],required:!0});return At(n)&&(Rt("Installation cancelled."),process.exit(0)),n}function vM(){let t=ct(),e=Sd();Ns(t);let r=[".agents",".codex-plugin","plugin","package.json","package-lock.json","openclaw","dist","LICENSE","README.md","CHANGELOG.md"];for(let i of r){let n=Zt(e,i),o=Zt(t,i);bn(n)&&(bn(o)&&pM(o,{recursive:!0,force:!0}),uM(n,o,{recursive:!0,force:!0}))}}function SM(t){let e=Eb(),r=$s(t);pM(r,{recursive:!0,force:!0}),Ns(r),uM(e,r,{recursive:!0,force:!0})}function EM(t,e,r,i){Xs(t,e,r,i),Xs(Zt(t,"plugin"),e,r,i)}async function wM(t){let e=ct(),r=Zt(e,"package.json");if(!bn(r))return;let i=["install","--omit=dev","--ignore-scripts"],n=await Ov(e,i);if(n.code===0)return;n.timedOut&&bt("ABORT",{component:"marketplace-npm-install",phase:"marketplace-deps",cause:new Error("npm install timed out"),details:n.stderr.slice(0,4e3)},t),yK(n.stderr)||bt("ABORT",{component:"marketplace-npm-install",phase:"marketplace-deps",cause:new Error(`npm install failed (exit ${n.code})`),details:n.stderr.slice(0,4e3)},t),Z.warn("npm reported an ERESOLVE peer-dependency conflict in marketplace deps; retrying once with --legacy-peer-deps."),Z.warn(gK(n.stderr));let o=await Ov(e,[...i,"--legacy-peer-deps"]);if(o.code===0){t.warnings.push({component:"marketplace-npm-install",message:"tree-sitter peer-dep ERESOLVE was resolved with the --legacy-peer-deps fallback. Benign for the marketplace install; re-evaluate when tree-sitter peer ranges change.",remediation:"No action required."});return}bt("ABORT",{component:"marketplace-npm-install",phase:"marketplace-deps",cause:new Error(`npm install --legacy-peer-deps still failed (exit ${o.code}): ERESOLVE`),details:o.stderr.slice(0,4e3)},t)}function or(t){let e=ut;try{let r={},i=!1;if(bn(e))try{let o=Nt(TE(e,"utf-8"));o&&typeof o=="object"&&(r=o,i=typeof r.env=="object"&&r.env!==null)}catch(o){console.warn("[install] Failed to parse existing settings.json, starting from empty:",o instanceof Error?o.message:String(o)),r={}}else{let o=hM(e);bn(o)||dM(o,{recursive:!0})}let n=i?r.env:r;for(let[o,s]of Object.entries(t))n[o]=s;lt(e,r);try{s7(e,384)}catch(o){Z.warn(`Could not restrict permissions on ${e} to 0600: ${o instanceof Error?o.message:String(o)}`)}return!0}catch(r){return Z.error(`Failed to write settings to ${e}: ${r instanceof Error?r.message:String(r)}`),!1}}function aM(){try{return Lo(ut)??{}}catch{return{}}}function v7(){try{let t=Lo(ut)?.CLAUDE_MEM_CLAUDE_AUTH_METHOD;return t==="subscription"||t==="api-key"||t==="gateway"?t:void 0}catch{return}}function kM(){let t=v7();if(t)return t;let e=fR();return e.ANTHROPIC_BASE_URL?.trim()?"gateway":e.ANTHROPIC_API_KEY?.trim()?"api-key":"subscription"}async function E7(t){if(t.runtime!==void 0){let r=op(t.runtime);return r===null&&(Z.error(`Unknown --runtime: ${t.runtime}. Allowed: worker, server`),process.exit(1)),r==="server"?(await w7(t),"server"):(or({CLAUDE_MEM_RUNTIME:"worker"}),"worker")}if(!Ee)return or({CLAUDE_MEM_RUNTIME:"worker"}),"worker";let e=await Wl({message:"Which runtime should claude-mem start after install?",options:[{value:"worker",label:"Worker",hint:"stable compatibility path"},{value:"server",label:"Server (beta)",hint:"REST V1, API keys, team-ready storage"}],initialValue:"worker"});return At(e)&&(Rt("Installation cancelled."),process.exit(0)),or({CLAUDE_MEM_RUNTIME:e}),e==="server"&&await xM(),e}async function w7(t){let e=(t.serverUrl??"").trim()||S7;or({CLAUDE_MEM_RUNTIME:"server",CLAUDE_MEM_SERVER_URL:e}),Z.info(`Server runtime selected. Bring up the bundled stack with \`docker compose up -d postgres valkey claude-mem-server claude-mem-worker\` (pg + redis/valkey). The server listens at ${e}.`),Z.info(`IDE MCP config target for the server runtime: http ${e.replace(/\/+$/,"")}/mcp`),await xM()}async function xM(){if(!process.env.CLAUDE_MEM_SERVER_DATABASE_URL){Z.warn("Skipping local hook API key bootstrap: CLAUDE_MEM_SERVER_DATABASE_URL is not set. Run `npx claude-mem server keys rotate` after configuring Postgres to provision a key.");return}try{await k7()}catch(t){Z.warn(`Failed to bootstrap server API key: ${t instanceof Error?t.message:String(t)}. Hooks will fall back to the worker until you run \`npx claude-mem server keys rotate\`.`)}}async function k7(){let{bootstrapServerApiKey:t,persistServerSettings:e}=await Promise.resolve().then(()=>(ef(),Qp)),r=await t();e(ut,{apiKey:r.rawKey,projectId:r.projectId}),Z.info(`Provisioned local hook API key (project=${r.projectId.slice(0,8)}\u2026). Settings saved with mode 0600.`)}function IM(t){try{process.platform==="darwin"?tf("open",[t],{stdio:"ignore"}):process.platform==="win32"?tf("cmd",["/c","start","",t],{stdio:"ignore"}):tf("xdg-open",[t],{stdio:"ignore"})}catch{}}async function x7(t,e,r){let i=vr("CLAUDE_MEM_PROVIDER")||"claude",n=aM(),o=_=>{let C=_??kM();or({CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:C})&&Z.info("Saved Claude Agent SDK configuration to ~/.claude-mem/settings.json")},s=()=>{or(CK(n))||(Rt("Could not save the local Anthropic Max configuration."),process.exit(1)),mR({ANTHROPIC_API_KEY:"",ANTHROPIC_BASE_URL:"",ANTHROPIC_AUTH_TOKEN:""}),Z.info("Disabled cloud sync and saved local Anthropic Max configuration."),Z.info("Configured claude-mem to use your logged-in Claude SDK account.")},a;if(t.provider)a=t.provider;else{if(!Ee)throw new Error("Non-interactive provider validation did not run.");let _=EK();for(;;){let C=await Lb({message:SK,options:[{value:"cmem",label:_.cmem,hint:_.cmemHint},{value:"claude",label:_.claude,hint:_.claudeHint}],initialValues:[],required:!0});if(At(C)&&(Rt("Installation cancelled."),process.exit(1)),C.length===1){a=C[0];break}Z.warn("Select exactly one provider.")}}if(a==="cmem"){if(!e)throw new Error("CMEM Pro requires a signed-in claude-mem account.");let _=await RM(e,r);_||(Rt("CMEM Pro setup was not completed. Run npx claude-mem install to try again."),process.exit(1));let C=_K(_,n);return C||(Rt("CMEM Pro did not return memory credentials. Run npx claude-mem install to try again."),process.exit(1)),or(TK(C))||(Rt("Could not save the CMEM Pro configuration."),process.exit(1)),C.clearFallback&&Rv(),Z.info("CMEM Pro configured with your signed-in memory key."),"openrouter"}if(a==="claude")return s(),"claude";let l=a==="gemini"?"Gemini":"OpenRouter",c=a==="gemini"?"CLAUDE_MEM_GEMINI_API_KEY":"CLAUDE_MEM_OPENROUTER_API_KEY",u=vr(c),d=a==="openrouter"?String(vr("CLAUDE_MEM_OPENROUTER_BASE_URL")??""):"",f=a==="openrouter"&&No(d);if(u&&u.trim().length>0&&!f)return or({CLAUDE_MEM_PROVIDER:a})&&Z.info(`Saved provider=${a} to ~/.claude-mem/settings.json`),a;if(!Ee)throw new Error(`Non-interactive ${l} configuration is missing a personal API key.`);let p=await $A({message:`Paste your ${l} API key:`,mask:"*",validate:_=>!_||_.trim().length===0?"API key required":void 0});if(At(p))return Z.warn("API key prompt cancelled \u2014 falling back to Claude provider."),o(),"claude";let m=String(p).trim(),y=a==="openrouter"?OK(m,aM(),Ue.getAllDefaults().CLAUDE_MEM_OPENROUTER_MODEL):{CLAUDE_MEM_PROVIDER:a,[c]:m};return or(y)&&Z.info(`Saved provider=${a} to ~/.claude-mem/settings.json`),a}async function I7(t){let e=new Set(["claude-haiku-4-5-20251001","claude-sonnet-5","claude-opus-4-8"]),r=kM()==="gateway";if(t.model&&!r){if(!e.has(t.model))throw new Error(`Unknown Claude model: ${t.model}. Allowed: ${[...e].join(", ")}`);or({CLAUDE_MEM_MODEL:t.model})&&Z.info(`Saved Claude model=${t.model} to ~/.claude-mem/settings.json`);return}if(t.model&&r){or({CLAUDE_MEM_MODEL:t.model})&&Z.info(`Saved gateway model=${t.model} to ~/.claude-mem/settings.json`);return}if(!Ee)return;let i=vr("CLAUDE_MEM_MODEL");if(r){let l=await JA({message:"Which model should the gateway use?",placeholder:"claude-haiku-4-5-20251001",defaultValue:i||"claude-haiku-4-5-20251001",validate:d=>!d||d.trim().length===0?"Model required":void 0});At(l)&&(Rt("Installation cancelled."),process.exit(0));let c=String(l).trim();or({CLAUDE_MEM_MODEL:c})&&Z.info(`Saved gateway model=${c} to ~/.claude-mem/settings.json`);return}let n=e.has(i)?i:"claude-haiku-4-5-20251001",o=await Wl({message:`Which Claude model should claude-mem use to compress observations?
473
+ `;a7(o,c+d,"utf-8"),Z.success(`Added Claude Code to PATH in ${o}`)}catch(u){Z.warn(`Could not update ${o}: ${u instanceof Error?u.message:String(u)}`),Z.info(`Run manually: echo '${l}' >> ${o}`);return}process.env.PATH=`${e}:${i}`}async function g7(){let t=rt?'powershell -ExecutionPolicy ByPass -c "irm https://claude.ai/install.ps1 | iex"':"curl -fsSL https://claude.ai/install.sh | bash",e=rt?process.env.ComSpec??"cmd.exe":"/bin/bash",r=Ee?Fs():null;return r?.start("Installing Claude Code (this can take a few minutes \u2014 downloading the native build)\u2026"),new Promise(i=>{let n="",o=ji(t,[],{shell:e,stdio:r?["inherit","pipe","pipe"]:"inherit"});o.stdout?.on("data",s=>{n+=s.toString()}),o.stderr?.on("data",s=>{n+=s.toString()}),o.on("error",s=>{r?.error("Claude Code install failed"),n&&process.stderr.write(n),Z.error(`Claude Code install failed: ${s.message}`),Z.info("You can install it manually later: https://claude.ai/install.sh"),i(!1)}),o.on("exit",s=>{if(s!==0){r?.error("Claude Code install failed"),n&&process.stderr.write(n),Z.error(`Claude Code install failed (exit ${s??"unknown"})`),Z.info("You can install it manually later: https://claude.ai/install.sh"),i(!1);return}if(r?.stop("Claude Code installed"),!rt)try{y7()}catch(a){Z.warn(`Could not auto-apply PATH setup: ${a instanceof Error?a.message:String(a)}`)}i(!0)})})}async function b7(){let t=cc(),e=t.find(s=>s.id==="claude-code");if(e&&!e.detected){Z.warn("Claude Code is not installed. Claude-mem works best in Claude Code, but also works with the IDEs below.");let s=await Wl({message:"Install Claude Code now?",options:[{value:"install",label:"Yes \u2014 install Claude Code (recommended)"},{value:"skip",label:"No \u2014 pick another IDE below"},{value:"cancel",label:"Cancel installation"}],initialValue:"install"});(At(s)||s==="cancel")&&(Rt("Installation cancelled."),process.exit(0)),s==="install"&&await g7()&&(t=cc())}t.filter(s=>s.detected).length===0&&Z.warn("No supported IDEs detected \u2014 pick the one(s) you plan to use.");let i=t.map(s=>{let a=s.detected?" [detected]":"";return{value:s.id,label:s.label,hint:`${s.hint}${a}`}}),n=t.filter(s=>s.detected||s.id==="claude-code").map(s=>s.id),o=await Lb({message:"Which IDEs do you use?",options:i,initialValues:n,required:!0});return At(o)&&(Rt("Installation cancelled."),process.exit(0)),o}function vM(){let t=ct(),e=Sd();Ns(t);let r=[".agents",".codex-plugin","plugin","package.json","package-lock.json","openclaw","dist","LICENSE","README.md","CHANGELOG.md"];for(let i of r){let n=Zt(e,i),o=Zt(t,i);bn(n)&&(bn(o)&&pM(o,{recursive:!0,force:!0}),uM(n,o,{recursive:!0,force:!0}))}}function SM(t){let e=Eb(),r=$s(t);pM(r,{recursive:!0,force:!0}),Ns(r),uM(e,r,{recursive:!0,force:!0})}function EM(t,e,r,i){Xs(t,e,r,i),Xs(Zt(t,"plugin"),e,r,i)}async function wM(t){let e=ct(),r=Zt(e,"package.json");if(!bn(r))return;let i=["install","--omit=dev","--ignore-scripts"],n=await Ov(e,i);if(n.code===0)return;n.timedOut&&bt("ABORT",{component:"marketplace-npm-install",phase:"marketplace-deps",cause:new Error("npm install timed out"),details:n.stderr.slice(0,4e3)},t),yK(n.stderr)||bt("ABORT",{component:"marketplace-npm-install",phase:"marketplace-deps",cause:new Error(`npm install failed (exit ${n.code})`),details:n.stderr.slice(0,4e3)},t),Z.warn("npm reported an ERESOLVE peer-dependency conflict in marketplace deps; retrying once with --legacy-peer-deps."),Z.warn(gK(n.stderr));let o=await Ov(e,[...i,"--legacy-peer-deps"]);if(o.code===0){t.warnings.push({component:"marketplace-npm-install",message:"tree-sitter peer-dep ERESOLVE was resolved with the --legacy-peer-deps fallback. Benign for the marketplace install; re-evaluate when tree-sitter peer ranges change.",remediation:"No action required."});return}bt("ABORT",{component:"marketplace-npm-install",phase:"marketplace-deps",cause:new Error(`npm install --legacy-peer-deps still failed (exit ${o.code}): ERESOLVE`),details:o.stderr.slice(0,4e3)},t)}function or(t){let e=ut;try{let r={},i=!1;if(bn(e))try{let o=Nt(TE(e,"utf-8"));o&&typeof o=="object"&&(r=o,i=typeof r.env=="object"&&r.env!==null)}catch(o){console.warn("[install] Failed to parse existing settings.json, starting from empty:",o instanceof Error?o.message:String(o)),r={}}else{let o=hM(e);bn(o)||dM(o,{recursive:!0})}let n=i?r.env:r;for(let[o,s]of Object.entries(t))n[o]=s;lt(e,r);try{s7(e,384)}catch(o){Z.warn(`Could not restrict permissions on ${e} to 0600: ${o instanceof Error?o.message:String(o)}`)}return!0}catch(r){return Z.error(`Failed to write settings to ${e}: ${r instanceof Error?r.message:String(r)}`),!1}}function aM(){try{return Lo(ut)??{}}catch{return{}}}function v7(){try{let t=Lo(ut)?.CLAUDE_MEM_CLAUDE_AUTH_METHOD;return t==="subscription"||t==="api-key"||t==="gateway"?t:void 0}catch{return}}function kM(){let t=v7();if(t)return t;let e=fR();return e.ANTHROPIC_BASE_URL?.trim()?"gateway":e.ANTHROPIC_API_KEY?.trim()?"api-key":"subscription"}async function E7(t){if(t.runtime!==void 0){let r=op(t.runtime);return r===null&&(Z.error(`Unknown --runtime: ${t.runtime}. Allowed: worker, server`),process.exit(1)),r==="server"?(await w7(t),"server"):(or({CLAUDE_MEM_RUNTIME:"worker"}),"worker")}if(!Ee)return or({CLAUDE_MEM_RUNTIME:"worker"}),"worker";let e=await Wl({message:"Which runtime should claude-mem start after install?",options:[{value:"worker",label:"Worker",hint:"stable compatibility path"},{value:"server",label:"Server (beta)",hint:"REST V1, API keys, team-ready storage"}],initialValue:"worker"});return At(e)&&(Rt("Installation cancelled."),process.exit(0)),or({CLAUDE_MEM_RUNTIME:e}),e==="server"&&await xM(),e}async function w7(t){let e=(t.serverUrl??"").trim()||S7;or({CLAUDE_MEM_RUNTIME:"server",CLAUDE_MEM_SERVER_URL:e}),Z.info(`Server runtime selected. Bring up the bundled stack with \`docker compose up -d postgres valkey claude-mem-server claude-mem-worker\` (pg + redis/valkey). The server listens at ${e}.`),Z.info(`IDE MCP config target for the server runtime: http ${e.replace(/\/+$/,"")}/mcp`),await xM()}async function xM(){if(!process.env.CLAUDE_MEM_SERVER_DATABASE_URL){Z.warn("Skipping local hook API key bootstrap: CLAUDE_MEM_SERVER_DATABASE_URL is not set. Run `npx claude-mem server keys rotate` after configuring Postgres to provision a key.");return}try{await k7()}catch(t){Z.warn(`Failed to bootstrap server API key: ${t instanceof Error?t.message:String(t)}. Hooks will fall back to the worker until you run \`npx claude-mem server keys rotate\`.`)}}async function k7(){let{bootstrapServerApiKey:t,persistServerSettings:e}=await Promise.resolve().then(()=>(ef(),Qp)),r=await t();e(ut,{apiKey:r.rawKey,projectId:r.projectId}),Z.info(`Provisioned local hook API key (project=${r.projectId.slice(0,8)}\u2026). Settings saved with mode 0600.`)}function IM(t){try{process.platform==="darwin"?tf("open",[t],{stdio:"ignore"}):process.platform==="win32"?tf("cmd",["/c","start","",t],{stdio:"ignore"}):tf("xdg-open",[t],{stdio:"ignore"})}catch{}}async function x7(t,e,r){let i=vr("CLAUDE_MEM_PROVIDER")||"claude",n=aM(),o=_=>{let C=_??kM();or({CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:C})&&Z.info("Saved Claude Agent SDK configuration to ~/.claude-mem/settings.json")},s=()=>{or(CK(n))||(Rt("Could not save the local Anthropic Max configuration."),process.exit(1)),mR({ANTHROPIC_API_KEY:"",ANTHROPIC_BASE_URL:"",ANTHROPIC_AUTH_TOKEN:""}),Z.info("Disabled cloud sync and saved local Anthropic Max configuration."),Z.info("Configured claude-mem to use your logged-in Claude SDK account.")},a;if(t.provider)a=t.provider;else{if(!Ee)throw new Error("Non-interactive provider validation did not run.");let _=EK();for(;;){let C=await Lb({message:SK,options:[{value:"cmem",label:_.cmem,hint:_.cmemHint},{value:"claude",label:_.claude,hint:_.claudeHint}],initialValues:["cmem"],required:!0});if(At(C)&&(Rt("Installation cancelled."),process.exit(1)),C.length===1){a=C[0];break}Z.warn("Select exactly one provider.")}}if(a==="cmem"){if(!e)throw new Error("CMEM Pro requires a signed-in claude-mem account.");let _=await RM(e,r);_||(Rt("CMEM Pro setup was not completed. Run npx claude-mem install to try again."),process.exit(1));let C=_K(_,n);return C||(Rt("CMEM Pro did not return memory credentials. Run npx claude-mem install to try again."),process.exit(1)),or(TK(C))||(Rt("Could not save the CMEM Pro configuration."),process.exit(1)),C.clearFallback&&Rv(),Z.info("CMEM Pro configured with your signed-in memory key."),"openrouter"}if(a==="claude")return s(),"claude";let l=a==="gemini"?"Gemini":"OpenRouter",c=a==="gemini"?"CLAUDE_MEM_GEMINI_API_KEY":"CLAUDE_MEM_OPENROUTER_API_KEY",u=vr(c),d=a==="openrouter"?String(vr("CLAUDE_MEM_OPENROUTER_BASE_URL")??""):"",f=a==="openrouter"&&No(d);if(u&&u.trim().length>0&&!f)return or({CLAUDE_MEM_PROVIDER:a})&&Z.info(`Saved provider=${a} to ~/.claude-mem/settings.json`),a;if(!Ee)throw new Error(`Non-interactive ${l} configuration is missing a personal API key.`);let p=await $A({message:`Paste your ${l} API key:`,mask:"*",validate:_=>!_||_.trim().length===0?"API key required":void 0});if(At(p))return Z.warn("API key prompt cancelled \u2014 falling back to Claude provider."),o(),"claude";let m=String(p).trim(),y=a==="openrouter"?OK(m,aM(),Ue.getAllDefaults().CLAUDE_MEM_OPENROUTER_MODEL):{CLAUDE_MEM_PROVIDER:a,[c]:m};return or(y)&&Z.info(`Saved provider=${a} to ~/.claude-mem/settings.json`),a}async function I7(t){let e=new Set(["claude-haiku-4-5-20251001","claude-sonnet-5","claude-opus-4-8"]),r=kM()==="gateway";if(t.model&&!r){if(!e.has(t.model))throw new Error(`Unknown Claude model: ${t.model}. Allowed: ${[...e].join(", ")}`);or({CLAUDE_MEM_MODEL:t.model})&&Z.info(`Saved Claude model=${t.model} to ~/.claude-mem/settings.json`);return}if(t.model&&r){or({CLAUDE_MEM_MODEL:t.model})&&Z.info(`Saved gateway model=${t.model} to ~/.claude-mem/settings.json`);return}if(!Ee)return;let i=vr("CLAUDE_MEM_MODEL");if(r){let l=await JA({message:"Which model should the gateway use?",placeholder:"claude-haiku-4-5-20251001",defaultValue:i||"claude-haiku-4-5-20251001",validate:d=>!d||d.trim().length===0?"Model required":void 0});At(l)&&(Rt("Installation cancelled."),process.exit(0));let c=String(l).trim();or({CLAUDE_MEM_MODEL:c})&&Z.info(`Saved gateway model=${c} to ~/.claude-mem/settings.json`);return}let n=e.has(i)?i:"claude-haiku-4-5-20251001",o=await Wl({message:`Which Claude model should claude-mem use to compress observations?
474
474
  This runs whenever you and Claude touch a file \u2014 keep it cheap and fast.`,options:[{value:"claude-haiku-4-5-20251001",label:"Haiku 4.5 (recommended \u2014 fast, cheap, great for compression)"},{value:"claude-sonnet-5",label:"Sonnet 5 (balanced quality and cost)"},{value:"claude-opus-4-8",label:"Opus 4.8 (highest quality, slowest)"}],initialValue:n});At(o)&&(Rt("Installation cancelled."),process.exit(0));let s=o;or({CLAUDE_MEM_MODEL:s})&&Z.info(`Saved Claude model=${s} to ~/.claude-mem/settings.json`)}function rn(t){return typeof t=="string"&&t.trim().length>0?t.trim():null}function IE(t,e){let r=rn(t);if(!r)return null;try{let i=new URL(r),n=new URL(ap).origin;return i.origin!==n||i.pathname!==e||i.username||i.password||i.hash?null:i}catch{return null}}function lM(t,e){let r=[...t.searchParams.entries()],i=Object.entries(e);return r.length===i.length&&i.every(([n,o])=>t.searchParams.get(n)===o)}function A7(t,e){if([...t.searchParams.entries()].length!==2||t.searchParams.get("pairing")!==e)return!1;let i=t.searchParams.get("trial");if(i===null||!/^[0-9]{1,3}$/.test(i))return!1;let n=Number(i);return n>=1&&n<=365}function _M(t){if(!t||typeof t!="object")return null;let e=t,r=rn(e.pairing_id),i=rn(e.secret),n=rn(e.user_code),o=IE(e.authorization_url,"/login"),s=IE(e.checkout_url,"/api/pro/trial/claim");if(!r||!/^[0-9a-f]{32}$/.test(r)||!i||!/^[0-9a-f]{48}$/.test(i)||!n||!/^[A-HJ-KM-NP-TV-Z2-9]{4}-[A-HJ-KM-NP-TV-Z2-9]{4}$/.test(n)||!o||!s)return null;let a=new URL(ap).origin,l=o.searchParams.get("next");if(!l||!l.startsWith("/")||l.startsWith("//")||!lM(o,{next:l}))return null;let c=IE(`${a}${l}`,"/api/pro/trial/claim");if(!c||!lM(c,{pairing:r,login_only:"1"})||!A7(s,r))return null;let u=typeof e.poll_interval=="number"&&Number.isFinite(e.poll_interval)&&e.poll_interval>0?Math.min(Math.max(e.poll_interval,1),30):O7;return{pairingId:r,secret:i,userCode:n,authorizationUrl:o.toString(),checkoutUrl:s.toString(),pollIntervalMs:u*1e3}}async function TM(){let t=new AbortController,e=setTimeout(()=>t.abort(),_7);try{let r=await fetch(ap,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:"npx-installer",device_name:mM()}),signal:t.signal});return r.ok?_M(await r.json()):null}catch{return null}finally{clearTimeout(e)}}function CE(t,e=mM()){return{CLAUDE_MEM_CLOUD_SYNC_TOKEN:t.setupToken,CLAUDE_MEM_CLOUD_SYNC_USER_ID:t.userId,CLAUDE_MEM_CLOUD_SYNC_HUB_URL:t.hubUrl,CLAUDE_MEM_CLOUD_SYNC_DEVICE_ID:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_NAME:e,CLAUDE_MEM_PRO_TRIAL_STATE:"active",CLAUDE_MEM_PRO_TRIAL_ENDS_AT:t.trialEndsAt??"",CLAUDE_MEM_PRO_PLAN:t.plan,CLAUDE_MEM_PRO_MEMORY_KEY:t.memoryKey,CLAUDE_MEM_PRO_MEMORY_BASE_URL:t.memoryBaseUrl,CLAUDE_MEM_PRO_MEMORY_MODEL:t.memoryModel,CLAUDE_MEM_PRO_FALLBACK_AT:""}}function CM(t){if(!t||typeof t!="object")return null;let e=t,r=rn(e.user_id),i=rn(e.setup_token),n=rn(e.hub_url);return e.status!=="ready"||!r||!i||!n?null:{userId:r,setupToken:i,hubUrl:n,memoryKey:rn(e.memory_key)??i,memoryBaseUrl:rn(e.memory_base_url)??lp,memoryModel:rn(e.memory_model)??Qs,plan:e.plan==="trial"||e.plan==="pro"||e.plan==="none"?e.plan:"trial",trialEndsAt:rn(e.trial?.ends_at)}}async function R7(t){let e=new AbortController,r=setTimeout(()=>e.abort(),T7);try{let i=await fetch(wK,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pairing_id:t.pairingId,secret:t.secret}),signal:e.signal});if(i.status===404||i.status===410)return{kind:"gone"};let n=await i.json().catch(()=>({}));if(i.status===202)return{kind:"pending",stage:n.stage==="awaiting_checkout"||n.stage==="awaiting_approval"?n.stage:"awaiting_login"};if(i.ok&&n.status==="authenticated"){let o=rn(n.user_id);return o?{kind:"authenticated",userId:o}:{kind:"unreachable"}}if(i.ok){let o=CM(n);return o?{kind:"ready",...o}:{kind:"unreachable"}}return{kind:"unreachable"}}catch{return{kind:"unreachable"}}finally{clearTimeout(r)}}function K7(t,e){return new Promise(r=>{let i=Date.now(),n=setInterval(()=>{(e()||Date.now()-i>=t)&&(clearInterval(n),r())},250)})}async function OM(t,e,r){let i=Date.now(),n={awaiting_login:"Waiting for OAuth login in the browser\u2026",awaiting_checkout:e==="login"?"Waiting for the browser to finish signing you in\u2026":"Waiting for CMEM Pro setup in the browser\u2026",awaiting_approval:`Enter code ${t.userCode} in the browser to approve this device\u2026`},o=e==="login"?"awaiting_login":"awaiting_checkout";Z.info(n[o]);let s=!1,a=f=>{(typeof f=="string"?f.includes(""):f.includes(3))&&(s=!0)},l=()=>{s=!0},c=process.stdin.isTTY===!0,u=process.stdin.isRaw===!0,d=!1;c&&(process.stdin.on("data",a),u||(process.stdin.setRawMode(!0),d=!0),process.stdin.resume()),process.on("SIGINT",l);try{let f=0;for(;Date.now()-i<C7;){if(s)return null;let p=await R7(t);if(s)return null;if(p.kind==="authenticated"&&e==="login"||p.kind==="ready")return p;if(p.kind==="gone")return Z.error("This browser authorization expired. Run the installer again."),null;if(p.kind==="unreachable"){if(f+=1,f>=3)return Z.error("cmem.ai is not responding. Run the installer again when it is reachable."),null}else f=0,p.kind==="pending"&&p.stage!==o&&(o=p.stage,Z.info(n[o]));await K7(t.pollIntervalMs,()=>s)}return await Kn("installer_oauth_timeout",{version:r,phase:e,duration_ms:Date.now()-i}),Z.error("Browser authorization timed out. Run the installer again."),null}finally{process.off("SIGINT",l),c&&(process.stdin.off("data",a),d&&process.stdin.setRawMode(!1),process.stdin.pause())}}async function AM(t,e){let r=await OM(t,"login",e);if(!r)return!1;if(r.kind==="ready"){if(!or(CE(r)))return!1;t.delivered=r}return Z.success("OAuth login complete."),await Kn("installer_oauth_completed",{version:e}),r.kind==="authenticated"||r.kind==="ready"}async function D7(t){!Ee||process.stdin.isTTY!==!0||(Z.info(t),await new Promise(e=>{let r=process.stdin.isRaw===!0,i=!1,n=()=>{process.stdin.off("data",o),i&&process.stdin.setRawMode(!1),process.stdin.pause(),e()},o=s=>{let a=typeof s=="string"?s:s.toString("utf8");(a.includes("\r")||a.includes(`
475
475
  `)||a.includes(""))&&n()};r||(process.stdin.setRawMode(!0),i=!0),process.stdin.resume(),process.stdin.on("data",o)}))}async function P7(t){let e=Ee?Fs():null;e?.start("Starting secure OAuth login\u2026");let r=await TM();return r?(e?.stop("OAuth login ready."),Z.info(`Open this URL: ${r.authorizationUrl}`),await D7("Continue setup in browser... (hit return to open automatically)"),IM(r.authorizationUrl),await Kn("installer_oauth_started",{version:t}),await AM(r,t)?r:null):(e?.stop(z("red","Could not start OAuth login.")),Z.error("OAuth login is required. Run npx claude-mem install again when cmem.ai is reachable."),null)}function j7(t){let e=[z(["bold","cyan"],t.userCode),"","Enter this code in the browser to approve this device."].join(`
476
476
  `);Ee?Di(e,"Your device code"):Z.info(`Device code: ${t.userCode}`)}async function RM(t,e){if(t.delivered)return t.delivered;j7(t),Z.info(`Continue CMEM Pro setup: ${t.checkoutUrl}`),IM(t.checkoutUrl);let r=await OM(t,"enrollment",e);return!r||r.kind!=="ready"?null:or(CE(r))?(t.delivered=r,Rv(),Z.success("CMEM Pro Free Trial active."),await Kn("trial_activated",{version:e}),r):(Z.error("Could not save the one-time CMEM Pro credentials."),null)}async function M7(){if(!Ee||process.env.CI)return;let t=process.env.DO_NOT_TRACK;if(t!==void 0&&t!==""&&t!=="0"&&t!=="false")return;let e=Pi();if(e?.enabled!==void 0)return;Ae.message(z("dim",`Anonymous install ID only \u2014 no prompts, file paths, code, or project names, ever.
@@ -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.21.1",
6
+ "version": "13.22.0",
7
7
  "license": "Apache-2.0",
8
8
  "author": "thedotmack",
9
9
  "homepage": "https://claude-mem.ai",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "13.21.1",
3
+ "version": "13.22.0",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "keywords": [
6
6
  "claude",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "13.21.1",
3
+ "version": "13.22.0",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "author": {
6
6
  "name": "Alex Newman"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "13.21.1",
3
+ "version": "13.22.0",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "author": {
6
6
  "name": "Alex Newman",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem-plugin",
3
- "version": "13.21.1",
3
+ "version": "13.22.0",
4
4
  "private": true,
5
5
  "description": "Runtime dependencies for claude-mem bundled hooks",
6
6
  "type": "module",
@@ -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.21.1";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.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):
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
@@ -63,7 +63,7 @@ ${s.stack}`:` ${s.message}`;else if(this.getLevel()===0&&typeof s=="object")try{
63
63
  ${m.stack??""}
64
64
  `)}else wo(p+`
65
65
  `)}debug(e,r,n,i){this.log(0,e,r,n,i)}info(e,r,n,i){this.log(1,e,r,n,i)}warn(e,r,n,i){this.log(2,e,r,n,i)}setErrorSink(e){eE=e}error(e,r,n,i){this.log(3,e,r,n,i),this.routeErrorToSink(r,n,i)}routeErrorToSink(e,r,n){try{if(!eE||!(n instanceof Error))return;eE(n)}catch{}}dataIn(e,r,n,i){this.info(e,`\u2192 ${r}`,n,i)}dataOut(e,r,n,i){this.info(e,`\u2190 ${r}`,n,i)}success(e,r,n,i){this.info(e,`\u2713 ${r}`,n,i)}failure(e,r,n,i){this.error(e,`\u2717 ${r}`,n,i)}},x=new rE});function XP(){let t=[];t.push(nE.default.json({limit:"5mb"})),t.push((n,i,s)=>{let o=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(f=>n.path.endsWith(f)),c=n.path==="/api/logs";if(n.path.startsWith("/health")||n.path==="/"||o||c)return s();let l=Date.now(),u=`${n.method}-${Date.now()}`,d=dre(n.method,n.path,n.body);x.debug("HTTP",`\u2192 ${n.method} ${n.path}`,{requestId:u},d);let p=i.send.bind(i);i.send=function(f){let m=Date.now()-l;return x.debug("HTTP",`\u2190 ${i.statusCode} ${n.path}`,{requestId:u,duration:`${m}ms`}),p(f)},s()});let e=ea(),r=QP.default.join(e,"plugin","ui");return t.push(nE.default.static(r)),t}function ZP(){return(t,e,r)=>{let n=t.headers.origin;if(n){if(!n.startsWith("http://localhost:")&&!n.startsWith("http://127.0.0.1:")){r(new Error("CORS not allowed"));return}e.setHeader("Access-Control-Allow-Origin",n),e.setHeader("Vary","Origin")}if(t.method==="OPTIONS"){e.setHeader("Access-Control-Allow-Methods","GET,HEAD,POST,PUT,PATCH,DELETE"),e.setHeader("Access-Control-Allow-Headers","Content-Type,Authorization,X-Requested-With"),e.status(204).end();return}r()}}function Xp(t,e,r){let n=t.ip||t.connection.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){x.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:t.path,clientIp:n,method:t.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}r()}function dre(t,e,r){if(!r||Object.keys(r).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=r.tool_name||"?",i=r.tool_input;return`tool=${x.formatTool(n,i)}`}return e.includes("/summarize")?"requesting summary":""}var nE,QP,eD=R(()=>{"use strict";nE=Ze(Wp(),1),QP=Ze(require("path"),1);Jn();fe()});function tD(t,e,r,n){let i={error:t,message:e};return r&&(i.code=r),n&&(i.details=n),i}function nD(t,e){e.status(404).json(tD("NotFound",`Cannot ${t.method} ${t.path}`))}var Io,rD,iD=R(()=>{"use strict";fe();Io=class extends Error{constructor(r,n=500,i,s){super(r);this.statusCode=n;this.code=i;this.details=s;this.name="AppError"}statusCode;code;details};rD=(t,e,r,n)=>{let i=t instanceof Io?t.statusCode:500;x.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:t.message,code:t instanceof Io?t.code:void 0},t);let s=tD(t.name||"Error",t.message,t instanceof Io?t.code:void 0,t instanceof Io?t.details:void 0);r.status(i).json(s)}});var pre,fre,GRe,sD=R(()=>{"use strict";pre=new Set([".cmd",".bat"]),fre=new Set([".exe",".com"]),GRe=new Set([...fre,...pre])});function ko(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(hre.has(r)){e[r]=n;continue}sE.has(r)||iE.some(i=>r.startsWith(i))||(e[r]=n)}return e}var iE,sE,mre,hre,Ll=R(()=>{"use strict";iE=["CLAUDECODE_","CLAUDE_CODE_"],sE=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),mre=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"]),hre=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",...mre])});function gre(t){aE+=1;let e=(0,oE.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...ko(process.env),LC_ALL:"C",LANG:"C"}});if(e.status===0){let r=e.stdout.trim();return r.length>0?r:null}return null}function bre(t,e=!1){if(!e){let n=aD.get(t);if(n&&Date.now()-n.capturedAtMs<yre)return n.token}let r=null;try{r=gre(t)}catch(n){x.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:n instanceof Error?n.message:String(n)}),r=null}return aD.set(t,{token:r,capturedAtMs:Date.now()}),r}function cD(t,e){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux"){aE+=1;try{let r=(0,oD.readFileSync)(`/proc/${t}/stat`,"utf-8"),n=r.lastIndexOf(") ");if(n<0)return null;let s=r.slice(n+2).split(" ")[19];return s&&/^\d+$/.test(s)?s:null}catch(r){return x.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}if(process.platform==="win32")return bre(t,e);aE+=1;try{let r=(0,oE.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...ko(process.env),LC_ALL:"C",LANG:"C"}});if(r.status!==0)return null;let n=r.stdout.trim();return n.length>0?n:null}catch(r){return x.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}function mi(t){return cD(t,!1)}function hi(t,e){if(e===null)return!0;let r=cD(t,!0);return r===null?!0:r===e}var oE,oD,yre,aD,aE,cE=R(()=>{"use strict";oE=require("child_process"),oD=require("fs");fe();Ll();yre=5e3,aD=new Map,aE=0});async function Vi(t,e={}){let r=e.signalMode==="immediate",n=e.expectedStartToken!==void 0?e.expectedStartToken:mi(t),i=()=>hi(t,n);if(!i()){x.warn("PROCESS","Skipping tree-kill: root PID was reused since it was captured",{pid:t});return}if(x.debug("PROCESS",`Killing process tree rooted at PID ${t}`,{immediate:r}),process.platform==="win32"){try{await lE("taskkill",["/PID",String(t),"/T","/F"],{timeout:5e3,windowsHide:!0})}catch(s){let a=s.code,o=String(s.stderr??""),c=s instanceof Error?s.message:String(s);if(a===vre||Ere.test(`${o} ${c}`)){x.debug("PROCESS","taskkill reported the process was already gone",{pid:t});return}throw new Zp(t,`taskkill failed for PID ${t} (exit ${String(a)}): ${o.trim()||c}`,{cause:s})}return}try{let s=r?"SIGKILL":"SIGTERM",a=await ef(t);for(let l of a){if(!hi(l.pid,l.startToken)){x.debug("PROCESS",`Skipping ${s}: descendant PID was reused since enumeration`,{pid:l.pid,rootPid:t});continue}try{process.kill(l.pid,s)}catch{}}if(i())try{process.kill(t,s)}catch(l){let u=l instanceof Error?l:new Error(String(l)),d=u.code;d!=="ESRCH"&&x.debug("PROCESS",`Failed to ${s} PID ${t}`,{code:d},u)}else x.warn("PROCESS","Skipping root signal: PID was reused during descendant enumeration",{pid:t,signal:s});r||await new Promise(l=>setTimeout(l,500));let o=i()?await ef(t):[],c=new Map;for(let l of a)c.set(l.pid,l.startToken);for(let l of o)c.set(l.pid,l.startToken);for(let[l,u]of c){if(!hi(l,u)){x.debug("PROCESS","Skipping SIGKILL: descendant PID was reused since the scan",{pid:l,rootPid:t});continue}try{process.kill(l,"SIGKILL")}catch{}}if(!r&&i())try{process.kill(t,"SIGKILL")}catch{}}catch(s){throw new Zp(t,`tree-kill failed for PID ${t}: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}async function Sre(){return process.platform==="win32"?_re():process.platform==="linux"?xre():wre()}function xre(){let t=[],e;try{e=(0,tf.readdirSync)("/proc")}catch(r){return x.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 n;try{n=(0,tf.readFileSync)(`/proc/${r}/stat`,"utf-8")}catch{continue}let i=n.lastIndexOf(") ");if(i<0)continue;let s=n.slice(i+2).split(" "),a=Number.parseInt(s[1]??"",10),o=s[19];Number.isFinite(a)&&t.push({pid:Number.parseInt(r,10),ppid:a,startToken:o&&/^\d+$/.test(o)?o:null})}return t}async function wre(){let t;try{t=(await lE("ps",["-eo","pid=,ppid=,lstart="],{timeout:1e4,maxBuffer:33554432,env:{...process.env,LC_ALL:"C",LANG:"C"}})).stdout}catch(r){return x.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(`
66
- `)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);if(!n)continue;let i=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:i.length>0?i:null})}return e}async function _re(){let t;try{t=(await lE("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,@{Name='StartToken';Expression={$_.CreationDate.ToString('yyyyMMddHHmmss.ffffff')}} | ConvertTo-Csv -NoTypeInformation"],{timeout:3e4,windowsHide:!0,maxBuffer:33554432})).stdout}catch(r){return x.warn("PROCESS","Cannot enumerate the Windows process table \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),[]}let e=[];for(let r of t.split(/\r?\n/).slice(1)){let n=r.match(/^"(\d+)","(\d+)","(.*)"$/);if(!n)continue;let i=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:i.length>0?i:null})}return e}async function ef(t){let e=await Sre(),r=new Map;for(let a of e){let o=r.get(a.ppid);o?o.push(a):r.set(a.ppid,[a])}let n=new Set([t]),i=[],s=a=>{for(let o of r.get(a)??[])n.has(o.pid)||(n.add(o.pid),s(o.pid),i.push({pid:o.pid,startToken:o.startToken}))};return s(t),i}var lD,tf,uD,lE,vre,Ere,Zp,rf=R(()=>{"use strict";lD=require("child_process"),tf=require("fs"),uD=require("util");fe();cE();lE=(0,uD.promisify)(lD.execFile),vre=128,Ere=/not found|no running instance|no tasks/i,Zp=class extends Error{pid;constructor(e,r,n){super(r,n),this.name="ProcessTreeKillError",this.pid=e}}});function zt(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;return r==="EPERM"?!0:(x.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return x.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function nf(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!zt(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function Hi(t){if(!t||!zt(t.pid))return!1;if(!t.startToken)return!0;let e=mi(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||x.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}function sf(){return uE||(uE=new fE),uE}function dE(){let t=Are.shift();t&&t()}var yi,pE,Ire,kre,Tre,fE,uE,Are,To=R(()=>{"use strict";sD();yi=require("fs"),pE=Ze(require("path"),1);fe();Ll();Jn();cE();rf();Ire=5e3,kre=1e3,Tre=Ue.supervisorRegistry();fE=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=Tre){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,yi.mkdirSync)(pE.default.dirname(this.registryPath),{recursive:!0}),!(0,yi.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,yi.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[i,s]of Object.entries(n))this.entries.set(i,s)}catch(r){r instanceof Error?x.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):x.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&x.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,r,n){this.initialize(),this.entries.set(e,r),n&&this.runtimeProcesses.set(e,n),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"&&dE()}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 n=Date.parse(e.startedAt),i=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(i)?0:i)})}getBySession(e){let r=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[n,i]of this.entries)zt(i.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,i.type==="sdk"&&(r+=1));e>0&&this.persist();for(let n=0;n<r;n+=1)dE();return e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;x.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:n,pids:r.map(o=>o.pid)});let i=r.filter(o=>zt(o.pid)),s=new Map(i.map(o=>[o.pid,mi(o.pid)]));for(let o of i)try{process.platform==="win32"?await Vi(o.pid,{expectedStartToken:s.get(o.pid)??null}):typeof o.pgid=="number"?process.kill(-o.pgid,"SIGTERM"):process.kill(o.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&x.debug("SYSTEM",`Failed to SIGTERM session process PID ${o.pid}`,{pid:o.pid,pgid:o.pgid},c):x.warn("SYSTEM",`Failed to SIGTERM session process PID ${o.pid} (non-Error)`,{pid:o.pid,pgid:o.pgid,error:String(c)})}await nf(i,Ire);let a=i.filter(o=>zt(o.pid));for(let o of a){x.warn("SYSTEM",`Session process PID ${o.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:o.pid,pgid:o.pgid,sessionId:n});let c=s.get(o.pid)??null;if(!hi(o.pid,c)){x.warn("SYSTEM","Skipping SIGKILL: session process PID was reused during the grace window",{pid:o.pid,sessionId:n});continue}try{process.platform==="win32"?await Vi(o.pid,{expectedStartToken:c}):typeof o.pgid=="number"?process.kill(-o.pgid,"SIGKILL"):process.kill(o.pid,"SIGKILL")}catch(l){l instanceof Error?l.code!=="ESRCH"&&x.debug("SYSTEM",`Failed to SIGKILL session process PID ${o.pid}`,{pid:o.pid,pgid:o.pgid},l):x.warn("SYSTEM",`Failed to SIGKILL session process PID ${o.pid} (non-Error)`,{pid:o.pid,pgid:o.pgid,error:String(l)})}}if(a.length>0){let o=Date.now()+kre;for(;Date.now()<o&&a.filter(l=>zt(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let o of r)this.entries.delete(o.id),this.runtimeProcesses.delete(o.id);this.persist();for(let o of r)o.type==="sdk"&&dE();return x.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:n,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,yi.mkdirSync)(pE.default.dirname(this.registryPath),{recursive:!0}),(0,yi.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},uE=null;Are=[]});async function pD(t){let e=t.currentPid??process.pid,r=t.pidFilePath??Rre,n=t.registry.getAll(),i=[...n].filter(c=>c.pid!==e).sort((c,l)=>Date.parse(l.startedAt)-Date.parse(c.startedAt)),s=new Map,a=new Map;for(let c of i){if(!zt(c.pid)){t.registry.unregister(c.id);continue}a.set(c.id,mi(c.pid)),s.set(c.id,await ef(c.pid));try{await dD(c,"SIGTERM")}catch(l){l instanceof Error?x.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:c.pid,pgid:c.pgid,type:c.type},l):x.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(l)})}}await nf(i,5e3);let o=i.filter(c=>zt(c.pid)||(s.get(c.id)??[]).some(l=>zt(l.pid)));for(let c of o){let l=hi(c.pid,a.get(c.id)??null);l||x.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:c.pid,type:c.type});try{l&&await dD(c,"SIGKILL")}catch(u){u instanceof Error?x.debug("SYSTEM","Failed to force kill child process",{pid:c.pid,pgid:c.pgid,type:c.type},u):x.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(u)})}finally{Cre(s.get(c.id)??[],c.pid)}}await nf(o,1e3);for(let c of i)t.registry.unregister(c.id);for(let c of n.filter(l=>l.pid===e))t.registry.unregister(c.id);Ore(r,e),t.registry.pruneDeadEntries()}function Ore(t,e,r=!1){if(!(0,Ao.existsSync)(t))return;let n=null;try{let a=JSON.parse((0,Ao.readFileSync)(t,"utf-8"));n=typeof a.pid=="number"?a.pid:null}catch(a){x.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:a instanceof Error?a.message:String(a)});return}let i=e!==null&&n===e,s=n===null||!zt(n);if(!i&&!(r&&s)){x.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:n,currentPid:e});return}try{(0,Ao.rmSync)(t,{force:!0})}catch(a){a instanceof Error?x.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},a):x.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(a)})}}function Cre(t,e){for(let{pid:r,startToken:n}of t)if(!(r===e||!zt(r))){if(!hi(r,n)){x.debug("SYSTEM","Skipping reap: PID was recycled during the grace window",{pid:r,rootPid:e});continue}try{process.kill(r,"SIGKILL"),x.debug("SYSTEM","Reaped orphaned descendant during shutdown cascade",{pid:r,rootPid:e})}catch(i){let s=i instanceof Error?i.code:void 0;s!=="ESRCH"&&x.warn("SYSTEM","Failed to reap orphaned descendant during shutdown cascade",{pid:r,rootPid:e,errno:s})}}}async function dD(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}if(e==="SIGKILL"){await Vi(r,{signalMode:"immediate"});return}try{process.kill(r,e)}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}return}await Vi(r)}var Ao,Rre,fD=R(()=>{"use strict";Ao=require("fs");fe();To();Jn();rf();Rre=Ue.workerPid()});function jre(){let e=sf().pruneDeadEntries();e>0&&x.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function hD(){Ro===null&&(Ro=setInterval(jre,mD),Ro.unref(),x.debug("SYSTEM","Health checker started",{intervalMs:mD}))}function yD(){Ro!==null&&(clearInterval(Ro),Ro=null,x.debug("SYSTEM","Health checker stopped"))}var mD,Ro,gD=R(()=>{"use strict";fe();To();mD=3e4,Ro=null});function bD(){return Pre}function Dre(t={}){let e=t.pidFilePath??Kre;if(!(0,ta.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,ta.readFileSync)(e,"utf-8"))}catch(i){return i instanceof Error?x.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},i):x.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(i)}),(0,ta.rmSync)(e,{force:!0}),"invalid"}return Hi(r)&&r?((t.logAlive??!0)&&x.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(x.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,ta.rmSync)(e,{force:!0}),"stale")}var ta,Kre,mE,Pre,vD=R(()=>{"use strict";ta=require("fs");fe();To();fD();gD();Jn();Kre=Ue.workerPid(),mE=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(),Dre({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,hD()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){x.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,x.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){i instanceof Error?x.error("SYSTEM","Error during shutdown",{},i):x.error("SYSTEM","Error during shutdown (non-Error)",{error:String(i)});try{await this.stop()}catch(s){s instanceof Error?x.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):x.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(s)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{x.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}yD(),this.stopPromise=pD({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,n){this.registry.register(e,r,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},Pre=new mE(sf())});function hE(t,e,r){t.on("finish",async()=>{try{await r()}finally{process.exit(0)}}),t.json(e)}var ED=R(()=>{"use strict"});function yE(t,e=Date.now){return Math.max(0,Math.floor((e()-t)/1e3))}var SD=R(()=>{"use strict"});function gE(){let t=Array.from(Mre.values()).map(e=>({...e})).sort((e,r)=>e.dependency.localeCompare(r.dependency));return{degraded:t.length>0,statuses:t}}var Mre,xD=R(()=>{"use strict";Mre=new Map});var bE,wD,IOe,_D=R(()=>{"use strict";bE=class{entries=new Map;set(e){if(!e||typeof e!="object")return;let r=e.rateLimitType??"default";this.entries.set(r,{...e,observedAt:Date.now()})}get(e){return e?this.entries.get(e):this.entries.get("default")}getMostRecentByWindow(){return{five_hour:this.entries.get("five_hour"),seven_day:this.entries.get("seven_day"),seven_day_opus:this.entries.get("seven_day_opus"),seven_day_sonnet:this.entries.get("seven_day_sonnet"),overage:this.entries.get("overage")}}get size(){return this.entries.size}},wD=new bE,IOe=900*1e3});function qre(t){t.setHeader("X-Content-Type-Options","nosniff"),t.setHeader("X-Frame-Options","DENY"),t.setHeader("X-DNS-Prefetch-Control","off"),t.setHeader("Referrer-Policy","no-referrer"),t.setHeader("Cross-Origin-Opener-Policy","same-origin"),t.setHeader("Cross-Origin-Resource-Policy","same-origin"),t.setHeader("Origin-Agent-Cluster","?1"),t.removeHeader("X-Powered-By")}var TD,AD,EE,ql,RD,Nre,vE,ID,Lre,kD,af,OD=R(()=>{"use strict";TD=Ze(Wp(),1),AD=Ze(require("http"),1),EE=Ze(require("fs"),1),ql=Ze(require("path"),1);zP();fe();eD();iD();vD();To();Ll();ED();SD();xD();_D();RD=ql.default.resolve(__dirname,"../skills/mem-search"),Nre=ql.default.join(RD,"operations"),vE=ql.default.join(RD,"SKILL.md"),ID=(()=>{try{let t=EE.readFileSync(vE,"utf-8");return x.info("SYSTEM","Cached SKILL.md at boot",{path:vE,bytes:Buffer.byteLength(t,"utf-8")}),t}catch(t){return x.debug("SYSTEM","SKILL.md not present at boot, /api/instructions will 404 for topic queries",{path:vE,message:t instanceof Error?t.message:String(t)}),null}})(),Lre=(()=>{let t=new Map;for(let e of Y0){let r=ql.default.join(Nre,`${e}.md`);try{t.set(e,EE.readFileSync(r,"utf-8"))}catch(n){x.debug("SYSTEM","Operation instruction file not present at boot",{path:r,message:n instanceof Error?n.message:String(n)})}}return t.size>0&&x.info("SYSTEM","Cached operation instruction files at boot",{count:t.size,operations:Array.from(t.keys())}),t})(),kD="13.21.1";af=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,TD.default)(),this.app.disable("x-powered-by"),this.setupSecurityHeaders(),this.setupCors(),this.setupPreBodyParserRoutes(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,r){return new Promise((n,i)=>{let s=AD.default.createServer(this.app),a=c=>{s.off("listening",o),i(c)},o=()=>{s.off("error",a),this.server=s,x.info("SYSTEM","HTTP server started",{host:r,port:e,pid:process.pid}),n()};s.once("error",a),s.once("listening",o),s.listen(e,r)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{this.server.close(n=>n?r(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,x.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(nD),this.app.use(rD)}setupMiddleware(){XP().forEach(r=>this.app.use(r))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,r,n)=>{qre(r),n()})}setupCors(){this.app.use(ZP())}setupPreBodyParserRoutes(){this.options.preBodyParserRoutes?.forEach(e=>e.setupRoutes(this.app))}setupCoreRoutes(){this.app.get("/api/health",async(e,r)=>{let n=this.options.getQueueHealth?await this.options.getQueueHealth():null,i=n?.engine==="bullmq"&&n.redis.status==="error",s=this.options.getDependencyHealth?this.options.getDependencyHealth():gE();r.status(i?503:200).json({status:i?"degraded":"ok",...this.options.runtime?{runtime:this.options.runtime}:{},version:kD,workerPath:this.options.workerPath,uptime:yE(this.startTime),managed:process.env.CLAUDE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.options.getInitializationComplete(),mcpReady:this.options.getMcpReady(),ai:this.options.getAiStatus(),dependencies:s,rateLimits:wD.getMostRecentByWindow(),...n?{queue:n}:{}})}),this.app.get("/api/readiness",(e,r)=>{this.options.getInitializationComplete()?r.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):r.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(e,r)=>{r.status(200).json({version:kD})}),this.app.get("/api/instructions",(e,r)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!UP.includes(n))return r.status(400).json({error:"Invalid topic"});if(i&&!Y0.includes(i))return r.status(400).json({error:"Invalid operation"});if(i){let a=Lre.get(i);return a===void 0?(x.debug("HTTP","Instruction file not cached at boot",{operation:i}),r.status(404).json({error:"Instruction not found"})):r.json({content:[{type:"text",text:a}]})}if(ID===null)return x.debug("HTTP","SKILL.md not cached at boot",{topic:n}),r.status(404).json({error:"Instruction not found"});let s=this.extractInstructionSection(ID,n);r.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",Xp,async(e,r)=>{process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(r.json({status:"restarting"}),x.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):hE(r,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",Xp,async(e,r)=>{let n=e.query.reason==="restart"?"restart":"stop";process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(r.json({status:"shutting_down"}),x.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown",reason:n})):hE(r,{status:"shutting_down"},()=>this.options.onShutdown(n))}),this.app.get("/api/admin/doctor",Xp,(e,r)=>{let a=bD().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:zt(f.pid)?"alive":"dead",startedAt:f.startedAt})),o=a.filter(f=>f.status==="dead").map(f=>f.pid),c=!Object.keys(process.env).some(f=>sE.has(f)||iE.some(m=>f.startsWith(m))),l=yE(this.startTime),u=Math.floor(l/3600),d=Math.floor(l%3600/60),p=u>0?`${u}h ${d}m`:`${d}m`;r.json({supervisor:{running:!0,pid:process.pid,uptime:p},processes:a,health:{deadProcessPids:o,envClean:c,dependencies:this.options.getDependencyHealth?this.options.getDependencyHealth():gE()}})})}extractInstructionSection(e,r){let n={workflow:this.extractBetween(e,"## The Workflow","## Search Parameters"),search_params:this.extractBetween(e,"## Search Parameters","## Examples"),examples:this.extractBetween(e,"## Examples","## Why This Workflow"),all:e};return n[r]||n.all}extractBetween(e,r,n){let i=e.indexOf(r),s=e.indexOf(n);return i===-1?e:s===-1?e.substring(i):e.substring(i,s).trim()}}});var Ir,Fre,$re,SE,CD=R(()=>{"use strict";Ir=require("zod"),Fre=Ir.z.enum(["hook","worker","provider","server","api"]),$re=Ir.z.object({id:Ir.z.string().min(1),projectId:Ir.z.string().min(1),serverSessionId:Ir.z.string().min(1).nullable().default(null),sourceType:Fre,eventType:Ir.z.string().min(1),platformSource:Ir.z.string().min(1).nullable().default(null),payload:Ir.z.unknown().default({}),contentSessionId:Ir.z.string().min(1).nullable().default(null),memorySessionId:Ir.z.string().min(1).nullable().default(null),occurredAtEpoch:Ir.z.number().int().nonnegative(),createdAtEpoch:Ir.z.number().int().nonnegative()}),SE=$re.omit({id:!0,createdAtEpoch:!0}).partial({serverSessionId:!0,platformSource:!0,payload:!0,contentSessionId:!0,memorySessionId:!0})});function We(){return(0,of.randomUUID)()}function ft(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function jD(t){return Array.isArray(t)?t:[]}function Pe(t){return typeof t=="number"?t:new Date(t).getTime()}function Hr(t){return t==null?null:t instanceof Date?t:new Date(t)}async function ie(t,e,r=[]){return(await t.query(e,r)).rows[0]??null}async function gn(t,e,r){if(!await ie(t,"SELECT id FROM projects WHERE id = $1 AND team_id = $2",[e,r]))throw new Error("project_id must belong to team_id")}async function gi(t,e,r,n){if(!await ie(t,"SELECT id FROM server_sessions WHERE id = $1 AND project_id = $2 AND team_id = $3",[e,r,n]))throw new Error("server_session_id must belong to project_id and team_id")}function Fl(t){return JSON.stringify(xE(t))}function bn(t){return(0,of.createHash)("sha256").update(Fl(t)).digest("hex")}function xE(t){if(Array.isArray(t))return t.map(xE);if(t&&typeof t=="object"){let e=t;return Object.keys(e).sort().reduce((r,n)=>(r[n]=xE(e[n]),r),{})}return t}var of,vn=R(()=>{"use strict";of=require("crypto")});function Jre(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Yi(t){if(!t)return Oo;let e=Jre(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:Oo}function ar(t){return typeof t!="string"?null:Yi(t)}var Oo,ra=R(()=>{"use strict";Oo="claude"});function KD(t){let e=ar(t.platformSource),r=e?[e]:[];return t.sourceEventId?`agent_event:v1:${bn([t.teamId,t.projectId,t.sourceAdapter,...r,t.sourceEventId])}`:`agent_event:v1:${bn([t.teamId,t.projectId,t.sourceAdapter,...r,t.contentSessionId??t.serverSessionId??null,t.eventType,new Date(t.occurredAt).toISOString(),Fl(t.payload??{})])}`}function wE(t){return{id:t.id,projectId:t.project_id,teamId:t.team_id,serverSessionId:t.server_session_id,sourceAdapter:t.source_adapter,sourceEventId:t.source_event_id,idempotencyKey:t.idempotency_key,eventType:t.event_type,platformSource:t.platform_source,payload:t.payload,metadata:ft(t.metadata),occurredAtEpoch:Pe(t.occurred_at),receivedAtEpoch:Pe(t.received_at),createdAtEpoch:Pe(t.created_at)}}var Yr,Co=R(()=>{"use strict";vn();ra();Yr=class{constructor(e){this.client=e}client;async create(e){await gn(this.client,e.projectId,e.teamId),e.serverSessionId&&await gi(this.client,e.serverSessionId,e.projectId,e.teamId);let r=KD(e),n=ar(e.platformSource),i=await ie(this.client,`
66
+ `)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);if(!n)continue;let i=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:i.length>0?i:null})}return e}async function _re(){let t;try{t=(await lE("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,@{Name='StartToken';Expression={$_.CreationDate.ToString('yyyyMMddHHmmss.ffffff')}} | ConvertTo-Csv -NoTypeInformation"],{timeout:3e4,windowsHide:!0,maxBuffer:33554432})).stdout}catch(r){return x.warn("PROCESS","Cannot enumerate the Windows process table \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),[]}let e=[];for(let r of t.split(/\r?\n/).slice(1)){let n=r.match(/^"(\d+)","(\d+)","(.*)"$/);if(!n)continue;let i=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:i.length>0?i:null})}return e}async function ef(t){let e=await Sre(),r=new Map;for(let a of e){let o=r.get(a.ppid);o?o.push(a):r.set(a.ppid,[a])}let n=new Set([t]),i=[],s=a=>{for(let o of r.get(a)??[])n.has(o.pid)||(n.add(o.pid),s(o.pid),i.push({pid:o.pid,startToken:o.startToken}))};return s(t),i}var lD,tf,uD,lE,vre,Ere,Zp,rf=R(()=>{"use strict";lD=require("child_process"),tf=require("fs"),uD=require("util");fe();cE();lE=(0,uD.promisify)(lD.execFile),vre=128,Ere=/not found|no running instance|no tasks/i,Zp=class extends Error{pid;constructor(e,r,n){super(r,n),this.name="ProcessTreeKillError",this.pid=e}}});function zt(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;return r==="EPERM"?!0:(x.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return x.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function nf(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!zt(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function Hi(t){if(!t||!zt(t.pid))return!1;if(!t.startToken)return!0;let e=mi(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||x.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}function sf(){return uE||(uE=new fE),uE}function dE(){let t=Are.shift();t&&t()}var yi,pE,Ire,kre,Tre,fE,uE,Are,To=R(()=>{"use strict";sD();yi=require("fs"),pE=Ze(require("path"),1);fe();Ll();Jn();cE();rf();Ire=5e3,kre=1e3,Tre=Ue.supervisorRegistry();fE=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=Tre){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,yi.mkdirSync)(pE.default.dirname(this.registryPath),{recursive:!0}),!(0,yi.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,yi.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[i,s]of Object.entries(n))this.entries.set(i,s)}catch(r){r instanceof Error?x.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):x.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&x.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,r,n){this.initialize(),this.entries.set(e,r),n&&this.runtimeProcesses.set(e,n),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"&&dE()}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 n=Date.parse(e.startedAt),i=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(i)?0:i)})}getBySession(e){let r=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[n,i]of this.entries)zt(i.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,i.type==="sdk"&&(r+=1));e>0&&this.persist();for(let n=0;n<r;n+=1)dE();return e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;x.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:n,pids:r.map(o=>o.pid)});let i=r.filter(o=>zt(o.pid)),s=new Map(i.map(o=>[o.pid,mi(o.pid)]));for(let o of i)try{process.platform==="win32"?await Vi(o.pid,{expectedStartToken:s.get(o.pid)??null}):typeof o.pgid=="number"?process.kill(-o.pgid,"SIGTERM"):process.kill(o.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&x.debug("SYSTEM",`Failed to SIGTERM session process PID ${o.pid}`,{pid:o.pid,pgid:o.pgid},c):x.warn("SYSTEM",`Failed to SIGTERM session process PID ${o.pid} (non-Error)`,{pid:o.pid,pgid:o.pgid,error:String(c)})}await nf(i,Ire);let a=i.filter(o=>zt(o.pid));for(let o of a){x.warn("SYSTEM",`Session process PID ${o.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:o.pid,pgid:o.pgid,sessionId:n});let c=s.get(o.pid)??null;if(!hi(o.pid,c)){x.warn("SYSTEM","Skipping SIGKILL: session process PID was reused during the grace window",{pid:o.pid,sessionId:n});continue}try{process.platform==="win32"?await Vi(o.pid,{expectedStartToken:c}):typeof o.pgid=="number"?process.kill(-o.pgid,"SIGKILL"):process.kill(o.pid,"SIGKILL")}catch(l){l instanceof Error?l.code!=="ESRCH"&&x.debug("SYSTEM",`Failed to SIGKILL session process PID ${o.pid}`,{pid:o.pid,pgid:o.pgid},l):x.warn("SYSTEM",`Failed to SIGKILL session process PID ${o.pid} (non-Error)`,{pid:o.pid,pgid:o.pgid,error:String(l)})}}if(a.length>0){let o=Date.now()+kre;for(;Date.now()<o&&a.filter(l=>zt(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let o of r)this.entries.delete(o.id),this.runtimeProcesses.delete(o.id);this.persist();for(let o of r)o.type==="sdk"&&dE();return x.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:n,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,yi.mkdirSync)(pE.default.dirname(this.registryPath),{recursive:!0}),(0,yi.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},uE=null;Are=[]});async function pD(t){let e=t.currentPid??process.pid,r=t.pidFilePath??Rre,n=t.registry.getAll(),i=[...n].filter(c=>c.pid!==e).sort((c,l)=>Date.parse(l.startedAt)-Date.parse(c.startedAt)),s=new Map,a=new Map;for(let c of i){if(!zt(c.pid)){t.registry.unregister(c.id);continue}a.set(c.id,mi(c.pid)),s.set(c.id,await ef(c.pid));try{await dD(c,"SIGTERM")}catch(l){l instanceof Error?x.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:c.pid,pgid:c.pgid,type:c.type},l):x.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(l)})}}await nf(i,5e3);let o=i.filter(c=>zt(c.pid)||(s.get(c.id)??[]).some(l=>zt(l.pid)));for(let c of o){let l=hi(c.pid,a.get(c.id)??null);l||x.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:c.pid,type:c.type});try{l&&await dD(c,"SIGKILL")}catch(u){u instanceof Error?x.debug("SYSTEM","Failed to force kill child process",{pid:c.pid,pgid:c.pgid,type:c.type},u):x.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(u)})}finally{Cre(s.get(c.id)??[],c.pid)}}await nf(o,1e3);for(let c of i)t.registry.unregister(c.id);for(let c of n.filter(l=>l.pid===e))t.registry.unregister(c.id);Ore(r,e),t.registry.pruneDeadEntries()}function Ore(t,e,r=!1){if(!(0,Ao.existsSync)(t))return;let n=null;try{let a=JSON.parse((0,Ao.readFileSync)(t,"utf-8"));n=typeof a.pid=="number"?a.pid:null}catch(a){x.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:a instanceof Error?a.message:String(a)});return}let i=e!==null&&n===e,s=n===null||!zt(n);if(!i&&!(r&&s)){x.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:n,currentPid:e});return}try{(0,Ao.rmSync)(t,{force:!0})}catch(a){a instanceof Error?x.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},a):x.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(a)})}}function Cre(t,e){for(let{pid:r,startToken:n}of t)if(!(r===e||!zt(r))){if(!hi(r,n)){x.debug("SYSTEM","Skipping reap: PID was recycled during the grace window",{pid:r,rootPid:e});continue}try{process.kill(r,"SIGKILL"),x.debug("SYSTEM","Reaped orphaned descendant during shutdown cascade",{pid:r,rootPid:e})}catch(i){let s=i instanceof Error?i.code:void 0;s!=="ESRCH"&&x.warn("SYSTEM","Failed to reap orphaned descendant during shutdown cascade",{pid:r,rootPid:e,errno:s})}}}async function dD(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}if(e==="SIGKILL"){await Vi(r,{signalMode:"immediate"});return}try{process.kill(r,e)}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}return}await Vi(r)}var Ao,Rre,fD=R(()=>{"use strict";Ao=require("fs");fe();To();Jn();rf();Rre=Ue.workerPid()});function jre(){let e=sf().pruneDeadEntries();e>0&&x.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function hD(){Ro===null&&(Ro=setInterval(jre,mD),Ro.unref(),x.debug("SYSTEM","Health checker started",{intervalMs:mD}))}function yD(){Ro!==null&&(clearInterval(Ro),Ro=null,x.debug("SYSTEM","Health checker stopped"))}var mD,Ro,gD=R(()=>{"use strict";fe();To();mD=3e4,Ro=null});function bD(){return Pre}function Dre(t={}){let e=t.pidFilePath??Kre;if(!(0,ta.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,ta.readFileSync)(e,"utf-8"))}catch(i){return i instanceof Error?x.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},i):x.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(i)}),(0,ta.rmSync)(e,{force:!0}),"invalid"}return Hi(r)&&r?((t.logAlive??!0)&&x.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(x.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,ta.rmSync)(e,{force:!0}),"stale")}var ta,Kre,mE,Pre,vD=R(()=>{"use strict";ta=require("fs");fe();To();fD();gD();Jn();Kre=Ue.workerPid(),mE=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(),Dre({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,hD()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){x.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,x.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){i instanceof Error?x.error("SYSTEM","Error during shutdown",{},i):x.error("SYSTEM","Error during shutdown (non-Error)",{error:String(i)});try{await this.stop()}catch(s){s instanceof Error?x.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):x.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(s)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{x.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}yD(),this.stopPromise=pD({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,n){this.registry.register(e,r,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},Pre=new mE(sf())});function hE(t,e,r){t.on("finish",async()=>{try{await r()}finally{process.exit(0)}}),t.json(e)}var ED=R(()=>{"use strict"});function yE(t,e=Date.now){return Math.max(0,Math.floor((e()-t)/1e3))}var SD=R(()=>{"use strict"});function gE(){let t=Array.from(Mre.values()).map(e=>({...e})).sort((e,r)=>e.dependency.localeCompare(r.dependency));return{degraded:t.length>0,statuses:t}}var Mre,xD=R(()=>{"use strict";Mre=new Map});var bE,wD,IOe,_D=R(()=>{"use strict";bE=class{entries=new Map;set(e){if(!e||typeof e!="object")return;let r=e.rateLimitType??"default";this.entries.set(r,{...e,observedAt:Date.now()})}get(e){return e?this.entries.get(e):this.entries.get("default")}getMostRecentByWindow(){return{five_hour:this.entries.get("five_hour"),seven_day:this.entries.get("seven_day"),seven_day_opus:this.entries.get("seven_day_opus"),seven_day_sonnet:this.entries.get("seven_day_sonnet"),overage:this.entries.get("overage")}}get size(){return this.entries.size}},wD=new bE,IOe=900*1e3});function qre(t){t.setHeader("X-Content-Type-Options","nosniff"),t.setHeader("X-Frame-Options","DENY"),t.setHeader("X-DNS-Prefetch-Control","off"),t.setHeader("Referrer-Policy","no-referrer"),t.setHeader("Cross-Origin-Opener-Policy","same-origin"),t.setHeader("Cross-Origin-Resource-Policy","same-origin"),t.setHeader("Origin-Agent-Cluster","?1"),t.removeHeader("X-Powered-By")}var TD,AD,EE,ql,RD,Nre,vE,ID,Lre,kD,af,OD=R(()=>{"use strict";TD=Ze(Wp(),1),AD=Ze(require("http"),1),EE=Ze(require("fs"),1),ql=Ze(require("path"),1);zP();fe();eD();iD();vD();To();Ll();ED();SD();xD();_D();RD=ql.default.resolve(__dirname,"../skills/mem-search"),Nre=ql.default.join(RD,"operations"),vE=ql.default.join(RD,"SKILL.md"),ID=(()=>{try{let t=EE.readFileSync(vE,"utf-8");return x.info("SYSTEM","Cached SKILL.md at boot",{path:vE,bytes:Buffer.byteLength(t,"utf-8")}),t}catch(t){return x.debug("SYSTEM","SKILL.md not present at boot, /api/instructions will 404 for topic queries",{path:vE,message:t instanceof Error?t.message:String(t)}),null}})(),Lre=(()=>{let t=new Map;for(let e of Y0){let r=ql.default.join(Nre,`${e}.md`);try{t.set(e,EE.readFileSync(r,"utf-8"))}catch(n){x.debug("SYSTEM","Operation instruction file not present at boot",{path:r,message:n instanceof Error?n.message:String(n)})}}return t.size>0&&x.info("SYSTEM","Cached operation instruction files at boot",{count:t.size,operations:Array.from(t.keys())}),t})(),kD="13.22.0";af=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,TD.default)(),this.app.disable("x-powered-by"),this.setupSecurityHeaders(),this.setupCors(),this.setupPreBodyParserRoutes(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,r){return new Promise((n,i)=>{let s=AD.default.createServer(this.app),a=c=>{s.off("listening",o),i(c)},o=()=>{s.off("error",a),this.server=s,x.info("SYSTEM","HTTP server started",{host:r,port:e,pid:process.pid}),n()};s.once("error",a),s.once("listening",o),s.listen(e,r)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{this.server.close(n=>n?r(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,x.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(nD),this.app.use(rD)}setupMiddleware(){XP().forEach(r=>this.app.use(r))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,r,n)=>{qre(r),n()})}setupCors(){this.app.use(ZP())}setupPreBodyParserRoutes(){this.options.preBodyParserRoutes?.forEach(e=>e.setupRoutes(this.app))}setupCoreRoutes(){this.app.get("/api/health",async(e,r)=>{let n=this.options.getQueueHealth?await this.options.getQueueHealth():null,i=n?.engine==="bullmq"&&n.redis.status==="error",s=this.options.getDependencyHealth?this.options.getDependencyHealth():gE();r.status(i?503:200).json({status:i?"degraded":"ok",...this.options.runtime?{runtime:this.options.runtime}:{},version:kD,workerPath:this.options.workerPath,uptime:yE(this.startTime),managed:process.env.CLAUDE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.options.getInitializationComplete(),mcpReady:this.options.getMcpReady(),ai:this.options.getAiStatus(),dependencies:s,rateLimits:wD.getMostRecentByWindow(),...n?{queue:n}:{}})}),this.app.get("/api/readiness",(e,r)=>{this.options.getInitializationComplete()?r.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):r.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(e,r)=>{r.status(200).json({version:kD})}),this.app.get("/api/instructions",(e,r)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!UP.includes(n))return r.status(400).json({error:"Invalid topic"});if(i&&!Y0.includes(i))return r.status(400).json({error:"Invalid operation"});if(i){let a=Lre.get(i);return a===void 0?(x.debug("HTTP","Instruction file not cached at boot",{operation:i}),r.status(404).json({error:"Instruction not found"})):r.json({content:[{type:"text",text:a}]})}if(ID===null)return x.debug("HTTP","SKILL.md not cached at boot",{topic:n}),r.status(404).json({error:"Instruction not found"});let s=this.extractInstructionSection(ID,n);r.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",Xp,async(e,r)=>{process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(r.json({status:"restarting"}),x.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):hE(r,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",Xp,async(e,r)=>{let n=e.query.reason==="restart"?"restart":"stop";process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(r.json({status:"shutting_down"}),x.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown",reason:n})):hE(r,{status:"shutting_down"},()=>this.options.onShutdown(n))}),this.app.get("/api/admin/doctor",Xp,(e,r)=>{let a=bD().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:zt(f.pid)?"alive":"dead",startedAt:f.startedAt})),o=a.filter(f=>f.status==="dead").map(f=>f.pid),c=!Object.keys(process.env).some(f=>sE.has(f)||iE.some(m=>f.startsWith(m))),l=yE(this.startTime),u=Math.floor(l/3600),d=Math.floor(l%3600/60),p=u>0?`${u}h ${d}m`:`${d}m`;r.json({supervisor:{running:!0,pid:process.pid,uptime:p},processes:a,health:{deadProcessPids:o,envClean:c,dependencies:this.options.getDependencyHealth?this.options.getDependencyHealth():gE()}})})}extractInstructionSection(e,r){let n={workflow:this.extractBetween(e,"## The Workflow","## Search Parameters"),search_params:this.extractBetween(e,"## Search Parameters","## Examples"),examples:this.extractBetween(e,"## Examples","## Why This Workflow"),all:e};return n[r]||n.all}extractBetween(e,r,n){let i=e.indexOf(r),s=e.indexOf(n);return i===-1?e:s===-1?e.substring(i):e.substring(i,s).trim()}}});var Ir,Fre,$re,SE,CD=R(()=>{"use strict";Ir=require("zod"),Fre=Ir.z.enum(["hook","worker","provider","server","api"]),$re=Ir.z.object({id:Ir.z.string().min(1),projectId:Ir.z.string().min(1),serverSessionId:Ir.z.string().min(1).nullable().default(null),sourceType:Fre,eventType:Ir.z.string().min(1),platformSource:Ir.z.string().min(1).nullable().default(null),payload:Ir.z.unknown().default({}),contentSessionId:Ir.z.string().min(1).nullable().default(null),memorySessionId:Ir.z.string().min(1).nullable().default(null),occurredAtEpoch:Ir.z.number().int().nonnegative(),createdAtEpoch:Ir.z.number().int().nonnegative()}),SE=$re.omit({id:!0,createdAtEpoch:!0}).partial({serverSessionId:!0,platformSource:!0,payload:!0,contentSessionId:!0,memorySessionId:!0})});function We(){return(0,of.randomUUID)()}function ft(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function jD(t){return Array.isArray(t)?t:[]}function Pe(t){return typeof t=="number"?t:new Date(t).getTime()}function Hr(t){return t==null?null:t instanceof Date?t:new Date(t)}async function ie(t,e,r=[]){return(await t.query(e,r)).rows[0]??null}async function gn(t,e,r){if(!await ie(t,"SELECT id FROM projects WHERE id = $1 AND team_id = $2",[e,r]))throw new Error("project_id must belong to team_id")}async function gi(t,e,r,n){if(!await ie(t,"SELECT id FROM server_sessions WHERE id = $1 AND project_id = $2 AND team_id = $3",[e,r,n]))throw new Error("server_session_id must belong to project_id and team_id")}function Fl(t){return JSON.stringify(xE(t))}function bn(t){return(0,of.createHash)("sha256").update(Fl(t)).digest("hex")}function xE(t){if(Array.isArray(t))return t.map(xE);if(t&&typeof t=="object"){let e=t;return Object.keys(e).sort().reduce((r,n)=>(r[n]=xE(e[n]),r),{})}return t}var of,vn=R(()=>{"use strict";of=require("crypto")});function Jre(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Yi(t){if(!t)return Oo;let e=Jre(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:Oo}function ar(t){return typeof t!="string"?null:Yi(t)}var Oo,ra=R(()=>{"use strict";Oo="claude"});function KD(t){let e=ar(t.platformSource),r=e?[e]:[];return t.sourceEventId?`agent_event:v1:${bn([t.teamId,t.projectId,t.sourceAdapter,...r,t.sourceEventId])}`:`agent_event:v1:${bn([t.teamId,t.projectId,t.sourceAdapter,...r,t.contentSessionId??t.serverSessionId??null,t.eventType,new Date(t.occurredAt).toISOString(),Fl(t.payload??{})])}`}function wE(t){return{id:t.id,projectId:t.project_id,teamId:t.team_id,serverSessionId:t.server_session_id,sourceAdapter:t.source_adapter,sourceEventId:t.source_event_id,idempotencyKey:t.idempotency_key,eventType:t.event_type,platformSource:t.platform_source,payload:t.payload,metadata:ft(t.metadata),occurredAtEpoch:Pe(t.occurred_at),receivedAtEpoch:Pe(t.received_at),createdAtEpoch:Pe(t.created_at)}}var Yr,Co=R(()=>{"use strict";vn();ra();Yr=class{constructor(e){this.client=e}client;async create(e){await gn(this.client,e.projectId,e.teamId),e.serverSessionId&&await gi(this.client,e.serverSessionId,e.projectId,e.teamId);let r=KD(e),n=ar(e.platformSource),i=await ie(this.client,`
67
67
  INSERT INTO agent_events (
68
68
  id, project_id, team_id, server_session_id, source_adapter,
69
69
  source_event_id, idempotency_key, event_type, platform_source, payload, metadata, occurred_at
@@ -346,7 +346,7 @@ data:
346
346
  )
347
347
  ORDER BY e.occurred_at ASC
348
348
  LIMIT $4
349
- `,[e.serverSessionId,e.projectId,e.teamId,r])).rows.map(Hme)}}});function j4(t){let e=Qme.safeParse(t);if(!e.success)throw new zu(e.error.issues);return e.data}var Xt,Ec,O4,C4,Yme,Wme,Qme,zu,zm=R(()=>{"use strict";Xt=require("zod"),Ec={event:"server_beta_generate_event",summary:"server_beta_generate_summary"},O4={event:"evt",summary:"sum"},C4=Xt.z.object({team_id:Xt.z.string().min(1,"team_id is required"),project_id:Xt.z.string().min(1,"project_id is required"),source_type:Xt.z.enum(["agent_event","session_summary","observation_reindex"]),source_id:Xt.z.string().min(1,"source_id is required"),generation_job_id:Xt.z.string().min(1,"generation_job_id is required"),api_key_id:Xt.z.string().min(1).nullable(),actor_id:Xt.z.string().min(1).nullable(),source_adapter:Xt.z.string().min(1,"source_adapter is required"),request_id:Xt.z.string().min(1).nullable().optional()}),Yme=C4.extend({kind:Xt.z.literal("event"),agent_event_id:Xt.z.string().min(1)}),Wme=C4.extend({kind:Xt.z.literal("summary"),server_session_id:Xt.z.string().min(1)}),Qme=Xt.z.discriminatedUnion("kind",[Yme,Wme]),zu=class extends Error{issues;constructor(e){super(`invalid server generation job payload: ${e.map(r=>r.message).join("; ")}`),this.issues=e}}});function Sc(t){let e=O4[t.kind],r=JSON.stringify({kind:t.kind,team_id:t.team_id,project_id:t.project_id,source_type:t.source_type,source_id:t.source_id}),n=(0,K4.createHash)("sha256").update(r).digest("hex");return`${e}_${n}`}var K4,A_=R(()=>{"use strict";K4=require("crypto");zm()});function P4(t){return{kind:"event",team_id:t.event.teamId,project_id:t.event.projectId,source_type:"agent_event",source_id:t.event.id,generation_job_id:t.outboxId,agent_event_id:t.event.id,api_key_id:t.apiKeyId,actor_id:t.actorId,source_adapter:t.sourceAdapter??t.event.sourceAdapter??"api",request_id:t.requestId}}var D4,Gm,M4=R(()=>{"use strict";Co();Wi();ca();fe();A_();vn();D4="observation_generate_for_event",Gm=class{constructor(e){this.options=e}options;async ingestOne(e,r={}){let n=r.generate??!0,i=r.source??"http_post_v1_events",s=await Sn(this.options.pool,async o=>{let l=await new Yr(o).create(e);if(!n)return{event:l,outbox:null};let u=new ut(o),d=new Gt(o),p=We(),f=P4({outboxId:p,event:l,apiKeyId:r.apiKeyId??null,actorId:r.actorId??null,sourceAdapter:r.sourceAdapter??null,requestId:r.requestId??null}),m=await u.create({id:p,projectId:l.projectId,teamId:l.teamId,sourceType:"agent_event",sourceId:l.id,agentEventId:l.id,serverSessionId:l.serverSessionId,jobType:D4,bullmqJobId:Sc({kind:"event",team_id:l.teamId,project_id:l.projectId,source_type:"agent_event",source_id:l.id}),payload:f});return await d.append({generationJobId:m.id,projectId:m.projectId,teamId:m.teamId,eventType:"queued",statusAfter:m.status,attempt:m.attempts,details:{source:i}}),{event:l,outbox:m}}),a="skipped";return s.outbox&&(a=await this.publishEventJob(s.event,s.outbox)),{event:s.event,outbox:s.outbox,enqueueState:a}}async ingestBatch(e,r={}){let n=r.generate??!0,i=r.source??"http_post_v1_events_batch",s=await Sn(this.options.pool,async a=>{let o=new Yr(a),c=new ut(a),l=new Gt(a),u=[];for(let d of e){let p=await o.create(d);if(!n){u.push({event:p,outbox:null});continue}let f=We(),m=P4({outboxId:f,event:p,apiKeyId:r.apiKeyId??null,actorId:r.actorId??null,sourceAdapter:r.sourceAdapter??null,requestId:r.requestId??null}),g=await c.create({id:f,projectId:p.projectId,teamId:p.teamId,sourceType:"agent_event",sourceId:p.id,agentEventId:p.id,serverSessionId:p.serverSessionId,jobType:D4,bullmqJobId:Sc({kind:"event",team_id:p.teamId,project_id:p.projectId,source_type:"agent_event",source_id:p.id}),payload:m});await l.append({generationJobId:g.id,projectId:g.projectId,teamId:g.teamId,eventType:"queued",statusAfter:g.status,attempt:g.attempts,details:{source:i}}),u.push({event:p,outbox:g})}return u});return Promise.all(s.map(async({event:a,outbox:o})=>{let c=o?await this.publishEventJob(a,o):"skipped";return{event:a,outbox:o,enqueueState:c}}))}async publishEventJob(e,r){let n=this.options.resolveEventQueue();if(!n)return"queued_only";let i=r.bullmqJobId??Sc({kind:"event",team_id:e.teamId,project_id:e.projectId,source_type:"agent_event",source_id:e.id});try{return await n.add(i,r.payload),"enqueued"}catch(s){return x.warn("SYSTEM","failed to publish event generation job to BullMQ",{outboxId:r.id,error:s instanceof Error?s.message:String(s)}),"queued_only"}}}});function R_(t){return Sc({kind:"summary",team_id:t.teamId,project_id:t.projectId,source_type:"session_summary",source_id:t.serverSessionId})}function O_(t){return{kind:"summary",team_id:t.teamId,project_id:t.projectId,source_type:"session_summary",source_id:t.serverSessionId,generation_job_id:t.generationJobId,server_session_id:t.serverSessionId,api_key_id:t.apiKeyId??null,actor_id:t.actorId??null,source_adapter:t.sourceAdapter??"api",request_id:t.requestId??null}}var N4=R(()=>{"use strict";A_()});var Xme,Bm,L4=R(()=>{"use strict";Wi();ca();fs();fe();N4();vn();Xme="observation_generate_session_summary",Bm=class{constructor(e){this.options=e}options;async end(e){let r=e.source??"http_post_v1_sessions_end",n=await Sn(this.options.pool,async s=>{let o=await new Qt(s).endSession({id:e.sessionId,projectId:e.projectId,teamId:e.teamId});if(!o)return{session:null,outbox:null};let c=new ut(s),l=new Gt(s),u=We(),d=O_({serverSessionId:o.id,teamId:o.teamId,projectId:o.projectId,generationJobId:u,apiKeyId:e.apiKeyId??null,actorId:e.actorId??null,sourceAdapter:e.sourceAdapter??null}),p=await c.create({id:u,projectId:o.projectId,teamId:o.teamId,sourceType:"session_summary",sourceId:o.id,serverSessionId:o.id,jobType:Xme,bullmqJobId:R_({serverSessionId:o.id,teamId:o.teamId,projectId:o.projectId}),payload:d});return await l.append({generationJobId:p.id,projectId:p.projectId,teamId:p.teamId,eventType:"queued",statusAfter:p.status,attempt:p.attempts,details:{source:r}}),{session:o,outbox:p}});if(!n.session||!n.outbox)return{session:n.session,outbox:null,enqueueState:"skipped"};let i=await this.publishSummaryJob(n.session.id,n.outbox,e);return{session:n.session,outbox:n.outbox,enqueueState:i}}async publishSummaryJob(e,r,n){let i=this.options.resolveSummaryQueue();if(!i)return"queued_only";let s=r.bullmqJobId??R_({serverSessionId:e,teamId:r.teamId,projectId:r.projectId}),a=O_({serverSessionId:e,teamId:r.teamId,projectId:r.projectId,generationJobId:r.id,apiKeyId:n.apiKeyId??null,actorId:n.actorId??null,sourceAdapter:n.sourceAdapter??null});try{return await i.add(s,a),"enqueued"}catch(o){return x.warn("SYSTEM","failed to publish summary generation job to BullMQ",{outboxId:r.id,error:o instanceof Error?o.message:String(o)}),"queued_only"}}}});function q4(t){return`${(process.env.CLAUDE_MEM_PUBLIC_URL??`${t.protocol}://${t.get("host")??"localhost"}`).replace(/\/+$/,"")}/v1/mcp`}function F4(t,e){return`claude mcp add --transport http claude-mem ${t} --header "Authorization: Bearer ${e}"`}async function U4(t,e,r=V4,n=the){if(J4.includes(e.status))return{job:e,timedOut:!1};let i=Date.now()+r,s=e;for(;Date.now()<i;){await new Promise(o=>setTimeout(o,n));let a=await t.getByIdForScope({id:e.id,projectId:e.projectId,teamId:e.teamId});if(!a)return{job:s,timedOut:!1};if(s=a,J4.includes(a.status))return{job:a,timedOut:!1}}return{job:s,timedOut:!0}}function nhe(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&H4.has(e)?e:null,n=typeof t.query.source_type=="string"?t.query.source_type.trim():"",i=n&&rhe.has(n)?n:null,s=Hm(t.query.limit,Y4,1,W4),a=Hm(t.query.offset,0,0,Number.MAX_SAFE_INTEGER),o=typeof t.query.since=="string"?t.query.since.trim():"",c=null;if(o){let l=new Date(o);Number.isNaN(l.getTime())||(c=l)}return{status:r,sourceType:i,limit:s,offset:a,since:c}}function z4(t){if(!t||typeof t!="object")return 0;let e=t.retried_count;return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function G4(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&H4.has(e)?e:null,n=Hm(t.query.limit,Y4,1,W4),i=Hm(t.query.offset,0,0,Number.MAX_SAFE_INTEGER);return{status:r,limit:n,offset:i}}function Hm(t,e,r,n){if(typeof t!="string")return e;let i=Number.parseInt(t,10);return Number.isFinite(i)?Math.max(r,Math.min(n,i)):e}function C_(t,e={}){let r={id:t.id,projectId:t.project_id,teamId:t.team_id,sourceType:t.source_type,sourceId:t.source_id,status:t.status,attempts:t.attempts,maxAttempts:t.max_attempts,createdAtEpoch:new Date(t.created_at).getTime(),completedAtEpoch:t.completed_at?new Date(t.completed_at).getTime():null,failedAtEpoch:t.failed_at?new Date(t.failed_at).getTime():null,lastError:t.last_error&&typeof t.last_error=="object"?t.last_error:null};return e.includePayload&&t.payload&&typeof t.payload=="object"&&(r.payload=t.payload),r}function ihe(t){let e={"event.received":"agent_event","event.batch_received":"agent_event","event.write":"agent_event","event.batch_write":"agent_event","session.write":"server_session","session.end":"server_session","memory.write":"observation","observation.read":"observation","observation.search":"observation","observation.context":"observation","observation.generated":"observation","session_summary.generated":"observation","generation_job.queued":"observation_generation_job","generation_job.enqueued":"observation_generation_job","generation_job.processing":"observation_generation_job","generation_job.completed":"observation_generation_job","generation_job.failed":"observation_generation_job","generation_job.scope_violation":"observation_generation_job","generation_job.revoked_key":"observation_generation_job","generation_job.retried_by_operator":"observation_generation_job","generation_job.cancelled_by_operator":"observation_generation_job","generation_job.stalled":"observation_generation_job"};return e[t]?e[t]:t.split(".")[0]??"unknown"}function she(t,e){let r=t.authContext?.projectId??null;if(!(t.authContext?.teamId??null))return{status:403,body:{error:"Forbidden",message:"API key is not bound to a team"}};if(!r)return null;for(let i of e)if(i.projectId!==r)return{status:403,body:{error:"Forbidden",message:"API key is scoped to a different project"}};return null}function Gu(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,externalSessionId:t.externalSessionId,contentSessionId:t.contentSessionId,agentId:t.agentId,agentType:t.agentType,platformSource:t.platformSource,generationStatus:t.generationStatus,metadata:t.metadata,startedAtEpoch:t.startedAtEpoch,endedAtEpoch:t.endedAtEpoch,lastGeneratedAtEpoch:t.lastGeneratedAtEpoch,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function Bu(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,serverSessionId:t.serverSessionId,sourceAdapter:t.sourceAdapter,sourceEventId:t.sourceEventId,eventType:t.eventType,platformSource:t.platformSource,payload:t.payload,metadata:t.metadata,occurredAtEpoch:t.occurredAtEpoch,receivedAtEpoch:t.receivedAtEpoch,createdAtEpoch:t.createdAtEpoch}}function xc(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,serverSessionId:t.serverSessionId,kind:t.kind,content:t.content,metadata:t.metadata,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function ahe(t){return{id:t.id,projectId:t.project_id,teamId:t.team_id,serverSessionId:t.server_session_id,kind:t.kind,content:t.content,metadata:t.metadata&&typeof t.metadata=="object"?t.metadata:{},generationKey:t.generation_key,createdByJobId:t.created_by_job_id,createdAtEpoch:new Date(t.created_at).getTime(),updatedAtEpoch:new Date(t.updated_at).getTime(),source:{id:t.source_id_pk,sourceType:t.source_type,sourceId:t.source_id,generationJobId:t.generation_job_id,createdAtEpoch:new Date(t.source_created_at).getTime()}}}function j_(t,e){return{id:t.id,status:t.status,bullmqJobId:t.bullmqJobId,sourceType:t.sourceType,sourceId:t.sourceId,transport:e,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function B4(t,e){return{id:t.id,status:t.status,transport:e,bullmqJobId:t.bullmqJobId,sourceType:t.sourceType,sourceId:t.sourceId,attempts:t.attempts,maxAttempts:t.maxAttempts,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function K_(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,sourceType:t.sourceType,sourceId:t.sourceId,agentEventId:t.agentEventId,serverSessionId:t.serverSessionId,jobType:t.jobType,status:t.status,bullmqJobId:t.bullmqJobId,attempts:t.attempts,maxAttempts:t.maxAttempts,nextAttemptAtEpoch:t.nextAttemptAtEpoch,completedAtEpoch:t.completedAtEpoch,failedAtEpoch:t.failedAtEpoch,cancelledAtEpoch:t.cancelledAtEpoch,lastError:t.lastError,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}var ce,Ym,Zme,ehe,$4,V4,the,J4,Vm,rhe,H4,Y4,W4,Q4=R(()=>{"use strict";ce=require("zod");CD();Co();Wi();bi();Jl();jo();fe();lf();RS();$N();fL();_4();k4();A4();wa();Ym=require("node:crypto");fs();M4();L4();ra();Zme="api",ehe="13.21.1";$4=ce.z.object({generate:ce.z.union([ce.z.literal("true"),ce.z.literal("false")]).optional(),wait:ce.z.union([ce.z.literal("true"),ce.z.literal("false")]).optional()}),V4=3e4,the=100,J4=["completed","failed","cancelled"];Vm=class{constructor(e){this.options=e;this.ingestEvents=new Gm({pool:e.pool,resolveEventQueue:()=>this.resolveQueue("event")}),this.endSession=new Bm({pool:e.pool,resolveSummaryQueue:()=>this.resolveQueue("summary")})}options;ingestEvents;endSession;getIngestEventsService(){return this.ingestEvents}getEndSessionService(){return this.endSession}setupRoutes(e){e.use("/v1",FN());let r=ia(this.options.pool,{authMode:this.options.authMode,allowLocalDevBypass:this.options.allowLocalDevBypass,requiredScopes:["memories:write"]}),n=ia(this.options.pool,{authMode:this.options.authMode,allowLocalDevBypass:this.options.allowLocalDevBypass,requiredScopes:["memories:read"]}),i=[],s=Number(process.env.CLAUDE_MEM_RATE_LIMIT_PER_MIN??"0");s>0&&i.push(I4(this.options.pool,{windowSec:60,max:s}));let a=Number(process.env.CLAUDE_MEM_MONTHLY_REQUEST_CAP??"0");a>0&&i.push(T_(this.options.pool,{kind:"request",cap:a})),process.env.CLAUDE_MEM_USAGE_METERING==="1"&&i.push(T4(this.options.pool));let o=[...i],c=Number(process.env.CLAUDE_MEM_MONTHLY_TOKEN_CAP??"0");c>0&&o.push(T_(this.options.pool,{kind:"tokens",cap:c}));let l=[r,...o],u=[n,...i];e.get("/v1/usage",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let g=new Date(Date.UTC(new Date().getUTCFullYear(),new Date().getUTCMonth(),1)),b=await new Or(this.options.pool).summarize({teamId:m,since:g});f.status(200).json({since:g.toISOString(),usage:b})})),e.post("/v1/keys",l,this.handleCreate(ce.z.object({label:ce.z.string().max(120).optional(),expiresInDays:ce.z.number().int().positive().max(365).optional()}),async(p,f,m)=>{let g=this.requireTeamId(p,f);if(!g)return;let b=`cm_${(0,Ym.randomBytes)(24).toString("hex")}`,v=(0,Ym.createHash)("sha256").update(b).digest("hex"),E=m.expiresInDays?new Date(Date.now()+m.expiresInDays*864e5):null,S=await new Dt(this.options.pool).createApiKey({keyHash:v,teamId:g,projectId:p.authContext?.projectId??null,actorId:p.authContext?.apiKeyId??"api",scopes:["memories:read"],expiresAt:E});m.label;let _=q4(p);f.status(201).json({id:S.id,apiKey:b,scopes:["memories:read"],expiresAt:E?.toISOString()??null,mcpUrl:_,connectCommand:F4(_,b)})})),e.get("/v1/connect",u,this.asyncHandler(async(p,f)=>{if(!this.requireTeamId(p,f))return;let g=q4(p);f.status(200).json({mcpUrl:g,connectCommand:F4(g,"<YOUR_API_KEY>"),hint:"POST /v1/keys (write scope) to mint a read-only key for this link."})})),e.post("/v1/events",l,this.asyncHandler(async(p,f)=>{let m=$4.safeParse(p.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let g=m.data.generate!=="false",b=m.data.wait==="true",v=SE.safeParse(p.body);if(!v.success){f.status(400).json({error:"ValidationError",issues:v.error.issues});return}let E=v.data,S=this.requireTeamId(p,f);if(!S||!this.ensureProjectAllowed(p,f,E.projectId))return;let _=this.toAgentEventInput(E,S);await this.applyContentSessionLinks([_],[p.body],S);let A,j=null,L="skipped",te={generate:g,source:"http_post_v1_events",apiKeyId:p.authContext?.apiKeyId??null,actorId:await this.resolveActorId(p),sourceAdapter:_.sourceAdapter,requestId:p.requestId??null};try{let q=await this.ingestEvents.ingestOne(_,te);A=q.event,j=q.outbox,L=q.enqueueState}catch(q){let J=q instanceof Error?q:new Error(String(q));x.warn("SYSTEM","event.write ingest failed",{requestId:p.requestId??null},J),this.handleDbError(J,f,"event.write");return}if(await this.auditWrite(p,"event.received",A.id,A.projectId,{sourceAdapter:A.sourceAdapter,sourceEventId:A.sourceEventId,eventType:A.eventType,serverSessionId:A.serverSessionId,generationJobId:j?.id??null}),b){let q=j,J=!1;if(j){let re=new ut(this.options.pool),at=await U4(re,j);q=at.job,J=at.timedOut}f.status(201).json({event:Bu(A),generationJob:q?B4(q,L):null,...J?{waitTimedOut:!0}:{}});return}f.status(201).json({event:Bu(A),...j?{generationJob:j_(j,L)}:{}})})),e.post("/v1/events/batch",l,this.asyncHandler(async(p,f)=>{let m=$4.safeParse(p.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let g=m.data.generate!=="false",b=m.data.wait==="true",E=ce.z.array(SE).min(1).max(500).safeParse(p.body);if(!E.success){f.status(400).json({error:"ValidationError",issues:E.error.issues});return}let S=this.requireTeamId(p,f);if(!S)return;let _=she(p,E.data);if(_){f.status(_.status).json(_.body);return}let A=E.data.map(q=>this.toAgentEventInput(q,S));await this.applyContentSessionLinks(A,Array.isArray(p.body)?p.body:E.data,S);let j=[],L=[],te={generate:g,source:"http_post_v1_events_batch",apiKeyId:p.authContext?.apiKeyId??null,actorId:await this.resolveActorId(p),sourceAdapter:null,requestId:p.requestId??null};try{let q=await this.ingestEvents.ingestBatch(A,te);j=q.map(({event:J,outbox:re})=>({event:J,outbox:re})),L=q.map(({enqueueState:J})=>J)}catch(q){let J=q instanceof Error?q:new Error(String(q));x.warn("SYSTEM","event.batch_write ingest failed",{requestId:p.requestId??null},J),this.handleDbError(J,f,"event.batch_write");return}if(await this.auditWrite(p,"event.batch_received",null,null,{eventCount:j.length,generationJobIds:j.map(({outbox:q})=>q?.id??null).filter(Boolean)}),b){let q=new ut(this.options.pool),J=Date.now()+V4,re=[];for(let I of j){if(!I.outbox){re.push({event:I.event,outbox:null,timedOut:!1});continue}let P=Math.max(0,J-Date.now()),O=await U4(q,I.outbox,P);re.push({event:I.event,outbox:O.job,timedOut:O.timedOut})}let at=re.some(I=>I.timedOut);f.status(201).json({events:re.map(({event:I,outbox:P,timedOut:O},C)=>({event:Bu(I),generationJob:P?B4(P,L[C]):null,...O?{waitTimedOut:!0}:{}})),...at?{waitTimedOut:!0}:{}});return}f.status(201).json({events:j.map(({event:q,outbox:J},re)=>({event:Bu(q),...J?{generationJob:j_(J,L[re])}:{}}))})})),e.get("/v1/events/:id",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let g=this.routeParam(p.params.id),b=new Yr(this.options.pool),v=await this.loadScopedById(p,f,{id:g,teamId:m,table:"agent_events",notFound:"Event not found",load:E=>b.getByIdForScope({id:g,projectId:E,teamId:m})});v&&f.json({event:Bu(v)})})),e.get("/v1/events/:id/observations",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let g=this.routeParam(p.params.id),v=(await this.options.pool.query("SELECT id, project_id FROM agent_events WHERE id = $1 AND team_id = $2",[g,m])).rows[0];if(!v){f.status(404).json({error:"NotFound",message:"Event not found"});return}if(!this.ensureProjectAllowed(p,f,v.project_id))return;let E=await this.options.pool.query(`
349
+ `,[e.serverSessionId,e.projectId,e.teamId,r])).rows.map(Hme)}}});function j4(t){let e=Qme.safeParse(t);if(!e.success)throw new zu(e.error.issues);return e.data}var Xt,Ec,O4,C4,Yme,Wme,Qme,zu,zm=R(()=>{"use strict";Xt=require("zod"),Ec={event:"server_beta_generate_event",summary:"server_beta_generate_summary"},O4={event:"evt",summary:"sum"},C4=Xt.z.object({team_id:Xt.z.string().min(1,"team_id is required"),project_id:Xt.z.string().min(1,"project_id is required"),source_type:Xt.z.enum(["agent_event","session_summary","observation_reindex"]),source_id:Xt.z.string().min(1,"source_id is required"),generation_job_id:Xt.z.string().min(1,"generation_job_id is required"),api_key_id:Xt.z.string().min(1).nullable(),actor_id:Xt.z.string().min(1).nullable(),source_adapter:Xt.z.string().min(1,"source_adapter is required"),request_id:Xt.z.string().min(1).nullable().optional()}),Yme=C4.extend({kind:Xt.z.literal("event"),agent_event_id:Xt.z.string().min(1)}),Wme=C4.extend({kind:Xt.z.literal("summary"),server_session_id:Xt.z.string().min(1)}),Qme=Xt.z.discriminatedUnion("kind",[Yme,Wme]),zu=class extends Error{issues;constructor(e){super(`invalid server generation job payload: ${e.map(r=>r.message).join("; ")}`),this.issues=e}}});function Sc(t){let e=O4[t.kind],r=JSON.stringify({kind:t.kind,team_id:t.team_id,project_id:t.project_id,source_type:t.source_type,source_id:t.source_id}),n=(0,K4.createHash)("sha256").update(r).digest("hex");return`${e}_${n}`}var K4,A_=R(()=>{"use strict";K4=require("crypto");zm()});function P4(t){return{kind:"event",team_id:t.event.teamId,project_id:t.event.projectId,source_type:"agent_event",source_id:t.event.id,generation_job_id:t.outboxId,agent_event_id:t.event.id,api_key_id:t.apiKeyId,actor_id:t.actorId,source_adapter:t.sourceAdapter??t.event.sourceAdapter??"api",request_id:t.requestId}}var D4,Gm,M4=R(()=>{"use strict";Co();Wi();ca();fe();A_();vn();D4="observation_generate_for_event",Gm=class{constructor(e){this.options=e}options;async ingestOne(e,r={}){let n=r.generate??!0,i=r.source??"http_post_v1_events",s=await Sn(this.options.pool,async o=>{let l=await new Yr(o).create(e);if(!n)return{event:l,outbox:null};let u=new ut(o),d=new Gt(o),p=We(),f=P4({outboxId:p,event:l,apiKeyId:r.apiKeyId??null,actorId:r.actorId??null,sourceAdapter:r.sourceAdapter??null,requestId:r.requestId??null}),m=await u.create({id:p,projectId:l.projectId,teamId:l.teamId,sourceType:"agent_event",sourceId:l.id,agentEventId:l.id,serverSessionId:l.serverSessionId,jobType:D4,bullmqJobId:Sc({kind:"event",team_id:l.teamId,project_id:l.projectId,source_type:"agent_event",source_id:l.id}),payload:f});return await d.append({generationJobId:m.id,projectId:m.projectId,teamId:m.teamId,eventType:"queued",statusAfter:m.status,attempt:m.attempts,details:{source:i}}),{event:l,outbox:m}}),a="skipped";return s.outbox&&(a=await this.publishEventJob(s.event,s.outbox)),{event:s.event,outbox:s.outbox,enqueueState:a}}async ingestBatch(e,r={}){let n=r.generate??!0,i=r.source??"http_post_v1_events_batch",s=await Sn(this.options.pool,async a=>{let o=new Yr(a),c=new ut(a),l=new Gt(a),u=[];for(let d of e){let p=await o.create(d);if(!n){u.push({event:p,outbox:null});continue}let f=We(),m=P4({outboxId:f,event:p,apiKeyId:r.apiKeyId??null,actorId:r.actorId??null,sourceAdapter:r.sourceAdapter??null,requestId:r.requestId??null}),g=await c.create({id:f,projectId:p.projectId,teamId:p.teamId,sourceType:"agent_event",sourceId:p.id,agentEventId:p.id,serverSessionId:p.serverSessionId,jobType:D4,bullmqJobId:Sc({kind:"event",team_id:p.teamId,project_id:p.projectId,source_type:"agent_event",source_id:p.id}),payload:m});await l.append({generationJobId:g.id,projectId:g.projectId,teamId:g.teamId,eventType:"queued",statusAfter:g.status,attempt:g.attempts,details:{source:i}}),u.push({event:p,outbox:g})}return u});return Promise.all(s.map(async({event:a,outbox:o})=>{let c=o?await this.publishEventJob(a,o):"skipped";return{event:a,outbox:o,enqueueState:c}}))}async publishEventJob(e,r){let n=this.options.resolveEventQueue();if(!n)return"queued_only";let i=r.bullmqJobId??Sc({kind:"event",team_id:e.teamId,project_id:e.projectId,source_type:"agent_event",source_id:e.id});try{return await n.add(i,r.payload),"enqueued"}catch(s){return x.warn("SYSTEM","failed to publish event generation job to BullMQ",{outboxId:r.id,error:s instanceof Error?s.message:String(s)}),"queued_only"}}}});function R_(t){return Sc({kind:"summary",team_id:t.teamId,project_id:t.projectId,source_type:"session_summary",source_id:t.serverSessionId})}function O_(t){return{kind:"summary",team_id:t.teamId,project_id:t.projectId,source_type:"session_summary",source_id:t.serverSessionId,generation_job_id:t.generationJobId,server_session_id:t.serverSessionId,api_key_id:t.apiKeyId??null,actor_id:t.actorId??null,source_adapter:t.sourceAdapter??"api",request_id:t.requestId??null}}var N4=R(()=>{"use strict";A_()});var Xme,Bm,L4=R(()=>{"use strict";Wi();ca();fs();fe();N4();vn();Xme="observation_generate_session_summary",Bm=class{constructor(e){this.options=e}options;async end(e){let r=e.source??"http_post_v1_sessions_end",n=await Sn(this.options.pool,async s=>{let o=await new Qt(s).endSession({id:e.sessionId,projectId:e.projectId,teamId:e.teamId});if(!o)return{session:null,outbox:null};let c=new ut(s),l=new Gt(s),u=We(),d=O_({serverSessionId:o.id,teamId:o.teamId,projectId:o.projectId,generationJobId:u,apiKeyId:e.apiKeyId??null,actorId:e.actorId??null,sourceAdapter:e.sourceAdapter??null}),p=await c.create({id:u,projectId:o.projectId,teamId:o.teamId,sourceType:"session_summary",sourceId:o.id,serverSessionId:o.id,jobType:Xme,bullmqJobId:R_({serverSessionId:o.id,teamId:o.teamId,projectId:o.projectId}),payload:d});return await l.append({generationJobId:p.id,projectId:p.projectId,teamId:p.teamId,eventType:"queued",statusAfter:p.status,attempt:p.attempts,details:{source:r}}),{session:o,outbox:p}});if(!n.session||!n.outbox)return{session:n.session,outbox:null,enqueueState:"skipped"};let i=await this.publishSummaryJob(n.session.id,n.outbox,e);return{session:n.session,outbox:n.outbox,enqueueState:i}}async publishSummaryJob(e,r,n){let i=this.options.resolveSummaryQueue();if(!i)return"queued_only";let s=r.bullmqJobId??R_({serverSessionId:e,teamId:r.teamId,projectId:r.projectId}),a=O_({serverSessionId:e,teamId:r.teamId,projectId:r.projectId,generationJobId:r.id,apiKeyId:n.apiKeyId??null,actorId:n.actorId??null,sourceAdapter:n.sourceAdapter??null});try{return await i.add(s,a),"enqueued"}catch(o){return x.warn("SYSTEM","failed to publish summary generation job to BullMQ",{outboxId:r.id,error:o instanceof Error?o.message:String(o)}),"queued_only"}}}});function q4(t){return`${(process.env.CLAUDE_MEM_PUBLIC_URL??`${t.protocol}://${t.get("host")??"localhost"}`).replace(/\/+$/,"")}/v1/mcp`}function F4(t,e){return`claude mcp add --transport http claude-mem ${t} --header "Authorization: Bearer ${e}"`}async function U4(t,e,r=V4,n=the){if(J4.includes(e.status))return{job:e,timedOut:!1};let i=Date.now()+r,s=e;for(;Date.now()<i;){await new Promise(o=>setTimeout(o,n));let a=await t.getByIdForScope({id:e.id,projectId:e.projectId,teamId:e.teamId});if(!a)return{job:s,timedOut:!1};if(s=a,J4.includes(a.status))return{job:a,timedOut:!1}}return{job:s,timedOut:!0}}function nhe(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&H4.has(e)?e:null,n=typeof t.query.source_type=="string"?t.query.source_type.trim():"",i=n&&rhe.has(n)?n:null,s=Hm(t.query.limit,Y4,1,W4),a=Hm(t.query.offset,0,0,Number.MAX_SAFE_INTEGER),o=typeof t.query.since=="string"?t.query.since.trim():"",c=null;if(o){let l=new Date(o);Number.isNaN(l.getTime())||(c=l)}return{status:r,sourceType:i,limit:s,offset:a,since:c}}function z4(t){if(!t||typeof t!="object")return 0;let e=t.retried_count;return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function G4(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&H4.has(e)?e:null,n=Hm(t.query.limit,Y4,1,W4),i=Hm(t.query.offset,0,0,Number.MAX_SAFE_INTEGER);return{status:r,limit:n,offset:i}}function Hm(t,e,r,n){if(typeof t!="string")return e;let i=Number.parseInt(t,10);return Number.isFinite(i)?Math.max(r,Math.min(n,i)):e}function C_(t,e={}){let r={id:t.id,projectId:t.project_id,teamId:t.team_id,sourceType:t.source_type,sourceId:t.source_id,status:t.status,attempts:t.attempts,maxAttempts:t.max_attempts,createdAtEpoch:new Date(t.created_at).getTime(),completedAtEpoch:t.completed_at?new Date(t.completed_at).getTime():null,failedAtEpoch:t.failed_at?new Date(t.failed_at).getTime():null,lastError:t.last_error&&typeof t.last_error=="object"?t.last_error:null};return e.includePayload&&t.payload&&typeof t.payload=="object"&&(r.payload=t.payload),r}function ihe(t){let e={"event.received":"agent_event","event.batch_received":"agent_event","event.write":"agent_event","event.batch_write":"agent_event","session.write":"server_session","session.end":"server_session","memory.write":"observation","observation.read":"observation","observation.search":"observation","observation.context":"observation","observation.generated":"observation","session_summary.generated":"observation","generation_job.queued":"observation_generation_job","generation_job.enqueued":"observation_generation_job","generation_job.processing":"observation_generation_job","generation_job.completed":"observation_generation_job","generation_job.failed":"observation_generation_job","generation_job.scope_violation":"observation_generation_job","generation_job.revoked_key":"observation_generation_job","generation_job.retried_by_operator":"observation_generation_job","generation_job.cancelled_by_operator":"observation_generation_job","generation_job.stalled":"observation_generation_job"};return e[t]?e[t]:t.split(".")[0]??"unknown"}function she(t,e){let r=t.authContext?.projectId??null;if(!(t.authContext?.teamId??null))return{status:403,body:{error:"Forbidden",message:"API key is not bound to a team"}};if(!r)return null;for(let i of e)if(i.projectId!==r)return{status:403,body:{error:"Forbidden",message:"API key is scoped to a different project"}};return null}function Gu(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,externalSessionId:t.externalSessionId,contentSessionId:t.contentSessionId,agentId:t.agentId,agentType:t.agentType,platformSource:t.platformSource,generationStatus:t.generationStatus,metadata:t.metadata,startedAtEpoch:t.startedAtEpoch,endedAtEpoch:t.endedAtEpoch,lastGeneratedAtEpoch:t.lastGeneratedAtEpoch,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function Bu(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,serverSessionId:t.serverSessionId,sourceAdapter:t.sourceAdapter,sourceEventId:t.sourceEventId,eventType:t.eventType,platformSource:t.platformSource,payload:t.payload,metadata:t.metadata,occurredAtEpoch:t.occurredAtEpoch,receivedAtEpoch:t.receivedAtEpoch,createdAtEpoch:t.createdAtEpoch}}function xc(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,serverSessionId:t.serverSessionId,kind:t.kind,content:t.content,metadata:t.metadata,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function ahe(t){return{id:t.id,projectId:t.project_id,teamId:t.team_id,serverSessionId:t.server_session_id,kind:t.kind,content:t.content,metadata:t.metadata&&typeof t.metadata=="object"?t.metadata:{},generationKey:t.generation_key,createdByJobId:t.created_by_job_id,createdAtEpoch:new Date(t.created_at).getTime(),updatedAtEpoch:new Date(t.updated_at).getTime(),source:{id:t.source_id_pk,sourceType:t.source_type,sourceId:t.source_id,generationJobId:t.generation_job_id,createdAtEpoch:new Date(t.source_created_at).getTime()}}}function j_(t,e){return{id:t.id,status:t.status,bullmqJobId:t.bullmqJobId,sourceType:t.sourceType,sourceId:t.sourceId,transport:e,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function B4(t,e){return{id:t.id,status:t.status,transport:e,bullmqJobId:t.bullmqJobId,sourceType:t.sourceType,sourceId:t.sourceId,attempts:t.attempts,maxAttempts:t.maxAttempts,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function K_(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,sourceType:t.sourceType,sourceId:t.sourceId,agentEventId:t.agentEventId,serverSessionId:t.serverSessionId,jobType:t.jobType,status:t.status,bullmqJobId:t.bullmqJobId,attempts:t.attempts,maxAttempts:t.maxAttempts,nextAttemptAtEpoch:t.nextAttemptAtEpoch,completedAtEpoch:t.completedAtEpoch,failedAtEpoch:t.failedAtEpoch,cancelledAtEpoch:t.cancelledAtEpoch,lastError:t.lastError,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}var ce,Ym,Zme,ehe,$4,V4,the,J4,Vm,rhe,H4,Y4,W4,Q4=R(()=>{"use strict";ce=require("zod");CD();Co();Wi();bi();Jl();jo();fe();lf();RS();$N();fL();_4();k4();A4();wa();Ym=require("node:crypto");fs();M4();L4();ra();Zme="api",ehe="13.22.0";$4=ce.z.object({generate:ce.z.union([ce.z.literal("true"),ce.z.literal("false")]).optional(),wait:ce.z.union([ce.z.literal("true"),ce.z.literal("false")]).optional()}),V4=3e4,the=100,J4=["completed","failed","cancelled"];Vm=class{constructor(e){this.options=e;this.ingestEvents=new Gm({pool:e.pool,resolveEventQueue:()=>this.resolveQueue("event")}),this.endSession=new Bm({pool:e.pool,resolveSummaryQueue:()=>this.resolveQueue("summary")})}options;ingestEvents;endSession;getIngestEventsService(){return this.ingestEvents}getEndSessionService(){return this.endSession}setupRoutes(e){e.use("/v1",FN());let r=ia(this.options.pool,{authMode:this.options.authMode,allowLocalDevBypass:this.options.allowLocalDevBypass,requiredScopes:["memories:write"]}),n=ia(this.options.pool,{authMode:this.options.authMode,allowLocalDevBypass:this.options.allowLocalDevBypass,requiredScopes:["memories:read"]}),i=[],s=Number(process.env.CLAUDE_MEM_RATE_LIMIT_PER_MIN??"0");s>0&&i.push(I4(this.options.pool,{windowSec:60,max:s}));let a=Number(process.env.CLAUDE_MEM_MONTHLY_REQUEST_CAP??"0");a>0&&i.push(T_(this.options.pool,{kind:"request",cap:a})),process.env.CLAUDE_MEM_USAGE_METERING==="1"&&i.push(T4(this.options.pool));let o=[...i],c=Number(process.env.CLAUDE_MEM_MONTHLY_TOKEN_CAP??"0");c>0&&o.push(T_(this.options.pool,{kind:"tokens",cap:c}));let l=[r,...o],u=[n,...i];e.get("/v1/usage",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let g=new Date(Date.UTC(new Date().getUTCFullYear(),new Date().getUTCMonth(),1)),b=await new Or(this.options.pool).summarize({teamId:m,since:g});f.status(200).json({since:g.toISOString(),usage:b})})),e.post("/v1/keys",l,this.handleCreate(ce.z.object({label:ce.z.string().max(120).optional(),expiresInDays:ce.z.number().int().positive().max(365).optional()}),async(p,f,m)=>{let g=this.requireTeamId(p,f);if(!g)return;let b=`cm_${(0,Ym.randomBytes)(24).toString("hex")}`,v=(0,Ym.createHash)("sha256").update(b).digest("hex"),E=m.expiresInDays?new Date(Date.now()+m.expiresInDays*864e5):null,S=await new Dt(this.options.pool).createApiKey({keyHash:v,teamId:g,projectId:p.authContext?.projectId??null,actorId:p.authContext?.apiKeyId??"api",scopes:["memories:read"],expiresAt:E});m.label;let _=q4(p);f.status(201).json({id:S.id,apiKey:b,scopes:["memories:read"],expiresAt:E?.toISOString()??null,mcpUrl:_,connectCommand:F4(_,b)})})),e.get("/v1/connect",u,this.asyncHandler(async(p,f)=>{if(!this.requireTeamId(p,f))return;let g=q4(p);f.status(200).json({mcpUrl:g,connectCommand:F4(g,"<YOUR_API_KEY>"),hint:"POST /v1/keys (write scope) to mint a read-only key for this link."})})),e.post("/v1/events",l,this.asyncHandler(async(p,f)=>{let m=$4.safeParse(p.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let g=m.data.generate!=="false",b=m.data.wait==="true",v=SE.safeParse(p.body);if(!v.success){f.status(400).json({error:"ValidationError",issues:v.error.issues});return}let E=v.data,S=this.requireTeamId(p,f);if(!S||!this.ensureProjectAllowed(p,f,E.projectId))return;let _=this.toAgentEventInput(E,S);await this.applyContentSessionLinks([_],[p.body],S);let A,j=null,L="skipped",te={generate:g,source:"http_post_v1_events",apiKeyId:p.authContext?.apiKeyId??null,actorId:await this.resolveActorId(p),sourceAdapter:_.sourceAdapter,requestId:p.requestId??null};try{let q=await this.ingestEvents.ingestOne(_,te);A=q.event,j=q.outbox,L=q.enqueueState}catch(q){let J=q instanceof Error?q:new Error(String(q));x.warn("SYSTEM","event.write ingest failed",{requestId:p.requestId??null},J),this.handleDbError(J,f,"event.write");return}if(await this.auditWrite(p,"event.received",A.id,A.projectId,{sourceAdapter:A.sourceAdapter,sourceEventId:A.sourceEventId,eventType:A.eventType,serverSessionId:A.serverSessionId,generationJobId:j?.id??null}),b){let q=j,J=!1;if(j){let re=new ut(this.options.pool),at=await U4(re,j);q=at.job,J=at.timedOut}f.status(201).json({event:Bu(A),generationJob:q?B4(q,L):null,...J?{waitTimedOut:!0}:{}});return}f.status(201).json({event:Bu(A),...j?{generationJob:j_(j,L)}:{}})})),e.post("/v1/events/batch",l,this.asyncHandler(async(p,f)=>{let m=$4.safeParse(p.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let g=m.data.generate!=="false",b=m.data.wait==="true",E=ce.z.array(SE).min(1).max(500).safeParse(p.body);if(!E.success){f.status(400).json({error:"ValidationError",issues:E.error.issues});return}let S=this.requireTeamId(p,f);if(!S)return;let _=she(p,E.data);if(_){f.status(_.status).json(_.body);return}let A=E.data.map(q=>this.toAgentEventInput(q,S));await this.applyContentSessionLinks(A,Array.isArray(p.body)?p.body:E.data,S);let j=[],L=[],te={generate:g,source:"http_post_v1_events_batch",apiKeyId:p.authContext?.apiKeyId??null,actorId:await this.resolveActorId(p),sourceAdapter:null,requestId:p.requestId??null};try{let q=await this.ingestEvents.ingestBatch(A,te);j=q.map(({event:J,outbox:re})=>({event:J,outbox:re})),L=q.map(({enqueueState:J})=>J)}catch(q){let J=q instanceof Error?q:new Error(String(q));x.warn("SYSTEM","event.batch_write ingest failed",{requestId:p.requestId??null},J),this.handleDbError(J,f,"event.batch_write");return}if(await this.auditWrite(p,"event.batch_received",null,null,{eventCount:j.length,generationJobIds:j.map(({outbox:q})=>q?.id??null).filter(Boolean)}),b){let q=new ut(this.options.pool),J=Date.now()+V4,re=[];for(let I of j){if(!I.outbox){re.push({event:I.event,outbox:null,timedOut:!1});continue}let P=Math.max(0,J-Date.now()),O=await U4(q,I.outbox,P);re.push({event:I.event,outbox:O.job,timedOut:O.timedOut})}let at=re.some(I=>I.timedOut);f.status(201).json({events:re.map(({event:I,outbox:P,timedOut:O},C)=>({event:Bu(I),generationJob:P?B4(P,L[C]):null,...O?{waitTimedOut:!0}:{}})),...at?{waitTimedOut:!0}:{}});return}f.status(201).json({events:j.map(({event:q,outbox:J},re)=>({event:Bu(q),...J?{generationJob:j_(J,L[re])}:{}}))})})),e.get("/v1/events/:id",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let g=this.routeParam(p.params.id),b=new Yr(this.options.pool),v=await this.loadScopedById(p,f,{id:g,teamId:m,table:"agent_events",notFound:"Event not found",load:E=>b.getByIdForScope({id:g,projectId:E,teamId:m})});v&&f.json({event:Bu(v)})})),e.get("/v1/events/:id/observations",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let g=this.routeParam(p.params.id),v=(await this.options.pool.query("SELECT id, project_id FROM agent_events WHERE id = $1 AND team_id = $2",[g,m])).rows[0];if(!v){f.status(404).json({error:"NotFound",message:"Event not found"});return}if(!this.ensureProjectAllowed(p,f,v.project_id))return;let E=await this.options.pool.query(`
350
350
  SELECT o.id, o.project_id, o.team_id, o.server_session_id, o.kind, o.content,
351
351
  o.metadata, o.generation_key, o.created_by_job_id, o.created_at, o.updated_at,
352
352
  os.id AS source_id_pk, os.source_type, os.source_id, os.generation_job_id, os.created_at AS source_created_at