@bjlee2024/claude-mem 13.4.18 → 13.4.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/openclaw/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/.codex-plugin/plugin.json +1 -1
- package/plugin/package.json +1 -1
- package/plugin/scripts/mcp-server.cjs +1 -1
- package/plugin/scripts/server-beta-service.cjs +2 -2
- package/plugin/scripts/worker-service.cjs +3 -3
- package/plugin/ui/viewer-bundle.js +9 -9
|
@@ -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.4.
|
|
6
|
+
"version": "13.4.19",
|
|
7
7
|
"license": "Apache-2.0",
|
|
8
8
|
"author": "bjlee2024",
|
|
9
9
|
"homepage": "https://claude-mem.ai",
|
package/package.json
CHANGED
package/plugin/package.json
CHANGED
|
@@ -212,7 +212,7 @@ ${f}`}let a=s.lineStart;for(let u=s.lineStart-1;u>=0;u--){let l=i[u].trim();if(l
|
|
|
212
212
|
${c}`}var P_=new Set([".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".pyw",".go",".rs",".rb",".java",".cs",".cpp",".cc",".cxx",".c",".h",".hpp",".hh",".swift",".kt",".kts",".php",".vue",".svelte",".ex",".exs",".lua",".scala",".sc",".sh",".bash",".zsh",".hs",".zig",".css",".scss",".toml",".yml",".yaml",".sql",".md",".mdx"]),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*T_(t,e,r=20,n){if(r<=0)return;let o;try{o=await(0,Dr.readdir)(t,{withFileTypes:!0})}catch(s){y.debug("WORKER",`walkDir: failed to read directory ${t}`,void 0,s instanceof Error?s:void 0);return}for(let s of o){if(s.name.startsWith(".")&&s.name!=="."||SP.has(s.name))continue;let i=(0,no.join)(t,s.name);if(s.isDirectory())yield*T_(i,e,r-1,n);else if(s.isFile()){let a=s.name.slice(s.name.lastIndexOf("."));(P_.has(a)||n&&n.has(a))&&(yield i)}}}async function bP(t){try{let e=await(0,Dr.stat)(t);if(e.size>vP||e.size===0)return null;let r=await(0,Dr.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 z_(t,e,r={}){let n=r.maxResults||20,o=e.toLowerCase(),s=o.split(/[\s_\-./]+/).filter(E=>E.length>0),i=r.projectRoot||t,a=ro(i),c=new Set;for(let E of Object.values(a.grammars))for(let v of E.extensions)P_.has(v)||c.add(v);let u=[];for await(let E of T_(t,t,20,c.size>0?c:void 0)){if(r.filePattern&&!(0,no.relative)(t,E).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let v=await bP(E);v&&u.push({absolutePath:E,relativePath:(0,no.relative)(t,E),content:v})}let l=k_(u,i),d=[],p=[],f=0;for(let[E,v]of l){f+=EP(v);let x=Us(E.toLowerCase(),s)>0,ye=[],we=(Ut,rr)=>{for(let ae of Ut){let bt=0,Ke="",Hr=Us(ae.name.toLowerCase(),s);Hr>0&&(bt+=Hr*3,Ke="name match"),ae.signature.toLowerCase().includes(o)&&(bt+=2,Ke=Ke?`${Ke} + signature`:"signature match"),ae.jsdoc&&ae.jsdoc.toLowerCase().includes(o)&&(bt+=1,Ke=Ke?`${Ke} + jsdoc`:"jsdoc match"),bt>0&&(x=!0,ye.push({filePath:E,symbolName:rr?`${rr}.${ae.name}`:ae.name,kind:ae.kind,signature:ae.signature,jsdoc:ae.jsdoc,lineStart:ae.lineStart,lineEnd:ae.lineEnd,matchReason:Ke})),ae.children&&we(ae.children,ae.name)}};we(v.symbols),x&&(d.push(v),p.push(...ye))}p.sort((E,v)=>{let $=Us(E.symbolName.toLowerCase(),s);return Us(v.symbolName.toLowerCase(),s)-$});let m=p.slice(0,n),_=new Set(m.map(E=>E.filePath)),S=d.filter(E=>_.has(E.filePath)).slice(0,n),b=S.reduce((E,v)=>E+v.foldedTokenEstimate,0);return{foldedFiles:S,matchingSymbols:m,totalFilesScanned:u.length,totalSymbolsFound:f,tokenEstimate:b}}function Us(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 R_(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(`
|
|
213
213
|
`);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(`
|
|
214
214
|
`).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(Nr(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(`
|
|
215
|
-
`)}var wu=require("node:fs/promises"),Zs=require("node:fs"),rt=require("node:path"),j_=require("node:os"),L_=require("node:url");var wP=Or(le.API_REQUEST),Be=class extends Error{kind;status;cause;constructor(e,r,n={}){super(r),this.name="ServerBetaClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},oo=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=kP(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??wP}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 Be("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 timelineObservations(e){let r={projectId:e.projectId};return e.limit!==void 0&&(r.limit=e.limit),e.offset!==void 0&&(r.offset=e.offset),this.request("POST","/v1/timeline",r)}async resolveProject(e){return(await this.request("POST","/v1/projects/resolve",{name:e})).id}async getJobStatus(e){if(!e)throw new Be("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,type:n,narrative:r,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:e.platformSource}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.payload!==void 0?{payload:e.payload}:{},...e.sourceEventId!==void 0?{sourceEventId:e.sourceEventId}:{}}}async request(e,r,n){if(!this.apiKey||!this.apiKey.trim())throw new Be("missing_api_key","Server beta API key is not configured (CLAUDE_MEM_SERVER_BETA_API_KEY).");let o=`${this.baseUrl}${r}`,s={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(s.body=JSON.stringify(n));let i;try{i=await lu(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new Be(l?"timeout":"transport",`Server beta ${e} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new Be("http_error",`Server beta ${e} ${r} returned ${i.status}: ${xP(c,200)}`,{status:i.status})}let a=await i.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(c){throw new Be("invalid_response",`Server beta ${e} ${r} returned non-JSON response`,{cause:c})}}};function bu(t){return t instanceof Be}function kP(t){return t.replace(/\/+$/,"")}function xP(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}var qs=require("node:path"),Lt=require("node:fs"),jr=class t{client;mapPath;cache;constructor(e){this.client=e.client,this.mapPath=e.mapPath,this.cache=this.load()}static projectName(e){return(0,qs.basename)(e)}async resolve(e){let r=t.projectName(e),n=this.cache[r];if(n)return n;let o=await this.client.resolveProject(r);return this.cache[r]=o,this.persist(),o}load(){try{return(0,Lt.existsSync)(this.mapPath)?JSON.parse((0,Lt.readFileSync)(this.mapPath,"utf8")):{}}catch{return{}}}persist(){try{(0,Lt.mkdirSync)((0,qs.dirname)(this.mapPath),{recursive:!0}),(0,Lt.writeFileSync)(this.mapPath,JSON.stringify(this.cache,null,2),{mode:384})}catch{}}};function $P(t){let e=(t??"worker").trim().toLowerCase();return e==="server-beta"?"server-beta":e==="client"?"client":"worker"}function Ve(){return $P(Jn().CLAUDE_MEM_RUNTIME)}function I_(){let t=Jn(),e=(t.CLAUDE_MEM_SERVER_BETA_URL??"").trim(),r=(t.CLAUDE_MEM_SERVER_BETA_API_KEY??"").trim(),n=(t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID??"").trim();if(!e)return y.warn("HOOK","[server-beta-fallback] reason=missing_base_url"),null;if(!r)return y.warn("HOOK","[server-beta-fallback] reason=missing_api_key"),null;if(!n)return y.warn("HOOK","[server-beta-fallback] reason=missing_project_id"),null;let o={serverBaseUrl:e,apiKey:r};return{runtime:"server-beta",client:new oo(o),projectId:n,serverBaseUrl:e}}function O_(){let t=Jn(),e=(t.CLAUDE_MEM_SERVER_BETA_URL??"").trim(),r=(t.CLAUDE_MEM_SERVER_BETA_API_KEY??"").trim();if(!e)return y.warn("HOOK","[client-fallback] reason=missing_base_url"),null;if(!r)return y.warn("HOOK","[client-fallback] reason=missing_api_key"),null;let n=(t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID??"").trim()||null;return{runtime:"client",client:new oo({serverBaseUrl:e,apiKey:r}),projectId:n,serverBaseUrl:e}}var U_=require("node:path"),qP={},PP="13.4.18";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var q_=!1,Z_=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,rt.dirname)((0,L_.fileURLToPath)(qP.url))}catch{return q_=!0,process.cwd()}})(),ku=(0,rt.resolve)(Z_,"worker-service.cjs");function TP(){q_&&((0,Zs.existsSync)(ku)||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:ku,mcpServerDir:Z_}))}var A_={search:"/api/search",timeline:"/api/timeline"};async function Eu(t,e){y.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t,params:e});let r=new URLSearchParams;for(let[o,s]of Object.entries(e))s!=null&&r.append(o,String(s));let n=`${t}?${r}`;try{let o=await Ds(n);if(!o.ok){let i=await o.text();throw new Error(`Worker API error (${o.status}): ${i}`)}let s=await o.json();return y.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),s}catch(o){return y.error("SYSTEM","\u2190 Worker API error",{endpoint:t},o instanceof Error?o:new Error(String(o))),{content:[{type:"text",text:`Error calling Worker API: ${o instanceof Error?o.message:String(o)}`}],isError:!0}}}async function zP(t,e){let r=await Ds(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){let o=await r.text();throw new Error(`Worker API error (${r.status}): ${o}`)}let n=await r.json();return y.debug("HTTP","Worker API success (POST)",void 0,{endpoint:t}),{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}async function Lr(t,e){y.debug("HTTP","Worker API request (POST)",void 0,{endpoint:t});try{return await zP(t,e)}catch(r){return y.error("HTTP","Worker API error (POST)",{endpoint:t},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function RP(){try{return(await Ds("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}function IP(){let t=Ve();if(t==="server-beta"){let e=I_();return e?{...e,available:!0}:{runtime:"server-beta",available:!1,reason:"server-beta is selected but configuration is incomplete (missing url, api key, or project id)"}}if(t==="client"){let e=O_();return e?{...e,available:!0}:{runtime:"client",available:!1,reason:"client runtime selected but CLAUDE_MEM_SERVER_BETA_URL or CLAUDE_MEM_SERVER_BETA_API_KEY is missing"}}return null}function qr(t){return bu(t)?{content:[{type:"text",text:`Server beta error (${t.kind}${t.status?` ${t.status}`:""}): ${t.message}`}],isError:!0}:{content:[{type:"text",text:`Tool error: ${t instanceof Error?t.message:String(t)}`}],isError:!0}}function Zr(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function Fr(t){let e=IP();if(!e)throw new Be("transport",`${t} requires CLAUDE_MEM_RUNTIME=server-beta or CLAUDE_MEM_RUNTIME=client. Current runtime is "worker"; use the existing search/timeline/get_observations tools for worker-mode memory access.`);if(!e.available)throw new Be("missing_api_key",`${t}: ${e.reason}`);return e}async function io(t,e){let r=e?.trim();return r||(t.projectId?t.projectId:new jr({client:t.client,mapPath:(0,U_.join)(V,"project-map.json")}).resolve(process.cwd()))}async function M_(t){try{let e=Fr("observation_add");if(typeof t?.content!="string"||t.content.trim().length===0)throw new Error('observation_add: "content" is required');let n={projectId:await io(e,t.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 Zr(o)}catch(e){return qr(e)}}async function OP(t){try{let e=Fr("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:await io(e,t.projectId),sourceType:t.sourceType??"api",eventType:t.eventType,occurredAtEpoch:typeof t.occurredAtEpoch=="number"?t.occurredAtEpoch:Date.now(),...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.memorySessionId!==void 0?{memorySessionId:t.memorySessionId}:{},...t.payload!==void 0?{payload:t.payload}:{},...t.generate!==void 0?{generate:t.generate}:{}},o=await e.client.recordEvent(n);return Zr(o)}catch(e){return qr(e)}}async function C_(t){try{let e=Fr("observation_search");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_search: "query" is required');let n={projectId:await io(e,t.projectId),query:t.query,...t.limit!==void 0?{limit:t.limit}:{}},o=await e.client.searchObservations(n);return Zr(o)}catch(e){return qr(e)}}async function N_(t){try{let e=Fr("observation_context");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_context: "query" is required');let n={projectId:await io(e,t.projectId),query:t.query,...t.limit!==void 0?{limit:t.limit}:{}},o=await e.client.contextObservations(n);return Zr(o)}catch(e){return qr(e)}}async function AP(t){try{let e=Fr("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 Zr(n)}catch(e){return qr(e)}}async function MP(){if(await RP())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),TP();try{let t=du(),e=await p_(t,ku);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}}function Ur(){return{content:[{type:"text",text:"Knowledge-agent / corpus tools require the worker runtime (Chroma-backed) and are not available in server/client mode yet. Use the `search` MCP tool (the mem-search skill) for memory recall against the server."}]}}var F_=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
|
|
215
|
+
`)}var wu=require("node:fs/promises"),Zs=require("node:fs"),rt=require("node:path"),j_=require("node:os"),L_=require("node:url");var wP=Or(le.API_REQUEST),Be=class extends Error{kind;status;cause;constructor(e,r,n={}){super(r),this.name="ServerBetaClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},oo=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=kP(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??wP}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 Be("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 timelineObservations(e){let r={projectId:e.projectId};return e.limit!==void 0&&(r.limit=e.limit),e.offset!==void 0&&(r.offset=e.offset),this.request("POST","/v1/timeline",r)}async resolveProject(e){return(await this.request("POST","/v1/projects/resolve",{name:e})).id}async getJobStatus(e){if(!e)throw new Be("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,type:n,narrative:r,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:e.platformSource}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.payload!==void 0?{payload:e.payload}:{},...e.sourceEventId!==void 0?{sourceEventId:e.sourceEventId}:{}}}async request(e,r,n){if(!this.apiKey||!this.apiKey.trim())throw new Be("missing_api_key","Server beta API key is not configured (CLAUDE_MEM_SERVER_BETA_API_KEY).");let o=`${this.baseUrl}${r}`,s={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(s.body=JSON.stringify(n));let i;try{i=await lu(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new Be(l?"timeout":"transport",`Server beta ${e} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new Be("http_error",`Server beta ${e} ${r} returned ${i.status}: ${xP(c,200)}`,{status:i.status})}let a=await i.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(c){throw new Be("invalid_response",`Server beta ${e} ${r} returned non-JSON response`,{cause:c})}}};function bu(t){return t instanceof Be}function kP(t){return t.replace(/\/+$/,"")}function xP(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}var qs=require("node:path"),Lt=require("node:fs"),jr=class t{client;mapPath;cache;constructor(e){this.client=e.client,this.mapPath=e.mapPath,this.cache=this.load()}static projectName(e){return(0,qs.basename)(e)}async resolve(e){let r=t.projectName(e),n=this.cache[r];if(n)return n;let o=await this.client.resolveProject(r);return this.cache[r]=o,this.persist(),o}load(){try{return(0,Lt.existsSync)(this.mapPath)?JSON.parse((0,Lt.readFileSync)(this.mapPath,"utf8")):{}}catch{return{}}}persist(){try{(0,Lt.mkdirSync)((0,qs.dirname)(this.mapPath),{recursive:!0}),(0,Lt.writeFileSync)(this.mapPath,JSON.stringify(this.cache,null,2),{mode:384})}catch{}}};function $P(t){let e=(t??"worker").trim().toLowerCase();return e==="server-beta"?"server-beta":e==="client"?"client":"worker"}function Ve(){return $P(Jn().CLAUDE_MEM_RUNTIME)}function I_(){let t=Jn(),e=(t.CLAUDE_MEM_SERVER_BETA_URL??"").trim(),r=(t.CLAUDE_MEM_SERVER_BETA_API_KEY??"").trim(),n=(t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID??"").trim();if(!e)return y.warn("HOOK","[server-beta-fallback] reason=missing_base_url"),null;if(!r)return y.warn("HOOK","[server-beta-fallback] reason=missing_api_key"),null;if(!n)return y.warn("HOOK","[server-beta-fallback] reason=missing_project_id"),null;let o={serverBaseUrl:e,apiKey:r};return{runtime:"server-beta",client:new oo(o),projectId:n,serverBaseUrl:e}}function O_(){let t=Jn(),e=(t.CLAUDE_MEM_SERVER_BETA_URL??"").trim(),r=(t.CLAUDE_MEM_SERVER_BETA_API_KEY??"").trim();if(!e)return y.warn("HOOK","[client-fallback] reason=missing_base_url"),null;if(!r)return y.warn("HOOK","[client-fallback] reason=missing_api_key"),null;let n=(t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID??"").trim()||null;return{runtime:"client",client:new oo({serverBaseUrl:e,apiKey:r}),projectId:n,serverBaseUrl:e}}var U_=require("node:path"),qP={},PP="13.4.19";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var q_=!1,Z_=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,rt.dirname)((0,L_.fileURLToPath)(qP.url))}catch{return q_=!0,process.cwd()}})(),ku=(0,rt.resolve)(Z_,"worker-service.cjs");function TP(){q_&&((0,Zs.existsSync)(ku)||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:ku,mcpServerDir:Z_}))}var A_={search:"/api/search",timeline:"/api/timeline"};async function Eu(t,e){y.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t,params:e});let r=new URLSearchParams;for(let[o,s]of Object.entries(e))s!=null&&r.append(o,String(s));let n=`${t}?${r}`;try{let o=await Ds(n);if(!o.ok){let i=await o.text();throw new Error(`Worker API error (${o.status}): ${i}`)}let s=await o.json();return y.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),s}catch(o){return y.error("SYSTEM","\u2190 Worker API error",{endpoint:t},o instanceof Error?o:new Error(String(o))),{content:[{type:"text",text:`Error calling Worker API: ${o instanceof Error?o.message:String(o)}`}],isError:!0}}}async function zP(t,e){let r=await Ds(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){let o=await r.text();throw new Error(`Worker API error (${r.status}): ${o}`)}let n=await r.json();return y.debug("HTTP","Worker API success (POST)",void 0,{endpoint:t}),{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}async function Lr(t,e){y.debug("HTTP","Worker API request (POST)",void 0,{endpoint:t});try{return await zP(t,e)}catch(r){return y.error("HTTP","Worker API error (POST)",{endpoint:t},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function RP(){try{return(await Ds("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}function IP(){let t=Ve();if(t==="server-beta"){let e=I_();return e?{...e,available:!0}:{runtime:"server-beta",available:!1,reason:"server-beta is selected but configuration is incomplete (missing url, api key, or project id)"}}if(t==="client"){let e=O_();return e?{...e,available:!0}:{runtime:"client",available:!1,reason:"client runtime selected but CLAUDE_MEM_SERVER_BETA_URL or CLAUDE_MEM_SERVER_BETA_API_KEY is missing"}}return null}function qr(t){return bu(t)?{content:[{type:"text",text:`Server beta error (${t.kind}${t.status?` ${t.status}`:""}): ${t.message}`}],isError:!0}:{content:[{type:"text",text:`Tool error: ${t instanceof Error?t.message:String(t)}`}],isError:!0}}function Zr(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function Fr(t){let e=IP();if(!e)throw new Be("transport",`${t} requires CLAUDE_MEM_RUNTIME=server-beta or CLAUDE_MEM_RUNTIME=client. Current runtime is "worker"; use the existing search/timeline/get_observations tools for worker-mode memory access.`);if(!e.available)throw new Be("missing_api_key",`${t}: ${e.reason}`);return e}async function io(t,e){let r=e?.trim();return r||(t.projectId?t.projectId:new jr({client:t.client,mapPath:(0,U_.join)(V,"project-map.json")}).resolve(process.cwd()))}async function M_(t){try{let e=Fr("observation_add");if(typeof t?.content!="string"||t.content.trim().length===0)throw new Error('observation_add: "content" is required');let n={projectId:await io(e,t.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 Zr(o)}catch(e){return qr(e)}}async function OP(t){try{let e=Fr("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:await io(e,t.projectId),sourceType:t.sourceType??"api",eventType:t.eventType,occurredAtEpoch:typeof t.occurredAtEpoch=="number"?t.occurredAtEpoch:Date.now(),...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.memorySessionId!==void 0?{memorySessionId:t.memorySessionId}:{},...t.payload!==void 0?{payload:t.payload}:{},...t.generate!==void 0?{generate:t.generate}:{}},o=await e.client.recordEvent(n);return Zr(o)}catch(e){return qr(e)}}async function C_(t){try{let e=Fr("observation_search");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_search: "query" is required');let n={projectId:await io(e,t.projectId),query:t.query,...t.limit!==void 0?{limit:t.limit}:{}},o=await e.client.searchObservations(n);return Zr(o)}catch(e){return qr(e)}}async function N_(t){try{let e=Fr("observation_context");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_context: "query" is required');let n={projectId:await io(e,t.projectId),query:t.query,...t.limit!==void 0?{limit:t.limit}:{}},o=await e.client.contextObservations(n);return Zr(o)}catch(e){return qr(e)}}async function AP(t){try{let e=Fr("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 Zr(n)}catch(e){return qr(e)}}async function MP(){if(await RP())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),TP();try{let t=du(),e=await p_(t,ku);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}}function Ur(){return{content:[{type:"text",text:"Knowledge-agent / corpus tools require the worker runtime (Chroma-backed) and are not available in server/client mode yet. Use the `search` MCP tool (the mem-search skill) for memory recall against the server."}]}}var F_=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
|
|
216
216
|
1. search(query) \u2192 Get index with IDs (~50-100 tokens/result)
|
|
217
217
|
2. timeline(anchor=ID) \u2192 Get context around interesting results
|
|
218
218
|
3. get_observations([IDs]) \u2192 Fetch full details ONLY for filtered IDs
|
|
@@ -59,7 +59,7 @@ ${s.stack}`:` ${s.message}`;else if(this.getLevel()===0&&typeof s=="object")try{
|
|
|
59
59
|
`,"utf8")}catch(f){Hy(`[LOGGER] Failed to write to log file: ${f instanceof Error?f.message:String(f)}
|
|
60
60
|
`)}else Hy(p+`
|
|
61
61
|
`)}debug(e,t,n,i){this.log(0,e,t,n,i)}info(e,t,n,i){this.log(1,e,t,n,i)}warn(e,t,n,i){this.log(2,e,t,n,i)}error(e,t,n,i){this.log(3,e,t,n,i)}dataIn(e,t,n,i){this.info(e,`\u2192 ${t}`,n,i)}dataOut(e,t,n,i){this.info(e,`\u2190 ${t}`,n,i)}success(e,t,n,i){this.info(e,`\u2713 ${t}`,n,i)}failure(e,t,n,i){this.error(e,`\u2717 ${t}`,n,i)}timing(e,t,n,i){this.info(e,`\u23F1 ${t}`,i,{duration:`${n}ms`})}happyPathError(e,t,n,i,s=""){let l=((new Error().stack||"").split(`
|
|
62
|
-
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),u=l?`${l[1].split("/").pop()}:${l[2]}`:"unknown",d={...n,location:u};return this.warn(e,`[HAPPY-PATH] ${t}`,d,i),s}},_=new Wy});var KA=h((ife,CA)=>{"use strict";var RA=Object.getOwnPropertySymbols,nV=Object.prototype.hasOwnProperty,iV=Object.prototype.propertyIsEnumerable;function sV(r){if(r==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(r)}function oV(){try{if(!Object.assign)return!1;var r=new String("abc");if(r[5]="de",Object.getOwnPropertyNames(r)[0]==="5")return!1;for(var e={},t=0;t<10;t++)e["_"+String.fromCharCode(t)]=t;var n=Object.getOwnPropertyNames(e).map(function(s){return e[s]});if(n.join("")!=="0123456789")return!1;var i={};return"abcdefghijklmnopqrst".split("").forEach(function(s){i[s]=s}),Object.keys(Object.assign({},i)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}CA.exports=oV()?Object.assign:function(r,e){for(var t,n=sV(r),i,s=1;s<arguments.length;s++){t=Object(arguments[s]);for(var o in t)nV.call(t,o)&&(n[o]=t[o]);if(RA){i=RA(t);for(var a=0;a<i.length;a++)iV.call(t,i[a])&&(n[i[a]]=t[i[a]])}}return n}});var DA=h((sfe,jA)=>{(function(){"use strict";var r=KA(),e=Fy(),t={origin:"*",methods:"GET,HEAD,PUT,PATCH,POST,DELETE",preflightContinue:!1,optionsSuccessStatus:204};function n(m){return typeof m=="string"||m instanceof String}function i(m,y){if(Array.isArray(y)){for(var b=0;b<y.length;++b)if(i(m,y[b]))return!0;return!1}else return n(y)?m===y:y instanceof RegExp?y.test(m):!!y}function s(m,y){var b=y.headers.origin,g=[],E;return!m.origin||m.origin==="*"?g.push([{key:"Access-Control-Allow-Origin",value:"*"}]):n(m.origin)?(g.push([{key:"Access-Control-Allow-Origin",value:m.origin}]),g.push([{key:"Vary",value:"Origin"}])):(E=i(b,m.origin),g.push([{key:"Access-Control-Allow-Origin",value:E?b:!1}]),g.push([{key:"Vary",value:"Origin"}])),g}function o(m){var y=m.methods;return y.join&&(y=m.methods.join(",")),{key:"Access-Control-Allow-Methods",value:y}}function a(m){return m.credentials===!0?{key:"Access-Control-Allow-Credentials",value:"true"}:null}function c(m,y){var b=m.allowedHeaders||m.headers,g=[];return b?b.join&&(b=b.join(",")):(b=y.headers["access-control-request-headers"],g.push([{key:"Vary",value:"Access-Control-Request-Headers"}])),b&&b.length&&g.push([{key:"Access-Control-Allow-Headers",value:b}]),g}function l(m){var y=m.exposedHeaders;if(y)y.join&&(y=y.join(","));else return null;return y&&y.length?{key:"Access-Control-Expose-Headers",value:y}:null}function u(m){var y=(typeof m.maxAge=="number"||m.maxAge)&&m.maxAge.toString();return y&&y.length?{key:"Access-Control-Max-Age",value:y}:null}function d(m,y){for(var b=0,g=m.length;b<g;b++){var E=m[b];E&&(Array.isArray(E)?d(E,y):E.key==="Vary"&&E.value?e(y,E.value):E.value&&y.setHeader(E.key,E.value))}}function p(m,y,b,g){var E=[],I=y.method&&y.method.toUpperCase&&y.method.toUpperCase();I==="OPTIONS"?(E.push(s(m,y)),E.push(a(m)),E.push(o(m)),E.push(c(m,y)),E.push(u(m)),E.push(l(m)),d(E,b),m.preflightContinue?g():(b.statusCode=m.optionsSuccessStatus,b.setHeader("Content-Length","0"),b.end())):(E.push(s(m,y)),E.push(a(m)),E.push(l(m)),d(E,b),g())}function f(m){var y=null;return typeof m=="function"?y=m:y=function(b,g){g(null,m)},function(g,E,I){y(g,function(T,L){if(T)I(T);else{var U=r({},t,L),ie=null;U.origin&&typeof U.origin=="function"?ie=U.origin:U.origin&&(ie=function(je,ce){ce(null,U.origin)}),ie?ie(g.headers.origin,function(je,ce){je||!ce?I(je):(U.origin=ce,p(U,g,E,I))}):I()}})}}jA.exports=f})()});function zy(r,e={}){let t=[];e.includeCors!==!1&&t.push(Ql()),t.push(Yy.default.json({limit:"5mb"})),t.push((s,o,a)=>{let l=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(y=>s.path.endsWith(y)),u=s.path==="/api/logs";if(s.path.startsWith("/health")||s.path==="/"||l||u)return a();let d=Date.now(),p=`${s.method}-${Date.now()}`,f=r(s.method,s.path,s.body);_.debug("HTTP",`\u2192 ${s.method} ${s.path}`,{requestId:p},f);let m=o.send.bind(o);o.send=function(y){let b=Date.now()-d;return _.debug("HTTP",`\u2190 ${o.statusCode} ${s.path}`,{requestId:p,duration:`${b}ms`}),m(y)},a()});let n=Fi(),i=PA.default.join(n,"plugin","ui");return t.push(Yy.default.static(i)),t}function aV(r){let e=(process.env.CLAUDE_MEM_CORS_ALLOW_ORIGINS||"").split(",").map(i=>i.trim()).filter(Boolean);if(e.includes("*")||e.includes(r))return!0;let t;try{t=new URL(r).hostname}catch{return!1}if(t==="localhost"||t==="127.0.0.1"||t==="::1"||!t.includes(".")||t.endsWith(".local")||t.endsWith(".internal")||t.endsWith(".lan")||t.endsWith(".ts.net"))return!0;let n=t.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);if(n){let i=Number(n[1]),s=Number(n[2]);if(i===10||i===172&&s>=16&&s<=31||i===192&&s===168||i===100&&s>=64&&s<=127)return!0}return!1}function Ql(){return(0,MA.default)({origin:(r,e)=>{!r||aV(r)?e(null,!0):e(new Error("CORS not allowed"))},methods:["GET","HEAD","POST","PUT","PATCH","DELETE"],allowedHeaders:["Content-Type","Authorization","X-Requested-With"],credentials:!1})}function wa(r,e,t){let n=r.ip||r.connection.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){_.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:r.path,clientIp:n,method:r.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}t()}function Qy(r,e,t){if(!t||Object.keys(t).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=t.tool_name||"?",i=t.tool_input;return`tool=${_.formatTool(n,i)}`}return e.includes("/summarize")?"requesting summary":""}var Yy,MA,PA,NA=R(()=>{"use strict";Yy=ze(zl(),1),MA=ze(DA(),1),PA=ze(require("path"),1);kt();se()});var LA=R(()=>{"use strict";NA()});function qA(r,e,t,n){let i={error:r,message:e};return t&&(i.code=t),n&&(i.details=n),i}function JA(r,e){e.status(404).json(qA("NotFound",`Cannot ${r.method} ${r.path}`))}var Gs,FA,UA=R(()=>{"use strict";se();Gs=class extends Error{constructor(t,n=500,i,s){super(t);this.statusCode=n;this.code=i;this.details=s;this.name="AppError"}statusCode;code;details};FA=(r,e,t,n)=>{let i=r instanceof Gs?r.statusCode:500;_.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:r.message,code:r instanceof Gs?r.code:void 0},r);let s=qA(r.name||"Error",r.message,r instanceof Gs?r.code:void 0,r instanceof Gs?r.details:void 0);t.status(i).json(s)}});var GA=R(()=>{"use strict"});function Ia(r=process.env){let e={};for(let[t,n]of Object.entries(r))if(n!==void 0){if(lV.has(t)){e[t]=n;continue}Zy.has(t)||cV.has(t)||Xy.some(i=>t.startsWith(i))||(e[t]=n)}return e}var Xy,Zy,cV,lV,Xl=R(()=>{"use strict";Xy=["CLAUDECODE_","CLAUDE_CODE_"],Zy=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),cV=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"]),lV=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS"])});function pr(r){if(!Number.isInteger(r)||r<0||r===0)return!1;try{return process.kill(r,0),!0}catch(e){if(e instanceof Error){let t=e.code;return t==="EPERM"?!0:(_.debug("SYSTEM","PID check failed",{pid:r,code:t}),!1)}return _.warn("SYSTEM","PID check threw non-Error",{pid:r,error:String(e)}),!1}}function mV(r){let e=BA.get(r);if(e&&Date.now()-e.capturedAtMs<fV)return e.token;let t=null;try{let n=(0,ib.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:{...Ia(process.env),LC_ALL:"C",LANG:"C"}});if(n.status===0){let i=n.stdout.trim();t=i.length>0?i:null}}catch(n){_.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:r,error:n instanceof Error?n.message:String(n)}),t=null}return BA.set(r,{token:t,capturedAtMs:Date.now()}),t}function sb(r){if(!Number.isInteger(r)||r<=0)return null;if(process.platform==="linux")try{let e=(0,Hr.readFileSync)(`/proc/${r}/stat`,"utf-8"),t=e.lastIndexOf(") ");if(t<0)return null;let i=e.slice(t+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(e){return _.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return mV(r);try{let e=(0,ib.spawnSync)("ps",["-p",String(r),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Ia(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let t=e.stdout.trim();return t.length>0?t:null}catch(e){return _.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}}function Hn(r){if(!r||!pr(r.pid))return!1;if(!r.startToken)return!0;let e=sb(r.pid);if(e===null)return!0;let t=e===r.startToken;return t||_.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:r.pid,stored:r.startToken,current:e}),t}function Zl(){return eb||(eb=new nb),eb}function tb(){let r=hV.shift();r&&r()}var ib,Hr,rb,uV,dV,pV,fV,BA,nb,eb,hV,Bs=R(()=>{"use strict";ib=require("child_process");GA();Hr=require("fs"),rb=ze(require("path"),1);se();Xl();kt();uV=5e3,dV=1e3,pV=Pe.supervisorRegistry();fV=5e3,BA=new Map;nb=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=pV){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,Hr.mkdirSync)(rb.default.dirname(this.registryPath),{recursive:!0}),!(0,Hr.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Hr.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[i,s]of Object.entries(n))this.entries.set(i,s)}catch(t){t instanceof Error?_.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},t):_.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(t)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&_.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,t,n){this.initialize(),this.entries.set(e,t),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let t=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),t?.type==="sdk"&&tb()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,t])=>({id:e,...t})).sort((e,t)=>{let n=Date.parse(e.startedAt),i=Date.parse(t.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(i)?0:i)})}getBySession(e){let t=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===t)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}getByPid(e){return this.getAll().filter(t=>t.pid===e)}pruneDeadEntries(){this.initialize();let e=0,t=0;for(let[n,i]of this.entries)pr(i.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,i.type==="sdk"&&(t+=1));e>0&&this.persist();for(let n=0;n<t;n+=1)tb();return e}async reapSession(e){this.initialize();let t=this.getBySession(e);if(t.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;_.info("SYSTEM",`Reaping ${t.length} process(es) for session ${e}`,{sessionId:n,pids:t.map(a=>a.pid)});let i=t.filter(a=>pr(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(c){c instanceof Error?c.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):_.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}let s=Date.now()+uV;for(;Date.now()<s&&i.filter(c=>pr(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100));let o=i.filter(a=>pr(a.pid));for(let a of o){_.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(c){c instanceof Error?c.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):_.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}}if(o.length>0){let a=Date.now()+dV;for(;Date.now()<a&&o.filter(l=>pr(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let a of t)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of t)a.type==="sdk"&&tb();return _.info("SYSTEM",`Reaped ${t.length} process(es) for session ${e}`,{sessionId:n,reaped:t.length}),t.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,Hr.mkdirSync)(rb.default.dirname(this.registryPath),{recursive:!0}),(0,Hr.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},eb=null;hV=[]});var $A,HA=R(()=>{"use strict";$A={DEFAULT:3e5,HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,WORKER_STARTUP_WAIT:1e3,PRE_RESTART_SETTLE_DELAY:2e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5}});async function XA(r){let e=r.currentPid??process.pid,t=r.pidFilePath??bV,n=r.registry.getAll(),i=[...n].filter(o=>o.pid!==e).sort((o,a)=>Date.parse(a.startedAt)-Date.parse(o.startedAt));for(let o of i){if(!pr(o.pid)){r.registry.unregister(o.id);continue}try{await WA(o,"SIGTERM")}catch(a){a instanceof Error?_.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:o.pid,pgid:o.pgid,type:o.type},a):_.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:o.pid,pgid:o.pgid,type:o.type,error:String(a)})}}await VA(i,5e3);let s=i.filter(o=>pr(o.pid));for(let o of s)try{await WA(o,"SIGKILL")}catch(a){a instanceof Error?_.debug("SYSTEM","Failed to force kill child process",{pid:o.pid,pgid:o.pgid,type:o.type},a):_.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:o.pid,pgid:o.pgid,type:o.type,error:String(a)})}await VA(s,1e3);for(let o of i)r.registry.unregister(o.id);for(let o of n.filter(a=>a.pid===e))r.registry.unregister(o.id);try{(0,zA.rmSync)(t,{force:!0})}catch(o){o instanceof Error?_.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:t},o):_.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:t,error:String(o)})}r.registry.pruneDeadEntries()}async function VA(r,e){let t=Date.now()+e;for(;Date.now()<t;){if(r.filter(i=>pr(i.pid)).length===0)return;await new Promise(i=>setTimeout(i,100))}}async function WA(r,e){let{pid:t,pgid:n}=r;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}try{process.kill(t,e)}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}return}if(e==="SIGTERM"){try{process.kill(t,e)}catch(o){if(o instanceof Error&&o.code==="ESRCH")return;throw o}return}let i=await gV();if(i){await new Promise((o,a)=>{i(t,e,c=>{if(!c){o();return}if(c.code==="ESRCH"){o();return}a(c)})});return}let s=["/PID",String(t),"/T"];e==="SIGKILL"&&s.push("/F"),await yV("taskkill",s,{timeout:$A.POWERSHELL_COMMAND,windowsHide:!0})}async function gV(){let r="tree-kill";try{let e=await import(r);return e.default??e}catch(e){return _.debug("SYSTEM","tree-kill module not available, using fallback",{},e instanceof Error?e:void 0),null}}var YA,zA,QA,yV,bV,ZA=R(()=>{"use strict";YA=require("child_process"),zA=require("fs"),QA=require("util");se();HA();Bs();kt();yV=(0,QA.promisify)(YA.execFile),bV=Pe.workerPid()});function vV(){let e=Zl().pruneDeadEntries();e>0&&_.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function tk(){$s===null&&($s=setInterval(vV,ek),$s.unref(),_.debug("SYSTEM","Health checker started",{intervalMs:ek}))}function rk(){$s!==null&&(clearInterval($s),$s=null,_.debug("SYSTEM","Health checker stopped"))}var ek,$s,nk=R(()=>{"use strict";se();Bs();ek=3e4,$s=null});function ik(){return SV}function xV(r={}){let e=r.pidFilePath??EV;if(!(0,Ji.existsSync)(e))return"missing";let t=null;try{t=JSON.parse((0,Ji.readFileSync)(e,"utf-8"))}catch(i){return i instanceof Error?_.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},i):_.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(i)}),(0,Ji.rmSync)(e,{force:!0}),"invalid"}return Hn(t)&&t?((r.logAlive??!0)&&_.info("SYSTEM","Worker already running (PID alive)",{existingPid:t.pid,existingPort:t.port,startedAt:t.startedAt}),"alive"):(_.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:t?.pid,port:t?.port,startedAt:t?.startedAt}),(0,Ji.rmSync)(e,{force:!0}),"stale")}var Ji,EV,ob,SV,sk=R(()=>{"use strict";Ji=require("fs");se();Bs();ZA();nk();kt();EV=Pe.workerPid(),ob=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(),xV({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,tk()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let t=async n=>{if(this.shutdownInitiated){_.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,_.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){i instanceof Error?_.error("SYSTEM","Error during shutdown",{},i):_.error("SYSTEM","Error during shutdown (non-Error)",{error:String(i)});try{await this.stop()}catch(s){s instanceof Error?_.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):_.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(s)})}}process.exit(0)};process.on("SIGTERM",()=>{t("SIGTERM")}),process.on("SIGINT",()=>{t("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{_.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{t("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}rk(),this.stopPromise=XA({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}},SV=new ob(Zl())});function ab(r,e,t){r.on("finish",async()=>{try{await t()}finally{process.exit(0)}}),r.json(e)}var ok=R(()=>{"use strict"});function cb(r,e=Date.now){return Math.max(0,Math.floor((e()-r)/1e3))}var ak=R(()=>{"use strict"});var lb,ck,Gfe,lk=R(()=>{"use strict";lb=class{entries=new Map;set(e){if(!e||typeof e!="object")return;let t=e.rateLimitType??"default";this.entries.set(t,{...e,observedAt:Date.now()})}get(e){return e?this.entries.get(e):this.entries.get("default")}getAll(){return Array.from(this.entries.values()).sort((e,t)=>t.observedAt-e.observedAt)}getMostRecentByWindow(){return{five_hour:this.entries.get("five_hour"),seven_day:this.entries.get("seven_day"),seven_day_opus:this.entries.get("seven_day_opus"),seven_day_sonnet:this.entries.get("seven_day_sonnet"),overage:this.entries.get("overage")}}get size(){return this.entries.size}clear(){this.entries.clear()}},ck=new lb,Gfe=900*1e3});function IV(r){r.setHeader("X-Content-Type-Options","nosniff"),r.setHeader("X-Frame-Options","DENY"),r.setHeader("X-DNS-Prefetch-Control","off"),r.setHeader("Referrer-Policy","no-referrer"),r.setHeader("Cross-Origin-Opener-Policy","same-origin"),r.setHeader("Cross-Origin-Resource-Policy","same-origin"),r.setHeader("Origin-Agent-Cluster","?1"),r.removeHeader("X-Powered-By")}var pk,fk,db,Ta,mk,_V,ub,uk,wV,dk,eu,hk=R(()=>{"use strict";pk=ze(zl(),1),fk=ze(require("http"),1),db=ze(require("fs"),1),Ta=ze(require("path"),1);IA();se();LA();UA();sk();Bs();Xl();ok();ak();lk();mk=Ta.default.resolve(__dirname,"../skills/mem-search"),_V=Ta.default.join(mk,"operations"),ub=Ta.default.join(mk,"SKILL.md"),uk=(()=>{try{let r=db.readFileSync(ub,"utf-8");return _.info("SYSTEM","Cached SKILL.md at boot",{path:ub,bytes:Buffer.byteLength(r,"utf-8")}),r}catch(r){return _.debug("SYSTEM","SKILL.md not present at boot, /api/instructions will 404 for topic queries",{path:ub,message:r instanceof Error?r.message:String(r)}),null}})(),wV=(()=>{let r=new Map;for(let e of By){let t=Ta.default.join(_V,`${e}.md`);try{r.set(e,db.readFileSync(t,"utf-8"))}catch(n){_.debug("SYSTEM","Operation instruction file not present at boot",{path:t,message:n instanceof Error?n.message:String(n)})}}return r.size>0&&_.info("SYSTEM","Cached operation instruction files at boot",{count:r.size,operations:Array.from(r.keys())}),r})(),dk="13.4.18";eu=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,pk.default)(),this.app.disable("x-powered-by"),this.setupSecurityHeaders(),this.setupCors(),this.setupPreBodyParserRoutes(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,t){return new Promise((n,i)=>{let s=fk.default.createServer(this.app);this.server=s;let o=c=>{s.off("listening",a),i(c)},a=()=>{s.off("error",o),_.info("SYSTEM","HTTP server started",{host:t,port:e,pid:process.pid}),n()};s.once("error",o),s.once("listening",a),s.listen(e,t)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,t)=>{this.server.close(n=>n?t(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,_.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(JA),this.app.use(FA)}setupMiddleware(){zy(Qy,{includeCors:!1}).forEach(t=>this.app.use(t))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,t,n)=>{IV(t),n()})}setupCors(){this.app.use(Ql())}setupPreBodyParserRoutes(){this.options.preBodyParserRoutes?.forEach(e=>e.setupRoutes(this.app))}setupCoreRoutes(){this.app.get("/api/health",async(e,t)=>{let n=this.options.getQueueHealth?await this.options.getQueueHealth():null,i=n?.engine==="bullmq"&&n.redis.status==="error";t.status(i?503:200).json({status:i?"degraded":"ok",...this.options.runtime?{runtime:this.options.runtime}:{},version:dk,workerPath:this.options.workerPath,uptime:cb(this.startTime),managed:process.env.CLAUDE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.options.getInitializationComplete(),mcpReady:this.options.getMcpReady(),ai:this.options.getAiStatus(),rateLimits:ck.getMostRecentByWindow(),...n?{queue:n}:{}})}),this.app.get("/api/readiness",(e,t)=>{this.options.getInitializationComplete()?t.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):t.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(e,t)=>{t.status(200).json({version:dk})}),this.app.get("/api/instructions",(e,t)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!wA.includes(n))return t.status(400).json({error:"Invalid topic"});if(i&&!By.includes(i))return t.status(400).json({error:"Invalid operation"});if(i){let o=wV.get(i);return o===void 0?(_.debug("HTTP","Instruction file not cached at boot",{operation:i}),t.status(404).json({error:"Instruction not found"})):t.json({content:[{type:"text",text:o}]})}if(uk===null)return _.debug("HTTP","SKILL.md not cached at boot",{topic:n}),t.status(404).json({error:"Instruction not found"});let s=this.extractInstructionSection(uk,n);t.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",wa,async(e,t)=>{process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(t.json({status:"restarting"}),_.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):ab(t,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",wa,async(e,t)=>{process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(t.json({status:"shutting_down"}),_.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown"})):ab(t,{status:"shutting_down"},()=>this.options.onShutdown())}),this.app.get("/api/admin/doctor",wa,(e,t)=>{let o=ik().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:pr(f.pid)?"alive":"dead",startedAt:f.startedAt})),a=o.filter(f=>f.status==="dead").map(f=>f.pid),c=!Object.keys(process.env).some(f=>Zy.has(f)||Xy.some(m=>f.startsWith(m))),l=cb(this.startTime),u=Math.floor(l/3600),d=Math.floor(l%3600/60),p=u>0?`${u}h ${d}m`:`${d}m`;t.json({supervisor:{running:!0,pid:process.pid,uptime:p},processes:o,health:{deadProcessPids:a,envClean:c}})})}extractInstructionSection(e,t){let n={workflow:this.extractBetween(e,"## The Workflow","## Search Parameters"),search_params:this.extractBetween(e,"## Search Parameters","## Examples"),examples:this.extractBetween(e,"## Examples","## Why This Workflow"),all:e};return n[t]||n.all}extractBetween(e,t,n){let i=e.indexOf(t),s=e.indexOf(n);return i===-1?e:s===-1?e.substring(i):e.substring(i,s).trim()}}});var Nt,TV,AV,pb,yk=R(()=>{"use strict";Nt=require("zod"),TV=Nt.z.enum(["hook","worker","provider","server","api"]),AV=Nt.z.object({id:Nt.z.string().min(1),projectId:Nt.z.string().min(1),serverSessionId:Nt.z.string().min(1).nullable().default(null),sourceType:TV,eventType:Nt.z.string().min(1),platformSource:Nt.z.string().min(1).nullable().default(null),sourceEventId:Nt.z.string().min(1).nullable().default(null),payload:Nt.z.unknown().default({}),contentSessionId:Nt.z.string().min(1).nullable().default(null),memorySessionId:Nt.z.string().min(1).nullable().default(null),occurredAtEpoch:Nt.z.number().int().nonnegative(),createdAtEpoch:Nt.z.number().int().nonnegative()}),pb=AV.omit({id:!0,createdAtEpoch:!0}).partial({serverSessionId:!0,platformSource:!0,sourceEventId:!0,payload:!0,contentSessionId:!0,memorySessionId:!0})});function Ue(){return(0,tu.randomUUID)()}function Qe(r){return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}function bk(r){return Array.isArray(r)?r:[]}function Ee(r){return typeof r=="number"?r:new Date(r).getTime()}function fr(r){return r==null?null:r instanceof Date?r:new Date(r)}async function Q(r,e,t=[]){return(await r.query(e,t)).rows[0]??null}async function Or(r,e,t){if(!await Q(r,"SELECT id FROM projects WHERE id = $1 AND team_id = $2",[e,t]))throw new Error("project_id must belong to team_id")}async function gn(r,e,t,n){if(!await Q(r,"SELECT id FROM server_sessions WHERE id = $1 AND project_id = $2 AND team_id = $3",[e,t,n]))throw new Error("server_session_id must belong to project_id and team_id")}function Aa(r){return JSON.stringify(fb(r))}function Rr(r){return(0,tu.createHash)("sha256").update(Aa(r)).digest("hex")}function fb(r){if(Array.isArray(r))return r.map(fb);if(r&&typeof r=="object"){let e=r;return Object.keys(e).sort().reduce((t,n)=>(t[n]=fb(e[n]),t),{})}return r}var tu,Vr=R(()=>{"use strict";tu=require("crypto")});function gk(r){return r.sourceEventId?`agent_event:v1:${Rr([r.teamId,r.projectId,r.sourceAdapter,r.sourceEventId])}`:`agent_event:v1:${Rr([r.teamId,r.projectId,r.sourceAdapter,r.serverSessionId??null,r.eventType,new Date(r.occurredAt).toISOString(),Aa(r.payload??{})])}`}function mb(r){return{id:r.id,projectId:r.project_id,teamId:r.team_id,serverSessionId:r.server_session_id,sourceAdapter:r.source_adapter,sourceEventId:r.source_event_id,idempotencyKey:r.idempotency_key,eventType:r.event_type,platformSource:r.platform_source,payload:r.payload,metadata:Qe(r.metadata),occurredAtEpoch:Ee(r.occurred_at),receivedAtEpoch:Ee(r.received_at),createdAtEpoch:Ee(r.created_at)}}var mr,Hs=R(()=>{"use strict";Vr();mr=class{constructor(e){this.client=e}client;async create(e){await Or(this.client,e.projectId,e.teamId),e.serverSessionId&&await gn(this.client,e.serverSessionId,e.projectId,e.teamId);let t=gk(e),n=await Q(this.client,`
|
|
62
|
+
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),u=l?`${l[1].split("/").pop()}:${l[2]}`:"unknown",d={...n,location:u};return this.warn(e,`[HAPPY-PATH] ${t}`,d,i),s}},_=new Wy});var KA=h((ife,CA)=>{"use strict";var RA=Object.getOwnPropertySymbols,nV=Object.prototype.hasOwnProperty,iV=Object.prototype.propertyIsEnumerable;function sV(r){if(r==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(r)}function oV(){try{if(!Object.assign)return!1;var r=new String("abc");if(r[5]="de",Object.getOwnPropertyNames(r)[0]==="5")return!1;for(var e={},t=0;t<10;t++)e["_"+String.fromCharCode(t)]=t;var n=Object.getOwnPropertyNames(e).map(function(s){return e[s]});if(n.join("")!=="0123456789")return!1;var i={};return"abcdefghijklmnopqrst".split("").forEach(function(s){i[s]=s}),Object.keys(Object.assign({},i)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}CA.exports=oV()?Object.assign:function(r,e){for(var t,n=sV(r),i,s=1;s<arguments.length;s++){t=Object(arguments[s]);for(var o in t)nV.call(t,o)&&(n[o]=t[o]);if(RA){i=RA(t);for(var a=0;a<i.length;a++)iV.call(t,i[a])&&(n[i[a]]=t[i[a]])}}return n}});var DA=h((sfe,jA)=>{(function(){"use strict";var r=KA(),e=Fy(),t={origin:"*",methods:"GET,HEAD,PUT,PATCH,POST,DELETE",preflightContinue:!1,optionsSuccessStatus:204};function n(m){return typeof m=="string"||m instanceof String}function i(m,y){if(Array.isArray(y)){for(var b=0;b<y.length;++b)if(i(m,y[b]))return!0;return!1}else return n(y)?m===y:y instanceof RegExp?y.test(m):!!y}function s(m,y){var b=y.headers.origin,g=[],E;return!m.origin||m.origin==="*"?g.push([{key:"Access-Control-Allow-Origin",value:"*"}]):n(m.origin)?(g.push([{key:"Access-Control-Allow-Origin",value:m.origin}]),g.push([{key:"Vary",value:"Origin"}])):(E=i(b,m.origin),g.push([{key:"Access-Control-Allow-Origin",value:E?b:!1}]),g.push([{key:"Vary",value:"Origin"}])),g}function o(m){var y=m.methods;return y.join&&(y=m.methods.join(",")),{key:"Access-Control-Allow-Methods",value:y}}function a(m){return m.credentials===!0?{key:"Access-Control-Allow-Credentials",value:"true"}:null}function c(m,y){var b=m.allowedHeaders||m.headers,g=[];return b?b.join&&(b=b.join(",")):(b=y.headers["access-control-request-headers"],g.push([{key:"Vary",value:"Access-Control-Request-Headers"}])),b&&b.length&&g.push([{key:"Access-Control-Allow-Headers",value:b}]),g}function l(m){var y=m.exposedHeaders;if(y)y.join&&(y=y.join(","));else return null;return y&&y.length?{key:"Access-Control-Expose-Headers",value:y}:null}function u(m){var y=(typeof m.maxAge=="number"||m.maxAge)&&m.maxAge.toString();return y&&y.length?{key:"Access-Control-Max-Age",value:y}:null}function d(m,y){for(var b=0,g=m.length;b<g;b++){var E=m[b];E&&(Array.isArray(E)?d(E,y):E.key==="Vary"&&E.value?e(y,E.value):E.value&&y.setHeader(E.key,E.value))}}function p(m,y,b,g){var E=[],I=y.method&&y.method.toUpperCase&&y.method.toUpperCase();I==="OPTIONS"?(E.push(s(m,y)),E.push(a(m)),E.push(o(m)),E.push(c(m,y)),E.push(u(m)),E.push(l(m)),d(E,b),m.preflightContinue?g():(b.statusCode=m.optionsSuccessStatus,b.setHeader("Content-Length","0"),b.end())):(E.push(s(m,y)),E.push(a(m)),E.push(l(m)),d(E,b),g())}function f(m){var y=null;return typeof m=="function"?y=m:y=function(b,g){g(null,m)},function(g,E,I){y(g,function(T,L){if(T)I(T);else{var U=r({},t,L),ie=null;U.origin&&typeof U.origin=="function"?ie=U.origin:U.origin&&(ie=function(je,ce){ce(null,U.origin)}),ie?ie(g.headers.origin,function(je,ce){je||!ce?I(je):(U.origin=ce,p(U,g,E,I))}):I()}})}}jA.exports=f})()});function zy(r,e={}){let t=[];e.includeCors!==!1&&t.push(Ql()),t.push(Yy.default.json({limit:"5mb"})),t.push((s,o,a)=>{let l=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(y=>s.path.endsWith(y)),u=s.path==="/api/logs";if(s.path.startsWith("/health")||s.path==="/"||l||u)return a();let d=Date.now(),p=`${s.method}-${Date.now()}`,f=r(s.method,s.path,s.body);_.debug("HTTP",`\u2192 ${s.method} ${s.path}`,{requestId:p},f);let m=o.send.bind(o);o.send=function(y){let b=Date.now()-d;return _.debug("HTTP",`\u2190 ${o.statusCode} ${s.path}`,{requestId:p,duration:`${b}ms`}),m(y)},a()});let n=Fi(),i=PA.default.join(n,"plugin","ui");return t.push(Yy.default.static(i)),t}function aV(r){let e=(process.env.CLAUDE_MEM_CORS_ALLOW_ORIGINS||"").split(",").map(i=>i.trim()).filter(Boolean);if(e.includes("*")||e.includes(r))return!0;let t;try{t=new URL(r).hostname}catch{return!1}if(t==="localhost"||t==="127.0.0.1"||t==="::1"||!t.includes(".")||t.endsWith(".local")||t.endsWith(".internal")||t.endsWith(".lan")||t.endsWith(".ts.net"))return!0;let n=t.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);if(n){let i=Number(n[1]),s=Number(n[2]);if(i===10||i===172&&s>=16&&s<=31||i===192&&s===168||i===100&&s>=64&&s<=127)return!0}return!1}function Ql(){return(0,MA.default)({origin:(r,e)=>{!r||aV(r)?e(null,!0):e(new Error("CORS not allowed"))},methods:["GET","HEAD","POST","PUT","PATCH","DELETE"],allowedHeaders:["Content-Type","Authorization","X-Requested-With"],credentials:!1})}function wa(r,e,t){let n=r.ip||r.connection.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){_.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:r.path,clientIp:n,method:r.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}t()}function Qy(r,e,t){if(!t||Object.keys(t).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=t.tool_name||"?",i=t.tool_input;return`tool=${_.formatTool(n,i)}`}return e.includes("/summarize")?"requesting summary":""}var Yy,MA,PA,NA=R(()=>{"use strict";Yy=ze(zl(),1),MA=ze(DA(),1),PA=ze(require("path"),1);kt();se()});var LA=R(()=>{"use strict";NA()});function qA(r,e,t,n){let i={error:r,message:e};return t&&(i.code=t),n&&(i.details=n),i}function JA(r,e){e.status(404).json(qA("NotFound",`Cannot ${r.method} ${r.path}`))}var Gs,FA,UA=R(()=>{"use strict";se();Gs=class extends Error{constructor(t,n=500,i,s){super(t);this.statusCode=n;this.code=i;this.details=s;this.name="AppError"}statusCode;code;details};FA=(r,e,t,n)=>{let i=r instanceof Gs?r.statusCode:500;_.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:r.message,code:r instanceof Gs?r.code:void 0},r);let s=qA(r.name||"Error",r.message,r instanceof Gs?r.code:void 0,r instanceof Gs?r.details:void 0);t.status(i).json(s)}});var GA=R(()=>{"use strict"});function Ia(r=process.env){let e={};for(let[t,n]of Object.entries(r))if(n!==void 0){if(lV.has(t)){e[t]=n;continue}Zy.has(t)||cV.has(t)||Xy.some(i=>t.startsWith(i))||(e[t]=n)}return e}var Xy,Zy,cV,lV,Xl=R(()=>{"use strict";Xy=["CLAUDECODE_","CLAUDE_CODE_"],Zy=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),cV=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"]),lV=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS"])});function pr(r){if(!Number.isInteger(r)||r<0||r===0)return!1;try{return process.kill(r,0),!0}catch(e){if(e instanceof Error){let t=e.code;return t==="EPERM"?!0:(_.debug("SYSTEM","PID check failed",{pid:r,code:t}),!1)}return _.warn("SYSTEM","PID check threw non-Error",{pid:r,error:String(e)}),!1}}function mV(r){let e=BA.get(r);if(e&&Date.now()-e.capturedAtMs<fV)return e.token;let t=null;try{let n=(0,ib.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:{...Ia(process.env),LC_ALL:"C",LANG:"C"}});if(n.status===0){let i=n.stdout.trim();t=i.length>0?i:null}}catch(n){_.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:r,error:n instanceof Error?n.message:String(n)}),t=null}return BA.set(r,{token:t,capturedAtMs:Date.now()}),t}function sb(r){if(!Number.isInteger(r)||r<=0)return null;if(process.platform==="linux")try{let e=(0,Hr.readFileSync)(`/proc/${r}/stat`,"utf-8"),t=e.lastIndexOf(") ");if(t<0)return null;let i=e.slice(t+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(e){return _.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return mV(r);try{let e=(0,ib.spawnSync)("ps",["-p",String(r),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Ia(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let t=e.stdout.trim();return t.length>0?t:null}catch(e){return _.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}}function Hn(r){if(!r||!pr(r.pid))return!1;if(!r.startToken)return!0;let e=sb(r.pid);if(e===null)return!0;let t=e===r.startToken;return t||_.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:r.pid,stored:r.startToken,current:e}),t}function Zl(){return eb||(eb=new nb),eb}function tb(){let r=hV.shift();r&&r()}var ib,Hr,rb,uV,dV,pV,fV,BA,nb,eb,hV,Bs=R(()=>{"use strict";ib=require("child_process");GA();Hr=require("fs"),rb=ze(require("path"),1);se();Xl();kt();uV=5e3,dV=1e3,pV=Pe.supervisorRegistry();fV=5e3,BA=new Map;nb=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=pV){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,Hr.mkdirSync)(rb.default.dirname(this.registryPath),{recursive:!0}),!(0,Hr.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Hr.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[i,s]of Object.entries(n))this.entries.set(i,s)}catch(t){t instanceof Error?_.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},t):_.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(t)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&_.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,t,n){this.initialize(),this.entries.set(e,t),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let t=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),t?.type==="sdk"&&tb()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,t])=>({id:e,...t})).sort((e,t)=>{let n=Date.parse(e.startedAt),i=Date.parse(t.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(i)?0:i)})}getBySession(e){let t=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===t)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}getByPid(e){return this.getAll().filter(t=>t.pid===e)}pruneDeadEntries(){this.initialize();let e=0,t=0;for(let[n,i]of this.entries)pr(i.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,i.type==="sdk"&&(t+=1));e>0&&this.persist();for(let n=0;n<t;n+=1)tb();return e}async reapSession(e){this.initialize();let t=this.getBySession(e);if(t.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;_.info("SYSTEM",`Reaping ${t.length} process(es) for session ${e}`,{sessionId:n,pids:t.map(a=>a.pid)});let i=t.filter(a=>pr(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(c){c instanceof Error?c.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):_.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}let s=Date.now()+uV;for(;Date.now()<s&&i.filter(c=>pr(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100));let o=i.filter(a=>pr(a.pid));for(let a of o){_.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(c){c instanceof Error?c.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):_.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}}if(o.length>0){let a=Date.now()+dV;for(;Date.now()<a&&o.filter(l=>pr(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let a of t)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of t)a.type==="sdk"&&tb();return _.info("SYSTEM",`Reaped ${t.length} process(es) for session ${e}`,{sessionId:n,reaped:t.length}),t.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,Hr.mkdirSync)(rb.default.dirname(this.registryPath),{recursive:!0}),(0,Hr.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},eb=null;hV=[]});var $A,HA=R(()=>{"use strict";$A={DEFAULT:3e5,HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,WORKER_STARTUP_WAIT:1e3,PRE_RESTART_SETTLE_DELAY:2e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5}});async function XA(r){let e=r.currentPid??process.pid,t=r.pidFilePath??bV,n=r.registry.getAll(),i=[...n].filter(o=>o.pid!==e).sort((o,a)=>Date.parse(a.startedAt)-Date.parse(o.startedAt));for(let o of i){if(!pr(o.pid)){r.registry.unregister(o.id);continue}try{await WA(o,"SIGTERM")}catch(a){a instanceof Error?_.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:o.pid,pgid:o.pgid,type:o.type},a):_.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:o.pid,pgid:o.pgid,type:o.type,error:String(a)})}}await VA(i,5e3);let s=i.filter(o=>pr(o.pid));for(let o of s)try{await WA(o,"SIGKILL")}catch(a){a instanceof Error?_.debug("SYSTEM","Failed to force kill child process",{pid:o.pid,pgid:o.pgid,type:o.type},a):_.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:o.pid,pgid:o.pgid,type:o.type,error:String(a)})}await VA(s,1e3);for(let o of i)r.registry.unregister(o.id);for(let o of n.filter(a=>a.pid===e))r.registry.unregister(o.id);try{(0,zA.rmSync)(t,{force:!0})}catch(o){o instanceof Error?_.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:t},o):_.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:t,error:String(o)})}r.registry.pruneDeadEntries()}async function VA(r,e){let t=Date.now()+e;for(;Date.now()<t;){if(r.filter(i=>pr(i.pid)).length===0)return;await new Promise(i=>setTimeout(i,100))}}async function WA(r,e){let{pid:t,pgid:n}=r;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}try{process.kill(t,e)}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}return}if(e==="SIGTERM"){try{process.kill(t,e)}catch(o){if(o instanceof Error&&o.code==="ESRCH")return;throw o}return}let i=await gV();if(i){await new Promise((o,a)=>{i(t,e,c=>{if(!c){o();return}if(c.code==="ESRCH"){o();return}a(c)})});return}let s=["/PID",String(t),"/T"];e==="SIGKILL"&&s.push("/F"),await yV("taskkill",s,{timeout:$A.POWERSHELL_COMMAND,windowsHide:!0})}async function gV(){let r="tree-kill";try{let e=await import(r);return e.default??e}catch(e){return _.debug("SYSTEM","tree-kill module not available, using fallback",{},e instanceof Error?e:void 0),null}}var YA,zA,QA,yV,bV,ZA=R(()=>{"use strict";YA=require("child_process"),zA=require("fs"),QA=require("util");se();HA();Bs();kt();yV=(0,QA.promisify)(YA.execFile),bV=Pe.workerPid()});function vV(){let e=Zl().pruneDeadEntries();e>0&&_.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function tk(){$s===null&&($s=setInterval(vV,ek),$s.unref(),_.debug("SYSTEM","Health checker started",{intervalMs:ek}))}function rk(){$s!==null&&(clearInterval($s),$s=null,_.debug("SYSTEM","Health checker stopped"))}var ek,$s,nk=R(()=>{"use strict";se();Bs();ek=3e4,$s=null});function ik(){return SV}function xV(r={}){let e=r.pidFilePath??EV;if(!(0,Ji.existsSync)(e))return"missing";let t=null;try{t=JSON.parse((0,Ji.readFileSync)(e,"utf-8"))}catch(i){return i instanceof Error?_.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},i):_.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(i)}),(0,Ji.rmSync)(e,{force:!0}),"invalid"}return Hn(t)&&t?((r.logAlive??!0)&&_.info("SYSTEM","Worker already running (PID alive)",{existingPid:t.pid,existingPort:t.port,startedAt:t.startedAt}),"alive"):(_.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:t?.pid,port:t?.port,startedAt:t?.startedAt}),(0,Ji.rmSync)(e,{force:!0}),"stale")}var Ji,EV,ob,SV,sk=R(()=>{"use strict";Ji=require("fs");se();Bs();ZA();nk();kt();EV=Pe.workerPid(),ob=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(),xV({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,tk()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let t=async n=>{if(this.shutdownInitiated){_.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,_.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){i instanceof Error?_.error("SYSTEM","Error during shutdown",{},i):_.error("SYSTEM","Error during shutdown (non-Error)",{error:String(i)});try{await this.stop()}catch(s){s instanceof Error?_.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):_.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(s)})}}process.exit(0)};process.on("SIGTERM",()=>{t("SIGTERM")}),process.on("SIGINT",()=>{t("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{_.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{t("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}rk(),this.stopPromise=XA({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}},SV=new ob(Zl())});function ab(r,e,t){r.on("finish",async()=>{try{await t()}finally{process.exit(0)}}),r.json(e)}var ok=R(()=>{"use strict"});function cb(r,e=Date.now){return Math.max(0,Math.floor((e()-r)/1e3))}var ak=R(()=>{"use strict"});var lb,ck,Gfe,lk=R(()=>{"use strict";lb=class{entries=new Map;set(e){if(!e||typeof e!="object")return;let t=e.rateLimitType??"default";this.entries.set(t,{...e,observedAt:Date.now()})}get(e){return e?this.entries.get(e):this.entries.get("default")}getAll(){return Array.from(this.entries.values()).sort((e,t)=>t.observedAt-e.observedAt)}getMostRecentByWindow(){return{five_hour:this.entries.get("five_hour"),seven_day:this.entries.get("seven_day"),seven_day_opus:this.entries.get("seven_day_opus"),seven_day_sonnet:this.entries.get("seven_day_sonnet"),overage:this.entries.get("overage")}}get size(){return this.entries.size}clear(){this.entries.clear()}},ck=new lb,Gfe=900*1e3});function IV(r){r.setHeader("X-Content-Type-Options","nosniff"),r.setHeader("X-Frame-Options","DENY"),r.setHeader("X-DNS-Prefetch-Control","off"),r.setHeader("Referrer-Policy","no-referrer"),r.setHeader("Cross-Origin-Opener-Policy","same-origin"),r.setHeader("Cross-Origin-Resource-Policy","same-origin"),r.setHeader("Origin-Agent-Cluster","?1"),r.removeHeader("X-Powered-By")}var pk,fk,db,Ta,mk,_V,ub,uk,wV,dk,eu,hk=R(()=>{"use strict";pk=ze(zl(),1),fk=ze(require("http"),1),db=ze(require("fs"),1),Ta=ze(require("path"),1);IA();se();LA();UA();sk();Bs();Xl();ok();ak();lk();mk=Ta.default.resolve(__dirname,"../skills/mem-search"),_V=Ta.default.join(mk,"operations"),ub=Ta.default.join(mk,"SKILL.md"),uk=(()=>{try{let r=db.readFileSync(ub,"utf-8");return _.info("SYSTEM","Cached SKILL.md at boot",{path:ub,bytes:Buffer.byteLength(r,"utf-8")}),r}catch(r){return _.debug("SYSTEM","SKILL.md not present at boot, /api/instructions will 404 for topic queries",{path:ub,message:r instanceof Error?r.message:String(r)}),null}})(),wV=(()=>{let r=new Map;for(let e of By){let t=Ta.default.join(_V,`${e}.md`);try{r.set(e,db.readFileSync(t,"utf-8"))}catch(n){_.debug("SYSTEM","Operation instruction file not present at boot",{path:t,message:n instanceof Error?n.message:String(n)})}}return r.size>0&&_.info("SYSTEM","Cached operation instruction files at boot",{count:r.size,operations:Array.from(r.keys())}),r})(),dk="13.4.19";eu=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,pk.default)(),this.app.disable("x-powered-by"),this.setupSecurityHeaders(),this.setupCors(),this.setupPreBodyParserRoutes(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,t){return new Promise((n,i)=>{let s=fk.default.createServer(this.app);this.server=s;let o=c=>{s.off("listening",a),i(c)},a=()=>{s.off("error",o),_.info("SYSTEM","HTTP server started",{host:t,port:e,pid:process.pid}),n()};s.once("error",o),s.once("listening",a),s.listen(e,t)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,t)=>{this.server.close(n=>n?t(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,_.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(JA),this.app.use(FA)}setupMiddleware(){zy(Qy,{includeCors:!1}).forEach(t=>this.app.use(t))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,t,n)=>{IV(t),n()})}setupCors(){this.app.use(Ql())}setupPreBodyParserRoutes(){this.options.preBodyParserRoutes?.forEach(e=>e.setupRoutes(this.app))}setupCoreRoutes(){this.app.get("/api/health",async(e,t)=>{let n=this.options.getQueueHealth?await this.options.getQueueHealth():null,i=n?.engine==="bullmq"&&n.redis.status==="error";t.status(i?503:200).json({status:i?"degraded":"ok",...this.options.runtime?{runtime:this.options.runtime}:{},version:dk,workerPath:this.options.workerPath,uptime:cb(this.startTime),managed:process.env.CLAUDE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.options.getInitializationComplete(),mcpReady:this.options.getMcpReady(),ai:this.options.getAiStatus(),rateLimits:ck.getMostRecentByWindow(),...n?{queue:n}:{}})}),this.app.get("/api/readiness",(e,t)=>{this.options.getInitializationComplete()?t.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):t.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(e,t)=>{t.status(200).json({version:dk})}),this.app.get("/api/instructions",(e,t)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!wA.includes(n))return t.status(400).json({error:"Invalid topic"});if(i&&!By.includes(i))return t.status(400).json({error:"Invalid operation"});if(i){let o=wV.get(i);return o===void 0?(_.debug("HTTP","Instruction file not cached at boot",{operation:i}),t.status(404).json({error:"Instruction not found"})):t.json({content:[{type:"text",text:o}]})}if(uk===null)return _.debug("HTTP","SKILL.md not cached at boot",{topic:n}),t.status(404).json({error:"Instruction not found"});let s=this.extractInstructionSection(uk,n);t.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",wa,async(e,t)=>{process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(t.json({status:"restarting"}),_.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):ab(t,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",wa,async(e,t)=>{process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(t.json({status:"shutting_down"}),_.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown"})):ab(t,{status:"shutting_down"},()=>this.options.onShutdown())}),this.app.get("/api/admin/doctor",wa,(e,t)=>{let o=ik().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:pr(f.pid)?"alive":"dead",startedAt:f.startedAt})),a=o.filter(f=>f.status==="dead").map(f=>f.pid),c=!Object.keys(process.env).some(f=>Zy.has(f)||Xy.some(m=>f.startsWith(m))),l=cb(this.startTime),u=Math.floor(l/3600),d=Math.floor(l%3600/60),p=u>0?`${u}h ${d}m`:`${d}m`;t.json({supervisor:{running:!0,pid:process.pid,uptime:p},processes:o,health:{deadProcessPids:a,envClean:c}})})}extractInstructionSection(e,t){let n={workflow:this.extractBetween(e,"## The Workflow","## Search Parameters"),search_params:this.extractBetween(e,"## Search Parameters","## Examples"),examples:this.extractBetween(e,"## Examples","## Why This Workflow"),all:e};return n[t]||n.all}extractBetween(e,t,n){let i=e.indexOf(t),s=e.indexOf(n);return i===-1?e:s===-1?e.substring(i):e.substring(i,s).trim()}}});var Nt,TV,AV,pb,yk=R(()=>{"use strict";Nt=require("zod"),TV=Nt.z.enum(["hook","worker","provider","server","api"]),AV=Nt.z.object({id:Nt.z.string().min(1),projectId:Nt.z.string().min(1),serverSessionId:Nt.z.string().min(1).nullable().default(null),sourceType:TV,eventType:Nt.z.string().min(1),platformSource:Nt.z.string().min(1).nullable().default(null),sourceEventId:Nt.z.string().min(1).nullable().default(null),payload:Nt.z.unknown().default({}),contentSessionId:Nt.z.string().min(1).nullable().default(null),memorySessionId:Nt.z.string().min(1).nullable().default(null),occurredAtEpoch:Nt.z.number().int().nonnegative(),createdAtEpoch:Nt.z.number().int().nonnegative()}),pb=AV.omit({id:!0,createdAtEpoch:!0}).partial({serverSessionId:!0,platformSource:!0,sourceEventId:!0,payload:!0,contentSessionId:!0,memorySessionId:!0})});function Ue(){return(0,tu.randomUUID)()}function Qe(r){return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}function bk(r){return Array.isArray(r)?r:[]}function Ee(r){return typeof r=="number"?r:new Date(r).getTime()}function fr(r){return r==null?null:r instanceof Date?r:new Date(r)}async function Q(r,e,t=[]){return(await r.query(e,t)).rows[0]??null}async function Or(r,e,t){if(!await Q(r,"SELECT id FROM projects WHERE id = $1 AND team_id = $2",[e,t]))throw new Error("project_id must belong to team_id")}async function gn(r,e,t,n){if(!await Q(r,"SELECT id FROM server_sessions WHERE id = $1 AND project_id = $2 AND team_id = $3",[e,t,n]))throw new Error("server_session_id must belong to project_id and team_id")}function Aa(r){return JSON.stringify(fb(r))}function Rr(r){return(0,tu.createHash)("sha256").update(Aa(r)).digest("hex")}function fb(r){if(Array.isArray(r))return r.map(fb);if(r&&typeof r=="object"){let e=r;return Object.keys(e).sort().reduce((t,n)=>(t[n]=fb(e[n]),t),{})}return r}var tu,Vr=R(()=>{"use strict";tu=require("crypto")});function gk(r){return r.sourceEventId?`agent_event:v1:${Rr([r.teamId,r.projectId,r.sourceAdapter,r.sourceEventId])}`:`agent_event:v1:${Rr([r.teamId,r.projectId,r.sourceAdapter,r.serverSessionId??null,r.eventType,new Date(r.occurredAt).toISOString(),Aa(r.payload??{})])}`}function mb(r){return{id:r.id,projectId:r.project_id,teamId:r.team_id,serverSessionId:r.server_session_id,sourceAdapter:r.source_adapter,sourceEventId:r.source_event_id,idempotencyKey:r.idempotency_key,eventType:r.event_type,platformSource:r.platform_source,payload:r.payload,metadata:Qe(r.metadata),occurredAtEpoch:Ee(r.occurred_at),receivedAtEpoch:Ee(r.received_at),createdAtEpoch:Ee(r.created_at)}}var mr,Hs=R(()=>{"use strict";Vr();mr=class{constructor(e){this.client=e}client;async create(e){await Or(this.client,e.projectId,e.teamId),e.serverSessionId&&await gn(this.client,e.serverSessionId,e.projectId,e.teamId);let t=gk(e),n=await Q(this.client,`
|
|
63
63
|
INSERT INTO agent_events (
|
|
64
64
|
id, project_id, team_id, server_session_id, source_adapter,
|
|
65
65
|
source_event_id, idempotency_key, event_type, platform_source, payload, metadata, occurred_at
|
|
@@ -9541,7 +9541,7 @@ CREATE UNIQUE INDEX IF NOT EXISTS projects_team_name_uniq ON projects (team_id,
|
|
|
9541
9541
|
`).trim()}function Ule(r){let e=5e3*Math.pow(5,Math.max(0,r));return Math.min(e,600*1e3)}var y8=R(()=>{"use strict";f8();se();Oa();Vn();vn();no();Yf()});var om,am,b8=R(()=>{"use strict";se();Hs();Vn();Nc();vn();Tu();vs();y8();zn();om=class extends Error{reason;constructor(e,t){super(t),this.reason=e}},am=class{constructor(e){this.options=e}options;async process(e){let t=`bullmq:${e.id??"?"}`,n=e.data?.request_id??null,i;try{i=xR(e.data)}catch(a){throw a instanceof Ja&&_.error("SYSTEM","rejecting malformed job payload at execution",{correlationId:t,issues:a.issues}),a}if(i.kind!=="event"&&i.kind!=="event-batch"&&i.kind!=="summary")throw _.warn("SYSTEM","unsupported job kind for ProviderObservationGenerator",{correlationId:t,kind:i.kind}),new Error(`unsupported job kind: ${i.kind}`);let s=await this.loadCanonicalOutbox(i.generation_job_id);if(!s)return _.info("SYSTEM","job row not found by id; nothing to do",{correlationId:t,generationJobId:i.generation_job_id}),{jobId:i.generation_job_id,status:"completed",observationCount:0};if(s.teamId!==i.team_id||s.projectId!==i.project_id){let a=new om("scope_mismatch",`BullMQ payload team/project does not match outbox row (jobId=${i.generation_job_id})`);throw await this.auditScopeViolation(i,s,a,t),await qc({pool:this.options.pool,job:s,reason:a.message,classification:"scope_mismatch",retryable:!1,...this.options.workerId!==void 0?{workerId:this.options.workerId}:{}}),a}if(i.api_key_id&&await this.isApiKeyRevoked(i.api_key_id)){let c=new om("revoked_key",`api key ${i.api_key_id} is revoked; refusing to generate for outbox ${s.id}`);throw await this.auditRevokedKey(i,s,c,t),await qc({pool:this.options.pool,job:s,reason:c.message,classification:"revoked_key",retryable:!1,...this.options.workerId!==void 0?{workerId:this.options.workerId}:{}}),c}let o=await this.lockOutbox(i.generation_job_id,i.team_id,i.project_id);if(!o)return _.info("SYSTEM","job no longer exists or is in terminal status; nothing to do",{correlationId:t,generationJobId:i.generation_job_id}),{jobId:i.generation_job_id,status:"completed",observationCount:0};_.info("SYSTEM","[generation] job locked for processing",{correlationId:t,jobId:o.id,bullmqJobId:e.id??null,requestId:n,sourceType:o.sourceType,attempt:o.attempts}),await this.auditEvent({teamId:o.teamId,projectId:o.projectId,apiKeyId:i.api_key_id,actorId:i.actor_id,action:"generation_job.processing",resourceId:o.id,details:{sourceType:o.sourceType,sourceId:o.sourceId,sourceAdapter:i.source_adapter,attempt:o.attempts,correlationId:t,requestId:n}});try{let a=await this.loadEvents(o,i),c=await this.loadProject(o),l=await this.options.provider.generate({job:o,events:a,project:{projectId:o.projectId,teamId:o.teamId,serverSessionId:o.serverSessionId,projectName:c?.name??null}}),u={pool:this.options.pool,job:o,rawText:l.rawText,modelId:l.modelId,providerLabel:l.providerLabel,apiKeyId:i.api_key_id,actorId:i.actor_id,sourceAdapter:i.source_adapter,...this.options.workerId!==void 0?{workerId:this.options.workerId}:{}},d=o.sourceType==="session_summary"?await h8(u):await m8(u);if(d.kind==="parse_error")throw await qc({pool:this.options.pool,job:o,reason:d.reason,classification:"parse_error",retryable:!1,...this.options.workerId!==void 0?{workerId:this.options.workerId}:{}}),new Error(`generation parse error: ${d.reason}`);return _.info("SYSTEM","generation completed",{correlationId:t,jobId:d.jobId,bullmqJobId:e.id??null,requestId:n,observationCount:d.observations.length,privateContentDetected:d.privateContentDetected}),{jobId:d.jobId,status:"completed",observationCount:d.observations.length}}catch(a){let c=a instanceof pe?a:null,l=c?c.kind==="transient"||c.kind==="rate_limit":!1;throw await qc({pool:this.options.pool,job:o,reason:a instanceof Error?a.message:String(a),classification:c?.kind??"unknown",retryable:l,...this.options.workerId!==void 0?{workerId:this.options.workerId}:{}}),a}}async loadCanonicalOutbox(e){let n=(await this.options.pool.query("SELECT * FROM observation_generation_jobs WHERE id = $1",[e])).rows[0];return n?{id:n.id,projectId:n.project_id,teamId:n.team_id,agentEventId:n.agent_event_id,sourceType:n.source_type,sourceId:n.source_id,serverSessionId:n.server_session_id,jobType:n.job_type,status:n.status,idempotencyKey:n.idempotency_key,bullmqJobId:n.bullmq_job_id,attempts:n.attempts,maxAttempts:n.max_attempts,nextAttemptAtEpoch:n.next_attempt_at?.getTime()??null,lockedAtEpoch:n.locked_at?.getTime()??null,lockedBy:n.locked_by,completedAtEpoch:n.completed_at?.getTime()??null,failedAtEpoch:n.failed_at?.getTime()??null,cancelledAtEpoch:n.cancelled_at?.getTime()??null,lastError:n.last_error&&typeof n.last_error=="object"?n.last_error:null,payload:n.payload&&typeof n.payload=="object"&&!Array.isArray(n.payload)?n.payload:{},createdAtEpoch:n.created_at.getTime(),updatedAtEpoch:n.updated_at.getTime()}:null}async isApiKeyRevoked(e){let n=(await this.options.pool.query("SELECT revoked_at, expires_at FROM api_keys WHERE id = $1",[e])).rows[0];return!!(!n||n.revoked_at||n.expires_at&&n.expires_at.getTime()<=Date.now())}async auditScopeViolation(e,t,n,i){_.error("SYSTEM","BullMQ payload scope mismatch \u2014 refusing to generate",{correlationId:i,generationJobId:e.generation_job_id,payloadTeamId:e.team_id,payloadProjectId:e.project_id,canonicalTeamId:t.teamId,canonicalProjectId:t.projectId}),await this.auditEvent({teamId:t.teamId,projectId:t.projectId,apiKeyId:e.api_key_id,actorId:e.actor_id,action:"generation_job.scope_violation",resourceId:t.id,details:{reason:"scope_mismatch",message:n.message,payloadTeamId:e.team_id,payloadProjectId:e.project_id,canonicalTeamId:t.teamId,canonicalProjectId:t.projectId,sourceAdapter:e.source_adapter,correlationId:i}})}async auditRevokedKey(e,t,n,i){_.warn("SYSTEM","api key revoked between enqueue and execute \u2014 refusing to generate",{correlationId:i,generationJobId:e.generation_job_id,apiKeyId:e.api_key_id}),await this.auditEvent({teamId:t.teamId,projectId:t.projectId,apiKeyId:e.api_key_id,actorId:e.actor_id,action:"generation_job.revoked_key",resourceId:t.id,details:{reason:"revoked_key",message:n.message,sourceAdapter:e.source_adapter,correlationId:i}})}async auditEvent(e){try{await new yt(this.options.pool).createAuditLog({teamId:e.teamId,projectId:e.projectId,actorId:e.actorId,apiKeyId:e.apiKeyId,action:e.action,resourceType:"observation_generation_job",resourceId:e.resourceId,details:e.details??{}})}catch(t){_.warn("SYSTEM","audit_log insert failed in ProviderObservationGenerator",{action:e.action,error:t instanceof Error?t.message:String(t)})}}async lockOutbox(e,t,n){let i=new Ge(this.options.pool),s=await i.getByIdForScope({id:e,projectId:n,teamId:t});return!s||s.status==="completed"||s.status==="cancelled"||s.status==="failed"?null:s.status==="processing"?(_.info("SYSTEM","generation job already in processing; skipping duplicate worker run",{jobId:s.id,lockedBy:s.lockedBy,lockedAtEpoch:s.lockedAtEpoch,attempts:s.attempts}),null):await i.transitionStatus({id:s.id,projectId:s.projectId,teamId:s.teamId,status:"processing",lockedBy:this.options.workerId??"server-beta-worker"})}async loadEvents(e,t){let n=new mr(this.options.pool);if(e.sourceType==="session_summary")return e.serverSessionId?await new Ot(this.options.pool).listUnprocessedEvents({serverSessionId:e.serverSessionId,projectId:e.projectId,teamId:e.teamId}):[];if(e.sourceType!=="agent_event")return[];if(t.kind==="event"){let i=await n.getByIdForScope({id:t.agent_event_id,projectId:e.projectId,teamId:e.teamId});return i?[i]:[]}if(t.kind==="event-batch"){let i=[];for(let s of t.agent_event_ids){let o=await n.getByIdForScope({id:s,projectId:e.projectId,teamId:e.teamId});o&&i.push(o)}return i}return[]}async loadProject(e){return await new Pn(this.options.pool).getByIdForTeam(e.projectId,e.teamId)}}});var Fc,g8=R(()=>{"use strict";se();vn();b8();Fc=class{constructor(e){this.options=e;this.workerId=e.workerId??`server-beta-${process.pid}`,this.generator=e.generatorFactory?e.generatorFactory(e.pool,e.provider,this.workerId):new am({pool:e.pool,provider:e.provider,workerId:this.workerId})}options;kind="generation-worker-manager";started=!1;closed=!1;generator;workerId;start(){if(this.started)return;let e=async t=>{try{return await this.generator.process(t)}catch(n){throw _.warn("SYSTEM","observation generator failed",{jobId:t.id,kind:t.data.kind,error:n instanceof Error?n.message:String(n)}),n}};this.options.queueManager.start("event",e),this.options.queueManager.start("summary",e);for(let t of["event","summary"])try{this.options.queueManager.getQueue(t).observe({onStalled:i=>{this.auditStalledJob(i,t)}})}catch(n){_.warn("SYSTEM",`failed to wire stalled observer for ${t} lane`,{error:n instanceof Error?n.message:String(n)})}this.started=!0}async auditStalledJob(e,t){try{let i=(await this.options.pool.query("SELECT id, team_id, project_id FROM observation_generation_jobs WHERE bullmq_job_id = $1 LIMIT 1",[e])).rows[0];if(!i)return;await new yt(this.options.pool).createAuditLog({teamId:i.team_id,projectId:i.project_id,actorId:null,apiKeyId:null,action:"generation_job.stalled",resourceType:"observation_generation_job",resourceId:i.id,details:{lane:t,bullmqJobId:e}})}catch(n){_.warn("SYSTEM","failed to audit stalled generation_job",{bullmqJobId:e,error:n instanceof Error?n.message:String(n)})}}getHealth(){return this.closed?{status:"errored",reason:"generation-worker-manager closed"}:{status:this.started?"active":"disabled",reason:this.started?"BullMQ Worker attached to event queue with ProviderObservationGenerator":"wired but not started",details:{provider:this.options.provider.providerLabel,workerId:this.workerId}}}async close(){this.closed||(this.closed=!0)}}});function Ai(r,e={}){let t=e.mode??$le(),n=!1,i=!0,s=[];for(let d of r.events){let p=Ble(d);p.hadPrivate&&(n=!0),p.body.length>0&&(i=!1,s.push(p.body))}let o=r.events.length>0&&i,a=r.project.serverSessionId?`
|
|
9542
9542
|
<server_session_id>${Nn(r.project.serverSessionId)}</server_session_id>`:"",c=r.project.projectName?`
|
|
9543
9543
|
<project_name>${Nn(r.project.projectName)}</project_name>`:"",l=Hle(t);return{prompt:["<server_beta_observation_request>",` <project_id>${Nn(r.project.projectId)}</project_id>`,` <team_id>${Nn(r.project.teamId)}</team_id>`+a+c,` <generation_job_id>${Nn(r.job.id)}</generation_job_id>`," <agent_events>",s.length>0?s.join(`
|
|
9544
|
-
`):" <!-- empty after privacy stripping -->"," </agent_events>","</server_beta_observation_request>","","You are observing an agent at work. Return one or more","<observation>...</observation> XML blocks summarizing durable, useful","discoveries from the events above. If the events contain nothing worth","recording (e.g., everything was scrubbed by privacy filters or the","activity was trivial), return a single self-closing <skip_summary />","tag and nothing else. Do not include any prose outside the XML.","","Schema for each <observation> block:",l].join(`
|
|
9544
|
+
`):" <!-- empty after privacy stripping -->"," </agent_events>","</server_beta_observation_request>","","You are observing an agent at work. Return one or more","<observation>...</observation> XML blocks summarizing durable, useful","discoveries from the events above. If the events contain nothing worth","recording (e.g., everything was scrubbed by privacy filters or the","activity was trivial), return a single self-closing <skip_summary />","tag and nothing else. Do not include any prose outside the XML.","","LANGUAGE: Write every field (title, subtitle, facts, narrative, concepts)","in English ONLY. Never emit Chinese, Japanese, Korean, or any other","non-English text in these fields, even when the source events contain","such text \u2014 translate or summarize into English instead. Keep code","identifiers, file paths, and commands verbatim.","","Schema for each <observation> block:",l].join(`
|
|
9545
9545
|
`),hadPrivateContent:n,skippedAll:o}}function Ble(r){let e=typeof r.payload=="string"?r.payload:JSON.stringify(r.payload??{},null,2),t=Dc(e),n=(t.counts.private??0)>0,i=t.stripped.length>v8?t.stripped.slice(0,v8)+`
|
|
9546
9546
|
[...truncated]`:t.stripped;return i.trim().length===0?{body:"",hadPrivate:n}:{body:[" <agent_event>",` <id>${Nn(r.id)}</id>`,` <event_type>${Nn(r.eventType)}</event_type>`,` <source_adapter>${Nn(r.sourceAdapter)}</source_adapter>`,` <occurred_at>${new Date(r.occurredAtEpoch).toISOString()}</occurred_at>`," <payload>",Nn(i)," </payload>"," </agent_event>"].join(`
|
|
9547
9547
|
`),hadPrivate:n}}function $le(){try{return Je.getInstance().getActiveMode()}catch{return{observation_types:Gle}}}function Hle(r){return["<observation>",` <type>[ ${r.observation_types.map(t=>t.id).join(" | ")} ]</type>`," <title>...</title>"," <subtitle>...</subtitle>"," <facts><fact>...</fact></facts>"," <narrative>...</narrative>"," <concepts><concept>...</concept></concepts>"," <files_read><file>...</file></files_read>"," <files_modified><file>...</file></files_modified>","</observation>"].join(`
|