claude-mem 13.12.2 → 13.12.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.codex-plugin/plugin.json +1 -1
- package/dist/npx-cli/index.js +12 -12
- 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 +2 -2
- package/plugin/scripts/server-service.cjs +2 -2
- package/plugin/scripts/transcript-watcher.cjs +15 -15
- package/plugin/scripts/worker-service.cjs +218 -218
|
@@ -62,7 +62,7 @@ ${s.stack}`:` ${s.message}`;else if(this.getLevel()===0&&typeof s=="object")try{
|
|
|
62
62
|
`,"utf8")}catch(f){let m=f instanceof Error?f:new Error(String(f));Eo(`[LOGGER] Failed to write to log file: ${m.message}
|
|
63
63
|
${m.stack??""}
|
|
64
64
|
`)}else Eo(p+`
|
|
65
|
-
`)}debug(e,r,n,i){this.log(0,e,r,n,i)}info(e,r,n,i){this.log(1,e,r,n,i)}warn(e,r,n,i){this.log(2,e,r,n,i)}setErrorSink(e){B0=e}error(e,r,n,i){this.log(3,e,r,n,i),this.routeErrorToSink(r,n,i)}routeErrorToSink(e,r,n){try{if(!B0||!(n instanceof Error))return;B0(n)}catch{}}dataIn(e,r,n,i){this.info(e,`\u2192 ${r}`,n,i)}dataOut(e,r,n,i){this.info(e,`\u2190 ${r}`,n,i)}success(e,r,n,i){this.info(e,`\u2713 ${r}`,n,i)}failure(e,r,n,i){this.error(e,`\u2717 ${r}`,n,i)}},w=new H0});function qP(){let t=[];t.push(Y0.default.json({limit:"5mb"})),t.push((n,i,s)=>{let o=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(f=>n.path.endsWith(f)),c=n.path==="/api/logs";if(n.path.startsWith("/health")||n.path==="/"||o||c)return s();let l=Date.now(),u=`${n.method}-${Date.now()}`,d=Vte(n.method,n.path,n.body);w.debug("HTTP",`\u2192 ${n.method} ${n.path}`,{requestId:u},d);let p=i.send.bind(i);i.send=function(f){let m=Date.now()-l;return w.debug("HTTP",`\u2190 ${i.statusCode} ${n.path}`,{requestId:u,duration:`${m}ms`}),p(f)},s()});let e=Qs(),r=LP.default.join(e,"plugin","ui");return t.push(Y0.default.static(r)),t}function FP(){return(t,e,r)=>{let n=t.headers.origin;if(n){if(!n.startsWith("http://localhost:")&&!n.startsWith("http://127.0.0.1:")){r(new Error("CORS not allowed"));return}e.setHeader("Access-Control-Allow-Origin",n),e.setHeader("Vary","Origin")}if(t.method==="OPTIONS"){e.setHeader("Access-Control-Allow-Methods","GET,HEAD,POST,PUT,PATCH,DELETE"),e.setHeader("Access-Control-Allow-Headers","Content-Type,Authorization,X-Requested-With"),e.status(204).end();return}r()}}function Yp(t,e,r){let n=t.ip||t.connection.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){w.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:t.path,clientIp:n,method:t.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}r()}function Vte(t,e,r){if(!r||Object.keys(r).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=r.tool_name||"?",i=r.tool_input;return`tool=${w.formatTool(n,i)}`}return e.includes("/summarize")?"requesting summary":""}var Y0,LP,$P=R(()=>{"use strict";Y0=Xe(Hp(),1),LP=Xe(require("path"),1);Jn();he()});function JP(t,e,r,n){let i={error:t,message:e};return r&&(i.code=r),n&&(i.details=n),i}function zP(t,e){e.status(404).json(JP("NotFound",`Cannot ${t.method} ${t.path}`))}var So,UP,GP=R(()=>{"use strict";he();So=class extends Error{constructor(r,n=500,i,s){super(r);this.statusCode=n;this.code=i;this.details=s;this.name="AppError"}statusCode;code;details};UP=(t,e,r,n)=>{let i=t instanceof So?t.statusCode:500;w.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:t.message,code:t instanceof So?t.code:void 0},t);let s=JP(t.name||"Error",t.message,t instanceof So?t.code:void 0,t instanceof So?t.details:void 0);r.status(i).json(s)}});var Hte,Yte,mRe,BP=R(()=>{"use strict";Hte=new Set([".cmd",".bat"]),Yte=new Set([".exe",".com"]),mRe=new Set([...Yte,...Hte])});function Dl(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(Qte.has(r)){e[r]=n;continue}Q0.has(r)||W0.some(i=>r.startsWith(i))||(e[r]=n)}return e}var W0,Q0,Wte,Qte,Wp=R(()=>{"use strict";W0=["CLAUDECODE_","CLAUDE_CODE_"],Q0=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),Wte=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy","npm_config_noproxy"]),Qte=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS",...Wte])});function Vr(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;return r==="EPERM"?!0:(w.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return w.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function Qp(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!Vr(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function rre(t){let e=(0,rE.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Dl(process.env),LC_ALL:"C",LANG:"C"}});if(e.status===0){let r=e.stdout.trim();return r.length>0?r:null}return null}function nre(t){let e=VP.get(t);if(e&&Date.now()-e.capturedAtMs<tre)return e.token;let r=null;try{r=rre(t)}catch(n){w.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:n instanceof Error?n.message:String(n)}),r=null}return VP.set(t,{token:r,capturedAtMs:Date.now()}),r}function nE(t){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux")try{let e=(0,Un.readFileSync)(`/proc/${t}/stat`,"utf-8"),r=e.lastIndexOf(") ");if(r<0)return null;let i=e.slice(r+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(e){return w.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return nre(t);try{let e=(0,rE.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Dl(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let r=e.stdout.trim();return r.length>0?r:null}catch(e){return w.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}}function Gi(t){if(!t||!Vr(t.pid))return!1;if(!t.startToken)return!0;let e=nE(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||w.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}function Xp(){return X0||(X0=new tE),X0}function Z0(){let t=ire.shift();t&&t()}var rE,Un,eE,Xte,Zte,ere,tre,VP,tE,X0,ire,xo=R(()=>{"use strict";rE=require("child_process");BP();Un=require("fs"),eE=Xe(require("path"),1);he();Wp();Jn();Xte=5e3,Zte=1e3,ere=tt.supervisorRegistry();tre=5e3,VP=new Map;tE=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=ere){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,Un.mkdirSync)(eE.default.dirname(this.registryPath),{recursive:!0}),!(0,Un.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Un.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[i,s]of Object.entries(n))this.entries.set(i,s)}catch(r){r instanceof Error?w.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):w.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&w.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,r,n){this.initialize(),this.entries.set(e,r),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let r=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),r?.type==="sdk"&&Z0()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let n=Date.parse(e.startedAt),i=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(i)?0:i)})}getBySession(e){let r=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[n,i]of this.entries)Vr(i.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,i.type==="sdk"&&(r+=1));e>0&&this.persist();for(let n=0;n<r;n+=1)Z0();return e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;w.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:n,pids:r.map(a=>a.pid)});let i=r.filter(a=>Vr(a.pid));for(let a of i)try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(o){o instanceof Error?o.code!=="ESRCH"&&w.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},o):w.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(o)})}await Qp(i,Xte);let s=i.filter(a=>Vr(a.pid));for(let a of s){w.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(o){o instanceof Error?o.code!=="ESRCH"&&w.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},o):w.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(o)})}}if(s.length>0){let a=Date.now()+Zte;for(;Date.now()<a&&s.filter(c=>Vr(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100))}for(let a of r)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of r)a.type==="sdk"&&Z0();return w.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:n,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,Un.mkdirSync)(eE.default.dirname(this.registryPath),{recursive:!0}),(0,Un.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},X0=null;ire=[]});function HP(t){return process.platform==="win32"?Math.round(t*Ml.WINDOWS_MULTIPLIER):t}var Ml,iE=R(()=>{"use strict";Ml={HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5}});async function XP(t){let e=t.currentPid??process.pid,r=t.pidFilePath??are,n=t.registry.getAll(),i=[...n].filter(a=>a.pid!==e).sort((a,o)=>Date.parse(o.startedAt)-Date.parse(a.startedAt));for(let a of i){if(!Vr(a.pid)){t.registry.unregister(a.id);continue}try{await YP(a,"SIGTERM")}catch(o){o instanceof Error?w.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:a.pid,pgid:a.pgid,type:a.type},o):w.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:a.pid,pgid:a.pgid,type:a.type,error:String(o)})}}await Qp(i,5e3);let s=i.filter(a=>Vr(a.pid));for(let a of s)try{await YP(a,"SIGKILL")}catch(o){o instanceof Error?w.debug("SYSTEM","Failed to force kill child process",{pid:a.pid,pgid:a.pgid,type:a.type},o):w.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:a.pid,pgid:a.pgid,type:a.type,error:String(o)})}await Qp(s,1e3);for(let a of i)t.registry.unregister(a.id);for(let a of n.filter(o=>o.pid===e))t.registry.unregister(a.id);ore(r,e),t.registry.pruneDeadEntries()}function ore(t,e,r=!1){if(!(0,wo.existsSync)(t))return;let n=null;try{let a=JSON.parse((0,wo.readFileSync)(t,"utf-8"));n=typeof a.pid=="number"?a.pid:null}catch(a){w.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:a instanceof Error?a.message:String(a)});return}let i=e!==null&&n===e,s=n===null||!Vr(n);if(!i&&!(r&&s)){w.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:n,currentPid:e});return}try{(0,wo.rmSync)(t,{force:!0})}catch(a){a instanceof Error?w.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},a):w.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(a)})}}async function YP(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}try{process.kill(r,e)}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}return}if(e==="SIGTERM"){try{process.kill(r,e)}catch(s){if(s instanceof Error&&s.code==="ESRCH")return;throw s}return}let i=["/PID",String(r),"/T"];e==="SIGKILL"&&i.push("/F"),await sre("taskkill",i,{timeout:Ml.POWERSHELL_COMMAND,windowsHide:!0})}var WP,wo,QP,sre,are,ZP=R(()=>{"use strict";WP=require("child_process"),wo=require("fs"),QP=require("util");he();iE();xo();Jn();sre=(0,QP.promisify)(WP.execFile),are=tt.workerPid()});function cre(){let e=Xp().pruneDeadEntries();e>0&&w.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function tD(){_o===null&&(_o=setInterval(cre,eD),_o.unref(),w.debug("SYSTEM","Health checker started",{intervalMs:eD}))}function rD(){_o!==null&&(clearInterval(_o),_o=null,w.debug("SYSTEM","Health checker stopped"))}var eD,_o,nD=R(()=>{"use strict";he();xo();eD=3e4,_o=null});function iD(){return ure}function dre(t={}){let e=t.pidFilePath??lre;if(!(0,Xs.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,Xs.readFileSync)(e,"utf-8"))}catch(i){return i instanceof Error?w.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},i):w.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(i)}),(0,Xs.rmSync)(e,{force:!0}),"invalid"}return Gi(r)&&r?((t.logAlive??!0)&&w.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(w.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,Xs.rmSync)(e,{force:!0}),"stale")}var Xs,lre,sE,ure,sD=R(()=>{"use strict";Xs=require("fs");he();xo();ZP();nD();Jn();lre=tt.workerPid(),sE=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(),dre({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,tD()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){w.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,w.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){i instanceof Error?w.error("SYSTEM","Error during shutdown",{},i):w.error("SYSTEM","Error during shutdown (non-Error)",{error:String(i)});try{await this.stop()}catch(s){s instanceof Error?w.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):w.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(s)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{w.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}rD(),this.stopPromise=XP({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,n){this.registry.register(e,r,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},ure=new sE(Xp())});function aE(t,e,r){t.on("finish",async()=>{try{await r()}finally{process.exit(0)}}),t.json(e)}var aD=R(()=>{"use strict"});function oE(t,e=Date.now){return Math.max(0,Math.floor((e()-t)/1e3))}var oD=R(()=>{"use strict"});function cE(){let t=Array.from(pre.values()).map(e=>({...e})).sort((e,r)=>e.dependency.localeCompare(r.dependency));return{degraded:t.length>0,statuses:t}}var pre,cD=R(()=>{"use strict";pre=new Map});var lE,lD,JRe,uD=R(()=>{"use strict";lE=class{entries=new Map;set(e){if(!e||typeof e!="object")return;let r=e.rateLimitType??"default";this.entries.set(r,{...e,observedAt:Date.now()})}get(e){return e?this.entries.get(e):this.entries.get("default")}getMostRecentByWindow(){return{five_hour:this.entries.get("five_hour"),seven_day:this.entries.get("seven_day"),seven_day_opus:this.entries.get("seven_day_opus"),seven_day_sonnet:this.entries.get("seven_day_sonnet"),overage:this.entries.get("overage")}}get size(){return this.entries.size}},lD=new lE,JRe=900*1e3});function hre(t){t.setHeader("X-Content-Type-Options","nosniff"),t.setHeader("X-Frame-Options","DENY"),t.setHeader("X-DNS-Prefetch-Control","off"),t.setHeader("Referrer-Policy","no-referrer"),t.setHeader("Cross-Origin-Opener-Policy","same-origin"),t.setHeader("Cross-Origin-Resource-Policy","same-origin"),t.setHeader("Origin-Agent-Cluster","?1"),t.removeHeader("X-Powered-By")}var fD,mD,dE,Nl,hD,fre,uE,dD,mre,pD,Zp,yD=R(()=>{"use strict";fD=Xe(Hp(),1),mD=Xe(require("http"),1),dE=Xe(require("fs"),1),Nl=Xe(require("path"),1);CP();he();$P();GP();sD();xo();Wp();aD();oD();cD();uD();hD=Nl.default.resolve(__dirname,"../skills/mem-search"),fre=Nl.default.join(hD,"operations"),uE=Nl.default.join(hD,"SKILL.md"),dD=(()=>{try{let t=dE.readFileSync(uE,"utf-8");return w.info("SYSTEM","Cached SKILL.md at boot",{path:uE,bytes:Buffer.byteLength(t,"utf-8")}),t}catch(t){return w.debug("SYSTEM","SKILL.md not present at boot, /api/instructions will 404 for topic queries",{path:uE,message:t instanceof Error?t.message:String(t)}),null}})(),mre=(()=>{let t=new Map;for(let e of U0){let r=Nl.default.join(fre,`${e}.md`);try{t.set(e,dE.readFileSync(r,"utf-8"))}catch(n){w.debug("SYSTEM","Operation instruction file not present at boot",{path:r,message:n instanceof Error?n.message:String(n)})}}return t.size>0&&w.info("SYSTEM","Cached operation instruction files at boot",{count:t.size,operations:Array.from(t.keys())}),t})(),pD="13.12.2";Zp=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,fD.default)(),this.app.disable("x-powered-by"),this.setupSecurityHeaders(),this.setupCors(),this.setupPreBodyParserRoutes(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,r){return new Promise((n,i)=>{let s=mD.default.createServer(this.app);this.server=s;let a=c=>{s.off("listening",o),i(c)},o=()=>{s.off("error",a),w.info("SYSTEM","HTTP server started",{host:r,port:e,pid:process.pid}),n()};s.once("error",a),s.once("listening",o),s.listen(e,r)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{this.server.close(n=>n?r(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,w.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(zP),this.app.use(UP)}setupMiddleware(){qP().forEach(r=>this.app.use(r))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,r,n)=>{hre(r),n()})}setupCors(){this.app.use(FP())}setupPreBodyParserRoutes(){this.options.preBodyParserRoutes?.forEach(e=>e.setupRoutes(this.app))}setupCoreRoutes(){this.app.get("/api/health",async(e,r)=>{let n=this.options.getQueueHealth?await this.options.getQueueHealth():null,i=n?.engine==="bullmq"&&n.redis.status==="error",s=this.options.getDependencyHealth?this.options.getDependencyHealth():cE();r.status(i?503:200).json({status:i?"degraded":"ok",...this.options.runtime?{runtime:this.options.runtime}:{},version:pD,workerPath:this.options.workerPath,uptime:oE(this.startTime),managed:process.env.CLAUDE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.options.getInitializationComplete(),mcpReady:this.options.getMcpReady(),ai:this.options.getAiStatus(),dependencies:s,rateLimits:lD.getMostRecentByWindow(),...n?{queue:n}:{}})}),this.app.get("/api/readiness",(e,r)=>{this.options.getInitializationComplete()?r.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):r.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(e,r)=>{r.status(200).json({version:pD})}),this.app.get("/api/instructions",(e,r)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!jP.includes(n))return r.status(400).json({error:"Invalid topic"});if(i&&!U0.includes(i))return r.status(400).json({error:"Invalid operation"});if(i){let a=mre.get(i);return a===void 0?(w.debug("HTTP","Instruction file not cached at boot",{operation:i}),r.status(404).json({error:"Instruction not found"})):r.json({content:[{type:"text",text:a}]})}if(dD===null)return w.debug("HTTP","SKILL.md not cached at boot",{topic:n}),r.status(404).json({error:"Instruction not found"});let s=this.extractInstructionSection(dD,n);r.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",Yp,async(e,r)=>{process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(r.json({status:"restarting"}),w.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):aE(r,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",Yp,async(e,r)=>{let n=e.query.reason==="restart"?"restart":"stop";process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(r.json({status:"shutting_down"}),w.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown",reason:n})):aE(r,{status:"shutting_down"},()=>this.options.onShutdown(n))}),this.app.get("/api/admin/doctor",Yp,(e,r)=>{let a=iD().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:Vr(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=>Q0.has(f)||W0.some(m=>f.startsWith(m))),l=oE(this.startTime),u=Math.floor(l/3600),d=Math.floor(l%3600/60),p=u>0?`${u}h ${d}m`:`${d}m`;r.json({supervisor:{running:!0,pid:process.pid,uptime:p},processes:a,health:{deadProcessPids:o,envClean:c,dependencies:this.options.getDependencyHealth?this.options.getDependencyHealth():cE()}})})}extractInstructionSection(e,r){let n={workflow:this.extractBetween(e,"## The Workflow","## Search Parameters"),search_params:this.extractBetween(e,"## Search Parameters","## Examples"),examples:this.extractBetween(e,"## Examples","## Why This Workflow"),all:e};return n[r]||n.all}extractBetween(e,r,n){let i=e.indexOf(r),s=e.indexOf(n);return i===-1?e:s===-1?e.substring(i):e.substring(i,s).trim()}}});var _r,yre,gre,pE,gD=R(()=>{"use strict";_r=require("zod"),yre=_r.z.enum(["hook","worker","provider","server","api"]),gre=_r.z.object({id:_r.z.string().min(1),projectId:_r.z.string().min(1),serverSessionId:_r.z.string().min(1).nullable().default(null),sourceType:yre,eventType:_r.z.string().min(1),platformSource:_r.z.string().min(1).nullable().default(null),payload:_r.z.unknown().default({}),contentSessionId:_r.z.string().min(1).nullable().default(null),memorySessionId:_r.z.string().min(1).nullable().default(null),occurredAtEpoch:_r.z.number().int().nonnegative(),createdAtEpoch:_r.z.number().int().nonnegative()}),pE=gre.omit({id:!0,createdAtEpoch:!0}).partial({serverSessionId:!0,platformSource:!0,payload:!0,contentSessionId:!0,memorySessionId:!0})});function Ye(){return(0,ef.randomUUID)()}function ft(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function bD(t){return Array.isArray(t)?t:[]}function De(t){return typeof t=="number"?t:new Date(t).getTime()}function Hr(t){return t==null?null:t instanceof Date?t:new Date(t)}async function ie(t,e,r=[]){return(await t.query(e,r)).rows[0]??null}async function gn(t,e,r){if(!await ie(t,"SELECT id FROM projects WHERE id = $1 AND team_id = $2",[e,r]))throw new Error("project_id must belong to team_id")}async function hi(t,e,r,n){if(!await ie(t,"SELECT id FROM server_sessions WHERE id = $1 AND project_id = $2 AND team_id = $3",[e,r,n]))throw new Error("server_session_id must belong to project_id and team_id")}function Ll(t){return JSON.stringify(fE(t))}function bn(t){return(0,ef.createHash)("sha256").update(Ll(t)).digest("hex")}function fE(t){if(Array.isArray(t))return t.map(fE);if(t&&typeof t=="object"){let e=t;return Object.keys(e).sort().reduce((r,n)=>(r[n]=fE(e[n]),r),{})}return t}var ef,vn=R(()=>{"use strict";ef=require("crypto")});function bre(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Bi(t){if(!t)return Io;let e=bre(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:Io}function sr(t){return typeof t!="string"?null:Bi(t)}var Io,Zs=R(()=>{"use strict";Io="claude"});function vD(t){let e=sr(t.platformSource),r=e?[e]:[];return t.sourceEventId?`agent_event:v1:${bn([t.teamId,t.projectId,t.sourceAdapter,...r,t.sourceEventId])}`:`agent_event:v1:${bn([t.teamId,t.projectId,t.sourceAdapter,...r,t.contentSessionId??t.serverSessionId??null,t.eventType,new Date(t.occurredAt).toISOString(),Ll(t.payload??{})])}`}function mE(t){return{id:t.id,projectId:t.project_id,teamId:t.team_id,serverSessionId:t.server_session_id,sourceAdapter:t.source_adapter,sourceEventId:t.source_event_id,idempotencyKey:t.idempotency_key,eventType:t.event_type,platformSource:t.platform_source,payload:t.payload,metadata:ft(t.metadata),occurredAtEpoch:De(t.occurred_at),receivedAtEpoch:De(t.received_at),createdAtEpoch:De(t.created_at)}}var Yr,ko=R(()=>{"use strict";vn();Zs();Yr=class{constructor(e){this.client=e}client;async create(e){await gn(this.client,e.projectId,e.teamId),e.serverSessionId&&await hi(this.client,e.serverSessionId,e.projectId,e.teamId);let r=vD(e),n=sr(e.platformSource),i=await ie(this.client,`
|
|
65
|
+
`)}debug(e,r,n,i){this.log(0,e,r,n,i)}info(e,r,n,i){this.log(1,e,r,n,i)}warn(e,r,n,i){this.log(2,e,r,n,i)}setErrorSink(e){B0=e}error(e,r,n,i){this.log(3,e,r,n,i),this.routeErrorToSink(r,n,i)}routeErrorToSink(e,r,n){try{if(!B0||!(n instanceof Error))return;B0(n)}catch{}}dataIn(e,r,n,i){this.info(e,`\u2192 ${r}`,n,i)}dataOut(e,r,n,i){this.info(e,`\u2190 ${r}`,n,i)}success(e,r,n,i){this.info(e,`\u2713 ${r}`,n,i)}failure(e,r,n,i){this.error(e,`\u2717 ${r}`,n,i)}},w=new H0});function qP(){let t=[];t.push(Y0.default.json({limit:"5mb"})),t.push((n,i,s)=>{let o=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(f=>n.path.endsWith(f)),c=n.path==="/api/logs";if(n.path.startsWith("/health")||n.path==="/"||o||c)return s();let l=Date.now(),u=`${n.method}-${Date.now()}`,d=Vte(n.method,n.path,n.body);w.debug("HTTP",`\u2192 ${n.method} ${n.path}`,{requestId:u},d);let p=i.send.bind(i);i.send=function(f){let m=Date.now()-l;return w.debug("HTTP",`\u2190 ${i.statusCode} ${n.path}`,{requestId:u,duration:`${m}ms`}),p(f)},s()});let e=Qs(),r=LP.default.join(e,"plugin","ui");return t.push(Y0.default.static(r)),t}function FP(){return(t,e,r)=>{let n=t.headers.origin;if(n){if(!n.startsWith("http://localhost:")&&!n.startsWith("http://127.0.0.1:")){r(new Error("CORS not allowed"));return}e.setHeader("Access-Control-Allow-Origin",n),e.setHeader("Vary","Origin")}if(t.method==="OPTIONS"){e.setHeader("Access-Control-Allow-Methods","GET,HEAD,POST,PUT,PATCH,DELETE"),e.setHeader("Access-Control-Allow-Headers","Content-Type,Authorization,X-Requested-With"),e.status(204).end();return}r()}}function Yp(t,e,r){let n=t.ip||t.connection.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){w.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:t.path,clientIp:n,method:t.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}r()}function Vte(t,e,r){if(!r||Object.keys(r).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=r.tool_name||"?",i=r.tool_input;return`tool=${w.formatTool(n,i)}`}return e.includes("/summarize")?"requesting summary":""}var Y0,LP,$P=R(()=>{"use strict";Y0=Xe(Hp(),1),LP=Xe(require("path"),1);Jn();he()});function JP(t,e,r,n){let i={error:t,message:e};return r&&(i.code=r),n&&(i.details=n),i}function zP(t,e){e.status(404).json(JP("NotFound",`Cannot ${t.method} ${t.path}`))}var So,UP,GP=R(()=>{"use strict";he();So=class extends Error{constructor(r,n=500,i,s){super(r);this.statusCode=n;this.code=i;this.details=s;this.name="AppError"}statusCode;code;details};UP=(t,e,r,n)=>{let i=t instanceof So?t.statusCode:500;w.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:t.message,code:t instanceof So?t.code:void 0},t);let s=JP(t.name||"Error",t.message,t instanceof So?t.code:void 0,t instanceof So?t.details:void 0);r.status(i).json(s)}});var Hte,Yte,mRe,BP=R(()=>{"use strict";Hte=new Set([".cmd",".bat"]),Yte=new Set([".exe",".com"]),mRe=new Set([...Yte,...Hte])});function Dl(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(Qte.has(r)){e[r]=n;continue}Q0.has(r)||W0.some(i=>r.startsWith(i))||(e[r]=n)}return e}var W0,Q0,Wte,Qte,Wp=R(()=>{"use strict";W0=["CLAUDECODE_","CLAUDE_CODE_"],Q0=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),Wte=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy","npm_config_noproxy"]),Qte=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS",...Wte])});function Vr(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;return r==="EPERM"?!0:(w.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return w.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function Qp(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!Vr(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function rre(t){let e=(0,rE.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Dl(process.env),LC_ALL:"C",LANG:"C"}});if(e.status===0){let r=e.stdout.trim();return r.length>0?r:null}return null}function nre(t){let e=VP.get(t);if(e&&Date.now()-e.capturedAtMs<tre)return e.token;let r=null;try{r=rre(t)}catch(n){w.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:n instanceof Error?n.message:String(n)}),r=null}return VP.set(t,{token:r,capturedAtMs:Date.now()}),r}function nE(t){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux")try{let e=(0,Un.readFileSync)(`/proc/${t}/stat`,"utf-8"),r=e.lastIndexOf(") ");if(r<0)return null;let i=e.slice(r+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(e){return w.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return nre(t);try{let e=(0,rE.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Dl(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let r=e.stdout.trim();return r.length>0?r:null}catch(e){return w.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:e instanceof Error?e.message:String(e)}),null}}function Gi(t){if(!t||!Vr(t.pid))return!1;if(!t.startToken)return!0;let e=nE(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||w.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}function Xp(){return X0||(X0=new tE),X0}function Z0(){let t=ire.shift();t&&t()}var rE,Un,eE,Xte,Zte,ere,tre,VP,tE,X0,ire,xo=R(()=>{"use strict";rE=require("child_process");BP();Un=require("fs"),eE=Xe(require("path"),1);he();Wp();Jn();Xte=5e3,Zte=1e3,ere=tt.supervisorRegistry();tre=5e3,VP=new Map;tE=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=ere){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,Un.mkdirSync)(eE.default.dirname(this.registryPath),{recursive:!0}),!(0,Un.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Un.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[i,s]of Object.entries(n))this.entries.set(i,s)}catch(r){r instanceof Error?w.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):w.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&w.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,r,n){this.initialize(),this.entries.set(e,r),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let r=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),r?.type==="sdk"&&Z0()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let n=Date.parse(e.startedAt),i=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(i)?0:i)})}getBySession(e){let r=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[n,i]of this.entries)Vr(i.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,i.type==="sdk"&&(r+=1));e>0&&this.persist();for(let n=0;n<r;n+=1)Z0();return e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;w.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:n,pids:r.map(a=>a.pid)});let i=r.filter(a=>Vr(a.pid));for(let a of i)try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(o){o instanceof Error?o.code!=="ESRCH"&&w.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},o):w.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(o)})}await Qp(i,Xte);let s=i.filter(a=>Vr(a.pid));for(let a of s){w.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(o){o instanceof Error?o.code!=="ESRCH"&&w.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},o):w.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(o)})}}if(s.length>0){let a=Date.now()+Zte;for(;Date.now()<a&&s.filter(c=>Vr(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100))}for(let a of r)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of r)a.type==="sdk"&&Z0();return w.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:n,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,Un.mkdirSync)(eE.default.dirname(this.registryPath),{recursive:!0}),(0,Un.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},X0=null;ire=[]});function HP(t){return process.platform==="win32"?Math.round(t*Ml.WINDOWS_MULTIPLIER):t}var Ml,iE=R(()=>{"use strict";Ml={HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5}});async function XP(t){let e=t.currentPid??process.pid,r=t.pidFilePath??are,n=t.registry.getAll(),i=[...n].filter(a=>a.pid!==e).sort((a,o)=>Date.parse(o.startedAt)-Date.parse(a.startedAt));for(let a of i){if(!Vr(a.pid)){t.registry.unregister(a.id);continue}try{await YP(a,"SIGTERM")}catch(o){o instanceof Error?w.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:a.pid,pgid:a.pgid,type:a.type},o):w.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:a.pid,pgid:a.pgid,type:a.type,error:String(o)})}}await Qp(i,5e3);let s=i.filter(a=>Vr(a.pid));for(let a of s)try{await YP(a,"SIGKILL")}catch(o){o instanceof Error?w.debug("SYSTEM","Failed to force kill child process",{pid:a.pid,pgid:a.pgid,type:a.type},o):w.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:a.pid,pgid:a.pgid,type:a.type,error:String(o)})}await Qp(s,1e3);for(let a of i)t.registry.unregister(a.id);for(let a of n.filter(o=>o.pid===e))t.registry.unregister(a.id);ore(r,e),t.registry.pruneDeadEntries()}function ore(t,e,r=!1){if(!(0,wo.existsSync)(t))return;let n=null;try{let a=JSON.parse((0,wo.readFileSync)(t,"utf-8"));n=typeof a.pid=="number"?a.pid:null}catch(a){w.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:a instanceof Error?a.message:String(a)});return}let i=e!==null&&n===e,s=n===null||!Vr(n);if(!i&&!(r&&s)){w.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:n,currentPid:e});return}try{(0,wo.rmSync)(t,{force:!0})}catch(a){a instanceof Error?w.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},a):w.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(a)})}}async function YP(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}try{process.kill(r,e)}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}return}if(e==="SIGTERM"){try{process.kill(r,e)}catch(s){if(s instanceof Error&&s.code==="ESRCH")return;throw s}return}let i=["/PID",String(r),"/T"];e==="SIGKILL"&&i.push("/F"),await sre("taskkill",i,{timeout:Ml.POWERSHELL_COMMAND,windowsHide:!0})}var WP,wo,QP,sre,are,ZP=R(()=>{"use strict";WP=require("child_process"),wo=require("fs"),QP=require("util");he();iE();xo();Jn();sre=(0,QP.promisify)(WP.execFile),are=tt.workerPid()});function cre(){let e=Xp().pruneDeadEntries();e>0&&w.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function tD(){_o===null&&(_o=setInterval(cre,eD),_o.unref(),w.debug("SYSTEM","Health checker started",{intervalMs:eD}))}function rD(){_o!==null&&(clearInterval(_o),_o=null,w.debug("SYSTEM","Health checker stopped"))}var eD,_o,nD=R(()=>{"use strict";he();xo();eD=3e4,_o=null});function iD(){return ure}function dre(t={}){let e=t.pidFilePath??lre;if(!(0,Xs.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,Xs.readFileSync)(e,"utf-8"))}catch(i){return i instanceof Error?w.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},i):w.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(i)}),(0,Xs.rmSync)(e,{force:!0}),"invalid"}return Gi(r)&&r?((t.logAlive??!0)&&w.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(w.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,Xs.rmSync)(e,{force:!0}),"stale")}var Xs,lre,sE,ure,sD=R(()=>{"use strict";Xs=require("fs");he();xo();ZP();nD();Jn();lre=tt.workerPid(),sE=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(),dre({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,tD()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){w.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,w.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){i instanceof Error?w.error("SYSTEM","Error during shutdown",{},i):w.error("SYSTEM","Error during shutdown (non-Error)",{error:String(i)});try{await this.stop()}catch(s){s instanceof Error?w.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):w.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(s)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{w.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}rD(),this.stopPromise=XP({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,n){this.registry.register(e,r,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},ure=new sE(Xp())});function aE(t,e,r){t.on("finish",async()=>{try{await r()}finally{process.exit(0)}}),t.json(e)}var aD=R(()=>{"use strict"});function oE(t,e=Date.now){return Math.max(0,Math.floor((e()-t)/1e3))}var oD=R(()=>{"use strict"});function cE(){let t=Array.from(pre.values()).map(e=>({...e})).sort((e,r)=>e.dependency.localeCompare(r.dependency));return{degraded:t.length>0,statuses:t}}var pre,cD=R(()=>{"use strict";pre=new Map});var lE,lD,JRe,uD=R(()=>{"use strict";lE=class{entries=new Map;set(e){if(!e||typeof e!="object")return;let r=e.rateLimitType??"default";this.entries.set(r,{...e,observedAt:Date.now()})}get(e){return e?this.entries.get(e):this.entries.get("default")}getMostRecentByWindow(){return{five_hour:this.entries.get("five_hour"),seven_day:this.entries.get("seven_day"),seven_day_opus:this.entries.get("seven_day_opus"),seven_day_sonnet:this.entries.get("seven_day_sonnet"),overage:this.entries.get("overage")}}get size(){return this.entries.size}},lD=new lE,JRe=900*1e3});function hre(t){t.setHeader("X-Content-Type-Options","nosniff"),t.setHeader("X-Frame-Options","DENY"),t.setHeader("X-DNS-Prefetch-Control","off"),t.setHeader("Referrer-Policy","no-referrer"),t.setHeader("Cross-Origin-Opener-Policy","same-origin"),t.setHeader("Cross-Origin-Resource-Policy","same-origin"),t.setHeader("Origin-Agent-Cluster","?1"),t.removeHeader("X-Powered-By")}var fD,mD,dE,Nl,hD,fre,uE,dD,mre,pD,Zp,yD=R(()=>{"use strict";fD=Xe(Hp(),1),mD=Xe(require("http"),1),dE=Xe(require("fs"),1),Nl=Xe(require("path"),1);CP();he();$P();GP();sD();xo();Wp();aD();oD();cD();uD();hD=Nl.default.resolve(__dirname,"../skills/mem-search"),fre=Nl.default.join(hD,"operations"),uE=Nl.default.join(hD,"SKILL.md"),dD=(()=>{try{let t=dE.readFileSync(uE,"utf-8");return w.info("SYSTEM","Cached SKILL.md at boot",{path:uE,bytes:Buffer.byteLength(t,"utf-8")}),t}catch(t){return w.debug("SYSTEM","SKILL.md not present at boot, /api/instructions will 404 for topic queries",{path:uE,message:t instanceof Error?t.message:String(t)}),null}})(),mre=(()=>{let t=new Map;for(let e of U0){let r=Nl.default.join(fre,`${e}.md`);try{t.set(e,dE.readFileSync(r,"utf-8"))}catch(n){w.debug("SYSTEM","Operation instruction file not present at boot",{path:r,message:n instanceof Error?n.message:String(n)})}}return t.size>0&&w.info("SYSTEM","Cached operation instruction files at boot",{count:t.size,operations:Array.from(t.keys())}),t})(),pD="13.12.3";Zp=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,fD.default)(),this.app.disable("x-powered-by"),this.setupSecurityHeaders(),this.setupCors(),this.setupPreBodyParserRoutes(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,r){return new Promise((n,i)=>{let s=mD.default.createServer(this.app);this.server=s;let a=c=>{s.off("listening",o),i(c)},o=()=>{s.off("error",a),w.info("SYSTEM","HTTP server started",{host:r,port:e,pid:process.pid}),n()};s.once("error",a),s.once("listening",o),s.listen(e,r)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{this.server.close(n=>n?r(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,w.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(zP),this.app.use(UP)}setupMiddleware(){qP().forEach(r=>this.app.use(r))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,r,n)=>{hre(r),n()})}setupCors(){this.app.use(FP())}setupPreBodyParserRoutes(){this.options.preBodyParserRoutes?.forEach(e=>e.setupRoutes(this.app))}setupCoreRoutes(){this.app.get("/api/health",async(e,r)=>{let n=this.options.getQueueHealth?await this.options.getQueueHealth():null,i=n?.engine==="bullmq"&&n.redis.status==="error",s=this.options.getDependencyHealth?this.options.getDependencyHealth():cE();r.status(i?503:200).json({status:i?"degraded":"ok",...this.options.runtime?{runtime:this.options.runtime}:{},version:pD,workerPath:this.options.workerPath,uptime:oE(this.startTime),managed:process.env.CLAUDE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.options.getInitializationComplete(),mcpReady:this.options.getMcpReady(),ai:this.options.getAiStatus(),dependencies:s,rateLimits:lD.getMostRecentByWindow(),...n?{queue:n}:{}})}),this.app.get("/api/readiness",(e,r)=>{this.options.getInitializationComplete()?r.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):r.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(e,r)=>{r.status(200).json({version:pD})}),this.app.get("/api/instructions",(e,r)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!jP.includes(n))return r.status(400).json({error:"Invalid topic"});if(i&&!U0.includes(i))return r.status(400).json({error:"Invalid operation"});if(i){let a=mre.get(i);return a===void 0?(w.debug("HTTP","Instruction file not cached at boot",{operation:i}),r.status(404).json({error:"Instruction not found"})):r.json({content:[{type:"text",text:a}]})}if(dD===null)return w.debug("HTTP","SKILL.md not cached at boot",{topic:n}),r.status(404).json({error:"Instruction not found"});let s=this.extractInstructionSection(dD,n);r.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",Yp,async(e,r)=>{process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(r.json({status:"restarting"}),w.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):aE(r,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",Yp,async(e,r)=>{let n=e.query.reason==="restart"?"restart":"stop";process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(r.json({status:"shutting_down"}),w.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown",reason:n})):aE(r,{status:"shutting_down"},()=>this.options.onShutdown(n))}),this.app.get("/api/admin/doctor",Yp,(e,r)=>{let a=iD().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:Vr(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=>Q0.has(f)||W0.some(m=>f.startsWith(m))),l=oE(this.startTime),u=Math.floor(l/3600),d=Math.floor(l%3600/60),p=u>0?`${u}h ${d}m`:`${d}m`;r.json({supervisor:{running:!0,pid:process.pid,uptime:p},processes:a,health:{deadProcessPids:o,envClean:c,dependencies:this.options.getDependencyHealth?this.options.getDependencyHealth():cE()}})})}extractInstructionSection(e,r){let n={workflow:this.extractBetween(e,"## The Workflow","## Search Parameters"),search_params:this.extractBetween(e,"## Search Parameters","## Examples"),examples:this.extractBetween(e,"## Examples","## Why This Workflow"),all:e};return n[r]||n.all}extractBetween(e,r,n){let i=e.indexOf(r),s=e.indexOf(n);return i===-1?e:s===-1?e.substring(i):e.substring(i,s).trim()}}});var _r,yre,gre,pE,gD=R(()=>{"use strict";_r=require("zod"),yre=_r.z.enum(["hook","worker","provider","server","api"]),gre=_r.z.object({id:_r.z.string().min(1),projectId:_r.z.string().min(1),serverSessionId:_r.z.string().min(1).nullable().default(null),sourceType:yre,eventType:_r.z.string().min(1),platformSource:_r.z.string().min(1).nullable().default(null),payload:_r.z.unknown().default({}),contentSessionId:_r.z.string().min(1).nullable().default(null),memorySessionId:_r.z.string().min(1).nullable().default(null),occurredAtEpoch:_r.z.number().int().nonnegative(),createdAtEpoch:_r.z.number().int().nonnegative()}),pE=gre.omit({id:!0,createdAtEpoch:!0}).partial({serverSessionId:!0,platformSource:!0,payload:!0,contentSessionId:!0,memorySessionId:!0})});function Ye(){return(0,ef.randomUUID)()}function ft(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function bD(t){return Array.isArray(t)?t:[]}function De(t){return typeof t=="number"?t:new Date(t).getTime()}function Hr(t){return t==null?null:t instanceof Date?t:new Date(t)}async function ie(t,e,r=[]){return(await t.query(e,r)).rows[0]??null}async function gn(t,e,r){if(!await ie(t,"SELECT id FROM projects WHERE id = $1 AND team_id = $2",[e,r]))throw new Error("project_id must belong to team_id")}async function hi(t,e,r,n){if(!await ie(t,"SELECT id FROM server_sessions WHERE id = $1 AND project_id = $2 AND team_id = $3",[e,r,n]))throw new Error("server_session_id must belong to project_id and team_id")}function Ll(t){return JSON.stringify(fE(t))}function bn(t){return(0,ef.createHash)("sha256").update(Ll(t)).digest("hex")}function fE(t){if(Array.isArray(t))return t.map(fE);if(t&&typeof t=="object"){let e=t;return Object.keys(e).sort().reduce((r,n)=>(r[n]=fE(e[n]),r),{})}return t}var ef,vn=R(()=>{"use strict";ef=require("crypto")});function bre(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Bi(t){if(!t)return Io;let e=bre(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:Io}function sr(t){return typeof t!="string"?null:Bi(t)}var Io,Zs=R(()=>{"use strict";Io="claude"});function vD(t){let e=sr(t.platformSource),r=e?[e]:[];return t.sourceEventId?`agent_event:v1:${bn([t.teamId,t.projectId,t.sourceAdapter,...r,t.sourceEventId])}`:`agent_event:v1:${bn([t.teamId,t.projectId,t.sourceAdapter,...r,t.contentSessionId??t.serverSessionId??null,t.eventType,new Date(t.occurredAt).toISOString(),Ll(t.payload??{})])}`}function mE(t){return{id:t.id,projectId:t.project_id,teamId:t.team_id,serverSessionId:t.server_session_id,sourceAdapter:t.source_adapter,sourceEventId:t.source_event_id,idempotencyKey:t.idempotency_key,eventType:t.event_type,platformSource:t.platform_source,payload:t.payload,metadata:ft(t.metadata),occurredAtEpoch:De(t.occurred_at),receivedAtEpoch:De(t.received_at),createdAtEpoch:De(t.created_at)}}var Yr,ko=R(()=>{"use strict";vn();Zs();Yr=class{constructor(e){this.client=e}client;async create(e){await gn(this.client,e.projectId,e.teamId),e.serverSessionId&&await hi(this.client,e.serverSessionId,e.projectId,e.teamId);let r=vD(e),n=sr(e.platformSource),i=await ie(this.client,`
|
|
66
66
|
INSERT INTO agent_events (
|
|
67
67
|
id, project_id, team_id, server_session_id, source_adapter,
|
|
68
68
|
source_event_id, idempotency_key, event_type, platform_source, payload, metadata, occurred_at
|
|
@@ -345,7 +345,7 @@ data:
|
|
|
345
345
|
)
|
|
346
346
|
ORDER BY e.occurred_at ASC
|
|
347
347
|
LIMIT $4
|
|
348
|
-
`,[e.serverSessionId,e.projectId,e.teamId,r])).rows.map(_me)}}});function b4(t){let e=Tme.safeParse(t);if(!e.success)throw new Ju(e.error.issues);return e.data}var Qt,hc,y4,g4,Ime,kme,Tme,Ju,Lm=R(()=>{"use strict";Qt=require("zod"),hc={event:"server_beta_generate_event",summary:"server_beta_generate_summary"},y4={event:"evt",summary:"sum"},g4=Qt.z.object({team_id:Qt.z.string().min(1,"team_id is required"),project_id:Qt.z.string().min(1,"project_id is required"),source_type:Qt.z.enum(["agent_event","session_summary","observation_reindex"]),source_id:Qt.z.string().min(1,"source_id is required"),generation_job_id:Qt.z.string().min(1,"generation_job_id is required"),api_key_id:Qt.z.string().min(1).nullable(),actor_id:Qt.z.string().min(1).nullable(),source_adapter:Qt.z.string().min(1,"source_adapter is required"),request_id:Qt.z.string().min(1).nullable().optional()}),Ime=g4.extend({kind:Qt.z.literal("event"),agent_event_id:Qt.z.string().min(1)}),kme=g4.extend({kind:Qt.z.literal("summary"),server_session_id:Qt.z.string().min(1)}),Tme=Qt.z.discriminatedUnion("kind",[Ime,kme]),Ju=class extends Error{issues;constructor(e){super(`invalid server generation job payload: ${e.map(r=>r.message).join("; ")}`),this.issues=e}}});function yc(t){let e=y4[t.kind],r=JSON.stringify({kind:t.kind,team_id:t.team_id,project_id:t.project_id,source_type:t.source_type,source_id:t.source_id}),n=(0,v4.createHash)("sha256").update(r).digest("hex");return`${e}_${n}`}var v4,v_=R(()=>{"use strict";v4=require("crypto");Lm()});function E4(t){return{kind:"event",team_id:t.event.teamId,project_id:t.event.projectId,source_type:"agent_event",source_id:t.event.id,generation_job_id:t.outboxId,agent_event_id:t.event.id,api_key_id:t.apiKeyId,actor_id:t.actorId,source_adapter:t.sourceAdapter??t.event.sourceAdapter??"api",request_id:t.requestId}}var S4,qm,x4=R(()=>{"use strict";ko();Vi();sa();he();v_();vn();S4="observation_generate_for_event",qm=class{constructor(e){this.options=e}options;async ingestOne(e,r={}){let n=r.generate??!0,i=r.source??"http_post_v1_events",s=await Sn(this.options.pool,async o=>{let l=await new Yr(o).create(e);if(!n)return{event:l,outbox:null};let u=new ut(o),d=new zt(o),p=Ye(),f=E4({outboxId:p,event:l,apiKeyId:r.apiKeyId??null,actorId:r.actorId??null,sourceAdapter:r.sourceAdapter??null,requestId:r.requestId??null}),m=await u.create({id:p,projectId:l.projectId,teamId:l.teamId,sourceType:"agent_event",sourceId:l.id,agentEventId:l.id,serverSessionId:l.serverSessionId,jobType:S4,bullmqJobId:yc({kind:"event",team_id:l.teamId,project_id:l.projectId,source_type:"agent_event",source_id:l.id}),payload:f});return await d.append({generationJobId:m.id,projectId:m.projectId,teamId:m.teamId,eventType:"queued",statusAfter:m.status,attempt:m.attempts,details:{source:i}}),{event:l,outbox:m}}),a="skipped";return s.outbox&&(a=await this.publishEventJob(s.event,s.outbox)),{event:s.event,outbox:s.outbox,enqueueState:a}}async ingestBatch(e,r={}){let n=r.generate??!0,i=r.source??"http_post_v1_events_batch",s=await Sn(this.options.pool,async a=>{let o=new Yr(a),c=new ut(a),l=new zt(a),u=[];for(let d of e){let p=await o.create(d);if(!n){u.push({event:p,outbox:null});continue}let f=Ye(),m=E4({outboxId:f,event:p,apiKeyId:r.apiKeyId??null,actorId:r.actorId??null,sourceAdapter:r.sourceAdapter??null,requestId:r.requestId??null}),g=await c.create({id:f,projectId:p.projectId,teamId:p.teamId,sourceType:"agent_event",sourceId:p.id,agentEventId:p.id,serverSessionId:p.serverSessionId,jobType:S4,bullmqJobId:yc({kind:"event",team_id:p.teamId,project_id:p.projectId,source_type:"agent_event",source_id:p.id}),payload:m});await l.append({generationJobId:g.id,projectId:g.projectId,teamId:g.teamId,eventType:"queued",statusAfter:g.status,attempt:g.attempts,details:{source:i}}),u.push({event:p,outbox:g})}return u});return Promise.all(s.map(async({event:a,outbox:o})=>{let c=o?await this.publishEventJob(a,o):"skipped";return{event:a,outbox:o,enqueueState:c}}))}async publishEventJob(e,r){let n=this.options.resolveEventQueue();if(!n)return"queued_only";let i=r.bullmqJobId??yc({kind:"event",team_id:e.teamId,project_id:e.projectId,source_type:"agent_event",source_id:e.id});try{return await n.add(i,r.payload),"enqueued"}catch(s){return w.warn("SYSTEM","failed to publish event generation job to BullMQ",{outboxId:r.id,error:s instanceof Error?s.message:String(s)}),"queued_only"}}}});function E_(t){return yc({kind:"summary",team_id:t.teamId,project_id:t.projectId,source_type:"session_summary",source_id:t.serverSessionId})}function S_(t){return{kind:"summary",team_id:t.teamId,project_id:t.projectId,source_type:"session_summary",source_id:t.serverSessionId,generation_job_id:t.generationJobId,server_session_id:t.serverSessionId,api_key_id:t.apiKeyId??null,actor_id:t.actorId??null,source_adapter:t.sourceAdapter??"api",request_id:t.requestId??null}}var w4=R(()=>{"use strict";v_()});var Ame,Fm,_4=R(()=>{"use strict";Vi();sa();us();he();w4();vn();Ame="observation_generate_session_summary",Fm=class{constructor(e){this.options=e}options;async end(e){let r=e.source??"http_post_v1_sessions_end",n=await Sn(this.options.pool,async s=>{let o=await new Wt(s).endSession({id:e.sessionId,projectId:e.projectId,teamId:e.teamId});if(!o)return{session:null,outbox:null};let c=new ut(s),l=new zt(s),u=Ye(),d=S_({serverSessionId:o.id,teamId:o.teamId,projectId:o.projectId,generationJobId:u,apiKeyId:e.apiKeyId??null,actorId:e.actorId??null,sourceAdapter:e.sourceAdapter??null}),p=await c.create({id:u,projectId:o.projectId,teamId:o.teamId,sourceType:"session_summary",sourceId:o.id,serverSessionId:o.id,jobType:Ame,bullmqJobId:E_({serverSessionId:o.id,teamId:o.teamId,projectId:o.projectId}),payload:d});return await l.append({generationJobId:p.id,projectId:p.projectId,teamId:p.teamId,eventType:"queued",statusAfter:p.status,attempt:p.attempts,details:{source:r}}),{session:o,outbox:p}});if(!n.session||!n.outbox)return{session:n.session,outbox:null,enqueueState:"skipped"};let i=await this.publishSummaryJob(n.session.id,n.outbox,e);return{session:n.session,outbox:n.outbox,enqueueState:i}}async publishSummaryJob(e,r,n){let i=this.options.resolveSummaryQueue();if(!i)return"queued_only";let s=r.bullmqJobId??E_({serverSessionId:e,teamId:r.teamId,projectId:r.projectId}),a=S_({serverSessionId:e,teamId:r.teamId,projectId:r.projectId,generationJobId:r.id,apiKeyId:n.apiKeyId??null,actorId:n.actorId??null,sourceAdapter:n.sourceAdapter??null});try{return await i.add(s,a),"enqueued"}catch(o){return w.warn("SYSTEM","failed to publish summary generation job to BullMQ",{outboxId:r.id,error:o instanceof Error?o.message:String(o)}),"queued_only"}}}});function I4(t){return`${(process.env.CLAUDE_MEM_PUBLIC_URL??`${t.protocol}://${t.get("host")??"localhost"}`).replace(/\/+$/,"")}/v1/mcp`}function k4(t,e){return`claude mcp add --transport http claude-mem ${t} --header "Authorization: Bearer ${e}"`}async function R4(t,e,r=K4,n=jme){if(A4.includes(e.status))return{job:e,timedOut:!1};let i=Date.now()+r,s=e;for(;Date.now()<i;){await new Promise(o=>setTimeout(o,n));let a=await t.getByIdForScope({id:e.id,projectId:e.projectId,teamId:e.teamId});if(!a)return{job:s,timedOut:!1};if(s=a,A4.includes(a.status))return{job:a,timedOut:!1}}return{job:s,timedOut:!0}}function Kme(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&P4.has(e)?e:null,n=typeof t.query.source_type=="string"?t.query.source_type.trim():"",i=n&&Cme.has(n)?n:null,s=Jm(t.query.limit,D4,1,M4),a=Jm(t.query.offset,0,0,Number.MAX_SAFE_INTEGER),o=typeof t.query.since=="string"?t.query.since.trim():"",c=null;if(o){let l=new Date(o);Number.isNaN(l.getTime())||(c=l)}return{status:r,sourceType:i,limit:s,offset:a,since:c}}function O4(t){if(!t||typeof t!="object")return 0;let e=t.retried_count;return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function j4(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&P4.has(e)?e:null,n=Jm(t.query.limit,D4,1,M4),i=Jm(t.query.offset,0,0,Number.MAX_SAFE_INTEGER);return{status:r,limit:n,offset:i}}function Jm(t,e,r,n){if(typeof t!="string")return e;let i=Number.parseInt(t,10);return Number.isFinite(i)?Math.max(r,Math.min(n,i)):e}function x_(t,e={}){let r={id:t.id,projectId:t.project_id,teamId:t.team_id,sourceType:t.source_type,sourceId:t.source_id,status:t.status,attempts:t.attempts,maxAttempts:t.max_attempts,createdAtEpoch:new Date(t.created_at).getTime(),completedAtEpoch:t.completed_at?new Date(t.completed_at).getTime():null,failedAtEpoch:t.failed_at?new Date(t.failed_at).getTime():null,lastError:t.last_error&&typeof t.last_error=="object"?t.last_error:null};return e.includePayload&&t.payload&&typeof t.payload=="object"&&(r.payload=t.payload),r}function Pme(t){let e={"event.received":"agent_event","event.batch_received":"agent_event","event.write":"agent_event","event.batch_write":"agent_event","session.write":"server_session","session.end":"server_session","memory.write":"observation","observation.read":"observation","observation.search":"observation","observation.context":"observation","observation.generated":"observation","session_summary.generated":"observation","generation_job.queued":"observation_generation_job","generation_job.enqueued":"observation_generation_job","generation_job.processing":"observation_generation_job","generation_job.completed":"observation_generation_job","generation_job.failed":"observation_generation_job","generation_job.scope_violation":"observation_generation_job","generation_job.revoked_key":"observation_generation_job","generation_job.retried_by_operator":"observation_generation_job","generation_job.cancelled_by_operator":"observation_generation_job","generation_job.stalled":"observation_generation_job"};return e[t]?e[t]:t.split(".")[0]??"unknown"}function Dme(t,e){let r=t.authContext?.projectId??null;if(!(t.authContext?.teamId??null))return{status:403,body:{error:"Forbidden",message:"API key is not bound to a team"}};if(!r)return null;for(let i of e)if(i.projectId!==r)return{status:403,body:{error:"Forbidden",message:"API key is scoped to a different project"}};return null}function Uu(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,externalSessionId:t.externalSessionId,contentSessionId:t.contentSessionId,agentId:t.agentId,agentType:t.agentType,platformSource:t.platformSource,generationStatus:t.generationStatus,metadata:t.metadata,startedAtEpoch:t.startedAtEpoch,endedAtEpoch:t.endedAtEpoch,lastGeneratedAtEpoch:t.lastGeneratedAtEpoch,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function zu(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,serverSessionId:t.serverSessionId,sourceAdapter:t.sourceAdapter,sourceEventId:t.sourceEventId,eventType:t.eventType,platformSource:t.platformSource,payload:t.payload,metadata:t.metadata,occurredAtEpoch:t.occurredAtEpoch,receivedAtEpoch:t.receivedAtEpoch,createdAtEpoch:t.createdAtEpoch}}function gc(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,serverSessionId:t.serverSessionId,kind:t.kind,content:t.content,metadata:t.metadata,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function Mme(t){return{id:t.id,projectId:t.project_id,teamId:t.team_id,serverSessionId:t.server_session_id,kind:t.kind,content:t.content,metadata:t.metadata&&typeof t.metadata=="object"?t.metadata:{},generationKey:t.generation_key,createdByJobId:t.created_by_job_id,createdAtEpoch:new Date(t.created_at).getTime(),updatedAtEpoch:new Date(t.updated_at).getTime(),source:{id:t.source_id_pk,sourceType:t.source_type,sourceId:t.source_id,generationJobId:t.generation_job_id,createdAtEpoch:new Date(t.source_created_at).getTime()}}}function w_(t,e){return{id:t.id,status:t.status,bullmqJobId:t.bullmqJobId,sourceType:t.sourceType,sourceId:t.sourceId,transport:e,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function C4(t,e){return{id:t.id,status:t.status,transport:e,bullmqJobId:t.bullmqJobId,sourceType:t.sourceType,sourceId:t.sourceId,attempts:t.attempts,maxAttempts:t.maxAttempts,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function __(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,sourceType:t.sourceType,sourceId:t.sourceId,agentEventId:t.agentEventId,serverSessionId:t.serverSessionId,jobType:t.jobType,status:t.status,bullmqJobId:t.bullmqJobId,attempts:t.attempts,maxAttempts:t.maxAttempts,nextAttemptAtEpoch:t.nextAttemptAtEpoch,completedAtEpoch:t.completedAtEpoch,failedAtEpoch:t.failedAtEpoch,cancelledAtEpoch:t.cancelledAtEpoch,lastError:t.lastError,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}var ce,Um,Rme,Ome,T4,K4,jme,A4,$m,Cme,P4,D4,M4,N4=R(()=>{"use strict";ce=require("zod");gD();ko();Vi();yi();Fl();To();he();rf();ES();TN();ZN();u4();p4();m4();Ea();Um=require("node:crypto");us();x4();_4();Zs();Rme="api",Ome="13.12.2";T4=ce.z.object({generate:ce.z.union([ce.z.literal("true"),ce.z.literal("false")]).optional(),wait:ce.z.union([ce.z.literal("true"),ce.z.literal("false")]).optional()}),K4=3e4,jme=100,A4=["completed","failed","cancelled"];$m=class{constructor(e){this.options=e;this.ingestEvents=new qm({pool:e.pool,resolveEventQueue:()=>this.resolveQueue("event")}),this.endSession=new Fm({pool:e.pool,resolveSummaryQueue:()=>this.resolveQueue("summary")})}options;ingestEvents;endSession;getIngestEventsService(){return this.ingestEvents}getEndSessionService(){return this.endSession}setupRoutes(e){e.use("/v1",kN());let r=ta(this.options.pool,{authMode:this.options.authMode,allowLocalDevBypass:this.options.allowLocalDevBypass,requiredScopes:["memories:write"]}),n=ta(this.options.pool,{authMode:this.options.authMode,allowLocalDevBypass:this.options.allowLocalDevBypass,requiredScopes:["memories:read"]}),i=[],s=Number(process.env.CLAUDE_MEM_RATE_LIMIT_PER_MIN??"0");s>0&&i.push(d4(this.options.pool,{windowSec:60,max:s}));let a=Number(process.env.CLAUDE_MEM_MONTHLY_REQUEST_CAP??"0");a>0&&i.push(b_(this.options.pool,{kind:"request",cap:a})),process.env.CLAUDE_MEM_USAGE_METERING==="1"&&i.push(f4(this.options.pool));let o=[...i],c=Number(process.env.CLAUDE_MEM_MONTHLY_TOKEN_CAP??"0");c>0&&o.push(b_(this.options.pool,{kind:"tokens",cap:c}));let l=[r,...o],u=[n,...i];e.get("/v1/usage",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let g=new Date(Date.UTC(new Date().getUTCFullYear(),new Date().getUTCMonth(),1)),b=await new Rr(this.options.pool).summarize({teamId:m,since:g});f.status(200).json({since:g.toISOString(),usage:b})})),e.post("/v1/keys",l,this.handleCreate(ce.z.object({label:ce.z.string().max(120).optional(),expiresInDays:ce.z.number().int().positive().max(365).optional()}),async(p,f,m)=>{let g=this.requireTeamId(p,f);if(!g)return;let b=`cm_${(0,Um.randomBytes)(24).toString("hex")}`,v=(0,Um.createHash)("sha256").update(b).digest("hex"),E=m.expiresInDays?new Date(Date.now()+m.expiresInDays*864e5):null,S=await new Dt(this.options.pool).createApiKey({keyHash:v,teamId:g,projectId:p.authContext?.projectId??null,actorId:p.authContext?.apiKeyId??"api",scopes:["memories:read"],expiresAt:E});m.label;let k=I4(p);f.status(201).json({id:S.id,apiKey:b,scopes:["memories:read"],expiresAt:E?.toISOString()??null,mcpUrl:k,connectCommand:k4(k,b)})})),e.get("/v1/connect",u,this.asyncHandler(async(p,f)=>{if(!this.requireTeamId(p,f))return;let g=I4(p);f.status(200).json({mcpUrl:g,connectCommand:k4(g,"<YOUR_API_KEY>"),hint:"POST /v1/keys (write scope) to mint a read-only key for this link."})})),e.post("/v1/events",l,this.asyncHandler(async(p,f)=>{let m=T4.safeParse(p.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let g=m.data.generate!=="false",b=m.data.wait==="true",v=pE.safeParse(p.body);if(!v.success){f.status(400).json({error:"ValidationError",issues:v.error.issues});return}let E=v.data,S=this.requireTeamId(p,f);if(!S||!this.ensureProjectAllowed(p,f,E.projectId))return;let k=this.toAgentEventInput(E,S);await this.applyContentSessionLinks([k],[p.body],S);let A,C=null,L="skipped",te={generate:g,source:"http_post_v1_events",apiKeyId:p.authContext?.apiKeyId??null,actorId:await this.resolveActorId(p),sourceAdapter:k.sourceAdapter,requestId:p.requestId??null};try{let q=await this.ingestEvents.ingestOne(k,te);A=q.event,C=q.outbox,L=q.enqueueState}catch(q){let J=q instanceof Error?q:new Error(String(q));w.warn("SYSTEM","event.write ingest failed",{requestId:p.requestId??null},J),this.handleDbError(J,f,"event.write");return}if(await this.auditWrite(p,"event.received",A.id,A.projectId,{sourceAdapter:A.sourceAdapter,sourceEventId:A.sourceEventId,eventType:A.eventType,serverSessionId:A.serverSessionId,generationJobId:C?.id??null}),b){let q=C,J=!1;if(C){let re=new ut(this.options.pool),at=await R4(re,C);q=at.job,J=at.timedOut}f.status(201).json({event:zu(A),generationJob:q?C4(q,L):null,...J?{waitTimedOut:!0}:{}});return}f.status(201).json({event:zu(A),...C?{generationJob:w_(C,L)}:{}})})),e.post("/v1/events/batch",l,this.asyncHandler(async(p,f)=>{let m=T4.safeParse(p.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let g=m.data.generate!=="false",b=m.data.wait==="true",E=ce.z.array(pE).min(1).max(500).safeParse(p.body);if(!E.success){f.status(400).json({error:"ValidationError",issues:E.error.issues});return}let S=this.requireTeamId(p,f);if(!S)return;let k=Dme(p,E.data);if(k){f.status(k.status).json(k.body);return}let A=E.data.map(q=>this.toAgentEventInput(q,S));await this.applyContentSessionLinks(A,Array.isArray(p.body)?p.body:E.data,S);let C=[],L=[],te={generate:g,source:"http_post_v1_events_batch",apiKeyId:p.authContext?.apiKeyId??null,actorId:await this.resolveActorId(p),sourceAdapter:null,requestId:p.requestId??null};try{let q=await this.ingestEvents.ingestBatch(A,te);C=q.map(({event:J,outbox:re})=>({event:J,outbox:re})),L=q.map(({enqueueState:J})=>J)}catch(q){let J=q instanceof Error?q:new Error(String(q));w.warn("SYSTEM","event.batch_write ingest failed",{requestId:p.requestId??null},J),this.handleDbError(J,f,"event.batch_write");return}if(await this.auditWrite(p,"event.batch_received",null,null,{eventCount:C.length,generationJobIds:C.map(({outbox:q})=>q?.id??null).filter(Boolean)}),b){let q=new ut(this.options.pool),J=Date.now()+K4,re=[];for(let _ of C){if(!_.outbox){re.push({event:_.event,outbox:null,timedOut:!1});continue}let P=Math.max(0,J-Date.now()),O=await R4(q,_.outbox,P);re.push({event:_.event,outbox:O.job,timedOut:O.timedOut})}let at=re.some(_=>_.timedOut);f.status(201).json({events:re.map(({event:_,outbox:P,timedOut:O},j)=>({event:zu(_),generationJob:P?C4(P,L[j]):null,...O?{waitTimedOut:!0}:{}})),...at?{waitTimedOut:!0}:{}});return}f.status(201).json({events:C.map(({event:q,outbox:J},re)=>({event:zu(q),...J?{generationJob:w_(J,L[re])}:{}}))})})),e.get("/v1/events/:id",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let g=this.routeParam(p.params.id),b=new Yr(this.options.pool),v=await this.loadScopedById(p,f,{id:g,teamId:m,table:"agent_events",notFound:"Event not found",load:E=>b.getByIdForScope({id:g,projectId:E,teamId:m})});v&&f.json({event:zu(v)})})),e.get("/v1/events/:id/observations",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let g=this.routeParam(p.params.id),v=(await this.options.pool.query("SELECT id, project_id FROM agent_events WHERE id = $1 AND team_id = $2",[g,m])).rows[0];if(!v){f.status(404).json({error:"NotFound",message:"Event not found"});return}if(!this.ensureProjectAllowed(p,f,v.project_id))return;let E=await this.options.pool.query(`
|
|
348
|
+
`,[e.serverSessionId,e.projectId,e.teamId,r])).rows.map(_me)}}});function b4(t){let e=Tme.safeParse(t);if(!e.success)throw new Ju(e.error.issues);return e.data}var Qt,hc,y4,g4,Ime,kme,Tme,Ju,Lm=R(()=>{"use strict";Qt=require("zod"),hc={event:"server_beta_generate_event",summary:"server_beta_generate_summary"},y4={event:"evt",summary:"sum"},g4=Qt.z.object({team_id:Qt.z.string().min(1,"team_id is required"),project_id:Qt.z.string().min(1,"project_id is required"),source_type:Qt.z.enum(["agent_event","session_summary","observation_reindex"]),source_id:Qt.z.string().min(1,"source_id is required"),generation_job_id:Qt.z.string().min(1,"generation_job_id is required"),api_key_id:Qt.z.string().min(1).nullable(),actor_id:Qt.z.string().min(1).nullable(),source_adapter:Qt.z.string().min(1,"source_adapter is required"),request_id:Qt.z.string().min(1).nullable().optional()}),Ime=g4.extend({kind:Qt.z.literal("event"),agent_event_id:Qt.z.string().min(1)}),kme=g4.extend({kind:Qt.z.literal("summary"),server_session_id:Qt.z.string().min(1)}),Tme=Qt.z.discriminatedUnion("kind",[Ime,kme]),Ju=class extends Error{issues;constructor(e){super(`invalid server generation job payload: ${e.map(r=>r.message).join("; ")}`),this.issues=e}}});function yc(t){let e=y4[t.kind],r=JSON.stringify({kind:t.kind,team_id:t.team_id,project_id:t.project_id,source_type:t.source_type,source_id:t.source_id}),n=(0,v4.createHash)("sha256").update(r).digest("hex");return`${e}_${n}`}var v4,v_=R(()=>{"use strict";v4=require("crypto");Lm()});function E4(t){return{kind:"event",team_id:t.event.teamId,project_id:t.event.projectId,source_type:"agent_event",source_id:t.event.id,generation_job_id:t.outboxId,agent_event_id:t.event.id,api_key_id:t.apiKeyId,actor_id:t.actorId,source_adapter:t.sourceAdapter??t.event.sourceAdapter??"api",request_id:t.requestId}}var S4,qm,x4=R(()=>{"use strict";ko();Vi();sa();he();v_();vn();S4="observation_generate_for_event",qm=class{constructor(e){this.options=e}options;async ingestOne(e,r={}){let n=r.generate??!0,i=r.source??"http_post_v1_events",s=await Sn(this.options.pool,async o=>{let l=await new Yr(o).create(e);if(!n)return{event:l,outbox:null};let u=new ut(o),d=new zt(o),p=Ye(),f=E4({outboxId:p,event:l,apiKeyId:r.apiKeyId??null,actorId:r.actorId??null,sourceAdapter:r.sourceAdapter??null,requestId:r.requestId??null}),m=await u.create({id:p,projectId:l.projectId,teamId:l.teamId,sourceType:"agent_event",sourceId:l.id,agentEventId:l.id,serverSessionId:l.serverSessionId,jobType:S4,bullmqJobId:yc({kind:"event",team_id:l.teamId,project_id:l.projectId,source_type:"agent_event",source_id:l.id}),payload:f});return await d.append({generationJobId:m.id,projectId:m.projectId,teamId:m.teamId,eventType:"queued",statusAfter:m.status,attempt:m.attempts,details:{source:i}}),{event:l,outbox:m}}),a="skipped";return s.outbox&&(a=await this.publishEventJob(s.event,s.outbox)),{event:s.event,outbox:s.outbox,enqueueState:a}}async ingestBatch(e,r={}){let n=r.generate??!0,i=r.source??"http_post_v1_events_batch",s=await Sn(this.options.pool,async a=>{let o=new Yr(a),c=new ut(a),l=new zt(a),u=[];for(let d of e){let p=await o.create(d);if(!n){u.push({event:p,outbox:null});continue}let f=Ye(),m=E4({outboxId:f,event:p,apiKeyId:r.apiKeyId??null,actorId:r.actorId??null,sourceAdapter:r.sourceAdapter??null,requestId:r.requestId??null}),g=await c.create({id:f,projectId:p.projectId,teamId:p.teamId,sourceType:"agent_event",sourceId:p.id,agentEventId:p.id,serverSessionId:p.serverSessionId,jobType:S4,bullmqJobId:yc({kind:"event",team_id:p.teamId,project_id:p.projectId,source_type:"agent_event",source_id:p.id}),payload:m});await l.append({generationJobId:g.id,projectId:g.projectId,teamId:g.teamId,eventType:"queued",statusAfter:g.status,attempt:g.attempts,details:{source:i}}),u.push({event:p,outbox:g})}return u});return Promise.all(s.map(async({event:a,outbox:o})=>{let c=o?await this.publishEventJob(a,o):"skipped";return{event:a,outbox:o,enqueueState:c}}))}async publishEventJob(e,r){let n=this.options.resolveEventQueue();if(!n)return"queued_only";let i=r.bullmqJobId??yc({kind:"event",team_id:e.teamId,project_id:e.projectId,source_type:"agent_event",source_id:e.id});try{return await n.add(i,r.payload),"enqueued"}catch(s){return w.warn("SYSTEM","failed to publish event generation job to BullMQ",{outboxId:r.id,error:s instanceof Error?s.message:String(s)}),"queued_only"}}}});function E_(t){return yc({kind:"summary",team_id:t.teamId,project_id:t.projectId,source_type:"session_summary",source_id:t.serverSessionId})}function S_(t){return{kind:"summary",team_id:t.teamId,project_id:t.projectId,source_type:"session_summary",source_id:t.serverSessionId,generation_job_id:t.generationJobId,server_session_id:t.serverSessionId,api_key_id:t.apiKeyId??null,actor_id:t.actorId??null,source_adapter:t.sourceAdapter??"api",request_id:t.requestId??null}}var w4=R(()=>{"use strict";v_()});var Ame,Fm,_4=R(()=>{"use strict";Vi();sa();us();he();w4();vn();Ame="observation_generate_session_summary",Fm=class{constructor(e){this.options=e}options;async end(e){let r=e.source??"http_post_v1_sessions_end",n=await Sn(this.options.pool,async s=>{let o=await new Wt(s).endSession({id:e.sessionId,projectId:e.projectId,teamId:e.teamId});if(!o)return{session:null,outbox:null};let c=new ut(s),l=new zt(s),u=Ye(),d=S_({serverSessionId:o.id,teamId:o.teamId,projectId:o.projectId,generationJobId:u,apiKeyId:e.apiKeyId??null,actorId:e.actorId??null,sourceAdapter:e.sourceAdapter??null}),p=await c.create({id:u,projectId:o.projectId,teamId:o.teamId,sourceType:"session_summary",sourceId:o.id,serverSessionId:o.id,jobType:Ame,bullmqJobId:E_({serverSessionId:o.id,teamId:o.teamId,projectId:o.projectId}),payload:d});return await l.append({generationJobId:p.id,projectId:p.projectId,teamId:p.teamId,eventType:"queued",statusAfter:p.status,attempt:p.attempts,details:{source:r}}),{session:o,outbox:p}});if(!n.session||!n.outbox)return{session:n.session,outbox:null,enqueueState:"skipped"};let i=await this.publishSummaryJob(n.session.id,n.outbox,e);return{session:n.session,outbox:n.outbox,enqueueState:i}}async publishSummaryJob(e,r,n){let i=this.options.resolveSummaryQueue();if(!i)return"queued_only";let s=r.bullmqJobId??E_({serverSessionId:e,teamId:r.teamId,projectId:r.projectId}),a=S_({serverSessionId:e,teamId:r.teamId,projectId:r.projectId,generationJobId:r.id,apiKeyId:n.apiKeyId??null,actorId:n.actorId??null,sourceAdapter:n.sourceAdapter??null});try{return await i.add(s,a),"enqueued"}catch(o){return w.warn("SYSTEM","failed to publish summary generation job to BullMQ",{outboxId:r.id,error:o instanceof Error?o.message:String(o)}),"queued_only"}}}});function I4(t){return`${(process.env.CLAUDE_MEM_PUBLIC_URL??`${t.protocol}://${t.get("host")??"localhost"}`).replace(/\/+$/,"")}/v1/mcp`}function k4(t,e){return`claude mcp add --transport http claude-mem ${t} --header "Authorization: Bearer ${e}"`}async function R4(t,e,r=K4,n=jme){if(A4.includes(e.status))return{job:e,timedOut:!1};let i=Date.now()+r,s=e;for(;Date.now()<i;){await new Promise(o=>setTimeout(o,n));let a=await t.getByIdForScope({id:e.id,projectId:e.projectId,teamId:e.teamId});if(!a)return{job:s,timedOut:!1};if(s=a,A4.includes(a.status))return{job:a,timedOut:!1}}return{job:s,timedOut:!0}}function Kme(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&P4.has(e)?e:null,n=typeof t.query.source_type=="string"?t.query.source_type.trim():"",i=n&&Cme.has(n)?n:null,s=Jm(t.query.limit,D4,1,M4),a=Jm(t.query.offset,0,0,Number.MAX_SAFE_INTEGER),o=typeof t.query.since=="string"?t.query.since.trim():"",c=null;if(o){let l=new Date(o);Number.isNaN(l.getTime())||(c=l)}return{status:r,sourceType:i,limit:s,offset:a,since:c}}function O4(t){if(!t||typeof t!="object")return 0;let e=t.retried_count;return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function j4(t){let e=typeof t.query.status=="string"?t.query.status.trim():"",r=e&&P4.has(e)?e:null,n=Jm(t.query.limit,D4,1,M4),i=Jm(t.query.offset,0,0,Number.MAX_SAFE_INTEGER);return{status:r,limit:n,offset:i}}function Jm(t,e,r,n){if(typeof t!="string")return e;let i=Number.parseInt(t,10);return Number.isFinite(i)?Math.max(r,Math.min(n,i)):e}function x_(t,e={}){let r={id:t.id,projectId:t.project_id,teamId:t.team_id,sourceType:t.source_type,sourceId:t.source_id,status:t.status,attempts:t.attempts,maxAttempts:t.max_attempts,createdAtEpoch:new Date(t.created_at).getTime(),completedAtEpoch:t.completed_at?new Date(t.completed_at).getTime():null,failedAtEpoch:t.failed_at?new Date(t.failed_at).getTime():null,lastError:t.last_error&&typeof t.last_error=="object"?t.last_error:null};return e.includePayload&&t.payload&&typeof t.payload=="object"&&(r.payload=t.payload),r}function Pme(t){let e={"event.received":"agent_event","event.batch_received":"agent_event","event.write":"agent_event","event.batch_write":"agent_event","session.write":"server_session","session.end":"server_session","memory.write":"observation","observation.read":"observation","observation.search":"observation","observation.context":"observation","observation.generated":"observation","session_summary.generated":"observation","generation_job.queued":"observation_generation_job","generation_job.enqueued":"observation_generation_job","generation_job.processing":"observation_generation_job","generation_job.completed":"observation_generation_job","generation_job.failed":"observation_generation_job","generation_job.scope_violation":"observation_generation_job","generation_job.revoked_key":"observation_generation_job","generation_job.retried_by_operator":"observation_generation_job","generation_job.cancelled_by_operator":"observation_generation_job","generation_job.stalled":"observation_generation_job"};return e[t]?e[t]:t.split(".")[0]??"unknown"}function Dme(t,e){let r=t.authContext?.projectId??null;if(!(t.authContext?.teamId??null))return{status:403,body:{error:"Forbidden",message:"API key is not bound to a team"}};if(!r)return null;for(let i of e)if(i.projectId!==r)return{status:403,body:{error:"Forbidden",message:"API key is scoped to a different project"}};return null}function Uu(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,externalSessionId:t.externalSessionId,contentSessionId:t.contentSessionId,agentId:t.agentId,agentType:t.agentType,platformSource:t.platformSource,generationStatus:t.generationStatus,metadata:t.metadata,startedAtEpoch:t.startedAtEpoch,endedAtEpoch:t.endedAtEpoch,lastGeneratedAtEpoch:t.lastGeneratedAtEpoch,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function zu(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,serverSessionId:t.serverSessionId,sourceAdapter:t.sourceAdapter,sourceEventId:t.sourceEventId,eventType:t.eventType,platformSource:t.platformSource,payload:t.payload,metadata:t.metadata,occurredAtEpoch:t.occurredAtEpoch,receivedAtEpoch:t.receivedAtEpoch,createdAtEpoch:t.createdAtEpoch}}function gc(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,serverSessionId:t.serverSessionId,kind:t.kind,content:t.content,metadata:t.metadata,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function Mme(t){return{id:t.id,projectId:t.project_id,teamId:t.team_id,serverSessionId:t.server_session_id,kind:t.kind,content:t.content,metadata:t.metadata&&typeof t.metadata=="object"?t.metadata:{},generationKey:t.generation_key,createdByJobId:t.created_by_job_id,createdAtEpoch:new Date(t.created_at).getTime(),updatedAtEpoch:new Date(t.updated_at).getTime(),source:{id:t.source_id_pk,sourceType:t.source_type,sourceId:t.source_id,generationJobId:t.generation_job_id,createdAtEpoch:new Date(t.source_created_at).getTime()}}}function w_(t,e){return{id:t.id,status:t.status,bullmqJobId:t.bullmqJobId,sourceType:t.sourceType,sourceId:t.sourceId,transport:e,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function C4(t,e){return{id:t.id,status:t.status,transport:e,bullmqJobId:t.bullmqJobId,sourceType:t.sourceType,sourceId:t.sourceId,attempts:t.attempts,maxAttempts:t.maxAttempts,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}function __(t){return{id:t.id,projectId:t.projectId,teamId:t.teamId,sourceType:t.sourceType,sourceId:t.sourceId,agentEventId:t.agentEventId,serverSessionId:t.serverSessionId,jobType:t.jobType,status:t.status,bullmqJobId:t.bullmqJobId,attempts:t.attempts,maxAttempts:t.maxAttempts,nextAttemptAtEpoch:t.nextAttemptAtEpoch,completedAtEpoch:t.completedAtEpoch,failedAtEpoch:t.failedAtEpoch,cancelledAtEpoch:t.cancelledAtEpoch,lastError:t.lastError,createdAtEpoch:t.createdAtEpoch,updatedAtEpoch:t.updatedAtEpoch}}var ce,Um,Rme,Ome,T4,K4,jme,A4,$m,Cme,P4,D4,M4,N4=R(()=>{"use strict";ce=require("zod");gD();ko();Vi();yi();Fl();To();he();rf();ES();TN();ZN();u4();p4();m4();Ea();Um=require("node:crypto");us();x4();_4();Zs();Rme="api",Ome="13.12.3";T4=ce.z.object({generate:ce.z.union([ce.z.literal("true"),ce.z.literal("false")]).optional(),wait:ce.z.union([ce.z.literal("true"),ce.z.literal("false")]).optional()}),K4=3e4,jme=100,A4=["completed","failed","cancelled"];$m=class{constructor(e){this.options=e;this.ingestEvents=new qm({pool:e.pool,resolveEventQueue:()=>this.resolveQueue("event")}),this.endSession=new Fm({pool:e.pool,resolveSummaryQueue:()=>this.resolveQueue("summary")})}options;ingestEvents;endSession;getIngestEventsService(){return this.ingestEvents}getEndSessionService(){return this.endSession}setupRoutes(e){e.use("/v1",kN());let r=ta(this.options.pool,{authMode:this.options.authMode,allowLocalDevBypass:this.options.allowLocalDevBypass,requiredScopes:["memories:write"]}),n=ta(this.options.pool,{authMode:this.options.authMode,allowLocalDevBypass:this.options.allowLocalDevBypass,requiredScopes:["memories:read"]}),i=[],s=Number(process.env.CLAUDE_MEM_RATE_LIMIT_PER_MIN??"0");s>0&&i.push(d4(this.options.pool,{windowSec:60,max:s}));let a=Number(process.env.CLAUDE_MEM_MONTHLY_REQUEST_CAP??"0");a>0&&i.push(b_(this.options.pool,{kind:"request",cap:a})),process.env.CLAUDE_MEM_USAGE_METERING==="1"&&i.push(f4(this.options.pool));let o=[...i],c=Number(process.env.CLAUDE_MEM_MONTHLY_TOKEN_CAP??"0");c>0&&o.push(b_(this.options.pool,{kind:"tokens",cap:c}));let l=[r,...o],u=[n,...i];e.get("/v1/usage",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let g=new Date(Date.UTC(new Date().getUTCFullYear(),new Date().getUTCMonth(),1)),b=await new Rr(this.options.pool).summarize({teamId:m,since:g});f.status(200).json({since:g.toISOString(),usage:b})})),e.post("/v1/keys",l,this.handleCreate(ce.z.object({label:ce.z.string().max(120).optional(),expiresInDays:ce.z.number().int().positive().max(365).optional()}),async(p,f,m)=>{let g=this.requireTeamId(p,f);if(!g)return;let b=`cm_${(0,Um.randomBytes)(24).toString("hex")}`,v=(0,Um.createHash)("sha256").update(b).digest("hex"),E=m.expiresInDays?new Date(Date.now()+m.expiresInDays*864e5):null,S=await new Dt(this.options.pool).createApiKey({keyHash:v,teamId:g,projectId:p.authContext?.projectId??null,actorId:p.authContext?.apiKeyId??"api",scopes:["memories:read"],expiresAt:E});m.label;let k=I4(p);f.status(201).json({id:S.id,apiKey:b,scopes:["memories:read"],expiresAt:E?.toISOString()??null,mcpUrl:k,connectCommand:k4(k,b)})})),e.get("/v1/connect",u,this.asyncHandler(async(p,f)=>{if(!this.requireTeamId(p,f))return;let g=I4(p);f.status(200).json({mcpUrl:g,connectCommand:k4(g,"<YOUR_API_KEY>"),hint:"POST /v1/keys (write scope) to mint a read-only key for this link."})})),e.post("/v1/events",l,this.asyncHandler(async(p,f)=>{let m=T4.safeParse(p.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let g=m.data.generate!=="false",b=m.data.wait==="true",v=pE.safeParse(p.body);if(!v.success){f.status(400).json({error:"ValidationError",issues:v.error.issues});return}let E=v.data,S=this.requireTeamId(p,f);if(!S||!this.ensureProjectAllowed(p,f,E.projectId))return;let k=this.toAgentEventInput(E,S);await this.applyContentSessionLinks([k],[p.body],S);let A,C=null,L="skipped",te={generate:g,source:"http_post_v1_events",apiKeyId:p.authContext?.apiKeyId??null,actorId:await this.resolveActorId(p),sourceAdapter:k.sourceAdapter,requestId:p.requestId??null};try{let q=await this.ingestEvents.ingestOne(k,te);A=q.event,C=q.outbox,L=q.enqueueState}catch(q){let J=q instanceof Error?q:new Error(String(q));w.warn("SYSTEM","event.write ingest failed",{requestId:p.requestId??null},J),this.handleDbError(J,f,"event.write");return}if(await this.auditWrite(p,"event.received",A.id,A.projectId,{sourceAdapter:A.sourceAdapter,sourceEventId:A.sourceEventId,eventType:A.eventType,serverSessionId:A.serverSessionId,generationJobId:C?.id??null}),b){let q=C,J=!1;if(C){let re=new ut(this.options.pool),at=await R4(re,C);q=at.job,J=at.timedOut}f.status(201).json({event:zu(A),generationJob:q?C4(q,L):null,...J?{waitTimedOut:!0}:{}});return}f.status(201).json({event:zu(A),...C?{generationJob:w_(C,L)}:{}})})),e.post("/v1/events/batch",l,this.asyncHandler(async(p,f)=>{let m=T4.safeParse(p.query);if(!m.success){f.status(400).json({error:"ValidationError",issues:m.error.issues});return}let g=m.data.generate!=="false",b=m.data.wait==="true",E=ce.z.array(pE).min(1).max(500).safeParse(p.body);if(!E.success){f.status(400).json({error:"ValidationError",issues:E.error.issues});return}let S=this.requireTeamId(p,f);if(!S)return;let k=Dme(p,E.data);if(k){f.status(k.status).json(k.body);return}let A=E.data.map(q=>this.toAgentEventInput(q,S));await this.applyContentSessionLinks(A,Array.isArray(p.body)?p.body:E.data,S);let C=[],L=[],te={generate:g,source:"http_post_v1_events_batch",apiKeyId:p.authContext?.apiKeyId??null,actorId:await this.resolveActorId(p),sourceAdapter:null,requestId:p.requestId??null};try{let q=await this.ingestEvents.ingestBatch(A,te);C=q.map(({event:J,outbox:re})=>({event:J,outbox:re})),L=q.map(({enqueueState:J})=>J)}catch(q){let J=q instanceof Error?q:new Error(String(q));w.warn("SYSTEM","event.batch_write ingest failed",{requestId:p.requestId??null},J),this.handleDbError(J,f,"event.batch_write");return}if(await this.auditWrite(p,"event.batch_received",null,null,{eventCount:C.length,generationJobIds:C.map(({outbox:q})=>q?.id??null).filter(Boolean)}),b){let q=new ut(this.options.pool),J=Date.now()+K4,re=[];for(let _ of C){if(!_.outbox){re.push({event:_.event,outbox:null,timedOut:!1});continue}let P=Math.max(0,J-Date.now()),O=await R4(q,_.outbox,P);re.push({event:_.event,outbox:O.job,timedOut:O.timedOut})}let at=re.some(_=>_.timedOut);f.status(201).json({events:re.map(({event:_,outbox:P,timedOut:O},j)=>({event:zu(_),generationJob:P?C4(P,L[j]):null,...O?{waitTimedOut:!0}:{}})),...at?{waitTimedOut:!0}:{}});return}f.status(201).json({events:C.map(({event:q,outbox:J},re)=>({event:zu(q),...J?{generationJob:w_(J,L[re])}:{}}))})})),e.get("/v1/events/:id",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let g=this.routeParam(p.params.id),b=new Yr(this.options.pool),v=await this.loadScopedById(p,f,{id:g,teamId:m,table:"agent_events",notFound:"Event not found",load:E=>b.getByIdForScope({id:g,projectId:E,teamId:m})});v&&f.json({event:zu(v)})})),e.get("/v1/events/:id/observations",u,this.asyncHandler(async(p,f)=>{let m=this.requireTeamId(p,f);if(!m)return;let g=this.routeParam(p.params.id),v=(await this.options.pool.query("SELECT id, project_id FROM agent_events WHERE id = $1 AND team_id = $2",[g,m])).rows[0];if(!v){f.status(404).json({error:"NotFound",message:"Event not found"});return}if(!this.ensureProjectAllowed(p,f,v.project_id))return;let E=await this.options.pool.query(`
|
|
349
349
|
SELECT o.id, o.project_id, o.team_id, o.server_session_id, o.kind, o.content,
|
|
350
350
|
o.metadata, o.generation_key, o.created_by_job_id, o.created_at, o.updated_at,
|
|
351
351
|
os.id AS source_id_pk, os.source_type, os.source_id, os.generation_job_id, os.created_at AS source_created_at
|