@bjlee2024/claude-mem 13.4.19 → 13.4.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/dist/npx-cli/index.js +4 -3
- 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/context-generator.cjs +4 -3
- package/plugin/scripts/mcp-server.cjs +5 -4
- package/plugin/scripts/server-beta-service.cjs +6 -5
- package/plugin/scripts/worker-service.cjs +7 -6
|
@@ -51,15 +51,16 @@ return fn.apply(this, arguments)
|
|
|
51
51
|
<pre>`+e+`</pre>
|
|
52
52
|
</body>
|
|
53
53
|
</html>
|
|
54
|
-
`}function q9(){return function(){this.error(404)}}function F9(){return function(e){if(this.hasTrailingSlash()){this.error(404);return}var t=Gy.original(this.req);t.path=null,t.pathname=N9(t.pathname+"/");var n=C9(M9.format(t)),i=L9("Redirecting","Redirecting to "+K9(n));e.statusCode=301,e.setHeader("Content-Type","text/html; charset=UTF-8"),e.setHeader("Content-Length",Buffer.byteLength(i)),e.setHeader("Content-Security-Policy","default-src 'none'"),e.setHeader("X-Content-Type-Options","nosniff"),e.setHeader("Location",n),e.end(i)}}});var xA=h((ur,SA)=>{"use strict";var Yl=ZI(),J9=require("node:events").EventEmitter,yA=tT(),bA=a1(),gA=_y(),vA=P1(),EA=fA();ur=SA.exports=U9;function U9(){var r=function(e,t,n){r.handle(e,t,n)};return yA(r,J9.prototype,!1),yA(r,bA,!1),r.request=Object.create(vA,{app:{configurable:!0,enumerable:!0,writable:!0,value:r}}),r.response=Object.create(EA,{app:{configurable:!0,enumerable:!0,writable:!0,value:r}}),r.init(),r}ur.application=bA;ur.request=vA;ur.response=EA;ur.Route=gA.Route;ur.Router=gA;ur.json=Yl.json;ur.raw=Yl.raw;ur.static=hA();ur.text=Yl.text;ur.urlencoded=Yl.urlencoded});var zl=h(($pe,_A)=>{"use strict";_A.exports=xA()});var By,wA,IA=R(()=>{"use strict";By=["search","context","summarize","import","export"],wA=["workflow","search_params","examples","all"]});function G9(){return typeof __dirname<"u"?__dirname:(0,le.dirname)((0,TA.fileURLToPath)(eV.url))}function $9(){if(process.env.CLAUDE_MEM_DATA_DIR)return process.env.CLAUDE_MEM_DATA_DIR;let r=(0,le.join)((0,$y.homedir)(),".claude-mem"),e=(0,le.join)(r,"settings.json");try{if((0,_a.existsSync)(e)){let t=JSON.parse((0,_a.readFileSync)(e,"utf-8")),n=t.env??t;if(n.CLAUDE_MEM_DATA_DIR)return n.CLAUDE_MEM_DATA_DIR}}catch{}return r}function Fi(){return(0,le.join)(B9,"..")}var le,$y,_a,TA,eV,B9,Oe,Us,Ype,H9,V9,W9,Y9,z9,dr,Q9,X9,AA,Z9,zpe,Qpe,Xpe,Pe,kt=R(()=>{"use strict";le=require("path"),$y=require("os"),_a=require("fs"),TA=require("url");se();eV={};B9=G9();Oe=$9(),Us=process.env.CLAUDE_CONFIG_DIR||(0,le.join)((0,$y.homedir)(),".claude"),Ype=(0,le.join)(Us,"plugins","marketplaces","bjlee2024"),H9=(0,le.join)(Oe,"archives"),V9=(0,le.join)(Oe,"logs"),W9=(0,le.join)(Oe,"trash"),Y9=(0,le.join)(Oe,"backups"),z9=(0,le.join)(Oe,"modes"),dr=(0,le.join)(Oe,"settings.json"),Q9=(0,le.join)(Oe,"claude-mem.db"),X9=(0,le.join)(Oe,"vector-db"),AA=(0,le.join)(Oe,"observer-sessions"),Z9=(0,le.basename)(AA),zpe=(0,le.join)(Us,"settings.json"),Qpe=(0,le.join)(Us,"commands"),Xpe=(0,le.join)(Us,"CLAUDE.md");Pe={dataDir:()=>Oe,workerPid:()=>(0,le.join)(Oe,"worker.pid"),serverBetaPid:()=>(0,le.join)(Oe,".server-beta.pid"),serverBetaPort:()=>(0,le.join)(Oe,".server-beta.port"),serverBetaRuntime:()=>(0,le.join)(Oe,".server-beta.runtime.json"),settings:()=>(0,le.join)(Oe,"settings.json"),database:()=>(0,le.join)(Oe,"claude-mem.db"),chroma:()=>(0,le.join)(Oe,"chroma"),combinedCerts:()=>(0,le.join)(Oe,"combined_certs.pem"),transcriptsConfig:()=>(0,le.join)(Oe,"transcript-watch.json"),transcriptsState:()=>(0,le.join)(Oe,"transcript-watch-state.json"),corpora:()=>(0,le.join)(Oe,"corpora"),supervisorRegistry:()=>(0,le.join)(Oe,"supervisor.json"),envFile:()=>(0,le.join)(Oe,".env"),logsDir:()=>V9,archives:()=>H9,trash:()=>W9,backups:()=>Y9,modes:()=>z9,vectorDb:()=>X9,observerSessions:()=>AA}});function rV(r){return(tV??process.stderr.write.bind(process.stderr))(r)}function Hy(r){rV(r)}var tV,kA=R(()=>{"use strict";tV=null});var bn,OA,Vy,Wy,_,se=R(()=>{"use strict";bn=require("fs"),OA=require("path");kt();kA();Vy=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.WARN=2]="WARN",s[s.ERROR=3]="ERROR",s[s.SILENT=4]="SILENT",s))(Vy||{}),Wy=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){if(!this.logFileInitialized){this.logFileInitialized=!0;try{let e=Pe.logsDir();(0,bn.existsSync)(e)||(0,bn.mkdirSync)(e,{recursive:!0});let t=new Date().toISOString().split("T")[0];this.logFilePath=(0,OA.join)(e,`claude-mem-${t}.log`)}catch(e){console.error("[LOGGER] Failed to initialize log file:",e instanceof Error?e.message:String(e)),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let e=Pe.settings();if((0,bn.existsSync)(e)){let t=(0,bn.readFileSync)(e,"utf-8"),i=(JSON.parse(t).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=Vy[i]??1}else this.level=1}catch(e){console.error("[LOGGER] Failed to load log level from settings:",e instanceof Error?e.message:String(e)),this.level=1}return this.level}correlationId(e,t){return`obs-${e}-${t}`}sessionId(e){return`session-${e}`}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.getLevel()===0?`${e.message}
|
|
54
|
+
`}function q9(){return function(){this.error(404)}}function F9(){return function(e){if(this.hasTrailingSlash()){this.error(404);return}var t=Gy.original(this.req);t.path=null,t.pathname=N9(t.pathname+"/");var n=C9(M9.format(t)),i=L9("Redirecting","Redirecting to "+K9(n));e.statusCode=301,e.setHeader("Content-Type","text/html; charset=UTF-8"),e.setHeader("Content-Length",Buffer.byteLength(i)),e.setHeader("Content-Security-Policy","default-src 'none'"),e.setHeader("X-Content-Type-Options","nosniff"),e.setHeader("Location",n),e.end(i)}}});var xA=h((ur,SA)=>{"use strict";var Yl=ZI(),J9=require("node:events").EventEmitter,yA=tT(),bA=a1(),gA=_y(),vA=P1(),EA=fA();ur=SA.exports=U9;function U9(){var r=function(e,t,n){r.handle(e,t,n)};return yA(r,J9.prototype,!1),yA(r,bA,!1),r.request=Object.create(vA,{app:{configurable:!0,enumerable:!0,writable:!0,value:r}}),r.response=Object.create(EA,{app:{configurable:!0,enumerable:!0,writable:!0,value:r}}),r.init(),r}ur.application=bA;ur.request=vA;ur.response=EA;ur.Route=gA.Route;ur.Router=gA;ur.json=Yl.json;ur.raw=Yl.raw;ur.static=hA();ur.text=Yl.text;ur.urlencoded=Yl.urlencoded});var zl=h(($pe,_A)=>{"use strict";_A.exports=xA()});var By,wA,IA=R(()=>{"use strict";By=["search","context","summarize","import","export"],wA=["workflow","search_params","examples","all"]});function G9(){return typeof __dirname<"u"?__dirname:(0,le.dirname)((0,TA.fileURLToPath)(eV.url))}function $9(){if(process.env.CLAUDE_MEM_DATA_DIR)return process.env.CLAUDE_MEM_DATA_DIR;let r=(0,le.join)((0,$y.homedir)(),".claude-mem"),e=(0,le.join)(r,"settings.json");try{if((0,_a.existsSync)(e)){let t=JSON.parse((0,_a.readFileSync)(e,"utf-8")),n=t.env??t;if(n.CLAUDE_MEM_DATA_DIR)return n.CLAUDE_MEM_DATA_DIR}}catch{}return r}function Fi(){return(0,le.join)(B9,"..")}var le,$y,_a,TA,eV,B9,Oe,Us,Ype,H9,V9,W9,Y9,z9,dr,Q9,X9,AA,Z9,zpe,Qpe,Xpe,Pe,kt=R(()=>{"use strict";le=require("path"),$y=require("os"),_a=require("fs"),TA=require("url");se();eV={};B9=G9();Oe=$9(),Us=process.env.CLAUDE_CONFIG_DIR||(0,le.join)((0,$y.homedir)(),".claude"),Ype=(0,le.join)(Us,"plugins","marketplaces","bjlee2024"),H9=(0,le.join)(Oe,"archives"),V9=(0,le.join)(Oe,"logs"),W9=(0,le.join)(Oe,"trash"),Y9=(0,le.join)(Oe,"backups"),z9=(0,le.join)(Oe,"modes"),dr=(0,le.join)(Oe,"settings.json"),Q9=(0,le.join)(Oe,"claude-mem.db"),X9=(0,le.join)(Oe,"vector-db"),AA=(0,le.join)(Oe,"observer-sessions"),Z9=(0,le.basename)(AA),zpe=(0,le.join)(Us,"settings.json"),Qpe=(0,le.join)(Us,"commands"),Xpe=(0,le.join)(Us,"CLAUDE.md");Pe={dataDir:()=>Oe,workerPid:()=>(0,le.join)(Oe,"worker.pid"),serverBetaPid:()=>(0,le.join)(Oe,".server-beta.pid"),serverBetaPort:()=>(0,le.join)(Oe,".server-beta.port"),serverBetaRuntime:()=>(0,le.join)(Oe,".server-beta.runtime.json"),settings:()=>(0,le.join)(Oe,"settings.json"),database:()=>(0,le.join)(Oe,"claude-mem.db"),chroma:()=>(0,le.join)(Oe,"chroma"),combinedCerts:()=>(0,le.join)(Oe,"combined_certs.pem"),transcriptsConfig:()=>(0,le.join)(Oe,"transcript-watch.json"),transcriptsState:()=>(0,le.join)(Oe,"transcript-watch-state.json"),corpora:()=>(0,le.join)(Oe,"corpora"),supervisorRegistry:()=>(0,le.join)(Oe,"supervisor.json"),envFile:()=>(0,le.join)(Oe,".env"),logsDir:()=>V9,archives:()=>H9,trash:()=>W9,backups:()=>Y9,modes:()=>z9,vectorDb:()=>X9,observerSessions:()=>AA}});function rV(r){return(tV??process.stderr.write.bind(process.stderr))(r)}function Hy(r){rV(r)}var tV,kA=R(()=>{"use strict";tV=null});var bn,OA,Vy,Wy,_,se=R(()=>{"use strict";bn=require("fs"),OA=require("path");kt();kA();Vy=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.WARN=2]="WARN",s[s.ERROR=3]="ERROR",s[s.SILENT=4]="SILENT",s))(Vy||{}),Wy=class r{level=null;recentLogs=[];static MAX_RECENT_LOGS=2e3;useColor;logFilePath=null;logFileInitialized=!1;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){if(!this.logFileInitialized){this.logFileInitialized=!0;try{let e=Pe.logsDir();(0,bn.existsSync)(e)||(0,bn.mkdirSync)(e,{recursive:!0});let t=new Date().toISOString().split("T")[0];this.logFilePath=(0,OA.join)(e,`claude-mem-${t}.log`)}catch(e){console.error("[LOGGER] Failed to initialize log file:",e instanceof Error?e.message:String(e)),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let e=Pe.settings();if((0,bn.existsSync)(e)){let t=(0,bn.readFileSync)(e,"utf-8"),i=(JSON.parse(t).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=Vy[i]??1}else this.level=1}catch(e){console.error("[LOGGER] Failed to load log level from settings:",e instanceof Error?e.message:String(e)),this.level=1}return this.level}correlationId(e,t){return`obs-${e}-${t}`}sessionId(e){return`session-${e}`}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.getLevel()===0?`${e.message}
|
|
55
55
|
${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let t=Object.keys(e);return t.length===0?"{}":t.length<=3?JSON.stringify(e):`{${t.length} keys: ${t.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,t){if(!t)return e;let n=t;if(typeof t=="string")try{n=JSON.parse(t)}catch{n=t}if(e==="Bash"&&n.command)return`${e}(${n.command})`;if(n.file_path)return`${e}(${n.file_path})`;if(n.notebook_path)return`${e}(${n.notebook_path})`;if(e==="Glob"&&n.pattern)return`${e}(${n.pattern})`;if(e==="Grep"&&n.pattern)return`${e}(${n.pattern})`;if(n.url)return`${e}(${n.url})`;if(n.query)return`${e}(${n.query})`;if(e==="Task"){if(n.subagent_type)return`${e}(${n.subagent_type})`;if(n.description)return`${e}(${n.description})`}return e==="Skill"&&n.skill?`${e}(${n.skill})`:e==="LSP"&&n.operation?`${e}(${n.operation})`:e}formatTimestamp(e){let t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0"),s=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0"),c=String(e.getMilliseconds()).padStart(3,"0");return`${t}-${n}-${i} ${s}:${o}:${a}.${c}`}log(e,t,n,i,s){if(e<this.getLevel())return;this.ensureLogFileInitialized();let o=this.formatTimestamp(new Date),a=Vy[e].padEnd(5),c=t.padEnd(6),l="";i?.correlationId?l=`[${i.correlationId}] `:i?.sessionId&&(l=`[session-${i.sessionId}] `);let u="";if(s!=null)if(s instanceof Error)u=this.getLevel()===0?`
|
|
56
56
|
${s.message}
|
|
57
57
|
${s.stack}`:` ${s.message}`;else if(this.getLevel()===0&&typeof s=="object")try{u=`
|
|
58
|
-
`+JSON.stringify(s,null,2)}catch{u=" "+this.formatData(s)}else u=" "+this.formatData(s);let d="";if(i){let{sessionId:f,memorySessionId:m,correlationId:y,...b}=i;Object.keys(b).length>0&&(d=` {${Object.entries(b).map(([E,I])=>`${E}=${I}`).join(", ")}}`)}let p=`[${o}] [${a}] [${c}] ${l}${n}${d}${u}`;if(this.logFilePath)try{(0,bn.appendFileSync)(this.logFilePath,p+`
|
|
58
|
+
`+JSON.stringify(s,null,2)}catch{u=" "+this.formatData(s)}else u=" "+this.formatData(s);let d="";if(i){let{sessionId:f,memorySessionId:m,correlationId:y,...b}=i;Object.keys(b).length>0&&(d=` {${Object.entries(b).map(([E,I])=>`${E}=${I}`).join(", ")}}`)}let p=`[${o}] [${a}] [${c}] ${l}${n}${d}${u}`;if(this.recentLogs.push(p),this.recentLogs.length>r.MAX_RECENT_LOGS&&this.recentLogs.splice(0,this.recentLogs.length-r.MAX_RECENT_LOGS),this.logFilePath)try{(0,bn.appendFileSync)(this.logFilePath,p+`
|
|
59
59
|
`,"utf8")}catch(f){Hy(`[LOGGER] Failed to write to log file: ${f instanceof Error?f.message:String(f)}
|
|
60
60
|
`)}else Hy(p+`
|
|
61
|
-
`)}
|
|
62
|
-
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),u=l?`${l[1].split("/").pop()}:${l[2]}`:"unknown",d={...n,location:u};return this.warn(e,`[HAPPY-PATH] ${t}`,d,i),s}},_=new Wy});var KA=h((ife,CA)=>{"use strict";var RA=Object.getOwnPropertySymbols,nV=Object.prototype.hasOwnProperty,iV=Object.prototype.propertyIsEnumerable;function sV(r){if(r==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(r)}function oV(){try{if(!Object.assign)return!1;var r=new String("abc");if(r[5]="de",Object.getOwnPropertyNames(r)[0]==="5")return!1;for(var e={},t=0;t<10;t++)e["_"+String.fromCharCode(t)]=t;var n=Object.getOwnPropertyNames(e).map(function(s){return e[s]});if(n.join("")!=="0123456789")return!1;var i={};return"abcdefghijklmnopqrst".split("").forEach(function(s){i[s]=s}),Object.keys(Object.assign({},i)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}CA.exports=oV()?Object.assign:function(r,e){for(var t,n=sV(r),i,s=1;s<arguments.length;s++){t=Object(arguments[s]);for(var o in t)nV.call(t,o)&&(n[o]=t[o]);if(RA){i=RA(t);for(var a=0;a<i.length;a++)iV.call(t,i[a])&&(n[i[a]]=t[i[a]])}}return n}});var DA=h((sfe,jA)=>{(function(){"use strict";var r=KA(),e=Fy(),t={origin:"*",methods:"GET,HEAD,PUT,PATCH,POST,DELETE",preflightContinue:!1,optionsSuccessStatus:204};function n(m){return typeof m=="string"||m instanceof String}function i(m,y){if(Array.isArray(y)){for(var b=0;b<y.length;++b)if(i(m,y[b]))return!0;return!1}else return n(y)?m===y:y instanceof RegExp?y.test(m):!!y}function s(m,y){var b=y.headers.origin,g=[],E;return!m.origin||m.origin==="*"?g.push([{key:"Access-Control-Allow-Origin",value:"*"}]):n(m.origin)?(g.push([{key:"Access-Control-Allow-Origin",value:m.origin}]),g.push([{key:"Vary",value:"Origin"}])):(E=i(b,m.origin),g.push([{key:"Access-Control-Allow-Origin",value:E?b:!1}]),g.push([{key:"Vary",value:"Origin"}])),g}function o(m){var y=m.methods;return y.join&&(y=m.methods.join(",")),{key:"Access-Control-Allow-Methods",value:y}}function a(m){return m.credentials===!0?{key:"Access-Control-Allow-Credentials",value:"true"}:null}function c(m,y){var b=m.allowedHeaders||m.headers,g=[];return b?b.join&&(b=b.join(",")):(b=y.headers["access-control-request-headers"],g.push([{key:"Vary",value:"Access-Control-Request-Headers"}])),b&&b.length&&g.push([{key:"Access-Control-Allow-Headers",value:b}]),g}function l(m){var y=m.exposedHeaders;if(y)y.join&&(y=y.join(","));else return null;return y&&y.length?{key:"Access-Control-Expose-Headers",value:y}:null}function u(m){var y=(typeof m.maxAge=="number"||m.maxAge)&&m.maxAge.toString();return y&&y.length?{key:"Access-Control-Max-Age",value:y}:null}function d(m,y){for(var b=0,g=m.length;b<g;b++){var E=m[b];E&&(Array.isArray(E)?d(E,y):E.key==="Vary"&&E.value?e(y,E.value):E.value&&y.setHeader(E.key,E.value))}}function p(m,y,b,g){var E=[],I=y.method&&y.method.toUpperCase&&y.method.toUpperCase();I==="OPTIONS"?(E.push(s(m,y)),E.push(a(m)),E.push(o(m)),E.push(c(m,y)),E.push(u(m)),E.push(l(m)),d(E,b),m.preflightContinue?g():(b.statusCode=m.optionsSuccessStatus,b.setHeader("Content-Length","0"),b.end())):(E.push(s(m,y)),E.push(a(m)),E.push(l(m)),d(E,b),g())}function f(m){var y=null;return typeof m=="function"?y=m:y=function(b,g){g(null,m)},function(g,E,I){y(g,function(T,L){if(T)I(T);else{var U=r({},t,L),ie=null;U.origin&&typeof U.origin=="function"?ie=U.origin:U.origin&&(ie=function(je,ce){ce(null,U.origin)}),ie?ie(g.headers.origin,function(je,ce){je||!ce?I(je):(U.origin=ce,p(U,g,E,I))}):I()}})}}jA.exports=f})()});function zy(r,e={}){let t=[];e.includeCors!==!1&&t.push(Ql()),t.push(Yy.default.json({limit:"5mb"})),t.push((s,o,a)=>{let l=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(y=>s.path.endsWith(y)),u=s.path==="/api/logs";if(s.path.startsWith("/health")||s.path==="/"||l||u)return a();let d=Date.now(),p=`${s.method}-${Date.now()}`,f=r(s.method,s.path,s.body);_.debug("HTTP",`\u2192 ${s.method} ${s.path}`,{requestId:p},f);let m=o.send.bind(o);o.send=function(y){let b=Date.now()-d;return _.debug("HTTP",`\u2190 ${o.statusCode} ${s.path}`,{requestId:p,duration:`${b}ms`}),m(y)},a()});let n=Fi(),i=PA.default.join(n,"plugin","ui");return t.push(Yy.default.static(i)),t}function aV(r){let e=(process.env.CLAUDE_MEM_CORS_ALLOW_ORIGINS||"").split(",").map(i=>i.trim()).filter(Boolean);if(e.includes("*")||e.includes(r))return!0;let t;try{t=new URL(r).hostname}catch{return!1}if(t==="localhost"||t==="127.0.0.1"||t==="::1"||!t.includes(".")||t.endsWith(".local")||t.endsWith(".internal")||t.endsWith(".lan")||t.endsWith(".ts.net"))return!0;let n=t.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);if(n){let i=Number(n[1]),s=Number(n[2]);if(i===10||i===172&&s>=16&&s<=31||i===192&&s===168||i===100&&s>=64&&s<=127)return!0}return!1}function Ql(){return(0,MA.default)({origin:(r,e)=>{!r||aV(r)?e(null,!0):e(new Error("CORS not allowed"))},methods:["GET","HEAD","POST","PUT","PATCH","DELETE"],allowedHeaders:["Content-Type","Authorization","X-Requested-With"],credentials:!1})}function wa(r,e,t){let n=r.ip||r.connection.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){_.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:r.path,clientIp:n,method:r.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}t()}function Qy(r,e,t){if(!t||Object.keys(t).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=t.tool_name||"?",i=t.tool_input;return`tool=${_.formatTool(n,i)}`}return e.includes("/summarize")?"requesting summary":""}var Yy,MA,PA,NA=R(()=>{"use strict";Yy=ze(zl(),1),MA=ze(DA(),1),PA=ze(require("path"),1);kt();se()});var LA=R(()=>{"use strict";NA()});function qA(r,e,t,n){let i={error:r,message:e};return t&&(i.code=t),n&&(i.details=n),i}function JA(r,e){e.status(404).json(qA("NotFound",`Cannot ${r.method} ${r.path}`))}var Gs,FA,UA=R(()=>{"use strict";se();Gs=class extends Error{constructor(t,n=500,i,s){super(t);this.statusCode=n;this.code=i;this.details=s;this.name="AppError"}statusCode;code;details};FA=(r,e,t,n)=>{let i=r instanceof Gs?r.statusCode:500;_.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:r.message,code:r instanceof Gs?r.code:void 0},r);let s=qA(r.name||"Error",r.message,r instanceof Gs?r.code:void 0,r instanceof Gs?r.details:void 0);t.status(i).json(s)}});var GA=R(()=>{"use strict"});function Ia(r=process.env){let e={};for(let[t,n]of Object.entries(r))if(n!==void 0){if(lV.has(t)){e[t]=n;continue}Zy.has(t)||cV.has(t)||Xy.some(i=>t.startsWith(i))||(e[t]=n)}return e}var Xy,Zy,cV,lV,Xl=R(()=>{"use strict";Xy=["CLAUDECODE_","CLAUDE_CODE_"],Zy=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),cV=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy"]),lV=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS"])});function pr(r){if(!Number.isInteger(r)||r<0||r===0)return!1;try{return process.kill(r,0),!0}catch(e){if(e instanceof Error){let t=e.code;return t==="EPERM"?!0:(_.debug("SYSTEM","PID check failed",{pid:r,code:t}),!1)}return _.warn("SYSTEM","PID check threw non-Error",{pid:r,error:String(e)}),!1}}function mV(r){let e=BA.get(r);if(e&&Date.now()-e.capturedAtMs<fV)return e.token;let t=null;try{let n=(0,ib.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${r}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Ia(process.env),LC_ALL:"C",LANG:"C"}});if(n.status===0){let i=n.stdout.trim();t=i.length>0?i:null}}catch(n){_.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:r,error:n instanceof Error?n.message:String(n)}),t=null}return BA.set(r,{token:t,capturedAtMs:Date.now()}),t}function sb(r){if(!Number.isInteger(r)||r<=0)return null;if(process.platform==="linux")try{let e=(0,Hr.readFileSync)(`/proc/${r}/stat`,"utf-8"),t=e.lastIndexOf(") ");if(t<0)return null;let i=e.slice(t+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(e){return _.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return mV(r);try{let e=(0,ib.spawnSync)("ps",["-p",String(r),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Ia(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let t=e.stdout.trim();return t.length>0?t:null}catch(e){return _.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}}function Hn(r){if(!r||!pr(r.pid))return!1;if(!r.startToken)return!0;let e=sb(r.pid);if(e===null)return!0;let t=e===r.startToken;return t||_.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:r.pid,stored:r.startToken,current:e}),t}function Zl(){return eb||(eb=new nb),eb}function tb(){let r=hV.shift();r&&r()}var ib,Hr,rb,uV,dV,pV,fV,BA,nb,eb,hV,Bs=R(()=>{"use strict";ib=require("child_process");GA();Hr=require("fs"),rb=ze(require("path"),1);se();Xl();kt();uV=5e3,dV=1e3,pV=Pe.supervisorRegistry();fV=5e3,BA=new Map;nb=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=pV){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,Hr.mkdirSync)(rb.default.dirname(this.registryPath),{recursive:!0}),!(0,Hr.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Hr.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[i,s]of Object.entries(n))this.entries.set(i,s)}catch(t){t instanceof Error?_.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},t):_.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(t)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&_.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,t,n){this.initialize(),this.entries.set(e,t),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let t=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),t?.type==="sdk"&&tb()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,t])=>({id:e,...t})).sort((e,t)=>{let n=Date.parse(e.startedAt),i=Date.parse(t.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(i)?0:i)})}getBySession(e){let t=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===t)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}getByPid(e){return this.getAll().filter(t=>t.pid===e)}pruneDeadEntries(){this.initialize();let e=0,t=0;for(let[n,i]of this.entries)pr(i.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,i.type==="sdk"&&(t+=1));e>0&&this.persist();for(let n=0;n<t;n+=1)tb();return e}async reapSession(e){this.initialize();let t=this.getBySession(e);if(t.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;_.info("SYSTEM",`Reaping ${t.length} process(es) for session ${e}`,{sessionId:n,pids:t.map(a=>a.pid)});let i=t.filter(a=>pr(a.pid));for(let a of i)try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):_.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}let s=Date.now()+uV;for(;Date.now()<s&&i.filter(c=>pr(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100));let o=i.filter(a=>pr(a.pid));for(let a of o){_.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(c){c instanceof Error?c.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):_.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}}if(o.length>0){let a=Date.now()+dV;for(;Date.now()<a&&o.filter(l=>pr(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let a of t)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of t)a.type==="sdk"&&tb();return _.info("SYSTEM",`Reaped ${t.length} process(es) for session ${e}`,{sessionId:n,reaped:t.length}),t.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,Hr.mkdirSync)(rb.default.dirname(this.registryPath),{recursive:!0}),(0,Hr.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},eb=null;hV=[]});var $A,HA=R(()=>{"use strict";$A={DEFAULT:3e5,HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,WORKER_STARTUP_WAIT:1e3,PRE_RESTART_SETTLE_DELAY:2e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5}});async function XA(r){let e=r.currentPid??process.pid,t=r.pidFilePath??bV,n=r.registry.getAll(),i=[...n].filter(o=>o.pid!==e).sort((o,a)=>Date.parse(a.startedAt)-Date.parse(o.startedAt));for(let o of i){if(!pr(o.pid)){r.registry.unregister(o.id);continue}try{await WA(o,"SIGTERM")}catch(a){a instanceof Error?_.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:o.pid,pgid:o.pgid,type:o.type},a):_.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:o.pid,pgid:o.pgid,type:o.type,error:String(a)})}}await VA(i,5e3);let s=i.filter(o=>pr(o.pid));for(let o of s)try{await WA(o,"SIGKILL")}catch(a){a instanceof Error?_.debug("SYSTEM","Failed to force kill child process",{pid:o.pid,pgid:o.pgid,type:o.type},a):_.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:o.pid,pgid:o.pgid,type:o.type,error:String(a)})}await VA(s,1e3);for(let o of i)r.registry.unregister(o.id);for(let o of n.filter(a=>a.pid===e))r.registry.unregister(o.id);try{(0,zA.rmSync)(t,{force:!0})}catch(o){o instanceof Error?_.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:t},o):_.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:t,error:String(o)})}r.registry.pruneDeadEntries()}async function VA(r,e){let t=Date.now()+e;for(;Date.now()<t;){if(r.filter(i=>pr(i.pid)).length===0)return;await new Promise(i=>setTimeout(i,100))}}async function WA(r,e){let{pid:t,pgid:n}=r;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}try{process.kill(t,e)}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}return}if(e==="SIGTERM"){try{process.kill(t,e)}catch(o){if(o instanceof Error&&o.code==="ESRCH")return;throw o}return}let i=await gV();if(i){await new Promise((o,a)=>{i(t,e,c=>{if(!c){o();return}if(c.code==="ESRCH"){o();return}a(c)})});return}let s=["/PID",String(t),"/T"];e==="SIGKILL"&&s.push("/F"),await yV("taskkill",s,{timeout:$A.POWERSHELL_COMMAND,windowsHide:!0})}async function gV(){let r="tree-kill";try{let e=await import(r);return e.default??e}catch(e){return _.debug("SYSTEM","tree-kill module not available, using fallback",{},e instanceof Error?e:void 0),null}}var YA,zA,QA,yV,bV,ZA=R(()=>{"use strict";YA=require("child_process"),zA=require("fs"),QA=require("util");se();HA();Bs();kt();yV=(0,QA.promisify)(YA.execFile),bV=Pe.workerPid()});function vV(){let e=Zl().pruneDeadEntries();e>0&&_.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function tk(){$s===null&&($s=setInterval(vV,ek),$s.unref(),_.debug("SYSTEM","Health checker started",{intervalMs:ek}))}function rk(){$s!==null&&(clearInterval($s),$s=null,_.debug("SYSTEM","Health checker stopped"))}var ek,$s,nk=R(()=>{"use strict";se();Bs();ek=3e4,$s=null});function ik(){return SV}function xV(r={}){let e=r.pidFilePath??EV;if(!(0,Ji.existsSync)(e))return"missing";let t=null;try{t=JSON.parse((0,Ji.readFileSync)(e,"utf-8"))}catch(i){return i instanceof Error?_.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},i):_.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(i)}),(0,Ji.rmSync)(e,{force:!0}),"invalid"}return Hn(t)&&t?((r.logAlive??!0)&&_.info("SYSTEM","Worker already running (PID alive)",{existingPid:t.pid,existingPort:t.port,startedAt:t.startedAt}),"alive"):(_.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:t?.pid,port:t?.port,startedAt:t?.startedAt}),(0,Ji.rmSync)(e,{force:!0}),"stale")}var Ji,EV,ob,SV,sk=R(()=>{"use strict";Ji=require("fs");se();Bs();ZA();nk();kt();EV=Pe.workerPid(),ob=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),xV({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,tk()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let t=async n=>{if(this.shutdownInitiated){_.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,_.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){i instanceof Error?_.error("SYSTEM","Error during shutdown",{},i):_.error("SYSTEM","Error during shutdown (non-Error)",{error:String(i)});try{await this.stop()}catch(s){s instanceof Error?_.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):_.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(s)})}}process.exit(0)};process.on("SIGTERM",()=>{t("SIGTERM")}),process.on("SIGINT",()=>{t("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{_.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{t("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}rk(),this.stopPromise=XA({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,t,n){this.registry.register(e,t,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},SV=new ob(Zl())});function ab(r,e,t){r.on("finish",async()=>{try{await t()}finally{process.exit(0)}}),r.json(e)}var ok=R(()=>{"use strict"});function cb(r,e=Date.now){return Math.max(0,Math.floor((e()-r)/1e3))}var ak=R(()=>{"use strict"});var lb,ck,Gfe,lk=R(()=>{"use strict";lb=class{entries=new Map;set(e){if(!e||typeof e!="object")return;let t=e.rateLimitType??"default";this.entries.set(t,{...e,observedAt:Date.now()})}get(e){return e?this.entries.get(e):this.entries.get("default")}getAll(){return Array.from(this.entries.values()).sort((e,t)=>t.observedAt-e.observedAt)}getMostRecentByWindow(){return{five_hour:this.entries.get("five_hour"),seven_day:this.entries.get("seven_day"),seven_day_opus:this.entries.get("seven_day_opus"),seven_day_sonnet:this.entries.get("seven_day_sonnet"),overage:this.entries.get("overage")}}get size(){return this.entries.size}clear(){this.entries.clear()}},ck=new lb,Gfe=900*1e3});function IV(r){r.setHeader("X-Content-Type-Options","nosniff"),r.setHeader("X-Frame-Options","DENY"),r.setHeader("X-DNS-Prefetch-Control","off"),r.setHeader("Referrer-Policy","no-referrer"),r.setHeader("Cross-Origin-Opener-Policy","same-origin"),r.setHeader("Cross-Origin-Resource-Policy","same-origin"),r.setHeader("Origin-Agent-Cluster","?1"),r.removeHeader("X-Powered-By")}var pk,fk,db,Ta,mk,_V,ub,uk,wV,dk,eu,hk=R(()=>{"use strict";pk=ze(zl(),1),fk=ze(require("http"),1),db=ze(require("fs"),1),Ta=ze(require("path"),1);IA();se();LA();UA();sk();Bs();Xl();ok();ak();lk();mk=Ta.default.resolve(__dirname,"../skills/mem-search"),_V=Ta.default.join(mk,"operations"),ub=Ta.default.join(mk,"SKILL.md"),uk=(()=>{try{let r=db.readFileSync(ub,"utf-8");return _.info("SYSTEM","Cached SKILL.md at boot",{path:ub,bytes:Buffer.byteLength(r,"utf-8")}),r}catch(r){return _.debug("SYSTEM","SKILL.md not present at boot, /api/instructions will 404 for topic queries",{path:ub,message:r instanceof Error?r.message:String(r)}),null}})(),wV=(()=>{let r=new Map;for(let e of By){let t=Ta.default.join(_V,`${e}.md`);try{r.set(e,db.readFileSync(t,"utf-8"))}catch(n){_.debug("SYSTEM","Operation instruction file not present at boot",{path:t,message:n instanceof Error?n.message:String(n)})}}return r.size>0&&_.info("SYSTEM","Cached operation instruction files at boot",{count:r.size,operations:Array.from(r.keys())}),r})(),dk="13.4.19";eu=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,pk.default)(),this.app.disable("x-powered-by"),this.setupSecurityHeaders(),this.setupCors(),this.setupPreBodyParserRoutes(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,t){return new Promise((n,i)=>{let s=fk.default.createServer(this.app);this.server=s;let o=c=>{s.off("listening",a),i(c)},a=()=>{s.off("error",o),_.info("SYSTEM","HTTP server started",{host:t,port:e,pid:process.pid}),n()};s.once("error",o),s.once("listening",a),s.listen(e,t)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,t)=>{this.server.close(n=>n?t(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,_.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(JA),this.app.use(FA)}setupMiddleware(){zy(Qy,{includeCors:!1}).forEach(t=>this.app.use(t))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,t,n)=>{IV(t),n()})}setupCors(){this.app.use(Ql())}setupPreBodyParserRoutes(){this.options.preBodyParserRoutes?.forEach(e=>e.setupRoutes(this.app))}setupCoreRoutes(){this.app.get("/api/health",async(e,t)=>{let n=this.options.getQueueHealth?await this.options.getQueueHealth():null,i=n?.engine==="bullmq"&&n.redis.status==="error";t.status(i?503:200).json({status:i?"degraded":"ok",...this.options.runtime?{runtime:this.options.runtime}:{},version:dk,workerPath:this.options.workerPath,uptime:cb(this.startTime),managed:process.env.CLAUDE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.options.getInitializationComplete(),mcpReady:this.options.getMcpReady(),ai:this.options.getAiStatus(),rateLimits:ck.getMostRecentByWindow(),...n?{queue:n}:{}})}),this.app.get("/api/readiness",(e,t)=>{this.options.getInitializationComplete()?t.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):t.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(e,t)=>{t.status(200).json({version:dk})}),this.app.get("/api/instructions",(e,t)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!wA.includes(n))return t.status(400).json({error:"Invalid topic"});if(i&&!By.includes(i))return t.status(400).json({error:"Invalid operation"});if(i){let o=wV.get(i);return o===void 0?(_.debug("HTTP","Instruction file not cached at boot",{operation:i}),t.status(404).json({error:"Instruction not found"})):t.json({content:[{type:"text",text:o}]})}if(uk===null)return _.debug("HTTP","SKILL.md not cached at boot",{topic:n}),t.status(404).json({error:"Instruction not found"});let s=this.extractInstructionSection(uk,n);t.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",wa,async(e,t)=>{process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(t.json({status:"restarting"}),_.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):ab(t,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",wa,async(e,t)=>{process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(t.json({status:"shutting_down"}),_.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown"})):ab(t,{status:"shutting_down"},()=>this.options.onShutdown())}),this.app.get("/api/admin/doctor",wa,(e,t)=>{let o=ik().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:pr(f.pid)?"alive":"dead",startedAt:f.startedAt})),a=o.filter(f=>f.status==="dead").map(f=>f.pid),c=!Object.keys(process.env).some(f=>Zy.has(f)||Xy.some(m=>f.startsWith(m))),l=cb(this.startTime),u=Math.floor(l/3600),d=Math.floor(l%3600/60),p=u>0?`${u}h ${d}m`:`${d}m`;t.json({supervisor:{running:!0,pid:process.pid,uptime:p},processes:o,health:{deadProcessPids:a,envClean:c}})})}extractInstructionSection(e,t){let n={workflow:this.extractBetween(e,"## The Workflow","## Search Parameters"),search_params:this.extractBetween(e,"## Search Parameters","## Examples"),examples:this.extractBetween(e,"## Examples","## Why This Workflow"),all:e};return n[t]||n.all}extractBetween(e,t,n){let i=e.indexOf(t),s=e.indexOf(n);return i===-1?e:s===-1?e.substring(i):e.substring(i,s).trim()}}});var Nt,TV,AV,pb,yk=R(()=>{"use strict";Nt=require("zod"),TV=Nt.z.enum(["hook","worker","provider","server","api"]),AV=Nt.z.object({id:Nt.z.string().min(1),projectId:Nt.z.string().min(1),serverSessionId:Nt.z.string().min(1).nullable().default(null),sourceType:TV,eventType:Nt.z.string().min(1),platformSource:Nt.z.string().min(1).nullable().default(null),sourceEventId:Nt.z.string().min(1).nullable().default(null),payload:Nt.z.unknown().default({}),contentSessionId:Nt.z.string().min(1).nullable().default(null),memorySessionId:Nt.z.string().min(1).nullable().default(null),occurredAtEpoch:Nt.z.number().int().nonnegative(),createdAtEpoch:Nt.z.number().int().nonnegative()}),pb=AV.omit({id:!0,createdAtEpoch:!0}).partial({serverSessionId:!0,platformSource:!0,sourceEventId:!0,payload:!0,contentSessionId:!0,memorySessionId:!0})});function Ue(){return(0,tu.randomUUID)()}function Qe(r){return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}function bk(r){return Array.isArray(r)?r:[]}function Ee(r){return typeof r=="number"?r:new Date(r).getTime()}function fr(r){return r==null?null:r instanceof Date?r:new Date(r)}async function Q(r,e,t=[]){return(await r.query(e,t)).rows[0]??null}async function Or(r,e,t){if(!await Q(r,"SELECT id FROM projects WHERE id = $1 AND team_id = $2",[e,t]))throw new Error("project_id must belong to team_id")}async function gn(r,e,t,n){if(!await Q(r,"SELECT id FROM server_sessions WHERE id = $1 AND project_id = $2 AND team_id = $3",[e,t,n]))throw new Error("server_session_id must belong to project_id and team_id")}function Aa(r){return JSON.stringify(fb(r))}function Rr(r){return(0,tu.createHash)("sha256").update(Aa(r)).digest("hex")}function fb(r){if(Array.isArray(r))return r.map(fb);if(r&&typeof r=="object"){let e=r;return Object.keys(e).sort().reduce((t,n)=>(t[n]=fb(e[n]),t),{})}return r}var tu,Vr=R(()=>{"use strict";tu=require("crypto")});function gk(r){return r.sourceEventId?`agent_event:v1:${Rr([r.teamId,r.projectId,r.sourceAdapter,r.sourceEventId])}`:`agent_event:v1:${Rr([r.teamId,r.projectId,r.sourceAdapter,r.serverSessionId??null,r.eventType,new Date(r.occurredAt).toISOString(),Aa(r.payload??{})])}`}function mb(r){return{id:r.id,projectId:r.project_id,teamId:r.team_id,serverSessionId:r.server_session_id,sourceAdapter:r.source_adapter,sourceEventId:r.source_event_id,idempotencyKey:r.idempotency_key,eventType:r.event_type,platformSource:r.platform_source,payload:r.payload,metadata:Qe(r.metadata),occurredAtEpoch:Ee(r.occurred_at),receivedAtEpoch:Ee(r.received_at),createdAtEpoch:Ee(r.created_at)}}var mr,Hs=R(()=>{"use strict";Vr();mr=class{constructor(e){this.client=e}client;async create(e){await Or(this.client,e.projectId,e.teamId),e.serverSessionId&&await gn(this.client,e.serverSessionId,e.projectId,e.teamId);let t=gk(e),n=await Q(this.client,`
|
|
61
|
+
`)}getRecentLogs(){return this.recentLogs.join(`
|
|
62
|
+
`)}clearRecentLogs(){this.recentLogs=[]}debug(e,t,n,i){this.log(0,e,t,n,i)}info(e,t,n,i){this.log(1,e,t,n,i)}warn(e,t,n,i){this.log(2,e,t,n,i)}error(e,t,n,i){this.log(3,e,t,n,i)}dataIn(e,t,n,i){this.info(e,`\u2192 ${t}`,n,i)}dataOut(e,t,n,i){this.info(e,`\u2190 ${t}`,n,i)}success(e,t,n,i){this.info(e,`\u2713 ${t}`,n,i)}failure(e,t,n,i){this.error(e,`\u2717 ${t}`,n,i)}timing(e,t,n,i){this.info(e,`\u23F1 ${t}`,i,{duration:`${n}ms`})}happyPathError(e,t,n,i,s=""){let l=((new Error().stack||"").split(`
|
|
63
|
+
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),u=l?`${l[1].split("/").pop()}:${l[2]}`:"unknown",d={...n,location:u};return this.warn(e,`[HAPPY-PATH] ${t}`,d,i),s}},_=new Wy});var KA=h((ife,CA)=>{"use strict";var RA=Object.getOwnPropertySymbols,nV=Object.prototype.hasOwnProperty,iV=Object.prototype.propertyIsEnumerable;function sV(r){if(r==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(r)}function oV(){try{if(!Object.assign)return!1;var r=new String("abc");if(r[5]="de",Object.getOwnPropertyNames(r)[0]==="5")return!1;for(var e={},t=0;t<10;t++)e["_"+String.fromCharCode(t)]=t;var n=Object.getOwnPropertyNames(e).map(function(s){return e[s]});if(n.join("")!=="0123456789")return!1;var i={};return"abcdefghijklmnopqrst".split("").forEach(function(s){i[s]=s}),Object.keys(Object.assign({},i)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}CA.exports=oV()?Object.assign:function(r,e){for(var t,n=sV(r),i,s=1;s<arguments.length;s++){t=Object(arguments[s]);for(var o in t)nV.call(t,o)&&(n[o]=t[o]);if(RA){i=RA(t);for(var a=0;a<i.length;a++)iV.call(t,i[a])&&(n[i[a]]=t[i[a]])}}return n}});var DA=h((sfe,jA)=>{(function(){"use strict";var r=KA(),e=Fy(),t={origin:"*",methods:"GET,HEAD,PUT,PATCH,POST,DELETE",preflightContinue:!1,optionsSuccessStatus:204};function n(m){return typeof m=="string"||m instanceof String}function i(m,y){if(Array.isArray(y)){for(var b=0;b<y.length;++b)if(i(m,y[b]))return!0;return!1}else return n(y)?m===y:y instanceof RegExp?y.test(m):!!y}function s(m,y){var b=y.headers.origin,g=[],E;return!m.origin||m.origin==="*"?g.push([{key:"Access-Control-Allow-Origin",value:"*"}]):n(m.origin)?(g.push([{key:"Access-Control-Allow-Origin",value:m.origin}]),g.push([{key:"Vary",value:"Origin"}])):(E=i(b,m.origin),g.push([{key:"Access-Control-Allow-Origin",value:E?b:!1}]),g.push([{key:"Vary",value:"Origin"}])),g}function o(m){var y=m.methods;return y.join&&(y=m.methods.join(",")),{key:"Access-Control-Allow-Methods",value:y}}function a(m){return m.credentials===!0?{key:"Access-Control-Allow-Credentials",value:"true"}:null}function c(m,y){var b=m.allowedHeaders||m.headers,g=[];return b?b.join&&(b=b.join(",")):(b=y.headers["access-control-request-headers"],g.push([{key:"Vary",value:"Access-Control-Request-Headers"}])),b&&b.length&&g.push([{key:"Access-Control-Allow-Headers",value:b}]),g}function l(m){var y=m.exposedHeaders;if(y)y.join&&(y=y.join(","));else return null;return y&&y.length?{key:"Access-Control-Expose-Headers",value:y}:null}function u(m){var y=(typeof m.maxAge=="number"||m.maxAge)&&m.maxAge.toString();return y&&y.length?{key:"Access-Control-Max-Age",value:y}:null}function d(m,y){for(var b=0,g=m.length;b<g;b++){var E=m[b];E&&(Array.isArray(E)?d(E,y):E.key==="Vary"&&E.value?e(y,E.value):E.value&&y.setHeader(E.key,E.value))}}function p(m,y,b,g){var E=[],I=y.method&&y.method.toUpperCase&&y.method.toUpperCase();I==="OPTIONS"?(E.push(s(m,y)),E.push(a(m)),E.push(o(m)),E.push(c(m,y)),E.push(u(m)),E.push(l(m)),d(E,b),m.preflightContinue?g():(b.statusCode=m.optionsSuccessStatus,b.setHeader("Content-Length","0"),b.end())):(E.push(s(m,y)),E.push(a(m)),E.push(l(m)),d(E,b),g())}function f(m){var y=null;return typeof m=="function"?y=m:y=function(b,g){g(null,m)},function(g,E,I){y(g,function(T,L){if(T)I(T);else{var U=r({},t,L),ie=null;U.origin&&typeof U.origin=="function"?ie=U.origin:U.origin&&(ie=function(je,ce){ce(null,U.origin)}),ie?ie(g.headers.origin,function(je,ce){je||!ce?I(je):(U.origin=ce,p(U,g,E,I))}):I()}})}}jA.exports=f})()});function zy(r,e={}){let t=[];e.includeCors!==!1&&t.push(Ql()),t.push(Yy.default.json({limit:"5mb"})),t.push((s,o,a)=>{let l=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(y=>s.path.endsWith(y)),u=s.path==="/api/logs";if(s.path.startsWith("/health")||s.path==="/"||l||u)return a();let d=Date.now(),p=`${s.method}-${Date.now()}`,f=r(s.method,s.path,s.body);_.debug("HTTP",`\u2192 ${s.method} ${s.path}`,{requestId:p},f);let m=o.send.bind(o);o.send=function(y){let b=Date.now()-d;return _.debug("HTTP",`\u2190 ${o.statusCode} ${s.path}`,{requestId:p,duration:`${b}ms`}),m(y)},a()});let n=Fi(),i=PA.default.join(n,"plugin","ui");return t.push(Yy.default.static(i)),t}function aV(r){let e=(process.env.CLAUDE_MEM_CORS_ALLOW_ORIGINS||"").split(",").map(i=>i.trim()).filter(Boolean);if(e.includes("*")||e.includes(r))return!0;let t;try{t=new URL(r).hostname}catch{return!1}if(t==="localhost"||t==="127.0.0.1"||t==="::1"||!t.includes(".")||t.endsWith(".local")||t.endsWith(".internal")||t.endsWith(".lan")||t.endsWith(".ts.net"))return!0;let n=t.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);if(n){let i=Number(n[1]),s=Number(n[2]);if(i===10||i===172&&s>=16&&s<=31||i===192&&s===168||i===100&&s>=64&&s<=127)return!0}return!1}function Ql(){return(0,MA.default)({origin:(r,e)=>{!r||aV(r)?e(null,!0):e(new Error("CORS not allowed"))},methods:["GET","HEAD","POST","PUT","PATCH","DELETE"],allowedHeaders:["Content-Type","Authorization","X-Requested-With"],credentials:!1})}function wa(r,e,t){let n=r.ip||r.connection.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){_.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:r.path,clientIp:n,method:r.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}t()}function Qy(r,e,t){if(!t||Object.keys(t).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=t.tool_name||"?",i=t.tool_input;return`tool=${_.formatTool(n,i)}`}return e.includes("/summarize")?"requesting summary":""}var Yy,MA,PA,NA=R(()=>{"use strict";Yy=ze(zl(),1),MA=ze(DA(),1),PA=ze(require("path"),1);kt();se()});var LA=R(()=>{"use strict";NA()});function qA(r,e,t,n){let i={error:r,message:e};return t&&(i.code=t),n&&(i.details=n),i}function JA(r,e){e.status(404).json(qA("NotFound",`Cannot ${r.method} ${r.path}`))}var Gs,FA,UA=R(()=>{"use strict";se();Gs=class extends Error{constructor(t,n=500,i,s){super(t);this.statusCode=n;this.code=i;this.details=s;this.name="AppError"}statusCode;code;details};FA=(r,e,t,n)=>{let i=r instanceof Gs?r.statusCode:500;_.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:r.message,code:r instanceof Gs?r.code:void 0},r);let s=qA(r.name||"Error",r.message,r instanceof Gs?r.code:void 0,r instanceof Gs?r.details:void 0);t.status(i).json(s)}});var GA=R(()=>{"use strict"});function Ia(r=process.env){let e={};for(let[t,n]of Object.entries(r))if(n!==void 0){if(lV.has(t)){e[t]=n;continue}Zy.has(t)||cV.has(t)||Xy.some(i=>t.startsWith(i))||(e[t]=n)}return e}var Xy,Zy,cV,lV,Xl=R(()=>{"use strict";Xy=["CLAUDECODE_","CLAUDE_CODE_"],Zy=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),cV=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy"]),lV=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS"])});function pr(r){if(!Number.isInteger(r)||r<0||r===0)return!1;try{return process.kill(r,0),!0}catch(e){if(e instanceof Error){let t=e.code;return t==="EPERM"?!0:(_.debug("SYSTEM","PID check failed",{pid:r,code:t}),!1)}return _.warn("SYSTEM","PID check threw non-Error",{pid:r,error:String(e)}),!1}}function mV(r){let e=BA.get(r);if(e&&Date.now()-e.capturedAtMs<fV)return e.token;let t=null;try{let n=(0,ib.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${r}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...Ia(process.env),LC_ALL:"C",LANG:"C"}});if(n.status===0){let i=n.stdout.trim();t=i.length>0?i:null}}catch(n){_.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:r,error:n instanceof Error?n.message:String(n)}),t=null}return BA.set(r,{token:t,capturedAtMs:Date.now()}),t}function sb(r){if(!Number.isInteger(r)||r<=0)return null;if(process.platform==="linux")try{let e=(0,Hr.readFileSync)(`/proc/${r}/stat`,"utf-8"),t=e.lastIndexOf(") ");if(t<0)return null;let i=e.slice(t+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(e){return _.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return mV(r);try{let e=(0,ib.spawnSync)("ps",["-p",String(r),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...Ia(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let t=e.stdout.trim();return t.length>0?t:null}catch(e){return _.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}}function Hn(r){if(!r||!pr(r.pid))return!1;if(!r.startToken)return!0;let e=sb(r.pid);if(e===null)return!0;let t=e===r.startToken;return t||_.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:r.pid,stored:r.startToken,current:e}),t}function Zl(){return eb||(eb=new nb),eb}function tb(){let r=hV.shift();r&&r()}var ib,Hr,rb,uV,dV,pV,fV,BA,nb,eb,hV,Bs=R(()=>{"use strict";ib=require("child_process");GA();Hr=require("fs"),rb=ze(require("path"),1);se();Xl();kt();uV=5e3,dV=1e3,pV=Pe.supervisorRegistry();fV=5e3,BA=new Map;nb=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=pV){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,Hr.mkdirSync)(rb.default.dirname(this.registryPath),{recursive:!0}),!(0,Hr.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Hr.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[i,s]of Object.entries(n))this.entries.set(i,s)}catch(t){t instanceof Error?_.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},t):_.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(t)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&_.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,t,n){this.initialize(),this.entries.set(e,t),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let t=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),t?.type==="sdk"&&tb()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,t])=>({id:e,...t})).sort((e,t)=>{let n=Date.parse(e.startedAt),i=Date.parse(t.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(i)?0:i)})}getBySession(e){let t=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===t)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}getByPid(e){return this.getAll().filter(t=>t.pid===e)}pruneDeadEntries(){this.initialize();let e=0,t=0;for(let[n,i]of this.entries)pr(i.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,i.type==="sdk"&&(t+=1));e>0&&this.persist();for(let n=0;n<t;n+=1)tb();return e}async reapSession(e){this.initialize();let t=this.getBySession(e);if(t.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;_.info("SYSTEM",`Reaping ${t.length} process(es) for session ${e}`,{sessionId:n,pids:t.map(a=>a.pid)});let i=t.filter(a=>pr(a.pid));for(let a of i)try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):_.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}let s=Date.now()+uV;for(;Date.now()<s&&i.filter(c=>pr(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100));let o=i.filter(a=>pr(a.pid));for(let a of o){_.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});try{typeof a.pgid=="number"&&process.platform!=="win32"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(c){c instanceof Error?c.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):_.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}}if(o.length>0){let a=Date.now()+dV;for(;Date.now()<a&&o.filter(l=>pr(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let a of t)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of t)a.type==="sdk"&&tb();return _.info("SYSTEM",`Reaped ${t.length} process(es) for session ${e}`,{sessionId:n,reaped:t.length}),t.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,Hr.mkdirSync)(rb.default.dirname(this.registryPath),{recursive:!0}),(0,Hr.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},eb=null;hV=[]});var $A,HA=R(()=>{"use strict";$A={DEFAULT:3e5,HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,WORKER_STARTUP_WAIT:1e3,PRE_RESTART_SETTLE_DELAY:2e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5}});async function XA(r){let e=r.currentPid??process.pid,t=r.pidFilePath??bV,n=r.registry.getAll(),i=[...n].filter(o=>o.pid!==e).sort((o,a)=>Date.parse(a.startedAt)-Date.parse(o.startedAt));for(let o of i){if(!pr(o.pid)){r.registry.unregister(o.id);continue}try{await WA(o,"SIGTERM")}catch(a){a instanceof Error?_.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:o.pid,pgid:o.pgid,type:o.type},a):_.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:o.pid,pgid:o.pgid,type:o.type,error:String(a)})}}await VA(i,5e3);let s=i.filter(o=>pr(o.pid));for(let o of s)try{await WA(o,"SIGKILL")}catch(a){a instanceof Error?_.debug("SYSTEM","Failed to force kill child process",{pid:o.pid,pgid:o.pgid,type:o.type},a):_.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:o.pid,pgid:o.pgid,type:o.type,error:String(a)})}await VA(s,1e3);for(let o of i)r.registry.unregister(o.id);for(let o of n.filter(a=>a.pid===e))r.registry.unregister(o.id);try{(0,zA.rmSync)(t,{force:!0})}catch(o){o instanceof Error?_.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:t},o):_.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:t,error:String(o)})}r.registry.pruneDeadEntries()}async function VA(r,e){let t=Date.now()+e;for(;Date.now()<t;){if(r.filter(i=>pr(i.pid)).length===0)return;await new Promise(i=>setTimeout(i,100))}}async function WA(r,e){let{pid:t,pgid:n}=r;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}try{process.kill(t,e)}catch(o){if((o instanceof Error?o.code:void 0)!=="ESRCH")throw o}return}if(e==="SIGTERM"){try{process.kill(t,e)}catch(o){if(o instanceof Error&&o.code==="ESRCH")return;throw o}return}let i=await gV();if(i){await new Promise((o,a)=>{i(t,e,c=>{if(!c){o();return}if(c.code==="ESRCH"){o();return}a(c)})});return}let s=["/PID",String(t),"/T"];e==="SIGKILL"&&s.push("/F"),await yV("taskkill",s,{timeout:$A.POWERSHELL_COMMAND,windowsHide:!0})}async function gV(){let r="tree-kill";try{let e=await import(r);return e.default??e}catch(e){return _.debug("SYSTEM","tree-kill module not available, using fallback",{},e instanceof Error?e:void 0),null}}var YA,zA,QA,yV,bV,ZA=R(()=>{"use strict";YA=require("child_process"),zA=require("fs"),QA=require("util");se();HA();Bs();kt();yV=(0,QA.promisify)(YA.execFile),bV=Pe.workerPid()});function vV(){let e=Zl().pruneDeadEntries();e>0&&_.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function tk(){$s===null&&($s=setInterval(vV,ek),$s.unref(),_.debug("SYSTEM","Health checker started",{intervalMs:ek}))}function rk(){$s!==null&&(clearInterval($s),$s=null,_.debug("SYSTEM","Health checker stopped"))}var ek,$s,nk=R(()=>{"use strict";se();Bs();ek=3e4,$s=null});function ik(){return SV}function xV(r={}){let e=r.pidFilePath??EV;if(!(0,Ji.existsSync)(e))return"missing";let t=null;try{t=JSON.parse((0,Ji.readFileSync)(e,"utf-8"))}catch(i){return i instanceof Error?_.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},i):_.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(i)}),(0,Ji.rmSync)(e,{force:!0}),"invalid"}return Hn(t)&&t?((r.logAlive??!0)&&_.info("SYSTEM","Worker already running (PID alive)",{existingPid:t.pid,existingPort:t.port,startedAt:t.startedAt}),"alive"):(_.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:t?.pid,port:t?.port,startedAt:t?.startedAt}),(0,Ji.rmSync)(e,{force:!0}),"stale")}var Ji,EV,ob,SV,sk=R(()=>{"use strict";Ji=require("fs");se();Bs();ZA();nk();kt();EV=Pe.workerPid(),ob=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),xV({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,tk()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let t=async n=>{if(this.shutdownInitiated){_.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,_.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){i instanceof Error?_.error("SYSTEM","Error during shutdown",{},i):_.error("SYSTEM","Error during shutdown (non-Error)",{error:String(i)});try{await this.stop()}catch(s){s instanceof Error?_.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):_.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(s)})}}process.exit(0)};process.on("SIGTERM",()=>{t("SIGTERM")}),process.on("SIGINT",()=>{t("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{_.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{t("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}rk(),this.stopPromise=XA({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,t,n){this.registry.register(e,t,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},SV=new ob(Zl())});function ab(r,e,t){r.on("finish",async()=>{try{await t()}finally{process.exit(0)}}),r.json(e)}var ok=R(()=>{"use strict"});function cb(r,e=Date.now){return Math.max(0,Math.floor((e()-r)/1e3))}var ak=R(()=>{"use strict"});var lb,ck,Gfe,lk=R(()=>{"use strict";lb=class{entries=new Map;set(e){if(!e||typeof e!="object")return;let t=e.rateLimitType??"default";this.entries.set(t,{...e,observedAt:Date.now()})}get(e){return e?this.entries.get(e):this.entries.get("default")}getAll(){return Array.from(this.entries.values()).sort((e,t)=>t.observedAt-e.observedAt)}getMostRecentByWindow(){return{five_hour:this.entries.get("five_hour"),seven_day:this.entries.get("seven_day"),seven_day_opus:this.entries.get("seven_day_opus"),seven_day_sonnet:this.entries.get("seven_day_sonnet"),overage:this.entries.get("overage")}}get size(){return this.entries.size}clear(){this.entries.clear()}},ck=new lb,Gfe=900*1e3});function IV(r){r.setHeader("X-Content-Type-Options","nosniff"),r.setHeader("X-Frame-Options","DENY"),r.setHeader("X-DNS-Prefetch-Control","off"),r.setHeader("Referrer-Policy","no-referrer"),r.setHeader("Cross-Origin-Opener-Policy","same-origin"),r.setHeader("Cross-Origin-Resource-Policy","same-origin"),r.setHeader("Origin-Agent-Cluster","?1"),r.removeHeader("X-Powered-By")}var pk,fk,db,Ta,mk,_V,ub,uk,wV,dk,eu,hk=R(()=>{"use strict";pk=ze(zl(),1),fk=ze(require("http"),1),db=ze(require("fs"),1),Ta=ze(require("path"),1);IA();se();LA();UA();sk();Bs();Xl();ok();ak();lk();mk=Ta.default.resolve(__dirname,"../skills/mem-search"),_V=Ta.default.join(mk,"operations"),ub=Ta.default.join(mk,"SKILL.md"),uk=(()=>{try{let r=db.readFileSync(ub,"utf-8");return _.info("SYSTEM","Cached SKILL.md at boot",{path:ub,bytes:Buffer.byteLength(r,"utf-8")}),r}catch(r){return _.debug("SYSTEM","SKILL.md not present at boot, /api/instructions will 404 for topic queries",{path:ub,message:r instanceof Error?r.message:String(r)}),null}})(),wV=(()=>{let r=new Map;for(let e of By){let t=Ta.default.join(_V,`${e}.md`);try{r.set(e,db.readFileSync(t,"utf-8"))}catch(n){_.debug("SYSTEM","Operation instruction file not present at boot",{path:t,message:n instanceof Error?n.message:String(n)})}}return r.size>0&&_.info("SYSTEM","Cached operation instruction files at boot",{count:r.size,operations:Array.from(r.keys())}),r})(),dk="13.4.20";eu=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,pk.default)(),this.app.disable("x-powered-by"),this.setupSecurityHeaders(),this.setupCors(),this.setupPreBodyParserRoutes(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,t){return new Promise((n,i)=>{let s=fk.default.createServer(this.app);this.server=s;let o=c=>{s.off("listening",a),i(c)},a=()=>{s.off("error",o),_.info("SYSTEM","HTTP server started",{host:t,port:e,pid:process.pid}),n()};s.once("error",o),s.once("listening",a),s.listen(e,t)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,t)=>{this.server.close(n=>n?t(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,_.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(JA),this.app.use(FA)}setupMiddleware(){zy(Qy,{includeCors:!1}).forEach(t=>this.app.use(t))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,t,n)=>{IV(t),n()})}setupCors(){this.app.use(Ql())}setupPreBodyParserRoutes(){this.options.preBodyParserRoutes?.forEach(e=>e.setupRoutes(this.app))}setupCoreRoutes(){this.app.get("/api/health",async(e,t)=>{let n=this.options.getQueueHealth?await this.options.getQueueHealth():null,i=n?.engine==="bullmq"&&n.redis.status==="error";t.status(i?503:200).json({status:i?"degraded":"ok",...this.options.runtime?{runtime:this.options.runtime}:{},version:dk,workerPath:this.options.workerPath,uptime:cb(this.startTime),managed:process.env.CLAUDE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.options.getInitializationComplete(),mcpReady:this.options.getMcpReady(),ai:this.options.getAiStatus(),rateLimits:ck.getMostRecentByWindow(),...n?{queue:n}:{}})}),this.app.get("/api/readiness",(e,t)=>{this.options.getInitializationComplete()?t.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):t.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(e,t)=>{t.status(200).json({version:dk})}),this.app.get("/api/instructions",(e,t)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!wA.includes(n))return t.status(400).json({error:"Invalid topic"});if(i&&!By.includes(i))return t.status(400).json({error:"Invalid operation"});if(i){let o=wV.get(i);return o===void 0?(_.debug("HTTP","Instruction file not cached at boot",{operation:i}),t.status(404).json({error:"Instruction not found"})):t.json({content:[{type:"text",text:o}]})}if(uk===null)return _.debug("HTTP","SKILL.md not cached at boot",{topic:n}),t.status(404).json({error:"Instruction not found"});let s=this.extractInstructionSection(uk,n);t.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",wa,async(e,t)=>{process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(t.json({status:"restarting"}),_.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):ab(t,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",wa,async(e,t)=>{process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(t.json({status:"shutting_down"}),_.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown"})):ab(t,{status:"shutting_down"},()=>this.options.onShutdown())}),this.app.get("/api/admin/doctor",wa,(e,t)=>{let o=ik().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:pr(f.pid)?"alive":"dead",startedAt:f.startedAt})),a=o.filter(f=>f.status==="dead").map(f=>f.pid),c=!Object.keys(process.env).some(f=>Zy.has(f)||Xy.some(m=>f.startsWith(m))),l=cb(this.startTime),u=Math.floor(l/3600),d=Math.floor(l%3600/60),p=u>0?`${u}h ${d}m`:`${d}m`;t.json({supervisor:{running:!0,pid:process.pid,uptime:p},processes:o,health:{deadProcessPids:a,envClean:c}})})}extractInstructionSection(e,t){let n={workflow:this.extractBetween(e,"## The Workflow","## Search Parameters"),search_params:this.extractBetween(e,"## Search Parameters","## Examples"),examples:this.extractBetween(e,"## Examples","## Why This Workflow"),all:e};return n[t]||n.all}extractBetween(e,t,n){let i=e.indexOf(t),s=e.indexOf(n);return i===-1?e:s===-1?e.substring(i):e.substring(i,s).trim()}}});var Nt,TV,AV,pb,yk=R(()=>{"use strict";Nt=require("zod"),TV=Nt.z.enum(["hook","worker","provider","server","api"]),AV=Nt.z.object({id:Nt.z.string().min(1),projectId:Nt.z.string().min(1),serverSessionId:Nt.z.string().min(1).nullable().default(null),sourceType:TV,eventType:Nt.z.string().min(1),platformSource:Nt.z.string().min(1).nullable().default(null),sourceEventId:Nt.z.string().min(1).nullable().default(null),payload:Nt.z.unknown().default({}),contentSessionId:Nt.z.string().min(1).nullable().default(null),memorySessionId:Nt.z.string().min(1).nullable().default(null),occurredAtEpoch:Nt.z.number().int().nonnegative(),createdAtEpoch:Nt.z.number().int().nonnegative()}),pb=AV.omit({id:!0,createdAtEpoch:!0}).partial({serverSessionId:!0,platformSource:!0,sourceEventId:!0,payload:!0,contentSessionId:!0,memorySessionId:!0})});function Ue(){return(0,tu.randomUUID)()}function Qe(r){return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}function bk(r){return Array.isArray(r)?r:[]}function Ee(r){return typeof r=="number"?r:new Date(r).getTime()}function fr(r){return r==null?null:r instanceof Date?r:new Date(r)}async function Q(r,e,t=[]){return(await r.query(e,t)).rows[0]??null}async function Or(r,e,t){if(!await Q(r,"SELECT id FROM projects WHERE id = $1 AND team_id = $2",[e,t]))throw new Error("project_id must belong to team_id")}async function gn(r,e,t,n){if(!await Q(r,"SELECT id FROM server_sessions WHERE id = $1 AND project_id = $2 AND team_id = $3",[e,t,n]))throw new Error("server_session_id must belong to project_id and team_id")}function Aa(r){return JSON.stringify(fb(r))}function Rr(r){return(0,tu.createHash)("sha256").update(Aa(r)).digest("hex")}function fb(r){if(Array.isArray(r))return r.map(fb);if(r&&typeof r=="object"){let e=r;return Object.keys(e).sort().reduce((t,n)=>(t[n]=fb(e[n]),t),{})}return r}var tu,Vr=R(()=>{"use strict";tu=require("crypto")});function gk(r){return r.sourceEventId?`agent_event:v1:${Rr([r.teamId,r.projectId,r.sourceAdapter,r.sourceEventId])}`:`agent_event:v1:${Rr([r.teamId,r.projectId,r.sourceAdapter,r.serverSessionId??null,r.eventType,new Date(r.occurredAt).toISOString(),Aa(r.payload??{})])}`}function mb(r){return{id:r.id,projectId:r.project_id,teamId:r.team_id,serverSessionId:r.server_session_id,sourceAdapter:r.source_adapter,sourceEventId:r.source_event_id,idempotencyKey:r.idempotency_key,eventType:r.event_type,platformSource:r.platform_source,payload:r.payload,metadata:Qe(r.metadata),occurredAtEpoch:Ee(r.occurred_at),receivedAtEpoch:Ee(r.received_at),createdAtEpoch:Ee(r.created_at)}}var mr,Hs=R(()=>{"use strict";Vr();mr=class{constructor(e){this.client=e}client;async create(e){await Or(this.client,e.projectId,e.teamId),e.serverSessionId&&await gn(this.client,e.serverSessionId,e.projectId,e.teamId);let t=gk(e),n=await Q(this.client,`
|
|
63
64
|
INSERT INTO agent_events (
|
|
64
65
|
id, project_id, team_id, server_session_id, source_adapter,
|
|
65
66
|
source_event_id, idempotency_key, event_type, platform_source, payload, metadata, occurred_at
|
|
@@ -9262,7 +9263,7 @@ return ''
|
|
|
9262
9263
|
`)}};Df.QueueGetters=cS});var Mf=h(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.getNextMillis=hs.Repeat=void 0;var Jce=(St(),dt(Et)),Uce=eS(),Gce=require("crypto"),Bce=Ii(),uS=class extends Bce.QueueBase{constructor(e,t,n){super(e,t,n),this.repeatStrategy=t.settings&&t.settings.repeatStrategy||hs.getNextMillis,this.repeatKeyHashAlgorithm=t.settings&&t.settings.repeatKeyHashAlgorithm||"md5"}async updateRepeatableJob(e,t,n,{override:i}){var s,o;let a=Object.assign({},n.repeat);(s=a.pattern)!==null&&s!==void 0||(a.pattern=a.cron),delete a.cron;let c=a.count?a.count+1:1;if(typeof a.limit<"u"&&c>a.limit)return;let l=Date.now(),{endDate:u}=a;if(u&&l>new Date(u).getTime())return;let d=n.prevMillis||0;l=d<l?l:d;let p=await this.repeatStrategy(l,a,e),{every:f,pattern:m}=a,y=!!((f||m)&&a.immediately),b=y&&f?l-p:void 0;if(p){!d&&n.jobId&&(a.jobId=n.jobId);let g=z2(e,a),E=(o=n.repeat.key)!==null&&o!==void 0?o:this.hash(g),I;if(i)I=await this.scripts.addRepeatableJob(E,p,{name:e,endDate:u?new Date(u).getTime():void 0,tz:a.tz,pattern:m,every:f},g);else{let U=await this.client;I=await this.scripts.updateRepeatableJobMillis(U,E,p,g)}let{immediately:T}=a,L=Jce.__rest(a,["immediately"]);return this.createNextJob(e,p,I,Object.assign(Object.assign({},n),{repeat:Object.assign({offset:b},L)}),t,c,y)}}async createNextJob(e,t,n,i,s,o,a){let c=this.getRepeatJobKey(e,t,n,s),l=Date.now(),u=t+(i.repeat.offset?i.repeat.offset:0)-l,d=Object.assign(Object.assign({},i),{jobId:c,delay:u<0||a?0:u,timestamp:l,prevMillis:t,repeatJobKey:n});return d.repeat=Object.assign(Object.assign({},i.repeat),{count:o}),this.Job.create(this,e,s,d)}getRepeatJobKey(e,t,n,i){return n.split(":").length>2?this.getRepeatJobId({name:e,nextMillis:t,namespace:this.hash(n),jobId:i?.id}):this.getRepeatDelayedJobId({customKey:n,nextMillis:t})}async removeRepeatable(e,t,n){var i;let s=z2(e,Object.assign(Object.assign({},t),{jobId:n})),o=(i=t.key)!==null&&i!==void 0?i:this.hash(s),a=this.getRepeatJobId({name:e,nextMillis:"",namespace:this.hash(s),jobId:n??t.jobId,key:t.key});return this.scripts.removeRepeatable(a,s,o)}async removeRepeatableByKey(e){let t=this.keyToData(e),n=this.getRepeatJobId({name:t.name,nextMillis:"",namespace:this.hash(e),jobId:t.id});return this.scripts.removeRepeatable(n,"",e)}async getRepeatableData(e,t,n){let i=await e.hgetall(this.toKey("repeat:"+t));return i?{key:t,name:i.name,endDate:parseInt(i.endDate)||null,tz:i.tz||null,pattern:i.pattern||null,every:i.every||null,next:n}:this.keyToData(t,n)}keyToData(e,t){let n=e.split(":"),i=n.slice(4).join(":")||null;return{key:e,name:n[0],id:n[1]||null,endDate:parseInt(n[2])||null,tz:n[3]||null,pattern:i,next:t}}async getRepeatableJobs(e=0,t=-1,n=!1){let i=await this.client,s=this.keys.repeat,o=n?await i.zrange(s,e,t,{WITHSCORES:!0}):await i.zrevrange(s,e,t,{WITHSCORES:!0}),a=[];for(let c=0;c<o.length;c+=2)a.push(this.getRepeatableData(i,o[c],parseInt(o[c+1])));return Promise.all(a)}async getRepeatableCount(){return(await this.client).zcard(this.toKey("repeat"))}hash(e){return(0,Gce.createHash)(this.repeatKeyHashAlgorithm).update(e).digest("hex")}getRepeatDelayedJobId({nextMillis:e,customKey:t}){return`repeat:${t}:${e}`}getRepeatJobId({name:e,nextMillis:t,namespace:n,jobId:i,key:s}){return`repeat:${s??this.hash(`${e}${i||""}${n}`)}:${t}`}};hs.Repeat=uS;function z2(r,e){let t=e.endDate?new Date(e.endDate).getTime():"",n=e.tz||"",i=e.pattern,s=i||String(e.every)||"",o=e.jobId?e.jobId:"";return`${r}:${o}:${t}:${n}:${s}`}var $ce=(r,e)=>{let t=e.pattern;if(t&&e.every)throw new Error("Both .pattern and .every options are defined for this repeatable job");if(e.every)return Math.floor(r/e.every)*e.every+(e.immediately?0:e.every);let n=e.startDate&&new Date(e.startDate)>new Date(r)?new Date(e.startDate):new Date(r),i=(0,Uce.parseExpression)(t,Object.assign(Object.assign({},e),{currentDate:n}));try{return e.immediately?new Date().getTime():i.next().getTime()}catch{}};hs.getNextMillis=$ce});var Q2=h(Pf=>{"use strict";Object.defineProperty(Pf,"__esModule",{value:!0});Pf.Queue=void 0;var Hce=vo(),Vce=lS(),Wce=Mf(),ee=qt(),Yce=kf(),zce=Od(),Qce=Wt(),dS=class extends Vce.QueueGetters{constructor(e,t,n){var i;super(e,Object.assign({},t),n),this.token=(0,Qce.randomUUID)(),this.libName="bullmq",this.jobsOpts=(i=t?.defaultJobOptions)!==null&&i!==void 0?i:{},this.waitUntilReady().then(s=>{if(!this.closing&&!t?.skipMetasUpdate)return s.hset(this.keys.meta,this.metaValues)}).catch(s=>{})}emit(e,...t){return super.emit(e,...t)}off(e,t){return super.off(e,t),this}on(e,t){return super.on(e,t),this}once(e,t){return super.once(e,t),this}get defaultJobOptions(){return Object.assign({},this.jobsOpts)}get metaValues(){var e,t,n,i;return{"opts.maxLenEvents":(i=(n=(t=(e=this.opts)===null||e===void 0?void 0:e.streams)===null||t===void 0?void 0:t.events)===null||n===void 0?void 0:n.maxLen)!==null&&i!==void 0?i:1e4,version:`${this.libName}:${zce.version}`}}async getVersion(){return await(await this.client).hget(this.keys.meta,"version")}get repeat(){return new Promise(async e=>{this._repeat||(this._repeat=new Wce.Repeat(this.name,Object.assign(Object.assign({},this.opts),{connection:await this.client})),this._repeat.on("error",this.emit.bind(this,"error"))),e(this._repeat)})}get jobScheduler(){return new Promise(async e=>{this._jobScheduler||(this._jobScheduler=new Yce.JobScheduler(this.name,Object.assign(Object.assign({},this.opts),{connection:await this.client})),this._jobScheduler.on("error",this.emit.bind(this,"error"))),e(this._jobScheduler)})}async setGlobalConcurrency(e){return(await this.client).hset(this.keys.meta,{concurrency:e})}async setGlobalRateLimit(e,t){return(await this.client).hset(this.keys.meta,{max:e,duration:t})}async removeGlobalConcurrency(){return(await this.client).hdel(this.keys.meta,"concurrency")}async removeGlobalRateLimit(){return(await this.client).hdel(this.keys.meta,"max","duration")}async add(e,t,n){return this.trace(ee.SpanKind.PRODUCER,"add",`${this.name}.${e}`,async(i,s)=>{var o;if(s&&!(!((o=n?.telemetry)===null||o===void 0)&&o.omitContext)){let c={metadata:s};n=Object.assign(Object.assign({},n),{telemetry:c})}let a=await this.addJob(e,t,n);return i?.setAttributes({[ee.TelemetryAttributes.JobName]:e,[ee.TelemetryAttributes.JobId]:a.id}),a})}async addJob(e,t,n){if(n&&n.repeat){if(n.repeat.endDate&&+new Date(n.repeat.endDate)<Date.now())throw new Error("End date must be greater than current timestamp");return(await this.repeat).updateRepeatableJob(e,t,Object.assign(Object.assign({},this.jobsOpts),n),{override:!0})}else{let i=n?.jobId;if(i=="0"||i?.startsWith("0:"))throw new Error("JobId cannot be '0' or start with 0:");let s=Object.assign(Object.assign(Object.assign({},this.jobsOpts),n),{jobId:i}),o=await this.Job.create(this,e,t,s);return this.emit("waiting",o),o}}async addBulk(e){return this.trace(ee.SpanKind.PRODUCER,"addBulk",this.name,async(t,n)=>(t&&t.setAttributes({[ee.TelemetryAttributes.BulkNames]:e.map(i=>i.name),[ee.TelemetryAttributes.BulkCount]:e.length}),await this.Job.createBulk(this,e.map(i=>{var s,o,a,c,l,u;let d=(s=i.opts)===null||s===void 0?void 0:s.telemetry;if(n){let f=(a=(o=i.opts)===null||o===void 0?void 0:o.telemetry)===null||a===void 0?void 0:a.omitContext,m=((l=(c=i.opts)===null||c===void 0?void 0:c.telemetry)===null||l===void 0?void 0:l.metadata)||!f&&n;(m||f)&&(d={metadata:m,omitContext:f})}let p=Object.assign(Object.assign(Object.assign({},this.jobsOpts),i.opts),{jobId:(u=i.opts)===null||u===void 0?void 0:u.jobId,telemetry:d});return{name:i.name,data:i.data,opts:p}}))))}async upsertJobScheduler(e,t,n){var i,s;if(t.endDate&&+new Date(t.endDate)<Date.now())throw new Error("End date must be greater than current timestamp");return(await this.jobScheduler).upsertJobScheduler(e,t,(i=n?.name)!==null&&i!==void 0?i:e,(s=n?.data)!==null&&s!==void 0?s:{},Object.assign(Object.assign({},this.jobsOpts),n?.opts),{override:!0})}async pause(){await this.trace(ee.SpanKind.INTERNAL,"pause",this.name,async()=>{await this.scripts.pause(!0),this.emit("paused")})}async close(){await this.trace(ee.SpanKind.INTERNAL,"close",this.name,async()=>{this.closing||this._repeat&&await this._repeat.close(),await super.close()})}async rateLimit(e){await this.trace(ee.SpanKind.INTERNAL,"rateLimit",this.name,async t=>{t?.setAttributes({[ee.TelemetryAttributes.QueueRateLimit]:e}),await this.client.then(n=>n.set(this.keys.limiter,Number.MAX_SAFE_INTEGER,{PX:e}))})}async resume(){await this.trace(ee.SpanKind.INTERNAL,"resume",this.name,async()=>{await this.scripts.pause(!1),this.emit("resumed")})}async isPaused(){return await(await this.client).hexists(this.keys.meta,"paused")===1}isMaxed(){return this.scripts.isMaxed()}async getRepeatableJobs(e,t,n){return(await this.repeat).getRepeatableJobs(e,t,n)}async getJobScheduler(e){return(await this.jobScheduler).getScheduler(e)}async getJobSchedulers(e,t,n){return(await this.jobScheduler).getJobSchedulers(e,t,n)}async getJobSchedulersCount(){return(await this.jobScheduler).getSchedulersCount()}async removeRepeatable(e,t,n){return this.trace(ee.SpanKind.INTERNAL,"removeRepeatable",`${this.name}.${e}`,async i=>(i?.setAttributes({[ee.TelemetryAttributes.JobName]:e,[ee.TelemetryAttributes.JobId]:n}),!await(await this.repeat).removeRepeatable(e,t,n)))}async removeJobScheduler(e){return!await(await this.jobScheduler).removeJobScheduler(e)}async removeDebounceKey(e){return this.trace(ee.SpanKind.INTERNAL,"removeDebounceKey",`${this.name}`,async t=>(t?.setAttributes({[ee.TelemetryAttributes.JobKey]:e}),await(await this.client).del(`${this.keys.de}:${e}`)))}async removeDeduplicationKey(e){return this.trace(ee.SpanKind.INTERNAL,"removeDeduplicationKey",`${this.name}`,async t=>(t?.setAttributes({[ee.TelemetryAttributes.DeduplicationKey]:e}),(await this.client).del(`${this.keys.de}:${e}`)))}async removeRateLimitKey(){return(await this.client).del(this.keys.limiter)}async removeRepeatableByKey(e){return this.trace(ee.SpanKind.INTERNAL,"removeRepeatableByKey",`${this.name}`,async t=>(t?.setAttributes({[ee.TelemetryAttributes.JobKey]:e}),!await(await this.repeat).removeRepeatableByKey(e)))}async remove(e,{removeChildren:t=!0}={}){return this.trace(ee.SpanKind.INTERNAL,"remove",this.name,async n=>{n?.setAttributes({[ee.TelemetryAttributes.JobId]:e,[ee.TelemetryAttributes.JobOptions]:JSON.stringify({removeChildren:t})});let i=await this.scripts.remove(e,t);return i===1&&this.emit("removed",e),i})}async updateJobProgress(e,t){await this.trace(ee.SpanKind.INTERNAL,"updateJobProgress",this.name,async n=>{n?.setAttributes({[ee.TelemetryAttributes.JobId]:e,[ee.TelemetryAttributes.JobProgress]:JSON.stringify(t)}),await this.scripts.updateProgress(e,t),this.emit("progress",e,t)})}async addJobLog(e,t,n){return Hce.Job.addJobLog(this,e,t,n)}async drain(e=!1){await this.trace(ee.SpanKind.INTERNAL,"drain",this.name,async t=>{t?.setAttributes({[ee.TelemetryAttributes.QueueDrainDelay]:e}),await this.scripts.drain(e)})}async clean(e,t,n="completed"){return this.trace(ee.SpanKind.INTERNAL,"clean",this.name,async i=>{let s=t||1/0,o=Math.min(1e4,s),a=Date.now()-e,c=0,l=[],u=n==="waiting"?"wait":n;for(;c<s;){let d=await this.scripts.cleanJobsInSet(u,a,o);if(this.emit("cleaned",d,u),c+=d.length,l.push(...d),d.length<o)break}return i?.setAttributes({[ee.TelemetryAttributes.QueueGrace]:e,[ee.TelemetryAttributes.JobType]:n,[ee.TelemetryAttributes.QueueCleanLimit]:s,[ee.TelemetryAttributes.JobIds]:l}),l})}async obliterate(e){await this.trace(ee.SpanKind.INTERNAL,"obliterate",this.name,async()=>{await this.pause();let t=0;do t=await this.scripts.obliterate(Object.assign({force:!1,count:1e3},e));while(t)})}async retryJobs(e={}){await this.trace(ee.SpanKind.PRODUCER,"retryJobs",this.name,async t=>{t?.setAttributes({[ee.TelemetryAttributes.QueueOptions]:JSON.stringify(e)});let n=0;do n=await this.scripts.retryJobs(e.state,e.count,e.timestamp);while(n)})}async promoteJobs(e={}){await this.trace(ee.SpanKind.INTERNAL,"promoteJobs",this.name,async t=>{t?.setAttributes({[ee.TelemetryAttributes.QueueOptions]:JSON.stringify(e)});let n=0;do n=await this.scripts.promoteJobs(e.count);while(n)})}async trimEvents(e){return this.trace(ee.SpanKind.INTERNAL,"trimEvents",this.name,async t=>(t?.setAttributes({[ee.TelemetryAttributes.QueueEventMaxLength]:e}),await(await this.client).xtrim(this.keys.events,"MAXLEN",e,{approximate:!0})))}async removeDeprecatedPriorityKey(){return(await this.client).del(this.toKey("priority"))}async removeOrphanedJobs(e=1e3,t=0){let n=await this.client,i=new Set(Object.keys(this.keys)),s=Object.keys(this.keys).filter(d=>d!==""),o=["logs","dependencies","processed","failed","unsuccessful","lock"],a=this.qualifiedName+":",c=a+"*",l=0,u="0";do{let[d,p]=await n.scan(u,{MATCH:c,COUNT:e});u=d;let f=new Set;for(let y of p){let b=y.slice(a.length);if(i.has(b))continue;let g=b.indexOf(":");if(g!==-1){let I=b.slice(0,g);if(i.has(I))continue}let E=g===-1?b:b.slice(0,g);if(g!==-1){let I=b.slice(g+1);if(!o.includes(I))continue}f.add(E)}if(f.size===0)continue;let m=await this.scripts.removeOrphanedJobs([...f],s,o);if(l+=m||0,t>0&&l>=t)break}while(u!=="0");return l}};Pf.Queue=dS});var fS=h(pS=>{"use strict";Object.defineProperty(pS,"__esModule",{value:!0});var et=qt(),Xce=(r,e)=>async function(n,i,s){let o,a,c,l;try{let u=new Promise((d,p)=>{(async()=>{try{c=(m,y)=>{p(new Error("Unexpected exit code: "+m+" signal: "+y))},o=await e.retain(r),o.on("exit",c),a=async m=>{var y,b,g,E,I;try{switch(m.cmd){case et.ParentCommand.Completed:d(m.value);break;case et.ParentCommand.Failed:case et.ParentCommand.Error:{let T=new Error;Object.assign(T,m.value),p(T);break}case et.ParentCommand.Progress:await n.updateProgress(m.value);break;case et.ParentCommand.Log:await n.log(m.value);break;case et.ParentCommand.MoveToDelayed:await n.moveToDelayed((y=m.value)===null||y===void 0?void 0:y.timestamp,(b=m.value)===null||b===void 0?void 0:b.token);break;case et.ParentCommand.MoveToWait:await n.moveToWait((g=m.value)===null||g===void 0?void 0:g.token);break;case et.ParentCommand.MoveToWaitingChildren:{let T=await n.moveToWaitingChildren((E=m.value)===null||E===void 0?void 0:E.token,(I=m.value)===null||I===void 0?void 0:I.opts);o.send({requestId:m.requestId,cmd:et.ChildCommand.MoveToWaitingChildrenResponse,value:T})}break;case et.ParentCommand.Update:await n.updateData(m.value);break;case et.ParentCommand.GetChildrenValues:{let T=await n.getChildrenValues();o.send({requestId:m.requestId,cmd:et.ChildCommand.GetChildrenValuesResponse,value:T})}break;case et.ParentCommand.GetIgnoredChildrenFailures:{let T=await n.getIgnoredChildrenFailures();o.send({requestId:m.requestId,cmd:et.ChildCommand.GetIgnoredChildrenFailuresResponse,value:T})}break;case et.ParentCommand.GetDependenciesCount:{let T=await n.getDependenciesCount(m.value);o.send({requestId:m.requestId,cmd:et.ChildCommand.GetDependenciesCountResponse,value:T})}break;case et.ParentCommand.GetDependencies:{let T=await n.getDependencies(m.value);o.send({requestId:m.requestId,cmd:et.ChildCommand.GetDependenciesResponse,value:T})}break}}catch(T){p(T)}},o.on("message",a),o.send({cmd:et.ChildCommand.Start,job:n.asJSONSandbox(),token:i}),s&&(l=()=>{try{o.send({cmd:et.ChildCommand.Cancel,value:s.reason})}catch{}},s.aborted?l():s.addEventListener("abort",l,{once:!0}))}catch(m){p(m)}})()});return await u,u}finally{s&&l&&s.removeEventListener("abort",l),o&&(o.off("message",a),o.off("exit",c),o.exitCode===null&&o.signalCode===null&&e.release(o))}};pS.default=Xce});var eq=h((Lf,Z2)=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});Lf.Worker=void 0;var Nf=require("fs"),Zce=require("url"),kc=require("path"),ele=Wu(),Jo=Wt(),tle=Ii(),rle=Mf(),nle=Fg(),ile=hc(),X2=fc(),sle=fS(),ole=Dg(),Uo=ud(),te=qt(),ale=kf(),cle=iS(),lle=10,mS=class extends tle.QueueBase{static RateLimitError(){return new Uo.RateLimitError}constructor(e,t,n,i){if(super(e,Object.assign(Object.assign({drainDelay:5,concurrency:1,lockDuration:3e4,maximumRateLimitDelay:3e4,maxStalledCount:1,stalledInterval:3e4,autorun:!0,runRetryDelay:15e3},n),{blockingConnection:!0}),i),this.abortDelayController=null,this.blockUntil=0,this.drained=!1,this.limitUntil=0,this.processorAcceptsSignal=!1,this.stalledCheckerRunning=!1,this.waiting=null,this.running=!1,this.mainLoopRunning=null,!n||!n.connection)throw new Error("Worker requires a connection");if(typeof this.opts.maxStalledCount!="number"||this.opts.maxStalledCount<0)throw new Error("maxStalledCount must be greater or equal than 0");if(typeof this.opts.maxStartedAttempts=="number"&&this.opts.maxStartedAttempts<0)throw new Error("maxStartedAttempts must be greater or equal than 0");if(typeof this.opts.stalledInterval!="number"||this.opts.stalledInterval<=0)throw new Error("stalledInterval must be greater than 0");if(typeof this.opts.drainDelay!="number"||this.opts.drainDelay<=0)throw new Error("drainDelay must be greater than 0");if(this.concurrency=this.opts.concurrency,this.opts.lockRenewTime=this.opts.lockRenewTime||this.opts.lockDuration/2,this.id=(0,Jo.randomUUID)(),this.createLockManager(),t){if(typeof t=="function")this.processFn=t,this.processorAcceptsSignal=t.length>=3;else{if(t instanceof Zce.URL){if(!Nf.existsSync(t))throw new Error(`URL ${t} does not exist in the local file system`);t=t.href}else{let d=t+([".js",".ts",".flow",".cjs",".mjs"].includes(kc.extname(t))?"":".js");if(!Nf.existsSync(d))throw new Error(`File ${d} does not exist`)}let o=kc.dirname(Z2.filename||__filename),a=kc.join(o,"main-worker.js"),c=kc.join(o,"main.js"),l=this.opts.useWorkerThreads?a:c;try{Nf.statSync(l)}catch{let d=this.opts.useWorkerThreads?"main-worker.js":"main.js";l=kc.join(process.cwd(),`dist/cjs/classes/${d}`),Nf.statSync(l)}this.childPool=new nle.ChildPool({mainFile:l,useWorkerThreads:this.opts.useWorkerThreads,workerForkOptions:this.opts.workerForkOptions,workerThreadsOptions:this.opts.workerThreadsOptions}),this.createSandbox(t),this.processorAcceptsSignal=!0}this.opts.autorun&&this.run().catch(o=>this.emit("error",o))}let s=this.clientName()+(this.opts.name?`:w:${this.opts.name}`:"");this.blockingConnection=new ile.RedisConnection((0,Jo.isRedisInstance)(n.connection)?((0,X2.isIRedisClient)(n.connection)?n.connection:(0,X2.createIORedisClient)(n.connection)).duplicate({connectionName:s}):Object.assign(Object.assign({},n.connection),{connectionName:s}),{shared:!1,blocking:!0,skipVersionCheck:n.skipVersionCheck}),this.blockingConnection.on("error",o=>this.emit("error",o)),this.blockingConnection.on("ready",()=>setTimeout(()=>this.emit("ready"),0))}createLockManager(){this.lockManager=new cle.LockManager(this,{lockRenewTime:this.opts.lockRenewTime,lockDuration:this.opts.lockDuration,workerId:this.id,workerName:this.opts.name})}createSandbox(e){this.processFn=(0,sle.default)(e,this.childPool).bind(this)}async extendJobLocks(e,t,n){return this.scripts.extendLocks(e,t,n)}emit(e,...t){return super.emit(e,...t)}off(e,t){return super.off(e,t),this}on(e,t){return super.on(e,t),this}once(e,t){return super.once(e,t),this}callProcessJob(e,t,n){return this.processFn(e,t,n)}createJob(e,t){return this.Job.fromJSON(this,e,t)}async waitUntilReady(){return await super.waitUntilReady(),this.blockingConnection.client}cancelJob(e,t){return this.lockManager.cancelJob(e,t)}cancelAllJobs(e){this.lockManager.cancelAllJobs(e)}set concurrency(e){if(typeof e!="number"||e<1||!isFinite(e))throw new Error("concurrency must be a finite number greater than 0");this._concurrency=e}get concurrency(){return this._concurrency}get repeat(){return new Promise(async e=>{if(!this._repeat){let t=await this.client;this._repeat=new rle.Repeat(this.name,Object.assign(Object.assign({},this.opts),{connection:t})),this._repeat.on("error",this.emit.bind(this,"error"))}e(this._repeat)})}get jobScheduler(){return new Promise(async e=>{if(!this._jobScheduler){let t=await this.client;this._jobScheduler=new ale.JobScheduler(this.name,Object.assign(Object.assign({},this.opts),{connection:t})),this._jobScheduler.on("error",this.emit.bind(this,"error"))}e(this._jobScheduler)})}async run(){if(!this.processFn)throw new Error("No process function is defined.");if(this.running)throw new Error("Worker is already running.");try{if(this.running=!0,this.closing||this.paused)return;await this.startStalledCheckTimer(),this.opts.skipLockRenewal||this.lockManager.start();let e=await this.client,t=await this.blockingConnection.client;this.mainLoopRunning=this.mainLoop(e,t),await this.mainLoopRunning}finally{this.running=!1}}async waitForRateLimit(){var e;let t=this.limitUntil;if(t>Date.now()){(e=this.abortDelayController)===null||e===void 0||e.abort(),this.abortDelayController=new ele.AbortController;let n=this.getRateLimitDelay(t-Date.now());await this.delay(n,this.abortDelayController),this.drained=!1,this.limitUntil=0}}async mainLoop(e,t){let n=new ole.AsyncFifoQueue,i=0;for(;!this.closing&&!this.paused||n.numTotal()>0;){for(;!this.closing&&!this.paused&&!this.waiting&&n.numTotal()<this._concurrency&&!this.isRateLimited();){let o=`${this.id}:${i++}`,a=this.retryIfFailed(()=>this._getNextJob(e,t,o,{block:!0}),{delayInMs:this.opts.runRetryDelay,onlyEmitError:!0});if(n.add(a),this.waiting&&n.numTotal()>1||!await a&&n.numTotal()>1||this.blockUntil)break}let s;do s=await n.fetch();while(!s&&n.numQueued()>0);if(s){let o=s.token;n.add(this.processJob(s,o,()=>n.numTotal()<=this._concurrency))}else n.numQueued()===0&&await this.waitForRateLimit()}}async getNextJob(e,{block:t=!0}={}){var n,i;let s=await this._getNextJob(await this.client,await this.blockingConnection.client,e,{block:t});return this.trace(te.SpanKind.INTERNAL,"getNextJob",this.name,async o=>(o?.setAttributes({[te.TelemetryAttributes.WorkerId]:this.id,[te.TelemetryAttributes.QueueName]:this.name,[te.TelemetryAttributes.WorkerName]:this.opts.name,[te.TelemetryAttributes.WorkerOptions]:JSON.stringify({block:t}),[te.TelemetryAttributes.JobId]:s?.id}),s),(i=(n=s?.opts)===null||n===void 0?void 0:n.telemetry)===null||i===void 0?void 0:i.metadata)}async _getNextJob(e,t,n,{block:i=!0}={}){if(this.paused||this.closing)return;let s;if(this.drained&&i&&!this.limitUntil&&!this.waiting){this.waiting=this.waitForJob(t,this.blockUntil);try{this.blockUntil=await this.waiting,(this.blockUntil<=0||this.blockUntil-Date.now()<1)&&(s=await this.moveToActive(e,n,this.opts.name))}finally{this.waiting=null}}else this.isRateLimited()||(s=await this.moveToActive(e,n,this.opts.name));return s&&this.emit("active",s,"waiting"),s}async rateLimit(e){await this.trace(te.SpanKind.INTERNAL,"rateLimit",this.name,async t=>{t?.setAttributes({[te.TelemetryAttributes.WorkerId]:this.id,[te.TelemetryAttributes.WorkerRateLimit]:e}),await this.client.then(n=>n.set(this.keys.limiter,Number.MAX_SAFE_INTEGER,{PX:e}))})}get minimumBlockTimeout(){return this.blockingConnection.capabilities.canBlockFor1Ms?.001:.002}isRateLimited(){return this.limitUntil>Date.now()}async moveToActive(e,t,n){let[i,s,o,a]=await this.scripts.moveToActive(e,t,n);return this.updateDelays(o,a),this.nextJobFromJobData(i,s,t)}async waitForJob(e,t){if(this.paused)return 1/0;let n;try{if(!this.closing&&!this.isRateLimited()){let i=this.getBlockTimeout(t);if(i>0){i=this.blockingConnection.capabilities.canDoubleTimeout?i:Math.ceil(i),n=setTimeout(async()=>{e.disconnect(!this.closing)},i*1e3+1e3),this.updateDelays();let s=await e.bzpopmin(this.keys.marker,i);if(s){let[,o,a]=s;if(o){let c=parseInt(a);return t&&c>t?t:c}}}return 0}}catch(i){(0,Jo.isNotConnectionError)(i)&&this.emit("error",i),this.closing||await this.delay()}finally{clearTimeout(n)}return 1/0}getBlockTimeout(e){let t=this.opts;if(e){let n=e-Date.now();return n<=0?n:n<this.minimumBlockTimeout*1e3?this.minimumBlockTimeout:Math.min(n/1e3,lle)}else return Math.max(t.drainDelay,this.minimumBlockTimeout)}getRateLimitDelay(e){return Math.min(e,this.opts.maximumRateLimitDelay)}async delay(e,t){await(0,Jo.delay)(e||Jo.DELAY_TIME_1,t)}updateDelays(e=0,t=0){let n=Math.max(e,0);n>0?this.limitUntil=Date.now()+n:this.limitUntil=0,this.blockUntil=Math.max(t,0)||0}async nextJobFromJobData(e,t,n){if(!e)this.drained||(this.emit("drained"),this.drained=!0);else{this.drained=!1;let i=this.createJob(e,t);i.token=n;try{await this.retryIfFailed(async()=>{let s=!!i.repeatJobKey,o=s&&i.repeatJobKey.split(":").length>=5,a=s&&!o;o&&(a=await(await this.jobScheduler).isJobScheduler(i.repeatJobKey)),a?await(await this.jobScheduler).upsertJobScheduler(i.repeatJobKey,i.opts.repeat,i.name,i.data,i.opts,{override:!1,producerId:i.id}):i.opts.repeat&&await(await this.repeat).updateRepeatableJob(i.name,i.data,i.opts,{override:!1})},{delayInMs:this.opts.runRetryDelay})}catch(s){let o=s instanceof Error?s.message:String(s),a=new Error(`Failed to add repeatable job for next iteration: ${o}`);this.emit("error",a);return}return i}}async processJob(e,t,n=()=>!0){var i,s;let o=(s=(i=e.opts)===null||i===void 0?void 0:i.telemetry)===null||s===void 0?void 0:s.metadata;return this.trace(te.SpanKind.CONSUMER,"process",this.name,async a=>{a?.setAttributes({[te.TelemetryAttributes.WorkerId]:this.id,[te.TelemetryAttributes.WorkerName]:this.opts.name,[te.TelemetryAttributes.JobId]:e.id,[te.TelemetryAttributes.JobName]:e.name});let c=this.lockManager.trackJob(e.id,t,e.processedOn,this.processorAcceptsSignal);try{let l=this.getUnrecoverableErrorMessage(e);if(l)return await this.retryIfFailed(()=>(this.lockManager.untrackJob(e.id),this.handleFailed(new Uo.UnrecoverableError(l),e,t,n,a)),{delayInMs:this.opts.runRetryDelay,span:a});let u=await this.callProcessJob(e,t,c?c.signal:void 0);return await this.retryIfFailed(()=>(this.lockManager.untrackJob(e.id),this.handleCompleted(u,e,t,n,a)),{delayInMs:this.opts.runRetryDelay,span:a})}catch(l){return await this.retryIfFailed(()=>(this.lockManager.untrackJob(e.id),this.handleFailed(l,e,t,n,a)),{delayInMs:this.opts.runRetryDelay,span:a,onlyEmitError:!0})}finally{this.lockManager.untrackJob(e.id);let l=Date.now();a?.setAttributes({[te.TelemetryAttributes.JobFinishedTimestamp]:l,[te.TelemetryAttributes.JobAttemptFinishedTimestamp]:e.finishedOn||l,[te.TelemetryAttributes.JobProcessedTimestamp]:e.processedOn})}},o)}getUnrecoverableErrorMessage(e){if(e.deferredFailure)return e.deferredFailure;if(this.opts.maxStartedAttempts&&this.opts.maxStartedAttempts<e.attemptsStarted)return"job started more than allowable limit"}async handleCompleted(e,t,n,i=()=>!0,s){if(!this.connection.closing){let o=await t.moveToCompleted(e,n,i()&&!(this.closing||this.paused));if(this.emit("completed",t,e,"active"),s?.addEvent("job completed",{[te.TelemetryAttributes.JobResult]:JSON.stringify(e)}),s?.setAttributes({[te.TelemetryAttributes.JobAttemptsMade]:t.attemptsMade}),Array.isArray(o)){let[a,c,l,u]=o;return this.updateDelays(l,u),this.nextJobFromJobData(a,c,n)}}}async handleFailed(e,t,n,i=()=>!0,s){if(!this.connection.closing){if(e.message===Uo.RATE_LIMIT_ERROR){let c=await this.moveLimitedBackToWait(t,n);this.limitUntil=c>0?Date.now()+c:0;return}let o=i()&&!(this.closing||this.paused);if(e instanceof Uo.DelayedError||e.name=="DelayedError"||e instanceof Uo.WaitingError||e.name=="WaitingError"||e instanceof Uo.WaitingChildrenError||e.name=="WaitingChildrenError"){if(!o)return;let c=await this.client;return this.moveToActive(c,n,this.opts.name)}let a=await t.moveToFailed(e,n,o);if(this.emit("failed",t,e,"active"),s?.addEvent("job failed",{[te.TelemetryAttributes.JobFailedReason]:e.message}),s?.setAttributes({[te.TelemetryAttributes.JobAttemptsMade]:t.attemptsMade}),Array.isArray(a)){let[c,l,u,d]=a;return this.updateDelays(u,d),this.nextJobFromJobData(c,l,n)}}}async pause(e){await this.trace(te.SpanKind.INTERNAL,"pause",this.name,async t=>{var n;t?.setAttributes({[te.TelemetryAttributes.WorkerId]:this.id,[te.TelemetryAttributes.WorkerName]:this.opts.name,[te.TelemetryAttributes.WorkerDoNotWaitActive]:e}),this.paused||(this.paused=!0,e||await this.whenCurrentJobsFinished(),(n=this.stalledCheckStopper)===null||n===void 0||n.call(this),this.emit("paused"))})}resume(){(!this.running||this.paused)&&this.trace(te.SpanKind.INTERNAL,"resume",this.name,e=>{e?.setAttributes({[te.TelemetryAttributes.WorkerId]:this.id,[te.TelemetryAttributes.WorkerName]:this.opts.name}),this.paused=!1,this.running?this.startStalledCheckTimer().catch(t=>{this.emit("error",t)}):this.processFn&&this.run(),this.emit("resumed")}).catch(e=>{this.emit("error",e)})}isPaused(){return!!this.paused}isRunning(){return this.running}async close(e=!1){return this.closing?this.closing:(this.closing=(async()=>{await this.trace(te.SpanKind.INTERNAL,"close",this.name,async t=>{var n,i;t?.setAttributes({[te.TelemetryAttributes.WorkerId]:this.id,[te.TelemetryAttributes.WorkerName]:this.opts.name,[te.TelemetryAttributes.WorkerForceClose]:e}),this.emit("closing","closing queue"),(n=this.abortDelayController)===null||n===void 0||n.abort();let s=[()=>e||this.whenCurrentJobsFinished(!1),()=>this.lockManager.close(),()=>{var o;return(o=this.childPool)===null||o===void 0?void 0:o.clean()},()=>this.blockingConnection.close(e),()=>this.connection.close(e)];for(let o of s)try{await o()}catch(a){this.emit("error",a)}(i=this.stalledCheckStopper)===null||i===void 0||i.call(this),this.closed=!0,this.emit("closed")})})(),await this.closing)}async startStalledCheckTimer(){this.opts.skipStalledCheck||!this.closing&&!this.stalledCheckerRunning&&await this.trace(te.SpanKind.INTERNAL,"startStalledCheckTimer",this.name,async e=>{e?.setAttributes({[te.TelemetryAttributes.WorkerId]:this.id,[te.TelemetryAttributes.WorkerName]:this.opts.name}),this.stalledCheckerRunning=!0,this.stalledChecker().catch(t=>{this.emit("error",t)}).finally(()=>{this.stalledCheckerRunning=!1})})}async stalledChecker(){for(;!(this.closing||this.paused);)await this.checkConnectionError(()=>this.moveStalledJobsToWait()),await new Promise(e=>{let t=setTimeout(e,this.opts.stalledInterval);this.stalledCheckStopper=()=>{clearTimeout(t),e()}})}async whenCurrentJobsFinished(e=!0){this.mainLoopRunning?(await this.blockingConnection.disconnect(!0),await this.mainLoopRunning):e=!1,e&&await this.blockingConnection.reconnect()}async retryIfFailed(e,t){var n;let i=0,s=t.maxRetries||1/0;do try{return await e()}catch(o){if((n=t.span)===null||n===void 0||n.recordException(o.message),(0,Jo.isNotConnectionError)(o)){if(!this.paused&&!this.closing&&this.emit("error",o),t.onlyEmitError)return;throw o}else if(t.delayInMs&&!this.closing&&!this.closed&&await this.delay(t.delayInMs,this.abortDelayController),i+1>=s)throw o}while(++i<s)}async moveStalledJobsToWait(){await this.trace(te.SpanKind.INTERNAL,"moveStalledJobsToWait",this.name,async e=>{let t=await this.scripts.moveStalledJobsToWait();e?.setAttributes({[te.TelemetryAttributes.WorkerId]:this.id,[te.TelemetryAttributes.WorkerName]:this.opts.name,[te.TelemetryAttributes.WorkerStalledJobs]:t}),t.forEach(n=>{e?.addEvent("job stalled",{[te.TelemetryAttributes.JobId]:n}),this.emit("stalled",n,"active")})})}moveLimitedBackToWait(e,t){return e.moveToWait(t)}};Lf.Worker=mS});var tq=h(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});var Ke=(St(),dt(Et));Ke.__exportStar(Dg(),Ie);Ke.__exportStar(Mg(),Ie);Ke.__exportStar(Ng(),Ie);Ke.__exportStar(Fg(),Ie);Ke.__exportStar(Hj(),Ie);Ke.__exportStar(ud(),Ie);Ke.__exportStar(QN(),Ie);Ke.__exportStar(fc(),Ie);Ke.__exportStar(ZN(),Ie);Ke.__exportStar(rL(),Ie);Ke.__exportStar(vo(),Ie);Ke.__exportStar(kf(),Ie);Ke.__exportStar(iS(),Ie);Ke.__exportStar(Ii(),Ie);Ke.__exportStar(H2(),Ie);Ke.__exportStar(V2(),Ie);Ke.__exportStar(lS(),Ie);Ke.__exportStar(Dd(),Ie);Ke.__exportStar(Q2(),Ie);Ke.__exportStar(hc(),Ie);Ke.__exportStar(Mf(),Ie);Ke.__exportStar(fS(),Ie);Ke.__exportStar($v(),Ie);Ke.__exportStar(eq(),Ie)});var nq=h(rq=>{"use strict";Object.defineProperty(rq,"__esModule",{value:!0})});var sq=h(iq=>{"use strict";Object.defineProperty(iq,"__esModule",{value:!0})});var aq=h(oq=>{"use strict";Object.defineProperty(oq,"__esModule",{value:!0})});var lq=h(cq=>{"use strict";Object.defineProperty(cq,"__esModule",{value:!0})});var dq=h(uq=>{"use strict";Object.defineProperty(uq,"__esModule",{value:!0})});var fq=h(pq=>{"use strict";Object.defineProperty(pq,"__esModule",{value:!0})});var hq=h(mq=>{"use strict";Object.defineProperty(mq,"__esModule",{value:!0})});var bq=h(yq=>{"use strict";Object.defineProperty(yq,"__esModule",{value:!0})});var vq=h(gq=>{"use strict";Object.defineProperty(gq,"__esModule",{value:!0})});var Sq=h(Eq=>{"use strict";Object.defineProperty(Eq,"__esModule",{value:!0})});var _q=h(xq=>{"use strict";Object.defineProperty(xq,"__esModule",{value:!0})});var Iq=h(wq=>{"use strict";Object.defineProperty(wq,"__esModule",{value:!0})});var Aq=h(Tq=>{"use strict";Object.defineProperty(Tq,"__esModule",{value:!0})});var Oq=h(kq=>{"use strict";Object.defineProperty(kq,"__esModule",{value:!0})});var Cq=h(Rq=>{"use strict";Object.defineProperty(Rq,"__esModule",{value:!0})});var jq=h(Kq=>{"use strict";Object.defineProperty(Kq,"__esModule",{value:!0})});var Mq=h(Dq=>{"use strict";Object.defineProperty(Dq,"__esModule",{value:!0})});var Nq=h(Pq=>{"use strict";Object.defineProperty(Pq,"__esModule",{value:!0})});var qq=h(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0});qf.ClientType=void 0;var Lq;(function(r){r.blocking="blocking",r.normal="normal"})(Lq||(qf.ClientType=Lq={}))});var Jq=h(Fq=>{"use strict";Object.defineProperty(Fq,"__esModule",{value:!0})});var Gq=h(Uq=>{"use strict";Object.defineProperty(Uq,"__esModule",{value:!0})});var $q=h(Bq=>{"use strict";Object.defineProperty(Bq,"__esModule",{value:!0})});var Vq=h(Hq=>{"use strict";Object.defineProperty(Hq,"__esModule",{value:!0})});var Yq=h(Wq=>{"use strict";Object.defineProperty(Wq,"__esModule",{value:!0})});var Qq=h(zq=>{"use strict";Object.defineProperty(zq,"__esModule",{value:!0})});var Zq=h(Xq=>{"use strict";Object.defineProperty(Xq,"__esModule",{value:!0})});var tF=h(eF=>{"use strict";Object.defineProperty(eF,"__esModule",{value:!0})});var nF=h(rF=>{"use strict";Object.defineProperty(rF,"__esModule",{value:!0})});var sF=h(iF=>{"use strict";Object.defineProperty(iF,"__esModule",{value:!0})});var aF=h(oF=>{"use strict";Object.defineProperty(oF,"__esModule",{value:!0})});var lF=h(cF=>{"use strict";Object.defineProperty(cF,"__esModule",{value:!0})});var dF=h(uF=>{"use strict";Object.defineProperty(uF,"__esModule",{value:!0})});var fF=h(pF=>{"use strict";Object.defineProperty(pF,"__esModule",{value:!0})});var hF=h(mF=>{"use strict";Object.defineProperty(mF,"__esModule",{value:!0})});var yF=h(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});var de=(St(),dt(Et));de.__exportStar(nq(),ae);de.__exportStar(sq(),ae);de.__exportStar(aq(),ae);de.__exportStar(lq(),ae);de.__exportStar(dq(),ae);de.__exportStar(fq(),ae);de.__exportStar(hq(),ae);de.__exportStar(bq(),ae);de.__exportStar(vq(),ae);de.__exportStar(Sq(),ae);de.__exportStar(_q(),ae);de.__exportStar(Iq(),ae);de.__exportStar(Aq(),ae);de.__exportStar(Oq(),ae);de.__exportStar(Cq(),ae);de.__exportStar(jq(),ae);de.__exportStar(Mq(),ae);de.__exportStar(Nq(),ae);de.__exportStar(qq(),ae);de.__exportStar(Jq(),ae);de.__exportStar(Gq(),ae);de.__exportStar($q(),ae);de.__exportStar(Vq(),ae);de.__exportStar(Yq(),ae);de.__exportStar(Qq(),ae);de.__exportStar(Zq(),ae);de.__exportStar(tF(),ae);de.__exportStar(nF(),ae);de.__exportStar(sF(),ae);de.__exportStar(aF(),ae);de.__exportStar(lF(),ae);de.__exportStar(dF(),ae);de.__exportStar(fF(),ae);de.__exportStar(hF(),ae)});var gF=h(bF=>{"use strict";Object.defineProperty(bF,"__esModule",{value:!0})});var EF=h(vF=>{"use strict";Object.defineProperty(vF,"__esModule",{value:!0})});var xF=h(SF=>{"use strict";Object.defineProperty(SF,"__esModule",{value:!0})});var wF=h(_F=>{"use strict";Object.defineProperty(_F,"__esModule",{value:!0})});var TF=h(IF=>{"use strict";Object.defineProperty(IF,"__esModule",{value:!0})});var kF=h(AF=>{"use strict";Object.defineProperty(AF,"__esModule",{value:!0})});var RF=h(OF=>{"use strict";Object.defineProperty(OF,"__esModule",{value:!0})});var KF=h(CF=>{"use strict";Object.defineProperty(CF,"__esModule",{value:!0})});var DF=h(jF=>{"use strict";Object.defineProperty(jF,"__esModule",{value:!0})});var PF=h(MF=>{"use strict";Object.defineProperty(MF,"__esModule",{value:!0})});var LF=h(NF=>{"use strict";Object.defineProperty(NF,"__esModule",{value:!0})});var qF=h(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});var Nr=(St(),dt(Et));Nr.__exportStar(gF(),ir);Nr.__exportStar(EF(),ir);Nr.__exportStar(xF(),ir);Nr.__exportStar(wF(),ir);Nr.__exportStar(TF(),ir);Nr.__exportStar(kF(),ir);Nr.__exportStar(RF(),ir);Nr.__exportStar(KF(),ir);Nr.__exportStar(DF(),ir);Nr.__exportStar(PF(),ir);Nr.__exportStar(LF(),ir)});var JF=h(FF=>{"use strict";Object.defineProperty(FF,"__esModule",{value:!0})});var UF=h(jn=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});var ys=(St(),dt(Et));ys.__exportStar(tq(),jn);ys.__exportStar(qt(),jn);ys.__exportStar(yF(),jn);ys.__exportStar(qF(),jn);ys.__exportStar(Wt(),jn);ys.__exportStar(JF(),jn);ys.__exportStar(Kd(),jn)});var Go,ule,Ff,GF=R(()=>{"use strict";Go=ze(UF(),1);se();ule=300*1e3,Ff=class r{name;config;concurrency;lockDurationMs;defaultJobOptions;queueFactory;workerFactory;queue=null;worker=null;queueEvents=null;started=!1;counters={stalled:0,errored:0};listeners=[];jobStartTimes=new Map;recentlyStalled=new Map;static STALLED_DEDUPE_WINDOW_MS=3e4;constructor(e){this.name=e.name,this.config=e.config,this.concurrency=e.concurrency??1,this.lockDurationMs=e.lockDurationMs??ule,this.defaultJobOptions=e.defaultJobOptions??{attempts:3,backoff:{type:"exponential",delay:5e3},removeOnComplete:{age:10080*60,count:1e3},removeOnFail:{age:720*60*60,count:1e3}},this.queueFactory=e.queueFactory,this.workerFactory=e.workerFactory}getQueue(){if(this.queue)return this.queue;let e={connection:this.config.connection,prefix:this.config.prefix,defaultJobOptions:this.defaultJobOptions};return this.queue=this.queueFactory?this.queueFactory(this.name,e):new Go.Queue(this.name,e),this.queue}async add(e,t,n){if(e.includes(":"))throw new Error(`server job ID must not contain ':' (got ${e})`);try{await this.getQueue().add(this.name,t,{...this.defaultJobOptions,...n,jobId:e})}catch(i){throw this.toRedisUnavailableError(i)}}async getJob(e){try{return await this.getQueue().getJob(e)}catch(t){throw this.toRedisUnavailableError(t)}}async remove(e){try{await this.getQueue().remove(e)}catch(t){throw this.toRedisUnavailableError(t)}}async getCounts(){try{let e=await this.getQueue().getJobCounts("waiting","active","delayed","failed","completed");return{waiting:e.waiting??0,active:e.active??0,delayed:e.delayed??0,failed:e.failed??0,completed:e.completed??0}}catch(e){throw this.toRedisUnavailableError(e)}}notifyStalled(e,t){if(this.recentlyStalled.has(e)){_.debug?.("QUEUE",`[generation] job=${e} stalled (suppressed duplicate from ${t})`,{queue:this.name,jobId:e,source:t});return}let n=setTimeout(()=>{this.recentlyStalled.delete(e)},r.STALLED_DEDUPE_WINDOW_MS);typeof n.unref=="function"&&n.unref(),this.recentlyStalled.set(e,n),this.counters.stalled+=1,_.warn("QUEUE",`[generation] job=${e} stalled${t==="queue-events"?" (queue-events)":""}`,{queue:this.name,jobId:e,source:t});for(let i of this.listeners)try{i.onStalled?.(e)}catch{}}notifyQueueError(e,t){this.counters.errored+=1,_.warn("QUEUE",`${this.name} ${t} error`,{error:e instanceof Error?e.message:String(e)});for(let n of this.listeners)try{n.onError?.(e)}catch{}}start(e){if(this.started)throw new Error(`ServerJobQueue ${this.name} is already started`);let t={connection:this.config.connection,prefix:this.config.prefix,autorun:!1,concurrency:this.concurrency,lockDuration:this.lockDurationMs},n=this.workerFactory?this.workerFactory(this.name,e,t):new Go.Worker(this.name,e,t);if(n.on("error",i=>this.notifyQueueError(i,"worker")),typeof n.on=="function"){let i=n;i.on("active",s=>{s.id&&this.jobStartTimes.set(s.id,Date.now())}),i.on("completed",(s,o)=>{let a=s.id?this.jobStartTimes.get(s.id):void 0,c=a?Date.now()-a:0;s.id&&this.jobStartTimes.delete(s.id);let l=s.data?.source_type??"?";_.info("QUEUE",`[generation] job=${s.id??"?"} source_type=${l} duration=${c}ms`,{queue:this.name,jobId:s.id??null,sourceType:l,durationMs:c});for(let u of this.listeners)try{u.onCompleted?.(s.id??"?",c,o)}catch{}}),i.on("failed",(s,o)=>{s?.id&&this.jobStartTimes.delete(s.id);let a=s?.data?.source_type??"?",c=s?.attemptsMade??0;_.warn("QUEUE",`[generation] job=${s?.id??"?"} source_type=${a} attempts=${c} reason=${o.message}`,{queue:this.name,jobId:s?.id??null,sourceType:a,attemptsMade:c,reason:o.message});for(let l of this.listeners)try{l.onFailed?.(s?.id,c,o.message)}catch{}}),i.on("progress",(s,o)=>{_.debug?.("QUEUE",`[generation] job=${s.id??"?"} progress`,{queue:this.name,jobId:s.id??null,progress:o})}),i.on("stalled",s=>this.notifyStalled(s,"worker"))}if(n.run(),this.worker=n,!this.workerFactory)try{let i=new Go.QueueEvents(this.name,{connection:this.config.connection,prefix:this.config.prefix});i.on("stalled",({jobId:s})=>this.notifyStalled(s,"queue-events")),i.on("error",s=>this.notifyQueueError(s,"queue-events")),this.queueEvents=i}catch(i){_.warn("QUEUE",`${this.name} failed to start QueueEvents listener`,{error:i instanceof Error?i.message:String(i)})}this.started=!0}observe(e){this.listeners.push(e)}getLifecycleCounters(){return{...this.counters}}isStarted(){return this.started}async close(){let e=[];if(this.queueEvents){try{await this.queueEvents.close()}catch(t){e.push(t instanceof Error?t:new Error(String(t)))}this.queueEvents=null}if(this.worker){try{await this.worker.close()}catch(t){e.push(t instanceof Error?t:new Error(String(t)))}this.worker=null,this.started=!1}if(this.queue){try{await this.queue.close()}catch(t){e.push(t instanceof Error?t:new Error(String(t)))}this.queue=null}for(let t of this.recentlyStalled.values())clearTimeout(t);if(this.recentlyStalled.clear(),e.length>0)throw e[0]}toRedisUnavailableError(e){let t=e instanceof Error?e.message:String(e);return new Error(`ServerJobQueue ${this.name} requires Redis/Valkey when CLAUDE_MEM_QUEUE_ENGINE=bullmq: ${t}`)}}});var hS,bs,yS=R(()=>{"use strict";GF();Tu();se();hS=["event","event-batch","summary","reindex"],bs=class{constructor(e,t){this.config=e;if(e.engine!=="bullmq")throw new Error(`ActiveServerBetaQueueManager requires CLAUDE_MEM_QUEUE_ENGINE=bullmq (got ${e.engine}); do not instantiate when bullmq is not selected.`);this.queues=t??this.buildQueues(e)}config;kind="queue-manager";queues;closed=!1;getQueue(e){let t=this.queues.get(e);if(!t)throw new Error(`unknown server generation job kind: ${e}`);return t}start(e,t){this.getQueue(e).start(t)}getHealth(){if(this.closed)return{status:"errored",reason:"queue-manager closed"};let e=hS.map(t=>({kind:t,name:Ua[t]}));return{status:"active",reason:"BullMQ-backed queue manager wired",details:{engine:this.config.engine,mode:this.config.mode,host:this.config.host,port:this.config.port,prefix:this.config.prefix,lanes:e}}}async getLaneMetrics(){let e=[];for(let t of hS){let n=this.queues.get(t);if(!n)continue;let i=n.getLifecycleCounters();try{let s=await n.getCounts();e.push({kind:t,name:Ua[t],waiting:s.waiting,active:s.active,completed:s.completed,failed:s.failed,delayed:s.delayed,stalled:i.stalled,unavailable:!1})}catch(s){e.push({kind:t,name:Ua[t],waiting:0,active:0,completed:0,failed:0,delayed:0,stalled:i.stalled,unavailable:!0,unavailableReason:s instanceof Error?s.message:String(s)})}}return e}async close(){if(this.closed)return;this.closed=!0;let e=[];for(let t of this.queues.values())try{await t.close()}catch(n){e.push(n instanceof Error?n:new Error(String(n)))}if(e.length>0)throw _.warn("QUEUE","errors closing server-beta queue manager",{count:e.length,first:e[0].message}),e[0]}buildQueues(e){let t=new Map;for(let n of hS)t.set(n,new Ff({name:Ua[n],config:e}));return t}}});var bS,Oc,Bf,BF,Uf,Jf,Gf,$F=R(()=>{"use strict";bS=ze(zl(),1),Oc=ze(require("path"),1),Bf=require("fs");kt();se();BF=(()=>{let r=Fi();return[Oc.default.join(r,"ui","viewer.html"),Oc.default.join(r,"plugin","ui","viewer.html")]})(),Uf=BF.find(r=>(0,Bf.existsSync)(r))??null,Jf=Uf?(0,Bf.readFileSync)(Uf):null;Uf?_.info("SYSTEM","Cached viewer.html at boot (server runtime)",{path:Uf,bytes:Jf.byteLength}):_.warn("SYSTEM","viewer.html not found for server runtime",{candidates:BF});Gf=class{setupRoutes(e){let t=Fi();e.use(bS.default.static(Oc.default.join(t,"ui"))),e.use(bS.default.static(Oc.default.join(t,"plugin","ui"))),e.get("/",(n,i)=>{if(!Jf){i.status(503).json({error:"ViewerUnavailable",message:"Viewer UI not found at any expected location"});return}i.setHeader("Content-Type","text/html; charset=utf-8"),i.send(Jf)})}static hasViewerHtml(){return Jf!==null}}});var HF=R(()=>{"use strict";se()});var gS=R(()=>{"use strict";se();HF()});var VF=R(()=>{"use strict";se();gS()});var WF=R(()=>{"use strict"});var YF=R(()=>{"use strict"});var ple,zF=R(()=>{"use strict";ple=require("bun:sqlite");kt();se();VF();WF();YF()});var Rc,$f,Je,Dn=R(()=>{"use strict";Rc=require("fs"),$f=require("path");se();kt();Je=class r{static instance=null;activeMode=null;modesDir;constructor(){let e=Fi(),t=[(0,$f.join)(e,"modes"),(0,$f.join)(e,"..","plugin","modes")],n=t.find(i=>(0,Rc.existsSync)(i));this.modesDir=n||t[0]}static getInstance(){return r.instance||(r.instance=new r),r.instance}parseInheritance(e){let t=e.split("--");if(t.length===1)return{hasParent:!1,parentId:"",overrideId:""};if(t.length>2)throw new Error(`Invalid mode inheritance: ${e}. Only one level of inheritance supported (parent--override)`);return{hasParent:!0,parentId:t[0],overrideId:e}}isPlainObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}deepMerge(e,t){let n={...e};for(let i in t){let s=t[i],o=e[i];this.isPlainObject(s)&&this.isPlainObject(o)?n[i]=this.deepMerge(o,s):n[i]=s}return n}loadModeFile(e){let t=(0,$f.join)(this.modesDir,`${e}.json`);if(!(0,Rc.existsSync)(t))throw new Error(`Mode file not found: ${t}`);let n=(0,Rc.readFileSync)(t,"utf-8");return JSON.parse(n)}loadMode(e){let t=this.parseInheritance(e);if(!t.hasParent)try{let c=this.loadModeFile(e);return this.activeMode=c,_.debug("SYSTEM",`Loaded mode: ${c.name} (${e})`,void 0,{types:c.observation_types.map(l=>l.id),concepts:c.observation_concepts.map(l=>l.id)}),c}catch(c){if(c instanceof Error?_.warn("WORKER",`Mode file not found: ${e}, falling back to 'code'`,{message:c.message}):_.warn("WORKER",`Mode file not found: ${e}, falling back to 'code'`,{error:String(c)}),e==="code")throw new Error("Critical: code.json mode file missing");return this.loadMode("code")}let{parentId:n,overrideId:i}=t,s;try{s=this.loadMode(n)}catch(c){c instanceof Error?_.warn("WORKER",`Parent mode '${n}' not found for ${e}, falling back to 'code'`,{message:c.message}):_.warn("WORKER",`Parent mode '${n}' not found for ${e}, falling back to 'code'`,{error:String(c)}),s=this.loadMode("code")}let o;try{o=this.loadModeFile(i),_.debug("SYSTEM",`Loaded override file: ${i} for parent ${n}`)}catch(c){return c instanceof Error?_.warn("WORKER",`Override file '${i}' not found, using parent mode '${n}' only`,{message:c.message}):_.warn("WORKER",`Override file '${i}' not found, using parent mode '${n}' only`,{error:String(c)}),this.activeMode=s,s}if(!o)return _.warn("SYSTEM",`Invalid override file: ${i}, using parent mode '${n}' only`),this.activeMode=s,s;let a=this.deepMerge(s,o);return this.activeMode=a,_.debug("SYSTEM",`Loaded mode with inheritance: ${a.name} (${e} = ${n} + ${i})`,void 0,{parent:n,override:i,types:a.observation_types.map(c=>c.id),concepts:a.observation_concepts.map(c=>c.id)}),a}getActiveMode(){if(!this.activeMode)throw new Error("No mode loaded. Call loadMode() first.");return this.activeMode}getObservationTypes(){return this.getActiveMode().observation_types}getObservationConcepts(){return this.getActiveMode().observation_concepts}getTypeIcon(e){return this.getObservationTypes().find(n=>n.id===e)?.emoji||"\u{1F4DD}"}getWorkEmoji(e){return this.getObservationTypes().find(n=>n.id===e)?.work_emoji||"\u{1F4DD}"}validateType(e){return this.getObservationTypes().some(t=>t.id===e)}getTypeLabel(e){return this.getObservationTypes().find(n=>n.id===e)?.label||e}}});var an,Cc,vS,Mn,Hf=R(()=>{"use strict";an=require("fs"),Cc=require("path"),vS=require("os"),Mn=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_GEMINI_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_GEMINI_MAX_TOKENS:"100000",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_OPENROUTER_MAX_TOKENS:"100000",CLAUDE_MEM_DATA_DIR:(0,Cc.join)((0,vS.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,Cc.join)((0,vS.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let t=this.get(e);return parseInt(t,10)}static getBool(e){let t=this.get(e);return t==="true"||t===!0}static applyEnvOverrides(e){let t={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(t[n]=process.env[n]);return t}static loadFromFile(e){try{if(!(0,an.existsSync)(e)){let o=this.getAllDefaults();try{let a=(0,Cc.dirname)(e);(0,an.existsSync)(a)||(0,an.mkdirSync)(a,{recursive:!0}),(0,an.writeFileSync)(e,JSON.stringify(o,null,2),"utf-8"),console.log("[SETTINGS] Created settings file with defaults:",e)}catch(a){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,a instanceof Error?a.message:String(a))}return this.applyEnvOverrides(o)}let t=(0,an.readFileSync)(e,"utf-8"),n=JSON.parse(t),i=n;if(n.env&&typeof n.env=="object"){i=n.env;try{(0,an.writeFileSync)(e,JSON.stringify(i,null,2),"utf-8"),console.log("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(o){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,o instanceof Error?o.message:String(o))}}let s={...this.DEFAULTS};for(let o of Object.keys(this.DEFAULTS))i[o]!==void 0&&(s[o]=i[o]);return this.applyEnvOverrides(s)}catch(t){return console.warn("[SETTINGS] Failed to load settings, using defaults:",e,t instanceof Error?t.message:String(t)),this.applyEnvOverrides(this.getAllDefaults())}}}});function QF(){return Vf!==null||(Vf=Mn.loadFromFile(dr)),Vf}var Vf,XF=R(()=>{"use strict";Hf();kt();Vf=null});function ZF(){let r=Pe.settings(),e=Mn.loadFromFile(r),t=Je.getInstance().getActiveMode(),n=new Set(t.observation_types.map(s=>s.id)),i=new Set(t.observation_concepts.map(s=>s.id));return{totalObservationCount:parseInt(e.CLAUDE_MEM_CONTEXT_OBSERVATIONS,10),fullObservationCount:parseInt(e.CLAUDE_MEM_CONTEXT_FULL_COUNT,10),sessionCount:parseInt(e.CLAUDE_MEM_CONTEXT_SESSION_COUNT,10),showReadTokens:e.CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS==="true",showWorkTokens:e.CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS==="true",showSavingsAmount:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT==="true",showSavingsPercent:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT==="true",observationTypes:n,observationConcepts:i,fullObservationField:e.CLAUDE_MEM_CONTEXT_FULL_FIELD,showLastSummary:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY==="true",showLastMessage:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE==="true"}}var e4=R(()=>{"use strict";Hf();kt();Dn()});var D,t4,Kc=R(()=>{"use strict";D={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",cyan:"\x1B[36m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",gray:"\x1B[90m",red:"\x1B[31m"},t4=4});function r4(r){let e=(r.title?.length||0)+(r.subtitle?.length||0)+(r.narrative?.length||0)+JSON.stringify(r.facts||[]).length;return Math.ceil(e/t4)}function n4(r){let e=r.length,t=r.reduce((o,a)=>o+r4(a),0),n=r.reduce((o,a)=>o+(a.discovery_tokens||0),0),i=n-t,s=n>0?Math.round(i/n*100):0;return{totalObservations:e,totalReadTokens:t,totalDiscoveryTokens:n,savings:i,savingsPercent:s}}function fle(r){return Je.getInstance().getWorkEmoji(r)}function jc(r,e){let t=r4(r),n=r.discovery_tokens||0,i=fle(r.type),s=n>0?`${i} ${n.toLocaleString()}`:"-";return{readTokens:t,discoveryTokens:n,discoveryDisplay:s,workEmoji:i}}function Wf(r){return r.showReadTokens||r.showWorkTokens||r.showSavingsAmount||r.showSavingsPercent}var Bo=R(()=>{"use strict";Kc();Dn()});function Dc(r){let e=Object.fromEntries(o4.map(i=>[i,0]));i4.lastIndex=0;let t=0,n=r.replace(i4,(i,s)=>(e[s]=(e[s]??0)+1,t+=1,""));return t>s4&&_.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:t,maxAllowed:s4,contentLength:r.length}),{stripped:n.trim(),counts:e}}var o4,i4,a4,s4,mle,M0e,P0e,Yf=R(()=>{"use strict";se();o4=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],i4=new RegExp(`<(${o4.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g"),a4=/<system-reminder>[\s\S]*?<\/system-reminder>/g,s4=100;mle=["task-notification"],M0e=new RegExp(`^\\s*<(${mle.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),P0e=256*1024});function hle(r){return r.replace(/[/.]/g,"-")}function yle(r){if(!r.includes('"type":"assistant"'))return null;let e=JSON.parse(r);if(e.type==="assistant"&&e.message?.content&&Array.isArray(e.message.content)){let t="";for(let n of e.message.content)n.type==="text"&&(t+=n.text);if(t=t.replace(a4,"").trim(),t)return t}return null}function ble(r){for(let e=r.length-1;e>=0;e--)try{let t=yle(r[e]);if(t)return t}catch(t){t instanceof Error?_.debug("WORKER","Skipping malformed transcript line",{lineIndex:e},t):_.debug("WORKER","Skipping malformed transcript line",{lineIndex:e,error:String(t)});continue}return""}function gle(r){try{if(!(0,zf.existsSync)(r))return{userMessage:"",assistantMessage:""};let e=(0,zf.readFileSync)(r,"utf-8").trim();if(!e)return{userMessage:"",assistantMessage:""};let t=e.split(`
|
|
9263
9264
|
`).filter(i=>i.trim());return{userMessage:"",assistantMessage:ble(t)}}catch(e){return e instanceof Error?_.failure("WORKER","Failed to extract prior messages from transcript",{transcriptPath:r},e):_.warn("WORKER","Failed to extract prior messages from transcript",{transcriptPath:r,error:String(e)}),{userMessage:"",assistantMessage:""}}}function l4(r,e,t,n){if(!e.showLastMessage||r.length===0)return{userMessage:"",assistantMessage:""};let i=r.find(c=>c.memory_session_id!==t);if(!i)return{userMessage:"",assistantMessage:""};let s=i.memory_session_id,o=hle(n),a=c4.default.join(Us,"projects",o,`${s}.jsonl`);return gle(a)}function u4(r,e){let t=e[0]?.id;return r.map((n,i)=>{let s=i===0?null:e[i+1];return{...n,displayEpoch:s?s.created_at_epoch:n.created_at_epoch,displayTime:s?s.created_at:n.created_at,shouldShowLink:n.id!==t}})}function d4(r,e){let t=[...r.map(n=>({type:"observation",data:n})),...e.map(n=>({type:"summary",data:n}))];return t.sort((n,i)=>{let s=n.type==="observation"?n.data.created_at_epoch:n.data.displayEpoch,o=i.type==="observation"?i.data.created_at_epoch:i.data.displayEpoch;return s-o}),t}function p4(r,e){return new Set(r.slice(0,e).map(t=>t.id))}var c4,zf,f4=R(()=>{"use strict";c4=ze(require("path"),1),zf=require("fs");se();Yf();kt();Kc()});function vle(){let r=new Date,e=r.toLocaleDateString("en-CA"),t=r.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}).toLowerCase().replace(" ",""),n=r.toLocaleTimeString("en-US",{timeZoneName:"short"}).split(" ").pop();return`${e} ${t} ${n}`}function m4(r){return[`# [${r}] recent context, ${vle()}`,""]}function h4(){return[`Legend: \u{1F3AF}session ${Je.getInstance().getActiveMode().observation_types.map(t=>`${t.emoji}${t.id}`).join(" ")}`,"Format: ID TIME TYPE TITLE","Fetch details: get_observations([IDs]) | Search: mem-search skill",""]}function y4(){return[]}function b4(){return[]}function g4(r,e){let t=[],n=[`${r.totalObservations} obs (${r.totalReadTokens.toLocaleString()}t read)`,`${r.totalDiscoveryTokens.toLocaleString()}t work`];return r.totalDiscoveryTokens>0&&(e.showSavingsAmount||e.showSavingsPercent)&&(e.showSavingsPercent?n.push(`${r.savingsPercent}% savings`):e.showSavingsAmount&&n.push(`${r.savings.toLocaleString()}t saved`)),t.push(`Stats: ${n.join(" | ")}`),t.push(""),t}function v4(r){return[`### ${r}`]}function E4(r){return r.toLowerCase().replace(" am","a").replace(" pm","p")}function S4(r,e,t){let n=r.title||"Untitled",i=Je.getInstance().getTypeIcon(r.type),s=e?E4(e):'"';return`${r.id} ${s} ${i} ${n}`}function x4(r,e,t,n){let i=[],s=r.title||"Untitled",o=Je.getInstance().getTypeIcon(r.type),a=e?E4(e):'"',{readTokens:c,discoveryDisplay:l}=jc(r,n);i.push(`**${r.id}** ${a} ${o} **${s}**`),t&&i.push(t);let u=[];return n.showReadTokens&&u.push(`~${c}t`),n.showWorkTokens&&u.push(l),u.length>0&&i.push(u.join(" ")),i.push(""),i}function _4(r,e){return[`S${r.id} ${r.request||"Session started"} (${e})`]}function Mc(r,e){return e?[`**${r}**: ${e}`,""]:[]}function w4(r){return r.assistantMessage?["","---","","**Previously**","",`A: ${r.assistantMessage}`,""]:[]}function I4(r,e){return["",`Access ${Math.round(r/1e3)}k tokens of past work via get_observations([IDs]) or mem-search skill.`]}var $o=R(()=>{"use strict";Dn();Bo()});function Ele(){let r=new Date,e=r.toLocaleDateString("en-CA"),t=r.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}).toLowerCase().replace(" ",""),n=r.toLocaleTimeString("en-US",{timeZoneName:"short"}).split(" ").pop();return`${e} ${t} ${n}`}function T4(r){return["",`${D.bright}${D.cyan}[${r}] recent context, ${Ele()}${D.reset}`,`${D.gray}${"\u2500".repeat(60)}${D.reset}`,""]}function A4(){let e=Je.getInstance().getActiveMode().observation_types.map(t=>`${t.emoji} ${t.id}`).join(" | ");return[`${D.dim}Legend: session-request | ${e}${D.reset}`,""]}function k4(){return[`${D.bright}Column Key${D.reset}`,`${D.dim} Read: Tokens to read this observation (cost to learn it now)${D.reset}`,`${D.dim} Work: Tokens spent on work that produced this record ( research, building, deciding)${D.reset}`,""]}function O4(){return[`${D.dim}Context Index: This semantic index (titles, types, files, tokens) is usually sufficient to understand past work.${D.reset}`,"",`${D.dim}When you need implementation details, rationale, or debugging context:${D.reset}`,`${D.dim} - Fetch by ID: get_observations([IDs]) for observations visible in this index${D.reset}`,`${D.dim} - Search history: Use the mem-search skill for past decisions, bugs, and deeper research${D.reset}`,`${D.dim} - Trust this index over re-reading code for past decisions and learnings${D.reset}`,""]}function R4(r,e){let t=[];if(t.push(`${D.bright}${D.cyan}Context Economics${D.reset}`),t.push(`${D.dim} Loading: ${r.totalObservations} observations (${r.totalReadTokens.toLocaleString()} tokens to read)${D.reset}`),t.push(`${D.dim} Work investment: ${r.totalDiscoveryTokens.toLocaleString()} tokens spent on research, building, and decisions${D.reset}`),r.totalDiscoveryTokens>0&&(e.showSavingsAmount||e.showSavingsPercent)){let n=" Your savings: ";e.showSavingsAmount&&e.showSavingsPercent?n+=`${r.savings.toLocaleString()} tokens (${r.savingsPercent}% reduction from reuse)`:e.showSavingsAmount?n+=`${r.savings.toLocaleString()} tokens`:n+=`${r.savingsPercent}% reduction from reuse`,t.push(`${D.green}${n}${D.reset}`)}return t.push(""),t}function C4(r){return[`${D.bright}${D.cyan}${r}${D.reset}`,""]}function K4(r){return[`${D.dim}${r}${D.reset}`]}function j4(r,e,t,n){let i=r.title||"Untitled",s=Je.getInstance().getTypeIcon(r.type),{readTokens:o,discoveryTokens:a,workEmoji:c}=jc(r,n),l=t?`${D.dim}${e}${D.reset}`:" ".repeat(e.length),u=n.showReadTokens&&o>0?`${D.dim}(~${o}t)${D.reset}`:"",d=n.showWorkTokens&&a>0?`${D.dim}(${c} ${a.toLocaleString()}t)${D.reset}`:"";return` ${D.dim}#${r.id}${D.reset} ${l} ${s} ${i} ${u} ${d}`}function D4(r,e,t,n,i){let s=[],o=r.title||"Untitled",a=Je.getInstance().getTypeIcon(r.type),{readTokens:c,discoveryTokens:l,workEmoji:u}=jc(r,i),d=t?`${D.dim}${e}${D.reset}`:" ".repeat(e.length),p=i.showReadTokens&&c>0?`${D.dim}(~${c}t)${D.reset}`:"",f=i.showWorkTokens&&l>0?`${D.dim}(${u} ${l.toLocaleString()}t)${D.reset}`:"";return s.push(` ${D.dim}#${r.id}${D.reset} ${d} ${a} ${D.bright}${o}${D.reset}`),n&&s.push(` ${D.dim}${n}${D.reset}`),(p||f)&&s.push(` ${p} ${f}`),s.push(""),s}function M4(r,e){let t=`${r.request||"Session started"} (${e})`;return[`${D.yellow}#S${r.id}${D.reset} ${t}`,""]}function Pc(r,e,t){return e?[`${t}${r}:${D.reset} ${e}`,""]:[]}function P4(r){return r.assistantMessage?["","---","",`${D.bright}${D.magenta}Previously${D.reset}`,"",`${D.dim}A: ${r.assistantMessage}${D.reset}`,""]:[]}function N4(r,e){let t=Math.round(r/1e3);return["",`${D.dim}Access ${t}k tokens of past research & decisions for just ${e.toLocaleString()}t. Use the claude-mem skill to access memories by ID.${D.reset}`]}var Ho=R(()=>{"use strict";Kc();Dn();Bo()});function L4(r,e,t,n){let i=[];return n?i.push(...T4(r)):i.push(...m4(r)),n?i.push(...A4()):i.push(...h4()),n?i.push(...k4()):i.push(...y4()),n?i.push(...O4()):i.push(...b4()),Wf(t)&&(n?i.push(...R4(e,t)):i.push(...g4(e,t))),i}var q4=R(()=>{"use strict";Bo();$o();Ho()});function Zf(r){if(!r)return[];try{let e=JSON.parse(r);return Array.isArray(e)?e:[]}catch(e){return _.debug("PARSER","Failed to parse JSON array, using empty fallback",{preview:r?.substring(0,50)},e instanceof Error?e:new Error(String(e))),[]}}function SS(r){return new Date(r).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}function xS(r){return new Date(r).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function J4(r){return new Date(r).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})}function F4(r,e){return ES.default.isAbsolute(r)?ES.default.relative(e,r):r}function U4(r,e,t){let n=Zf(r);if(n.length>0)return F4(n[0],e);if(t){let i=Zf(t);if(i.length>0)return F4(i[0],e)}return"General"}var ES,G4=R(()=>{"use strict";ES=ze(require("path"),1);se()});function Sle(r){let e=new Map;for(let n of r){let i=n.type==="observation"?n.data.created_at:n.data.displayTime,s=J4(i);e.has(s)||e.set(s,[]),e.get(s).push(n)}let t=Array.from(e.entries()).sort((n,i)=>{let s=new Date(n[0]).getTime(),o=new Date(i[0]).getTime();return s-o});return new Map(t)}function B4(r,e){return e.fullObservationField==="narrative"?r.narrative:r.facts?Zf(r.facts).join(`
|
|
9264
9265
|
`):null}function xle(r,e,t,n){let i=[];i.push(...v4(r));let s="";for(let o of e)if(o.type==="summary"){let a=o.data,c=SS(a.displayTime);i.push(..._4(a,c))}else{let a=o.data,c=xS(a.created_at),u=c!==s?c:"";if(s=c,t.has(a.id)){let p=B4(a,n);i.push(...x4(a,u,p,n))}else i.push(S4(a,u,n))}return i}function _le(r,e,t,n,i){let s=[];s.push(...C4(r));let o=null,a="";for(let c of e)if(c.type==="summary"){o=null,a="";let l=c.data,u=SS(l.displayTime);s.push(...M4(l,u))}else{let l=c.data,u=U4(l.files_modified,i,l.files_read),d=xS(l.created_at),p=d!==a;a=d;let f=t.has(l.id);if(u!==o&&(s.push(...K4(u)),o=u),f){let m=B4(l,n);s.push(...D4(l,d,p,m,n))}else s.push(j4(l,d,p,n))}return s.push(""),s}function wle(r,e,t,n,i,s){return s?_le(r,e,t,n,i):xle(r,e,t,n)}function $4(r,e,t,n,i){let s=[],o=Sle(r);for(let[a,c]of o)s.push(...wle(a,c,e,t,n,i));return s}var H4=R(()=>{"use strict";G4();$o();Ho()});function V4(r,e,t){return!(!r.showLastSummary||!e||!!!(e.investigated||e.learned||e.completed||e.next_steps)||t&&e.created_at_epoch<=t.created_at_epoch)}function W4(r,e){let t=[];return e?(t.push(...Pc("Investigated",r.investigated,D.blue)),t.push(...Pc("Learned",r.learned,D.yellow)),t.push(...Pc("Completed",r.completed,D.green)),t.push(...Pc("Next Steps",r.next_steps,D.magenta))):(t.push(...Mc("Investigated",r.investigated)),t.push(...Mc("Learned",r.learned)),t.push(...Mc("Completed",r.completed)),t.push(...Mc("Next Steps",r.next_steps))),t}var Y4=R(()=>{"use strict";Kc();$o();Ho()});function z4(r,e){return e?P4(r):w4(r)}function Q4(r,e,t){return!Wf(e)||r.totalDiscoveryTokens<=0||r.savings<=0?[]:t?N4(r.totalDiscoveryTokens,r.totalReadTokens):I4(r.totalDiscoveryTokens,r.totalReadTokens)}var X4=R(()=>{"use strict";Bo();$o();Ho()});function Ile(r,e,t,n,i,s,o){let a=[],c=n4(e);a.push(...L4(r,c,n,o));let l=t.slice(0,n.sessionCount),u=u4(l,t),d=d4(e,u),p=p4(e,n.fullObservationCount);a.push(...$4(d,p,n,i,o));let f=t[0],m=e[0];V4(n,f,m)&&a.push(...W4(f,o));let y=l4(e,n,s,i);return a.push(...z4(y,o)),a.push(...Q4(c,n,o)),a.join(`
|
|
9265
|
-
`).trimEnd()}function t8(r,e,t,n,i=[],s){if(e.length===0&&i.length===0)return"";try{Je.getInstance().getActiveMode()}catch{Je.getInstance().loadMode(QF().CLAUDE_MEM_MODE||"code")}return Ile(r,e,i,ZF(),t,s,n)}var Z4,e8,TSe,r8=R(()=>{"use strict";Z4=ze(require("path"),1),e8=require("os");zF();se();gS();Dn();XF();e4();Bo();f4();q4();H4();Y4();X4();$o();Ho();TSe=Z4.default.join((0,e8.homedir)(),".claude","plugins","marketplaces","bjlee2024","plugin",".install-version")});function em(r){return Array.isArray(r)?JSON.stringify(r):null}function _S(r){return typeof r=="string"?r:null}function Tle(r){let e=r.metadata&&typeof r.metadata=="object"?r.metadata:{},t=r.created_at instanceof Date?r.created_at:new Date(r.created_at);return{id:r.id,memory_session_id:r.server_session_id??"",project:r.project_name??"",merged_into_project:null,platform_source:typeof e.provider=="string"?e.provider:"claude",type:r.kind,title:_S(e.title),subtitle:_S(e.subtitle),narrative:_S(e.narrative),text:r.content,facts:em(e.facts),concepts:em(e.concepts),files_read:em(e.files_read),files_modified:em(e.files_modified),prompt_number:null,created_at:t.toISOString(),created_at_epoch:t.getTime()}}function n8(r){let e=Number.parseInt(String(r.query.offset??""),10),t=Number.parseInt(String(r.query.limit??""),10),n=Number.isInteger(e)&&e>=0?e:0,i=Number.isInteger(t)&&t>0?t:50;i>200&&(i=200);let s=typeof r.query.project=="string"&&r.query.project.length>0?r.query.project:void 0;return{offset:n,limit:i,project:s}}function Ale(r,e,t){let n=r.metadata&&typeof r.metadata=="object"?r.metadata:{},i=r.created_at instanceof Date?r.created_at:new Date(r.created_at),s=o=>Array.isArray(o)?JSON.stringify(o):typeof o=="string"?o:null;return{id:e,memory_session_id:typeof r.server_session_id=="string"?r.server_session_id:"",platform_source:typeof n.provider=="string"?n.provider:void 0,type:typeof n.type=="string"?n.type:r.kind||"observation",title:typeof n.title=="string"?n.title:null,subtitle:typeof n.subtitle=="string"?n.subtitle:null,narrative:typeof n.narrative=="string"?n.narrative:typeof r.content=="string"?r.content:null,facts:s(n.facts),concepts:s(n.concepts),files_read:s(n.files_read),files_modified:s(n.files_modified),discovery_tokens:null,created_at:i.toISOString(),created_at_epoch:i.getTime(),project:t}}var cn,i8,tm,s8=R(()=>{"use strict";cn=require("fs"),i8=require("path");se();r8();kt();tm=class{constructor(e){this.pool=e}pool;setupRoutes(e){e.get("/api/observations",(t,n)=>this.handleObservations(t,n,!1)),e.get("/api/summaries",(t,n)=>this.handleObservations(t,n,!0)),e.get("/api/prompts",(t,n)=>{let{offset:i,limit:s}=n8(t);n.json({items:[],hasMore:!1,offset:i,limit:s})}),e.get("/api/projects",(t,n)=>this.handleProjects(t,n)),e.get("/api/stats",(t,n)=>this.handleStats(t,n)),e.get("/api/processing-status",(t,n)=>this.handleProcessingStatus(t,n)),e.get("/api/settings",(t,n)=>this.handleGetSettings(n)),e.post("/api/settings",(t,n)=>this.handleSaveSettings(t,n)),e.get("/api/context/preview",(t,n)=>this.handleContextPreview(t,n)),e.get("/stream",(t,n)=>this.handleStream(t,n))}handleGetSettings(e){try{let t=(0,cn.existsSync)(dr)?JSON.parse((0,cn.readFileSync)(dr,"utf8")):{};e.json(t)}catch{e.json({})}}handleSaveSettings(e,t){try{let n=e.body&&typeof e.body=="object"?e.body:{},s={...(0,cn.existsSync)(dr)?JSON.parse((0,cn.readFileSync)(dr,"utf8")):{},...n};(0,cn.mkdirSync)((0,i8.dirname)(dr),{recursive:!0}),(0,cn.writeFileSync)(dr,JSON.stringify(s,null,2)),t.json({success:!0})}catch(n){_.error("SYSTEM","viewer POST /api/settings failed",{error:String(n)}),t.status(500).json({error:"InternalError",message:"Failed to save settings"})}}async handleContextPreview(e,t){try{let n=typeof e.query.project=="string"?e.query.project:"";if(!n){t.status(400).type("text/plain").send("project parameter is required");return}let s=(await this.pool.query(`SELECT o.id, o.server_session_id, p.name AS project_name, o.kind, o.content,
|
|
9266
|
+
`).trimEnd()}function t8(r,e,t,n,i=[],s){if(e.length===0&&i.length===0)return"";try{Je.getInstance().getActiveMode()}catch{Je.getInstance().loadMode(QF().CLAUDE_MEM_MODE||"code")}return Ile(r,e,i,ZF(),t,s,n)}var Z4,e8,TSe,r8=R(()=>{"use strict";Z4=ze(require("path"),1),e8=require("os");zF();se();gS();Dn();XF();e4();Bo();f4();q4();H4();Y4();X4();$o();Ho();TSe=Z4.default.join((0,e8.homedir)(),".claude","plugins","marketplaces","bjlee2024","plugin",".install-version")});function em(r){return Array.isArray(r)?JSON.stringify(r):null}function _S(r){return typeof r=="string"?r:null}function Tle(r){let e=r.metadata&&typeof r.metadata=="object"?r.metadata:{},t=r.created_at instanceof Date?r.created_at:new Date(r.created_at);return{id:r.id,memory_session_id:r.server_session_id??"",project:r.project_name??"",merged_into_project:null,platform_source:typeof e.provider=="string"?e.provider:"claude",type:r.kind,title:_S(e.title),subtitle:_S(e.subtitle),narrative:_S(e.narrative),text:r.content,facts:em(e.facts),concepts:em(e.concepts),files_read:em(e.files_read),files_modified:em(e.files_modified),prompt_number:null,created_at:t.toISOString(),created_at_epoch:t.getTime()}}function n8(r){let e=Number.parseInt(String(r.query.offset??""),10),t=Number.parseInt(String(r.query.limit??""),10),n=Number.isInteger(e)&&e>=0?e:0,i=Number.isInteger(t)&&t>0?t:50;i>200&&(i=200);let s=typeof r.query.project=="string"&&r.query.project.length>0?r.query.project:void 0;return{offset:n,limit:i,project:s}}function Ale(r,e,t){let n=r.metadata&&typeof r.metadata=="object"?r.metadata:{},i=r.created_at instanceof Date?r.created_at:new Date(r.created_at),s=o=>Array.isArray(o)?JSON.stringify(o):typeof o=="string"?o:null;return{id:e,memory_session_id:typeof r.server_session_id=="string"?r.server_session_id:"",platform_source:typeof n.provider=="string"?n.provider:void 0,type:typeof n.type=="string"?n.type:r.kind||"observation",title:typeof n.title=="string"?n.title:null,subtitle:typeof n.subtitle=="string"?n.subtitle:null,narrative:typeof n.narrative=="string"?n.narrative:typeof r.content=="string"?r.content:null,facts:s(n.facts),concepts:s(n.concepts),files_read:s(n.files_read),files_modified:s(n.files_modified),discovery_tokens:null,created_at:i.toISOString(),created_at_epoch:i.getTime(),project:t}}var cn,i8,tm,s8=R(()=>{"use strict";cn=require("fs"),i8=require("path");se();r8();kt();tm=class{constructor(e){this.pool=e}pool;setupRoutes(e){e.get("/api/observations",(t,n)=>this.handleObservations(t,n,!1)),e.get("/api/summaries",(t,n)=>this.handleObservations(t,n,!0)),e.get("/api/prompts",(t,n)=>{let{offset:i,limit:s}=n8(t);n.json({items:[],hasMore:!1,offset:i,limit:s})}),e.get("/api/projects",(t,n)=>this.handleProjects(t,n)),e.get("/api/stats",(t,n)=>this.handleStats(t,n)),e.get("/api/processing-status",(t,n)=>this.handleProcessingStatus(t,n)),e.get("/api/settings",(t,n)=>this.handleGetSettings(n)),e.post("/api/settings",(t,n)=>this.handleSaveSettings(t,n)),e.get("/api/context/preview",(t,n)=>this.handleContextPreview(t,n)),e.get("/api/logs",(t,n)=>n.json({logs:_.getRecentLogs()})),e.post("/api/logs/clear",(t,n)=>{_.clearRecentLogs(),n.json({success:!0})}),e.get("/stream",(t,n)=>this.handleStream(t,n))}handleGetSettings(e){try{let t=(0,cn.existsSync)(dr)?JSON.parse((0,cn.readFileSync)(dr,"utf8")):{};e.json(t)}catch{e.json({})}}handleSaveSettings(e,t){try{let n=e.body&&typeof e.body=="object"?e.body:{},s={...(0,cn.existsSync)(dr)?JSON.parse((0,cn.readFileSync)(dr,"utf8")):{},...n};(0,cn.mkdirSync)((0,i8.dirname)(dr),{recursive:!0}),(0,cn.writeFileSync)(dr,JSON.stringify(s,null,2)),t.json({success:!0})}catch(n){_.error("SYSTEM","viewer POST /api/settings failed",{error:String(n)}),t.status(500).json({error:"InternalError",message:"Failed to save settings"})}}async handleContextPreview(e,t){try{let n=typeof e.query.project=="string"?e.query.project:"";if(!n){t.status(400).type("text/plain").send("project parameter is required");return}let s=(await this.pool.query(`SELECT o.id, o.server_session_id, p.name AS project_name, o.kind, o.content,
|
|
9266
9267
|
o.metadata, o.created_at
|
|
9267
9268
|
FROM observations o
|
|
9268
9269
|
LEFT JOIN projects p ON o.project_id = p.id
|