claude-mem 13.24.0 β 13.24.1
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/.agents/plugins/marketplace.json +1 -2
- package/.codex-plugin/plugin.json +1 -1
- package/README.md +29 -7
- package/dist/npx-cli/index.js +1 -1
- package/openclaw/openclaw.plugin.json +1 -1
- package/package.json +2 -2
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/.codex-plugin/plugin.json +1 -1
- package/plugin/package.json +1 -1
- package/plugin/scripts/mcp-server.cjs +1 -1
- package/plugin/scripts/server-service.cjs +2 -2
- package/plugin/scripts/transcript-watcher.cjs +1 -1
- package/plugin/scripts/worker-service.cjs +363 -363
package/README.md
CHANGED
|
@@ -1,18 +1,26 @@
|
|
|
1
1
|
<h1 align="center">
|
|
2
2
|
<br>
|
|
3
|
-
<a href="https://
|
|
3
|
+
<a href="https://grok-mem.ai">
|
|
4
4
|
<picture>
|
|
5
|
-
<source media="(prefers-color-scheme: dark)" srcset="
|
|
6
|
-
<source media="(prefers-color-scheme: light)" srcset="
|
|
7
|
-
<img src="
|
|
5
|
+
<source media="(prefers-color-scheme: dark)" srcset="docs/public/claude-mem-logo-for-dark-mode.webp">
|
|
6
|
+
<source media="(prefers-color-scheme: light)" srcset="docs/public/claude-mem-logo-for-light-mode.webp">
|
|
7
|
+
<img src="docs/public/claude-mem-logo-for-light-mode.webp" alt="Grok Mem" width="400">
|
|
8
8
|
</picture>
|
|
9
9
|
</a>
|
|
10
10
|
<br>
|
|
11
11
|
<a href="https://vercel.com/open-source-program">
|
|
12
12
|
<img alt="Vercel OSS Program" src="https://vercel.com/oss/program-badge-2026.svg" />
|
|
13
13
|
</a>
|
|
14
|
+
<a href="https://www.greptile.com">
|
|
15
|
+
<img alt="Greptile, code review partner" src="docs/public/greptile-wordmark-green.svg" height="40" />
|
|
16
|
+
</a>
|
|
17
|
+
<a href="https://serpapi.com">
|
|
18
|
+
<img alt="SerpApi" src="docs/public/serpapi-logo-with-wordmark-gradient.svg" height="40" />
|
|
19
|
+
</a>
|
|
14
20
|
</h1>
|
|
15
21
|
|
|
22
|
+
<p align="center">Claude-Mem is now Grok Mem. The package is still <code>claude-mem</code>.</p>
|
|
23
|
+
|
|
16
24
|
<p align="center">
|
|
17
25
|
<a href="docs/i18n/README.zh.md">π¨π³ δΈζ</a> β’
|
|
18
26
|
<a href="docs/i18n/README.zh-tw.md">πΉπΌ ηΉι«δΈζ</a> β’
|
|
@@ -48,14 +56,20 @@
|
|
|
48
56
|
<a href="docs/i18n/README.no.md">π³π΄ Norsk</a>
|
|
49
57
|
</p>
|
|
50
58
|
|
|
51
|
-
<h4 align="center"
|
|
59
|
+
<h4 align="center"><a href="https://grok-mem.ai">Grok Mem</a> is how Grok Bots remember. Sits next to Grok's own memory. Does not replace it.</h4>
|
|
60
|
+
|
|
61
|
+
<p align="center">
|
|
62
|
+
<a href="https://grok-mem.ai">
|
|
63
|
+
<img src="https://img.shields.io/badge/Grok%20mem-1A1A1A?style=for-the-badge" alt="Grok mem">
|
|
64
|
+
</a>
|
|
65
|
+
</p>
|
|
52
66
|
|
|
53
67
|
<p align="center">
|
|
54
68
|
<a href="LICENSE">
|
|
55
69
|
<img src="https://img.shields.io/badge/License-Apache%202.0-blue.svg" alt="License">
|
|
56
70
|
</a>
|
|
57
71
|
<a href="package.json">
|
|
58
|
-
<img src="https://img.shields.io/badge/version-13.
|
|
72
|
+
<img src="https://img.shields.io/badge/version-13.24.1-green.svg" alt="Version">
|
|
59
73
|
</a>
|
|
60
74
|
<a href="package.json">
|
|
61
75
|
<img src="https://img.shields.io/badge/node-%3E%3D20.0.0-brightgreen.svg" alt="Node">
|
|
@@ -123,13 +137,21 @@
|
|
|
123
137
|
</p>
|
|
124
138
|
|
|
125
139
|
<p align="center">
|
|
126
|
-
|
|
140
|
+
<a href="https://grok-mem.ai">Grok Mem</a> is how Grok Bots remember the work. Grok already remembers you. Grok Mem remembers what the bot did, what we decided, what to do next. Those notes come back in the next chat.
|
|
127
141
|
</p>
|
|
128
142
|
|
|
129
143
|
---
|
|
130
144
|
|
|
131
145
|
## Quick Start
|
|
132
146
|
|
|
147
|
+
Install [Grok Mem](https://grok-mem.ai) for Grok Bot. The package name is still [`claude-mem`](https://www.npmjs.com/package/claude-mem).
|
|
148
|
+
|
|
149
|
+
```bash
|
|
150
|
+
npx claude-mem install --ide grok-bot
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
Grok Bot has no host hooks, so we watch the chat log files. Default is CMEM Pro, the hosted memory. Local observer is opt-in: `--provider host`. Installing this plugin does not install Cursor.
|
|
154
|
+
|
|
133
155
|
Install with a single command:
|
|
134
156
|
|
|
135
157
|
```bash
|
package/dist/npx-cli/index.js
CHANGED
|
@@ -98,7 +98,7 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
|
|
|
98
98
|
${m.stack??""}
|
|
99
99
|
`)}else Ii(p+`
|
|
100
100
|
`)}debug(e,r,i,n){this.log(0,e,r,i,n)}info(e,r,i,n){this.log(1,e,r,i,n)}warn(e,r,i,n){this.log(2,e,r,i,n)}setErrorSink(e){lS=e}error(e,r,i,n){this.log(3,e,r,i,n),this.routeErrorToSink(r,i,n)}routeErrorToSink(e,r,i){try{if(!lS||!(i instanceof Error))return;lS(i)}catch{}}dataIn(e,r,i,n){this.info(e,`\u2192 ${r}`,i,n)}dataOut(e,r,i,n){this.info(e,`\u2190 ${r}`,i,n)}success(e,r,i,n){this.info(e,`\u2713 ${r}`,i,n)}failure(e,r,i,n){this.error(e,`\u2717 ${r}`,i,n)}},x=new uS});import{join as UD}from"path";import{mkdirSync as i5,writeFileSync as o5}from"fs";import{randomUUID as s5}from"crypto";function a5(t){let e=t.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function dS(t,e){if(a5(t))return{enabled:!1,source:"DO_NOT_TRACK"};let r=t.CLAUDE_MEM_TELEMETRY?.toLowerCase();return r==="0"||r==="false"||r==="off"?{enabled:!1,source:"env"}:r==="1"||r==="true"||r==="on"?{enabled:!0,source:"env"}:e?.enabled===!0?{enabled:!0,source:"config"}:e?.enabled===!1?{enabled:!1,source:"config"}:{enabled:!0,source:"default"}}function JD(t,e){return dS(t,e).enabled}function Mc(){return UD(Zn(),FD)}function ro(){let t;try{t=or(Mc(),null)}catch(e){let r=e instanceof Error?e:new Error(String(e));return x.warn("SYSTEM","Telemetry: corrupt telemetry.json; treating as no recorded consent",void 0,r),null}return!t||typeof t!="object"||typeof t.installId!="string"||t.enabled!==void 0&&typeof t.enabled!="boolean"?null:{enabled:t.enabled,installId:t.installId,decidedAt:typeof t.decidedAt=="string"?t.decidedAt:""}}function _a(t){let e=Zn();i5(e,{recursive:!0}),o5(UD(e,FD),JSON.stringify(t,null,2)+`
|
|
101
|
-
`)}function Ap(){let t=ro();if(t?.installId)return t.installId;let e=s5();return _a({installId:e,decidedAt:""}),e}var FD,Op=S(()=>{"use strict";tt();Xo();Pe();FD="telemetry.json"});function c5(t,e){if(!(!t||typeof t!="object"))for(let r of Object.keys(t)){if(!l5.has(r))continue;let i=t[r];typeof i=="string"?e[r]=i.length>zD?i.slice(0,zD):i:(typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean")&&(e[r]=i)}}function qD(t){let e={};try{c5(t,e)}catch{}return e}var l5,zD,GD=S(()=>{"use strict";l5=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","stage","install_method","interactive","bun_version","uv_version","claude_code_version","trial_days","trial_variant","offer_surface","funnel_source","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","limit_window","overage_status","is_using_overage","resets_in_minutes","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_invalid_output","top_model","observed_model","observed_billing","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","observations_created","total_observations_injected","total_tokens_saved_vs_naive"]),zD=200});import VD from"os";function BD(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||d5}function WD(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||p5}function HD(t){let e={};for(let r of f5)t[r]!==void 0&&(e[r]=t[r]);return e}function m5(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||VD.release().toLowerCase().includes("microsoft")}catch(t){let e=t instanceof Error?t:new Error(String(t));return x.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function ZD(){return{version:u5,os:process.platform,os_version:VD.release(),is_wsl:m5(),arch:process.arch,runtime:process.versions.bun?"bun":"node",runtime_version:process.versions.bun??process.versions.node,node_version:process.versions.node,is_ci:!!process.env.CI,locale:Intl.DateTimeFormat().resolvedOptions().locale}}var u5,d5,p5,f5,YD=S(()=>{"use strict";Pe();u5="13.24.
|
|
101
|
+
`)}function Ap(){let t=ro();if(t?.installId)return t.installId;let e=s5();return _a({installId:e,decidedAt:""}),e}var FD,Op=S(()=>{"use strict";tt();Xo();Pe();FD="telemetry.json"});function c5(t,e){if(!(!t||typeof t!="object"))for(let r of Object.keys(t)){if(!l5.has(r))continue;let i=t[r];typeof i=="string"?e[r]=i.length>zD?i.slice(0,zD):i:(typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean")&&(e[r]=i)}}function qD(t){let e={};try{c5(t,e)}catch{}return e}var l5,zD,GD=S(()=>{"use strict";l5=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","stage","install_method","interactive","bun_version","uv_version","claude_code_version","trial_days","trial_variant","offer_surface","funnel_source","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","limit_window","overage_status","is_using_overage","resets_in_minutes","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_invalid_output","top_model","observed_model","observed_billing","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","observations_created","total_observations_injected","total_tokens_saved_vs_naive"]),zD=200});import VD from"os";function BD(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||d5}function WD(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||p5}function HD(t){let e={};for(let r of f5)t[r]!==void 0&&(e[r]=t[r]);return e}function m5(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||VD.release().toLowerCase().includes("microsoft")}catch(t){let e=t instanceof Error?t:new Error(String(t));return x.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function ZD(){return{version:u5,os:process.platform,os_version:VD.release(),is_wsl:m5(),arch:process.arch,runtime:process.versions.bun?"bun":"node",runtime_version:process.versions.bun??process.versions.node,node_version:process.versions.node,is_ci:!!process.env.CI,locale:Intl.DateTimeFormat().resolvedOptions().locale}}var u5,d5,p5,f5,YD=S(()=>{"use strict";Pe();u5="13.24.1",d5="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",p5="https://us.i.posthog.com";f5=["version","os","os_version","is_wsl","arch","runtime","locale","ide","provider","runtime_mode","install_method","claude_code_version","first_active_date","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs"]});async function Yn(t,e,r){try{if(!JD(process.env,ro()))return;let i=qD({...ZD(),...e??{}});if(r?.person?i.$set=HD(i):i.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:t,properties:i})+`
|
|
102
102
|
`);return}let n=BD(),o=new AbortController,s=setTimeout(()=>o.abort(),h5);try{await y5(n,t,i,o.signal)}finally{clearTimeout(s)}}catch{}}async function y5(t,e,r,i){await fetch(`${WD()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:t,event:e,distinct_id:Ap(),properties:r}),signal:i})}var h5,Rp=S(()=>{"use strict";Op();GD();YD();h5=2e3});import{spawn as g5,spawnSync as b5}from"node:child_process";import{extname as pS}from"node:path";function Xn(t,e,r){return g5(t,e??[],{windowsHide:!0,...r})}function S5(t){return`"${t.replace(/"/g,'""')}"`}function fS(t){if(process.platform!=="win32")return[];try{let e=b5("where",[t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0});return e.status!==0||!e.stdout.trim()?[]:e.stdout.split(/\r?\n/).map(r=>r.trim()).filter(Boolean)}catch{return[]}}function Dp(t){let e=fS(t);return e.find(r=>QD.has(pS(r).toLowerCase()))??e.find(r=>v5.has(pS(r).toLowerCase()))??e[0]??null}function Ia(t,e,r,i=process.platform){let n={...i==="win32"?{windowsHide:!0}:{},...r};if(i==="win32"&&XD.has(pS(t).toLowerCase())){let o=[t,...e].map(S5).join(" ");return{command:process.env.ComSpec??"cmd.exe",args:["/d","/s","/c",`"${o}"`],options:{...n,windowsVerbatimArguments:!0}}}return{command:t,args:[...e],options:n}}var XD,QD,v5,Ti=S(()=>{"use strict";XD=new Set([".cmd",".bat"]),QD=new Set([".exe",".com"]),v5=new Set([...QD,...XD])});function xa(t){return process.platform==="win32"?Math.round(t*Ur.WINDOWS_MULTIPLIER):t}var Ur,Kp=S(()=>{"use strict";Ur={HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5}});var rK={};Re(rK,{SettingsDefaultsManager:()=>qe});import{readFileSync as E5,existsSync as w5}from"fs";import{join as eK}from"path";import{homedir as tK,hostname as k5}from"os";var _5,qe,dn=S(()=>{"use strict";Kp();ln();_5="security_alert",qe=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_API_TIMEOUT_MS:String(xa(Ur.API_REQUEST)),CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-flash-latest",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_DATA_DIR:eK(tK(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:eK(tK(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_OBSERVER_MAX_CONVERSATION_CHARS:"400000",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_CHROMA_MAX_PENDING_MUTATIONS:"5000",CLAUDE_MEM_CLOUD_SYNC_TOKEN:"",CLAUDE_MEM_CLOUD_SYNC_USER_ID:"",CLAUDE_MEM_CLOUD_SYNC_HUB_URL:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_ID:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_NAME:k5(),CLAUDE_MEM_CLOUD_SYNC_WS:"true",CLAUDE_MEM_PRO_TRIAL_EMAIL:"",CLAUDE_MEM_PRO_TRIAL_AT:"",CLAUDE_MEM_PRO_TRIAL_STATE:"",CLAUDE_MEM_PRO_TRIAL_ENDS_AT:"",CLAUDE_MEM_PRO_PLAN:"",CLAUDE_MEM_PRO_FALLBACK_AT:"",CLAUDE_MEM_PRO_MEMORY_KEY:"",CLAUDE_MEM_PRO_MEMORY_BASE_URL:"",CLAUDE_MEM_PRO_MEMORY_MODEL:"",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert,sensitive",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let r=this.get(e);return parseInt(r,10)}static applyEnvOverrides(e){let r={...e};for(let i of Object.keys(this.DEFAULTS))process.env[i]!==void 0&&(r[i]=process.env[i]);return r}static loadFromFile(e,r=!0){try{if(!w5(e)){let c=this.getAllDefaults();try{yt(e,c),console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(u){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,u instanceof Error?u.message:String(u))}return r?this.applyEnvOverrides(c):c}let i=E5(e,"utf-8"),n=Zt(i),o=n,s=n.env&&typeof n.env=="object"&&!Array.isArray(n.env),a=s&&Object.keys(n).some(c=>c!=="env");if(s&&(o=n.env,!a))try{yt(e,o),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(c){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,c instanceof Error?c.message:String(c))}if(o.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES===_5){o={...o,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES};try{yt(e,a?{...n,env:o}:o),console.warn("[SETTINGS] Migrated Telegram trigger types off the legacy default:",e)}catch(c){console.warn("[SETTINGS] Failed to migrate Telegram trigger types:",e,c instanceof Error?c.message:String(c))}}let l={...this.DEFAULTS};for(let c of Object.keys(this.DEFAULTS))o[c]!==void 0&&(l[c]=o[c]);return r?this.applyEnvOverrides(l):l}catch(i){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,i instanceof Error?i.message:String(i));let n=this.getAllDefaults();return r?this.applyEnvOverrides(n):n}}}});import{execFile as I5}from"child_process";import{promisify as x5}from"util";import{existsSync as Z0e,readFileSync as Y0e,writeFileSync as X0e,mkdirSync as Q0e,unlinkSync as eke}from"fs";import{userInfo as rke}from"os";import{join as ike}from"path";var ake,nK=S(()=>{"use strict";tt();Pe();ake=x5(I5)});import{existsSync as mS,readFileSync as oK,writeFileSync as T5,mkdirSync as C5,chmodSync as iK}from"fs";import{parseEnv as A5}from"util";function sK(){return process.env.CLAUDE_MEM_ENV_FILE??et.envFile()}function lK(t){return A5(t)}function O5(t){let e=["# claude-mem credentials","# This file stores keys and gateway settings for the claude-mem memory agent","# Edit this file or use claude-mem settings to configure",""];for(let[r,i]of Object.entries(t))if(i){let n=/[\s#=]/.test(i);e.push(`${r}=${n?`"${i}"`:i}`)}return e.join(`
|
|
103
103
|
`)+`
|
|
104
104
|
`}function cK(){let t=sK();if(!mS(t))return{};try{let e=oK(t,"utf-8"),r=lK(e),i={};for(let n of aK)r[n]&&(i[n]=r[n]);return i}catch(e){return x.warn("ENV","Failed to load .env file",{path:t},e instanceof Error?e:new Error(String(e))),{}}}function uK(t){let e=sK(),r={};try{mS(et.dataDir())||C5(et.dataDir(),{recursive:!0,mode:448}),iK(et.dataDir(),448),r=mS(e)?lK(oK(e,"utf-8")):{}}catch(n){let o=n instanceof Error?n:new Error(String(n));throw x.error("ENV","Failed to set up env directory or read existing env",{},o),o}let i={...r};for(let n of aK){let o=t[n];o!==void 0&&(o?i[n]=o:delete i[n])}try{T5(e,O5(i),{encoding:"utf-8",mode:384}),iK(e,384)}catch(n){throw x.error("ENV","Failed to save .env file",{path:e},n instanceof Error?n:new Error(String(n))),n}}var aK,dK=S(()=>{"use strict";Pe();tt();nK();aK=["ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN","GEMINI_API_KEY","OPENROUTER_API_KEY"]});function Qn(t=process.env){let e={};for(let[r,i]of Object.entries(t))if(i!==void 0){if(P5.has(r)){e[r]=i;continue}D5.has(r)||R5.some(n=>r.startsWith(n))||(e[r]=i)}return e}var R5,D5,K5,P5,Nc=S(()=>{"use strict";R5=["CLAUDECODE_","CLAUDE_CODE_"],D5=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),K5=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"]),P5=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS",...K5])});import{spawnSync as fK}from"child_process";import{readFileSync as j5}from"fs";function N5(t){hS+=1;let e=fK("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Qn(process.env),LC_ALL:"C",LANG:"C"}});if(e.status===0){let r=e.stdout.trim();return r.length>0?r:null}return null}function L5(t,e=!1){if(!e){let i=pK.get(t);if(i&&Date.now()-i.capturedAtMs<M5)return i.token}let r=null;try{r=N5(t)}catch(i){x.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:i instanceof Error?i.message:String(i)}),r=null}return pK.set(t,{token:r,capturedAtMs:Date.now()}),r}function mK(t,e){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux"){hS+=1;try{let r=j5(`/proc/${t}/stat`,"utf-8"),i=r.lastIndexOf(") ");if(i<0)return null;let o=r.slice(i+2).split(" ")[19];return o&&/^\d+$/.test(o)?o:null}catch(r){return x.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}if(process.platform==="win32")return L5(t,e);hS+=1;try{let r=fK("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Qn(process.env),LC_ALL:"C",LANG:"C"}});if(r.status!==0)return null;let i=r.stdout.trim();return i.length>0?i:null}catch(r){return x.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}function no(t){return mK(t,!1)}function Ci(t,e){if(e===null)return!0;let r=mK(t,!0);return r===null?!0:r===e}var M5,pK,hS,yS=S(()=>{"use strict";Pe();Nc();M5=5e3,pK=new Map,hS=0});import{execFile as $5}from"child_process";import{readdirSync as U5,readFileSync as F5}from"fs";import{promisify as J5}from"util";async function is(t,e={}){let r=e.signalMode==="immediate",i=e.expectedStartToken!==void 0?e.expectedStartToken:no(t),n=()=>Ci(t,i);if(!n()){x.warn("PROCESS","Skipping tree-kill: root PID was reused since it was captured",{pid:t});return}if(x.debug("PROCESS",`Killing process tree rooted at PID ${t}`,{immediate:r}),process.platform==="win32"){try{await gS("taskkill",["/PID",String(t),"/T","/F"],{timeout:5e3,windowsHide:!0})}catch(o){let s=o.code,a=String(o.stderr??""),l=o instanceof Error?o.message:String(o);if(s===z5||q5.test(`${a} ${l}`)){x.debug("PROCESS","taskkill reported the process was already gone",{pid:t});return}throw new Pp(t,`taskkill failed for PID ${t} (exit ${String(s)}): ${a.trim()||l}`,{cause:o})}return}try{let o=r?"SIGKILL":"SIGTERM",s=await jp(t);for(let c of s){if(!Ci(c.pid,c.startToken)){x.debug("PROCESS",`Skipping ${o}: descendant PID was reused since enumeration`,{pid:c.pid,rootPid:t});continue}try{process.kill(c.pid,o)}catch{}}if(n())try{process.kill(t,o)}catch(c){let u=c instanceof Error?c:new Error(String(c)),d=u.code;d!=="ESRCH"&&x.debug("PROCESS",`Failed to ${o} PID ${t}`,{code:d},u)}else x.warn("PROCESS","Skipping root signal: PID was reused during descendant enumeration",{pid:t,signal:o});r||await new Promise(c=>setTimeout(c,500));let a=n()?await jp(t):[],l=new Map;for(let c of s)l.set(c.pid,c.startToken);for(let c of a)l.set(c.pid,c.startToken);for(let[c,u]of l){if(!Ci(c,u)){x.debug("PROCESS","Skipping SIGKILL: descendant PID was reused since the scan",{pid:c,rootPid:t});continue}try{process.kill(c,"SIGKILL")}catch{}}if(!r&&n())try{process.kill(t,"SIGKILL")}catch{}}catch(o){throw new Pp(t,`tree-kill failed for PID ${t}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}}async function G5(){return process.platform==="win32"?W5():process.platform==="linux"?V5():B5()}function V5(){let t=[],e;try{e=U5("/proc")}catch(r){return x.warn("PROCESS","Cannot read /proc \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),t}for(let r of e){if(!/^\d+$/.test(r))continue;let i;try{i=F5(`/proc/${r}/stat`,"utf-8")}catch{continue}let n=i.lastIndexOf(") ");if(n<0)continue;let o=i.slice(n+2).split(" "),s=Number.parseInt(o[1]??"",10),a=o[19];Number.isFinite(s)&&t.push({pid:Number.parseInt(r,10),ppid:s,startToken:a&&/^\d+$/.test(a)?a:null})}return t}async function B5(){let t;try{t=(await gS("ps",["-eo","pid=,ppid=,lstart="],{timeout:1e4,maxBuffer:33554432,env:{...process.env,LC_ALL:"C",LANG:"C"}})).stdout}catch(r){return x.warn("PROCESS","Cannot enumerate the process table \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),[]}let e=[];for(let r of t.split(`
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "Claude-Mem (Persistent Memory)",
|
|
4
4
|
"description": "OpenClaw plugin for Claude-Mem. Records observations from embedded runner sessions and streams them to messaging channels.",
|
|
5
5
|
"kind": "memory",
|
|
6
|
-
"version": "13.24.
|
|
6
|
+
"version": "13.24.1",
|
|
7
7
|
"license": "Apache-2.0",
|
|
8
8
|
"author": "thedotmack",
|
|
9
9
|
"homepage": "https://claude-mem.ai",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "claude-mem",
|
|
3
|
-
"version": "13.24.
|
|
3
|
+
"version": "13.24.1",
|
|
4
4
|
"description": "Memory compression system for Claude Code - persist context across sessions",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"claude",
|
|
@@ -122,7 +122,7 @@
|
|
|
122
122
|
"@better-auth/api-key": "^1.6.16",
|
|
123
123
|
"better-auth": "^1.6.16"
|
|
124
124
|
},
|
|
125
|
-
"//dependencies-note": "Only deps that survive the bundler as a live `import`/`require` in a shipped artifact live here
|
|
125
|
+
"//dependencies-note": "Only deps that survive the bundler as a live `import`/`require` in a shipped artifact live here β better-auth (+ api-key) is the server-runtime auth surface, externalized from the worker bundle deliberately (see scripts/build-hooks.js). Everything else (express, bullmq, ioredis, react, react-dom, dompurify, @clack/prompts, ansi-to-html, posthog-node, shell-quote, pg, zod, @modelcontextprotocol/sdk, @anthropic-ai/claude-agent-sdk) is esbuild-inlined into the worker/server/npx bundles (or, for zod's plugin runtime copy, resolved from plugin/package.json's own dependency), so it is a build-time devDependency and is not downloaded by consumers of the `claude-mem` package.",
|
|
126
126
|
"overrides": {
|
|
127
127
|
"tmp": "^0.2.7"
|
|
128
128
|
},
|
package/plugin/package.json
CHANGED
|
@@ -211,7 +211,7 @@ ${f}`}let a=s.lineStart;for(let u=s.lineStart-1;u>=0;u--){let l=i[u].trim();if(l
|
|
|
211
211
|
${c}`}ae();var oI=new Set([".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".pyw",".go",".rs",".rb",".java",".cs",".cpp",".cc",".cxx",".c",".h",".hpp",".hh",".swift",".kt",".kts",".php",".vue",".svelte",".lua",".scala",".sc",".sh",".bash",".zsh",".hs",".zig",".css",".scss",".toml",".yml",".yaml",".sql",".md",".mdx"]),sI=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),iI=512*1024;async function*dS(e,t,r=20){if(r<=0)return;let n;try{n=await(0,Jr.readdir)(e,{withFileTypes:!0})}catch(o){_.debug("WORKER",`walkDir: failed to read directory ${e}`,void 0,o instanceof Error?o:void 0);return}for(let o of n){if(o.name.startsWith(".")&&o.name!=="."||sI.has(o.name))continue;let s=(0,mo.join)(e,o.name);if(o.isDirectory())yield*dS(s,t,r-1);else if(o.isFile()){let i=o.name.slice(o.name.lastIndexOf("."));oI.has(i)&&(yield s)}}}async function aI(e){try{let t=await(0,Jr.stat)(e);if(t.size>iI||t.size===0)return null;let r=await(0,Jr.readFile)(e,"utf-8");return r.slice(0,1e3).includes("\0")?null:r}catch(t){return _.debug("WORKER",`safeReadFile: failed to read ${e}`,void 0,t instanceof Error?t:void 0),null}}async function pS(e,t,r={}){let n=r.maxResults||20,o=t.toLowerCase(),s=o.split(/[\s_\-./]+/).filter(h=>h.length>0),i=[];for await(let h of dS(e,e,20)){if(r.filePattern&&!(0,mo.relative)(e,h).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let g=await aI(h);g&&i.push({absolutePath:h,relativePath:(0,mo.relative)(e,h),content:g})}let a=cS(i),c=[],u=[],l=0;for(let[h,g]of a){l+=cI(g);let v=Oi(h.toLowerCase(),s)>0,E=[],I=(x,D)=>{for(let j of x){let Ze=0,ke="",rt=Oi(j.name.toLowerCase(),s);rt>0&&(Ze+=rt*3,ke="name match"),j.signature.toLowerCase().includes(o)&&(Ze+=2,ke=ke?`${ke} + signature`:"signature match"),j.jsdoc&&j.jsdoc.toLowerCase().includes(o)&&(Ze+=1,ke=ke?`${ke} + jsdoc`:"jsdoc match"),Ze>0&&(v=!0,E.push({filePath:h,symbolName:D?`${D}.${j.name}`:j.name,kind:j.kind,signature:j.signature,jsdoc:j.jsdoc,lineStart:j.lineStart,lineEnd:j.lineEnd,matchReason:ke})),j.children&&I(j.children,j.name)}};I(g.symbols),v&&(c.push(g),u.push(...E))}u.sort((h,g)=>{let b=Oi(h.symbolName.toLowerCase(),s);return Oi(g.symbolName.toLowerCase(),s)-b});let d=u.slice(0,n),p=new Set(d.map(h=>h.filePath)),f=c.filter(h=>p.has(h.filePath)).slice(0,n),m=f.reduce((h,g)=>h+g.foldedTokenEstimate,0);return{foldedFiles:f,matchingSymbols:d,totalFilesScanned:i.length,totalSymbolsFound:l,tokenEstimate:m}}function Oi(e,t){let r=0;for(let n of t)if(e===n)r+=10;else if(e.includes(n))r+=5;else{let o=0,s=0;for(let i of n){let a=e.indexOf(i,o);a!==-1&&(s++,o=a+1)}s===n.length&&(r+=1)}return r}function cI(e){let t=e.symbols.length;for(let r of e.symbols)r.children&&(t+=r.children.length);return t}function fS(e,t){let r=[];if(r.push(`\u{1F50D} Smart Search: "${t}"`),r.push(` Scanned ${e.totalFilesScanned} files, found ${e.totalSymbolsFound} symbols`),r.push(` ${e.matchingSymbols.length} matches across ${e.foldedFiles.length} files (~${e.tokenEstimate} tokens for folded view)`),r.push(""),e.matchingSymbols.length===0)return r.push(" No matching symbols found."),r.join(`
|
|
212
212
|
`);r.push("\u2500\u2500 Matching Symbols \u2500\u2500"),r.push("");for(let n of e.matchingSymbols){if(r.push(` ${n.kind} ${n.symbolName} (${n.filePath}:${n.lineStart+1})`),r.push(` ${n.signature}`),n.jsdoc){let o=n.jsdoc.split(`
|
|
213
213
|
`).find(s=>s.replace(/^[\s*/]+/,"").trim().length>0);o&&r.push(` \u{1F4AC} ${o.replace(/^[\s*/]+/,"").trim()}`)}r.push("")}r.push("\u2500\u2500 Folded File Views \u2500\u2500"),r.push("");for(let n of e.foldedFiles)r.push(Gr(n)),r.push("");return r.push("\u2500\u2500 Actions \u2500\u2500"),r.push(" To see full implementation: use smart_unfold with file path and symbol name"),r.join(`
|
|
214
|
-
`)}var Ul=require("node:fs/promises"),Mi=require("node:fs"),ft=require("node:path"),bS=require("node:os"),vS=require("node:url");var mS="claude";function uI(e){return e.trim().toLowerCase().replace(/\s+/g,"-")}function zi(e){if(!e)return mS;let t=uI(e);return t?t==="transcript"||t.includes("codex")?"codex":t.includes("cursor")?"cursor":t.includes("claude")?"claude":t:mS}var lI=Gt(Re.API_REQUEST),tt=class extends Error{kind;status;cause;constructor(t,r,n={}){super(r),this.name="ServerClientError",this.kind=t,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},Ai=class{baseUrl;apiKey;timeoutMs;constructor(t){this.baseUrl=dI(t.serverBaseUrl),this.apiKey=t.apiKey,this.timeoutMs=t.timeoutMs??lI}async startSession(t){let r=this.buildStartSessionPayload(t);return this.request("POST","/v1/sessions/start",r)}async recordEvent(t){let r=this.buildEventPayload(t),n=t.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(t){if(!t.sessionId)throw new tt("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(t.sessionId)}/end`,{})}async addObservation(t){return this.request("POST","/v1/memories",this.buildAddObservationPayload(t))}async searchObservations(t){return this.request("POST","/v1/search",this.buildSearchPayload(t))}async contextObservations(t){return this.request("POST","/v1/context",this.buildSearchPayload(t))}async getJobStatus(t){if(!t)throw new tt("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(t)}`)}buildAddObservationPayload(t){let r=t.content,n=t.kind??"manual",o=typeof t.metadata?.title=="string"?t.metadata.title:void 0;return{projectId:t.projectId,kind:n,type:n,narrative:r,...o?{title:o}:{},...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}}}buildSearchPayload(t){return{projectId:t.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:jl(t.platformSource)}:{}}}buildStartSessionPayload(t){return{projectId:t.projectId,...t.externalSessionId!==void 0?{externalSessionId:t.externalSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.agentId!==void 0?{agentId:t.agentId}:{},...t.agentType!==void 0?{agentType:t.agentType}:{},...t.platformSource!==void 0?{platformSource:jl(t.platformSource)}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}}}buildEventPayload(t){return{projectId:t.projectId,sourceType:t.sourceType,eventType:t.eventType,occurredAtEpoch:t.occurredAtEpoch,...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.memorySessionId!==void 0?{memorySessionId:t.memorySessionId}:{},...t.platformSource!==void 0?{platformSource:jl(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{}}}async request(t,r,n){if(!this.apiKey||!this.apiKey.trim())throw new tt("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let o=`${this.baseUrl}${r}`,s={method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(s.body=JSON.stringify(n));let i;try{i=await Rl(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new tt(l?"timeout":"transport",`Server ${t} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new tt("http_error",`Server ${t} ${r} returned ${i.status}: ${pI(c,200)}`,{status:i.status})}let a=await i.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(c){let u=c instanceof Error?c:new Error(String(c));throw new tt("invalid_response",`Server ${t} ${r} returned non-JSON response`,{cause:u})}}};function hS(e){return e instanceof tt}function dI(e){return e.replace(/\/+$/,"")}function jl(e){return typeof e=="string"?zi(e):null}function pI(e,t){return e.length<=t?e:`${e.slice(0,t)}\u2026`}ae();function Ci(){let t=(fi().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return t==="server"||t==="server-beta"?"server":"worker"}function gS(){let e=fi(),t=(...i)=>{for(let a of i){let c=(a??"").trim();if(c.length>0)return c}return""},r=t(e.CLAUDE_MEM_SERVER_URL,e.CLAUDE_MEM_SERVER_BETA_URL),n=t(e.CLAUDE_MEM_SERVER_API_KEY,e.CLAUDE_MEM_SERVER_BETA_API_KEY),o=t(e.CLAUDE_MEM_SERVER_PROJECT_ID,e.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!r)return _.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return _.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return _.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let s={serverBaseUrl:r,apiKey:n};return{runtime:"server",client:new Ai(s),projectId:o,serverBaseUrl:r}}ae();var _S=["observation_add","observation_record_event","observation_search","observation_context","observation_generation_status","memory_add","memory_search","memory_context"],fI=new Set(_S);function yS(e,t){return t==="server"?[...e]:(_.debug("SYSTEM","Filtering server-beta-only MCP tools from worker runtime advertisement",{runtime:t,hiddenToolCount:_S.length}),e.filter(r=>!fI.has(r.name)))}var AI={},mI="13.24.0";console.log=(...e)=>{_.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:e})};var ES=!1,wS=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,ft.dirname)((0,vS.fileURLToPath)(AI.url))}catch(e){return ES=!0,_.warn("SYSTEM","mcp-server: failed to resolve module directory from import.meta.url, falling back to process.cwd()",void 0,e instanceof Error?e:new Error(String(e))),process.cwd()}})(),Fl=Jy()??(0,ft.resolve)(wS,"worker-service.cjs");function hI(){ES&&((0,Mi.existsSync)(Fl)||_.error("SYSTEM","mcp-server: dirname resolution failed (both __dirname and import.meta.url are unavailable). Fell back to process.cwd() and the resolved WORKER_SCRIPT_PATH does not exist. This is the actual problem \u2014 the worker bundle is fine, but mcp-server cannot locate it. Worker auto-start will fail until the dirname-resolution path is fixed.",{workerScriptPath:Fl,mcpServerDir:wS}))}async function vt(e,t={}){_.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:e});try{let r;if(t.body)r=await Pi(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t.body)});else{let n=new URLSearchParams;for(let[o,s]of Object.entries(t.query??{}))s!=null&&n.append(o,String(s));r=await Pi(`${e}?${n}`)}if(!r.ok){let n=await r.text();throw new Error(`Worker API error (${r.status}): ${n}`)}return _.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:e}),t.text?{content:[{type:"text",text:await r.text()}]}:t.body?{content:[{type:"text",text:JSON.stringify(await r.json(),null,2)}]}:await r.json()}catch(r){return _.error("SYSTEM","\u2190 Worker API error",{endpoint:e},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function gI(){try{return(await Pi("/api/health")).ok}catch(e){return _.debug("SYSTEM","Worker health check failed",{},e instanceof Error?e:new Error(String(e))),!1}}function kS(){if(Ci()!=="server")return null;let t=gS();return t?{...t,available:!0}:{runtime:"server",available:!1,reason:"server runtime is selected but configuration is incomplete (missing url, api key, or project id)"}}function _I(e){return hS(e)?{content:[{type:"text",text:`Server error (${e.kind}${e.status?` ${e.status}`:""}): ${e.message}`}],isError:!0}:{content:[{type:"text",text:`Tool error: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}function Xr(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function go(e){let t=kS();if(!t)throw new tt("transport",`${e} requires CLAUDE_MEM_RUNTIME=server. Current runtime is "worker"; use the existing search/timeline/get_observations tools for worker-mode memory access.`);if(!t.available)throw new tt("missing_api_key",`${e}: ${t.reason}`);return t}function _o(e,t){return async r=>{try{return await t(r)}catch(n){let o=n instanceof Error?n:new Error(String(n));return _.warn("SYSTEM",`${e} failed`,void 0,o),_I(n)}}}var yI=_o("observation_add",async e=>{let t=go("observation_add");if(typeof e?.content!="string"||e.content.trim().length===0)throw new Error('observation_add: "content" is required');let n={projectId:e.projectId&&e.projectId.trim().length>0?e.projectId:t.projectId,content:e.content,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.kind!==void 0?{kind:e.kind}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}},o=await t.client.addObservation(n);return Xr(o)});function Ni(e){return typeof e=="string"?zi(e):null}var SI=_o("observation_record_event",async e=>{let t=go("observation_record_event");if(typeof e?.eventType!="string"||e.eventType.trim().length===0)throw new Error('observation_record_event: "eventType" is required');let n={projectId:e.projectId&&e.projectId.trim().length>0?e.projectId:t.projectId,sourceType:e.sourceType??"api",eventType:e.eventType,occurredAtEpoch:typeof e.occurredAtEpoch=="number"?e.occurredAtEpoch:Date.now(),...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:Ni(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{},...e.generate!==void 0?{generate:e.generate}:{}},o=await t.client.recordEvent(n);return Xr(o)}),bI=_o("observation_search",async e=>{let t=go("observation_search");if(typeof e?.query!="string"||e.query.trim().length===0)throw new Error('observation_search: "query" is required');let n={projectId:e.projectId&&e.projectId.trim().length>0?e.projectId:t.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Ni(e.platformSource)}:{}},o=await t.client.searchObservations(n);return Xr(o)}),vI=_o("observation_context",async e=>{let t=go("observation_context");if(typeof e?.query!="string"||e.query.trim().length===0)throw new Error('observation_context: "query" is required');let n={projectId:e.projectId&&e.projectId.trim().length>0?e.projectId:t.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Ni(e.platformSource)}:{}},o=await t.client.contextObservations(n);return Xr(o)});function EI(e){return Array.isArray(e.projects)?e.projects.map(t=>typeof t=="string"?t.trim():"").filter(Boolean):typeof e.projects=="string"?e.projects.split(",").map(t=>t.trim()).filter(Boolean):typeof e.project=="string"&&e.project.trim().length>0?[e.project.trim()]:[]}async function wI(e){let t=EI(e);return t.length===0?{content:[{type:"text",text:'session_start_context: "project" or "projects" is required'}],isError:!0}:vt("/api/context/inject",{query:{projects:t.join(","),...e.platformSource!==void 0?{platformSource:Ni(e.platformSource)}:{},...e.full!==void 0?{full:e.full}:{},...e.colors!==void 0?{colors:e.colors}:{}},text:!0})}var kI=_o("observation_generation_status",async e=>{let t=go("observation_generation_status"),r=(e?.jobId??e?.job_id??"").trim();if(!r)throw new Error('observation_generation_status: "jobId" is required');let n=await t.client.getJobStatus(r);return Xr(n)});async function xI(){if(await gI())return!0;_.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),hI();try{let e=Ol(),t=await Xy(e,Fl);return t==="dead"&&_.error("SYSTEM","Worker auto-start failed \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running. Check earlier log lines for the specific failure reason (Bun not found, missing worker bundle, port conflict, etc.)."),t!=="dead"}catch(e){return _.error("SYSTEM","Worker auto-start threw \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running.",void 0,e instanceof Error?e:new Error(String(e))),!1}}var xS=[{name:"important_workflow",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
|
|
214
|
+
`)}var Ul=require("node:fs/promises"),Mi=require("node:fs"),ft=require("node:path"),bS=require("node:os"),vS=require("node:url");var mS="claude";function uI(e){return e.trim().toLowerCase().replace(/\s+/g,"-")}function zi(e){if(!e)return mS;let t=uI(e);return t?t==="transcript"||t.includes("codex")?"codex":t.includes("cursor")?"cursor":t.includes("claude")?"claude":t:mS}var lI=Gt(Re.API_REQUEST),tt=class extends Error{kind;status;cause;constructor(t,r,n={}){super(r),this.name="ServerClientError",this.kind=t,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},Ai=class{baseUrl;apiKey;timeoutMs;constructor(t){this.baseUrl=dI(t.serverBaseUrl),this.apiKey=t.apiKey,this.timeoutMs=t.timeoutMs??lI}async startSession(t){let r=this.buildStartSessionPayload(t);return this.request("POST","/v1/sessions/start",r)}async recordEvent(t){let r=this.buildEventPayload(t),n=t.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(t){if(!t.sessionId)throw new tt("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(t.sessionId)}/end`,{})}async addObservation(t){return this.request("POST","/v1/memories",this.buildAddObservationPayload(t))}async searchObservations(t){return this.request("POST","/v1/search",this.buildSearchPayload(t))}async contextObservations(t){return this.request("POST","/v1/context",this.buildSearchPayload(t))}async getJobStatus(t){if(!t)throw new tt("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(t)}`)}buildAddObservationPayload(t){let r=t.content,n=t.kind??"manual",o=typeof t.metadata?.title=="string"?t.metadata.title:void 0;return{projectId:t.projectId,kind:n,type:n,narrative:r,...o?{title:o}:{},...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}}}buildSearchPayload(t){return{projectId:t.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:jl(t.platformSource)}:{}}}buildStartSessionPayload(t){return{projectId:t.projectId,...t.externalSessionId!==void 0?{externalSessionId:t.externalSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.agentId!==void 0?{agentId:t.agentId}:{},...t.agentType!==void 0?{agentType:t.agentType}:{},...t.platformSource!==void 0?{platformSource:jl(t.platformSource)}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}}}buildEventPayload(t){return{projectId:t.projectId,sourceType:t.sourceType,eventType:t.eventType,occurredAtEpoch:t.occurredAtEpoch,...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.memorySessionId!==void 0?{memorySessionId:t.memorySessionId}:{},...t.platformSource!==void 0?{platformSource:jl(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{}}}async request(t,r,n){if(!this.apiKey||!this.apiKey.trim())throw new tt("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let o=`${this.baseUrl}${r}`,s={method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(s.body=JSON.stringify(n));let i;try{i=await Rl(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new tt(l?"timeout":"transport",`Server ${t} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new tt("http_error",`Server ${t} ${r} returned ${i.status}: ${pI(c,200)}`,{status:i.status})}let a=await i.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(c){let u=c instanceof Error?c:new Error(String(c));throw new tt("invalid_response",`Server ${t} ${r} returned non-JSON response`,{cause:u})}}};function hS(e){return e instanceof tt}function dI(e){return e.replace(/\/+$/,"")}function jl(e){return typeof e=="string"?zi(e):null}function pI(e,t){return e.length<=t?e:`${e.slice(0,t)}\u2026`}ae();function Ci(){let t=(fi().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return t==="server"||t==="server-beta"?"server":"worker"}function gS(){let e=fi(),t=(...i)=>{for(let a of i){let c=(a??"").trim();if(c.length>0)return c}return""},r=t(e.CLAUDE_MEM_SERVER_URL,e.CLAUDE_MEM_SERVER_BETA_URL),n=t(e.CLAUDE_MEM_SERVER_API_KEY,e.CLAUDE_MEM_SERVER_BETA_API_KEY),o=t(e.CLAUDE_MEM_SERVER_PROJECT_ID,e.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!r)return _.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return _.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return _.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let s={serverBaseUrl:r,apiKey:n};return{runtime:"server",client:new Ai(s),projectId:o,serverBaseUrl:r}}ae();var _S=["observation_add","observation_record_event","observation_search","observation_context","observation_generation_status","memory_add","memory_search","memory_context"],fI=new Set(_S);function yS(e,t){return t==="server"?[...e]:(_.debug("SYSTEM","Filtering server-beta-only MCP tools from worker runtime advertisement",{runtime:t,hiddenToolCount:_S.length}),e.filter(r=>!fI.has(r.name)))}var AI={},mI="13.24.1";console.log=(...e)=>{_.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:e})};var ES=!1,wS=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,ft.dirname)((0,vS.fileURLToPath)(AI.url))}catch(e){return ES=!0,_.warn("SYSTEM","mcp-server: failed to resolve module directory from import.meta.url, falling back to process.cwd()",void 0,e instanceof Error?e:new Error(String(e))),process.cwd()}})(),Fl=Jy()??(0,ft.resolve)(wS,"worker-service.cjs");function hI(){ES&&((0,Mi.existsSync)(Fl)||_.error("SYSTEM","mcp-server: dirname resolution failed (both __dirname and import.meta.url are unavailable). Fell back to process.cwd() and the resolved WORKER_SCRIPT_PATH does not exist. This is the actual problem \u2014 the worker bundle is fine, but mcp-server cannot locate it. Worker auto-start will fail until the dirname-resolution path is fixed.",{workerScriptPath:Fl,mcpServerDir:wS}))}async function vt(e,t={}){_.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:e});try{let r;if(t.body)r=await Pi(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t.body)});else{let n=new URLSearchParams;for(let[o,s]of Object.entries(t.query??{}))s!=null&&n.append(o,String(s));r=await Pi(`${e}?${n}`)}if(!r.ok){let n=await r.text();throw new Error(`Worker API error (${r.status}): ${n}`)}return _.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:e}),t.text?{content:[{type:"text",text:await r.text()}]}:t.body?{content:[{type:"text",text:JSON.stringify(await r.json(),null,2)}]}:await r.json()}catch(r){return _.error("SYSTEM","\u2190 Worker API error",{endpoint:e},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function gI(){try{return(await Pi("/api/health")).ok}catch(e){return _.debug("SYSTEM","Worker health check failed",{},e instanceof Error?e:new Error(String(e))),!1}}function kS(){if(Ci()!=="server")return null;let t=gS();return t?{...t,available:!0}:{runtime:"server",available:!1,reason:"server runtime is selected but configuration is incomplete (missing url, api key, or project id)"}}function _I(e){return hS(e)?{content:[{type:"text",text:`Server error (${e.kind}${e.status?` ${e.status}`:""}): ${e.message}`}],isError:!0}:{content:[{type:"text",text:`Tool error: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}function Xr(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function go(e){let t=kS();if(!t)throw new tt("transport",`${e} requires CLAUDE_MEM_RUNTIME=server. Current runtime is "worker"; use the existing search/timeline/get_observations tools for worker-mode memory access.`);if(!t.available)throw new tt("missing_api_key",`${e}: ${t.reason}`);return t}function _o(e,t){return async r=>{try{return await t(r)}catch(n){let o=n instanceof Error?n:new Error(String(n));return _.warn("SYSTEM",`${e} failed`,void 0,o),_I(n)}}}var yI=_o("observation_add",async e=>{let t=go("observation_add");if(typeof e?.content!="string"||e.content.trim().length===0)throw new Error('observation_add: "content" is required');let n={projectId:e.projectId&&e.projectId.trim().length>0?e.projectId:t.projectId,content:e.content,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.kind!==void 0?{kind:e.kind}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}},o=await t.client.addObservation(n);return Xr(o)});function Ni(e){return typeof e=="string"?zi(e):null}var SI=_o("observation_record_event",async e=>{let t=go("observation_record_event");if(typeof e?.eventType!="string"||e.eventType.trim().length===0)throw new Error('observation_record_event: "eventType" is required');let n={projectId:e.projectId&&e.projectId.trim().length>0?e.projectId:t.projectId,sourceType:e.sourceType??"api",eventType:e.eventType,occurredAtEpoch:typeof e.occurredAtEpoch=="number"?e.occurredAtEpoch:Date.now(),...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:Ni(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{},...e.generate!==void 0?{generate:e.generate}:{}},o=await t.client.recordEvent(n);return Xr(o)}),bI=_o("observation_search",async e=>{let t=go("observation_search");if(typeof e?.query!="string"||e.query.trim().length===0)throw new Error('observation_search: "query" is required');let n={projectId:e.projectId&&e.projectId.trim().length>0?e.projectId:t.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Ni(e.platformSource)}:{}},o=await t.client.searchObservations(n);return Xr(o)}),vI=_o("observation_context",async e=>{let t=go("observation_context");if(typeof e?.query!="string"||e.query.trim().length===0)throw new Error('observation_context: "query" is required');let n={projectId:e.projectId&&e.projectId.trim().length>0?e.projectId:t.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Ni(e.platformSource)}:{}},o=await t.client.contextObservations(n);return Xr(o)});function EI(e){return Array.isArray(e.projects)?e.projects.map(t=>typeof t=="string"?t.trim():"").filter(Boolean):typeof e.projects=="string"?e.projects.split(",").map(t=>t.trim()).filter(Boolean):typeof e.project=="string"&&e.project.trim().length>0?[e.project.trim()]:[]}async function wI(e){let t=EI(e);return t.length===0?{content:[{type:"text",text:'session_start_context: "project" or "projects" is required'}],isError:!0}:vt("/api/context/inject",{query:{projects:t.join(","),...e.platformSource!==void 0?{platformSource:Ni(e.platformSource)}:{},...e.full!==void 0?{full:e.full}:{},...e.colors!==void 0?{colors:e.colors}:{}},text:!0})}var kI=_o("observation_generation_status",async e=>{let t=go("observation_generation_status"),r=(e?.jobId??e?.job_id??"").trim();if(!r)throw new Error('observation_generation_status: "jobId" is required');let n=await t.client.getJobStatus(r);return Xr(n)});async function xI(){if(await gI())return!0;_.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),hI();try{let e=Ol(),t=await Xy(e,Fl);return t==="dead"&&_.error("SYSTEM","Worker auto-start failed \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running. Check earlier log lines for the specific failure reason (Bun not found, missing worker bundle, port conflict, etc.)."),t!=="dead"}catch(e){return _.error("SYSTEM","Worker auto-start threw \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running.",void 0,e instanceof Error?e:new Error(String(e))),!1}}var xS=[{name:"important_workflow",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
|
|
215
215
|
1. search(query) \u2192 Get index with IDs (~50-100 tokens/result)
|
|
216
216
|
2. timeline(anchor=ID) \u2192 Get context around interesting results
|
|
217
217
|
3. get_observations([IDs]) \u2192 Fetch full details ONLY for filtered IDs
|
|
@@ -63,7 +63,7 @@ ${s.stack}`:` ${s.message}`;else if(this.getLevel()===0&&typeof s=="object")try{
|
|
|
63
63
|
${m.stack??""}
|
|
64
64
|
`)}else $o(p+`
|
|
65
65
|
`)}debug(e,r,n,i){this.log(0,e,r,n,i)}info(e,r,n,i){this.log(1,e,r,n,i)}warn(e,r,n,i){this.log(2,e,r,n,i)}setErrorSink(e){DE=e}error(e,r,n,i){this.log(3,e,r,n,i),this.routeErrorToSink(r,n,i)}routeErrorToSink(e,r,n){try{if(!DE||!(n instanceof Error))return;DE(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)}},w=new NE});function ZD(){let t=[];t.push(LE.default.json({limit:"5mb"})),t.push((n,i,s)=>{let o=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(f=>n.path.endsWith(f)),c=n.path==="/api/logs";if(n.path.startsWith("/health")||n.path==="/"||o||c)return s();let l=Date.now(),u=`${n.method}-${Date.now()}`,d=rie(n.method,n.path,n.body);w.debug("HTTP",`\u2192 ${n.method} ${n.path}`,{requestId:u},d);let p=i.send.bind(i);i.send=function(f){let m=Date.now()-l;return w.debug("HTTP",`\u2190 ${i.statusCode} ${n.path}`,{requestId:u,duration:`${m}ms`}),p(f)},s()});let e=ya(),r=XD.default.join(e,"plugin","ui");return t.push(LE.default.static(r)),t}function eM(){return(t,e,r)=>{let n=t.headers.origin;if(n){if(!n.startsWith("http://localhost:")&&!n.startsWith("http://127.0.0.1:")){r(new Error("CORS not allowed"));return}e.setHeader("Access-Control-Allow-Origin",n),e.setHeader("Vary","Origin")}if(t.method==="OPTIONS"){e.setHeader("Access-Control-Allow-Methods","GET,HEAD,POST,PUT,PATCH,DELETE"),e.setHeader("Access-Control-Allow-Headers","Content-Type,Authorization,X-Requested-With"),e.status(204).end();return}r()}}function bf(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")){w.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 rie(t,e,r){if(!r||Object.keys(r).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=r.tool_name||"?",i=r.tool_input;return`tool=${w.formatTool(n,i)}`}return e.includes("/summarize")?"requesting summary":""}var LE,XD,tM=R(()=>{"use strict";LE=tt(yf(),1),XD=tt(require("path"),1);Hn();me()});function rM(t,e,r,n){let i={error:t,message:e};return r&&(i.code=r),n&&(i.details=n),i}function iM(t,e){e.status(404).json(rM("NotFound",`Cannot ${t.method} ${t.path}`))}var Uo,nM,sM=R(()=>{"use strict";me();Uo=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};nM=(t,e,r,n)=>{let i=t instanceof Uo?t.statusCode:500;w.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:t.message,code:t instanceof Uo?t.code:void 0},t);let s=rM(t.name||"Error",t.message,t instanceof Uo?t.code:void 0,t instanceof Uo?t.details:void 0);r.status(i).json(s)}});var nie,iie,lje,aM=R(()=>{"use strict";nie=new Set([".cmd",".bat"]),iie=new Set([".exe",".com"]),lje=new Set([...iie,...nie])});function zo(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(aie.has(r)){e[r]=n;continue}FE.has(r)||qE.some(i=>r.startsWith(i))||(e[r]=n)}return e}var qE,FE,sie,aie,Xl=R(()=>{"use strict";qE=["CLAUDECODE_","CLAUDE_CODE_"],FE=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),sie=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"]),aie=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS",...sie])});function cie(t){$E+=1;let e=(0,JE.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:{...zo(process.env),LC_ALL:"C",LANG:"C"}});if(e.status===0){let r=e.stdout.trim();return r.length>0?r:null}return null}function lie(t,e=!1){if(!e){let n=oM.get(t);if(n&&Date.now()-n.capturedAtMs<oie)return n.token}let r=null;try{r=cie(t)}catch(n){w.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:n instanceof Error?n.message:String(n)}),r=null}return oM.set(t,{token:r,capturedAtMs:Date.now()}),r}function lM(t,e){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux"){$E+=1;try{let r=(0,cM.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 w.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}if(process.platform==="win32")return lie(t,e);$E+=1;try{let r=(0,JE.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...zo(process.env),LC_ALL:"C",LANG:"C"}});if(r.status!==0)return null;let n=r.stdout.trim();return n.length>0?n:null}catch(r){return w.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}function Ii(t){return lM(t,!1)}function ki(t,e){if(e===null)return!0;let r=lM(t,!0);return r===null?!0:r===e}var JE,cM,oie,oM,$E,UE=R(()=>{"use strict";JE=require("child_process"),cM=require("fs");me();Xl();oie=5e3,oM=new Map,$E=0});async function ls(t,e={}){let r=e.signalMode==="immediate",n=e.expectedStartToken!==void 0?e.expectedStartToken:Ii(t),i=()=>ki(t,n);if(!i()){w.warn("PROCESS","Skipping tree-kill: root PID was reused since it was captured",{pid:t});return}if(w.debug("PROCESS",`Killing process tree rooted at PID ${t}`,{immediate:r}),process.platform==="win32"){try{await zE("taskkill",["/PID",String(t),"/T","/F"],{timeout:5e3,windowsHide:!0})}catch(s){let a=s.code,o=String(s.stderr??""),c=s instanceof Error?s.message:String(s);if(a===uie||die.test(`${o} ${c}`)){w.debug("PROCESS","taskkill reported the process was already gone",{pid:t});return}throw new vf(t,`taskkill failed for PID ${t} (exit ${String(a)}): ${o.trim()||c}`,{cause:s})}return}try{let s=r?"SIGKILL":"SIGTERM",a=await Ef(t);for(let l of a){if(!ki(l.pid,l.startToken)){w.debug("PROCESS",`Skipping ${s}: descendant PID was reused since enumeration`,{pid:l.pid,rootPid:t});continue}try{process.kill(l.pid,s)}catch{}}if(i())try{process.kill(t,s)}catch(l){let u=l instanceof Error?l:new Error(String(l)),d=u.code;d!=="ESRCH"&&w.debug("PROCESS",`Failed to ${s} PID ${t}`,{code:d},u)}else w.warn("PROCESS","Skipping root signal: PID was reused during descendant enumeration",{pid:t,signal:s});r||await new Promise(l=>setTimeout(l,500));let o=i()?await Ef(t):[],c=new Map;for(let l of a)c.set(l.pid,l.startToken);for(let l of o)c.set(l.pid,l.startToken);for(let[l,u]of c){if(!ki(l,u)){w.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 vf(t,`tree-kill failed for PID ${t}: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}async function pie(){return process.platform==="win32"?hie():process.platform==="linux"?fie():mie()}function fie(){let t=[],e;try{e=(0,Sf.readdirSync)("/proc")}catch(r){return w.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,Sf.readFileSync)(`/proc/${r}/stat`,"utf-8")}catch{continue}let i=n.lastIndexOf(") ");if(i<0)continue;let s=n.slice(i+2).split(" "),a=Number.parseInt(s[1]??"",10),o=s[19];Number.isFinite(a)&&t.push({pid:Number.parseInt(r,10),ppid:a,startToken:o&&/^\d+$/.test(o)?o:null})}return t}async function mie(){let t;try{t=(await zE("ps",["-eo","pid=,ppid=,lstart="],{timeout:1e4,maxBuffer:33554432,env:{...process.env,LC_ALL:"C",LANG:"C"}})).stdout}catch(r){return w.warn("PROCESS","Cannot enumerate the process table \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),[]}let e=[];for(let r of t.split(`
|
|
66
|
-
`)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);if(!n)continue;let i=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:i.length>0?i:null})}return e}async function hie(){let t;try{t=(await zE("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 w.warn("PROCESS","Cannot enumerate the Windows process table \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),[]}let e=[];for(let r of t.split(/\r?\n/).slice(1)){let n=r.match(/^"(\d+)","(\d+)","(.*)"$/);if(!n)continue;let i=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:i.length>0?i:null})}return e}async function Ef(t){let e=await pie(),r=new Map;for(let a of e){let o=r.get(a.ppid);o?o.push(a):r.set(a.ppid,[a])}let n=new Set([t]),i=[],s=a=>{for(let o of r.get(a)??[])n.has(o.pid)||(n.add(o.pid),s(o.pid),i.push({pid:o.pid,startToken:o.startToken}))};return s(t),i}var uM,Sf,dM,zE,uie,die,vf,xf=R(()=>{"use strict";uM=require("child_process"),Sf=require("fs"),dM=require("util");me();UE();zE=(0,dM.promisify)(uM.execFile),uie=128,die=/not found|no running instance|no tasks/i,vf=class extends Error{pid;constructor(e,r,n){super(r,n),this.name="ProcessTreeKillError",this.pid=e}}});function Bt(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:(w.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return w.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function wf(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!Bt(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function us(t){if(!t||!Bt(t.pid))return!1;if(!t.startToken)return!0;let e=Ii(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||w.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}function _f(){return GE||(GE=new VE),GE}function BE(){let t=vie.shift();t&&t()}var Ti,HE,yie,gie,bie,VE,GE,vie,Go=R(()=>{"use strict";aM();Ti=require("fs"),HE=tt(require("path"),1);me();Xl();Hn();UE();xf();yie=5e3,gie=1e3,bie=Ge.supervisorRegistry();VE=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=bie){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,Ti.mkdirSync)(HE.default.dirname(this.registryPath),{recursive:!0}),!(0,Ti.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Ti.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[i,s]of Object.entries(n))this.entries.set(i,s)}catch(r){r instanceof Error?w.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):w.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&w.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,r,n){this.initialize(),this.entries.set(e,r),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let r=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),r?.type==="sdk"&&BE()}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)Bt(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)BE();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;w.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:n,pids:r.map(o=>o.pid)});let i=r.filter(o=>Bt(o.pid)),s=new Map(i.map(o=>[o.pid,Ii(o.pid)]));for(let o of i)try{process.platform==="win32"?await ls(o.pid,{expectedStartToken:s.get(o.pid)??null}):typeof o.pgid=="number"?process.kill(-o.pgid,"SIGTERM"):process.kill(o.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&w.debug("SYSTEM",`Failed to SIGTERM session process PID ${o.pid}`,{pid:o.pid,pgid:o.pgid},c):w.warn("SYSTEM",`Failed to SIGTERM session process PID ${o.pid} (non-Error)`,{pid:o.pid,pgid:o.pgid,error:String(c)})}await wf(i,yie);let a=i.filter(o=>Bt(o.pid));for(let o of a){w.warn("SYSTEM",`Session process PID ${o.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:o.pid,pgid:o.pgid,sessionId:n});let c=s.get(o.pid)??null;if(!ki(o.pid,c)){w.warn("SYSTEM","Skipping SIGKILL: session process PID was reused during the grace window",{pid:o.pid,sessionId:n});continue}try{process.platform==="win32"?await ls(o.pid,{expectedStartToken:c}):typeof o.pgid=="number"?process.kill(-o.pgid,"SIGKILL"):process.kill(o.pid,"SIGKILL")}catch(l){l instanceof Error?l.code!=="ESRCH"&&w.debug("SYSTEM",`Failed to SIGKILL session process PID ${o.pid}`,{pid:o.pid,pgid:o.pgid},l):w.warn("SYSTEM",`Failed to SIGKILL session process PID ${o.pid} (non-Error)`,{pid:o.pid,pgid:o.pgid,error:String(l)})}}if(a.length>0){let o=Date.now()+gie;for(;Date.now()<o&&a.filter(l=>Bt(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let o of r)this.entries.delete(o.id),this.runtimeProcesses.delete(o.id);this.persist();for(let o of r)o.type==="sdk"&&BE();return w.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:n,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,Ti.mkdirSync)(HE.default.dirname(this.registryPath),{recursive:!0}),(0,Ti.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},GE=null;vie=[]});async function fM(t){let e=t.currentPid??process.pid,r=t.pidFilePath??Eie,n=t.registry.getAll(),i=[...n].filter(c=>c.pid!==e).sort((c,l)=>Date.parse(l.startedAt)-Date.parse(c.startedAt)),s=new Map,a=new Map;for(let c of i){if(!Bt(c.pid)){t.registry.unregister(c.id);continue}a.set(c.id,Ii(c.pid)),s.set(c.id,await Ef(c.pid));try{await pM(c,"SIGTERM")}catch(l){l instanceof Error?w.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:c.pid,pgid:c.pgid,type:c.type},l):w.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(l)})}}await wf(i,5e3);let o=i.filter(c=>Bt(c.pid)||(s.get(c.id)??[]).some(l=>Bt(l.pid)));for(let c of o){let l=ki(c.pid,a.get(c.id)??null);l||w.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:c.pid,type:c.type});try{l&&await pM(c,"SIGKILL")}catch(u){u instanceof Error?w.debug("SYSTEM","Failed to force kill child process",{pid:c.pid,pgid:c.pgid,type:c.type},u):w.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(u)})}finally{xie(s.get(c.id)??[],c.pid)}}await wf(o,1e3);for(let c of i)t.registry.unregister(c.id);for(let c of n.filter(l=>l.pid===e))t.registry.unregister(c.id);Sie(r,e),t.registry.pruneDeadEntries()}function Sie(t,e,r=!1){if(!(0,Bo.existsSync)(t))return;let n=null;try{let a=JSON.parse((0,Bo.readFileSync)(t,"utf-8"));n=typeof a.pid=="number"?a.pid:null}catch(a){w.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:a instanceof Error?a.message:String(a)});return}let i=e!==null&&n===e,s=n===null||!Bt(n);if(!i&&!(r&&s)){w.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,Bo.rmSync)(t,{force:!0})}catch(a){a instanceof Error?w.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},a):w.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(a)})}}function xie(t,e){for(let{pid:r,startToken:n}of t)if(!(r===e||!Bt(r))){if(!ki(r,n)){w.debug("SYSTEM","Skipping reap: PID was recycled during the grace window",{pid:r,rootPid:e});continue}try{process.kill(r,"SIGKILL"),w.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"&&w.warn("SYSTEM","Failed to reap orphaned descendant during shutdown cascade",{pid:r,rootPid:e,errno:s})}}}async function pM(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 ls(r,{signalMode:"immediate"});return}try{process.kill(r,e)}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}return}await ls(r)}var Bo,Eie,mM=R(()=>{"use strict";Bo=require("fs");me();Go();Hn();xf();Eie=Ge.workerPid()});function wie(){let e=_f().pruneDeadEntries();e>0&&w.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function yM(){Ho===null&&(Ho=setInterval(wie,hM),Ho.unref(),w.debug("SYSTEM","Health checker started",{intervalMs:hM}))}function gM(){Ho!==null&&(clearInterval(Ho),Ho=null,w.debug("SYSTEM","Health checker stopped"))}var hM,Ho,bM=R(()=>{"use strict";me();Go();hM=3e4,Ho=null});function vM(){return Iie}function kie(t={}){let e=t.pidFilePath??_ie;if(!(0,ga.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,ga.readFileSync)(e,"utf-8"))}catch(i){return i instanceof Error?w.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},i):w.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(i)}),(0,ga.rmSync)(e,{force:!0}),"invalid"}return us(r)&&r?((t.logAlive??!0)&&w.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(w.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,ga.rmSync)(e,{force:!0}),"stale")}var ga,_ie,YE,Iie,EM=R(()=>{"use strict";ga=require("fs");me();Go();mM();bM();Hn();_ie=Ge.workerPid(),YE=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(),kie({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,yM()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){w.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,w.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){i instanceof Error?w.error("SYSTEM","Error during shutdown",{},i):w.error("SYSTEM","Error during shutdown (non-Error)",{error:String(i)});try{await this.stop()}catch(s){s instanceof Error?w.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):w.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",()=>{w.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}gM(),this.stopPromise=fM({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,n){this.registry.register(e,r,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},Iie=new YE(_f())});function WE(t,e,r){t.on("finish",async()=>{try{await r()}finally{process.exit(0)}}),t.json(e)}var SM=R(()=>{"use strict"});function QE(t,e=Date.now){return Math.max(0,Math.floor((e()-t)/1e3))}var xM=R(()=>{"use strict"});function XE(){let t=Array.from(Tie.values()).map(e=>({...e})).sort((e,r)=>e.dependency.localeCompare(r.dependency));return{degraded:t.length>0,statuses:t}}var Tie,wM=R(()=>{"use strict";Tie=new Map});function Aie(t,e){return e.status!=="rejected"?!1:!t||t.status!=="rejected"?!0:t.resetsAt!==e.resetsAt}var ZE,_M,Uje,IM=R(()=>{"use strict";ZE=class{entries=new Map;set(e){if(!e||typeof e!="object")return!1;let r=e.rateLimitType??"default",n=this.entries.get(r);return this.entries.set(r,{...e,observedAt:Date.now()}),Aie(n,e)}get(e){return e?this.entries.get(e):this.entries.get("default")}getMostRecentByWindow(){return{five_hour:this.entries.get("five_hour"),seven_day:this.entries.get("seven_day"),seven_day_opus:this.entries.get("seven_day_opus"),seven_day_sonnet:this.entries.get("seven_day_sonnet"),overage:this.entries.get("overage")}}get size(){return this.entries.size}},_M=new ZE;Uje=900*1e3});function Cie(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 AM,RM,tS,Zl,OM,Rie,eS,kM,Oie,TM,If,CM=R(()=>{"use strict";AM=tt(yf(),1),RM=tt(require("http"),1),tS=tt(require("fs"),1),Zl=tt(require("path"),1);GD();me();tM();sM();EM();Go();Xl();SM();xM();wM();IM();OM=Zl.default.resolve(__dirname,"../skills/mem-search"),Rie=Zl.default.join(OM,"operations"),eS=Zl.default.join(OM,"SKILL.md"),kM=(()=>{try{let t=tS.readFileSync(eS,"utf-8");return w.info("SYSTEM","Cached SKILL.md at boot",{path:eS,bytes:Buffer.byteLength(t,"utf-8")}),t}catch(t){return w.debug("SYSTEM","SKILL.md not present at boot, /api/instructions will 404 for topic queries",{path:eS,message:t instanceof Error?t.message:String(t)}),null}})(),Oie=(()=>{let t=new Map;for(let e of OE){let r=Zl.default.join(Rie,`${e}.md`);try{t.set(e,tS.readFileSync(r,"utf-8"))}catch(n){w.debug("SYSTEM","Operation instruction file not present at boot",{path:r,message:n instanceof Error?n.message:String(n)})}}return t.size>0&&w.info("SYSTEM","Cached operation instruction files at boot",{count:t.size,operations:Array.from(t.keys())}),t})(),TM="13.24.0";If=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,AM.default)(),this.app.disable("x-powered-by"),this.setupSecurityHeaders(),this.setupCors(),this.setupPreBodyParserRoutes(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,r){return new Promise((n,i)=>{let s=RM.default.createServer(this.app),a=c=>{s.off("listening",o),i(c)},o=()=>{s.off("error",a),this.server=s,w.info("SYSTEM","HTTP server started",{host:r,port:e,pid:process.pid}),n()};s.once("error",a),s.once("listening",o),s.listen(e,r)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{this.server.close(n=>n?r(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,w.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(iM),this.app.use(nM)}setupMiddleware(){ZD().forEach(r=>this.app.use(r))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,r,n)=>{Cie(r),n()})}setupCors(){this.app.use(eM())}setupPreBodyParserRoutes(){this.options.preBodyParserRoutes?.forEach(e=>e.setupRoutes(this.app))}setupCoreRoutes(){this.app.get("/api/health",async(e,r)=>{let n=this.options.getQueueHealth?await this.options.getQueueHealth():null,i=n?.engine==="bullmq"&&n.redis.status==="error",s=this.options.getDependencyHealth?this.options.getDependencyHealth():XE();r.status(i?503:200).json({status:i?"degraded":"ok",...this.options.runtime?{runtime:this.options.runtime}:{},version:TM,workerPath:this.options.workerPath,uptime:QE(this.startTime),managed:process.env.CLAUDE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.options.getInitializationComplete(),mcpReady:this.options.getMcpReady(),ai:this.options.getAiStatus(),dependencies:s,rateLimits:_M.getMostRecentByWindow(),...n?{queue:n}:{}})}),this.app.get("/api/readiness",(e,r)=>{this.options.getInitializationComplete()?r.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):r.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(e,r)=>{r.status(200).json({version:TM})}),this.app.get("/api/instructions",(e,r)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!zD.includes(n))return r.status(400).json({error:"Invalid topic"});if(i&&!OE.includes(i))return r.status(400).json({error:"Invalid operation"});if(i){let a=Oie.get(i);return a===void 0?(w.debug("HTTP","Instruction file not cached at boot",{operation:i}),r.status(404).json({error:"Instruction not found"})):r.json({content:[{type:"text",text:a}]})}if(kM===null)return w.debug("HTTP","SKILL.md not cached at boot",{topic:n}),r.status(404).json({error:"Instruction not found"});let s=this.extractInstructionSection(kM,n);r.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",bf,async(e,r)=>{process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(r.json({status:"restarting"}),w.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):WE(r,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",bf,async(e,r)=>{let n=e.query.reason==="restart"?"restart":"stop";process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(r.json({status:"shutting_down"}),w.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown",reason:n})):WE(r,{status:"shutting_down"},()=>this.options.onShutdown(n))}),this.app.get("/api/admin/doctor",bf,(e,r)=>{let a=vM().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:Bt(f.pid)?"alive":"dead",startedAt:f.startedAt})),o=a.filter(f=>f.status==="dead").map(f=>f.pid),c=!Object.keys(process.env).some(f=>FE.has(f)||qE.some(m=>f.startsWith(m))),l=QE(this.startTime),u=Math.floor(l/3600),d=Math.floor(l%3600/60),p=u>0?`${u}h ${d}m`:`${d}m`;r.json({supervisor:{running:!0,pid:process.pid,uptime:p},processes:a,health:{deadProcessPids:o,envClean:c,dependencies:this.options.getDependencyHealth?this.options.getDependencyHealth():XE()}})})}extractInstructionSection(e,r){let n={workflow:this.extractBetween(e,"## The Workflow","## Search Parameters"),search_params:this.extractBetween(e,"## Search Parameters","## Examples"),examples:this.extractBetween(e,"## Examples","## Why This Workflow"),all:e};return n[r]||n.all}extractBetween(e,r,n){let i=e.indexOf(r),s=e.indexOf(n);return i===-1?e:s===-1?e.substring(i):e.substring(i,s).trim()}}});var Rr,jie,Pie,rS,jM=R(()=>{"use strict";Rr=require("zod"),jie=Rr.z.enum(["hook","worker","provider","server","api"]),Pie=Rr.z.object({id:Rr.z.string().min(1),projectId:Rr.z.string().min(1),serverSessionId:Rr.z.string().min(1).nullable().default(null),sourceType:jie,eventType:Rr.z.string().min(1),platformSource:Rr.z.string().min(1).nullable().default(null),payload:Rr.z.unknown().default({}),contentSessionId:Rr.z.string().min(1).nullable().default(null),memorySessionId:Rr.z.string().min(1).nullable().default(null),occurredAtEpoch:Rr.z.number().int().nonnegative(),createdAtEpoch:Rr.z.number().int().nonnegative()}),rS=Pie.omit({id:!0,createdAtEpoch:!0}).partial({serverSessionId:!0,platformSource:!0,payload:!0,contentSessionId:!0,memorySessionId:!0})});function Ze(){return(0,kf.randomUUID)()}function ht(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function PM(t){return Array.isArray(t)?t:[]}function De(t){return typeof t=="number"?t:new Date(t).getTime()}function Qr(t){return t==null?null:t instanceof Date?t:new Date(t)}async function se(t,e,r=[]){return(await t.query(e,r)).rows[0]??null}async function Sn(t,e,r){if(!await se(t,"SELECT id FROM projects WHERE id = $1 AND team_id = $2",[e,r]))throw new Error("project_id must belong to team_id")}async function Ai(t,e,r,n){if(!await se(t,"SELECT id FROM server_sessions WHERE id = $1 AND project_id = $2 AND team_id = $3",[e,r,n]))throw new Error("server_session_id must belong to project_id and team_id")}function eu(t){return JSON.stringify(nS(t))}function xn(t){return(0,kf.createHash)("sha256").update(eu(t)).digest("hex")}function nS(t){if(Array.isArray(t))return t.map(nS);if(t&&typeof t=="object"){let e=t;return Object.keys(e).sort().reduce((r,n)=>(r[n]=nS(e[n]),r),{})}return t}var kf,wn=R(()=>{"use strict";kf=require("crypto")});function Kie(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function ds(t){if(!t)return Vo;let e=Kie(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:Vo}function cr(t){return typeof t!="string"?null:ds(t)}var Vo,ba=R(()=>{"use strict";Vo="claude"});function KM(t){let e=cr(t.platformSource),r=e?[e]:[];return t.sourceEventId?`agent_event:v1:${xn([t.teamId,t.projectId,t.sourceAdapter,...r,t.sourceEventId])}`:`agent_event:v1:${xn([t.teamId,t.projectId,t.sourceAdapter,...r,t.contentSessionId??t.serverSessionId??null,t.eventType,new Date(t.occurredAt).toISOString(),eu(t.payload??{})])}`}function iS(t){return{id:t.id,projectId:t.project_id,teamId:t.team_id,serverSessionId:t.server_session_id,sourceAdapter:t.source_adapter,sourceEventId:t.source_event_id,idempotencyKey:t.idempotency_key,eventType:t.event_type,platformSource:t.platform_source,payload:t.payload,metadata:ht(t.metadata),occurredAtEpoch:De(t.occurred_at),receivedAtEpoch:De(t.received_at),createdAtEpoch:De(t.created_at)}}var Xr,Yo=R(()=>{"use strict";wn();ba();Xr=class{constructor(e){this.client=e}client;async create(e){await Sn(this.client,e.projectId,e.teamId),e.serverSessionId&&await Ai(this.client,e.serverSessionId,e.projectId,e.teamId);let r=KM(e),n=cr(e.platformSource),i=await se(this.client,`
|
|
66
|
+
`)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);if(!n)continue;let i=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:i.length>0?i:null})}return e}async function hie(){let t;try{t=(await zE("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 w.warn("PROCESS","Cannot enumerate the Windows process table \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),[]}let e=[];for(let r of t.split(/\r?\n/).slice(1)){let n=r.match(/^"(\d+)","(\d+)","(.*)"$/);if(!n)continue;let i=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:i.length>0?i:null})}return e}async function Ef(t){let e=await pie(),r=new Map;for(let a of e){let o=r.get(a.ppid);o?o.push(a):r.set(a.ppid,[a])}let n=new Set([t]),i=[],s=a=>{for(let o of r.get(a)??[])n.has(o.pid)||(n.add(o.pid),s(o.pid),i.push({pid:o.pid,startToken:o.startToken}))};return s(t),i}var uM,Sf,dM,zE,uie,die,vf,xf=R(()=>{"use strict";uM=require("child_process"),Sf=require("fs"),dM=require("util");me();UE();zE=(0,dM.promisify)(uM.execFile),uie=128,die=/not found|no running instance|no tasks/i,vf=class extends Error{pid;constructor(e,r,n){super(r,n),this.name="ProcessTreeKillError",this.pid=e}}});function Bt(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:(w.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return w.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function wf(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!Bt(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function us(t){if(!t||!Bt(t.pid))return!1;if(!t.startToken)return!0;let e=Ii(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||w.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}function _f(){return GE||(GE=new VE),GE}function BE(){let t=vie.shift();t&&t()}var Ti,HE,yie,gie,bie,VE,GE,vie,Go=R(()=>{"use strict";aM();Ti=require("fs"),HE=tt(require("path"),1);me();Xl();Hn();UE();xf();yie=5e3,gie=1e3,bie=Ge.supervisorRegistry();VE=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=bie){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,Ti.mkdirSync)(HE.default.dirname(this.registryPath),{recursive:!0}),!(0,Ti.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Ti.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[i,s]of Object.entries(n))this.entries.set(i,s)}catch(r){r instanceof Error?w.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):w.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&w.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,r,n){this.initialize(),this.entries.set(e,r),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let r=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),r?.type==="sdk"&&BE()}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)Bt(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)BE();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;w.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:n,pids:r.map(o=>o.pid)});let i=r.filter(o=>Bt(o.pid)),s=new Map(i.map(o=>[o.pid,Ii(o.pid)]));for(let o of i)try{process.platform==="win32"?await ls(o.pid,{expectedStartToken:s.get(o.pid)??null}):typeof o.pgid=="number"?process.kill(-o.pgid,"SIGTERM"):process.kill(o.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&w.debug("SYSTEM",`Failed to SIGTERM session process PID ${o.pid}`,{pid:o.pid,pgid:o.pgid},c):w.warn("SYSTEM",`Failed to SIGTERM session process PID ${o.pid} (non-Error)`,{pid:o.pid,pgid:o.pgid,error:String(c)})}await wf(i,yie);let a=i.filter(o=>Bt(o.pid));for(let o of a){w.warn("SYSTEM",`Session process PID ${o.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:o.pid,pgid:o.pgid,sessionId:n});let c=s.get(o.pid)??null;if(!ki(o.pid,c)){w.warn("SYSTEM","Skipping SIGKILL: session process PID was reused during the grace window",{pid:o.pid,sessionId:n});continue}try{process.platform==="win32"?await ls(o.pid,{expectedStartToken:c}):typeof o.pgid=="number"?process.kill(-o.pgid,"SIGKILL"):process.kill(o.pid,"SIGKILL")}catch(l){l instanceof Error?l.code!=="ESRCH"&&w.debug("SYSTEM",`Failed to SIGKILL session process PID ${o.pid}`,{pid:o.pid,pgid:o.pgid},l):w.warn("SYSTEM",`Failed to SIGKILL session process PID ${o.pid} (non-Error)`,{pid:o.pid,pgid:o.pgid,error:String(l)})}}if(a.length>0){let o=Date.now()+gie;for(;Date.now()<o&&a.filter(l=>Bt(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let o of r)this.entries.delete(o.id),this.runtimeProcesses.delete(o.id);this.persist();for(let o of r)o.type==="sdk"&&BE();return w.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:n,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,Ti.mkdirSync)(HE.default.dirname(this.registryPath),{recursive:!0}),(0,Ti.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},GE=null;vie=[]});async function fM(t){let e=t.currentPid??process.pid,r=t.pidFilePath??Eie,n=t.registry.getAll(),i=[...n].filter(c=>c.pid!==e).sort((c,l)=>Date.parse(l.startedAt)-Date.parse(c.startedAt)),s=new Map,a=new Map;for(let c of i){if(!Bt(c.pid)){t.registry.unregister(c.id);continue}a.set(c.id,Ii(c.pid)),s.set(c.id,await Ef(c.pid));try{await pM(c,"SIGTERM")}catch(l){l instanceof Error?w.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:c.pid,pgid:c.pgid,type:c.type},l):w.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(l)})}}await wf(i,5e3);let o=i.filter(c=>Bt(c.pid)||(s.get(c.id)??[]).some(l=>Bt(l.pid)));for(let c of o){let l=ki(c.pid,a.get(c.id)??null);l||w.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:c.pid,type:c.type});try{l&&await pM(c,"SIGKILL")}catch(u){u instanceof Error?w.debug("SYSTEM","Failed to force kill child process",{pid:c.pid,pgid:c.pgid,type:c.type},u):w.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(u)})}finally{xie(s.get(c.id)??[],c.pid)}}await wf(o,1e3);for(let c of i)t.registry.unregister(c.id);for(let c of n.filter(l=>l.pid===e))t.registry.unregister(c.id);Sie(r,e),t.registry.pruneDeadEntries()}function Sie(t,e,r=!1){if(!(0,Bo.existsSync)(t))return;let n=null;try{let a=JSON.parse((0,Bo.readFileSync)(t,"utf-8"));n=typeof a.pid=="number"?a.pid:null}catch(a){w.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:a instanceof Error?a.message:String(a)});return}let i=e!==null&&n===e,s=n===null||!Bt(n);if(!i&&!(r&&s)){w.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,Bo.rmSync)(t,{force:!0})}catch(a){a instanceof Error?w.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},a):w.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(a)})}}function xie(t,e){for(let{pid:r,startToken:n}of t)if(!(r===e||!Bt(r))){if(!ki(r,n)){w.debug("SYSTEM","Skipping reap: PID was recycled during the grace window",{pid:r,rootPid:e});continue}try{process.kill(r,"SIGKILL"),w.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"&&w.warn("SYSTEM","Failed to reap orphaned descendant during shutdown cascade",{pid:r,rootPid:e,errno:s})}}}async function pM(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 ls(r,{signalMode:"immediate"});return}try{process.kill(r,e)}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}return}await ls(r)}var Bo,Eie,mM=R(()=>{"use strict";Bo=require("fs");me();Go();Hn();xf();Eie=Ge.workerPid()});function wie(){let e=_f().pruneDeadEntries();e>0&&w.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function yM(){Ho===null&&(Ho=setInterval(wie,hM),Ho.unref(),w.debug("SYSTEM","Health checker started",{intervalMs:hM}))}function gM(){Ho!==null&&(clearInterval(Ho),Ho=null,w.debug("SYSTEM","Health checker stopped"))}var hM,Ho,bM=R(()=>{"use strict";me();Go();hM=3e4,Ho=null});function vM(){return Iie}function kie(t={}){let e=t.pidFilePath??_ie;if(!(0,ga.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,ga.readFileSync)(e,"utf-8"))}catch(i){return i instanceof Error?w.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},i):w.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(i)}),(0,ga.rmSync)(e,{force:!0}),"invalid"}return us(r)&&r?((t.logAlive??!0)&&w.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(w.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,ga.rmSync)(e,{force:!0}),"stale")}var ga,_ie,YE,Iie,EM=R(()=>{"use strict";ga=require("fs");me();Go();mM();bM();Hn();_ie=Ge.workerPid(),YE=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(),kie({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,yM()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){w.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,w.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){i instanceof Error?w.error("SYSTEM","Error during shutdown",{},i):w.error("SYSTEM","Error during shutdown (non-Error)",{error:String(i)});try{await this.stop()}catch(s){s instanceof Error?w.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):w.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",()=>{w.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}gM(),this.stopPromise=fM({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,n){this.registry.register(e,r,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},Iie=new YE(_f())});function WE(t,e,r){t.on("finish",async()=>{try{await r()}finally{process.exit(0)}}),t.json(e)}var SM=R(()=>{"use strict"});function QE(t,e=Date.now){return Math.max(0,Math.floor((e()-t)/1e3))}var xM=R(()=>{"use strict"});function XE(){let t=Array.from(Tie.values()).map(e=>({...e})).sort((e,r)=>e.dependency.localeCompare(r.dependency));return{degraded:t.length>0,statuses:t}}var Tie,wM=R(()=>{"use strict";Tie=new Map});function Aie(t,e){return e.status!=="rejected"?!1:!t||t.status!=="rejected"?!0:t.resetsAt!==e.resetsAt}var ZE,_M,Uje,IM=R(()=>{"use strict";ZE=class{entries=new Map;set(e){if(!e||typeof e!="object")return!1;let r=e.rateLimitType??"default",n=this.entries.get(r);return this.entries.set(r,{...e,observedAt:Date.now()}),Aie(n,e)}get(e){return e?this.entries.get(e):this.entries.get("default")}getMostRecentByWindow(){return{five_hour:this.entries.get("five_hour"),seven_day:this.entries.get("seven_day"),seven_day_opus:this.entries.get("seven_day_opus"),seven_day_sonnet:this.entries.get("seven_day_sonnet"),overage:this.entries.get("overage")}}get size(){return this.entries.size}},_M=new ZE;Uje=900*1e3});function Cie(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 AM,RM,tS,Zl,OM,Rie,eS,kM,Oie,TM,If,CM=R(()=>{"use strict";AM=tt(yf(),1),RM=tt(require("http"),1),tS=tt(require("fs"),1),Zl=tt(require("path"),1);GD();me();tM();sM();EM();Go();Xl();SM();xM();wM();IM();OM=Zl.default.resolve(__dirname,"../skills/mem-search"),Rie=Zl.default.join(OM,"operations"),eS=Zl.default.join(OM,"SKILL.md"),kM=(()=>{try{let t=tS.readFileSync(eS,"utf-8");return w.info("SYSTEM","Cached SKILL.md at boot",{path:eS,bytes:Buffer.byteLength(t,"utf-8")}),t}catch(t){return w.debug("SYSTEM","SKILL.md not present at boot, /api/instructions will 404 for topic queries",{path:eS,message:t instanceof Error?t.message:String(t)}),null}})(),Oie=(()=>{let t=new Map;for(let e of OE){let r=Zl.default.join(Rie,`${e}.md`);try{t.set(e,tS.readFileSync(r,"utf-8"))}catch(n){w.debug("SYSTEM","Operation instruction file not present at boot",{path:r,message:n instanceof Error?n.message:String(n)})}}return t.size>0&&w.info("SYSTEM","Cached operation instruction files at boot",{count:t.size,operations:Array.from(t.keys())}),t})(),TM="13.24.1";If=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,AM.default)(),this.app.disable("x-powered-by"),this.setupSecurityHeaders(),this.setupCors(),this.setupPreBodyParserRoutes(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,r){return new Promise((n,i)=>{let s=RM.default.createServer(this.app),a=c=>{s.off("listening",o),i(c)},o=()=>{s.off("error",a),this.server=s,w.info("SYSTEM","HTTP server started",{host:r,port:e,pid:process.pid}),n()};s.once("error",a),s.once("listening",o),s.listen(e,r)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{this.server.close(n=>n?r(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,w.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(iM),this.app.use(nM)}setupMiddleware(){ZD().forEach(r=>this.app.use(r))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,r,n)=>{Cie(r),n()})}setupCors(){this.app.use(eM())}setupPreBodyParserRoutes(){this.options.preBodyParserRoutes?.forEach(e=>e.setupRoutes(this.app))}setupCoreRoutes(){this.app.get("/api/health",async(e,r)=>{let n=this.options.getQueueHealth?await this.options.getQueueHealth():null,i=n?.engine==="bullmq"&&n.redis.status==="error",s=this.options.getDependencyHealth?this.options.getDependencyHealth():XE();r.status(i?503:200).json({status:i?"degraded":"ok",...this.options.runtime?{runtime:this.options.runtime}:{},version:TM,workerPath:this.options.workerPath,uptime:QE(this.startTime),managed:process.env.CLAUDE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.options.getInitializationComplete(),mcpReady:this.options.getMcpReady(),ai:this.options.getAiStatus(),dependencies:s,rateLimits:_M.getMostRecentByWindow(),...n?{queue:n}:{}})}),this.app.get("/api/readiness",(e,r)=>{this.options.getInitializationComplete()?r.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):r.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(e,r)=>{r.status(200).json({version:TM})}),this.app.get("/api/instructions",(e,r)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!zD.includes(n))return r.status(400).json({error:"Invalid topic"});if(i&&!OE.includes(i))return r.status(400).json({error:"Invalid operation"});if(i){let a=Oie.get(i);return a===void 0?(w.debug("HTTP","Instruction file not cached at boot",{operation:i}),r.status(404).json({error:"Instruction not found"})):r.json({content:[{type:"text",text:a}]})}if(kM===null)return w.debug("HTTP","SKILL.md not cached at boot",{topic:n}),r.status(404).json({error:"Instruction not found"});let s=this.extractInstructionSection(kM,n);r.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",bf,async(e,r)=>{process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(r.json({status:"restarting"}),w.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):WE(r,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",bf,async(e,r)=>{let n=e.query.reason==="restart"?"restart":"stop";process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(r.json({status:"shutting_down"}),w.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown",reason:n})):WE(r,{status:"shutting_down"},()=>this.options.onShutdown(n))}),this.app.get("/api/admin/doctor",bf,(e,r)=>{let a=vM().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:Bt(f.pid)?"alive":"dead",startedAt:f.startedAt})),o=a.filter(f=>f.status==="dead").map(f=>f.pid),c=!Object.keys(process.env).some(f=>FE.has(f)||qE.some(m=>f.startsWith(m))),l=QE(this.startTime),u=Math.floor(l/3600),d=Math.floor(l%3600/60),p=u>0?`${u}h ${d}m`:`${d}m`;r.json({supervisor:{running:!0,pid:process.pid,uptime:p},processes:a,health:{deadProcessPids:o,envClean:c,dependencies:this.options.getDependencyHealth?this.options.getDependencyHealth():XE()}})})}extractInstructionSection(e,r){let n={workflow:this.extractBetween(e,"## The Workflow","## Search Parameters"),search_params:this.extractBetween(e,"## Search Parameters","## Examples"),examples:this.extractBetween(e,"## Examples","## Why This Workflow"),all:e};return n[r]||n.all}extractBetween(e,r,n){let i=e.indexOf(r),s=e.indexOf(n);return i===-1?e:s===-1?e.substring(i):e.substring(i,s).trim()}}});var Rr,jie,Pie,rS,jM=R(()=>{"use strict";Rr=require("zod"),jie=Rr.z.enum(["hook","worker","provider","server","api"]),Pie=Rr.z.object({id:Rr.z.string().min(1),projectId:Rr.z.string().min(1),serverSessionId:Rr.z.string().min(1).nullable().default(null),sourceType:jie,eventType:Rr.z.string().min(1),platformSource:Rr.z.string().min(1).nullable().default(null),payload:Rr.z.unknown().default({}),contentSessionId:Rr.z.string().min(1).nullable().default(null),memorySessionId:Rr.z.string().min(1).nullable().default(null),occurredAtEpoch:Rr.z.number().int().nonnegative(),createdAtEpoch:Rr.z.number().int().nonnegative()}),rS=Pie.omit({id:!0,createdAtEpoch:!0}).partial({serverSessionId:!0,platformSource:!0,payload:!0,contentSessionId:!0,memorySessionId:!0})});function Ze(){return(0,kf.randomUUID)()}function ht(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function PM(t){return Array.isArray(t)?t:[]}function De(t){return typeof t=="number"?t:new Date(t).getTime()}function Qr(t){return t==null?null:t instanceof Date?t:new Date(t)}async function se(t,e,r=[]){return(await t.query(e,r)).rows[0]??null}async function Sn(t,e,r){if(!await se(t,"SELECT id FROM projects WHERE id = $1 AND team_id = $2",[e,r]))throw new Error("project_id must belong to team_id")}async function Ai(t,e,r,n){if(!await se(t,"SELECT id FROM server_sessions WHERE id = $1 AND project_id = $2 AND team_id = $3",[e,r,n]))throw new Error("server_session_id must belong to project_id and team_id")}function eu(t){return JSON.stringify(nS(t))}function xn(t){return(0,kf.createHash)("sha256").update(eu(t)).digest("hex")}function nS(t){if(Array.isArray(t))return t.map(nS);if(t&&typeof t=="object"){let e=t;return Object.keys(e).sort().reduce((r,n)=>(r[n]=nS(e[n]),r),{})}return t}var kf,wn=R(()=>{"use strict";kf=require("crypto")});function Kie(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function ds(t){if(!t)return Vo;let e=Kie(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:Vo}function cr(t){return typeof t!="string"?null:ds(t)}var Vo,ba=R(()=>{"use strict";Vo="claude"});function KM(t){let e=cr(t.platformSource),r=e?[e]:[];return t.sourceEventId?`agent_event:v1:${xn([t.teamId,t.projectId,t.sourceAdapter,...r,t.sourceEventId])}`:`agent_event:v1:${xn([t.teamId,t.projectId,t.sourceAdapter,...r,t.contentSessionId??t.serverSessionId??null,t.eventType,new Date(t.occurredAt).toISOString(),eu(t.payload??{})])}`}function iS(t){return{id:t.id,projectId:t.project_id,teamId:t.team_id,serverSessionId:t.server_session_id,sourceAdapter:t.source_adapter,sourceEventId:t.source_event_id,idempotencyKey:t.idempotency_key,eventType:t.event_type,platformSource:t.platform_source,payload:t.payload,metadata:ht(t.metadata),occurredAtEpoch:De(t.occurred_at),receivedAtEpoch:De(t.received_at),createdAtEpoch:De(t.created_at)}}var Xr,Yo=R(()=>{"use strict";wn();ba();Xr=class{constructor(e){this.client=e}client;async create(e){await Sn(this.client,e.projectId,e.teamId),e.serverSessionId&&await Ai(this.client,e.serverSessionId,e.projectId,e.teamId);let r=KM(e),n=cr(e.platformSource),i=await se(this.client,`
|
|
67
67
|
INSERT INTO agent_events (
|
|
68
68
|
id, project_id, team_id, server_session_id, source_adapter,
|
|
69
69
|
source_event_id, idempotency_key, event_type, platform_source, payload, metadata, occurred_at
|
|
@@ -348,7 +348,7 @@ data:
|
|
|
348
348
|
)
|
|
349
349
|
ORDER BY e.occurred_at ASC
|
|
350
350
|
LIMIT $4
|
|
351
|
-
`,[e.serverSessionId,e.projectId,e.teamId,r])).rows.map(gge)}}});function o$(t){let e=Ege.safeParse(t);if(!e.success)throw new ad(e.error.issues);return e.data}var er,Kc,s$,a$,bge,vge,Ege,ad,gh=R(()=>{"use strict";er=require("zod"),Kc={event:"server_beta_generate_event",summary:"server_beta_generate_summary"},s$={event:"evt",summary:"sum"},a$=er.z.object({team_id:er.z.string().min(1,"team_id is required"),project_id:er.z.string().min(1,"project_id is required"),source_type:er.z.enum(["agent_event","session_summary","observation_reindex"]),source_id:er.z.string().min(1,"source_id is required"),generation_job_id:er.z.string().min(1,"generation_job_id is required"),api_key_id:er.z.string().min(1).nullable(),actor_id:er.z.string().min(1).nullable(),source_adapter:er.z.string().min(1,"source_adapter is required"),request_id:er.z.string().min(1).nullable().optional()}),bge=a$.extend({kind:er.z.literal("event"),agent_event_id:er.z.string().min(1)}),vge=a$.extend({kind:er.z.literal("summary"),server_session_id:er.z.string().min(1)}),Ege=er.z.discriminatedUnion("kind",[bge,vge]),ad=class extends Error{issues;constructor(e){super(`invalid server generation job payload: ${e.map(r=>r.message).join("; ")}`),this.issues=e}}});function Dc(t){let e=s$[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,c$.createHash)("sha256").update(r).digest("hex");return`${e}_${n}`}var c$,vI=R(()=>{"use strict";c$=require("crypto");gh()});function l$(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 u$,bh,d$=R(()=>{"use strict";Yo();ps();Ia();me();vI();wn();u$="observation_generate_for_event",bh=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 In(this.options.pool,async o=>{let l=await new Xr(o).create(e);if(!n)return{event:l,outbox:null};let u=new dt(o),d=new Ht(o),p=Ze(),f=l$({outboxId:p,event:l,apiKeyId:r.apiKeyId??null,actorId:r.actorId??null,sourceAdapter:r.sourceAdapter??null,requestId:r.requestId??null}),m=await u.create({id:p,projectId:l.projectId,teamId:l.teamId,sourceType:"agent_event",sourceId:l.id,agentEventId:l.id,serverSessionId:l.serverSessionId,jobType:u$,bullmqJobId:Dc({kind:"event",team_id:l.teamId,project_id:l.projectId,source_type:"agent_event",source_id:l.id}),payload:f});return await d.append({generationJobId:m.id,projectId:m.projectId,teamId:m.teamId,eventType:"queued",statusAfter:m.status,attempt:m.attempts,details:{source:i}}),{event:l,outbox:m}}),a="skipped";return s.outbox&&(a=await this.publishEventJob(s.event,s.outbox)),{event:s.event,outbox:s.outbox,enqueueState:a}}async ingestBatch(e,r={}){let n=r.generate??!0,i=r.source??"http_post_v1_events_batch",s=await In(this.options.pool,async a=>{let o=new Xr(a),c=new dt(a),l=new Ht(a),u=[];for(let d of e){let p=await o.create(d);if(!n){u.push({event:p,outbox:null});continue}let f=Ze(),m=l$({outboxId:f,event:p,apiKeyId:r.apiKeyId??null,actorId:r.actorId??null,sourceAdapter:r.sourceAdapter??null,requestId:r.requestId??null}),y=await c.create({id:f,projectId:p.projectId,teamId:p.teamId,sourceType:"agent_event",sourceId:p.id,agentEventId:p.id,serverSessionId:p.serverSessionId,jobType:u$,bullmqJobId:Dc({kind:"event",team_id:p.teamId,project_id:p.projectId,source_type:"agent_event",source_id:p.id}),payload:m});await l.append({generationJobId:y.id,projectId:y.projectId,teamId:y.teamId,eventType:"queued",statusAfter:y.status,attempt:y.attempts,details:{source:i}}),u.push({event:p,outbox:y})}return u});return Promise.all(s.map(async({event:a,outbox:o})=>{let c=o?await this.publishEventJob(a,o):"skipped";return{event:a,outbox:o,enqueueState:c}}))}async publishEventJob(e,r){let n=this.options.resolveEventQueue();if(!n)return"queued_only";let i=r.bullmqJobId??Dc({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 w.warn("SYSTEM","failed to publish event generation job to BullMQ",{outboxId:r.id,error:s instanceof Error?s.message:String(s)}),"queued_only"}}}});function EI(t){return Dc({kind:"summary",team_id:t.teamId,project_id:t.projectId,source_type:"session_summary",source_id:t.serverSessionId})}function SI(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 p$=R(()=>{"use strict";vI()});var Sge,vh,f$=R(()=>{"use strict";ps();Ia();Cs();me();p$();wn();Sge="observation_generate_session_summary",vh=class{constructor(e){this.options=e}options;async end(e){let r=e.source??"http_post_v1_sessions_end",n=await In(this.options.pool,async s=>{let o=await new Zt(s).endSession({id:e.sessionId,projectId:e.projectId,teamId:e.teamId});if(!o)return{session:null,outbox:null};let c=new dt(s),l=new Ht(s),u=Ze(),d=SI({serverSessionId:o.id,teamId:o.teamId,projectId:o.projectId,generationJobId:u,apiKeyId:e.apiKeyId??null,actorId:e.actorId??null,sourceAdapter:e.sourceAdapter??null}),p=await c.create({id:u,projectId:o.projectId,teamId:o.teamId,sourceType:"session_summary",sourceId:o.id,serverSessionId:o.id,jobType:Sge,bullmqJobId:EI({serverSessionId:o.id,teamId:o.teamId,projectId:o.projectId}),payload:d});return await l.append({generationJobId:p.id,projectId:p.projectId,teamId:p.teamId,eventType:"queued",statusAfter:p.status,attempt:p.attempts,details:{source:r}}),{session:o,outbox:p}});if(!n.session||!n.outbox)return{session:n.session,outbox:null,enqueueState:"skipped"};let i=await this.publishSummaryJob(n.session.id,n.outbox,e);return{session:n.session,outbox:n.outbox,enqueueState:i}}async publishSummaryJob(e,r,n){let i=this.options.resolveSummaryQueue();if(!i)return"queued_only";let s=r.bullmqJobId??EI({serverSessionId:e,teamId:r.teamId,projectId:r.projectId}),a=SI({serverSessionId:e,teamId:r.teamId,projectId:r.projectId,generationJobId:r.id,apiKeyId:n.apiKeyId??null,actorId:n.actorId??null,sourceAdapter:n.sourceAdapter??null});try{return await i.add(s,a),"enqueued"}catch(o){return w.warn("SYSTEM","failed to publish summary generation job to BullMQ",{outboxId:r.id,error:o instanceof Error?o.message:String(o)}),"queued_only"}}}});function m$(t){return`${(process.env.CLAUDE_MEM_PUBLIC_URL??`${t.protocol}://${t.get("host")??"localhost"}`).replace(/\/+$/,"")}/v1/mcp`}function h$(t,e){return`claude mcp add --transport http claude-mem ${t} --header "Authorization: Bearer ${e}"`}async function b$(t,e,r=x$,n=_ge){if(g$.includes(e.status))return{job:e,timedOut:!1};let i=Date.now()+r,s=e;for(;Date.now()<i;){await new Promise(o=>setTimeout(o,n));let a=await t.getByIdForScope({id:e.id,projectId:e.projectId,teamId:e.teamId});if(!a)return{job:s,timedOut:!1};if(s=a,g$.includes(a.status))return{job:a,timedOut:!1}}return{job:s,timedOut:!0}}function kge(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&w$.has(e)?e:null,n=typeof t.query.source_type=="string"?t.query.source_type.trim():"",i=n&&Ige.has(n)?n:null,s=Sh(t.query.limit,_$,1,I$),a=Sh(t.query.offset,0,0,Number.MAX_SAFE_INTEGER),o=typeof t.query.since=="string"?t.query.since.trim():"",c=null;if(o){let l=new Date(o);Number.isNaN(l.getTime())||(c=l)}return{status:r,sourceType:i,limit:s,offset:a,since:c}}function v$(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 E$(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&w$.has(e)?e:null,n=Sh(t.query.limit,_$,1,I$),i=Sh(t.query.offset,0,0,Number.MAX_SAFE_INTEGER);return{status:r,limit:n,offset:i}}function Sh(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 xI(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 Tge(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 Age(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 od(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 cd(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 Mc(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,serverSessionId:t.serverSessionId,kind:t.kind,content:t.content,metadata:t.metadata,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function Rge(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 wI(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 S$(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 _I(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 ue,xh,xge,wge,y$,x$,_ge,g$,Eh,Ige,w$,_$,I$,k$=R(()=>{"use strict";ue=require("zod");jM();Yo();ps();Ri();ru();Wo();me();Af();ux();JL();Kq();ZF();t$();n$();qa();xh=require("node:crypto");Cs();d$();f$();ba();xge="api",wge="13.24.0";y$=ue.z.object({generate:ue.z.union([ue.z.literal("true"),ue.z.literal("false")]).optional(),wait:ue.z.union([ue.z.literal("true"),ue.z.literal("false")]).optional()}),x$=3e4,_ge=100,g$=["completed","failed","cancelled"];Eh=class{constructor(e){this.options=e;this.ingestEvents=new bh({pool:e.pool,resolveEventQueue:()=>this.resolveQueue("event")}),this.endSession=new vh({pool:e.pool,resolveSummaryQueue:()=>this.resolveQueue("summary")})}options;ingestEvents;endSession;getIngestEventsService(){return this.ingestEvents}getEndSessionService(){return this.endSession}setupRoutes(e){e.use("/v1",$L());let r=Ea(this.options.pool,{authMode:this.options.authMode,allowLocalDevBypass:this.options.allowLocalDevBypass,requiredScopes:["memories:write"]}),n=Ea(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(e$(this.options.pool,{windowSec:60,max:s}));let a=Number(process.env.CLAUDE_MEM_MONTHLY_REQUEST_CAP??"0");a>0&&i.push(bI(this.options.pool,{kind:"request",cap:a})),process.env.CLAUDE_MEM_USAGE_METERING==="1"&&i.push(r$(this.options.pool));let o=[...i],c=Number(process.env.CLAUDE_MEM_MONTHLY_TOKEN_CAP??"0");c>0&&o.push(bI(this.options.pool,{kind:"tokens",cap:c}));let l=[r,...o],u=[n,...i];e.get("/v1/usage",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let y=new Date(Date.UTC(new Date().getUTCFullYear(),new Date().getUTCMonth(),1)),b=await new Kr(this.options.pool).summarize({teamId:m,since:y});f.status(200).json({since:y.toISOString(),usage:b})})),e.post("/v1/keys",l,this.handleCreate(ue.z.object({label:ue.z.string().max(120).optional(),expiresInDays:ue.z.number().int().positive().max(365).optional()}),async(p,f,m)=>{let y=this.requireTeamId(p,f);if(!y)return;let b=`cm_${(0,xh.randomBytes)(24).toString("hex")}`,v=(0,xh.createHash)("sha256").update(b).digest("hex"),E=m.expiresInDays?new Date(Date.now()+m.expiresInDays*864e5):null,S=await new Mt(this.options.pool).createApiKey({keyHash:v,teamId:y,projectId:p.authContext?.projectId??null,actorId:p.authContext?.apiKeyId??"api",scopes:["memories:read"],expiresAt:E});m.label;let T=m$(p);f.status(201).json({id:S.id,apiKey:b,scopes:["memories:read"],expiresAt:E?.toISOString()??null,mcpUrl:T,connectCommand:h$(T,b)})})),e.get("/v1/connect",u,this.asyncHandler(async(p,f)=>{if(!this.requireTeamId(p,f))return;let y=m$(p);f.status(200).json({mcpUrl:y,connectCommand:h$(y,"<YOUR_API_KEY>"),hint:"POST /v1/keys (write scope) to mint a read-only key for this link."})})),e.post("/v1/events",l,this.asyncHandler(async(p,f)=>{let m=y$.safeParse(p.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let y=m.data.generate!=="false",b=m.data.wait==="true",v=rS.safeParse(p.body);if(!v.success){f.status(400).json({error:"ValidationError",issues:v.error.issues});return}let E=v.data,S=this.requireTeamId(p,f);if(!S||!this.ensureProjectAllowed(p,f,E.projectId))return;let T=this.toAgentEventInput(E,S);await this.applyContentSessionLinks([T],[p.body],S);let _,j=null,N="skipped",ee={generate:y,source:"http_post_v1_events",apiKeyId:p.authContext?.apiKeyId??null,actorId:await this.resolveActorId(p),sourceAdapter:T.sourceAdapter,requestId:p.requestId??null};try{let q=await this.ingestEvents.ingestOne(T,ee);_=q.event,j=q.outbox,N=q.enqueueState}catch(q){let J=q instanceof Error?q:new Error(String(q));w.warn("SYSTEM","event.write ingest failed",{requestId:p.requestId??null},J),this.handleDbError(J,f,"event.write");return}if(await this.auditWrite(p,"event.received",_.id,_.projectId,{sourceAdapter:_.sourceAdapter,sourceEventId:_.sourceEventId,eventType:_.eventType,serverSessionId:_.serverSessionId,generationJobId:j?.id??null}),b){let q=j,J=!1;if(j){let te=new dt(this.options.pool),ze=await b$(te,j);q=ze.job,J=ze.timedOut}f.status(201).json({event:cd(_),generationJob:q?S$(q,N):null,...J?{waitTimedOut:!0}:{}});return}f.status(201).json({event:cd(_),...j?{generationJob:wI(j,N)}:{}})})),e.post("/v1/events/batch",l,this.asyncHandler(async(p,f)=>{let m=y$.safeParse(p.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let y=m.data.generate!=="false",b=m.data.wait==="true",E=ue.z.array(rS).min(1).max(500).safeParse(p.body);if(!E.success){f.status(400).json({error:"ValidationError",issues:E.error.issues});return}let S=this.requireTeamId(p,f);if(!S)return;let T=Age(p,E.data);if(T){f.status(T.status).json(T.body);return}let _=E.data.map(q=>this.toAgentEventInput(q,S));await this.applyContentSessionLinks(_,Array.isArray(p.body)?p.body:E.data,S);let j=[],N=[],ee={generate:y,source:"http_post_v1_events_batch",apiKeyId:p.authContext?.apiKeyId??null,actorId:await this.resolveActorId(p),sourceAdapter:null,requestId:p.requestId??null};try{let q=await this.ingestEvents.ingestBatch(_,ee);j=q.map(({event:J,outbox:te})=>({event:J,outbox:te})),N=q.map(({enqueueState:J})=>J)}catch(q){let J=q instanceof Error?q:new Error(String(q));w.warn("SYSTEM","event.batch_write ingest failed",{requestId:p.requestId??null},J),this.handleDbError(J,f,"event.batch_write");return}if(await this.auditWrite(p,"event.batch_received",null,null,{eventCount:j.length,generationJobIds:j.map(({outbox:q})=>q?.id??null).filter(Boolean)}),b){let q=new dt(this.options.pool),J=Date.now()+x$,te=[];for(let k of j){if(!k.outbox){te.push({event:k.event,outbox:null,timedOut:!1});continue}let K=Math.max(0,J-Date.now()),P=await b$(q,k.outbox,K);te.push({event:k.event,outbox:P.job,timedOut:P.timedOut})}let ze=te.some(k=>k.timedOut);f.status(201).json({events:te.map(({event:k,outbox:K,timedOut:P},O)=>({event:cd(k),generationJob:K?S$(K,N[O]):null,...P?{waitTimedOut:!0}:{}})),...ze?{waitTimedOut:!0}:{}});return}f.status(201).json({events:j.map(({event:q,outbox:J},te)=>({event:cd(q),...J?{generationJob:wI(J,N[te])}:{}}))})})),e.get("/v1/events/:id",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let y=this.routeParam(p.params.id),b=new Xr(this.options.pool),v=await this.loadScopedById(p,f,{id:y,teamId:m,table:"agent_events",notFound:"Event not found",load:E=>b.getByIdForScope({id:y,projectId:E,teamId:m})});v&&f.json({event:cd(v)})})),e.get("/v1/events/:id/observations",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let y=this.routeParam(p.params.id),v=(await this.options.pool.query("SELECT id, project_id FROM agent_events WHERE id = $1 AND team_id = $2",[y,m])).rows[0];if(!v){f.status(404).json({error:"NotFound",message:"Event not found"});return}if(!this.ensureProjectAllowed(p,f,v.project_id))return;let E=await this.options.pool.query(`
|
|
351
|
+
`,[e.serverSessionId,e.projectId,e.teamId,r])).rows.map(gge)}}});function o$(t){let e=Ege.safeParse(t);if(!e.success)throw new ad(e.error.issues);return e.data}var er,Kc,s$,a$,bge,vge,Ege,ad,gh=R(()=>{"use strict";er=require("zod"),Kc={event:"server_beta_generate_event",summary:"server_beta_generate_summary"},s$={event:"evt",summary:"sum"},a$=er.z.object({team_id:er.z.string().min(1,"team_id is required"),project_id:er.z.string().min(1,"project_id is required"),source_type:er.z.enum(["agent_event","session_summary","observation_reindex"]),source_id:er.z.string().min(1,"source_id is required"),generation_job_id:er.z.string().min(1,"generation_job_id is required"),api_key_id:er.z.string().min(1).nullable(),actor_id:er.z.string().min(1).nullable(),source_adapter:er.z.string().min(1,"source_adapter is required"),request_id:er.z.string().min(1).nullable().optional()}),bge=a$.extend({kind:er.z.literal("event"),agent_event_id:er.z.string().min(1)}),vge=a$.extend({kind:er.z.literal("summary"),server_session_id:er.z.string().min(1)}),Ege=er.z.discriminatedUnion("kind",[bge,vge]),ad=class extends Error{issues;constructor(e){super(`invalid server generation job payload: ${e.map(r=>r.message).join("; ")}`),this.issues=e}}});function Dc(t){let e=s$[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,c$.createHash)("sha256").update(r).digest("hex");return`${e}_${n}`}var c$,vI=R(()=>{"use strict";c$=require("crypto");gh()});function l$(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 u$,bh,d$=R(()=>{"use strict";Yo();ps();Ia();me();vI();wn();u$="observation_generate_for_event",bh=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 In(this.options.pool,async o=>{let l=await new Xr(o).create(e);if(!n)return{event:l,outbox:null};let u=new dt(o),d=new Ht(o),p=Ze(),f=l$({outboxId:p,event:l,apiKeyId:r.apiKeyId??null,actorId:r.actorId??null,sourceAdapter:r.sourceAdapter??null,requestId:r.requestId??null}),m=await u.create({id:p,projectId:l.projectId,teamId:l.teamId,sourceType:"agent_event",sourceId:l.id,agentEventId:l.id,serverSessionId:l.serverSessionId,jobType:u$,bullmqJobId:Dc({kind:"event",team_id:l.teamId,project_id:l.projectId,source_type:"agent_event",source_id:l.id}),payload:f});return await d.append({generationJobId:m.id,projectId:m.projectId,teamId:m.teamId,eventType:"queued",statusAfter:m.status,attempt:m.attempts,details:{source:i}}),{event:l,outbox:m}}),a="skipped";return s.outbox&&(a=await this.publishEventJob(s.event,s.outbox)),{event:s.event,outbox:s.outbox,enqueueState:a}}async ingestBatch(e,r={}){let n=r.generate??!0,i=r.source??"http_post_v1_events_batch",s=await In(this.options.pool,async a=>{let o=new Xr(a),c=new dt(a),l=new Ht(a),u=[];for(let d of e){let p=await o.create(d);if(!n){u.push({event:p,outbox:null});continue}let f=Ze(),m=l$({outboxId:f,event:p,apiKeyId:r.apiKeyId??null,actorId:r.actorId??null,sourceAdapter:r.sourceAdapter??null,requestId:r.requestId??null}),y=await c.create({id:f,projectId:p.projectId,teamId:p.teamId,sourceType:"agent_event",sourceId:p.id,agentEventId:p.id,serverSessionId:p.serverSessionId,jobType:u$,bullmqJobId:Dc({kind:"event",team_id:p.teamId,project_id:p.projectId,source_type:"agent_event",source_id:p.id}),payload:m});await l.append({generationJobId:y.id,projectId:y.projectId,teamId:y.teamId,eventType:"queued",statusAfter:y.status,attempt:y.attempts,details:{source:i}}),u.push({event:p,outbox:y})}return u});return Promise.all(s.map(async({event:a,outbox:o})=>{let c=o?await this.publishEventJob(a,o):"skipped";return{event:a,outbox:o,enqueueState:c}}))}async publishEventJob(e,r){let n=this.options.resolveEventQueue();if(!n)return"queued_only";let i=r.bullmqJobId??Dc({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 w.warn("SYSTEM","failed to publish event generation job to BullMQ",{outboxId:r.id,error:s instanceof Error?s.message:String(s)}),"queued_only"}}}});function EI(t){return Dc({kind:"summary",team_id:t.teamId,project_id:t.projectId,source_type:"session_summary",source_id:t.serverSessionId})}function SI(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 p$=R(()=>{"use strict";vI()});var Sge,vh,f$=R(()=>{"use strict";ps();Ia();Cs();me();p$();wn();Sge="observation_generate_session_summary",vh=class{constructor(e){this.options=e}options;async end(e){let r=e.source??"http_post_v1_sessions_end",n=await In(this.options.pool,async s=>{let o=await new Zt(s).endSession({id:e.sessionId,projectId:e.projectId,teamId:e.teamId});if(!o)return{session:null,outbox:null};let c=new dt(s),l=new Ht(s),u=Ze(),d=SI({serverSessionId:o.id,teamId:o.teamId,projectId:o.projectId,generationJobId:u,apiKeyId:e.apiKeyId??null,actorId:e.actorId??null,sourceAdapter:e.sourceAdapter??null}),p=await c.create({id:u,projectId:o.projectId,teamId:o.teamId,sourceType:"session_summary",sourceId:o.id,serverSessionId:o.id,jobType:Sge,bullmqJobId:EI({serverSessionId:o.id,teamId:o.teamId,projectId:o.projectId}),payload:d});return await l.append({generationJobId:p.id,projectId:p.projectId,teamId:p.teamId,eventType:"queued",statusAfter:p.status,attempt:p.attempts,details:{source:r}}),{session:o,outbox:p}});if(!n.session||!n.outbox)return{session:n.session,outbox:null,enqueueState:"skipped"};let i=await this.publishSummaryJob(n.session.id,n.outbox,e);return{session:n.session,outbox:n.outbox,enqueueState:i}}async publishSummaryJob(e,r,n){let i=this.options.resolveSummaryQueue();if(!i)return"queued_only";let s=r.bullmqJobId??EI({serverSessionId:e,teamId:r.teamId,projectId:r.projectId}),a=SI({serverSessionId:e,teamId:r.teamId,projectId:r.projectId,generationJobId:r.id,apiKeyId:n.apiKeyId??null,actorId:n.actorId??null,sourceAdapter:n.sourceAdapter??null});try{return await i.add(s,a),"enqueued"}catch(o){return w.warn("SYSTEM","failed to publish summary generation job to BullMQ",{outboxId:r.id,error:o instanceof Error?o.message:String(o)}),"queued_only"}}}});function m$(t){return`${(process.env.CLAUDE_MEM_PUBLIC_URL??`${t.protocol}://${t.get("host")??"localhost"}`).replace(/\/+$/,"")}/v1/mcp`}function h$(t,e){return`claude mcp add --transport http claude-mem ${t} --header "Authorization: Bearer ${e}"`}async function b$(t,e,r=x$,n=_ge){if(g$.includes(e.status))return{job:e,timedOut:!1};let i=Date.now()+r,s=e;for(;Date.now()<i;){await new Promise(o=>setTimeout(o,n));let a=await t.getByIdForScope({id:e.id,projectId:e.projectId,teamId:e.teamId});if(!a)return{job:s,timedOut:!1};if(s=a,g$.includes(a.status))return{job:a,timedOut:!1}}return{job:s,timedOut:!0}}function kge(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&w$.has(e)?e:null,n=typeof t.query.source_type=="string"?t.query.source_type.trim():"",i=n&&Ige.has(n)?n:null,s=Sh(t.query.limit,_$,1,I$),a=Sh(t.query.offset,0,0,Number.MAX_SAFE_INTEGER),o=typeof t.query.since=="string"?t.query.since.trim():"",c=null;if(o){let l=new Date(o);Number.isNaN(l.getTime())||(c=l)}return{status:r,sourceType:i,limit:s,offset:a,since:c}}function v$(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 E$(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&w$.has(e)?e:null,n=Sh(t.query.limit,_$,1,I$),i=Sh(t.query.offset,0,0,Number.MAX_SAFE_INTEGER);return{status:r,limit:n,offset:i}}function Sh(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 xI(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 Tge(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 Age(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 od(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 cd(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 Mc(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,serverSessionId:t.serverSessionId,kind:t.kind,content:t.content,metadata:t.metadata,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function Rge(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 wI(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 S$(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 _I(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 ue,xh,xge,wge,y$,x$,_ge,g$,Eh,Ige,w$,_$,I$,k$=R(()=>{"use strict";ue=require("zod");jM();Yo();ps();Ri();ru();Wo();me();Af();ux();JL();Kq();ZF();t$();n$();qa();xh=require("node:crypto");Cs();d$();f$();ba();xge="api",wge="13.24.1";y$=ue.z.object({generate:ue.z.union([ue.z.literal("true"),ue.z.literal("false")]).optional(),wait:ue.z.union([ue.z.literal("true"),ue.z.literal("false")]).optional()}),x$=3e4,_ge=100,g$=["completed","failed","cancelled"];Eh=class{constructor(e){this.options=e;this.ingestEvents=new bh({pool:e.pool,resolveEventQueue:()=>this.resolveQueue("event")}),this.endSession=new vh({pool:e.pool,resolveSummaryQueue:()=>this.resolveQueue("summary")})}options;ingestEvents;endSession;getIngestEventsService(){return this.ingestEvents}getEndSessionService(){return this.endSession}setupRoutes(e){e.use("/v1",$L());let r=Ea(this.options.pool,{authMode:this.options.authMode,allowLocalDevBypass:this.options.allowLocalDevBypass,requiredScopes:["memories:write"]}),n=Ea(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(e$(this.options.pool,{windowSec:60,max:s}));let a=Number(process.env.CLAUDE_MEM_MONTHLY_REQUEST_CAP??"0");a>0&&i.push(bI(this.options.pool,{kind:"request",cap:a})),process.env.CLAUDE_MEM_USAGE_METERING==="1"&&i.push(r$(this.options.pool));let o=[...i],c=Number(process.env.CLAUDE_MEM_MONTHLY_TOKEN_CAP??"0");c>0&&o.push(bI(this.options.pool,{kind:"tokens",cap:c}));let l=[r,...o],u=[n,...i];e.get("/v1/usage",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let y=new Date(Date.UTC(new Date().getUTCFullYear(),new Date().getUTCMonth(),1)),b=await new Kr(this.options.pool).summarize({teamId:m,since:y});f.status(200).json({since:y.toISOString(),usage:b})})),e.post("/v1/keys",l,this.handleCreate(ue.z.object({label:ue.z.string().max(120).optional(),expiresInDays:ue.z.number().int().positive().max(365).optional()}),async(p,f,m)=>{let y=this.requireTeamId(p,f);if(!y)return;let b=`cm_${(0,xh.randomBytes)(24).toString("hex")}`,v=(0,xh.createHash)("sha256").update(b).digest("hex"),E=m.expiresInDays?new Date(Date.now()+m.expiresInDays*864e5):null,S=await new Mt(this.options.pool).createApiKey({keyHash:v,teamId:y,projectId:p.authContext?.projectId??null,actorId:p.authContext?.apiKeyId??"api",scopes:["memories:read"],expiresAt:E});m.label;let T=m$(p);f.status(201).json({id:S.id,apiKey:b,scopes:["memories:read"],expiresAt:E?.toISOString()??null,mcpUrl:T,connectCommand:h$(T,b)})})),e.get("/v1/connect",u,this.asyncHandler(async(p,f)=>{if(!this.requireTeamId(p,f))return;let y=m$(p);f.status(200).json({mcpUrl:y,connectCommand:h$(y,"<YOUR_API_KEY>"),hint:"POST /v1/keys (write scope) to mint a read-only key for this link."})})),e.post("/v1/events",l,this.asyncHandler(async(p,f)=>{let m=y$.safeParse(p.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let y=m.data.generate!=="false",b=m.data.wait==="true",v=rS.safeParse(p.body);if(!v.success){f.status(400).json({error:"ValidationError",issues:v.error.issues});return}let E=v.data,S=this.requireTeamId(p,f);if(!S||!this.ensureProjectAllowed(p,f,E.projectId))return;let T=this.toAgentEventInput(E,S);await this.applyContentSessionLinks([T],[p.body],S);let _,j=null,N="skipped",ee={generate:y,source:"http_post_v1_events",apiKeyId:p.authContext?.apiKeyId??null,actorId:await this.resolveActorId(p),sourceAdapter:T.sourceAdapter,requestId:p.requestId??null};try{let q=await this.ingestEvents.ingestOne(T,ee);_=q.event,j=q.outbox,N=q.enqueueState}catch(q){let J=q instanceof Error?q:new Error(String(q));w.warn("SYSTEM","event.write ingest failed",{requestId:p.requestId??null},J),this.handleDbError(J,f,"event.write");return}if(await this.auditWrite(p,"event.received",_.id,_.projectId,{sourceAdapter:_.sourceAdapter,sourceEventId:_.sourceEventId,eventType:_.eventType,serverSessionId:_.serverSessionId,generationJobId:j?.id??null}),b){let q=j,J=!1;if(j){let te=new dt(this.options.pool),ze=await b$(te,j);q=ze.job,J=ze.timedOut}f.status(201).json({event:cd(_),generationJob:q?S$(q,N):null,...J?{waitTimedOut:!0}:{}});return}f.status(201).json({event:cd(_),...j?{generationJob:wI(j,N)}:{}})})),e.post("/v1/events/batch",l,this.asyncHandler(async(p,f)=>{let m=y$.safeParse(p.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let y=m.data.generate!=="false",b=m.data.wait==="true",E=ue.z.array(rS).min(1).max(500).safeParse(p.body);if(!E.success){f.status(400).json({error:"ValidationError",issues:E.error.issues});return}let S=this.requireTeamId(p,f);if(!S)return;let T=Age(p,E.data);if(T){f.status(T.status).json(T.body);return}let _=E.data.map(q=>this.toAgentEventInput(q,S));await this.applyContentSessionLinks(_,Array.isArray(p.body)?p.body:E.data,S);let j=[],N=[],ee={generate:y,source:"http_post_v1_events_batch",apiKeyId:p.authContext?.apiKeyId??null,actorId:await this.resolveActorId(p),sourceAdapter:null,requestId:p.requestId??null};try{let q=await this.ingestEvents.ingestBatch(_,ee);j=q.map(({event:J,outbox:te})=>({event:J,outbox:te})),N=q.map(({enqueueState:J})=>J)}catch(q){let J=q instanceof Error?q:new Error(String(q));w.warn("SYSTEM","event.batch_write ingest failed",{requestId:p.requestId??null},J),this.handleDbError(J,f,"event.batch_write");return}if(await this.auditWrite(p,"event.batch_received",null,null,{eventCount:j.length,generationJobIds:j.map(({outbox:q})=>q?.id??null).filter(Boolean)}),b){let q=new dt(this.options.pool),J=Date.now()+x$,te=[];for(let k of j){if(!k.outbox){te.push({event:k.event,outbox:null,timedOut:!1});continue}let K=Math.max(0,J-Date.now()),P=await b$(q,k.outbox,K);te.push({event:k.event,outbox:P.job,timedOut:P.timedOut})}let ze=te.some(k=>k.timedOut);f.status(201).json({events:te.map(({event:k,outbox:K,timedOut:P},O)=>({event:cd(k),generationJob:K?S$(K,N[O]):null,...P?{waitTimedOut:!0}:{}})),...ze?{waitTimedOut:!0}:{}});return}f.status(201).json({events:j.map(({event:q,outbox:J},te)=>({event:cd(q),...J?{generationJob:wI(J,N[te])}:{}}))})})),e.get("/v1/events/:id",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let y=this.routeParam(p.params.id),b=new Xr(this.options.pool),v=await this.loadScopedById(p,f,{id:y,teamId:m,table:"agent_events",notFound:"Event not found",load:E=>b.getByIdForScope({id:y,projectId:E,teamId:m})});v&&f.json({event:cd(v)})})),e.get("/v1/events/:id/observations",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let y=this.routeParam(p.params.id),v=(await this.options.pool.query("SELECT id, project_id FROM agent_events WHERE id = $1 AND team_id = $2",[y,m])).rows[0];if(!v){f.status(404).json({error:"NotFound",message:"Event not found"});return}if(!this.ensureProjectAllowed(p,f,v.project_id))return;let E=await this.options.pool.query(`
|
|
352
352
|
SELECT o.id, o.project_id, o.team_id, o.server_session_id, o.kind, o.content,
|
|
353
353
|
o.metadata, o.generation_key, o.created_by_job_id, o.created_at, o.updated_at,
|
|
354
354
|
os.id AS source_id_pk, os.source_type, os.source_id, os.generation_job_id, os.created_at AS source_created_at
|