claude-mem 13.5.2 → 13.5.3

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.2",
3
+ "version": "13.5.3",
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 cb(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 pb});import{join as De,dirname as PW,basename as NW}from"path";import{homedir as VO}from"os";import{existsSync as MW,mkdirSync as yye,readFileSync as LW}from"fs";import{execSync as bye}from"child_process";import{fileURLToPath as UW}from"url";function FW(){return typeof __dirname<"u"?__dirname:PW(UW(import.meta.url))}function Ti(){if(process.env.CLAUDE_MEM_DATA_DIR)return process.env.CLAUDE_MEM_DATA_DIR;let t=De(VO(),".claude-mem"),e=De(t,"settings.json");try{if(MW(e)){let r=JSON.parse(LW(e,"utf-8")),i=r.env??r;if(i.CLAUDE_MEM_DATA_DIR)return i.CLAUDE_MEM_DATA_DIR}}catch{}return t}var Sye,Ne,Rs,Pl,JW,$W,qW,zW,GW,ht,Iye,BW,WO,xye,wye,kye,_ye,ft,at=E(()=>{"use strict";dt();Sye=FW();Ne=Ti(),Rs=process.env.CLAUDE_CONFIG_DIR||De(VO(),".claude"),Pl=De(Rs,"plugins","marketplaces","thedotmack"),JW=De(Ne,"archives"),$W=De(Ne,"logs"),qW=De(Ne,"trash"),zW=De(Ne,"backups"),GW=De(Ne,"modes"),ht=De(Ne,"settings.json"),Iye=De(Ne,"claude-mem.db"),BW=De(Ne,"vector-db"),WO=De(Ne,"observer-sessions"),xye=NW(WO),wye=De(Rs,"settings.json"),kye=De(Rs,"commands"),_ye=De(Rs,"CLAUDE.md"),ft={dataDir:()=>Ne,workerPid:()=>De(Ne,"worker.pid"),serverBetaPid:()=>De(Ne,".server-beta.pid"),serverBetaPort:()=>De(Ne,".server-beta.port"),serverBetaRuntime:()=>De(Ne,".server-beta.runtime.json"),settings:()=>De(Ne,"settings.json"),database:()=>De(Ne,"claude-mem.db"),chroma:()=>De(Ne,"chroma"),combinedCerts:()=>De(Ne,"combined_certs.pem"),transcriptsConfig:()=>De(Ne,"transcript-watch.json"),transcriptsState:()=>De(Ne,"transcript-watch-state.json"),corpora:()=>De(Ne,"corpora"),supervisorRegistry:()=>De(Ne,"supervisor.json"),envFile:()=>De(Ne,".env"),logsDir:()=>$W,archives:()=>JW,trash:()=>qW,backups:()=>zW,modes:()=>GW,vectorDb:()=>BW,observerSessions:()=>WO}});import{join as ZO}from"path";import{mkdirSync as VW,writeFileSync as WW}from"fs";import{randomUUID as ZW}from"crypto";function HW(t){let e=t.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function mb(t,e){if(HW(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 YO(t,e){return mb(t,e).enabled}function Nl(){return ZO(Ti(),HO)}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=Ti();VW(e,{recursive:!0}),WW(ZO(e,HO),JSON.stringify(t,null,2)+`
97
- `)}function bd(){let t=Ci();if(t?.installId)return t.installId;let e=ZW();return Ks({installId:e,decidedAt:""}),e}var HO,vd=E(()=>{"use strict";at();ws();HO="telemetry.json"});function QO(t){let e={};try{if(!t||typeof t!="object")return e;for(let r of Object.keys(t)){if(!YW.has(r))continue;let i=t[r];typeof i=="string"?e[r]=i.length>XO?i.slice(0,XO):i:(typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean")&&(e[r]=i)}}catch{}return e}var YW,XO,eA=E(()=>{"use strict";YW=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"]),XO=200});import tA from"os";function rA(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||QW}function nA(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||e3}function iA(t){let e={};for(let r of t3)t[r]!==void 0&&(e[r]=t[r]);return e}function r3(){try{return tA.release()}catch{return"unknown"}}function n3(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||tA.release().toLowerCase().includes("microsoft")}catch{return!1}}function oA(){return{version:XW,os:process.platform,os_version:r3(),is_wsl:n3(),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 XW,QW,e3,t3,sA=E(()=>{"use strict";XW="13.5.2",QW="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",e3="https://us.i.posthog.com";t3=["version","os","os_version","is_wsl","arch","runtime","locale","ide","provider","runtime_mode","install_method","claude_code_version"]});async function Ml(t,e,r){try{if(!YO(process.env,Ci()))return;let i=QO({...oA(),...e??{}});if(r?.person?i.$set=iA(i):i.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:t,properties:i})+`
97
+ `)}function bd(){let t=Ci();if(t?.installId)return t.installId;let e=ZW();return Ks({installId:e,decidedAt:""}),e}var HO,vd=E(()=>{"use strict";at();ws();HO="telemetry.json"});function QO(t){let e={};try{if(!t||typeof t!="object")return e;for(let r of Object.keys(t)){if(!YW.has(r))continue;let i=t[r];typeof i=="string"?e[r]=i.length>XO?i.slice(0,XO):i:(typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean")&&(e[r]=i)}}catch{}return e}var YW,XO,eA=E(()=>{"use strict";YW=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"]),XO=200});import tA from"os";function rA(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||QW}function nA(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||e3}function iA(t){let e={};for(let r of t3)t[r]!==void 0&&(e[r]=t[r]);return e}function r3(){try{return tA.release()}catch{return"unknown"}}function n3(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||tA.release().toLowerCase().includes("microsoft")}catch{return!1}}function oA(){return{version:XW,os:process.platform,os_version:r3(),is_wsl:n3(),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 XW,QW,e3,t3,sA=E(()=>{"use strict";XW="13.5.3",QW="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",e3="https://us.i.posthog.com";t3=["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 Ml(t,e,r){try{if(!YO(process.env,Ci()))return;let i=QO({...oA(),...e??{}});if(r?.person?i.$set=iA(i):i.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:t,properties:i})+`
98
98
  `);return}let n=rA();if(!n)return;let o=new AbortController,s=setTimeout(()=>o.abort(),i3);try{await fetch(`${nA()}/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 i3,fb=E(()=>{"use strict";vd();eA();sA();i3=2e3});import{spawn as o3}from"node:child_process";function an(t,e,r){return o3(t,e??[],{windowsHide:!0,...r})}var Ds=E(()=>{"use strict"});function Ro(t){return process.platform==="win32"?Math.round(t*St.WINDOWS_MULTIPLIER):t}var St,js=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 dA={};_e(dA,{SettingsDefaultsManager:()=>tt});import{readFileSync as s3,writeFileSync as aA,existsSync as lA,mkdirSync as a3}from"fs";import{join as cA,dirname as l3}from"path";import{homedir as uA}from"os";var tt,ln=E(()=>{"use strict";js();tt=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:cA(uA(),".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:cA(uA(),".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(!lA(e)){let a=this.getAllDefaults();try{let l=l3(e);lA(l)||a3(l,{recursive:!0}),aA(e,JSON.stringify(a,null,2),"utf-8"),console.log("[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=s3(e,"utf-8"),n=JSON.parse(i.replace(/^\uFEFF/,"")),o=n;if(n.env&&typeof n.env=="object"){o=n.env;try{aA(e,JSON.stringify(o,null,2),"utf-8"),console.log("[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 c3}from"child_process";import{promisify as u3}from"util";import{existsSync as Yye,readFileSync as Xye,writeFileSync as Qye,mkdirSync as ege,unlinkSync as tge}from"fs";import{userInfo as nge}from"os";import{join as oge}from"path";var lge,pA=E(()=>{"use strict";at();dt();lge=u3(c3)});import{existsSync as hb,readFileSync as fA,writeFileSync as d3,mkdirSync as p3,chmodSync as mA}from"fs";function yb(){return process.env.CLAUDE_MEM_ENV_FILE??ft.envFile()}function hA(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 m3(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
  `)+`
@@ -549,7 +549,7 @@ claude-mem installed successfully!`)),await Ml("install_completed",{ide:d.join("
549
549
  `),"Note"),await Ml("uninstall_completed",{},{person:!0}),sn(rr.default.green("claude-mem has been uninstalled."))}var rr,PL=E(()=>{"use strict";gd();rr=lr(Bn(),1);Ii();ws();ln();at();nx();tx();fb()});import{spawnSync as ste}from"child_process";import{existsSync as ate}from"fs";import{homedir as Xw}from"os";import{join as Qw}from"path";function lte(){return on?[Qw(Xw(),".bun","bin","bun.exe"),Qw(process.env.USERPROFILE||Xw(),".bun","bin","bun.exe")]:[Qw(Xw(),".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun"]}function NL(){let e=ste(on?"where":"which",["bun"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:on});if(e.status===0&&e.stdout.trim())return"bun";for(let r of lte())if(ate(r))return r;return null}var ML=E(()=>{"use strict";Ii()});var ii={};_e(ii,{runAdoptCommand:()=>ute,runCleanupCommand:()=>dte,runRestartCommand:()=>lk,runSearchCommand:()=>pte,runServerApiKeyCommand:()=>uk,runServerBetaRestartCommand:()=>nk,runServerBetaStartCommand:()=>tk,runServerBetaStatusCommand:()=>ik,runServerBetaStopCommand:()=>rk,runServerBetaWorkerStartCommand:()=>ok,runStartCommand:()=>sk,runStatusCommand:()=>ck,runStopCommand:()=>ak,runTranscriptWatchCommand:()=>mte});import{existsSync as yf}from"fs";import{join as ek}from"path";function au(){Os()||(console.error(xt.default.red("claude-mem is not installed.")),console.error(`Run: ${xt.default.bold("npx claude-mem install")}`),process.exit(1))}function gf(){let t=NL();return t||(console.error(xt.default.red("Bun not found.")),console.error("Install Bun: https://bun.sh"),console.error("After installation, restart your terminal."),process.exit(1)),t}function LL(){return ek(st(),"plugin","scripts","worker-service.cjs")}function cte(){return ek(st(),"plugin","scripts","server-beta-service.cjs")}function Zo(t,e=[]){au();let r=gf(),i=LL();yf(i)||(console.error(xt.default.red(`Worker script not found at: ${i}`)),console.error("The installation may be corrupted. Try: npx claude-mem install"),process.exit(1));let n=[i,t,...e],o=an(r,n,{stdio:"inherit",cwd:st(),env:kn(process.env)});o.on("error",s=>{console.error(xt.default.red(`Failed to start Bun: ${s.message}`)),process.exit(1)}),o.on("close",s=>{process.exit(s??0)})}function lu(t,e=[]){au();let r=gf(),i=cte();yf(i)||(console.error(xt.default.red(`Server beta script not found at: ${i}`)),console.error("The installation may be corrupted. Try: npx claude-mem install"),process.exit(1));let n=an(r,[i,t,...e],{stdio:"inherit",cwd:st(),env:kn(process.env)});n.on("error",o=>{console.error(xt.default.red(`Failed to start Bun: ${o.message}`)),process.exit(1)}),n.on("close",o=>{process.exit(o??0)})}function tk(){lu("start")}function rk(){lu("stop")}function nk(){lu("restart")}function ik(){lu("status")}function ok(){lu("worker",["start"])}function sk(){Zo("start")}function ak(){Zo("stop")}function lk(){Zo("restart")}function ck(){Zo("status")}function uk(t=[]){Zo("server",["api-key",...t])}function ute(t=[]){au();let e=gf(),r=LL();yf(r)||(console.error(xt.default.red(`Worker script not found at: ${r}`)),console.error("The installation may be corrupted. Try: npx claude-mem install"),process.exit(1));let i=process.cwd(),n=[r,"adopt","--cwd",i,...t],o=an(e,n,{stdio:"inherit",cwd:st(),env:kn(process.env)});o.on("error",s=>{console.error(xt.default.red(`Failed to start Bun: ${s.message}`)),process.exit(1)}),o.on("close",s=>{process.exit(s??0)})}function dte(t=[]){Zo("cleanup",t)}async function pte(t){au();let e=t.join(" ").trim();e||(console.error(xt.default.red("Usage: npx claude-mem search <query>")),process.exit(1));let i=`http://127.0.0.1:${tt.get("CLAUDE_MEM_WORKER_PORT")}/api/search?query=${encodeURIComponent(e)}`,n;try{n=await fetch(i)}catch(s){let a=s instanceof Error?s.message:String(s);((s instanceof Error?s.cause:void 0)?.code==="ECONNREFUSED"||a.includes("ECONNREFUSED"))&&(console.error(xt.default.red("Worker is not running.")),console.error(`Start it with: ${xt.default.bold("npx claude-mem start")}`),process.exit(1)),console.error(xt.default.red(`Search failed: ${a}`)),process.exit(1)}n.ok||(n.status===404&&(console.error(xt.default.red("Search endpoint not found. Is the worker running?")),console.error(`Try: ${xt.default.bold("npx claude-mem start")}`),process.exit(1)),console.error(xt.default.red(`Search failed: HTTP ${n.status}`)),process.exit(1));let o;try{o=await n.json()}catch(s){let a=s instanceof Error?s.message:String(s);console.error(xt.default.red(`Search failed: invalid JSON response (${a})`)),process.exit(1)}console.log(typeof o=="object"&&o!==null?JSON.stringify(o,null,2):o)}function mte(){au();let t=gf(),e=ek(st(),"plugin","scripts","transcript-watcher.cjs");if(!yf(e)){Zo("transcript",["watch"]);return}let r=an(t,[e,"watch"],{stdio:"inherit",cwd:st(),env:kn(process.env)});r.on("error",i=>{console.error(xt.default.red(`Failed to start transcript watcher: ${i.message}`)),process.exit(1)}),r.on("close",i=>{process.exit(i??0)})}var xt,jn=E(()=>{"use strict";Ds();Ed();xt=lr(Bn(),1);ML();Ii();ln()});var $L={};_e($L,{runDoctorCommand:()=>gte});import{existsSync as UL,readFileSync as fte}from"fs";import{join as FL}from"path";import{spawnSync as hte}from"child_process";function JL(t){try{let e=hte(t,["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:yte});return e.status===0?e.stdout.trim():null}catch{return null}}async function gte(){let t=[],e=Ti(),r=JL("bun");t.push({name:"Bun runtime",status:r?"ok":"fail",detail:r?`v${r.replace(/^v/,"")}`:"not found on PATH \u2014 install: https://bun.sh",required:!0});let i=JL("uv");t.push({name:"uv (vector search)",status:i?"ok":"warn",detail:i||"not found \u2014 vector/semantic search disabled until installed",required:!1});let n=Os();t.push({name:"Plugin installed",status:n?"ok":"fail",detail:n?st():"run `npx claude-mem install`",required:!0});let o=FL(st(),"node_modules"),s=UL(o);t.push({name:"Marketplace deps",status:n?s?"ok":"fail":"warn",detail:s?"node_modules present":"missing \u2014 run `npx claude-mem repair`",required:n});let a=tt.get("CLAUDE_MEM_WORKER_PORT"),l="fail",c=`no response on port ${a} \u2014 start with \`npx claude-mem start\``;try{let p=await fetch(`http://127.0.0.1:${a}/api/health`,{signal:AbortSignal.timeout(3e3)});p.ok?(l="ok",c=`healthy at http://127.0.0.1:${a}`):(l="warn",c=`reachable but unhealthy (HTTP ${p.status}) on port ${a}`)}catch{}t.push({name:"Worker daemon",status:l,detail:c,required:!1});let u=FL(e,"last-install-error.json");if(UL(u)){let p=`present at ${u}`;try{let f=JSON.parse(fte(u,"utf-8"));f&&typeof f=="object"&&(p=`${f.categoryId??"error"}: ${f.remediation??p}`)}catch{}t.push({name:"Last install error",status:"warn",detail:p,required:!1})}let d=p=>p==="ok"?Xi.default.green("\u2713"):p==="warn"?Xi.default.yellow("!"):Xi.default.red("\u2717");console.log(Xi.default.bold(`
550
550
  claude-mem doctor
551
551
  `));for(let p of t)console.log(` ${d(p.status)} ${p.name.padEnd(22)} ${Xi.default.dim(p.detail)}`);let m=t.filter(p=>p.required&&p.status==="fail");console.log(""),m.length===0?(console.log(Xi.default.green("All required checks passed.")),process.exit(0)):(console.log(Xi.default.red(`${m.length} required check(s) failed \u2014 see remediation above.`)),process.exit(1))}var Xi,yte,qL=E(()=>{"use strict";Xi=lr(Bn(),1);Ii();ln();at();yte=process.platform==="win32"});var zL={};_e(zL,{runTelemetryCommand:()=>kte});function Ste(){console.error(`Usage: ${pt.default.bold("npx claude-mem telemetry [status|enable|disable]")}`),console.error(" status Show whether telemetry is on and which setting decided it (default)"),console.error(" enable Turn anonymous usage analytics back on (interactive)"),console.error(" disable Opt out of telemetry"),console.error(`Docs: ${bf}`)}function Ite(){let t=Ci(),{enabled:e,source:r}=mb(process.env,t),i=e?pt.default.green("ENABLED"):pt.default.yellow("DISABLED");console.log(`${pt.default.bold("Telemetry:")} ${i}`),console.log(`${pt.default.bold("Decided by:")} ${Ete[r]}`),t?.installId?console.log(`${pt.default.bold("Install ID:")} ${t.installId} ${pt.default.dim("(random UUID, not tied to you)")}`):console.log(t?`${pt.default.bold("Install ID:")} ${pt.default.dim("none recorded")}`:`${pt.default.bold("Install ID:")} ${pt.default.dim("none (no telemetry config has been written)")}`),console.log(`${pt.default.bold("Config file:")} ${Nl()}`),console.log(`${pt.default.bold("Docs:")} ${bf}`)}async function xte(){process.stdin.isTTY||(console.error(pt.default.red("telemetry enable requires an interactive terminal (consent prompt).")),console.error(`Read what is collected first: ${bf}`),process.exit(1)),Ao(pt.default.bgBlue(pt.default.white(" claude-mem telemetry "))),_i(["Anonymous events only, identified by a random install UUID:",...vte.map(r=>` ${r}`),"","Each event carries ONLY these fields:",...bte.map(r=>` ${r}`),"","NEVER collected \u2014 not now, not ever:"," prompts or conversation content, file paths, source code,"," project names, git remotes, search queries, error messages,"," IP addresses, hardware IDs, env values, emails.","",`Full details: ${bf}`].join(`
552
- `),"What telemetry collects"),process.env.DO_NOT_TRACK&&process.env.DO_NOT_TRACK!=="0"&&process.env.DO_NOT_TRACK!=="false"&&Ge.warn("DO_NOT_TRACK is set in your environment. It overrides everything: telemetry will remain OFF even after enabling here.");let t=await ki({message:"Enable anonymous usage telemetry?",initialValue:!0});if(ze(t)||!t){Zt("Telemetry remains disabled. Nothing was written.");return}let e=bd();Ks({enabled:!0,installId:e,decidedAt:new Date().toISOString()}),Ge.success(`Telemetry enabled. Config: ${Nl()}`),sn(`Change your mind anytime: ${pt.default.cyan("npx claude-mem telemetry disable")}`)}function wte(){let t=Ci();Ks({enabled:!1,installId:t?.installId??"",decidedAt:new Date().toISOString()}),console.log(pt.default.green("Telemetry disabled.")),console.log(`${pt.default.bold("Config file:")} ${Nl()}`)}async function kte(t=[]){let e=t[0]?.toLowerCase()??"status";switch(e){case"status":Ite();break;case"enable":await xte();break;case"disable":wte();break;default:console.error(pt.default.red(`Unknown telemetry subcommand: ${e}`)),Ste(),process.exit(1)}}var pt,bf,bte,vte,Ete,GL=E(()=>{"use strict";gd();pt=lr(Bn(),1);vd();bf="https://docs.claude-mem.ai/telemetry",bte=["version claude-mem version (e.g. 13.4.2)","os platform (darwin / linux / win32)","os_version OS kernel release (e.g. 10.0.22631)","is_wsl whether running under WSL","arch CPU architecture (arm64 / x64)","runtime bun or node","runtime_version runtime version string","node_version Node.js version string","duration_ms how long an operation took","outcome ok / error / partial","error_category coarse error bucket (never a message)","locale language tag (e.g. en-US)","is_ci whether running in CI","endpoint which claude-mem search route (our route names)","ide installer IDE choice (claude-code / cursor / ...)","provider LLM provider choice (claude / gemini / openrouter)","runtime_mode worker or server","trigger start or heartbeat","count integer volume (e.g. observations stored)","has_summary whether a compression produced a summary","is_update whether an install was an update","interactive whether the installer ran in a TTY","install_method npm / bun / pnpm / yarn (launcher of the CLI)","bun_version / uv_version / claude_code_version"," toolchain versions detected during install","mode active claude-mem mode id","model model id used for compression","hook compression trigger (init / ingest / summarize)","observation_type / obs_type_* observation type buckets (counts only)","compression_ms / tokens_input / tokens_output / compression_ratio"," latency + real token usage of one compression call","observation_count / session_count / timeline_depth_days / has_session_summary"," depth of one context injection","tokens_injected / tokens_saved_vs_naive / search_strategy"," token economics of one context injection"],vte=["install_completed","install_failed","uninstall_completed","worker_started","session_compressed","context_injected","search_performed","error_occurred"],Ete={DO_NOT_TRACK:"DO_NOT_TRACK environment variable",env:"CLAUDE_MEM_TELEMETRY environment variable",config:"telemetry.json config file",default:"default (on \u2014 no opt-out recorded)"}});function BL(t){return t.sourceEventId?`agent_event:v1:${mn([t.teamId,t.projectId,t.sourceAdapter,t.sourceEventId])}`:`agent_event:v1:${mn([t.teamId,t.projectId,t.sourceAdapter,t.contentSessionId??t.serverSessionId??null,t.eventType,new Date(t.occurredAt).toISOString(),iu(t.payload??{})])}`}function dk(t){return{id:t.id,projectId:t.project_id,teamId:t.team_id,serverSessionId:t.server_session_id,sourceAdapter:t.source_adapter,sourceEventId:t.source_event_id,idempotencyKey:t.idempotency_key,eventType:t.event_type,platformSource:t.platform_source,payload:t.payload,metadata:yt(t.metadata),occurredAtEpoch:Ue(t.occurred_at),receivedAtEpoch:Ue(t.received_at),createdAtEpoch:Ue(t.created_at)}}var cu,pk=E(()=>{"use strict";Hi();cu=class{constructor(e){this.client=e}client;async create(e){await pn(this.client,e.projectId,e.teamId),e.serverSessionId&&await ri(this.client,e.serverSessionId,e.projectId,e.teamId);let r=BL(e),i=await ue(this.client,`
552
+ `),"What telemetry collects"),process.env.DO_NOT_TRACK&&process.env.DO_NOT_TRACK!=="0"&&process.env.DO_NOT_TRACK!=="false"&&Ge.warn("DO_NOT_TRACK is set in your environment. It overrides everything: telemetry will remain OFF even after enabling here.");let t=await ki({message:"Enable anonymous usage telemetry?",initialValue:!0});if(ze(t)||!t){Zt("Telemetry remains disabled. Nothing was written.");return}let e=bd();Ks({enabled:!0,installId:e,decidedAt:new Date().toISOString()}),Ge.success(`Telemetry enabled. Config: ${Nl()}`),sn(`Change your mind anytime: ${pt.default.cyan("npx claude-mem telemetry disable")}`)}function wte(){let t=Ci();Ks({enabled:!1,installId:t?.installId??"",decidedAt:new Date().toISOString()}),console.log(pt.default.green("Telemetry disabled.")),console.log(`${pt.default.bold("Config file:")} ${Nl()}`)}async function kte(t=[]){let e=t[0]?.toLowerCase()??"status";switch(e){case"status":Ite();break;case"enable":await xte();break;case"disable":wte();break;default:console.error(pt.default.red(`Unknown telemetry subcommand: ${e}`)),Ste(),process.exit(1)}}var pt,bf,bte,vte,Ete,GL=E(()=>{"use strict";gd();pt=lr(Bn(),1);vd();bf="https://docs.claude-mem.ai/telemetry",bte=["version claude-mem version (e.g. 13.4.2)","os platform (darwin / linux / win32)","os_version OS kernel release (e.g. 10.0.22631)","is_wsl whether running under WSL","arch CPU architecture (arm64 / x64)","runtime bun or node","runtime_version runtime version string","node_version Node.js version string","duration_ms how long an operation took","outcome ok / error / partial","error_category coarse error bucket (never a message)","locale language tag (e.g. en-US)","is_ci whether running in CI","endpoint which claude-mem search route (our route names)","ide installer IDE choice (claude-code / cursor / ...)","provider LLM provider choice (claude / gemini / openrouter)","runtime_mode worker or server","trigger start or heartbeat","count integer volume (e.g. observations stored)","has_summary whether a compression produced a summary","is_update whether an install was an update","interactive whether the installer ran in a TTY","install_method npm / bun / pnpm / yarn (launcher of the CLI)","bun_version / uv_version / claude_code_version"," toolchain versions detected during install","mode active claude-mem mode id","model model id used for compression","hook compression trigger (init / ingest / summarize)","observation_type / obs_type_* observation type buckets (counts only)","compression_ms / tokens_input / tokens_output / compression_ratio"," latency + real token usage of one compression call","cost_usd provider-reported cost of one compression call (USD)","endpoint_class openrouter.ai vs custom gateway (enum)","observation_count / session_count / timeline_depth_days / has_session_summary"," depth of one context injection","tokens_injected / tokens_saved_vs_naive / search_strategy"," token economics of one context injection","db_observation_count / db_session_count / db_summary_count / db_project_count"," total rows in your local memory DB (counts only)","db_size_mb memory database file size in MB","install_age_days / days_since_last_obs / obs_count_7d / obs_count_30d"," install age and recent activity, in days/counts"],vte=["install_completed","install_failed","uninstall_completed","worker_started","session_compressed","context_injected","search_performed","error_occurred"],Ete={DO_NOT_TRACK:"DO_NOT_TRACK environment variable",env:"CLAUDE_MEM_TELEMETRY environment variable",config:"telemetry.json config file",default:"default (on \u2014 no opt-out recorded)"}});function BL(t){return t.sourceEventId?`agent_event:v1:${mn([t.teamId,t.projectId,t.sourceAdapter,t.sourceEventId])}`:`agent_event:v1:${mn([t.teamId,t.projectId,t.sourceAdapter,t.contentSessionId??t.serverSessionId??null,t.eventType,new Date(t.occurredAt).toISOString(),iu(t.payload??{})])}`}function dk(t){return{id:t.id,projectId:t.project_id,teamId:t.team_id,serverSessionId:t.server_session_id,sourceAdapter:t.source_adapter,sourceEventId:t.source_event_id,idempotencyKey:t.idempotency_key,eventType:t.event_type,platformSource:t.platform_source,payload:t.payload,metadata:yt(t.metadata),occurredAtEpoch:Ue(t.occurred_at),receivedAtEpoch:Ue(t.received_at),createdAtEpoch:Ue(t.created_at)}}var cu,pk=E(()=>{"use strict";Hi();cu=class{constructor(e){this.client=e}client;async create(e){await pn(this.client,e.projectId,e.teamId),e.serverSessionId&&await ri(this.client,e.serverSessionId,e.projectId,e.teamId);let r=BL(e),i=await ue(this.client,`
553
553
  INSERT INTO agent_events (
554
554
  id, project_id, team_id, server_session_id, source_adapter,
555
555
  source_event_id, idempotency_key, event_type, platform_source, payload, metadata, occurred_at
@@ -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.2",
6
+ "version": "13.5.3",
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.2",
3
+ "version": "13.5.3",
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.2",
3
+ "version": "13.5.3",
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.2",
3
+ "version": "13.5.3",
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.2",
3
+ "version": "13.5.3",
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 x_=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"]),vP=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),bP=512*1024;async function*P_(t,e,r=20,n){if(r<=0)return;let o;try{o=await(0,Cr.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!=="."||vP.has(s.name))continue;let i=(0,Kn.join)(t,s.name);if(s.isDirectory())yield*P_(i,e,r-1,n);else if(s.isFile()){let a=s.name.slice(s.name.lastIndexOf("."));(x_.has(a)||n&&n.has(a))&&(yield i)}}}async function EP(t){try{let e=await(0,Cr.stat)(t);if(e.size>bP||e.size===0)return null;let r=await(0,Cr.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 T_(t,e,r={}){let n=r.maxResults||20,o=e.toLowerCase(),s=o.split(/[\s_\-./]+/).filter(E=>E.length>0),i=r.projectRoot||t,a=Gn(i),c=new Set;for(let E of Object.values(a.grammars))for(let v of E.extensions)x_.has(v)||c.add(v);let u=[];for await(let E of P_(t,t,20,c.size>0?c:void 0)){if(r.filePattern&&!(0,Kn.relative)(t,E).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let v=await EP(E);v&&u.push({absolutePath:E,relativePath:(0,Kn.relative)(t,E),content:v})}let l=w_(u,i),d=[],p=[],f=0;for(let[E,v]of l){f+=wP(v);let $=Ns(E.toLowerCase(),s)>0,Se=[],we=(Lt,tr)=>{for(let ce of Lt){let bt=0,Be="",Dr=Ns(ce.name.toLowerCase(),s);Dr>0&&(bt+=Dr*3,Be="name match"),ce.signature.toLowerCase().includes(o)&&(bt+=2,Be=Be?`${Be} + signature`:"signature match"),ce.jsdoc&&ce.jsdoc.toLowerCase().includes(o)&&(bt+=1,Be=Be?`${Be} + jsdoc`:"jsdoc match"),bt>0&&($=!0,Se.push({filePath:E,symbolName:tr?`${tr}.${ce.name}`:ce.name,kind:ce.kind,signature:ce.signature,jsdoc:ce.jsdoc,lineStart:ce.lineStart,lineEnd:ce.lineEnd,matchReason:Be})),ce.children&&we(ce.children,ce.name)}};we(v.symbols),$&&(d.push(v),p.push(...Se))}p.sort((E,v)=>{let x=Ns(E.symbolName.toLowerCase(),s);return Ns(v.symbolName.toLowerCase(),s)-x});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 Ns(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 wP(t){let e=t.symbols.length;for(let r of t.symbols)r.children&&(e+=r.children.length);return e}function z_(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(Mr(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 bu=require("node:fs/promises"),js=require("node:fs"),et=require("node:path"),D_=require("node:os"),j_=require("node:url");var kP=St(ae.API_REQUEST),Ve=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)}},Ds=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=$P(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??kP}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 Ve("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 Ve("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 Ve("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 au(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new Ve(l?"timeout":"transport",`Server beta ${e} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new Ve("http_error",`Server beta ${e} ${r} returned ${i.status}: ${xP(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 Ve("invalid_response",`Server beta ${e} ${r} returned non-JSON response`,{cause:c})}}};function R_(t){return t instanceof Ve}function $P(t){return t.replace(/\/+$/,"")}function xP(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Su(){return(xs().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase()==="server-beta"?"server-beta":"worker"}function I_(){let t=xs(),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 Ds(o),projectId:n,serverBaseUrl:e}}var qP={},PP="13.5.2";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var L_=!1,U_=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,et.dirname)((0,j_.fileURLToPath)(qP.url))}catch{return L_=!0,process.cwd()}})(),Eu=(0,et.resolve)(U_,"worker-service.cjs");function TP(){L_&&((0,js.existsSync)(Eu)||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:Eu,mcpServerDir:U_}))}var O_={search:"/api/search",timeline:"/api/timeline"};async function vu(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 As(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 zP(t,e){let r=await As(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 Nr(t,e){y.debug("HTTP","Worker API request (POST)",void 0,{endpoint:t});try{return await zP(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 RP(){try{return(await As("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}function IP(){if(Su()!=="server-beta")return null;let e=I_();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 Yn(t){return R_(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 Xn(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function Qn(t){let e=IP();if(!e)throw new Ve("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 Ve("missing_api_key",`${t}: ${e.reason}`);return e}async function A_(t){try{let e=Qn("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 Xn(o)}catch(e){return Yn(e)}}async function OP(t){try{let e=Qn("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 Xn(o)}catch(e){return Yn(e)}}async function M_(t){try{let e=Qn("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 Xn(o)}catch(e){return Yn(e)}}async function C_(t){try{let e=Qn("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 Xn(o)}catch(e){return Yn(e)}}async function AP(t){try{let e=Qn("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 Xn(n)}catch(e){return Yn(e)}}async function MP(){if(await RP())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),TP();try{let t=uu(),e=await d_(t,Eu);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 q_=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
222
+ `)}var bu=require("node:fs/promises"),js=require("node:fs"),et=require("node:path"),D_=require("node:os"),j_=require("node:url");var kP=St(ae.API_REQUEST),Ve=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)}},Ds=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=$P(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??kP}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 Ve("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 Ve("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 Ve("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 au(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new Ve(l?"timeout":"transport",`Server beta ${e} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new Ve("http_error",`Server beta ${e} ${r} returned ${i.status}: ${xP(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 Ve("invalid_response",`Server beta ${e} ${r} returned non-JSON response`,{cause:c})}}};function R_(t){return t instanceof Ve}function $P(t){return t.replace(/\/+$/,"")}function xP(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Su(){return(xs().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase()==="server-beta"?"server-beta":"worker"}function I_(){let t=xs(),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 Ds(o),projectId:n,serverBaseUrl:e}}var qP={},PP="13.5.3";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var L_=!1,U_=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,et.dirname)((0,j_.fileURLToPath)(qP.url))}catch{return L_=!0,process.cwd()}})(),Eu=(0,et.resolve)(U_,"worker-service.cjs");function TP(){L_&&((0,js.existsSync)(Eu)||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:Eu,mcpServerDir:U_}))}var O_={search:"/api/search",timeline:"/api/timeline"};async function vu(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 As(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 zP(t,e){let r=await As(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 Nr(t,e){y.debug("HTTP","Worker API request (POST)",void 0,{endpoint:t});try{return await zP(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 RP(){try{return(await As("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}function IP(){if(Su()!=="server-beta")return null;let e=I_();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 Yn(t){return R_(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 Xn(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function Qn(t){let e=IP();if(!e)throw new Ve("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 Ve("missing_api_key",`${t}: ${e.reason}`);return e}async function A_(t){try{let e=Qn("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 Xn(o)}catch(e){return Yn(e)}}async function OP(t){try{let e=Qn("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 Xn(o)}catch(e){return Yn(e)}}async function M_(t){try{let e=Qn("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 Xn(o)}catch(e){return Yn(e)}}async function C_(t){try{let e=Qn("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 Xn(o)}catch(e){return Yn(e)}}async function AP(t){try{let e=Qn("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 Xn(n)}catch(e){return Yn(e)}}async function MP(){if(await RP())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),TP();try{let t=uu(),e=await d_(t,Eu);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 q_=[{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){Ey(`[LOGGER] Failed to write to log file: ${f instanceof Error?f.message:String(f)}
60
60
  `)}else Ey(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 Sy});var nT=h((nde,rT)=>{"use strict";var tT=Object.getOwnPropertySymbols,m$=Object.prototype.hasOwnProperty,h$=Object.prototype.propertyIsEnumerable;function y$(r){if(r==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(r)}function b$(){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}}rT.exports=b$()?Object.assign:function(r,e){for(var t,n=y$(r),i,s=1;s<arguments.length;s++){t=Object(arguments[s]);for(var a in t)m$.call(t,a)&&(n[a]=t[a]);if(tT){i=tT(t);for(var o=0;o<i.length;o++)h$.call(t,i[o])&&(n[i[o]]=t[i[o]])}}return n}});var sT=h((ide,iT)=>{(function(){"use strict";var r=nT(),e=fy(),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,L){if(k)I(k);else{var J=r({},t,L),re=null;J.origin&&typeof J.origin=="function"?re=J.origin:J.origin&&(re=function(je,se){se(null,J.origin)}),re?re(g.headers.origin,function(je,se){je||!se?I(je):(J.origin=se,p(J,g,E,I))}):I()}})}}iT.exports=f})()});function Iy(r,e={}){let t=[];e.includeCors!==!1&&t.push(ql()),t.push(wy.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=Ci(),i=oT.default.join(n,"plugin","ui");return t.push(wy.default.static(i)),t}function ql(){return(0,aT.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 fo(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 _y(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 wy,aT,oT,cT=M(()=>{"use strict";wy=ct(Ll(),1),aT=ct(sT(),1),oT=ct(require("path"),1);Ur();ge()});var lT=M(()=>{"use strict";cT()});function uT(r,e,t,n){let i={error:r,message:e};return t&&(i.code=t),n&&(i.details=n),i}function pT(r,e){e.status(404).json(uT("NotFound",`Cannot ${r.method} ${r.path}`))}var Ds,dT,fT=M(()=>{"use strict";ge();Ds=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};dT=(r,e,t,n)=>{let i=r instanceof Ds?r.statusCode:500;_.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:r.message,code:r instanceof Ds?r.code:void 0},r);let s=uT(r.name||"Error",r.message,r instanceof Ds?r.code:void 0,r instanceof Ds?r.details:void 0);t.status(i).json(s)}});var mT=M(()=>{"use strict"});function mo(r=process.env){let e={};for(let[t,n]of Object.entries(r))if(n!==void 0){if(v$.has(t)){e[t]=n;continue}Ty.has(t)||g$.has(t)||ky.some(i=>t.startsWith(i))||(e[t]=n)}return e}var ky,Ty,g$,v$,Fl=M(()=>{"use strict";ky=["CLAUDECODE_","CLAUDE_CODE_"],Ty=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),g$=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"]),v$=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 I$(r){let e=hT.get(r);if(e&&Date.now()-e.capturedAtMs<w$)return e.token;let t=null;try{let n=(0,Ry.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:{...mo(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 hT.set(r,{token:t,capturedAtMs:Date.now()}),t}function Cy(r){if(!Number.isInteger(r)||r<=0)return null;if(process.platform==="linux")try{let e=(0,Gr.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 I$(r);try{let e=(0,Ry.spawnSync)("ps",["-p",String(r),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...mo(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 Fn(r){if(!r||!or(r.pid))return!1;if(!r.startToken)return!0;let e=Cy(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 Jl(){return Ay||(Ay=new jy),Ay}function Ky(){let r=_$.shift();r&&r()}var Ry,Gr,Oy,E$,x$,S$,w$,hT,jy,Ay,_$,Ps=M(()=>{"use strict";Ry=require("child_process");mT();Gr=require("fs"),Oy=ct(require("path"),1);ge();Fl();Ur();E$=5e3,x$=1e3,S$=$e.supervisorRegistry();w$=5e3,hT=new Map;jy=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,Gr.mkdirSync)(Oy.default.dirname(this.registryPath),{recursive:!0}),!(0,Gr.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Gr.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"&&Ky()}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)Ky();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()+E$;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()+x$;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"&&Ky();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,Gr.mkdirSync)(Oy.default.dirname(this.registryPath),{recursive:!0}),(0,Gr.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},Ay=null;_$=[]});function yT(r){return process.platform==="win32"?Math.round(r*ho.WINDOWS_MULTIPLIER):r}var ho,Dy=M(()=>{"use strict";ho={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 ST(r){let e=r.currentPid??process.pid,t=r.pidFilePath??T$,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 gT(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 bT(i,5e3);let s=i.filter(a=>or(a.pid));for(let a of s)try{await gT(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 bT(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);try{(0,ET.rmSync)(t,{force:!0})}catch(a){a instanceof Error?_.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:t},a):_.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:t,error:String(a)})}r.registry.pruneDeadEntries()}async function bT(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 gT(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 A$();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 k$("taskkill",s,{timeout:ho.POWERSHELL_COMMAND,windowsHide:!0})}async function A$(){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 vT,ET,xT,k$,T$,wT=M(()=>{"use strict";vT=require("child_process"),ET=require("fs"),xT=require("util");ge();Dy();Ps();Ur();k$=(0,xT.promisify)(vT.execFile),T$=$e.workerPid()});function K$(){let e=Jl().pruneDeadEntries();e>0&&_.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function _T(){Ms===null&&(Ms=setInterval(K$,IT),Ms.unref(),_.debug("SYSTEM","Health checker started",{intervalMs:IT}))}function kT(){Ms!==null&&(clearInterval(Ms),Ms=null,_.debug("SYSTEM","Health checker stopped"))}var IT,Ms,TT=M(()=>{"use strict";ge();Ps();IT=3e4,Ms=null});function AT(){return j$}function R$(r={}){let e=r.pidFilePath??O$;if(!(0,Di.existsSync)(e))return"missing";let t=null;try{t=JSON.parse((0,Di.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,Di.rmSync)(e,{force:!0}),"invalid"}return Fn(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,Di.rmSync)(e,{force:!0}),"stale")}var Di,O$,Py,j$,KT=M(()=>{"use strict";Di=require("fs");ge();Ps();wT();TT();Ur();O$=$e.workerPid(),Py=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(),R$({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,_T()}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}kT(),this.stopPromise=ST({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}},j$=new Py(Jl())});function My(r,e,t){r.on("finish",async()=>{try{await t()}finally{process.exit(0)}}),r.json(e)}var OT=M(()=>{"use strict"});function Ly(r,e=Date.now){return Math.max(0,Math.floor((e()-r)/1e3))}var jT=M(()=>{"use strict"});var Ny,RT,Ude,CT=M(()=>{"use strict";Ny=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()}},RT=new Ny,Ude=900*1e3});function P$(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 MT,LT,Fy,yo,NT,C$,qy,DT,D$,PT,Ul,qT=M(()=>{"use strict";MT=ct(Ll(),1),LT=ct(require("http"),1),Fy=ct(require("fs"),1),yo=ct(require("path"),1);Wk();ge();lT();fT();KT();Ps();Fl();OT();jT();CT();NT=yo.default.resolve(__dirname,"../skills/mem-search"),C$=yo.default.join(NT,"operations"),qy=yo.default.join(NT,"SKILL.md"),DT=(()=>{try{let r=Fy.readFileSync(qy,"utf-8");return _.info("SYSTEM","Cached SKILL.md at boot",{path:qy,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:qy,message:r instanceof Error?r.message:String(r)}),null}})(),D$=(()=>{let r=new Map;for(let e of by){let t=yo.default.join(C$,`${e}.md`);try{r.set(e,Fy.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})(),PT="13.5.2";Ul=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,MT.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=LT.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(pT),this.app.use(dT)}setupMiddleware(){Iy(_y,{includeCors:!1}).forEach(t=>this.app.use(t))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,t,n)=>{P$(t),n()})}setupCors(){this.app.use(ql())}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:PT,workerPath:this.options.workerPath,uptime:Ly(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:RT.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:PT})}),this.app.get("/api/instructions",(e,t)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!Yk.includes(n))return t.status(400).json({error:"Invalid topic"});if(i&&!by.includes(i))return t.status(400).json({error:"Invalid operation"});if(i){let a=D$.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(DT===null)return _.debug("HTTP","SKILL.md not cached at boot",{topic:n}),t.status(404).json({error:"Instruction not found"});let s=this.extractInstructionSection(DT,n);t.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",fo,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"})):My(t,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",fo,async(e,t)=>{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"})):My(t,{status:"shutting_down"},()=>this.options.onShutdown())}),this.app.get("/api/admin/doctor",fo,(e,t)=>{let a=AT().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=>Ty.has(f)||ky.some(m=>f.startsWith(m))),l=Ly(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,M$,L$,Jy,FT=M(()=>{"use strict";Jt=require("zod"),M$=Jt.z.enum(["hook","worker","provider","server","api"]),L$=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:M$,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()}),Jy=L$.omit({id:!0,createdAtEpoch:!0}).partial({serverSessionId:!0,platformSource:!0,payload:!0,contentSessionId:!0,memorySessionId:!0})});function qe(){return(0,Gl.randomUUID)()}function ze(r){return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}function JT(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 mn(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 bo(r){return JSON.stringify(Uy(r))}function kr(r){return(0,Gl.createHash)("sha256").update(bo(r)).digest("hex")}function Uy(r){if(Array.isArray(r))return r.map(Uy);if(r&&typeof r=="object"){let e=r;return Object.keys(e).sort().reduce((t,n)=>(t[n]=Uy(e[n]),t),{})}return r}var Gl,Br=M(()=>{"use strict";Gl=require("crypto")});function UT(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(),bo(r.payload??{})])}`}function Gy(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,Ls=M(()=>{"use strict";Br();lr=class{constructor(e){this.client=e}client;async create(e){await _r(this.client,e.projectId,e.teamId),e.serverSessionId&&await mn(this.client,e.serverSessionId,e.projectId,e.teamId);let t=UT(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 Sy});var nT=h((nde,rT)=>{"use strict";var tT=Object.getOwnPropertySymbols,m$=Object.prototype.hasOwnProperty,h$=Object.prototype.propertyIsEnumerable;function y$(r){if(r==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(r)}function b$(){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}}rT.exports=b$()?Object.assign:function(r,e){for(var t,n=y$(r),i,s=1;s<arguments.length;s++){t=Object(arguments[s]);for(var a in t)m$.call(t,a)&&(n[a]=t[a]);if(tT){i=tT(t);for(var o=0;o<i.length;o++)h$.call(t,i[o])&&(n[i[o]]=t[i[o]])}}return n}});var sT=h((ide,iT)=>{(function(){"use strict";var r=nT(),e=fy(),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,L){if(k)I(k);else{var J=r({},t,L),re=null;J.origin&&typeof J.origin=="function"?re=J.origin:J.origin&&(re=function(je,se){se(null,J.origin)}),re?re(g.headers.origin,function(je,se){je||!se?I(je):(J.origin=se,p(J,g,E,I))}):I()}})}}iT.exports=f})()});function Iy(r,e={}){let t=[];e.includeCors!==!1&&t.push(ql()),t.push(wy.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=Ci(),i=oT.default.join(n,"plugin","ui");return t.push(wy.default.static(i)),t}function ql(){return(0,aT.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 fo(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 _y(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 wy,aT,oT,cT=M(()=>{"use strict";wy=ct(Ll(),1),aT=ct(sT(),1),oT=ct(require("path"),1);Ur();ge()});var lT=M(()=>{"use strict";cT()});function uT(r,e,t,n){let i={error:r,message:e};return t&&(i.code=t),n&&(i.details=n),i}function pT(r,e){e.status(404).json(uT("NotFound",`Cannot ${r.method} ${r.path}`))}var Ds,dT,fT=M(()=>{"use strict";ge();Ds=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};dT=(r,e,t,n)=>{let i=r instanceof Ds?r.statusCode:500;_.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:r.message,code:r instanceof Ds?r.code:void 0},r);let s=uT(r.name||"Error",r.message,r instanceof Ds?r.code:void 0,r instanceof Ds?r.details:void 0);t.status(i).json(s)}});var mT=M(()=>{"use strict"});function mo(r=process.env){let e={};for(let[t,n]of Object.entries(r))if(n!==void 0){if(v$.has(t)){e[t]=n;continue}Ty.has(t)||g$.has(t)||ky.some(i=>t.startsWith(i))||(e[t]=n)}return e}var ky,Ty,g$,v$,Fl=M(()=>{"use strict";ky=["CLAUDECODE_","CLAUDE_CODE_"],Ty=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),g$=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"]),v$=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 I$(r){let e=hT.get(r);if(e&&Date.now()-e.capturedAtMs<w$)return e.token;let t=null;try{let n=(0,Ry.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:{...mo(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 hT.set(r,{token:t,capturedAtMs:Date.now()}),t}function Cy(r){if(!Number.isInteger(r)||r<=0)return null;if(process.platform==="linux")try{let e=(0,Gr.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 I$(r);try{let e=(0,Ry.spawnSync)("ps",["-p",String(r),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...mo(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 Fn(r){if(!r||!or(r.pid))return!1;if(!r.startToken)return!0;let e=Cy(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 Jl(){return Ay||(Ay=new jy),Ay}function Ky(){let r=_$.shift();r&&r()}var Ry,Gr,Oy,E$,x$,S$,w$,hT,jy,Ay,_$,Ps=M(()=>{"use strict";Ry=require("child_process");mT();Gr=require("fs"),Oy=ct(require("path"),1);ge();Fl();Ur();E$=5e3,x$=1e3,S$=$e.supervisorRegistry();w$=5e3,hT=new Map;jy=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,Gr.mkdirSync)(Oy.default.dirname(this.registryPath),{recursive:!0}),!(0,Gr.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Gr.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"&&Ky()}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)Ky();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()+E$;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()+x$;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"&&Ky();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,Gr.mkdirSync)(Oy.default.dirname(this.registryPath),{recursive:!0}),(0,Gr.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},Ay=null;_$=[]});function yT(r){return process.platform==="win32"?Math.round(r*ho.WINDOWS_MULTIPLIER):r}var ho,Dy=M(()=>{"use strict";ho={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 ST(r){let e=r.currentPid??process.pid,t=r.pidFilePath??T$,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 gT(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 bT(i,5e3);let s=i.filter(a=>or(a.pid));for(let a of s)try{await gT(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 bT(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);try{(0,ET.rmSync)(t,{force:!0})}catch(a){a instanceof Error?_.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:t},a):_.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:t,error:String(a)})}r.registry.pruneDeadEntries()}async function bT(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 gT(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 A$();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 k$("taskkill",s,{timeout:ho.POWERSHELL_COMMAND,windowsHide:!0})}async function A$(){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 vT,ET,xT,k$,T$,wT=M(()=>{"use strict";vT=require("child_process"),ET=require("fs"),xT=require("util");ge();Dy();Ps();Ur();k$=(0,xT.promisify)(vT.execFile),T$=$e.workerPid()});function K$(){let e=Jl().pruneDeadEntries();e>0&&_.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function _T(){Ms===null&&(Ms=setInterval(K$,IT),Ms.unref(),_.debug("SYSTEM","Health checker started",{intervalMs:IT}))}function kT(){Ms!==null&&(clearInterval(Ms),Ms=null,_.debug("SYSTEM","Health checker stopped"))}var IT,Ms,TT=M(()=>{"use strict";ge();Ps();IT=3e4,Ms=null});function AT(){return j$}function R$(r={}){let e=r.pidFilePath??O$;if(!(0,Di.existsSync)(e))return"missing";let t=null;try{t=JSON.parse((0,Di.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,Di.rmSync)(e,{force:!0}),"invalid"}return Fn(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,Di.rmSync)(e,{force:!0}),"stale")}var Di,O$,Py,j$,KT=M(()=>{"use strict";Di=require("fs");ge();Ps();wT();TT();Ur();O$=$e.workerPid(),Py=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(),R$({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,_T()}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}kT(),this.stopPromise=ST({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}},j$=new Py(Jl())});function My(r,e,t){r.on("finish",async()=>{try{await t()}finally{process.exit(0)}}),r.json(e)}var OT=M(()=>{"use strict"});function Ly(r,e=Date.now){return Math.max(0,Math.floor((e()-r)/1e3))}var jT=M(()=>{"use strict"});var Ny,RT,Ude,CT=M(()=>{"use strict";Ny=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()}},RT=new Ny,Ude=900*1e3});function P$(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 MT,LT,Fy,yo,NT,C$,qy,DT,D$,PT,Ul,qT=M(()=>{"use strict";MT=ct(Ll(),1),LT=ct(require("http"),1),Fy=ct(require("fs"),1),yo=ct(require("path"),1);Wk();ge();lT();fT();KT();Ps();Fl();OT();jT();CT();NT=yo.default.resolve(__dirname,"../skills/mem-search"),C$=yo.default.join(NT,"operations"),qy=yo.default.join(NT,"SKILL.md"),DT=(()=>{try{let r=Fy.readFileSync(qy,"utf-8");return _.info("SYSTEM","Cached SKILL.md at boot",{path:qy,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:qy,message:r instanceof Error?r.message:String(r)}),null}})(),D$=(()=>{let r=new Map;for(let e of by){let t=yo.default.join(C$,`${e}.md`);try{r.set(e,Fy.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})(),PT="13.5.3";Ul=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,MT.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=LT.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(pT),this.app.use(dT)}setupMiddleware(){Iy(_y,{includeCors:!1}).forEach(t=>this.app.use(t))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,t,n)=>{P$(t),n()})}setupCors(){this.app.use(ql())}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:PT,workerPath:this.options.workerPath,uptime:Ly(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:RT.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:PT})}),this.app.get("/api/instructions",(e,t)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!Yk.includes(n))return t.status(400).json({error:"Invalid topic"});if(i&&!by.includes(i))return t.status(400).json({error:"Invalid operation"});if(i){let a=D$.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(DT===null)return _.debug("HTTP","SKILL.md not cached at boot",{topic:n}),t.status(404).json({error:"Instruction not found"});let s=this.extractInstructionSection(DT,n);t.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",fo,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"})):My(t,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",fo,async(e,t)=>{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"})):My(t,{status:"shutting_down"},()=>this.options.onShutdown())}),this.app.get("/api/admin/doctor",fo,(e,t)=>{let a=AT().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=>Ty.has(f)||ky.some(m=>f.startsWith(m))),l=Ly(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,M$,L$,Jy,FT=M(()=>{"use strict";Jt=require("zod"),M$=Jt.z.enum(["hook","worker","provider","server","api"]),L$=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:M$,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()}),Jy=L$.omit({id:!0,createdAtEpoch:!0}).partial({serverSessionId:!0,platformSource:!0,payload:!0,contentSessionId:!0,memorySessionId:!0})});function qe(){return(0,Gl.randomUUID)()}function ze(r){return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}function JT(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 mn(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 bo(r){return JSON.stringify(Uy(r))}function kr(r){return(0,Gl.createHash)("sha256").update(bo(r)).digest("hex")}function Uy(r){if(Array.isArray(r))return r.map(Uy);if(r&&typeof r=="object"){let e=r;return Object.keys(e).sort().reduce((t,n)=>(t[n]=Uy(e[n]),t),{})}return r}var Gl,Br=M(()=>{"use strict";Gl=require("crypto")});function UT(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(),bo(r.payload??{})])}`}function Gy(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,Ls=M(()=>{"use strict";Br();lr=class{constructor(e){this.client=e}client;async create(e){await _r(this.client,e.projectId,e.teamId),e.serverSessionId&&await mn(this.client,e.serverSessionId,e.projectId,e.teamId);let t=UT(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