claude-mem 13.26.0 → 13.26.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -64,7 +64,7 @@ ${m.stack??""}
64
64
  `)}else za(p+`
65
65
  `)}debug(e,r,n,i){this.log(0,e,r,n,i)}info(e,r,n,i){this.log(1,e,r,n,i)}warn(e,r,n,i){this.log(2,e,r,n,i)}setErrorSink(e){UE=e}error(e,r,n,i){this.log(3,e,r,n,i),this.routeErrorToSink(r,n,i)}routeErrorToSink(e,r,n){try{if(!UE||!(n instanceof Error))return;UE(n)}catch{}}dataIn(e,r,n,i){this.info(e,`\u2192 ${r}`,n,i)}dataOut(e,r,n,i){this.info(e,`\u2190 ${r}`,n,i)}success(e,r,n,i){this.info(e,`\u2713 ${r}`,n,i)}failure(e,r,n,i){this.error(e,`\u2717 ${r}`,n,i)}},x=new zE});function xf(t){return/^Bearer\s+(.+)$/i.exec(t.trim())?.[1]?.trim()||null}function wf(t){let e=t.ip||t.socket.remoteAddress||"";return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"||e==="localhost"}function dM(t){let e=kie(t.header("host")??"");return e==="127.0.0.1"||e==="localhost"||e==="::1"}function kie(t){let e=t.trim().toLowerCase();if(e.startsWith("[")){let n=e.indexOf("]");return n===-1?e:e.slice(1,n)}let r=e.lastIndexOf(":");return r>-1&&/^\d+$/.test(e.slice(r+1))?e.slice(0,r):e}function _f(t){return!!(t.header("forwarded")||t.header("x-forwarded-for")||t.header("x-forwarded-host")||t.header("x-real-ip"))}var GE=R(()=>{"use strict"});function hM(){let t=[];t.push(BE.default.json({limit:"5mb"})),t.push((n,i,s)=>{let a=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(f=>n.path.endsWith(f)),c=n.path==="/api/logs";if(n.path.startsWith("/health")||n.path==="/"||a||c)return s();let l=Date.now(),u=`${n.method}-${Date.now()}`,d=Die(n.method,n.path,n.body);x.debug("HTTP",`\u2192 ${n.method} ${n.path}`,{requestId:u},d);let p=i.send.bind(i);i.send=function(f){let m=Date.now()-l;return x.debug("HTTP",`\u2190 ${i.statusCode} ${n.path}`,{requestId:u,duration:`${m}ms`}),p(f)},s()});let e=bo(),r=mM.default.join(e,"plugin","ui");return t.push(BE.default.static(r)),t}function yM(){return(t,e,r)=>{let n=t.headers.origin;if(n){if(!n.startsWith("http://localhost:")&&!n.startsWith("http://127.0.0.1:")){e.status(403).json({error:"Forbidden",message:"CORS not allowed"});return}e.setHeader("Access-Control-Allow-Origin",n),e.setHeader("Vary","Origin")}if(t.method==="OPTIONS"){e.setHeader("Access-Control-Allow-Methods","GET,HEAD,POST,PUT,PATCH,DELETE"),e.setHeader("Access-Control-Allow-Headers","Content-Type,Authorization,X-Requested-With"),e.status(204).end();return}r()}}function If(t,e,r){let n=t.ip||t.connection.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){x.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:t.path,clientIp:n,method:t.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}r()}function Oie(t,e){let r=(0,Ga.createHash)("sha256").update(t,"utf8").digest(),n=(0,Ga.createHash)("sha256").update(e,"utf8").digest();if(r.length!==n.length)return!1;try{return(0,Ga.timingSafeEqual)(r,n)}catch(i){let s=i instanceof Error?i:new Error(String(i));return x.warn("SECURITY","timing-safe secret comparison failed",{},s),!1}}function Cie(t){return Rie.has(t.method.toUpperCase())?Aie.has(t.path)?!t.expectedToken||!t.presentedToken?{allow:!1,status:401,reason:"token"}:Oie(t.presentedToken,t.expectedToken)?{allow:!0}:{allow:!1,status:401,reason:"token"}:{allow:!1,status:404,reason:"path"}:{allow:!1,status:403,reason:"method"}}function jie(t){let e=Date.now(),r=vo.get(t.clientIp);if(r&&e-r.windowStart>fM&&(r.count=0,r.windowStart=e),!r){if(vo.size>=pM){let n=null,i=1/0;for(let[s,o]of vo)e-o.windowStart>fM?vo.delete(s):o.windowStart<i&&(i=o.windowStart,n=s);n!==null&&vo.size>=pM&&vo.delete(n)}r={count:0,windowStart:e},vo.set(t.clientIp,r)}r.count+=1,r.count<=Pie?x.warn("SECURITY","Remote request denied",t):x.debug("SECURITY","Remote request denied",t)}function Kie(t){let e=t.query?.token;if(Array.isArray(e)||typeof e!="string")return null;let r=e.trim();return r.length>0?r:null}function gM(t){return(e,r,n)=>{if(wf(e)&&!_f(e)){n();return}let i=e.ip||e.socket.remoteAddress||"",s=xf(e.header("authorization")??"")||e.header("x-api-key")?.trim()||Kie(e)||null,o=Cie({method:e.method,path:e.path,presentedToken:s,expectedToken:t.getToken()});if(!o.allow){jie({path:e.path,method:e.method,clientIp:i,reason:o.reason}),o.status===404?r.status(404).json({error:"Not found"}):o.status===403?r.status(403).json({error:"Forbidden",message:"Observation TV remote access is read-only"}):r.status(401).json({error:"Unauthorized",message:"Missing or invalid Observation TV token"});return}r.setHeader("Cache-Control","no-store"),n()}}function Die(t,e,r){if(!r||Object.keys(r).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=r.tool_name||"?",i=r.tool_input;return`tool=${x.formatTool(n,i)}`}return e.includes("/summarize")?"requesting summary":""}var BE,mM,Ga,Aie,Rie,Pie,pM,fM,vo,bM=R(()=>{"use strict";BE=tt(Ef(),1),mM=tt(require("path"),1),Ga=require("crypto");Hn();GE();fe();Aie=new Set(["/tv","/tv.html","/stream","/api/observations"]),Rie=new Set(["GET","HEAD"]);Pie=10,pM=512,fM=6e4,vo=new Map});function vM(t,e,r,n){let i={error:t,message:e};return r&&(i.code=r),n&&(i.details=n),i}function SM(t,e){e.status(404).json(vM("NotFound",`Cannot ${t.method} ${t.path}`))}var Ba,EM,xM=R(()=>{"use strict";fe();Ba=class extends Error{constructor(r,n=500,i,s){super(r);this.statusCode=n;this.code=i;this.details=s;this.name="AppError"}statusCode;code;details};EM=(t,e,r,n)=>{let i=t instanceof Ba?t.statusCode:500;x.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:t.message,code:t instanceof Ba?t.code:void 0},t);let s=vM(t.name||"Error",t.message,t instanceof Ba?t.code:void 0,t instanceof Ba?t.details:void 0);r.status(i).json(s)}});var Mie,Nie,sje,wM=R(()=>{"use strict";Mie=new Set([".cmd",".bat"]),Nie=new Set([".exe",".com"]),sje=new Set([...Nie,...Mie])});function Ha(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(qie.has(r)){e[r]=n;continue}VE.has(r)||HE.some(i=>r.startsWith(i))||(e[r]=n)}return e}var HE,VE,Lie,qie,eu=R(()=>{"use strict";HE=["CLAUDECODE_","CLAUDE_CODE_"],VE=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),Lie=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy","npm_config_noproxy"]),qie=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS",...Lie])});function $ie(t){WE+=1;let e=(0,YE.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Ha(process.env),LC_ALL:"C",LANG:"C"}});if(e.status===0){let r=e.stdout.trim();return r.length>0?r:null}return null}function Uie(t,e=!1){if(!e){let n=_M.get(t);if(n&&Date.now()-n.capturedAtMs<Fie)return n.token}let r=null;try{r=$ie(t)}catch(n){x.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:n instanceof Error?n.message:String(n)}),r=null}return _M.set(t,{token:r,capturedAtMs:Date.now()}),r}function TM(t,e){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux"){WE+=1;try{let r=(0,IM.readFileSync)(`/proc/${t}/stat`,"utf-8"),n=r.lastIndexOf(") ");if(n<0)return null;let s=r.slice(n+2).split(" ")[19];return s&&/^\d+$/.test(s)?s:null}catch(r){return x.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}if(process.platform==="win32")return Uie(t,e);WE+=1;try{let r=(0,YE.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Ha(process.env),LC_ALL:"C",LANG:"C"}});if(r.status!==0)return null;let n=r.stdout.trim();return n.length>0?n:null}catch(r){return x.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}function Ti(t){return TM(t,!1)}function ki(t,e){if(e===null)return!0;let r=TM(t,!0);return r===null?!0:r===e}var YE,IM,Fie,_M,WE,QE=R(()=>{"use strict";YE=require("child_process"),IM=require("fs");fe();eu();Fie=5e3,_M=new Map,WE=0});async function Vn(t,e={}){let r=e.signalMode==="immediate",n=e.expectedStartToken!==void 0?e.expectedStartToken:Ti(t),i=()=>ki(t,n);if(!i()){x.warn("PROCESS","Skipping tree-kill: root PID was reused since it was captured",{pid:t});return}if(x.debug("PROCESS",`Killing process tree rooted at PID ${t}`,{immediate:r}),process.platform==="win32"){try{await XE("taskkill",["/PID",String(t),"/T","/F"],{timeout:5e3,windowsHide:!0})}catch(s){let o=s.code,a=String(s.stderr??""),c=s instanceof Error?s.message:String(s);if(o===Jie||zie.test(`${a} ${c}`)){x.debug("PROCESS","taskkill reported the process was already gone",{pid:t});return}throw new Tf(t,`taskkill failed for PID ${t} (exit ${String(o)}): ${a.trim()||c}`,{cause:s})}return}try{let s=r?"SIGKILL":"SIGTERM",o=await kf(t);for(let l of o){if(!ki(l.pid,l.startToken)){x.debug("PROCESS",`Skipping ${s}: descendant PID was reused since enumeration`,{pid:l.pid,rootPid:t});continue}try{process.kill(l.pid,s)}catch{}}if(i())try{process.kill(t,s)}catch(l){let u=l instanceof Error?l:new Error(String(l)),d=u.code;d!=="ESRCH"&&x.debug("PROCESS",`Failed to ${s} PID ${t}`,{code:d},u)}else x.warn("PROCESS","Skipping root signal: PID was reused during descendant enumeration",{pid:t,signal:s});r||await new Promise(l=>setTimeout(l,500));let a=i()?await kf(t):[],c=new Map;for(let l of o)c.set(l.pid,l.startToken);for(let l of a)c.set(l.pid,l.startToken);for(let[l,u]of c){if(!ki(l,u)){x.debug("PROCESS","Skipping SIGKILL: descendant PID was reused since the scan",{pid:l,rootPid:t});continue}try{process.kill(l,"SIGKILL")}catch{}}if(!r&&i())try{process.kill(t,"SIGKILL")}catch{}}catch(s){throw new Tf(t,`tree-kill failed for PID ${t}: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}async function Gie(){return process.platform==="win32"?Vie():process.platform==="linux"?Bie():Hie()}function Bie(){let t=[],e;try{e=(0,Af.readdirSync)("/proc")}catch(r){return x.warn("PROCESS","Cannot read /proc \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),t}for(let r of e){if(!/^\d+$/.test(r))continue;let n;try{n=(0,Af.readFileSync)(`/proc/${r}/stat`,"utf-8")}catch{continue}let i=n.lastIndexOf(") ");if(i<0)continue;let s=n.slice(i+2).split(" "),o=Number.parseInt(s[1]??"",10),a=s[19];Number.isFinite(o)&&t.push({pid:Number.parseInt(r,10),ppid:o,startToken:a&&/^\d+$/.test(a)?a:null})}return t}async function Hie(){let t;try{t=(await XE("ps",["-eo","pid=,ppid=,lstart="],{timeout:1e4,maxBuffer:33554432,env:{...process.env,LC_ALL:"C",LANG:"C"}})).stdout}catch(r){return x.warn("PROCESS","Cannot enumerate the process table \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),[]}let e=[];for(let r of t.split(`
66
66
  `)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);if(!n)continue;let i=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:i.length>0?i:null})}return e}async function Vie(){let t;try{t=(await XE("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,@{Name='StartToken';Expression={$_.CreationDate.ToString('yyyyMMddHHmmss.ffffff')}} | ConvertTo-Csv -NoTypeInformation"],{timeout:3e4,windowsHide:!0,maxBuffer:33554432})).stdout}catch(r){return x.warn("PROCESS","Cannot enumerate the Windows process table \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),[]}let e=[];for(let r of t.split(/\r?\n/).slice(1)){let n=r.match(/^"(\d+)","(\d+)","(.*)"$/);if(!n)continue;let i=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:i.length>0?i:null})}return e}async function kf(t){let e=await Gie(),r=new Map;for(let o of e){let a=r.get(o.ppid);a?a.push(o):r.set(o.ppid,[o])}let n=new Set([t]),i=[],s=o=>{for(let a of r.get(o)??[])n.has(a.pid)||(n.add(a.pid),s(a.pid),i.push({pid:a.pid,startToken:a.startToken}))};return s(t),i}var kM,Af,AM,XE,Jie,zie,Tf,tu=R(()=>{"use strict";kM=require("child_process"),Af=require("fs"),AM=require("util");fe();QE();XE=(0,AM.promisify)(kM.execFile),Jie=128,zie=/not found|no running instance|no tasks/i,Tf=class extends Error{pid;constructor(e,r,n){super(r,n),this.name="ProcessTreeKillError",this.pid=e}}});function Et(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;return r==="EPERM"?!0:(x.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return x.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function Rf(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!Et(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function ds(t){if(!t||!Et(t.pid))return!1;if(!t.startToken)return!0;let e=Ti(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||x.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}function Of(){return ZE||(ZE=new rS),ZE}function eS(){let t=Xie.shift();t&&t.notify()}var Ai,tS,Wie,Yie,Qie,rS,ZE,xje,Xie,Eo=R(()=>{"use strict";wM();Ai=require("fs"),tS=tt(require("path"),1);fe();eu();Hn();QE();tu();Wie=5e3,Yie=1e3,Qie=Le.supervisorRegistry();rS=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=Qie){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,Ai.mkdirSync)(tS.default.dirname(this.registryPath),{recursive:!0}),!(0,Ai.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Ai.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[i,s]of Object.entries(n))this.entries.set(i,s)}catch(r){r instanceof Error?x.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):x.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&x.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}retainSupersededEntry(e,r){let n=this.entries.get(e);if(!n||n.pid===r||!Et(n.pid))return;let i=`${e}#superseded:${n.pid}`;this.entries.set(i,n);let s=this.runtimeProcesses.get(e);s&&(this.runtimeProcesses.set(i,s),this.runtimeProcesses.delete(e)),x.warn("SYSTEM","Registry id reused while the previous process was still alive; kept it for reaping",{id:e,supersededId:i,supersededPid:n.pid,incomingPid:r})}register(e,r,n){this.initialize(),this.retainSupersededEntry(e,r.pid),this.entries.set(e,r),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let r=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),r?.type==="sdk"&&eS()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let n=Date.parse(e.startedAt),i=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(i)?0:i)})}getBySession(e){let r=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[n,i]of this.entries)Et(i.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,i.type==="sdk"&&(r+=1));e>0&&this.persist();for(let n=0;n<r;n+=1)eS();return e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;x.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:n,pids:r.map(a=>a.pid)});let i=r.filter(a=>Et(a.pid)),s=new Map(i.map(a=>[a.pid,Ti(a.pid)]));for(let a of i)try{process.platform==="win32"?await Vn(a.pid,{expectedStartToken:s.get(a.pid)??null}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&x.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):x.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}await Rf(i,Wie);let o=i.filter(a=>Et(a.pid));for(let a of o){x.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});let c=s.get(a.pid)??null;if(!ki(a.pid,c)){x.warn("SYSTEM","Skipping SIGKILL: session process PID was reused during the grace window",{pid:a.pid,sessionId:n});continue}try{process.platform==="win32"?await Vn(a.pid,{expectedStartToken:c}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(l){l instanceof Error?l.code!=="ESRCH"&&x.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},l):x.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(l)})}}if(o.length>0){let a=Date.now()+Yie;for(;Date.now()<a&&o.filter(l=>Et(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let a of r)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of r)a.type==="sdk"&&eS();return x.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:n,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,Ai.mkdirSync)(tS.default.dirname(this.registryPath),{recursive:!0}),(0,Ai.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},ZE=null;xje=180*1e3,Xie=[]});async function OM(t){let e=t.currentPid??process.pid,r=t.pidFilePath??Zie,n=t.registry.getAll(),i=[...n].filter(c=>c.pid!==e).sort((c,l)=>Date.parse(l.startedAt)-Date.parse(c.startedAt)),s=new Map,o=new Map;for(let c of i){if(!Et(c.pid)){t.registry.unregister(c.id);continue}o.set(c.id,Ti(c.pid)),s.set(c.id,await kf(c.pid));try{await RM(c,"SIGTERM")}catch(l){l instanceof Error?x.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:c.pid,pgid:c.pgid,type:c.type},l):x.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(l)})}}await Rf(i,5e3);let a=i.filter(c=>Et(c.pid)||(s.get(c.id)??[]).some(l=>Et(l.pid)));for(let c of a){let l=ki(c.pid,o.get(c.id)??null);l||x.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:c.pid,type:c.type});try{l&&await RM(c,"SIGKILL")}catch(u){u instanceof Error?x.debug("SYSTEM","Failed to force kill child process",{pid:c.pid,pgid:c.pgid,type:c.type},u):x.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(u)})}finally{tse(s.get(c.id)??[],c.pid)}}await Rf(a,1e3);for(let c of i)t.registry.unregister(c.id);for(let c of n.filter(l=>l.pid===e))t.registry.unregister(c.id);ese(r,e),t.registry.pruneDeadEntries()}function ese(t,e,r=!1){if(!(0,Va.existsSync)(t))return;let n=null;try{let o=JSON.parse((0,Va.readFileSync)(t,"utf-8"));n=typeof o.pid=="number"?o.pid:null}catch(o){x.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:o instanceof Error?o.message:String(o)});return}let i=e!==null&&n===e,s=n===null||!Et(n);if(!i&&!(r&&s)){x.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:n,currentPid:e});return}try{(0,Va.rmSync)(t,{force:!0})}catch(o){o instanceof Error?x.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},o):x.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(o)})}}function tse(t,e){for(let{pid:r,startToken:n}of t)if(!(r===e||!Et(r))){if(!ki(r,n)){x.debug("SYSTEM","Skipping reap: PID was recycled during the grace window",{pid:r,rootPid:e});continue}try{process.kill(r,"SIGKILL"),x.debug("SYSTEM","Reaped orphaned descendant during shutdown cascade",{pid:r,rootPid:e})}catch(i){let s=i instanceof Error?i.code:void 0;s!=="ESRCH"&&x.warn("SYSTEM","Failed to reap orphaned descendant during shutdown cascade",{pid:r,rootPid:e,errno:s})}}}async function RM(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}if(e==="SIGKILL"){await Vn(r,{signalMode:"immediate"});return}try{process.kill(r,e)}catch(i){if((i instanceof Error?i.code:void 0)!=="ESRCH")throw i}return}await Vn(r)}var Va,Zie,CM=R(()=>{"use strict";Va=require("fs");fe();Eo();Hn();tu();Zie=Le.workerPid()});function rse(){let e=Of().pruneDeadEntries();e>0&&x.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function jM(){Wa===null&&(Wa=setInterval(rse,PM),Wa.unref(),x.debug("SYSTEM","Health checker started",{intervalMs:PM}))}function KM(){Wa!==null&&(clearInterval(Wa),Wa=null,x.debug("SYSTEM","Health checker stopped"))}var PM,Wa,DM=R(()=>{"use strict";fe();Eo();PM=3e4,Wa=null});function sse(t){let e=[];for(let r of t.split(`
67
- `)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);n&&e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),command:n[3].trim()})}return e}async function ose(){let t=await nse("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return sse(t.stdout)}function ase(t,e){let r=t.filter(o=>ise.test(o.command)&&o.pid!==e.selfPid),n=new Set(r.map(o=>o.pid)),i=r.filter(o=>!n.has(o.ppid)),s=i.filter(o=>o.ppid===e.selfPid?!1:o.ppid===1?!0:!e.isAlive(o.ppid));return{matched:r,roots:i,orphans:s}}async function LM(t={}){let e=t.platform??process.platform,r={matched:0,trees:0,orphans:0,killed:0,failed:0,unregistered:0,skipped:null};if(e==="win32")return r.skipped="windows",r;let n=t.readTable??ose,i=t.isAlive??Et,s=t.killTree??(f=>Vn(f,{signalMode:"graceful"})),o=t.selfPid??process.pid,a;try{a=await n()}catch(f){return x.warn("PROCESS","Orphaned chroma-mcp sweep skipped: cannot read the process table",{error:f instanceof Error?f.message:String(f)}),r.skipped="unreadable",r}let{matched:c,roots:l,orphans:u}=ase(a,{isAlive:i,selfPid:o});if(r.matched=c.length,r.trees=l.length,r.orphans=u.length,u.length===0)return x.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:r.matched,trees:r.trees}),r;x.warn("PROCESS","Reaping orphaned chroma-mcp trees left by dead workers",{orphans:u.length,roots:u.map(f=>f.pid)});let d=new Set,p=8;for(let f=0;f<u.length;f+=p){let m=u.slice(f,f+p);(await Promise.allSettled(m.map(b=>s(b.pid)))).forEach((b,v)=>{let E=m[v];b.status==="fulfilled"?(r.killed+=1,d.add(E.pid)):(r.failed+=1,x.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:E.pid,ppid:E.ppid,error:b.reason instanceof Error?b.reason.message:String(b.reason)}))})}if(t.registry)for(let f of t.registry.getAll())f.type==="chroma"&&d.has(f.pid)&&(t.registry.unregister(f.id),r.unregistered+=1);return x.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:r.orphans,killed:r.killed,failed:r.failed,unregistered:r.unregistered}),r}var MM,NM,nse,ise,qM=R(()=>{"use strict";MM=require("child_process"),NM=require("util");fe();tu();Eo();nse=(0,NM.promisify)(MM.execFile),ise=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/});function FM(){return lse}function use(t={}){let e=t.pidFilePath??cse;if(!(0,So.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,So.readFileSync)(e,"utf-8"))}catch(i){return i instanceof Error?x.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},i):x.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(i)}),(0,So.rmSync)(e,{force:!0}),"invalid"}return ds(r)&&r?((t.logAlive??!0)&&x.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(x.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,So.rmSync)(e,{force:!0}),"stale")}var So,cse,nS,lse,$M=R(()=>{"use strict";So=require("fs");fe();Eo();CM();DM();qM();Hn();cse=Le.workerPid(),nS=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(),use({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,LM({registry:this.registry}).catch(r=>{x.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),jM()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){x.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,x.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){i instanceof Error?x.error("SYSTEM","Error during shutdown",{},i):x.error("SYSTEM","Error during shutdown (non-Error)",{error:String(i)});try{await this.stop()}catch(s){s instanceof Error?x.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):x.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(s)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{x.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}KM(),this.stopPromise=OM({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,n){this.registry.register(e,r,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},lse=new nS(Of())});function iS(t,e,r){t.on("finish",async()=>{try{await r()}finally{process.exit(0)}}),t.json(e)}var UM=R(()=>{"use strict"});function sS(t,e=Date.now){return Math.max(0,Math.floor((e()-t)/1e3))}var JM=R(()=>{"use strict"});function oS(){let t=Array.from(dse.values()).map(e=>({...e})).sort((e,r)=>e.dependency.localeCompare(r.dependency));return{degraded:t.length>0,statuses:t}}var dse,zM=R(()=>{"use strict";dse=new Map});function pse(t,e){return e.status!=="rejected"?!1:!t||t.status!=="rejected"?!0:t.resetsAt!==e.resetsAt}var aS,GM,Bje,BM=R(()=>{"use strict";aS=class{entries=new Map;set(e){if(!e||typeof e!="object")return!1;let r=e.rateLimitType??"default",n=this.entries.get(r);return this.entries.set(r,{...e,observedAt:Date.now()}),pse(n,e)}get(e){return e?this.entries.get(e):this.entries.get("default")}getMostRecentByWindow(){return{five_hour:this.entries.get("five_hour"),seven_day:this.entries.get("seven_day"),seven_day_opus:this.entries.get("seven_day_opus"),seven_day_sonnet:this.entries.get("seven_day_sonnet"),overage:this.entries.get("overage")}}get size(){return this.entries.size}},GM=new aS;Bje=900*1e3});function hse(t){t.setHeader("X-Content-Type-Options","nosniff"),t.setHeader("X-Frame-Options","DENY"),t.setHeader("X-DNS-Prefetch-Control","off"),t.setHeader("Referrer-Policy","no-referrer"),t.setHeader("Cross-Origin-Opener-Policy","same-origin"),t.setHeader("Cross-Origin-Resource-Policy","same-origin"),t.setHeader("Origin-Agent-Cluster","?1"),t.removeHeader("X-Powered-By")}var WM,YM,lS,ru,QM,fse,cS,HM,mse,VM,Cf,XM=R(()=>{"use strict";WM=tt(Ef(),1),YM=tt(require("http"),1),lS=tt(require("fs"),1),ru=tt(require("path"),1);rM();fe();bM();xM();$M();Eo();eu();UM();JM();zM();BM();QM=ru.default.resolve(__CM_DIRNAME__,"../skills/mem-search"),fse=ru.default.join(QM,"operations"),cS=ru.default.join(QM,"SKILL.md"),HM=(()=>{try{let t=lS.readFileSync(cS,"utf-8");return x.info("SYSTEM","Cached SKILL.md at boot",{path:cS,bytes:Buffer.byteLength(t,"utf-8")}),t}catch(t){return x.debug("SYSTEM","SKILL.md not present at boot, /api/instructions will 404 for topic queries",{path:cS,message:t instanceof Error?t.message:String(t)}),null}})(),mse=(()=>{let t=new Map;for(let e of NE){let r=ru.default.join(fse,`${e}.md`);try{t.set(e,lS.readFileSync(r,"utf-8"))}catch(n){x.debug("SYSTEM","Operation instruction file not present at boot",{path:r,message:n instanceof Error?n.message:String(n)})}}return t.size>0&&x.info("SYSTEM","Cached operation instruction files at boot",{count:t.size,operations:Array.from(t.keys())}),t})(),VM="13.26.0";Cf=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,WM.default)(),this.app.disable("x-powered-by"),this.setupRemoteReadOnlyGuard(),this.setupSecurityHeaders(),this.setupCors(),this.setupPreBodyParserRoutes(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,r){return new Promise((n,i)=>{let s=YM.default.createServer(this.app),o=c=>{s.off("listening",a),i(c)},a=()=>{s.off("error",o),this.server=s,x.info("SYSTEM","HTTP server started",{host:r,port:e,pid:process.pid}),n()};s.once("error",o),s.once("listening",a),s.listen(e,r)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{this.server.close(n=>n?r(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,x.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(SM),this.app.use(EM)}setupMiddleware(){hM().forEach(r=>this.app.use(r))}setupRemoteReadOnlyGuard(){this.options.remoteReadOnly&&this.app.use(gM(this.options.remoteReadOnly))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,r,n)=>{hse(r),n()})}setupCors(){this.app.use(yM())}setupPreBodyParserRoutes(){this.options.preBodyParserRoutes?.forEach(e=>e.setupRoutes(this.app))}setupCoreRoutes(){this.app.get("/api/health",async(e,r)=>{let n=this.options.getQueueHealth?await this.options.getQueueHealth():null,i=n?.engine==="bullmq"&&n.redis.status==="error",s=this.options.getDependencyHealth?this.options.getDependencyHealth():oS();r.status(i?503:200).json({status:i?"degraded":"ok",...this.options.runtime?{runtime:this.options.runtime}:{},version:VM,workerPath:this.options.workerPath,uptime:sS(this.startTime),managed:process.env.CLAUDE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.options.getInitializationComplete(),mcpReady:this.options.getMcpReady(),ai:this.options.getAiStatus(),dependencies:s,rateLimits:GM.getMostRecentByWindow(),...n?{queue:n}:{}})}),this.app.get("/api/readiness",(e,r)=>{this.options.getInitializationComplete()?r.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):r.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(e,r)=>{r.status(200).json({version:VM})}),this.app.get("/api/instructions",(e,r)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!tM.includes(n))return r.status(400).json({error:"Invalid topic"});if(i&&!NE.includes(i))return r.status(400).json({error:"Invalid operation"});if(i){let o=mse.get(i);return o===void 0?(x.debug("HTTP","Instruction file not cached at boot",{operation:i}),r.status(404).json({error:"Instruction not found"})):r.json({content:[{type:"text",text:o}]})}if(HM===null)return x.debug("HTTP","SKILL.md not cached at boot",{topic:n}),r.status(404).json({error:"Instruction not found"});let s=this.extractInstructionSection(HM,n);r.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",If,async(e,r)=>{process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(r.json({status:"restarting"}),x.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):iS(r,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",If,async(e,r)=>{let n=e.query.reason==="restart"?"restart":"stop";process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(r.json({status:"shutting_down"}),x.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown",reason:n})):iS(r,{status:"shutting_down"},()=>this.options.onShutdown(n))}),this.app.get("/api/admin/doctor",If,(e,r)=>{let o=FM().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:Et(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=>VE.has(f)||HE.some(m=>f.startsWith(m))),l=sS(this.startTime),u=Math.floor(l/3600),d=Math.floor(l%3600/60),p=u>0?`${u}h ${d}m`:`${d}m`;r.json({supervisor:{running:!0,pid:process.pid,uptime:p},processes:o,health:{deadProcessPids:a,envClean:c,dependencies:this.options.getDependencyHealth?this.options.getDependencyHealth():oS()}})})}extractInstructionSection(e,r){let n={workflow:this.extractBetween(e,"## The Workflow","## Search Parameters"),search_params:this.extractBetween(e,"## Search Parameters","## Examples"),examples:this.extractBetween(e,"## Examples","## Why This Workflow"),all:e};return n[r]||n.all}extractBetween(e,r,n){let i=e.indexOf(r),s=e.indexOf(n);return i===-1?e:s===-1?e.substring(i):e.substring(i,s).trim()}}});var Rr,yse,gse,uS,ZM=R(()=>{"use strict";Rr=require("zod"),yse=Rr.z.enum(["hook","worker","provider","server","api"]),gse=Rr.z.object({id:Rr.z.string().min(1),projectId:Rr.z.string().min(1),serverSessionId:Rr.z.string().min(1).nullable().default(null),sourceType:yse,eventType:Rr.z.string().min(1),platformSource:Rr.z.string().min(1).nullable().default(null),payload:Rr.z.unknown().default({}),contentSessionId:Rr.z.string().min(1).nullable().default(null),memorySessionId:Rr.z.string().min(1).nullable().default(null),occurredAtEpoch:Rr.z.number().int().nonnegative(),createdAtEpoch:Rr.z.number().int().nonnegative()}),uS=gse.omit({id:!0,createdAtEpoch:!0}).partial({serverSessionId:!0,platformSource:!0,payload:!0,contentSessionId:!0,memorySessionId:!0})});function Ze(){return(0,Pf.randomUUID)()}function ht(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function eN(t){return Array.isArray(t)?t:[]}function De(t){return typeof t=="number"?t:new Date(t).getTime()}function Qr(t){return t==null?null:t instanceof Date?t:new Date(t)}async function se(t,e,r=[]){return(await t.query(e,r)).rows[0]??null}async function Sn(t,e,r){if(!await se(t,"SELECT id FROM projects WHERE id = $1 AND team_id = $2",[e,r]))throw new Error("project_id must belong to team_id")}async function Ri(t,e,r,n){if(!await se(t,"SELECT id FROM server_sessions WHERE id = $1 AND project_id = $2 AND team_id = $3",[e,r,n]))throw new Error("server_session_id must belong to project_id and team_id")}function nu(t){return JSON.stringify(dS(t))}function xn(t){return(0,Pf.createHash)("sha256").update(nu(t)).digest("hex")}function dS(t){if(Array.isArray(t))return t.map(dS);if(t&&typeof t=="object"){let e=t;return Object.keys(e).sort().reduce((r,n)=>(r[n]=dS(e[n]),r),{})}return t}var Pf,wn=R(()=>{"use strict";Pf=require("crypto")});function bse(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function ps(t){if(!t)return Ya;let e=bse(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:Ya}function cr(t){return typeof t!="string"?null:ps(t)}var Ya,xo=R(()=>{"use strict";Ya="claude"});function tN(t){let e=cr(t.platformSource),r=e?[e]:[];return t.sourceEventId?`agent_event:v1:${xn([t.teamId,t.projectId,t.sourceAdapter,...r,t.sourceEventId])}`:`agent_event:v1:${xn([t.teamId,t.projectId,t.sourceAdapter,...r,t.contentSessionId??t.serverSessionId??null,t.eventType,new Date(t.occurredAt).toISOString(),nu(t.payload??{})])}`}function pS(t){return{id:t.id,projectId:t.project_id,teamId:t.team_id,serverSessionId:t.server_session_id,sourceAdapter:t.source_adapter,sourceEventId:t.source_event_id,idempotencyKey:t.idempotency_key,eventType:t.event_type,platformSource:t.platform_source,payload:t.payload,metadata:ht(t.metadata),occurredAtEpoch:De(t.occurred_at),receivedAtEpoch:De(t.received_at),createdAtEpoch:De(t.created_at)}}var Xr,Qa=R(()=>{"use strict";wn();xo();Xr=class{constructor(e){this.client=e}client;async create(e){await Sn(this.client,e.projectId,e.teamId),e.serverSessionId&&await Ri(this.client,e.serverSessionId,e.projectId,e.teamId);let r=tN(e),n=cr(e.platformSource),i=await se(this.client,`
67
+ `)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);n&&e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),command:n[3].trim()})}return e}async function ose(){let t=await nse("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return sse(t.stdout)}function ase(t,e){let r=t.filter(o=>ise.test(o.command)&&o.pid!==e.selfPid),n=new Set(r.map(o=>o.pid)),i=r.filter(o=>!n.has(o.ppid)),s=i.filter(o=>o.ppid===e.selfPid?!1:o.ppid===1?!0:!e.isAlive(o.ppid));return{matched:r,roots:i,orphans:s}}async function LM(t={}){let e=t.platform??process.platform,r={matched:0,trees:0,orphans:0,killed:0,failed:0,unregistered:0,skipped:null};if(e==="win32")return r.skipped="windows",r;let n=t.readTable??ose,i=t.isAlive??Et,s=t.killTree??(f=>Vn(f,{signalMode:"graceful"})),o=t.selfPid??process.pid,a;try{a=await n()}catch(f){return x.warn("PROCESS","Orphaned chroma-mcp sweep skipped: cannot read the process table",{error:f instanceof Error?f.message:String(f)}),r.skipped="unreadable",r}let{matched:c,roots:l,orphans:u}=ase(a,{isAlive:i,selfPid:o});if(r.matched=c.length,r.trees=l.length,r.orphans=u.length,u.length===0)return x.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:r.matched,trees:r.trees}),r;x.warn("PROCESS","Reaping orphaned chroma-mcp trees left by dead workers",{orphans:u.length,roots:u.map(f=>f.pid)});let d=new Set,p=8;for(let f=0;f<u.length;f+=p){let m=u.slice(f,f+p);(await Promise.allSettled(m.map(b=>s(b.pid)))).forEach((b,v)=>{let E=m[v];b.status==="fulfilled"?(r.killed+=1,d.add(E.pid)):(r.failed+=1,x.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:E.pid,ppid:E.ppid,error:b.reason instanceof Error?b.reason.message:String(b.reason)}))})}if(t.registry)for(let f of t.registry.getAll())f.type==="chroma"&&d.has(f.pid)&&(t.registry.unregister(f.id),r.unregistered+=1);return x.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:r.orphans,killed:r.killed,failed:r.failed,unregistered:r.unregistered}),r}var MM,NM,nse,ise,qM=R(()=>{"use strict";MM=require("child_process"),NM=require("util");fe();tu();Eo();nse=(0,NM.promisify)(MM.execFile),ise=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/});function FM(){return lse}function use(t={}){let e=t.pidFilePath??cse;if(!(0,So.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,So.readFileSync)(e,"utf-8"))}catch(i){return i instanceof Error?x.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},i):x.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(i)}),(0,So.rmSync)(e,{force:!0}),"invalid"}return ds(r)&&r?((t.logAlive??!0)&&x.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(x.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,So.rmSync)(e,{force:!0}),"stale")}var So,cse,nS,lse,$M=R(()=>{"use strict";So=require("fs");fe();Eo();CM();DM();qM();Hn();cse=Le.workerPid(),nS=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(),use({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,LM({registry:this.registry}).catch(r=>{x.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),jM()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){x.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,x.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){i instanceof Error?x.error("SYSTEM","Error during shutdown",{},i):x.error("SYSTEM","Error during shutdown (non-Error)",{error:String(i)});try{await this.stop()}catch(s){s instanceof Error?x.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):x.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(s)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{x.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}KM(),this.stopPromise=OM({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,n){this.registry.register(e,r,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},lse=new nS(Of())});function iS(t,e,r){t.on("finish",async()=>{try{await r()}finally{process.exit(0)}}),t.json(e)}var UM=R(()=>{"use strict"});function sS(t,e=Date.now){return Math.max(0,Math.floor((e()-t)/1e3))}var JM=R(()=>{"use strict"});function oS(){let t=Array.from(dse.values()).map(e=>({...e})).sort((e,r)=>e.dependency.localeCompare(r.dependency));return{degraded:t.length>0,statuses:t}}var dse,zM=R(()=>{"use strict";dse=new Map});function pse(t,e){return e.status!=="rejected"?!1:!t||t.status!=="rejected"?!0:t.resetsAt!==e.resetsAt}var aS,GM,Bje,BM=R(()=>{"use strict";aS=class{entries=new Map;set(e){if(!e||typeof e!="object")return!1;let r=e.rateLimitType??"default",n=this.entries.get(r);return this.entries.set(r,{...e,observedAt:Date.now()}),pse(n,e)}get(e){return e?this.entries.get(e):this.entries.get("default")}getMostRecentByWindow(){return{five_hour:this.entries.get("five_hour"),seven_day:this.entries.get("seven_day"),seven_day_opus:this.entries.get("seven_day_opus"),seven_day_sonnet:this.entries.get("seven_day_sonnet"),overage:this.entries.get("overage")}}get size(){return this.entries.size}},GM=new aS;Bje=900*1e3});function hse(t){t.setHeader("X-Content-Type-Options","nosniff"),t.setHeader("X-Frame-Options","DENY"),t.setHeader("X-DNS-Prefetch-Control","off"),t.setHeader("Referrer-Policy","no-referrer"),t.setHeader("Cross-Origin-Opener-Policy","same-origin"),t.setHeader("Cross-Origin-Resource-Policy","same-origin"),t.setHeader("Origin-Agent-Cluster","?1"),t.removeHeader("X-Powered-By")}var WM,YM,lS,ru,QM,fse,cS,HM,mse,VM,Cf,XM=R(()=>{"use strict";WM=tt(Ef(),1),YM=tt(require("http"),1),lS=tt(require("fs"),1),ru=tt(require("path"),1);rM();fe();bM();xM();$M();Eo();eu();UM();JM();zM();BM();QM=ru.default.resolve(__CM_DIRNAME__,"../skills/mem-search"),fse=ru.default.join(QM,"operations"),cS=ru.default.join(QM,"SKILL.md"),HM=(()=>{try{let t=lS.readFileSync(cS,"utf-8");return x.info("SYSTEM","Cached SKILL.md at boot",{path:cS,bytes:Buffer.byteLength(t,"utf-8")}),t}catch(t){return x.debug("SYSTEM","SKILL.md not present at boot, /api/instructions will 404 for topic queries",{path:cS,message:t instanceof Error?t.message:String(t)}),null}})(),mse=(()=>{let t=new Map;for(let e of NE){let r=ru.default.join(fse,`${e}.md`);try{t.set(e,lS.readFileSync(r,"utf-8"))}catch(n){x.debug("SYSTEM","Operation instruction file not present at boot",{path:r,message:n instanceof Error?n.message:String(n)})}}return t.size>0&&x.info("SYSTEM","Cached operation instruction files at boot",{count:t.size,operations:Array.from(t.keys())}),t})(),VM="13.26.1";Cf=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,WM.default)(),this.app.disable("x-powered-by"),this.setupRemoteReadOnlyGuard(),this.setupSecurityHeaders(),this.setupCors(),this.setupPreBodyParserRoutes(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,r){return new Promise((n,i)=>{let s=YM.default.createServer(this.app),o=c=>{s.off("listening",a),i(c)},a=()=>{s.off("error",o),this.server=s,x.info("SYSTEM","HTTP server started",{host:r,port:e,pid:process.pid}),n()};s.once("error",o),s.once("listening",a),s.listen(e,r)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{this.server.close(n=>n?r(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,x.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(SM),this.app.use(EM)}setupMiddleware(){hM().forEach(r=>this.app.use(r))}setupRemoteReadOnlyGuard(){this.options.remoteReadOnly&&this.app.use(gM(this.options.remoteReadOnly))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,r,n)=>{hse(r),n()})}setupCors(){this.app.use(yM())}setupPreBodyParserRoutes(){this.options.preBodyParserRoutes?.forEach(e=>e.setupRoutes(this.app))}setupCoreRoutes(){this.app.get("/api/health",async(e,r)=>{let n=this.options.getQueueHealth?await this.options.getQueueHealth():null,i=n?.engine==="bullmq"&&n.redis.status==="error",s=this.options.getDependencyHealth?this.options.getDependencyHealth():oS();r.status(i?503:200).json({status:i?"degraded":"ok",...this.options.runtime?{runtime:this.options.runtime}:{},version:VM,workerPath:this.options.workerPath,uptime:sS(this.startTime),managed:process.env.CLAUDE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.options.getInitializationComplete(),mcpReady:this.options.getMcpReady(),ai:this.options.getAiStatus(),dependencies:s,rateLimits:GM.getMostRecentByWindow(),...n?{queue:n}:{}})}),this.app.get("/api/readiness",(e,r)=>{this.options.getInitializationComplete()?r.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):r.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(e,r)=>{r.status(200).json({version:VM})}),this.app.get("/api/instructions",(e,r)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!tM.includes(n))return r.status(400).json({error:"Invalid topic"});if(i&&!NE.includes(i))return r.status(400).json({error:"Invalid operation"});if(i){let o=mse.get(i);return o===void 0?(x.debug("HTTP","Instruction file not cached at boot",{operation:i}),r.status(404).json({error:"Instruction not found"})):r.json({content:[{type:"text",text:o}]})}if(HM===null)return x.debug("HTTP","SKILL.md not cached at boot",{topic:n}),r.status(404).json({error:"Instruction not found"});let s=this.extractInstructionSection(HM,n);r.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",If,async(e,r)=>{process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(r.json({status:"restarting"}),x.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):iS(r,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",If,async(e,r)=>{let n=e.query.reason==="restart"?"restart":"stop";process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(r.json({status:"shutting_down"}),x.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown",reason:n})):iS(r,{status:"shutting_down"},()=>this.options.onShutdown(n))}),this.app.get("/api/admin/doctor",If,(e,r)=>{let o=FM().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:Et(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=>VE.has(f)||HE.some(m=>f.startsWith(m))),l=sS(this.startTime),u=Math.floor(l/3600),d=Math.floor(l%3600/60),p=u>0?`${u}h ${d}m`:`${d}m`;r.json({supervisor:{running:!0,pid:process.pid,uptime:p},processes:o,health:{deadProcessPids:a,envClean:c,dependencies:this.options.getDependencyHealth?this.options.getDependencyHealth():oS()}})})}extractInstructionSection(e,r){let n={workflow:this.extractBetween(e,"## The Workflow","## Search Parameters"),search_params:this.extractBetween(e,"## Search Parameters","## Examples"),examples:this.extractBetween(e,"## Examples","## Why This Workflow"),all:e};return n[r]||n.all}extractBetween(e,r,n){let i=e.indexOf(r),s=e.indexOf(n);return i===-1?e:s===-1?e.substring(i):e.substring(i,s).trim()}}});var Rr,yse,gse,uS,ZM=R(()=>{"use strict";Rr=require("zod"),yse=Rr.z.enum(["hook","worker","provider","server","api"]),gse=Rr.z.object({id:Rr.z.string().min(1),projectId:Rr.z.string().min(1),serverSessionId:Rr.z.string().min(1).nullable().default(null),sourceType:yse,eventType:Rr.z.string().min(1),platformSource:Rr.z.string().min(1).nullable().default(null),payload:Rr.z.unknown().default({}),contentSessionId:Rr.z.string().min(1).nullable().default(null),memorySessionId:Rr.z.string().min(1).nullable().default(null),occurredAtEpoch:Rr.z.number().int().nonnegative(),createdAtEpoch:Rr.z.number().int().nonnegative()}),uS=gse.omit({id:!0,createdAtEpoch:!0}).partial({serverSessionId:!0,platformSource:!0,payload:!0,contentSessionId:!0,memorySessionId:!0})});function Ze(){return(0,Pf.randomUUID)()}function ht(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function eN(t){return Array.isArray(t)?t:[]}function De(t){return typeof t=="number"?t:new Date(t).getTime()}function Qr(t){return t==null?null:t instanceof Date?t:new Date(t)}async function se(t,e,r=[]){return(await t.query(e,r)).rows[0]??null}async function Sn(t,e,r){if(!await se(t,"SELECT id FROM projects WHERE id = $1 AND team_id = $2",[e,r]))throw new Error("project_id must belong to team_id")}async function Ri(t,e,r,n){if(!await se(t,"SELECT id FROM server_sessions WHERE id = $1 AND project_id = $2 AND team_id = $3",[e,r,n]))throw new Error("server_session_id must belong to project_id and team_id")}function nu(t){return JSON.stringify(dS(t))}function xn(t){return(0,Pf.createHash)("sha256").update(nu(t)).digest("hex")}function dS(t){if(Array.isArray(t))return t.map(dS);if(t&&typeof t=="object"){let e=t;return Object.keys(e).sort().reduce((r,n)=>(r[n]=dS(e[n]),r),{})}return t}var Pf,wn=R(()=>{"use strict";Pf=require("crypto")});function bse(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function ps(t){if(!t)return Ya;let e=bse(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:Ya}function cr(t){return typeof t!="string"?null:ps(t)}var Ya,xo=R(()=>{"use strict";Ya="claude"});function tN(t){let e=cr(t.platformSource),r=e?[e]:[];return t.sourceEventId?`agent_event:v1:${xn([t.teamId,t.projectId,t.sourceAdapter,...r,t.sourceEventId])}`:`agent_event:v1:${xn([t.teamId,t.projectId,t.sourceAdapter,...r,t.contentSessionId??t.serverSessionId??null,t.eventType,new Date(t.occurredAt).toISOString(),nu(t.payload??{})])}`}function pS(t){return{id:t.id,projectId:t.project_id,teamId:t.team_id,serverSessionId:t.server_session_id,sourceAdapter:t.source_adapter,sourceEventId:t.source_event_id,idempotencyKey:t.idempotency_key,eventType:t.event_type,platformSource:t.platform_source,payload:t.payload,metadata:ht(t.metadata),occurredAtEpoch:De(t.occurred_at),receivedAtEpoch:De(t.received_at),createdAtEpoch:De(t.created_at)}}var Xr,Qa=R(()=>{"use strict";wn();xo();Xr=class{constructor(e){this.client=e}client;async create(e){await Sn(this.client,e.projectId,e.teamId),e.serverSessionId&&await Ri(this.client,e.serverSessionId,e.projectId,e.teamId);let r=tN(e),n=cr(e.platformSource),i=await se(this.client,`
68
68
  INSERT INTO agent_events (
69
69
  id, project_id, team_id, server_session_id, source_adapter,
70
70
  source_event_id, idempotency_key, event_type, platform_source, payload, metadata, occurred_at
@@ -358,7 +358,7 @@ data:
358
358
  )
359
359
  ORDER BY e.occurred_at ASC
360
360
  LIMIT $4
361
- `,[e.serverSessionId,e.projectId,e.teamId,r])).rows.map(ebe)}}});function T$(t){let e=nbe.safeParse(t);if(!e.success)throw new ld(e.error.issues);return e.data}var tr,Mc,_$,I$,tbe,rbe,nbe,ld,wh=R(()=>{"use strict";tr=require("zod"),Mc={event:"server_beta_generate_event",summary:"server_beta_generate_summary"},_$={event:"evt",summary:"sum"},I$=tr.z.object({team_id:tr.z.string().min(1,"team_id is required"),project_id:tr.z.string().min(1,"project_id is required"),source_type:tr.z.enum(["agent_event","session_summary","observation_reindex"]),source_id:tr.z.string().min(1,"source_id is required"),generation_job_id:tr.z.string().min(1,"generation_job_id is required"),api_key_id:tr.z.string().min(1).nullable(),actor_id:tr.z.string().min(1).nullable(),source_adapter:tr.z.string().min(1,"source_adapter is required"),request_id:tr.z.string().min(1).nullable().optional()}),tbe=I$.extend({kind:tr.z.literal("event"),agent_event_id:tr.z.string().min(1)}),rbe=I$.extend({kind:tr.z.literal("summary"),server_session_id:tr.z.string().min(1)}),nbe=tr.z.discriminatedUnion("kind",[tbe,rbe]),ld=class extends Error{issues;constructor(e){super(`invalid server generation job payload: ${e.map(r=>r.message).join("; ")}`),this.issues=e}}});function Nc(t){let e=_$[t.kind],r=JSON.stringify({kind:t.kind,team_id:t.team_id,project_id:t.project_id,source_type:t.source_type,source_id:t.source_id}),n=(0,k$.createHash)("sha256").update(r).digest("hex");return`${e}_${n}`}var k$,RI=R(()=>{"use strict";k$=require("crypto");wh()});function A$(t){return{kind:"event",team_id:t.event.teamId,project_id:t.event.projectId,source_type:"agent_event",source_id:t.event.id,generation_job_id:t.outboxId,agent_event_id:t.event.id,api_key_id:t.apiKeyId,actor_id:t.actorId,source_adapter:t.sourceAdapter??t.event.sourceAdapter??"api",request_id:t.requestId}}var R$,_h,O$=R(()=>{"use strict";Qa();fs();Ro();fe();RI();wn();R$="observation_generate_for_event",_h=class{constructor(e){this.options=e}options;async ingestOne(e,r={}){let n=r.generate??!0,i=r.source??"http_post_v1_events",s=await In(this.options.pool,async a=>{let l=await new Xr(a).create(e);if(!n)return{event:l,outbox:null};let u=new dt(a),d=new Wt(a),p=Ze(),f=A$({outboxId:p,event:l,apiKeyId:r.apiKeyId??null,actorId:r.actorId??null,sourceAdapter:r.sourceAdapter??null,requestId:r.requestId??null}),m=await u.create({id:p,projectId:l.projectId,teamId:l.teamId,sourceType:"agent_event",sourceId:l.id,agentEventId:l.id,serverSessionId:l.serverSessionId,jobType:R$,bullmqJobId:Nc({kind:"event",team_id:l.teamId,project_id:l.projectId,source_type:"agent_event",source_id:l.id}),payload:f});return await d.append({generationJobId:m.id,projectId:m.projectId,teamId:m.teamId,eventType:"queued",statusAfter:m.status,attempt:m.attempts,details:{source:i}}),{event:l,outbox:m}}),o="skipped";return s.outbox&&(o=await this.publishEventJob(s.event,s.outbox)),{event:s.event,outbox:s.outbox,enqueueState:o}}async ingestBatch(e,r={}){let n=r.generate??!0,i=r.source??"http_post_v1_events_batch",s=await In(this.options.pool,async o=>{let a=new Xr(o),c=new dt(o),l=new Wt(o),u=[];for(let d of e){let p=await a.create(d);if(!n){u.push({event:p,outbox:null});continue}let f=Ze(),m=A$({outboxId:f,event:p,apiKeyId:r.apiKeyId??null,actorId:r.actorId??null,sourceAdapter:r.sourceAdapter??null,requestId:r.requestId??null}),y=await c.create({id:f,projectId:p.projectId,teamId:p.teamId,sourceType:"agent_event",sourceId:p.id,agentEventId:p.id,serverSessionId:p.serverSessionId,jobType:R$,bullmqJobId:Nc({kind:"event",team_id:p.teamId,project_id:p.projectId,source_type:"agent_event",source_id:p.id}),payload:m});await l.append({generationJobId:y.id,projectId:y.projectId,teamId:y.teamId,eventType:"queued",statusAfter:y.status,attempt:y.attempts,details:{source:i}}),u.push({event:p,outbox:y})}return u});return Promise.all(s.map(async({event:o,outbox:a})=>{let c=a?await this.publishEventJob(o,a):"skipped";return{event:o,outbox:a,enqueueState:c}}))}async publishEventJob(e,r){let n=this.options.resolveEventQueue();if(!n)return"queued_only";let i=r.bullmqJobId??Nc({kind:"event",team_id:e.teamId,project_id:e.projectId,source_type:"agent_event",source_id:e.id});try{return await n.add(i,r.payload),"enqueued"}catch(s){return x.warn("SYSTEM","failed to publish event generation job to BullMQ",{outboxId:r.id,error:s instanceof Error?s.message:String(s)}),"queued_only"}}}});function OI(t){return Nc({kind:"summary",team_id:t.teamId,project_id:t.projectId,source_type:"session_summary",source_id:t.serverSessionId})}function CI(t){return{kind:"summary",team_id:t.teamId,project_id:t.projectId,source_type:"session_summary",source_id:t.serverSessionId,generation_job_id:t.generationJobId,server_session_id:t.serverSessionId,api_key_id:t.apiKeyId??null,actor_id:t.actorId??null,source_adapter:t.sourceAdapter??"api",request_id:t.requestId??null}}var C$=R(()=>{"use strict";RI()});var ibe,Ih,P$=R(()=>{"use strict";fs();Ro();Ps();fe();C$();wn();ibe="observation_generate_session_summary",Ih=class{constructor(e){this.options=e}options;async end(e){let r=e.source??"http_post_v1_sessions_end",n=await In(this.options.pool,async s=>{let a=await new zt(s).endSession({id:e.sessionId,projectId:e.projectId,teamId:e.teamId});if(!a)return{session:null,outbox:null};let c=new dt(s),l=new Wt(s),u=Ze(),d=CI({serverSessionId:a.id,teamId:a.teamId,projectId:a.projectId,generationJobId:u,apiKeyId:e.apiKeyId??null,actorId:e.actorId??null,sourceAdapter:e.sourceAdapter??null}),p=await c.create({id:u,projectId:a.projectId,teamId:a.teamId,sourceType:"session_summary",sourceId:a.id,serverSessionId:a.id,jobType:ibe,bullmqJobId:OI({serverSessionId:a.id,teamId:a.teamId,projectId:a.projectId}),payload:d});return await l.append({generationJobId:p.id,projectId:p.projectId,teamId:p.teamId,eventType:"queued",statusAfter:p.status,attempt:p.attempts,details:{source:r}}),{session:a,outbox:p}});if(!n.session||!n.outbox)return{session:n.session,outbox:null,enqueueState:"skipped"};let i=await this.publishSummaryJob(n.session.id,n.outbox,e);return{session:n.session,outbox:n.outbox,enqueueState:i}}async publishSummaryJob(e,r,n){let i=this.options.resolveSummaryQueue();if(!i)return"queued_only";let s=r.bullmqJobId??OI({serverSessionId:e,teamId:r.teamId,projectId:r.projectId}),o=CI({serverSessionId:e,teamId:r.teamId,projectId:r.projectId,generationJobId:r.id,apiKeyId:n.apiKeyId??null,actorId:n.actorId??null,sourceAdapter:n.sourceAdapter??null});try{return await i.add(s,o),"enqueued"}catch(a){return x.warn("SYSTEM","failed to publish summary generation job to BullMQ",{outboxId:r.id,error:a instanceof Error?a.message:String(a)}),"queued_only"}}}});function j$(t){return`${(process.env.CLAUDE_MEM_PUBLIC_URL??`${t.protocol}://${t.get("host")??"localhost"}`).replace(/\/+$/,"")}/v1/mcp`}function K$(t,e){return`claude mcp add --transport http claude-mem ${t} --header "Authorization: Bearer ${e}"`}async function N$(t,e,r=$$,n=abe){if(M$.includes(e.status))return{job:e,timedOut:!1};let i=Date.now()+r,s=e;for(;Date.now()<i;){await new Promise(a=>setTimeout(a,n));let o=await t.getByIdForScope({id:e.id,projectId:e.projectId,teamId:e.teamId});if(!o)return{job:s,timedOut:!1};if(s=o,M$.includes(o.status))return{job:o,timedOut:!1}}return{job:s,timedOut:!0}}function lbe(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&U$.has(e)?e:null,n=typeof t.query.source_type=="string"?t.query.source_type.trim():"",i=n&&cbe.has(n)?n:null,s=kh(t.query.limit,J$,1,z$),o=kh(t.query.offset,0,0,Number.MAX_SAFE_INTEGER),a=typeof t.query.since=="string"?t.query.since.trim():"",c=null;if(a){let l=new Date(a);Number.isNaN(l.getTime())||(c=l)}return{status:r,sourceType:i,limit:s,offset:o,since:c}}function L$(t){if(!t||typeof t!="object")return 0;let e=t.retried_count;return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function q$(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&U$.has(e)?e:null,n=kh(t.query.limit,J$,1,z$),i=kh(t.query.offset,0,0,Number.MAX_SAFE_INTEGER);return{status:r,limit:n,offset:i}}function kh(t,e,r,n){if(typeof t!="string")return e;let i=Number.parseInt(t,10);return Number.isFinite(i)?Math.max(r,Math.min(n,i)):e}function PI(t,e={}){let r={id:t.id,projectId:t.project_id,teamId:t.team_id,sourceType:t.source_type,sourceId:t.source_id,status:t.status,attempts:t.attempts,maxAttempts:t.max_attempts,createdAtEpoch:new Date(t.created_at).getTime(),completedAtEpoch:t.completed_at?new Date(t.completed_at).getTime():null,failedAtEpoch:t.failed_at?new Date(t.failed_at).getTime():null,lastError:t.last_error&&typeof t.last_error=="object"?t.last_error:null};return e.includePayload&&t.payload&&typeof t.payload=="object"&&(r.payload=t.payload),r}function ube(t){let e={"event.received":"agent_event","event.batch_received":"agent_event","event.write":"agent_event","event.batch_write":"agent_event","session.write":"server_session","session.end":"server_session","memory.write":"observation","observation.read":"observation","observation.search":"observation","observation.context":"observation","observation.generated":"observation","session_summary.generated":"observation","generation_job.queued":"observation_generation_job","generation_job.enqueued":"observation_generation_job","generation_job.processing":"observation_generation_job","generation_job.completed":"observation_generation_job","generation_job.failed":"observation_generation_job","generation_job.scope_violation":"observation_generation_job","generation_job.revoked_key":"observation_generation_job","generation_job.retried_by_operator":"observation_generation_job","generation_job.cancelled_by_operator":"observation_generation_job","generation_job.stalled":"observation_generation_job"};return e[t]?e[t]:t.split(".")[0]??"unknown"}function dbe(t,e){let r=t.authContext?.projectId??null;if(!(t.authContext?.teamId??null))return{status:403,body:{error:"Forbidden",message:"API key is not bound to a team"}};if(!r)return null;for(let i of e)if(i.projectId!==r)return{status:403,body:{error:"Forbidden",message:"API key is scoped to a different project"}};return null}function ud(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,externalSessionId:t.externalSessionId,contentSessionId:t.contentSessionId,agentId:t.agentId,agentType:t.agentType,platformSource:t.platformSource,generationStatus:t.generationStatus,metadata:t.metadata,startedAtEpoch:t.startedAtEpoch,endedAtEpoch:t.endedAtEpoch,lastGeneratedAtEpoch:t.lastGeneratedAtEpoch,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function dd(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,serverSessionId:t.serverSessionId,sourceAdapter:t.sourceAdapter,sourceEventId:t.sourceEventId,eventType:t.eventType,platformSource:t.platformSource,payload:t.payload,metadata:t.metadata,occurredAtEpoch:t.occurredAtEpoch,receivedAtEpoch:t.receivedAtEpoch,createdAtEpoch:t.createdAtEpoch}}function Lc(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,serverSessionId:t.serverSessionId,kind:t.kind,content:t.content,metadata:t.metadata,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function pbe(t){return{id:t.id,projectId:t.project_id,teamId:t.team_id,serverSessionId:t.server_session_id,kind:t.kind,content:t.content,metadata:t.metadata&&typeof t.metadata=="object"?t.metadata:{},generationKey:t.generation_key,createdByJobId:t.created_by_job_id,createdAtEpoch:new Date(t.created_at).getTime(),updatedAtEpoch:new Date(t.updated_at).getTime(),source:{id:t.source_id_pk,sourceType:t.source_type,sourceId:t.source_id,generationJobId:t.generation_job_id,createdAtEpoch:new Date(t.source_created_at).getTime()}}}function jI(t,e){return{id:t.id,status:t.status,bullmqJobId:t.bullmqJobId,sourceType:t.sourceType,sourceId:t.sourceId,transport:e,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function F$(t,e){return{id:t.id,status:t.status,transport:e,bullmqJobId:t.bullmqJobId,sourceType:t.sourceType,sourceId:t.sourceId,attempts:t.attempts,maxAttempts:t.maxAttempts,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function KI(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,sourceType:t.sourceType,sourceId:t.sourceId,agentEventId:t.agentEventId,serverSessionId:t.serverSessionId,jobType:t.jobType,status:t.status,bullmqJobId:t.bullmqJobId,attempts:t.attempts,maxAttempts:t.maxAttempts,nextAttemptAtEpoch:t.nextAttemptAtEpoch,completedAtEpoch:t.completedAtEpoch,failedAtEpoch:t.failedAtEpoch,cancelledAtEpoch:t.cancelledAtEpoch,lastError:t.lastError,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}var oe,Ah,sbe,obe,D$,$$,abe,M$,Th,cbe,U$,J$,z$,G$=R(()=>{"use strict";oe=require("zod");ZM();Qa();fs();Oi();su();Xa();fe();Kf();bx();iq();e2();b$();E$();x$();Jo();Ah=require("node:crypto");Ps();O$();P$();xo();sbe="api",obe="13.26.0";D$=oe.z.object({generate:oe.z.union([oe.z.literal("true"),oe.z.literal("false")]).optional(),wait:oe.z.union([oe.z.literal("true"),oe.z.literal("false")]).optional()}),$$=3e4,abe=100,M$=["completed","failed","cancelled"];Th=class{constructor(e){this.options=e;this.ingestEvents=new _h({pool:e.pool,resolveEventQueue:()=>this.resolveQueue("event")}),this.endSession=new Ih({pool:e.pool,resolveSummaryQueue:()=>this.resolveQueue("summary")})}options;ingestEvents;endSession;getIngestEventsService(){return this.ingestEvents}getEndSessionService(){return this.endSession}setupRoutes(e){e.use("/v1",nq());let r=_o(this.options.pool,{authMode:this.options.authMode,allowLocalDevBypass:this.options.allowLocalDevBypass,requiredScopes:["memories:write"]}),n=_o(this.options.pool,{authMode:this.options.authMode,allowLocalDevBypass:this.options.allowLocalDevBypass,requiredScopes:["memories:read"]}),i=[],s=Number(process.env.CLAUDE_MEM_RATE_LIMIT_PER_MIN??"0");s>0&&i.push(v$(this.options.pool,{windowSec:60,max:s}));let o=Number(process.env.CLAUDE_MEM_MONTHLY_REQUEST_CAP??"0");o>0&&i.push(AI(this.options.pool,{kind:"request",cap:o})),process.env.CLAUDE_MEM_USAGE_METERING==="1"&&i.push(S$(this.options.pool));let a=[...i],c=Number(process.env.CLAUDE_MEM_MONTHLY_TOKEN_CAP??"0");c>0&&a.push(AI(this.options.pool,{kind:"tokens",cap:c}));let l=[r,...a],u=[n,...i];e.get("/v1/usage",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let y=new Date(Date.UTC(new Date().getUTCFullYear(),new Date().getUTCMonth(),1)),b=await new Kr(this.options.pool).summarize({teamId:m,since:y});f.status(200).json({since:y.toISOString(),usage:b})})),e.post("/v1/keys",l,this.handleCreate(oe.z.object({label:oe.z.string().max(120).optional(),expiresInDays:oe.z.number().int().positive().max(365).optional()}),async(p,f,m)=>{let y=this.requireTeamId(p,f);if(!y)return;let b=`cm_${(0,Ah.randomBytes)(24).toString("hex")}`,v=(0,Ah.createHash)("sha256").update(b).digest("hex"),E=m.expiresInDays?new Date(Date.now()+m.expiresInDays*864e5):null,S=await new Nt(this.options.pool).createApiKey({keyHash:v,teamId:y,projectId:p.authContext?.projectId??null,actorId:p.authContext?.apiKeyId??"api",scopes:["memories:read"],expiresAt:E});m.label;let k=j$(p);f.status(201).json({id:S.id,apiKey:b,scopes:["memories:read"],expiresAt:E?.toISOString()??null,mcpUrl:k,connectCommand:K$(k,b)})})),e.get("/v1/connect",u,this.asyncHandler(async(p,f)=>{if(!this.requireTeamId(p,f))return;let y=j$(p);f.status(200).json({mcpUrl:y,connectCommand:K$(y,"<YOUR_API_KEY>"),hint:"POST /v1/keys (write scope) to mint a read-only key for this link."})})),e.post("/v1/events",l,this.asyncHandler(async(p,f)=>{let m=D$.safeParse(p.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let y=m.data.generate!=="false",b=m.data.wait==="true",v=uS.safeParse(p.body);if(!v.success){f.status(400).json({error:"ValidationError",issues:v.error.issues});return}let E=v.data,S=this.requireTeamId(p,f);if(!S||!this.ensureProjectAllowed(p,f,E.projectId))return;let k=this.toAgentEventInput(E,S);await this.applyContentSessionLinks([k],[p.body],S);let _,O=null,N="skipped",ee={generate:y,source:"http_post_v1_events",apiKeyId:p.authContext?.apiKeyId??null,actorId:await this.resolveActorId(p),sourceAdapter:k.sourceAdapter,requestId:p.requestId??null};try{let q=await this.ingestEvents.ingestOne(k,ee);_=q.event,O=q.outbox,N=q.enqueueState}catch(q){let U=q instanceof Error?q:new Error(String(q));x.warn("SYSTEM","event.write ingest failed",{requestId:p.requestId??null},U),this.handleDbError(U,f,"event.write");return}if(await this.auditWrite(p,"event.received",_.id,_.projectId,{sourceAdapter:_.sourceAdapter,sourceEventId:_.sourceEventId,eventType:_.eventType,serverSessionId:_.serverSessionId,generationJobId:O?.id??null}),b){let q=O,U=!1;if(O){let te=new dt(this.options.pool),Ge=await N$(te,O);q=Ge.job,U=Ge.timedOut}f.status(201).json({event:dd(_),generationJob:q?F$(q,N):null,...U?{waitTimedOut:!0}:{}});return}f.status(201).json({event:dd(_),...O?{generationJob:jI(O,N)}:{}})})),e.post("/v1/events/batch",l,this.asyncHandler(async(p,f)=>{let m=D$.safeParse(p.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let y=m.data.generate!=="false",b=m.data.wait==="true",E=oe.z.array(uS).min(1).max(500).safeParse(p.body);if(!E.success){f.status(400).json({error:"ValidationError",issues:E.error.issues});return}let S=this.requireTeamId(p,f);if(!S)return;let k=dbe(p,E.data);if(k){f.status(k.status).json(k.body);return}let _=E.data.map(q=>this.toAgentEventInput(q,S));await this.applyContentSessionLinks(_,Array.isArray(p.body)?p.body:E.data,S);let O=[],N=[],ee={generate:y,source:"http_post_v1_events_batch",apiKeyId:p.authContext?.apiKeyId??null,actorId:await this.resolveActorId(p),sourceAdapter:null,requestId:p.requestId??null};try{let q=await this.ingestEvents.ingestBatch(_,ee);O=q.map(({event:U,outbox:te})=>({event:U,outbox:te})),N=q.map(({enqueueState:U})=>U)}catch(q){let U=q instanceof Error?q:new Error(String(q));x.warn("SYSTEM","event.batch_write ingest failed",{requestId:p.requestId??null},U),this.handleDbError(U,f,"event.batch_write");return}if(await this.auditWrite(p,"event.batch_received",null,null,{eventCount:O.length,generationJobIds:O.map(({outbox:q})=>q?.id??null).filter(Boolean)}),b){let q=new dt(this.options.pool),U=Date.now()+$$,te=[];for(let T of O){if(!T.outbox){te.push({event:T.event,outbox:null,timedOut:!1});continue}let K=Math.max(0,U-Date.now()),j=await N$(q,T.outbox,K);te.push({event:T.event,outbox:j.job,timedOut:j.timedOut})}let Ge=te.some(T=>T.timedOut);f.status(201).json({events:te.map(({event:T,outbox:K,timedOut:j},C)=>({event:dd(T),generationJob:K?F$(K,N[C]):null,...j?{waitTimedOut:!0}:{}})),...Ge?{waitTimedOut:!0}:{}});return}f.status(201).json({events:O.map(({event:q,outbox:U},te)=>({event:dd(q),...U?{generationJob:jI(U,N[te])}:{}}))})})),e.get("/v1/events/:id",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let y=this.routeParam(p.params.id),b=new Xr(this.options.pool),v=await this.loadScopedById(p,f,{id:y,teamId:m,table:"agent_events",notFound:"Event not found",load:E=>b.getByIdForScope({id:y,projectId:E,teamId:m})});v&&f.json({event:dd(v)})})),e.get("/v1/events/:id/observations",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let y=this.routeParam(p.params.id),v=(await this.options.pool.query("SELECT id, project_id FROM agent_events WHERE id = $1 AND team_id = $2",[y,m])).rows[0];if(!v){f.status(404).json({error:"NotFound",message:"Event not found"});return}if(!this.ensureProjectAllowed(p,f,v.project_id))return;let E=await this.options.pool.query(`
361
+ `,[e.serverSessionId,e.projectId,e.teamId,r])).rows.map(ebe)}}});function T$(t){let e=nbe.safeParse(t);if(!e.success)throw new ld(e.error.issues);return e.data}var tr,Mc,_$,I$,tbe,rbe,nbe,ld,wh=R(()=>{"use strict";tr=require("zod"),Mc={event:"server_beta_generate_event",summary:"server_beta_generate_summary"},_$={event:"evt",summary:"sum"},I$=tr.z.object({team_id:tr.z.string().min(1,"team_id is required"),project_id:tr.z.string().min(1,"project_id is required"),source_type:tr.z.enum(["agent_event","session_summary","observation_reindex"]),source_id:tr.z.string().min(1,"source_id is required"),generation_job_id:tr.z.string().min(1,"generation_job_id is required"),api_key_id:tr.z.string().min(1).nullable(),actor_id:tr.z.string().min(1).nullable(),source_adapter:tr.z.string().min(1,"source_adapter is required"),request_id:tr.z.string().min(1).nullable().optional()}),tbe=I$.extend({kind:tr.z.literal("event"),agent_event_id:tr.z.string().min(1)}),rbe=I$.extend({kind:tr.z.literal("summary"),server_session_id:tr.z.string().min(1)}),nbe=tr.z.discriminatedUnion("kind",[tbe,rbe]),ld=class extends Error{issues;constructor(e){super(`invalid server generation job payload: ${e.map(r=>r.message).join("; ")}`),this.issues=e}}});function Nc(t){let e=_$[t.kind],r=JSON.stringify({kind:t.kind,team_id:t.team_id,project_id:t.project_id,source_type:t.source_type,source_id:t.source_id}),n=(0,k$.createHash)("sha256").update(r).digest("hex");return`${e}_${n}`}var k$,RI=R(()=>{"use strict";k$=require("crypto");wh()});function A$(t){return{kind:"event",team_id:t.event.teamId,project_id:t.event.projectId,source_type:"agent_event",source_id:t.event.id,generation_job_id:t.outboxId,agent_event_id:t.event.id,api_key_id:t.apiKeyId,actor_id:t.actorId,source_adapter:t.sourceAdapter??t.event.sourceAdapter??"api",request_id:t.requestId}}var R$,_h,O$=R(()=>{"use strict";Qa();fs();Ro();fe();RI();wn();R$="observation_generate_for_event",_h=class{constructor(e){this.options=e}options;async ingestOne(e,r={}){let n=r.generate??!0,i=r.source??"http_post_v1_events",s=await In(this.options.pool,async a=>{let l=await new Xr(a).create(e);if(!n)return{event:l,outbox:null};let u=new dt(a),d=new Wt(a),p=Ze(),f=A$({outboxId:p,event:l,apiKeyId:r.apiKeyId??null,actorId:r.actorId??null,sourceAdapter:r.sourceAdapter??null,requestId:r.requestId??null}),m=await u.create({id:p,projectId:l.projectId,teamId:l.teamId,sourceType:"agent_event",sourceId:l.id,agentEventId:l.id,serverSessionId:l.serverSessionId,jobType:R$,bullmqJobId:Nc({kind:"event",team_id:l.teamId,project_id:l.projectId,source_type:"agent_event",source_id:l.id}),payload:f});return await d.append({generationJobId:m.id,projectId:m.projectId,teamId:m.teamId,eventType:"queued",statusAfter:m.status,attempt:m.attempts,details:{source:i}}),{event:l,outbox:m}}),o="skipped";return s.outbox&&(o=await this.publishEventJob(s.event,s.outbox)),{event:s.event,outbox:s.outbox,enqueueState:o}}async ingestBatch(e,r={}){let n=r.generate??!0,i=r.source??"http_post_v1_events_batch",s=await In(this.options.pool,async o=>{let a=new Xr(o),c=new dt(o),l=new Wt(o),u=[];for(let d of e){let p=await a.create(d);if(!n){u.push({event:p,outbox:null});continue}let f=Ze(),m=A$({outboxId:f,event:p,apiKeyId:r.apiKeyId??null,actorId:r.actorId??null,sourceAdapter:r.sourceAdapter??null,requestId:r.requestId??null}),y=await c.create({id:f,projectId:p.projectId,teamId:p.teamId,sourceType:"agent_event",sourceId:p.id,agentEventId:p.id,serverSessionId:p.serverSessionId,jobType:R$,bullmqJobId:Nc({kind:"event",team_id:p.teamId,project_id:p.projectId,source_type:"agent_event",source_id:p.id}),payload:m});await l.append({generationJobId:y.id,projectId:y.projectId,teamId:y.teamId,eventType:"queued",statusAfter:y.status,attempt:y.attempts,details:{source:i}}),u.push({event:p,outbox:y})}return u});return Promise.all(s.map(async({event:o,outbox:a})=>{let c=a?await this.publishEventJob(o,a):"skipped";return{event:o,outbox:a,enqueueState:c}}))}async publishEventJob(e,r){let n=this.options.resolveEventQueue();if(!n)return"queued_only";let i=r.bullmqJobId??Nc({kind:"event",team_id:e.teamId,project_id:e.projectId,source_type:"agent_event",source_id:e.id});try{return await n.add(i,r.payload),"enqueued"}catch(s){return x.warn("SYSTEM","failed to publish event generation job to BullMQ",{outboxId:r.id,error:s instanceof Error?s.message:String(s)}),"queued_only"}}}});function OI(t){return Nc({kind:"summary",team_id:t.teamId,project_id:t.projectId,source_type:"session_summary",source_id:t.serverSessionId})}function CI(t){return{kind:"summary",team_id:t.teamId,project_id:t.projectId,source_type:"session_summary",source_id:t.serverSessionId,generation_job_id:t.generationJobId,server_session_id:t.serverSessionId,api_key_id:t.apiKeyId??null,actor_id:t.actorId??null,source_adapter:t.sourceAdapter??"api",request_id:t.requestId??null}}var C$=R(()=>{"use strict";RI()});var ibe,Ih,P$=R(()=>{"use strict";fs();Ro();Ps();fe();C$();wn();ibe="observation_generate_session_summary",Ih=class{constructor(e){this.options=e}options;async end(e){let r=e.source??"http_post_v1_sessions_end",n=await In(this.options.pool,async s=>{let a=await new zt(s).endSession({id:e.sessionId,projectId:e.projectId,teamId:e.teamId});if(!a)return{session:null,outbox:null};let c=new dt(s),l=new Wt(s),u=Ze(),d=CI({serverSessionId:a.id,teamId:a.teamId,projectId:a.projectId,generationJobId:u,apiKeyId:e.apiKeyId??null,actorId:e.actorId??null,sourceAdapter:e.sourceAdapter??null}),p=await c.create({id:u,projectId:a.projectId,teamId:a.teamId,sourceType:"session_summary",sourceId:a.id,serverSessionId:a.id,jobType:ibe,bullmqJobId:OI({serverSessionId:a.id,teamId:a.teamId,projectId:a.projectId}),payload:d});return await l.append({generationJobId:p.id,projectId:p.projectId,teamId:p.teamId,eventType:"queued",statusAfter:p.status,attempt:p.attempts,details:{source:r}}),{session:a,outbox:p}});if(!n.session||!n.outbox)return{session:n.session,outbox:null,enqueueState:"skipped"};let i=await this.publishSummaryJob(n.session.id,n.outbox,e);return{session:n.session,outbox:n.outbox,enqueueState:i}}async publishSummaryJob(e,r,n){let i=this.options.resolveSummaryQueue();if(!i)return"queued_only";let s=r.bullmqJobId??OI({serverSessionId:e,teamId:r.teamId,projectId:r.projectId}),o=CI({serverSessionId:e,teamId:r.teamId,projectId:r.projectId,generationJobId:r.id,apiKeyId:n.apiKeyId??null,actorId:n.actorId??null,sourceAdapter:n.sourceAdapter??null});try{return await i.add(s,o),"enqueued"}catch(a){return x.warn("SYSTEM","failed to publish summary generation job to BullMQ",{outboxId:r.id,error:a instanceof Error?a.message:String(a)}),"queued_only"}}}});function j$(t){return`${(process.env.CLAUDE_MEM_PUBLIC_URL??`${t.protocol}://${t.get("host")??"localhost"}`).replace(/\/+$/,"")}/v1/mcp`}function K$(t,e){return`claude mcp add --transport http claude-mem ${t} --header "Authorization: Bearer ${e}"`}async function N$(t,e,r=$$,n=abe){if(M$.includes(e.status))return{job:e,timedOut:!1};let i=Date.now()+r,s=e;for(;Date.now()<i;){await new Promise(a=>setTimeout(a,n));let o=await t.getByIdForScope({id:e.id,projectId:e.projectId,teamId:e.teamId});if(!o)return{job:s,timedOut:!1};if(s=o,M$.includes(o.status))return{job:o,timedOut:!1}}return{job:s,timedOut:!0}}function lbe(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&U$.has(e)?e:null,n=typeof t.query.source_type=="string"?t.query.source_type.trim():"",i=n&&cbe.has(n)?n:null,s=kh(t.query.limit,J$,1,z$),o=kh(t.query.offset,0,0,Number.MAX_SAFE_INTEGER),a=typeof t.query.since=="string"?t.query.since.trim():"",c=null;if(a){let l=new Date(a);Number.isNaN(l.getTime())||(c=l)}return{status:r,sourceType:i,limit:s,offset:o,since:c}}function L$(t){if(!t||typeof t!="object")return 0;let e=t.retried_count;return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function q$(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&U$.has(e)?e:null,n=kh(t.query.limit,J$,1,z$),i=kh(t.query.offset,0,0,Number.MAX_SAFE_INTEGER);return{status:r,limit:n,offset:i}}function kh(t,e,r,n){if(typeof t!="string")return e;let i=Number.parseInt(t,10);return Number.isFinite(i)?Math.max(r,Math.min(n,i)):e}function PI(t,e={}){let r={id:t.id,projectId:t.project_id,teamId:t.team_id,sourceType:t.source_type,sourceId:t.source_id,status:t.status,attempts:t.attempts,maxAttempts:t.max_attempts,createdAtEpoch:new Date(t.created_at).getTime(),completedAtEpoch:t.completed_at?new Date(t.completed_at).getTime():null,failedAtEpoch:t.failed_at?new Date(t.failed_at).getTime():null,lastError:t.last_error&&typeof t.last_error=="object"?t.last_error:null};return e.includePayload&&t.payload&&typeof t.payload=="object"&&(r.payload=t.payload),r}function ube(t){let e={"event.received":"agent_event","event.batch_received":"agent_event","event.write":"agent_event","event.batch_write":"agent_event","session.write":"server_session","session.end":"server_session","memory.write":"observation","observation.read":"observation","observation.search":"observation","observation.context":"observation","observation.generated":"observation","session_summary.generated":"observation","generation_job.queued":"observation_generation_job","generation_job.enqueued":"observation_generation_job","generation_job.processing":"observation_generation_job","generation_job.completed":"observation_generation_job","generation_job.failed":"observation_generation_job","generation_job.scope_violation":"observation_generation_job","generation_job.revoked_key":"observation_generation_job","generation_job.retried_by_operator":"observation_generation_job","generation_job.cancelled_by_operator":"observation_generation_job","generation_job.stalled":"observation_generation_job"};return e[t]?e[t]:t.split(".")[0]??"unknown"}function dbe(t,e){let r=t.authContext?.projectId??null;if(!(t.authContext?.teamId??null))return{status:403,body:{error:"Forbidden",message:"API key is not bound to a team"}};if(!r)return null;for(let i of e)if(i.projectId!==r)return{status:403,body:{error:"Forbidden",message:"API key is scoped to a different project"}};return null}function ud(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,externalSessionId:t.externalSessionId,contentSessionId:t.contentSessionId,agentId:t.agentId,agentType:t.agentType,platformSource:t.platformSource,generationStatus:t.generationStatus,metadata:t.metadata,startedAtEpoch:t.startedAtEpoch,endedAtEpoch:t.endedAtEpoch,lastGeneratedAtEpoch:t.lastGeneratedAtEpoch,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function dd(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,serverSessionId:t.serverSessionId,sourceAdapter:t.sourceAdapter,sourceEventId:t.sourceEventId,eventType:t.eventType,platformSource:t.platformSource,payload:t.payload,metadata:t.metadata,occurredAtEpoch:t.occurredAtEpoch,receivedAtEpoch:t.receivedAtEpoch,createdAtEpoch:t.createdAtEpoch}}function Lc(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,serverSessionId:t.serverSessionId,kind:t.kind,content:t.content,metadata:t.metadata,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function pbe(t){return{id:t.id,projectId:t.project_id,teamId:t.team_id,serverSessionId:t.server_session_id,kind:t.kind,content:t.content,metadata:t.metadata&&typeof t.metadata=="object"?t.metadata:{},generationKey:t.generation_key,createdByJobId:t.created_by_job_id,createdAtEpoch:new Date(t.created_at).getTime(),updatedAtEpoch:new Date(t.updated_at).getTime(),source:{id:t.source_id_pk,sourceType:t.source_type,sourceId:t.source_id,generationJobId:t.generation_job_id,createdAtEpoch:new Date(t.source_created_at).getTime()}}}function jI(t,e){return{id:t.id,status:t.status,bullmqJobId:t.bullmqJobId,sourceType:t.sourceType,sourceId:t.sourceId,transport:e,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function F$(t,e){return{id:t.id,status:t.status,transport:e,bullmqJobId:t.bullmqJobId,sourceType:t.sourceType,sourceId:t.sourceId,attempts:t.attempts,maxAttempts:t.maxAttempts,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function KI(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,sourceType:t.sourceType,sourceId:t.sourceId,agentEventId:t.agentEventId,serverSessionId:t.serverSessionId,jobType:t.jobType,status:t.status,bullmqJobId:t.bullmqJobId,attempts:t.attempts,maxAttempts:t.maxAttempts,nextAttemptAtEpoch:t.nextAttemptAtEpoch,completedAtEpoch:t.completedAtEpoch,failedAtEpoch:t.failedAtEpoch,cancelledAtEpoch:t.cancelledAtEpoch,lastError:t.lastError,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}var oe,Ah,sbe,obe,D$,$$,abe,M$,Th,cbe,U$,J$,z$,G$=R(()=>{"use strict";oe=require("zod");ZM();Qa();fs();Oi();su();Xa();fe();Kf();bx();iq();e2();b$();E$();x$();Jo();Ah=require("node:crypto");Ps();O$();P$();xo();sbe="api",obe="13.26.1";D$=oe.z.object({generate:oe.z.union([oe.z.literal("true"),oe.z.literal("false")]).optional(),wait:oe.z.union([oe.z.literal("true"),oe.z.literal("false")]).optional()}),$$=3e4,abe=100,M$=["completed","failed","cancelled"];Th=class{constructor(e){this.options=e;this.ingestEvents=new _h({pool:e.pool,resolveEventQueue:()=>this.resolveQueue("event")}),this.endSession=new Ih({pool:e.pool,resolveSummaryQueue:()=>this.resolveQueue("summary")})}options;ingestEvents;endSession;getIngestEventsService(){return this.ingestEvents}getEndSessionService(){return this.endSession}setupRoutes(e){e.use("/v1",nq());let r=_o(this.options.pool,{authMode:this.options.authMode,allowLocalDevBypass:this.options.allowLocalDevBypass,requiredScopes:["memories:write"]}),n=_o(this.options.pool,{authMode:this.options.authMode,allowLocalDevBypass:this.options.allowLocalDevBypass,requiredScopes:["memories:read"]}),i=[],s=Number(process.env.CLAUDE_MEM_RATE_LIMIT_PER_MIN??"0");s>0&&i.push(v$(this.options.pool,{windowSec:60,max:s}));let o=Number(process.env.CLAUDE_MEM_MONTHLY_REQUEST_CAP??"0");o>0&&i.push(AI(this.options.pool,{kind:"request",cap:o})),process.env.CLAUDE_MEM_USAGE_METERING==="1"&&i.push(S$(this.options.pool));let a=[...i],c=Number(process.env.CLAUDE_MEM_MONTHLY_TOKEN_CAP??"0");c>0&&a.push(AI(this.options.pool,{kind:"tokens",cap:c}));let l=[r,...a],u=[n,...i];e.get("/v1/usage",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let y=new Date(Date.UTC(new Date().getUTCFullYear(),new Date().getUTCMonth(),1)),b=await new Kr(this.options.pool).summarize({teamId:m,since:y});f.status(200).json({since:y.toISOString(),usage:b})})),e.post("/v1/keys",l,this.handleCreate(oe.z.object({label:oe.z.string().max(120).optional(),expiresInDays:oe.z.number().int().positive().max(365).optional()}),async(p,f,m)=>{let y=this.requireTeamId(p,f);if(!y)return;let b=`cm_${(0,Ah.randomBytes)(24).toString("hex")}`,v=(0,Ah.createHash)("sha256").update(b).digest("hex"),E=m.expiresInDays?new Date(Date.now()+m.expiresInDays*864e5):null,S=await new Nt(this.options.pool).createApiKey({keyHash:v,teamId:y,projectId:p.authContext?.projectId??null,actorId:p.authContext?.apiKeyId??"api",scopes:["memories:read"],expiresAt:E});m.label;let k=j$(p);f.status(201).json({id:S.id,apiKey:b,scopes:["memories:read"],expiresAt:E?.toISOString()??null,mcpUrl:k,connectCommand:K$(k,b)})})),e.get("/v1/connect",u,this.asyncHandler(async(p,f)=>{if(!this.requireTeamId(p,f))return;let y=j$(p);f.status(200).json({mcpUrl:y,connectCommand:K$(y,"<YOUR_API_KEY>"),hint:"POST /v1/keys (write scope) to mint a read-only key for this link."})})),e.post("/v1/events",l,this.asyncHandler(async(p,f)=>{let m=D$.safeParse(p.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let y=m.data.generate!=="false",b=m.data.wait==="true",v=uS.safeParse(p.body);if(!v.success){f.status(400).json({error:"ValidationError",issues:v.error.issues});return}let E=v.data,S=this.requireTeamId(p,f);if(!S||!this.ensureProjectAllowed(p,f,E.projectId))return;let k=this.toAgentEventInput(E,S);await this.applyContentSessionLinks([k],[p.body],S);let _,O=null,N="skipped",ee={generate:y,source:"http_post_v1_events",apiKeyId:p.authContext?.apiKeyId??null,actorId:await this.resolveActorId(p),sourceAdapter:k.sourceAdapter,requestId:p.requestId??null};try{let q=await this.ingestEvents.ingestOne(k,ee);_=q.event,O=q.outbox,N=q.enqueueState}catch(q){let U=q instanceof Error?q:new Error(String(q));x.warn("SYSTEM","event.write ingest failed",{requestId:p.requestId??null},U),this.handleDbError(U,f,"event.write");return}if(await this.auditWrite(p,"event.received",_.id,_.projectId,{sourceAdapter:_.sourceAdapter,sourceEventId:_.sourceEventId,eventType:_.eventType,serverSessionId:_.serverSessionId,generationJobId:O?.id??null}),b){let q=O,U=!1;if(O){let te=new dt(this.options.pool),Ge=await N$(te,O);q=Ge.job,U=Ge.timedOut}f.status(201).json({event:dd(_),generationJob:q?F$(q,N):null,...U?{waitTimedOut:!0}:{}});return}f.status(201).json({event:dd(_),...O?{generationJob:jI(O,N)}:{}})})),e.post("/v1/events/batch",l,this.asyncHandler(async(p,f)=>{let m=D$.safeParse(p.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let y=m.data.generate!=="false",b=m.data.wait==="true",E=oe.z.array(uS).min(1).max(500).safeParse(p.body);if(!E.success){f.status(400).json({error:"ValidationError",issues:E.error.issues});return}let S=this.requireTeamId(p,f);if(!S)return;let k=dbe(p,E.data);if(k){f.status(k.status).json(k.body);return}let _=E.data.map(q=>this.toAgentEventInput(q,S));await this.applyContentSessionLinks(_,Array.isArray(p.body)?p.body:E.data,S);let O=[],N=[],ee={generate:y,source:"http_post_v1_events_batch",apiKeyId:p.authContext?.apiKeyId??null,actorId:await this.resolveActorId(p),sourceAdapter:null,requestId:p.requestId??null};try{let q=await this.ingestEvents.ingestBatch(_,ee);O=q.map(({event:U,outbox:te})=>({event:U,outbox:te})),N=q.map(({enqueueState:U})=>U)}catch(q){let U=q instanceof Error?q:new Error(String(q));x.warn("SYSTEM","event.batch_write ingest failed",{requestId:p.requestId??null},U),this.handleDbError(U,f,"event.batch_write");return}if(await this.auditWrite(p,"event.batch_received",null,null,{eventCount:O.length,generationJobIds:O.map(({outbox:q})=>q?.id??null).filter(Boolean)}),b){let q=new dt(this.options.pool),U=Date.now()+$$,te=[];for(let T of O){if(!T.outbox){te.push({event:T.event,outbox:null,timedOut:!1});continue}let K=Math.max(0,U-Date.now()),j=await N$(q,T.outbox,K);te.push({event:T.event,outbox:j.job,timedOut:j.timedOut})}let Ge=te.some(T=>T.timedOut);f.status(201).json({events:te.map(({event:T,outbox:K,timedOut:j},C)=>({event:dd(T),generationJob:K?F$(K,N[C]):null,...j?{waitTimedOut:!0}:{}})),...Ge?{waitTimedOut:!0}:{}});return}f.status(201).json({events:O.map(({event:q,outbox:U},te)=>({event:dd(q),...U?{generationJob:jI(U,N[te])}:{}}))})})),e.get("/v1/events/:id",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let y=this.routeParam(p.params.id),b=new Xr(this.options.pool),v=await this.loadScopedById(p,f,{id:y,teamId:m,table:"agent_events",notFound:"Event not found",load:E=>b.getByIdForScope({id:y,projectId:E,teamId:m})});v&&f.json({event:dd(v)})})),e.get("/v1/events/:id/observations",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let y=this.routeParam(p.params.id),v=(await this.options.pool.query("SELECT id, project_id FROM agent_events WHERE id = $1 AND team_id = $2",[y,m])).rows[0];if(!v){f.status(404).json({error:"NotFound",message:"Event not found"});return}if(!this.ensureProjectAllowed(p,f,v.project_id))return;let E=await this.options.pool.query(`
362
362
  SELECT o.id, o.project_id, o.team_id, o.server_session_id, o.kind, o.content,
363
363
  o.metadata, o.generation_key, o.created_by_job_id, o.created_at, o.updated_at,
364
364
  os.id AS source_id_pk, os.source_type, os.source_id, os.generation_job_id, os.created_at AS source_created_at
@@ -9787,7 +9787,7 @@ CREATE TABLE IF NOT EXISTS rate_limit_counters (
9787
9787
  PRIMARY KEY (subject_id, window_start)
9788
9788
  );
9789
9789
  CREATE INDEX IF NOT EXISTS idx_rate_limit_counters_window ON rate_limit_counters(window_start);
9790
- `});var Yb={};io(Yb,{PostgresAgentEventsRepository:()=>Xr,PostgresAuthRepository:()=>Nt,PostgresDataDeletionRepository:()=>cc,PostgresObservationGenerationJobEventsRepository:()=>Wt,PostgresObservationGenerationJobRepository:()=>dt,PostgresObservationRepository:()=>Zr,PostgresObservationSourcesRepository:()=>wo,PostgresProjectsRepository:()=>_n,PostgresRateLimitRepository:()=>Uo,PostgresServerSessionsRepository:()=>zt,PostgresTeamsRepository:()=>va,PostgresUsageRepository:()=>Kr,SERVER_POSTGRES_SCHEMA_VERSION:()=>Xd,SERVER_POSTGRES_TABLES:()=>$Ae,bootstrapServerPostgresSchema:()=>Wb,buildAgentEventIdempotencyKey:()=>tN,buildObservationGenerationJobIdempotencyKey:()=>nN,buildObservationGenerationKey:()=>fS,buildServerSessionIdempotencyKey:()=>w$,closePostgresPool:()=>sle,createPostgresPool:()=>em,createPostgresStorageRepositories:()=>GAe,getPostgresDatabaseUrl:()=>tq,getSharedPostgresPool:()=>gx,parsePostgresConfig:()=>yu,withPostgresTransaction:()=>In});function GAe(t){return{teams:new va(t),projects:new _n(t),auth:new Nt(t),sessions:new zt(t),agentEvents:new Xr(t),observations:new Zr(t),observationSources:new wo(t),observationGenerationJobs:new dt(t),observationGenerationJobEvents:new Wt(t),usage:new Kr(t),rateLimits:new Uo(t)}}var Zd=R(()=>{"use strict";Qa();Oi();fs();su();Xa();Ps();Vb();Jo();xh();Qa();Oi();Zf();bx();fs();su();Ro();Xa();xh();jA();Ps();Vb();Jo()});function ZH(t){return process.platform==="win32"?Math.round(t*KA.WINDOWS_MULTIPLIER):t}var KA,eV=R(()=>{"use strict";KA={HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5}});function WAe(t){if(typeof t!="string")return null;let e=t.trim();if(e.length===0)return null;try{if(new URL(e).hostname===HAe)return VAe}catch{return null}return null}var Qb,DA,ep,BAe,HAe,VAe,tp,tV=R(()=>{"use strict";Qb=require("fs"),DA=require("path"),ep=require("os");eV();Xl();BAe="security_alert",HAe="sync-hub.black-pond-afbb.workers.dev",VAe="https://sync.cmem.ai";tp=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_API_TIMEOUT_MS:String(ZH(KA.API_REQUEST)),CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-flash-latest",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_DATA_DIR:(0,DA.join)((0,ep.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_CLAUDE_CONFIG_DIR:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES:"",CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:"",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,DA.join)((0,ep.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_OBSERVER_MAX_CONVERSATION_CHARS:"400000",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_CHROMA_MAX_PENDING_MUTATIONS:"5000",CLAUDE_MEM_CLOUD_SYNC_TOKEN:"",CLAUDE_MEM_CLOUD_SYNC_USER_ID:"",CLAUDE_MEM_CLOUD_SYNC_HUB_URL:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_ID:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_NAME:(0,ep.hostname)(),CLAUDE_MEM_CLOUD_SYNC_WS:"true",CLAUDE_MEM_CLOUD_SYNC_CONTENT_BATCH_SIZE:"40",CLAUDE_MEM_CLOUD_SYNC_REQUEST_TIMEOUT_MS:"90000",CLAUDE_MEM_LLM_TIMEOUT_MS:"30000",CLAUDE_MEM_TV_TOKEN:"",CLAUDE_MEM_PRO_TRIAL_EMAIL:"",CLAUDE_MEM_PRO_TRIAL_AT:"",CLAUDE_MEM_PRO_TRIAL_STATE:"",CLAUDE_MEM_PRO_TRIAL_ENDS_AT:"",CLAUDE_MEM_PRO_PLAN:"",CLAUDE_MEM_PRO_FALLBACK_AT:"",CLAUDE_MEM_PRO_MEMORY_KEY:"",CLAUDE_MEM_PRO_MEMORY_BASE_URL:"",CLAUDE_MEM_PRO_MEMORY_MODEL:"",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_WRAPUPS_ENABLED:"true",CLAUDE_MEM_TELEGRAM_OBSERVATION_ALERTS_ENABLED:"false",CLAUDE_MEM_TELEGRAM_WRAPUP_ROUTES:"{}",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert,sensitive",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_AWARENESS_ENABLED:"true",CLAUDE_MEM_GROK_BOT_AWARENESS_AGENT_IDS:"521e962d-2ec3-4488-bfbc-54d5209ce118,95601360-61f7-4fd9-bb3a-2c976b2b85c0",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_INJECT_ENABLED:"true",CLAUDE_MEM_GROK_BOT_INJECT_AGENT_IDS:"*",CLAUDE_MEM_GROK_BOT_INJECT_TIER:"episode",CLAUDE_MEM_GROK_BOT_INJECT_WINDOW:"80",CLAUDE_MEM_GROK_BOT_INJECT_FALLBACK:"house",CLAUDE_MEM_GROK_BOT_INJECT_PLATFORM_SOURCE:"",CLAUDE_MEM_GROK_BOT_INJECT_PROJECTS_BY_AGENT:"",CLAUDE_MEM_GROK_BOT_INJECT_MAX_LINE_CHARS:"160",CLAUDE_MEM_GROK_BOT_INJECT_DEBOUNCE_MS:"1500",CLAUDE_MEM_CCS_ALIGN_ENABLED:"true",CLAUDE_MEM_CCS_ALIGN_VIEWER_IDS:"ccs-align",CLAUDE_MEM_CCS_ALIGN_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_CCS_ALIGN_PATCH_SHADOWS:"false",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){let r=process.env[e]??this.DEFAULTS[e];return e==="CLAUDE_MEM_WORKER_HOST"?this.normalizeWorkerHost(r):r}static normalizeWorkerHost(e){return e==="localhost"?"127.0.0.1":e}static finalizeSettings(e,r){let n=r?this.applyEnvOverrides(e):e;return n.CLAUDE_MEM_WORKER_HOST=this.normalizeWorkerHost(n.CLAUDE_MEM_WORKER_HOST),n}static getInt(e){let r=this.get(e);return parseInt(r,10)}static applyEnvOverrides(e){let r={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(r[n]=process.env[n]);return r}static loadFromFile(e,r=!0){try{if(!(0,Qb.existsSync)(e)){let u=this.getAllDefaults();try{go(e,u),console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(d){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,d instanceof Error?d.message:String(d))}return this.finalizeSettings(u,r)}let n=(0,Qb.readFileSync)(e,"utf-8"),i=yo(n),s=i,o=i.env&&typeof i.env=="object"&&!Array.isArray(i.env),a=o&&Object.keys(i).some(u=>u!=="env");if(o&&(s=i.env,!a))try{go(e,s),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(u){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,u instanceof Error?u.message:String(u))}if(s.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES===BAe){s={...s,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES};try{go(e,a?{...i,env:s}:s),console.warn("[SETTINGS] Migrated Telegram trigger types off the legacy default:",e)}catch(u){console.warn("[SETTINGS] Failed to migrate Telegram trigger types:",e,u instanceof Error?u.message:String(u))}}let c=WAe(s.CLAUDE_MEM_CLOUD_SYNC_HUB_URL);if(c!==null){s={...s,CLAUDE_MEM_CLOUD_SYNC_HUB_URL:c};try{go(e,a?{...i,env:s}:s),console.warn("[SETTINGS] Migrated cloud sync hub URL off the legacy workers.dev host:",e)}catch(u){console.warn("[SETTINGS] Failed to migrate cloud sync hub URL:",e,u instanceof Error?u.message:String(u))}}let l={...this.DEFAULTS};for(let u of Object.keys(this.DEFAULTS))s[u]!==void 0&&(l[u]=s[u]);return this.finalizeSettings(l,r)}catch(n){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,n instanceof Error?n.message:String(n));let i=this.getAllDefaults();return this.finalizeSettings(i,r)}}}});function YAe(){let t=xl("CLAUDE_MEM_QUEUE_ENGINE").trim().toLowerCase();if(t==="sqlite"||t==="bullmq")return t;throw new Error(`Invalid CLAUDE_MEM_QUEUE_ENGINE=${t}; expected sqlite or bullmq`)}function iV(){let t=YAe(),e=QAe(xl("CLAUDE_MEM_REDIS_MODE")),r=xl("CLAUDE_MEM_REDIS_URL").trim()||null,n=xl("CLAUDE_MEM_REDIS_HOST").trim()||"127.0.0.1",i=XAe(xl("CLAUDE_MEM_REDIS_PORT")),s=ZAe(xl("CLAUDE_MEM_QUEUE_REDIS_PREFIX")),o=r?tRe(r):eRe(n,i);return{engine:t,mode:e,url:r,host:r?rV(r).host:n,port:r?rV(r).port:i,prefix:s,connection:o}}function xl(t){if(process.env[t]!==void 0)return process.env[t];if((0,nV.existsSync)($E)){let e=tp.loadFromFile($E,!1)[t];if(e!==void 0)return e}return tp.get(t)}function QAe(t){let e=t.trim().toLowerCase();if(e==="external"||e==="managed"||e==="docker")return e;throw new Error(`Invalid CLAUDE_MEM_REDIS_MODE=${t}; expected external, managed, or docker`)}function XAe(t){let e=Number.parseInt(t,10);if(!Number.isInteger(e)||e<=0||e>65535)throw new Error(`Invalid CLAUDE_MEM_REDIS_PORT=${t}; expected a TCP port`);return e}function ZAe(t){return(t.trim()||"claude_mem").replace(/[^a-zA-Z0-9_-]/g,"_")}function eRe(t,e){return{host:t,port:e,maxRetriesPerRequest:null,connectTimeout:1e3,lazyConnect:!0}}function tRe(t){let e=new URL(t);if(e.protocol!=="redis:"&&e.protocol!=="rediss:")throw new Error("CLAUDE_MEM_REDIS_URL must use redis:// or rediss://");let r=e.pathname.length>1?Number.parseInt(e.pathname.slice(1),10):void 0;if(r!==void 0&&(!Number.isInteger(r)||r<0))throw new Error(`Invalid Redis database in CLAUDE_MEM_REDIS_URL: ${e.pathname}`);return{host:e.hostname||"127.0.0.1",port:e.port?Number.parseInt(e.port,10):6379,username:e.username?decodeURIComponent(e.username):void 0,password:e.password?decodeURIComponent(e.password):void 0,db:r,tls:e.protocol==="rediss:"?{}:void 0,maxRetriesPerRequest:null,connectTimeout:1e3,lazyConnect:!0}}function rV(t){let e=new URL(t);return{host:e.hostname||"127.0.0.1",port:e.port?Number.parseInt(e.port,10):6379}}var nV,sV=R(()=>{"use strict";nV=require("fs");tV();Hn()});function Xb(t){let e=Object.fromEntries(cV.map(i=>[i,0]));oV.lastIndex=0;let r=0,n=t.replace(oV,(i,s)=>(e[s]=(e[s]??0)+1,r+=1,""));return r>aV&&x.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:r,maxAllowed:aV,contentLength:t.length}),{stripped:n.trim(),counts:e}}var cV,oV,aV,rRe,i6e,s6e,MA=R(()=>{"use strict";fe();cV=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],oV=new RegExp(`<(${cV.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g"),aV=100;rRe=["task-notification"],i6e=new RegExp(`^\\s*<(${rRe.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),s6e=256*1024});function wl(t,e={}){let r=e.mode??nRe(),n=!1,i=!0,s=[];for(let m of t.events){let y=dV(m);y.hadPrivate&&(n=!0),y.body.length>0&&(i=!1,s.push(y.body))}let o=t.events.length>0&&i,a=t.project.serverSessionId?`
9790
+ `});var Yb={};io(Yb,{PostgresAgentEventsRepository:()=>Xr,PostgresAuthRepository:()=>Nt,PostgresDataDeletionRepository:()=>cc,PostgresObservationGenerationJobEventsRepository:()=>Wt,PostgresObservationGenerationJobRepository:()=>dt,PostgresObservationRepository:()=>Zr,PostgresObservationSourcesRepository:()=>wo,PostgresProjectsRepository:()=>_n,PostgresRateLimitRepository:()=>Uo,PostgresServerSessionsRepository:()=>zt,PostgresTeamsRepository:()=>va,PostgresUsageRepository:()=>Kr,SERVER_POSTGRES_SCHEMA_VERSION:()=>Xd,SERVER_POSTGRES_TABLES:()=>$Ae,bootstrapServerPostgresSchema:()=>Wb,buildAgentEventIdempotencyKey:()=>tN,buildObservationGenerationJobIdempotencyKey:()=>nN,buildObservationGenerationKey:()=>fS,buildServerSessionIdempotencyKey:()=>w$,closePostgresPool:()=>sle,createPostgresPool:()=>em,createPostgresStorageRepositories:()=>GAe,getPostgresDatabaseUrl:()=>tq,getSharedPostgresPool:()=>gx,parsePostgresConfig:()=>yu,withPostgresTransaction:()=>In});function GAe(t){return{teams:new va(t),projects:new _n(t),auth:new Nt(t),sessions:new zt(t),agentEvents:new Xr(t),observations:new Zr(t),observationSources:new wo(t),observationGenerationJobs:new dt(t),observationGenerationJobEvents:new Wt(t),usage:new Kr(t),rateLimits:new Uo(t)}}var Zd=R(()=>{"use strict";Qa();Oi();fs();su();Xa();Ps();Vb();Jo();xh();Qa();Oi();Zf();bx();fs();su();Ro();Xa();xh();jA();Ps();Vb();Jo()});function ZH(t){return process.platform==="win32"?Math.round(t*KA.WINDOWS_MULTIPLIER):t}var KA,eV=R(()=>{"use strict";KA={HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5}});function WAe(t){if(typeof t!="string")return null;let e=t.trim();if(e.length===0)return null;try{if(new URL(e).hostname===HAe)return VAe}catch{return null}return null}var Qb,DA,ep,BAe,HAe,VAe,tp,tV=R(()=>{"use strict";Qb=require("fs"),DA=require("path"),ep=require("os");eV();Xl();BAe="security_alert",HAe="sync-hub.black-pond-afbb.workers.dev",VAe="https://sync.cmem.ai";tp=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_API_TIMEOUT_MS:String(ZH(KA.API_REQUEST)),CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-flash-latest",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_DATA_DIR:(0,DA.join)((0,ep.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_CLAUDE_CONFIG_DIR:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES:"",CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:"",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,DA.join)((0,ep.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_OBSERVER_MAX_CONVERSATION_CHARS:"400000",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_CHROMA_PREWARM_TIMEOUT_MS:"120000",CLAUDE_MEM_CHROMA_MAX_PENDING_MUTATIONS:"5000",CLAUDE_MEM_CLOUD_SYNC_TOKEN:"",CLAUDE_MEM_CLOUD_SYNC_USER_ID:"",CLAUDE_MEM_CLOUD_SYNC_HUB_URL:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_ID:"",CLAUDE_MEM_CLOUD_SYNC_DEVICE_NAME:(0,ep.hostname)(),CLAUDE_MEM_CLOUD_SYNC_WS:"true",CLAUDE_MEM_CLOUD_SYNC_CONTENT_BATCH_SIZE:"40",CLAUDE_MEM_CLOUD_SYNC_REQUEST_TIMEOUT_MS:"90000",CLAUDE_MEM_LLM_TIMEOUT_MS:"30000",CLAUDE_MEM_TV_TOKEN:"",CLAUDE_MEM_PRO_TRIAL_EMAIL:"",CLAUDE_MEM_PRO_TRIAL_AT:"",CLAUDE_MEM_PRO_TRIAL_STATE:"",CLAUDE_MEM_PRO_TRIAL_ENDS_AT:"",CLAUDE_MEM_PRO_PLAN:"",CLAUDE_MEM_PRO_FALLBACK_AT:"",CLAUDE_MEM_PRO_MEMORY_KEY:"",CLAUDE_MEM_PRO_MEMORY_BASE_URL:"",CLAUDE_MEM_PRO_MEMORY_MODEL:"",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_WRAPUPS_ENABLED:"true",CLAUDE_MEM_TELEGRAM_OBSERVATION_ALERTS_ENABLED:"false",CLAUDE_MEM_TELEGRAM_WRAPUP_ROUTES:"{}",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert,sensitive",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_AWARENESS_ENABLED:"true",CLAUDE_MEM_GROK_BOT_AWARENESS_AGENT_IDS:"521e962d-2ec3-4488-bfbc-54d5209ce118,95601360-61f7-4fd9-bb3a-2c976b2b85c0",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_GROK_BOT_AWARENESS_TRIGGER_CONCEPTS:"",CLAUDE_MEM_GROK_BOT_INJECT_ENABLED:"true",CLAUDE_MEM_GROK_BOT_INJECT_AGENT_IDS:"*",CLAUDE_MEM_GROK_BOT_INJECT_TIER:"episode",CLAUDE_MEM_GROK_BOT_INJECT_WINDOW:"80",CLAUDE_MEM_GROK_BOT_INJECT_FALLBACK:"house",CLAUDE_MEM_GROK_BOT_INJECT_PLATFORM_SOURCE:"",CLAUDE_MEM_GROK_BOT_INJECT_PROJECTS_BY_AGENT:"",CLAUDE_MEM_GROK_BOT_INJECT_MAX_LINE_CHARS:"160",CLAUDE_MEM_GROK_BOT_INJECT_DEBOUNCE_MS:"1500",CLAUDE_MEM_GROK_BOT_INJECT_STANDING_LINE:"",CLAUDE_MEM_CCS_ALIGN_ENABLED:"true",CLAUDE_MEM_CCS_ALIGN_VIEWER_IDS:"ccs-align",CLAUDE_MEM_CCS_ALIGN_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",CLAUDE_MEM_CCS_ALIGN_PATCH_SHADOWS:"false",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_API_KEY:"",CLAUDE_MEM_SERVER_PROJECT_ID:"",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){let r=process.env[e]??this.DEFAULTS[e];return e==="CLAUDE_MEM_WORKER_HOST"?this.normalizeWorkerHost(r):r}static normalizeWorkerHost(e){return e==="localhost"?"127.0.0.1":e}static finalizeSettings(e,r){let n=r?this.applyEnvOverrides(e):e;return n.CLAUDE_MEM_WORKER_HOST=this.normalizeWorkerHost(n.CLAUDE_MEM_WORKER_HOST),n}static getInt(e){let r=this.get(e);return parseInt(r,10)}static applyEnvOverrides(e){let r={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(r[n]=process.env[n]);return r}static loadFromFile(e,r=!0){try{if(!(0,Qb.existsSync)(e)){let u=this.getAllDefaults();try{go(e,u),console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(d){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,d instanceof Error?d.message:String(d))}return this.finalizeSettings(u,r)}let n=(0,Qb.readFileSync)(e,"utf-8"),i=yo(n),s=i,o=i.env&&typeof i.env=="object"&&!Array.isArray(i.env),a=o&&Object.keys(i).some(u=>u!=="env");if(o&&(s=i.env,!a))try{go(e,s),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(u){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,u instanceof Error?u.message:String(u))}if(s.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES===BAe){s={...s,CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:this.DEFAULTS.CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES};try{go(e,a?{...i,env:s}:s),console.warn("[SETTINGS] Migrated Telegram trigger types off the legacy default:",e)}catch(u){console.warn("[SETTINGS] Failed to migrate Telegram trigger types:",e,u instanceof Error?u.message:String(u))}}let c=WAe(s.CLAUDE_MEM_CLOUD_SYNC_HUB_URL);if(c!==null){s={...s,CLAUDE_MEM_CLOUD_SYNC_HUB_URL:c};try{go(e,a?{...i,env:s}:s),console.warn("[SETTINGS] Migrated cloud sync hub URL off the legacy workers.dev host:",e)}catch(u){console.warn("[SETTINGS] Failed to migrate cloud sync hub URL:",e,u instanceof Error?u.message:String(u))}}let l={...this.DEFAULTS};for(let u of Object.keys(this.DEFAULTS))s[u]!==void 0&&(l[u]=s[u]);return this.finalizeSettings(l,r)}catch(n){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,n instanceof Error?n.message:String(n));let i=this.getAllDefaults();return this.finalizeSettings(i,r)}}}});function YAe(){let t=xl("CLAUDE_MEM_QUEUE_ENGINE").trim().toLowerCase();if(t==="sqlite"||t==="bullmq")return t;throw new Error(`Invalid CLAUDE_MEM_QUEUE_ENGINE=${t}; expected sqlite or bullmq`)}function iV(){let t=YAe(),e=QAe(xl("CLAUDE_MEM_REDIS_MODE")),r=xl("CLAUDE_MEM_REDIS_URL").trim()||null,n=xl("CLAUDE_MEM_REDIS_HOST").trim()||"127.0.0.1",i=XAe(xl("CLAUDE_MEM_REDIS_PORT")),s=ZAe(xl("CLAUDE_MEM_QUEUE_REDIS_PREFIX")),o=r?tRe(r):eRe(n,i);return{engine:t,mode:e,url:r,host:r?rV(r).host:n,port:r?rV(r).port:i,prefix:s,connection:o}}function xl(t){if(process.env[t]!==void 0)return process.env[t];if((0,nV.existsSync)($E)){let e=tp.loadFromFile($E,!1)[t];if(e!==void 0)return e}return tp.get(t)}function QAe(t){let e=t.trim().toLowerCase();if(e==="external"||e==="managed"||e==="docker")return e;throw new Error(`Invalid CLAUDE_MEM_REDIS_MODE=${t}; expected external, managed, or docker`)}function XAe(t){let e=Number.parseInt(t,10);if(!Number.isInteger(e)||e<=0||e>65535)throw new Error(`Invalid CLAUDE_MEM_REDIS_PORT=${t}; expected a TCP port`);return e}function ZAe(t){return(t.trim()||"claude_mem").replace(/[^a-zA-Z0-9_-]/g,"_")}function eRe(t,e){return{host:t,port:e,maxRetriesPerRequest:null,connectTimeout:1e3,lazyConnect:!0}}function tRe(t){let e=new URL(t);if(e.protocol!=="redis:"&&e.protocol!=="rediss:")throw new Error("CLAUDE_MEM_REDIS_URL must use redis:// or rediss://");let r=e.pathname.length>1?Number.parseInt(e.pathname.slice(1),10):void 0;if(r!==void 0&&(!Number.isInteger(r)||r<0))throw new Error(`Invalid Redis database in CLAUDE_MEM_REDIS_URL: ${e.pathname}`);return{host:e.hostname||"127.0.0.1",port:e.port?Number.parseInt(e.port,10):6379,username:e.username?decodeURIComponent(e.username):void 0,password:e.password?decodeURIComponent(e.password):void 0,db:r,tls:e.protocol==="rediss:"?{}:void 0,maxRetriesPerRequest:null,connectTimeout:1e3,lazyConnect:!0}}function rV(t){let e=new URL(t);return{host:e.hostname||"127.0.0.1",port:e.port?Number.parseInt(e.port,10):6379}}var nV,sV=R(()=>{"use strict";nV=require("fs");tV();Hn()});function Xb(t){let e=Object.fromEntries(cV.map(i=>[i,0]));oV.lastIndex=0;let r=0,n=t.replace(oV,(i,s)=>(e[s]=(e[s]??0)+1,r+=1,""));return r>aV&&x.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:r,maxAllowed:aV,contentLength:t.length}),{stripped:n.trim(),counts:e}}var cV,oV,aV,rRe,i6e,s6e,MA=R(()=>{"use strict";fe();cV=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],oV=new RegExp(`<(${cV.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g"),aV=100;rRe=["task-notification"],i6e=new RegExp(`^\\s*<(${rRe.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),s6e=256*1024});function wl(t,e={}){let r=e.mode??nRe(),n=!1,i=!0,s=[];for(let m of t.events){let y=dV(m);y.hadPrivate&&(n=!0),y.body.length>0&&(i=!1,s.push(y.body))}let o=t.events.length>0&&i,a=t.project.serverSessionId?`
9791
9791
  <server_session_id>${rs(t.project.serverSessionId)}</server_session_id>`:"",c=t.project.projectName?`
9792
9792
  <project_name>${rs(t.project.projectName)}</project_name>`:"",l=iRe(r),u=t.job.sourceType==="session_summary",d=["You are reviewing a complete agent session. Return a single","<summary>...</summary> XML block describing the arc of the session. If the","session contains 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 the <summary> block (at least one of the first five is required):","<summary>"," <request>what the user asked for</request>"," <investigated>what was explored, and how</investigated>"," <learned>durable findings worth remembering later</learned>"," <completed>what was actually done</completed>"," <next_steps>what is left open</next_steps>"," <notes>anything else worth keeping</notes>","</summary>"],p=["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];return{prompt:["<server_beta_observation_request>",` <project_id>${rs(t.project.projectId)}</project_id>`,` <team_id>${rs(t.project.teamId)}</team_id>`+a+c,` <generation_job_id>${rs(t.job.id)}</generation_job_id>`," <agent_events>",s.length>0?s.join(`
9793
9793
  `):" <!-- empty after privacy stripping -->"," </agent_events>","</server_beta_observation_request>","",...u?d:p].join(`