claude-mem 13.10.2 → 13.10.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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.10.2",
6
+ "version": "13.10.3",
7
7
  "license": "Apache-2.0",
8
8
  "author": "thedotmack",
9
9
  "homepage": "https://claude-mem.ai",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "13.10.2",
3
+ "version": "13.10.3",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "keywords": [
6
6
  "claude",
@@ -80,9 +80,9 @@
80
80
  "strip-comments:check": "bun scripts/strip-comments.ts --check",
81
81
  "strip-comments:dry-run": "bun scripts/strip-comments.ts --dry-run",
82
82
  "translate-readme": "bun scripts/translate-readme/cli.ts -v -o docs/i18n README.md",
83
- "translate:tier1": "npm run translate-readme -- zh zh-tw ja pt-br ko es de fr",
83
+ "translate:tier1": "npm run translate-readme -- zh zh-tw ja pt pt-br ko es de fr",
84
84
  "translate:tier2": "npm run translate-readme -- he ar ru pl cs nl tr uk",
85
- "translate:tier3": "npm run translate-readme -- vi id th hi bn ro sv",
85
+ "translate:tier3": "npm run translate-readme -- vi tl id th hi bn ur ro sv",
86
86
  "translate:tier4": "npm run translate-readme -- it el hu fi da no",
87
87
  "translate:all": "npm run translate:tier1 & npm run translate:tier2 & npm run translate:tier3 & npm run translate:tier4 & wait",
88
88
  "bug-report": "bun scripts/bug-report/cli.ts",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "13.10.2",
3
+ "version": "13.10.3",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "author": {
6
6
  "name": "Alex Newman"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "13.10.2",
3
+ "version": "13.10.3",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "author": {
6
6
  "name": "Alex Newman",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem-plugin",
3
- "version": "13.10.2",
3
+ "version": "13.10.3",
4
4
  "private": true,
5
5
  "description": "Runtime dependencies for claude-mem bundled hooks",
6
6
  "type": "module",
@@ -222,7 +222,7 @@ ${f}`}let a=s.lineStart;for(let u=s.lineStart-1;u>=0;u--){let l=i[u].trim();if(l
222
222
  ${c}`}pe();var yP=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"]),SP=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),vP=512*1024;async function*D_(t,e,r=20){if(r<=0)return;let n;try{n=await(0,Ur.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!=="."||SP.has(o.name))continue;let s=(0,Gn.join)(t,o.name);if(o.isDirectory())yield*D_(s,e,r-1);else if(o.isFile()){let i=o.name.slice(o.name.lastIndexOf("."));yP.has(i)&&(yield s)}}}async function bP(t){try{let e=await(0,Ur.stat)(t);if(e.size>vP||e.size===0)return null;let r=await(0,Ur.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 j_(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 D_(t,t,20)){if(r.filePattern&&!(0,Gn.relative)(t,g).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let S=await bP(g);S&&i.push({absolutePath:g,relativePath:(0,Gn.relative)(t,g),content:S})}let a=M_(i),c=[],u=[],l=0;for(let[g,S]of a){l+=EP(S);let x=Ks(g.toLowerCase(),s)>0,b=[],$=(k,Se)=>{for(let K of k){let at=0,Ne="",zt=Ks(K.name.toLowerCase(),s);zt>0&&(at+=zt*3,Ne="name match"),K.signature.toLowerCase().includes(o)&&(at+=2,Ne=Ne?`${Ne} + signature`:"signature match"),K.jsdoc&&K.jsdoc.toLowerCase().includes(o)&&(at+=1,Ne=Ne?`${Ne} + jsdoc`:"jsdoc match"),at>0&&(x=!0,b.push({filePath:g,symbolName:Se?`${Se}.${K.name}`:K.name,kind:K.kind,signature:K.signature,jsdoc:K.jsdoc,lineStart:K.lineStart,lineEnd:K.lineEnd,matchReason:Ne})),K.children&&$(K.children,K.name)}};$(S.symbols),x&&(c.push(S),u.push(...b))}u.sort((g,S)=>{let v=Ks(g.symbolName.toLowerCase(),s);return Ks(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 Ks(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 EP(t){let e=t.symbols.length;for(let r of t.symbols)r.children&&(e+=r.children.length);return e}function L_(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(`
223
223
  `);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(`
224
224
  `).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(Lr(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(`
225
- `)}var Du=require("node:fs/promises"),Ys=require("node:fs"),it=require("node:path"),H_=require("node:os"),W_=require("node:url");var U_="claude";function wP(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Js(t){if(!t)return U_;let e=wP(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:U_}var kP=Vt(le.API_REQUEST),Ge=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)}},Gs=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=xP(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??kP}async startSession(e){let r=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",r)}async recordEvent(e){let r=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(e){if(!e.sessionId)throw new Ge("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 Ge("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:Cu(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:Cu(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:Cu(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,r,n){if(!this.apiKey||!this.apiKey.trim())throw new Ge("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 xu(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new Ge(l?"timeout":"transport",`Server ${e} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new Ge("http_error",`Server ${e} ${r} returned ${i.status}: ${$P(c,200)}`,{status:i.status})}let a=await i.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(c){let u=c instanceof Error?c:new Error(String(c));throw new Ge("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:u})}}};function q_(t){return t instanceof Ge}function xP(t){return t.replace(/\/+$/,"")}function Cu(t){return typeof t=="string"?Js(t):null}function $P(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}pe();function Nu(){let e=(Ms().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function Z_(){let t=Ms(),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 Gs(s),projectId:o,serverBaseUrl:r}}var KP={},PP="13.10.2";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var V_=!1,K_=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,it.dirname)((0,W_.fileURLToPath)(KP.url))}catch(t){return V_=!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()}})(),ju=w_()??(0,it.resolve)(K_,"worker-service.cjs");function TP(){V_&&((0,Ys.existsSync)(ju)||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:ju,mcpServerDir:K_}))}async function yt(t,e={}){y.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t});try{let r;if(e.body)r=await Hs(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 Hs(`${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 zP(){try{return(await Hs("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}function RP(){if(Nu()!=="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 IP(t){return q_(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 Bn(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function Xn(t){let e=RP();if(!e)throw new Ge("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 Ge("missing_api_key",`${t}: ${e.reason}`);return e}function Qn(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),IP(n)}}}var OP=Qn("observation_add",async t=>{let e=Xn("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 Bn(o)});function Xs(t){return typeof t=="string"?Js(t):null}var AP=Qn("observation_record_event",async t=>{let e=Xn("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:Xs(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{},...t.generate!==void 0?{generate:t.generate}:{}},o=await e.client.recordEvent(n);return Bn(o)}),MP=Qn("observation_search",async t=>{let e=Xn("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:Xs(t.platformSource)}:{}},o=await e.client.searchObservations(n);return Bn(o)}),CP=Qn("observation_context",async t=>{let e=Xn("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:Xs(t.platformSource)}:{}},o=await e.client.contextObservations(n);return Bn(o)});function NP(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 DP(t){let e=NP(t);return e.length===0?{content:[{type:"text",text:'session_start_context: "project" or "projects" is required'}],isError:!0}:yt("/api/context/inject",{query:{projects:e.join(","),...t.platformSource!==void 0?{platformSource:Xs(t.platformSource)}:{},...t.full!==void 0?{full:t.full}:{},...t.colors!==void 0?{colors:t.colors}:{}},text:!0})}var jP=Qn("observation_generation_status",async t=>{let e=Xn("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 Bn(n)});async function LP(){if(await zP())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),TP();try{let t=Pu(),e=await k_(t,ju);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 J_=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
225
+ `)}var Du=require("node:fs/promises"),Ys=require("node:fs"),it=require("node:path"),H_=require("node:os"),W_=require("node:url");var U_="claude";function wP(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Js(t){if(!t)return U_;let e=wP(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:U_}var kP=Vt(le.API_REQUEST),Ge=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)}},Gs=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=xP(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??kP}async startSession(e){let r=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",r)}async recordEvent(e){let r=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(e){if(!e.sessionId)throw new Ge("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 Ge("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:Cu(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:Cu(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:Cu(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,r,n){if(!this.apiKey||!this.apiKey.trim())throw new Ge("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 xu(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new Ge(l?"timeout":"transport",`Server ${e} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new Ge("http_error",`Server ${e} ${r} returned ${i.status}: ${$P(c,200)}`,{status:i.status})}let a=await i.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(c){let u=c instanceof Error?c:new Error(String(c));throw new Ge("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:u})}}};function q_(t){return t instanceof Ge}function xP(t){return t.replace(/\/+$/,"")}function Cu(t){return typeof t=="string"?Js(t):null}function $P(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}pe();function Nu(){let e=(Ms().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function Z_(){let t=Ms(),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 Gs(s),projectId:o,serverBaseUrl:r}}var KP={},PP="13.10.3";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var V_=!1,K_=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,it.dirname)((0,W_.fileURLToPath)(KP.url))}catch(t){return V_=!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()}})(),ju=w_()??(0,it.resolve)(K_,"worker-service.cjs");function TP(){V_&&((0,Ys.existsSync)(ju)||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:ju,mcpServerDir:K_}))}async function yt(t,e={}){y.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t});try{let r;if(e.body)r=await Hs(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 Hs(`${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 zP(){try{return(await Hs("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}function RP(){if(Nu()!=="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 IP(t){return q_(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 Bn(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function Xn(t){let e=RP();if(!e)throw new Ge("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 Ge("missing_api_key",`${t}: ${e.reason}`);return e}function Qn(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),IP(n)}}}var OP=Qn("observation_add",async t=>{let e=Xn("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 Bn(o)});function Xs(t){return typeof t=="string"?Js(t):null}var AP=Qn("observation_record_event",async t=>{let e=Xn("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:Xs(t.platformSource)}:{},...t.payload!==void 0?{payload:t.payload}:{},...t.generate!==void 0?{generate:t.generate}:{}},o=await e.client.recordEvent(n);return Bn(o)}),MP=Qn("observation_search",async t=>{let e=Xn("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:Xs(t.platformSource)}:{}},o=await e.client.searchObservations(n);return Bn(o)}),CP=Qn("observation_context",async t=>{let e=Xn("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:Xs(t.platformSource)}:{}},o=await e.client.contextObservations(n);return Bn(o)});function NP(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 DP(t){let e=NP(t);return e.length===0?{content:[{type:"text",text:'session_start_context: "project" or "projects" is required'}],isError:!0}:yt("/api/context/inject",{query:{projects:e.join(","),...t.platformSource!==void 0?{platformSource:Xs(t.platformSource)}:{},...t.full!==void 0?{full:t.full}:{},...t.colors!==void 0?{colors:t.colors}:{}},text:!0})}var jP=Qn("observation_generation_status",async t=>{let e=Xn("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 Bn(n)});async function LP(){if(await zP())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),TP();try{let t=Pu(),e=await k_(t,ju);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 J_=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
226
226
  1. search(query) \u2192 Get index with IDs (~50-100 tokens/result)
227
227
  2. timeline(anchor=ID) \u2192 Get context around interesting results
228
228
  3. get_observations([IDs]) \u2192 Fetch full details ONLY for filtered IDs
@@ -62,7 +62,7 @@ ${s.stack}`:` ${s.message}`;else if(this.getLevel()===0&&typeof s=="object")try{
62
62
  `,"utf8")}catch(f){let m=f instanceof Error?f:new Error(String(f));go(`[LOGGER] Failed to write to log file: ${m.message}
63
63
  ${m.stack??""}
64
64
  `)}else go(p+`
65
- `)}debug(e,r,n,i){this.log(0,e,r,n,i)}info(e,r,n,i){this.log(1,e,r,n,i)}warn(e,r,n,i){this.log(2,e,r,n,i)}setErrorSink(e){C0=e}error(e,r,n,i){this.log(3,e,r,n,i),this.routeErrorToSink(r,n,i)}routeErrorToSink(e,r,n){try{if(!C0||!(n instanceof Error))return;C0(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 D0});function pP(){let t=[];t.push(M0.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=Zee(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=Qs(),r=dP.default.join(e,"plugin","ui");return t.push(M0.default.static(r)),t}function fP(){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 Fp(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 Zee(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 M0,dP,mP=R(()=>{"use strict";M0=Xe(qp(),1),dP=Xe(require("path"),1);$n();he()});function hP(t,e,r,n){let i={error:t,message:e};return r&&(i.code=r),n&&(i.details=n),i}function gP(t,e){e.status(404).json(hP("NotFound",`Cannot ${t.method} ${t.path}`))}var bo,yP,bP=R(()=>{"use strict";he();bo=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};yP=(t,e,r,n)=>{let i=t instanceof bo?t.statusCode:500;w.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:t.message,code:t instanceof bo?t.code:void 0},t);let s=hP(t.name||"Error",t.message,t instanceof bo?t.code:void 0,t instanceof bo?t.details:void 0);r.status(i).json(s)}});var ete,tte,rAe,vP=R(()=>{"use strict";ete=new Set([".cmd",".bat"]),tte=new Set([".exe",".com"]),rAe=new Set([...tte,...ete])});function Al(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(nte.has(r)){e[r]=n;continue}L0.has(r)||N0.some(i=>r.startsWith(i))||(e[r]=n)}return e}var N0,L0,rte,nte,$p=R(()=>{"use strict";N0=["CLAUDECODE_","CLAUDE_CODE_"],L0=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),rte=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy","npm_config_noproxy"]),nte=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS",...rte])});function Br(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 Jp(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!Br(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function cte(t){let e=(0,U0.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:{...Al(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 lte(t){let e=EP.get(t);if(e&&Date.now()-e.capturedAtMs<ote)return e.token;let r=null;try{r=cte(t)}catch(n){w.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:n instanceof Error?n.message:String(n)}),r=null}return EP.set(t,{token:r,capturedAtMs:Date.now()}),r}function z0(t){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux")try{let e=(0,Jn.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 lte(t);try{let e=(0,U0.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Al(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||!Br(t.pid))return!1;if(!t.startToken)return!0;let e=z0(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 Up(){return q0||(q0=new J0),q0}function F0(){let t=ute.shift();t&&t()}var U0,Jn,$0,ite,ste,ate,ote,EP,J0,q0,ute,vo=R(()=>{"use strict";U0=require("child_process");vP();Jn=require("fs"),$0=Xe(require("path"),1);he();$p();$n();ite=5e3,ste=1e3,ate=et.supervisorRegistry();ote=5e3,EP=new Map;J0=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=ate){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,Jn.mkdirSync)($0.default.dirname(this.registryPath),{recursive:!0}),!(0,Jn.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Jn.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"&&F0()}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)Br(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)F0();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=>Br(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 Jp(i,ite);let s=i.filter(a=>Br(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()+ste;for(;Date.now()<a&&s.filter(c=>Br(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"&&F0();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,Jn.mkdirSync)($0.default.dirname(this.registryPath),{recursive:!0}),(0,Jn.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},q0=null;ute=[]});function SP(t){return process.platform==="win32"?Math.round(t*Rl.WINDOWS_MULTIPLIER):t}var Rl,G0=R(()=>{"use strict";Rl={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 IP(t){let e=t.currentPid??process.pid,r=t.pidFilePath??pte,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(!Br(a.pid)){t.registry.unregister(a.id);continue}try{await xP(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 Jp(i,5e3);let s=i.filter(a=>Br(a.pid));for(let a of s)try{await xP(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 Jp(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);fte(r,e),t.registry.pruneDeadEntries()}function fte(t,e,r=!1){if(!(0,Eo.existsSync)(t))return;let n=null;try{let a=JSON.parse((0,Eo.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||!Br(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,Eo.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 xP(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 dte("taskkill",i,{timeout:Rl.POWERSHELL_COMMAND,windowsHide:!0})}var wP,Eo,_P,dte,pte,kP=R(()=>{"use strict";wP=require("child_process"),Eo=require("fs"),_P=require("util");he();G0();vo();$n();dte=(0,_P.promisify)(wP.execFile),pte=et.workerPid()});function mte(){let e=Up().pruneDeadEntries();e>0&&w.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function AP(){So===null&&(So=setInterval(mte,TP),So.unref(),w.debug("SYSTEM","Health checker started",{intervalMs:TP}))}function RP(){So!==null&&(clearInterval(So),So=null,w.debug("SYSTEM","Health checker stopped"))}var TP,So,OP=R(()=>{"use strict";he();vo();TP=3e4,So=null});function jP(){return yte}function gte(t={}){let e=t.pidFilePath??hte;if(!(0,Xs.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,Xs.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,Xs.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,Xs.rmSync)(e,{force:!0}),"stale")}var Xs,hte,B0,yte,KP=R(()=>{"use strict";Xs=require("fs");he();vo();kP();OP();$n();hte=et.workerPid(),B0=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(),gte({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,AP()}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}RP(),this.stopPromise=IP({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}},yte=new B0(Up())});function V0(t,e,r){t.on("finish",async()=>{try{await r()}finally{process.exit(0)}}),t.json(e)}var CP=R(()=>{"use strict"});function H0(t,e=Date.now){return Math.max(0,Math.floor((e()-t)/1e3))}var PP=R(()=>{"use strict"});function W0(){let t=Array.from(bte.values()).map(e=>({...e})).sort((e,r)=>e.dependency.localeCompare(r.dependency));return{degraded:t.length>0,statuses:t}}var bte,DP=R(()=>{"use strict";bte=new Map});var Y0,MP,OAe,NP=R(()=>{"use strict";Y0=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}},MP=new Y0,OAe=900*1e3});function Ste(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 FP,$P,X0,Ol,JP,vte,Q0,LP,Ete,qP,zp,UP=R(()=>{"use strict";FP=Xe(qp(),1),$P=Xe(require("http"),1),X0=Xe(require("fs"),1),Ol=Xe(require("path"),1);aP();he();mP();bP();KP();vo();$p();CP();PP();DP();NP();JP=Ol.default.resolve(__dirname,"../skills/mem-search"),vte=Ol.default.join(JP,"operations"),Q0=Ol.default.join(JP,"SKILL.md"),LP=(()=>{try{let t=X0.readFileSync(Q0,"utf-8");return w.info("SYSTEM","Cached SKILL.md at boot",{path:Q0,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:Q0,message:t instanceof Error?t.message:String(t)}),null}})(),Ete=(()=>{let t=new Map;for(let e of R0){let r=Ol.default.join(vte,`${e}.md`);try{t.set(e,X0.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})(),qP="13.10.2";zp=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,FP.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=$P.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(gP),this.app.use(yP)}setupMiddleware(){pP().forEach(r=>this.app.use(r))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,r,n)=>{Ste(r),n()})}setupCors(){this.app.use(fP())}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():W0();r.status(i?503:200).json({status:i?"degraded":"ok",...this.options.runtime?{runtime:this.options.runtime}:{},version:qP,workerPath:this.options.workerPath,uptime:H0(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:MP.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:qP})}),this.app.get("/api/instructions",(e,r)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!sP.includes(n))return r.status(400).json({error:"Invalid topic"});if(i&&!R0.includes(i))return r.status(400).json({error:"Invalid operation"});if(i){let a=Ete.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(LP===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(LP,n);r.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",Fp,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"})):V0(r,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",Fp,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})):V0(r,{status:"shutting_down"},()=>this.options.onShutdown(n))}),this.app.get("/api/admin/doctor",Fp,(e,r)=>{let a=jP().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:Br(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=>L0.has(f)||N0.some(m=>f.startsWith(m))),l=H0(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():W0()}})})}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 _r,xte,wte,Z0,zP=R(()=>{"use strict";_r=require("zod"),xte=_r.z.enum(["hook","worker","provider","server","api"]),wte=_r.z.object({id:_r.z.string().min(1),projectId:_r.z.string().min(1),serverSessionId:_r.z.string().min(1).nullable().default(null),sourceType:xte,eventType:_r.z.string().min(1),platformSource:_r.z.string().min(1).nullable().default(null),payload:_r.z.unknown().default({}),contentSessionId:_r.z.string().min(1).nullable().default(null),memorySessionId:_r.z.string().min(1).nullable().default(null),occurredAtEpoch:_r.z.number().int().nonnegative(),createdAtEpoch:_r.z.number().int().nonnegative()}),Z0=wte.omit({id:!0,createdAtEpoch:!0}).partial({serverSessionId:!0,platformSource:!0,payload:!0,contentSessionId:!0,memorySessionId:!0})});function He(){return(0,Gp.randomUUID)()}function ft(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function GP(t){return Array.isArray(t)?t:[]}function Pe(t){return typeof t=="number"?t:new Date(t).getTime()}function Vr(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 gn(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 jl(t){return JSON.stringify(eE(t))}function bn(t){return(0,Gp.createHash)("sha256").update(jl(t)).digest("hex")}function eE(t){if(Array.isArray(t))return t.map(eE);if(t&&typeof t=="object"){let e=t;return Object.keys(e).sort().reduce((r,n)=>(r[n]=eE(e[n]),r),{})}return t}var Gp,vn=R(()=>{"use strict";Gp=require("crypto")});function _te(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Bi(t){if(!t)return xo;let e=_te(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:xo}function nr(t){return typeof t!="string"?null:Bi(t)}var xo,Zs=R(()=>{"use strict";xo="claude"});function BP(t){let e=nr(t.platformSource),r=e?[e]:[];return t.sourceEventId?`agent_event:v1:${bn([t.teamId,t.projectId,t.sourceAdapter,...r,t.sourceEventId])}`:`agent_event:v1:${bn([t.teamId,t.projectId,t.sourceAdapter,...r,t.contentSessionId??t.serverSessionId??null,t.eventType,new Date(t.occurredAt).toISOString(),jl(t.payload??{})])}`}function tE(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:ft(t.metadata),occurredAtEpoch:Pe(t.occurred_at),receivedAtEpoch:Pe(t.received_at),createdAtEpoch:Pe(t.created_at)}}var Hr,wo=R(()=>{"use strict";vn();Zs();Hr=class{constructor(e){this.client=e}client;async create(e){await gn(this.client,e.projectId,e.teamId),e.serverSessionId&&await mi(this.client,e.serverSessionId,e.projectId,e.teamId);let r=BP(e),n=nr(e.platformSource),i=await ie(this.client,`
65
+ `)}debug(e,r,n,i){this.log(0,e,r,n,i)}info(e,r,n,i){this.log(1,e,r,n,i)}warn(e,r,n,i){this.log(2,e,r,n,i)}setErrorSink(e){C0=e}error(e,r,n,i){this.log(3,e,r,n,i),this.routeErrorToSink(r,n,i)}routeErrorToSink(e,r,n){try{if(!C0||!(n instanceof Error))return;C0(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 D0});function pP(){let t=[];t.push(M0.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=Zee(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=Qs(),r=dP.default.join(e,"plugin","ui");return t.push(M0.default.static(r)),t}function fP(){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 Fp(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 Zee(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 M0,dP,mP=R(()=>{"use strict";M0=Xe(qp(),1),dP=Xe(require("path"),1);$n();he()});function hP(t,e,r,n){let i={error:t,message:e};return r&&(i.code=r),n&&(i.details=n),i}function gP(t,e){e.status(404).json(hP("NotFound",`Cannot ${t.method} ${t.path}`))}var bo,yP,bP=R(()=>{"use strict";he();bo=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};yP=(t,e,r,n)=>{let i=t instanceof bo?t.statusCode:500;w.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:t.message,code:t instanceof bo?t.code:void 0},t);let s=hP(t.name||"Error",t.message,t instanceof bo?t.code:void 0,t instanceof bo?t.details:void 0);r.status(i).json(s)}});var ete,tte,rAe,vP=R(()=>{"use strict";ete=new Set([".cmd",".bat"]),tte=new Set([".exe",".com"]),rAe=new Set([...tte,...ete])});function Al(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(nte.has(r)){e[r]=n;continue}L0.has(r)||N0.some(i=>r.startsWith(i))||(e[r]=n)}return e}var N0,L0,rte,nte,$p=R(()=>{"use strict";N0=["CLAUDECODE_","CLAUDE_CODE_"],L0=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),rte=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy","npm_config_noproxy"]),nte=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS",...rte])});function Br(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 Jp(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!Br(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function cte(t){let e=(0,U0.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:{...Al(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 lte(t){let e=EP.get(t);if(e&&Date.now()-e.capturedAtMs<ote)return e.token;let r=null;try{r=cte(t)}catch(n){w.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:n instanceof Error?n.message:String(n)}),r=null}return EP.set(t,{token:r,capturedAtMs:Date.now()}),r}function z0(t){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux")try{let e=(0,Jn.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 lte(t);try{let e=(0,U0.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Al(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||!Br(t.pid))return!1;if(!t.startToken)return!0;let e=z0(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 Up(){return q0||(q0=new J0),q0}function F0(){let t=ute.shift();t&&t()}var U0,Jn,$0,ite,ste,ate,ote,EP,J0,q0,ute,vo=R(()=>{"use strict";U0=require("child_process");vP();Jn=require("fs"),$0=Xe(require("path"),1);he();$p();$n();ite=5e3,ste=1e3,ate=et.supervisorRegistry();ote=5e3,EP=new Map;J0=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=ate){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,Jn.mkdirSync)($0.default.dirname(this.registryPath),{recursive:!0}),!(0,Jn.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Jn.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"&&F0()}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)Br(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)F0();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=>Br(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 Jp(i,ite);let s=i.filter(a=>Br(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()+ste;for(;Date.now()<a&&s.filter(c=>Br(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"&&F0();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,Jn.mkdirSync)($0.default.dirname(this.registryPath),{recursive:!0}),(0,Jn.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},q0=null;ute=[]});function SP(t){return process.platform==="win32"?Math.round(t*Rl.WINDOWS_MULTIPLIER):t}var Rl,G0=R(()=>{"use strict";Rl={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 IP(t){let e=t.currentPid??process.pid,r=t.pidFilePath??pte,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(!Br(a.pid)){t.registry.unregister(a.id);continue}try{await xP(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 Jp(i,5e3);let s=i.filter(a=>Br(a.pid));for(let a of s)try{await xP(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 Jp(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);fte(r,e),t.registry.pruneDeadEntries()}function fte(t,e,r=!1){if(!(0,Eo.existsSync)(t))return;let n=null;try{let a=JSON.parse((0,Eo.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||!Br(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,Eo.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 xP(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 dte("taskkill",i,{timeout:Rl.POWERSHELL_COMMAND,windowsHide:!0})}var wP,Eo,_P,dte,pte,kP=R(()=>{"use strict";wP=require("child_process"),Eo=require("fs"),_P=require("util");he();G0();vo();$n();dte=(0,_P.promisify)(wP.execFile),pte=et.workerPid()});function mte(){let e=Up().pruneDeadEntries();e>0&&w.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function AP(){So===null&&(So=setInterval(mte,TP),So.unref(),w.debug("SYSTEM","Health checker started",{intervalMs:TP}))}function RP(){So!==null&&(clearInterval(So),So=null,w.debug("SYSTEM","Health checker stopped"))}var TP,So,OP=R(()=>{"use strict";he();vo();TP=3e4,So=null});function jP(){return yte}function gte(t={}){let e=t.pidFilePath??hte;if(!(0,Xs.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,Xs.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,Xs.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,Xs.rmSync)(e,{force:!0}),"stale")}var Xs,hte,B0,yte,KP=R(()=>{"use strict";Xs=require("fs");he();vo();kP();OP();$n();hte=et.workerPid(),B0=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(),gte({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,AP()}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}RP(),this.stopPromise=IP({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}},yte=new B0(Up())});function V0(t,e,r){t.on("finish",async()=>{try{await r()}finally{process.exit(0)}}),t.json(e)}var CP=R(()=>{"use strict"});function H0(t,e=Date.now){return Math.max(0,Math.floor((e()-t)/1e3))}var PP=R(()=>{"use strict"});function W0(){let t=Array.from(bte.values()).map(e=>({...e})).sort((e,r)=>e.dependency.localeCompare(r.dependency));return{degraded:t.length>0,statuses:t}}var bte,DP=R(()=>{"use strict";bte=new Map});var Y0,MP,OAe,NP=R(()=>{"use strict";Y0=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}},MP=new Y0,OAe=900*1e3});function Ste(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 FP,$P,X0,Ol,JP,vte,Q0,LP,Ete,qP,zp,UP=R(()=>{"use strict";FP=Xe(qp(),1),$P=Xe(require("http"),1),X0=Xe(require("fs"),1),Ol=Xe(require("path"),1);aP();he();mP();bP();KP();vo();$p();CP();PP();DP();NP();JP=Ol.default.resolve(__dirname,"../skills/mem-search"),vte=Ol.default.join(JP,"operations"),Q0=Ol.default.join(JP,"SKILL.md"),LP=(()=>{try{let t=X0.readFileSync(Q0,"utf-8");return w.info("SYSTEM","Cached SKILL.md at boot",{path:Q0,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:Q0,message:t instanceof Error?t.message:String(t)}),null}})(),Ete=(()=>{let t=new Map;for(let e of R0){let r=Ol.default.join(vte,`${e}.md`);try{t.set(e,X0.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})(),qP="13.10.3";zp=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,FP.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=$P.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(gP),this.app.use(yP)}setupMiddleware(){pP().forEach(r=>this.app.use(r))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,r,n)=>{Ste(r),n()})}setupCors(){this.app.use(fP())}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():W0();r.status(i?503:200).json({status:i?"degraded":"ok",...this.options.runtime?{runtime:this.options.runtime}:{},version:qP,workerPath:this.options.workerPath,uptime:H0(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:MP.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:qP})}),this.app.get("/api/instructions",(e,r)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!sP.includes(n))return r.status(400).json({error:"Invalid topic"});if(i&&!R0.includes(i))return r.status(400).json({error:"Invalid operation"});if(i){let a=Ete.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(LP===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(LP,n);r.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",Fp,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"})):V0(r,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",Fp,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})):V0(r,{status:"shutting_down"},()=>this.options.onShutdown(n))}),this.app.get("/api/admin/doctor",Fp,(e,r)=>{let a=jP().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:Br(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=>L0.has(f)||N0.some(m=>f.startsWith(m))),l=H0(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():W0()}})})}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 _r,xte,wte,Z0,zP=R(()=>{"use strict";_r=require("zod"),xte=_r.z.enum(["hook","worker","provider","server","api"]),wte=_r.z.object({id:_r.z.string().min(1),projectId:_r.z.string().min(1),serverSessionId:_r.z.string().min(1).nullable().default(null),sourceType:xte,eventType:_r.z.string().min(1),platformSource:_r.z.string().min(1).nullable().default(null),payload:_r.z.unknown().default({}),contentSessionId:_r.z.string().min(1).nullable().default(null),memorySessionId:_r.z.string().min(1).nullable().default(null),occurredAtEpoch:_r.z.number().int().nonnegative(),createdAtEpoch:_r.z.number().int().nonnegative()}),Z0=wte.omit({id:!0,createdAtEpoch:!0}).partial({serverSessionId:!0,platformSource:!0,payload:!0,contentSessionId:!0,memorySessionId:!0})});function He(){return(0,Gp.randomUUID)()}function ft(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function GP(t){return Array.isArray(t)?t:[]}function Pe(t){return typeof t=="number"?t:new Date(t).getTime()}function Vr(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 gn(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 jl(t){return JSON.stringify(eE(t))}function bn(t){return(0,Gp.createHash)("sha256").update(jl(t)).digest("hex")}function eE(t){if(Array.isArray(t))return t.map(eE);if(t&&typeof t=="object"){let e=t;return Object.keys(e).sort().reduce((r,n)=>(r[n]=eE(e[n]),r),{})}return t}var Gp,vn=R(()=>{"use strict";Gp=require("crypto")});function _te(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Bi(t){if(!t)return xo;let e=_te(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:xo}function nr(t){return typeof t!="string"?null:Bi(t)}var xo,Zs=R(()=>{"use strict";xo="claude"});function BP(t){let e=nr(t.platformSource),r=e?[e]:[];return t.sourceEventId?`agent_event:v1:${bn([t.teamId,t.projectId,t.sourceAdapter,...r,t.sourceEventId])}`:`agent_event:v1:${bn([t.teamId,t.projectId,t.sourceAdapter,...r,t.contentSessionId??t.serverSessionId??null,t.eventType,new Date(t.occurredAt).toISOString(),jl(t.payload??{})])}`}function tE(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:ft(t.metadata),occurredAtEpoch:Pe(t.occurred_at),receivedAtEpoch:Pe(t.received_at),createdAtEpoch:Pe(t.created_at)}}var Hr,wo=R(()=>{"use strict";vn();Zs();Hr=class{constructor(e){this.client=e}client;async create(e){await gn(this.client,e.projectId,e.teamId),e.serverSessionId&&await mi(this.client,e.serverSessionId,e.projectId,e.teamId);let r=BP(e),n=nr(e.platformSource),i=await ie(this.client,`
66
66
  INSERT INTO agent_events (
67
67
  id, project_id, team_id, server_session_id, source_adapter,
68
68
  source_event_id, idempotency_key, event_type, platform_source, payload, metadata, occurred_at
@@ -345,7 +345,7 @@ data:
345
345
  )
346
346
  ORDER BY e.occurred_at ASC
347
347
  LIMIT $4
348
- `,[e.serverSessionId,e.projectId,e.teamId,r])).rows.map(bfe)}}});function q2(t){let e=Sfe.safeParse(t);if(!e.success)throw new Du(e.error.issues);return e.data}var Ht,uc,N2,L2,vfe,Efe,Sfe,Du,jm=R(()=>{"use strict";Ht=require("zod"),uc={event:"server_beta_generate_event",summary:"server_beta_generate_summary"},N2={event:"evt",summary:"sum"},L2=Ht.z.object({team_id:Ht.z.string().min(1,"team_id is required"),project_id:Ht.z.string().min(1,"project_id is required"),source_type:Ht.z.enum(["agent_event","session_summary","observation_reindex"]),source_id:Ht.z.string().min(1,"source_id is required"),generation_job_id:Ht.z.string().min(1,"generation_job_id is required"),api_key_id:Ht.z.string().min(1).nullable(),actor_id:Ht.z.string().min(1).nullable(),source_adapter:Ht.z.string().min(1,"source_adapter is required"),request_id:Ht.z.string().min(1).nullable().optional()}),vfe=L2.extend({kind:Ht.z.literal("event"),agent_event_id:Ht.z.string().min(1)}),Efe=L2.extend({kind:Ht.z.literal("summary"),server_session_id:Ht.z.string().min(1)}),Sfe=Ht.z.discriminatedUnion("kind",[vfe,Efe]),Du=class extends Error{issues;constructor(e){super(`invalid server generation job payload: ${e.map(r=>r.message).join("; ")}`),this.issues=e}}});function dc(t){let e=N2[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,F2.createHash)("sha256").update(r).digest("hex");return`${e}_${n}`}var F2,s_=R(()=>{"use strict";F2=require("crypto");jm()});function $2(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 J2,Km,U2=R(()=>{"use strict";wo();Vi();ia();he();s_();vn();J2="observation_generate_for_event",Km=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 Sn(this.options.pool,async o=>{let l=await new Hr(o).create(e);if(!n)return{event:l,outbox:null};let u=new ut(o),d=new Jt(o),p=He(),f=$2({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:J2,bullmqJobId:dc({kind:"event",team_id:l.teamId,project_id:l.projectId,source_type:"agent_event",source_id:l.id}),payload:f});return await d.append({generationJobId:m.id,projectId:m.projectId,teamId:m.teamId,eventType:"queued",statusAfter:m.status,attempt:m.attempts,details:{source:i}}),{event:l,outbox:m}}),a="skipped";return s.outbox&&(a=await this.publishEventJob(s.event,s.outbox)),{event:s.event,outbox:s.outbox,enqueueState:a}}async ingestBatch(e,r={}){let n=r.generate??!0,i=r.source??"http_post_v1_events_batch",s=await Sn(this.options.pool,async a=>{let o=new Hr(a),c=new ut(a),l=new Jt(a),u=[];for(let d of e){let p=await o.create(d);if(!n){u.push({event:p,outbox:null});continue}let f=He(),m=$2({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:J2,bullmqJobId:dc({kind:"event",team_id:p.teamId,project_id:p.projectId,source_type:"agent_event",source_id:p.id}),payload:m});await l.append({generationJobId: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??dc({kind:"event",team_id:e.teamId,project_id:e.projectId,source_type:"agent_event",source_id:e.id});try{return await n.add(i,r.payload),"enqueued"}catch(s){return w.warn("SYSTEM","failed to publish event generation job to BullMQ",{outboxId:r.id,error:s instanceof Error?s.message:String(s)}),"queued_only"}}}});function a_(t){return dc({kind:"summary",team_id:t.teamId,project_id:t.projectId,source_type:"session_summary",source_id:t.serverSessionId})}function o_(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 z2=R(()=>{"use strict";s_()});var xfe,Cm,G2=R(()=>{"use strict";Vi();ia();ds();he();z2();vn();xfe="observation_generate_session_summary",Cm=class{constructor(e){this.options=e}options;async end(e){let r=e.source??"http_post_v1_sessions_end",n=await Sn(this.options.pool,async s=>{let o=await new Vt(s).endSession({id:e.sessionId,projectId:e.projectId,teamId:e.teamId});if(!o)return{session:null,outbox:null};let c=new ut(s),l=new Jt(s),u=He(),d=o_({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:xfe,bullmqJobId:a_({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??a_({serverSessionId:e,teamId:r.teamId,projectId:r.projectId}),a=o_({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 B2(t){return`${(process.env.CLAUDE_MEM_PUBLIC_URL??`${t.protocol}://${t.get("host")??"localhost"}`).replace(/\/+$/,"")}/v1/mcp`}function V2(t,e){return`claude mcp add --transport http claude-mem ${t} --header "Authorization: Bearer ${e}"`}async function Y2(t,e,r=e4,n=Ife){if(W2.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,W2.includes(a.status))return{job:a,timedOut:!1}}return{job:s,timedOut:!0}}function Tfe(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&t4.has(e)?e:null,n=typeof t.query.source_type=="string"?t.query.source_type.trim():"",i=n&&kfe.has(n)?n:null,s=Dm(t.query.limit,r4,1,n4),a=Dm(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 Q2(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 X2(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&t4.has(e)?e:null,n=Dm(t.query.limit,r4,1,n4),i=Dm(t.query.offset,0,0,Number.MAX_SAFE_INTEGER);return{status:r,limit:n,offset:i}}function Dm(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 c_(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 Afe(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 Rfe(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 Mu(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 Nu(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 pc(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 Ofe(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 l_(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 Z2(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 u_(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,Mm,wfe,_fe,H2,e4,Ife,W2,Pm,kfe,t4,r4,n4,i4=R(()=>{"use strict";ce=require("zod");zP();wo();Vi();hi();Cl();_o();he();Vp();oS();ZM();IN();j2();C2();D2();ba();Mm=require("node:crypto");ds();U2();G2();Zs();wfe="api",_fe="13.10.2";H2=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()}),e4=3e4,Ife=100,W2=["completed","failed","cancelled"];Pm=class{constructor(e){this.options=e;this.ingestEvents=new Km({pool:e.pool,resolveEventQueue:()=>this.resolveQueue("event")}),this.endSession=new Cm({pool:e.pool,resolveSummaryQueue:()=>this.resolveQueue("summary")})}options;ingestEvents;endSession;getIngestEventsService(){return this.ingestEvents}getEndSessionService(){return this.endSession}setupRoutes(e){e.use("/v1",XM());let r=ta(this.options.pool,{authMode:this.options.authMode,allowLocalDevBypass:this.options.allowLocalDevBypass,requiredScopes:["memories:write"]}),n=ta(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(K2(this.options.pool,{windowSec:60,max:s}));let a=Number(process.env.CLAUDE_MEM_MONTHLY_REQUEST_CAP??"0");a>0&&i.push(i_(this.options.pool,{kind:"request",cap:a})),process.env.CLAUDE_MEM_USAGE_METERING==="1"&&i.push(P2(this.options.pool));let o=[...i],c=Number(process.env.CLAUDE_MEM_MONTHLY_TOKEN_CAP??"0");c>0&&o.push(i_(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 Ar(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,Mm.randomBytes)(24).toString("hex")}`,v=(0,Mm.createHash)("sha256").update(b).digest("hex"),E=m.expiresInDays?new Date(Date.now()+m.expiresInDays*864e5):null,S=await new Pt(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=B2(p);f.status(201).json({id:S.id,apiKey:b,scopes:["memories:read"],expiresAt:E?.toISOString()??null,mcpUrl:k,connectCommand:V2(k,b)})})),e.get("/v1/connect",u,this.asyncHandler(async(p,f)=>{if(!this.requireTeamId(p,f))return;let g=B2(p);f.status(200).json({mcpUrl:g,connectCommand:V2(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=H2.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=Z0.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 ut(this.options.pool),st=await Y2(te,K);q=st.job,J=st.timedOut}f.status(201).json({event:Nu(A),generationJob:q?Z2(q,L):null,...J?{waitTimedOut:!0}:{}});return}f.status(201).json({event:Nu(A),...K?{generationJob:l_(K,L)}:{}})})),e.post("/v1/events/batch",l,this.asyncHandler(async(p,f)=>{let m=H2.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(Z0).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=Rfe(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 ut(this.options.pool),J=Date.now()+e4,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 Y2(q,_.outbox,P);te.push({event:_.event,outbox:O.job,timedOut:O.timedOut})}let st=te.some(_=>_.timedOut);f.status(201).json({events:te.map(({event:_,outbox:P,timedOut:O},j)=>({event:Nu(_),generationJob:P?Z2(P,L[j]):null,...O?{waitTimedOut:!0}:{}})),...st?{waitTimedOut:!0}:{}});return}f.status(201).json({events:K.map(({event:q,outbox:J},te)=>({event:Nu(q),...J?{generationJob:l_(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 Hr(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:Nu(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(`
348
+ `,[e.serverSessionId,e.projectId,e.teamId,r])).rows.map(bfe)}}});function q2(t){let e=Sfe.safeParse(t);if(!e.success)throw new Du(e.error.issues);return e.data}var Ht,uc,N2,L2,vfe,Efe,Sfe,Du,jm=R(()=>{"use strict";Ht=require("zod"),uc={event:"server_beta_generate_event",summary:"server_beta_generate_summary"},N2={event:"evt",summary:"sum"},L2=Ht.z.object({team_id:Ht.z.string().min(1,"team_id is required"),project_id:Ht.z.string().min(1,"project_id is required"),source_type:Ht.z.enum(["agent_event","session_summary","observation_reindex"]),source_id:Ht.z.string().min(1,"source_id is required"),generation_job_id:Ht.z.string().min(1,"generation_job_id is required"),api_key_id:Ht.z.string().min(1).nullable(),actor_id:Ht.z.string().min(1).nullable(),source_adapter:Ht.z.string().min(1,"source_adapter is required"),request_id:Ht.z.string().min(1).nullable().optional()}),vfe=L2.extend({kind:Ht.z.literal("event"),agent_event_id:Ht.z.string().min(1)}),Efe=L2.extend({kind:Ht.z.literal("summary"),server_session_id:Ht.z.string().min(1)}),Sfe=Ht.z.discriminatedUnion("kind",[vfe,Efe]),Du=class extends Error{issues;constructor(e){super(`invalid server generation job payload: ${e.map(r=>r.message).join("; ")}`),this.issues=e}}});function dc(t){let e=N2[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,F2.createHash)("sha256").update(r).digest("hex");return`${e}_${n}`}var F2,s_=R(()=>{"use strict";F2=require("crypto");jm()});function $2(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 J2,Km,U2=R(()=>{"use strict";wo();Vi();ia();he();s_();vn();J2="observation_generate_for_event",Km=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 Sn(this.options.pool,async o=>{let l=await new Hr(o).create(e);if(!n)return{event:l,outbox:null};let u=new ut(o),d=new Jt(o),p=He(),f=$2({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:J2,bullmqJobId:dc({kind:"event",team_id:l.teamId,project_id:l.projectId,source_type:"agent_event",source_id:l.id}),payload:f});return await d.append({generationJobId:m.id,projectId:m.projectId,teamId:m.teamId,eventType:"queued",statusAfter:m.status,attempt:m.attempts,details:{source:i}}),{event:l,outbox:m}}),a="skipped";return s.outbox&&(a=await this.publishEventJob(s.event,s.outbox)),{event:s.event,outbox:s.outbox,enqueueState:a}}async ingestBatch(e,r={}){let n=r.generate??!0,i=r.source??"http_post_v1_events_batch",s=await Sn(this.options.pool,async a=>{let o=new Hr(a),c=new ut(a),l=new Jt(a),u=[];for(let d of e){let p=await o.create(d);if(!n){u.push({event:p,outbox:null});continue}let f=He(),m=$2({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:J2,bullmqJobId:dc({kind:"event",team_id:p.teamId,project_id:p.projectId,source_type:"agent_event",source_id:p.id}),payload:m});await l.append({generationJobId: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??dc({kind:"event",team_id:e.teamId,project_id:e.projectId,source_type:"agent_event",source_id:e.id});try{return await n.add(i,r.payload),"enqueued"}catch(s){return w.warn("SYSTEM","failed to publish event generation job to BullMQ",{outboxId:r.id,error:s instanceof Error?s.message:String(s)}),"queued_only"}}}});function a_(t){return dc({kind:"summary",team_id:t.teamId,project_id:t.projectId,source_type:"session_summary",source_id:t.serverSessionId})}function o_(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 z2=R(()=>{"use strict";s_()});var xfe,Cm,G2=R(()=>{"use strict";Vi();ia();ds();he();z2();vn();xfe="observation_generate_session_summary",Cm=class{constructor(e){this.options=e}options;async end(e){let r=e.source??"http_post_v1_sessions_end",n=await Sn(this.options.pool,async s=>{let o=await new Vt(s).endSession({id:e.sessionId,projectId:e.projectId,teamId:e.teamId});if(!o)return{session:null,outbox:null};let c=new ut(s),l=new Jt(s),u=He(),d=o_({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:xfe,bullmqJobId:a_({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??a_({serverSessionId:e,teamId:r.teamId,projectId:r.projectId}),a=o_({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 B2(t){return`${(process.env.CLAUDE_MEM_PUBLIC_URL??`${t.protocol}://${t.get("host")??"localhost"}`).replace(/\/+$/,"")}/v1/mcp`}function V2(t,e){return`claude mcp add --transport http claude-mem ${t} --header "Authorization: Bearer ${e}"`}async function Y2(t,e,r=e4,n=Ife){if(W2.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,W2.includes(a.status))return{job:a,timedOut:!1}}return{job:s,timedOut:!0}}function Tfe(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&t4.has(e)?e:null,n=typeof t.query.source_type=="string"?t.query.source_type.trim():"",i=n&&kfe.has(n)?n:null,s=Dm(t.query.limit,r4,1,n4),a=Dm(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 Q2(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 X2(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&t4.has(e)?e:null,n=Dm(t.query.limit,r4,1,n4),i=Dm(t.query.offset,0,0,Number.MAX_SAFE_INTEGER);return{status:r,limit:n,offset:i}}function Dm(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 c_(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 Afe(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 Rfe(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 Mu(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 Nu(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 pc(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 Ofe(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 l_(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 Z2(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 u_(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,Mm,wfe,_fe,H2,e4,Ife,W2,Pm,kfe,t4,r4,n4,i4=R(()=>{"use strict";ce=require("zod");zP();wo();Vi();hi();Cl();_o();he();Vp();oS();ZM();IN();j2();C2();D2();ba();Mm=require("node:crypto");ds();U2();G2();Zs();wfe="api",_fe="13.10.3";H2=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()}),e4=3e4,Ife=100,W2=["completed","failed","cancelled"];Pm=class{constructor(e){this.options=e;this.ingestEvents=new Km({pool:e.pool,resolveEventQueue:()=>this.resolveQueue("event")}),this.endSession=new Cm({pool:e.pool,resolveSummaryQueue:()=>this.resolveQueue("summary")})}options;ingestEvents;endSession;getIngestEventsService(){return this.ingestEvents}getEndSessionService(){return this.endSession}setupRoutes(e){e.use("/v1",XM());let r=ta(this.options.pool,{authMode:this.options.authMode,allowLocalDevBypass:this.options.allowLocalDevBypass,requiredScopes:["memories:write"]}),n=ta(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(K2(this.options.pool,{windowSec:60,max:s}));let a=Number(process.env.CLAUDE_MEM_MONTHLY_REQUEST_CAP??"0");a>0&&i.push(i_(this.options.pool,{kind:"request",cap:a})),process.env.CLAUDE_MEM_USAGE_METERING==="1"&&i.push(P2(this.options.pool));let o=[...i],c=Number(process.env.CLAUDE_MEM_MONTHLY_TOKEN_CAP??"0");c>0&&o.push(i_(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 Ar(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,Mm.randomBytes)(24).toString("hex")}`,v=(0,Mm.createHash)("sha256").update(b).digest("hex"),E=m.expiresInDays?new Date(Date.now()+m.expiresInDays*864e5):null,S=await new Pt(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=B2(p);f.status(201).json({id:S.id,apiKey:b,scopes:["memories:read"],expiresAt:E?.toISOString()??null,mcpUrl:k,connectCommand:V2(k,b)})})),e.get("/v1/connect",u,this.asyncHandler(async(p,f)=>{if(!this.requireTeamId(p,f))return;let g=B2(p);f.status(200).json({mcpUrl:g,connectCommand:V2(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=H2.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=Z0.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 ut(this.options.pool),st=await Y2(te,K);q=st.job,J=st.timedOut}f.status(201).json({event:Nu(A),generationJob:q?Z2(q,L):null,...J?{waitTimedOut:!0}:{}});return}f.status(201).json({event:Nu(A),...K?{generationJob:l_(K,L)}:{}})})),e.post("/v1/events/batch",l,this.asyncHandler(async(p,f)=>{let m=H2.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(Z0).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=Rfe(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 ut(this.options.pool),J=Date.now()+e4,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 Y2(q,_.outbox,P);te.push({event:_.event,outbox:O.job,timedOut:O.timedOut})}let st=te.some(_=>_.timedOut);f.status(201).json({events:te.map(({event:_,outbox:P,timedOut:O},j)=>({event:Nu(_),generationJob:P?Z2(P,L[j]):null,...O?{waitTimedOut:!0}:{}})),...st?{waitTimedOut:!0}:{}});return}f.status(201).json({events:K.map(({event:q,outbox:J},te)=>({event:Nu(q),...J?{generationJob:l_(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 Hr(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:Nu(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(`
349
349
  SELECT o.id, o.project_id, o.team_id, o.server_session_id, o.kind, o.content,
350
350
  o.metadata, o.generation_key, o.created_by_job_id, o.created_at, o.updated_at,
351
351
  os.id AS source_id_pk, os.source_type, os.source_id, os.generation_job_id, os.created_at AS source_created_at
@@ -13,7 +13,7 @@ ${i.stack}`:` ${i.message}`;else if(this.getLevel()===0&&typeof i=="object")try{
13
13
  ${E.stack??""}
14
14
  `)}else Z(g+`
15
15
  `)}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){Ze=e}error(e,t,n,o){this.log(3,e,t,n,o),this.routeErrorToSink(t,n,o)}routeErrorToSink(e,t,n){try{if(!Ze||!(n instanceof Error))return;Ze(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 tt});var N=require("fs"),Qe=require("os"),le=require("path");y();var ne=T.transcriptsConfig(),he=T.transcriptsState(),En={version:1,schemas:{},watches:[],stateFile:he};function Sn(r){let e=typeof r.schema=="string"?r.schema:r.schema?.name;if(!(r.name==="codex"||e==="codex")||!r.path)return!1;let n=v(r.path).replace(/\\/g,"/"),o=(0,le.join)((0,Qe.homedir)(),".codex","sessions").replace(/\\/g,"/");return n===`${o}/**/*.jsonl`}function It(r){let e=typeof r.schema=="string"?r.schema:r.schema?.name,t=r.name==="codex"&&(!e||e==="codex");return r.context?.mode==="agents"&&t&&Sn(r)}function v(r){return r&&(r.startsWith("~")?(0,le.join)((0,Qe.homedir)(),r.slice(1)):r)}function de(r=ne){let e=v(r);if(!(0,N.existsSync)(e))throw new Error(`Transcript watch config not found: ${e}`);let t=(0,N.readFileSync)(e,"utf-8"),n=JSON.parse(t);if(!n.version||!n.watches)throw new Error(`Invalid transcript watch config: ${e}`);return n.stateFile||(n.stateFile=he),n}function Te(r=ne){let e=v(r),t=(0,le.dirname)(e);(0,N.existsSync)(t)||(0,N.mkdirSync)(t,{recursive:!0}),(0,N.writeFileSync)(e,JSON.stringify(En,null,2))}var M=require("fs"),I=require("path");f();var F=require("fs"),Pt=require("path");f();function Lt(r){try{if(!(0,F.existsSync)(r))return{offsets:{}};let e=(0,F.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 xt(r,e){try{let t=(0,Pt.dirname)(r);(0,F.existsSync)(t)||(0,F.mkdirSync)(t,{recursive:!0}),(0,F.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 fe=K(require("path"),1);var R=K(require("path"),1),h=require("fs");var rt=require("node:child_process");function ye(r,e,t){return(0,rt.spawn)(r,e??[],{windowsHide:!0,...t})}var _n=new Set([".cmd",".bat"]),hn=new Set([".exe",".com"]),os=new Set([...hn,..._n]);f();var b={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},Y={SUCCESS:0,BLOCKING_ERROR:2};function B(r){return process.platform==="win32"?Math.round(r*b.WINDOWS_MULTIPLIER):r}var we=require("fs"),nt=require("path"),ot=require("os");_e();var A=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(B(b.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,nt.join)((0,ot.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,nt.join)((0,ot.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,we.existsSync)(e)){let c=this.getAllDefaults();try{Xe(e,c),console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(u){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,u instanceof Error?u.message:String(u))}return t?this.applyEnvOverrides(c):c}let n=(0,we.readFileSync)(e,"utf-8"),o=ee(n),i=o;if(o.env&&typeof o.env=="object"){i=o.env;try{Xe(e,i),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}}};y();y();var Me=null;function W(){return Me!==null||(Me=A.loadFromFile(re)),Me}var X=require("fs");f();var ut=require("child_process");var L=require("fs"),at=K(require("path"),1);f();var Tn=["CLAUDECODE_","CLAUDE_CODE_"],yn=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),wn=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy","npm_config_noproxy"]),Mn=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS",...wn]);function ve(r=process.env){let e={};for(let[t,n]of Object.entries(r))if(n!==void 0){if(Mn.has(t)){e[t]=n;continue}yn.has(t)||Tn.some(o=>t.startsWith(o))||(e[t]=n)}return e}y();var vn=5e3,Rn=1e3,An=T.supervisorRegistry();function P(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 Re(r,e){let t=Date.now()+e;for(;Date.now()<t;){if(r.every(n=>!P(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}var Cn=5e3,Nt=new Map;function kn(r){let e=(0,ut.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:{...ve(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 bn(r){let e=Nt.get(r);if(e&&Date.now()-e.capturedAtMs<Cn)return e.token;let t=null;try{t=kn(r)}catch(n){a.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:r,error:n instanceof Error?n.message:String(n)}),t=null}return Nt.set(r,{token:t,capturedAtMs:Date.now()}),t}function Ut(r){if(!Number.isInteger(r)||r<=0)return null;if(process.platform==="linux")try{let e=(0,L.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 bn(r);try{let e=(0,ut.spawnSync)("ps",["-p",String(r),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...ve(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 lt(r){if(!r||!P(r.pid))return!1;if(!r.startToken)return!0;let e=Ut(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 ct=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=An){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,L.mkdirSync)(at.default.dirname(this.registryPath),{recursive:!0}),!(0,L.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,L.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"&&it()}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)P(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)it();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=>P(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 Re(o,vn);let i=o.filter(s=>P(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()+Rn;for(;Date.now()<s&&i.filter(u=>P(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"&&it();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,L.mkdirSync)(at.default.dirname(this.registryPath),{recursive:!0}),(0,L.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},st=null;function Ae(){return st||(st=new ct),st}var On=[];function it(){let r=On.shift();r&&r()}var Wt=require("child_process"),oe=require("fs"),Ht=require("util");f();y();var In=(0,Ht.promisify)(Wt.execFile),Dn=T.workerPid();async function $t(r){let e=r.currentPid??process.pid,t=r.pidFilePath??Dn,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(!P(s.pid)){r.registry.unregister(s.id);continue}try{await Ft(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 Re(o,5e3);let i=o.filter(s=>P(s.pid));for(let s of i)try{await Ft(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 Re(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);jt(t,e),r.registry.pruneDeadEntries()}function jt(r,e,t=!1){if(!(0,oe.existsSync)(r))return;let n=null;try{let s=JSON.parse((0,oe.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||!P(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,oe.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 Ft(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 In("taskkill",o,{timeout:b.POWERSHELL_COMMAND,windowsHide:!0})}f();var Gt=3e4,se=null;function Pn(){let e=Ae().pruneDeadEntries();e>0&&a.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function Kt(){se===null&&(se=setInterval(Pn,Gt),se.unref(),a.debug("SYSTEM","Health checker started",{intervalMs:Gt}))}function Yt(){se!==null&&(clearInterval(se),se=null,a.debug("SYSTEM","Health checker stopped"))}y();var Ln=T.workerPid(),dt=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(),Ce({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,Kt()}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}Yt(),this.stopPromise=$t({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}},Ps=new dt(Ae());function Ce(r={}){let e=r.pidFilePath??Ln;if(!(0,X.existsSync)(e))return"missing";let t=null;try{t=JSON.parse((0,X.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,X.rmSync)(e,{force:!0}),"invalid"}return lt(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,X.rmSync)(e,{force:!0}),"stale")}Se();var pt=require("path"),be=require("fs"),Jt=require("crypto");y();var ke=require("fs");function Bt(r,e){if(!(0,ke.existsSync)(r))return e;try{return JSON.parse((0,ke.readFileSync)(r,"utf-8"))}catch(t){throw new Error(`Corrupt JSON file, refusing to overwrite: ${r}: ${t instanceof Error?t.message:String(t)}`)}}f();var Vt="telemetry.json";function xn(r){let e=r.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function Nn(r,e){if(xn(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 Xt(r,e){return Nn(r,e).enabled}function Un(){return(0,pt.join)(te(),Vt)}function ft(){let r;try{r=Bt(Un(),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 Fn(r){let e=te();(0,be.mkdirSync)(e,{recursive:!0}),(0,be.writeFileSync)((0,pt.join)(e,Vt),JSON.stringify(r,null,2)+`
16
- `)}function qt(){let r=ft();if(r?.installId)return r.installId;let e=(0,Jt.randomUUID)();return Fn({installId:e,decidedAt:""}),e}var Wn=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"]),zt=200;function Hn(r,e){if(!(!r||typeof r!="object"))for(let t of Object.keys(r)){if(!Wn.has(t))continue;let n=r[t];typeof n=="string"?e[t]=n.length>zt?n.slice(0,zt):n:(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(e[t]=n)}}function Qt(r){let e={};try{Hn(r,e)}catch{}return e}var mt=K(require("os"),1);f();var $n="13.10.2",jn="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",Gn="https://us.i.posthog.com";function Zt(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||jn}function er(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||Gn}var Kn=["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 tr(r){let e={};for(let t of Kn)r[t]!==void 0&&(e[t]=r[t]);return e}function Yn(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||mt.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 rr(){return{version:$n,os:process.platform,os_version:mt.default.release(),is_wsl:Yn(),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 nr(r,e,t){try{if(!Xt(process.env,ft()))return;let n=Qt({...rr(),...e??{}});if(t?.person?n.$set=tr(n):n.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:r,properties:n})+`
16
+ `)}function qt(){let r=ft();if(r?.installId)return r.installId;let e=(0,Jt.randomUUID)();return Fn({installId:e,decidedAt:""}),e}var Wn=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"]),zt=200;function Hn(r,e){if(!(!r||typeof r!="object"))for(let t of Object.keys(r)){if(!Wn.has(t))continue;let n=r[t];typeof n=="string"?e[t]=n.length>zt?n.slice(0,zt):n:(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(e[t]=n)}}function Qt(r){let e={};try{Hn(r,e)}catch{}return e}var mt=K(require("os"),1);f();var $n="13.10.3",jn="phc_BKJAeNbpj932N9qEiU6qhutZEiu6LLfRpXfTbLM9MLaG",Gn="https://us.i.posthog.com";function Zt(){return process.env.CLAUDE_MEM_TELEMETRY_KEY||jn}function er(){return process.env.CLAUDE_MEM_TELEMETRY_HOST||Gn}var Kn=["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 tr(r){let e={};for(let t of Kn)r[t]!==void 0&&(e[t]=r[t]);return e}function Yn(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||mt.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 rr(){return{version:$n,os:process.platform,os_version:mt.default.release(),is_wsl:Yn(),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 nr(r,e,t){try{if(!Xt(process.env,ft()))return;let n=Qt({...rr(),...e??{}});if(t?.person?n.$set=tr(n):n.$process_person_profile=!1,process.env.CLAUDE_MEM_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:r,properties:n})+`
17
17
  `);return}let o=Zt(),i=new AbortController,s=setTimeout(()=>i.abort(),Bn);try{await Jn(o,r,n,i.signal)}finally{clearTimeout(s)}}catch{}}async function Jn(r,e,t,n){await fetch(`${er()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:r,event:e,distinct_id:qt(),properties:t}),signal:n})}var q=K(require("path"),1),sr=require("os"),H=require("fs"),Et=require("child_process");f();y();var Zs=T.dataDir(),ei=T.workerPid();function or(r){return r?/(^|[\\/])bun(\.exe)?$/i.test(r.trim()):!1}function Xn(r,e){let t=e==="win32"?`where ${r}`:`which ${r}`,n;try{n=(0,Et.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 gt;function ir(r={}){let e=Object.keys(r).length===0;if(e&&gt!==void 0)return gt;let t=qn(r);return e&&t!==null&&(gt=t),t}function qn(r){let e=r.platform??process.platform,t=r.execPath??process.execPath;if(or(t))return t;let n=r.env??process.env,o=r.homeDirectory??(0,sr.homedir)(),i=r.pathExists??H.existsSync,s=r.lookupInPath??Xn,c=e==="win32"?[n.BUN,n.BUN_PATH,q.default.join(o,".bun","bin","bun.exe"),q.default.join(o,".bun","bin","bun"),n.USERPROFILE?q.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?q.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?q.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0]:[n.BUN,n.BUN_PATH,q.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&&(or(d)&&i(d)||d.toLowerCase()==="bun"))return d}return s("bun",e)}var ar=K(require("path"),1);var cr=require("fs");f();y();function zn(){return A.loadFromFile(re).CLAUDE_MEM_WORKER_HOST}function Qn(r){return r.startsWith("[")&&r.endsWith("]")?r:r.includes(":")?`[${r}]`:r}async function Zn(r,e,t="GET"){let n=await fetch(`http://${Qn(zn())}:${r}${e}`,{method:t}),o="";try{o=await n.text()}catch{}return{ok:n.ok,statusCode:n.status,body:o}}function eo(){try{let r=ar.default.join(ue,"package.json");return JSON.parse((0,cr.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 to(r){try{let e=await Zn(r,"/api/health");return e.ok?JSON.parse(e.body).version:null}catch{return a.debug("SYSTEM","Could not fetch worker version",{}),null}}async function ur(r){let e=eo(),t=await to(r);return!t||e==="unknown"?{matches:!0,pluginVersion:e,workerVersion:t}:{matches:e===t,pluginVersion:e,workerVersion:t}}f();var Oe=require("path"),C=require("fs");y();f();var ro=6e4;function lr(){return(0,Oe.join)(te(),"spawn.lock")}function dr(){let r=lr(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let t=0;t<2;t++)try{return(0,C.mkdirSync)((0,Oe.dirname)(r),{recursive:!0}),(0,C.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,C.statSync)(r).mtimeMs}catch{continue}if(Date.now()-s<=ro)return!1;let c;try{c=(0,C.statSync)(r).mtimeMs}catch{continue}if(c!==s)return!1;try{(0,C.unlinkSync)(r)}catch{return!1}}return!1}function pr(){let r=lr();try{if(JSON.parse((0,C.readFileSync)(r,"utf-8")).pid!==process.pid)return;(0,C.unlinkSync)(r)}catch{}}function Sr(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 Ne=Sr("CLAUDE_MEM_HEALTH_TIMEOUT_MS",B(b.HEALTH_CHECK),{min:500,max:3e5}),_r=Sr("CLAUDE_MEM_HOOK_READINESS_TIMEOUT_MS",B(b.HOOK_READINESS_WAIT),{min:0,max:3e5}),no={min:500,max:3e5};async function Tt(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 Ie=null,De=null,Pe=null,Le=null;function oo(){return R.default.join(A.get("CLAUDE_MEM_DATA_DIR"),"settings.json")}function yt(){return Pe!==null||(Pe=A.loadFromFile(oo())),Pe}function fr(r,e){if(!r)return null;let t=parseInt(r,10);return Number.isFinite(t)&&t>=e.min&&t<=e.max?t:null}function so(r,e,t){let n=process.env[r];if(n!==void 0){let s=fr(n,t);return s!==null?s:(a.warn("SYSTEM",`Invalid ${r}, using default`,{value:n,min:t.min,max:t.max}),e)}let o=yt()[r],i=fr(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 hr(){if(Ie!==null)return Ie;let r=yt();return Ie=parseInt(r.CLAUDE_MEM_WORKER_PORT,10),Ie}function io(){return De!==null||(De=yt().CLAUDE_MEM_WORKER_HOST),De}function ao(){return Le!==null||(Le=so("CLAUDE_MEM_API_TIMEOUT_MS",B(b.API_REQUEST),no)),Le}function co(r){return r.startsWith("[")&&r.endsWith("]")?r:r.includes(":")?`[${r}]`:r}function uo(r){return`http://${co(io())}:${hr()}${r}`}function $(r,e={}){let t=e.method??"GET",n=e.timeoutMs??ao(),o=uo(r),i={method:t};return e.headers&&(i.headers=e.headers),e.body&&(i.body=e.body),n>0?Tt(o,i,n):fetch(o,i)}async function lo(){return(await $("/api/health",{timeoutMs:Ne})).ok}async function mr(){return(await $("/api/readiness",{timeoutMs:Ne})).ok}function Tr(r){let e=(0,h.existsSync)(R.default.join(r,"plugin","scripts"))?R.default.join(r,"plugin"):r;return R.default.join(e,"scripts","worker-service.cjs")}function po(){let r=R.default.dirname(R.default.dirname(ue)),e=R.default.join(r,"cache","thedotmack","claude-mem");try{return(0,h.readdirSync)(e).filter(t=>/^\d/.test(t)).map(t=>R.default.join(e,t)).filter(t=>{try{return(0,h.statSync)(t).isDirectory()}catch{return!1}}).sort((t,n)=>(0,h.statSync)(n).mtimeMs-(0,h.statSync)(t).mtimeMs).map(Tr)}catch{return[]}}function fo(){let r=process.env.CLAUDE_MEM_WORKER_SCRIPT_PATH?.trim();if(r){if((0,h.existsSync)(r))return r;a.debug("SYSTEM","Ignoring missing CLAUDE_MEM_WORKER_SCRIPT_PATH override",{override:r})}let e=[...po(),Tr(R.default.join(ue,"plugin")),R.default.join(process.cwd(),"plugin","scripts","worker-service.cjs")];for(let t of e)if((0,h.existsSync)(t))return t;return null}async function mo(r){let e=r.backoffMs;for(let t=1;t<=r.attempts;t++){if(await wr())return!0;t<r.attempts&&(await new Promise(n=>setTimeout(n,e)),e*=2)}return!1}async function St(r=_r){if(r<=0)try{return await mr()}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 mr())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 yr(){try{let e=await(await $("/api/health",{timeoutMs:Ne})).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 go(r,e=_r){let t=Date.now();for(;Date.now()-t<e;){if(await yr()===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 _t(r){let e=await yr();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 wr(){let r;try{r=await lo()}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=Ce({logAlive:!1});return e==="missing"||e==="alive"}async function Ue(){let r=null;if(await wr()){let{matches:i,pluginVersion:s,workerVersion:c}=await ur(hr());if(s!=="unknown"&&(r=s),i)return await St()?(r!==null&&await _t(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 $("/api/admin/restart",{method:"POST",timeoutMs:Ne}),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 go(s))return await St()?(r!==null&&await _t(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=ir(),t=fo();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=dr();try{if(n){a.info("SYSTEM","Worker not running \u2014 lazy-spawning",{runtimePath:e,scriptPath:t});try{ye(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 mo({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&&pr()}return await St()?(r!==null&&await _t(r),!0):(a.warn("SYSTEM","Worker lazy-spawned but did not become ready before hook readiness timeout"),!1)}var xe=null;async function Eo(){return xe!==null||(xe=await Ue()),xe}var So=3;function Mr(){return R.default.join(S,"state")}function vr(){return R.default.join(Mr(),"hook-failures.json")}function _o(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 Rr(){try{return _o((0,h.readFileSync)(vr(),"utf-8"))}catch{return{consecutiveFailures:0,lastFailureAt:0}}}function Ar(r){let e=Mr(),t=vr(),n=`${t}.tmp`;try{(0,h.existsSync)(e)||(0,h.mkdirSync)(e,{recursive:!0}),(0,h.writeFileSync)(n,JSON.stringify(r),"utf-8"),(0,h.renameSync)(n,t)}catch(o){a.debug("SYSTEM","Failed to persist hook-failure counter",{error:o instanceof Error?o.message:String(o)})}}function ho(){try{let e=W().CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD,t=parseInt(e,10);if(Number.isFinite(t)&&t>=1)return t}catch{}return So}var gr=null;async function To(){let e={consecutiveFailures:Rr().consecutiveFailures+1,lastFailureAt:Date.now()};Ar(e);let t=ho();return e.consecutiveFailures>=t&&(e.consecutiveFailures===t&&await nr("hook_failed",{...gr!==null?{hook_type:gr}:{},error_mode:"worker_unavailable",consecutive_failures:e.consecutiveFailures,threshold_tripped:!0}),kt(`claude-mem worker unreachable for ${e.consecutiveFailures} consecutive hooks.`)),e.consecutiveFailures}function Er(){Rr().consecutiveFailures!==0&&Ar({consecutiveFailures:0,lastFailureAt:0})}var ht=Symbol.for("claude-mem/worker-fallback");function Fe(r){return typeof r=="object"&&r!==null&&r[ht]===!0}async function We(r,e,t,n={}){if(!await Eo())return await To(),{continue:!0,reason:"worker_unreachable",[ht]:!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 $(r,i);if(!s.ok){let u=await s.text().catch(()=>"");if(Er(),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}`,[ht]:!0};let d=u;try{d=JSON.parse(u)}catch{}return d}Er();let c=await s.text();if(c.length!==0)try{return JSON.parse(c)}catch{return c}}var kr=require("os"),br=K(require("path"),1),Or=require("child_process");f();var He=require("fs"),ie=K(require("path"),1);f();var pe={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function Cr(r){let e=ie.default.join(r,".git"),t;try{t=(0,He.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)}),pe}if(!t.isFile())return pe;let n;try{n=(0,He.readFileSync)(e,"utf-8").trim()}catch(l){return a.warn("GIT","Failed to read .git file",{error:l instanceof Error?l.message:String(l)}),pe}let o=n.match(/^gitdir:\s*(.+)$/);if(!o)return pe;let s=ie.default.resolve(ie.default.dirname(e),o[1]).match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!s)return pe;let c=s[1],u=ie.default.basename(r),d=ie.default.basename(c);return{isWorktree:!0,worktreeName:u,parentRepoPath:c,parentProjectName:d}}function Ir(r){return r==="~"||r.startsWith("~/")?r.replace(/^~/,(0,kr.homedir)()):r}function yo(r){try{return(0,Or.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 wo(r){if(!r||r.trim()==="")return a.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:r}),"unknown-project";let e=Ir(r),n=yo(e)??e,o=br.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 z(r){let e=wo(r);if(!r)return{primary:e,parent:null,isWorktree:!1,allProjects:[e]};let t=Ir(r),n=Cr(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]}}f();var Q=require("path");var Dr=require("os"),Pr=require("path");f();function Mo(r){let e=r.startsWith("~")?(0,Dr.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 $e(r,e){if(!e||!e.trim())return!1;let t=r.replace(/\\/g,"/"),n=(0,Pr.basename)(t),o=e.split(",").map(i=>i.trim()).filter(Boolean);for(let i of o)try{let s=Mo(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}y();function vo(r,e){let t=(0,Q.normalize)(r),n=(0,Q.normalize)(e);if(t===n)return!0;let o=(0,Q.relative)(n,t);return o.length>0&&!o.startsWith("..")&&!(0,Q.isAbsolute)(o)}function je(r){if(process.env.CLAUDE_MEM_INTERNAL==="1")return!1;if(!r)return!0;if(vo(r,ze))return!1;let e=W();return!$e(r,e.CLAUDE_MEM_EXCLUDED_PROJECTS)}var Lr="claude";function Ro(r){return r.trim().toLowerCase().replace(/\s+/g,"-")}function x(r){if(!r)return Lr;let e=Ro(r);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:Lr}f();var Ur=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],xr=new RegExp(`<(${Ur.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g");var Nr=100;function Ao(r){let e=Object.fromEntries(Ur.map(o=>[o,0]));xr.lastIndex=0;let t=0,n=r.replace(xr,(o,i)=>(e[i]=(e[i]??0)+1,t+=1,""));return t>Nr&&a.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:t,maxAllowed:Nr,contentLength:r.length}),{stripped:n.trim(),counts:e}}function wt(r){return Ao(r).stripped}var Co=["task-notification"],ko=new RegExp(`^\\s*<(${Co.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),bo=256*1024;function Fr(r){return!r||r.length>bo?!1:ko.test(r)}f();var Oo=B(b.API_REQUEST),j=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)}},Ge=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=Io(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??Oo}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 j("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 j("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:Mt(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:Mt(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:Mt(e.platformSource)}:{},...e.payload!==void 0?{payload:e.payload}:{}}}async request(e,t,n){if(!this.apiKey||!this.apiKey.trim())throw new j("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 Tt(o,i,this.timeoutMs)}catch(u){let d=u instanceof Error?u.message:String(u),l=/timed out|timeout/i.test(d);throw new j(l?"timeout":"transport",`Server ${e} ${t} failed: ${d}`,{cause:u})}if(!s.ok){let u=await s.text().catch(()=>"");throw new j("http_error",`Server ${e} ${t} returned ${s.status}: ${Do(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 j("invalid_response",`Server ${e} ${t} returned non-JSON response`,{cause:d})}}};function Wr(r){return r instanceof j}function Io(r){return r.replace(/\/+$/,"")}function Mt(r){return typeof r=="string"?x(r):null}function Do(r,e){return r.length<=e?r:`${r.slice(0,e)}\u2026`}function Po(){let e=(W().CLAUDE_MEM_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function Lo(){let r=W(),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 Ge(i),projectId:o,serverBaseUrl:t}}function Hr(){if(Po()!=="server")return{runtime:"worker"};let r=Lo();return r||{runtime:"worker"}}function $r(r,e){a.warn("HOOK",`[server-fallback] reason=${r}`,e??{})}var xo={executeWithWorkerFallback:We,isWorkerFallback:Fe,loadFromFileOnce:W,resolveRuntimeContext:Hr,logServerFallback:$r,shouldTrackProject:je},J=xo;var jr={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:Y.SUCCESS};if(!J.shouldTrackProject(n))return a.info("HOOK","Project excluded from tracking",{cwd:n}),{continue:!0,suppressOutput:!0};if(t&&Fr(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=z(n).primary,s=x(r.platform),c=J.loadFromFileOnce(),u=String(c.CLAUDE_MEM_SEMANTIC_INJECT).toLowerCase()==="true",d=J.resolveRuntimeContext();if(d.runtime==="server")try{return await No(d,r,e,s,i,o),{continue:!0,suppressOutput:!0}}catch(E){if(Wr(E)&&E.isFallbackEligible())J.logServerFallback(E.kind,{status:E.status,message:E.message,route:"/v1/sessions/start"});else return a.error("HOOK","Server session-start failed (non-recoverable)",{error:E instanceof Error?E.message:String(E)}),{continue:!0,suppressOutput:!0,exitCode:Y.SUCCESS}}a.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:e,project:i});let l=await J.executeWithWorkerFallback("/api/sessions/init","POST",{contentSessionId:e,project:i,prompt:o,platformSource:s});if(J.isWorkerFallback(l))return{continue:!0,suppressOutput:!0,exitCode:Y.SUCCESS};if(typeof l?.sessionDbId!="number")return a.failure("HOOK","Session initialization returned malformed response",{contentSessionId:e,project:i}),{continue:!0,suppressOutput:!0,exitCode:Y.SUCCESS};let _=l.sessionDbId,g=l.promptNumber;if(a.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:_,promptNumber:g,skipped:l.skipped,contextInjected:l.contextInjected}),a.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${e} | prompt#=${g} | sessionDbId=${_}`),l.skipped&&l.reason==="private")return a.info("HOOK",`INIT_COMPLETE | sessionDbId=${_} | promptNumber=${g} | skipped=true | reason=private`,{sessionId:_}),{continue:!0,suppressOutput:!0};let w="";if(u&&o&&o.length>=20&&o!=="[media prompt]"){let E=c.CLAUDE_MEM_SEMANTIC_INJECT_LIMIT||"5",G=await J.executeWithWorkerFallback("/api/context/semantic","POST",{q:o,project:i,limit:E,platformSource:s});!J.isWorkerFallback(G)&&G?.context&&(a.debug("HOOK",`Semantic injection: ${G.count} observations for prompt`,{sessionId:_,count:G.count}),w=G.context)}return a.info("HOOK",`INIT_COMPLETE | sessionDbId=${_} | promptNumber=${g} | project=${i}`,{sessionId:_}),w?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:w}}:{continue:!0,suppressOutput:!0}}};async function No(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})}f();var Gr={async execute(r){let{sessionId:e,cwd:t,filePath:n,edits:o}=r,i=x(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(!je(t))return a.debug("HOOK","Project excluded from tracking, skipping file edit observation",{cwd:t,filePath:n}),{continue:!0,suppressOutput:!0,exitCode:Y.SUCCESS};let s=await We("/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 Fe(s)?{continue:!0,suppressOutput:!0,exitCode:Y.SUCCESS}:(a.debug("HOOK","File edit observation sent successfully",{filePath:n}),{continue:!0,suppressOutput:!0})}};y();f();var O=require("fs"),Ke=require("path");f();f();y();var ba=T.settings();function Kr(r,e){let t="<claude-mem-context>",n="</claude-mem-context>";if(!r)return`${t}
18
18
  ${e}
19
19
  ${n}`;let o=r.indexOf(t),i=r.indexOf(n);return o!==-1&&i!==-1?r.substring(0,o)+`${t}