claude-mem 13.7.1 → 13.8.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.7.1",
3
+ "version": "13.8.0",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "author": {
6
6
  "name": "Alex Newman",
@@ -94,7 +94,7 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
94
94
  `)}else ub(m+`
95
95
  `)}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){pb=e}error(e,r,i,n){this.log(3,e,r,i,n),this.routeErrorToSink(r,i,n)}routeErrorToSink(e,r,i){try{if(!pb||!(i instanceof Error))return;pb(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)}happyPathError(e,r,i,n,o=""){let c=((new Error().stack||"").split(`
96
96
  `)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),u=c?`${c[1].split("/").pop()}:${c[2]}`:"unknown",d={...i,location:u};return this.warn(e,`[HAPPY-PATH] ${r}`,d,n),o}},T=new fb});import{join as je,dirname as FW,basename as JW}from"path";import{homedir as HO}from"os";import{existsSync as $W,mkdirSync as vye,readFileSync as qW}from"fs";import{execSync as Sye}from"child_process";import{fileURLToPath as zW}from"url";function GW(){return typeof __dirname<"u"?__dirname:FW(zW(import.meta.url))}function xn(){if(process.env.CLAUDE_MEM_DATA_DIR)return process.env.CLAUDE_MEM_DATA_DIR;let t=je(HO(),".claude-mem"),e=je(t,"settings.json");try{if($W(e)){let r=JSON.parse(qW(e,"utf-8")),i=r.env??r;if(i.CLAUDE_MEM_DATA_DIR)return i.CLAUDE_MEM_DATA_DIR}}catch{}return t}var xye,Ne,yd,Dl,BW,VW,WW,ZW,HW,ht,kye,YW,YO,_ye,Tye,Cye,Oye,ft,rt=E(()=>{"use strict";ut();xye=GW();Ne=xn(),yd=process.env.CLAUDE_CONFIG_DIR||je(HO(),".claude"),Dl=je(yd,"plugins","marketplaces","thedotmack"),BW=je(Ne,"archives"),VW=je(Ne,"logs"),WW=je(Ne,"trash"),ZW=je(Ne,"backups"),HW=je(Ne,"modes"),ht=je(Ne,"settings.json"),kye=je(Ne,"claude-mem.db"),YW=je(Ne,"vector-db"),YO=je(Ne,"observer-sessions"),_ye=JW(YO),Tye=je(yd,"settings.json"),Cye=je(yd,"commands"),Oye=je(yd,"CLAUDE.md"),ft={dataDir:()=>Ne,workerPid:()=>je(Ne,"worker.pid"),serverBetaPid:()=>je(Ne,".server-beta.pid"),serverBetaPort:()=>je(Ne,".server-beta.port"),serverBetaRuntime:()=>je(Ne,".server-beta.runtime.json"),settings:()=>je(Ne,"settings.json"),database:()=>je(Ne,"claude-mem.db"),chroma:()=>je(Ne,"chroma"),combinedCerts:()=>je(Ne,"combined_certs.pem"),transcriptsConfig:()=>je(Ne,"transcript-watch.json"),transcriptsState:()=>je(Ne,"transcript-watch-state.json"),corpora:()=>je(Ne,"corpora"),supervisorRegistry:()=>je(Ne,"supervisor.json"),envFile:()=>je(Ne,".env"),logsDir:()=>VW,archives:()=>BW,trash:()=>WW,backups:()=>ZW,modes:()=>HW,vectorDb:()=>YW,observerSessions:()=>YO}});import{join as XO}from"path";import{mkdirSync as XW,writeFileSync as QW}from"fs";import{randomUUID as e3}from"crypto";function t3(t){let e=t.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function hb(t,e){if(t3(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 eA(t,e){return hb(t,e).enabled}function jl(){return XO(xn(),QO)}function xi(){try{let t=ur(jl(),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:""}}catch{return null}}function As(t){let e=xn();XW(e,{recursive:!0}),QW(XO(e,QO),JSON.stringify(t,null,2)+`
97
- `)}function gd(){let t=xi();if(t?.installId)return t.installId;let e=e3();return As({installId:e,decidedAt:""}),e}var QO,bd=E(()=>{"use strict";rt();ws();QO="telemetry.json"});function rA(t){let e={};try{if(!t||typeof t!="object")return e;for(let r of Object.keys(t)){if(!r3.has(r))continue;let i=t[r];typeof i=="string"?e[r]=i.length>tA?i.slice(0,tA):i:(typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean")&&(e[r]=i)}}catch{}return e}var r3,tA,nA=E(()=>{"use strict";r3=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","install_method","interactive","bun_version","uv_version","claude_code_version","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_invalid_output","top_model","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens"]),tA=200});import iA from"os";function oA(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||i3}function sA(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||o3}function aA(t){let e={};for(let r of s3)t[r]!==void 0&&(e[r]=t[r]);return e}function a3(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||iA.release().toLowerCase().includes("microsoft")}catch{return!1}}function lA(){return{version:n3,os:process.platform,os_version:iA.release(),is_wsl:a3(),arch:process.arch,runtime:process.versions.bun?"bun":"node",runtime_version:process.versions.bun??process.versions.node,node_version:process.versions.node,is_ci:!!process.env.CI,locale:Intl.DateTimeFormat().resolvedOptions().locale}}var n3,i3,o3,s3,cA=E(()=>{"use strict";n3="13.7.1",i3="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",o3="https://us.i.posthog.com";s3=["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 Rs(t,e,r){try{if(!eA(process.env,xi()))return;let i=rA({...lA(),...e??{}});if(r?.person?i.$set=aA(i):i.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:t,properties:i})+`
97
+ `)}function gd(){let t=xi();if(t?.installId)return t.installId;let e=e3();return As({installId:e,decidedAt:""}),e}var QO,bd=E(()=>{"use strict";rt();ws();QO="telemetry.json"});function rA(t){let e={};try{if(!t||typeof t!="object")return e;for(let r of Object.keys(t)){if(!r3.has(r))continue;let i=t[r];typeof i=="string"?e[r]=i.length>tA?i.slice(0,tA):i:(typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean")&&(e[r]=i)}}catch{}return e}var r3,tA,nA=E(()=>{"use strict";r3=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","install_method","interactive","bun_version","uv_version","claude_code_version","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_invalid_output","top_model","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","observations_created","total_observations_injected","total_tokens_saved_vs_naive"]),tA=200});import iA from"os";function oA(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||i3}function sA(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||o3}function aA(t){let e={};for(let r of s3)t[r]!==void 0&&(e[r]=t[r]);return e}function a3(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||iA.release().toLowerCase().includes("microsoft")}catch{return!1}}function lA(){return{version:n3,os:process.platform,os_version:iA.release(),is_wsl:a3(),arch:process.arch,runtime:process.versions.bun?"bun":"node",runtime_version:process.versions.bun??process.versions.node,node_version:process.versions.node,is_ci:!!process.env.CI,locale:Intl.DateTimeFormat().resolvedOptions().locale}}var n3,i3,o3,s3,cA=E(()=>{"use strict";n3="13.8.0",i3="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",o3="https://us.i.posthog.com";s3=["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 Rs(t,e,r){try{if(!eA(process.env,xi()))return;let i=rA({...lA(),...e??{}});if(r?.person?i.$set=aA(i):i.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:t,properties:i})+`
98
98
  `);return}let n=oA();if(!n)return;let o=new AbortController,s=setTimeout(()=>o.abort(),l3);try{await fetch(`${sA()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:n,event:t,distinct_id:gd(),properties:i}),signal:o.signal})}finally{clearTimeout(s)}}catch{}}var l3,vd=E(()=>{"use strict";bd();nA();cA();l3=2e3});import{spawn as c3}from"node:child_process";function ki(t,e,r){return c3(t,e??[],{windowsHide:!0,...r})}var Ks=E(()=>{"use strict"});function Oo(t){return process.platform==="win32"?Math.round(t*kt.WINDOWS_MULTIPLIER):t}var kt,Pl=E(()=>{"use strict";kt={DEFAULT:3e5,HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,WORKER_STARTUP_WAIT:1e3,PRE_RESTART_SETTLE_DELAY:2e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5}});var fA={};_e(fA,{SettingsDefaultsManager:()=>nt});import{readFileSync as u3,writeFileSync as uA,existsSync as dA,mkdirSync as d3}from"fs";import{join as pA,dirname as p3}from"path";import{homedir as mA}from"os";var nt,sn=E(()=>{"use strict";Pl();nt=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(Oo(kt.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-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_GEMINI_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_GEMINI_MAX_TOKENS:"100000",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_OPENROUTER_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_OPENROUTER_MAX_TOKENS:"100000",CLAUDE_MEM_DATA_DIR:pA(mA(),".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:pA(mA(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_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 getBool(e){let r=this.get(e);return r==="true"||r===!0}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(!dA(e)){let a=this.getAllDefaults();try{let l=p3(e);dA(l)||d3(l,{recursive:!0}),uA(e,JSON.stringify(a,null,2),"utf-8"),console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(l){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,l instanceof Error?l.message:String(l))}return r?this.applyEnvOverrides(a):a}let i=u3(e,"utf-8"),n=JSON.parse(i.replace(/^\uFEFF/,"")),o=n;if(n.env&&typeof n.env=="object"){o=n.env;try{uA(e,JSON.stringify(o,null,2),"utf-8"),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(a){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,a instanceof Error?a.message:String(a))}}let s={...this.DEFAULTS};for(let a of Object.keys(this.DEFAULTS))o[a]!==void 0&&(s[a]=o[a]);return r?this.applyEnvOverrides(s):s}catch(i){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,i instanceof Error?i.message:String(i));let n=this.getAllDefaults();return r?this.applyEnvOverrides(n):n}}}});import{execFile as m3}from"child_process";import{promisify as f3}from"util";import{existsSync as ege,readFileSync as tge,writeFileSync as rge,mkdirSync as nge,unlinkSync as ige}from"fs";import{userInfo as sge}from"os";import{join as lge}from"path";var dge,hA=E(()=>{"use strict";rt();ut();dge=f3(m3)});import{existsSync as yb,readFileSync as gA,writeFileSync as h3,mkdirSync as y3,chmodSync as yA}from"fs";import{parseEnv as g3}from"util";function bA(){return process.env.CLAUDE_MEM_ENV_FILE??ft.envFile()}function EA(t){return g3(t)}function b3(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(`
99
99
  `)+`
100
100
  `}function Ml(){let t=bA();if(!yb(t))return{};try{let e=gA(t,"utf-8"),r=EA(e),i={};for(let n of vA)r[n]&&(i[n]=r[n]);return i}catch(e){return T.warn("ENV","Failed to load .env file",{path:t},e instanceof Error?e:new Error(String(e))),{}}}function Nl(t){let e=bA(),r={};try{yb(ft.dataDir())||y3(ft.dataDir(),{recursive:!0,mode:448}),yA(ft.dataDir(),448),r=yb(e)?EA(gA(e,"utf-8")):{}}catch(n){let o=n instanceof Error?n:new Error(String(n));throw T.error("ENV","Failed to set up env directory or read existing env",{},o),o}let i={...r};for(let n of vA){let o=t[n];o!==void 0&&(o?i[n]=o:delete i[n])}try{h3(e,b3(i),{encoding:"utf-8",mode:384}),yA(e,384)}catch(n){throw T.error("ENV","Failed to save .env file",{path:e},n instanceof Error?n:new Error(String(n))),n}}var vA,SA=E(()=>{"use strict";ut();rt();hA();vA=["ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","GEMINI_API_KEY","OPENROUTER_API_KEY"]});function IA(t){return t instanceof Error?t:new Error(String(t))}var wA=E(()=>{"use strict"});function Ao(t=process.env){let e={};for(let[r,i]of Object.entries(t))if(i!==void 0){if(S3.has(r)){e[r]=i;continue}E3.has(r)||v3.some(n=>r.startsWith(n))||(e[r]=i)}return e}var v3,E3,S3,Ed=E(()=>{"use strict";v3=["CLAUDECODE_","CLAUDE_CODE_"],E3=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID","HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy"]),S3=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","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"])});import{spawnSync as TA}from"child_process";import{existsSync as I3,mkdirSync as xA,readFileSync as CA,writeFileSync as w3}from"fs";import kA from"path";function Vn(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:(T.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return T.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function Sd(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(i=>!Vn(i.pid)))return;await new Promise(i=>setTimeout(i,100))}}function C3(t){let e=_A.get(t);if(e&&Date.now()-e.capturedAtMs<T3)return e.token;let r=null;try{let i=TA("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Ao(process.env),LC_ALL:"C",LANG:"C"}});if(i.status===0){let n=i.stdout.trim();r=n.length>0?n:null}}catch(i){T.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:i instanceof Error?i.message:String(i)}),r=null}return _A.set(t,{token:r,capturedAtMs:Date.now()}),r}function OA(t){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux")try{let e=CA(`/proc/${t}/stat`,"utf-8"),r=e.lastIndexOf(") ");if(r<0)return null;let n=e.slice(r+2).split(" ")[19];return n&&/^\d+$/.test(n)?n:null}catch(e){return T.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return C3(t);try{let e=TA("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Ao(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let r=e.stdout.trim();return r.length>0?r:null}catch(e){return T.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}}function Eb(t){if(!t||!Vn(t.pid))return!1;if(!t.startToken)return!0;let e=OA(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||T.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}function Id(){return gb||(gb=new vb),gb}function bb(){let t=O3.shift();t&&t()}var x3,k3,_3,T3,_A,vb,gb,O3,Ll=E(()=>{"use strict";Ks();ut();Ed();rt();x3=5e3,k3=1e3,_3=ft.supervisorRegistry();T3=5e3,_A=new Map;vb=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=_3){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,xA(kA.dirname(this.registryPath),{recursive:!0}),!I3(this.registryPath)){this.persist();return}try{let i=JSON.parse(CA(this.registryPath,"utf-8")).processes??{};for(let[n,o]of Object.entries(i))this.entries.set(n,o)}catch(r){r instanceof Error?T.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):T.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&T.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,r,i){this.initialize(),this.entries.set(e,r),i&&this.runtimeProcesses.set(e,i),this.persist()}unregister(e){this.initialize();let r=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),r?.type==="sdk"&&bb()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let i=Date.parse(e.startedAt),n=Date.parse(r.startedAt);return(Number.isNaN(i)?0:i)-(Number.isNaN(n)?0:n)})}getBySession(e){let r=String(e);return this.getAll().filter(i=>i.sessionId!==void 0&&String(i.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}getByPid(e){return this.getAll().filter(r=>r.pid===e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[i,n]of this.entries)Vn(n.pid)||(this.entries.delete(i),this.runtimeProcesses.delete(i),e+=1,n.type==="sdk"&&(r+=1));e>0&&this.persist();for(let i=0;i<r;i+=1)bb();return e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let i=typeof e=="number"?e:Number(e)||void 0;T.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:i,pids:r.map(s=>s.pid)});let n=r.filter(s=>Vn(s.pid));for(let s of n)try{typeof s.pgid=="number"&&process.platform!=="win32"?process.kill(-s.pgid,"SIGTERM"):process.kill(s.pid,"SIGTERM")}catch(a){a instanceof Error?a.code!=="ESRCH"&&T.debug("SYSTEM",`Failed to SIGTERM session process PID ${s.pid}`,{pid:s.pid,pgid:s.pgid},a):T.warn("SYSTEM",`Failed to SIGTERM session process PID ${s.pid} (non-Error)`,{pid:s.pid,pgid:s.pgid,error:String(a)})}await Sd(n,x3);let o=n.filter(s=>Vn(s.pid));for(let s of o){T.warn("SYSTEM",`Session process PID ${s.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:s.pid,pgid:s.pgid,sessionId:i});try{typeof s.pgid=="number"&&process.platform!=="win32"?process.kill(-s.pgid,"SIGKILL"):process.kill(s.pid,"SIGKILL")}catch(a){a instanceof Error?a.code!=="ESRCH"&&T.debug("SYSTEM",`Failed to SIGKILL session process PID ${s.pid}`,{pid:s.pid,pgid:s.pgid},a):T.warn("SYSTEM",`Failed to SIGKILL session process PID ${s.pid} (non-Error)`,{pid:s.pid,pgid:s.pgid,error:String(a)})}}if(o.length>0){let s=Date.now()+k3;for(;Date.now()<s&&o.filter(l=>Vn(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let s of r)this.entries.delete(s.id),this.runtimeProcesses.delete(s.id);this.persist();for(let s of r)s.type==="sdk"&&bb();return T.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:i,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};xA(kA.dirname(this.registryPath),{recursive:!0}),w3(this.registryPath,JSON.stringify(e,null,2))}},gb=null;O3=[]});import{execFile as A3}from"child_process";import{existsSync as R3,readFileSync as K3,rmSync as D3}from"fs";import{promisify as j3}from"util";async function RA(t){let e=t.currentPid??process.pid,r=t.pidFilePath??M3,i=t.registry.getAll(),n=[...i].filter(s=>s.pid!==e).sort((s,a)=>Date.parse(a.startedAt)-Date.parse(s.startedAt));for(let s of n){if(!Vn(s.pid)){t.registry.unregister(s.id);continue}try{await AA(s,"SIGTERM")}catch(a){a instanceof Error?T.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:s.pid,pgid:s.pgid,type:s.type},a):T.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:s.pid,pgid:s.pgid,type:s.type,error:String(a)})}}await Sd(n,5e3);let o=n.filter(s=>Vn(s.pid));for(let s of o)try{await AA(s,"SIGKILL")}catch(a){a instanceof Error?T.debug("SYSTEM","Failed to force kill child process",{pid:s.pid,pgid:s.pgid,type:s.type},a):T.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:s.pid,pgid:s.pgid,type:s.type,error:String(a)})}await Sd(o,1e3);for(let s of n)t.registry.unregister(s.id);for(let s of i.filter(a=>a.pid===e))t.registry.unregister(s.id);N3(r,e),t.registry.pruneDeadEntries()}function N3(t,e){if(!R3(t))return;let r=null;try{let i=JSON.parse(K3(t,"utf-8"));r=typeof i.pid=="number"?i.pid:null}catch(i){T.debug("SYSTEM","PID file unreadable during shutdown \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:i instanceof Error?i.message:String(i)});return}if(r!==e){T.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:r,currentPid:e});return}try{D3(t,{force:!0})}catch(i){i instanceof Error?T.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:t},i):T.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:t,error:String(i)})}}async function AA(t,e){let{pid:r,pgid:i}=t;if(process.platform!=="win32"){if(typeof i=="number")try{process.kill(-i,e);return}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}try{process.kill(r,e)}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}return}if(e==="SIGTERM"){try{process.kill(r,e)}catch(s){if(s instanceof Error&&s.code==="ESRCH")return;throw s}return}let n=await L3();if(n){await new Promise((s,a)=>{n(r,e,l=>{if(!l){s();return}if(l.code==="ESRCH"){s();return}a(l)})});return}let o=["/PID",String(r),"/T"];e==="SIGKILL"&&o.push("/F"),await P3("taskkill",o,{timeout:kt.POWERSHELL_COMMAND,windowsHide:!0})}async function L3(){let t="tree-kill";try{let e=await import(t);return e.default??e}catch(e){return T.debug("SYSTEM","tree-kill module not available, using fallback",{},e instanceof Error?e:void 0),null}}var P3,M3,KA=E(()=>{"use strict";ut();Pl();Ll();rt();P3=j3(A3),M3=ft.workerPid()});function U3(){let e=Id().pruneDeadEntries();e>0&&T.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function jA(){Ds===null&&(Ds=setInterval(U3,DA),Ds.unref(),T.debug("SYSTEM","Health checker started",{intervalMs:DA}))}function PA(){Ds!==null&&(clearInterval(Ds),Ds=null,T.debug("SYSTEM","Health checker stopped"))}var DA,Ds,MA=E(()=>{"use strict";ut();Ll();DA=3e4,Ds=null});import{existsSync as F3,readFileSync as J3,rmSync as NA}from"fs";function Ib(){return q3}function wd(t={}){let e=t.pidFilePath??$3;if(!F3(e))return"missing";let r=null;try{r=JSON.parse(J3(e,"utf-8"))}catch(n){return n instanceof Error?T.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},n):T.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(n)}),NA(e,{force:!0}),"invalid"}return Eb(r)&&r?((t.logAlive??!0)&&T.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(T.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),NA(e,{force:!0}),"stale")}var $3,Sb,q3,xd=E(()=>{"use strict";ut();Ll();KA();MA();rt();$3=ft.workerPid(),Sb=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(),wd({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,jA()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async i=>{if(this.shutdownInitiated){T.warn("SYSTEM",`Received ${i} but shutdown already in progress`);return}this.shutdownInitiated=!0,T.info("SYSTEM",`Received ${i}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(n){n instanceof Error?T.error("SYSTEM","Error during shutdown",{},n):T.error("SYSTEM","Error during shutdown (non-Error)",{error:String(n)});try{await this.stop()}catch(o){o instanceof Error?T.debug("SYSTEM","Supervisor shutdown fallback failed",{},o):T.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(o)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{T.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}PA(),this.stopPromise=RA({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,i){this.registry.register(e,r,i)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},q3=new Sb(Id())});import js from"path";import{homedir as z3}from"os";import{existsSync as xb,writeFileSync as ebe,readFileSync as tbe,unlinkSync as rbe,mkdirSync as nbe,rmSync as ibe,statSync as obe,utimesSync as G3,copyFileSync as sbe}from"fs";import{execSync as FA,spawnSync as lbe}from"child_process";function UA(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function B3(t,e){let r=e==="win32"?`where ${t}`:`which ${t}`,i;try{i=FA(r,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(o){return o instanceof Error?T.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},o):T.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r},new Error(String(o))),null}return i.split(/\r?\n/).map(o=>o.trim()).find(o=>o.length>0)||null}function JA(t={}){let e=Object.keys(t).length===0;if(e&&wb!==void 0)return wb;let r=V3(t);return e&&r!==null&&(wb=r),r}function V3(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(UA(r))return r;let i=t.env??process.env,n=t.homeDirectory??z3(),o=t.pathExists??xb,s=t.lookupInPath??B3,a=e==="win32"?[i.BUN,i.BUN_PATH,js.join(n,".bun","bin","bun.exe"),js.join(n,".bun","bin","bun"),i.USERPROFILE?js.join(i.USERPROFILE,".bun","bin","bun.exe"):void 0,i.LOCALAPPDATA?js.join(i.LOCALAPPDATA,"bun","bun.exe"):void 0,i.LOCALAPPDATA?js.join(i.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[i.BUN,i.BUN_PATH,js.join(n,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun"];for(let l of a){let c=l?.trim();if(c&&(UA(c)&&o(c)||c.toLowerCase()==="bun"))return c}return s("bun",e)}function _i(t){return process.platform==="win32"?Math.round(t*2):t}function $A(t,e,r={}){Ib().assertCanSpawn("worker daemon");let i=Ao({...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r}),n=JA();if(!n){T.error("SYSTEM","Bun runtime not found \u2014 install from https://bun.sh and ensure it is on PATH or set BUN env var. The worker daemon requires Bun because it uses bun:sqlite.");return}if(process.platform==="win32"){let u=`Start-Process -FilePath '${n.replace(/'/g,"''")}' -ArgumentList @('${t.replace(/'/g,"''")}','--daemon') -WindowStyle Hidden`,d=Buffer.from(u,"utf16le").toString("base64");try{return FA(`powershell -NoProfile -EncodedCommand ${d}`,{stdio:"ignore",windowsHide:!0,env:i}),0}catch(m){T.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:n},IA(m));return}}let o="/usr/bin/setsid",s=xb(o),c=ki(s?o:n,s?[n,t,"--daemon"]:[t,"--daemon"],{detached:!0,stdio:"ignore",env:i});if(c.pid!==void 0)return c.unref(),c.pid}function qA(){try{if(!xb(LA))return;let t=new Date;G3(LA,t,t)}catch{}}function zA(){return wd({logAlive:!1})}var hbe,LA,wb,kd=E(()=>{"use strict";Ks();ut();wA();Ed();xd();rt();Ll();hbe=ft.dataDir(),LA=ft.workerPid()});import vbe from"path";import W3 from"net";import{readFileSync as Ibe}from"fs";async function Z3(t,e,r="GET"){let i=await fetch(`http://127.0.0.1:${t}${e}`,{method:r}),n="";try{n=await i.text()}catch{}return{ok:i.ok,statusCode:i.status,body:n}}async function GA(t){if(process.platform==="win32")try{return(await fetch(`http://127.0.0.1:${t}/api/health`)).ok}catch(e){return e instanceof Error?T.debug("SYSTEM","Windows health check failed (port not in use)",{},e):T.debug("SYSTEM","Windows health check failed (port not in use)",{error:String(e)}),!1}return new Promise(e=>{let r=W3.createServer();r.once("error",i=>{i.code==="EADDRINUSE"?e(!0):e(!1)}),r.once("listening",()=>{r.close(()=>e(!1))}),r.listen(t,"127.0.0.1")})}async function BA(t,e,r,i){let n=Date.now();for(;Date.now()-n<r;){try{if((await Z3(t,e)).ok)return!0}catch(o){o instanceof Error?T.debug("SYSTEM",i,{},o):T.debug("SYSTEM",i,{error:String(o)})}await new Promise(o=>setTimeout(o,500))}return!1}function Ul(t,e=3e4){return BA(t,"/api/health",e,"Service not ready yet, will retry")}function Fl(t,e=3e4){return BA(t,"/api/readiness",e,"Worker not ready yet, will retry")}var kb=E(()=>{"use strict";ut();rt()});import{dirname as H3,join as Y3}from"path";import{mkdirSync as X3,readFileSync as Q3,statSync as VA,unlinkSync as WA,writeFileSync as eZ}from"fs";function ZA(){return Y3(xn(),"spawn.lock")}function _b(){let t=ZA(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return X3(H3(t),{recursive:!0}),eZ(t,e,{flag:"wx"}),!0}catch(i){if(i?.code!=="EEXIST")return!0;if(r>0)return!1;let o;try{o=VA(t).mtimeMs}catch{continue}if(Date.now()-o<=tZ)return!1;let s;try{s=VA(t).mtimeMs}catch{continue}if(s!==o)return!1;try{WA(t)}catch{return!1}}return!1}function Tb(){let t=ZA();try{if(JSON.parse(Q3(t,"utf-8")).pid!==process.pid)return;WA(t)}catch{}}var tZ,Cb=E(()=>{"use strict";rt();tZ=6e4});import HA from"path";import{existsSync as Ob,mkdirSync as rZ,writeFileSync as nZ,unlinkSync as iZ,statSync as oZ}from"fs";function Ab(){return HA.join(nt.get("CLAUDE_MEM_DATA_DIR"),".worker-start-attempted")}function aZ(){if(process.platform!=="win32")return!1;let t=Ab();if(!Ob(t))return!1;try{let e=oZ(t).mtimeMs;return Date.now()-e<sZ}catch(e){return e instanceof Error?T.debug("SYSTEM","Could not stat worker spawn lock file",{},e):T.debug("SYSTEM","Could not stat worker spawn lock file",{error:String(e)}),!1}}function lZ(){if(process.platform==="win32")try{let t=Ab();rZ(HA.dirname(t),{recursive:!0}),nZ(t,"","utf-8")}catch{}}function _d(){if(process.platform==="win32")try{let t=Ab();Ob(t)&&iZ(t)}catch{}}async function YA(t,e){if(!e)return T.error("SYSTEM","ensureWorkerStarted called with empty workerScriptPath \u2014 caller bug"),"dead";if(!Ob(e))return T.error("SYSTEM","ensureWorkerStarted: worker script not found at expected path \u2014 likely a partial install or build artifact missing",{workerScriptPath:e}),"dead";if(zA()==="alive"){if(T.info("SYSTEM","Worker PID file points to a live process, skipping duplicate spawn"),await Ul(t,_i(kt.PORT_IN_USE_WAIT))){_d();let a=await Fl(t,_i(kt.READINESS_WAIT));return T.info("SYSTEM","Worker became healthy while waiting on live PID"),a?"ready":"warming"}return T.warn("SYSTEM","Live PID detected but worker did not become healthy before timeout \u2014 likely still starting"),"warming"}if(await Ul(t,1e3)){_d();let s=await Fl(t,_i(kt.READINESS_WAIT));return s||T.warn("SYSTEM","Worker is alive but readiness timed out \u2014 proceeding anyway"),T.info("SYSTEM","Worker already running and healthy"),s?"ready":"warming"}if(await GA(t)){if(T.info("SYSTEM","Port in use, waiting for worker to become healthy"),await Ul(t,_i(kt.PORT_IN_USE_WAIT))){_d();let a=await Fl(t,_i(kt.READINESS_WAIT));return T.info("SYSTEM","Worker is now healthy"),a?"ready":"warming"}return T.error("SYSTEM","Port in use but worker not responding to health checks"),"dead"}if(aZ())return T.warn("SYSTEM","Worker unavailable on Windows \u2014 skipping spawn (recent attempt failed within cooldown)"),"dead";let n=_b();try{if(n){if(T.info("SYSTEM","Starting worker daemon",{workerScriptPath:e}),lZ(),$A(e,t)===void 0)return T.error("SYSTEM","Failed to spawn worker daemon"),"dead"}else T.info("SYSTEM","Another launcher holds the spawn lock \u2014 skipping duplicate spawn and waiting for its worker");if(!await Ul(t,_i(kt.POST_SPAWN_WAIT)))return T.warn("SYSTEM",n?"Worker spawned but health endpoint not responding within window \u2014 likely still starting in background":"Spawn-lock holder's worker not healthy within window \u2014 likely still starting in background"),"warming"}finally{n&&Tb()}let o=await Fl(t,_i(kt.READINESS_WAIT));return o||T.warn("SYSTEM","Worker is alive but readiness timed out \u2014 proceeding anyway"),_d(),qA(),T.info("SYSTEM",n?"Worker started successfully":"Worker is up (started by another launcher)"),o?"ready":"warming"}var sZ,XA=E(()=>{"use strict";ut();Pl();sn();kd();kb();Cb();sZ=120*1e3});function Ro(t){return t instanceof Error?t.message:typeof t=="string"?t:t&&typeof t=="object"&&"message"in t?String(t.message):String(t??"")}function QA(t,e){for(let r of Rb)if(r.match(t,e))return r;return Rb[Rb.length-1]}var cZ,uZ,Rb,Td=E(()=>{"use strict";cZ=t=>t.platform==="win32"?'Install Bun manually then re-run `npx claude-mem install`. Windows: `winget install Oven-sh.Bun` (or `powershell -c "irm bun.sh/install.ps1 | iex"`).':"Install Bun manually then re-run `npx claude-mem install`. macOS/Linux: `curl -fsSL https://bun.sh/install | bash` (or `brew install oven-sh/bun/bun`).",uZ=t=>t.platform==="win32"?'Install uv manually then re-run `npx claude-mem install`. Windows: `winget install astral-sh.uv` (or `powershell -c "irm https://astral.sh/uv/install.ps1 | iex"`).':"Install uv manually then re-run `npx claude-mem install`. macOS/Linux: `curl -LsSf https://astral.sh/uv/install.sh | sh` (or `brew install uv`).",Rb=[{id:"bun-missing-after-install",severity:"ABORT",match:t=>{let e=Ro(t);return e.includes("Bun executable not found")||e.includes("Bun installation completed but binary not found")||e.includes("Failed to install Bun")},remediation:cZ},{id:"uv-missing-after-install",severity:"ABORT",match:t=>{let e=Ro(t);return e.includes("uv executable not found")||e.includes("uv installed but version probe failed")||e.includes("uv binary not found")||e.includes("Failed to install uv")},remediation:uZ},{id:"tree-sitter-eresolve",severity:"ABORT",match:t=>/\bERESOLVE\b/.test(Ro(t)),remediation:()=>"ERESOLVE peer-dependency conflict in marketplace deps that --legacy-peer-deps could not resolve. Open an issue at https://github.com/thedotmack/claude-mem/issues with the conflicting peer ranges shown above."},{id:"bun-install-network-fail",severity:"SILENT_RETRY",match:t=>/error: failed to resolve/.test(Ro(t)),remediation:()=>"bun install failed to resolve packages \u2014 check network connectivity and re-run `npx claude-mem install`. Cached packages in ~/.bun/install/cache will be reused."},{id:"marketplace-dir-not-writable",severity:"ABORT",match:t=>/\b(EACCES|EPERM)\b/.test(Ro(t)),remediation:t=>`Cannot write to the claude-mem data/marketplace directory under ${t.dataDir}. Check filesystem permissions or set CLAUDE_MEM_DATA_DIR to a writable path, then re-run.`},{id:"plugin-json-corrupt",severity:"ABORT",match:(t,e)=>e.component==="plugin-json"&&/Unexpected token|JSON|parse/i.test(Ro(t)),remediation:()=>"Existing plugin.json is corrupt. Run `rm -rf ~/.claude/plugins/marketplaces/thedotmack` and re-run `npx claude-mem install`."},{id:"all-ides-failed",severity:"ABORT",match:(t,e)=>e.component==="all-ides",remediation:()=>"Every selected IDE integration failed. See the per-IDE errors above. Re-run with `--ide=<single>` to isolate the failure."},{id:"single-ide-failed",severity:"FAIL_LOUD_PER_IDE",match:(t,e)=>e.phase==="ide-install",remediation:()=>"Re-run `npx claude-mem install --ide=<name>` to retry just this IDE. The captured stderr is shown above."},{id:"path-update-failed",severity:"WARN_CONTINUE",match:(t,e)=>e.component==="path-update",remediation:()=>"Could not auto-update PATH in your shell config. Add the printed export line manually and restart your shell."},{id:"auto-memory-toggle-failed",severity:"WARN_CONTINUE",match:(t,e)=>e.component==="auto-memory",remediation:()=>'Could not disable Claude Code auto-memory. Add `"CLAUDE_CODE_DISABLE_AUTO_MEMORY": "1"` to the env block in ~/.claude/settings.json.'},{id:"version-probe-transient",severity:"WARN_CONTINUE",match:(t,e)=>e.component.endsWith("-version-probe"),remediation:()=>"Could not verify the tool version after install \u2014 the installation is likely OK. Re-run `npx claude-mem install` if features misbehave."},{id:"child-process-timeout",severity:"ABORT",match:t=>/timed out|ETIMEDOUT|SIGTERM|did not finish/i.test(Ro(t)),remediation:()=>"An install command did not finish in time. Check network connectivity. On a slow host, raise the budget with CLAUDE_MEM_INSTALL_TIMEOUT_MS and re-run."},{id:"unknown-install-error",severity:"ABORT",match:()=>!0,remediation:t=>`An unexpected installer error occurred. Capture ${t.dataDir}/last-install-error.json and open an issue at https://github.com/thedotmack/claude-mem/issues.`}]});import{mkdirSync as dZ,writeFileSync as pZ}from"fs";import{join as mZ}from"path";function tR(){return{warnings:[],failedIDEs:[],retryCount:{}}}function Ps(t){return t instanceof Error?t.message:typeof t=="string"?t:String(t??"")}function fZ(t,e,r,i){try{dZ(i,{recursive:!0});let n={severity:t.severity,categoryId:t.id,component:e.component,phase:e.phase,cause:Ps(e.cause),remediation:r,details:e.details??null,timestamp:new Date().toISOString()};pZ(mZ(i,"last-install-error.json"),JSON.stringify(n,null,2))}catch{}}function Nt(t,e,r){let i=xn(),n=QA(e.cause,{component:e.component,phase:e.phase}),o=e.remediation??n.remediation({platform:process.platform,dataDir:i});switch(t){case"ABORT":throw fZ(n,e,o,i),new Jl(`${e.component} failed during ${e.phase}: ${Ps(e.cause)}`,{category:n,remediation:o,cause:e.cause});case"FAIL_LOUD_PER_IDE":{let s=e.ide??e.component;r.failedIDEs.includes(s)||r.failedIDEs.push(s),r.warnings.push({component:s,message:e.details?`${Ps(e.cause)}
@@ -3,7 +3,7 @@
3
3
  "name": "Claude-Mem (Persistent Memory)",
4
4
  "description": "OpenClaw plugin for Claude-Mem. Records observations from embedded runner sessions and streams them to messaging channels.",
5
5
  "kind": "memory",
6
- "version": "13.7.1",
6
+ "version": "13.8.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.7.1",
3
+ "version": "13.8.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.7.1",
3
+ "version": "13.8.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.7.1",
3
+ "version": "13.8.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.7.1",
3
+ "version": "13.8.0",
4
4
  "private": true,
5
5
  "description": "Runtime dependencies for claude-mem bundled hooks",
6
6
  "type": "module",
@@ -219,7 +219,7 @@ ${m}`}let c=i.lineStart;for(let l=i.lineStart-1;l>=0;l--){let d=a[l].trim();if(d
219
219
  ${u}`}var I_=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",".ex",".exs",".lua",".scala",".sc",".sh",".bash",".zsh",".hs",".zig",".css",".scss",".toml",".yml",".yaml",".sql",".md",".mdx"]),dP=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),pP=512*1024;async function*O_(t,e,r=20,n){if(r<=0)return;let o;try{o=await(0,Nr.readdir)(t,{withFileTypes:!0})}catch(s){y.debug("WORKER",`walkDir: failed to read directory ${t}`,void 0,s instanceof Error?s:void 0);return}for(let s of o){if(s.name.startsWith(".")&&s.name!=="."||dP.has(s.name))continue;let i=(0,Jn.join)(t,s.name);if(s.isDirectory())yield*O_(i,e,r-1,n);else if(s.isFile()){let a=s.name.slice(s.name.lastIndexOf("."));(I_.has(a)||n&&n.has(a))&&(yield i)}}}async function fP(t){try{let e=await(0,Nr.stat)(t);if(e.size>pP||e.size===0)return null;let r=await(0,Nr.readFile)(t,"utf-8");return r.slice(0,1e3).includes("\0")?null:r}catch(e){return y.debug("WORKER",`safeReadFile: failed to read ${t}`,void 0,e instanceof Error?e:void 0),null}}async function A_(t,e,r={}){let n=r.maxResults||20,o=e.toLowerCase(),s=o.split(/[\s_\-./]+/).filter(E=>E.length>0),i=r.projectRoot||t,a=Gn(i),c=new Set;for(let E of Object.values(a.grammars))for(let v of E.extensions)I_.has(v)||c.add(v);let u=[];for await(let E of O_(t,t,20,c.size>0?c:void 0)){if(r.filePattern&&!(0,Jn.relative)(t,E).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let v=await fP(E);v&&u.push({absolutePath:E,relativePath:(0,Jn.relative)(t,E),content:v})}let l=T_(u,i),d=[],p=[],f=0;for(let[E,v]of l){f+=mP(v);let x=Hs(E.toLowerCase(),s)>0,Se=[],we=(Zt,nr)=>{for(let ae of Zt){let kt=0,Ke="",jr=Hs(ae.name.toLowerCase(),s);jr>0&&(kt+=jr*3,Ke="name match"),ae.signature.toLowerCase().includes(o)&&(kt+=2,Ke=Ke?`${Ke} + signature`:"signature match"),ae.jsdoc&&ae.jsdoc.toLowerCase().includes(o)&&(kt+=1,Ke=Ke?`${Ke} + jsdoc`:"jsdoc match"),kt>0&&(x=!0,Se.push({filePath:E,symbolName:nr?`${nr}.${ae.name}`:ae.name,kind:ae.kind,signature:ae.signature,jsdoc:ae.jsdoc,lineStart:ae.lineStart,lineEnd:ae.lineEnd,matchReason:Ke})),ae.children&&we(ae.children,ae.name)}};we(v.symbols),x&&(d.push(v),p.push(...Se))}p.sort((E,v)=>{let $=Hs(E.symbolName.toLowerCase(),s);return Hs(v.symbolName.toLowerCase(),s)-$});let m=p.slice(0,n),_=new Set(m.map(E=>E.filePath)),S=d.filter(E=>_.has(E.filePath)).slice(0,n),b=S.reduce((E,v)=>E+v.foldedTokenEstimate,0);return{foldedFiles:S,matchingSymbols:m,totalFilesScanned:u.length,totalSymbolsFound:f,tokenEstimate:b}}function Hs(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 mP(t){let e=t.symbols.length;for(let r of t.symbols)r.children&&(e+=r.children.length);return e}function M_(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(`
220
220
  `);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(`
221
221
  `).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(Cr(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(`
222
- `)}var Ou=require("node:fs/promises"),Vs=require("node:fs"),tt=require("node:path"),Z_=require("node:os"),F_=require("node:url");var hP=bt(ce.API_REQUEST),Be=class extends Error{kind;status;cause;constructor(e,r,n={}){super(r),this.name="ServerBetaClientError",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)}},Ws=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=gP(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??hP}async startSession(e){let r=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",r)}async recordEvent(e){let r=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(e){if(!e.sessionId)throw new Be("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async getJobStatus(e){if(!e)throw new Be("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,type:n,narrative:r,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{}}}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: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.payload!==void 0?{payload:e.payload}:{}}}async request(e,r,n){if(!this.apiKey||!this.apiKey.trim())throw new Be("missing_api_key","Server beta API key is not configured (CLAUDE_MEM_SERVER_BETA_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 yu(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new Be(l?"timeout":"transport",`Server beta ${e} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new Be("http_error",`Server beta ${e} ${r} returned ${i.status}: ${_P(c,200)}`,{status:i.status})}let a=await i.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(c){throw new Be("invalid_response",`Server beta ${e} ${r} returned non-JSON response`,{cause:c})}}};function C_(t){return t instanceof Be}function gP(t){return t.replace(/\/+$/,"")}function _P(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Ru(){return(Rs().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase()==="server-beta"?"server-beta":"worker"}function N_(){let t=Rs(),e=(t.CLAUDE_MEM_SERVER_BETA_URL??"").trim(),r=(t.CLAUDE_MEM_SERVER_BETA_API_KEY??"").trim(),n=(t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID??"").trim();if(!e)return y.warn("HOOK","[server-beta-fallback] reason=missing_base_url"),null;if(!r)return y.warn("HOOK","[server-beta-fallback] reason=missing_api_key"),null;if(!n)return y.warn("HOOK","[server-beta-fallback] reason=missing_project_id"),null;let o={serverBaseUrl:e,apiKey:r};return{runtime:"server-beta",client:new Ws(o),projectId:n,serverBaseUrl:e}}var OP={},yP="13.7.1";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var H_=!1,W_=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,tt.dirname)((0,F_.fileURLToPath)(OP.url))}catch{return H_=!0,process.cwd()}})(),Au=h_()??(0,tt.resolve)(W_,"worker-service.cjs");function SP(){H_&&((0,Vs.existsSync)(Au)||y.error("SYSTEM","mcp-server: dirname resolution failed (both __dirname and import.meta.url are unavailable). Fell back to process.cwd() and the resolved WORKER_SCRIPT_PATH does not exist. This is the actual problem \u2014 the worker bundle is fine, but mcp-server cannot locate it. Worker auto-start will fail until the dirname-resolution path is fixed.",{workerScriptPath:Au,mcpServerDir:W_}))}var D_={search:"/api/search",timeline:"/api/timeline"};async function Iu(t,e){y.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t,params:e});let r=new URLSearchParams;for(let[o,s]of Object.entries(e))s!=null&&r.append(o,String(s));let n=`${t}?${r}`;try{let o=await qs(n);if(!o.ok){let i=await o.text();throw new Error(`Worker API error (${o.status}): ${i}`)}let s=await o.json();return y.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),s}catch(o){return y.error("SYSTEM","\u2190 Worker API error",{endpoint:t},o instanceof Error?o:new Error(String(o))),{content:[{type:"text",text:`Error calling Worker API: ${o instanceof Error?o.message:String(o)}`}],isError:!0}}}async function vP(t,e){let r=await qs(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){let o=await r.text();throw new Error(`Worker API error (${r.status}): ${o}`)}let n=await r.json();return y.debug("HTTP","Worker API success (POST)",void 0,{endpoint:t}),{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}async function Dr(t,e){y.debug("HTTP","Worker API request (POST)",void 0,{endpoint:t});try{return await vP(t,e)}catch(r){return y.error("HTTP","Worker API error (POST)",{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 bP(){try{return(await qs("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}function EP(){if(Ru()!=="server-beta")return null;let e=N_();return e?{...e,available:!0}:{runtime:"server-beta",available:!1,reason:"server-beta is selected but configuration is incomplete (missing url, api key, or project id)"}}function Xn(t){return C_(t)?{content:[{type:"text",text:`Server beta 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 Qn(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function eo(t){let e=EP();if(!e)throw new Be("transport",`${t} requires CLAUDE_MEM_RUNTIME=server-beta. Current runtime is "worker"; use the existing search/timeline/get_observations tools for worker-mode memory access.`);if(!e.available)throw new Be("missing_api_key",`${t}: ${e.reason}`);return e}async function j_(t){try{let e=eo("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 Qn(o)}catch(e){return Xn(e)}}async function wP(t){try{let e=eo("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.payload!==void 0?{payload:t.payload}:{},...t.generate!==void 0?{generate:t.generate}:{}},o=await e.client.recordEvent(n);return Qn(o)}catch(e){return Xn(e)}}async function L_(t){try{let e=eo("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}:{}},o=await e.client.searchObservations(n);return Qn(o)}catch(e){return Xn(e)}}async function U_(t){try{let e=eo("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}:{}},o=await e.client.contextObservations(n);return Qn(o)}catch(e){return Xn(e)}}async function kP(t){try{let e=eo("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 Qn(n)}catch(e){return Xn(e)}}async function xP(){if(await bP())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),SP();try{let t=vu(),e=await g_(t,Au);return e==="dead"&&y.error("SYSTEM","Worker auto-start failed \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running. Check earlier log lines for the specific failure reason (Bun not found, missing worker bundle, port conflict, etc.)."),e!=="dead"}catch(t){return y.error("SYSTEM","Worker auto-start threw \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running.",void 0,t instanceof Error?t:new Error(String(t))),!1}}var V_=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
222
+ `)}var Ou=require("node:fs/promises"),Vs=require("node:fs"),tt=require("node:path"),Z_=require("node:os"),F_=require("node:url");var hP=bt(ce.API_REQUEST),Be=class extends Error{kind;status;cause;constructor(e,r,n={}){super(r),this.name="ServerBetaClientError",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)}},Ws=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=gP(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??hP}async startSession(e){let r=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",r)}async recordEvent(e){let r=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(e){if(!e.sessionId)throw new Be("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async getJobStatus(e){if(!e)throw new Be("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,type:n,narrative:r,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{}}}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: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.payload!==void 0?{payload:e.payload}:{}}}async request(e,r,n){if(!this.apiKey||!this.apiKey.trim())throw new Be("missing_api_key","Server beta API key is not configured (CLAUDE_MEM_SERVER_BETA_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 yu(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new Be(l?"timeout":"transport",`Server beta ${e} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new Be("http_error",`Server beta ${e} ${r} returned ${i.status}: ${_P(c,200)}`,{status:i.status})}let a=await i.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(c){throw new Be("invalid_response",`Server beta ${e} ${r} returned non-JSON response`,{cause:c})}}};function C_(t){return t instanceof Be}function gP(t){return t.replace(/\/+$/,"")}function _P(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Ru(){return(Rs().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase()==="server-beta"?"server-beta":"worker"}function N_(){let t=Rs(),e=(t.CLAUDE_MEM_SERVER_BETA_URL??"").trim(),r=(t.CLAUDE_MEM_SERVER_BETA_API_KEY??"").trim(),n=(t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID??"").trim();if(!e)return y.warn("HOOK","[server-beta-fallback] reason=missing_base_url"),null;if(!r)return y.warn("HOOK","[server-beta-fallback] reason=missing_api_key"),null;if(!n)return y.warn("HOOK","[server-beta-fallback] reason=missing_project_id"),null;let o={serverBaseUrl:e,apiKey:r};return{runtime:"server-beta",client:new Ws(o),projectId:n,serverBaseUrl:e}}var OP={},yP="13.8.0";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var H_=!1,W_=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,tt.dirname)((0,F_.fileURLToPath)(OP.url))}catch{return H_=!0,process.cwd()}})(),Au=h_()??(0,tt.resolve)(W_,"worker-service.cjs");function SP(){H_&&((0,Vs.existsSync)(Au)||y.error("SYSTEM","mcp-server: dirname resolution failed (both __dirname and import.meta.url are unavailable). Fell back to process.cwd() and the resolved WORKER_SCRIPT_PATH does not exist. This is the actual problem \u2014 the worker bundle is fine, but mcp-server cannot locate it. Worker auto-start will fail until the dirname-resolution path is fixed.",{workerScriptPath:Au,mcpServerDir:W_}))}var D_={search:"/api/search",timeline:"/api/timeline"};async function Iu(t,e){y.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t,params:e});let r=new URLSearchParams;for(let[o,s]of Object.entries(e))s!=null&&r.append(o,String(s));let n=`${t}?${r}`;try{let o=await qs(n);if(!o.ok){let i=await o.text();throw new Error(`Worker API error (${o.status}): ${i}`)}let s=await o.json();return y.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),s}catch(o){return y.error("SYSTEM","\u2190 Worker API error",{endpoint:t},o instanceof Error?o:new Error(String(o))),{content:[{type:"text",text:`Error calling Worker API: ${o instanceof Error?o.message:String(o)}`}],isError:!0}}}async function vP(t,e){let r=await qs(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){let o=await r.text();throw new Error(`Worker API error (${r.status}): ${o}`)}let n=await r.json();return y.debug("HTTP","Worker API success (POST)",void 0,{endpoint:t}),{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}async function Dr(t,e){y.debug("HTTP","Worker API request (POST)",void 0,{endpoint:t});try{return await vP(t,e)}catch(r){return y.error("HTTP","Worker API error (POST)",{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 bP(){try{return(await qs("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}function EP(){if(Ru()!=="server-beta")return null;let e=N_();return e?{...e,available:!0}:{runtime:"server-beta",available:!1,reason:"server-beta is selected but configuration is incomplete (missing url, api key, or project id)"}}function Xn(t){return C_(t)?{content:[{type:"text",text:`Server beta 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 Qn(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function eo(t){let e=EP();if(!e)throw new Be("transport",`${t} requires CLAUDE_MEM_RUNTIME=server-beta. Current runtime is "worker"; use the existing search/timeline/get_observations tools for worker-mode memory access.`);if(!e.available)throw new Be("missing_api_key",`${t}: ${e.reason}`);return e}async function j_(t){try{let e=eo("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 Qn(o)}catch(e){return Xn(e)}}async function wP(t){try{let e=eo("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.payload!==void 0?{payload:t.payload}:{},...t.generate!==void 0?{generate:t.generate}:{}},o=await e.client.recordEvent(n);return Qn(o)}catch(e){return Xn(e)}}async function L_(t){try{let e=eo("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}:{}},o=await e.client.searchObservations(n);return Qn(o)}catch(e){return Xn(e)}}async function U_(t){try{let e=eo("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}:{}},o=await e.client.contextObservations(n);return Qn(o)}catch(e){return Xn(e)}}async function kP(t){try{let e=eo("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 Qn(n)}catch(e){return Xn(e)}}async function xP(){if(await bP())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),SP();try{let t=vu(),e=await g_(t,Au);return e==="dead"&&y.error("SYSTEM","Worker auto-start failed \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running. Check earlier log lines for the specific failure reason (Bun not found, missing worker bundle, port conflict, etc.)."),e!=="dead"}catch(t){return y.error("SYSTEM","Worker auto-start threw \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running.",void 0,t instanceof Error?t:new Error(String(t))),!1}}var V_=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
223
223
  1. search(query) \u2192 Get index with IDs (~50-100 tokens/result)
224
224
  2. timeline(anchor=ID) \u2192 Get context around interesting results
225
225
  3. get_observations([IDs]) \u2192 Fetch full details ONLY for filtered IDs
@@ -59,7 +59,7 @@ ${s.stack}`:` ${s.message}`;else if(this.getLevel()===0&&typeof s=="object")try{
59
59
  `,"utf8")}catch(f){dy(`[LOGGER] Failed to write to log file: ${f instanceof Error?f.message:String(f)}
60
60
  `)}else dy(p+`
61
61
  `)}debug(e,t,n,i){this.log(0,e,t,n,i)}info(e,t,n,i){this.log(1,e,t,n,i)}warn(e,t,n,i){this.log(2,e,t,n,i)}setErrorSink(e){py=e}error(e,t,n,i){this.log(3,e,t,n,i),this.routeErrorToSink(t,n,i)}routeErrorToSink(e,t,n){try{if(!py||!(n instanceof Error))return;py(n)}catch{}}dataIn(e,t,n,i){this.info(e,`\u2192 ${t}`,n,i)}dataOut(e,t,n,i){this.info(e,`\u2190 ${t}`,n,i)}success(e,t,n,i){this.info(e,`\u2713 ${t}`,n,i)}failure(e,t,n,i){this.error(e,`\u2717 ${t}`,n,i)}happyPathError(e,t,n,i,s=""){let l=((new Error().stack||"").split(`
62
- `)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),u=l?`${l[1].split("/").pop()}:${l[2]}`:"unknown",d={...n,location:u};return this.warn(e,`[HAPPY-PATH] ${t}`,d,i),s}},_=new my});var $k=h((Lue,Bk)=>{"use strict";var Gk=Object.getOwnPropertySymbols,Z9=Object.prototype.hasOwnProperty,e$=Object.prototype.propertyIsEnumerable;function t$(r){if(r==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(r)}function r$(){try{if(!Object.assign)return!1;var r=new String("abc");if(r[5]="de",Object.getOwnPropertyNames(r)[0]==="5")return!1;for(var e={},t=0;t<10;t++)e["_"+String.fromCharCode(t)]=t;var n=Object.getOwnPropertyNames(e).map(function(s){return e[s]});if(n.join("")!=="0123456789")return!1;var i={};return"abcdefghijklmnopqrst".split("").forEach(function(s){i[s]=s}),Object.keys(Object.assign({},i)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}Bk.exports=r$()?Object.assign:function(r,e){for(var t,n=t$(r),i,s=1;s<arguments.length;s++){t=Object(arguments[s]);for(var a in t)Z9.call(t,a)&&(n[a]=t[a]);if(Gk){i=Gk(t);for(var o=0;o<i.length;o++)e$.call(t,i[o])&&(n[i[o]]=t[i[o]])}}return n}});var Hk=h((que,Vk)=>{(function(){"use strict";var r=$k(),e=iy(),t={origin:"*",methods:"GET,HEAD,PUT,PATCH,POST,DELETE",preflightContinue:!1,optionsSuccessStatus:204};function n(m){return typeof m=="string"||m instanceof String}function i(m,y){if(Array.isArray(y)){for(var b=0;b<y.length;++b)if(i(m,y[b]))return!0;return!1}else return n(y)?m===y:y instanceof RegExp?y.test(m):!!y}function s(m,y){var b=y.headers.origin,g=[],E;return!m.origin||m.origin==="*"?g.push([{key:"Access-Control-Allow-Origin",value:"*"}]):n(m.origin)?(g.push([{key:"Access-Control-Allow-Origin",value:m.origin}]),g.push([{key:"Vary",value:"Origin"}])):(E=i(b,m.origin),g.push([{key:"Access-Control-Allow-Origin",value:E?b:!1}]),g.push([{key:"Vary",value:"Origin"}])),g}function a(m){var y=m.methods;return y.join&&(y=m.methods.join(",")),{key:"Access-Control-Allow-Methods",value:y}}function o(m){return m.credentials===!0?{key:"Access-Control-Allow-Credentials",value:"true"}:null}function c(m,y){var b=m.allowedHeaders||m.headers,g=[];return b?b.join&&(b=b.join(",")):(b=y.headers["access-control-request-headers"],g.push([{key:"Vary",value:"Access-Control-Request-Headers"}])),b&&b.length&&g.push([{key:"Access-Control-Allow-Headers",value:b}]),g}function l(m){var y=m.exposedHeaders;if(y)y.join&&(y=y.join(","));else return null;return y&&y.length?{key:"Access-Control-Expose-Headers",value:y}:null}function u(m){var y=(typeof m.maxAge=="number"||m.maxAge)&&m.maxAge.toString();return y&&y.length?{key:"Access-Control-Max-Age",value:y}:null}function d(m,y){for(var b=0,g=m.length;b<g;b++){var E=m[b];E&&(Array.isArray(E)?d(E,y):E.key==="Vary"&&E.value?e(y,E.value):E.value&&y.setHeader(E.key,E.value))}}function p(m,y,b,g){var E=[],I=y.method&&y.method.toUpperCase&&y.method.toUpperCase();I==="OPTIONS"?(E.push(s(m,y)),E.push(o(m)),E.push(a(m)),E.push(c(m,y)),E.push(u(m)),E.push(l(m)),d(E,b),m.preflightContinue?g():(b.statusCode=m.optionsSuccessStatus,b.setHeader("Content-Length","0"),b.end())):(E.push(s(m,y)),E.push(o(m)),E.push(l(m)),d(E,b),g())}function f(m){var y=null;return typeof m=="function"?y=m:y=function(b,g){g(null,m)},function(g,E,I){y(g,function(k,N){if(k)I(k);else{var J=r({},t,N),re=null;J.origin&&typeof J.origin=="function"?re=J.origin:J.origin&&(re=function(je,se){se(null,J.origin)}),re?re(g.headers.origin,function(je,se){je||!se?I(je):(J.origin=se,p(J,g,E,I))}):I()}})}}Vk.exports=f})()});function Wk(r,e={}){let t=[];e.includeCors!==!1&&t.push(yy()),t.push(hy.default.json({limit:"5mb"})),t.push((s,a,o)=>{let l=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(y=>s.path.endsWith(y)),u=s.path==="/api/logs";if(s.path.startsWith("/health")||s.path==="/"||l||u)return o();let d=Date.now(),p=`${s.method}-${Date.now()}`,f=r(s.method,s.path,s.body);_.debug("HTTP",`\u2192 ${s.method} ${s.path}`,{requestId:p},f);let m=a.send.bind(a);a.send=function(y){let b=Date.now()-d;return _.debug("HTTP",`\u2190 ${a.statusCode} ${s.path}`,{requestId:p,duration:`${b}ms`}),m(y)},o()});let n=ji(),i=Yk.default.join(n,"plugin","ui");return t.push(hy.default.static(i)),t}function yy(){return(0,zk.default)({origin:(r,e)=>{!r||r.startsWith("http://localhost:")||r.startsWith("http://127.0.0.1:")?e(null,!0):e(new Error("CORS not allowed"))},methods:["GET","HEAD","POST","PUT","PATCH","DELETE"],allowedHeaders:["Content-Type","Authorization","X-Requested-With"],credentials:!1})}function Dl(r,e,t){let n=r.ip||r.connection.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){_.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:r.path,clientIp:n,method:r.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}t()}function Qk(r,e,t){if(!t||Object.keys(t).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=t.tool_name||"?",i=t.tool_input;return`tool=${_.formatTool(n,i)}`}return e.includes("/summarize")?"requesting summary":""}var hy,zk,Yk,Xk=M(()=>{"use strict";hy=ct(Rl(),1),zk=ct(Hk(),1),Yk=ct(require("path"),1);Jr();ge()});function Zk(r,e,t,n){let i={error:r,message:e};return t&&(i.code=t),n&&(i.details=n),i}function tT(r,e){e.status(404).json(Zk("NotFound",`Cannot ${r.method} ${r.path}`))}var js,eT,rT=M(()=>{"use strict";ge();js=class extends Error{constructor(t,n=500,i,s){super(t);this.statusCode=n;this.code=i;this.details=s;this.name="AppError"}statusCode;code;details};eT=(r,e,t,n)=>{let i=r instanceof js?r.statusCode:500;_.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:r.message,code:r instanceof js?r.code:void 0},r);let s=Zk(r.name||"Error",r.message,r instanceof js?r.code:void 0,r instanceof js?r.details:void 0);t.status(i).json(s)}});var nT=M(()=>{"use strict"});function oo(r=process.env){let e={};for(let[t,n]of Object.entries(r))if(n!==void 0){if(n$.has(t)){e[t]=n;continue}gy.has(t)||by.some(i=>t.startsWith(i))||(e[t]=n)}return e}var by,gy,n$,Pl=M(()=>{"use strict";by=["CLAUDECODE_","CLAUDE_CODE_"],gy=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID","HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy"]),n$=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","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"])});function Ir(r){if(!Number.isInteger(r)||r<0||r===0)return!1;try{return process.kill(r,0),!0}catch(e){if(e instanceof Error){let t=e.code;return t==="EPERM"?!0:(_.debug("SYSTEM","PID check failed",{pid:r,code:t}),!1)}return _.warn("SYSTEM","PID check threw non-Error",{pid:r,error:String(e)}),!1}}async function Ml(r,e){let t=Date.now()+e;for(;Date.now()<t;){if(r.every(n=>!Ir(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function c$(r){let e=iT.get(r);if(e&&Date.now()-e.capturedAtMs<o$)return e.token;let t=null;try{let n=(0,wy.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${r}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...oo(process.env),LC_ALL:"C",LANG:"C"}});if(n.status===0){let i=n.stdout.trim();t=i.length>0?i:null}}catch(n){_.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:r,error:n instanceof Error?n.message:String(n)}),t=null}return iT.set(r,{token:t,capturedAtMs:Date.now()}),t}function Iy(r){if(!Number.isInteger(r)||r<=0)return null;if(process.platform==="linux")try{let e=(0,Ur.readFileSync)(`/proc/${r}/stat`,"utf-8"),t=e.lastIndexOf(") ");if(t<0)return null;let i=e.slice(t+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(e){return _.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return c$(r);try{let e=(0,wy.spawnSync)("ps",["-p",String(r),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...oo(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let t=e.stdout.trim();return t.length>0?t:null}catch(e){return _.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}}function Ln(r){if(!r||!Ir(r.pid))return!1;if(!r.startToken)return!0;let e=Iy(r.pid);if(e===null)return!0;let t=e===r.startToken;return t||_.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:r.pid,stored:r.startToken,current:e}),t}function Nl(){return vy||(vy=new Sy),vy}function Ey(){let r=l$.shift();r&&r()}var wy,Ur,xy,i$,s$,a$,o$,iT,Sy,vy,l$,Rs=M(()=>{"use strict";wy=require("child_process");nT();Ur=require("fs"),xy=ct(require("path"),1);ge();Pl();Jr();i$=5e3,s$=1e3,a$=$e.supervisorRegistry();o$=5e3,iT=new Map;Sy=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=a$){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,Ur.mkdirSync)(xy.default.dirname(this.registryPath),{recursive:!0}),!(0,Ur.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Ur.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[i,s]of Object.entries(n))this.entries.set(i,s)}catch(t){t instanceof Error?_.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},t):_.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(t)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&_.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,t,n){this.initialize(),this.entries.set(e,t),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let t=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),t?.type==="sdk"&&Ey()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,t])=>({id:e,...t})).sort((e,t)=>{let n=Date.parse(e.startedAt),i=Date.parse(t.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(i)?0:i)})}getBySession(e){let t=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===t)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}getByPid(e){return this.getAll().filter(t=>t.pid===e)}pruneDeadEntries(){this.initialize();let e=0,t=0;for(let[n,i]of this.entries)Ir(i.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,i.type==="sdk"&&(t+=1));e>0&&this.persist();for(let n=0;n<t;n+=1)Ey();return e}async reapSession(e){this.initialize();let t=this.getBySession(e);if(t.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;_.info("SYSTEM",`Reaping ${t.length} process(es) for session ${e}`,{sessionId:n,pids:t.map(a=>a.pid)});let i=t.filter(a=>Ir(a.pid));for(let a of i)try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(o){o instanceof Error?o.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},o):_.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(o)})}await Ml(i,i$);let s=i.filter(a=>Ir(a.pid));for(let a of s){_.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(o){o instanceof Error?o.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},o):_.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(o)})}}if(s.length>0){let a=Date.now()+s$;for(;Date.now()<a&&s.filter(c=>Ir(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100))}for(let a of t)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of t)a.type==="sdk"&&Ey();return _.info("SYSTEM",`Reaped ${t.length} process(es) for session ${e}`,{sessionId:n,reaped:t.length}),t.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,Ur.mkdirSync)(xy.default.dirname(this.registryPath),{recursive:!0}),(0,Ur.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},vy=null;l$=[]});function sT(r){return process.platform==="win32"?Math.round(r*co.WINDOWS_MULTIPLIER):r}var co,_y=M(()=>{"use strict";co={DEFAULT:3e5,HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,WORKER_STARTUP_WAIT:1e3,PRE_RESTART_SETTLE_DELAY:2e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5}});async function lT(r){let e=r.currentPid??process.pid,t=r.pidFilePath??d$,n=r.registry.getAll(),i=[...n].filter(a=>a.pid!==e).sort((a,o)=>Date.parse(o.startedAt)-Date.parse(a.startedAt));for(let a of i){if(!Ir(a.pid)){r.registry.unregister(a.id);continue}try{await aT(a,"SIGTERM")}catch(o){o instanceof Error?_.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:a.pid,pgid:a.pgid,type:a.type},o):_.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:a.pid,pgid:a.pgid,type:a.type,error:String(o)})}}await Ml(i,5e3);let s=i.filter(a=>Ir(a.pid));for(let a of s)try{await aT(a,"SIGKILL")}catch(o){o instanceof Error?_.debug("SYSTEM","Failed to force kill child process",{pid:a.pid,pgid:a.pgid,type:a.type},o):_.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:a.pid,pgid:a.pgid,type:a.type,error:String(o)})}await Ml(s,1e3);for(let a of i)r.registry.unregister(a.id);for(let a of n.filter(o=>o.pid===e))r.registry.unregister(a.id);p$(t,e),r.registry.pruneDeadEntries()}function p$(r,e){if(!(0,Cs.existsSync)(r))return;let t=null;try{let n=JSON.parse((0,Cs.readFileSync)(r,"utf-8"));t=typeof n.pid=="number"?n.pid:null}catch(n){_.debug("SYSTEM","PID file unreadable during shutdown \u2014 leaving it (cannot prove ownership)",{pidFilePath:r,error:n instanceof Error?n.message:String(n)});return}if(t!==e){_.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:r,recordedPid:t,currentPid:e});return}try{(0,Cs.rmSync)(r,{force:!0})}catch(n){n instanceof Error?_.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:r},n):_.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:r,error:String(n)})}}async function aT(r,e){let{pid:t,pgid:n}=r;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(a){if((a instanceof Error?a.code:void 0)!=="ESRCH")throw a}try{process.kill(t,e)}catch(a){if((a instanceof Error?a.code:void 0)!=="ESRCH")throw a}return}if(e==="SIGTERM"){try{process.kill(t,e)}catch(a){if(a instanceof Error&&a.code==="ESRCH")return;throw a}return}let i=await f$();if(i){await new Promise((a,o)=>{i(t,e,c=>{if(!c){a();return}if(c.code==="ESRCH"){a();return}o(c)})});return}let s=["/PID",String(t),"/T"];e==="SIGKILL"&&s.push("/F"),await u$("taskkill",s,{timeout:co.POWERSHELL_COMMAND,windowsHide:!0})}async function f$(){let r="tree-kill";try{let e=await import(r);return e.default??e}catch(e){return _.debug("SYSTEM","tree-kill module not available, using fallback",{},e instanceof Error?e:void 0),null}}var oT,Cs,cT,u$,d$,uT=M(()=>{"use strict";oT=require("child_process"),Cs=require("fs"),cT=require("util");ge();_y();Rs();Jr();u$=(0,cT.promisify)(oT.execFile),d$=$e.workerPid()});function m$(){let e=Nl().pruneDeadEntries();e>0&&_.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function pT(){Ds===null&&(Ds=setInterval(m$,dT),Ds.unref(),_.debug("SYSTEM","Health checker started",{intervalMs:dT}))}function fT(){Ds!==null&&(clearInterval(Ds),Ds=null,_.debug("SYSTEM","Health checker stopped"))}var dT,Ds,mT=M(()=>{"use strict";ge();Rs();dT=3e4,Ds=null});function hT(){return y$}function b$(r={}){let e=r.pidFilePath??h$;if(!(0,Ri.existsSync)(e))return"missing";let t=null;try{t=JSON.parse((0,Ri.readFileSync)(e,"utf-8"))}catch(i){return i instanceof Error?_.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},i):_.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(i)}),(0,Ri.rmSync)(e,{force:!0}),"invalid"}return Ln(t)&&t?((r.logAlive??!0)&&_.info("SYSTEM","Worker already running (PID alive)",{existingPid:t.pid,existingPort:t.port,startedAt:t.startedAt}),"alive"):(_.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:t?.pid,port:t?.port,startedAt:t?.startedAt}),(0,Ri.rmSync)(e,{force:!0}),"stale")}var Ri,h$,ky,y$,yT=M(()=>{"use strict";Ri=require("fs");ge();Rs();uT();mT();Jr();h$=$e.workerPid(),ky=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(),b$({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,pT()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let t=async n=>{if(this.shutdownInitiated){_.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,_.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){i instanceof Error?_.error("SYSTEM","Error during shutdown",{},i):_.error("SYSTEM","Error during shutdown (non-Error)",{error:String(i)});try{await this.stop()}catch(s){s instanceof Error?_.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):_.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(s)})}}process.exit(0)};process.on("SIGTERM",()=>{t("SIGTERM")}),process.on("SIGINT",()=>{t("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{_.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{t("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}fT(),this.stopPromise=lT({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,t,n){this.registry.register(e,t,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},y$=new ky(Nl())});function Ty(r,e,t){r.on("finish",async()=>{try{await t()}finally{process.exit(0)}}),r.json(e)}var bT=M(()=>{"use strict"});function Ay(r,e=Date.now){return Math.max(0,Math.floor((e()-r)/1e3))}var gT=M(()=>{"use strict"});var Ky,vT,xde,ET=M(()=>{"use strict";Ky=class{entries=new Map;set(e){if(!e||typeof e!="object")return;let t=e.rateLimitType??"default";this.entries.set(t,{...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}},vT=new Ky,xde=900*1e3});function E$(r){r.setHeader("X-Content-Type-Options","nosniff"),r.setHeader("X-Frame-Options","DENY"),r.setHeader("X-DNS-Prefetch-Control","off"),r.setHeader("Referrer-Policy","no-referrer"),r.setHeader("Cross-Origin-Opener-Policy","same-origin"),r.setHeader("Cross-Origin-Resource-Policy","same-origin"),r.setHeader("Origin-Agent-Cluster","?1"),r.removeHeader("X-Powered-By")}var wT,IT,jy,lo,_T,g$,Oy,xT,v$,ST,Ll,kT=M(()=>{"use strict";wT=ct(Rl(),1),IT=ct(require("http"),1),jy=ct(require("fs"),1),lo=ct(require("path"),1);Lk();ge();Xk();rT();yT();Rs();Pl();bT();gT();ET();_T=lo.default.resolve(__dirname,"../skills/mem-search"),g$=lo.default.join(_T,"operations"),Oy=lo.default.join(_T,"SKILL.md"),xT=(()=>{try{let r=jy.readFileSync(Oy,"utf-8");return _.info("SYSTEM","Cached SKILL.md at boot",{path:Oy,bytes:Buffer.byteLength(r,"utf-8")}),r}catch(r){return _.debug("SYSTEM","SKILL.md not present at boot, /api/instructions will 404 for topic queries",{path:Oy,message:r instanceof Error?r.message:String(r)}),null}})(),v$=(()=>{let r=new Map;for(let e of cy){let t=lo.default.join(g$,`${e}.md`);try{r.set(e,jy.readFileSync(t,"utf-8"))}catch(n){_.debug("SYSTEM","Operation instruction file not present at boot",{path:t,message:n instanceof Error?n.message:String(n)})}}return r.size>0&&_.info("SYSTEM","Cached operation instruction files at boot",{count:r.size,operations:Array.from(r.keys())}),r})(),ST="13.7.1";Ll=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,wT.default)(),this.app.disable("x-powered-by"),this.setupSecurityHeaders(),this.setupCors(),this.setupPreBodyParserRoutes(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,t){return new Promise((n,i)=>{let s=IT.default.createServer(this.app);this.server=s;let a=c=>{s.off("listening",o),i(c)},o=()=>{s.off("error",a),_.info("SYSTEM","HTTP server started",{host:t,port:e,pid:process.pid}),n()};s.once("error",a),s.once("listening",o),s.listen(e,t)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,t)=>{this.server.close(n=>n?t(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,_.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(tT),this.app.use(eT)}setupMiddleware(){Wk(Qk,{includeCors:!1}).forEach(t=>this.app.use(t))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,t,n)=>{E$(t),n()})}setupCors(){this.app.use(yy())}setupPreBodyParserRoutes(){this.options.preBodyParserRoutes?.forEach(e=>e.setupRoutes(this.app))}setupCoreRoutes(){this.app.get("/api/health",async(e,t)=>{let n=this.options.getQueueHealth?await this.options.getQueueHealth():null,i=n?.engine==="bullmq"&&n.redis.status==="error";t.status(i?503:200).json({status:i?"degraded":"ok",...this.options.runtime?{runtime:this.options.runtime}:{},version:ST,workerPath:this.options.workerPath,uptime:Ay(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(),rateLimits:vT.getMostRecentByWindow(),...n?{queue:n}:{}})}),this.app.get("/api/readiness",(e,t)=>{this.options.getInitializationComplete()?t.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):t.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(e,t)=>{t.status(200).json({version:ST})}),this.app.get("/api/instructions",(e,t)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!Nk.includes(n))return t.status(400).json({error:"Invalid topic"});if(i&&!cy.includes(i))return t.status(400).json({error:"Invalid operation"});if(i){let a=v$.get(i);return a===void 0?(_.debug("HTTP","Instruction file not cached at boot",{operation:i}),t.status(404).json({error:"Instruction not found"})):t.json({content:[{type:"text",text:a}]})}if(xT===null)return _.debug("HTTP","SKILL.md not cached at boot",{topic:n}),t.status(404).json({error:"Instruction not found"});let s=this.extractInstructionSection(xT,n);t.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",Dl,async(e,t)=>{process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(t.json({status:"restarting"}),_.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):Ty(t,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",Dl,async(e,t)=>{let n=e.query.reason==="restart"?"restart":"stop";process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(t.json({status:"shutting_down"}),_.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown",reason:n})):Ty(t,{status:"shutting_down"},()=>this.options.onShutdown(n))}),this.app.get("/api/admin/doctor",Dl,(e,t)=>{let a=hT().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:Ir(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=>gy.has(f)||by.some(m=>f.startsWith(m))),l=Ay(this.startTime),u=Math.floor(l/3600),d=Math.floor(l%3600/60),p=u>0?`${u}h ${d}m`:`${d}m`;t.json({supervisor:{running:!0,pid:process.pid,uptime:p},processes:a,health:{deadProcessPids:o,envClean:c}})})}extractInstructionSection(e,t){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[t]||n.all}extractBetween(e,t,n){let i=e.indexOf(t),s=e.indexOf(n);return i===-1?e:s===-1?e.substring(i):e.substring(i,s).trim()}}});var Jt,x$,S$,Ry,TT=M(()=>{"use strict";Jt=require("zod"),x$=Jt.z.enum(["hook","worker","provider","server","api"]),S$=Jt.z.object({id:Jt.z.string().min(1),projectId:Jt.z.string().min(1),serverSessionId:Jt.z.string().min(1).nullable().default(null),sourceType:x$,eventType:Jt.z.string().min(1),platformSource:Jt.z.string().min(1).nullable().default(null),payload:Jt.z.unknown().default({}),contentSessionId:Jt.z.string().min(1).nullable().default(null),memorySessionId:Jt.z.string().min(1).nullable().default(null),occurredAtEpoch:Jt.z.number().int().nonnegative(),createdAtEpoch:Jt.z.number().int().nonnegative()}),Ry=S$.omit({id:!0,createdAtEpoch:!0}).partial({serverSessionId:!0,platformSource:!0,payload:!0,contentSessionId:!0,memorySessionId:!0})});function qe(){return(0,ql.randomUUID)()}function ze(r){return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}function AT(r){return Array.isArray(r)?r:[]}function ve(r){return typeof r=="number"?r:new Date(r).getTime()}function or(r){return r==null?null:r instanceof Date?r:new Date(r)}async function W(r,e,t=[]){return(await r.query(e,t)).rows[0]??null}async function _r(r,e,t){if(!await W(r,"SELECT id FROM projects WHERE id = $1 AND team_id = $2",[e,t]))throw new Error("project_id must belong to team_id")}async function pn(r,e,t,n){if(!await W(r,"SELECT id FROM server_sessions WHERE id = $1 AND project_id = $2 AND team_id = $3",[e,t,n]))throw new Error("server_session_id must belong to project_id and team_id")}function uo(r){return JSON.stringify(Cy(r))}function kr(r){return(0,ql.createHash)("sha256").update(uo(r)).digest("hex")}function Cy(r){if(Array.isArray(r))return r.map(Cy);if(r&&typeof r=="object"){let e=r;return Object.keys(e).sort().reduce((t,n)=>(t[n]=Cy(e[n]),t),{})}return r}var ql,Gr=M(()=>{"use strict";ql=require("crypto")});function KT(r){return r.sourceEventId?`agent_event:v1:${kr([r.teamId,r.projectId,r.sourceAdapter,r.sourceEventId])}`:`agent_event:v1:${kr([r.teamId,r.projectId,r.sourceAdapter,r.contentSessionId??r.serverSessionId??null,r.eventType,new Date(r.occurredAt).toISOString(),uo(r.payload??{})])}`}function Dy(r){return{id:r.id,projectId:r.project_id,teamId:r.team_id,serverSessionId:r.server_session_id,sourceAdapter:r.source_adapter,sourceEventId:r.source_event_id,idempotencyKey:r.idempotency_key,eventType:r.event_type,platformSource:r.platform_source,payload:r.payload,metadata:ze(r.metadata),occurredAtEpoch:ve(r.occurred_at),receivedAtEpoch:ve(r.received_at),createdAtEpoch:ve(r.created_at)}}var cr,Ps=M(()=>{"use strict";Gr();cr=class{constructor(e){this.client=e}client;async create(e){await _r(this.client,e.projectId,e.teamId),e.serverSessionId&&await pn(this.client,e.serverSessionId,e.projectId,e.teamId);let t=KT(e),n=await W(this.client,`
62
+ `)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),u=l?`${l[1].split("/").pop()}:${l[2]}`:"unknown",d={...n,location:u};return this.warn(e,`[HAPPY-PATH] ${t}`,d,i),s}},_=new my});var $k=h((Lue,Bk)=>{"use strict";var Gk=Object.getOwnPropertySymbols,Z9=Object.prototype.hasOwnProperty,e$=Object.prototype.propertyIsEnumerable;function t$(r){if(r==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(r)}function r$(){try{if(!Object.assign)return!1;var r=new String("abc");if(r[5]="de",Object.getOwnPropertyNames(r)[0]==="5")return!1;for(var e={},t=0;t<10;t++)e["_"+String.fromCharCode(t)]=t;var n=Object.getOwnPropertyNames(e).map(function(s){return e[s]});if(n.join("")!=="0123456789")return!1;var i={};return"abcdefghijklmnopqrst".split("").forEach(function(s){i[s]=s}),Object.keys(Object.assign({},i)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}Bk.exports=r$()?Object.assign:function(r,e){for(var t,n=t$(r),i,s=1;s<arguments.length;s++){t=Object(arguments[s]);for(var a in t)Z9.call(t,a)&&(n[a]=t[a]);if(Gk){i=Gk(t);for(var o=0;o<i.length;o++)e$.call(t,i[o])&&(n[i[o]]=t[i[o]])}}return n}});var Hk=h((que,Vk)=>{(function(){"use strict";var r=$k(),e=iy(),t={origin:"*",methods:"GET,HEAD,PUT,PATCH,POST,DELETE",preflightContinue:!1,optionsSuccessStatus:204};function n(m){return typeof m=="string"||m instanceof String}function i(m,y){if(Array.isArray(y)){for(var b=0;b<y.length;++b)if(i(m,y[b]))return!0;return!1}else return n(y)?m===y:y instanceof RegExp?y.test(m):!!y}function s(m,y){var b=y.headers.origin,g=[],E;return!m.origin||m.origin==="*"?g.push([{key:"Access-Control-Allow-Origin",value:"*"}]):n(m.origin)?(g.push([{key:"Access-Control-Allow-Origin",value:m.origin}]),g.push([{key:"Vary",value:"Origin"}])):(E=i(b,m.origin),g.push([{key:"Access-Control-Allow-Origin",value:E?b:!1}]),g.push([{key:"Vary",value:"Origin"}])),g}function a(m){var y=m.methods;return y.join&&(y=m.methods.join(",")),{key:"Access-Control-Allow-Methods",value:y}}function o(m){return m.credentials===!0?{key:"Access-Control-Allow-Credentials",value:"true"}:null}function c(m,y){var b=m.allowedHeaders||m.headers,g=[];return b?b.join&&(b=b.join(",")):(b=y.headers["access-control-request-headers"],g.push([{key:"Vary",value:"Access-Control-Request-Headers"}])),b&&b.length&&g.push([{key:"Access-Control-Allow-Headers",value:b}]),g}function l(m){var y=m.exposedHeaders;if(y)y.join&&(y=y.join(","));else return null;return y&&y.length?{key:"Access-Control-Expose-Headers",value:y}:null}function u(m){var y=(typeof m.maxAge=="number"||m.maxAge)&&m.maxAge.toString();return y&&y.length?{key:"Access-Control-Max-Age",value:y}:null}function d(m,y){for(var b=0,g=m.length;b<g;b++){var E=m[b];E&&(Array.isArray(E)?d(E,y):E.key==="Vary"&&E.value?e(y,E.value):E.value&&y.setHeader(E.key,E.value))}}function p(m,y,b,g){var E=[],I=y.method&&y.method.toUpperCase&&y.method.toUpperCase();I==="OPTIONS"?(E.push(s(m,y)),E.push(o(m)),E.push(a(m)),E.push(c(m,y)),E.push(u(m)),E.push(l(m)),d(E,b),m.preflightContinue?g():(b.statusCode=m.optionsSuccessStatus,b.setHeader("Content-Length","0"),b.end())):(E.push(s(m,y)),E.push(o(m)),E.push(l(m)),d(E,b),g())}function f(m){var y=null;return typeof m=="function"?y=m:y=function(b,g){g(null,m)},function(g,E,I){y(g,function(k,N){if(k)I(k);else{var J=r({},t,N),re=null;J.origin&&typeof J.origin=="function"?re=J.origin:J.origin&&(re=function(je,se){se(null,J.origin)}),re?re(g.headers.origin,function(je,se){je||!se?I(je):(J.origin=se,p(J,g,E,I))}):I()}})}}Vk.exports=f})()});function Wk(r,e={}){let t=[];e.includeCors!==!1&&t.push(yy()),t.push(hy.default.json({limit:"5mb"})),t.push((s,a,o)=>{let l=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(y=>s.path.endsWith(y)),u=s.path==="/api/logs";if(s.path.startsWith("/health")||s.path==="/"||l||u)return o();let d=Date.now(),p=`${s.method}-${Date.now()}`,f=r(s.method,s.path,s.body);_.debug("HTTP",`\u2192 ${s.method} ${s.path}`,{requestId:p},f);let m=a.send.bind(a);a.send=function(y){let b=Date.now()-d;return _.debug("HTTP",`\u2190 ${a.statusCode} ${s.path}`,{requestId:p,duration:`${b}ms`}),m(y)},o()});let n=ji(),i=Yk.default.join(n,"plugin","ui");return t.push(hy.default.static(i)),t}function yy(){return(0,zk.default)({origin:(r,e)=>{!r||r.startsWith("http://localhost:")||r.startsWith("http://127.0.0.1:")?e(null,!0):e(new Error("CORS not allowed"))},methods:["GET","HEAD","POST","PUT","PATCH","DELETE"],allowedHeaders:["Content-Type","Authorization","X-Requested-With"],credentials:!1})}function Dl(r,e,t){let n=r.ip||r.connection.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){_.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:r.path,clientIp:n,method:r.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}t()}function Qk(r,e,t){if(!t||Object.keys(t).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=t.tool_name||"?",i=t.tool_input;return`tool=${_.formatTool(n,i)}`}return e.includes("/summarize")?"requesting summary":""}var hy,zk,Yk,Xk=M(()=>{"use strict";hy=ct(Rl(),1),zk=ct(Hk(),1),Yk=ct(require("path"),1);Jr();ge()});function Zk(r,e,t,n){let i={error:r,message:e};return t&&(i.code=t),n&&(i.details=n),i}function tT(r,e){e.status(404).json(Zk("NotFound",`Cannot ${r.method} ${r.path}`))}var js,eT,rT=M(()=>{"use strict";ge();js=class extends Error{constructor(t,n=500,i,s){super(t);this.statusCode=n;this.code=i;this.details=s;this.name="AppError"}statusCode;code;details};eT=(r,e,t,n)=>{let i=r instanceof js?r.statusCode:500;_.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:r.message,code:r instanceof js?r.code:void 0},r);let s=Zk(r.name||"Error",r.message,r instanceof js?r.code:void 0,r instanceof js?r.details:void 0);t.status(i).json(s)}});var nT=M(()=>{"use strict"});function oo(r=process.env){let e={};for(let[t,n]of Object.entries(r))if(n!==void 0){if(n$.has(t)){e[t]=n;continue}gy.has(t)||by.some(i=>t.startsWith(i))||(e[t]=n)}return e}var by,gy,n$,Pl=M(()=>{"use strict";by=["CLAUDECODE_","CLAUDE_CODE_"],gy=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID","HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy"]),n$=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","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"])});function Ir(r){if(!Number.isInteger(r)||r<0||r===0)return!1;try{return process.kill(r,0),!0}catch(e){if(e instanceof Error){let t=e.code;return t==="EPERM"?!0:(_.debug("SYSTEM","PID check failed",{pid:r,code:t}),!1)}return _.warn("SYSTEM","PID check threw non-Error",{pid:r,error:String(e)}),!1}}async function Ml(r,e){let t=Date.now()+e;for(;Date.now()<t;){if(r.every(n=>!Ir(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function c$(r){let e=iT.get(r);if(e&&Date.now()-e.capturedAtMs<o$)return e.token;let t=null;try{let n=(0,wy.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${r}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...oo(process.env),LC_ALL:"C",LANG:"C"}});if(n.status===0){let i=n.stdout.trim();t=i.length>0?i:null}}catch(n){_.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:r,error:n instanceof Error?n.message:String(n)}),t=null}return iT.set(r,{token:t,capturedAtMs:Date.now()}),t}function Iy(r){if(!Number.isInteger(r)||r<=0)return null;if(process.platform==="linux")try{let e=(0,Ur.readFileSync)(`/proc/${r}/stat`,"utf-8"),t=e.lastIndexOf(") ");if(t<0)return null;let i=e.slice(t+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(e){return _.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return c$(r);try{let e=(0,wy.spawnSync)("ps",["-p",String(r),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...oo(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let t=e.stdout.trim();return t.length>0?t:null}catch(e){return _.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}}function Ln(r){if(!r||!Ir(r.pid))return!1;if(!r.startToken)return!0;let e=Iy(r.pid);if(e===null)return!0;let t=e===r.startToken;return t||_.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:r.pid,stored:r.startToken,current:e}),t}function Nl(){return vy||(vy=new Sy),vy}function Ey(){let r=l$.shift();r&&r()}var wy,Ur,xy,i$,s$,a$,o$,iT,Sy,vy,l$,Rs=M(()=>{"use strict";wy=require("child_process");nT();Ur=require("fs"),xy=ct(require("path"),1);ge();Pl();Jr();i$=5e3,s$=1e3,a$=$e.supervisorRegistry();o$=5e3,iT=new Map;Sy=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=a$){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,Ur.mkdirSync)(xy.default.dirname(this.registryPath),{recursive:!0}),!(0,Ur.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Ur.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[i,s]of Object.entries(n))this.entries.set(i,s)}catch(t){t instanceof Error?_.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},t):_.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(t)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&_.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,t,n){this.initialize(),this.entries.set(e,t),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let t=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),t?.type==="sdk"&&Ey()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,t])=>({id:e,...t})).sort((e,t)=>{let n=Date.parse(e.startedAt),i=Date.parse(t.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(i)?0:i)})}getBySession(e){let t=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===t)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}getByPid(e){return this.getAll().filter(t=>t.pid===e)}pruneDeadEntries(){this.initialize();let e=0,t=0;for(let[n,i]of this.entries)Ir(i.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,i.type==="sdk"&&(t+=1));e>0&&this.persist();for(let n=0;n<t;n+=1)Ey();return e}async reapSession(e){this.initialize();let t=this.getBySession(e);if(t.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;_.info("SYSTEM",`Reaping ${t.length} process(es) for session ${e}`,{sessionId:n,pids:t.map(a=>a.pid)});let i=t.filter(a=>Ir(a.pid));for(let a of i)try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(o){o instanceof Error?o.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},o):_.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(o)})}await Ml(i,i$);let s=i.filter(a=>Ir(a.pid));for(let a of s){_.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(o){o instanceof Error?o.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},o):_.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(o)})}}if(s.length>0){let a=Date.now()+s$;for(;Date.now()<a&&s.filter(c=>Ir(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100))}for(let a of t)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of t)a.type==="sdk"&&Ey();return _.info("SYSTEM",`Reaped ${t.length} process(es) for session ${e}`,{sessionId:n,reaped:t.length}),t.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,Ur.mkdirSync)(xy.default.dirname(this.registryPath),{recursive:!0}),(0,Ur.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},vy=null;l$=[]});function sT(r){return process.platform==="win32"?Math.round(r*co.WINDOWS_MULTIPLIER):r}var co,_y=M(()=>{"use strict";co={DEFAULT:3e5,HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,WORKER_STARTUP_WAIT:1e3,PRE_RESTART_SETTLE_DELAY:2e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5}});async function lT(r){let e=r.currentPid??process.pid,t=r.pidFilePath??d$,n=r.registry.getAll(),i=[...n].filter(a=>a.pid!==e).sort((a,o)=>Date.parse(o.startedAt)-Date.parse(a.startedAt));for(let a of i){if(!Ir(a.pid)){r.registry.unregister(a.id);continue}try{await aT(a,"SIGTERM")}catch(o){o instanceof Error?_.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:a.pid,pgid:a.pgid,type:a.type},o):_.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:a.pid,pgid:a.pgid,type:a.type,error:String(o)})}}await Ml(i,5e3);let s=i.filter(a=>Ir(a.pid));for(let a of s)try{await aT(a,"SIGKILL")}catch(o){o instanceof Error?_.debug("SYSTEM","Failed to force kill child process",{pid:a.pid,pgid:a.pgid,type:a.type},o):_.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:a.pid,pgid:a.pgid,type:a.type,error:String(o)})}await Ml(s,1e3);for(let a of i)r.registry.unregister(a.id);for(let a of n.filter(o=>o.pid===e))r.registry.unregister(a.id);p$(t,e),r.registry.pruneDeadEntries()}function p$(r,e){if(!(0,Cs.existsSync)(r))return;let t=null;try{let n=JSON.parse((0,Cs.readFileSync)(r,"utf-8"));t=typeof n.pid=="number"?n.pid:null}catch(n){_.debug("SYSTEM","PID file unreadable during shutdown \u2014 leaving it (cannot prove ownership)",{pidFilePath:r,error:n instanceof Error?n.message:String(n)});return}if(t!==e){_.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:r,recordedPid:t,currentPid:e});return}try{(0,Cs.rmSync)(r,{force:!0})}catch(n){n instanceof Error?_.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:r},n):_.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:r,error:String(n)})}}async function aT(r,e){let{pid:t,pgid:n}=r;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(a){if((a instanceof Error?a.code:void 0)!=="ESRCH")throw a}try{process.kill(t,e)}catch(a){if((a instanceof Error?a.code:void 0)!=="ESRCH")throw a}return}if(e==="SIGTERM"){try{process.kill(t,e)}catch(a){if(a instanceof Error&&a.code==="ESRCH")return;throw a}return}let i=await f$();if(i){await new Promise((a,o)=>{i(t,e,c=>{if(!c){a();return}if(c.code==="ESRCH"){a();return}o(c)})});return}let s=["/PID",String(t),"/T"];e==="SIGKILL"&&s.push("/F"),await u$("taskkill",s,{timeout:co.POWERSHELL_COMMAND,windowsHide:!0})}async function f$(){let r="tree-kill";try{let e=await import(r);return e.default??e}catch(e){return _.debug("SYSTEM","tree-kill module not available, using fallback",{},e instanceof Error?e:void 0),null}}var oT,Cs,cT,u$,d$,uT=M(()=>{"use strict";oT=require("child_process"),Cs=require("fs"),cT=require("util");ge();_y();Rs();Jr();u$=(0,cT.promisify)(oT.execFile),d$=$e.workerPid()});function m$(){let e=Nl().pruneDeadEntries();e>0&&_.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function pT(){Ds===null&&(Ds=setInterval(m$,dT),Ds.unref(),_.debug("SYSTEM","Health checker started",{intervalMs:dT}))}function fT(){Ds!==null&&(clearInterval(Ds),Ds=null,_.debug("SYSTEM","Health checker stopped"))}var dT,Ds,mT=M(()=>{"use strict";ge();Rs();dT=3e4,Ds=null});function hT(){return y$}function b$(r={}){let e=r.pidFilePath??h$;if(!(0,Ri.existsSync)(e))return"missing";let t=null;try{t=JSON.parse((0,Ri.readFileSync)(e,"utf-8"))}catch(i){return i instanceof Error?_.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},i):_.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(i)}),(0,Ri.rmSync)(e,{force:!0}),"invalid"}return Ln(t)&&t?((r.logAlive??!0)&&_.info("SYSTEM","Worker already running (PID alive)",{existingPid:t.pid,existingPort:t.port,startedAt:t.startedAt}),"alive"):(_.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:t?.pid,port:t?.port,startedAt:t?.startedAt}),(0,Ri.rmSync)(e,{force:!0}),"stale")}var Ri,h$,ky,y$,yT=M(()=>{"use strict";Ri=require("fs");ge();Rs();uT();mT();Jr();h$=$e.workerPid(),ky=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(),b$({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,pT()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let t=async n=>{if(this.shutdownInitiated){_.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,_.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){i instanceof Error?_.error("SYSTEM","Error during shutdown",{},i):_.error("SYSTEM","Error during shutdown (non-Error)",{error:String(i)});try{await this.stop()}catch(s){s instanceof Error?_.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):_.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(s)})}}process.exit(0)};process.on("SIGTERM",()=>{t("SIGTERM")}),process.on("SIGINT",()=>{t("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{_.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{t("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}fT(),this.stopPromise=lT({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,t,n){this.registry.register(e,t,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},y$=new ky(Nl())});function Ty(r,e,t){r.on("finish",async()=>{try{await t()}finally{process.exit(0)}}),r.json(e)}var bT=M(()=>{"use strict"});function Ay(r,e=Date.now){return Math.max(0,Math.floor((e()-r)/1e3))}var gT=M(()=>{"use strict"});var Ky,vT,xde,ET=M(()=>{"use strict";Ky=class{entries=new Map;set(e){if(!e||typeof e!="object")return;let t=e.rateLimitType??"default";this.entries.set(t,{...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}},vT=new Ky,xde=900*1e3});function E$(r){r.setHeader("X-Content-Type-Options","nosniff"),r.setHeader("X-Frame-Options","DENY"),r.setHeader("X-DNS-Prefetch-Control","off"),r.setHeader("Referrer-Policy","no-referrer"),r.setHeader("Cross-Origin-Opener-Policy","same-origin"),r.setHeader("Cross-Origin-Resource-Policy","same-origin"),r.setHeader("Origin-Agent-Cluster","?1"),r.removeHeader("X-Powered-By")}var wT,IT,jy,lo,_T,g$,Oy,xT,v$,ST,Ll,kT=M(()=>{"use strict";wT=ct(Rl(),1),IT=ct(require("http"),1),jy=ct(require("fs"),1),lo=ct(require("path"),1);Lk();ge();Xk();rT();yT();Rs();Pl();bT();gT();ET();_T=lo.default.resolve(__dirname,"../skills/mem-search"),g$=lo.default.join(_T,"operations"),Oy=lo.default.join(_T,"SKILL.md"),xT=(()=>{try{let r=jy.readFileSync(Oy,"utf-8");return _.info("SYSTEM","Cached SKILL.md at boot",{path:Oy,bytes:Buffer.byteLength(r,"utf-8")}),r}catch(r){return _.debug("SYSTEM","SKILL.md not present at boot, /api/instructions will 404 for topic queries",{path:Oy,message:r instanceof Error?r.message:String(r)}),null}})(),v$=(()=>{let r=new Map;for(let e of cy){let t=lo.default.join(g$,`${e}.md`);try{r.set(e,jy.readFileSync(t,"utf-8"))}catch(n){_.debug("SYSTEM","Operation instruction file not present at boot",{path:t,message:n instanceof Error?n.message:String(n)})}}return r.size>0&&_.info("SYSTEM","Cached operation instruction files at boot",{count:r.size,operations:Array.from(r.keys())}),r})(),ST="13.8.0";Ll=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,wT.default)(),this.app.disable("x-powered-by"),this.setupSecurityHeaders(),this.setupCors(),this.setupPreBodyParserRoutes(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,t){return new Promise((n,i)=>{let s=IT.default.createServer(this.app);this.server=s;let a=c=>{s.off("listening",o),i(c)},o=()=>{s.off("error",a),_.info("SYSTEM","HTTP server started",{host:t,port:e,pid:process.pid}),n()};s.once("error",a),s.once("listening",o),s.listen(e,t)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,t)=>{this.server.close(n=>n?t(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,_.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(tT),this.app.use(eT)}setupMiddleware(){Wk(Qk,{includeCors:!1}).forEach(t=>this.app.use(t))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,t,n)=>{E$(t),n()})}setupCors(){this.app.use(yy())}setupPreBodyParserRoutes(){this.options.preBodyParserRoutes?.forEach(e=>e.setupRoutes(this.app))}setupCoreRoutes(){this.app.get("/api/health",async(e,t)=>{let n=this.options.getQueueHealth?await this.options.getQueueHealth():null,i=n?.engine==="bullmq"&&n.redis.status==="error";t.status(i?503:200).json({status:i?"degraded":"ok",...this.options.runtime?{runtime:this.options.runtime}:{},version:ST,workerPath:this.options.workerPath,uptime:Ay(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(),rateLimits:vT.getMostRecentByWindow(),...n?{queue:n}:{}})}),this.app.get("/api/readiness",(e,t)=>{this.options.getInitializationComplete()?t.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):t.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(e,t)=>{t.status(200).json({version:ST})}),this.app.get("/api/instructions",(e,t)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!Nk.includes(n))return t.status(400).json({error:"Invalid topic"});if(i&&!cy.includes(i))return t.status(400).json({error:"Invalid operation"});if(i){let a=v$.get(i);return a===void 0?(_.debug("HTTP","Instruction file not cached at boot",{operation:i}),t.status(404).json({error:"Instruction not found"})):t.json({content:[{type:"text",text:a}]})}if(xT===null)return _.debug("HTTP","SKILL.md not cached at boot",{topic:n}),t.status(404).json({error:"Instruction not found"});let s=this.extractInstructionSection(xT,n);t.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",Dl,async(e,t)=>{process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(t.json({status:"restarting"}),_.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):Ty(t,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",Dl,async(e,t)=>{let n=e.query.reason==="restart"?"restart":"stop";process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(t.json({status:"shutting_down"}),_.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown",reason:n})):Ty(t,{status:"shutting_down"},()=>this.options.onShutdown(n))}),this.app.get("/api/admin/doctor",Dl,(e,t)=>{let a=hT().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:Ir(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=>gy.has(f)||by.some(m=>f.startsWith(m))),l=Ay(this.startTime),u=Math.floor(l/3600),d=Math.floor(l%3600/60),p=u>0?`${u}h ${d}m`:`${d}m`;t.json({supervisor:{running:!0,pid:process.pid,uptime:p},processes:a,health:{deadProcessPids:o,envClean:c}})})}extractInstructionSection(e,t){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[t]||n.all}extractBetween(e,t,n){let i=e.indexOf(t),s=e.indexOf(n);return i===-1?e:s===-1?e.substring(i):e.substring(i,s).trim()}}});var Jt,x$,S$,Ry,TT=M(()=>{"use strict";Jt=require("zod"),x$=Jt.z.enum(["hook","worker","provider","server","api"]),S$=Jt.z.object({id:Jt.z.string().min(1),projectId:Jt.z.string().min(1),serverSessionId:Jt.z.string().min(1).nullable().default(null),sourceType:x$,eventType:Jt.z.string().min(1),platformSource:Jt.z.string().min(1).nullable().default(null),payload:Jt.z.unknown().default({}),contentSessionId:Jt.z.string().min(1).nullable().default(null),memorySessionId:Jt.z.string().min(1).nullable().default(null),occurredAtEpoch:Jt.z.number().int().nonnegative(),createdAtEpoch:Jt.z.number().int().nonnegative()}),Ry=S$.omit({id:!0,createdAtEpoch:!0}).partial({serverSessionId:!0,platformSource:!0,payload:!0,contentSessionId:!0,memorySessionId:!0})});function qe(){return(0,ql.randomUUID)()}function ze(r){return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}function AT(r){return Array.isArray(r)?r:[]}function ve(r){return typeof r=="number"?r:new Date(r).getTime()}function or(r){return r==null?null:r instanceof Date?r:new Date(r)}async function W(r,e,t=[]){return(await r.query(e,t)).rows[0]??null}async function _r(r,e,t){if(!await W(r,"SELECT id FROM projects WHERE id = $1 AND team_id = $2",[e,t]))throw new Error("project_id must belong to team_id")}async function pn(r,e,t,n){if(!await W(r,"SELECT id FROM server_sessions WHERE id = $1 AND project_id = $2 AND team_id = $3",[e,t,n]))throw new Error("server_session_id must belong to project_id and team_id")}function uo(r){return JSON.stringify(Cy(r))}function kr(r){return(0,ql.createHash)("sha256").update(uo(r)).digest("hex")}function Cy(r){if(Array.isArray(r))return r.map(Cy);if(r&&typeof r=="object"){let e=r;return Object.keys(e).sort().reduce((t,n)=>(t[n]=Cy(e[n]),t),{})}return r}var ql,Gr=M(()=>{"use strict";ql=require("crypto")});function KT(r){return r.sourceEventId?`agent_event:v1:${kr([r.teamId,r.projectId,r.sourceAdapter,r.sourceEventId])}`:`agent_event:v1:${kr([r.teamId,r.projectId,r.sourceAdapter,r.contentSessionId??r.serverSessionId??null,r.eventType,new Date(r.occurredAt).toISOString(),uo(r.payload??{})])}`}function Dy(r){return{id:r.id,projectId:r.project_id,teamId:r.team_id,serverSessionId:r.server_session_id,sourceAdapter:r.source_adapter,sourceEventId:r.source_event_id,idempotencyKey:r.idempotency_key,eventType:r.event_type,platformSource:r.platform_source,payload:r.payload,metadata:ze(r.metadata),occurredAtEpoch:ve(r.occurred_at),receivedAtEpoch:ve(r.received_at),createdAtEpoch:ve(r.created_at)}}var cr,Ps=M(()=>{"use strict";Gr();cr=class{constructor(e){this.client=e}client;async create(e){await _r(this.client,e.projectId,e.teamId),e.serverSessionId&&await pn(this.client,e.serverSessionId,e.projectId,e.teamId);let t=KT(e),n=await W(this.client,`
63
63
  INSERT INTO agent_events (
64
64
  id, project_id, team_id, server_session_id, source_adapter,
65
65
  source_event_id, idempotency_key, event_type, platform_source, payload, metadata, occurred_at