claude-mem 13.5.0 → 13.5.2

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.
@@ -59,7 +59,7 @@ ${s.stack}`:` ${s.message}`;else if(this.getLevel()===0&&typeof s=="object")try{
59
59
  `,"utf8")}catch(f){Ey(`[LOGGER] Failed to write to log file: ${f instanceof Error?f.message:String(f)}
60
60
  `)}else Ey(p+`
61
61
  `)}debug(e,t,n,i){this.log(0,e,t,n,i)}info(e,t,n,i){this.log(1,e,t,n,i)}warn(e,t,n,i){this.log(2,e,t,n,i)}error(e,t,n,i){this.log(3,e,t,n,i)}dataIn(e,t,n,i){this.info(e,`\u2192 ${t}`,n,i)}dataOut(e,t,n,i){this.info(e,`\u2190 ${t}`,n,i)}success(e,t,n,i){this.info(e,`\u2713 ${t}`,n,i)}failure(e,t,n,i){this.error(e,`\u2717 ${t}`,n,i)}timing(e,t,n,i){this.info(e,`\u23F1 ${t}`,i,{duration:`${n}ms`})}happyPathError(e,t,n,i,s=""){let l=((new Error().stack||"").split(`
62
- `)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),u=l?`${l[1].split("/").pop()}:${l[2]}`:"unknown",d={...n,location:u};return this.warn(e,`[HAPPY-PATH] ${t}`,d,i),s}},_=new Sy});var nT=h((nde,rT)=>{"use strict";var tT=Object.getOwnPropertySymbols,m$=Object.prototype.hasOwnProperty,h$=Object.prototype.propertyIsEnumerable;function y$(r){if(r==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(r)}function b$(){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}}rT.exports=b$()?Object.assign:function(r,e){for(var t,n=y$(r),i,s=1;s<arguments.length;s++){t=Object(arguments[s]);for(var a in t)m$.call(t,a)&&(n[a]=t[a]);if(tT){i=tT(t);for(var o=0;o<i.length;o++)h$.call(t,i[o])&&(n[i[o]]=t[i[o]])}}return n}});var sT=h((ide,iT)=>{(function(){"use strict";var r=nT(),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 a(m){var y=m.methods;return y.join&&(y=m.methods.join(",")),{key:"Access-Control-Allow-Methods",value:y}}function o(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(o(m)),E.push(a(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(o(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(k,L){if(k)I(k);else{var J=r({},t,L),re=null;J.origin&&typeof J.origin=="function"?re=J.origin:J.origin&&(re=function(je,se){se(null,J.origin)}),re?re(g.headers.origin,function(je,se){je||!se?I(je):(J.origin=se,p(J,g,E,I))}):I()}})}}iT.exports=f})()});function Iy(r,e={}){let t=[];e.includeCors!==!1&&t.push(ql()),t.push(wy.default.json({limit:"5mb"})),t.push((s,a,o)=>{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 o();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=a.send.bind(a);a.send=function(y){let b=Date.now()-d;return _.debug("HTTP",`\u2190 ${a.statusCode} ${s.path}`,{requestId:p,duration:`${b}ms`}),m(y)},o()});let n=Ci(),i=oT.default.join(n,"plugin","ui");return t.push(wy.default.static(i)),t}function ql(){return(0,aT.default)({origin:(r,e)=>{!r||r.startsWith("http://localhost:")||r.startsWith("http://127.0.0.1:")?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 fo(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 _y(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 wy,aT,oT,cT=M(()=>{"use strict";wy=ct(Ll(),1),aT=ct(sT(),1),oT=ct(require("path"),1);Ur();ge()});var lT=M(()=>{"use strict";cT()});function uT(r,e,t,n){let i={error:r,message:e};return t&&(i.code=t),n&&(i.details=n),i}function pT(r,e){e.status(404).json(uT("NotFound",`Cannot ${r.method} ${r.path}`))}var Ds,dT,fT=M(()=>{"use strict";ge();Ds=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};dT=(r,e,t,n)=>{let i=r instanceof Ds?r.statusCode:500;_.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:r.message,code:r instanceof Ds?r.code:void 0},r);let s=uT(r.name||"Error",r.message,r instanceof Ds?r.code:void 0,r instanceof Ds?r.details:void 0);t.status(i).json(s)}});var mT=M(()=>{"use strict"});function mo(r=process.env){let e={};for(let[t,n]of Object.entries(r))if(n!==void 0){if(v$.has(t)){e[t]=n;continue}Ty.has(t)||g$.has(t)||ky.some(i=>t.startsWith(i))||(e[t]=n)}return e}var ky,Ty,g$,v$,Fl=M(()=>{"use strict";ky=["CLAUDECODE_","CLAUDE_CODE_"],Ty=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),g$=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"]),v$=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 or(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 I$(r){let e=hT.get(r);if(e&&Date.now()-e.capturedAtMs<w$)return e.token;let t=null;try{let n=(0,Ry.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:{...mo(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 hT.set(r,{token:t,capturedAtMs:Date.now()}),t}function Cy(r){if(!Number.isInteger(r)||r<=0)return null;if(process.platform==="linux")try{let e=(0,Gr.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 I$(r);try{let e=(0,Ry.spawnSync)("ps",["-p",String(r),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...mo(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 Fn(r){if(!r||!or(r.pid))return!1;if(!r.startToken)return!0;let e=Cy(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 Jl(){return Ay||(Ay=new jy),Ay}function Ky(){let r=_$.shift();r&&r()}var Ry,Gr,Oy,E$,x$,S$,w$,hT,jy,Ay,_$,Ps=M(()=>{"use strict";Ry=require("child_process");mT();Gr=require("fs"),Oy=ct(require("path"),1);ge();Fl();Ur();E$=5e3,x$=1e3,S$=$e.supervisorRegistry();w$=5e3,hT=new Map;jy=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=S$){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,Gr.mkdirSync)(Oy.default.dirname(this.registryPath),{recursive:!0}),!(0,Gr.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Gr.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"&&Ky()}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)or(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)Ky();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(o=>o.pid)});let i=t.filter(o=>or(o.pid));for(let o of i)try{typeof o.pgid=="number"&&process.platform!=="win32"?process.kill(-o.pgid,"SIGTERM"):process.kill(o.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGTERM session process PID ${o.pid}`,{pid:o.pid,pgid:o.pgid},c):_.warn("SYSTEM",`Failed to SIGTERM session process PID ${o.pid} (non-Error)`,{pid:o.pid,pgid:o.pgid,error:String(c)})}let s=Date.now()+E$;for(;Date.now()<s&&i.filter(c=>or(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100));let a=i.filter(o=>or(o.pid));for(let o of a){_.warn("SYSTEM",`Session process PID ${o.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:o.pid,pgid:o.pgid,sessionId:n});try{typeof o.pgid=="number"&&process.platform!=="win32"?process.kill(-o.pgid,"SIGKILL"):process.kill(o.pid,"SIGKILL")}catch(c){c instanceof Error?c.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGKILL session process PID ${o.pid}`,{pid:o.pid,pgid:o.pgid},c):_.warn("SYSTEM",`Failed to SIGKILL session process PID ${o.pid} (non-Error)`,{pid:o.pid,pgid:o.pgid,error:String(c)})}}if(a.length>0){let o=Date.now()+x$;for(;Date.now()<o&&a.filter(l=>or(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let o of t)this.entries.delete(o.id),this.runtimeProcesses.delete(o.id);this.persist();for(let o of t)o.type==="sdk"&&Ky();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,Gr.mkdirSync)(Oy.default.dirname(this.registryPath),{recursive:!0}),(0,Gr.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},Ay=null;_$=[]});function yT(r){return process.platform==="win32"?Math.round(r*ho.WINDOWS_MULTIPLIER):r}var ho,Dy=M(()=>{"use strict";ho={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 ST(r){let e=r.currentPid??process.pid,t=r.pidFilePath??T$,n=r.registry.getAll(),i=[...n].filter(a=>a.pid!==e).sort((a,o)=>Date.parse(o.startedAt)-Date.parse(a.startedAt));for(let a of i){if(!or(a.pid)){r.registry.unregister(a.id);continue}try{await gT(a,"SIGTERM")}catch(o){o instanceof Error?_.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:a.pid,pgid:a.pgid,type:a.type},o):_.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:a.pid,pgid:a.pgid,type:a.type,error:String(o)})}}await bT(i,5e3);let s=i.filter(a=>or(a.pid));for(let a of s)try{await gT(a,"SIGKILL")}catch(o){o instanceof Error?_.debug("SYSTEM","Failed to force kill child process",{pid:a.pid,pgid:a.pgid,type:a.type},o):_.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:a.pid,pgid:a.pgid,type:a.type,error:String(o)})}await bT(s,1e3);for(let a of i)r.registry.unregister(a.id);for(let a of n.filter(o=>o.pid===e))r.registry.unregister(a.id);try{(0,ET.rmSync)(t,{force:!0})}catch(a){a instanceof Error?_.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:t},a):_.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:t,error:String(a)})}r.registry.pruneDeadEntries()}async function bT(r,e){let t=Date.now()+e;for(;Date.now()<t;){if(r.filter(i=>or(i.pid)).length===0)return;await new Promise(i=>setTimeout(i,100))}}async function gT(r,e){let{pid:t,pgid:n}=r;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(a){if((a instanceof Error?a.code:void 0)!=="ESRCH")throw a}try{process.kill(t,e)}catch(a){if((a instanceof Error?a.code:void 0)!=="ESRCH")throw a}return}if(e==="SIGTERM"){try{process.kill(t,e)}catch(a){if(a instanceof Error&&a.code==="ESRCH")return;throw a}return}let i=await A$();if(i){await new Promise((a,o)=>{i(t,e,c=>{if(!c){a();return}if(c.code==="ESRCH"){a();return}o(c)})});return}let s=["/PID",String(t),"/T"];e==="SIGKILL"&&s.push("/F"),await k$("taskkill",s,{timeout:ho.POWERSHELL_COMMAND,windowsHide:!0})}async function A$(){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 vT,ET,xT,k$,T$,wT=M(()=>{"use strict";vT=require("child_process"),ET=require("fs"),xT=require("util");ge();Dy();Ps();Ur();k$=(0,xT.promisify)(vT.execFile),T$=$e.workerPid()});function K$(){let e=Jl().pruneDeadEntries();e>0&&_.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function _T(){Ms===null&&(Ms=setInterval(K$,IT),Ms.unref(),_.debug("SYSTEM","Health checker started",{intervalMs:IT}))}function kT(){Ms!==null&&(clearInterval(Ms),Ms=null,_.debug("SYSTEM","Health checker stopped"))}var IT,Ms,TT=M(()=>{"use strict";ge();Ps();IT=3e4,Ms=null});function AT(){return j$}function R$(r={}){let e=r.pidFilePath??O$;if(!(0,Di.existsSync)(e))return"missing";let t=null;try{t=JSON.parse((0,Di.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,Di.rmSync)(e,{force:!0}),"invalid"}return Fn(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,Di.rmSync)(e,{force:!0}),"stale")}var Di,O$,Py,j$,KT=M(()=>{"use strict";Di=require("fs");ge();Ps();wT();TT();Ur();O$=$e.workerPid(),Py=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(),R$({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,_T()}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}kT(),this.stopPromise=ST({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}},j$=new Py(Jl())});function My(r,e,t){r.on("finish",async()=>{try{await t()}finally{process.exit(0)}}),r.json(e)}var OT=M(()=>{"use strict"});function Ly(r,e=Date.now){return Math.max(0,Math.floor((e()-r)/1e3))}var jT=M(()=>{"use strict"});var Ny,RT,Ude,CT=M(()=>{"use strict";Ny=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()}},RT=new Ny,Ude=900*1e3});function P$(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 MT,LT,Fy,yo,NT,C$,qy,DT,D$,PT,Ul,qT=M(()=>{"use strict";MT=ct(Ll(),1),LT=ct(require("http"),1),Fy=ct(require("fs"),1),yo=ct(require("path"),1);Wk();ge();lT();fT();KT();Ps();Fl();OT();jT();CT();NT=yo.default.resolve(__dirname,"../skills/mem-search"),C$=yo.default.join(NT,"operations"),qy=yo.default.join(NT,"SKILL.md"),DT=(()=>{try{let r=Fy.readFileSync(qy,"utf-8");return _.info("SYSTEM","Cached SKILL.md at boot",{path:qy,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:qy,message:r instanceof Error?r.message:String(r)}),null}})(),D$=(()=>{let r=new Map;for(let e of by){let t=yo.default.join(C$,`${e}.md`);try{r.set(e,Fy.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})(),PT="13.5.0";Ul=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,MT.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=LT.default.createServer(this.app);this.server=s;let a=c=>{s.off("listening",o),i(c)},o=()=>{s.off("error",a),_.info("SYSTEM","HTTP server started",{host:t,port:e,pid:process.pid}),n()};s.once("error",a),s.once("listening",o),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(pT),this.app.use(dT)}setupMiddleware(){Iy(_y,{includeCors:!1}).forEach(t=>this.app.use(t))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,t,n)=>{P$(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:PT,workerPath:this.options.workerPath,uptime:Ly(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:RT.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:PT})}),this.app.get("/api/instructions",(e,t)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!Yk.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 a=D$.get(i);return a===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:a}]})}if(DT===null)return _.debug("HTTP","SKILL.md not cached at boot",{topic:n}),t.status(404).json({error:"Instruction not found"});let s=this.extractInstructionSection(DT,n);t.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",fo,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"})):My(t,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",fo,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"})):My(t,{status:"shutting_down"},()=>this.options.onShutdown())}),this.app.get("/api/admin/doctor",fo,(e,t)=>{let a=AT().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:or(f.pid)?"alive":"dead",startedAt:f.startedAt})),o=a.filter(f=>f.status==="dead").map(f=>f.pid),c=!Object.keys(process.env).some(f=>Ty.has(f)||ky.some(m=>f.startsWith(m))),l=Ly(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:a,health:{deadProcessPids:o,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 Jt,M$,L$,Jy,FT=M(()=>{"use strict";Jt=require("zod"),M$=Jt.z.enum(["hook","worker","provider","server","api"]),L$=Jt.z.object({id:Jt.z.string().min(1),projectId:Jt.z.string().min(1),serverSessionId:Jt.z.string().min(1).nullable().default(null),sourceType:M$,eventType:Jt.z.string().min(1),platformSource:Jt.z.string().min(1).nullable().default(null),payload:Jt.z.unknown().default({}),contentSessionId:Jt.z.string().min(1).nullable().default(null),memorySessionId:Jt.z.string().min(1).nullable().default(null),occurredAtEpoch:Jt.z.number().int().nonnegative(),createdAtEpoch:Jt.z.number().int().nonnegative()}),Jy=L$.omit({id:!0,createdAtEpoch:!0}).partial({serverSessionId:!0,platformSource:!0,payload:!0,contentSessionId:!0,memorySessionId:!0})});function qe(){return(0,Gl.randomUUID)()}function ze(r){return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}function JT(r){return Array.isArray(r)?r:[]}function ve(r){return typeof r=="number"?r:new Date(r).getTime()}function cr(r){return r==null?null:r instanceof Date?r:new Date(r)}async function Y(r,e,t=[]){return(await r.query(e,t)).rows[0]??null}async function _r(r,e,t){if(!await Y(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 mn(r,e,t,n){if(!await Y(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 bo(r){return JSON.stringify(Uy(r))}function kr(r){return(0,Gl.createHash)("sha256").update(bo(r)).digest("hex")}function Uy(r){if(Array.isArray(r))return r.map(Uy);if(r&&typeof r=="object"){let e=r;return Object.keys(e).sort().reduce((t,n)=>(t[n]=Uy(e[n]),t),{})}return r}var Gl,Br=M(()=>{"use strict";Gl=require("crypto")});function UT(r){return r.sourceEventId?`agent_event:v1:${kr([r.teamId,r.projectId,r.sourceAdapter,r.sourceEventId])}`:`agent_event:v1:${kr([r.teamId,r.projectId,r.sourceAdapter,r.contentSessionId??r.serverSessionId??null,r.eventType,new Date(r.occurredAt).toISOString(),bo(r.payload??{})])}`}function Gy(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:ze(r.metadata),occurredAtEpoch:ve(r.occurred_at),receivedAtEpoch:ve(r.received_at),createdAtEpoch:ve(r.created_at)}}var lr,Ls=M(()=>{"use strict";Br();lr=class{constructor(e){this.client=e}client;async create(e){await _r(this.client,e.projectId,e.teamId),e.serverSessionId&&await mn(this.client,e.serverSessionId,e.projectId,e.teamId);let t=UT(e),n=await Y(this.client,`
62
+ `)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),u=l?`${l[1].split("/").pop()}:${l[2]}`:"unknown",d={...n,location:u};return this.warn(e,`[HAPPY-PATH] ${t}`,d,i),s}},_=new Sy});var nT=h((nde,rT)=>{"use strict";var tT=Object.getOwnPropertySymbols,m$=Object.prototype.hasOwnProperty,h$=Object.prototype.propertyIsEnumerable;function y$(r){if(r==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(r)}function b$(){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}}rT.exports=b$()?Object.assign:function(r,e){for(var t,n=y$(r),i,s=1;s<arguments.length;s++){t=Object(arguments[s]);for(var a in t)m$.call(t,a)&&(n[a]=t[a]);if(tT){i=tT(t);for(var o=0;o<i.length;o++)h$.call(t,i[o])&&(n[i[o]]=t[i[o]])}}return n}});var sT=h((ide,iT)=>{(function(){"use strict";var r=nT(),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 a(m){var y=m.methods;return y.join&&(y=m.methods.join(",")),{key:"Access-Control-Allow-Methods",value:y}}function o(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(o(m)),E.push(a(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(o(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(k,L){if(k)I(k);else{var J=r({},t,L),re=null;J.origin&&typeof J.origin=="function"?re=J.origin:J.origin&&(re=function(je,se){se(null,J.origin)}),re?re(g.headers.origin,function(je,se){je||!se?I(je):(J.origin=se,p(J,g,E,I))}):I()}})}}iT.exports=f})()});function Iy(r,e={}){let t=[];e.includeCors!==!1&&t.push(ql()),t.push(wy.default.json({limit:"5mb"})),t.push((s,a,o)=>{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 o();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=a.send.bind(a);a.send=function(y){let b=Date.now()-d;return _.debug("HTTP",`\u2190 ${a.statusCode} ${s.path}`,{requestId:p,duration:`${b}ms`}),m(y)},o()});let n=Ci(),i=oT.default.join(n,"plugin","ui");return t.push(wy.default.static(i)),t}function ql(){return(0,aT.default)({origin:(r,e)=>{!r||r.startsWith("http://localhost:")||r.startsWith("http://127.0.0.1:")?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 fo(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 _y(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 wy,aT,oT,cT=M(()=>{"use strict";wy=ct(Ll(),1),aT=ct(sT(),1),oT=ct(require("path"),1);Ur();ge()});var lT=M(()=>{"use strict";cT()});function uT(r,e,t,n){let i={error:r,message:e};return t&&(i.code=t),n&&(i.details=n),i}function pT(r,e){e.status(404).json(uT("NotFound",`Cannot ${r.method} ${r.path}`))}var Ds,dT,fT=M(()=>{"use strict";ge();Ds=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};dT=(r,e,t,n)=>{let i=r instanceof Ds?r.statusCode:500;_.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:r.message,code:r instanceof Ds?r.code:void 0},r);let s=uT(r.name||"Error",r.message,r instanceof Ds?r.code:void 0,r instanceof Ds?r.details:void 0);t.status(i).json(s)}});var mT=M(()=>{"use strict"});function mo(r=process.env){let e={};for(let[t,n]of Object.entries(r))if(n!==void 0){if(v$.has(t)){e[t]=n;continue}Ty.has(t)||g$.has(t)||ky.some(i=>t.startsWith(i))||(e[t]=n)}return e}var ky,Ty,g$,v$,Fl=M(()=>{"use strict";ky=["CLAUDECODE_","CLAUDE_CODE_"],Ty=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),g$=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"]),v$=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 or(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 I$(r){let e=hT.get(r);if(e&&Date.now()-e.capturedAtMs<w$)return e.token;let t=null;try{let n=(0,Ry.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:{...mo(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 hT.set(r,{token:t,capturedAtMs:Date.now()}),t}function Cy(r){if(!Number.isInteger(r)||r<=0)return null;if(process.platform==="linux")try{let e=(0,Gr.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 I$(r);try{let e=(0,Ry.spawnSync)("ps",["-p",String(r),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...mo(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 Fn(r){if(!r||!or(r.pid))return!1;if(!r.startToken)return!0;let e=Cy(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 Jl(){return Ay||(Ay=new jy),Ay}function Ky(){let r=_$.shift();r&&r()}var Ry,Gr,Oy,E$,x$,S$,w$,hT,jy,Ay,_$,Ps=M(()=>{"use strict";Ry=require("child_process");mT();Gr=require("fs"),Oy=ct(require("path"),1);ge();Fl();Ur();E$=5e3,x$=1e3,S$=$e.supervisorRegistry();w$=5e3,hT=new Map;jy=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=S$){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,Gr.mkdirSync)(Oy.default.dirname(this.registryPath),{recursive:!0}),!(0,Gr.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Gr.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"&&Ky()}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)or(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)Ky();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(o=>o.pid)});let i=t.filter(o=>or(o.pid));for(let o of i)try{typeof o.pgid=="number"&&process.platform!=="win32"?process.kill(-o.pgid,"SIGTERM"):process.kill(o.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGTERM session process PID ${o.pid}`,{pid:o.pid,pgid:o.pgid},c):_.warn("SYSTEM",`Failed to SIGTERM session process PID ${o.pid} (non-Error)`,{pid:o.pid,pgid:o.pgid,error:String(c)})}let s=Date.now()+E$;for(;Date.now()<s&&i.filter(c=>or(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100));let a=i.filter(o=>or(o.pid));for(let o of a){_.warn("SYSTEM",`Session process PID ${o.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:o.pid,pgid:o.pgid,sessionId:n});try{typeof o.pgid=="number"&&process.platform!=="win32"?process.kill(-o.pgid,"SIGKILL"):process.kill(o.pid,"SIGKILL")}catch(c){c instanceof Error?c.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGKILL session process PID ${o.pid}`,{pid:o.pid,pgid:o.pgid},c):_.warn("SYSTEM",`Failed to SIGKILL session process PID ${o.pid} (non-Error)`,{pid:o.pid,pgid:o.pgid,error:String(c)})}}if(a.length>0){let o=Date.now()+x$;for(;Date.now()<o&&a.filter(l=>or(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let o of t)this.entries.delete(o.id),this.runtimeProcesses.delete(o.id);this.persist();for(let o of t)o.type==="sdk"&&Ky();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,Gr.mkdirSync)(Oy.default.dirname(this.registryPath),{recursive:!0}),(0,Gr.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},Ay=null;_$=[]});function yT(r){return process.platform==="win32"?Math.round(r*ho.WINDOWS_MULTIPLIER):r}var ho,Dy=M(()=>{"use strict";ho={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 ST(r){let e=r.currentPid??process.pid,t=r.pidFilePath??T$,n=r.registry.getAll(),i=[...n].filter(a=>a.pid!==e).sort((a,o)=>Date.parse(o.startedAt)-Date.parse(a.startedAt));for(let a of i){if(!or(a.pid)){r.registry.unregister(a.id);continue}try{await gT(a,"SIGTERM")}catch(o){o instanceof Error?_.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:a.pid,pgid:a.pgid,type:a.type},o):_.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:a.pid,pgid:a.pgid,type:a.type,error:String(o)})}}await bT(i,5e3);let s=i.filter(a=>or(a.pid));for(let a of s)try{await gT(a,"SIGKILL")}catch(o){o instanceof Error?_.debug("SYSTEM","Failed to force kill child process",{pid:a.pid,pgid:a.pgid,type:a.type},o):_.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:a.pid,pgid:a.pgid,type:a.type,error:String(o)})}await bT(s,1e3);for(let a of i)r.registry.unregister(a.id);for(let a of n.filter(o=>o.pid===e))r.registry.unregister(a.id);try{(0,ET.rmSync)(t,{force:!0})}catch(a){a instanceof Error?_.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:t},a):_.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:t,error:String(a)})}r.registry.pruneDeadEntries()}async function bT(r,e){let t=Date.now()+e;for(;Date.now()<t;){if(r.filter(i=>or(i.pid)).length===0)return;await new Promise(i=>setTimeout(i,100))}}async function gT(r,e){let{pid:t,pgid:n}=r;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(a){if((a instanceof Error?a.code:void 0)!=="ESRCH")throw a}try{process.kill(t,e)}catch(a){if((a instanceof Error?a.code:void 0)!=="ESRCH")throw a}return}if(e==="SIGTERM"){try{process.kill(t,e)}catch(a){if(a instanceof Error&&a.code==="ESRCH")return;throw a}return}let i=await A$();if(i){await new Promise((a,o)=>{i(t,e,c=>{if(!c){a();return}if(c.code==="ESRCH"){a();return}o(c)})});return}let s=["/PID",String(t),"/T"];e==="SIGKILL"&&s.push("/F"),await k$("taskkill",s,{timeout:ho.POWERSHELL_COMMAND,windowsHide:!0})}async function A$(){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 vT,ET,xT,k$,T$,wT=M(()=>{"use strict";vT=require("child_process"),ET=require("fs"),xT=require("util");ge();Dy();Ps();Ur();k$=(0,xT.promisify)(vT.execFile),T$=$e.workerPid()});function K$(){let e=Jl().pruneDeadEntries();e>0&&_.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function _T(){Ms===null&&(Ms=setInterval(K$,IT),Ms.unref(),_.debug("SYSTEM","Health checker started",{intervalMs:IT}))}function kT(){Ms!==null&&(clearInterval(Ms),Ms=null,_.debug("SYSTEM","Health checker stopped"))}var IT,Ms,TT=M(()=>{"use strict";ge();Ps();IT=3e4,Ms=null});function AT(){return j$}function R$(r={}){let e=r.pidFilePath??O$;if(!(0,Di.existsSync)(e))return"missing";let t=null;try{t=JSON.parse((0,Di.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,Di.rmSync)(e,{force:!0}),"invalid"}return Fn(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,Di.rmSync)(e,{force:!0}),"stale")}var Di,O$,Py,j$,KT=M(()=>{"use strict";Di=require("fs");ge();Ps();wT();TT();Ur();O$=$e.workerPid(),Py=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(),R$({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,_T()}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}kT(),this.stopPromise=ST({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}},j$=new Py(Jl())});function My(r,e,t){r.on("finish",async()=>{try{await t()}finally{process.exit(0)}}),r.json(e)}var OT=M(()=>{"use strict"});function Ly(r,e=Date.now){return Math.max(0,Math.floor((e()-r)/1e3))}var jT=M(()=>{"use strict"});var Ny,RT,Ude,CT=M(()=>{"use strict";Ny=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()}},RT=new Ny,Ude=900*1e3});function P$(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 MT,LT,Fy,yo,NT,C$,qy,DT,D$,PT,Ul,qT=M(()=>{"use strict";MT=ct(Ll(),1),LT=ct(require("http"),1),Fy=ct(require("fs"),1),yo=ct(require("path"),1);Wk();ge();lT();fT();KT();Ps();Fl();OT();jT();CT();NT=yo.default.resolve(__dirname,"../skills/mem-search"),C$=yo.default.join(NT,"operations"),qy=yo.default.join(NT,"SKILL.md"),DT=(()=>{try{let r=Fy.readFileSync(qy,"utf-8");return _.info("SYSTEM","Cached SKILL.md at boot",{path:qy,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:qy,message:r instanceof Error?r.message:String(r)}),null}})(),D$=(()=>{let r=new Map;for(let e of by){let t=yo.default.join(C$,`${e}.md`);try{r.set(e,Fy.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})(),PT="13.5.2";Ul=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,MT.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=LT.default.createServer(this.app);this.server=s;let a=c=>{s.off("listening",o),i(c)},o=()=>{s.off("error",a),_.info("SYSTEM","HTTP server started",{host:t,port:e,pid:process.pid}),n()};s.once("error",a),s.once("listening",o),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(pT),this.app.use(dT)}setupMiddleware(){Iy(_y,{includeCors:!1}).forEach(t=>this.app.use(t))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,t,n)=>{P$(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:PT,workerPath:this.options.workerPath,uptime:Ly(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:RT.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:PT})}),this.app.get("/api/instructions",(e,t)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!Yk.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 a=D$.get(i);return a===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:a}]})}if(DT===null)return _.debug("HTTP","SKILL.md not cached at boot",{topic:n}),t.status(404).json({error:"Instruction not found"});let s=this.extractInstructionSection(DT,n);t.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",fo,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"})):My(t,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",fo,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"})):My(t,{status:"shutting_down"},()=>this.options.onShutdown())}),this.app.get("/api/admin/doctor",fo,(e,t)=>{let a=AT().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:or(f.pid)?"alive":"dead",startedAt:f.startedAt})),o=a.filter(f=>f.status==="dead").map(f=>f.pid),c=!Object.keys(process.env).some(f=>Ty.has(f)||ky.some(m=>f.startsWith(m))),l=Ly(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:a,health:{deadProcessPids:o,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 Jt,M$,L$,Jy,FT=M(()=>{"use strict";Jt=require("zod"),M$=Jt.z.enum(["hook","worker","provider","server","api"]),L$=Jt.z.object({id:Jt.z.string().min(1),projectId:Jt.z.string().min(1),serverSessionId:Jt.z.string().min(1).nullable().default(null),sourceType:M$,eventType:Jt.z.string().min(1),platformSource:Jt.z.string().min(1).nullable().default(null),payload:Jt.z.unknown().default({}),contentSessionId:Jt.z.string().min(1).nullable().default(null),memorySessionId:Jt.z.string().min(1).nullable().default(null),occurredAtEpoch:Jt.z.number().int().nonnegative(),createdAtEpoch:Jt.z.number().int().nonnegative()}),Jy=L$.omit({id:!0,createdAtEpoch:!0}).partial({serverSessionId:!0,platformSource:!0,payload:!0,contentSessionId:!0,memorySessionId:!0})});function qe(){return(0,Gl.randomUUID)()}function ze(r){return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}function JT(r){return Array.isArray(r)?r:[]}function ve(r){return typeof r=="number"?r:new Date(r).getTime()}function cr(r){return r==null?null:r instanceof Date?r:new Date(r)}async function Y(r,e,t=[]){return(await r.query(e,t)).rows[0]??null}async function _r(r,e,t){if(!await Y(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 mn(r,e,t,n){if(!await Y(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 bo(r){return JSON.stringify(Uy(r))}function kr(r){return(0,Gl.createHash)("sha256").update(bo(r)).digest("hex")}function Uy(r){if(Array.isArray(r))return r.map(Uy);if(r&&typeof r=="object"){let e=r;return Object.keys(e).sort().reduce((t,n)=>(t[n]=Uy(e[n]),t),{})}return r}var Gl,Br=M(()=>{"use strict";Gl=require("crypto")});function UT(r){return r.sourceEventId?`agent_event:v1:${kr([r.teamId,r.projectId,r.sourceAdapter,r.sourceEventId])}`:`agent_event:v1:${kr([r.teamId,r.projectId,r.sourceAdapter,r.contentSessionId??r.serverSessionId??null,r.eventType,new Date(r.occurredAt).toISOString(),bo(r.payload??{})])}`}function Gy(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:ze(r.metadata),occurredAtEpoch:ve(r.occurred_at),receivedAtEpoch:ve(r.received_at),createdAtEpoch:ve(r.created_at)}}var lr,Ls=M(()=>{"use strict";Br();lr=class{constructor(e){this.client=e}client;async create(e){await _r(this.client,e.projectId,e.teamId),e.serverSessionId&&await mn(this.client,e.serverSessionId,e.projectId,e.teamId);let t=UT(e),n=await Y(this.client,`
63
63
  INSERT INTO agent_events (
64
64
  id, project_id, team_id, server_session_id, source_adapter,
65
65
  source_event_id, idempotency_key, event_type, platform_source, payload, metadata, occurred_at