@bjlee2024/claude-mem 13.4.20 → 13.4.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/dist/npx-cli/index.js +241 -241
- package/openclaw/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/.codex-plugin/plugin.json +1 -1
- package/plugin/package.json +1 -1
- package/plugin/scripts/mcp-server.cjs +29 -29
- package/plugin/scripts/server-beta-service.cjs +1 -1
- package/plugin/scripts/worker-service.cjs +142 -142
|
@@ -60,7 +60,7 @@ ${s.stack}`:` ${s.message}`;else if(this.getLevel()===0&&typeof s=="object")try{
|
|
|
60
60
|
`)}else Hy(p+`
|
|
61
61
|
`)}getRecentLogs(){return this.recentLogs.join(`
|
|
62
62
|
`)}clearRecentLogs(){this.recentLogs=[]}debug(e,t,n,i){this.log(0,e,t,n,i)}info(e,t,n,i){this.log(1,e,t,n,i)}warn(e,t,n,i){this.log(2,e,t,n,i)}error(e,t,n,i){this.log(3,e,t,n,i)}dataIn(e,t,n,i){this.info(e,`\u2192 ${t}`,n,i)}dataOut(e,t,n,i){this.info(e,`\u2190 ${t}`,n,i)}success(e,t,n,i){this.info(e,`\u2713 ${t}`,n,i)}failure(e,t,n,i){this.error(e,`\u2717 ${t}`,n,i)}timing(e,t,n,i){this.info(e,`\u23F1 ${t}`,i,{duration:`${n}ms`})}happyPathError(e,t,n,i,s=""){let l=((new Error().stack||"").split(`
|
|
63
|
-
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),u=l?`${l[1].split("/").pop()}:${l[2]}`:"unknown",d={...n,location:u};return this.warn(e,`[HAPPY-PATH] ${t}`,d,i),s}},_=new Wy});var KA=h((ife,CA)=>{"use strict";var RA=Object.getOwnPropertySymbols,nV=Object.prototype.hasOwnProperty,iV=Object.prototype.propertyIsEnumerable;function sV(r){if(r==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(r)}function oV(){try{if(!Object.assign)return!1;var r=new String("abc");if(r[5]="de",Object.getOwnPropertyNames(r)[0]==="5")return!1;for(var e={},t=0;t<10;t++)e["_"+String.fromCharCode(t)]=t;var n=Object.getOwnPropertyNames(e).map(function(s){return e[s]});if(n.join("")!=="0123456789")return!1;var i={};return"abcdefghijklmnopqrst".split("").forEach(function(s){i[s]=s}),Object.keys(Object.assign({},i)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}CA.exports=oV()?Object.assign:function(r,e){for(var t,n=sV(r),i,s=1;s<arguments.length;s++){t=Object(arguments[s]);for(var o in t)nV.call(t,o)&&(n[o]=t[o]);if(RA){i=RA(t);for(var a=0;a<i.length;a++)iV.call(t,i[a])&&(n[i[a]]=t[i[a]])}}return n}});var DA=h((sfe,jA)=>{(function(){"use strict";var r=KA(),e=Fy(),t={origin:"*",methods:"GET,HEAD,PUT,PATCH,POST,DELETE",preflightContinue:!1,optionsSuccessStatus:204};function n(m){return typeof m=="string"||m instanceof String}function i(m,y){if(Array.isArray(y)){for(var b=0;b<y.length;++b)if(i(m,y[b]))return!0;return!1}else return n(y)?m===y:y instanceof RegExp?y.test(m):!!y}function s(m,y){var b=y.headers.origin,g=[],E;return!m.origin||m.origin==="*"?g.push([{key:"Access-Control-Allow-Origin",value:"*"}]):n(m.origin)?(g.push([{key:"Access-Control-Allow-Origin",value:m.origin}]),g.push([{key:"Vary",value:"Origin"}])):(E=i(b,m.origin),g.push([{key:"Access-Control-Allow-Origin",value:E?b:!1}]),g.push([{key:"Vary",value:"Origin"}])),g}function o(m){var y=m.methods;return y.join&&(y=m.methods.join(",")),{key:"Access-Control-Allow-Methods",value:y}}function a(m){return m.credentials===!0?{key:"Access-Control-Allow-Credentials",value:"true"}:null}function c(m,y){var b=m.allowedHeaders||m.headers,g=[];return b?b.join&&(b=b.join(",")):(b=y.headers["access-control-request-headers"],g.push([{key:"Vary",value:"Access-Control-Request-Headers"}])),b&&b.length&&g.push([{key:"Access-Control-Allow-Headers",value:b}]),g}function l(m){var y=m.exposedHeaders;if(y)y.join&&(y=y.join(","));else return null;return y&&y.length?{key:"Access-Control-Expose-Headers",value:y}:null}function u(m){var y=(typeof m.maxAge=="number"||m.maxAge)&&m.maxAge.toString();return y&&y.length?{key:"Access-Control-Max-Age",value:y}:null}function d(m,y){for(var b=0,g=m.length;b<g;b++){var E=m[b];E&&(Array.isArray(E)?d(E,y):E.key==="Vary"&&E.value?e(y,E.value):E.value&&y.setHeader(E.key,E.value))}}function p(m,y,b,g){var E=[],I=y.method&&y.method.toUpperCase&&y.method.toUpperCase();I==="OPTIONS"?(E.push(s(m,y)),E.push(a(m)),E.push(o(m)),E.push(c(m,y)),E.push(u(m)),E.push(l(m)),d(E,b),m.preflightContinue?g():(b.statusCode=m.optionsSuccessStatus,b.setHeader("Content-Length","0"),b.end())):(E.push(s(m,y)),E.push(a(m)),E.push(l(m)),d(E,b),g())}function f(m){var y=null;return typeof m=="function"?y=m:y=function(b,g){g(null,m)},function(g,E,I){y(g,function(T,L){if(T)I(T);else{var U=r({},t,L),ie=null;U.origin&&typeof U.origin=="function"?ie=U.origin:U.origin&&(ie=function(je,ce){ce(null,U.origin)}),ie?ie(g.headers.origin,function(je,ce){je||!ce?I(je):(U.origin=ce,p(U,g,E,I))}):I()}})}}jA.exports=f})()});function zy(r,e={}){let t=[];e.includeCors!==!1&&t.push(Ql()),t.push(Yy.default.json({limit:"5mb"})),t.push((s,o,a)=>{let l=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(y=>s.path.endsWith(y)),u=s.path==="/api/logs";if(s.path.startsWith("/health")||s.path==="/"||l||u)return a();let d=Date.now(),p=`${s.method}-${Date.now()}`,f=r(s.method,s.path,s.body);_.debug("HTTP",`\u2192 ${s.method} ${s.path}`,{requestId:p},f);let m=o.send.bind(o);o.send=function(y){let b=Date.now()-d;return _.debug("HTTP",`\u2190 ${o.statusCode} ${s.path}`,{requestId:p,duration:`${b}ms`}),m(y)},a()});let n=Fi(),i=PA.default.join(n,"plugin","ui");return t.push(Yy.default.static(i)),t}function aV(r){let e=(process.env.CLAUDE_MEM_CORS_ALLOW_ORIGINS||"").split(",").map(i=>i.trim()).filter(Boolean);if(e.includes("*")||e.includes(r))return!0;let t;try{t=new URL(r).hostname}catch{return!1}if(t==="localhost"||t==="127.0.0.1"||t==="::1"||!t.includes(".")||t.endsWith(".local")||t.endsWith(".internal")||t.endsWith(".lan")||t.endsWith(".ts.net"))return!0;let n=t.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);if(n){let i=Number(n[1]),s=Number(n[2]);if(i===10||i===172&&s>=16&&s<=31||i===192&&s===168||i===100&&s>=64&&s<=127)return!0}return!1}function Ql(){return(0,MA.default)({origin:(r,e)=>{!r||aV(r)?e(null,!0):e(new Error("CORS not allowed"))},methods:["GET","HEAD","POST","PUT","PATCH","DELETE"],allowedHeaders:["Content-Type","Authorization","X-Requested-With"],credentials:!1})}function wa(r,e,t){let n=r.ip||r.connection.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){_.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:r.path,clientIp:n,method:r.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}t()}function Qy(r,e,t){if(!t||Object.keys(t).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=t.tool_name||"?",i=t.tool_input;return`tool=${_.formatTool(n,i)}`}return e.includes("/summarize")?"requesting summary":""}var Yy,MA,PA,NA=R(()=>{"use strict";Yy=ze(zl(),1),MA=ze(DA(),1),PA=ze(require("path"),1);kt();se()});var LA=R(()=>{"use strict";NA()});function qA(r,e,t,n){let i={error:r,message:e};return t&&(i.code=t),n&&(i.details=n),i}function JA(r,e){e.status(404).json(qA("NotFound",`Cannot ${r.method} ${r.path}`))}var Gs,FA,UA=R(()=>{"use strict";se();Gs=class extends Error{constructor(t,n=500,i,s){super(t);this.statusCode=n;this.code=i;this.details=s;this.name="AppError"}statusCode;code;details};FA=(r,e,t,n)=>{let i=r instanceof Gs?r.statusCode:500;_.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:r.message,code:r instanceof Gs?r.code:void 0},r);let s=qA(r.name||"Error",r.message,r instanceof Gs?r.code:void 0,r instanceof Gs?r.details:void 0);t.status(i).json(s)}});var GA=R(()=>{"use strict"});function Ia(r=process.env){let e={};for(let[t,n]of Object.entries(r))if(n!==void 0){if(lV.has(t)){e[t]=n;continue}Zy.has(t)||cV.has(t)||Xy.some(i=>t.startsWith(i))||(e[t]=n)}return e}var Xy,Zy,cV,lV,Xl=R(()=>{"use strict";Xy=["CLAUDECODE_","CLAUDE_CODE_"],Zy=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),cV=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy"]),lV=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS"])});function pr(r){if(!Number.isInteger(r)||r<0||r===0)return!1;try{return process.kill(r,0),!0}catch(e){if(e instanceof Error){let t=e.code;return t==="EPERM"?!0:(_.debug("SYSTEM","PID check failed",{pid:r,code:t}),!1)}return _.warn("SYSTEM","PID check threw non-Error",{pid:r,error:String(e)}),!1}}function mV(r){let e=BA.get(r);if(e&&Date.now()-e.capturedAtMs<fV)return e.token;let t=null;try{let n=(0,ib.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${r}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Ia(process.env),LC_ALL:"C",LANG:"C"}});if(n.status===0){let i=n.stdout.trim();t=i.length>0?i:null}}catch(n){_.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:r,error:n instanceof Error?n.message:String(n)}),t=null}return BA.set(r,{token:t,capturedAtMs:Date.now()}),t}function sb(r){if(!Number.isInteger(r)||r<=0)return null;if(process.platform==="linux")try{let e=(0,Hr.readFileSync)(`/proc/${r}/stat`,"utf-8"),t=e.lastIndexOf(") ");if(t<0)return null;let i=e.slice(t+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(e){return _.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return mV(r);try{let e=(0,ib.spawnSync)("ps",["-p",String(r),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Ia(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let t=e.stdout.trim();return t.length>0?t:null}catch(e){return _.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}}function Hn(r){if(!r||!pr(r.pid))return!1;if(!r.startToken)return!0;let e=sb(r.pid);if(e===null)return!0;let t=e===r.startToken;return t||_.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:r.pid,stored:r.startToken,current:e}),t}function Zl(){return eb||(eb=new nb),eb}function tb(){let r=hV.shift();r&&r()}var ib,Hr,rb,uV,dV,pV,fV,BA,nb,eb,hV,Bs=R(()=>{"use strict";ib=require("child_process");GA();Hr=require("fs"),rb=ze(require("path"),1);se();Xl();kt();uV=5e3,dV=1e3,pV=Pe.supervisorRegistry();fV=5e3,BA=new Map;nb=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=pV){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,Hr.mkdirSync)(rb.default.dirname(this.registryPath),{recursive:!0}),!(0,Hr.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Hr.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[i,s]of Object.entries(n))this.entries.set(i,s)}catch(t){t instanceof Error?_.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},t):_.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(t)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&_.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,t,n){this.initialize(),this.entries.set(e,t),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let t=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),t?.type==="sdk"&&tb()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,t])=>({id:e,...t})).sort((e,t)=>{let n=Date.parse(e.startedAt),i=Date.parse(t.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(i)?0:i)})}getBySession(e){let t=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===t)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}getByPid(e){return this.getAll().filter(t=>t.pid===e)}pruneDeadEntries(){this.initialize();let e=0,t=0;for(let[n,i]of this.entries)pr(i.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,i.type==="sdk"&&(t+=1));e>0&&this.persist();for(let n=0;n<t;n+=1)tb();return e}async reapSession(e){this.initialize();let t=this.getBySession(e);if(t.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;_.info("SYSTEM",`Reaping ${t.length} process(es) for session ${e}`,{sessionId:n,pids:t.map(a=>a.pid)});let i=t.filter(a=>pr(a.pid));for(let a of i)try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):_.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}let s=Date.now()+uV;for(;Date.now()<s&&i.filter(c=>pr(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100));let o=i.filter(a=>pr(a.pid));for(let a of o){_.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(c){c instanceof Error?c.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):_.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}}if(o.length>0){let a=Date.now()+dV;for(;Date.now()<a&&o.filter(l=>pr(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let a of t)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of t)a.type==="sdk"&&tb();return _.info("SYSTEM",`Reaped ${t.length} process(es) for session ${e}`,{sessionId:n,reaped:t.length}),t.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,Hr.mkdirSync)(rb.default.dirname(this.registryPath),{recursive:!0}),(0,Hr.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},eb=null;hV=[]});var $A,HA=R(()=>{"use strict";$A={DEFAULT:3e5,HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,WORKER_STARTUP_WAIT:1e3,PRE_RESTART_SETTLE_DELAY:2e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5}});async function XA(r){let e=r.currentPid??process.pid,t=r.pidFilePath??bV,n=r.registry.getAll(),i=[...n].filter(o=>o.pid!==e).sort((o,a)=>Date.parse(a.startedAt)-Date.parse(o.startedAt));for(let o of i){if(!pr(o.pid)){r.registry.unregister(o.id);continue}try{await WA(o,"SIGTERM")}catch(a){a instanceof Error?_.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:o.pid,pgid:o.pgid,type:o.type},a):_.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:o.pid,pgid:o.pgid,type:o.type,error:String(a)})}}await VA(i,5e3);let s=i.filter(o=>pr(o.pid));for(let o of s)try{await WA(o,"SIGKILL")}catch(a){a instanceof Error?_.debug("SYSTEM","Failed to force kill child process",{pid:o.pid,pgid:o.pgid,type:o.type},a):_.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:o.pid,pgid:o.pgid,type:o.type,error:String(a)})}await VA(s,1e3);for(let o of i)r.registry.unregister(o.id);for(let o of n.filter(a=>a.pid===e))r.registry.unregister(o.id);try{(0,zA.rmSync)(t,{force:!0})}catch(o){o instanceof Error?_.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:t},o):_.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:t,error:String(o)})}r.registry.pruneDeadEntries()}async function VA(r,e){let t=Date.now()+e;for(;Date.now()<t;){if(r.filter(i=>pr(i.pid)).length===0)return;await new Promise(i=>setTimeout(i,100))}}async function WA(r,e){let{pid:t,pgid:n}=r;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}try{process.kill(t,e)}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}return}if(e==="SIGTERM"){try{process.kill(t,e)}catch(o){if(o instanceof Error&&o.code==="ESRCH")return;throw o}return}let i=await gV();if(i){await new Promise((o,a)=>{i(t,e,c=>{if(!c){o();return}if(c.code==="ESRCH"){o();return}a(c)})});return}let s=["/PID",String(t),"/T"];e==="SIGKILL"&&s.push("/F"),await yV("taskkill",s,{timeout:$A.POWERSHELL_COMMAND,windowsHide:!0})}async function gV(){let r="tree-kill";try{let e=await import(r);return e.default??e}catch(e){return _.debug("SYSTEM","tree-kill module not available, using fallback",{},e instanceof Error?e:void 0),null}}var YA,zA,QA,yV,bV,ZA=R(()=>{"use strict";YA=require("child_process"),zA=require("fs"),QA=require("util");se();HA();Bs();kt();yV=(0,QA.promisify)(YA.execFile),bV=Pe.workerPid()});function vV(){let e=Zl().pruneDeadEntries();e>0&&_.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function tk(){$s===null&&($s=setInterval(vV,ek),$s.unref(),_.debug("SYSTEM","Health checker started",{intervalMs:ek}))}function rk(){$s!==null&&(clearInterval($s),$s=null,_.debug("SYSTEM","Health checker stopped"))}var ek,$s,nk=R(()=>{"use strict";se();Bs();ek=3e4,$s=null});function ik(){return SV}function xV(r={}){let e=r.pidFilePath??EV;if(!(0,Ji.existsSync)(e))return"missing";let t=null;try{t=JSON.parse((0,Ji.readFileSync)(e,"utf-8"))}catch(i){return i instanceof Error?_.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},i):_.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(i)}),(0,Ji.rmSync)(e,{force:!0}),"invalid"}return Hn(t)&&t?((r.logAlive??!0)&&_.info("SYSTEM","Worker already running (PID alive)",{existingPid:t.pid,existingPort:t.port,startedAt:t.startedAt}),"alive"):(_.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:t?.pid,port:t?.port,startedAt:t?.startedAt}),(0,Ji.rmSync)(e,{force:!0}),"stale")}var Ji,EV,ob,SV,sk=R(()=>{"use strict";Ji=require("fs");se();Bs();ZA();nk();kt();EV=Pe.workerPid(),ob=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),xV({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,tk()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let t=async n=>{if(this.shutdownInitiated){_.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,_.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){i instanceof Error?_.error("SYSTEM","Error during shutdown",{},i):_.error("SYSTEM","Error during shutdown (non-Error)",{error:String(i)});try{await this.stop()}catch(s){s instanceof Error?_.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):_.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(s)})}}process.exit(0)};process.on("SIGTERM",()=>{t("SIGTERM")}),process.on("SIGINT",()=>{t("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{_.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{t("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}rk(),this.stopPromise=XA({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,t,n){this.registry.register(e,t,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},SV=new ob(Zl())});function ab(r,e,t){r.on("finish",async()=>{try{await t()}finally{process.exit(0)}}),r.json(e)}var ok=R(()=>{"use strict"});function cb(r,e=Date.now){return Math.max(0,Math.floor((e()-r)/1e3))}var ak=R(()=>{"use strict"});var lb,ck,Gfe,lk=R(()=>{"use strict";lb=class{entries=new Map;set(e){if(!e||typeof e!="object")return;let t=e.rateLimitType??"default";this.entries.set(t,{...e,observedAt:Date.now()})}get(e){return e?this.entries.get(e):this.entries.get("default")}getAll(){return Array.from(this.entries.values()).sort((e,t)=>t.observedAt-e.observedAt)}getMostRecentByWindow(){return{five_hour:this.entries.get("five_hour"),seven_day:this.entries.get("seven_day"),seven_day_opus:this.entries.get("seven_day_opus"),seven_day_sonnet:this.entries.get("seven_day_sonnet"),overage:this.entries.get("overage")}}get size(){return this.entries.size}clear(){this.entries.clear()}},ck=new lb,Gfe=900*1e3});function IV(r){r.setHeader("X-Content-Type-Options","nosniff"),r.setHeader("X-Frame-Options","DENY"),r.setHeader("X-DNS-Prefetch-Control","off"),r.setHeader("Referrer-Policy","no-referrer"),r.setHeader("Cross-Origin-Opener-Policy","same-origin"),r.setHeader("Cross-Origin-Resource-Policy","same-origin"),r.setHeader("Origin-Agent-Cluster","?1"),r.removeHeader("X-Powered-By")}var pk,fk,db,Ta,mk,_V,ub,uk,wV,dk,eu,hk=R(()=>{"use strict";pk=ze(zl(),1),fk=ze(require("http"),1),db=ze(require("fs"),1),Ta=ze(require("path"),1);IA();se();LA();UA();sk();Bs();Xl();ok();ak();lk();mk=Ta.default.resolve(__dirname,"../skills/mem-search"),_V=Ta.default.join(mk,"operations"),ub=Ta.default.join(mk,"SKILL.md"),uk=(()=>{try{let r=db.readFileSync(ub,"utf-8");return _.info("SYSTEM","Cached SKILL.md at boot",{path:ub,bytes:Buffer.byteLength(r,"utf-8")}),r}catch(r){return _.debug("SYSTEM","SKILL.md not present at boot, /api/instructions will 404 for topic queries",{path:ub,message:r instanceof Error?r.message:String(r)}),null}})(),wV=(()=>{let r=new Map;for(let e of By){let t=Ta.default.join(_V,`${e}.md`);try{r.set(e,db.readFileSync(t,"utf-8"))}catch(n){_.debug("SYSTEM","Operation instruction file not present at boot",{path:t,message:n instanceof Error?n.message:String(n)})}}return r.size>0&&_.info("SYSTEM","Cached operation instruction files at boot",{count:r.size,operations:Array.from(r.keys())}),r})(),dk="13.4.20";eu=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,pk.default)(),this.app.disable("x-powered-by"),this.setupSecurityHeaders(),this.setupCors(),this.setupPreBodyParserRoutes(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,t){return new Promise((n,i)=>{let s=fk.default.createServer(this.app);this.server=s;let o=c=>{s.off("listening",a),i(c)},a=()=>{s.off("error",o),_.info("SYSTEM","HTTP server started",{host:t,port:e,pid:process.pid}),n()};s.once("error",o),s.once("listening",a),s.listen(e,t)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,t)=>{this.server.close(n=>n?t(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,_.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(JA),this.app.use(FA)}setupMiddleware(){zy(Qy,{includeCors:!1}).forEach(t=>this.app.use(t))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,t,n)=>{IV(t),n()})}setupCors(){this.app.use(Ql())}setupPreBodyParserRoutes(){this.options.preBodyParserRoutes?.forEach(e=>e.setupRoutes(this.app))}setupCoreRoutes(){this.app.get("/api/health",async(e,t)=>{let n=this.options.getQueueHealth?await this.options.getQueueHealth():null,i=n?.engine==="bullmq"&&n.redis.status==="error";t.status(i?503:200).json({status:i?"degraded":"ok",...this.options.runtime?{runtime:this.options.runtime}:{},version:dk,workerPath:this.options.workerPath,uptime:cb(this.startTime),managed:process.env.CLAUDE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.options.getInitializationComplete(),mcpReady:this.options.getMcpReady(),ai:this.options.getAiStatus(),rateLimits:ck.getMostRecentByWindow(),...n?{queue:n}:{}})}),this.app.get("/api/readiness",(e,t)=>{this.options.getInitializationComplete()?t.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):t.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(e,t)=>{t.status(200).json({version:dk})}),this.app.get("/api/instructions",(e,t)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!wA.includes(n))return t.status(400).json({error:"Invalid topic"});if(i&&!By.includes(i))return t.status(400).json({error:"Invalid operation"});if(i){let o=wV.get(i);return o===void 0?(_.debug("HTTP","Instruction file not cached at boot",{operation:i}),t.status(404).json({error:"Instruction not found"})):t.json({content:[{type:"text",text:o}]})}if(uk===null)return _.debug("HTTP","SKILL.md not cached at boot",{topic:n}),t.status(404).json({error:"Instruction not found"});let s=this.extractInstructionSection(uk,n);t.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",wa,async(e,t)=>{process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(t.json({status:"restarting"}),_.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):ab(t,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",wa,async(e,t)=>{process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(t.json({status:"shutting_down"}),_.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown"})):ab(t,{status:"shutting_down"},()=>this.options.onShutdown())}),this.app.get("/api/admin/doctor",wa,(e,t)=>{let o=ik().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:pr(f.pid)?"alive":"dead",startedAt:f.startedAt})),a=o.filter(f=>f.status==="dead").map(f=>f.pid),c=!Object.keys(process.env).some(f=>Zy.has(f)||Xy.some(m=>f.startsWith(m))),l=cb(this.startTime),u=Math.floor(l/3600),d=Math.floor(l%3600/60),p=u>0?`${u}h ${d}m`:`${d}m`;t.json({supervisor:{running:!0,pid:process.pid,uptime:p},processes:o,health:{deadProcessPids:a,envClean:c}})})}extractInstructionSection(e,t){let n={workflow:this.extractBetween(e,"## The Workflow","## Search Parameters"),search_params:this.extractBetween(e,"## Search Parameters","## Examples"),examples:this.extractBetween(e,"## Examples","## Why This Workflow"),all:e};return n[t]||n.all}extractBetween(e,t,n){let i=e.indexOf(t),s=e.indexOf(n);return i===-1?e:s===-1?e.substring(i):e.substring(i,s).trim()}}});var Nt,TV,AV,pb,yk=R(()=>{"use strict";Nt=require("zod"),TV=Nt.z.enum(["hook","worker","provider","server","api"]),AV=Nt.z.object({id:Nt.z.string().min(1),projectId:Nt.z.string().min(1),serverSessionId:Nt.z.string().min(1).nullable().default(null),sourceType:TV,eventType:Nt.z.string().min(1),platformSource:Nt.z.string().min(1).nullable().default(null),sourceEventId:Nt.z.string().min(1).nullable().default(null),payload:Nt.z.unknown().default({}),contentSessionId:Nt.z.string().min(1).nullable().default(null),memorySessionId:Nt.z.string().min(1).nullable().default(null),occurredAtEpoch:Nt.z.number().int().nonnegative(),createdAtEpoch:Nt.z.number().int().nonnegative()}),pb=AV.omit({id:!0,createdAtEpoch:!0}).partial({serverSessionId:!0,platformSource:!0,sourceEventId:!0,payload:!0,contentSessionId:!0,memorySessionId:!0})});function Ue(){return(0,tu.randomUUID)()}function Qe(r){return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}function bk(r){return Array.isArray(r)?r:[]}function Ee(r){return typeof r=="number"?r:new Date(r).getTime()}function fr(r){return r==null?null:r instanceof Date?r:new Date(r)}async function Q(r,e,t=[]){return(await r.query(e,t)).rows[0]??null}async function Or(r,e,t){if(!await Q(r,"SELECT id FROM projects WHERE id = $1 AND team_id = $2",[e,t]))throw new Error("project_id must belong to team_id")}async function gn(r,e,t,n){if(!await Q(r,"SELECT id FROM server_sessions WHERE id = $1 AND project_id = $2 AND team_id = $3",[e,t,n]))throw new Error("server_session_id must belong to project_id and team_id")}function Aa(r){return JSON.stringify(fb(r))}function Rr(r){return(0,tu.createHash)("sha256").update(Aa(r)).digest("hex")}function fb(r){if(Array.isArray(r))return r.map(fb);if(r&&typeof r=="object"){let e=r;return Object.keys(e).sort().reduce((t,n)=>(t[n]=fb(e[n]),t),{})}return r}var tu,Vr=R(()=>{"use strict";tu=require("crypto")});function gk(r){return r.sourceEventId?`agent_event:v1:${Rr([r.teamId,r.projectId,r.sourceAdapter,r.sourceEventId])}`:`agent_event:v1:${Rr([r.teamId,r.projectId,r.sourceAdapter,r.serverSessionId??null,r.eventType,new Date(r.occurredAt).toISOString(),Aa(r.payload??{})])}`}function mb(r){return{id:r.id,projectId:r.project_id,teamId:r.team_id,serverSessionId:r.server_session_id,sourceAdapter:r.source_adapter,sourceEventId:r.source_event_id,idempotencyKey:r.idempotency_key,eventType:r.event_type,platformSource:r.platform_source,payload:r.payload,metadata:Qe(r.metadata),occurredAtEpoch:Ee(r.occurred_at),receivedAtEpoch:Ee(r.received_at),createdAtEpoch:Ee(r.created_at)}}var mr,Hs=R(()=>{"use strict";Vr();mr=class{constructor(e){this.client=e}client;async create(e){await Or(this.client,e.projectId,e.teamId),e.serverSessionId&&await gn(this.client,e.serverSessionId,e.projectId,e.teamId);let t=gk(e),n=await Q(this.client,`
|
|
63
|
+
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),u=l?`${l[1].split("/").pop()}:${l[2]}`:"unknown",d={...n,location:u};return this.warn(e,`[HAPPY-PATH] ${t}`,d,i),s}},_=new Wy});var KA=h((ife,CA)=>{"use strict";var RA=Object.getOwnPropertySymbols,nV=Object.prototype.hasOwnProperty,iV=Object.prototype.propertyIsEnumerable;function sV(r){if(r==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(r)}function oV(){try{if(!Object.assign)return!1;var r=new String("abc");if(r[5]="de",Object.getOwnPropertyNames(r)[0]==="5")return!1;for(var e={},t=0;t<10;t++)e["_"+String.fromCharCode(t)]=t;var n=Object.getOwnPropertyNames(e).map(function(s){return e[s]});if(n.join("")!=="0123456789")return!1;var i={};return"abcdefghijklmnopqrst".split("").forEach(function(s){i[s]=s}),Object.keys(Object.assign({},i)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}CA.exports=oV()?Object.assign:function(r,e){for(var t,n=sV(r),i,s=1;s<arguments.length;s++){t=Object(arguments[s]);for(var o in t)nV.call(t,o)&&(n[o]=t[o]);if(RA){i=RA(t);for(var a=0;a<i.length;a++)iV.call(t,i[a])&&(n[i[a]]=t[i[a]])}}return n}});var DA=h((sfe,jA)=>{(function(){"use strict";var r=KA(),e=Fy(),t={origin:"*",methods:"GET,HEAD,PUT,PATCH,POST,DELETE",preflightContinue:!1,optionsSuccessStatus:204};function n(m){return typeof m=="string"||m instanceof String}function i(m,y){if(Array.isArray(y)){for(var b=0;b<y.length;++b)if(i(m,y[b]))return!0;return!1}else return n(y)?m===y:y instanceof RegExp?y.test(m):!!y}function s(m,y){var b=y.headers.origin,g=[],E;return!m.origin||m.origin==="*"?g.push([{key:"Access-Control-Allow-Origin",value:"*"}]):n(m.origin)?(g.push([{key:"Access-Control-Allow-Origin",value:m.origin}]),g.push([{key:"Vary",value:"Origin"}])):(E=i(b,m.origin),g.push([{key:"Access-Control-Allow-Origin",value:E?b:!1}]),g.push([{key:"Vary",value:"Origin"}])),g}function o(m){var y=m.methods;return y.join&&(y=m.methods.join(",")),{key:"Access-Control-Allow-Methods",value:y}}function a(m){return m.credentials===!0?{key:"Access-Control-Allow-Credentials",value:"true"}:null}function c(m,y){var b=m.allowedHeaders||m.headers,g=[];return b?b.join&&(b=b.join(",")):(b=y.headers["access-control-request-headers"],g.push([{key:"Vary",value:"Access-Control-Request-Headers"}])),b&&b.length&&g.push([{key:"Access-Control-Allow-Headers",value:b}]),g}function l(m){var y=m.exposedHeaders;if(y)y.join&&(y=y.join(","));else return null;return y&&y.length?{key:"Access-Control-Expose-Headers",value:y}:null}function u(m){var y=(typeof m.maxAge=="number"||m.maxAge)&&m.maxAge.toString();return y&&y.length?{key:"Access-Control-Max-Age",value:y}:null}function d(m,y){for(var b=0,g=m.length;b<g;b++){var E=m[b];E&&(Array.isArray(E)?d(E,y):E.key==="Vary"&&E.value?e(y,E.value):E.value&&y.setHeader(E.key,E.value))}}function p(m,y,b,g){var E=[],I=y.method&&y.method.toUpperCase&&y.method.toUpperCase();I==="OPTIONS"?(E.push(s(m,y)),E.push(a(m)),E.push(o(m)),E.push(c(m,y)),E.push(u(m)),E.push(l(m)),d(E,b),m.preflightContinue?g():(b.statusCode=m.optionsSuccessStatus,b.setHeader("Content-Length","0"),b.end())):(E.push(s(m,y)),E.push(a(m)),E.push(l(m)),d(E,b),g())}function f(m){var y=null;return typeof m=="function"?y=m:y=function(b,g){g(null,m)},function(g,E,I){y(g,function(T,L){if(T)I(T);else{var U=r({},t,L),ie=null;U.origin&&typeof U.origin=="function"?ie=U.origin:U.origin&&(ie=function(je,ce){ce(null,U.origin)}),ie?ie(g.headers.origin,function(je,ce){je||!ce?I(je):(U.origin=ce,p(U,g,E,I))}):I()}})}}jA.exports=f})()});function zy(r,e={}){let t=[];e.includeCors!==!1&&t.push(Ql()),t.push(Yy.default.json({limit:"5mb"})),t.push((s,o,a)=>{let l=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(y=>s.path.endsWith(y)),u=s.path==="/api/logs";if(s.path.startsWith("/health")||s.path==="/"||l||u)return a();let d=Date.now(),p=`${s.method}-${Date.now()}`,f=r(s.method,s.path,s.body);_.debug("HTTP",`\u2192 ${s.method} ${s.path}`,{requestId:p},f);let m=o.send.bind(o);o.send=function(y){let b=Date.now()-d;return _.debug("HTTP",`\u2190 ${o.statusCode} ${s.path}`,{requestId:p,duration:`${b}ms`}),m(y)},a()});let n=Fi(),i=PA.default.join(n,"plugin","ui");return t.push(Yy.default.static(i)),t}function aV(r){let e=(process.env.CLAUDE_MEM_CORS_ALLOW_ORIGINS||"").split(",").map(i=>i.trim()).filter(Boolean);if(e.includes("*")||e.includes(r))return!0;let t;try{t=new URL(r).hostname}catch{return!1}if(t==="localhost"||t==="127.0.0.1"||t==="::1"||!t.includes(".")||t.endsWith(".local")||t.endsWith(".internal")||t.endsWith(".lan")||t.endsWith(".ts.net"))return!0;let n=t.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);if(n){let i=Number(n[1]),s=Number(n[2]);if(i===10||i===172&&s>=16&&s<=31||i===192&&s===168||i===100&&s>=64&&s<=127)return!0}return!1}function Ql(){return(0,MA.default)({origin:(r,e)=>{!r||aV(r)?e(null,!0):e(new Error("CORS not allowed"))},methods:["GET","HEAD","POST","PUT","PATCH","DELETE"],allowedHeaders:["Content-Type","Authorization","X-Requested-With"],credentials:!1})}function wa(r,e,t){let n=r.ip||r.connection.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){_.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:r.path,clientIp:n,method:r.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}t()}function Qy(r,e,t){if(!t||Object.keys(t).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=t.tool_name||"?",i=t.tool_input;return`tool=${_.formatTool(n,i)}`}return e.includes("/summarize")?"requesting summary":""}var Yy,MA,PA,NA=R(()=>{"use strict";Yy=ze(zl(),1),MA=ze(DA(),1),PA=ze(require("path"),1);kt();se()});var LA=R(()=>{"use strict";NA()});function qA(r,e,t,n){let i={error:r,message:e};return t&&(i.code=t),n&&(i.details=n),i}function JA(r,e){e.status(404).json(qA("NotFound",`Cannot ${r.method} ${r.path}`))}var Gs,FA,UA=R(()=>{"use strict";se();Gs=class extends Error{constructor(t,n=500,i,s){super(t);this.statusCode=n;this.code=i;this.details=s;this.name="AppError"}statusCode;code;details};FA=(r,e,t,n)=>{let i=r instanceof Gs?r.statusCode:500;_.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:r.message,code:r instanceof Gs?r.code:void 0},r);let s=qA(r.name||"Error",r.message,r instanceof Gs?r.code:void 0,r instanceof Gs?r.details:void 0);t.status(i).json(s)}});var GA=R(()=>{"use strict"});function Ia(r=process.env){let e={};for(let[t,n]of Object.entries(r))if(n!==void 0){if(lV.has(t)){e[t]=n;continue}Zy.has(t)||cV.has(t)||Xy.some(i=>t.startsWith(i))||(e[t]=n)}return e}var Xy,Zy,cV,lV,Xl=R(()=>{"use strict";Xy=["CLAUDECODE_","CLAUDE_CODE_"],Zy=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),cV=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy"]),lV=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS"])});function pr(r){if(!Number.isInteger(r)||r<0||r===0)return!1;try{return process.kill(r,0),!0}catch(e){if(e instanceof Error){let t=e.code;return t==="EPERM"?!0:(_.debug("SYSTEM","PID check failed",{pid:r,code:t}),!1)}return _.warn("SYSTEM","PID check threw non-Error",{pid:r,error:String(e)}),!1}}function mV(r){let e=BA.get(r);if(e&&Date.now()-e.capturedAtMs<fV)return e.token;let t=null;try{let n=(0,ib.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${r}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Ia(process.env),LC_ALL:"C",LANG:"C"}});if(n.status===0){let i=n.stdout.trim();t=i.length>0?i:null}}catch(n){_.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:r,error:n instanceof Error?n.message:String(n)}),t=null}return BA.set(r,{token:t,capturedAtMs:Date.now()}),t}function sb(r){if(!Number.isInteger(r)||r<=0)return null;if(process.platform==="linux")try{let e=(0,Hr.readFileSync)(`/proc/${r}/stat`,"utf-8"),t=e.lastIndexOf(") ");if(t<0)return null;let i=e.slice(t+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(e){return _.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return mV(r);try{let e=(0,ib.spawnSync)("ps",["-p",String(r),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Ia(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let t=e.stdout.trim();return t.length>0?t:null}catch(e){return _.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}}function Hn(r){if(!r||!pr(r.pid))return!1;if(!r.startToken)return!0;let e=sb(r.pid);if(e===null)return!0;let t=e===r.startToken;return t||_.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:r.pid,stored:r.startToken,current:e}),t}function Zl(){return eb||(eb=new nb),eb}function tb(){let r=hV.shift();r&&r()}var ib,Hr,rb,uV,dV,pV,fV,BA,nb,eb,hV,Bs=R(()=>{"use strict";ib=require("child_process");GA();Hr=require("fs"),rb=ze(require("path"),1);se();Xl();kt();uV=5e3,dV=1e3,pV=Pe.supervisorRegistry();fV=5e3,BA=new Map;nb=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=pV){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,Hr.mkdirSync)(rb.default.dirname(this.registryPath),{recursive:!0}),!(0,Hr.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Hr.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[i,s]of Object.entries(n))this.entries.set(i,s)}catch(t){t instanceof Error?_.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},t):_.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(t)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&_.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,t,n){this.initialize(),this.entries.set(e,t),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let t=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),t?.type==="sdk"&&tb()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,t])=>({id:e,...t})).sort((e,t)=>{let n=Date.parse(e.startedAt),i=Date.parse(t.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(i)?0:i)})}getBySession(e){let t=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===t)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}getByPid(e){return this.getAll().filter(t=>t.pid===e)}pruneDeadEntries(){this.initialize();let e=0,t=0;for(let[n,i]of this.entries)pr(i.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,i.type==="sdk"&&(t+=1));e>0&&this.persist();for(let n=0;n<t;n+=1)tb();return e}async reapSession(e){this.initialize();let t=this.getBySession(e);if(t.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;_.info("SYSTEM",`Reaping ${t.length} process(es) for session ${e}`,{sessionId:n,pids:t.map(a=>a.pid)});let i=t.filter(a=>pr(a.pid));for(let a of i)try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):_.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}let s=Date.now()+uV;for(;Date.now()<s&&i.filter(c=>pr(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100));let o=i.filter(a=>pr(a.pid));for(let a of o){_.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(c){c instanceof Error?c.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):_.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}}if(o.length>0){let a=Date.now()+dV;for(;Date.now()<a&&o.filter(l=>pr(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let a of t)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of t)a.type==="sdk"&&tb();return _.info("SYSTEM",`Reaped ${t.length} process(es) for session ${e}`,{sessionId:n,reaped:t.length}),t.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,Hr.mkdirSync)(rb.default.dirname(this.registryPath),{recursive:!0}),(0,Hr.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},eb=null;hV=[]});var $A,HA=R(()=>{"use strict";$A={DEFAULT:3e5,HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,WORKER_STARTUP_WAIT:1e3,PRE_RESTART_SETTLE_DELAY:2e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5}});async function XA(r){let e=r.currentPid??process.pid,t=r.pidFilePath??bV,n=r.registry.getAll(),i=[...n].filter(o=>o.pid!==e).sort((o,a)=>Date.parse(a.startedAt)-Date.parse(o.startedAt));for(let o of i){if(!pr(o.pid)){r.registry.unregister(o.id);continue}try{await WA(o,"SIGTERM")}catch(a){a instanceof Error?_.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:o.pid,pgid:o.pgid,type:o.type},a):_.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:o.pid,pgid:o.pgid,type:o.type,error:String(a)})}}await VA(i,5e3);let s=i.filter(o=>pr(o.pid));for(let o of s)try{await WA(o,"SIGKILL")}catch(a){a instanceof Error?_.debug("SYSTEM","Failed to force kill child process",{pid:o.pid,pgid:o.pgid,type:o.type},a):_.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:o.pid,pgid:o.pgid,type:o.type,error:String(a)})}await VA(s,1e3);for(let o of i)r.registry.unregister(o.id);for(let o of n.filter(a=>a.pid===e))r.registry.unregister(o.id);try{(0,zA.rmSync)(t,{force:!0})}catch(o){o instanceof Error?_.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:t},o):_.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:t,error:String(o)})}r.registry.pruneDeadEntries()}async function VA(r,e){let t=Date.now()+e;for(;Date.now()<t;){if(r.filter(i=>pr(i.pid)).length===0)return;await new Promise(i=>setTimeout(i,100))}}async function WA(r,e){let{pid:t,pgid:n}=r;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}try{process.kill(t,e)}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}return}if(e==="SIGTERM"){try{process.kill(t,e)}catch(o){if(o instanceof Error&&o.code==="ESRCH")return;throw o}return}let i=await gV();if(i){await new Promise((o,a)=>{i(t,e,c=>{if(!c){o();return}if(c.code==="ESRCH"){o();return}a(c)})});return}let s=["/PID",String(t),"/T"];e==="SIGKILL"&&s.push("/F"),await yV("taskkill",s,{timeout:$A.POWERSHELL_COMMAND,windowsHide:!0})}async function gV(){let r="tree-kill";try{let e=await import(r);return e.default??e}catch(e){return _.debug("SYSTEM","tree-kill module not available, using fallback",{},e instanceof Error?e:void 0),null}}var YA,zA,QA,yV,bV,ZA=R(()=>{"use strict";YA=require("child_process"),zA=require("fs"),QA=require("util");se();HA();Bs();kt();yV=(0,QA.promisify)(YA.execFile),bV=Pe.workerPid()});function vV(){let e=Zl().pruneDeadEntries();e>0&&_.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function tk(){$s===null&&($s=setInterval(vV,ek),$s.unref(),_.debug("SYSTEM","Health checker started",{intervalMs:ek}))}function rk(){$s!==null&&(clearInterval($s),$s=null,_.debug("SYSTEM","Health checker stopped"))}var ek,$s,nk=R(()=>{"use strict";se();Bs();ek=3e4,$s=null});function ik(){return SV}function xV(r={}){let e=r.pidFilePath??EV;if(!(0,Ji.existsSync)(e))return"missing";let t=null;try{t=JSON.parse((0,Ji.readFileSync)(e,"utf-8"))}catch(i){return i instanceof Error?_.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},i):_.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(i)}),(0,Ji.rmSync)(e,{force:!0}),"invalid"}return Hn(t)&&t?((r.logAlive??!0)&&_.info("SYSTEM","Worker already running (PID alive)",{existingPid:t.pid,existingPort:t.port,startedAt:t.startedAt}),"alive"):(_.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:t?.pid,port:t?.port,startedAt:t?.startedAt}),(0,Ji.rmSync)(e,{force:!0}),"stale")}var Ji,EV,ob,SV,sk=R(()=>{"use strict";Ji=require("fs");se();Bs();ZA();nk();kt();EV=Pe.workerPid(),ob=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),xV({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,tk()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let t=async n=>{if(this.shutdownInitiated){_.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,_.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){i instanceof Error?_.error("SYSTEM","Error during shutdown",{},i):_.error("SYSTEM","Error during shutdown (non-Error)",{error:String(i)});try{await this.stop()}catch(s){s instanceof Error?_.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):_.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(s)})}}process.exit(0)};process.on("SIGTERM",()=>{t("SIGTERM")}),process.on("SIGINT",()=>{t("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{_.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{t("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}rk(),this.stopPromise=XA({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,t,n){this.registry.register(e,t,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},SV=new ob(Zl())});function ab(r,e,t){r.on("finish",async()=>{try{await t()}finally{process.exit(0)}}),r.json(e)}var ok=R(()=>{"use strict"});function cb(r,e=Date.now){return Math.max(0,Math.floor((e()-r)/1e3))}var ak=R(()=>{"use strict"});var lb,ck,Gfe,lk=R(()=>{"use strict";lb=class{entries=new Map;set(e){if(!e||typeof e!="object")return;let t=e.rateLimitType??"default";this.entries.set(t,{...e,observedAt:Date.now()})}get(e){return e?this.entries.get(e):this.entries.get("default")}getAll(){return Array.from(this.entries.values()).sort((e,t)=>t.observedAt-e.observedAt)}getMostRecentByWindow(){return{five_hour:this.entries.get("five_hour"),seven_day:this.entries.get("seven_day"),seven_day_opus:this.entries.get("seven_day_opus"),seven_day_sonnet:this.entries.get("seven_day_sonnet"),overage:this.entries.get("overage")}}get size(){return this.entries.size}clear(){this.entries.clear()}},ck=new lb,Gfe=900*1e3});function IV(r){r.setHeader("X-Content-Type-Options","nosniff"),r.setHeader("X-Frame-Options","DENY"),r.setHeader("X-DNS-Prefetch-Control","off"),r.setHeader("Referrer-Policy","no-referrer"),r.setHeader("Cross-Origin-Opener-Policy","same-origin"),r.setHeader("Cross-Origin-Resource-Policy","same-origin"),r.setHeader("Origin-Agent-Cluster","?1"),r.removeHeader("X-Powered-By")}var pk,fk,db,Ta,mk,_V,ub,uk,wV,dk,eu,hk=R(()=>{"use strict";pk=ze(zl(),1),fk=ze(require("http"),1),db=ze(require("fs"),1),Ta=ze(require("path"),1);IA();se();LA();UA();sk();Bs();Xl();ok();ak();lk();mk=Ta.default.resolve(__dirname,"../skills/mem-search"),_V=Ta.default.join(mk,"operations"),ub=Ta.default.join(mk,"SKILL.md"),uk=(()=>{try{let r=db.readFileSync(ub,"utf-8");return _.info("SYSTEM","Cached SKILL.md at boot",{path:ub,bytes:Buffer.byteLength(r,"utf-8")}),r}catch(r){return _.debug("SYSTEM","SKILL.md not present at boot, /api/instructions will 404 for topic queries",{path:ub,message:r instanceof Error?r.message:String(r)}),null}})(),wV=(()=>{let r=new Map;for(let e of By){let t=Ta.default.join(_V,`${e}.md`);try{r.set(e,db.readFileSync(t,"utf-8"))}catch(n){_.debug("SYSTEM","Operation instruction file not present at boot",{path:t,message:n instanceof Error?n.message:String(n)})}}return r.size>0&&_.info("SYSTEM","Cached operation instruction files at boot",{count:r.size,operations:Array.from(r.keys())}),r})(),dk="13.4.21";eu=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,pk.default)(),this.app.disable("x-powered-by"),this.setupSecurityHeaders(),this.setupCors(),this.setupPreBodyParserRoutes(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,t){return new Promise((n,i)=>{let s=fk.default.createServer(this.app);this.server=s;let o=c=>{s.off("listening",a),i(c)},a=()=>{s.off("error",o),_.info("SYSTEM","HTTP server started",{host:t,port:e,pid:process.pid}),n()};s.once("error",o),s.once("listening",a),s.listen(e,t)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,t)=>{this.server.close(n=>n?t(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,_.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(JA),this.app.use(FA)}setupMiddleware(){zy(Qy,{includeCors:!1}).forEach(t=>this.app.use(t))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,t,n)=>{IV(t),n()})}setupCors(){this.app.use(Ql())}setupPreBodyParserRoutes(){this.options.preBodyParserRoutes?.forEach(e=>e.setupRoutes(this.app))}setupCoreRoutes(){this.app.get("/api/health",async(e,t)=>{let n=this.options.getQueueHealth?await this.options.getQueueHealth():null,i=n?.engine==="bullmq"&&n.redis.status==="error";t.status(i?503:200).json({status:i?"degraded":"ok",...this.options.runtime?{runtime:this.options.runtime}:{},version:dk,workerPath:this.options.workerPath,uptime:cb(this.startTime),managed:process.env.CLAUDE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.options.getInitializationComplete(),mcpReady:this.options.getMcpReady(),ai:this.options.getAiStatus(),rateLimits:ck.getMostRecentByWindow(),...n?{queue:n}:{}})}),this.app.get("/api/readiness",(e,t)=>{this.options.getInitializationComplete()?t.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):t.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(e,t)=>{t.status(200).json({version:dk})}),this.app.get("/api/instructions",(e,t)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!wA.includes(n))return t.status(400).json({error:"Invalid topic"});if(i&&!By.includes(i))return t.status(400).json({error:"Invalid operation"});if(i){let o=wV.get(i);return o===void 0?(_.debug("HTTP","Instruction file not cached at boot",{operation:i}),t.status(404).json({error:"Instruction not found"})):t.json({content:[{type:"text",text:o}]})}if(uk===null)return _.debug("HTTP","SKILL.md not cached at boot",{topic:n}),t.status(404).json({error:"Instruction not found"});let s=this.extractInstructionSection(uk,n);t.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",wa,async(e,t)=>{process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(t.json({status:"restarting"}),_.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):ab(t,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",wa,async(e,t)=>{process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(t.json({status:"shutting_down"}),_.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown"})):ab(t,{status:"shutting_down"},()=>this.options.onShutdown())}),this.app.get("/api/admin/doctor",wa,(e,t)=>{let o=ik().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:pr(f.pid)?"alive":"dead",startedAt:f.startedAt})),a=o.filter(f=>f.status==="dead").map(f=>f.pid),c=!Object.keys(process.env).some(f=>Zy.has(f)||Xy.some(m=>f.startsWith(m))),l=cb(this.startTime),u=Math.floor(l/3600),d=Math.floor(l%3600/60),p=u>0?`${u}h ${d}m`:`${d}m`;t.json({supervisor:{running:!0,pid:process.pid,uptime:p},processes:o,health:{deadProcessPids:a,envClean:c}})})}extractInstructionSection(e,t){let n={workflow:this.extractBetween(e,"## The Workflow","## Search Parameters"),search_params:this.extractBetween(e,"## Search Parameters","## Examples"),examples:this.extractBetween(e,"## Examples","## Why This Workflow"),all:e};return n[t]||n.all}extractBetween(e,t,n){let i=e.indexOf(t),s=e.indexOf(n);return i===-1?e:s===-1?e.substring(i):e.substring(i,s).trim()}}});var Nt,TV,AV,pb,yk=R(()=>{"use strict";Nt=require("zod"),TV=Nt.z.enum(["hook","worker","provider","server","api"]),AV=Nt.z.object({id:Nt.z.string().min(1),projectId:Nt.z.string().min(1),serverSessionId:Nt.z.string().min(1).nullable().default(null),sourceType:TV,eventType:Nt.z.string().min(1),platformSource:Nt.z.string().min(1).nullable().default(null),sourceEventId:Nt.z.string().min(1).nullable().default(null),payload:Nt.z.unknown().default({}),contentSessionId:Nt.z.string().min(1).nullable().default(null),memorySessionId:Nt.z.string().min(1).nullable().default(null),occurredAtEpoch:Nt.z.number().int().nonnegative(),createdAtEpoch:Nt.z.number().int().nonnegative()}),pb=AV.omit({id:!0,createdAtEpoch:!0}).partial({serverSessionId:!0,platformSource:!0,sourceEventId:!0,payload:!0,contentSessionId:!0,memorySessionId:!0})});function Ue(){return(0,tu.randomUUID)()}function Qe(r){return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}function bk(r){return Array.isArray(r)?r:[]}function Ee(r){return typeof r=="number"?r:new Date(r).getTime()}function fr(r){return r==null?null:r instanceof Date?r:new Date(r)}async function Q(r,e,t=[]){return(await r.query(e,t)).rows[0]??null}async function Or(r,e,t){if(!await Q(r,"SELECT id FROM projects WHERE id = $1 AND team_id = $2",[e,t]))throw new Error("project_id must belong to team_id")}async function gn(r,e,t,n){if(!await Q(r,"SELECT id FROM server_sessions WHERE id = $1 AND project_id = $2 AND team_id = $3",[e,t,n]))throw new Error("server_session_id must belong to project_id and team_id")}function Aa(r){return JSON.stringify(fb(r))}function Rr(r){return(0,tu.createHash)("sha256").update(Aa(r)).digest("hex")}function fb(r){if(Array.isArray(r))return r.map(fb);if(r&&typeof r=="object"){let e=r;return Object.keys(e).sort().reduce((t,n)=>(t[n]=fb(e[n]),t),{})}return r}var tu,Vr=R(()=>{"use strict";tu=require("crypto")});function gk(r){return r.sourceEventId?`agent_event:v1:${Rr([r.teamId,r.projectId,r.sourceAdapter,r.sourceEventId])}`:`agent_event:v1:${Rr([r.teamId,r.projectId,r.sourceAdapter,r.serverSessionId??null,r.eventType,new Date(r.occurredAt).toISOString(),Aa(r.payload??{})])}`}function mb(r){return{id:r.id,projectId:r.project_id,teamId:r.team_id,serverSessionId:r.server_session_id,sourceAdapter:r.source_adapter,sourceEventId:r.source_event_id,idempotencyKey:r.idempotency_key,eventType:r.event_type,platformSource:r.platform_source,payload:r.payload,metadata:Qe(r.metadata),occurredAtEpoch:Ee(r.occurred_at),receivedAtEpoch:Ee(r.received_at),createdAtEpoch:Ee(r.created_at)}}var mr,Hs=R(()=>{"use strict";Vr();mr=class{constructor(e){this.client=e}client;async create(e){await Or(this.client,e.projectId,e.teamId),e.serverSessionId&&await gn(this.client,e.serverSessionId,e.projectId,e.teamId);let t=gk(e),n=await Q(this.client,`
|
|
64
64
|
INSERT INTO agent_events (
|
|
65
65
|
id, project_id, team_id, server_session_id, source_adapter,
|
|
66
66
|
source_event_id, idempotency_key, event_type, platform_source, payload, metadata, occurred_at
|