claude-mem 13.9.3 → 13.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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.9.3",
6
+ "version": "13.10.0",
7
7
  "license": "Apache-2.0",
8
8
  "author": "thedotmack",
9
9
  "homepage": "https://claude-mem.ai",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "13.9.3",
3
+ "version": "13.10.0",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "keywords": [
6
6
  "claude",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "13.9.3",
3
+ "version": "13.10.0",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "author": {
6
6
  "name": "Alex Newman"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "13.9.3",
3
+ "version": "13.10.0",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "author": {
6
6
  "name": "Alex Newman",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem-plugin",
3
- "version": "13.9.3",
3
+ "version": "13.10.0",
4
4
  "private": true,
5
5
  "description": "Runtime dependencies for claude-mem bundled hooks",
6
6
  "type": "module",
@@ -219,7 +219,7 @@ ${f}`}let a=s.lineStart;for(let u=s.lineStart-1;u>=0;u--){let l=i[u].trim();if(l
219
219
  ${c}`}var Bx=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"]),Xx=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),Qx=512*1024;async function*k_(t,e,r=20){if(r<=0)return;let n;try{n=await(0,Mr.readdir)(t,{withFileTypes:!0})}catch(o){y.debug("WORKER",`walkDir: failed to read directory ${t}`,void 0,o instanceof Error?o:void 0);return}for(let o of n){if(o.name.startsWith(".")&&o.name!=="."||Xx.has(o.name))continue;let s=(0,Hn.join)(t,o.name);if(o.isDirectory())yield*k_(s,e,r-1);else if(o.isFile()){let i=o.name.slice(o.name.lastIndexOf("."));Bx.has(i)&&(yield s)}}}async function eP(t){try{let e=await(0,Mr.stat)(t);if(e.size>Qx||e.size===0)return null;let r=await(0,Mr.readFile)(t,"utf-8");return r.slice(0,1e3).includes("\0")?null:r}catch(e){return y.debug("WORKER",`safeReadFile: failed to read ${t}`,void 0,e instanceof Error?e:void 0),null}}async function $_(t,e,r={}){let n=r.maxResults||20,o=e.toLowerCase(),s=o.split(/[\s_\-./]+/).filter(g=>g.length>0),i=[];for await(let g of k_(t,t,20)){if(r.filePattern&&!(0,Hn.relative)(t,g).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let S=await eP(g);S&&i.push({absolutePath:g,relativePath:(0,Hn.relative)(t,g),content:S})}let a=b_(i),c=[],u=[],l=0;for(let[g,S]of a){l+=tP(S);let $=Ds(g.toLowerCase(),s)>0,b=[],x=(k,_e)=>{for(let V of k){let tt=0,Ae="",kt=Ds(V.name.toLowerCase(),s);kt>0&&(tt+=kt*3,Ae="name match"),V.signature.toLowerCase().includes(o)&&(tt+=2,Ae=Ae?`${Ae} + signature`:"signature match"),V.jsdoc&&V.jsdoc.toLowerCase().includes(o)&&(tt+=1,Ae=Ae?`${Ae} + jsdoc`:"jsdoc match"),tt>0&&($=!0,b.push({filePath:g,symbolName:_e?`${_e}.${V.name}`:V.name,kind:V.kind,signature:V.signature,jsdoc:V.jsdoc,lineStart:V.lineStart,lineEnd:V.lineEnd,matchReason:Ae})),V.children&&x(V.children,V.name)}};x(S.symbols),$&&(c.push(S),u.push(...b))}u.sort((g,S)=>{let v=Ds(g.symbolName.toLowerCase(),s);return Ds(S.symbolName.toLowerCase(),s)-v});let d=u.slice(0,n),p=new Set(d.map(g=>g.filePath)),f=c.filter(g=>p.has(g.filePath)).slice(0,n),m=f.reduce((g,S)=>g+S.foldedTokenEstimate,0);return{foldedFiles:f,matchingSymbols:d,totalFilesScanned:i.length,totalSymbolsFound:l,tokenEstimate:m}}function Ds(t,e){let r=0;for(let n of e)if(t===n)r+=10;else if(t.includes(n))r+=5;else{let o=0,s=0;for(let i of n){let a=t.indexOf(i,o);a!==-1&&(s++,o=a+1)}s===n.length&&(r+=1)}return r}function tP(t){let e=t.symbols.length;for(let r of t.symbols)r.children&&(e+=r.children.length);return e}function x_(t,e){let r=[];if(r.push(`\u{1F50D} Smart Search: "${e}"`),r.push(` Scanned ${t.totalFilesScanned} files, found ${t.totalSymbolsFound} symbols`),r.push(` ${t.matchingSymbols.length} matches across ${t.foldedFiles.length} files (~${t.tokenEstimate} tokens for folded view)`),r.push(""),t.matchingSymbols.length===0)return r.push(" No matching symbols found."),r.join(`
220
220
  `);r.push("\u2500\u2500 Matching Symbols \u2500\u2500"),r.push("");for(let n of t.matchingSymbols){if(r.push(` ${n.kind} ${n.symbolName} (${n.filePath}:${n.lineStart+1})`),r.push(` ${n.signature}`),n.jsdoc){let o=n.jsdoc.split(`
221
221
  `).find(s=>s.replace(/^[\s*/]+/,"").trim().length>0);o&&r.push(` \u{1F4AC} ${o.replace(/^[\s*/]+/,"").trim()}`)}r.push("")}r.push("\u2500\u2500 Folded File Views \u2500\u2500"),r.push("");for(let n of t.foldedFiles)r.push(Ar(n)),r.push("");return r.push("\u2500\u2500 Actions \u2500\u2500"),r.push(" To see full implementation: use smart_unfold with file path and symbol name"),r.join(`
222
- `)}var $u=require("node:fs/promises"),Us=require("node:fs"),et=require("node:path"),I_=require("node:os"),O_=require("node:url");var P_="claude";function rP(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function js(t){if(!t)return P_;let e=rP(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:P_}var nP=qt(ue.API_REQUEST),Ve=class extends Error{kind;status;cause;constructor(e,r,n={}){super(r),this.name="ServerClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},Ls=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=oP(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??nP}async startSession(e){let r=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",r)}async recordEvent(e){let r=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(e){if(!e.sessionId)throw new Ve("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async getJobStatus(e){if(!e)throw new Ve("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,type:n,narrative:r,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:wu(e.platformSource)}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:wu(e.platformSource)}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:wu(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,r,n){if(!this.apiKey||!this.apiKey.trim())throw new Ve("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let o=`${this.baseUrl}${r}`,s={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(s.body=JSON.stringify(n));let i;try{i=await fu(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new Ve(l?"timeout":"transport",`Server ${e} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new Ve("http_error",`Server ${e} ${r} returned ${i.status}: ${sP(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 Ve("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:u})}}};function T_(t){return t instanceof Ve}function oP(t){return t.replace(/\/+$/,"")}function wu(t){return typeof t=="string"?js(t):null}function sP(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function ku(){let e=(ws().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function z_(){let t=ws(),e=(...i)=>{for(let a of i){let c=(a??"").trim();if(c.length>0)return c}return""},r=e(t.CLAUDE_MEM_SERVER_URL,t.CLAUDE_MEM_SERVER_BETA_URL),n=e(t.CLAUDE_MEM_SERVER_API_KEY,t.CLAUDE_MEM_SERVER_BETA_API_KEY),o=e(t.CLAUDE_MEM_SERVER_PROJECT_ID,t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!r)return y.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return y.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return y.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let s={serverBaseUrl:r,apiKey:n};return{runtime:"server",client:new Ls(s),projectId:o,serverBaseUrl:r}}var xP={},iP="13.9.3";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var A_=!1,M_=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,et.dirname)((0,O_.fileURLToPath)(xP.url))}catch(t){return A_=!0,y.warn("SYSTEM","mcp-server: failed to resolve module directory from import.meta.url, falling back to process.cwd()",void 0,t instanceof Error?t:new Error(String(t))),process.cwd()}})(),xu=l_()??(0,et.resolve)(M_,"worker-service.cjs");function aP(){A_&&((0,Us.existsSync)(xu)||y.error("SYSTEM","mcp-server: dirname resolution failed (both __dirname and import.meta.url are unavailable). Fell back to process.cwd() and the resolved WORKER_SCRIPT_PATH does not exist. This is the actual problem \u2014 the worker bundle is fine, but mcp-server cannot locate it. Worker auto-start will fail until the dirname-resolution path is fixed.",{workerScriptPath:xu,mcpServerDir:M_}))}async function pt(t,e={}){y.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t});try{let r;if(e.body)r=await Ms(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e.body)});else{let n=new URLSearchParams;for(let[o,s]of Object.entries(e.query??{}))s!=null&&n.append(o,String(s));r=await Ms(`${t}?${n}`)}if(!r.ok){let n=await r.text();throw new Error(`Worker API error (${r.status}): ${n}`)}return y.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),e.text?{content:[{type:"text",text:await r.text()}]}:e.body?{content:[{type:"text",text:JSON.stringify(await r.json(),null,2)}]}:await r.json()}catch(r){return y.error("SYSTEM","\u2190 Worker API error",{endpoint:t},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function cP(){try{return(await Ms("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}function uP(){if(ku()!=="server")return null;let e=z_();return e?{...e,available:!0}:{runtime:"server",available:!1,reason:"server runtime is selected but configuration is incomplete (missing url, api key, or project id)"}}function lP(t){return T_(t)?{content:[{type:"text",text:`Server error (${t.kind}${t.status?` ${t.status}`:""}): ${t.message}`}],isError:!0}:{content:[{type:"text",text:`Tool error: ${t instanceof Error?t.message:String(t)}`}],isError:!0}}function Vn(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function Kn(t){let e=uP();if(!e)throw new Ve("transport",`${t} requires CLAUDE_MEM_RUNTIME=server. Current runtime is "worker"; use the existing search/timeline/get_observations tools for worker-mode memory access.`);if(!e.available)throw new Ve("missing_api_key",`${t}: ${e.reason}`);return e}function Jn(t,e){return async r=>{try{return await e(r)}catch(n){let o=n instanceof Error?n:new Error(String(n));return y.warn("SYSTEM",`${t} failed`,void 0,o),lP(n)}}}var dP=Jn("observation_add",async t=>{let e=Kn("observation_add");if(typeof t?.content!="string"||t.content.trim().length===0)throw new Error('observation_add: "content" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,content:t.content,...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.kind!==void 0?{kind:t.kind}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}},o=await e.client.addObservation(n);return Vn(o)});function Zs(t){return typeof t=="string"?js(t):null}var pP=Jn("observation_record_event",async t=>{let e=Kn("observation_record_event");if(typeof t?.eventType!="string"||t.eventType.trim().length===0)throw new Error('observation_record_event: "eventType" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,sourceType:t.sourceType??"api",eventType:t.eventType,occurredAtEpoch:typeof t.occurredAtEpoch=="number"?t.occurredAtEpoch:Date.now(),...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.memorySessionId!==void 0?{memorySessionId:t.memorySessionId}:{},...t.platformSource!==void 0?{platformSource:Zs(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{},...t.generate!==void 0?{generate:t.generate}:{}},o=await e.client.recordEvent(n);return Vn(o)}),fP=Jn("observation_search",async t=>{let e=Kn("observation_search");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_search: "query" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:Zs(t.platformSource)}:{}},o=await e.client.searchObservations(n);return Vn(o)}),mP=Jn("observation_context",async t=>{let e=Kn("observation_context");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_context: "query" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:Zs(t.platformSource)}:{}},o=await e.client.contextObservations(n);return Vn(o)});function hP(t){return Array.isArray(t.projects)?t.projects.map(e=>typeof e=="string"?e.trim():"").filter(Boolean):typeof t.projects=="string"?t.projects.split(",").map(e=>e.trim()).filter(Boolean):typeof t.project=="string"&&t.project.trim().length>0?[t.project.trim()]:[]}async function gP(t){let e=hP(t);return e.length===0?{content:[{type:"text",text:'session_start_context: "project" or "projects" is required'}],isError:!0}:pt("/api/context/inject",{query:{projects:e.join(","),...t.platformSource!==void 0?{platformSource:Zs(t.platformSource)}:{},...t.full!==void 0?{full:t.full}:{},...t.colors!==void 0?{colors:t.colors}:{}},text:!0})}var _P=Jn("observation_generation_status",async t=>{let e=Kn("observation_generation_status"),r=(t?.jobId??t?.job_id??"").trim();if(!r)throw new Error('observation_generation_status: "jobId" is required');let n=await e.client.getJobStatus(r);return Vn(n)});async function yP(){if(await cP())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),aP();try{let t=hu(),e=await d_(t,xu);return e==="dead"&&y.error("SYSTEM","Worker auto-start failed \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running. Check earlier log lines for the specific failure reason (Bun not found, missing worker bundle, port conflict, etc.)."),e!=="dead"}catch(t){return y.error("SYSTEM","Worker auto-start threw \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running.",void 0,t instanceof Error?t:new Error(String(t))),!1}}var C_=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
222
+ `)}var $u=require("node:fs/promises"),Us=require("node:fs"),et=require("node:path"),I_=require("node:os"),O_=require("node:url");var P_="claude";function rP(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function js(t){if(!t)return P_;let e=rP(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:P_}var nP=qt(ue.API_REQUEST),Ve=class extends Error{kind;status;cause;constructor(e,r,n={}){super(r),this.name="ServerClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},Ls=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=oP(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??nP}async startSession(e){let r=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",r)}async recordEvent(e){let r=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(e){if(!e.sessionId)throw new Ve("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async getJobStatus(e){if(!e)throw new Ve("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,type:n,narrative:r,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:wu(e.platformSource)}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:wu(e.platformSource)}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:wu(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,r,n){if(!this.apiKey||!this.apiKey.trim())throw new Ve("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let o=`${this.baseUrl}${r}`,s={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(s.body=JSON.stringify(n));let i;try{i=await fu(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new Ve(l?"timeout":"transport",`Server ${e} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new Ve("http_error",`Server ${e} ${r} returned ${i.status}: ${sP(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 Ve("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:u})}}};function T_(t){return t instanceof Ve}function oP(t){return t.replace(/\/+$/,"")}function wu(t){return typeof t=="string"?js(t):null}function sP(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function ku(){let e=(ws().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function z_(){let t=ws(),e=(...i)=>{for(let a of i){let c=(a??"").trim();if(c.length>0)return c}return""},r=e(t.CLAUDE_MEM_SERVER_URL,t.CLAUDE_MEM_SERVER_BETA_URL),n=e(t.CLAUDE_MEM_SERVER_API_KEY,t.CLAUDE_MEM_SERVER_BETA_API_KEY),o=e(t.CLAUDE_MEM_SERVER_PROJECT_ID,t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!r)return y.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return y.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return y.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let s={serverBaseUrl:r,apiKey:n};return{runtime:"server",client:new Ls(s),projectId:o,serverBaseUrl:r}}var xP={},iP="13.10.0";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var A_=!1,M_=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,et.dirname)((0,O_.fileURLToPath)(xP.url))}catch(t){return A_=!0,y.warn("SYSTEM","mcp-server: failed to resolve module directory from import.meta.url, falling back to process.cwd()",void 0,t instanceof Error?t:new Error(String(t))),process.cwd()}})(),xu=l_()??(0,et.resolve)(M_,"worker-service.cjs");function aP(){A_&&((0,Us.existsSync)(xu)||y.error("SYSTEM","mcp-server: dirname resolution failed (both __dirname and import.meta.url are unavailable). Fell back to process.cwd() and the resolved WORKER_SCRIPT_PATH does not exist. This is the actual problem \u2014 the worker bundle is fine, but mcp-server cannot locate it. Worker auto-start will fail until the dirname-resolution path is fixed.",{workerScriptPath:xu,mcpServerDir:M_}))}async function pt(t,e={}){y.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t});try{let r;if(e.body)r=await Ms(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e.body)});else{let n=new URLSearchParams;for(let[o,s]of Object.entries(e.query??{}))s!=null&&n.append(o,String(s));r=await Ms(`${t}?${n}`)}if(!r.ok){let n=await r.text();throw new Error(`Worker API error (${r.status}): ${n}`)}return y.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),e.text?{content:[{type:"text",text:await r.text()}]}:e.body?{content:[{type:"text",text:JSON.stringify(await r.json(),null,2)}]}:await r.json()}catch(r){return y.error("SYSTEM","\u2190 Worker API error",{endpoint:t},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function cP(){try{return(await Ms("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}function uP(){if(ku()!=="server")return null;let e=z_();return e?{...e,available:!0}:{runtime:"server",available:!1,reason:"server runtime is selected but configuration is incomplete (missing url, api key, or project id)"}}function lP(t){return T_(t)?{content:[{type:"text",text:`Server error (${t.kind}${t.status?` ${t.status}`:""}): ${t.message}`}],isError:!0}:{content:[{type:"text",text:`Tool error: ${t instanceof Error?t.message:String(t)}`}],isError:!0}}function Vn(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function Kn(t){let e=uP();if(!e)throw new Ve("transport",`${t} requires CLAUDE_MEM_RUNTIME=server. Current runtime is "worker"; use the existing search/timeline/get_observations tools for worker-mode memory access.`);if(!e.available)throw new Ve("missing_api_key",`${t}: ${e.reason}`);return e}function Jn(t,e){return async r=>{try{return await e(r)}catch(n){let o=n instanceof Error?n:new Error(String(n));return y.warn("SYSTEM",`${t} failed`,void 0,o),lP(n)}}}var dP=Jn("observation_add",async t=>{let e=Kn("observation_add");if(typeof t?.content!="string"||t.content.trim().length===0)throw new Error('observation_add: "content" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,content:t.content,...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.kind!==void 0?{kind:t.kind}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}},o=await e.client.addObservation(n);return Vn(o)});function Zs(t){return typeof t=="string"?js(t):null}var pP=Jn("observation_record_event",async t=>{let e=Kn("observation_record_event");if(typeof t?.eventType!="string"||t.eventType.trim().length===0)throw new Error('observation_record_event: "eventType" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,sourceType:t.sourceType??"api",eventType:t.eventType,occurredAtEpoch:typeof t.occurredAtEpoch=="number"?t.occurredAtEpoch:Date.now(),...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.memorySessionId!==void 0?{memorySessionId:t.memorySessionId}:{},...t.platformSource!==void 0?{platformSource:Zs(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{},...t.generate!==void 0?{generate:t.generate}:{}},o=await e.client.recordEvent(n);return Vn(o)}),fP=Jn("observation_search",async t=>{let e=Kn("observation_search");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_search: "query" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:Zs(t.platformSource)}:{}},o=await e.client.searchObservations(n);return Vn(o)}),mP=Jn("observation_context",async t=>{let e=Kn("observation_context");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_context: "query" is required');let n={projectId:t.projectId&&t.projectId.trim().length>0?t.projectId:e.projectId,query:t.query,...t.limit!==void 0?{limit:t.limit}:{},...t.platformSource!==void 0?{platformSource:Zs(t.platformSource)}:{}},o=await e.client.contextObservations(n);return Vn(o)});function hP(t){return Array.isArray(t.projects)?t.projects.map(e=>typeof e=="string"?e.trim():"").filter(Boolean):typeof t.projects=="string"?t.projects.split(",").map(e=>e.trim()).filter(Boolean):typeof t.project=="string"&&t.project.trim().length>0?[t.project.trim()]:[]}async function gP(t){let e=hP(t);return e.length===0?{content:[{type:"text",text:'session_start_context: "project" or "projects" is required'}],isError:!0}:pt("/api/context/inject",{query:{projects:e.join(","),...t.platformSource!==void 0?{platformSource:Zs(t.platformSource)}:{},...t.full!==void 0?{full:t.full}:{},...t.colors!==void 0?{colors:t.colors}:{}},text:!0})}var _P=Jn("observation_generation_status",async t=>{let e=Kn("observation_generation_status"),r=(t?.jobId??t?.job_id??"").trim();if(!r)throw new Error('observation_generation_status: "jobId" is required');let n=await e.client.getJobStatus(r);return Vn(n)});async function yP(){if(await cP())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),aP();try{let t=hu(),e=await d_(t,xu);return e==="dead"&&y.error("SYSTEM","Worker auto-start failed \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running. Check earlier log lines for the specific failure reason (Bun not found, missing worker bundle, port conflict, etc.)."),e!=="dead"}catch(t){return y.error("SYSTEM","Worker auto-start threw \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running.",void 0,t instanceof Error?t:new Error(String(t))),!1}}var C_=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
223
223
  1. search(query) \u2192 Get index with IDs (~50-100 tokens/result)
224
224
  2. timeline(anchor=ID) \u2192 Get context around interesting results
225
225
  3. get_observations([IDs]) \u2192 Fetch full details ONLY for filtered IDs
@@ -59,7 +59,7 @@ ${s.stack}`:` ${s.message}`;else if(this.getLevel()===0&&typeof s=="object")try{
59
59
  `,"utf8")}catch(f){let m=f instanceof Error?f:new Error(String(f));T0(`[LOGGER] Failed to write to log file: ${m.message}
60
60
  ${m.stack??""}
61
61
  `)}else T0(p+`
62
- `)}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){A0=e}error(e,r,n,i){this.log(3,e,r,n,i),this.routeErrorToSink(r,n,i)}routeErrorToSink(e,r,n){try{if(!A0||!(n instanceof Error))return;A0(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 O0});function sP(){let t=[];t.push(j0.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=Uee(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=Ws(),r=iP.default.join(e,"plugin","ui");return t.push(j0.default.static(r)),t}function aP(){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 Mp(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 Uee(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 j0,iP,oP=R(()=>{"use strict";j0=Qe(Dp(),1),iP=Qe(require("path"),1);Fn();he()});function cP(t,e,r,n){let i={error:t,message:e};return r&&(i.code=r),n&&(i.details=n),i}function uP(t,e){e.status(404).json(cP("NotFound",`Cannot ${t.method} ${t.path}`))}var ho,lP,dP=R(()=>{"use strict";he();ho=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};lP=(t,e,r,n)=>{let i=t instanceof ho?t.statusCode:500;w.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:t.message,code:t instanceof ho?t.code:void 0},t);let s=cP(t.name||"Error",t.message,t instanceof ho?t.code:void 0,t instanceof ho?t.details:void 0);r.status(i).json(s)}});var pP=R(()=>{"use strict"});function wl(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(zee.has(r)){e[r]=n;continue}C0.has(r)||K0.some(i=>r.startsWith(i))||(e[r]=n)}return e}var K0,C0,zee,Np=R(()=>{"use strict";K0=["CLAUDECODE_","CLAUDE_CODE_"],C0=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID","HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy"]),zee=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS"])});function Gr(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 Lp(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!Gr(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function Yee(t){let e=(0,L0.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:{...wl(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 Wee(t){let e=fP.get(t);if(e&&Date.now()-e.capturedAtMs<Hee)return e.token;let r=null;try{r=Yee(t)}catch(n){w.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:n instanceof Error?n.message:String(n)}),r=null}return fP.set(t,{token:r,capturedAtMs:Date.now()}),r}function q0(t){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux")try{let e=(0,$n.readFileSync)(`/proc/${t}/stat`,"utf-8"),r=e.lastIndexOf(") ");if(r<0)return null;let i=e.slice(r+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(e){return w.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return Wee(t);try{let e=(0,L0.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...wl(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let r=e.stdout.trim();return r.length>0?r:null}catch(e){return w.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}}function Gi(t){if(!t||!Gr(t.pid))return!1;if(!t.startToken)return!0;let e=q0(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 qp(){return P0||(P0=new N0),P0}function D0(){let t=Qee.shift();t&&t()}var L0,$n,M0,Gee,Bee,Vee,Hee,fP,N0,P0,Qee,yo=R(()=>{"use strict";L0=require("child_process");pP();$n=require("fs"),M0=Qe(require("path"),1);he();Np();Fn();Gee=5e3,Bee=1e3,Vee=Ze.supervisorRegistry();Hee=5e3,fP=new Map;N0=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=Vee){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,$n.mkdirSync)(M0.default.dirname(this.registryPath),{recursive:!0}),!(0,$n.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,$n.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"&&D0()}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)Gr(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)D0();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(a=>a.pid)});let i=r.filter(a=>Gr(a.pid));for(let a of i)try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(o){o instanceof Error?o.code!=="ESRCH"&&w.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},o):w.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(o)})}await Lp(i,Gee);let s=i.filter(a=>Gr(a.pid));for(let a of s){w.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(o){o instanceof Error?o.code!=="ESRCH"&&w.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},o):w.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(o)})}}if(s.length>0){let a=Date.now()+Bee;for(;Date.now()<a&&s.filter(c=>Gr(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100))}for(let a of r)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of r)a.type==="sdk"&&D0();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,$n.mkdirSync)(M0.default.dirname(this.registryPath),{recursive:!0}),(0,$n.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},P0=null;Qee=[]});function mP(t){return process.platform==="win32"?Math.round(t*_l.WINDOWS_MULTIPLIER):t}var _l,F0=R(()=>{"use strict";_l={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}});async function bP(t){let e=t.currentPid??process.pid,r=t.pidFilePath??Zee,n=t.registry.getAll(),i=[...n].filter(a=>a.pid!==e).sort((a,o)=>Date.parse(o.startedAt)-Date.parse(a.startedAt));for(let a of i){if(!Gr(a.pid)){t.registry.unregister(a.id);continue}try{await hP(a,"SIGTERM")}catch(o){o instanceof Error?w.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:a.pid,pgid:a.pgid,type:a.type},o):w.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:a.pid,pgid:a.pgid,type:a.type,error:String(o)})}}await Lp(i,5e3);let s=i.filter(a=>Gr(a.pid));for(let a of s)try{await hP(a,"SIGKILL")}catch(o){o instanceof Error?w.debug("SYSTEM","Failed to force kill child process",{pid:a.pid,pgid:a.pgid,type:a.type},o):w.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:a.pid,pgid:a.pgid,type:a.type,error:String(o)})}await Lp(s,1e3);for(let a of i)t.registry.unregister(a.id);for(let a of n.filter(o=>o.pid===e))t.registry.unregister(a.id);ete(r,e),t.registry.pruneDeadEntries()}function ete(t,e,r=!1){if(!(0,go.existsSync)(t))return;let n=null;try{let a=JSON.parse((0,go.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||!Gr(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,go.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)})}}async function hP(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}try{process.kill(r,e)}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}return}if(e==="SIGTERM"){try{process.kill(r,e)}catch(s){if(s instanceof Error&&s.code==="ESRCH")return;throw s}return}let i=["/PID",String(r),"/T"];e==="SIGKILL"&&i.push("/F"),await Xee("taskkill",i,{timeout:_l.POWERSHELL_COMMAND,windowsHide:!0})}var yP,go,gP,Xee,Zee,vP=R(()=>{"use strict";yP=require("child_process"),go=require("fs"),gP=require("util");he();F0();yo();Fn();Xee=(0,gP.promisify)(yP.execFile),Zee=Ze.workerPid()});function tte(){let e=qp().pruneDeadEntries();e>0&&w.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function SP(){bo===null&&(bo=setInterval(tte,EP),bo.unref(),w.debug("SYSTEM","Health checker started",{intervalMs:EP}))}function xP(){bo!==null&&(clearInterval(bo),bo=null,w.debug("SYSTEM","Health checker stopped"))}var EP,bo,wP=R(()=>{"use strict";he();yo();EP=3e4,bo=null});function _P(){return nte}function ite(t={}){let e=t.pidFilePath??rte;if(!(0,Qs.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,Qs.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,Qs.rmSync)(e,{force:!0}),"invalid"}return Gi(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,Qs.rmSync)(e,{force:!0}),"stale")}var Qs,rte,$0,nte,IP=R(()=>{"use strict";Qs=require("fs");he();yo();vP();wP();Fn();rte=Ze.workerPid(),$0=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(),ite({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,SP()}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}xP(),this.stopPromise=bP({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}},nte=new $0(qp())});function J0(t,e,r){t.on("finish",async()=>{try{await r()}finally{process.exit(0)}}),t.json(e)}var kP=R(()=>{"use strict"});function U0(t,e=Date.now){return Math.max(0,Math.floor((e()-t)/1e3))}var TP=R(()=>{"use strict"});function z0(){let t=Array.from(ste.values()).map(e=>({...e})).sort((e,r)=>e.dependency.localeCompare(r.dependency));return{degraded:t.length>0,statuses:t}}var ste,AP=R(()=>{"use strict";ste=new Map});var G0,RP,pAe,OP=R(()=>{"use strict";G0=class{entries=new Map;set(e){if(!e||typeof e!="object")return;let r=e.rateLimitType??"default";this.entries.set(r,{...e,observedAt:Date.now()})}get(e){return e?this.entries.get(e):this.entries.get("default")}getMostRecentByWindow(){return{five_hour:this.entries.get("five_hour"),seven_day:this.entries.get("seven_day"),seven_day_opus:this.entries.get("seven_day_opus"),seven_day_sonnet:this.entries.get("seven_day_sonnet"),overage:this.entries.get("overage")}}get size(){return this.entries.size}},RP=new G0,pAe=900*1e3});function cte(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 CP,PP,V0,Il,DP,ate,B0,jP,ote,KP,Fp,MP=R(()=>{"use strict";CP=Qe(Dp(),1),PP=Qe(require("http"),1),V0=Qe(require("fs"),1),Il=Qe(require("path"),1);eP();he();oP();dP();IP();yo();Np();kP();TP();AP();OP();DP=Il.default.resolve(__dirname,"../skills/mem-search"),ate=Il.default.join(DP,"operations"),B0=Il.default.join(DP,"SKILL.md"),jP=(()=>{try{let t=V0.readFileSync(B0,"utf-8");return w.info("SYSTEM","Cached SKILL.md at boot",{path:B0,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:B0,message:t instanceof Error?t.message:String(t)}),null}})(),ote=(()=>{let t=new Map;for(let e of _0){let r=Il.default.join(ate,`${e}.md`);try{t.set(e,V0.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})(),KP="13.9.3";Fp=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,CP.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=PP.default.createServer(this.app);this.server=s;let a=c=>{s.off("listening",o),i(c)},o=()=>{s.off("error",a),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(uP),this.app.use(lP)}setupMiddleware(){sP().forEach(r=>this.app.use(r))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,r,n)=>{cte(r),n()})}setupCors(){this.app.use(aP())}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():z0();r.status(i?503:200).json({status:i?"degraded":"ok",...this.options.runtime?{runtime:this.options.runtime}:{},version:KP,workerPath:this.options.workerPath,uptime:U0(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:RP.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:KP})}),this.app.get("/api/instructions",(e,r)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!ZC.includes(n))return r.status(400).json({error:"Invalid topic"});if(i&&!_0.includes(i))return r.status(400).json({error:"Invalid operation"});if(i){let a=ote.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(jP===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(jP,n);r.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",Mp,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"})):J0(r,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",Mp,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})):J0(r,{status:"shutting_down"},()=>this.options.onShutdown(n))}),this.app.get("/api/admin/doctor",Mp,(e,r)=>{let a=_P().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:Gr(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=>C0.has(f)||K0.some(m=>f.startsWith(m))),l=U0(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():z0()}})})}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 wr,lte,ute,H0,NP=R(()=>{"use strict";wr=require("zod"),lte=wr.z.enum(["hook","worker","provider","server","api"]),ute=wr.z.object({id:wr.z.string().min(1),projectId:wr.z.string().min(1),serverSessionId:wr.z.string().min(1).nullable().default(null),sourceType:lte,eventType:wr.z.string().min(1),platformSource:wr.z.string().min(1).nullable().default(null),payload:wr.z.unknown().default({}),contentSessionId:wr.z.string().min(1).nullable().default(null),memorySessionId:wr.z.string().min(1).nullable().default(null),occurredAtEpoch:wr.z.number().int().nonnegative(),createdAtEpoch:wr.z.number().int().nonnegative()}),H0=ute.omit({id:!0,createdAtEpoch:!0}).partial({serverSessionId:!0,platformSource:!0,payload:!0,contentSessionId:!0,memorySessionId:!0})});function Ve(){return(0,$p.randomUUID)()}function pt(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function LP(t){return Array.isArray(t)?t:[]}function Ce(t){return typeof t=="number"?t:new Date(t).getTime()}function Br(t){return t==null?null:t instanceof Date?t:new Date(t)}async function ie(t,e,r=[]){return(await t.query(e,r)).rows[0]??null}async function yn(t,e,r){if(!await ie(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 mi(t,e,r,n){if(!await ie(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 kl(t){return JSON.stringify(Y0(t))}function gn(t){return(0,$p.createHash)("sha256").update(kl(t)).digest("hex")}function Y0(t){if(Array.isArray(t))return t.map(Y0);if(t&&typeof t=="object"){let e=t;return Object.keys(e).sort().reduce((r,n)=>(r[n]=Y0(e[n]),r),{})}return t}var $p,bn=R(()=>{"use strict";$p=require("crypto")});function dte(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Bi(t){if(!t)return vo;let e=dte(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:vo}function rr(t){return typeof t!="string"?null:Bi(t)}var vo,Xs=R(()=>{"use strict";vo="claude"});function qP(t){let e=rr(t.platformSource),r=e?[e]:[];return t.sourceEventId?`agent_event:v1:${gn([t.teamId,t.projectId,t.sourceAdapter,...r,t.sourceEventId])}`:`agent_event:v1:${gn([t.teamId,t.projectId,t.sourceAdapter,...r,t.contentSessionId??t.serverSessionId??null,t.eventType,new Date(t.occurredAt).toISOString(),kl(t.payload??{})])}`}function W0(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:pt(t.metadata),occurredAtEpoch:Ce(t.occurred_at),receivedAtEpoch:Ce(t.received_at),createdAtEpoch:Ce(t.created_at)}}var Vr,Eo=R(()=>{"use strict";bn();Xs();Vr=class{constructor(e){this.client=e}client;async create(e){await yn(this.client,e.projectId,e.teamId),e.serverSessionId&&await mi(this.client,e.serverSessionId,e.projectId,e.teamId);let r=qP(e),n=rr(e.platformSource),i=await ie(this.client,`
62
+ `)}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){A0=e}error(e,r,n,i){this.log(3,e,r,n,i),this.routeErrorToSink(r,n,i)}routeErrorToSink(e,r,n){try{if(!A0||!(n instanceof Error))return;A0(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 O0});function sP(){let t=[];t.push(j0.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=Uee(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=Ws(),r=iP.default.join(e,"plugin","ui");return t.push(j0.default.static(r)),t}function aP(){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 Mp(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 Uee(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 j0,iP,oP=R(()=>{"use strict";j0=Qe(Dp(),1),iP=Qe(require("path"),1);Fn();he()});function cP(t,e,r,n){let i={error:t,message:e};return r&&(i.code=r),n&&(i.details=n),i}function uP(t,e){e.status(404).json(cP("NotFound",`Cannot ${t.method} ${t.path}`))}var ho,lP,dP=R(()=>{"use strict";he();ho=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};lP=(t,e,r,n)=>{let i=t instanceof ho?t.statusCode:500;w.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:t.message,code:t instanceof ho?t.code:void 0},t);let s=cP(t.name||"Error",t.message,t instanceof ho?t.code:void 0,t instanceof ho?t.details:void 0);r.status(i).json(s)}});var pP=R(()=>{"use strict"});function wl(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(zee.has(r)){e[r]=n;continue}C0.has(r)||K0.some(i=>r.startsWith(i))||(e[r]=n)}return e}var K0,C0,zee,Np=R(()=>{"use strict";K0=["CLAUDECODE_","CLAUDE_CODE_"],C0=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID","HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy"]),zee=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS"])});function Gr(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 Lp(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!Gr(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function Yee(t){let e=(0,L0.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:{...wl(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 Wee(t){let e=fP.get(t);if(e&&Date.now()-e.capturedAtMs<Hee)return e.token;let r=null;try{r=Yee(t)}catch(n){w.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:n instanceof Error?n.message:String(n)}),r=null}return fP.set(t,{token:r,capturedAtMs:Date.now()}),r}function q0(t){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux")try{let e=(0,$n.readFileSync)(`/proc/${t}/stat`,"utf-8"),r=e.lastIndexOf(") ");if(r<0)return null;let i=e.slice(r+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(e){return w.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return Wee(t);try{let e=(0,L0.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...wl(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let r=e.stdout.trim();return r.length>0?r:null}catch(e){return w.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}}function Gi(t){if(!t||!Gr(t.pid))return!1;if(!t.startToken)return!0;let e=q0(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 qp(){return P0||(P0=new N0),P0}function D0(){let t=Qee.shift();t&&t()}var L0,$n,M0,Gee,Bee,Vee,Hee,fP,N0,P0,Qee,yo=R(()=>{"use strict";L0=require("child_process");pP();$n=require("fs"),M0=Qe(require("path"),1);he();Np();Fn();Gee=5e3,Bee=1e3,Vee=Ze.supervisorRegistry();Hee=5e3,fP=new Map;N0=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=Vee){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,$n.mkdirSync)(M0.default.dirname(this.registryPath),{recursive:!0}),!(0,$n.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,$n.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"&&D0()}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)Gr(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)D0();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(a=>a.pid)});let i=r.filter(a=>Gr(a.pid));for(let a of i)try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(o){o instanceof Error?o.code!=="ESRCH"&&w.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},o):w.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(o)})}await Lp(i,Gee);let s=i.filter(a=>Gr(a.pid));for(let a of s){w.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(o){o instanceof Error?o.code!=="ESRCH"&&w.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},o):w.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(o)})}}if(s.length>0){let a=Date.now()+Bee;for(;Date.now()<a&&s.filter(c=>Gr(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100))}for(let a of r)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of r)a.type==="sdk"&&D0();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,$n.mkdirSync)(M0.default.dirname(this.registryPath),{recursive:!0}),(0,$n.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},P0=null;Qee=[]});function mP(t){return process.platform==="win32"?Math.round(t*_l.WINDOWS_MULTIPLIER):t}var _l,F0=R(()=>{"use strict";_l={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}});async function bP(t){let e=t.currentPid??process.pid,r=t.pidFilePath??Zee,n=t.registry.getAll(),i=[...n].filter(a=>a.pid!==e).sort((a,o)=>Date.parse(o.startedAt)-Date.parse(a.startedAt));for(let a of i){if(!Gr(a.pid)){t.registry.unregister(a.id);continue}try{await hP(a,"SIGTERM")}catch(o){o instanceof Error?w.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:a.pid,pgid:a.pgid,type:a.type},o):w.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:a.pid,pgid:a.pgid,type:a.type,error:String(o)})}}await Lp(i,5e3);let s=i.filter(a=>Gr(a.pid));for(let a of s)try{await hP(a,"SIGKILL")}catch(o){o instanceof Error?w.debug("SYSTEM","Failed to force kill child process",{pid:a.pid,pgid:a.pgid,type:a.type},o):w.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:a.pid,pgid:a.pgid,type:a.type,error:String(o)})}await Lp(s,1e3);for(let a of i)t.registry.unregister(a.id);for(let a of n.filter(o=>o.pid===e))t.registry.unregister(a.id);ete(r,e),t.registry.pruneDeadEntries()}function ete(t,e,r=!1){if(!(0,go.existsSync)(t))return;let n=null;try{let a=JSON.parse((0,go.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||!Gr(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,go.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)})}}async function hP(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}try{process.kill(r,e)}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}return}if(e==="SIGTERM"){try{process.kill(r,e)}catch(s){if(s instanceof Error&&s.code==="ESRCH")return;throw s}return}let i=["/PID",String(r),"/T"];e==="SIGKILL"&&i.push("/F"),await Xee("taskkill",i,{timeout:_l.POWERSHELL_COMMAND,windowsHide:!0})}var yP,go,gP,Xee,Zee,vP=R(()=>{"use strict";yP=require("child_process"),go=require("fs"),gP=require("util");he();F0();yo();Fn();Xee=(0,gP.promisify)(yP.execFile),Zee=Ze.workerPid()});function tte(){let e=qp().pruneDeadEntries();e>0&&w.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function SP(){bo===null&&(bo=setInterval(tte,EP),bo.unref(),w.debug("SYSTEM","Health checker started",{intervalMs:EP}))}function xP(){bo!==null&&(clearInterval(bo),bo=null,w.debug("SYSTEM","Health checker stopped"))}var EP,bo,wP=R(()=>{"use strict";he();yo();EP=3e4,bo=null});function _P(){return nte}function ite(t={}){let e=t.pidFilePath??rte;if(!(0,Qs.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,Qs.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,Qs.rmSync)(e,{force:!0}),"invalid"}return Gi(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,Qs.rmSync)(e,{force:!0}),"stale")}var Qs,rte,$0,nte,IP=R(()=>{"use strict";Qs=require("fs");he();yo();vP();wP();Fn();rte=Ze.workerPid(),$0=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(),ite({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,SP()}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}xP(),this.stopPromise=bP({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}},nte=new $0(qp())});function J0(t,e,r){t.on("finish",async()=>{try{await r()}finally{process.exit(0)}}),t.json(e)}var kP=R(()=>{"use strict"});function U0(t,e=Date.now){return Math.max(0,Math.floor((e()-t)/1e3))}var TP=R(()=>{"use strict"});function z0(){let t=Array.from(ste.values()).map(e=>({...e})).sort((e,r)=>e.dependency.localeCompare(r.dependency));return{degraded:t.length>0,statuses:t}}var ste,AP=R(()=>{"use strict";ste=new Map});var G0,RP,pAe,OP=R(()=>{"use strict";G0=class{entries=new Map;set(e){if(!e||typeof e!="object")return;let r=e.rateLimitType??"default";this.entries.set(r,{...e,observedAt:Date.now()})}get(e){return e?this.entries.get(e):this.entries.get("default")}getMostRecentByWindow(){return{five_hour:this.entries.get("five_hour"),seven_day:this.entries.get("seven_day"),seven_day_opus:this.entries.get("seven_day_opus"),seven_day_sonnet:this.entries.get("seven_day_sonnet"),overage:this.entries.get("overage")}}get size(){return this.entries.size}},RP=new G0,pAe=900*1e3});function cte(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 CP,PP,V0,Il,DP,ate,B0,jP,ote,KP,Fp,MP=R(()=>{"use strict";CP=Qe(Dp(),1),PP=Qe(require("http"),1),V0=Qe(require("fs"),1),Il=Qe(require("path"),1);eP();he();oP();dP();IP();yo();Np();kP();TP();AP();OP();DP=Il.default.resolve(__dirname,"../skills/mem-search"),ate=Il.default.join(DP,"operations"),B0=Il.default.join(DP,"SKILL.md"),jP=(()=>{try{let t=V0.readFileSync(B0,"utf-8");return w.info("SYSTEM","Cached SKILL.md at boot",{path:B0,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:B0,message:t instanceof Error?t.message:String(t)}),null}})(),ote=(()=>{let t=new Map;for(let e of _0){let r=Il.default.join(ate,`${e}.md`);try{t.set(e,V0.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})(),KP="13.10.0";Fp=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,CP.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=PP.default.createServer(this.app);this.server=s;let a=c=>{s.off("listening",o),i(c)},o=()=>{s.off("error",a),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(uP),this.app.use(lP)}setupMiddleware(){sP().forEach(r=>this.app.use(r))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,r,n)=>{cte(r),n()})}setupCors(){this.app.use(aP())}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():z0();r.status(i?503:200).json({status:i?"degraded":"ok",...this.options.runtime?{runtime:this.options.runtime}:{},version:KP,workerPath:this.options.workerPath,uptime:U0(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:RP.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:KP})}),this.app.get("/api/instructions",(e,r)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!ZC.includes(n))return r.status(400).json({error:"Invalid topic"});if(i&&!_0.includes(i))return r.status(400).json({error:"Invalid operation"});if(i){let a=ote.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(jP===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(jP,n);r.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",Mp,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"})):J0(r,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",Mp,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})):J0(r,{status:"shutting_down"},()=>this.options.onShutdown(n))}),this.app.get("/api/admin/doctor",Mp,(e,r)=>{let a=_P().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:Gr(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=>C0.has(f)||K0.some(m=>f.startsWith(m))),l=U0(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():z0()}})})}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 wr,lte,ute,H0,NP=R(()=>{"use strict";wr=require("zod"),lte=wr.z.enum(["hook","worker","provider","server","api"]),ute=wr.z.object({id:wr.z.string().min(1),projectId:wr.z.string().min(1),serverSessionId:wr.z.string().min(1).nullable().default(null),sourceType:lte,eventType:wr.z.string().min(1),platformSource:wr.z.string().min(1).nullable().default(null),payload:wr.z.unknown().default({}),contentSessionId:wr.z.string().min(1).nullable().default(null),memorySessionId:wr.z.string().min(1).nullable().default(null),occurredAtEpoch:wr.z.number().int().nonnegative(),createdAtEpoch:wr.z.number().int().nonnegative()}),H0=ute.omit({id:!0,createdAtEpoch:!0}).partial({serverSessionId:!0,platformSource:!0,payload:!0,contentSessionId:!0,memorySessionId:!0})});function Ve(){return(0,$p.randomUUID)()}function pt(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function LP(t){return Array.isArray(t)?t:[]}function Ce(t){return typeof t=="number"?t:new Date(t).getTime()}function Br(t){return t==null?null:t instanceof Date?t:new Date(t)}async function ie(t,e,r=[]){return(await t.query(e,r)).rows[0]??null}async function yn(t,e,r){if(!await ie(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 mi(t,e,r,n){if(!await ie(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 kl(t){return JSON.stringify(Y0(t))}function gn(t){return(0,$p.createHash)("sha256").update(kl(t)).digest("hex")}function Y0(t){if(Array.isArray(t))return t.map(Y0);if(t&&typeof t=="object"){let e=t;return Object.keys(e).sort().reduce((r,n)=>(r[n]=Y0(e[n]),r),{})}return t}var $p,bn=R(()=>{"use strict";$p=require("crypto")});function dte(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Bi(t){if(!t)return vo;let e=dte(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:vo}function rr(t){return typeof t!="string"?null:Bi(t)}var vo,Xs=R(()=>{"use strict";vo="claude"});function qP(t){let e=rr(t.platformSource),r=e?[e]:[];return t.sourceEventId?`agent_event:v1:${gn([t.teamId,t.projectId,t.sourceAdapter,...r,t.sourceEventId])}`:`agent_event:v1:${gn([t.teamId,t.projectId,t.sourceAdapter,...r,t.contentSessionId??t.serverSessionId??null,t.eventType,new Date(t.occurredAt).toISOString(),kl(t.payload??{})])}`}function W0(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:pt(t.metadata),occurredAtEpoch:Ce(t.occurred_at),receivedAtEpoch:Ce(t.received_at),createdAtEpoch:Ce(t.created_at)}}var Vr,Eo=R(()=>{"use strict";bn();Xs();Vr=class{constructor(e){this.client=e}client;async create(e){await yn(this.client,e.projectId,e.teamId),e.serverSessionId&&await mi(this.client,e.serverSessionId,e.projectId,e.teamId);let r=qP(e),n=rr(e.platformSource),i=await ie(this.client,`
63
63
  INSERT INTO agent_events (
64
64
  id, project_id, team_id, server_session_id, source_adapter,
65
65
  source_event_id, idempotency_key, event_type, platform_source, payload, metadata, occurred_at
@@ -342,7 +342,7 @@ data:
342
342
  )
343
343
  ORDER BY e.occurred_at ASC
344
344
  LIMIT $4
345
- `,[e.serverSessionId,e.projectId,e.teamId,r])).rows.map(sfe)}}});function K2(t){let e=cfe.safeParse(t);if(!e.success)throw new Ou(e.error.issues);return e.data}var Vt,oc,O2,j2,afe,ofe,cfe,Ou,Tm=R(()=>{"use strict";Vt=require("zod"),oc={event:"server_beta_generate_event",summary:"server_beta_generate_summary"},O2={event:"evt",summary:"sum"},j2=Vt.z.object({team_id:Vt.z.string().min(1,"team_id is required"),project_id:Vt.z.string().min(1,"project_id is required"),source_type:Vt.z.enum(["agent_event","session_summary","observation_reindex"]),source_id:Vt.z.string().min(1,"source_id is required"),generation_job_id:Vt.z.string().min(1,"generation_job_id is required"),api_key_id:Vt.z.string().min(1).nullable(),actor_id:Vt.z.string().min(1).nullable(),source_adapter:Vt.z.string().min(1,"source_adapter is required"),request_id:Vt.z.string().min(1).nullable().optional()}),afe=j2.extend({kind:Vt.z.literal("event"),agent_event_id:Vt.z.string().min(1)}),ofe=j2.extend({kind:Vt.z.literal("summary"),server_session_id:Vt.z.string().min(1)}),cfe=Vt.z.discriminatedUnion("kind",[afe,ofe]),Ou=class extends Error{issues;constructor(e){super(`invalid server generation job payload: ${e.map(r=>r.message).join("; ")}`),this.issues=e}}});function cc(t){let e=O2[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,C2.createHash)("sha256").update(r).digest("hex");return`${e}_${n}`}var C2,e_=R(()=>{"use strict";C2=require("crypto");Tm()});function P2(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 D2,Am,M2=R(()=>{"use strict";Eo();Vi();na();he();e_();bn();D2="observation_generate_for_event",Am=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 En(this.options.pool,async o=>{let l=await new Vr(o).create(e);if(!n)return{event:l,outbox:null};let u=new lt(o),d=new $t(o),p=Ve(),f=P2({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:D2,bullmqJobId:cc({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 En(this.options.pool,async a=>{let o=new Vr(a),c=new lt(a),l=new $t(a),u=[];for(let d of e){let p=await o.create(d);if(!n){u.push({event:p,outbox:null});continue}let f=Ve(),m=P2({outboxId:f,event:p,apiKeyId:r.apiKeyId??null,actorId:r.actorId??null,sourceAdapter:r.sourceAdapter??null,requestId:r.requestId??null}),g=await c.create({id:f,projectId:p.projectId,teamId:p.teamId,sourceType:"agent_event",sourceId:p.id,agentEventId:p.id,serverSessionId:p.serverSessionId,jobType:D2,bullmqJobId:cc({kind:"event",team_id:p.teamId,project_id:p.projectId,source_type:"agent_event",source_id:p.id}),payload:m});await l.append({generationJobId:g.id,projectId:g.projectId,teamId:g.teamId,eventType:"queued",statusAfter:g.status,attempt:g.attempts,details:{source:i}}),u.push({event:p,outbox:g})}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??cc({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 t_(t){return cc({kind:"summary",team_id:t.teamId,project_id:t.projectId,source_type:"session_summary",source_id:t.serverSessionId})}function r_(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 N2=R(()=>{"use strict";e_()});var lfe,Rm,L2=R(()=>{"use strict";Vi();na();ds();he();N2();bn();lfe="observation_generate_session_summary",Rm=class{constructor(e){this.options=e}options;async end(e){let r=e.source??"http_post_v1_sessions_end",n=await En(this.options.pool,async s=>{let o=await new Bt(s).endSession({id:e.sessionId,projectId:e.projectId,teamId:e.teamId});if(!o)return{session:null,outbox:null};let c=new lt(s),l=new $t(s),u=Ve(),d=r_({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:lfe,bullmqJobId:t_({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??t_({serverSessionId:e,teamId:r.teamId,projectId:r.projectId}),a=r_({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 q2(t){return`${(process.env.CLAUDE_MEM_PUBLIC_URL??`${t.protocol}://${t.get("host")??"localhost"}`).replace(/\/+$/,"")}/v1/mcp`}function F2(t,e){return`claude mcp add --transport http claude-mem ${t} --header "Authorization: Bearer ${e}"`}async function U2(t,e,r=V2,n=pfe){if(J2.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,J2.includes(a.status))return{job:a,timedOut:!1}}return{job:s,timedOut:!0}}function mfe(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&H2.has(e)?e:null,n=typeof t.query.source_type=="string"?t.query.source_type.trim():"",i=n&&ffe.has(n)?n:null,s=jm(t.query.limit,Y2,1,W2),a=jm(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 z2(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 G2(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&H2.has(e)?e:null,n=jm(t.query.limit,Y2,1,W2),i=jm(t.query.offset,0,0,Number.MAX_SAFE_INTEGER);return{status:r,limit:n,offset:i}}function jm(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 n_(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 hfe(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 yfe(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 ju(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 Ku(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 lc(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 gfe(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 i_(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 B2(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 s_(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 ce,Km,ufe,dfe,$2,V2,pfe,J2,Om,ffe,H2,Y2,W2,Q2=R(()=>{"use strict";ce=require("zod");NP();Eo();Vi();hi();Al();So();he();Up();rS();BM();bN();_2();k2();A2();ga();Km=require("node:crypto");ds();M2();L2();Xs();ufe="api",dfe="13.9.3";$2=ce.z.object({generate:ce.z.union([ce.z.literal("true"),ce.z.literal("false")]).optional(),wait:ce.z.union([ce.z.literal("true"),ce.z.literal("false")]).optional()}),V2=3e4,pfe=100,J2=["completed","failed","cancelled"];Om=class{constructor(e){this.options=e;this.ingestEvents=new Am({pool:e.pool,resolveEventQueue:()=>this.resolveQueue("event")}),this.endSession=new Rm({pool:e.pool,resolveSummaryQueue:()=>this.resolveQueue("summary")})}options;ingestEvents;endSession;getIngestEventsService(){return this.ingestEvents}getEndSessionService(){return this.endSession}setupRoutes(e){e.use("/v1",GM());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(I2(this.options.pool,{windowSec:60,max:s}));let a=Number(process.env.CLAUDE_MEM_MONTHLY_REQUEST_CAP??"0");a>0&&i.push(Zw(this.options.pool,{kind:"request",cap:a})),process.env.CLAUDE_MEM_USAGE_METERING==="1"&&i.push(T2(this.options.pool));let o=[...i],c=Number(process.env.CLAUDE_MEM_MONTHLY_TOKEN_CAP??"0");c>0&&o.push(Zw(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 g=new Date(Date.UTC(new Date().getUTCFullYear(),new Date().getUTCMonth(),1)),b=await new Tr(this.options.pool).summarize({teamId:m,since:g});f.status(200).json({since:g.toISOString(),usage:b})})),e.post("/v1/keys",l,this.handleCreate(ce.z.object({label:ce.z.string().max(120).optional(),expiresInDays:ce.z.number().int().positive().max(365).optional()}),async(p,f,m)=>{let g=this.requireTeamId(p,f);if(!g)return;let b=`cm_${(0,Km.randomBytes)(24).toString("hex")}`,v=(0,Km.createHash)("sha256").update(b).digest("hex"),E=m.expiresInDays?new Date(Date.now()+m.expiresInDays*864e5):null,S=await new Ct(this.options.pool).createApiKey({keyHash:v,teamId:g,projectId:p.authContext?.projectId??null,actorId:p.authContext?.apiKeyId??"api",scopes:["memories:read"],expiresAt:E});m.label;let k=q2(p);f.status(201).json({id:S.id,apiKey:b,scopes:["memories:read"],expiresAt:E?.toISOString()??null,mcpUrl:k,connectCommand:F2(k,b)})})),e.get("/v1/connect",u,this.asyncHandler(async(p,f)=>{if(!this.requireTeamId(p,f))return;let g=q2(p);f.status(200).json({mcpUrl:g,connectCommand:F2(g,"<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=$2.safeParse(p.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let g=m.data.generate!=="false",b=m.data.wait==="true",v=H0.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 k=this.toAgentEventInput(E,S);await this.applyContentSessionLinks([k],[p.body],S);let A,K=null,L="skipped",ee={generate:g,source:"http_post_v1_events",apiKeyId:p.authContext?.apiKeyId??null,actorId:await this.resolveActorId(p),sourceAdapter:k.sourceAdapter,requestId:p.requestId??null};try{let q=await this.ingestEvents.ingestOne(k,ee);A=q.event,K=q.outbox,L=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",A.id,A.projectId,{sourceAdapter:A.sourceAdapter,sourceEventId:A.sourceEventId,eventType:A.eventType,serverSessionId:A.serverSessionId,generationJobId:K?.id??null}),b){let q=K,J=!1;if(K){let te=new lt(this.options.pool),it=await U2(te,K);q=it.job,J=it.timedOut}f.status(201).json({event:Ku(A),generationJob:q?B2(q,L):null,...J?{waitTimedOut:!0}:{}});return}f.status(201).json({event:Ku(A),...K?{generationJob:i_(K,L)}:{}})})),e.post("/v1/events/batch",l,this.asyncHandler(async(p,f)=>{let m=$2.safeParse(p.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let g=m.data.generate!=="false",b=m.data.wait==="true",E=ce.z.array(H0).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 k=yfe(p,E.data);if(k){f.status(k.status).json(k.body);return}let A=E.data.map(q=>this.toAgentEventInput(q,S));await this.applyContentSessionLinks(A,Array.isArray(p.body)?p.body:E.data,S);let K=[],L=[],ee={generate:g,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(A,ee);K=q.map(({event:J,outbox:te})=>({event:J,outbox:te})),L=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:K.length,generationJobIds:K.map(({outbox:q})=>q?.id??null).filter(Boolean)}),b){let q=new lt(this.options.pool),J=Date.now()+V2,te=[];for(let _ of K){if(!_.outbox){te.push({event:_.event,outbox:null,timedOut:!1});continue}let P=Math.max(0,J-Date.now()),O=await U2(q,_.outbox,P);te.push({event:_.event,outbox:O.job,timedOut:O.timedOut})}let it=te.some(_=>_.timedOut);f.status(201).json({events:te.map(({event:_,outbox:P,timedOut:O},j)=>({event:Ku(_),generationJob:P?B2(P,L[j]):null,...O?{waitTimedOut:!0}:{}})),...it?{waitTimedOut:!0}:{}});return}f.status(201).json({events:K.map(({event:q,outbox:J},te)=>({event:Ku(q),...J?{generationJob:i_(J,L[te])}:{}}))})})),e.get("/v1/events/:id",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let g=this.routeParam(p.params.id),b=new Vr(this.options.pool),v=await this.loadScopedById(p,f,{id:g,teamId:m,table:"agent_events",notFound:"Event not found",load:E=>b.getByIdForScope({id:g,projectId:E,teamId:m})});v&&f.json({event:Ku(v)})})),e.get("/v1/events/:id/observations",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let g=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",[g,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(`
345
+ `,[e.serverSessionId,e.projectId,e.teamId,r])).rows.map(sfe)}}});function K2(t){let e=cfe.safeParse(t);if(!e.success)throw new Ou(e.error.issues);return e.data}var Vt,oc,O2,j2,afe,ofe,cfe,Ou,Tm=R(()=>{"use strict";Vt=require("zod"),oc={event:"server_beta_generate_event",summary:"server_beta_generate_summary"},O2={event:"evt",summary:"sum"},j2=Vt.z.object({team_id:Vt.z.string().min(1,"team_id is required"),project_id:Vt.z.string().min(1,"project_id is required"),source_type:Vt.z.enum(["agent_event","session_summary","observation_reindex"]),source_id:Vt.z.string().min(1,"source_id is required"),generation_job_id:Vt.z.string().min(1,"generation_job_id is required"),api_key_id:Vt.z.string().min(1).nullable(),actor_id:Vt.z.string().min(1).nullable(),source_adapter:Vt.z.string().min(1,"source_adapter is required"),request_id:Vt.z.string().min(1).nullable().optional()}),afe=j2.extend({kind:Vt.z.literal("event"),agent_event_id:Vt.z.string().min(1)}),ofe=j2.extend({kind:Vt.z.literal("summary"),server_session_id:Vt.z.string().min(1)}),cfe=Vt.z.discriminatedUnion("kind",[afe,ofe]),Ou=class extends Error{issues;constructor(e){super(`invalid server generation job payload: ${e.map(r=>r.message).join("; ")}`),this.issues=e}}});function cc(t){let e=O2[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,C2.createHash)("sha256").update(r).digest("hex");return`${e}_${n}`}var C2,e_=R(()=>{"use strict";C2=require("crypto");Tm()});function P2(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 D2,Am,M2=R(()=>{"use strict";Eo();Vi();na();he();e_();bn();D2="observation_generate_for_event",Am=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 En(this.options.pool,async o=>{let l=await new Vr(o).create(e);if(!n)return{event:l,outbox:null};let u=new lt(o),d=new $t(o),p=Ve(),f=P2({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:D2,bullmqJobId:cc({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 En(this.options.pool,async a=>{let o=new Vr(a),c=new lt(a),l=new $t(a),u=[];for(let d of e){let p=await o.create(d);if(!n){u.push({event:p,outbox:null});continue}let f=Ve(),m=P2({outboxId:f,event:p,apiKeyId:r.apiKeyId??null,actorId:r.actorId??null,sourceAdapter:r.sourceAdapter??null,requestId:r.requestId??null}),g=await c.create({id:f,projectId:p.projectId,teamId:p.teamId,sourceType:"agent_event",sourceId:p.id,agentEventId:p.id,serverSessionId:p.serverSessionId,jobType:D2,bullmqJobId:cc({kind:"event",team_id:p.teamId,project_id:p.projectId,source_type:"agent_event",source_id:p.id}),payload:m});await l.append({generationJobId:g.id,projectId:g.projectId,teamId:g.teamId,eventType:"queued",statusAfter:g.status,attempt:g.attempts,details:{source:i}}),u.push({event:p,outbox:g})}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??cc({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 t_(t){return cc({kind:"summary",team_id:t.teamId,project_id:t.projectId,source_type:"session_summary",source_id:t.serverSessionId})}function r_(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 N2=R(()=>{"use strict";e_()});var lfe,Rm,L2=R(()=>{"use strict";Vi();na();ds();he();N2();bn();lfe="observation_generate_session_summary",Rm=class{constructor(e){this.options=e}options;async end(e){let r=e.source??"http_post_v1_sessions_end",n=await En(this.options.pool,async s=>{let o=await new Bt(s).endSession({id:e.sessionId,projectId:e.projectId,teamId:e.teamId});if(!o)return{session:null,outbox:null};let c=new lt(s),l=new $t(s),u=Ve(),d=r_({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:lfe,bullmqJobId:t_({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??t_({serverSessionId:e,teamId:r.teamId,projectId:r.projectId}),a=r_({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 q2(t){return`${(process.env.CLAUDE_MEM_PUBLIC_URL??`${t.protocol}://${t.get("host")??"localhost"}`).replace(/\/+$/,"")}/v1/mcp`}function F2(t,e){return`claude mcp add --transport http claude-mem ${t} --header "Authorization: Bearer ${e}"`}async function U2(t,e,r=V2,n=pfe){if(J2.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,J2.includes(a.status))return{job:a,timedOut:!1}}return{job:s,timedOut:!0}}function mfe(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&H2.has(e)?e:null,n=typeof t.query.source_type=="string"?t.query.source_type.trim():"",i=n&&ffe.has(n)?n:null,s=jm(t.query.limit,Y2,1,W2),a=jm(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 z2(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 G2(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&H2.has(e)?e:null,n=jm(t.query.limit,Y2,1,W2),i=jm(t.query.offset,0,0,Number.MAX_SAFE_INTEGER);return{status:r,limit:n,offset:i}}function jm(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 n_(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 hfe(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 yfe(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 ju(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 Ku(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 lc(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 gfe(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 i_(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 B2(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 s_(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 ce,Km,ufe,dfe,$2,V2,pfe,J2,Om,ffe,H2,Y2,W2,Q2=R(()=>{"use strict";ce=require("zod");NP();Eo();Vi();hi();Al();So();he();Up();rS();BM();bN();_2();k2();A2();ga();Km=require("node:crypto");ds();M2();L2();Xs();ufe="api",dfe="13.10.0";$2=ce.z.object({generate:ce.z.union([ce.z.literal("true"),ce.z.literal("false")]).optional(),wait:ce.z.union([ce.z.literal("true"),ce.z.literal("false")]).optional()}),V2=3e4,pfe=100,J2=["completed","failed","cancelled"];Om=class{constructor(e){this.options=e;this.ingestEvents=new Am({pool:e.pool,resolveEventQueue:()=>this.resolveQueue("event")}),this.endSession=new Rm({pool:e.pool,resolveSummaryQueue:()=>this.resolveQueue("summary")})}options;ingestEvents;endSession;getIngestEventsService(){return this.ingestEvents}getEndSessionService(){return this.endSession}setupRoutes(e){e.use("/v1",GM());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(I2(this.options.pool,{windowSec:60,max:s}));let a=Number(process.env.CLAUDE_MEM_MONTHLY_REQUEST_CAP??"0");a>0&&i.push(Zw(this.options.pool,{kind:"request",cap:a})),process.env.CLAUDE_MEM_USAGE_METERING==="1"&&i.push(T2(this.options.pool));let o=[...i],c=Number(process.env.CLAUDE_MEM_MONTHLY_TOKEN_CAP??"0");c>0&&o.push(Zw(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 g=new Date(Date.UTC(new Date().getUTCFullYear(),new Date().getUTCMonth(),1)),b=await new Tr(this.options.pool).summarize({teamId:m,since:g});f.status(200).json({since:g.toISOString(),usage:b})})),e.post("/v1/keys",l,this.handleCreate(ce.z.object({label:ce.z.string().max(120).optional(),expiresInDays:ce.z.number().int().positive().max(365).optional()}),async(p,f,m)=>{let g=this.requireTeamId(p,f);if(!g)return;let b=`cm_${(0,Km.randomBytes)(24).toString("hex")}`,v=(0,Km.createHash)("sha256").update(b).digest("hex"),E=m.expiresInDays?new Date(Date.now()+m.expiresInDays*864e5):null,S=await new Ct(this.options.pool).createApiKey({keyHash:v,teamId:g,projectId:p.authContext?.projectId??null,actorId:p.authContext?.apiKeyId??"api",scopes:["memories:read"],expiresAt:E});m.label;let k=q2(p);f.status(201).json({id:S.id,apiKey:b,scopes:["memories:read"],expiresAt:E?.toISOString()??null,mcpUrl:k,connectCommand:F2(k,b)})})),e.get("/v1/connect",u,this.asyncHandler(async(p,f)=>{if(!this.requireTeamId(p,f))return;let g=q2(p);f.status(200).json({mcpUrl:g,connectCommand:F2(g,"<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=$2.safeParse(p.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let g=m.data.generate!=="false",b=m.data.wait==="true",v=H0.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 k=this.toAgentEventInput(E,S);await this.applyContentSessionLinks([k],[p.body],S);let A,K=null,L="skipped",ee={generate:g,source:"http_post_v1_events",apiKeyId:p.authContext?.apiKeyId??null,actorId:await this.resolveActorId(p),sourceAdapter:k.sourceAdapter,requestId:p.requestId??null};try{let q=await this.ingestEvents.ingestOne(k,ee);A=q.event,K=q.outbox,L=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",A.id,A.projectId,{sourceAdapter:A.sourceAdapter,sourceEventId:A.sourceEventId,eventType:A.eventType,serverSessionId:A.serverSessionId,generationJobId:K?.id??null}),b){let q=K,J=!1;if(K){let te=new lt(this.options.pool),it=await U2(te,K);q=it.job,J=it.timedOut}f.status(201).json({event:Ku(A),generationJob:q?B2(q,L):null,...J?{waitTimedOut:!0}:{}});return}f.status(201).json({event:Ku(A),...K?{generationJob:i_(K,L)}:{}})})),e.post("/v1/events/batch",l,this.asyncHandler(async(p,f)=>{let m=$2.safeParse(p.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let g=m.data.generate!=="false",b=m.data.wait==="true",E=ce.z.array(H0).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 k=yfe(p,E.data);if(k){f.status(k.status).json(k.body);return}let A=E.data.map(q=>this.toAgentEventInput(q,S));await this.applyContentSessionLinks(A,Array.isArray(p.body)?p.body:E.data,S);let K=[],L=[],ee={generate:g,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(A,ee);K=q.map(({event:J,outbox:te})=>({event:J,outbox:te})),L=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:K.length,generationJobIds:K.map(({outbox:q})=>q?.id??null).filter(Boolean)}),b){let q=new lt(this.options.pool),J=Date.now()+V2,te=[];for(let _ of K){if(!_.outbox){te.push({event:_.event,outbox:null,timedOut:!1});continue}let P=Math.max(0,J-Date.now()),O=await U2(q,_.outbox,P);te.push({event:_.event,outbox:O.job,timedOut:O.timedOut})}let it=te.some(_=>_.timedOut);f.status(201).json({events:te.map(({event:_,outbox:P,timedOut:O},j)=>({event:Ku(_),generationJob:P?B2(P,L[j]):null,...O?{waitTimedOut:!0}:{}})),...it?{waitTimedOut:!0}:{}});return}f.status(201).json({events:K.map(({event:q,outbox:J},te)=>({event:Ku(q),...J?{generationJob:i_(J,L[te])}:{}}))})})),e.get("/v1/events/:id",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let g=this.routeParam(p.params.id),b=new Vr(this.options.pool),v=await this.loadScopedById(p,f,{id:g,teamId:m,table:"agent_events",notFound:"Event not found",load:E=>b.getByIdForScope({id:g,projectId:E,teamId:m})});v&&f.json({event:Ku(v)})})),e.get("/v1/events/:id/observations",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let g=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",[g,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(`
346
346
  SELECT o.id, o.project_id, o.team_id, o.server_session_id, o.kind, o.content,
347
347
  o.metadata, o.generation_key, o.created_by_job_id, o.created_at, o.updated_at,
348
348
  os.id AS source_id_pk, os.source_type, os.source_id, os.generation_job_id, os.created_at AS source_created_at
@@ -10,7 +10,7 @@ ${i.stack}`:` ${i.message}`;else if(this.getLevel()===0&&typeof i=="object")try{
10
10
  ${f.stack??""}
11
11
  `)}else Ke(g+`
12
12
  `)}debug(e,t,n,o){this.log(0,e,t,n,o)}info(e,t,n,o){this.log(1,e,t,n,o)}warn(e,t,n,o){this.log(2,e,t,n,o)}setErrorSink(e){Ye=e}error(e,t,n,o){this.log(3,e,t,n,o),this.routeErrorToSink(t,n,o)}routeErrorToSink(e,t,n){try{if(!Ye||!(n instanceof Error))return;Ye(n)}catch{}}dataIn(e,t,n,o){this.info(e,`\u2192 ${t}`,n,o)}dataOut(e,t,n,o){this.info(e,`\u2190 ${t}`,n,o)}success(e,t,n,o){this.info(e,`\u2713 ${t}`,n,o)}failure(e,t,n,o){this.error(e,`\u2717 ${t}`,n,o)}},a=new Je;var L=require("fs"),yt=require("path");function Mt(r){try{if(!(0,L.existsSync)(r))return{offsets:{}};let e=(0,L.readFileSync)(r,"utf-8"),t=JSON.parse(e);return t.offsets?t:{offsets:{}}}catch(e){return a.warn("TRANSCRIPT","Failed to load watch state, starting fresh",{statePath:r,error:e instanceof Error?e.message:String(e)}),{offsets:{}}}}function vt(r,e){try{let t=(0,yt.dirname)(r);(0,L.existsSync)(t)||(0,L.mkdirSync)(t,{recursive:!0}),(0,L.writeFileSync)(r,JSON.stringify(e,null,2))}catch(t){a.warn("TRANSCRIPT","Failed to save watch state",{statePath:r,error:t instanceof Error?t.message:String(t)})}}var ie=H(require("path"),1);var Z=H(require("path"),1),v=require("fs");var Rt=require("node:child_process");function fe(r,e,t){return(0,Rt.spawn)(r,e??[],{windowsHide:!0,...t})}var M={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},$={SUCCESS:0,BLOCKING_ERROR:2};function j(r){return process.platform==="win32"?Math.round(r*M.WINDOWS_MULTIPLIER):r}var C=require("fs"),oe=require("path"),Ve=require("os");var k=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(j(M.API_REQUEST)),CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_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:(0,oe.join)((0,Ve.homedir)(),".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:(0,oe.join)((0,Ve.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_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 t=this.get(e);return parseInt(t,10)}static applyEnvOverrides(e){let t={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(t[n]=process.env[n]);return t}static loadFromFile(e,t=!0){try{if(!(0,C.existsSync)(e)){let c=this.getAllDefaults();try{let u=(0,oe.dirname)(e);(0,C.existsSync)(u)||(0,C.mkdirSync)(u,{recursive:!0}),(0,C.writeFileSync)(e,JSON.stringify(c,null,2),"utf-8"),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 t?this.applyEnvOverrides(c):c}let n=(0,C.readFileSync)(e,"utf-8"),o=JSON.parse(n.replace(/^\uFEFF/,"")),i=o;if(o.env&&typeof o.env=="object"){i=o.env;try{(0,C.writeFileSync)(e,JSON.stringify(i,null,2),"utf-8"),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))}}let s={...this.DEFAULTS};for(let c of Object.keys(this.DEFAULTS))i[c]!==void 0&&(s[c]=i[c]);return t?this.applyEnvOverrides(s):s}catch(n){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,n instanceof Error?n.message:String(n));let o=this.getAllDefaults();return t?this.applyEnvOverrides(o):o}}};var me=null;function x(){return me!==null||(me=k.loadFromFile(ue)),me}var Y=require("fs");var Ze=require("child_process");var O=require("fs"),ze=H(require("path"),1);var nn=["CLAUDECODE_","CLAUDE_CODE_"],on=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID","HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy"]),sn=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS"]);function ge(r=process.env){let e={};for(let[t,n]of Object.entries(r))if(n!==void 0){if(sn.has(t)){e[t]=n;continue}on.has(t)||nn.some(o=>t.startsWith(o))||(e[t]=n)}return e}var an=5e3,cn=1e3,un=E.supervisorRegistry();function b(r){if(!Number.isInteger(r)||r<0||r===0)return!1;try{return process.kill(r,0),!0}catch(e){if(e instanceof Error){let t=e.code;return t==="EPERM"?!0:(a.debug("SYSTEM","PID check failed",{pid:r,code:t}),!1)}return a.warn("SYSTEM","PID check threw non-Error",{pid:r,error:String(e)}),!1}}async function Ee(r,e){let t=Date.now()+e;for(;Date.now()<t;){if(r.every(n=>!b(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}var ln=5e3,At=new Map;function dn(r){let e=(0,Ze.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${r}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...ge(process.env),LC_ALL:"C",LANG:"C"}});if(e.status===0){let t=e.stdout.trim();return t.length>0?t:null}return null}function pn(r){let e=At.get(r);if(e&&Date.now()-e.capturedAtMs<ln)return e.token;let t=null;try{t=dn(r)}catch(n){a.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:r,error:n instanceof Error?n.message:String(n)}),t=null}return At.set(r,{token:t,capturedAtMs:Date.now()}),t}function Ct(r){if(!Number.isInteger(r)||r<=0)return null;if(process.platform==="linux")try{let e=(0,O.readFileSync)(`/proc/${r}/stat`,"utf-8"),t=e.lastIndexOf(") ");if(t<0)return null;let o=e.slice(t+2).split(" ")[19];return o&&/^\d+$/.test(o)?o:null}catch(e){return a.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return pn(r);try{let e=(0,Ze.spawnSync)("ps",["-p",String(r),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...ge(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let t=e.stdout.trim();return t.length>0?t:null}catch(e){return a.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}}function et(r){if(!r||!b(r.pid))return!1;if(!r.startToken)return!0;let e=Ct(r.pid);if(e===null)return!0;let t=e===r.startToken;return t||a.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:r.pid,stored:r.startToken,current:e}),t}var Qe=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=un){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,O.mkdirSync)(ze.default.dirname(this.registryPath),{recursive:!0}),!(0,O.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,O.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[o,i]of Object.entries(n))this.entries.set(o,i)}catch(t){t instanceof Error?a.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},t):a.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(t)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&a.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,t,n){this.initialize(),this.entries.set(e,t),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let t=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),t?.type==="sdk"&&qe()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,t])=>({id:e,...t})).sort((e,t)=>{let n=Date.parse(e.startedAt),o=Date.parse(t.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(o)?0:o)})}getBySession(e){let t=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===t)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,t=0;for(let[n,o]of this.entries)b(o.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,o.type==="sdk"&&(t+=1));e>0&&this.persist();for(let n=0;n<t;n+=1)qe();return e}async reapSession(e){this.initialize();let t=this.getBySession(e);if(t.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;a.info("SYSTEM",`Reaping ${t.length} process(es) for session ${e}`,{sessionId:n,pids:t.map(s=>s.pid)});let o=t.filter(s=>b(s.pid));for(let s of o)try{typeof s.pgid=="number"&&process.platform!=="win32"?process.kill(-s.pgid,"SIGTERM"):process.kill(s.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&a.debug("SYSTEM",`Failed to SIGTERM session process PID ${s.pid}`,{pid:s.pid,pgid:s.pgid},c):a.warn("SYSTEM",`Failed to SIGTERM session process PID ${s.pid} (non-Error)`,{pid:s.pid,pgid:s.pgid,error:String(c)})}await Ee(o,an);let i=o.filter(s=>b(s.pid));for(let s of i){a.warn("SYSTEM",`Session process PID ${s.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:s.pid,pgid:s.pgid,sessionId:n});try{typeof s.pgid=="number"&&process.platform!=="win32"?process.kill(-s.pgid,"SIGKILL"):process.kill(s.pid,"SIGKILL")}catch(c){c instanceof Error?c.code!=="ESRCH"&&a.debug("SYSTEM",`Failed to SIGKILL session process PID ${s.pid}`,{pid:s.pid,pgid:s.pgid},c):a.warn("SYSTEM",`Failed to SIGKILL session process PID ${s.pid} (non-Error)`,{pid:s.pid,pgid:s.pgid,error:String(c)})}}if(i.length>0){let s=Date.now()+cn;for(;Date.now()<s&&i.filter(u=>b(u.pid)).length!==0;)await new Promise(u=>setTimeout(u,100))}for(let s of t)this.entries.delete(s.id),this.runtimeProcesses.delete(s.id);this.persist();for(let s of t)s.type==="sdk"&&qe();return a.info("SYSTEM",`Reaped ${t.length} process(es) for session ${e}`,{sessionId:n,reaped:t.length}),t.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,O.mkdirSync)(ze.default.dirname(this.registryPath),{recursive:!0}),(0,O.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},Xe=null;function Se(){return Xe||(Xe=new Qe),Xe}var fn=[];function qe(){let r=fn.shift();r&&r()}var bt=require("child_process"),z=require("fs"),Ot=require("util");var mn=(0,Ot.promisify)(bt.execFile),gn=E.workerPid();async function It(r){let e=r.currentPid??process.pid,t=r.pidFilePath??gn,n=r.registry.getAll(),o=[...n].filter(s=>s.pid!==e).sort((s,c)=>Date.parse(c.startedAt)-Date.parse(s.startedAt));for(let s of o){if(!b(s.pid)){r.registry.unregister(s.id);continue}try{await kt(s,"SIGTERM")}catch(c){c instanceof Error?a.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:s.pid,pgid:s.pgid,type:s.type},c):a.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:s.pid,pgid:s.pgid,type:s.type,error:String(c)})}}await Ee(o,5e3);let i=o.filter(s=>b(s.pid));for(let s of i)try{await kt(s,"SIGKILL")}catch(c){c instanceof Error?a.debug("SYSTEM","Failed to force kill child process",{pid:s.pid,pgid:s.pgid,type:s.type},c):a.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:s.pid,pgid:s.pgid,type:s.type,error:String(c)})}await Ee(i,1e3);for(let s of o)r.registry.unregister(s.id);for(let s of n.filter(c=>c.pid===e))r.registry.unregister(s.id);Pt(t,e),r.registry.pruneDeadEntries()}function Pt(r,e,t=!1){if(!(0,z.existsSync)(r))return;let n=null;try{let s=JSON.parse((0,z.readFileSync)(r,"utf-8"));n=typeof s.pid=="number"?s.pid:null}catch(s){a.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:r,error:s instanceof Error?s.message:String(s)});return}let o=e!==null&&n===e,i=n===null||!b(n);if(!o&&!(t&&i)){a.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:r,recordedPid:n,currentPid:e});return}try{(0,z.rmSync)(r,{force:!0})}catch(s){s instanceof Error?a.debug("SYSTEM","Failed to remove PID file",{pidFilePath:r},s):a.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:r,error:String(s)})}}async function kt(r,e){let{pid:t,pgid:n}=r;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}try{process.kill(t,e)}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}return}if(e==="SIGTERM"){try{process.kill(t,e)}catch(i){if(i instanceof Error&&i.code==="ESRCH")return;throw i}return}let o=["/PID",String(t),"/T"];e==="SIGKILL"&&o.push("/F"),await mn("taskkill",o,{timeout:M.POWERSHELL_COMMAND,windowsHide:!0})}var Dt=3e4,Q=null;function En(){let e=Se().pruneDeadEntries();e>0&&a.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function Lt(){Q===null&&(Q=setInterval(En,Dt),Q.unref(),a.debug("SYSTEM","Health checker started",{intervalMs:Dt}))}function xt(){Q!==null&&(clearInterval(Q),Q=null,a.debug("SYSTEM","Health checker stopped"))}var Sn=E.workerPid(),tt=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(),_e({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,Lt()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let t=async n=>{if(this.shutdownInitiated){a.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,a.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(o){o instanceof Error?a.error("SYSTEM","Error during shutdown",{},o):a.error("SYSTEM","Error during shutdown (non-Error)",{error:String(o)});try{await this.stop()}catch(i){i instanceof Error?a.debug("SYSTEM","Supervisor shutdown fallback failed",{},i):a.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(i)})}}process.exit(0)};process.on("SIGTERM",()=>{t("SIGTERM")}),process.on("SIGINT",()=>{t("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{a.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{t("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}xt(),this.stopPromise=It({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,t,n){this.registry.register(e,t,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},is=new tt(Se());function _e(r={}){let e=r.pidFilePath??Sn;if(!(0,Y.existsSync)(e))return"missing";let t=null;try{t=JSON.parse((0,Y.readFileSync)(e,"utf-8"))}catch(o){return o instanceof Error?a.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},o):a.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(o)}),(0,Y.rmSync)(e,{force:!0}),"invalid"}return et(t)&&t?((r.logAlive??!0)&&a.info("SYSTEM","Worker already running (PID alive)",{existingPid:t.pid,existingPort:t.port,startedAt:t.startedAt}),"alive"):(a.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:t?.pid,port:t?.port,startedAt:t?.startedAt}),(0,Y.rmSync)(e,{force:!0}),"stale")}var rt=require("path"),Te=require("fs"),Ut=require("crypto");var he=require("fs");function Nt(r,e){if(!(0,he.existsSync)(r))return e;try{return JSON.parse((0,he.readFileSync)(r,"utf-8"))}catch(t){throw new Error(`Corrupt JSON file, refusing to overwrite: ${r}: ${t instanceof Error?t.message:String(t)}`)}}var Ft="telemetry.json";function _n(r){let e=r.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function hn(r,e){if(_n(r))return{enabled:!1,source:"DO_NOT_TRACK"};let t=r.CLAUDE_MEM_TELEMETRY?.toLowerCase();return t==="0"||t==="false"||t==="off"?{enabled:!1,source:"env"}:t==="1"||t==="true"||t==="on"?{enabled:!0,source:"env"}:e?.enabled===!0?{enabled:!0,source:"config"}:e?.enabled===!1?{enabled:!1,source:"config"}:{enabled:!0,source:"default"}}function Wt(r,e){return hn(r,e).enabled}function Tn(){return(0,rt.join)(X(),Ft)}function nt(){let r;try{r=Nt(Tn(),null)}catch(e){let t=e instanceof Error?e:new Error(String(e));return a.warn("SYSTEM","Telemetry: corrupt telemetry.json; treating as no recorded consent",void 0,t),null}return!r||typeof r!="object"||typeof r.installId!="string"||r.enabled!==void 0&&typeof r.enabled!="boolean"?null:{enabled:r.enabled,installId:r.installId,decidedAt:typeof r.decidedAt=="string"?r.decidedAt:""}}function wn(r){let e=X();(0,Te.mkdirSync)(e,{recursive:!0}),(0,Te.writeFileSync)((0,rt.join)(e,Ft),JSON.stringify(r,null,2)+`
13
- `)}function Ht(){let r=nt();if(r?.installId)return r.installId;let e=(0,Ut.randomUUID)();return wn({installId:e,decidedAt:""}),e}var yn=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","install_method","interactive","bun_version","uv_version","claude_code_version","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_invalid_output","top_model","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","observations_created","total_observations_injected","total_tokens_saved_vs_naive"]),$t=200;function Mn(r,e){if(!(!r||typeof r!="object"))for(let t of Object.keys(r)){if(!yn.has(t))continue;let n=r[t];typeof n=="string"?e[t]=n.length>$t?n.slice(0,$t):n:(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(e[t]=n)}}function jt(r){let e={};try{Mn(r,e)}catch{}return e}var ot=H(require("os"),1);var vn="13.9.3",Rn="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",An="https://us.i.posthog.com";function Gt(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||Rn}function Kt(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||An}var Cn=["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"];function Yt(r){let e={};for(let t of Cn)r[t]!==void 0&&(e[t]=r[t]);return e}function kn(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||ot.default.release().toLowerCase().includes("microsoft")}catch(r){let e=r instanceof Error?r:new Error(String(r));return a.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function Bt(){return{version:vn,os:process.platform,os_version:ot.default.release(),is_wsl:kn(),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 bn=2e3;async function Jt(r,e,t){try{if(!Wt(process.env,nt()))return;let n=jt({...Bt(),...e??{}});if(t?.person?n.$set=Yt(n):n.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:r,properties:n})+`
13
+ `)}function Ht(){let r=nt();if(r?.installId)return r.installId;let e=(0,Ut.randomUUID)();return wn({installId:e,decidedAt:""}),e}var yn=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","install_method","interactive","bun_version","uv_version","claude_code_version","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_invalid_output","top_model","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","observations_created","total_observations_injected","total_tokens_saved_vs_naive"]),$t=200;function Mn(r,e){if(!(!r||typeof r!="object"))for(let t of Object.keys(r)){if(!yn.has(t))continue;let n=r[t];typeof n=="string"?e[t]=n.length>$t?n.slice(0,$t):n:(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(e[t]=n)}}function jt(r){let e={};try{Mn(r,e)}catch{}return e}var ot=H(require("os"),1);var vn="13.10.0",Rn="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",An="https://us.i.posthog.com";function Gt(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||Rn}function Kt(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||An}var Cn=["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"];function Yt(r){let e={};for(let t of Cn)r[t]!==void 0&&(e[t]=r[t]);return e}function kn(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||ot.default.release().toLowerCase().includes("microsoft")}catch(r){let e=r instanceof Error?r:new Error(String(r));return a.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function Bt(){return{version:vn,os:process.platform,os_version:ot.default.release(),is_wsl:kn(),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 bn=2e3;async function Jt(r,e,t){try{if(!Wt(process.env,nt()))return;let n=jt({...Bt(),...e??{}});if(t?.person?n.$set=Yt(n):n.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:r,properties:n})+`
14
14
  `);return}let o=Gt(),i=new AbortController,s=setTimeout(()=>i.abort(),bn);try{await On(o,r,n,i.signal)}finally{clearTimeout(s)}}catch{}}async function On(r,e,t,n){await fetch(`${Kt()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:r,event:e,distinct_id:Ht(),properties:t}),signal:n})}var B=H(require("path"),1),Xt=require("os"),N=require("fs"),it=require("child_process");var As=E.dataDir(),Cs=E.workerPid();function Vt(r){return r?/(^|[\\/])bun(\.exe)?$/i.test(r.trim()):!1}function Pn(r,e){let t=e==="win32"?`where ${r}`:`which ${r}`,n;try{n=(0,it.execSync)(t,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(i){return i instanceof Error?a.debug("SYSTEM",`Binary lookup failed for ${r}`,{command:t},i):a.debug("SYSTEM",`Binary lookup failed for ${r}`,{command:t},new Error(String(i))),null}return n.split(/\r?\n/).map(i=>i.trim()).find(i=>i.length>0)||null}var st;function qt(r={}){let e=Object.keys(r).length===0;if(e&&st!==void 0)return st;let t=Dn(r);return e&&t!==null&&(st=t),t}function Dn(r){let e=r.platform??process.platform,t=r.execPath??process.execPath;if(Vt(t))return t;let n=r.env??process.env,o=r.homeDirectory??(0,Xt.homedir)(),i=r.pathExists??N.existsSync,s=r.lookupInPath??Pn,c=e==="win32"?[n.BUN,n.BUN_PATH,B.default.join(o,".bun","bin","bun.exe"),B.default.join(o,".bun","bin","bun"),n.USERPROFILE?B.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?B.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?B.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[n.BUN,n.BUN_PATH,B.default.join(o,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun"];for(let u of c){let d=u?.trim();if(d&&(Vt(d)&&i(d)||d.toLowerCase()==="bun"))return d}return s("bun",e)}var zt=H(require("path"),1);var Qt=require("fs");async function Ln(r,e,t="GET"){let n=await fetch(`http://127.0.0.1:${r}${e}`,{method:t}),o="";try{o=await n.text()}catch{}return{ok:n.ok,statusCode:n.status,body:o}}function xn(){try{let r=zt.default.join(ce,"package.json");return JSON.parse((0,Qt.readFileSync)(r,"utf-8")).version}catch(r){if(r instanceof Error){let e=r.code;if(e==="ENOENT"||e==="EBUSY")return a.debug("SYSTEM","Could not read plugin version (shutdown race)",{code:e}),"unknown";throw r}throw r}}async function Nn(r){try{let e=await Ln(r,"/api/version");return e.ok?JSON.parse(e.body).version:null}catch{return a.debug("SYSTEM","Could not fetch worker version",{}),null}}async function Zt(r){let e=xn(),t=await Nn(r);return!t||e==="unknown"?{matches:!0,pluginVersion:e,workerVersion:t}:{matches:e===t,pluginVersion:e,workerVersion:t}}var we=require("path"),w=require("fs");var Un=6e4;function er(){return(0,we.join)(X(),"spawn.lock")}function tr(){let r=er(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let t=0;t<2;t++)try{return(0,w.mkdirSync)((0,we.dirname)(r),{recursive:!0}),(0,w.writeFileSync)(r,e,{flag:"wx"}),!0}catch(n){let o=n instanceof Error?n:new Error(String(n)),i=o.code;if(i!=="EEXIST")return a.warn("SYSTEM","Spawn lock write failed for a non-contention reason; failing open (spawning unlocked)",{lockPath:r,code:i},o),!0;if(t>0)return!1;let s;try{s=(0,w.statSync)(r).mtimeMs}catch{continue}if(Date.now()-s<=Un)return!1;let c;try{c=(0,w.statSync)(r).mtimeMs}catch{continue}if(c!==s)return!1;try{(0,w.unlinkSync)(r)}catch{return!1}}return!1}function rr(){let r=er();try{if(JSON.parse((0,w.readFileSync)(r,"utf-8")).pid!==process.pid)return;(0,w.unlinkSync)(r)}catch{}}function ar(r,e,t){let n=process.env[r];if(n){let o=parseInt(n,10);if(Number.isFinite(o)&&o>=t.min&&o<=t.max)return o;a.warn("SYSTEM",`Invalid ${r}, using default`,{value:n,min:t.min,max:t.max})}return e}var Ce=ar("CLAUDE_MEM_HEALTH_TIMEOUT_MS",j(M.HEALTH_CHECK),{min:500,max:3e5}),cr=ar("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",j(M.HOOK_READINESS_WAIT),{min:0,max:3e5}),Fn={min:500,max:3e5};async function lt(r,e={},t){try{return await fetch(r,{...e,signal:AbortSignal.timeout(t)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new Error(`Request timed out after ${t}ms`):n}}var ye=null,Me=null,ve=null,Re=null;function Wn(){return Z.default.join(k.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function dt(){return ve!==null||(ve=k.loadFromFile(Wn())),ve}function nr(r,e){if(!r)return null;let t=parseInt(r,10);return Number.isFinite(t)&&t>=e.min&&t<=e.max?t:null}function Hn(r,e,t){let n=process.env[r];if(n!==void 0){let s=nr(n,t);return s!==null?s:(a.warn("SYSTEM",`Invalid ${r}, using default`,{value:n,min:t.min,max:t.max}),e)}let o=dt()[r],i=nr(o,t);return i!==null?i:(a.warn("SYSTEM",`Invalid ${r} in settings.json, using default`,{value:o,min:t.min,max:t.max}),e)}function ur(){if(ye!==null)return ye;let r=dt();return ye=parseInt(r.CLAUDE_MEM_WORKER_PORT,10),ye}function $n(){return Me!==null||(Me=dt().CLAUDE_MEM_WORKER_HOST),Me}function jn(){return Re!==null||(Re=Hn("CLAUDE_MEM_API_TIMEOUT_MS",j(M.API_REQUEST),Fn)),Re}function Gn(r){return`http://${$n()}:${ur()}${r}`}function U(r,e={}){let t=e.method??"GET",n=e.timeoutMs??jn(),o=Gn(r),i={method:t};return e.headers&&(i.headers=e.headers),e.body&&(i.body=e.body),n>0?lt(o,i,n):fetch(o,i)}async function Kn(){return(await U("/api/health",{timeoutMs:Ce})).ok}async function or(){return(await U("/api/readiness",{timeoutMs:Ce})).ok}function Yn(){let r=[Z.default.join(ce,"plugin","scripts","worker-service.cjs"),Z.default.join(process.cwd(),"plugin","scripts","worker-service.cjs")];for(let e of r)if((0,v.existsSync)(e))return e;return null}async function Bn(r){let e=r.backoffMs;for(let t=1;t<=r.attempts;t++){if(await dr())return!0;t<r.attempts&&(await new Promise(n=>setTimeout(n,e)),e*=2)}return!1}async function at(r=cr){if(r<=0)try{return await or()}catch(t){let n=t instanceof Error?t:new Error(String(t));return a.debug("SYSTEM","Worker readiness check threw",{},n),!1}let e=Date.now();for(;Date.now()-e<r;){try{if(await or())return!0}catch(n){a.debug("SYSTEM","Worker readiness check threw",{error:n instanceof Error?n.message:String(n)})}let t=r-(Date.now()-e);if(t<=0)break;await new Promise(n=>setTimeout(n,Math.min(250,t)))}return!1}async function lr(){try{let e=await(await U("/api/health",{timeoutMs:Ce})).json();return typeof e.version=="string"?e.version:null}catch(r){let e=r instanceof Error?r:new Error(String(r));return a.debug("SYSTEM","Worker health-version fetch failed",{},e),null}}async function Jn(r,e=cr){let t=Date.now();for(;Date.now()-t<e;){if(await lr()===r)return!0;let o=e-(Date.now()-t);if(o<=0)break;await new Promise(i=>setTimeout(i,Math.min(500,o)))}return!1}async function ct(r){let e=await lr();e!==null&&e!==r&&a.warn("SYSTEM","Worker is ready but still reports a stale version; not recycling again in this hook invocation (one recycle per hook event)",{pluginVersion:r,workerVersion:e})}async function dr(){let r;try{r=await Kn()}catch(t){return a.debug("SYSTEM","Worker health check threw",{error:t instanceof Error?t.message:String(t)}),!1}if(!r)return!1;let e=_e({logAlive:!1});return e==="missing"||e==="alive"}async function ke(){let r=null;if(await dr()){let{matches:i,pluginVersion:s,workerVersion:c}=await Zt(ur());if(s!=="unknown"&&(r=s),i)return await at()?(r!==null&&await ct(r),!0):(a.warn("SYSTEM","Worker is healthy but not ready; skipping hook API call"),!1);a.info("SYSTEM","Worker version mismatch \u2014 recycling stale worker",{pluginVersion:s,workerVersion:c});let u=!1;try{await U("/api/admin/restart",{method:"POST",timeoutMs:Ce}),u=!0}catch(d){let l=d instanceof Error?d:new Error(String(d));a.debug("SYSTEM","Worker restart request failed; falling through to lazy-spawn",{},l)}if(u){if(await Jn(s))return await at()?(r!==null&&await ct(r),!0):(a.warn("SYSTEM","Recycled worker appeared but did not become ready; skipping hook API call"),!1);a.warn("SYSTEM","No successor worker appeared after recycle; falling through to lazy-spawn",{pluginVersion:s,workerVersion:c})}}let e=qt(),t=Yn();if(!e)return a.warn("SYSTEM","Cannot lazy-spawn worker: Bun runtime not found on PATH"),!1;if(!t)return a.warn("SYSTEM","Cannot lazy-spawn worker: worker-service.cjs not found in plugin/scripts"),!1;let n=tr();try{if(n){a.info("SYSTEM","Worker not running \u2014 lazy-spawning",{runtimePath:e,scriptPath:t});try{fe(e,[t,"--daemon"],{detached:!0,stdio:["ignore","ignore","ignore"]}).unref()}catch(s){return s instanceof Error?a.error("SYSTEM","Lazy-spawn of worker failed",{runtimePath:e,scriptPath:t},s):a.error("SYSTEM","Lazy-spawn of worker failed (non-Error)",{runtimePath:e,scriptPath:t,error:String(s)}),!1}}else a.info("SYSTEM","Another launcher holds the spawn lock \u2014 skipping lazy-spawn and waiting for its worker");if(!await Bn({attempts:6,backoffMs:500}))return a.warn("SYSTEM",n?"Worker port did not open after lazy-spawn within the cold-boot wait (~15s)":"Spawn-lock holder's worker port did not open within the cold-boot wait (~15s)"),!1}finally{n&&rr()}return await at()?(r!==null&&await ct(r),!0):(a.warn("SYSTEM","Worker lazy-spawned but did not become ready before hook readiness timeout"),!1)}var Ae=null;async function Vn(){return Ae!==null||(Ae=await ke()),Ae}var Xn=3;function pr(){return Z.default.join(m,"state")}function fr(){return Z.default.join(pr(),"hook-failures.json")}function qn(r){let e=JSON.parse(r);return{consecutiveFailures:typeof e.consecutiveFailures=="number"&&Number.isFinite(e.consecutiveFailures)?Math.max(0,Math.floor(e.consecutiveFailures)):0,lastFailureAt:typeof e.lastFailureAt=="number"&&Number.isFinite(e.lastFailureAt)?e.lastFailureAt:0}}function mr(){try{return qn((0,v.readFileSync)(fr(),"utf-8"))}catch{return{consecutiveFailures:0,lastFailureAt:0}}}function gr(r){let e=pr(),t=fr(),n=`${t}.tmp`;try{(0,v.existsSync)(e)||(0,v.mkdirSync)(e,{recursive:!0}),(0,v.writeFileSync)(n,JSON.stringify(r),"utf-8"),(0,v.renameSync)(n,t)}catch(o){a.debug("SYSTEM","Failed to persist hook-failure counter",{error:o instanceof Error?o.message:String(o)})}}function zn(){try{let e=x().CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD,t=parseInt(e,10);if(Number.isFinite(t)&&t>=1)return t}catch{}return Xn}var sr=null;async function Qn(){let e={consecutiveFailures:mr().consecutiveFailures+1,lastFailureAt:Date.now()};gr(e);let t=zn();return e.consecutiveFailures>=t&&(e.consecutiveFailures===t&&await Jt("hook_failed",{...sr!==null?{hook_type:sr}:{},error_mode:"worker_unavailable",consecutive_failures:e.consecutiveFailures,threshold_tripped:!0}),Tt(`claude-mem worker unreachable for ${e.consecutiveFailures} consecutive hooks.`)),e.consecutiveFailures}function ir(){mr().consecutiveFailures!==0&&gr({consecutiveFailures:0,lastFailureAt:0})}var ut=Symbol.for("claude-mem/worker-fallback");function be(r){return typeof r=="object"&&r!==null&&r[ut]===!0}async function Oe(r,e,t,n={}){if(!await Vn())return await Qn(),{continue:!0,reason:"worker_unreachable",[ut]:!0};let i={method:e};t!==void 0&&(i.headers={"Content-Type":"application/json"},i.body=JSON.stringify(t)),n.timeoutMs!==void 0&&(i.timeoutMs=n.timeoutMs);let s=await U(r,i);if(!s.ok){let u=await s.text().catch(()=>"");if(ir(),s.status===429||s.status>=500)return a.warn("SYSTEM",`Worker API ${e} ${r} returned ${s.status}; skipping hook API call`,{body:u.substring(0,200)}),{continue:!0,reason:`worker_api_${s.status}`,[ut]:!0};let d=u;try{d=JSON.parse(u)}catch{}return d}ir();let c=await s.text();if(c.length!==0)try{return JSON.parse(c)}catch{return c}}var Sr=require("os"),_r=H(require("path"),1),hr=require("child_process");var Pe=require("fs"),Ie=H(require("path"),1);var se={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function Er(r){let e=Ie.default.join(r,".git"),t;try{t=(0,Pe.statSync)(e)}catch(l){return l instanceof Error&&l.code!=="ENOENT"&&a.warn("GIT","Unexpected error checking .git",{error:l instanceof Error?l.message:String(l)}),se}if(!t.isFile())return se;let n;try{n=(0,Pe.readFileSync)(e,"utf-8").trim()}catch(l){return a.warn("GIT","Failed to read .git file",{error:l instanceof Error?l.message:String(l)}),se}let o=n.match(/^gitdir:\s*(.+)$/);if(!o)return se;let s=o[1].match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!s)return se;let c=s[1],u=Ie.default.basename(r),d=Ie.default.basename(c);return{isWorktree:!0,worktreeName:u,parentRepoPath:c,parentProjectName:d}}function Tr(r){return r==="~"||r.startsWith("~/")?r.replace(/^~/,(0,Sr.homedir)()):r}function Zn(r){try{return(0,hr.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:r,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch(e){let t=e instanceof Error?e:new Error(String(e));return a.debug("PROJECT_NAME","git rev-parse failed, falling back to basename",{dir:r},t),null}}function eo(r){if(!r||r.trim()==="")return a.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:r}),"unknown-project";let e=Tr(r),n=Zn(e)??e,o=_r.default.basename(n);if(o===""){if(process.platform==="win32"){let s=r.match(/^([A-Z]):\\/i);if(s){let u=`drive-${s[1].toUpperCase()}`;return a.info("PROJECT_NAME","Drive root detected",{cwd:r,projectName:u}),u}}return a.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:r}),"unknown-project"}return o}function J(r){let e=eo(r);if(!r)return{primary:e,parent:null,isWorktree:!1,allProjects:[e]};let t=Tr(r),n=Er(t);if(n.isWorktree&&n.parentProjectName){let o=`${n.parentProjectName}/${e}`;return{primary:o,parent:n.parentProjectName,isWorktree:!0,allProjects:[n.parentProjectName,o]}}return{primary:e,parent:null,isWorktree:!1,allProjects:[e]}}var V=require("path");var wr=require("os"),yr=require("path");function to(r){let e=r.startsWith("~")?(0,wr.homedir)()+r.slice(1):r;e=e.replace(/\\/g,"/");let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return t=t.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${t}$`)}function De(r,e){if(!e||!e.trim())return!1;let t=r.replace(/\\/g,"/"),n=(0,yr.basename)(t),o=e.split(",").map(i=>i.trim()).filter(Boolean);for(let i of o)try{let s=to(i);if(s.test(t)||s.test(n))return!0}catch(s){a.warn("PROJECT_NAME","Invalid exclusion pattern",{pattern:i,error:s instanceof Error?s.message:String(s)});continue}return!1}function ro(r,e){let t=(0,V.normalize)(r),n=(0,V.normalize)(e);if(t===n)return!0;let o=(0,V.relative)(n,t);return o.length>0&&!o.startsWith("..")&&!(0,V.isAbsolute)(o)}function Le(r){if(process.env.CLAUDE_MEM_INTERNAL==="1")return!1;if(!r)return!0;if(ro(r,$e))return!1;let e=x();return!De(r,e.CLAUDE_MEM_EXCLUDED_PROJECTS)}var Mr="claude";function no(r){return r.trim().toLowerCase().replace(/\s+/g,"-")}function I(r){if(!r)return Mr;let e=no(r);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:Mr}var Ar=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],vr=new RegExp(`<(${Ar.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g");var Rr=100;function oo(r){let e=Object.fromEntries(Ar.map(o=>[o,0]));vr.lastIndex=0;let t=0,n=r.replace(vr,(o,i)=>(e[i]=(e[i]??0)+1,t+=1,""));return t>Rr&&a.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:t,maxAllowed:Rr,contentLength:r.length}),{stripped:n.trim(),counts:e}}function pt(r){return oo(r).stripped}var so=["task-notification"],io=new RegExp(`^\\s*<(${so.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),ao=256*1024;function Cr(r){return!r||r.length>ao?!1:io.test(r)}var co=j(M.API_REQUEST),F=class extends Error{kind;status;cause;constructor(e,t,n={}){super(t),this.name="ServerClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},xe=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=uo(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??co}async startSession(e){let t=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",t)}async recordEvent(e){let t=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,t)}async endSession(e){if(!e.sessionId)throw new F("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async getJobStatus(e){if(!e)throw new F("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let t=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,type:n,narrative:t,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:ft(e.platformSource)}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:ft(e.platformSource)}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:ft(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,t,n){if(!this.apiKey||!this.apiKey.trim())throw new F("missing_api_key","Server API key is not configured (CLAUDE_MEM_SERVER_API_KEY).");let o=`${this.baseUrl}${t}`,i={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(i.body=JSON.stringify(n));let s;try{s=await lt(o,i,this.timeoutMs)}catch(u){let d=u instanceof Error?u.message:String(u),l=/timed out|timeout/i.test(d);throw new F(l?"timeout":"transport",`Server ${e} ${t} failed: ${d}`,{cause:u})}if(!s.ok){let u=await s.text().catch(()=>"");throw new F("http_error",`Server ${e} ${t} returned ${s.status}: ${lo(u,200)}`,{status:s.status})}let c=await s.text();if(!c||c.length===0)return{};try{return JSON.parse(c)}catch(u){let d=u instanceof Error?u:new Error(String(u));throw new F("invalid_response",`Server ${e} ${t} returned non-JSON response`,{cause:d})}}};function kr(r){return r instanceof F}function uo(r){return r.replace(/\/+$/,"")}function ft(r){return typeof r=="string"?I(r):null}function lo(r,e){return r.length<=e?r:`${r.slice(0,e)}\u2026`}function po(){let e=(x().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function fo(){let r=x(),e=(...s)=>{for(let c of s){let u=(c??"").trim();if(u.length>0)return u}return""},t=e(r.CLAUDE_MEM_SERVER_URL,r.CLAUDE_MEM_SERVER_BETA_URL),n=e(r.CLAUDE_MEM_SERVER_API_KEY,r.CLAUDE_MEM_SERVER_BETA_API_KEY),o=e(r.CLAUDE_MEM_SERVER_PROJECT_ID,r.CLAUDE_MEM_SERVER_BETA_PROJECT_ID);if(!t)return a.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!n)return a.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!o)return a.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let i={serverBaseUrl:t,apiKey:n};return{runtime:"server",client:new xe(i),projectId:o,serverBaseUrl:t}}function br(){if(po()!=="server")return{runtime:"worker"};let r=fo();return r||{runtime:"worker"}}function Or(r,e){a.warn("HOOK",`[server-fallback] reason=${r}`,e??{})}var mo={executeWithWorkerFallback:Oe,isWorkerFallback:be,loadFromFileOnce:x,resolveRuntimeContext:br,logServerFallback:Or,shouldTrackProject:Le},G=mo;var Ir={async execute(r){let{sessionId:e,prompt:t}=r,n=r.cwd??process.cwd();if(!e)return a.warn("HOOK","session-init: No sessionId provided, skipping (Codex CLI or unknown platform)"),{continue:!0,suppressOutput:!0,exitCode:$.SUCCESS};if(!G.shouldTrackProject(n))return a.info("HOOK","Project excluded from tracking",{cwd:n}),{continue:!0,suppressOutput:!0};if(t&&Cr(t))return a.debug("HOOK","session-init: skipping internal protocol payload",{preview:t.slice(0,80)}),{continue:!0,suppressOutput:!0};let o=!t||!t.trim()?"[media prompt]":t,i=J(n).primary,s=I(r.platform),c=G.loadFromFileOnce(),u=String(c.CLAUDE_MEM_SEMANTIC_INJECT).toLowerCase()==="true",d=G.resolveRuntimeContext();if(d.runtime==="server")try{return await go(d,r,e,s,i,o),{continue:!0,suppressOutput:!0}}catch(f){if(kr(f)&&f.isFallbackEligible())G.logServerFallback(f.kind,{status:f.status,message:f.message,route:"/v1/sessions/start"});else return a.error("HOOK","Server session-start failed (non-recoverable)",{error:f instanceof Error?f.message:String(f)}),{continue:!0,suppressOutput:!0,exitCode:$.SUCCESS}}a.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:e,project:i});let l=await G.executeWithWorkerFallback("/api/sessions/init","POST",{contentSessionId:e,project:i,prompt:o,platformSource:s});if(G.isWorkerFallback(l))return{continue:!0,suppressOutput:!0,exitCode:$.SUCCESS};if(typeof l?.sessionDbId!="number")return a.failure("HOOK","Session initialization returned malformed response",{contentSessionId:e,project:i}),{continue:!0,suppressOutput:!0,exitCode:$.SUCCESS};let S=l.sessionDbId,g=l.promptNumber;if(a.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:S,promptNumber:g,skipped:l.skipped,contextInjected:l.contextInjected}),a.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${e} | prompt#=${g} | sessionDbId=${S}`),l.skipped&&l.reason==="private")return a.info("HOOK",`INIT_COMPLETE | sessionDbId=${S} | promptNumber=${g} | skipped=true | reason=private`,{sessionId:S}),{continue:!0,suppressOutput:!0};let _="";if(u&&o&&o.length>=20&&o!=="[media prompt]"){let f=c.CLAUDE_MEM_SEMANTIC_INJECT_LIMIT||"5",W=await G.executeWithWorkerFallback("/api/context/semantic","POST",{q:o,project:i,limit:f,platformSource:s});!G.isWorkerFallback(W)&&W?.context&&(a.debug("HOOK",`Semantic injection: ${W.count} observations for prompt`,{sessionId:S,count:W.count}),_=W.context)}return a.info("HOOK",`INIT_COMPLETE | sessionDbId=${S} | promptNumber=${g} | project=${i}`,{sessionId:S}),_?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:_}}:{continue:!0,suppressOutput:!0}}};async function go(r,e,t,n,o,i){await r.client.startSession({projectId:r.projectId,externalSessionId:t,contentSessionId:t,agentId:e.agentId??null,agentType:e.agentType??null,platformSource:n,metadata:{project:o,prompt:i}}),a.info("HOOK","session-init: server session started",{contentSessionId:t,project:o})}var Pr={async execute(r){let{sessionId:e,cwd:t,filePath:n,edits:o}=r,i=I(r.platform);if(!n)throw new Error("fileEditHandler requires filePath");if(a.dataIn("HOOK",`FileEdit: ${n}`,{editCount:o?.length??0}),!t)throw new Error(`Missing cwd in FileEdit hook input for session ${e}, file ${n}`);if(!Le(t))return a.debug("HOOK","Project excluded from tracking, skipping file edit observation",{cwd:t,filePath:n}),{continue:!0,suppressOutput:!0,exitCode:$.SUCCESS};let s=await Oe("/api/sessions/observations","POST",{contentSessionId:e,platformSource:i,tool_name:"write_file",tool_input:{filePath:n,edits:o},tool_response:{success:!0},cwd:t});return be(s)?{continue:!0,suppressOutput:!0,exitCode:$.SUCCESS}:(a.debug("HOOK","File edit observation sent successfully",{filePath:n}),{continue:!0,suppressOutput:!0})}};var R=require("fs"),Ne=require("path");var ta=E.settings();function Dr(r,e){let t="<claude-mem-context>",n="</claude-mem-context>";if(!r)return`${t}
15
15
  ${e}
16
16
  ${n}`;let o=r.indexOf(t),i=r.indexOf(n);return o!==-1&&i!==-1?r.substring(0,o)+`${t}