claude-mem 13.5.7 → 13.6.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.5.7",
3
+ "version": "13.6.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 db(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)}error(e,r,i,n){this.log(3,e,r,i,n)}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)}timing(e,r,i,n){this.info(e,`\u23F1 ${r}`,n,{duration:`${i}ms`})}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}},_=new fb});import{join as De,dirname as $W,basename as qW}from"path";import{homedir as ZO}from"os";import{existsSync as zW,mkdirSync as Rye,readFileSync as GW}from"fs";import{execSync as Dye}from"child_process";import{fileURLToPath as BW}from"url";function VW(){return typeof __dirname<"u"?__dirname:$W(BW(import.meta.url))}function kn(){if(process.env.CLAUDE_MEM_DATA_DIR)return process.env.CLAUDE_MEM_DATA_DIR;let t=De(ZO(),".claude-mem"),e=De(t,"settings.json");try{if(zW(e)){let r=JSON.parse(GW(e,"utf-8")),i=r.env??r;if(i.CLAUDE_MEM_DATA_DIR)return i.CLAUDE_MEM_DATA_DIR}}catch{}return t}var Mye,Me,Rs,Ml,WW,HW,ZW,YW,XW,ht,Nye,QW,YO,Lye,Uye,Fye,Jye,ft,tt=E(()=>{"use strict";dt();Mye=VW();Me=kn(),Rs=process.env.CLAUDE_CONFIG_DIR||De(ZO(),".claude"),Ml=De(Rs,"plugins","marketplaces","thedotmack"),WW=De(Me,"archives"),HW=De(Me,"logs"),ZW=De(Me,"trash"),YW=De(Me,"backups"),XW=De(Me,"modes"),ht=De(Me,"settings.json"),Nye=De(Me,"claude-mem.db"),QW=De(Me,"vector-db"),YO=De(Me,"observer-sessions"),Lye=qW(YO),Uye=De(Rs,"settings.json"),Fye=De(Rs,"commands"),Jye=De(Rs,"CLAUDE.md"),ft={dataDir:()=>Me,workerPid:()=>De(Me,"worker.pid"),serverBetaPid:()=>De(Me,".server-beta.pid"),serverBetaPort:()=>De(Me,".server-beta.port"),serverBetaRuntime:()=>De(Me,".server-beta.runtime.json"),settings:()=>De(Me,"settings.json"),database:()=>De(Me,"claude-mem.db"),chroma:()=>De(Me,"chroma"),combinedCerts:()=>De(Me,"combined_certs.pem"),transcriptsConfig:()=>De(Me,"transcript-watch.json"),transcriptsState:()=>De(Me,"transcript-watch-state.json"),corpora:()=>De(Me,"corpora"),supervisorRegistry:()=>De(Me,"supervisor.json"),envFile:()=>De(Me,".env"),logsDir:()=>HW,archives:()=>WW,trash:()=>ZW,backups:()=>YW,modes:()=>XW,vectorDb:()=>QW,observerSessions:()=>YO}});import{join as XO}from"path";import{mkdirSync as e3,writeFileSync as t3}from"fs";import{randomUUID as r3}from"crypto";function n3(t){let e=t.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function hb(t,e){if(n3(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 Nl(){return XO(kn(),QO)}function Ci(){try{let t=cr(Nl(),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 Ks(t){let e=kn();e3(e,{recursive:!0}),t3(XO(e,QO),JSON.stringify(t,null,2)+`
97
- `)}function bd(){let t=Ci();if(t?.installId)return t.installId;let e=r3();return Ks({installId:e,decidedAt:""}),e}var QO,vd=E(()=>{"use strict";tt();xs();QO="telemetry.json"});function rA(t){let e={};try{if(!t||typeof t!="object")return e;for(let r of Object.keys(t)){if(!i3.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 i3,tA,nA=E(()=>{"use strict";i3=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","fabrication_detected","fabricated_count","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"]),tA=200});import iA from"os";function oA(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||s3}function sA(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||a3}function aA(t){let e={};for(let r of l3)t[r]!==void 0&&(e[r]=t[r]);return e}function c3(){try{return iA.release()}catch{return"unknown"}}function u3(){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:o3,os:process.platform,os_version:c3(),is_wsl:u3(),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 o3,s3,a3,l3,cA=E(()=>{"use strict";o3="13.5.7",s3="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",a3="https://us.i.posthog.com";l3=["version","os","os_version","is_wsl","arch","runtime","locale","ide","provider","runtime_mode","install_method","claude_code_version","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 Ds(t,e,r){try{if(!eA(process.env,Ci()))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 bd(){let t=Ci();if(t?.installId)return t.installId;let e=r3();return Ks({installId:e,decidedAt:""}),e}var QO,vd=E(()=>{"use strict";tt();xs();QO="telemetry.json"});function rA(t){let e={};try{if(!t||typeof t!="object")return e;for(let r of Object.keys(t)){if(!i3.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 i3,tA,nA=E(()=>{"use strict";i3=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","fabrication_detected","fabricated_count","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","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"]),tA=200});import iA from"os";function oA(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||s3}function sA(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||a3}function aA(t){let e={};for(let r of l3)t[r]!==void 0&&(e[r]=t[r]);return e}function c3(){try{return iA.release()}catch{return"unknown"}}function u3(){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:o3,os:process.platform,os_version:c3(),is_wsl:u3(),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 o3,s3,a3,l3,cA=E(()=>{"use strict";o3="13.6.0",s3="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",a3="https://us.i.posthog.com";l3=["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 Ds(t,e,r){try{if(!eA(process.env,Ci()))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(),d3);try{await fetch(`${sA()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:n,event:t,distinct_id:bd(),properties:i}),signal:o.signal})}finally{clearTimeout(s)}}catch{}}var d3,Ed=E(()=>{"use strict";vd();nA();cA();d3=2e3});import{spawn as p3}from"node:child_process";function an(t,e,r){return p3(t,e??[],{windowsHide:!0,...r})}var js=E(()=>{"use strict"});function Ro(t){return process.platform==="win32"?Math.round(t*St.WINDOWS_MULTIPLIER):t}var St,Ps=E(()=>{"use strict";St={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:()=>rt});import{readFileSync as m3,writeFileSync as uA,existsSync as dA,mkdirSync as f3}from"fs";import{join as pA,dirname as h3}from"path";import{homedir as mA}from"os";var rt,ln=E(()=>{"use strict";Ps();rt=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(Ro(St.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=h3(e);dA(l)||f3(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=m3(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 y3}from"child_process";import{promisify as g3}from"util";import{existsSync as pge,readFileSync as mge,writeFileSync as fge,mkdirSync as hge,unlinkSync as yge}from"fs";import{userInfo as bge}from"os";import{join as Ege}from"path";var wge,hA=E(()=>{"use strict";tt();dt();wge=g3(y3)});import{existsSync as yb,readFileSync as gA,writeFileSync as b3,mkdirSync as v3,chmodSync as yA}from"fs";function gb(){return process.env.CLAUDE_MEM_ENV_FILE??ft.envFile()}function bA(t){let e={};for(let r of t.split(`
99
99
  `)){let i=r.trim();if(!i||i.startsWith("#"))continue;let n=i.indexOf("=");if(n===-1)continue;let o=i.slice(0,n).trim(),s=i.slice(n+1).trim();(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),o&&(e[o]=s)}return e}function E3(t){let e=["# claude-mem credentials","# This file stores keys and gateway settings for the claude-mem memory agent","# Edit this file or use claude-mem settings to configure",""];for(let[r,i]of Object.entries(t))if(i){let n=/[\s#=]/.test(i);e.push(`${r}=${n?`"${i}"`:i}`)}return e.join(`
100
100
  `)+`
@@ -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.5.7",
6
+ "version": "13.6.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.5.7",
3
+ "version": "13.6.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.5.7",
3
+ "version": "13.6.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.5.7",
3
+ "version": "13.6.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.5.7",
3
+ "version": "13.6.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 R_=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*I_(t,e,r=20,n){if(r<=0)return;let o;try{o=await(0,Dr.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,Yn.join)(t,s.name);if(s.isDirectory())yield*I_(i,e,r-1,n);else if(s.isFile()){let a=s.name.slice(s.name.lastIndexOf("."));(R_.has(a)||n&&n.has(a))&&(yield i)}}}async function fP(t){try{let e=await(0,Dr.stat)(t);if(e.size>pP||e.size===0)return null;let r=await(0,Dr.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 O_(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=Jn(i),c=new Set;for(let E of Object.values(a.grammars))for(let v of E.extensions)R_.has(v)||c.add(v);let u=[];for await(let E of I_(t,t,20,c.size>0?c:void 0)){if(r.filePattern&&!(0,Yn.relative)(t,E).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let v=await fP(E);v&&u.push({absolutePath:E,relativePath:(0,Yn.relative)(t,E),content:v})}let l=P_(u,i),d=[],p=[],f=0;for(let[E,v]of l){f+=mP(v);let x=Fs(E.toLowerCase(),s)>0,Se=[],we=(Zt,nr)=>{for(let ce of Zt){let kt=0,Ke="",Lr=Fs(ce.name.toLowerCase(),s);Lr>0&&(kt+=Lr*3,Ke="name match"),ce.signature.toLowerCase().includes(o)&&(kt+=2,Ke=Ke?`${Ke} + signature`:"signature match"),ce.jsdoc&&ce.jsdoc.toLowerCase().includes(o)&&(kt+=1,Ke=Ke?`${Ke} + jsdoc`:"jsdoc match"),kt>0&&(x=!0,Se.push({filePath:E,symbolName:nr?`${nr}.${ce.name}`:ce.name,kind:ce.kind,signature:ce.signature,jsdoc:ce.jsdoc,lineStart:ce.lineStart,lineEnd:ce.lineEnd,matchReason:Ke})),ce.children&&we(ce.children,ce.name)}};we(v.symbols),x&&(d.push(v),p.push(...Se))}p.sort((E,v)=>{let $=Fs(E.symbolName.toLowerCase(),s);return Fs(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 Fs(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 A_(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(Nr(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 Ru=require("node:fs/promises"),Ws=require("node:fs"),tt=require("node:path"),q_=require("node:os"),Z_=require("node:url");var hP=Et(ae.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)}},Hs=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 gu(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 M_(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 Tu(){return(Is().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase()==="server-beta"?"server-beta":"worker"}function C_(){let t=Is(),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 Hs(o),projectId:n,serverBaseUrl:e}}var OP={},yP="13.5.7";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var F_=!1,H_=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,tt.dirname)((0,Z_.fileURLToPath)(OP.url))}catch{return F_=!0,process.cwd()}})(),Iu=m_()??(0,tt.resolve)(H_,"worker-service.cjs");function SP(){F_&&((0,Ws.existsSync)(Iu)||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:Iu,mcpServerDir:H_}))}var N_={search:"/api/search",timeline:"/api/timeline"};async function zu(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 Us(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 Us(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 jr(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 Us("/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(Tu()!=="server-beta")return null;let e=C_();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 Qn(t){return M_(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 eo(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function to(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 D_(t){try{let e=to("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 eo(o)}catch(e){return Qn(e)}}async function wP(t){try{let e=to("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 eo(o)}catch(e){return Qn(e)}}async function j_(t){try{let e=to("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 eo(o)}catch(e){return Qn(e)}}async function L_(t){try{let e=to("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 eo(o)}catch(e){return Qn(e)}}async function kP(t){try{let e=to("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 eo(n)}catch(e){return Qn(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=yu(),e=await h_(t,Iu);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 W_=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
222
+ `)}var Ru=require("node:fs/promises"),Ws=require("node:fs"),tt=require("node:path"),q_=require("node:os"),Z_=require("node:url");var hP=Et(ae.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)}},Hs=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 gu(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 M_(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 Tu(){return(Is().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase()==="server-beta"?"server-beta":"worker"}function C_(){let t=Is(),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 Hs(o),projectId:n,serverBaseUrl:e}}var OP={},yP="13.6.0";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var F_=!1,H_=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,tt.dirname)((0,Z_.fileURLToPath)(OP.url))}catch{return F_=!0,process.cwd()}})(),Iu=m_()??(0,tt.resolve)(H_,"worker-service.cjs");function SP(){F_&&((0,Ws.existsSync)(Iu)||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:Iu,mcpServerDir:H_}))}var N_={search:"/api/search",timeline:"/api/timeline"};async function zu(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 Us(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 Us(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 jr(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 Us("/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(Tu()!=="server-beta")return null;let e=C_();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 Qn(t){return M_(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 eo(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function to(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 D_(t){try{let e=to("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 eo(o)}catch(e){return Qn(e)}}async function wP(t){try{let e=to("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 eo(o)}catch(e){return Qn(e)}}async function j_(t){try{let e=to("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 eo(o)}catch(e){return Qn(e)}}async function L_(t){try{let e=to("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 eo(o)}catch(e){return Qn(e)}}async function kP(t){try{let e=to("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 eo(n)}catch(e){return Qn(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=yu(),e=await h_(t,Iu);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 W_=[{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){fy(`[LOGGER] Failed to write to log file: ${f instanceof Error?f.message:String(f)}
60
60
  `)}else fy(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)}error(e,t,n,i){this.log(3,e,t,n,i)}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)}timing(e,t,n,i){this.info(e,`\u23F1 ${t}`,i,{duration:`${n}ms`})}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 hy});var Hk=h((Fue,Vk)=>{"use strict";var $k=Object.getOwnPropertySymbols,Q9=Object.prototype.hasOwnProperty,X9=Object.prototype.propertyIsEnumerable;function Z9(r){if(r==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(r)}function e$(){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}}Vk.exports=e$()?Object.assign:function(r,e){for(var t,n=Z9(r),i,s=1;s<arguments.length;s++){t=Object(arguments[s]);for(var a in t)Q9.call(t,a)&&(n[a]=t[a]);if($k){i=$k(t);for(var o=0;o<i.length;o++)X9.call(t,i[o])&&(n[i[o]]=t[i[o]])}}return n}});var Yk=h((Jue,zk)=>{(function(){"use strict";var r=Hk(),e=ay(),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(Re,se){se(null,J.origin)}),re?re(g.headers.origin,function(Re,se){Re||!se?I(Re):(J.origin=se,p(J,g,E,I))}):I()}})}}zk.exports=f})()});function by(r,e={}){let t=[];e.includeCors!==!1&&t.push(Ml()),t.push(yy.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=Ri(),i=Qk.default.join(n,"plugin","ui");return t.push(yy.default.static(i)),t}function Ml(){return(0,Wk.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 co(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 gy(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 yy,Wk,Qk,Xk=M(()=>{"use strict";yy=ct(Dl(),1),Wk=ct(Yk(),1),Qk=ct(require("path"),1);Jr();ge()});var Zk=M(()=>{"use strict";Xk()});function eT(r,e,t,n){let i={error:r,message:e};return t&&(i.code=t),n&&(i.details=n),i}function rT(r,e){e.status(404).json(eT("NotFound",`Cannot ${r.method} ${r.path}`))}var Rs,tT,nT=M(()=>{"use strict";ge();Rs=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};tT=(r,e,t,n)=>{let i=r instanceof Rs?r.statusCode:500;_.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:r.message,code:r instanceof Rs?r.code:void 0},r);let s=eT(r.name||"Error",r.message,r instanceof Rs?r.code:void 0,r instanceof Rs?r.details:void 0);t.status(i).json(s)}});var iT=M(()=>{"use strict"});function lo(r=process.env){let e={};for(let[t,n]of Object.entries(r))if(n!==void 0){if(r$.has(t)){e[t]=n;continue}Ey.has(t)||t$.has(t)||vy.some(i=>t.startsWith(i))||(e[t]=n)}return e}var vy,Ey,t$,r$,Nl=M(()=>{"use strict";vy=["CLAUDECODE_","CLAUDE_CODE_"],Ey=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),t$=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy"]),r$=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 or(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}}function o$(r){let e=sT.get(r);if(e&&Date.now()-e.capturedAtMs<a$)return e.token;let t=null;try{let n=(0,_y.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:{...lo(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 sT.set(r,{token:t,capturedAtMs:Date.now()}),t}function ky(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 o$(r);try{let e=(0,_y.spawnSync)("ps",["-p",String(r),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...lo(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||!or(r.pid))return!1;if(!r.startToken)return!0;let e=ky(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 Ll(){return xy||(xy=new Iy),xy}function Sy(){let r=c$.shift();r&&r()}var _y,Ur,wy,n$,i$,s$,a$,sT,Iy,xy,c$,js=M(()=>{"use strict";_y=require("child_process");iT();Ur=require("fs"),wy=ct(require("path"),1);ge();Nl();Jr();n$=5e3,i$=1e3,s$=$e.supervisorRegistry();a$=5e3,sT=new Map;Iy=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=s$){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,Ur.mkdirSync)(wy.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"&&Sy()}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)or(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)Sy();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(o=>o.pid)});let i=t.filter(o=>or(o.pid));for(let o of i)try{typeof o.pgid=="number"&&process.platform!=="win32"?process.kill(-o.pgid,"SIGTERM"):process.kill(o.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGTERM session process PID ${o.pid}`,{pid:o.pid,pgid:o.pgid},c):_.warn("SYSTEM",`Failed to SIGTERM session process PID ${o.pid} (non-Error)`,{pid:o.pid,pgid:o.pgid,error:String(c)})}let s=Date.now()+n$;for(;Date.now()<s&&i.filter(c=>or(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100));let a=i.filter(o=>or(o.pid));for(let o of a){_.warn("SYSTEM",`Session process PID ${o.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:o.pid,pgid:o.pgid,sessionId:n});try{typeof o.pgid=="number"&&process.platform!=="win32"?process.kill(-o.pgid,"SIGKILL"):process.kill(o.pid,"SIGKILL")}catch(c){c instanceof Error?c.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGKILL session process PID ${o.pid}`,{pid:o.pid,pgid:o.pgid},c):_.warn("SYSTEM",`Failed to SIGKILL session process PID ${o.pid} (non-Error)`,{pid:o.pid,pgid:o.pgid,error:String(c)})}}if(a.length>0){let o=Date.now()+i$;for(;Date.now()<o&&a.filter(l=>or(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let o of t)this.entries.delete(o.id),this.runtimeProcesses.delete(o.id);this.persist();for(let o of t)o.type==="sdk"&&Sy();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)(wy.default.dirname(this.registryPath),{recursive:!0}),(0,Ur.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},xy=null;c$=[]});function aT(r){return process.platform==="win32"?Math.round(r*uo.WINDOWS_MULTIPLIER):r}var uo,Ty=M(()=>{"use strict";uo={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 dT(r){let e=r.currentPid??process.pid,t=r.pidFilePath??u$,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(!or(a.pid)){r.registry.unregister(a.id);continue}try{await cT(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 oT(i,5e3);let s=i.filter(a=>or(a.pid));for(let a of s)try{await cT(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 oT(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);d$(t,e),r.registry.pruneDeadEntries()}function d$(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 oT(r,e){let t=Date.now()+e;for(;Date.now()<t;){if(r.filter(i=>or(i.pid)).length===0)return;await new Promise(i=>setTimeout(i,100))}}async function cT(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 p$();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 l$("taskkill",s,{timeout:uo.POWERSHELL_COMMAND,windowsHide:!0})}async function p$(){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 lT,Cs,uT,l$,u$,pT=M(()=>{"use strict";lT=require("child_process"),Cs=require("fs"),uT=require("util");ge();Ty();js();Jr();l$=(0,uT.promisify)(lT.execFile),u$=$e.workerPid()});function f$(){let e=Ll().pruneDeadEntries();e>0&&_.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function mT(){Ds===null&&(Ds=setInterval(f$,fT),Ds.unref(),_.debug("SYSTEM","Health checker started",{intervalMs:fT}))}function hT(){Ds!==null&&(clearInterval(Ds),Ds=null,_.debug("SYSTEM","Health checker stopped"))}var fT,Ds,yT=M(()=>{"use strict";ge();js();fT=3e4,Ds=null});function bT(){return h$}function y$(r={}){let e=r.pidFilePath??m$;if(!(0,ji.existsSync)(e))return"missing";let t=null;try{t=JSON.parse((0,ji.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,ji.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,ji.rmSync)(e,{force:!0}),"stale")}var ji,m$,Ay,h$,gT=M(()=>{"use strict";ji=require("fs");ge();js();pT();yT();Jr();m$=$e.workerPid(),Ay=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(),y$({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,mT()}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}hT(),this.stopPromise=dT({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}},h$=new Ay(Ll())});function Ky(r,e,t){r.on("finish",async()=>{try{await t()}finally{process.exit(0)}}),r.json(e)}var vT=M(()=>{"use strict"});function Oy(r,e=Date.now){return Math.max(0,Math.floor((e()-r)/1e3))}var ET=M(()=>{"use strict"});var Ry,xT,_de,ST=M(()=>{"use strict";Ry=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")}getAll(){return Array.from(this.entries.values()).sort((e,t)=>t.observedAt-e.observedAt)}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}clear(){this.entries.clear()}},xT=new Ry,_de=900*1e3});function v$(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 _T,kT,Cy,po,TT,b$,jy,wT,g$,IT,ql,AT=M(()=>{"use strict";_T=ct(Dl(),1),kT=ct(require("http"),1),Cy=ct(require("fs"),1),po=ct(require("path"),1);Fk();ge();Zk();nT();gT();js();Nl();vT();ET();ST();TT=po.default.resolve(__dirname,"../skills/mem-search"),b$=po.default.join(TT,"operations"),jy=po.default.join(TT,"SKILL.md"),wT=(()=>{try{let r=Cy.readFileSync(jy,"utf-8");return _.info("SYSTEM","Cached SKILL.md at boot",{path:jy,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:jy,message:r instanceof Error?r.message:String(r)}),null}})(),g$=(()=>{let r=new Map;for(let e of uy){let t=po.default.join(b$,`${e}.md`);try{r.set(e,Cy.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})(),IT="13.5.7";ql=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,_T.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=kT.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(rT),this.app.use(tT)}setupMiddleware(){by(gy,{includeCors:!1}).forEach(t=>this.app.use(t))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,t,n)=>{v$(t),n()})}setupCors(){this.app.use(Ml())}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:IT,workerPath:this.options.workerPath,uptime:Oy(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:xT.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:IT})}),this.app.get("/api/instructions",(e,t)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!qk.includes(n))return t.status(400).json({error:"Invalid topic"});if(i&&!uy.includes(i))return t.status(400).json({error:"Invalid operation"});if(i){let a=g$.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(wT===null)return _.debug("HTTP","SKILL.md not cached at boot",{topic:n}),t.status(404).json({error:"Instruction not found"});let s=this.extractInstructionSection(wT,n);t.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",co,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"})):Ky(t,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",co,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})):Ky(t,{status:"shutting_down"},()=>this.options.onShutdown(n))}),this.app.get("/api/admin/doctor",co,(e,t)=>{let a=bT().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:or(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=>Ey.has(f)||vy.some(m=>f.startsWith(m))),l=Oy(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,E$,x$,Dy,KT=M(()=>{"use strict";Jt=require("zod"),E$=Jt.z.enum(["hook","worker","provider","server","api"]),x$=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:E$,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()}),Dy=x$.omit({id:!0,createdAtEpoch:!0}).partial({serverSessionId:!0,platformSource:!0,payload:!0,contentSessionId:!0,memorySessionId:!0})});function qe(){return(0,Fl.randomUUID)()}function ze(r){return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}function OT(r){return Array.isArray(r)?r:[]}function ve(r){return typeof r=="number"?r:new Date(r).getTime()}function cr(r){return r==null?null:r instanceof Date?r:new Date(r)}async function Y(r,e,t=[]){return(await r.query(e,t)).rows[0]??null}async function _r(r,e,t){if(!await Y(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 Y(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 fo(r){return JSON.stringify(Py(r))}function kr(r){return(0,Fl.createHash)("sha256").update(fo(r)).digest("hex")}function Py(r){if(Array.isArray(r))return r.map(Py);if(r&&typeof r=="object"){let e=r;return Object.keys(e).sort().reduce((t,n)=>(t[n]=Py(e[n]),t),{})}return r}var Fl,Gr=M(()=>{"use strict";Fl=require("crypto")});function RT(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(),fo(r.payload??{})])}`}function My(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 lr,Ps=M(()=>{"use strict";Gr();lr=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=RT(e),n=await Y(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 hy});var Hk=h((Fue,Vk)=>{"use strict";var $k=Object.getOwnPropertySymbols,Q9=Object.prototype.hasOwnProperty,X9=Object.prototype.propertyIsEnumerable;function Z9(r){if(r==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(r)}function e$(){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}}Vk.exports=e$()?Object.assign:function(r,e){for(var t,n=Z9(r),i,s=1;s<arguments.length;s++){t=Object(arguments[s]);for(var a in t)Q9.call(t,a)&&(n[a]=t[a]);if($k){i=$k(t);for(var o=0;o<i.length;o++)X9.call(t,i[o])&&(n[i[o]]=t[i[o]])}}return n}});var Yk=h((Jue,zk)=>{(function(){"use strict";var r=Hk(),e=ay(),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(Re,se){se(null,J.origin)}),re?re(g.headers.origin,function(Re,se){Re||!se?I(Re):(J.origin=se,p(J,g,E,I))}):I()}})}}zk.exports=f})()});function by(r,e={}){let t=[];e.includeCors!==!1&&t.push(Ml()),t.push(yy.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=Ri(),i=Qk.default.join(n,"plugin","ui");return t.push(yy.default.static(i)),t}function Ml(){return(0,Wk.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 co(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 gy(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 yy,Wk,Qk,Xk=M(()=>{"use strict";yy=ct(Dl(),1),Wk=ct(Yk(),1),Qk=ct(require("path"),1);Jr();ge()});var Zk=M(()=>{"use strict";Xk()});function eT(r,e,t,n){let i={error:r,message:e};return t&&(i.code=t),n&&(i.details=n),i}function rT(r,e){e.status(404).json(eT("NotFound",`Cannot ${r.method} ${r.path}`))}var Rs,tT,nT=M(()=>{"use strict";ge();Rs=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};tT=(r,e,t,n)=>{let i=r instanceof Rs?r.statusCode:500;_.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:r.message,code:r instanceof Rs?r.code:void 0},r);let s=eT(r.name||"Error",r.message,r instanceof Rs?r.code:void 0,r instanceof Rs?r.details:void 0);t.status(i).json(s)}});var iT=M(()=>{"use strict"});function lo(r=process.env){let e={};for(let[t,n]of Object.entries(r))if(n!==void 0){if(r$.has(t)){e[t]=n;continue}Ey.has(t)||t$.has(t)||vy.some(i=>t.startsWith(i))||(e[t]=n)}return e}var vy,Ey,t$,r$,Nl=M(()=>{"use strict";vy=["CLAUDECODE_","CLAUDE_CODE_"],Ey=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),t$=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy"]),r$=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 or(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}}function o$(r){let e=sT.get(r);if(e&&Date.now()-e.capturedAtMs<a$)return e.token;let t=null;try{let n=(0,_y.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:{...lo(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 sT.set(r,{token:t,capturedAtMs:Date.now()}),t}function ky(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 o$(r);try{let e=(0,_y.spawnSync)("ps",["-p",String(r),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...lo(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||!or(r.pid))return!1;if(!r.startToken)return!0;let e=ky(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 Ll(){return xy||(xy=new Iy),xy}function Sy(){let r=c$.shift();r&&r()}var _y,Ur,wy,n$,i$,s$,a$,sT,Iy,xy,c$,js=M(()=>{"use strict";_y=require("child_process");iT();Ur=require("fs"),wy=ct(require("path"),1);ge();Nl();Jr();n$=5e3,i$=1e3,s$=$e.supervisorRegistry();a$=5e3,sT=new Map;Iy=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=s$){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,Ur.mkdirSync)(wy.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"&&Sy()}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)or(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)Sy();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(o=>o.pid)});let i=t.filter(o=>or(o.pid));for(let o of i)try{typeof o.pgid=="number"&&process.platform!=="win32"?process.kill(-o.pgid,"SIGTERM"):process.kill(o.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGTERM session process PID ${o.pid}`,{pid:o.pid,pgid:o.pgid},c):_.warn("SYSTEM",`Failed to SIGTERM session process PID ${o.pid} (non-Error)`,{pid:o.pid,pgid:o.pgid,error:String(c)})}let s=Date.now()+n$;for(;Date.now()<s&&i.filter(c=>or(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100));let a=i.filter(o=>or(o.pid));for(let o of a){_.warn("SYSTEM",`Session process PID ${o.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:o.pid,pgid:o.pgid,sessionId:n});try{typeof o.pgid=="number"&&process.platform!=="win32"?process.kill(-o.pgid,"SIGKILL"):process.kill(o.pid,"SIGKILL")}catch(c){c instanceof Error?c.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGKILL session process PID ${o.pid}`,{pid:o.pid,pgid:o.pgid},c):_.warn("SYSTEM",`Failed to SIGKILL session process PID ${o.pid} (non-Error)`,{pid:o.pid,pgid:o.pgid,error:String(c)})}}if(a.length>0){let o=Date.now()+i$;for(;Date.now()<o&&a.filter(l=>or(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let o of t)this.entries.delete(o.id),this.runtimeProcesses.delete(o.id);this.persist();for(let o of t)o.type==="sdk"&&Sy();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)(wy.default.dirname(this.registryPath),{recursive:!0}),(0,Ur.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},xy=null;c$=[]});function aT(r){return process.platform==="win32"?Math.round(r*uo.WINDOWS_MULTIPLIER):r}var uo,Ty=M(()=>{"use strict";uo={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 dT(r){let e=r.currentPid??process.pid,t=r.pidFilePath??u$,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(!or(a.pid)){r.registry.unregister(a.id);continue}try{await cT(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 oT(i,5e3);let s=i.filter(a=>or(a.pid));for(let a of s)try{await cT(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 oT(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);d$(t,e),r.registry.pruneDeadEntries()}function d$(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 oT(r,e){let t=Date.now()+e;for(;Date.now()<t;){if(r.filter(i=>or(i.pid)).length===0)return;await new Promise(i=>setTimeout(i,100))}}async function cT(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 p$();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 l$("taskkill",s,{timeout:uo.POWERSHELL_COMMAND,windowsHide:!0})}async function p$(){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 lT,Cs,uT,l$,u$,pT=M(()=>{"use strict";lT=require("child_process"),Cs=require("fs"),uT=require("util");ge();Ty();js();Jr();l$=(0,uT.promisify)(lT.execFile),u$=$e.workerPid()});function f$(){let e=Ll().pruneDeadEntries();e>0&&_.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function mT(){Ds===null&&(Ds=setInterval(f$,fT),Ds.unref(),_.debug("SYSTEM","Health checker started",{intervalMs:fT}))}function hT(){Ds!==null&&(clearInterval(Ds),Ds=null,_.debug("SYSTEM","Health checker stopped"))}var fT,Ds,yT=M(()=>{"use strict";ge();js();fT=3e4,Ds=null});function bT(){return h$}function y$(r={}){let e=r.pidFilePath??m$;if(!(0,ji.existsSync)(e))return"missing";let t=null;try{t=JSON.parse((0,ji.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,ji.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,ji.rmSync)(e,{force:!0}),"stale")}var ji,m$,Ay,h$,gT=M(()=>{"use strict";ji=require("fs");ge();js();pT();yT();Jr();m$=$e.workerPid(),Ay=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(),y$({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,mT()}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}hT(),this.stopPromise=dT({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}},h$=new Ay(Ll())});function Ky(r,e,t){r.on("finish",async()=>{try{await t()}finally{process.exit(0)}}),r.json(e)}var vT=M(()=>{"use strict"});function Oy(r,e=Date.now){return Math.max(0,Math.floor((e()-r)/1e3))}var ET=M(()=>{"use strict"});var Ry,xT,_de,ST=M(()=>{"use strict";Ry=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")}getAll(){return Array.from(this.entries.values()).sort((e,t)=>t.observedAt-e.observedAt)}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}clear(){this.entries.clear()}},xT=new Ry,_de=900*1e3});function v$(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 _T,kT,Cy,po,TT,b$,jy,wT,g$,IT,ql,AT=M(()=>{"use strict";_T=ct(Dl(),1),kT=ct(require("http"),1),Cy=ct(require("fs"),1),po=ct(require("path"),1);Fk();ge();Zk();nT();gT();js();Nl();vT();ET();ST();TT=po.default.resolve(__dirname,"../skills/mem-search"),b$=po.default.join(TT,"operations"),jy=po.default.join(TT,"SKILL.md"),wT=(()=>{try{let r=Cy.readFileSync(jy,"utf-8");return _.info("SYSTEM","Cached SKILL.md at boot",{path:jy,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:jy,message:r instanceof Error?r.message:String(r)}),null}})(),g$=(()=>{let r=new Map;for(let e of uy){let t=po.default.join(b$,`${e}.md`);try{r.set(e,Cy.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})(),IT="13.6.0";ql=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,_T.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=kT.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(rT),this.app.use(tT)}setupMiddleware(){by(gy,{includeCors:!1}).forEach(t=>this.app.use(t))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,t,n)=>{v$(t),n()})}setupCors(){this.app.use(Ml())}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:IT,workerPath:this.options.workerPath,uptime:Oy(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:xT.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:IT})}),this.app.get("/api/instructions",(e,t)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!qk.includes(n))return t.status(400).json({error:"Invalid topic"});if(i&&!uy.includes(i))return t.status(400).json({error:"Invalid operation"});if(i){let a=g$.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(wT===null)return _.debug("HTTP","SKILL.md not cached at boot",{topic:n}),t.status(404).json({error:"Instruction not found"});let s=this.extractInstructionSection(wT,n);t.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",co,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"})):Ky(t,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",co,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})):Ky(t,{status:"shutting_down"},()=>this.options.onShutdown(n))}),this.app.get("/api/admin/doctor",co,(e,t)=>{let a=bT().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:or(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=>Ey.has(f)||vy.some(m=>f.startsWith(m))),l=Oy(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,E$,x$,Dy,KT=M(()=>{"use strict";Jt=require("zod"),E$=Jt.z.enum(["hook","worker","provider","server","api"]),x$=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:E$,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()}),Dy=x$.omit({id:!0,createdAtEpoch:!0}).partial({serverSessionId:!0,platformSource:!0,payload:!0,contentSessionId:!0,memorySessionId:!0})});function qe(){return(0,Fl.randomUUID)()}function ze(r){return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}function OT(r){return Array.isArray(r)?r:[]}function ve(r){return typeof r=="number"?r:new Date(r).getTime()}function cr(r){return r==null?null:r instanceof Date?r:new Date(r)}async function Y(r,e,t=[]){return(await r.query(e,t)).rows[0]??null}async function _r(r,e,t){if(!await Y(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 Y(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 fo(r){return JSON.stringify(Py(r))}function kr(r){return(0,Fl.createHash)("sha256").update(fo(r)).digest("hex")}function Py(r){if(Array.isArray(r))return r.map(Py);if(r&&typeof r=="object"){let e=r;return Object.keys(e).sort().reduce((t,n)=>(t[n]=Py(e[n]),t),{})}return r}var Fl,Gr=M(()=>{"use strict";Fl=require("crypto")});function RT(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(),fo(r.payload??{})])}`}function My(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 lr,Ps=M(()=>{"use strict";Gr();lr=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=RT(e),n=await Y(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