claude-mem 15.8.2 → 15.8.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.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/.qoder-plugin/plugin.json +1 -1
- package/README.md +1 -1
- package/dist/npx-cli/index.js +3 -3
- package/dsh/package.json +1 -1
- package/openclaw/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/.codex-plugin/plugin.json +1 -1
- package/plugin/.qoder-plugin/plugin.json +1 -1
- package/plugin/package.json +1 -1
- package/plugin/scripts/mcp-server.cjs +2 -2
- package/plugin/scripts/server-service.cjs +2 -2
- package/plugin/scripts/transcript-watcher.cjs +1 -1
- package/plugin/scripts/worker-service.cjs +150 -150
- package/plugin/scripts/worker-service.cjs.map +2 -2
- package/plugin/skills/how-it-works/onboarding-explainer.md +1 -1
- package/plugin/ui/work-view/assets/{index-CsxZxEdH.js → index-CbqxWmfj.js} +2 -2
- package/plugin/ui/work-view/assets/setup-page-BREOBm1A.css +1 -0
- package/plugin/ui/work-view/assets/setup-page-DKi95flt.js +8 -0
- package/plugin/ui/work-view/assets/{setup-sample-D1IY_sPY.js → setup-sample-D-wH9Ys6.js} +1 -1
- package/plugin/ui/work-view/index.html +1 -1
- package/plugin/ui/work-view/assets/setup-page-CpAsRFja.css +0 -1
- package/plugin/ui/work-view/assets/setup-page-DBRWnL2x.js +0 -8
|
@@ -66,7 +66,7 @@ ${m.stack??""}
|
|
|
66
66
|
`)}else Mo(d+`
|
|
67
67
|
`)}debug(e,r,n,i){this.log(0,e,r,n,i)}info(e,r,n,i){this.log(1,e,r,n,i)}warn(e,r,n,i){this.log(2,e,r,n,i)}setErrorSink(e){_S=e}error(e,r,n,i){this.log(3,e,r,n,i),this.routeErrorToSink(r,n,i)}routeErrorToSink(e,r,n){try{if(!_S||!(n instanceof Error))return;_S(n)}catch{}}dataIn(e,r,n,i){this.info(e,`\u2192 ${r}`,n,i)}dataOut(e,r,n,i){this.info(e,`\u2190 ${r}`,n,i)}success(e,r,n,i){this.info(e,`\u2713 ${r}`,n,i)}failure(e,r,n,i){this.error(e,`\u2717 ${r}`,n,i)}},_=new wS});function Pm(t){return/^Bearer\s+(.+)$/i.exec(t.trim())?.[1]?.trim()||null}function Dm(t){let e=t.ip||t.socket.remoteAddress||"";return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"||e==="localhost"}function iq(t){let e=jm(t.header("host")??"");return e==="127.0.0.1"||e==="localhost"||e==="::1"}function jm(t){let e=t.trim().toLowerCase();if(e.startsWith("[")){let n=e.indexOf("]");return n===-1?e:e.slice(1,n)}let r=e.lastIndexOf(":");return r>-1&&/^\d+$/.test(e.slice(r+1))?e.slice(0,r):e}function Km(t){return!!(t.header("forwarded")||t.header("x-forwarded-for")||t.header("x-forwarded-host")||t.header("x-real-ip"))}var xS=k(()=>{"use strict"});function IS(t){return t.startsWith("http://localhost:")||t.startsWith("http://127.0.0.1:")}function TS(t,e){if(!e)return!1;try{return new URL(t).host===e.trim().toLowerCase()}catch{return!1}}function AS(t,e,r){let n;try{n=new URL(t)}catch{return!1}if(n.protocol!=="http:"&&n.protocol!=="https:")return!1;if(r.allowedOrigins.includes(n.origin))return!0;if(!e)return!1;if(TS(t,e))return!0;let i;try{i=new URL(`${n.protocol}//${e.trim().toLowerCase()}`)}catch{return!1}return sq.has(n.hostname)&&sq.has(i.hostname)&&n.port===i.port}var sq,kS=k(()=>{"use strict";sq=new Set(["localhost","127.0.0.1","[::1]"])});function Lle(t=process.platform){return t==="win32"?8e3:5e3}function oq(t=process.platform){return Lm.SESSION_INIT_HOOK_CAP-Lle(t)}function aq(t){return process.platform==="win32"?Math.round(t*Lm.WINDOWS_MULTIPLIER):t}var Lm,cq=k(()=>{"use strict";Lm={HEALTH_CHECK:3e3,API_REQUEST:3e4,SESSION_INIT_HOOK_CAP:15e3,SESSION_INIT_REQUEST:1e4,SESSION_INIT_REQUEST_MAX:14e3,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5}});function Ule(t){try{return qle.has(new URL(t).protocol)}catch{return!1}}function Fle(t){uq!==t&&(uq=t,_.warn("SDK","CLAUDE_MEM_OPENROUTER_BASE_URL is not an http(s) URL; requests to it will fail until it is fixed",{baseUrl:t}))}function qm(t){let e=(t??"").trim();if(!e)return Nle;if(!Ule(e)){Fle(e);let i=e.replace(lq,"");return i.toLowerCase().endsWith(Nm)?i:`${i}${Nm}`}let r=new URL(e),n=r.pathname.replace(lq,"");return r.pathname=n.toLowerCase().endsWith(Nm)?n:`${n}${Nm}`,r.href}function Gu(t){try{return new URL(t).hostname.toLowerCase()==="openrouter.ai"}catch{return!1}}var Nle,Nm,qle,lq,uq,hc=k(()=>{"use strict";V();Nle="https://openrouter.ai/api/v1/chat/completions",Nm="/chat/completions",qle=new Set(["http:","https:"]),lq=/\/+$/;uq=null});function Hle(t){return typeof t=="boolean"?String(t):t}function Wle(t){let e=process.env.CLAUDE_MEM_ENV_FILE??(0,Mn.join)((0,Mn.dirname)(t),".env");try{return(0,Ki.existsSync)(e)?!!(0,fq.parseEnv)(Bu((0,Ki.readFileSync)(e,"utf-8"))).ANTHROPIC_BASE_URL:!1}catch{return!0}}function Yle(t,e){let r=t.CLAUDE_MEM_MODEL;return typeof r!="string"||!Vle.has(r.trim())?!1:(typeof t.CLAUDE_MEM_CLAUDE_AUTH_METHOD=="string"?t.CLAUDE_MEM_CLAUDE_AUTH_METHOD.trim():"")!=="gateway"&&!Wle(e)}function Qle(t){let e=t.CLAUDE_MEM_OPENROUTER_MODEL;if(typeof e!="string"||!zle.has(e.trim()))return!1;let r=typeof t.CLAUDE_MEM_OPENROUTER_BASE_URL=="string"?t.CLAUDE_MEM_OPENROUTER_BASE_URL.trim():"";return r===""||Gu(r)}function mq(t,e){return(0,Mn.join)((0,Mn.dirname)(t),`.${(0,Mn.basename)(t)}.${e.markerTag}`)}function RS(t,e){try{(0,Ki.writeFileSync)(mq(t,e),new Date().toISOString(),{encoding:"utf-8",mode:384})}catch{}}function Xle(t){if(typeof t!="string")return null;let e=t.trim();if(e.length===0)return null;try{let r=new URL(e).hostname;if(r===Jle||r===Ble)return Gle}catch{return null}return null}var Ki,Mn,zu,fq,$le,Jle,Ble,Gle,zle,Vle,OS,dq,pq,qt,Li=k(()=>{"use strict";Ki=require("fs"),Mn=require("path"),zu=require("os");cq();fq=require("util");Po();hc();mc();Cm();$le="security_alert",Jle="sync-hub.black-pond-afbb.workers.dev",Ble="ziczmqtpmaxbornfghye.supabase.co",Gle="https://sync.cmem.ai",zle=new Set(["xiaomi/mimo-v2-flash:free"]);Vle=new Set(["claude-haiku-4-5-20251001","claude-haiku-4-5"]);OS=18e4,dq=[{key:"CLAUDE_MEM_LLM_TIMEOUT_MS",legacy:"30000",markerTag:"llm-timeout-migrated-v1"},{key:"CLAUDE_MEM_FIELD_OPTIMIZE_TIMEOUT_MS",legacy:"30000",markerTag:"field-optimize-timeout-migrated-v1"}];pq=new Set;qt=class{static DEFAULTS={CLAUDE_MEM_MEMORY_SEARCH_HOOK_ENABLED:"true",CLAUDE_MEM_MEMORY_INSTRUCTIONS_ENABLED:"true",CLAUDE_MEM_MEMORY_WATCH_ROOTS:"",CLAUDE_MEM_MODEL:"haiku",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_SESSION_START_INCLUDE_ALL_SOURCES:"false",CLAUDE_MEM_CONTEXT_PROJECTS:"current",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_WORKER_INGEST_TOKEN:"",CLAUDE_MEM_WORKER_INGEST_MAX_BYTES:"5242880",CLAUDE_MEM_HOOK_SPOOL_TRANSPORT:"auto",CLAUDE_MEM_ALLOWED_ORIGINS:"",CLAUDE_MEM_PUBLIC_URL:"",CLAUDE_MEM_API_TIMEOUT_MS:String(aq(Lm.API_REQUEST)),CLAUDE_MEM_SESSION_INIT_TIMEOUT_MS:String(oq()),CLAUDE_MEM_IDLE_EXIT_SEC:"0",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_SKIP_BASH_PATTERNS:"",CLAUDE_MEM_SKIP_SUBAGENT_OBSERVATIONS:"false",CLAUDE_MEM_SKIP_AGENT_TYPES:"",CLAUDE_MEM_CAPTURE_ADVISOR_CALLS:"false",CLAUDE_MEM_DELIVERABLES_ENABLED:"true",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_MEDIA_CAPTURE_ENABLED:"false",CLAUDE_MEM_MEDIA_INFERENCE_ENABLED:"false",CLAUDE_MEM_CODEX_MODEL:"",CLAUDE_MEM_CODEX_PATH:"codex",CLAUDE_MEM_CODEX_REASONING_EFFORT:"low",CLAUDE_MEM_CODEX_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_CODEX_OBSERVATION_BATCH_SIZE:"8",CLAUDE_MEM_CODEX_OBSERVATION_BATCH_MAX_CHARS:"32000",CLAUDE_MEM_CLAUDE_OBSERVATION_BATCH_SIZE:"1",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_API_KEYS:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-flash-latest",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_API_KEYS:"",CLAUDE_MEM_OPENROUTER_MODEL:"cohere/north-mini-code:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_TEMPERATURE:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_EXTRA_BODY:"",CLAUDE_MEM_OPENROUTER_REASONING_EFFORT:"",CLAUDE_MEM_OPENAI_COMPAT_PRESET:"",CLAUDE_MEM_OPENAI_COMPAT_API_KEY:"",CLAUDE_MEM_OPENAI_COMPAT_API_KEYS:"",CLAUDE_MEM_OPENAI_COMPAT_BASE_URL:"",CLAUDE_MEM_OPENAI_COMPAT_MODEL:"",CLAUDE_MEM_OPENAI_COMPAT_REASONING:"",CLAUDE_MEM_OPENAI_COMPAT_OBSERVATION_BATCH_SIZE:"1",CLAUDE_MEM_QUOTA_FALLBACK_PROVIDER:"claude",CLAUDE_MEM_QUOTA_FALLBACK_MODEL:"",CLAUDE_MEM_QUOTA_FALLBACK_AUTH_METHOD:"",CLAUDE_MEM_QUOTA_THRESHOLD_FIVE_HOUR:"0.95",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY:"0.93",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY_OPUS:"0.93",CLAUDE_MEM_QUOTA_THRESHOLD_SEVEN_DAY_SONNET:"0.92",CLAUDE_MEM_QUOTA_THRESHOLD_OVERAGE:"0.95",CLAUDE_MEM_DATA_DIR:(0,Mn.join)((0,zu.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_CLAUDE_CONFIG_DIR:"",CLAUDE_MEM_OBSERVER_CLAUDE_CONFIG_DIR:"",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_OBSERVATION_TYPES:"",CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:"",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_MAIN_AGENT_ONLY:"true",CLAUDE_MEM_REINFORCE_ALPHA:"0",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_WORK_STATE_ENABLED:"true",CLAUDE_MEM_FILE_READ_GATE_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:(0,Mn.join)((0,zu.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_CODEX_SUBAGENT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_OBSERVER_MAX_CONVERSATION_CHARS:"400000",CLAUDE_MEM_OBSERVER_THINKING:"disabled",CLAUDE_MEM_OBSERVER_CONTEXT_WINDOW:"",CLAUDE_MEM_OBSERVER_MAX_OUTPUT_TOKENS:"4096",CLAUDE_MEM_OBSERVE_BARE_PROMPTS:"false",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_REDACT_ENABLED:"false",CLAUDE_MEM_REDACT_DISABLED_BUILTINS:"",CLAUDE_MEM_REDACT_CUSTOM_PATTERNS:"[]",CLAUDE_MEM_REDACT_LOG_MATCHES:"false",CLAUDE_MEM_REDACT_GENERIC_ENABLED:"false",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_PROJECT_ENVIRONMENTS:"[]",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_SEMANTIC_INJECT_FORMAT:"narrative",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_CHROMA_MUTATION_TIMEOUT_MS:"600000",CLAUDE_MEM_CHROMA_MAX_PENDING_MUTATIONS:"5000",CLAUDE_MEM_CHROMA_EMBEDDING_FUNCTION:"default",CLAUDE_MEM_SERVER_VECTOR_SEARCH:"auto",CLAUDE_MEM_EMBEDDING_BACKFILL_THREADS:"",CLAUDE_MEM_EMBEDDING_MODEL:"all-MiniLM-L6-v2",CLAUDE_MEM_CHROMA_UVX_PATH:"",CLAUDE_MEM_SEARCH_RECENCY_DAYS:"90",CLAUDE_MEM_CLOUD_SYNC_TOKEN:"",CLAUDE_MEM_CLOUD_SYNC_USER_ID:"",CLAUDE_MEM_CLOUD_SYNC_HUB_URL:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_ID:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_NAME:(0,zu.hostname)(),CLAUDE_MEM_CLOUD_SYNC_WS:"true",CLAUDE_MEM_CLOUD_SYNC_KEEP_PULLING:"false",CLAUDE_MEM_CLOUD_SYNC_CONTENT_BATCH_SIZE:"40",CLAUDE_MEM_CLOUD_SYNC_REQUEST_TIMEOUT_MS:"90000",CLAUDE_MEM_TEAMBRAIN_URL:"",CLAUDE_MEM_TEAMBRAIN_TEAM_ID:"",CLAUDE_MEM_LLM_TIMEOUT_MS:String(OS),CLAUDE_MEM_FIELD_OPTIMIZE_TIMEOUT_MS:String(OS),CLAUDE_MEM_LLM_STREAM_IDLE_TIMEOUT_MS:"90000",CLAUDE_MEM_WORKER_HEARTBEAT_STALE_MS:"120000",CLAUDE_MEM_TV_TOKEN:"",CLAUDE_MEM_PRO_TRIAL_EMAIL:"",CLAUDE_MEM_PRO_TRIAL_AT:"",CLAUDE_MEM_PRO_TRIAL_STATE:"",CLAUDE_MEM_PRO_TRIAL_ENDS_AT:"",CLAUDE_MEM_PRO_PLAN:"",CLAUDE_MEM_PRO_FALLBACK_AT:"",CLAUDE_MEM_PRO_FALLBACK_MESSAGE:"",CLAUDE_MEM_PRO_FALLBACK_ACTION:"",CLAUDE_MEM_PRO_FALLBACK_URL:"",CLAUDE_MEM_PRO_MEMORY_KEY:"",CLAUDE_MEM_PRO_MEMORY_BASE_URL:"",CLAUDE_MEM_PRO_MEMORY_MODEL:"",CLAUDE_MEM_WORK_VIEW_AUTO_REFRESH:"true",CLAUDE_MEM_WORK_VIEW_COPY_PROVIDER:"",CLAUDE_MEM_WORK_VIEW_COPY_MODEL:"",CLAUDE_MEM_BACKUP_ENABLED:"false",CLAUDE_MEM_BACKUP_INTERVAL_HOURS:"24",CLAUDE_MEM_BACKUP_RETAIN_COUNT:"7",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_WRAPUPS_ENABLED:"true",CLAUDE_MEM_TELEGRAM_OBSERVATION_ALERTS_ENABLED:"false",CLAUDE_MEM_TELEGRAM_WRAPUP_ROUTES:"{}",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert,sensitive",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_AWARENESS_ENABLED:"true",CLAUDE_MEM_GROK_BOT_AWARENESS_AGENT_IDS:"521e962d-2ec3-4488-bfbc-54d5209ce118,95601360-61f7-4fd9-bb3a-2c976b2b85c0",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_WEBHOOK_URL:"",CLAUDE_MEM_GROK_BOT_WEBHOOK_SECRET:"",CLAUDE_MEM_NOTION_ENABLED:"false",CLAUDE_MEM_NOTION_TOKEN:"",CLAUDE_MEM_NOTION_DATABASE_ID:"",CLAUDE_MEM_NOTION_AUTO_CREATE_PROPERTIES:"true",CLAUDE_MEM_GROK_BOT_INJECT_ENABLED:"true",CLAUDE_MEM_GROK_BOT_INJECT_AGENT_IDS:"*",CLAUDE_MEM_GROK_BOT_INJECT_TIER:"episode",CLAUDE_MEM_GROK_BOT_INJECT_WINDOW:"80",CLAUDE_MEM_GROK_BOT_INJECT_FALLBACK:"house",CLAUDE_MEM_GROK_BOT_INJECT_PLATFORM_SOURCE:"",CLAUDE_MEM_GROK_BOT_INJECT_PROJECTS_BY_AGENT:"",CLAUDE_MEM_GROK_BOT_INJECT_MAX_LINE_CHARS:"160",CLAUDE_MEM_GROK_BOT_INJECT_DEBOUNCE_MS:"1500",CLAUDE_MEM_GROK_BOT_INJECT_STANDING_LINE:"",CLAUDE_MEM_CCS_ALIGN_ENABLED:"true",CLAUDE_MEM_CCS_ALIGN_VIEWER_IDS:"ccs-align",CLAUDE_MEM_CCS_ALIGN_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_CCS_ALIGN_PATCH_SHADOWS:"false",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:"",CLAUDE_MEM_DEDUP_ENABLED:"false",CLAUDE_MEM_DEDUP_COSINE_THRESHOLD:"0.80",CLAUDE_MEM_DEDUP_IDF_VETO_DF:"10",CLAUDE_MEM_DEDUP_MIN_SHARED_TOKENS:"2",CLAUDE_MEM_DEDUP_MIN_PROJECT_DOCS:"10",CLAUDE_MEM_DEDUP_MAX_SCAN:"2000",CLAUDE_MEM_DEDUP_MAX_BACKFILL_ROWS:"50000",CLAUDE_MEM_TOOL_USES_RETENTION_DAYS:"0",CLAUDE_MEM_LOG_RETENTION_DAYS:"30",CLAUDE_MEM_WORKER_AUTOSTART:"true",CLAUDE_MEM_PROJECT_NAME_SOURCE:"path"};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){let r=process.env[e]??this.DEFAULTS[e];return e==="CLAUDE_MEM_WORKER_HOST"?this.normalizeWorkerHost(r):e==="CLAUDE_MEM_DATA_DIR"?Ko(r):r}static normalizeWorkerHost(e){return e==="localhost"?"127.0.0.1":e}static finalizeSettings(e,r){let n=r?this.applyEnvOverrides(e):e;n.CLAUDE_MEM_WORKER_HOST=this.normalizeWorkerHost(n.CLAUDE_MEM_WORKER_HOST);let i=n.CLAUDE_MEM_DATA_DIR?.trim();return i&&n.CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH===this.DEFAULTS.CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH&&(n.CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH=(0,Mn.join)(Ko(i),"transcript-watch.json")),n}static getInt(e){let r=this.get(e);return parseInt(r,10)}static applyEnvOverrides(e){let r={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(r[n]=process.env[n]);return r}static loadFromFile(e,r=!0,n={}){try{if(!(0,Ki.existsSync)(e)){let d=this.getAllDefaults();if(!n.readOnly)try{on(e,d,{mode:384});for(let f of dq)RS(e,f);console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(f){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,f instanceof Error?f.message:String(f))}return this.finalizeSettings(d,r)}let i=(0,Ki.readFileSync)(e,"utf-8"),s=hS(i),o=jo(s),a=o!==s,c=gS(s),l=a&&Object.keys(c).some(d=>d!=="env");if(a&&!l&&!n.readOnly)try{on(e,o,{mode:384}),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(d){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,d instanceof Error?d.message:String(d))}if(o.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES===$le&&(o={...o,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES},!n.readOnly))try{on(e,l?{...c,env:o}:o,{mode:384}),console.warn("[SETTINGS] Migrated Telegram trigger types off the legacy default:",e)}catch(d){console.warn("[SETTINGS] Failed to migrate Telegram trigger types:",e,d instanceof Error?d.message:String(d))}if(Yle(o,e)){let d=String(o.CLAUDE_MEM_MODEL).trim();if(o={...o,CLAUDE_MEM_MODEL:this.DEFAULTS.CLAUDE_MEM_MODEL},!n.readOnly)try{on(e,l?{...c,env:o}:o,{mode:384}),console.warn(`[SETTINGS] Migrated Claude model off the pinned ${d} to ${this.DEFAULTS.CLAUDE_MEM_MODEL}:`,e)}catch(f){console.warn("[SETTINGS] Failed to migrate the pinned Claude model:",e,f instanceof Error?f.message:String(f))}}if(Qle(o)){let d=String(o.CLAUDE_MEM_OPENROUTER_MODEL).trim();if(o={...o,CLAUDE_MEM_OPENROUTER_MODEL:this.DEFAULTS.CLAUDE_MEM_OPENROUTER_MODEL},!n.readOnly)try{on(e,l?{...c,env:o}:o,{mode:384}),console.warn(`[SETTINGS] Migrated OpenRouter model off the retired default ${d} to ${this.DEFAULTS.CLAUDE_MEM_OPENROUTER_MODEL}:`,e)}catch(f){console.warn("[SETTINGS] Failed to migrate the retired OpenRouter model:",e,f instanceof Error?f.message:String(f))}}let u=Xle(o.CLAUDE_MEM_CLOUD_SYNC_HUB_URL);if(u!==null&&(o={...o,CLAUDE_MEM_CLOUD_SYNC_HUB_URL:u},!n.readOnly))try{on(e,l?{...c,env:o}:o,{mode:384}),console.warn("[SETTINGS] Migrated cloud sync hub URL to",u,"from a retired hub host:",e)}catch(d){console.warn("[SETTINGS] Failed to migrate cloud sync hub URL:",e,d instanceof Error?d.message:String(d))}for(let d of dq)if(!(0,Ki.existsSync)(mq(e,d))){if(o[d.key]!==d.legacy){n.readOnly||RS(e,d);continue}if(o={...o,[d.key]:this.DEFAULTS[d.key]},!n.readOnly)try{on(e,l?{...c,env:o}:o,{mode:384}),RS(e,d),console.warn(`[SETTINGS] Migrated ${d.key} off the old ${d.legacy}ms default to ${this.DEFAULTS[d.key]}ms:`,e)}catch(f){let m=`${d.key}\0${e}`;pq.has(m)||(pq.add(m),console.warn(`[SETTINGS] Failed to migrate ${d.key}; using the new default in memory (reported once per process):`,e,f instanceof Error?f.message:String(f)))}}let p={...this.DEFAULTS};for(let d of Object.keys(this.DEFAULTS))o[d]!==void 0&&(p[d]=Hle(o[d]));return this.finalizeSettings(p,r)}catch(i){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,i instanceof Error?i.message:String(i));let s=this.getAllDefaults();return this.finalizeSettings(s,r)}}}});function hq(t){return new RegExp(`${t}${No}`,"gi")}function $m(t){return`(?<=${t}${qo}${Ni}[=:]${Ni}${qo})`}function Bm(t,e){if(!e.enabled||t.length===0)return{redacted:t,counts:{},oversize:!1};if(t.length>sue)return _.warn("REDACT","field exceeds the 1M-char redaction cap; replaced by an oversize marker",void 0,{inputLength:t.length}),{redacted:oue,counts:{oversize:1},oversize:!0};let r=new Set(e.disabledBuiltinPatterns??[]),n={},i=t,s=[];for(let a of e.customPatterns??[]){if(!a.name||a.name.length===0){_.warn("REDACT","custom pattern skipped: missing name",void 0,{pattern:a});continue}try{s.push({name:a.name,regex:new RegExp(a.regex,"g")})}catch(c){_.warn("REDACT","custom pattern skipped: invalid regex",{name:a.name},c instanceof Error?c:new Error(String(c)))}}let o=[...s,...nue,...e.genericEnabled?iue:[]];for(let a of o)r.has(a.name)||(a.regex.lastIndex=0,i=i.replace(a.regex,()=>(n[a.name]=(n[a.name]??0)+1,`<redacted type='${a.name}'/>`)));return e.logMatches&&Object.keys(n).length>0&&_.debug("REDACT","patterns matched",void 0,{counts:n}),{redacted:i,counts:n,oversize:!1}}function PS(t){return t.includes("<redacted type='")||t.includes("<redacted type=")}function aue(t){if(!t||t.trim()==="")return[];try{let e=JSON.parse(t);return Array.isArray(e)?e.filter(r=>r&&typeof r.name=="string"&&typeof r.regex=="string"):(_.warn("REDACT","CLAUDE_MEM_REDACT_CUSTOM_PATTERNS is not a JSON array, ignoring"),[])}catch(e){return _.warn("REDACT","failed to parse CLAUDE_MEM_REDACT_CUSTOM_PATTERNS as JSON",void 0,e instanceof Error?e:new Error(String(e))),[]}}function cue(t){return{enabled:t.CLAUDE_MEM_REDACT_ENABLED==="true",disabledBuiltinPatterns:(t.CLAUDE_MEM_REDACT_DISABLED_BUILTINS??"").split(",").map(e=>e.trim()).filter(Boolean),customPatterns:aue(t.CLAUDE_MEM_REDACT_CUSTOM_PATTERNS??"[]"),logMatches:t.CLAUDE_MEM_REDACT_LOG_MATCHES==="true",genericEnabled:t.CLAUDE_MEM_REDACT_GENERIC_ENABLED==="true"}}function pue(t){if(!(0,Jm.existsSync)(t))return null;try{return(0,Jm.readFileSync)(t,"utf-8")}catch{return""}}function fue(t){if(t===null)return!1;try{let e=JSON.parse(Bu(t));return e===null||typeof e!="object"||Array.isArray(e)}catch{return!0}}function mue(t,e,r){return process.env.CLAUDE_MEM_REDACT_ENABLED==="false"||!(Vu?.enabled===!0||due.test(e))?r:(gq||(gq=!0,_.warn("REDACT","settings.json could not be read; secret redaction stays on until it is repaired",{settingsPath:t,using:Vu?.enabled?"the last configuration that loaded":"the built-in patterns"})),Vu?.enabled?Vu:uue)}function Gm(t=ji){let e=Date.now();if(Hu&&e-yq<lue)return Hu;let r=qt.loadFromFile(t),n=cue(r),i=n.enabled?null:pue(t);return fue(i)?Hu=mue(t,i,n):(Hu=n,Vu=n),yq=e,Hu}function bq(t){return Bm(t,Gm()).redacted}function bue(t,e,r){if(!r.genericEnabled)return null;let n=hue.test(t)?"generic_password":yue.test(t)?"generic_token":null;return!n||r.disabledBuiltinPatterns?.includes(n)||!gue.test(e)||!/[A-Za-z]/.test(e)?null:`<redacted type='${n}'/>`}function _ue(t,e,r){if(!r.genericEnabled||r.disabledBuiltinPatterns?.includes("bearer_token")||!vue.test(t))return null;let n=Eue.exec(e);return n?`${n[1]}<redacted type='bearer_token'/>${e.slice(n[0].length)}`:null}function xue(t,e,r){return r.disabledBuiltinPatterns?.includes("aws_session_token")||!Sue.test(t)||!wue.test(e)?null:"<redacted type='aws_session_token'/>"}function Aue(t,e,r){return r.disabledBuiltinPatterns?.includes("aws_secret_key")||!Iue.test(t)||!Tue.test(e)?null:"<redacted type='aws_secret_key'/>"}function vq(t,e=Gm()){if(!e.enabled)return t;let r=(n,i)=>{if(typeof n=="string"){let s=Bm(n,e);return i===void 0||Object.keys(s.counts).length>0?s.redacted:xue(i,n,e)??Aue(i,n,e)??_ue(i,n,e)??bue(i,n,e)??s.redacted}return Array.isArray(n)?n.map(s=>r(s)):n!==null&&typeof n=="object"?Object.fromEntries(Object.entries(n).map(([s,o])=>[s,r(o,s)])):n};return r(t)}var Jm,Wu,No,qo,Ni,Um,Fm,CS,Zle,eue,tue,rue,nue,iue,sue,oue,MS,Hu,yq,lue,Vu,gq,uue,due,hue,yue,gue,vue,Eue,Sue,wue,Iue,Tue,yc=k(()=>{"use strict";Jm=require("fs");V();Li();Nt();Po();Wu=String.raw`[A-Za-z0-9_.\-+/=~@#$%^*!?]`,No=`(?=${Wu}{8})${Wu}*[A-Za-z]${Wu}*`,qo=String.raw`(?:\\{0,3}["'])?`,Ni=String.raw`\s{0,8}`;Um=String.raw`(?:token|secret|api_key)`,Fm=String.raw`\\{0,3}["']`,CS=String.raw`(?<!\\)"`,Zle=String.raw`(?:^|[\s?&]|\\[nrt]|${CS})`,eue=String.raw`(?:^|\n|\\n|${CS})[ \t]{0,8}(?:-[ \t]{1,8})?`,tue=String.raw`(?:${Fm})?[ \t]{0,8}(?:$|\r?\n|\\{1,3}[rn]|#|${CS})`,rue=new RegExp([`${$m(String.raw`\b\w*_${Um}`)}${No}`,`(?<=${Fm}${Um}${Fm}${Ni}:${Ni}${Fm})${No}`,`(?<=${Zle}${Um}=${qo})${No}(?!\\(|${Wu})`,String.raw`(?<=--(?:token|secret|api[-_]key)(?:=|[ \t]{1,8})${qo})${No}`,`(?<=${eue}${Um}:[ \\t]{1,8}${qo})${No}(?=${tue})`].join("|"),"gi"),nue=[{name:"url_credentials",regex:/(?<=\b[a-z][a-z0-9+.-]*:\/\/[^\s:\/@'"<>]*:)(?![${<])[^\s\/@'"<>]+(?=@)/gi},{name:"aws_access_key",regex:/(?:AKIA|ASIA)[0-9A-Z]{16}/g},{name:"aws_secret_key",regex:new RegExp(`${$m(String.raw`(?:aws_secret_access_key|\bSecretAccessKey)`)}[A-Za-z0-9/+=]{40}`,"gi")},{name:"aws_session_token",regex:new RegExp(`${$m(String.raw`\b(?:aws_session_token|SessionToken)`)}[A-Za-z0-9/+=]{100,}`,"gi")},{name:"github_pat",regex:/\bgh[oprsu]_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{82}\b/g},{name:"openai_key",regex:/\bsk-(?!ant-)[A-Za-z0-9_-]{20,}(?!\w)/g},{name:"anthropic_key",regex:/\bsk-ant-[A-Za-z0-9_-]{20,}(?!\w)/g},{name:"slack_token",regex:/\b(?:xox[abeprs]|xapp)-[A-Za-z0-9-]{10,}(?!\w)/g},{name:"jwt",regex:/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+(?!\w)/g},{name:"private_key_pem",regex:/-----BEGIN (?:RSA |DSA |EC |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY(?: BLOCK)?-----[\s\S]*?-----END (?:RSA |DSA |EC |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY(?: BLOCK)?-----/g},{name:"stripe_key",regex:/\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]{24,}\b/g},{name:"google_api_key",regex:/\bAIza[0-9A-Za-z_-]{35}(?!\w)/g},{name:"gitlab_token",regex:/\bglpat-[A-Za-z0-9_-]{20,}(?:\.[A-Za-z0-9_-]+)*(?!\w)/g},{name:"huggingface_token",regex:/\bhf_[A-Za-z0-9]{30,}\b/g},{name:"npm_token",regex:/\bnpm_[A-Za-z0-9]{36}\b/g},{name:"claude_mem_key",regex:/\bcmem_[A-Za-z0-9_-]{32,}|\bcm_pro_[A-Za-z0-9_-]{8,}/g}],iue=[{name:"generic_password",regex:hq($m(String.raw`\b(?:\w*_?(?:password|passwd)|\w+_pwd)`))},{name:"generic_token",regex:rue},{name:"bearer_token",regex:hq(`(?<=\\bAuthorization${qo}${Ni}:${Ni}${qo}Bearer${Ni})`)}],sue=1024*1024,oue="<redacted type='oversize'/>";MS=`If you see a "<redacted type='...'/>" marker, that field was a recognized secret pattern and was removed before storage. Treat it as a placeholder; do not infer the literal value or copy the marker itself into generated memory content.`;Hu=null,yq=0,lue=5e3,Vu=null,gq=!1,uue={enabled:!0,disabledBuiltinPatterns:[],customPatterns:[],logMatches:!1},due=/"CLAUDE_MEM_REDACT_ENABLED"\s*:\s*"true"/;hue=/(?:password|passwd)$|\w_pwd$/i,yue=/(?:^|_)(?:secret|token|api_key)$/i,gue=new RegExp(`^${Wu}{8,}$`);vue=/^authorization$/i,Eue=new RegExp(`^(${Ni}Bearer${Ni})${No}`,"i");Sue=/^(?:aws_session_token|SessionToken)$/i,wue=/^[A-Za-z0-9/+=]{100,}$/;Iue=/^(?:aws_secret_access_key|SecretAccessKey)$/i,Tue=/^[A-Za-z0-9/+=]{40}$/});var Yu,Eq,_q=k(()=>{"use strict";Yu=Object.freeze({maxImagesPerEvent:4,maxSourceBytes:3145728,maxCanonicalBytes:3145728,maxPixels:24e6,maxDimension:8192,conversionTimeoutSeconds:5,maxConcurrentConversions:1,maxDerivativeBytes:262144,maxDerivativeDimension:1536,maxInlineEncodedBytes:4194304,maxObservationRefs:32,maxLabelChars:64,maxManifestBytes:8192,maxProvenanceBytes:8192,maxSourceLocatorChars:4096,maxGatewayImageBytes:1048576,maxUploadBodyBytes:3211264,ownerQuotaBytes:268435456}),Eq=["image/png","image/jpeg","image/webp"]});function Qu(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function DS(t){return t.type==="image"&&Qu(t.source)?t.source:void 0}function jS(t){return t.type==="image"&&Qu(t.file)?t.file:void 0}function KS(t){return t.type==="image"&&typeof t.data=="string"}function LS(t){return t.type==="image_url"&&Qu(t.image_url)?t.image_url:void 0}function zm(t){let e=typeof t.media_type=="string"?t.media_type:t.type;if(!(typeof e!="string"||!/^image\//i.test(e)))return e.toLowerCase()}var NS=k(()=>{"use strict"});function Tq(t){let e=Object.fromEntries(Iq.map(u=>[u,0]));if(!t.includes("<"))return{text:t,counts:e,total:0};let r=t.length,n=new Int32Array(r+1);n[r]=r;for(let u=r-1;u>=0;u--)n[u]=t.charCodeAt(u)===62?u:n[u+1];let i=new Map,s=[],o=0,a=0;for(;a<r;){if(t.charCodeAt(a)!==60){a+=1;continue}wq.lastIndex=a;let u=wq.exec(t);if(u){let d=u[1],f=i.get(d),m=f&&f.head<f.items.length?f.items[f.head]:void 0;m&&a>=m.attrEnd&&(f.head+=1,s.push([m.start,a+u[0].length]),e[d]+=1,o+=1),a+=u[0].length;continue}Sq.lastIndex=a;let p=Sq.exec(t);if(p&&kue.has(p[1])){let d=p[1],f=a+p[0].length,m={start:a,attrEnd:n[f]},h=i.get(d);h?h.items.push(m):i.set(d,{items:[m],head:0}),a=f;continue}a+=1}s.sort((u,p)=>u[0]-p[0]);let c="",l=0;for(let[u,p]of s)u>l&&(c+=t.slice(l,u)),p>l&&(l=p);return c+=t.slice(l),{text:c,counts:e,total:o}}function gc(t){return Aq(t,Tq(t))}function Aq(t,{text:e,counts:r,total:n}){return n>xq&&_.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:n,maxAllowed:xq,contentLength:t.length}),{stripped:Bm(e.trim(),Gm()).redacted,counts:r}}function Xu(t){let e=r=>{if(typeof r=="string"){let n=Tq(r);return n.total>0?Aq(r,n).stripped:r}return Array.isArray(r)?r.map(e):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).map(([n,i])=>[n,e(i)])):r};return e(t)}var Iq,kue,Sq,wq,xq,Rue,X2e,Z2e,bc=k(()=>{"use strict";V();yc();Iq=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],kue=new Set(Iq),Sq=/<([A-Za-z_][A-Za-z0-9_-]*)/y,wq=/<\/([A-Za-z_][A-Za-z0-9_-]*)\s*>/y;xq=100;Rue=["task-notification"],X2e=new RegExp(`^\\s*<(${Rue.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),Z2e=256*1024});function jue(t){let e=DS(t);if(e&&typeof e.data=="string")return{shape:"anthropic_base64",byteContainerKey:"source",byteFieldKey:"data",encodedBytes:e.data,declaredMimeType:typeof e.media_type=="string"?e.media_type:void 0};let r=jS(t);if(r&&typeof r.base64=="string")return{shape:"claude_read_base64",byteContainerKey:"file",byteFieldKey:"base64",encodedBytes:r.base64,declaredMimeType:zm(r)};if(KS(t))return{shape:"mcp_base64",byteContainerKey:null,byteFieldKey:"data",encodedBytes:t.data,declaredMimeType:typeof t.mimeType=="string"?t.mimeType:void 0};let n=LS(t);if(n&&typeof n.url=="string"){let i=Cue.exec(n.url);if(i)return{shape:"openai_data_url",byteContainerKey:"image_url",byteFieldKey:"url",encodedBytes:i[2],declaredMimeType:i[1].toLowerCase()}}if(r&&typeof r.path=="string")return{shape:"trusted_tool_file",byteContainerKey:"file",trustedFilePath:r.path,declaredMimeType:zm(r)}}function Kue(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function US(t,e){let r={};for(let[n,i]of Object.entries(t))n!==e&&Object.defineProperty(r,n,{value:i,enumerable:!0,writable:!0,configurable:!0});return r}function Lue(t){return t.startsWith("{")||t.startsWith("[")||t.startsWith('"')}function Rq(t,e,r="capture"){let n=[],i=[],s=0,o=!1,a=0,c=0,l=(b,v)=>{let E={version:1,state:r==="disabled"?"disabled":"rejected",code:b,inspection:"uninspected",...v?{label:v}:{}};return i.length<Yu.maxImagesPerEvent&&i.push(E),E},u=b=>{let v=b.encodedBytes?.length??0;if(r==="disabled")return"converter_disabled";if(r==="reject"||a>Yu.maxImagesPerEvent||v>Yu.maxInlineEncodedBytes||c+v>Yu.maxInlineEncodedBytes)return"source_too_large";if(b.declaredMimeType&&!Oue.has(b.declaredMimeType))return"unsupported_format"},p=(b,v,E,S)=>{let w={},x=!1;for(let[O,C]of Object.entries(b)){let J=O===S?C:h(C,`${v}/${Kue(O)}`,E+1);J!==C&&(x=!0),Object.defineProperty(w,O,{value:J,enumerable:!0,writable:!0,configurable:!0})}return x?w:b},d=(b,v,E,S)=>{a+=1;let w=`event1_image${a}`,x=v.encodedBytes?.length??0,O=u(v);if(c+=x,O||n.push({shape:v.shape,...v.encodedBytes!==void 0?{encoded:v.encodedBytes}:{},...v.trustedFilePath!==void 0?{filePath:v.trustedFilePath}:{},...v.declaredMimeType!==void 0?{mimeType:v.declaredMimeType}:{},pointer:E,label:w}),v.trustedFilePath!==void 0){if(!O&&r==="dispatch")return p(b,E,S);if(O)return{...p(b,E,S),media_status:l(O,w)};let ke=b[v.byteContainerKey],T=`${E}/${v.byteContainerKey}`;return{...p(b,E,S,v.byteContainerKey),[v.byteContainerKey]:p(US(ke,"path"),T,S+1),media_status:{version:1,state:"captured",inspection:"uninspected",label:w}}}if(!O&&r==="dispatch"){if(v.byteContainerKey===null)return p(b,E,S,v.byteFieldKey);let ke=b[v.byteContainerKey],T=`${E}/${v.byteContainerKey}`,K=p(ke,T,S+1,v.byteFieldKey),M=p(b,E,S,v.byteContainerKey);return K===ke?M:{...M,[v.byteContainerKey]:K}}let C={elided:qS,bytes:x,...v.declaredMimeType?{media_type:v.declaredMimeType}:{}},J=O?l(O,w):{version:1,state:"captured",inspection:"uninspected",label:w};if(v.byteContainerKey===null){let ke=US(b,v.byteFieldKey);return{...p(ke,E,S),...C,media_status:J}}let j=b[v.byteContainerKey],q=US(j,v.byteFieldKey),ee=`${E}/${v.byteContainerKey}`;return{...p(b,E,S,v.byteContainerKey),[v.byteContainerKey]:{...p(q,ee,S+1),...C},media_status:J}},f=(b,v,E)=>{if(/^data:image\//i.test(b))return{elided:qS,bytes:b.length,media_status:l("unsupported_source")};if(!Lue(b)||!kq.test(b))return b;let S;try{S=JSON.parse(b)}catch{return b}let w=h(S,v,E+1);return w===S?b:JSON.stringify(w)},m=b=>{if(b===null||typeof b!="string"&&typeof b!="object")return b;let v=typeof b=="string"?b:JSON.stringify(b);return typeof v!="string"||!kq.test(v)||!Pue.test(v)?b:{elided:qS,bytes:v.length,media_status:l("source_too_large")}},h=(b,v,E)=>{if(s+=1,s>Mue||E>Due)return o=!0,m(b);if(typeof b=="string")return f(b,v,E);if(Array.isArray(b)){let w=!1,x=b.map((O,C)=>{let J=h(O,`${v}/${C}`,E+1);return J!==O&&(w=!0),J});return w?x:b}if(!Qu(b))return b;let S=jue(b);return S?d(b,S,v,E):p(b,v,E)};return{toolInput:h(t,"/tool_input",0),toolResponse:h(e,"/tool_response",0),candidates:n,failures:i,walkLimitReached:o}}var Oue,Cue,kq,qS,Mue,Pue,Due,iUe,sUe,oUe,aUe,Oq=k(()=>{"use strict";_q();NS();bc();Oue=new Set(Eq),Cue=/^data:(image\/[^;,]+);base64,(.*)$/is,kq=/image(?:"|\\|_url)|data:image\//i,qS="image data withheld from the observer",Mue=4096,Pue=/[A-Za-z0-9+/]{32,}/,Due=20;iUe=5*1024*1024,sUe=64*1024,oUe=16*1024,aUe=32*1024});function Nue(t,e,r){t.path!=="/tv"&&t.path!=="/tv.html"&&(e.setHeader("Content-Security-Policy","frame-ancestors 'none'"),e.setHeader("X-Frame-Options","DENY")),r()}function jq(){let t=[Nue],e=FS.default.json({limit:"5mb"});t.push((i,s,o)=>{if(i.method==="POST"&&/^\/api\/spool\/ingest\/?$/i.test(i.path))return o();e(i,s,o)}),t.push((i,s,o)=>{let c=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(m=>i.path.endsWith(m)),l=i.path==="/api/logs";if(i.path.startsWith("/health")||i.path==="/"||c||l)return o();let u=Date.now(),p=`${i.method}-${Date.now()}`,d=Wue(i.method,i.path,i.body);_.debug("HTTP",`\u2192 ${i.method} ${i.path}`,{requestId:p},d);let f=s.send.bind(s);s.send=function(m){let h=Date.now()-u;return _.debug("HTTP",`\u2190 ${s.statusCode} ${i.path}`,{requestId:p,duration:`${h}ms`}),f(m)},o()});let r=Lo(),n=Pq.default.join(r,"plugin","ui");return t.push(FS.default.static(n)),t}function Kq(t){return(e,r,n)=>{let i=e.headers.origin;if(e.method!=="DELETE"||i===void 0||AS(i,e.headers.host,t)){n();return}_.warn("SECURITY","Refused a DELETE from a page other than the viewer",{origin:i,method:e.method,path:e.path}),r.status(403).json({error:"Forbidden",message:"Deletes are accepted only from the claude-mem viewer itself (or an origin in CLAUDE_MEM_ALLOWED_ORIGINS), not from other pages."})}}function Uue(t){let e=new Set(que),r=t.workerHost.trim().toLowerCase();r&&e.add(r);for(let n of t.allowedOrigins)try{e.add(new URL(n).hostname.toLowerCase())}catch{}return e}function Fue(t,e){if(!t)return!0;let r=jm(t);return(0,Dq.isIP)(r)!==0||r.endsWith(".localhost")?!0:e.has(r)}function Lq(t){let e=Uue(t);return(r,n,i)=>{let s=r.headers.host;if(Fue(s,e)){i();return}let o=jm(s??"");_.warn("SECURITY","Refused a request whose Host is not a trusted name (DNS rebinding check)",{host:o,method:r.method,path:r.path}),n.status(403).json({error:"Forbidden",message:`Host "${o}" is not trusted. To reach the worker by this name, add its origin (for example http://${s}) to CLAUDE_MEM_ALLOWED_ORIGINS and restart the worker.`})}}function Nq(t){let e=new Set(t?.allowedOrigins??[]);return(r,n,i)=>{let s=r.headers.origin;if(s){if(!(IS(s)||e.has(s.toLowerCase())||t!==void 0&&TS(s,r.headers.host))){n.status(403).json({error:"Forbidden",message:"CORS not allowed"});return}n.setHeader("Access-Control-Allow-Origin",s),n.setHeader("Vary","Origin")}if(r.method==="OPTIONS"){n.setHeader("Access-Control-Allow-Methods","GET,HEAD,POST,PUT,PATCH,DELETE"),n.setHeader("Access-Control-Allow-Headers","Content-Type,Authorization,X-Requested-With"),n.status(204).end();return}i()}}function Hm(t,e,r){let n=t.ip||t.connection.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){_.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:t.path,clientIp:n,method:t.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}r()}function Bue(t,e){let r=(0,vc.createHash)("sha256").update(t,"utf8").digest(),n=(0,vc.createHash)("sha256").update(e,"utf8").digest();if(r.length!==n.length)return!1;try{return(0,vc.timingSafeEqual)(r,n)}catch(i){let s=i instanceof Error?i:new Error(String(i));return _.warn("SECURITY","timing-safe secret comparison failed",{},s),!1}}function Gue(t){return Jue.has(t.method.toUpperCase())?$ue.has(t.path)?!t.expectedToken||!t.presentedToken?{allow:!1,status:401,reason:"token"}:Bue(t.presentedToken,t.expectedToken)?{allow:!0}:{allow:!1,status:401,reason:"token"}:{allow:!1,status:404,reason:"path"}:{allow:!1,status:403,reason:"method"}}function Hue(t){let e=Date.now(),r=Uo.get(t.clientIp);if(r&&e-r.windowStart>Mq&&(r.count=0,r.windowStart=e),!r){if(Uo.size>=Cq){let n=null,i=1/0;for(let[s,o]of Uo)e-o.windowStart>Mq?Uo.delete(s):o.windowStart<i&&(i=o.windowStart,n=s);n!==null&&Uo.size>=Cq&&Uo.delete(n)}r={count:0,windowStart:e},Uo.set(t.clientIp,r)}r.count+=1,r.count<=zue?_.warn("SECURITY","Remote request denied",t):_.debug("SECURITY","Remote request denied",t)}function Vue(t){let e=t.query?.token;if(Array.isArray(e)||typeof e!="string")return null;let r=e.trim();return r.length>0?r:null}function qq(t){return(e,r,n)=>{if(Dm(e)&&!Km(e)){n();return}let i=e.ip||e.socket.remoteAddress||"",s=Pm(e.header("authorization")??"")||e.header("x-api-key")?.trim()||Vue(e)||null,o=Gue({method:e.method,path:e.path,presentedToken:s,expectedToken:t.getToken()});if(!o.allow){Hue({path:e.path,method:e.method,clientIp:i,reason:o.reason}),o.status===404?r.status(404).json({error:"Not found"}):o.status===403?r.status(403).json({error:"Forbidden",message:"Observation TV remote access is read-only"}):r.status(401).json({error:"Unauthorized",message:"Missing or invalid Observation TV token"});return}r.setHeader("Cache-Control","no-store"),n()}}function Wue(t,e,r){if(!r||Object.keys(r).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=r.tool_name||"?",i=Rq(r.tool_input,void 0,"disabled").toolInput;return`tool=${bq(_.formatTool(n,i))}`}return e.includes("/summarize")?"requesting summary":""}var FS,Pq,Dq,vc,que,$ue,Jue,zue,Cq,Mq,Uo,Uq=k(()=>{"use strict";FS=ut(Rm(),1),Pq=ut(require("path"),1),Dq=require("net"),vc=require("crypto");Nt();xS();V();kS();yc();Oq();kS();que=["localhost","host.docker.internal"];$ue=new Set(["/tv","/tv.html","/stream","/api/observations"]),Jue=new Set(["GET","HEAD"]);zue=10,Cq=512,Mq=6e4,Uo=new Map});function Fq(t,e,r,n){let i={error:t,message:e};return r&&(i.code=r),n&&(i.details=n),i}function Jq(t,e){e.status(404).json(Fq("NotFound",`Cannot ${t.method} ${t.path}`))}var Ec,$q,Bq=k(()=>{"use strict";V();Ec=class extends Error{constructor(r,n=500,i,s){super(r);this.statusCode=n;this.code=i;this.details=s;this.name="AppError"}statusCode;code;details};$q=(t,e,r,n)=>{let i=t.status,s=t instanceof Ec?t.statusCode:typeof i=="number"&&i>=400&&i<500?i:500;_.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:s,error:t.message,code:t instanceof Ec?t.code:void 0},t);let o=Fq(t.name||"Error",t.message,t instanceof Ec?t.code:void 0,t instanceof Ec?t.details:void 0);r.status(s).json(o)}});var Yue,Que,IUe,Gq=k(()=>{"use strict";Yue=new Set([".cmd",".bat"]),Que=new Set([".exe",".com"]),IUe=new Set([...Que,...Yue])});function _c(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(Zue.has(r)){e[r]=n;continue}JS.has(r)||$S.some(i=>r.startsWith(i))||(e[r]=n)}return e}var $S,JS,Xue,Zue,Zu=k(()=>{"use strict";$S=["CLAUDECODE_","CLAUDE_CODE_"],JS=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),Xue=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy","npm_config_noproxy"]),Zue=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_TMPDIR","CLAUDE_CODE_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS",...Xue])});function Vq(t,e,r){if(r.status!==0)return null;if(typeof r.stdout!="string")return _.warn("SYSTEM","captureProcessStartToken: start-token probe returned no stdout",{pid:e,source:t,status:r.status}),null;let n=r.stdout.trim();return n.length>0?n:null}function tde(t){BS+=1;let e=(0,GS.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{..._c(process.env),LC_ALL:"C",LANG:"C"}});return Vq("powershell-cim",t,e)}function rde(t,e=!1){if(!e){let n=zq.get(t);if(n&&(t===process.pid||Date.now()-n.capturedAtMs<ede))return n.token}let r=null;try{r=tde(t)}catch(n){_.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:n instanceof Error?n.message:String(n)}),r=null}return(r!==null||t!==process.pid)&&zq.set(t,{token:r,capturedAtMs:Date.now()}),r}function Wq(t,e){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux"){BS+=1;try{let r=(0,Hq.readFileSync)(`/proc/${t}/stat`,"utf-8"),n=r.lastIndexOf(") ");if(n<0)return null;let s=r.slice(n+2).split(" ")[19];return s&&/^\d+$/.test(s)?s:null}catch(r){return _.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}if(process.platform==="win32")return rde(t,e);BS+=1;try{let r=(0,GS.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{..._c(process.env),LC_ALL:"C",LANG:"C"}});return Vq("ps-lstart",t,r)}catch(r){return _.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}function qi(t){return Wq(t,!1)}function Ui(t,e){if(e===null)return!0;let r=Wq(t,!0);return r===null?!0:r===e}var GS,Hq,ede,zq,BS,zS=k(()=>{"use strict";GS=require("child_process"),Hq=require("fs");V();Zu();ede=5e3,zq=new Map,BS=0});async function ade(t,e){let r=Date.now()+e,n=i=>{try{return process.kill(i,0),!0}catch(s){return s.code==="EPERM"}};for(;t.some(n);){let i=r-Date.now();if(i<=0)return;await new Promise(s=>setTimeout(s,Math.min(ode,i)))}}async function ti(t,e={}){let r=e.signalMode==="immediate",n=e.expectedStartToken!==void 0?e.expectedStartToken:qi(t),i=()=>Ui(t,n);if(!i()){_.warn("PROCESS","Skipping tree-kill: root PID was reused since it was captured",{pid:t});return}if(_.debug("PROCESS",`Killing process tree rooted at PID ${t}`,{immediate:r}),process.platform==="win32"){try{await HS("taskkill",["/PID",String(t),"/T","/F"],{timeout:5e3,windowsHide:!0})}catch(s){let o=s.code,a=String(s.stderr??""),c=s instanceof Error?s.message:String(s);if(o===nde||ide.test(`${a} ${c}`)){_.debug("PROCESS","taskkill reported the process was already gone",{pid:t});return}throw new Vm(t,`taskkill failed for PID ${t} (exit ${String(o)}): ${a.trim()||c}`,{cause:s})}return}try{let s=r?"SIGKILL":"SIGTERM",o=await Wm(t);for(let l of o){if(!Ui(l.pid,l.startToken)){_.debug("PROCESS",`Skipping ${s}: descendant PID was reused since enumeration`,{pid:l.pid,rootPid:t});continue}try{process.kill(l.pid,s)}catch{}}if(i())try{process.kill(t,s)}catch(l){let u=l instanceof Error?l:new Error(String(l)),p=u.code;p!=="ESRCH"&&_.debug("PROCESS",`Failed to ${s} PID ${t}`,{code:p},u)}else _.warn("PROCESS","Skipping root signal: PID was reused during descendant enumeration",{pid:t,signal:s});r||await ade([t,...o.map(l=>l.pid)],sde);let a=i()?await Wm(t):[],c=new Map;for(let l of o)c.set(l.pid,l.startToken);for(let l of a)c.set(l.pid,l.startToken);for(let[l,u]of c){if(!Ui(l,u)){_.debug("PROCESS","Skipping SIGKILL: descendant PID was reused since the scan",{pid:l,rootPid:t});continue}try{process.kill(l,"SIGKILL")}catch{}}if(!r&&i())try{process.kill(t,"SIGKILL")}catch{}}catch(s){throw new Vm(t,`tree-kill failed for PID ${t}: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}async function cde(){return process.platform==="win32"?dde():process.platform==="linux"?lde():ude()}function lde(){let t=[],e;try{e=(0,Ym.readdirSync)("/proc")}catch(r){return _.warn("PROCESS","Cannot read /proc \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),t}for(let r of e){if(!/^\d+$/.test(r))continue;let n;try{n=(0,Ym.readFileSync)(`/proc/${r}/stat`,"utf-8")}catch{continue}let i=n.lastIndexOf(") ");if(i<0)continue;let s=n.slice(i+2).split(" "),o=Number.parseInt(s[1]??"",10),a=s[19];Number.isFinite(o)&&t.push({pid:Number.parseInt(r,10),ppid:o,startToken:a&&/^\d+$/.test(a)?a:null})}return t}async function ude(){let t;try{t=(await HS("ps",["-eo","pid=,ppid=,lstart="],{timeout:1e4,maxBuffer:33554432,env:{...process.env,LC_ALL:"C",LANG:"C"}})).stdout}catch(r){return _.warn("PROCESS","Cannot enumerate the process table \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),[]}let e=[];for(let r of t.split(`
|
|
68
68
|
`)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);if(!n)continue;let i=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:i.length>0?i:null})}return e}async function dde(){let t;try{t=(await HS("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,@{Name='StartToken';Expression={$_.CreationDate.ToString('yyyyMMddHHmmss.ffffff')}} | ConvertTo-Csv -NoTypeInformation"],{timeout:3e4,windowsHide:!0,maxBuffer:33554432})).stdout}catch(r){return _.warn("PROCESS","Cannot enumerate the Windows process table \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),[]}let e=[];for(let r of t.split(/\r?\n/).slice(1)){let n=r.match(/^"(\d+)","(\d+)","(.*)"$/);if(!n)continue;let i=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:i.length>0?i:null})}return e}async function Wm(t){let e=await cde(),r=new Map;for(let o of e){let a=r.get(o.ppid);a?a.push(o):r.set(o.ppid,[o])}let n=new Set([t]),i=[],s=o=>{for(let a of r.get(o)??[])n.has(a.pid)||(n.add(a.pid),s(a.pid),i.push({pid:a.pid,startToken:a.startToken}))};return s(t),i}var Yq,Ym,Qq,HS,nde,ide,sde,ode,Vm,ed=k(()=>{"use strict";Yq=require("child_process"),Ym=require("fs"),Qq=require("util");V();zS();HS=(0,Qq.promisify)(Yq.execFile),nde=128,ide=/not found|no running instance|no tasks/i,sde=500,ode=10;Vm=class extends Error{pid;constructor(e,r,n){super(r,n),this.name="ProcessTreeKillError",this.pid=e}}});function _t(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;return r==="EPERM"?!0:(_.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return _.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function Qm(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!_t(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function Fo(t){if(!t||!_t(t.pid))return!1;if(!t.startToken)return!0;let e=qi(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||_.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}function Zq(t,e=yde){if(!Fo(t))return!1;if(t.startToken||e.platform!=="linux")return!0;let r;try{r=e.readCommandLine(t.pid)}catch(i){return _.debug("SYSTEM","Could not read the command line of a token-less worker PID; trusting the live PID",{pid:t.pid,error:i instanceof Error?i.message:String(i)}),!0}let n=r.split("\0").some(i=>Xq.default.basename(i)==="worker-service.cjs");return n||_.debug("SYSTEM","Token-less worker PID now belongs to another program (PID reused)",{pid:t.pid}),n}function Xm(){return VS||(VS=new YS),VS}function WS(){let t=gde.shift();t&&t.notify()}var td,Xq,pde,fde,mde,hde,yde,YS,VS,zUe,gde,Is=k(()=>{"use strict";Gq();td=require("fs"),Xq=ut(require("path"),1);V();Po();Zu();Nt();zS();ed();pde=5e3,fde=1e3,mde=Le.supervisorRegistry(),hde=null;yde={platform:process.platform,readCommandLine:t=>(0,td.readFileSync)(`/proc/${t}/cmdline`,"utf-8")};YS=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(e=mde){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,!(0,td.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,td.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[i,s]of Object.entries(n))this.entries.set(i,s)}catch(r){r instanceof Error?_.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):_.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&_.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}retainSupersededEntry(e,r){let n=this.entries.get(e);if(!n||n.pid===r||!_t(n.pid))return;let i=`${e}#superseded:${n.pid}`;this.entries.set(i,n);let s=this.runtimeProcesses.get(e);s&&(this.runtimeProcesses.set(i,s),this.runtimeProcesses.delete(e)),_.warn("SYSTEM","Registry id reused while the previous process was still alive; kept it for reaping",{id:e,supersededId:i,supersededPid:n.pid,incomingPid:r})}register(e,r,n){this.initialize(),this.retainSupersededEntry(e,r.pid),this.entries.set(e,r),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e,r){this.initialize();let n=e,i=this.entries.get(n);r!==void 0&&i?.pid!==r&&(n=`${e}#superseded:${r}`,i=this.entries.get(n),i?.pid!==r)||i&&(this.entries.delete(n),this.runtimeProcesses.delete(n),this.persist(),i?.type==="sdk"&&WS())}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let n=Date.parse(e.startedAt),i=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(i)?0:i)})}getBySession(e){let r=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[n,i]of this.entries)_t(i.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,i.type==="sdk"&&(r+=1));e>0&&this.persist();for(let n=0;n<r;n+=1)WS();return e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;_.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:n,pids:r.map(a=>a.pid)});let i=r.filter(a=>_t(a.pid)),s=new Map(i.map(a=>[a.pid,qi(a.pid)]));for(let a of i)try{process.platform==="win32"?await ti(a.pid,{expectedStartToken:s.get(a.pid)??null}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):_.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}await Qm(i,pde);let o=i.filter(a=>_t(a.pid));for(let a of o){_.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});let c=s.get(a.pid)??null;if(!Ui(a.pid,c)){_.warn("SYSTEM","Skipping SIGKILL: session process PID was reused during the grace window",{pid:a.pid,sessionId:n});continue}try{process.platform==="win32"?await ti(a.pid,{expectedStartToken:c}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(l){l instanceof Error?l.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},l):_.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(l)})}}if(o.length>0){let a=Date.now()+fde;for(;Date.now()<a&&o.filter(l=>_t(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let a of r)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of r)a.type==="sdk"&&WS();return _.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:n,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};try{on(this.registryPath,e),this.persistDegraded=!1}catch(r){this.reportPersistFailure(r)}}reportPersistFailure(e){if(this.persistDegraded)return;this.persistDegraded=!0;let r=e instanceof Error?e:new Error(String(e));_.warn("SYSTEM","Failed to persist supervisor registry; keeping it in memory",{path:this.registryPath},r);try{hde?.({errorCategory:r.code??"unknown"})}catch{}}},VS=null;zUe=180*1e3,gde=[]});async function t2(t){let e=t.currentPid??process.pid,r=t.pidFilePath??bde,n=t.registry.getAll(),i=[...n].filter(c=>c.pid!==e).sort((c,l)=>Date.parse(l.startedAt)-Date.parse(c.startedAt)),s=new Map,o=new Map;for(let c of i){if(!_t(c.pid)){t.registry.unregister(c.id);continue}o.set(c.id,qi(c.pid)),s.set(c.id,await Wm(c.pid));try{await e2(c,"SIGTERM")}catch(l){l instanceof Error?_.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:c.pid,pgid:c.pgid,type:c.type},l):_.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(l)})}}await Qm(i,5e3);let a=i.filter(c=>_t(c.pid)||(s.get(c.id)??[]).some(l=>_t(l.pid)));for(let c of a){let l=Ui(c.pid,o.get(c.id)??null);l||_.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:c.pid,type:c.type});try{l&&await e2(c,"SIGKILL")}catch(u){u instanceof Error?_.debug("SYSTEM","Failed to force kill child process",{pid:c.pid,pgid:c.pgid,type:c.type},u):_.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(u)})}finally{Ede(s.get(c.id)??[],c.pid)}}await Qm(a,1e3);for(let c of i)t.registry.unregister(c.id);for(let c of n.filter(l=>l.pid===e))t.registry.unregister(c.id);vde(r,e),t.registry.pruneDeadEntries()}function vde(t,e,r=!1){if(!(0,Sc.existsSync)(t))return;let n=null;try{let o=JSON.parse((0,Sc.readFileSync)(t,"utf-8"));n=typeof o.pid=="number"?o.pid:null}catch(o){_.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:o instanceof Error?o.message:String(o)});return}let i=e!==null&&n===e,s=n===null||!_t(n);if(!i&&!(r&&s)){_.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:n,currentPid:e});return}try{(0,Sc.rmSync)(t,{force:!0})}catch(o){o instanceof Error?_.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},o):_.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(o)})}}function Ede(t,e){for(let{pid:r,startToken:n}of t)if(!(r===e||!_t(r))){if(!Ui(r,n)){_.debug("SYSTEM","Skipping reap: PID was recycled during the grace window",{pid:r,rootPid:e});continue}try{process.kill(r,"SIGKILL"),_.debug("SYSTEM","Reaped orphaned descendant during shutdown cascade",{pid:r,rootPid:e})}catch(i){let s=i instanceof Error?i.code:void 0;s!=="ESRCH"&&_.warn("SYSTEM","Failed to reap orphaned descendant during shutdown cascade",{pid:r,rootPid:e,errno:s})}}}async function e2(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}if(e==="SIGKILL"){await ti(r,{signalMode:"immediate"});return}try{process.kill(r,e)}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}return}await ti(r)}var Sc,bde,r2=k(()=>{"use strict";Sc=require("fs");V();Is();Nt();ed();bde=Le.workerPid()});function _de(){let e=Xm().pruneDeadEntries();e>0&&_.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function i2(){wc===null&&(wc=setInterval(_de,n2),wc.unref(),_.debug("SYSTEM","Health checker started",{intervalMs:n2}))}function s2(){wc!==null&&(clearInterval(wc),wc=null,_.debug("SYSTEM","Health checker stopped"))}var n2,wc,o2=k(()=>{"use strict";V();Is();n2=3e4,wc=null});function xde(t){let e=[];for(let r of t.split(`
|
|
69
|
-
`)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);n&&e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),command:n[3].trim()})}return e}async function Ide(){let t=await Sde("ps",["-e","-o","pid=","-o","ppid=","-o","args="],{timeout:1e4,maxBuffer:33554432});return xde(t.stdout)}function Tde(t,e){let r=t.filter(o=>wde.test(o.command)&&o.pid!==e.selfPid),n=new Set(r.map(o=>o.pid)),i=r.filter(o=>!n.has(o.ppid)),s=i.filter(o=>o.ppid===e.selfPid?!1:o.ppid===1?!0:!e.isAlive(o.ppid));return{matched:r,roots:i,orphans:s}}async function l2(t={}){let e=t.platform??process.platform,r={matched:0,trees:0,orphans:0,killed:0,failed:0,unregistered:0,skipped:null};if(e==="win32")return r.skipped="windows",r;let n=t.readTable??Ide,i=t.isAlive??_t,s=t.killTree??(f=>ti(f,{signalMode:"graceful"})),o=t.selfPid??process.pid,a;try{a=await n()}catch(f){return _.warn("PROCESS","Orphaned chroma-mcp sweep skipped: cannot read the process table",{error:f instanceof Error?f.message:String(f)}),r.skipped="unreadable",r}let{matched:c,roots:l,orphans:u}=Tde(a,{isAlive:i,selfPid:o});if(r.matched=c.length,r.trees=l.length,r.orphans=u.length,u.length===0)return _.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:r.matched,trees:r.trees}),r;_.warn("PROCESS","Reaping orphaned chroma-mcp trees left by dead workers",{orphans:u.length,roots:u.map(f=>f.pid)});let p=new Set,d=8;for(let f=0;f<u.length;f+=d){let m=u.slice(f,f+d);(await Promise.allSettled(m.map(b=>s(b.pid)))).forEach((b,v)=>{let E=m[v];b.status==="fulfilled"?(r.killed+=1,p.add(E.pid)):(r.failed+=1,_.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:E.pid,ppid:E.ppid,error:b.reason instanceof Error?b.reason.message:String(b.reason)}))})}if(t.registry)for(let f of t.registry.getAll())f.type==="chroma"&&p.has(f.pid)&&(t.registry.unregister(f.id),r.unregistered+=1);return _.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:r.orphans,killed:r.killed,failed:r.failed,unregistered:r.unregistered}),r}var a2,c2,Sde,wde,u2=k(()=>{"use strict";a2=require("child_process"),c2=require("util");V();ed();Is();Sde=(0,c2.promisify)(a2.execFile),wde=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/});function d2(){return kde}function Rde(t={}){let e=t.pidFilePath??Ade;if(!(0,$o.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,$o.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,$o.rmSync)(e,{force:!0}),"invalid"}return Zq(r)&&r?((t.logAlive??!0)&&_.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(t.removeStale===!1||(_.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,$o.rmSync)(e,{force:!0})),"stale")}var $o,Ade,QS,kde,p2=k(()=>{"use strict";$o=require("fs");V();Is();r2();o2();u2();Nt();Is();Ade=Le.workerPid(),QS=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(),Rde({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,l2({registry:this.registry}).catch(r=>{_.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),i2()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=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",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{_.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}s2(),this.stopPromise=t2({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,n){this.registry.register(e,r,n)}unregisterProcess(e,r){this.registry.unregister(e,r)}getRegistry(){return this.registry}},kde=new QS(Xm())});function XS(t,e,r){t.on("finish",async()=>{try{await r()}finally{process.exit(0)}}),t.json(e)}var f2=k(()=>{"use strict"});function ZS(t,e=Date.now){return Math.max(0,Math.floor((e()-t)/1e3))}var m2=k(()=>{"use strict"});var h2=k(()=>{"use strict"});function ew(){let t=Array.from(Ode.values()).map(e=>({...e})).sort((e,r)=>e.dependency.localeCompare(r.dependency));return{degraded:t.length>0,statuses:t}}var EFe,Ode,y2=k(()=>{"use strict";h2();EFe=5*6e4,Ode=new Map});function tw(t,e){return Jo(t)===Jo(e)}function g2(t,e){let r=Jo(t);return r!==void 0&&r>e}function Mde(t){let e=new Map,r=new Set;if(!t||typeof t!="object")return{windows:e,malformed:r};for(let n of Cde){let i=t[n];if(!i||typeof i!="object")continue;let{utilization:s,resetsAt:o}=i;(!b2(s)||!b2(o))&&r.add(n);let a={};nw(s)&&(a.utilization=s),nw(o)&&(a.resetsAt=Jo(o)),(a.utilization!==void 0||a.resetsAt!==void 0)&&e.set(n,a)}return{windows:e,malformed:r}}function nw(t){return typeof t=="number"&&Number.isFinite(t)}function b2(t){return t===void 0||nw(t)}function Pde(t,e){return e.status!=="rejected"?!1:!t||t.status!=="rejected"?!0:t.resetsAt!==e.resetsAt}function Jo(t){if(!(typeof t!="number"||!Number.isFinite(t)))return t<1e12?t*1e3:t}function Dde(t,e){return e!==void 0&&t.profile!==void 0&&t.profile!==e}var Cde,rw,v2,IFe,E2=k(()=>{"use strict";Li();Nt();V();Cde=["five_hour","seven_day"],rw=class{entries=new Map;rejections=new Map;set(e){if(!e||typeof e!="object")return!1;let{unifiedWindows:r,...n}=e,i=e.rateLimitType??"default",s=this.rejections.get(i),o=Date.now(),{windows:a,malformed:c}=Mde(r);for(let[d,f]of a){if(d===i||c.has(d))continue;let m=this.entries.get(d),h=m&&!Dde(m,e.profile)?m:void 0,b=g2(h?.resetsAt,o)?h?.resetsAt:void 0,v=f.resetsAt??b,E=f.utilization===void 0&&h?.status==="rejected"&&tw(v,h.resetsAt)&&g2(v,o);this.entries.set(d,{rateLimitType:d,...f,resetsAt:v,...E?{status:"rejected"}:{},...e.profile!==void 0?{profile:e.profile}:{},observedAt:o});let S=this.rejections.get(d);S&&f.resetsAt!==void 0&&!tw(f.resetsAt,S.resetsAt)&&this.rejections.delete(d)}let l=e.rateLimitType?a.get(e.rateLimitType):void 0,u={...n,utilization:e.utilization??l?.utilization,resetsAt:Jo(e.resetsAt)??l?.resetsAt,overageResetsAt:Jo(e.overageResetsAt),observedAt:o};this.entries.set(i,u);let p=Pde(s,u);return u.status==="rejected"?this.rejections.set(i,u):(e.status!==void 0||s&&u.resetsAt!==void 0&&!tw(u.resetsAt,s.resetsAt))&&this.rejections.delete(i),p}get(e){return e?this.entries.get(e):this.entries.get("default")}getMostRecentByWindow(e=Date.now()){let r=n=>{let i=this.entries.get(n);if(!i)return;let s=Jo(i.resetsAt);return s!==void 0&&s<=e?{...i,expired:!0}:i};return{five_hour:r("five_hour"),seven_day:r("seven_day"),seven_day_opus:r("seven_day_opus"),seven_day_sonnet:r("seven_day_sonnet"),seven_day_overage_included:r("seven_day_overage_included"),overage:r("overage")}}get size(){return this.entries.size}restoreForTesting(e,r){this.rejections.delete(e),r?(this.entries.set(e,r),r.status==="rejected"&&this.rejections.set(e,r)):this.entries.delete(e)}};v2=new rw;IFe=900*1e3});function Lde(){try{let{dlopen:t,FFIType:e,ptr:r,suffix:n}=require("bun:ffi"),i=t(`kernel32.${n}`,{SetHandleInformation:{args:[e.ptr,e.u32,e.u32],returns:e.i32}}),s=t(`ws2_32.${n}`,{getsockname:{args:[e.u64,e.ptr,e.ptr],returns:e.i32},ntohs:{args:[e.u16],returns:e.u16}});return{setHandleInformation:i.symbols.SetHandleInformation,getsockname:s.symbols.getsockname,ntohs:s.symbols.ntohs,ptr:r}}catch{return null}}function Nde(t){let e=t.address();return!e||typeof e=="string"?null:e.port}function qde(t,e,r){let i=t._handle?.fd;if(typeof i=="number"&&i>0)return i;let s=new Uint8Array(28),o=new Int32Array([16]);for(let a=4;a<Kde;a+=4){if(o[0]=16,s.fill(0),r.getsockname(a,r.ptr(s),r.ptr(o))!==0)continue;if(r.ntohs(s[2]|s[3]<<8)===e)return a}return null}function _2(t){if(process.platform!=="win32")return!1;let e=Nde(t);if(e===null||e<=0)return _.debug("SYSTEM","Windows listen socket inherit clear skipped: no bound port"),!1;let r=Lde();if(!r)return _.warn("SYSTEM","Windows listen socket inherit clear skipped: bun:ffi unavailable"),!1;let n=qde(t,e,r);if(n===null)return _.warn("SYSTEM","Windows listen socket inherit clear skipped: listen handle not found",{port:e}),!1;try{return r.setHandleInformation(n,jde,0)?(_.debug("SYSTEM","Cleared HANDLE_FLAG_INHERIT on Windows listen socket",{port:e,socketHandle:n}),!0):(_.warn("SYSTEM","SetHandleInformation failed to clear HANDLE_FLAG_INHERIT on listen socket",{port:e,socketHandle:n}),!1)}catch(i){let s=i instanceof Error?i:new Error(String(i));return _.warn("SYSTEM","Failed to clear Windows listen socket inherit flag",{port:e,socketHandle:n},s),!1}}var jde,Kde,S2=k(()=>{"use strict";V();jde=1,Kde=16384});var w2,x2=k(()=>{"use strict";w2=["ready","failed"]});function $de(){if(sw)return sw.text;let t;try{t=cw.readFileSync(iw,"utf-8"),_.debug("SYSTEM","Cached SKILL.md on first request",{path:iw,bytes:Buffer.byteLength(t,"utf-8")})}catch(e){_.debug("SYSTEM","SKILL.md not present, /api/instructions will 404 for topic queries",{path:iw,message:e instanceof Error?e.message:String(e)}),t=null}return sw={text:t},t}function Jde(){if(ow)return ow;let t=new Map;for(let e of mS){let r=rd.default.join(Fde,`${e}.md`);try{t.set(e,cw.readFileSync(r,"utf-8"))}catch(n){_.debug("SYSTEM","Operation instruction file not present",{path:r,message:n instanceof Error?n.message:String(n)})}}return t.size>0&&_.debug("SYSTEM","Cached operation instruction files on first request",{count:t.size,operations:Array.from(t.keys())}),ow=t,t}function Bde(t){t.setHeader("X-Content-Type-Options","nosniff"),t.setHeader("X-Frame-Options","DENY"),t.setHeader("X-DNS-Prefetch-Control","off"),t.setHeader("Referrer-Policy","no-referrer"),t.setHeader("Cross-Origin-Opener-Policy","same-origin"),t.setHeader("Cross-Origin-Resource-Policy","same-origin"),t.setHeader("Origin-Agent-Cluster","?1"),t.removeHeader("X-Powered-By")}var I2,T2,cw,rd,Ude,A2,Fde,iw,sw,ow,aw,Zm,k2=k(()=>{"use strict";I2=ut(Rm(),1),T2=ut(require("http"),1),cw=ut(require("fs"),1),rd=ut(require("path"),1);HN();V();Uq();Bq();p2();Is();Zu();f2();m2();y2();E2();S2();x2();Ude=2e3,A2=rd.default.resolve(__CM_DIRNAME__,"../skills/mem-search"),Fde=rd.default.join(A2,"operations"),iw=rd.default.join(A2,"SKILL.md");aw="15.8.2";Zm=class{app;server=null;lastRequestAt=null;inFlightRequests=0;lastResponseFinishedAt=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,I2.default)(),this.app.disable("x-powered-by"),this.setupRemoteReadOnlyGuard(),this.setupSecurityHeaders(),this.setupCors(),this.setupPreBodyParserRoutes(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}getLastRequestAt(){return this.lastRequestAt}getInFlightRequestCount(){return this.inFlightRequests}getLastResponseFinishedAt(){return this.lastResponseFinishedAt}trackRequestActivity(e){this.lastRequestAt=Date.now(),this.inFlightRequests++;let r=e.socket,n=!1,i=()=>{n||(n=!0,e.off("finish",i),e.off("close",i),r?.off("close",i),this.inFlightRequests--,this.lastRequestAt=Date.now())};e.on("finish",i),e.on("close",i),r?.on("close",i),e.once("finish",()=>{this.lastResponseFinishedAt=Date.now()})}async listen(e,r){return new Promise((n,i)=>{let s=T2.default.createServer(this.app),o=c=>{s.off("listening",a),i(c)},a=()=>{s.off("error",o),this.server=s,_2(s),_.info("SYSTEM","HTTP server started",{host:r,port:e,pid:process.pid}),n()};s.once("error",o),s.once("listening",a),s.listen(e,r)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{this.server.close(n=>n?r(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,_.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(Jq),this.app.use($q)}setupMiddleware(){this.app.use((r,n,i)=>{this.trackRequestActivity(n),i()}),jq().forEach(r=>this.app.use(r))}setupRemoteReadOnlyGuard(){this.options.remoteReadOnly&&this.app.use(qq(this.options.remoteReadOnly))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,r,n)=>{Bde(r),n()})}setupCors(){this.options.originPolicy&&(this.app.use(Lq(this.options.originPolicy)),this.app.use(Kq(this.options.originPolicy))),this.app.use(Nq(this.options.originPolicy))}setupPreBodyParserRoutes(){this.options.preBodyParserRoutes?.forEach(e=>e.setupRoutes(this.app))}handleReadyStream(e,r){r.setHeader("Content-Type","text/event-stream"),r.setHeader("Cache-Control","no-cache"),r.setHeader("Connection","keep-alive"),r.flushHeaders();let n=this.options.initPhaseSource,i=()=>n?n.getInitPhase():{phase:this.options.getInitializationComplete()?"ready":"starting"},s=!1,o=null,a=null,c=null,l=e.socket,u=()=>{s=!0,c!==null&&(clearInterval(c),c=null),a!==null&&(a(),a=null),r.off("close",u),l.off("close",u)},p=d=>{if(s||d.phase===o)return;o=d.phase;let f={phase:d.phase,...d.message!==void 0?{message:d.message}:{},version:aw,pid:process.pid};r.write(`event: phase
|
|
69
|
+
`)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);n&&e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),command:n[3].trim()})}return e}async function Ide(){let t=await Sde("ps",["-e","-o","pid=","-o","ppid=","-o","args="],{timeout:1e4,maxBuffer:33554432});return xde(t.stdout)}function Tde(t,e){let r=t.filter(o=>wde.test(o.command)&&o.pid!==e.selfPid),n=new Set(r.map(o=>o.pid)),i=r.filter(o=>!n.has(o.ppid)),s=i.filter(o=>o.ppid===e.selfPid?!1:o.ppid===1?!0:!e.isAlive(o.ppid));return{matched:r,roots:i,orphans:s}}async function l2(t={}){let e=t.platform??process.platform,r={matched:0,trees:0,orphans:0,killed:0,failed:0,unregistered:0,skipped:null};if(e==="win32")return r.skipped="windows",r;let n=t.readTable??Ide,i=t.isAlive??_t,s=t.killTree??(f=>ti(f,{signalMode:"graceful"})),o=t.selfPid??process.pid,a;try{a=await n()}catch(f){return _.warn("PROCESS","Orphaned chroma-mcp sweep skipped: cannot read the process table",{error:f instanceof Error?f.message:String(f)}),r.skipped="unreadable",r}let{matched:c,roots:l,orphans:u}=Tde(a,{isAlive:i,selfPid:o});if(r.matched=c.length,r.trees=l.length,r.orphans=u.length,u.length===0)return _.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:r.matched,trees:r.trees}),r;_.warn("PROCESS","Reaping orphaned chroma-mcp trees left by dead workers",{orphans:u.length,roots:u.map(f=>f.pid)});let p=new Set,d=8;for(let f=0;f<u.length;f+=d){let m=u.slice(f,f+d);(await Promise.allSettled(m.map(b=>s(b.pid)))).forEach((b,v)=>{let E=m[v];b.status==="fulfilled"?(r.killed+=1,p.add(E.pid)):(r.failed+=1,_.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:E.pid,ppid:E.ppid,error:b.reason instanceof Error?b.reason.message:String(b.reason)}))})}if(t.registry)for(let f of t.registry.getAll())f.type==="chroma"&&p.has(f.pid)&&(t.registry.unregister(f.id),r.unregistered+=1);return _.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:r.orphans,killed:r.killed,failed:r.failed,unregistered:r.unregistered}),r}var a2,c2,Sde,wde,u2=k(()=>{"use strict";a2=require("child_process"),c2=require("util");V();ed();Is();Sde=(0,c2.promisify)(a2.execFile),wde=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/});function d2(){return kde}function Rde(t={}){let e=t.pidFilePath??Ade;if(!(0,$o.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,$o.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,$o.rmSync)(e,{force:!0}),"invalid"}return Zq(r)&&r?((t.logAlive??!0)&&_.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(t.removeStale===!1||(_.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,$o.rmSync)(e,{force:!0})),"stale")}var $o,Ade,QS,kde,p2=k(()=>{"use strict";$o=require("fs");V();Is();r2();o2();u2();Nt();Is();Ade=Le.workerPid(),QS=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(),Rde({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,l2({registry:this.registry}).catch(r=>{_.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),i2()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=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",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{_.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}s2(),this.stopPromise=t2({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,n){this.registry.register(e,r,n)}unregisterProcess(e,r){this.registry.unregister(e,r)}getRegistry(){return this.registry}},kde=new QS(Xm())});function XS(t,e,r){t.on("finish",async()=>{try{await r()}finally{process.exit(0)}}),t.json(e)}var f2=k(()=>{"use strict"});function ZS(t,e=Date.now){return Math.max(0,Math.floor((e()-t)/1e3))}var m2=k(()=>{"use strict"});var h2=k(()=>{"use strict"});function ew(){let t=Array.from(Ode.values()).map(e=>({...e})).sort((e,r)=>e.dependency.localeCompare(r.dependency));return{degraded:t.length>0,statuses:t}}var EFe,Ode,y2=k(()=>{"use strict";h2();EFe=5*6e4,Ode=new Map});function tw(t,e){return Jo(t)===Jo(e)}function g2(t,e){let r=Jo(t);return r!==void 0&&r>e}function Mde(t){let e=new Map,r=new Set;if(!t||typeof t!="object")return{windows:e,malformed:r};for(let n of Cde){let i=t[n];if(!i||typeof i!="object")continue;let{utilization:s,resetsAt:o}=i;(!b2(s)||!b2(o))&&r.add(n);let a={};nw(s)&&(a.utilization=s),nw(o)&&(a.resetsAt=Jo(o)),(a.utilization!==void 0||a.resetsAt!==void 0)&&e.set(n,a)}return{windows:e,malformed:r}}function nw(t){return typeof t=="number"&&Number.isFinite(t)}function b2(t){return t===void 0||nw(t)}function Pde(t,e){return e.status!=="rejected"?!1:!t||t.status!=="rejected"?!0:t.resetsAt!==e.resetsAt}function Jo(t){if(!(typeof t!="number"||!Number.isFinite(t)))return t<1e12?t*1e3:t}function Dde(t,e){return e!==void 0&&t.profile!==void 0&&t.profile!==e}var Cde,rw,v2,IFe,E2=k(()=>{"use strict";Li();Nt();V();Cde=["five_hour","seven_day"],rw=class{entries=new Map;rejections=new Map;set(e){if(!e||typeof e!="object")return!1;let{unifiedWindows:r,...n}=e,i=e.rateLimitType??"default",s=this.rejections.get(i),o=Date.now(),{windows:a,malformed:c}=Mde(r);for(let[d,f]of a){if(d===i||c.has(d))continue;let m=this.entries.get(d),h=m&&!Dde(m,e.profile)?m:void 0,b=g2(h?.resetsAt,o)?h?.resetsAt:void 0,v=f.resetsAt??b,E=f.utilization===void 0&&h?.status==="rejected"&&tw(v,h.resetsAt)&&g2(v,o);this.entries.set(d,{rateLimitType:d,...f,resetsAt:v,...E?{status:"rejected"}:{},...e.profile!==void 0?{profile:e.profile}:{},observedAt:o});let S=this.rejections.get(d);S&&f.resetsAt!==void 0&&!tw(f.resetsAt,S.resetsAt)&&this.rejections.delete(d)}let l=e.rateLimitType?a.get(e.rateLimitType):void 0,u={...n,utilization:e.utilization??l?.utilization,resetsAt:Jo(e.resetsAt)??l?.resetsAt,overageResetsAt:Jo(e.overageResetsAt),observedAt:o};this.entries.set(i,u);let p=Pde(s,u);return u.status==="rejected"?this.rejections.set(i,u):(e.status!==void 0||s&&u.resetsAt!==void 0&&!tw(u.resetsAt,s.resetsAt))&&this.rejections.delete(i),p}get(e){return e?this.entries.get(e):this.entries.get("default")}getMostRecentByWindow(e=Date.now()){let r=n=>{let i=this.entries.get(n);if(!i)return;let s=Jo(i.resetsAt);return s!==void 0&&s<=e?{...i,expired:!0}:i};return{five_hour:r("five_hour"),seven_day:r("seven_day"),seven_day_opus:r("seven_day_opus"),seven_day_sonnet:r("seven_day_sonnet"),seven_day_overage_included:r("seven_day_overage_included"),overage:r("overage")}}get size(){return this.entries.size}restoreForTesting(e,r){this.rejections.delete(e),r?(this.entries.set(e,r),r.status==="rejected"&&this.rejections.set(e,r)):this.entries.delete(e)}};v2=new rw;IFe=900*1e3});function Lde(){try{let{dlopen:t,FFIType:e,ptr:r,suffix:n}=require("bun:ffi"),i=t(`kernel32.${n}`,{SetHandleInformation:{args:[e.ptr,e.u32,e.u32],returns:e.i32}}),s=t(`ws2_32.${n}`,{getsockname:{args:[e.u64,e.ptr,e.ptr],returns:e.i32},ntohs:{args:[e.u16],returns:e.u16}});return{setHandleInformation:i.symbols.SetHandleInformation,getsockname:s.symbols.getsockname,ntohs:s.symbols.ntohs,ptr:r}}catch{return null}}function Nde(t){let e=t.address();return!e||typeof e=="string"?null:e.port}function qde(t,e,r){let i=t._handle?.fd;if(typeof i=="number"&&i>0)return i;let s=new Uint8Array(28),o=new Int32Array([16]);for(let a=4;a<Kde;a+=4){if(o[0]=16,s.fill(0),r.getsockname(a,r.ptr(s),r.ptr(o))!==0)continue;if(r.ntohs(s[2]|s[3]<<8)===e)return a}return null}function _2(t){if(process.platform!=="win32")return!1;let e=Nde(t);if(e===null||e<=0)return _.debug("SYSTEM","Windows listen socket inherit clear skipped: no bound port"),!1;let r=Lde();if(!r)return _.warn("SYSTEM","Windows listen socket inherit clear skipped: bun:ffi unavailable"),!1;let n=qde(t,e,r);if(n===null)return _.warn("SYSTEM","Windows listen socket inherit clear skipped: listen handle not found",{port:e}),!1;try{return r.setHandleInformation(n,jde,0)?(_.debug("SYSTEM","Cleared HANDLE_FLAG_INHERIT on Windows listen socket",{port:e,socketHandle:n}),!0):(_.warn("SYSTEM","SetHandleInformation failed to clear HANDLE_FLAG_INHERIT on listen socket",{port:e,socketHandle:n}),!1)}catch(i){let s=i instanceof Error?i:new Error(String(i));return _.warn("SYSTEM","Failed to clear Windows listen socket inherit flag",{port:e,socketHandle:n},s),!1}}var jde,Kde,S2=k(()=>{"use strict";V();jde=1,Kde=16384});var w2,x2=k(()=>{"use strict";w2=["ready","failed"]});function $de(){if(sw)return sw.text;let t;try{t=cw.readFileSync(iw,"utf-8"),_.debug("SYSTEM","Cached SKILL.md on first request",{path:iw,bytes:Buffer.byteLength(t,"utf-8")})}catch(e){_.debug("SYSTEM","SKILL.md not present, /api/instructions will 404 for topic queries",{path:iw,message:e instanceof Error?e.message:String(e)}),t=null}return sw={text:t},t}function Jde(){if(ow)return ow;let t=new Map;for(let e of mS){let r=rd.default.join(Fde,`${e}.md`);try{t.set(e,cw.readFileSync(r,"utf-8"))}catch(n){_.debug("SYSTEM","Operation instruction file not present",{path:r,message:n instanceof Error?n.message:String(n)})}}return t.size>0&&_.debug("SYSTEM","Cached operation instruction files on first request",{count:t.size,operations:Array.from(t.keys())}),ow=t,t}function Bde(t){t.setHeader("X-Content-Type-Options","nosniff"),t.setHeader("X-Frame-Options","DENY"),t.setHeader("X-DNS-Prefetch-Control","off"),t.setHeader("Referrer-Policy","no-referrer"),t.setHeader("Cross-Origin-Opener-Policy","same-origin"),t.setHeader("Cross-Origin-Resource-Policy","same-origin"),t.setHeader("Origin-Agent-Cluster","?1"),t.removeHeader("X-Powered-By")}var I2,T2,cw,rd,Ude,A2,Fde,iw,sw,ow,aw,Zm,k2=k(()=>{"use strict";I2=ut(Rm(),1),T2=ut(require("http"),1),cw=ut(require("fs"),1),rd=ut(require("path"),1);HN();V();Uq();Bq();p2();Is();Zu();f2();m2();y2();E2();S2();x2();Ude=2e3,A2=rd.default.resolve(__CM_DIRNAME__,"../skills/mem-search"),Fde=rd.default.join(A2,"operations"),iw=rd.default.join(A2,"SKILL.md");aw="15.8.3";Zm=class{app;server=null;lastRequestAt=null;inFlightRequests=0;lastResponseFinishedAt=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,I2.default)(),this.app.disable("x-powered-by"),this.setupRemoteReadOnlyGuard(),this.setupSecurityHeaders(),this.setupCors(),this.setupPreBodyParserRoutes(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}getLastRequestAt(){return this.lastRequestAt}getInFlightRequestCount(){return this.inFlightRequests}getLastResponseFinishedAt(){return this.lastResponseFinishedAt}trackRequestActivity(e){this.lastRequestAt=Date.now(),this.inFlightRequests++;let r=e.socket,n=!1,i=()=>{n||(n=!0,e.off("finish",i),e.off("close",i),r?.off("close",i),this.inFlightRequests--,this.lastRequestAt=Date.now())};e.on("finish",i),e.on("close",i),r?.on("close",i),e.once("finish",()=>{this.lastResponseFinishedAt=Date.now()})}async listen(e,r){return new Promise((n,i)=>{let s=T2.default.createServer(this.app),o=c=>{s.off("listening",a),i(c)},a=()=>{s.off("error",o),this.server=s,_2(s),_.info("SYSTEM","HTTP server started",{host:r,port:e,pid:process.pid}),n()};s.once("error",o),s.once("listening",a),s.listen(e,r)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{this.server.close(n=>n?r(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,_.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(Jq),this.app.use($q)}setupMiddleware(){this.app.use((r,n,i)=>{this.trackRequestActivity(n),i()}),jq().forEach(r=>this.app.use(r))}setupRemoteReadOnlyGuard(){this.options.remoteReadOnly&&this.app.use(qq(this.options.remoteReadOnly))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,r,n)=>{Bde(r),n()})}setupCors(){this.options.originPolicy&&(this.app.use(Lq(this.options.originPolicy)),this.app.use(Kq(this.options.originPolicy))),this.app.use(Nq(this.options.originPolicy))}setupPreBodyParserRoutes(){this.options.preBodyParserRoutes?.forEach(e=>e.setupRoutes(this.app))}handleReadyStream(e,r){r.setHeader("Content-Type","text/event-stream"),r.setHeader("Cache-Control","no-cache"),r.setHeader("Connection","keep-alive"),r.flushHeaders();let n=this.options.initPhaseSource,i=()=>n?n.getInitPhase():{phase:this.options.getInitializationComplete()?"ready":"starting"},s=!1,o=null,a=null,c=null,l=e.socket,u=()=>{s=!0,c!==null&&(clearInterval(c),c=null),a!==null&&(a(),a=null),r.off("close",u),l.off("close",u)},p=d=>{if(s||d.phase===o)return;o=d.phase;let f={phase:d.phase,...d.message!==void 0?{message:d.message}:{},version:aw,pid:process.pid};r.write(`event: phase
|
|
70
70
|
data: ${JSON.stringify(f)}
|
|
71
71
|
|
|
72
72
|
`),w2.includes(d.phase)&&(u(),r.end())};r.on("close",u),l.on("close",u),n&&(a=n.subscribeInitPhase(p)),p(i()),!s&&(c=setInterval(()=>{s||(r.write(`: ping
|
|
@@ -904,7 +904,7 @@ ${n}`}))}}async function dxe(t,e,r){let n=j8.find(i=>i.name===e);if(!n)throw new
|
|
|
904
904
|
LIMIT $4)
|
|
905
905
|
)
|
|
906
906
|
ORDER BY e.occurred_at ASC, e.id ASC
|
|
907
|
-
`,[e.serverSessionId,e.projectId,e.teamId,r])).rows.map(yxe)}}});function G8(t){let e=vxe.safeParse(t);if(!e.success)throw new mp(e.error.issues);return e.data}var sr,_l,J8,B8,gxe,bxe,vxe,mp,ig=k(()=>{"use strict";sr=require("zod"),_l={event:"server_beta_generate_event",summary:"server_beta_generate_summary"},J8={event:"evt",summary:"sum"},B8=sr.z.object({team_id:sr.z.string().min(1,"team_id is required"),project_id:sr.z.string().min(1,"project_id is required"),source_type:sr.z.enum(["agent_event","session_summary","observation_reindex"]),source_id:sr.z.string().min(1,"source_id is required"),generation_job_id:sr.z.string().min(1,"generation_job_id is required"),api_key_id:sr.z.string().min(1).nullable(),actor_id:sr.z.string().min(1).nullable(),source_adapter:sr.z.string().min(1,"source_adapter is required"),request_id:sr.z.string().min(1).nullable().optional()}),gxe=B8.extend({kind:sr.z.literal("event"),agent_event_id:sr.z.string().min(1)}),bxe=B8.extend({kind:sr.z.literal("summary"),server_session_id:sr.z.string().min(1)}),vxe=sr.z.discriminatedUnion("kind",[gxe,bxe]),mp=class extends Error{issues;constructor(e){super(`invalid server generation job payload: ${e.map(r=>r.message).join("; ")}`),this.issues=e}}});function Sl(t){let e=J8[t.kind],r=JSON.stringify({kind:t.kind,team_id:t.team_id,project_id:t.project_id,source_type:t.source_type,source_id:t.source_id}),n=(0,z8.createHash)("sha256").update(r).digest("hex");return`${e}_${n}`}var z8,ZA=k(()=>{"use strict";z8=require("crypto");ig()});function H8(t){return{kind:"event",team_id:t.event.teamId,project_id:t.event.projectId,source_type:"agent_event",source_id:t.event.id,generation_job_id:t.outboxId,agent_event_id:t.event.id,api_key_id:t.apiKeyId,actor_id:t.actorId,source_adapter:t.sourceAdapter??t.event.sourceAdapter??"api",request_id:t.requestId}}var V8,sg,W8=k(()=>{"use strict";Ic();$i();Rs();V();ZA();cn();V8="observation_generate_for_event",sg=class{constructor(e){this.options=e}options;async ingestOne(e,r={}){let n=r.generate??!0,i=r.source??"http_post_v1_events",s=await Ur(this.options.pool,async a=>{let l=await new ln(a).create(e);if(!n)return{event:l,outbox:null};let u=new st(a),p=new Ct(a),d=et(),f=H8({outboxId:d,event:l,apiKeyId:r.apiKeyId??null,actorId:r.actorId??null,sourceAdapter:r.sourceAdapter??null,requestId:r.requestId??null}),m=await u.create({id:d,projectId:l.projectId,teamId:l.teamId,sourceType:"agent_event",sourceId:l.id,agentEventId:l.id,serverSessionId:l.serverSessionId,jobType:V8,bullmqJobId:Sl({kind:"event",team_id:l.teamId,project_id:l.projectId,source_type:"agent_event",source_id:l.id}),payload:f});return await p.append({generationJobId:m.id,projectId:m.projectId,teamId:m.teamId,eventType:"queued",statusAfter:m.status,attempt:m.attempts,details:{source:i}}),{event:l,outbox:m}}),o="skipped";return s.outbox&&(o=await this.publishEventJob(s.event,s.outbox)),{event:s.event,outbox:s.outbox,enqueueState:o}}async ingestBatch(e,r={}){let n=r.generate??!0,i=r.source??"http_post_v1_events_batch",s=await Ur(this.options.pool,async o=>{let a=new ln(o),c=new st(o),l=new Ct(o),u=[];for(let p of e){let d=await a.create(p);if(!n){u.push({event:d,outbox:null});continue}let f=et(),m=H8({outboxId:f,event:d,apiKeyId:r.apiKeyId??null,actorId:r.actorId??null,sourceAdapter:r.sourceAdapter??null,requestId:r.requestId??null}),h=await c.create({id:f,projectId:d.projectId,teamId:d.teamId,sourceType:"agent_event",sourceId:d.id,agentEventId:d.id,serverSessionId:d.serverSessionId,jobType:V8,bullmqJobId:Sl({kind:"event",team_id:d.teamId,project_id:d.projectId,source_type:"agent_event",source_id:d.id}),payload:m});await l.append({generationJobId:h.id,projectId:h.projectId,teamId:h.teamId,eventType:"queued",statusAfter:h.status,attempt:h.attempts,details:{source:i}}),u.push({event:d,outbox:h})}return u});return Promise.all(s.map(async({event:o,outbox:a})=>{let c=a?await this.publishEventJob(o,a):"skipped";return{event:o,outbox:a,enqueueState:c}}))}async publishEventJob(e,r){let n=this.options.resolveEventQueue();if(!n)return"queued_only";let i=r.bullmqJobId??Sl({kind:"event",team_id:e.teamId,project_id:e.projectId,source_type:"agent_event",source_id:e.id});try{return await n.add(i,r.payload),"enqueued"}catch(s){return _.warn("SYSTEM","failed to publish event generation job to BullMQ",{outboxId:r.id,error:s instanceof Error?s.message:String(s)}),"queued_only"}}}});function e1(t){return Sl({kind:"summary",team_id:t.teamId,project_id:t.projectId,source_type:"session_summary",source_id:t.serverSessionId})}function t1(t){return{kind:"summary",team_id:t.teamId,project_id:t.projectId,source_type:"session_summary",source_id:t.serverSessionId,generation_job_id:t.generationJobId,server_session_id:t.serverSessionId,api_key_id:t.apiKeyId??null,actor_id:t.actorId??null,source_adapter:t.sourceAdapter??"api",request_id:t.requestId??null}}var Y8=k(()=>{"use strict";ZA()});var Exe,og,Q8=k(()=>{"use strict";$i();Rs();zs();V();Y8();cn();Exe="observation_generate_session_summary",og=class{constructor(e){this.options=e}options;async end(e){let r=e.source??"http_post_v1_sessions_end",n=await Ur(this.options.pool,async s=>{let a=await new zt(s).endSession({id:e.sessionId,projectId:e.projectId,teamId:e.teamId});if(!a)return{session:null,outbox:null};let c=new st(s),l=new Ct(s),u=et(),p=t1({serverSessionId:a.id,teamId:a.teamId,projectId:a.projectId,generationJobId:u,apiKeyId:e.apiKeyId??null,actorId:e.actorId??null,sourceAdapter:e.sourceAdapter??null}),d=await c.create({id:u,projectId:a.projectId,teamId:a.teamId,sourceType:"session_summary",sourceId:a.id,serverSessionId:a.id,jobType:Exe,bullmqJobId:e1({serverSessionId:a.id,teamId:a.teamId,projectId:a.projectId}),payload:p});return await l.append({generationJobId:d.id,projectId:d.projectId,teamId:d.teamId,eventType:"queued",statusAfter:d.status,attempt:d.attempts,details:{source:r}}),{session:a,outbox:d}});if(!n.session||!n.outbox)return{session:n.session,outbox:null,enqueueState:"skipped"};let i=await this.publishSummaryJob(n.session.id,n.outbox,e);return{session:n.session,outbox:n.outbox,enqueueState:i}}async publishSummaryJob(e,r,n){let i=this.options.resolveSummaryQueue();if(!i)return"queued_only";let s=r.bullmqJobId??e1({serverSessionId:e,teamId:r.teamId,projectId:r.projectId}),o=t1({serverSessionId:e,teamId:r.teamId,projectId:r.projectId,generationJobId:r.id,apiKeyId:n.apiKeyId??null,actorId:n.actorId??null,sourceAdapter:n.sourceAdapter??null});try{return await i.add(s,o),"enqueued"}catch(a){return _.warn("SYSTEM","failed to publish summary generation job to BullMQ",{outboxId:r.id,error:a instanceof Error?a.message:String(a)}),"queued_only"}}}});var X8=k(()=>{"use strict"});function tB(t){return`${(process.env.CLAUDE_MEM_PUBLIC_URL??`${t.protocol}://${t.get("host")??"localhost"}`).replace(/\/+$/,"")}/v1/mcp`}function rB(t,e){return`claude mcp add --transport http claude-mem ${t} --header "Authorization: Bearer ${e}"`}async function sB(t,e,r=lB,n=Txe){if(iB.includes(e.status))return{job:e,timedOut:!1};let i=Date.now()+r,s=e;for(;Date.now()<i;){await new Promise(a=>setTimeout(a,n));let o=await t.getByIdForScope({id:e.id,projectId:e.projectId,teamId:e.teamId});if(!o)return{job:s,timedOut:!1};if(s=o,iB.includes(o.status))return{job:o,timedOut:!1}}return{job:s,timedOut:!0}}function kxe(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&uB.has(e)?e:null,n=typeof t.query.source_type=="string"?t.query.source_type.trim():"",i=n&&Axe.has(n)?n:null,s=cg(t.query.limit,dB,1,pB),o=cg(t.query.offset,0,0,Number.MAX_SAFE_INTEGER),a=typeof t.query.since=="string"?t.query.since.trim():"",c=null;if(a){let l=new Date(a);Number.isNaN(l.getTime())||(c=l)}return{status:r,sourceType:i,limit:s,offset:o,since:c}}function oB(t){if(!t||typeof t!="object")return 0;let e=t.retried_count;return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function aB(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&uB.has(e)?e:null,n=cg(t.query.limit,dB,1,pB),i=cg(t.query.offset,0,0,Number.MAX_SAFE_INTEGER);return{status:r,limit:n,offset:i}}function cg(t,e,r,n){if(typeof t!="string")return e;let i=Number.parseInt(t,10);return Number.isFinite(i)?Math.max(r,Math.min(n,i)):e}function r1(t,e={}){let r={id:t.id,projectId:t.project_id,teamId:t.team_id,sourceType:t.source_type,sourceId:t.source_id,status:t.status,attempts:t.attempts,maxAttempts:t.max_attempts,createdAtEpoch:new Date(t.created_at).getTime(),completedAtEpoch:t.completed_at?new Date(t.completed_at).getTime():null,failedAtEpoch:t.failed_at?new Date(t.failed_at).getTime():null,lastError:t.last_error&&typeof t.last_error=="object"?t.last_error:null};return e.includePayload&&t.payload&&typeof t.payload=="object"&&(r.payload=t.payload),r}function Rxe(t){let e={"event.received":"agent_event","event.batch_received":"agent_event","event.write":"agent_event","event.batch_write":"agent_event","session.write":"server_session","session.end":"server_session","memory.write":"observation","observation.read":"observation","observation.search":"observation","observation.context":"observation","observation.generated":"observation","session_summary.generated":"observation","generation_job.queued":"observation_generation_job","generation_job.enqueued":"observation_generation_job","generation_job.processing":"observation_generation_job","generation_job.completed":"observation_generation_job","generation_job.failed":"observation_generation_job","generation_job.scope_violation":"observation_generation_job","generation_job.revoked_key":"observation_generation_job","generation_job.retried_by_operator":"observation_generation_job","generation_job.cancelled_by_operator":"observation_generation_job","generation_job.stalled":"observation_generation_job"};return e[t]?e[t]:t.split(".")[0]??"unknown"}function Oxe(t,e){let r=t.authContext?.projectId??null;if(!(t.authContext?.teamId??null))return{status:403,body:{error:"Forbidden",message:"API key is not bound to a team"}};if(!r)return null;for(let i of e)if(i.projectId!==r)return{status:403,body:{error:"Forbidden",message:"API key is scoped to a different project"}};return null}function hp(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,externalSessionId:t.externalSessionId,contentSessionId:t.contentSessionId,agentId:t.agentId,agentType:t.agentType,platformSource:t.platformSource,generationStatus:t.generationStatus,metadata:t.metadata,startedAtEpoch:t.startedAtEpoch,endedAtEpoch:t.endedAtEpoch,lastGeneratedAtEpoch:t.lastGeneratedAtEpoch,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function yp(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,serverSessionId:t.serverSessionId,sourceAdapter:t.sourceAdapter,sourceEventId:t.sourceEventId,eventType:t.eventType,platformSource:t.platformSource,payload:t.payload,metadata:t.metadata,occurredAtEpoch:t.occurredAtEpoch,receivedAtEpoch:t.receivedAtEpoch,createdAtEpoch:t.createdAtEpoch}}function vn(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,serverSessionId:t.serverSessionId,...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},kind:t.kind,content:t.content,metadata:t.metadata,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function Cxe(t){return{id:t.id,projectId:t.project_id,teamId:t.team_id,serverSessionId:t.server_session_id,kind:t.kind,content:t.content,metadata:t.metadata&&typeof t.metadata=="object"?t.metadata:{},generationKey:t.generation_key,createdByJobId:t.created_by_job_id,createdAtEpoch:new Date(t.created_at).getTime(),updatedAtEpoch:new Date(t.updated_at).getTime(),source:{id:t.source_id_pk,sourceType:t.source_type,sourceId:t.source_id,generationJobId:t.generation_job_id,createdAtEpoch:new Date(t.source_created_at).getTime()}}}function n1(t,e){return{id:t.id,status:t.status,bullmqJobId:t.bullmqJobId,sourceType:t.sourceType,sourceId:t.sourceId,transport:e,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function cB(t,e){return{id:t.id,status:t.status,transport:e,bullmqJobId:t.bullmqJobId,sourceType:t.sourceType,sourceId:t.sourceId,attempts:t.attempts,maxAttempts:t.maxAttempts,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function i1(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,sourceType:t.sourceType,sourceId:t.sourceId,agentEventId:t.agentEventId,serverSessionId:t.serverSessionId,jobType:t.jobType,status:t.status,bullmqJobId:t.bullmqJobId,attempts:t.attempts,maxAttempts:t.maxAttempts,nextAttemptAtEpoch:t.nextAttemptAtEpoch,completedAtEpoch:t.completedAtEpoch,failedAtEpoch:t.failedAtEpoch,cancelledAtEpoch:t.cancelledAtEpoch,lastError:t.lastError,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}var B,lg,xxe,Ixe,nB,lB,Txe,iB,ag,Axe,uB,dB,pB,fB=k(()=>{"use strict";B=require("zod");R2();Ic();$i();ri();bd();vd();sd();$c();V();YF();Ch();jx();o$();a4();L8();q8();F8();fa();lg=require("node:crypto");_d();zs();W8();Q8();Bo();X8();xxe="api",Ixe="15.8.2";nB=B.z.object({generate:B.z.union([B.z.literal("true"),B.z.literal("false")]).optional(),wait:B.z.union([B.z.literal("true"),B.z.literal("false")]).optional()}),lB=3e4,Txe=100,iB=["completed","failed","cancelled"];ag=class{constructor(e){this.options=e;this.ingestEvents=new sg({pool:e.pool,resolveEventQueue:()=>this.resolveQueue("event")}),this.endSession=new og({pool:e.pool,resolveSummaryQueue:()=>this.resolveQueue("summary")})}options;ingestEvents;endSession;getIngestEventsService(){return this.ingestEvents}getEndSessionService(){return this.endSession}setupRoutes(e){e.use("/v1",s$());let r=Xo(this.options.pool,{authMode:this.options.authMode,allowLocalDevBypass:this.options.allowLocalDevBypass,requiredScopes:["memories:write"]}),n=Xo(this.options.pool,{authMode:this.options.authMode,allowLocalDevBypass:this.options.allowLocalDevBypass,requiredScopes:["memories:read"]}),i=[],s=Number(process.env.CLAUDE_MEM_RATE_LIMIT_PER_MIN??"0");s>0&&i.push(N8(this.options.pool,{windowSec:60,max:s}));let o=Number(process.env.CLAUDE_MEM_MONTHLY_REQUEST_CAP??"0");o>0&&i.push(XA(this.options.pool,{kind:"request",cap:o})),process.env.CLAUDE_MEM_USAGE_METERING==="1"&&i.push(U8(this.options.pool));let a=[...i],c=Number(process.env.CLAUDE_MEM_MONTHLY_TOKEN_CAP??"0");c>0&&a.push(XA(this.options.pool,{kind:"tokens",cap:c}));let l=[r,...a],u=[n,...i];e.get("/v1/usage",u,this.asyncHandler(async(d,f)=>{let m=this.requireTeamId(d,f);if(!m)return;let h=new Date(Date.UTC(new Date().getUTCFullYear(),new Date().getUTCMonth(),1)),b=await new Jr(this.options.pool).summarize({teamId:m,since:h});f.status(200).json({since:h.toISOString(),usage:b})})),e.post("/v1/keys",l,this.handleCreate(B.z.object({label:B.z.string().max(120).optional(),expiresInDays:B.z.number().int().positive().max(365).optional()}),async(d,f,m)=>{let h=this.requireTeamId(d,f);if(!h)return;let b=`cm_${(0,lg.randomBytes)(24).toString("hex")}`,v=Ed(b),E=Qo(b),S=m.expiresInDays?new Date(Date.now()+m.expiresInDays*864e5):null,w=await new St(this.options.pool).createApiKey({keyHash:v,keyPrefix:E,teamId:h,projectId:d.authContext?.projectId??null,actorId:d.authContext?.apiKeyId??"api",scopes:["memories:read"],expiresAt:S});m.label;let x=tB(d);f.status(201).json({id:w.id,apiKey:b,scopes:["memories:read"],expiresAt:S?.toISOString()??null,mcpUrl:x,connectCommand:rB(x,b)})})),e.get("/v1/connect",u,this.asyncHandler(async(d,f)=>{if(!this.requireTeamId(d,f))return;let h=tB(d);f.status(200).json({mcpUrl:h,connectCommand:rB(h,"<YOUR_API_KEY>"),hint:"POST /v1/keys (write scope) to mint a read-only key for this link."})})),e.post("/v1/events",l,this.asyncHandler(async(d,f)=>{let m=nB.safeParse(d.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let h=m.data.generate!=="false",b=m.data.wait==="true",v=lw.safeParse(d.body);if(!v.success){f.status(400).json({error:"ValidationError",issues:v.error.issues});return}let E=v.data,S=this.requireTeamId(d,f);if(!S||!this.ensureProjectAllowed(d,f,E.projectId))return;let w=this.toAgentEventInput(E,S);await this.applyContentSessionLinks([w],[d.body],S);let x,O=null,C="skipped",J={generate:h,source:"http_post_v1_events",apiKeyId:d.authContext?.apiKeyId??null,actorId:await this.resolveActorId(d),sourceAdapter:w.sourceAdapter,requestId:d.requestId??null};try{let j=await this.ingestEvents.ingestOne(w,J);x=j.event,O=j.outbox,C=j.enqueueState}catch(j){let q=j instanceof Error?j:new Error(String(j));_.warn("SYSTEM","event.write ingest failed",{requestId:d.requestId??null},q),this.handleDbError(q,f,"event.write");return}if(await this.auditWrite(d,"event.received",x.id,x.projectId,{sourceAdapter:x.sourceAdapter,sourceEventId:x.sourceEventId,eventType:x.eventType,serverSessionId:x.serverSessionId,generationJobId:O?.id??null}),b){let j=O,q=!1;if(O){let ee=new st(this.options.pool),ke=await sB(ee,O);j=ke.job,q=ke.timedOut}f.status(201).json({event:yp(x),generationJob:j?cB(j,C):null,...q?{waitTimedOut:!0}:{}});return}f.status(201).json({event:yp(x),...O?{generationJob:n1(O,C)}:{}})})),e.post("/v1/events/batch",l,this.asyncHandler(async(d,f)=>{let m=nB.safeParse(d.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let h=m.data.generate!=="false",b=m.data.wait==="true",E=B.z.array(lw).min(1).max(500).safeParse(d.body);if(!E.success){f.status(400).json({error:"ValidationError",issues:E.error.issues});return}let S=this.requireTeamId(d,f);if(!S)return;let w=Oxe(d,E.data);if(w){f.status(w.status).json(w.body);return}let x=E.data.map(j=>this.toAgentEventInput(j,S));await this.applyContentSessionLinks(x,Array.isArray(d.body)?d.body:E.data,S);let O=[],C=[],J={generate:h,source:"http_post_v1_events_batch",apiKeyId:d.authContext?.apiKeyId??null,actorId:await this.resolveActorId(d),sourceAdapter:null,requestId:d.requestId??null};try{let j=await this.ingestEvents.ingestBatch(x,J);O=j.map(({event:q,outbox:ee})=>({event:q,outbox:ee})),C=j.map(({enqueueState:q})=>q)}catch(j){let q=j instanceof Error?j:new Error(String(j));_.warn("SYSTEM","event.batch_write ingest failed",{requestId:d.requestId??null},q),this.handleDbError(q,f,"event.batch_write");return}if(await this.auditWrite(d,"event.batch_received",null,null,{eventCount:O.length,generationJobIds:O.map(({outbox:j})=>j?.id??null).filter(Boolean)}),b){let j=new st(this.options.pool),q=Date.now()+lB,ee=[];for(let T of O){if(!T.outbox){ee.push({event:T.event,outbox:null,timedOut:!1});continue}let K=Math.max(0,q-Date.now()),M=await sB(j,T.outbox,K);ee.push({event:T.event,outbox:M.job,timedOut:M.timedOut})}let ke=ee.some(T=>T.timedOut);f.status(201).json({events:ee.map(({event:T,outbox:K,timedOut:M},P)=>({event:yp(T),generationJob:K?cB(K,C[P]):null,...M?{waitTimedOut:!0}:{}})),...ke?{waitTimedOut:!0}:{}});return}f.status(201).json({events:O.map(({event:j,outbox:q},ee)=>({event:yp(j),...q?{generationJob:n1(q,C[ee])}:{}}))})})),e.get("/v1/events/:id",u,this.asyncHandler(async(d,f)=>{let m=this.requireTeamId(d,f);if(!m)return;let h=this.routeParam(d.params.id),b=new ln(this.options.pool),v=await this.loadScopedById(d,f,{id:h,teamId:m,table:"agent_events",notFound:"Event not found",load:E=>b.getByIdForScope({id:h,projectId:E,teamId:m})});v&&f.json({event:yp(v)})})),e.get("/v1/events/:id/observations",u,this.asyncHandler(async(d,f)=>{let m=this.requireTeamId(d,f);if(!m)return;let h=this.routeParam(d.params.id),v=(await this.options.pool.query("SELECT id, project_id FROM agent_events WHERE id = $1 AND team_id = $2",[h,m])).rows[0];if(!v){f.status(404).json({error:"NotFound",message:"Event not found"});return}if(!this.ensureProjectAllowed(d,f,v.project_id))return;let E=await this.options.pool.query(`
|
|
907
|
+
`,[e.serverSessionId,e.projectId,e.teamId,r])).rows.map(yxe)}}});function G8(t){let e=vxe.safeParse(t);if(!e.success)throw new mp(e.error.issues);return e.data}var sr,_l,J8,B8,gxe,bxe,vxe,mp,ig=k(()=>{"use strict";sr=require("zod"),_l={event:"server_beta_generate_event",summary:"server_beta_generate_summary"},J8={event:"evt",summary:"sum"},B8=sr.z.object({team_id:sr.z.string().min(1,"team_id is required"),project_id:sr.z.string().min(1,"project_id is required"),source_type:sr.z.enum(["agent_event","session_summary","observation_reindex"]),source_id:sr.z.string().min(1,"source_id is required"),generation_job_id:sr.z.string().min(1,"generation_job_id is required"),api_key_id:sr.z.string().min(1).nullable(),actor_id:sr.z.string().min(1).nullable(),source_adapter:sr.z.string().min(1,"source_adapter is required"),request_id:sr.z.string().min(1).nullable().optional()}),gxe=B8.extend({kind:sr.z.literal("event"),agent_event_id:sr.z.string().min(1)}),bxe=B8.extend({kind:sr.z.literal("summary"),server_session_id:sr.z.string().min(1)}),vxe=sr.z.discriminatedUnion("kind",[gxe,bxe]),mp=class extends Error{issues;constructor(e){super(`invalid server generation job payload: ${e.map(r=>r.message).join("; ")}`),this.issues=e}}});function Sl(t){let e=J8[t.kind],r=JSON.stringify({kind:t.kind,team_id:t.team_id,project_id:t.project_id,source_type:t.source_type,source_id:t.source_id}),n=(0,z8.createHash)("sha256").update(r).digest("hex");return`${e}_${n}`}var z8,ZA=k(()=>{"use strict";z8=require("crypto");ig()});function H8(t){return{kind:"event",team_id:t.event.teamId,project_id:t.event.projectId,source_type:"agent_event",source_id:t.event.id,generation_job_id:t.outboxId,agent_event_id:t.event.id,api_key_id:t.apiKeyId,actor_id:t.actorId,source_adapter:t.sourceAdapter??t.event.sourceAdapter??"api",request_id:t.requestId}}var V8,sg,W8=k(()=>{"use strict";Ic();$i();Rs();V();ZA();cn();V8="observation_generate_for_event",sg=class{constructor(e){this.options=e}options;async ingestOne(e,r={}){let n=r.generate??!0,i=r.source??"http_post_v1_events",s=await Ur(this.options.pool,async a=>{let l=await new ln(a).create(e);if(!n)return{event:l,outbox:null};let u=new st(a),p=new Ct(a),d=et(),f=H8({outboxId:d,event:l,apiKeyId:r.apiKeyId??null,actorId:r.actorId??null,sourceAdapter:r.sourceAdapter??null,requestId:r.requestId??null}),m=await u.create({id:d,projectId:l.projectId,teamId:l.teamId,sourceType:"agent_event",sourceId:l.id,agentEventId:l.id,serverSessionId:l.serverSessionId,jobType:V8,bullmqJobId:Sl({kind:"event",team_id:l.teamId,project_id:l.projectId,source_type:"agent_event",source_id:l.id}),payload:f});return await p.append({generationJobId:m.id,projectId:m.projectId,teamId:m.teamId,eventType:"queued",statusAfter:m.status,attempt:m.attempts,details:{source:i}}),{event:l,outbox:m}}),o="skipped";return s.outbox&&(o=await this.publishEventJob(s.event,s.outbox)),{event:s.event,outbox:s.outbox,enqueueState:o}}async ingestBatch(e,r={}){let n=r.generate??!0,i=r.source??"http_post_v1_events_batch",s=await Ur(this.options.pool,async o=>{let a=new ln(o),c=new st(o),l=new Ct(o),u=[];for(let p of e){let d=await a.create(p);if(!n){u.push({event:d,outbox:null});continue}let f=et(),m=H8({outboxId:f,event:d,apiKeyId:r.apiKeyId??null,actorId:r.actorId??null,sourceAdapter:r.sourceAdapter??null,requestId:r.requestId??null}),h=await c.create({id:f,projectId:d.projectId,teamId:d.teamId,sourceType:"agent_event",sourceId:d.id,agentEventId:d.id,serverSessionId:d.serverSessionId,jobType:V8,bullmqJobId:Sl({kind:"event",team_id:d.teamId,project_id:d.projectId,source_type:"agent_event",source_id:d.id}),payload:m});await l.append({generationJobId:h.id,projectId:h.projectId,teamId:h.teamId,eventType:"queued",statusAfter:h.status,attempt:h.attempts,details:{source:i}}),u.push({event:d,outbox:h})}return u});return Promise.all(s.map(async({event:o,outbox:a})=>{let c=a?await this.publishEventJob(o,a):"skipped";return{event:o,outbox:a,enqueueState:c}}))}async publishEventJob(e,r){let n=this.options.resolveEventQueue();if(!n)return"queued_only";let i=r.bullmqJobId??Sl({kind:"event",team_id:e.teamId,project_id:e.projectId,source_type:"agent_event",source_id:e.id});try{return await n.add(i,r.payload),"enqueued"}catch(s){return _.warn("SYSTEM","failed to publish event generation job to BullMQ",{outboxId:r.id,error:s instanceof Error?s.message:String(s)}),"queued_only"}}}});function e1(t){return Sl({kind:"summary",team_id:t.teamId,project_id:t.projectId,source_type:"session_summary",source_id:t.serverSessionId})}function t1(t){return{kind:"summary",team_id:t.teamId,project_id:t.projectId,source_type:"session_summary",source_id:t.serverSessionId,generation_job_id:t.generationJobId,server_session_id:t.serverSessionId,api_key_id:t.apiKeyId??null,actor_id:t.actorId??null,source_adapter:t.sourceAdapter??"api",request_id:t.requestId??null}}var Y8=k(()=>{"use strict";ZA()});var Exe,og,Q8=k(()=>{"use strict";$i();Rs();zs();V();Y8();cn();Exe="observation_generate_session_summary",og=class{constructor(e){this.options=e}options;async end(e){let r=e.source??"http_post_v1_sessions_end",n=await Ur(this.options.pool,async s=>{let a=await new zt(s).endSession({id:e.sessionId,projectId:e.projectId,teamId:e.teamId});if(!a)return{session:null,outbox:null};let c=new st(s),l=new Ct(s),u=et(),p=t1({serverSessionId:a.id,teamId:a.teamId,projectId:a.projectId,generationJobId:u,apiKeyId:e.apiKeyId??null,actorId:e.actorId??null,sourceAdapter:e.sourceAdapter??null}),d=await c.create({id:u,projectId:a.projectId,teamId:a.teamId,sourceType:"session_summary",sourceId:a.id,serverSessionId:a.id,jobType:Exe,bullmqJobId:e1({serverSessionId:a.id,teamId:a.teamId,projectId:a.projectId}),payload:p});return await l.append({generationJobId:d.id,projectId:d.projectId,teamId:d.teamId,eventType:"queued",statusAfter:d.status,attempt:d.attempts,details:{source:r}}),{session:a,outbox:d}});if(!n.session||!n.outbox)return{session:n.session,outbox:null,enqueueState:"skipped"};let i=await this.publishSummaryJob(n.session.id,n.outbox,e);return{session:n.session,outbox:n.outbox,enqueueState:i}}async publishSummaryJob(e,r,n){let i=this.options.resolveSummaryQueue();if(!i)return"queued_only";let s=r.bullmqJobId??e1({serverSessionId:e,teamId:r.teamId,projectId:r.projectId}),o=t1({serverSessionId:e,teamId:r.teamId,projectId:r.projectId,generationJobId:r.id,apiKeyId:n.apiKeyId??null,actorId:n.actorId??null,sourceAdapter:n.sourceAdapter??null});try{return await i.add(s,o),"enqueued"}catch(a){return _.warn("SYSTEM","failed to publish summary generation job to BullMQ",{outboxId:r.id,error:a instanceof Error?a.message:String(a)}),"queued_only"}}}});var X8=k(()=>{"use strict"});function tB(t){return`${(process.env.CLAUDE_MEM_PUBLIC_URL??`${t.protocol}://${t.get("host")??"localhost"}`).replace(/\/+$/,"")}/v1/mcp`}function rB(t,e){return`claude mcp add --transport http claude-mem ${t} --header "Authorization: Bearer ${e}"`}async function sB(t,e,r=lB,n=Txe){if(iB.includes(e.status))return{job:e,timedOut:!1};let i=Date.now()+r,s=e;for(;Date.now()<i;){await new Promise(a=>setTimeout(a,n));let o=await t.getByIdForScope({id:e.id,projectId:e.projectId,teamId:e.teamId});if(!o)return{job:s,timedOut:!1};if(s=o,iB.includes(o.status))return{job:o,timedOut:!1}}return{job:s,timedOut:!0}}function kxe(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&uB.has(e)?e:null,n=typeof t.query.source_type=="string"?t.query.source_type.trim():"",i=n&&Axe.has(n)?n:null,s=cg(t.query.limit,dB,1,pB),o=cg(t.query.offset,0,0,Number.MAX_SAFE_INTEGER),a=typeof t.query.since=="string"?t.query.since.trim():"",c=null;if(a){let l=new Date(a);Number.isNaN(l.getTime())||(c=l)}return{status:r,sourceType:i,limit:s,offset:o,since:c}}function oB(t){if(!t||typeof t!="object")return 0;let e=t.retried_count;return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function aB(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&uB.has(e)?e:null,n=cg(t.query.limit,dB,1,pB),i=cg(t.query.offset,0,0,Number.MAX_SAFE_INTEGER);return{status:r,limit:n,offset:i}}function cg(t,e,r,n){if(typeof t!="string")return e;let i=Number.parseInt(t,10);return Number.isFinite(i)?Math.max(r,Math.min(n,i)):e}function r1(t,e={}){let r={id:t.id,projectId:t.project_id,teamId:t.team_id,sourceType:t.source_type,sourceId:t.source_id,status:t.status,attempts:t.attempts,maxAttempts:t.max_attempts,createdAtEpoch:new Date(t.created_at).getTime(),completedAtEpoch:t.completed_at?new Date(t.completed_at).getTime():null,failedAtEpoch:t.failed_at?new Date(t.failed_at).getTime():null,lastError:t.last_error&&typeof t.last_error=="object"?t.last_error:null};return e.includePayload&&t.payload&&typeof t.payload=="object"&&(r.payload=t.payload),r}function Rxe(t){let e={"event.received":"agent_event","event.batch_received":"agent_event","event.write":"agent_event","event.batch_write":"agent_event","session.write":"server_session","session.end":"server_session","memory.write":"observation","observation.read":"observation","observation.search":"observation","observation.context":"observation","observation.generated":"observation","session_summary.generated":"observation","generation_job.queued":"observation_generation_job","generation_job.enqueued":"observation_generation_job","generation_job.processing":"observation_generation_job","generation_job.completed":"observation_generation_job","generation_job.failed":"observation_generation_job","generation_job.scope_violation":"observation_generation_job","generation_job.revoked_key":"observation_generation_job","generation_job.retried_by_operator":"observation_generation_job","generation_job.cancelled_by_operator":"observation_generation_job","generation_job.stalled":"observation_generation_job"};return e[t]?e[t]:t.split(".")[0]??"unknown"}function Oxe(t,e){let r=t.authContext?.projectId??null;if(!(t.authContext?.teamId??null))return{status:403,body:{error:"Forbidden",message:"API key is not bound to a team"}};if(!r)return null;for(let i of e)if(i.projectId!==r)return{status:403,body:{error:"Forbidden",message:"API key is scoped to a different project"}};return null}function hp(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,externalSessionId:t.externalSessionId,contentSessionId:t.contentSessionId,agentId:t.agentId,agentType:t.agentType,platformSource:t.platformSource,generationStatus:t.generationStatus,metadata:t.metadata,startedAtEpoch:t.startedAtEpoch,endedAtEpoch:t.endedAtEpoch,lastGeneratedAtEpoch:t.lastGeneratedAtEpoch,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function yp(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,serverSessionId:t.serverSessionId,sourceAdapter:t.sourceAdapter,sourceEventId:t.sourceEventId,eventType:t.eventType,platformSource:t.platformSource,payload:t.payload,metadata:t.metadata,occurredAtEpoch:t.occurredAtEpoch,receivedAtEpoch:t.receivedAtEpoch,createdAtEpoch:t.createdAtEpoch}}function vn(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,serverSessionId:t.serverSessionId,...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},kind:t.kind,content:t.content,metadata:t.metadata,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function Cxe(t){return{id:t.id,projectId:t.project_id,teamId:t.team_id,serverSessionId:t.server_session_id,kind:t.kind,content:t.content,metadata:t.metadata&&typeof t.metadata=="object"?t.metadata:{},generationKey:t.generation_key,createdByJobId:t.created_by_job_id,createdAtEpoch:new Date(t.created_at).getTime(),updatedAtEpoch:new Date(t.updated_at).getTime(),source:{id:t.source_id_pk,sourceType:t.source_type,sourceId:t.source_id,generationJobId:t.generation_job_id,createdAtEpoch:new Date(t.source_created_at).getTime()}}}function n1(t,e){return{id:t.id,status:t.status,bullmqJobId:t.bullmqJobId,sourceType:t.sourceType,sourceId:t.sourceId,transport:e,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function cB(t,e){return{id:t.id,status:t.status,transport:e,bullmqJobId:t.bullmqJobId,sourceType:t.sourceType,sourceId:t.sourceId,attempts:t.attempts,maxAttempts:t.maxAttempts,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function i1(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,sourceType:t.sourceType,sourceId:t.sourceId,agentEventId:t.agentEventId,serverSessionId:t.serverSessionId,jobType:t.jobType,status:t.status,bullmqJobId:t.bullmqJobId,attempts:t.attempts,maxAttempts:t.maxAttempts,nextAttemptAtEpoch:t.nextAttemptAtEpoch,completedAtEpoch:t.completedAtEpoch,failedAtEpoch:t.failedAtEpoch,cancelledAtEpoch:t.cancelledAtEpoch,lastError:t.lastError,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}var B,lg,xxe,Ixe,nB,lB,Txe,iB,ag,Axe,uB,dB,pB,fB=k(()=>{"use strict";B=require("zod");R2();Ic();$i();ri();bd();vd();sd();$c();V();YF();Ch();jx();o$();a4();L8();q8();F8();fa();lg=require("node:crypto");_d();zs();W8();Q8();Bo();X8();xxe="api",Ixe="15.8.3";nB=B.z.object({generate:B.z.union([B.z.literal("true"),B.z.literal("false")]).optional(),wait:B.z.union([B.z.literal("true"),B.z.literal("false")]).optional()}),lB=3e4,Txe=100,iB=["completed","failed","cancelled"];ag=class{constructor(e){this.options=e;this.ingestEvents=new sg({pool:e.pool,resolveEventQueue:()=>this.resolveQueue("event")}),this.endSession=new og({pool:e.pool,resolveSummaryQueue:()=>this.resolveQueue("summary")})}options;ingestEvents;endSession;getIngestEventsService(){return this.ingestEvents}getEndSessionService(){return this.endSession}setupRoutes(e){e.use("/v1",s$());let r=Xo(this.options.pool,{authMode:this.options.authMode,allowLocalDevBypass:this.options.allowLocalDevBypass,requiredScopes:["memories:write"]}),n=Xo(this.options.pool,{authMode:this.options.authMode,allowLocalDevBypass:this.options.allowLocalDevBypass,requiredScopes:["memories:read"]}),i=[],s=Number(process.env.CLAUDE_MEM_RATE_LIMIT_PER_MIN??"0");s>0&&i.push(N8(this.options.pool,{windowSec:60,max:s}));let o=Number(process.env.CLAUDE_MEM_MONTHLY_REQUEST_CAP??"0");o>0&&i.push(XA(this.options.pool,{kind:"request",cap:o})),process.env.CLAUDE_MEM_USAGE_METERING==="1"&&i.push(U8(this.options.pool));let a=[...i],c=Number(process.env.CLAUDE_MEM_MONTHLY_TOKEN_CAP??"0");c>0&&a.push(XA(this.options.pool,{kind:"tokens",cap:c}));let l=[r,...a],u=[n,...i];e.get("/v1/usage",u,this.asyncHandler(async(d,f)=>{let m=this.requireTeamId(d,f);if(!m)return;let h=new Date(Date.UTC(new Date().getUTCFullYear(),new Date().getUTCMonth(),1)),b=await new Jr(this.options.pool).summarize({teamId:m,since:h});f.status(200).json({since:h.toISOString(),usage:b})})),e.post("/v1/keys",l,this.handleCreate(B.z.object({label:B.z.string().max(120).optional(),expiresInDays:B.z.number().int().positive().max(365).optional()}),async(d,f,m)=>{let h=this.requireTeamId(d,f);if(!h)return;let b=`cm_${(0,lg.randomBytes)(24).toString("hex")}`,v=Ed(b),E=Qo(b),S=m.expiresInDays?new Date(Date.now()+m.expiresInDays*864e5):null,w=await new St(this.options.pool).createApiKey({keyHash:v,keyPrefix:E,teamId:h,projectId:d.authContext?.projectId??null,actorId:d.authContext?.apiKeyId??"api",scopes:["memories:read"],expiresAt:S});m.label;let x=tB(d);f.status(201).json({id:w.id,apiKey:b,scopes:["memories:read"],expiresAt:S?.toISOString()??null,mcpUrl:x,connectCommand:rB(x,b)})})),e.get("/v1/connect",u,this.asyncHandler(async(d,f)=>{if(!this.requireTeamId(d,f))return;let h=tB(d);f.status(200).json({mcpUrl:h,connectCommand:rB(h,"<YOUR_API_KEY>"),hint:"POST /v1/keys (write scope) to mint a read-only key for this link."})})),e.post("/v1/events",l,this.asyncHandler(async(d,f)=>{let m=nB.safeParse(d.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let h=m.data.generate!=="false",b=m.data.wait==="true",v=lw.safeParse(d.body);if(!v.success){f.status(400).json({error:"ValidationError",issues:v.error.issues});return}let E=v.data,S=this.requireTeamId(d,f);if(!S||!this.ensureProjectAllowed(d,f,E.projectId))return;let w=this.toAgentEventInput(E,S);await this.applyContentSessionLinks([w],[d.body],S);let x,O=null,C="skipped",J={generate:h,source:"http_post_v1_events",apiKeyId:d.authContext?.apiKeyId??null,actorId:await this.resolveActorId(d),sourceAdapter:w.sourceAdapter,requestId:d.requestId??null};try{let j=await this.ingestEvents.ingestOne(w,J);x=j.event,O=j.outbox,C=j.enqueueState}catch(j){let q=j instanceof Error?j:new Error(String(j));_.warn("SYSTEM","event.write ingest failed",{requestId:d.requestId??null},q),this.handleDbError(q,f,"event.write");return}if(await this.auditWrite(d,"event.received",x.id,x.projectId,{sourceAdapter:x.sourceAdapter,sourceEventId:x.sourceEventId,eventType:x.eventType,serverSessionId:x.serverSessionId,generationJobId:O?.id??null}),b){let j=O,q=!1;if(O){let ee=new st(this.options.pool),ke=await sB(ee,O);j=ke.job,q=ke.timedOut}f.status(201).json({event:yp(x),generationJob:j?cB(j,C):null,...q?{waitTimedOut:!0}:{}});return}f.status(201).json({event:yp(x),...O?{generationJob:n1(O,C)}:{}})})),e.post("/v1/events/batch",l,this.asyncHandler(async(d,f)=>{let m=nB.safeParse(d.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let h=m.data.generate!=="false",b=m.data.wait==="true",E=B.z.array(lw).min(1).max(500).safeParse(d.body);if(!E.success){f.status(400).json({error:"ValidationError",issues:E.error.issues});return}let S=this.requireTeamId(d,f);if(!S)return;let w=Oxe(d,E.data);if(w){f.status(w.status).json(w.body);return}let x=E.data.map(j=>this.toAgentEventInput(j,S));await this.applyContentSessionLinks(x,Array.isArray(d.body)?d.body:E.data,S);let O=[],C=[],J={generate:h,source:"http_post_v1_events_batch",apiKeyId:d.authContext?.apiKeyId??null,actorId:await this.resolveActorId(d),sourceAdapter:null,requestId:d.requestId??null};try{let j=await this.ingestEvents.ingestBatch(x,J);O=j.map(({event:q,outbox:ee})=>({event:q,outbox:ee})),C=j.map(({enqueueState:q})=>q)}catch(j){let q=j instanceof Error?j:new Error(String(j));_.warn("SYSTEM","event.batch_write ingest failed",{requestId:d.requestId??null},q),this.handleDbError(q,f,"event.batch_write");return}if(await this.auditWrite(d,"event.batch_received",null,null,{eventCount:O.length,generationJobIds:O.map(({outbox:j})=>j?.id??null).filter(Boolean)}),b){let j=new st(this.options.pool),q=Date.now()+lB,ee=[];for(let T of O){if(!T.outbox){ee.push({event:T.event,outbox:null,timedOut:!1});continue}let K=Math.max(0,q-Date.now()),M=await sB(j,T.outbox,K);ee.push({event:T.event,outbox:M.job,timedOut:M.timedOut})}let ke=ee.some(T=>T.timedOut);f.status(201).json({events:ee.map(({event:T,outbox:K,timedOut:M},P)=>({event:yp(T),generationJob:K?cB(K,C[P]):null,...M?{waitTimedOut:!0}:{}})),...ke?{waitTimedOut:!0}:{}});return}f.status(201).json({events:O.map(({event:j,outbox:q},ee)=>({event:yp(j),...q?{generationJob:n1(q,C[ee])}:{}}))})})),e.get("/v1/events/:id",u,this.asyncHandler(async(d,f)=>{let m=this.requireTeamId(d,f);if(!m)return;let h=this.routeParam(d.params.id),b=new ln(this.options.pool),v=await this.loadScopedById(d,f,{id:h,teamId:m,table:"agent_events",notFound:"Event not found",load:E=>b.getByIdForScope({id:h,projectId:E,teamId:m})});v&&f.json({event:yp(v)})})),e.get("/v1/events/:id/observations",u,this.asyncHandler(async(d,f)=>{let m=this.requireTeamId(d,f);if(!m)return;let h=this.routeParam(d.params.id),v=(await this.options.pool.query("SELECT id, project_id FROM agent_events WHERE id = $1 AND team_id = $2",[h,m])).rows[0];if(!v){f.status(404).json({error:"NotFound",message:"Event not found"});return}if(!this.ensureProjectAllowed(d,f,v.project_id))return;let E=await this.options.pool.query(`
|
|
908
908
|
SELECT o.id, o.project_id, o.team_id, o.server_session_id, o.kind, o.content,
|
|
909
909
|
o.metadata, o.generation_key, o.created_by_job_id, o.created_at, o.updated_at,
|
|
910
910
|
os.id AS source_id_pk, os.source_type, os.source_id, os.generation_job_id, os.created_at AS source_created_at
|