memindex 1.0.0 → 1.1.0
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/.agents/plugins/marketplace.json +12 -0
- package/.claude-plugin/marketplace.json +7 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/.qoder-plugin/plugin.json +1 -1
- package/README.md +10 -12
- package/dist/bug-report/index.js +63 -63
- package/dist/npx-cli/index.js +355 -10233
- package/dist/opencode-plugin/index.js +35 -35
- package/dist/pi-extension/index.js +6 -6
- package/integrations/dsh/lib/index.js +28 -28
- package/integrations/dsh/package.json +1 -1
- package/integrations/openclaw/openclaw.plugin.json +1 -1
- package/package.json +5 -8
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/.codex-plugin/plugin.json +1 -1
- package/plugin/.qoder-plugin/plugin.json +1 -1
- package/plugin/hooks.json +49 -0
- package/plugin/mcp_config.json +11 -0
- package/plugin/modes/personal.json +130 -0
- package/plugin/package.json +1 -1
- package/plugin/plugin.json +4 -0
- package/plugin/scripts/context-generator.cjs +51 -48
- package/plugin/scripts/context-generator.cjs.map +3 -3
- package/plugin/scripts/mcp-server.cjs +83 -83
- package/plugin/scripts/mcp-server.cjs.map +3 -3
- package/plugin/scripts/transcript-watcher.cjs +37 -37
- package/plugin/scripts/transcript-watcher.cjs.map +3 -3
- package/plugin/scripts/windows-hook-launcher.cjs +2 -0
- package/plugin/scripts/worker-service.cjs +1149 -668
- package/plugin/scripts/worker-service.cjs.map +3 -3
- package/plugin/skills/cloud-sync/SKILL.md +91 -0
- package/plugin/sqlite/SessionStore.js +317 -181
- package/plugin/sqlite/SessionStore.js.map +3 -3
- package/plugin/sqlite/observations/files.js +6 -6
- package/plugin/sqlite/observations/files.js.map +3 -3
- package/plugin/ui/viewer-bundle.js +2 -2
- package/plugin/scripts/server-service.cjs +0 -10305
- package/plugin/scripts/server-service.cjs.map +0 -6
|
@@ -1,49 +1,49 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
var __CM_FILENAME__ = typeof __filename !== "undefined" ? __filename : require("node:path").resolve(process.argv[1] || "");
|
|
3
3
|
var __CM_DIRNAME__ = typeof __dirname !== "undefined" ? __dirname : require("node:path").dirname(__CM_FILENAME__);
|
|
4
|
-
"use strict";var
|
|
5
|
-
`,r)}function
|
|
6
|
-
`);let m=(0,
|
|
7
|
-
`)}finally{if(p!==void 0)try{(0,
|
|
8
|
-
${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let r=Object.keys(e);return r.length===0?"{}":r.length<=3?this.safeStringify(e):`{${r.length} keys: ${r.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,r){if(!r)return e;let n=r;if(typeof r=="string")try{n=JSON.parse(r)}catch{n=r}if(n===null)return e;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 r=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),s=String(e.getDate()).padStart(2,"0"),
|
|
9
|
-
${
|
|
10
|
-
${
|
|
11
|
-
`+this.safeStringify(
|
|
12
|
-
`,"utf8")}catch(g){let m=g instanceof Error?g:new Error(String(g));
|
|
4
|
+
"use strict";var QS=Object.create;var Oa=Object.defineProperty;var ZS=Object.getOwnPropertyDescriptor;var ey=Object.getOwnPropertyNames;var ty=Object.getPrototypeOf,ry=Object.prototype.hasOwnProperty;var E=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(n){throw r=[n],n}};var As=(t,e)=>{for(var r in e)Oa(t,r,{get:e[r],enumerable:!0})},ny=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ey(e))!ry.call(t,s)&&s!==r&&Oa(t,s,{get:()=>e[s],enumerable:!(n=ZS(e,s))||n.enumerable});return t};var be=(t,e,r)=>(r=t!=null?QS(ty(t)):{},ny(e||!t||!t.__esModule?Oa(r,"default",{value:t,enumerable:!0}):r,t));function Pa(t){return t.startsWith(Os)||Ps.some(e=>t.startsWith(e))}function oy(t=process.env){for(let e of Ps)for(let r of Object.keys(t)){if(!r.startsWith(e))continue;let n=Os+r.slice(e.length);t[n]===void 0&&(t[n]=t[r])}}function Ms(t){let e=null;for(let r of Ps)for(let n of Object.keys(t)){if(!n.startsWith(r))continue;let s=Os+n.slice(r.length);(e??t)[s]===void 0&&(e??={...t},e[s]=t[n])}return e??t}var Os,sy,Ps,on=E(()=>{"use strict";Os="MEMINDEX_",sy="AGENT_MEM_",Ps=[sy];oy()});function he(t,e=process.platform,r=(0,Pd.homedir)()){return typeof t!="string"||t.length===0?t:t==="~"?r:t.startsWith("~/")||e==="win32"&&t.startsWith("~\\")?(0,Md.join)(r,t.slice(2)):t}var Pd,Md,Wt=E(()=>{"use strict";Pd=require("os"),Md=require("path")});function ay(t){return(iy??process.stderr.write.bind(process.stderr))(t)}function ct(t){ay(t)}var iy,NM,xs=E(()=>{"use strict";iy=null;NM=Promise.resolve()});function Ma(t){return t.replace(/^\uFEFF/,"")}function jt(t){return JSON.parse(Ma(t))}function ut(t){return jt((0,k.readFileSync)(t,"utf-8"))}function uy(t){(0,k.existsSync)(t)||(0,k.mkdirSync)(t,{recursive:!0})}function U(t,e,r={}){ly(t,JSON.stringify(e,null,2)+`
|
|
5
|
+
`,r)}function ly(t,e,r={}){let n=t,s=new Set;try{for(;(0,k.lstatSync)(n).isSymbolicLink();){let d=(0,Me.resolve)(n);if(s.has(d))throw Object.assign(new Error(`Symlink loop at ${n}`),{code:"ELOOP"});s.add(d);try{n=(0,k.realpathSync)(n);break}catch(p){if(p.code!=="ENOENT")throw p;let g=p instanceof Error?p:new Error(String(p));ct(`memindex: realpathSync failed for ${n}, resolving symlink manually: ${g.message}
|
|
6
|
+
`);let m=(0,k.readlinkSync)(n);n=(0,Me.resolve)((0,Me.dirname)(n),m)}}}catch(d){if(d.code!=="ENOENT")throw d}uy((0,Me.dirname)(n));let o=(0,Me.dirname)(n),i=(0,Me.basename)(n),a=(0,Me.join)(o,`.${i}.${process.pid}.${(0,xd.randomBytes)(6).toString("hex")}.tmp`),c=Buffer.from(e,"utf-8"),u=r.mode;if(u===void 0)try{u=(0,k.statSync)(n).mode&511}catch{}let l;try{l=u!==void 0?(0,k.openSync)(a,"w",u):(0,k.openSync)(a,"w");let d=0;for(;d<c.length;){let p=(0,k.writeSync)(l,c,d,c.length-d);if(p===0)throw new Error(`writeSync stalled at ${d}/${c.length} bytes`);d+=p}if((0,k.fsyncSync)(l),(0,k.closeSync)(l),l=void 0,(0,k.renameSync)(a,n),!cy){let p;try{p=(0,k.openSync)(o,"r"),(0,k.fsyncSync)(p)}catch(g){let m=g instanceof Error?g:new Error(String(g));ct(`memindex: directory fsync failed for ${o}: ${m.message}
|
|
7
|
+
`)}finally{if(p!==void 0)try{(0,k.closeSync)(p)}catch{}}}}catch(d){if(l!==void 0)try{(0,k.closeSync)(l)}catch{}try{(0,k.unlinkSync)(a)}catch{}throw d}}var k,xd,Me,cy,se=E(()=>{"use strict";k=require("fs"),xd=require("crypto"),Me=require("path");xs();cy=process.platform==="win32"});function kd(t){let e=t.env;return dy(e)&&Object.keys(e).some(Pa)?"nested":"flat"}function _r(t){return kd(t)==="nested"?t.env:t}function Nd(t){return kd(t)!=="nested"?t:Object.fromEntries(Object.entries(t).filter(([e])=>!Pa(e)))}var dy,ks=E(()=>{"use strict";se();on();dy=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)});function an(t=process.env,e=(0,Dd.homedir)()){if(t.MEMINDEX_DATA_DIR)return he(t.MEMINDEX_DATA_DIR,process.platform,e);let r=(0,xa.join)(e,".memindex"),n=(0,xa.join)(r,"settings.json");try{if((0,Cd.existsSync)(n)){let s=ut(n);if(s===null||typeof s!="object"||Array.isArray(s))return r;let o=Ms(_r(s));if(typeof o.MEMINDEX_DATA_DIR=="string"&&o.MEMINDEX_DATA_DIR)return he(o.MEMINDEX_DATA_DIR,process.platform,e)}}catch{}return r}var Cd,Dd,xa,ka=E(()=>{"use strict";Cd=require("fs"),Dd=require("os"),xa=require("path");se();on();Wt();ks()});function fy(){return typeof __CM_DIRNAME__<"u"?__CM_DIRNAME__:(0,j.dirname)((0,Fd.fileURLToPath)(_y.url))}function py(t){let e=process.env.MEMINDEX_TEST_FORBIDDEN_DATA_DIR;if(e&&t===e)throw new Error(`A test resolved the real data folder ${t}. Point MEMINDEX_DATA_DIR at a temporary directory (and pass env: process.env to any child process the test starts).`);return t}function N(){return py(an())}function Ud(t,e=(0,Na.homedir)(),r=process.platform){return he(t,r,e)}var j,Na,Fd,_y,VM,W,gy,lt,Er,my,_e,Ld,YM,Ns,hy,K,C=E(()=>{"use strict";j=require("path"),Na=require("os"),Fd=require("url");Wt();ka();Wt();_y={};VM=fy();W=N(),gy=(0,j.join)((0,Na.homedir)(),".claude"),lt=process.env.CLAUDE_CONFIG_DIR||gy,Er=(0,j.join)(lt,"plugins","marketplaces","memindex"),my=(0,j.join)(W,"logs"),_e=(0,j.join)(W,"settings.json"),Ld="memindex.db",YM=(0,j.join)(W,Ld),Ns=(0,j.join)(W,"observer-sessions"),hy=(0,j.basename)(Ns);K={dataDir:()=>W,workerPid:()=>(0,j.join)(W,"worker.pid"),serverPid:()=>(0,j.join)(W,".server-beta.pid"),serverPort:()=>(0,j.join)(W,".server-beta.port"),serverRuntime:()=>(0,j.join)(W,".server-beta.runtime.json"),settings:()=>(0,j.join)(W,"settings.json"),database:()=>(0,j.join)(W,Ld),chroma:()=>(0,j.join)(W,"chroma"),combinedCerts:()=>(0,j.join)(W,"combined_certs.pem"),transcriptsConfig:()=>(0,j.join)(W,"transcript-watch.json"),transcriptsState:()=>(0,j.join)(W,"transcript-watch-state.json"),corpora:()=>(0,j.join)(W,"corpora"),supervisorRegistry:()=>(0,j.join)(W,"supervisor.json"),envFile:()=>(0,j.join)(W,".env"),logsDir:()=>my}});function Bd(t=process.env){let e=Number.parseInt(t.MEMINDEX_WEDGED_WORKER_UPTIME_S??"",10);return Number.isFinite(e)&&e>=$d.min&&e<=$d.max?e:Ey}function Sy(t=process.platform){return t==="win32"?8e3:5e3}function cn(t=process.platform){return Q.SESSION_INIT_HOOK_CAP-Sy(t)}function Wd(t=process.platform){return t==="win32"?cn(t):Q.SESSION_INIT_REQUEST_MAX}function ze(t){return process.platform==="win32"?Math.round(t*Q.WINDOWS_MULTIPLIER):t}var Q,Ey,$d,D,xe=E(()=>{"use strict";Q={HEALTH_CHECK:3e3,API_REQUEST:3e4,SESSION_INIT_HOOK_CAP:15e3,SESSION_INIT_REQUEST:1e4,SESSION_INIT_REQUEST_MAX:14e3,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5},Ey=300,$d={min:60,max:86400};D={SUCCESS:0}});var Ht,jd,Da,Ca,Fa,f,O=E(()=>{"use strict";Ht=require("fs"),jd=require("path");C();xs();se();ks();Da=(o=>(o[o.DEBUG=0]="DEBUG",o[o.INFO=1]="INFO",o[o.WARN=2]="WARN",o[o.ERROR=3]="ERROR",o[o.SILENT=4]="SILENT",o))(Da||{}),Ca=null,Fa=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;logFileDate=null;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){let e=new Date().toISOString().split("T")[0];if(this.logFileInitialized&&this.logFileDate===e)return;let r=this.logFileDate!==e;this.logFileInitialized=!1,this.logFileDate=e;try{let n=K.logsDir();(0,Ht.existsSync)(n)||(0,Ht.mkdirSync)(n,{recursive:!0}),this.logFilePath=(0,jd.join)(n,`memindex-${e}.log`),this.logFileInitialized=!0}catch(n){r&&console.error("[LOGGER] Failed to initialize log file:",n instanceof Error?n.message:String(n)),this.logFilePath=null}}getLevel(){if(this.level===null)try{let e=K.settings();if((0,Ht.existsSync)(e)){let r=_r(ut(e)),n=(r.MEMINDEX_LOG_LEVEL||r.AGENT_MEM_LOG_LEVEL||"INFO").toString().toUpperCase();this.level=Da[n]??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}safeStringify(e,r,n=6){let s=new WeakSet,o=(i,a)=>{if(typeof i=="bigint")return`${i}n`;if(i===null||typeof i!="object")return i;let c=i.toJSON,u=typeof c=="function"?c.call(i):i;if(typeof u=="bigint")return`${u}n`;if(u===null||typeof u!="object")return u;if(s.has(u))return"[Circular]";if(a>=n)return Array.isArray(u)?"[Array]":"[Object]";s.add(u);try{if(Array.isArray(u))return u.map(d=>o(d,a+1));let l={};for(let d of Object.keys(u))try{l[d]=o(u[d],a+1)}catch{l[d]="[unreadable]"}return l}finally{s.delete(u)}};try{return JSON.stringify(o(e,0),null,r)??String(e)}catch{return Array.isArray(e)?`[${e.length} items]`:"[unserializable]"}}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}
|
|
8
|
+
${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let r=Object.keys(e);return r.length===0?"{}":r.length<=3?this.safeStringify(e):`{${r.length} keys: ${r.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,r){if(!r)return e;let n=r;if(typeof r=="string")try{n=JSON.parse(r)}catch{n=r}if(n===null)return e;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 r=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),s=String(e.getDate()).padStart(2,"0"),o=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0"),c=String(e.getMilliseconds()).padStart(3,"0");return`${r}-${n}-${s} ${o}:${i}:${a}.${c}`}log(e,r,n,s,o){if(e<this.getLevel())return;this.ensureLogFileInitialized();let i=this.formatTimestamp(new Date),a=Da[e].padEnd(5),c=r.padEnd(6),u="";s?.correlationId?u=`[${s.correlationId}] `:s?.sessionId&&(u=`[session-${s.sessionId}] `);let l="";o!=null&&(o instanceof Error?l=this.getLevel()===0?`
|
|
9
|
+
${o.message}
|
|
10
|
+
${o.stack}`:` ${o.message}`:this.getLevel()===0&&typeof o=="object"?l=`
|
|
11
|
+
`+this.safeStringify(o,2):l=" "+this.formatData(o));let d="";if(s){let{sessionId:g,memorySessionId:m,correlationId:h,..._}=s;Object.keys(_).length>0&&(d=` {${Object.entries(_).map(([b,w])=>typeof w!="object"||w===null||w instanceof Error||w instanceof Date?`${b}=${w}`:`${b}=${Array.isArray(w)?this.safeStringify(w):this.formatData(w)}`).join(", ")}}`)}let p=`[${i}] [${a}] [${c}] ${u}${n}${d}${l}`;if(this.logFilePath)try{(0,Ht.appendFileSync)(this.logFilePath,p+`
|
|
12
|
+
`,"utf8")}catch(g){let m=g instanceof Error?g:new Error(String(g));ct(`[LOGGER] Failed to write to log file: ${m.message}
|
|
13
13
|
${m.stack??""}
|
|
14
|
-
`)}else
|
|
15
|
-
`)}debug(e,r,n,s){this.log(0,e,r,n,s)}info(e,r,n,s){this.log(1,e,r,n,s)}warn(e,r,n,s){this.log(2,e,r,n,s)}setErrorSink(e){_a=e}error(e,r,n,s){this.log(3,e,r,n,s),this.routeErrorToSink(r,n,s)}routeErrorToSink(e,r,n){try{if(!_a||!(n instanceof Error))return;_a(n)}catch{}}dataIn(e,r,n,s){this.info(e,`\u2192 ${r}`,n,s)}dataOut(e,r,n,s){this.info(e,`\u2190 ${r}`,n,s)}success(e,r,n,s){this.info(e,`\u2713 ${r}`,n,s)}failure(e,r,n,s){this.error(e,`\u2717 ${r}`,n,s)}},f=new Sa});function _d(t){try{return new URL(t).hostname.toLowerCase()==="openrouter.ai"}catch{return!1}}var Ed=E(()=>{"use strict";A()});function $S(t){return typeof t=="boolean"?String(t):t}function BS(t){let e=t.MEMINDEX_OPENROUTER_MODEL;if(typeof e!="string"||!US.has(e.trim()))return!1;let r=typeof t.MEMINDEX_OPENROUTER_BASE_URL=="string"?t.MEMINDEX_OPENROUTER_BASE_URL.trim():"";return r===""||_d(r)}function wd(t,e){return(0,Et.join)((0,Et.dirname)(t),`.${(0,Et.basename)(t)}.${e.markerTag}`)}function ya(t,e){try{(0,Ft.writeFileSync)(wd(t,e),new Date().toISOString(),{encoding:"utf-8",mode:384})}catch{}}var Ft,Et,ba,US,Sd,yd,bd,z,st=E(()=>{"use strict";Ft=require("fs"),Et=require("path"),ba=require("os");He();ie();Ed();Yr();_s();US=new Set(["xiaomi/mimo-v2-flash:free"]);Sd=18e4,yd=[{key:"MEMINDEX_LLM_TIMEOUT_MS",legacy:"30000",markerTag:"llm-timeout-migrated-v1"},{key:"MEMINDEX_FIELD_OPTIMIZE_TIMEOUT_MS",legacy:"30000",markerTag:"field-optimize-timeout-migrated-v1"}];bd=new Set,z=class{static DEFAULTS={MEMINDEX_MEMORY_SEARCH_HOOK_ENABLED:"true",MEMINDEX_MEMORY_INSTRUCTIONS_ENABLED:"true",MEMINDEX_MEMORY_WATCH_ROOTS:"",MEMINDEX_MODEL:"claude-haiku-4-5-20251001",MEMINDEX_CONTEXT_OBSERVATIONS:"50",MEMINDEX_SESSION_START_INCLUDE_ALL_SOURCES:"false",MEMINDEX_WORKER_PORT:String(38700+(process.getuid?.()??77)%100),MEMINDEX_WORKER_HOST:"127.0.0.1",MEMINDEX_ALLOWED_ORIGINS:"",MEMINDEX_PUBLIC_URL:"",MEMINDEX_API_TIMEOUT_MS:String(We(re.API_REQUEST)),MEMINDEX_SESSION_INIT_TIMEOUT_MS:String(qr()),MEMINDEX_IDLE_EXIT_SEC:"0",MEMINDEX_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",MEMINDEX_SKIP_BASH_PATTERNS:"",MEMINDEX_SKIP_SUBAGENT_OBSERVATIONS:"false",MEMINDEX_SKIP_AGENT_TYPES:"",MEMINDEX_CAPTURE_ADVISOR_CALLS:"false",MEMINDEX_PROVIDER:"claude",MEMINDEX_CODEX_MODEL:"",MEMINDEX_CODEX_PATH:"codex",MEMINDEX_CODEX_REASONING_EFFORT:"low",MEMINDEX_CODEX_MAX_CONCURRENT_AGENTS:"2",MEMINDEX_CODEX_OBSERVATION_BATCH_SIZE:"8",MEMINDEX_CODEX_OBSERVATION_BATCH_MAX_CHARS:"32000",MEMINDEX_CLAUDE_AUTH_METHOD:"subscription",MEMINDEX_GEMINI_API_KEY:"",MEMINDEX_GEMINI_API_KEYS:"",MEMINDEX_GEMINI_MODEL:"gemini-flash-latest",MEMINDEX_GEMINI_RATE_LIMITING_ENABLED:"true",MEMINDEX_OPENROUTER_API_KEY:"",MEMINDEX_OPENROUTER_API_KEYS:"",MEMINDEX_OPENROUTER_MODEL:"cohere/north-mini-code:free",MEMINDEX_OPENROUTER_BASE_URL:"",MEMINDEX_OPENROUTER_TEMPERATURE:"",MEMINDEX_OPENROUTER_SITE_URL:"",MEMINDEX_OPENROUTER_APP_NAME:"memindex",MEMINDEX_OPENROUTER_EXTRA_BODY:"",MEMINDEX_OPENROUTER_REASONING_EFFORT:"",MEMINDEX_OPENAI_COMPAT_PRESET:"",MEMINDEX_OPENAI_COMPAT_API_KEY:"",MEMINDEX_OPENAI_COMPAT_API_KEYS:"",MEMINDEX_OPENAI_COMPAT_BASE_URL:"",MEMINDEX_OPENAI_COMPAT_MODEL:"",MEMINDEX_QUOTA_FALLBACK_PROVIDER:"claude",MEMINDEX_QUOTA_FALLBACK_MODEL:"",MEMINDEX_QUOTA_THRESHOLD_FIVE_HOUR:"0.95",MEMINDEX_QUOTA_THRESHOLD_SEVEN_DAY:"0.93",MEMINDEX_QUOTA_THRESHOLD_SEVEN_DAY_OPUS:"0.93",MEMINDEX_QUOTA_THRESHOLD_SEVEN_DAY_SONNET:"0.92",MEMINDEX_QUOTA_THRESHOLD_OVERAGE:"0.95",MEMINDEX_DATA_DIR:(0,Et.join)((0,ba.homedir)(),".memindex"),MEMINDEX_LOG_LEVEL:"INFO",MEMINDEX_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",MEMINDEX_CLAUDE_CONFIG_DIR:"",MEMINDEX_OBSERVER_CLAUDE_CONFIG_DIR:"",MEMINDEX_MODE:"code",MEMINDEX_CONTEXT_SHOW_READ_TOKENS:"false",MEMINDEX_CONTEXT_SHOW_WORK_TOKENS:"false",MEMINDEX_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",MEMINDEX_CONTEXT_SHOW_SAVINGS_PERCENT:"true",MEMINDEX_CONTEXT_OBSERVATION_TYPES:"",MEMINDEX_CONTEXT_OBSERVATION_CONCEPTS:"",MEMINDEX_CONTEXT_FULL_COUNT:"0",MEMINDEX_CONTEXT_FULL_FIELD:"narrative",MEMINDEX_CONTEXT_SESSION_COUNT:"10",MEMINDEX_CONTEXT_SHOW_LAST_SUMMARY:"true",MEMINDEX_CONTEXT_SHOW_LAST_MESSAGE:"false",MEMINDEX_CONTEXT_MAIN_AGENT_ONLY:"true",MEMINDEX_REINFORCE_ALPHA:"0",MEMINDEX_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",MEMINDEX_WELCOME_HINT_ENABLED:"true",MEMINDEX_WORK_STATE_ENABLED:"true",MEMINDEX_FILE_READ_GATE_ENABLED:"true",MEMINDEX_ENDLESS_MODE_ENABLED:"true",MEMINDEX_FOLDER_CLAUDEMD_ENABLED:"false",MEMINDEX_FOLDER_USE_LOCAL_MD:"false",MEMINDEX_TRANSCRIPTS_ENABLED:"true",MEMINDEX_TRANSCRIPTS_CONFIG_PATH:(0,Et.join)((0,ba.homedir)(),".memindex","transcript-watch.json"),MEMINDEX_CODEX_TRANSCRIPT_INGESTION:"false",MEMINDEX_CODEX_SUBAGENT_INGESTION:"false",MEMINDEX_MAX_CONCURRENT_AGENTS:"2",MEMINDEX_OBSERVER_MAX_CONVERSATION_CHARS:"400000",MEMINDEX_OBSERVER_CONTEXT_WINDOW:"",MEMINDEX_OBSERVER_MAX_OUTPUT_TOKENS:"4096",MEMINDEX_OBSERVE_BARE_PROMPTS:"false",MEMINDEX_HOOK_FAIL_LOUD_THRESHOLD:"3",MEMINDEX_REDACT_ENABLED:"false",MEMINDEX_REDACT_DISABLED_BUILTINS:"",MEMINDEX_REDACT_CUSTOM_PATTERNS:"[]",MEMINDEX_REDACT_LOG_MATCHES:"false",MEMINDEX_EXCLUDED_PROJECTS:"",MEMINDEX_PROJECT_ENVIRONMENTS:"[]",MEMINDEX_FOLDER_MD_EXCLUDE:"[]",MEMINDEX_FOLDER_MD_SKELETON_DENYLIST:"[]",MEMINDEX_SEMANTIC_INJECT:"false",MEMINDEX_SEMANTIC_INJECT_LIMIT:"5",MEMINDEX_SEMANTIC_INJECT_FORMAT:"narrative",MEMINDEX_TIER_ROUTING_ENABLED:"true",MEMINDEX_TIER_SIMPLE_MODEL:"haiku",MEMINDEX_TIER_SUMMARY_MODEL:"",MEMINDEX_TIER_FAST_MODEL:"haiku",MEMINDEX_TIER_SMART_MODEL:"sonnet",MEMINDEX_CHROMA_ENABLED:"true",MEMINDEX_CHROMA_MODE:"local",MEMINDEX_CHROMA_HOST:"127.0.0.1",MEMINDEX_CHROMA_PORT:"8000",MEMINDEX_CHROMA_SSL:"false",MEMINDEX_CHROMA_API_KEY:"",MEMINDEX_CHROMA_TENANT:"default_tenant",MEMINDEX_CHROMA_DATABASE:"default_database",MEMINDEX_CHROMA_PREWARM_TIMEOUT_MS:"120000",MEMINDEX_CHROMA_MUTATION_TIMEOUT_MS:"600000",MEMINDEX_CHROMA_MAX_PENDING_MUTATIONS:"5000",MEMINDEX_CHROMA_MEMORY_LIMIT_MB:"2048",MEMINDEX_CHROMA_EMBEDDING_FUNCTION:"default",MEMINDEX_CHROMA_UVX_PATH:"",MEMINDEX_SEARCH_RECENCY_DAYS:"90",MEMINDEX_HOSTING_OFFER:"true",MEMINDEX_LLM_TIMEOUT_MS:String(Sd),MEMINDEX_LLM_STREAM_IDLE_TIMEOUT_MS:"90000",MEMINDEX_FIELD_OPTIMIZE_TIMEOUT_MS:String(Sd),MEMINDEX_TV_TOKEN:"",MEMINDEX_GROK_BOT_AWARENESS_ENABLED:"false",MEMINDEX_GROK_BOT_AWARENESS_AGENT_IDS:"",MEMINDEX_GROK_BOT_AWARENESS_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",MEMINDEX_GROK_BOT_AWARENESS_TRIGGER_CONCEPTS:"",MEMINDEX_GROK_BOT_INJECT_ENABLED:"false",MEMINDEX_GROK_BOT_INJECT_AGENT_IDS:"*",MEMINDEX_GROK_BOT_INJECT_TIER:"episode",MEMINDEX_GROK_BOT_INJECT_WINDOW:"80",MEMINDEX_GROK_BOT_INJECT_FALLBACK:"house",MEMINDEX_GROK_BOT_INJECT_PLATFORM_SOURCE:"",MEMINDEX_GROK_BOT_INJECT_PROJECTS_BY_AGENT:"",MEMINDEX_GROK_BOT_INJECT_MAX_LINE_CHARS:"160",MEMINDEX_GROK_BOT_INJECT_DEBOUNCE_MS:"1500",MEMINDEX_GROK_BOT_INJECT_STANDING_LINE:"",MEMINDEX_CCS_ALIGN_ENABLED:"false",MEMINDEX_CCS_ALIGN_VIEWER_IDS:"ccs-align",MEMINDEX_CCS_ALIGN_TRIGGER_TYPES:"decision,bugfix,security_alert,sensitive",MEMINDEX_CCS_ALIGN_PATCH_SHADOWS:"false",MEMINDEX_QUEUE_ENGINE:"sqlite",MEMINDEX_REDIS_URL:"",MEMINDEX_REDIS_HOST:"127.0.0.1",MEMINDEX_REDIS_PORT:"6379",MEMINDEX_REDIS_MODE:"external",MEMINDEX_QUEUE_REDIS_PREFIX:`memindex_${process.env.MEMINDEX_WORKER_PORT??String(38700+(process.getuid?.()??77)%100)}`,MEMINDEX_AUTH_MODE:"api-key",MEMINDEX_RUNTIME:"worker",MEMINDEX_SERVER_URL:`http://127.0.0.1:${process.env.MEMINDEX_SERVER_PORT??String(38877+(process.getuid?.()??77)%100)}`,MEMINDEX_SERVER_API_KEY:"",MEMINDEX_SERVER_PROJECT_ID:"",MEMINDEX_SERVER_BETA_URL:`http://127.0.0.1:${process.env.MEMINDEX_SERVER_PORT??String(38877+(process.getuid?.()??77)%100)}`,MEMINDEX_SERVER_BETA_API_KEY:"",MEMINDEX_SERVER_BETA_PROJECT_ID:"",MEMINDEX_DEDUP_ENABLED:"false",MEMINDEX_DEDUP_COSINE_THRESHOLD:"0.80",MEMINDEX_DEDUP_IDF_VETO_DF:"10",MEMINDEX_DEDUP_MIN_SHARED_TOKENS:"2",MEMINDEX_DEDUP_MIN_PROJECT_DOCS:"10",MEMINDEX_DEDUP_MAX_SCAN:"2000",MEMINDEX_DEDUP_MAX_BACKFILL_ROWS:"50000",MEMINDEX_TOOL_USES_RETENTION_DAYS:"0",MEMINDEX_WORKER_AUTOSTART:"true",MEMINDEX_PROJECT_NAME_SOURCE:"path"};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){let r=process.env[e]??this.DEFAULTS[e];return e==="MEMINDEX_WORKER_HOST"?this.normalizeWorkerHost(r):r}static normalizeWorkerHost(e){return e==="localhost"?"127.0.0.1":e}static finalizeSettings(e,r){let n=r?this.applyEnvOverrides(e):e;return n.MEMINDEX_WORKER_HOST=this.normalizeWorkerHost(n.MEMINDEX_WORKER_HOST),n}static getInt(e){let r=this.get(e);return parseInt(r,10)}static applyEnvOverrides(e){let r={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(r[n]=process.env[n]);return r}static loadFromFile(e,r=!0,n={}){try{if(!(0,Ft.existsSync)(e)){let p=this.getAllDefaults();if(!n.readOnly)try{X(e,p,{mode:384});for(let g of yd)ya(e,g);console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(g){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,g instanceof Error?g.message:String(g))}return this.finalizeSettings(p,r)}let s=(0,Ft.readFileSync)(e,"utf-8"),i=Ct(s),o=or(i),a=o!==i,c=ms(o),u=ad(i),l=a&&Object.keys(u).some(p=>p!=="env");if(a&&!l&&!n.readOnly)try{X(e,c,{mode:384}),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(p){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,p instanceof Error?p.message:String(p))}if(BS(c)){let p=String(c.MEMINDEX_OPENROUTER_MODEL).trim();if(c={...c,MEMINDEX_OPENROUTER_MODEL:this.DEFAULTS.MEMINDEX_OPENROUTER_MODEL},!n.readOnly)try{X(e,l?{...u,env:c}:c,{mode:384}),console.warn(`[SETTINGS] Migrated OpenRouter model off the retired default ${p} to ${this.DEFAULTS.MEMINDEX_OPENROUTER_MODEL}:`,e)}catch(g){console.warn("[SETTINGS] Failed to migrate the retired OpenRouter model:",e,g instanceof Error?g.message:String(g))}}for(let p of yd)if(!(0,Ft.existsSync)(wd(e,p))){if(c[p.key]!==p.legacy){n.readOnly||ya(e,p);continue}if(c={...c,[p.key]:this.DEFAULTS[p.key]},!n.readOnly)try{X(e,l?{...u,env:c}:c,{mode:384}),ya(e,p),console.warn(`[SETTINGS] Migrated ${p.key} off the old ${p.legacy}ms default to ${this.DEFAULTS[p.key]}ms:`,e)}catch(g){let m=`${p.key}\0${e}`;bd.has(m)||(bd.add(m),console.warn(`[SETTINGS] Failed to migrate ${p.key}; using the new default in memory (reported once per process):`,e,g instanceof Error?g.message:String(g)))}}let d={...this.DEFAULTS};for(let p of Object.keys(this.DEFAULTS))c[p]!==void 0&&(d[p]=$S(c[p]));return this.finalizeSettings(d,r)}catch(s){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,s instanceof Error?s.message:String(s));let i=this.getAllDefaults();return this.finalizeSettings(i,r)}}}});function Cd(t=U()){let e=(0,$.openSync)((0,Ts.join)(t,Dd),$.constants.O_RDONLY|($.constants.O_NOFOLLOW??0));try{let r=(0,$.fstatSync)(e);if(!r.isFile()||process.getuid&&r.uid!==process.getuid()||process.platform!=="win32"&&(r.mode&63)!==0)throw new Error("Worker secret must be an owner-only file");let n=(0,$.readFileSync)(e,"utf8");if(!YS.test(n))throw new Error("Invalid worker secret");return n}finally{(0,$.closeSync)(e)}}function Fd(t=U()){(0,$.mkdirSync)(t,{recursive:!0,mode:448});let e=(0,Ts.join)(t,Dd);try{return Cd(t)}catch(s){if(s.code!=="ENOENT")throw s}let r=(0,Ts.join)(t,`.worker-secret-${(0,va.randomBytes)(16).toString("hex")}`),n=(0,$.openSync)(r,"wx",384);try{(0,$.fchmodSync)(n,384),(0,$.writeFileSync)(n,(0,va.randomBytes)(32).toString("hex")),(0,$.fsyncSync)(n)}finally{(0,$.closeSync)(n)}try{try{(0,$.linkSync)(r,e)}catch(s){if(s.code!=="EEXIST")throw s}}finally{(0,$.unlinkSync)(r)}return Cd(t)}function en(t,e=U()){if(!["POST","PUT","PATCH","DELETE"].includes((t.method??"GET").toUpperCase()))return t;let r=new Headers(t.headers);return r.set(VS,Fd(e)),{...t,headers:r,redirect:"error"}}var va,$,Ts,VS,Dd,YS,Ra=E(()=>{"use strict";va=require("node:crypto"),$=require("node:fs"),Ts=require("node:path");N();VS="X-Memindex-Secret",Dd="worker-secret",YS=/^[a-f0-9]{64}$/});async function*JS(t){if(!(t instanceof ReadableStream)){yield*t;return}let e=t.getReader(),r=!1;try{for(;;){let{done:n,value:s}=await e.read();if(n){r=!0;return}yield s}}finally{try{r||await e.cancel()}finally{e.releaseLock()}}}function QS(t,e){if(t.length===1)return t[0];let r=new Uint8Array(e),n=0;for(let s of t)r.set(s,n),n+=s.length;return r}async function*$d(t,e={}){let r=e.maxEventBytes??1048576,n=new TextDecoder,s=[],i=0,o=!1,a=0,c=null,u,l=null,d=!1,p=m=>{if(a+m>r)throw new Aa(r)},g=m=>{if(m.length===0){let T=c!==null||l!==null?{event:c||"message",data:(l??[]).join(`
|
|
16
|
-
`),...u!==void 0?{id:u}:{}}:null;return c=null,u=void 0,l=null,a=0,T}if(m[0]===
|
|
17
|
-
`)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);if(!n)continue;let s=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:s.length>0?s:null})}return e}async function py(){let t;try{t=(await Fa("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,@{Name='StartToken';Expression={$_.CreationDate.ToString('yyyyMMddHHmmss.ffffff')}} | ConvertTo-Csv -NoTypeInformation"],{timeout:3e4,windowsHide:!0,maxBuffer:33554432})).stdout}catch(r){return f.warn("PROCESS","Cannot enumerate the Windows process table \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),[]}let e=[];for(let r of t.split(/\r?\n/).slice(1)){let n=r.match(/^"(\d+)","(\d+)","(.*)"$/);if(!n)continue;let s=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:s.length>0?s:null})}return e}async function Ms(t){let e=await ly(),r=new Map;for(let o of e){let a=r.get(o.ppid);a?a.push(o):r.set(o.ppid,[o])}let n=new Set([t]),s=[],i=o=>{for(let a of r.get(o)??[])n.has(a.pid)||(n.add(a.pid),i(a.pid),s.push({pid:a.pid,startToken:a.startToken}))};return i(t),s}var zd,Ps,Vd,Fa,cy,uy,As,lr=E(()=>{"use strict";zd=require("child_process"),Ps=require("fs"),Vd=require("util");A();Rs();Fa=(0,Vd.promisify)(zd.execFile),cy=128,uy=/not found|no running instance|no tasks/i,As=class extends Error{pid;constructor(e,r,n){super(r,n),this.name="ProcessTreeKillError",this.pid=e}}});function V(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;return r==="EPERM"?!0:(f.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return f.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function Os(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!V(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function qd(t){if(!t||!V(t.pid))return!1;if(!t.startToken)return!0;let e=Xe(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||f.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}function ks(t,e=Sy){if(!qd(t))return!1;if(t.startToken||e.platform!=="linux")return!0;let r;try{r=e.readCommandLine(t.pid)}catch(s){return f.debug("SYSTEM","Could not read the command line of a token-less worker PID; trusting the live PID",{pid:t.pid,error:s instanceof Error?s.message:String(s)}),!0}let n=r.split("\0").some(s=>Yd.default.basename(s)==="worker-service.cjs");return n||f.debug("SYSTEM","Token-less worker PID now belongs to another program (PID reused)",{pid:t.pid}),n}function at(t=j.workerPid()){if(!(0,Ut.existsSync)(t))return null;let e;try{e=JSON.parse((0,Ut.readFileSync)(t,"utf-8"))}catch{return null}return e!==null&&ks(e)?e:null}function xs(){return La||(La=new $a),La}function Ua(){let t=yy.shift();t&&t.notify()}var Ut,Yd,my,hy,_y,Ey,Sy,$a,La,WO,yy,ct=E(()=>{"use strict";Na();Ut=require("fs"),Yd=Ee(require("path"),1);A();ie();tn();N();Rs();lr();my=5e3,hy=1e3,_y=j.supervisorRegistry(),Ey=null;Sy={platform:process.platform,readCommandLine:t=>(0,Ut.readFileSync)(`/proc/${t}/cmdline`,"utf-8")};$a=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(e=_y){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,!(0,Ut.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Ut.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[s,i]of Object.entries(n))this.entries.set(s,i)}catch(r){r instanceof Error?f.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):f.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&f.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}retainSupersededEntry(e,r){let n=this.entries.get(e);if(!n||n.pid===r||!V(n.pid))return;let s=`${e}#superseded:${n.pid}`;this.entries.set(s,n);let i=this.runtimeProcesses.get(e);i&&(this.runtimeProcesses.set(s,i),this.runtimeProcesses.delete(e)),f.warn("SYSTEM","Registry id reused while the previous process was still alive; kept it for reaping",{id:e,supersededId:s,supersededPid:n.pid,incomingPid:r})}register(e,r,n){this.initialize(),this.retainSupersededEntry(e,r.pid),this.entries.set(e,r),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e,r){this.initialize();let n=e,s=this.entries.get(n);r!==void 0&&s?.pid!==r&&(n=`${e}#superseded:${r}`,s=this.entries.get(n),s?.pid!==r)||s&&(this.entries.delete(n),this.runtimeProcesses.delete(n),this.persist(),s?.type==="sdk"&&Ua())}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let n=Date.parse(e.startedAt),s=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(s)?0:s)})}getBySession(e){let r=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[n,s]of this.entries)V(s.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,s.type==="sdk"&&(r+=1));e>0&&this.persist();for(let n=0;n<r;n+=1)Ua();return e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;f.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:n,pids:r.map(a=>a.pid)});let s=r.filter(a=>V(a.pid)),i=new Map(s.map(a=>[a.pid,Xe(a.pid)]));for(let a of s)try{process.platform==="win32"?await ye(a.pid,{expectedStartToken:i.get(a.pid)??null}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&f.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):f.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}await Os(s,my);let o=s.filter(a=>V(a.pid));for(let a of o){f.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});let c=i.get(a.pid)??null;if(!Oe(a.pid,c)){f.warn("SYSTEM","Skipping SIGKILL: session process PID was reused during the grace window",{pid:a.pid,sessionId:n});continue}try{process.platform==="win32"?await ye(a.pid,{expectedStartToken:c}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(u){u instanceof Error?u.code!=="ESRCH"&&f.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},u):f.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(u)})}}if(o.length>0){let a=Date.now()+hy;for(;Date.now()<a&&o.filter(u=>V(u.pid)).length!==0;)await new Promise(u=>setTimeout(u,100))}for(let a of r)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of r)a.type==="sdk"&&Ua();return f.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:n,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};try{X(this.registryPath,e),this.persistDegraded=!1}catch(r){this.reportPersistFailure(r)}}reportPersistFailure(e){if(this.persistDegraded)return;this.persistDegraded=!0;let r=e instanceof Error?e:new Error(String(e));f.warn("SYSTEM","Failed to persist supervisor registry; keeping it in memory",{path:this.registryPath},r);try{Ey?.({errorCategory:r.code??"unknown"})}catch{}}},La=null;WO=180*1e3,yy=[]});async function Qd(t){let e=t.currentPid??process.pid,r=t.pidFilePath??by,n=t.registry.getAll(),s=[...n].filter(c=>c.pid!==e).sort((c,u)=>Date.parse(u.startedAt)-Date.parse(c.startedAt)),i=new Map,o=new Map;for(let c of s){if(!V(c.pid)){t.registry.unregister(c.id);continue}o.set(c.id,Xe(c.pid)),i.set(c.id,await Ms(c.pid));try{await Jd(c,"SIGTERM")}catch(u){u instanceof Error?f.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:c.pid,pgid:c.pgid,type:c.type},u):f.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(u)})}}await Os(s,5e3);let a=s.filter(c=>V(c.pid)||(i.get(c.id)??[]).some(u=>V(u.pid)));for(let c of a){let u=Oe(c.pid,o.get(c.id)??null);u||f.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:c.pid,type:c.type});try{u&&await Jd(c,"SIGKILL")}catch(l){l instanceof Error?f.debug("SYSTEM","Failed to force kill child process",{pid:c.pid,pgid:c.pgid,type:c.type},l):f.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(l)})}finally{wy(i.get(c.id)??[],c.pid)}}await Os(a,1e3);for(let c of s)t.registry.unregister(c.id);for(let c of n.filter(u=>u.pid===e))t.registry.unregister(c.id);Zd(r,e),t.registry.pruneDeadEntries()}function Zd(t,e,r=!1){if(!(0,dr.existsSync)(t))return;let n=null;try{let o=JSON.parse((0,dr.readFileSync)(t,"utf-8"));n=typeof o.pid=="number"?o.pid:null}catch(o){f.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:o instanceof Error?o.message:String(o)});return}let s=e!==null&&n===e,i=n===null||!V(n);if(!s&&!(r&&i)){f.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:n,currentPid:e});return}try{(0,dr.rmSync)(t,{force:!0})}catch(o){o instanceof Error?f.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},o):f.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(o)})}}function wy(t,e){for(let{pid:r,startToken:n}of t)if(!(r===e||!V(r))){if(!Oe(r,n)){f.debug("SYSTEM","Skipping reap: PID was recycled during the grace window",{pid:r,rootPid:e});continue}try{process.kill(r,"SIGKILL"),f.debug("SYSTEM","Reaped orphaned descendant during shutdown cascade",{pid:r,rootPid:e})}catch(s){let i=s instanceof Error?s.code:void 0;i!=="ESRCH"&&f.warn("SYSTEM","Failed to reap orphaned descendant during shutdown cascade",{pid:r,rootPid:e,errno:i})}}}async function Jd(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}if(e==="SIGKILL"){await ye(r,{signalMode:"immediate"});return}try{process.kill(r,e)}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}return}await ye(r)}var dr,by,Ba=E(()=>{"use strict";dr=require("fs");A();ct();N();lr();by=j.workerPid()});function Ty(){let e=xs().pruneDeadEntries();e>0&&f.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function tf(){fr===null&&(fr=setInterval(Ty,ef),fr.unref(),f.debug("SYSTEM","Health checker started",{intervalMs:ef}))}function rf(){fr!==null&&(clearInterval(fr),fr=null,f.debug("SYSTEM","Health checker stopped"))}var ef,fr,nf=E(()=>{"use strict";A();ct();ef=3e4,fr=null});function Ry(t){let e=[];for(let r of t.split(`
|
|
18
|
-
`)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);n&&e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),command:n[3].trim()})}return e}async function
|
|
19
|
-
`)}function
|
|
20
|
-
`).trim()}function
|
|
21
|
-
`);return}let s=Us(),i=new AbortController,o=setTimeout(()=>i.abort(),Ky);try{await Gy(s,t,n,i.signal)}finally{clearTimeout(o)}}catch{}}async function Gy(t,e,r,n){await fetch(`${$s()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:t,event:e,distinct_id:Fs(),properties:r}),signal:n})}var Ky,Tf=E(()=>{"use strict";ja();Va();qa();Ky=2e3});function js(t){return t.error?.name==="ETIMEDOUT"}function Xs(t,e,r=If){let n=`git -C ${t} ${e.join(" ")}`,s=Date.now();return new Promise(i=>{let o=!1,a=!1,c="",u="",l=g=>{if(o)return;o=!0,clearTimeout(p);let m=Date.now()-s;m>1e3&&f.debug("GIT",`Slow git operation: ${n} took ${m}ms`),i(g)},d=(0,Hs.spawn)("git",["-C",t,...e],{stdio:["ignore","pipe","pipe"],windowsHide:!0}),p=setTimeout(()=>{a=!0,d.kill("SIGTERM"),d.stdout?.destroy(),d.stderr?.destroy();let g=Object.assign(new Error(`git timed out after ${r}ms`),{name:"ETIMEDOUT"});f.warn("GIT",`Git operation failed: ${n}`,{error:g.message,timedOut:!0}),l({status:null,stdout:"",error:g})},r);d.stdout?.setEncoding("utf8"),d.stderr?.setEncoding("utf8"),d.stdout?.on("data",g=>{c+=g}),d.stderr?.on("data",g=>{u+=g}),d.once("error",g=>{f.warn("GIT",`Git operation failed: ${n}`,{error:g.message,timedOut:!1}),l({status:null,stdout:"",error:g})}),d.once("close",(g,m)=>{if(!a){if(g!==0){f.debug("GIT",`Git returned non-zero exit code ${g??m}: ${n}`,{stderr:u.trim()}),l({status:g,stdout:"",error:void 0});return}l({status:g,stdout:c.trim(),error:void 0})}})})}function Ja(t,e,r=If){let n=(0,Hs.spawnSync)("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:Math.min(r,zy),windowsHide:!0});return n.error?{status:null,stdout:"",error:n.error}:n.status!==0?{status:n.status,stdout:"",error:void 0}:{status:0,stdout:(n.stdout??"").trim(),error:void 0}}var Hs,If,zy,Qa=E(()=>{"use strict";Hs=require("child_process");A();If=5e3,zy=5e3});function vf(t){let e=St.default.join(t,".git"),r;try{r=(0,Ks.statSync)(e)}catch(c){return c instanceof Error&&c.code!=="ENOENT"&&f.warn("GIT","Unexpected error checking .git",{error:c instanceof Error?c.message:String(c)}),sn}if(!r.isFile())return sn;let n;try{n=(0,Ks.readFileSync)(e,"utf-8").trim()}catch(c){return f.warn("GIT","Failed to read .git file",{error:c instanceof Error?c.message:String(c)}),sn}let s=n.match(/^gitdir:\s*(.+)$/);if(!s)return sn;let i=St.default.resolve(St.default.dirname(e),s[1]),o=i.match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(o){let c=o[1];return{isWorktree:!0,isSubmodule:!1,worktreeName:St.default.basename(t),parentRepoPath:c,parentProjectName:St.default.basename(c)}}let a=i.match(/^(.+)[/\\]\.git[/\\]modules[/\\](.+)$/);if(a){let c=a[1];return{isWorktree:!1,isSubmodule:!0,worktreeName:St.default.basename(t),parentRepoPath:c,parentProjectName:St.default.basename(c)}}return sn}var Ks,St,sn,Rf=E(()=>{"use strict";Ks=require("fs"),St=Ee(require("path"),1);A();sn={isWorktree:!1,isSubmodule:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null}});function Af(t){let e=Se(t.replace(/\\/g,"/"));e=e.replace(/\\/g,"/");let r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return r=r.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${r}$`)}function ec(t,e){if(!e.length)return!1;let r=t.replace(/\\/g,"/"),n=(0,Za.basename)(r);for(let s of e){let i=s.trim();if(i)try{let o=Af(i);if(o.test(r)||o.test(n))return!0}catch(o){f.warn("PROJECT_NAME","Invalid glob pattern",{pattern:i,error:o instanceof Error?o.message:String(o)});continue}}return!1}function Gs(t,e){if(!e||!e.trim())return!1;let r=t.replace(/\\/g,"/"),n=(0,Za.basename)(r),s=e.split(",").map(i=>i.trim()).filter(Boolean);for(let i of s)try{let o=Af(i);if(o.test(r)||o.test(n))return!0}catch(o){f.warn("PROJECT_NAME","Invalid exclusion pattern",{pattern:i,error:o instanceof Error?o.message:String(o)});continue}return!1}var Za,on=E(()=>{"use strict";Za=require("path");ar();A()});function Pf(t){let e=t;if(typeof e=="string"){if(!e.trim())return[];try{e=JSON.parse(e)}catch(n){return f.warn("PROJECT_NAME","MEMINDEX_PROJECT_ENVIRONMENTS is not valid JSON; ignoring it",{error:n instanceof Error?n.message:String(n)}),[]}}if(!Array.isArray(e))return e!=null&&f.warn("PROJECT_NAME","MEMINDEX_PROJECT_ENVIRONMENTS must be an array; ignoring it",{}),[];let r=[];for(let n of e){let s=typeof n?.name=="string"?n.name.trim():"",i=Array.isArray(n?.patterns)?n.patterns.filter(o=>typeof o=="string"&&o.trim()!==""):[];if(!s||i.length===0){f.warn("PROJECT_NAME","Ignoring a project environment without a name or patterns",{name:s});continue}r.push({name:s,patterns:i})}return r}function Vy(t){try{return(0,Mf.realpathSync)(t)}catch{return t}}function tc(t,e){if(e.length===0)return null;let r=[...new Set([t,Vy(t)])].flatMap(n=>[n,`${n.replace(/[\\/]+$/,"")}/`]);for(let n of e)if(r.some(s=>ec(s,n.patterns)))return n.name;return null}var Mf,Of=E(()=>{"use strict";Mf=require("fs");on();A()});function Nf(t){let e=process.env[Yy]?.trim();return e||(!t||t.trim()===""?null:t)}function Cf(t){return Df(t,Ja(t,["rev-parse","--show-toplevel"]))}async function Qy(t){let e=Date.now(),r=pr.get(t);if(r&&e-r.at<qy)return(await r.answer).root;pr.size>=Jy&&pr.clear();let n=Xs(t,["rev-parse","--show-toplevel"]).then(a=>({root:Df(t,a),kept:!js(a)})),s={at:e,answer:n};pr.set(t,s);let{root:i,kept:o}=await n;return!o&&pr.get(t)===s&&pr.delete(t),i}function Df(t,e){return e.status===0&&e.stdout?e.stdout:(f.debug("PROJECT_NAME","git rev-parse failed, falling back to non-git root",{dir:t},e.error),null)}function Ff(t){try{return(0,mr.realpathSync)(t)}catch{return t}}function tb(t,e){let r=ae.default.relative(e,t);return r===""||!r.startsWith("..")&&!ae.default.isAbsolute(r)}function rb(){return[(0,Ys.homedir)(),(0,Ys.tmpdir)(),nt].flatMap(t=>{let e=ae.default.resolve(t);return[e,Ff(e)]})}function Lf(t){let e=rb(),r=ae.default.resolve(t);if([ae.default.resolve(nt),Ff(ae.default.resolve(nt))].some(s=>tb(r,s)))return null;for(let s=0;s<eb;s++){if(e.includes(r))return null;let i=ae.default.dirname(r);if(i===r)return null;if(Zy.some(o=>(0,mr.existsSync)(ae.default.join(r,o))))return r;r=i}return null}function rc(t,e){let r=ae.default.basename(e);if(r===""){if(process.platform==="win32"){let s=t.match(/^([A-Z]):\\/i);if(s){let o=`drive-${s[1].toUpperCase()}`;return f.info("PROJECT_NAME","Drive root detected",{cwd:t,projectName:o}),o}}return f.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:t}),nc}return r}function kf(){try{return(0,mr.statSync)(ge).mtimeMs}catch{return-1}}function Uf(){let t=kf();if(t===-1)return z.getAllDefaults();if(zs&&zs.mtimeMs===t)return zs.settings;let e=z.loadFromFile(ge);return zs={mtimeMs:kf(),settings:e},e}function $f(){let t=process.env[nb]??Uf().MEMINDEX_PROJECT_NAME_SOURCE;return String(t??"path").trim().toLowerCase()==="git-remote"}function Bf(){let t=process.env[sb]??Uf().MEMINDEX_PROJECT_ENVIRONMENTS;return(!Vs||Vs.raw!==t)&&(Vs={raw:t,environments:Pf(t)}),Vs.environments}function ib(t){let e=(t??"").trim();if(!e||/^file:/i.test(e)||e.startsWith("/")||e.startsWith(".")||e.startsWith("~")||e.startsWith("\\\\")||/^[a-z]:[\\/]/i.test(e))return null;let n=e.replace(/\/+$/,"").replace(/\.git$/i,""),s=n.match(/^[a-z][a-z0-9+.-]*:\/\/[^/]+\/(.+)$/i),i=s?null:n.match(/^(?:[^/@\s]+@)?[^:/\s]+:(?!\/\/)(.+)$/),o=s?.[1]??i?.[1];if(!o)return null;let a=o.split("/").filter(c=>c&&c!=="_git");return a.length>=2?a.slice(-2).join("/"):a.length===1?a[0]:null}function Wf(t,e){return e.status===0&&e.stdout?ib(e.stdout):(f.debug("PROJECT_NAME","No usable origin remote, keeping the path-based name",{repoRoot:t},e.error),null)}function Hf(t){return $f()?(gr.has(t)||gr.set(t,Wf(t,Ja(t,["remote","get-url","origin"]))),gr.get(t)??null):null}async function ob(t){if(!$f())return null;if(!gr.has(t)){let e=await Xs(t,["remote","get-url","origin"]);if(js(e))return null;gr.set(t,Wf(t,e))}return gr.get(t)??null}function ab(t,e=process.platform){if(!t||t.trim()==="")return f.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),nc;let r=Se(t,e),n=tc(r,Bf());if(n)return n;let s=Cf(r),i=s?Hf(s):null;if(i)return i;let o=s??Lf(r)??r;return rc(t,o)}function jf(t,e){return e===t?t:`${t}/${e}`}function cb(t,e){if(!t.isSubmodule||!t.parentRepoPath)return null;let r=ae.default.relative(t.parentRepoPath,e);return!r||r.startsWith("..")||ae.default.isAbsolute(r)?null:r.split(ae.default.sep).join("/")}function qs(t,e=process.platform){if(!t||t.trim()==="")return Xf(t,e);let r=Se(t,e),n=Cf(r),s=n?Hf(n):null;return Kf(t,r,n,s)}async function an(t,e=process.platform){if(!t||t.trim()==="")return Xf(t,e);let r=Se(t,e),n=await Qy(r),s=n?await ob(n):null;return Kf(t,r,n,s)}function Xf(t,e){let r=ab(t,e);return{primary:r,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[r],keySource:"path"}}function Kf(t,e,r,n){let s=ub(t,e,r),i=n?xf(s,n,"git-remote"):s,o=tc(e,Bf());return o?xf(i,o,"environment"):i}function xf(t,e,r){return{primary:e,parent:null,isWorktree:t.isWorktree,isSubmodule:t.isSubmodule,allProjects:[...t.allProjects.filter(n=>n!==e),e],keySource:r}}function ub(t,e,r){let n=r?null:Lf(e),s=rc(t,r??n??e),i=r??e,o=vf(i);if((o.isWorktree||o.isSubmodule)&&o.parentProjectName){let a=o.parentProjectName,c,u;return o.isSubmodule?(c=`${a}/${cb(o,i)??s}`,u=s!==a?[s]:[]):(c=jf(a,s),u=c===a?[`${a}/${s}`]:[]),{primary:c,parent:a,isWorktree:o.isWorktree,isSubmodule:o.isSubmodule,allProjects:[...new Set([a,...u,c])].filter(l=>l!==c).concat(c),keySource:"path"}}if(n&&ae.default.resolve(n)!==ae.default.resolve(e)){let a=rc(t,e);if(a!==s&&a!==nc)return{primary:s,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[a,s],keySource:"path"}}return{primary:s,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[s],keySource:"path"}}var ae,mr,Ys,Yy,nc,qy,Jy,pr,Zy,eb,nb,zs,sb,Vs,gr,Bt=E(()=>{"use strict";ae=Ee(require("path"),1),mr=require("fs"),Ys=require("os");ar();N();st();A();Qa();Rf();Of();Yy="CLAUDE_PROJECT_DIR",nc="unknown-project";qy=3e4,Jy=500,pr=new Map;Zy=[".memindex-project",".memindex.json"],eb=64;nb="MEMINDEX_PROJECT_NAME_SOURCE",zs=null;sb="MEMINDEX_PROJECT_ENVIRONMENTS",Vs=null;gr=new Map});function db(t){return t===void 0?Gf:Math.max(1,Math.min(Gf,t))}function pb(t){try{return(0,me.realpathSync)(t)}catch{return null}}function sc(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function gb(t,e){let r=e==="win32"?"where.exe":"which",n=[t],s;try{s=(0,Js.execFileSync)(r,n,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(o){return o instanceof Error?f.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r,args:n},o):f.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r,args:n},new Error(String(o))),null}return s.split(/\r?\n/).map(o=>o.trim()).find(o=>o.length>0)||null}function Qs(t={}){let e=Object.keys(t).length===0;if(e&&ic!==void 0)return ic;let r=mb(t);return e&&r!==null&&(ic=r),r}function zf(t,e){let r=t?.trim();return r?e==="win32"?[de.default.join(r,"bin","bun.exe"),de.default.join(r,"bin","bun"),de.default.join(r,"bun.exe")]:[de.default.join(r,"bin","bun"),de.default.join(r,"bun")]:[]}function mb(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(sc(r))return r;let n=t.env??process.env,s=t.homeDirectory??(0,oc.homedir)(),i=t.pathExists??me.existsSync,o=t.lookupInPath??gb,a=t.realpath??pb,c=e==="win32"?[n.BUN,n.BUN_PATH,...zf(n.BUN_INSTALL,e),de.default.join(s,".bun","bin","bun.exe"),de.default.join(s,".bun","bin","bun"),n.USERPROFILE?de.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?de.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?de.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0,n.npm_config_prefix?de.default.join(n.npm_config_prefix,"bun.exe"):void 0]:[n.BUN,n.BUN_PATH,...zf(n.BUN_INSTALL,e),de.default.join(s,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun",n.npm_config_prefix?de.default.join(n.npm_config_prefix,"bin","bun"):void 0];for(let d of c){let p=d?.trim();if(p&&(sc(p)&&i(p)||p.toLowerCase()==="bun"))return p}let u=o("bun",e)?.trim();if(!u||!sc(u))return null;let l=a(u)??u;return i(l)?l:null}function ac(){let t=j.dataDir();return(0,me.mkdirSync)(t,{recursive:!0}),t}function hb(t,e,r=ac()){let n=s=>s.replace(/'/g,"''");return`Start-Process -FilePath '${n(t)}' -ArgumentList @('"${n(e)}"','--daemon') -WorkingDirectory '${n(r)}' -WindowStyle Hidden`}function _b(t=process.env){let e=t.SystemRoot||t.SYSTEMROOT;return e?`${e}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`:"powershell.exe"}function Eb(t,e,r=ac()){return["-NoProfile","-WindowStyle","Hidden","-EncodedCommand",Buffer.from(hb(t,e,r),"utf16le").toString("base64")]}function Zs(t,e,r,n=process.platform,s){if(n==="win32"){let l=_b(r),d=Eb(t,e),p=db(s);try{let g=(0,Js.spawnSync)(l,d,{stdio:"ignore",windowsHide:!0,env:r,timeout:p,killSignal:"SIGTERM"});if(g.error)throw g.error;if(g.signal)throw new Error(`powershell Start-Process killed by signal=${g.signal} after ${p}ms`);if(g.status!==0)throw new Error(`powershell Start-Process exited ${g.status??"null"}`);return 0}catch(g){let m=g instanceof Error?g:new Error(String(g));f.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:t,powershell:l},m);return}}let i="/usr/bin/setsid",o=(0,me.existsSync)(i),a=o?i:t,u=xa(a,o?[t,e,"--daemon"]:[e,"--daemon"],{detached:!0,stdio:"ignore",cwd:ac(),env:r});if(u.on("error",l=>{f.error("SYSTEM",fb,{runtimePath:t,execPath:a},l)}),u.pid!==void 0)return u.unref(),u.pid}var de,oc,me,Js,Gf,ex,tx,fb,ic,cc=E(()=>{"use strict";de=Ee(require("path"),1),oc=require("os"),me=require("fs"),Js=require("child_process");Na();A();tn();Ba();rn();Bt();Qa();N();He();ct();Gf=We(re.POWERSHELL_COMMAND);ex=j.dataDir(),tx=j.workerPid(),fb="Bun runtime not found \u2014 install from https://bun.sh and ensure it is on PATH, under ~/.bun/bin, or set BUN / BUN_PATH / BUN_INSTALL. The worker daemon requires Bun because it uses bun:sqlite."});function Vf(t){let e=t?.code;return e==="EACCES"||e==="EADDRNOTAVAIL"}var uc,lc=E(()=>{"use strict";uc="Set MEMINDEX_WORKER_PORT to a port between 1024 and 65535 and MEMINDEX_WORKER_HOST to an address of this machine (127.0.0.1 by default) in memindex settings"});function dc(){return z.loadFromFile(ge).MEMINDEX_WORKER_HOST}function qf(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}async function Jf(t,e,r="GET",n=Wt){let s={method:r,signal:AbortSignal.timeout(Math.max(1,n))},i=await fetch(`http://${qf(dc())}:${t}${e}`,r==="GET"||r==="HEAD"?s:en(s)),o="";try{o=await i.text()}catch{}return{ok:i.ok,statusCode:i.status,body:o}}async function Qf(t,e=Wt){let r=Date.now()+e;if(process.platform==="win32")try{let s=await fetch(`http://${qf(dc())}:${t}/api/health`,{signal:AbortSignal.timeout(Math.max(1,r-Date.now()))});if(s.ok)return!0;f.debug("SYSTEM","Windows health check returned non-ok; falling through to socket probe",{port:t,status:s.status})}catch(s){s instanceof Error?f.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:t,message:s.message}):f.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:t,error:String(s)})}let n=await ei(t,Math.max(1,r-Date.now()));return n==="occupied"||n==="indeterminate"}async function ei(t,e=Wt){return(await Sb(t,e)).occupancy}function Sb(t,e=Wt){return e<=0?Promise.resolve({occupancy:"indeterminate"}):new Promise(r=>{let n=!1,s=!1,i=!1,o;try{o=Yf.default.createServer()}catch{r({occupancy:"indeterminate"});return}let a=l=>{if(i){l?.();return}i=!0;try{o.close(l)}catch(d){l?.(d instanceof Error?d:new Error(String(d)))}},c=setTimeout(()=>{if(s)a();else try{o.close()}catch{}u({occupancy:"indeterminate"})},e),u=l=>{n||(n=!0,clearTimeout(c),r(l))};o.once("error",l=>{if(s)a();else try{o.close()}catch{}l.code==="EADDRINUSE"?u({occupancy:"occupied"}):Vf(l)?u({occupancy:"unbindable",bindErrorCode:l.code}):u({occupancy:"indeterminate"})}),o.once("listening",()=>{if(s=!0,n){a();return}try{a(l=>u({occupancy:l?"indeterminate":"free"}))}catch{u({occupancy:"indeterminate"})}});try{o.listen(t,dc())}catch{try{o.close()}catch{}u({occupancy:"indeterminate"})}})}async function yb(t,e,r,n){let s=Date.now()+r;for(;Date.now()<s;){try{let o=s-Date.now();if((await Jf(t,e,"GET",Math.min(Wt,o))).ok)return!0}catch(o){o instanceof Error?f.debug("SYSTEM",n,{},o):f.debug("SYSTEM",n,{error:String(o)})}let i=Math.min(500,s-Date.now());i>0&&await new Promise(o=>setTimeout(o,i))}return!1}function Zf(t,e=3e4){return yb(t,"/api/health",e,"Service not ready yet, will retry")}async function bb(t,e=Wt){try{let r=await Jf(t,"/api/health","GET",e);return r.ok?JSON.parse(r.body).version:null}catch{return f.debug("SYSTEM","Could not fetch worker version",{}),null}}async function ep(t,e,r=Wt){let n=e??"unknown",s=await bb(t,r);return!s||n==="unknown"?{matches:!0,pluginVersion:n,workerVersion:s}:{matches:n===s,pluginVersion:n,workerVersion:s}}var Yf,Wt,ti=E(()=>{"use strict";Yf=Ee(require("net"),1);A();st();N();lc();Ra();Wt=5e3});var tp=E(()=>{"use strict";A();rn()});var rp=E(()=>{"use strict";cc();ti();tp()});function ip(){return(0,ri.join)(U(),"spawn.lock")}function np(t){try{let e=JSON.parse((0,ne.readFileSync)(t,"utf-8"));return typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0?null:e.pid}catch{return null}}function wb(t){if(t===null)return null;try{return process.kill(t,0),!0}catch(e){return e?.code==="EPERM"}}function ni(){let t=ip(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return(0,ne.mkdirSync)((0,ri.dirname)(t),{recursive:!0}),(0,ne.writeFileSync)(t,e,{flag:"wx"}),!0}catch(n){let s=n instanceof Error?n:new Error(String(n)),i=s.code;if(i!=="EEXIST")return f.warn("SYSTEM","Spawn lock write failed for a non-contention reason; failing open (spawning unlocked)",{lockPath:t,code:i},s),!0;if(r>0)return!1;let o;try{o=(0,ne.statSync)(t).mtimeMs}catch{continue}let a=np(t),c=null;if(a===null)try{c=(0,ne.readFileSync)(t,"utf-8")}catch{continue}if(Date.now()-o<=sp&&wb(a)!==!1)return!1;let l;try{l=(0,ne.statSync)(t).mtimeMs}catch{continue}if(l!==o)return!1;if(a!==null){if(np(t)!==a)return!1}else try{if((0,ne.readFileSync)(t,"utf-8")!==c)return!1}catch{continue}try{(0,ne.unlinkSync)(t)}catch{return!1}}return!1}function cn(){let t=ip();try{if(JSON.parse((0,ne.readFileSync)(t,"utf-8")).pid!==process.pid)return;(0,ne.unlinkSync)(t)}catch{}}var ri,ne,sp,bx,op=E(()=>{"use strict";ri=require("path"),ne=require("fs");N();A();sp=9e4,bx=sp/3});function ap(t){return Tb.test(t.trim())}function Ib(t,e){if(!t)return!1;let r=t.toLowerCase().replace(/\\/g,"/"),n=r.indexOf("--data-dir");if(n<0)return!1;let s=r.slice(n+10).trim();if(s.startsWith('"')){let o=s.indexOf('"',1);s=o<0?s.slice(1):s.slice(1,o)}let i=e.toLowerCase().replace(/\\/g,"/");return s===i||s.startsWith(i)&&s[i.length]==="/"}function ii(t,e){return e===void 0?t:Math.max(1,Math.min(t,e))}async function vb(t){try{let e=await si("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name,CommandLine,@{Name='StartToken';Expression={$_.CreationDate.ToString('yyyyMMddHHmmss.ffffff')}} | ConvertTo-Json -Compress"],{timeout:ii(3e4,t),windowsHide:!0,maxBuffer:33554432}),r=JSON.parse(e.stdout),n=Array.isArray(r)?r:r===null?[]:[r],s=[];for(let i of n){let o=typeof i.Name=="string"?i.Name.trim():"";if(!o)continue;let a=typeof i.ProcessId=="number"?i.ProcessId:Number.parseInt(String(i.ProcessId),10),c=typeof i.ParentProcessId=="number"?i.ParentProcessId:Number.parseInt(String(i.ParentProcessId),10);!Number.isInteger(a)||!Number.isInteger(c)||s.push({pid:a,ppid:c,name:o,cmdline:typeof i.CommandLine=="string"?i.CommandLine:null,startToken:typeof i.StartToken=="string"&&i.StartToken.length>0?i.StartToken:null})}return s}catch(e){return f.warn("PROCESS","Cannot enumerate the Windows process table with names \u2014 ghost-port reclaim disabled",{error:e instanceof Error?e.message:String(e)}),null}}async function Rb(t,e){try{let r=await si("netstat",["-ano"],{timeout:ii(15e3,e),windowsHide:!0,maxBuffer:16777216});return Ob(r.stdout,t)}catch(r){return f.warn("PROCESS","netstat failed \u2014 ghost-port reclaim disabled for this attempt",{port:t,error:r instanceof Error?r.message:String(r)}),null}}async function Ab(t,e){try{let r=await si("lsof",["-nP",`-iTCP:${t}`,"-sTCP:LISTEN","-t"],{timeout:ii(1e4,e),maxBuffer:1048576});return Mb(r.stdout)}catch(r){let n=r;return n.code===1&&typeof n.stdout=="string"&&n.stdout.trim()===""?[]:(f.warn("PROCESS","lsof failed \u2014 cannot verify the worker port owner",{port:t,error:r instanceof Error?r.message:String(r)}),null)}}function Mb(t){let e=new Set;for(let r of t.split(/\r?\n/)){let n=Number.parseInt(r.trim(),10);Number.isInteger(n)&&n>0&&e.add(n)}return[...e]}async function Pb(t,e){try{let n=(await si("ps",["-p",String(t),"-o","command="],{timeout:ii(5e3,e)})).stdout.trim();return n.length>0?n:null}catch{return null}}function Ob(t,e){let r=new Set,n=`:${e}`;for(let s of t.split(/\r?\n/)){let i=s.trim();if(!/^TCP\b/i.test(i))continue;let o=i.split(/\s+/);if(!o[1]?.endsWith(n)||o[3]!=="LISTENING")continue;let c=Number.parseInt(o[4]??"",10);Number.isInteger(c)&&c>0&&r.add(c)}return[...r]}async function xb(t,e){let r=e.readOwnedWorker();if(r===null||r.port!==t)return null;let n=(u,l={})=>(f.info("PROCESS","Wedged-worker reclaim declined",{port:t,pid:r.pid,reason:u,...l}),{reclaimed:!1,reason:u,killedPids:[]}),s=(e.now()-Date.parse(r.startedAt))/1e3;if(!Number.isFinite(s)||s<e.minOwnerAgeSeconds)return n("owner-booting",{ageSeconds:s,minOwnerAgeSeconds:e.minOwnerAgeSeconds});for(let u=0;u<2;u++)if(u>0&&await e.sleep(fp),await e.probeHealth(t))return n("owner-responding");let i=await e.listOwners(t);if(i===null)return n("netstat-unreadable");if(!i.includes(r.pid))return f.info("PROCESS","Wedged-worker reclaim: our worker does not own the port \u2014 deferring to the ghost-listener check",{port:t,pid:r.pid,listeners:i}),null;let o=await e.readIdentity(r.pid),a=r.startToken!==void 0&&o.startToken!==null&&o.startToken!==r.startToken;if(a||o.cmdline===null||!kb.test(o.cmdline))return n("owner-identity-mismatch",{tokenMismatch:a,hasCmdline:o.cmdline!==null});if(!e.hasKillBudget())return n("out-of-budget");f.warn("PROCESS","Reclaiming wedged worker: past its boot grace, silent on two health probes, and still holding the port",{port:t,pid:r.pid,ageSeconds:Math.round(s)});try{await e.killTree(r.pid,{expectedStartToken:o.startToken??r.startToken??void 0,signalMode:"graceful"})}catch(u){return f.error("PROCESS","Wedged-worker reclaim tree-kill failed",{port:t,pid:r.pid},u instanceof Error?u:new Error(String(u))),{reclaimed:!1,reason:"kill-failed",killedPids:[]}}let c=await e.listOwners(t);return c!==null&&c.length===0?(f.info("PROCESS","Wedged worker reclaimed \u2014 port is free again",{port:t,killedPids:[r.pid]}),{reclaimed:!0,killedPids:[r.pid]}):(f.warn("PROCESS","Wedged-worker reclaim killed the worker but the port is still bound",{port:t,pid:r.pid,stillOwnedBy:c}),{reclaimed:!1,reason:"still-bound",killedPids:[r.pid]})}async function Nb(t,e,r,n){let s=Xe(t),i=e?(await r(n))?.find(o=>o.pid===t)?.cmdline??null:await Pb(t,n);return Oe(t,s)?{startToken:s,cmdline:i}:{startToken:null,cmdline:null}}async function pp(t,e={}){let r=e.isWin32??(()=>process.platform==="win32"),n=e.now??Date.now,s=e.deadlineAt??null,i=I=>s!==null&&s-n()<I,o=()=>s===null?void 0:Math.max(1,s-n());if(i(cp))return f.info("PROCESS","Port reclaim skipped: not enough of the hook budget is left to finish one",{port:t,remainingMs:o(),neededMs:cp}),{reclaimed:!1,reason:"out-of-budget",killedPids:[]};let a=e.listOwners??((I,O)=>r()?Rb(I,O):Ab(I,O)),c=I=>a(I,o()),u=e.readTable??vb,l=()=>u(o()),d=e.killTree??((I,O)=>ye(I,O)),p=e.dataDir??(()=>W),g=e.readIdentity??((I,O)=>Nb(I,r(),u,O)),m=await xb(t,{listOwners:c,killTree:d,readOwnedWorker:e.readOwnedWorker??at,probeHealth:e.probeHealth??(I=>Zf(I,dp)),readIdentity:I=>g(I,o()),minOwnerAgeSeconds:e.minOwnerAgeSeconds??gd(),now:n,sleep:e.sleep??(I=>new Promise(O=>setTimeout(O,I))),hasKillBudget:()=>!i(fc)});if(m!==null)return m;if(!r())return{reclaimed:!1,reason:"not-supported",killedPids:[]};let h=await c(t);if(h===null)return{reclaimed:!1,reason:"netstat-unreadable",killedPids:[]};if(h.length===0)return{reclaimed:!1,reason:"no-listener",killedPids:[]};let _=await l();if(_===null)return{reclaimed:!1,reason:"table-unreadable",killedPids:[]};if(h.filter(I=>V(I)).length>0)return{reclaimed:!1,reason:"owner-alive",killedPids:[]};let b=new Map;for(let I of _){let O=b.get(I.ppid);O?O.push(I):b.set(I.ppid,[I])}let w=new Map,T=new Set,y=I=>{for(let O of b.get(I)??[])T.has(O.pid)||(T.add(O.pid),y(O.pid),ap(O.name)&&w.set(O.pid,O))};for(let I of h)y(I);let P=p();if(P)for(let I of _)w.has(I.pid)||ap(I.name)&&Ib(I.cmdline,P)&&w.set(I.pid,I);if(w.size===0)return f.info("PROCESS","Ghost listener owner is dead but no chroma-sidecar descendants found",{port:t,deadOwners:h,processTableRows:_.length,dataDir:P??"(unresolved)"}),{reclaimed:!1,reason:"no-chroma-descendants",killedPids:[]};f.warn("PROCESS","Reclaiming ghost listener: killing dead worker's surviving chroma sidecar chain",{port:t,deadOwners:h,targets:[...w.values()].map(I=>({pid:I.pid,name:I.name}))});let v=[];for(let I of w.values()){if(i(fc))return f.info("PROCESS","Ghost-listener reclaim stopped before a kill: the hook budget is spent",{port:t,killedPids:v}),{reclaimed:!1,reason:"out-of-budget",killedPids:v};try{await d(I.pid,{expectedStartToken:I.startToken,signalMode:"immediate"}),v.push(I.pid)}catch(O){return f.error("PROCESS","Ghost-port reclaim tree-kill failed",{port:t,pid:I.pid},O instanceof Error?O:new Error(String(O))),{reclaimed:!1,reason:"kill-failed",killedPids:v}}}let R=await c(t);return R!==null&&R.length===0?(f.info("PROCESS","Ghost listener reclaimed \u2014 port is free again",{port:t,killedPids:v}),{reclaimed:!0,killedPids:v}):(f.warn("PROCESS","Ghost-port reclaim killed the sidecar chain but the port is still bound",{port:t,killedPids:v,stillOwnedBy:R}),{reclaimed:!1,reason:"still-bound",killedPids:v})}var up,lp,si,Tb,kb,dp,fp,fc,cp,gp=E(()=>{"use strict";up=require("node:child_process"),lp=require("node:util");A();lr();ct();rn();ti();Rs();He();N();si=(0,lp.promisify)(up.execFile),Tb=/^(uv|uvx|python|chroma-mcp)(\.exe)?$/i;kb=/worker-service/i,dp=1500,fp=1e3,fc=5500,cp=2*dp+fp+fc});function mp(t){try{return(0,hr.realpathSync)(t)}catch{return t}}function Db(t,e){let r=yt.default.relative(e,t);return r!==""&&!r.startsWith("..")&&!yt.default.isAbsolute(r)}function _p(t){let e;try{let s=JSON.parse((0,hr.readFileSync)(yt.default.join(t,"package.json"),"utf-8"));e=Object.keys(s?.dependencies??{})}catch{return[]}if(e.length===0)return[];let r=yt.default.join(t,"node_modules"),n=e.filter(s=>!(0,hr.existsSync)(yt.default.join(r,...s.split("/"),"package.json")));if(e.includes("zod")&&!n.includes("zod")){let s=(0,hp.createRequire)(yt.default.join(r,"noop.js")),i=mp(yt.default.join(r,"zod"));for(let o of Cb)try{let a=s.resolve(o,{paths:[r]});Db(mp(a),i)||n.push(o)}catch{n.push(o)}}return n}var hr,hp,yt,Cb,Ep=E(()=>{"use strict";hr=require("fs"),hp=require("module"),yt=Ee(require("path"),1),Cb=["zod/v3","zod/v4","zod/v4-mini"]});function bp(){return oi.default.join(U(),"worker-standby.json")}function mc(){return oi.default.join(U(),"worker-standby-attempt.json")}function hc(){return oi.default.join(U(),"worker-standby-failure.json")}function _c(t){try{return JSON.parse((0,ai.readFileSync)(t,"utf-8"))}catch{return null}}function Ec(t){try{(0,ai.unlinkSync)(t)}catch(e){e.code!=="ENOENT"&&f.debug("SYSTEM","Could not remove worker standby file",{path:t,error:e instanceof Error?e.message:String(e)})}}function ci(){let t=_c(bp());return!t||typeof t.pid!="number"||!Number.isInteger(t.pid)||t.pid<=0||typeof t.port!="number"||!Number.isInteger(t.port)||t.port<=0||typeof t.version!="string"?null:{pid:t.pid,port:t.port,version:t.version,startedAt:typeof t.startedAt=="string"?t.startedAt:""}}function ui(t){if(t!==void 0){let e=ci();if(e!==null&&e.pid!==t)return}Ec(bp())}function Fb(){let t=_c(hc());return!t||typeof t.buildKey!="string"||typeof t.failedAt!="string"?null:{buildKey:t.buildKey,failedAt:t.failedAt,reason:typeof t.reason=="string"?t.reason:""}}function wp(t,e,r=new Date){try{X(hc(),{buildKey:t,failedAt:r.toISOString(),reason:e})}catch(n){f.warn("SYSTEM","Could not save the failed worker update attempt",{error:n instanceof Error?n.message:String(n)})}}function Tp(){Ec(hc())}function Ip(t,e=Date.now()){if(t===null)return null;let r=Fb();if(r===null||r.buildKey!==t)return null;let n=Date.parse(r.failedAt);return!Number.isFinite(n)||e-n>=gc?null:r}function vp(){let t=_c(mc());return!t||typeof t.buildKey!="string"||typeof t.launchedAtMs!="number"||!Number.isFinite(t.launchedAtMs)?null:{buildKey:t.buildKey,launchedAtMs:t.launchedAtMs}}function Rp(t){try{X(mc(),t)}catch(e){f.debug("SYSTEM","Could not save the worker update attempt",{error:e instanceof Error?e.message:String(e)})}}function Ap(){Ec(mc())}var oi,ai,Sp,pc,yp,gc,Mp=E(()=>{"use strict";oi=Ee(require("path"),1),ai=require("fs");N();ie();A();Sp="MEMINDEX_WORKER_STANDBY",pc=12e4,yp=2e4,gc=10*6e4});function Ic(t,e,r){let n=process.env[t];if(n){let s=parseInt(n,10);if(Number.isFinite(s)&&s>=r.min&&s<=r.max)return s;f.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max})}return e}function Wp(t=process.env){let e=t.MEMINDEX_FETCH_VERBOSE;if(e===void 0)return!1;let r=e.trim().toLowerCase();return r==="1"||r==="true"||r==="on"||r==="yes"}function Bb(t){return Wp()?{...t,verbose:!0}:t}function Wb(t){let e={},r=t;for(let n=0;r&&n<4;n++){let s=n===0?"error":`cause${n}`;if(r instanceof Error){let i=r;e[s]={name:r.name,message:r.message,...i.code!==void 0?{code:i.code}:{}},r=r.cause;continue}e[s]=String(r);break}return e}function Hb(t,e,r){let n=typeof e.method=="string"?e.method:"GET",s=Wb(r),i=JSON.stringify(s);f.warn("SYSTEM","Worker IPC fetch failed",{url:t,method:n},i),tt(`[memindex] fetch verbose: ${n} ${t} ${i}
|
|
22
|
-
`)}async function Rc(t,e={}){let r=Bb(e);try{return await fetch(t,r)}catch(n){throw Wp()&&Hb(t,e,n),n}}async function dn(t,e={},r){try{return await Rc(t,{...e,signal:AbortSignal.timeout(r)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new Error(`Request timed out after ${r}ms`):n}}function jb(t,e){let r=new AbortController,n=null,s=null,i=null,o=!1,a=()=>{s!==null&&(clearTimeout(s),s=null)},c=()=>{o=!0,a(),i!==null&&(clearTimeout(i),i=null)},u=d=>{o||(n=d,c(),r.abort(d))},l=()=>{o||(a(),s=setTimeout(()=>u(new Error(`Request timed out after ${t.idleTimeoutMs}ms idle`)),t.idleTimeoutMs))};if(t.absoluteCapMs!==void 0&&t.absoluteCapMs>0){let d=t.absoluteCapMs;i=setTimeout(()=>u(new Error(`Request timed out after ${d}ms`)),d)}return l(),{signal:e?AbortSignal.any([e,r.signal]):r.signal,touch:l,pause:a,dispose:c,translate:d=>n??d}}async function Hp(t,e,r){let n=jb(r,e.signal),s;try{s=await Rc(t,{...e,signal:n.signal})}catch(u){throw n.dispose(),n.translate(u)}n.touch();let i=s.body,o=i?i.getReader():null,a=!1;async function*c(){if(!o){a=!0,n.dispose();return}try{for(;;){n.touch();let u;try{u=await o.read()}catch(l){throw a=!0,n.translate(l)}if(u.done){a=!0;return}n.pause(),r.onChunk?.(u.value),yield u.value}}finally{n.dispose(),a||await o.cancel()}}return{status:s.status,statusText:s.statusText,ok:s.ok,headers:s.headers,chunks:c(),cancel:async()=>{n.dispose(),o&&!a&&(a=!0,await o.cancel())}}}async function Xb(t,e,r){let n=await Hp(t,e,r),s=new TextDecoder,i="";for await(let o of n.chunks)i+=s.decode(o,{stream:!0});return i+=s.decode(),{status:n.status,statusText:n.statusText,ok:n.ok,headers:n.headers,text:i}}function Pp(){return F.default.join(z.get("MEMINDEX_DATA_DIR"),"settings.json")}function Ac(t={}){return t.readOnly?z.loadFromFile(Pp(),!0,t):(li!==null||(li=z.loadFromFile(Pp())),li)}function Op(t,e){if(!t)return null;let r=parseInt(t,10);return Number.isFinite(r)&&r>=e.min&&r<=e.max?r:null}function jp(t,e,r){let n=process.env[t];if(n!==void 0){let o=Op(n,r);return o!==null?o:(f.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max}),e)}let s=Ac()[t],i=Op(s,r);return i!==null?i:(f.warn("SYSTEM",`Invalid ${t} in settings.json, using default`,{value:s,min:r.min,max:r.max}),e)}function ce(t={}){if(!t.readOnly&&Sc!==null)return Sc;let e=parseInt(Ac(t).MEMINDEX_WORKER_PORT,10);return t.readOnly||(Sc=e),e}function Mc(t={}){if(!t.readOnly&&yc!==null)return yc;let e=Ac(t).MEMINDEX_WORKER_HOST;return t.readOnly||(yc=e),e}function Kb(){return di!==null||(di=jp("MEMINDEX_API_TIMEOUT_MS",We(re.API_REQUEST),Ub)),di}function Xp(){return fi!==null||(fi=Math.min(jp("MEMINDEX_SESSION_INIT_TIMEOUT_MS",qr(),$b),md())),fi}function hi(t){return t===null?null:Math.max(0,t-Date.now())}function gi(t){let e=hi(t);return e!==null&&e<vc}function ke(t,e){let r=hi(e);return r===null?t:Math.max(1,Math.min(t,r))}function Kp(t){return`http://${Pa(Mc())}:${ce()}${t}`}function fe(t,e={}){let r=e.method??"GET",n=Kp(t),s={method:r};e.headers&&(s.headers=e.headers),e.body&&(s.body=e.body);let i=en(s);if(e.idleTimeoutMs!==void 0&&e.idleTimeoutMs>0)return Xb(n,i,{idleTimeoutMs:e.idleTimeoutMs,absoluteCapMs:e.timeoutMs}).then(a=>new Response(a.text.length>0?a.text:null,{status:a.status,statusText:a.statusText,headers:a.headers}));let o=e.timeoutMs??Kb();return o>0?dn(n,i,o):Rc(n,i)}async function Gb(t){return(await fe("/api/health",{timeoutMs:t})).ok}async function kp(t=bt){return(await fe("/api/readiness",{timeoutMs:t})).ok}function Gp(t){let e=(0,k.existsSync)(F.default.join(t,"plugin","scripts"))?F.default.join(t,"plugin"):t;return F.default.join(e,"scripts","worker-service.cjs")}function zb(t,e){let r=d=>{let p=d.split("-")[0].split(".");return[parseInt(p[0],10)||0,parseInt(p[1],10)||0,parseInt(p[2],10)||0]},[n,s,i]=r(t),[o,a,c]=r(e);if(o!==n)return o-n;if(a!==s)return a-s;if(c!==i)return c-i;let u=t.includes("-")?1:0,l=e.includes("-")?1:0;return u!==l?u-l:t<e?1:t>e?-1:0}function Vb(t=F.default.join(F.default.dirname(F.default.dirname(cr)),"cache","memindex","memindex")){try{return(0,k.readdirSync)(t).filter(e=>/^\d/.test(e)).map(e=>F.default.join(t,e)).filter(e=>{try{if(!(0,k.statSync)(e).isDirectory())return!1}catch{return!1}return!(0,k.existsSync)(F.default.join(e,".orphaned_at"))}).map(e=>({scriptPath:Gp(e),version:F.default.basename(e)}))}catch{return[]}}function xp(t){try{let e=JSON.parse((0,k.readFileSync)(t,"utf-8"));return typeof e.version=="string"?e.version:null}catch(e){let r=e.code;return r!=="ENOENT"&&f.debug("SYSTEM","Could not read package version for worker resolution",{packageJsonPath:t,code:r}),null}}function Yb(){return{cacheRoot:F.default.join(F.default.dirname(F.default.dirname(cr)),"cache","memindex","memindex"),marketplaceRoot:cr,cwd:process.cwd()}}function Pc(t=Yb()){let e=process.env.MEMINDEX_WORKER_SCRIPT_PATH?.trim();if(e){if((0,k.existsSync)(e))return{scriptPath:e,version:null};f.debug("SYSTEM","Ignoring missing MEMINDEX_WORKER_SCRIPT_PATH override",{override:e})}let r=[...Vb(t.cacheRoot),{scriptPath:Gp(F.default.join(t.marketplaceRoot,"plugin")),version:xp(F.default.join(t.marketplaceRoot,"package.json"))},{scriptPath:F.default.join(t.cwd,"plugin","scripts","worker-service.cjs"),version:xp(F.default.join(t.cwd,"package.json"))}];return Qb(r)}function qb(t){return F.default.dirname(F.default.dirname(t))}function Jb(t){return _p(qb(t.scriptPath)).length===0}function Qb(t,e=Jb){let r=t.filter(n=>(0,k.existsSync)(n.scriptPath));return r.length===0?null:(r.sort((n,s)=>n.version===null&&s.version===null?0:n.version===null?1:s.version===null?-1:zb(n.version,s.version)),r.find(e)??r[0])}function Zb(){return Pc()?.scriptPath??null}async function ew(t){let e=t.deadlineAt??null,r=t.backoffMs;for(let n=1;n<=t.attempts;n++){if(gi(e))return!1;if(await tg(e??Number.POSITIVE_INFINITY))return!0;n<t.attempts&&(await new Promise(s=>setTimeout(s,ke(r,e))),r*=2)}return!1}function Np(t){return t instanceof Error&&/^Request timed out after \d+ms idle$/.test(t.message)}function Cp(t){return t instanceof Error&&/^Request timed out after \d+ms$/.test(t.message)}async function tw(t){let e;try{e=await Hp(Kp("/api/ready"),{method:"GET"},{idleTimeoutMs:Lb,absoluteCapMs:Math.max(1,t)})}catch(i){return Np(i)?{outcome:"unresponsive",detail:"no response headers within the idle window"}:Cp(i)?{outcome:"still_booting",detail:"budget spent before response headers"}:(f.debug("SYSTEM","Worker /api/ready connection failed",{error:i instanceof Error?i.message:String(i)}),{outcome:"not_running"})}let r=()=>e.cancel().catch(i=>{f.debug("SYSTEM","Releasing the /api/ready body failed",{error:i instanceof Error?i.message:String(i)})}),n=e.headers?.get("content-type")??"";if(!e.ok||!n.includes("text/event-stream"))return mi(),await r(),{outcome:"unsupported"};let s=null;try{for await(let i of $d(e.chunks)){if(i.event!=="phase")continue;let o=JSON.parse(i.data);if(s=typeof o.phase=="string"?o.phase:null,s==="ready")return mi(),await r(),{outcome:"ready"};if(s==="failed")return await r(),{outcome:"failed",detail:typeof o.message=="string"?o.message:"unknown init failure"}}}catch(i){return Cp(i)?(mi(),{outcome:"still_booting",detail:`last phase ${s??"none"}`}):Np(i)?{outcome:"unresponsive",detail:`silent past the idle window after response headers (last phase ${s??"none"})`}:{outcome:"wedged",detail:`stream error: ${i instanceof Error?i.message:String(i)} (last phase ${s??"none"})`}}return{outcome:"wedged",detail:`stream closed before ready/failed (last phase ${s??"none"})`}}async function rw(t){if(t<=0)try{return await kp()?{outcome:"ready"}:{outcome:"still_booting"}}catch(r){return f.debug("SYSTEM","Worker readiness check threw",{},r instanceof Error?r:new Error(String(r))),{outcome:"still_booting"}}let e=Date.now();do{let r=t-(Date.now()-e);try{if(await kp(Math.max(1,Math.min(bt,r))))return{outcome:"ready"}}catch(s){f.debug("SYSTEM","Worker readiness check threw",{error:s instanceof Error?s.message:String(s)})}let n=t-(Date.now()-e);if(n<=0)break;await new Promise(s=>setTimeout(s,Math.min(250,n)))}while(Date.now()-e<t);return{outcome:"still_booting",detail:"legacy /api/readiness never reported ready"}}async function jt(t=_r){let e=t>0?t:bt,r=await tw(e);return r.outcome==="ready"&&uw(),r.outcome!=="unsupported"?r:(f.debug("SYSTEM","Worker has no /api/ready stream; falling back to /api/readiness"),rw(t))}async function nw(t=bt){try{let r=await(await fe("/api/health",{timeoutMs:t})).json();return typeof r.version=="string"?r.version:null}catch(e){let r=e instanceof Error?e:new Error(String(e));return f.debug("SYSTEM","Worker health-version fetch failed",{},r),null}}async function sw(t=5e3){let e=Date.now()+t;for(;;){let r=e-Date.now();if(r<=0)return!1;if(await ei(ce(),Math.min(1e3,r))==="free")return!0;let n=Math.min(200,e-Date.now());n>0&&await new Promise(s=>setTimeout(s,n))}}function zp(t,e){if(!t)return null;try{let r=(0,k.statSync)(t.scriptPath);return JSON.stringify([t.scriptPath,e,r.size,r.mtimeMs,r.ctimeMs])}catch{return null}}function Vp(){return F.default.join(U(),"worker-version-recycle.json")}function iw(t,e){if(t===null||e===null)return!1;try{let r=JSON.parse((0,k.readFileSync)(Vp(),"utf-8"));return r?.buildKey===t&&r?.workerVersion===e}catch{return!1}}async function Dp(t,e=null,r=bt){let n=await nw(r);if(n!==null&&n!==t){if(e!==null)try{X(Vp(),{buildKey:e,workerVersion:n})}catch(s){f.warn("SYSTEM","Could not persist the failed worker version recycle",{error:s instanceof Error?s.message:String(s)})}f.warn("SYSTEM","Worker is ready but still reports a stale version; rebuild or reinstall the worker bundle before retrying",{pluginVersion:t,workerVersion:n})}}function Oc(){return F.default.join(U(),"worker-unresponsive.json")}function ow(){try{let t=JSON.parse((0,k.readFileSync)(Oc(),"utf-8"));return typeof t?.pid!="number"||typeof t?.firstUnresponsiveAtEpochMs!="number"?null:{pid:t.pid,firstUnresponsiveAtEpochMs:t.firstUnresponsiveAtEpochMs}}catch{return null}}function mi(){let t=Oc();if((0,k.existsSync)(t))try{(0,k.unlinkSync)(t)}catch(e){f.debug("SYSTEM","Could not clear the unresponsive-worker record",{error:e instanceof Error?e.message:String(e)})}}function aw(t=Date.now()){let e=at()?.pid??null;if(e===null)return!1;let r=ow();if(r!==null&&r.pid===e)return t-r.firstUnresponsiveAtEpochMs>=Yp;try{X(Oc(),{pid:e,firstUnresponsiveAtEpochMs:t})}catch(n){f.warn("SYSTEM","Could not persist the unresponsive-worker record",{error:n instanceof Error?n.message:String(n)})}return!1}function kc(){return F.default.join(U(),"worker-never-ready-recycle.json")}function cw(){try{let t=JSON.parse((0,k.readFileSync)(kc(),"utf-8"));return typeof t?.buildKey!="string"||typeof t?.failureMessage!="string"?null:{buildKey:t.buildKey,failureMessage:t.failureMessage,refusalLogged:t.refusalLogged===!0}}catch{return null}}function qp(t){try{X(kc(),t)}catch(e){f.warn("SYSTEM","Could not persist the never-ready worker recycle",{error:e instanceof Error?e.message:String(e)})}}function uw(){let t=kc();if((0,k.existsSync)(t))try{(0,k.unlinkSync)(t)}catch(e){f.debug("SYSTEM","Could not clear the never-ready worker recycle record",{error:e instanceof Error?e.message:String(e)})}}function Jp(t){return zp(t,t?.version??"unknown")??"unresolved-worker-bundle"}function Qp(t){return t.outcome==="failed"?t.detail??"unknown init failure":t.outcome}function Zp(t,e){if(t.outcome==="unresponsive"&&!aw())return f.warn("SYSTEM","Worker went silent on /api/ready; skipping this hook without killing it",{detail:t.detail,wedgedAfterMs:Yp}),!1;let r=Qp(t),n=cw();return n!==null&&n.buildKey===e&&n.failureMessage===r?(n.refusalLogged?f.debug("SYSTEM","Never-ready worker recycle already refused for this bundle and failure",{failureMessage:r}):(f.error("SYSTEM","Worker keeps failing to start the same way after a recycle; not recycling again. Run `npx memindex doctor` and check the worker logs",{outcome:t.outcome,failureMessage:r,logsDir:F.default.join(U(),"logs")}),qp({...n,refusalLogged:!0})),!1):!0}function eg(t,e){qp({buildKey:e,failureMessage:Qp(t)}),mi()}async function tg(t=Number.POSITIVE_INFINITY){let e=t-Date.now();if(e<=0)return!1;let r;try{r=await Gb(Math.min(bt,e))}catch(n){return f.debug("SYSTEM","Worker health check threw",{error:n instanceof Error?n.message:String(n)}),!1}return r}async function xc(t,e){let r=at();if(r===null||r.port!==ce())return f.error("SYSTEM","Stale worker is serving the port but the PID file does not identify it; kill the memindex worker process manually",{port:ce(),pidFilePid:r?.pid??null,pidFilePort:r?.port??null}),!1;if(e("stale-worker recycle"))return!1;try{await ye(r.pid,{signalMode:"immediate"})}catch(n){return f.error("SYSTEM","Could not kill stale worker",{pid:r.pid,port:r.port},n instanceof Error?n:new Error(String(n))),!1}return await sw(ke(5e3,t))?!0:(e("stale port release")||(Xt=ce(),f.error("SYSTEM","Stale worker port still open after SIGKILL; skipping spawn this hook event",{pid:r.pid,port:ce(),fix:_i})),!1)}function rg(t,e){return`http://127.0.0.1:${t}${e}`}async function ng(t,e){if(e<=0)return{answered:!1,version:null};try{let n=await(await dn(rg(t.port,"/api/health"),{},e)).json();return n.pid!==t.pid||n.standby!==!0?{answered:!1,version:null}:{answered:!0,version:typeof n.version=="string"?n.version:null}}catch{return{answered:!1,version:null}}}function sg(t){try{process.kill(t.pid,"SIGKILL")}catch(e){f.debug("SYSTEM","Could not stop the standby worker",{pid:t.pid,error:e instanceof Error?e.message:String(e)})}ui(t.pid)}async function lw(t,e,r,n){let s=await dw(t,e,r,n);return s.kind!=="out-of-budget"&&Ap(),s}async function dw(t,e,r,n){let s=ci(),i=s===null?null:await ng(s,ke(bt,n));if(s!==null&&i!==null&&i.answered&&i.version===e)return f.info("SYSTEM","Found the updated worker already waiting to take over",{pid:s.pid,port:s.port}),{kind:"ready",record:s};let o={kind:"failed",reason:`it did not answer its health check within ${Math.round(un/1e3)} seconds; the worker log has the reason`};if(s!==null&&i!==null)if(i.answered)sg(s);else{let d=Date.parse(s.startedAt);if((Number.isFinite(d)?Date.now()-d:Number.POSITIVE_INFINITY)<pc&&V(s.pid)){let g=Math.min(d+pc,Math.max(d+un,Date.now()+2e3)),m=await bc(e,g,n,o);return m.kind==="failed"&&ui(s.pid),m}ui(s.pid)}let a=r===null?null:vp();if(a!==null&&a.buildKey===r)return Date.now()-a.launchedAtMs>=un?o:bc(e,a.launchedAtMs+un,n,o);let c=Qs();if(!c)return{kind:"failed",reason:"Bun, which runs the worker, was not found"};if(!t)return{kind:"failed",reason:"the new worker program (worker-service.cjs) was not found"};f.info("SYSTEM","Starting the updated worker next to the running one",{runtimePath:c,scriptPath:t});let u;try{u=Zs(c,t,ot({...process.env,MEMINDEX_WORKER_PORT:String(ce()),[Sp]:"1"}),process.platform,hi(n)??void 0)}catch(d){return{kind:"failed",reason:`it could not be launched (${d instanceof Error?d.message:String(d)})`}}if(u===void 0)return{kind:"failed",reason:"it could not be launched"};let l=Date.now();return r!==null&&Rp({buildKey:r,launchedAtMs:l}),bc(e,l+un,n,o)}async function bc(t,e,r,n){let s=Math.min(e,r??Number.POSITIVE_INFINITY);for(;Date.now()<s;){let i=ci();if(i!==null){let a=await ng(i,Math.min(1e3,s-Date.now()));if(a.answered)return a.version===t?{kind:"ready",record:i}:(sg(i),{kind:"failed",reason:`it reports version ${a.version??"unknown"} instead of ${t}; the installed files are mislabelled`})}let o=Math.min(200,s-Date.now());o>0&&await new Promise(a=>setTimeout(a,o))}return Date.now()<e?{kind:"out-of-budget"}:n}async function fw(t,e){try{let r=await dn(rg(t.port,"/api/admin/promote"),en({method:"POST"}),e);if(r.ok)return null;let n=await r.json().catch(()=>({}));return typeof n.message=="string"?n.message:`HTTP ${r.status}`}catch(r){return r instanceof Error?r.message:String(r)}}async function pw(t){let{scriptPath:e,pluginVersion:r,workerVersion:n,buildKey:s,deadlineAt:i,outOfBudget:o}=t,a=n??"unknown",c=Ip(s);if(c!==null)return f.debug("SYSTEM","Keeping the running worker: this update failed to start a short while ago",{pluginVersion:r,workerVersion:n,failedAt:c.failedAt,reason:c.reason}),"kept-old";let u=at();if(u===null||u.port!==ce())return f.error("SYSTEM","Stale worker is serving the port but the PID file does not identify it; kill the memindex worker process manually",{port:ce(),pidFilePid:u?.pid??null,pidFilePort:u?.port??null}),"failed";if(!ni())return f.info("SYSTEM","Another launcher is starting the updated worker; the running worker keeps serving meanwhile"),"kept-old";let l=!1;try{let d=await lw(e,r,s,i);if(d.kind==="out-of-budget")return f.info("SYSTEM","The updated worker is still starting; the running worker keeps serving until a later hook hands over",{pluginVersion:r,workerVersion:n}),"kept-old";if(d.kind==="failed")return s!==null&&wp(s,d.reason),f.error("SYSTEM",`The updated MemIndex worker (version ${r}) did not start, so the running worker (version ${a}) keeps serving: ${d.reason}. MemIndex tries the update again in ${Math.round(gc/6e4)} minutes, or as soon as the plugin is reinstalled.`,{pluginVersion:r,workerVersion:n,scriptPath:e}),"kept-old";if(o("stale-worker recycle"))return"kept-old";if(!await xc(i,o))return"failed";l=!0;let p=await fw(d.record,ke(1e4,i));return p===null?(Tp(),f.info("SYSTEM","The updated worker took over from the old one",{from:n,to:r,pid:d.record.pid}),"promoted"):(f.warn("SYSTEM","The updated worker could not take over the worker port; starting a new worker the usual way",{pluginVersion:r,reason:p}),"old-stopped")}finally{l||cn()}}async function Er(t){let e=t===void 0?null:Date.now()+t,r=S=>gi(e)?(f.warn("SYSTEM","Worker check ran out of the hook budget; skipping the rest this hook event",{step:S,budgetMs:t}),!0):!1,n=()=>e===null?void 0:ke(bt,e),s=Math.min(Date.now()+5e3,e??Number.POSITIVE_INFINITY),i=Pc(),o=null,a=null,c=!1,u=!1,l=!1,d=null,p=null,g=vs(K());if(r("health probe"))return!1;if(await tg(s)){if(r("version probe"))return!1;let{matches:S,pluginVersion:b,workerVersion:w}=await ep(ce(),i?.version??null,n());if(b!=="unknown"&&(o=b),S){if(r("readiness wait"))return!1;let T=await jt(ke(_r,e));if(T.outcome==="ready")return o!==null&&!gi(e)&&await Dp(o,null,n()),!0;if(T.outcome==="still_booting"||T.outcome==="not_running")return f.warn("SYSTEM","Worker is healthy but not ready yet; skipping hook API call",{outcome:T.outcome,detail:T.detail}),!1;if(g)return f.warn("SYSTEM","Worker will never become ready; MEMINDEX_WORKER_AUTOSTART=false, so leaving it to whatever manages it",{outcome:T.outcome,detail:T.detail}),!1;if(p=Jp(i),!Zp(T,p))return!1;d=T,f.info("SYSTEM","Worker will never become ready \u2014 recycling wedged worker",{outcome:T.outcome,detail:T.detail,version:w})}else{if(g)return f.warn("SYSTEM","Worker version differs from the installed plugin; MEMINDEX_WORKER_AUTOSTART=false, so using it as is",{pluginVersion:b,workerVersion:w}),r("readiness wait")?!1:(await jt(ke(_r,e))).outcome==="ready";if(a=zp(i,b),iw(a,w))return f.warn("SYSTEM","Skipping repeated worker recycle: the unchanged bundle still reports a stale version; rebuild or reinstall it",{pluginVersion:b,workerVersion:w,scriptPath:i?.scriptPath}),r("readiness wait")?!1:(await jt(ke(_r,e))).outcome==="ready";f.info("SYSTEM","Worker version changed \u2014 starting the new worker before stopping the old one",{pluginVersion:b,workerVersion:w});let T=await pw({scriptPath:i?.scriptPath??null,pluginVersion:b,workerVersion:w,buildKey:a,deadlineAt:e,outOfBudget:r});if(T==="failed")return!1;if(T==="kept-old")return r("readiness wait")?!1:(await jt(ke(_r,e))).outcome==="ready";u=!0,l=T==="promoted"}if(!u&&!await xc(e,r))return!1;d!==null&&p!==null&&eg(d,p),c=!0}if(g)return f.debug("SYSTEM","Worker not running and MEMINDEX_WORKER_AUTOSTART=false \u2014 not lazy-spawning"),!1;let m=i?.scriptPath??null;if(r("lazy spawn"))return u&&cn(),!1;let h=u||ni();try{if(h&&!l){if(!c&&!await gw(s,e))return!1;let b=Qs();if(!b)return f.warn("SYSTEM","Cannot lazy-spawn worker: Bun runtime not found (PATH, BUN / BUN_PATH / BUN_INSTALL, or ~/.bun/bin)"),!1;if(!m)return f.warn("SYSTEM","Cannot lazy-spawn worker: worker-service.cjs not found in plugin/scripts"),!1;f.info("SYSTEM","Worker not running \u2014 lazy-spawning",{runtimePath:b,scriptPath:m});try{if(Zs(b,m,ot({...process.env,MEMINDEX_WORKER_PORT:String(ce())}),process.platform,hi(e)??void 0)===void 0)return!1}catch(w){return w instanceof Error?f.error("SYSTEM","Lazy-spawn of worker failed",{runtimePath:b,scriptPath:m},w):f.error("SYSTEM","Lazy-spawn of worker failed (non-Error)",{runtimePath:b,scriptPath:m,error:String(w)}),!1}}else h||f.info("SYSTEM","Another launcher holds the spawn lock \u2014 skipping lazy-spawn and waiting for its worker");if(!await ew({attempts:6,backoffMs:500,deadlineAt:e}))return r("cold-boot port wait")||(f.warn("SYSTEM",h?"Worker port did not open after lazy-spawn within the cold-boot wait (~15s)":"Spawn-lock holder's worker port did not open within the cold-boot wait (~15s)"),at()===null&&await Qf(ce(),e===null?void 0:ke(5e3,e))&&(Xt=ce(),f.error("SYSTEM","Worker port is occupied by an unreachable process that no PID file claims (likely an orphaned OS socket); every lazy-spawn on this port will be silently refused",{port:Xt,fix:_i}))),!1}finally{h&&cn()}if(r("readiness wait"))return!1;let _=await jt(ke(_r,e));return _.outcome!=="ready"?(f.warn("SYSTEM","Worker lazy-spawned but did not become ready before hook readiness timeout",{outcome:_.outcome,detail:_.detail}),!1):(o!==null&&!gi(e)&&await Dp(o,a,n()),!0)}async function gw(t,e){let r=ce(),n=t-Date.now();if(n<=0)return!1;let s=await ei(r,n);if(s==="free")return!0;if(s==="unbindable")return Tc=r,f.error("SYSTEM","Worker port cannot be bound (EACCES or EADDRNOTAVAIL) \u2014 skipping lazy-spawn",{port:r,host:Mc(),fix:uc}),!1;if(s==="indeterminate")return f.warn("SYSTEM","Worker port state could not be determined in time \u2014 skipping lazy-spawn",{port:r}),!1;let i=await pp(r,{deadlineAt:e});return i.reclaimed?(f.info("SYSTEM","Reclaimed the worker port before lazy-spawn",{port:r,killedPids:i.killedPids}),!0):(at()===null&&(Xt=r),f.warn("SYSTEM","Worker port is held by a listener that does not answer health \u2014 skipping lazy-spawn",{port:r,reclaimReason:i.reason,...Xt===r?{fix:_i}:{}}),!1)}async function mw(t){return pi!==null||(pi=await Er(t)),pi}async function hw(t){let e=Date.now()+t,r=()=>e-Date.now(),n=u=>r()>=vc?!1:(f.debug("SYSTEM","Bounded worker startup ran out of budget",{step:u,budgetMs:t}),!0),s=await jt(Math.max(1,r()));if(s.outcome==="ready")return!0;if(s.outcome==="still_booting")return f.warn("SYSTEM","Worker is still booting; bounded startup budget spent, skipping this call",{detail:s.detail,budgetMs:t}),!1;if(!!vs(K()))return Fp(e);let o=Qs(),a=Zb();if(!o||!a)return!1;if(s.outcome==="failed"||s.outcome==="wedged"||s.outcome==="unresponsive"){let u=Jp(Pc());if(!Zp(s,u)||(f.info("SYSTEM","Worker will never become ready \u2014 recycling wedged worker",{outcome:s.outcome,detail:s.detail}),!await xc(e,n)))return!1;eg(s,u)}let c=ni();try{return c&&Zs(o,a,ot({...process.env,MEMINDEX_WORKER_PORT:String(ce())}),process.platform,Math.max(1,r()))===void 0?!1:await Fp(e)}catch(u){return f.debug("SYSTEM","Bounded worker startup failed",{error:u instanceof Error?u.message:String(u)}),!1}finally{c&&cn()}}async function Fp(t){for(;t-Date.now()>0;){let e=await jt(Math.max(1,t-Date.now()));if(e.outcome==="ready")return!0;if(e.outcome!=="not_running")return f.debug("SYSTEM","Bounded worker startup did not reach ready",{outcome:e.outcome,detail:e.detail}),!1;let r=Math.min(100,t-Date.now());r>0&&await new Promise(n=>setTimeout(n,r))}return!1}function Ei(){return F.default.join(W,"state")}function cg(){return F.default.join(Ei(),"hook-failures.json")}function ug(){return F.default.join(Ei(),"hook-failures.lock")}async function Nc(t=og){let e=Ei(),r=ug(),n=(0,Bp.randomUUID)(),s=JSON.stringify({pid:process.pid,token:n}),i=Date.now()+t;for(;Date.now()<=i;)try{return(0,k.mkdirSync)(e,{recursive:!0}),(0,k.writeFileSync)(r,s,{flag:"wx"}),n}catch(o){let a=o instanceof Error?o:new Error(String(o)),c=a.code;if(c!=="EEXIST")return f.warn("SYSTEM","Hook-failure lock unavailable; skipping failure-state update",{lockPath:r,code:c},a),null;let u;try{u=(0,k.statSync)(r).mtimeMs}catch{continue}if(Date.now()-u>ag){let l;try{l=(0,k.statSync)(r).mtimeMs}catch{continue}if(l===u)try{(0,k.unlinkSync)(r);continue}catch{}}await new Promise(l=>setTimeout(l,Ew))}return f.warn("SYSTEM","Timed out waiting for hook-failure lock; skipping failure-state update",{lockPath:r,waitMs:t}),null}function Cc(t){let e=ug();try{if(JSON.parse((0,k.readFileSync)(e,"utf-8")).token!==t)return;(0,k.unlinkSync)(e)}catch{}}function yw(t){let e=JSON.parse(t);return{consecutiveFailures:typeof e.consecutiveFailures=="number"&&Number.isFinite(e.consecutiveFailures)?Math.max(0,Math.floor(e.consecutiveFailures)):0,lastFailureAt:typeof e.lastFailureAt=="number"&&Number.isFinite(e.lastFailureAt)?e.lastFailureAt:0,thresholdTripped:e.thresholdTripped===!0,notifiedSessionIds:Array.isArray(e.notifiedSessionIds)?e.notifiedSessionIds.filter(r=>typeof r=="string").slice(-ig):void 0}}function ln(){try{return yw((0,k.readFileSync)(cg(),"utf-8"))}catch{return{consecutiveFailures:0,lastFailureAt:0,thresholdTripped:!1}}}function Dc(t){let e=Ei(),r=cg(),n=`${r}.tmp`;try{return(0,k.existsSync)(e)||(0,k.mkdirSync)(e,{recursive:!0}),(0,k.writeFileSync)(n,JSON.stringify(t),"utf-8"),(0,k.renameSync)(n,r),!0}catch(s){return f.debug("SYSTEM","Failed to persist hook-failure counter",{error:s instanceof Error?s.message:String(s)}),!1}}function bw(){try{let e=K().MEMINDEX_HOOK_FAIL_LOUD_THRESHOLD,r=parseInt(e,10);if(Number.isFinite(r)&&r>=1)return r}catch{}return _w}function lg(t){let e=Tc!==null?`The worker cannot bind port ${Tc} on ${Mc()}: the system refuses it (EACCES or EADDRNOTAVAIL). ${uc}.`:Xt!==null?`Port ${Xt} is held by an unreachable process that no PID file claims, so the worker cannot bind it. ${_i}.`:"Run `npx memindex restart`; if it keeps failing, run `npx memindex doctor`.";return`memindex worker unreachable for ${t} consecutive hooks \u2014 memory features are degraded, but your prompts are not blocked. ${e}`}async function wc(){if(ww){if(Up)return ln().consecutiveFailures;Up=!0}let t=await Nc();if(t===null)return ln().consecutiveFailures;let e,r=!1;try{let n=ln();e={consecutiveFailures:n.consecutiveFailures+1,lastFailureAt:Date.now(),thresholdTripped:n.thresholdTripped,notifiedSessionIds:n.notifiedSessionIds};let s=bw();r=e.consecutiveFailures>=s&&!e.thresholdTripped,r&&(e.thresholdTripped=!0);let i=Dc(e);r=r&&i}finally{Cc(t)}return r&&(await wf("hook_failed",{...Lp!==null?{hook_type:Lp}:{},error_mode:"worker_unavailable",consecutive_failures:e.consecutiveFailures,threshold_tripped:!0}),tt(`${lg(e.consecutiveFailures)}
|
|
23
|
-
`)),e.consecutiveFailures}async function dg(t){if(!t)return null;let e=await Nc();if(e===null)return null;try{let r=ln(),n=r.notifiedSessionIds??[];return!r.thresholdTripped||n.includes(t)?null:Dc({...r,notifiedSessionIds:[...n,t].slice(-ig)})?lg(r.consecutiveFailures):null}finally{Cc(e)}}async function $p(){let t=await Nc(Sw);if(t!==null)try{let e=ln();if(e.consecutiveFailures===0&&!e.thresholdTripped)return;Dc({consecutiveFailures:0,lastFailureAt:0,thresholdTripped:!1})}finally{Cc(t)}}function fg(t){return typeof t=="object"&&t!==null&&t[Ht]===!0}async function pg(t,e,r,n={}){let s=Date.now(),i=n.workerStartupTimeoutMs!==void 0;if(!(i?await hw(n.workerStartupTimeoutMs):await mw(n.timeoutMs)))return vs(K())?{continue:!0,reason:"worker_autostart_disabled",[Ht]:!0}:(i||await wc(),{continue:!0,reason:"worker_unreachable",[Ht]:!0});let a={method:e};if(r!==void 0&&(a.headers={"Content-Type":"application/json"},a.body=JSON.stringify(r)),n.timeoutMs!==void 0){let l=i?n.timeoutMs:n.timeoutMs-(Date.now()-s);if(l<vc)return f.debug("SYSTEM","Hook budget spent before the worker request; skipping it",{url:t}),i||await wc(),{continue:!0,reason:"worker_budget_exhausted",[Ht]:!0};a.timeoutMs=l}let c;try{c=await fe(t,a)}catch(l){if(!i)throw l;return f.debug("SYSTEM","Worker unavailable for best-effort hook call",{error:l instanceof Error?l.message:String(l)}),{continue:!0,reason:"worker_unreachable",[Ht]:!0}}if(!c.ok){let l=await c.text().catch(()=>"");if(await $p(),c.status===429||c.status>=500)return f.warn("SYSTEM",`Worker API ${e} ${t} returned ${c.status}; skipping hook API call`,{body:l.substring(0,200)}),{continue:!0,reason:`worker_api_${c.status}`,[Ht]:!0};let d=l;try{d=JSON.parse(l)}catch{}return d}let u;try{u=await c.text()}catch(l){return f.debug("SYSTEM","Worker response body could not be read; treating the worker as unreachable",{error:l instanceof Error?l.message:String(l)}),i||await wc(),{continue:!0,reason:"worker_body_read_failed",[Ht]:!0}}if(await $p(),u.length!==0)try{return JSON.parse(u)}catch{return u}}var F,Bp,k,bt,_r,un,Lb,Ub,$b,vc,Sc,yc,li,di,fi,Yp,_i,Xt,Tc,pi,_w,ig,og,Ew,ag,Sw,Lp,ww,Up,Ht,wt=E(()=>{"use strict";Ra();F=Ee(require("path"),1),Bp=require("crypto"),k=require("fs");A();He();Bd();st();N();it();Wd();Hd();Oa();rn();ct();hs();Tf();rp();ti();lc();cc();op();gp();tn();lr();ie();Ep();Mp();Oa();bt=Ic("MEMINDEX_HEALTH_TIMEOUT_MS",We(re.HEALTH_CHECK),{min:500,max:3e5}),_r=Ic("MEMINDEX_HOOK_READINESS_TIMEOUT_MS",We(re.HOOK_READINESS_WAIT),{min:0,max:3e5}),un=Ic("MEMINDEX_WORKER_STANDBY_WAIT_MS",yp,{min:500,max:3e5}),Lb=5e3,Ub={min:500,max:3e5},$b={min:500,max:re.SESSION_INIT_REQUEST_MAX},vc=100;Sc=null,yc=null,li=null,di=null,fi=null;Yp=3e4;_i="Set MEMINDEX_WORKER_PORT to a different port in memindex settings, or reboot to release the stuck port",Xt=null,Tc=null;pi=null;_w=3,ig=20,og=1e3,Ew=10,ag=5e3,Sw=ag+og;Lp=null;ww=!1,Up=!1;Ht=Symbol.for("memindex/worker-fallback")});function Fc(t,e){let r=(0,Ke.normalize)(t),n=(0,Ke.normalize)(e);if(r===n)return!0;let s=(0,Ke.relative)(n,r);return s.length>0&&!s.startsWith("..")&&!(0,Ke.isAbsolute)(s)}function Ge(t){if(process.env.MEMINDEX_INTERNAL==="1")return!1;if(!t)return!0;if(Fc(t,Ss)||Fc(t,Mw)||Fc(t,Pw))return!1;let e=K();return!Gs(t,e.MEMINDEX_EXCLUDED_PROJECTS)}var Ke,Tw,Iw,vw,Rw,Aw,Mw,Pw,Sr=E(()=>{"use strict";Ke=require("path");on();it();N();Tw="plugins",Iw="cache",vw="memindex",Rw="memindex",Aw="plugin",Mw=(0,Ke.join)(nt,Tw,Iw,vw,Rw),Pw=(0,Ke.join)(cr,Aw)});function Ow(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function G(t){if(!t)return gg;let e=Ow(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e.includes("kimi")?"kimi":e==="pi-mono"?"pi":e==="agy"||e==="antigravity"||e.startsWith("antigravity-")?"antigravity-cli":e:gg}var gg,ut=E(()=>{"use strict";gg="claude"});var mg=E(()=>{"use strict"});function Uc(t){return new RegExp(`${t}${kw}`,"gi")}function $c(t,e){if(!e.enabled||t.length===0)return{redacted:t,counts:{},oversize:!1};if(t.length>Nw)return f.warn("REDACT","field exceeds the 1M-char redaction cap; replaced by an oversize marker",void 0,{inputLength:t.length}),{redacted:Cw,counts:{oversize:1},oversize:!0};let r=new Set(e.disabledBuiltinPatterns??[]),n={},s=t,i=[];for(let a of e.customPatterns??[]){if(!a.name||a.name.length===0){f.warn("REDACT","custom pattern skipped: missing name",void 0,{pattern:a});continue}try{i.push({name:a.name,regex:new RegExp(a.regex,"g")})}catch(c){f.warn("REDACT","custom pattern skipped: invalid regex",{name:a.name},c instanceof Error?c:new Error(String(c)))}}let o=[...i,...xw];for(let a of o)r.has(a.name)||(a.regex.lastIndex=0,s=s.replace(a.regex,()=>(n[a.name]=(n[a.name]??0)+1,`<redacted type='${a.name}'/>`)));return e.logMatches&&Object.keys(n).length>0&&f.debug("REDACT","patterns matched",void 0,{counts:n}),{redacted:s,counts:n,oversize:!1}}function Dw(t){if(!t||t.trim()==="")return[];try{let e=JSON.parse(t);return Array.isArray(e)?e.filter(r=>r&&typeof r.name=="string"&&typeof r.regex=="string"):(f.warn("REDACT","MEMINDEX_REDACT_CUSTOM_PATTERNS is not a JSON array, ignoring"),[])}catch(e){return f.warn("REDACT","failed to parse MEMINDEX_REDACT_CUSTOM_PATTERNS as JSON",void 0,e instanceof Error?e:new Error(String(e))),[]}}function Fw(t){return{enabled:t.MEMINDEX_REDACT_ENABLED==="true",disabledBuiltinPatterns:(t.MEMINDEX_REDACT_DISABLED_BUILTINS??"").split(",").map(e=>e.trim()).filter(Boolean),customPatterns:Dw(t.MEMINDEX_REDACT_CUSTOM_PATTERNS??"[]"),logMatches:t.MEMINDEX_REDACT_LOG_MATCHES==="true"}}function Bw(t){if(!(0,Si.existsSync)(t))return null;try{return(0,Si.readFileSync)(t,"utf-8")}catch{return""}}function Ww(t){if(t===null)return!1;try{let e=JSON.parse(ma(t));return e===null||typeof e!="object"||Array.isArray(e)}catch{return!0}}function Hw(t,e,r){return process.env.MEMINDEX_REDACT_ENABLED==="false"||!(pn?.enabled===!0||$w.test(e))?r:(_g||(_g=!0,f.warn("REDACT","settings.json could not be read; secret redaction stays on until it is repaired",{settingsPath:t,using:pn?.enabled?"the last configuration that loaded":"the built-in patterns"})),pn?.enabled?pn:Uw)}function Bc(t=ge){let e=Date.now();if(fn&&e-hg<Lw)return fn;let r=z.loadFromFile(t),n=Fw(r),s=n.enabled?null:Bw(t);return Ww(s)?fn=Hw(t,s,n):(fn=n,pn=n),hg=e,fn}function Eg(t){return $c(t,Bc()).redacted}var Si,Lc,kw,xw,Nw,Cw,fn,hg,Lw,pn,_g,Uw,$w,Wc=E(()=>{"use strict";Si=require("fs");A();st();N();ie();Lc=String.raw`[A-Za-z0-9_.\-+/=~@#$%^*!?]`,kw=`(?=${Lc}{8})${Lc}*[A-Za-z]${Lc}*`;xw=[{name:"aws_access_key",regex:/AKIA[0-9A-Z]{16}/g},{name:"aws_secret_key",regex:/(?<=AWS_SECRET_ACCESS_KEY\s*[=:]\s*['"]?)[A-Za-z0-9/+=]{40}/g},{name:"github_pat",regex:/\bgh[oprs]_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{82}\b/g},{name:"openai_key",regex:/\bsk-(?!ant-)[A-Za-z0-9_-]{20,}\b/g},{name:"anthropic_key",regex:/\bsk-ant-[A-Za-z0-9_-]{20,}\b/g},{name:"slack_token",regex:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g},{name:"jwt",regex:/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g},{name:"private_key_pem",regex:/-----BEGIN (?:RSA |DSA |EC |OPENSSH |PGP )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |DSA |EC |OPENSSH |PGP )?PRIVATE KEY-----/g},{name:"stripe_key",regex:/\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]{24,}\b/g},{name:"google_api_key",regex:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:"memindex_key",regex:new RegExp("\\bmi_[A-Za-z0-9_-]{32,}","g")},{name:"generic_password",regex:Uc(String.raw`(?<=\b\w*_?(?:password|passwd|pwd)\\{0,2}["']?\s*[=:]\s*\\{0,2}["']?)`)},{name:"generic_token",regex:Uc(String.raw`(?<=\b\w*_(?:token|secret|api_key)\\{0,2}["']?\s*[=:]\s*\\{0,2}["']?)`)},{name:"bearer_token",regex:Uc(String.raw`(?<=\bAuthorization\s*:\s*Bearer\s*)`)}],Nw=1024*1024,Cw="<redacted type='oversize'/>";fn=null,hg=0,Lw=5e3,pn=null,_g=!1,Uw={enabled:!0,disabledBuiltinPatterns:[],customPatterns:[],logMatches:!1},$w=/"(?:MEMINDEX|AGENT_MEM)_REDACT_ENABLED"\s*:\s*"true"/});function Xw(t){let e=Object.fromEntries(Hc.map(l=>[l,0])),r=t.length,n=new Int32Array(r+1);n[r]=r;for(let l=r-1;l>=0;l--)n[l]=t.charCodeAt(l)===62?l:n[l+1];let s=new Map,i=[],o=0,a=0;for(;a<r;){if(t.charCodeAt(a)!==60){a+=1;continue}yg.lastIndex=a;let l=yg.exec(t);if(l){let p=l[1],g=s.get(p),m=g&&g.head<g.items.length?g.items[g.head]:void 0;m&&a>=m.attrEnd&&(g.head+=1,i.push([m.start,a+l[0].length]),e[p]+=1,o+=1),a+=l[0].length;continue}Sg.lastIndex=a;let d=Sg.exec(t);if(d&&jw.has(d[1])){let p=d[1],g=a+d[0].length,m={start:a,attrEnd:n[g]},h=s.get(p);h?h.items.push(m):s.set(p,{items:[m],head:0}),a=g;continue}a+=1}i.sort((l,d)=>l[0]-d[0]);let c="",u=0;for(let[l,d]of i)l>u&&(c+=t.slice(u,l)),d>u&&(u=d);return c+=t.slice(u),{text:c,counts:e,total:o}}function Kw(t){let{text:e,counts:r,total:n}=Xw(t);return n>bg&&f.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:n,maxAllowed:bg,contentLength:t.length}),{stripped:$c(e.trim(),Bc()).redacted,counts:r}}function we(t){return Kw(t).stripped}function jc(t){let e=r=>typeof r=="string"?Gw.test(r)?we(r):r:Array.isArray(r)?r.map(e):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).map(([n,s])=>[n,e(s)])):r;return e(t)}function bi(t){return!t||t.length>Yw?!1:Vw.test(t)}function wg(t){let e=t.trimStart();return qw.some(r=>r.test(e))}var Hc,jw,Sg,yg,yi,bg,Gw,zw,Vw,Yw,qw,lt=E(()=>{"use strict";A();Wc();Hc=["private","memindex-context","agent-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],jw=new Set(Hc),Sg=/<([A-Za-z_][A-Za-z0-9_-]*)/y,yg=/<\/([A-Za-z_][A-Za-z0-9_-]*)\s*>/y;yi=/<system-reminder>[\s\S]*?<\/system-reminder>/g,bg=100;Gw=new RegExp(`<(${Hc.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`);zw=["task-notification"],Vw=new RegExp(`^\\s*<(${zw.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),Yw=256*1024;qw=[/^You are a helpful assistant\. You will be presented with a user prompt, and your job is to provide a short title/,/^## Memory Writing Agent: Phase 2 \(Consolidation\)/,/^# Overview\r?\n(?:\r?\n)?Generate 0 to 3 hyperpersonalized suggestions/]});function Tt(t){return t instanceof dt}function Qw(t){return t.replace(/\/+$/,"")}function wi(t){return typeof t=="string"?G(t):null}function Zw(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}var Jw,dt,Ti,yr=E(()=>{"use strict";wt();He();ut();lt();Jw=We(re.API_REQUEST),dt=class extends Error{kind;status;cause;constructor(e,r,n={}){super(r),this.name="ServerClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},Ti=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=Qw(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??Jw}async startSession(e,r={}){let n=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",n,r)}async recordEvent(e){let r=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(e){if(!e.sessionId)throw new dt("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e,r={}){let n={projectId:e.projectId};return e.query!==void 0&&(n.query=e.query),e.limit!==void 0&&(n.limit=e.limit),e.summaryLimit!==void 0&&(n.summaryLimit=e.summaryLimit),e.platformSource!==void 0&&(n.platformSource=wi(e.platformSource)),e.folderProjects&&e.folderProjects.length>0&&(n.folderProjects=e.folderProjects),e.excludeSubagents!==void 0&&(n.excludeSubagents=e.excludeSubagents),this.request("POST","/v1/context",n,r)}async getJobStatus(e){if(!e)throw new dt("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,n=e.kind??"manual",s=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,content:r,...s?{title:s}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.platformSource!==void 0?{platformSource:e.platformSource}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:wi(e.platformSource)}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:wi(e.platformSource)}:{},...e.metadata!==void 0?{metadata:jc(e.metadata)}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:wi(e.platformSource)}:{},...e.payload!==void 0?{payload:jc(e.payload)}:{}}}async request(e,r,n,s={}){if(!this.apiKey||!this.apiKey.trim())throw new dt("missing_api_key","Server API key is not configured (MEMINDEX_SERVER_API_KEY).");let i=`${this.baseUrl}${r}`,o={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(o.body=JSON.stringify(n));let a=d=>{let p=d instanceof Error?d.message:String(d),g=/timed out|timeout/i.test(p)||d instanceof Error&&(d.name==="TimeoutError"||d.name==="AbortError");return new dt(g?"timeout":"transport",`Server ${e} ${r} failed: ${p}`,{cause:d})},c,u=s.timeoutMs??this.timeoutMs;try{c=await dn(i,o,u)}catch(d){throw a(d)}if(!c.ok){let d=await c.text().catch(()=>"");throw new dt("http_error",`Server ${e} ${r} returned ${c.status}: ${Zw(d,200)}`,{status:c.status})}let l;try{l=await c.text()}catch(d){throw a(d)}if(!l||l.length===0)return{};try{return JSON.parse(l)}catch(d){let p=d instanceof Error?d:new Error(String(d));throw new dt("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:p})}}}});function eT(){let e=(K().MEMINDEX_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function tT(){let t=K(),e=(...r)=>{for(let n of r){let s=(n??"").trim();if(s.length>0)return s}return""};return{serverBaseUrl:e(t.MEMINDEX_SERVER_URL,t.MEMINDEX_SERVER_BETA_URL),apiKey:e(t.MEMINDEX_SERVER_API_KEY,t.MEMINDEX_SERVER_BETA_API_KEY),projectId:e(t.MEMINDEX_SERVER_PROJECT_ID,t.MEMINDEX_SERVER_BETA_PROJECT_ID)}}function rT(){let{serverBaseUrl:t,apiKey:e,projectId:r}=tT();if(!t)return f.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!e)return f.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!r)return f.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let n={serverBaseUrl:t,apiKey:e};return{runtime:"server",client:new Ti(n),projectId:r,serverBaseUrl:t}}function xe(){if(eT()!=="server")return{runtime:"worker"};let t=rT();return t||{runtime:"worker"}}function It(t,e){f.warn("HOOK",`[server-fallback] reason=${t}`,e??{})}var br=E(()=>{"use strict";it();A();yr()});function vi(t){return fT.run(t,!0)}async function pT(t,e,r,n,s,i,o){await t.client.startSession({projectId:t.projectId,externalSessionId:r,contentSessionId:r,agentId:e.agentId??null,agentType:e.agentType??null,platformSource:n,metadata:{project:s,prompt:i}},{timeoutMs:o}),f.info("HOOK","session-init: server session started",{contentSessionId:r,project:s})}function gT(t){let e=t.replace(aT," ").toLowerCase().match(/[\p{L}\p{N}_]{4,}/gu)??[],r=[...new Set(e)].slice(0,oT);return r.length>0?r.join(" or "):null}async function mT(t,e,r,n,s,i,o){if(e.length<20||e==="[media prompt]")return"";let a=gT(e);if(!a)return"";let c=Xc(i,o);if(c<Ii)return f.warn("HOOK","session-init: skipping server semantic injection because the prompt budget is spent",{remainingMs:c}),"";try{let u=await t.client.contextObservations({projectId:t.projectId,query:a,limit:Math.min(200,hT(s.MEMINDEX_SEMANTIC_INJECT_LIMIT||"5")),platformSource:n,...r.length>0?{folderProjects:r.slice(0,20)}:{}},{timeoutMs:c}),l=Array.isArray(u?.observations)?u.observations.length:0;return f.debug("HOOK",`Server semantic injection: ${l} observations for prompt`,{count:l}),typeof u?.context=="string"?u.context.slice(0,cT):""}catch(u){return f.warn("HOOK","session-init: server semantic context unavailable",{error:u instanceof Error?u.message:String(u)}),""}}function hT(t){let e=typeof t=="number"?t:Number.parseInt(t,10);return!Number.isFinite(e)||e<=0?5:e}function Xc(t,e){return Math.max(0,e-(Date.now()-t))}function Tg(t,e){return t==="codex"?{workerStartupTimeoutMs:re.POST_SPAWN_WAIT,timeoutMs:Math.min(uT,e)}:{timeoutMs:e}}var sT,Ne,iT,oT,aT,cT,Ii,uT,wr,lT,dT,fT,Kc=E(()=>{"use strict";wt();Bt();A();He();Sr();it();ut();mg();lt();br();yr();sT={executeWithWorkerFallback:pg,getSessionInitRequestTimeoutMs:Xp,isWorkerFallback:fg,consumeWorkerOutageNotice:dg,loadFromFileOnce:K,resolveRuntimeContext:xe,logServerFallback:It,shouldTrackProject:Ge,readHookEnvironment:()=>process.env},Ne=sT,iT=2,oT=12,aT=/<private\b[^>]*>[\s\S]*?<\/private\s*>/gi,cT=1e4,Ii=500,uT=2e3,wr=class extends Error{constructor(r){super(`session-init did not record the prompt (${r})`);this.reason=r;this.name="SessionPromptNotRecordedError"}reason};lT=t=>t?t.replace(/\\/g,"/").includes("/.qwen/"):!1,dT=(t,e=process.env)=>t?e.QWEN_PROJECT_DIR?!0:lT(t):!1,fT={async run(t,e){let{sessionId:r,prompt:n,submittedPrompt:s}=t,i=t.cwd??process.cwd();if(!r)return f.warn("HOOK","session-init: No sessionId provided, skipping (Codex CLI or unknown platform)"),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};if(!Ne.shouldTrackProject(i))return f.info("HOOK","Project excluded from tracking",{cwd:i}),{continue:!0,suppressOutput:!0};if(n&&bi(n))return f.debug("HOOK","session-init: skipping internal protocol payload",{preview:n.slice(0,80)}),{continue:!0,suppressOutput:!0};if(n&&G(t.platform)==="codex"&&wg(n))return f.debug("HOOK","session-init: skipping a Codex internal helper prompt",{reason:"internal_system_prompt",preview:n.slice(0,80)}),{continue:!0,suppressOutput:!0};if(s===null)return f.debug("HOOK","session-init: host reported no user-submitted text; not storing a prompt",{sessionId:r}),{continue:!0,suppressOutput:!0};if(s===void 0&&!n?.trim()&&dT(t.transcriptPath,Ne.readHookEnvironment()))return f.debug("HOOK","session-init: Qwen send carried no submitted_prompt and no prompt text; not storing a prompt",{sessionId:r}),{continue:!0,suppressOutput:!0};let o=s??n,a=!o||!o.trim()?"[media prompt]":o,c=qs(i),u=c.primary,l=G(t.platform),d=Ne.loadFromFileOnce(),p=String(d.MEMINDEX_SEMANTIC_INJECT).toLowerCase()==="true",g=Ne.resolveRuntimeContext(),m=Date.now(),h=Ne.getSessionInitRequestTimeoutMs();if(g.runtime==="server")try{await pT(g,t,r,l,u,a,Math.max(Ii,Math.floor(h/iT)));let y=p?await mT(g,a,c.allProjects,l,d,m,h):"";return y?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:y}}:{continue:!0,suppressOutput:!0}}catch(y){if(Tt(y)&&y.isFallbackEligible())Ne.logServerFallback(y.kind,{status:y.status,message:y.message,route:"/v1/sessions/start"});else return f.error("HOOK","Server session-start failed (non-recoverable)",{error:y instanceof Error?y.message:String(y)}),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS}}f.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:r,project:u});let _=Xc(m,h);if(_<Ii){if(f.warn("HOOK","session-init: skipping the worker call because the prompt budget is spent",{contentSessionId:r,project:u,remainingMs:_}),e)throw new wr("budget_exhausted");return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS}}let S=await Ne.executeWithWorkerFallback("/api/sessions/init","POST",{contentSessionId:r,project:u,prompt:a,platformSource:l,cwd:i,projectKeySource:c.keySource},Tg(l,_));if(Ne.isWorkerFallback(S)){if(e)throw new wr("reason"in S?S.reason:"worker_fallback");let y=await Ne.consumeWorkerOutageNotice(r);return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS,...y?{systemMessage:y}:{}}}if(typeof S?.sessionDbId!="number")return f.failure("HOOK","Session initialization returned malformed response",{contentSessionId:r,project:u}),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};let b=S.sessionDbId,w=S.promptNumber;if(f.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:b,promptNumber:w,skipped:S.skipped,contextInjected:S.contextInjected}),f.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${r} | prompt#=${w} | sessionDbId=${b}`),S.skipped&&S.reason==="private")return f.info("HOOK",`INIT_COMPLETE | sessionDbId=${b} | promptNumber=${w} | skipped=true | reason=private`,{sessionId:b}),{continue:!0,suppressOutput:!0};let T="";if(p&&a&&a.length>=20&&a!=="[media prompt]"){let y=d.MEMINDEX_SEMANTIC_INJECT_LIMIT||"5",P=Xc(m,h);if(P<Ii)f.warn("HOOK","session-init: skipping semantic injection because the prompt budget is spent",{contentSessionId:r,project:u,remainingMs:P});else{let v=await Ne.executeWithWorkerFallback("/api/context/semantic","POST",{q:a,project:u,projects:c.allProjects,limit:y,format:d.MEMINDEX_SEMANTIC_INJECT_FORMAT,platformSource:l},Tg(l,P));!Ne.isWorkerFallback(v)&&v?.context&&(f.debug("HOOK",`Semantic injection: ${v.count} observations for prompt`,{sessionId:b,count:v.count}),T=v.context)}}return f.info("HOOK",`INIT_COMPLETE | sessionDbId=${b} | promptNumber=${w} | project=${u}`,{sessionId:b}),T?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:T}}:{continue:!0,suppressOutput:!0}}}});var Ig=E(()=>{"use strict";ar();N()});function Pi(){return(0,Ce.join)(U(),"state","hook-spool")}function Ai(t){if(t===null||typeof t!="object")return JSON.stringify(t)??"null";if(Array.isArray(t))return`[${t.map(Ai).join(",")}]`;let e=t;return`{${Object.keys(e).filter(n=>e[n]!==void 0).sort().map(n=>`${JSON.stringify(n)}:${Ai(e[n])}`).join(",")}}`}function wT(t,e){if(t==="summarize"&&e.turnId){let n=e;return(0,Ri.createHash)("sha256").update(Ai({contentSessionId:n.contentSessionId,platformSource:G(n.platformSource),turnId:n.turnId,lastAssistantMessage:n.lastAssistantMessage})).digest("hex")}let r=e.toolUseId;return typeof r=="string"&&Ag.test(r)?`${(0,Ri.createHash)("sha256").update(e.contentSessionId).update("\0").update(G(e.platformSource)).digest("hex")}-${r}`:(0,Ri.createHash)("sha256").update(t).update("\0").update(e.contentSessionId).update("\0").update(Ai(e)).digest("hex")}function Rg(t){return typeof t=="string"&&t.length>0}function Gc(t){let e;try{e=JSON.parse(t)}catch(i){return{corruptReason:`invalid JSON: ${i instanceof Error?i.message:String(i)}`}}if(e===null||typeof e!="object")return{corruptReason:"not an object"};let r=e;if(!_T.includes(r.kind))return{corruptReason:`unknown kind ${JSON.stringify(r.kind)}`};if(typeof r.enqueuedAtEpochMs!="number"||!Number.isFinite(r.enqueuedAtEpochMs))return{corruptReason:"missing enqueuedAtEpochMs"};let n=r.payload;if(n===null||typeof n!="object"||!Rg(n.contentSessionId))return{corruptReason:"payload missing contentSessionId"};let s=r.kind;return(s==="observation"||s==="file_edit")&&!Rg(n.toolName)?{corruptReason:"observation payload missing toolName"}:s==="summarize"&&typeof n.lastAssistantMessage!="string"?{corruptReason:"summarize payload missing lastAssistantMessage"}:s==="advisor_calls"&&(!Array.isArray(n.calls)||n.calls.length===0)?{corruptReason:"advisor_calls payload has no calls"}:{kind:s,payload:{...n,platformSource:G(n.platformSource)},enqueuedAtEpochMs:r.enqueuedAtEpochMs}}function TT(){return zc=Math.max(Date.now(),zc+1),zc}var Ri,Z,Ce,_T,ET,Ag,ST,yT,vg,bT,zc,Mi,Vc=E(()=>{"use strict";Ri=require("crypto"),Z=require("fs"),Ce=require("path");ie();N();ut();A();Ig();_T=["observation","file_edit","summarize","session_end","advisor_calls"],ET=/^[a-z_]+-[A-Za-z0-9_-]+\.json$/,Ag=/^[A-Za-z0-9_-]{1,128}$/,ST="corrupt",yT="expired",vg=10080*60*1e3,bT=300*1e3;zc=0;Mi=class{constructor(e=Pi()){this.directory=e}directory;get corruptDirectory(){return(0,Ce.join)(this.directory,ST)}get expiredDirectory(){return(0,Ce.join)(this.directory,yT)}enqueue(e,r,n){let s={...r,platformSource:G(r.platformSource)},i=(0,Ce.join)(this.directory,`${e}-${wT(e,s)}.json`),o=s.toolUseId;if(typeof o=="string"&&Ag.test(o)){let c=(0,Ce.join)(this.directory,`${e}-${o}.json`);try{let u=Gc((0,Z.readFileSync)(c,"utf8"));!("corruptReason"in u)&&u.kind===e&&u.payload.contentSessionId===s.contentSessionId&&u.payload.platformSource===s.platformSource&&(i=c)}catch{}}let a=this.existingEnqueuedAt(i)??n??TT();return X(i,{kind:e,payload:s,enqueuedAtEpochMs:a}),i}entries(){return this.readEntries().files.map(e=>e.entry)}async drain(e,r){let{files:n,quarantined:s}=this.readEntries(),i=0,o=0,a=0;r?.pruneConsumedBefore(Date.now()-vg);let c=new Set;for(let u of n){let l=u.filename.replace(/\.json$/,""),d=u.entry.kind==="summarize"&&!!u.entry.payload.turnId;if(r?.isConsumed(l)){f.info("HOOK","Hook spool entry was already handed to ingest before a restart; removing it without ingesting again",{kind:u.entry.kind,contentSessionId:u.entry.payload.contentSessionId,file:u.filename}),this.unlinkEntry(u)?(d||r.clearConsumed(l),i++):o++;continue}let p=JSON.stringify([u.entry.payload.contentSessionId,u.entry.payload.platformSource]);if((u.entry.kind==="summarize"||u.entry.kind==="session_end")&&c.has(p)){o++;continue}let g=!1,m=()=>{if(!g){g=!0;try{r?.markConsumed(l,Date.now())}catch(_){f.error("HOOK","Could not record a hook spool hand-off marker; a crash before the file is removed would ingest it twice",{kind:u.entry.kind,contentSessionId:u.entry.payload.contentSessionId,file:u.filename},_ instanceof Error?_:new Error(String(_)))}}},h;try{h=await e(u.entry,m)}catch(_){f.warn("HOOK",g?"Hook spool entry failed after ingest accepted it; removing it (a retry would send it twice)":"Hook spool entry failed to ingest; keeping it for the next drain",{kind:u.entry.kind,contentSessionId:u.entry.payload.contentSessionId,file:u.filename},_ instanceof Error?_:new Error(String(_))),h=!1}if(g&&(h=!0),h==="expired"){this.expireIfPastWindow(u,bT,"unknown-session grace window")?a++:o++;continue}if(!h){this.expireIfPastWindow(u,vg,"retry window")?a++:((u.entry.kind==="observation"||u.entry.kind==="file_edit")&&c.add(p),o++);continue}this.unlinkEntry(u)?(d||r?.clearConsumed(l),i++):o++}return{drained:i,retained:o,quarantined:s,expired:a}}unlinkEntry(e){try{return(0,Z.unlinkSync)(e.path),!0}catch(r){return r.code==="ENOENT"?!0:(f.warn("HOOK","Hook spool entry was ingested but could not be removed",{kind:e.entry.kind,file:e.filename},r instanceof Error?r:new Error(String(r))),!1)}}expireIfPastWindow(e,r,n){let s=Date.now()-e.entry.enqueuedAtEpochMs;if(s<=r)return!1;let i={kind:e.entry.kind,contentSessionId:e.entry.payload.contentSessionId,ageMinutes:Math.round(s/6e4),ageHours:Math.round(s/36e5),file:e.filename,expiredDirectory:this.expiredDirectory};try{(0,Z.mkdirSync)(this.expiredDirectory,{recursive:!0}),(0,Z.renameSync)(e.path,(0,Ce.join)(this.expiredDirectory,e.filename))}catch(o){return f.error("HOOK",`Hook spool entry is past its ${n} but could not be moved to expired/; keeping it`,i,o instanceof Error?o:new Error(String(o))),!1}return f.error("HOOK",`Hook spool entry was never accepted within its ${n}; moved to expired/`,i),!0}existingEnqueuedAt(e){if(!(0,Z.existsSync)(e))return null;try{let r=Gc((0,Z.readFileSync)(e,"utf-8"));return"corruptReason"in r?null:r.enqueuedAtEpochMs}catch(r){return f.debug("HOOK","Could not read existing hook spool entry; writing a fresh one",{entryPath:e},r instanceof Error?r:new Error(String(r))),null}}quarantine(e,r){let n=(0,Ce.join)(this.directory,e);try{return(0,Z.mkdirSync)(this.corruptDirectory,{recursive:!0}),(0,Z.renameSync)(n,(0,Ce.join)(this.corruptDirectory,e)),f.error("HOOK","Quarantined corrupt hook spool entry",{file:e,reason:r,corruptDirectory:this.corruptDirectory}),!0}catch(s){return f.error("HOOK","Corrupt hook spool entry could not be quarantined; leaving it in place",{file:e,reason:r},s instanceof Error?s:new Error(String(s))),!1}}readEntries(){if(!(0,Z.existsSync)(this.directory))return{files:[],quarantined:0};let e;try{e=(0,Z.readdirSync)(this.directory).filter(s=>ET.test(s))}catch(s){return f.warn("HOOK","Could not list hook spool entries",{directory:this.directory},s instanceof Error?s:new Error(String(s))),{files:[],quarantined:0}}let r=[],n=0;for(let s of e){let i=(0,Ce.join)(this.directory,s),o;try{o=(0,Z.readFileSync)(i,"utf-8")}catch(c){c.code!=="ENOENT"&&f.warn("HOOK","Could not read hook spool entry; will retry",{file:s},c instanceof Error?c:new Error(String(c)));continue}let a=Gc(o);if("corruptReason"in a){this.quarantine(s,a.corruptReason)&&n++;continue}r.push({entry:a,path:i,filename:s})}return r.sort((s,i)=>s.entry.enqueuedAtEpochMs-i.entry.enqueuedAtEpochMs||s.filename.localeCompare(i.filename)),{files:r,quarantined:n}}}});var Og={};fs(Og,{SPOOL_NUDGE_TIMEOUT_MS:()=>Mg,nudgeWorkerToDrainHookSpool:()=>Pg,settleHookSpoolNudges:()=>IT,spoolHookEvent:()=>De});function Pg(){if(gn)return gn;let t=(async()=>{try{await(await fe("/api/spool/nudge",{method:"POST",timeoutMs:Mg})).body?.cancel()}catch(e){f.debug("HOOK","Hook spool nudge not delivered (worker will pick the entry up on its own)",{error:e instanceof Error?e.message:String(e)})}})();return gn=t,Yc.add(t),t.finally(()=>{Yc.delete(t),gn===t&&(gn=null)}),t}async function IT(){await Promise.all([...Yc])}function De(t,e,r){let n=new Mi().enqueue(t,e,r);return f.debug("HOOK","Hook event spooled for the worker",{kind:t,entryPath:n}),Pg(),n}var Mg,Yc,gn,Tr=E(()=>{"use strict";Vc();wt();A();Mg=250,Yc=new Set,gn=null});function vt(t,e){return e?new Set(e.split(",").map(n=>n.trim().toLowerCase()).filter(Boolean)).has(t.toLowerCase()):!1}var mn=E(()=>{"use strict"});function Ug(t,e){return!!t&&!!e}var $g=E(()=>{"use strict"});function OT(t){return new Set((t??"").split(",").map(e=>e.trim()).filter(Boolean))}function vr(t,e,r){return Ug(t,e)?r.MEMINDEX_SKIP_SUBAGENT_OBSERVATIONS==="true"?{skip:!0,reason:"subagent_observation"}:e&&OT(r.MEMINDEX_SKIP_AGENT_TYPES).has(e)?{skip:!0,reason:"agent_type_excluded"}:Bg:Bg}var Bg,ki=E(()=>{"use strict";$g();Bg={skip:!1}});var ht,el=E(()=>{ht="1.9.1"});function LR(t){let e=new Set([t]),r=new Set,n=t.match(Wh);if(!n)return()=>!1;let s={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(s.prerelease!=null)return function(c){return c===t};function i(a){return r.add(a),!1}function o(a){return e.add(a),!0}return function(c){if(e.has(c))return!0;if(r.has(c))return!1;let u=c.match(Wh);if(!u)return i(c);let l={major:+u[1],minor:+u[2],patch:+u[3],prerelease:u[4]};return l.prerelease!=null||s.major!==l.major?i(c):s.major===0?s.minor===l.minor&&s.patch<=l.patch?o(c):i(c):s.minor<=l.minor?o(c):i(c)}}var Wh,Hh,jh=E(()=>{el();Wh=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;Hh=LR(ht)});function Je(t,e,r,n=!1){var s;let i=Yn[Vn]=(s=Yn[Vn])!==null&&s!==void 0?s:{version:ht};if(!n&&i[t]){let o=new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${t}`);return r.error(o.stack||o.message),!1}if(i.version!==ht){let o=new Error(`@opentelemetry/api: Registration of version v${i.version} for ${t} does not match previously registered API v${ht}`);return r.error(o.stack||o.message),!1}return i[t]=e,r.debug(`@opentelemetry/api: Registered a global for ${t} v${ht}.`),!0}function _e(t){var e,r;let n=(e=Yn[Vn])===null||e===void 0?void 0:e.version;if(!(!n||!Hh(n)))return(r=Yn[Vn])===null||r===void 0?void 0:r[t]}function Qe(t,e){e.debug(`@opentelemetry/api: Unregistering a global for ${t} v${ht}.`);let r=Yn[Vn];r&&delete r[t]}var UR,Vn,Yn,er=E(()=>{el();jh();UR=ht.split(".")[0],Vn=Symbol.for(`opentelemetry.js.api.${UR}`),Yn=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{}});function qn(t,e,r){let n=_e("diag");if(n)return n[t](e,...r)}var Eo,Xh=E(()=>{er();Eo=class{constructor(e){this._namespace=e.namespace||"DiagComponentLogger"}debug(...e){return qn("debug",this._namespace,e)}error(...e){return qn("error",this._namespace,e)}info(...e){return qn("info",this._namespace,e)}warn(...e){return qn("warn",this._namespace,e)}verbose(...e){return qn("verbose",this._namespace,e)}}});var te,So=E(()=>{(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(te||(te={}))});function Kh(t,e){t<te.NONE?t=te.NONE:t>te.ALL&&(t=te.ALL),e=e||{};function r(n,s){let i=e[n];return typeof i=="function"&&t>=s?i.bind(e):function(){}}return{error:r("error",te.ERROR),warn:r("warn",te.WARN),info:r("info",te.INFO),debug:r("debug",te.DEBUG),verbose:r("verbose",te.VERBOSE)}}var Gh=E(()=>{So()});var $R,Q,tr=E(()=>{Xh();Gh();So();er();$R="diag",Q=class t{static instance(){return this._instance||(this._instance=new t),this._instance}constructor(){function e(s){return function(...i){let o=_e("diag");if(o)return o[s](...i)}}let r=this,n=(s,i={logLevel:te.INFO})=>{var o,a,c;if(s===r){let d=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((o=d.stack)!==null&&o!==void 0?o:d.message),!1}typeof i=="number"&&(i={logLevel:i});let u=_e("diag"),l=Kh((a=i.logLevel)!==null&&a!==void 0?a:te.INFO,s);if(u&&!i.suppressOverrideMessage){let d=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";u.warn(`Current logger will be overwritten from ${d}`),l.warn(`Current logger will overwrite one already registered from ${d}`)}return Je("diag",l,r,!0)};r.setLogger=n,r.disable=()=>{Qe($R,r)},r.createComponentLogger=s=>new Eo(s),r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error")}}});var yo,zh=E(()=>{yo=class t{constructor(e){this._entries=e?new Map(e):new Map}getEntry(e){let r=this._entries.get(e);if(r)return Object.assign({},r)}getAllEntries(){return Array.from(this._entries.entries())}setEntry(e,r){let n=new t(this._entries);return n._entries.set(e,r),n}removeEntry(e){let r=new t(this._entries);return r._entries.delete(e),r}removeEntries(...e){let r=new t(this._entries);for(let n of e)r._entries.delete(n);return r}clear(){return new t}}});var Vh,Yh=E(()=>{Vh=Symbol("BaggageEntryMetadata")});function qh(t={}){return new yo(new Map(Object.entries(t)))}function Jh(t){return typeof t!="string"&&(BR.error(`Cannot create baggage metadata from unknown type: ${typeof t}`),t=""),{__TYPE__:Vh,toString(){return t}}}var BR,tl=E(()=>{tr();zh();Yh();BR=Q.instance()});function $r(t){return Symbol.for(t)}var rl,bo,Jn=E(()=>{rl=class t{constructor(e){let r=this;r._currentContext=e?new Map(e):new Map,r.getValue=n=>r._currentContext.get(n),r.setValue=(n,s)=>{let i=new t(r._currentContext);return i._currentContext.set(n,s),i},r.deleteValue=n=>{let s=new t(r._currentContext);return s._currentContext.delete(n),s}}},bo=new rl});var nl,sl,wo,Qh=E(()=>{nl=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}],sl={};if(typeof console<"u"){let t=["error","warn","info","debug","trace","log"];for(let e of t)typeof console[e]=="function"&&(sl[e]=console[e])}wo=class{constructor(){function e(r){return function(...n){let s=sl[r];if(typeof s!="function"&&(s=sl.log),typeof s!="function"&&console&&(s=console[r],typeof s!="function"&&(s=console.log)),typeof s=="function")return s.apply(console,n)}}for(let r=0;r<nl.length;r++)this[nl[r].n]=e(nl[r].c)}}});function Zh(){return pl}var il,Br,ol,al,cl,ul,Qn,ll,dl,fl,pl,WR,HR,jR,XR,KR,GR,zR,gl=E(()=>{il=class{constructor(){}createGauge(e,r){return HR}createHistogram(e,r){return jR}createCounter(e,r){return WR}createUpDownCounter(e,r){return XR}createObservableGauge(e,r){return GR}createObservableCounter(e,r){return KR}createObservableUpDownCounter(e,r){return zR}addBatchObservableCallback(e,r){}removeBatchObservableCallback(e){}},Br=class{},ol=class extends Br{add(e,r){}},al=class extends Br{add(e,r){}},cl=class extends Br{record(e,r){}},ul=class extends Br{record(e,r){}},Qn=class{addCallback(e){}removeCallback(e){}},ll=class extends Qn{},dl=class extends Qn{},fl=class extends Qn{},pl=new il,WR=new ol,HR=new cl,jR=new ul,XR=new al,KR=new ll,GR=new dl,zR=new fl});var To,e_=E(()=>{(function(t){t[t.INT=0]="INT",t[t.DOUBLE=1]="DOUBLE"})(To||(To={}))});var Io,vo,ml=E(()=>{Io={get(t,e){if(t!=null)return t[e]},keys(t){return t==null?[]:Object.keys(t)}},vo={set(t,e,r){t!=null&&(t[e]=r)}}});var Ro,t_=E(()=>{Jn();Ro=class{active(){return bo}with(e,r,n,...s){return r.call(n,...s)}bind(e,r){return r}enable(){return this}disable(){return this}}});var hl,VR,Ze,Zn=E(()=>{t_();er();tr();hl="context",VR=new Ro,Ze=class t{constructor(){}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalContextManager(e){return Je(hl,e,Q.instance())}active(){return this._getContextManager().active()}with(e,r,n,...s){return this._getContextManager().with(e,r,n,...s)}bind(e,r){return this._getContextManager().bind(e,r)}_getContextManager(){return _e(hl)||VR}disable(){this._getContextManager().disable(),Qe(hl,Q.instance())}}});var Wr,_l=E(()=>{(function(t){t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED"})(Wr||(Wr={}))});var es,ts,Ao,Mo=E(()=>{_l();es="0000000000000000",ts="00000000000000000000000000000000",Ao={traceId:ts,spanId:es,traceFlags:Wr.NONE}});var et,Po=E(()=>{Mo();et=class{constructor(e=Ao){this._spanContext=e}spanContext(){return this._spanContext}setAttribute(e,r){return this}setAttributes(e){return this}addEvent(e,r){return this}addLink(e){return this}addLinks(e){return this}setStatus(e){return this}updateName(e){return this}end(e){}isRecording(){return!1}recordException(e,r){}}});function Oo(t){return t.getValue(El)||void 0}function r_(){return Oo(Ze.getInstance().active())}function rs(t,e){return t.setValue(El,e)}function n_(t){return t.deleteValue(El)}function s_(t,e){return rs(t,new et(e))}function ko(t){var e;return(e=Oo(t))===null||e===void 0?void 0:e.spanContext()}var El,Sl=E(()=>{Jn();Po();Zn();El=$r("OpenTelemetry Context Key SPAN")});function i_(t,e){if(typeof t!="string"||t.length!==e)return!1;let r=0;for(let n=0;n<t.length;n+=4)r+=(xo[t.charCodeAt(n)]|0)+(xo[t.charCodeAt(n+1)]|0)+(xo[t.charCodeAt(n+2)]|0)+(xo[t.charCodeAt(n+3)]|0);return r===e}function yl(t){return i_(t,32)&&t!==ts}function bl(t){return i_(t,16)&&t!==es}function Hr(t){return yl(t.traceId)&&bl(t.spanId)}function o_(t){return new et(t)}var xo,No=E(()=>{Mo();Po();xo=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1])});function YR(t){return t!==null&&typeof t=="object"&&"spanId"in t&&typeof t.spanId=="string"&&"traceId"in t&&typeof t.traceId=="string"&&"traceFlags"in t&&typeof t.traceFlags=="number"}var wl,jr,Tl=E(()=>{Zn();Sl();Po();No();wl=Ze.getInstance(),jr=class{startSpan(e,r,n=wl.active()){if(!!r?.root)return new et;let i=n&&ko(n);return YR(i)&&Hr(i)?new et(i):new et}startActiveSpan(e,r,n,s){let i,o,a;if(arguments.length<2)return;arguments.length===2?a=r:arguments.length===3?(i=r,a=n):(i=r,o=n,a=s);let c=o??wl.active(),u=this.startSpan(e,i,c),l=rs(c,u);return wl.with(l,a,void 0,u)}}});var qR,Xr,Il=E(()=>{Tl();qR=new jr,Xr=class{constructor(e,r,n,s){this._provider=e,this.name=r,this.version=n,this.options=s}startSpan(e,r,n){return this._getTracer().startSpan(e,r,n)}startActiveSpan(e,r,n,s){let i=this._getTracer();return Reflect.apply(i.startActiveSpan,i,arguments)}_getTracer(){if(this._delegate)return this._delegate;let e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):qR}}});var Co,a_=E(()=>{Tl();Co=class{getTracer(e,r,n){return new jr}}});var JR,rr,vl=E(()=>{Il();a_();JR=new Co,rr=class{getTracer(e,r,n){var s;return(s=this.getDelegateTracer(e,r,n))!==null&&s!==void 0?s:new Xr(this,e,r,n)}getDelegate(){var e;return(e=this._delegate)!==null&&e!==void 0?e:JR}setDelegate(e){this._delegate=e}getDelegateTracer(e,r,n){var s;return(s=this._delegate)===null||s===void 0?void 0:s.getTracer(e,r,n)}}});var Do,c_=E(()=>{(function(t){t[t.NOT_RECORD=0]="NOT_RECORD",t[t.RECORD=1]="RECORD",t[t.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"})(Do||(Do={}))});var Fo,u_=E(()=>{(function(t){t[t.INTERNAL=0]="INTERNAL",t[t.SERVER=1]="SERVER",t[t.CLIENT=2]="CLIENT",t[t.PRODUCER=3]="PRODUCER",t[t.CONSUMER=4]="CONSUMER"})(Fo||(Fo={}))});var Lo,l_=E(()=>{(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(Lo||(Lo={}))});function d_(t){return eA.test(t)}function f_(t){return tA.test(t)&&!rA.test(t)}var Rl,QR,ZR,eA,tA,rA,p_=E(()=>{Rl="[_0-9a-z-*/]",QR=`[a-z]${Rl}{0,255}`,ZR=`[a-z0-9]${Rl}{0,240}@[a-z]${Rl}{0,13}`,eA=new RegExp(`^(?:${QR}|${ZR})$`),tA=/^[ -~]{0,255}[!-~]$/,rA=/,|=/});var g_,nA,m_,h_,Uo,__=E(()=>{p_();g_=32,nA=512,m_=",",h_="=",Uo=class t{constructor(e){this._internalState=new Map,e&&this._parse(e)}set(e,r){let n=this._clone();return n._internalState.has(e)&&n._internalState.delete(e),n._internalState.set(e,r),n}unset(e){let r=this._clone();return r._internalState.delete(e),r}get(e){return this._internalState.get(e)}serialize(){return Array.from(this._internalState.keys()).reduceRight((e,r)=>(e.push(r+h_+this.get(r)),e),[]).join(m_)}_parse(e){e.length>nA||(this._internalState=e.split(m_).reduceRight((r,n)=>{let s=n.trim(),i=s.indexOf(h_);if(i!==-1){let o=s.slice(0,i),a=s.slice(i+1,n.length);d_(o)&&f_(a)&&r.set(o,a)}return r},new Map),this._internalState.size>g_&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,g_))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let e=new t;return e._internalState=new Map(this._internalState),e}}});function E_(t){return new Uo(t)}var S_=E(()=>{__()});var Al,y_=E(()=>{Zn();Al=Ze.getInstance()});var Ml,b_=E(()=>{tr();Ml=Q.instance()});var Pl,w_,T_=E(()=>{gl();Pl=class{getMeter(e,r,n){return pl}},w_=new Pl});var Ol,$o,I_=E(()=>{T_();er();tr();Ol="metrics",$o=class t{constructor(){}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalMeterProvider(e){return Je(Ol,e,Q.instance())}getMeterProvider(){return _e(Ol)||w_}getMeter(e,r,n){return this.getMeterProvider().getMeter(e,r,n)}disable(){Qe(Ol,Q.instance())}}});var kl,v_=E(()=>{I_();kl=$o.getInstance()});var Bo,R_=E(()=>{Bo=class{inject(e,r){}extract(e,r){return e}fields(){return[]}}});function Nl(t){return t.getValue(xl)||void 0}function A_(){return Nl(Ze.getInstance().active())}function M_(t,e){return t.setValue(xl,e)}function P_(t){return t.deleteValue(xl)}var xl,O_=E(()=>{Zn();Jn();xl=$r("OpenTelemetry Baggage Key")});var Cl,sA,Wo,k_=E(()=>{er();R_();ml();O_();tl();tr();Cl="propagation",sA=new Bo,Wo=class t{constructor(){this.createBaggage=qh,this.getBaggage=Nl,this.getActiveBaggage=A_,this.setBaggage=M_,this.deleteBaggage=P_}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalPropagator(e){return Je(Cl,e,Q.instance())}inject(e,r,n=vo){return this._getGlobalPropagator().inject(e,r,n)}extract(e,r,n=Io){return this._getGlobalPropagator().extract(e,r,n)}fields(){return this._getGlobalPropagator().fields()}disable(){Qe(Cl,Q.instance())}_getGlobalPropagator(){return _e(Cl)||sA}}});var Dl,x_=E(()=>{k_();Dl=Wo.getInstance()});var Fl,Ho,N_=E(()=>{er();vl();No();Sl();tr();Fl="trace",Ho=class t{constructor(){this._proxyTracerProvider=new rr,this.wrapSpanContext=o_,this.isSpanContextValid=Hr,this.deleteSpan=n_,this.getSpan=Oo,this.getActiveSpan=r_,this.getSpanContext=ko,this.setSpan=rs,this.setSpanContext=s_}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalTracerProvider(e){let r=Je(Fl,this._proxyTracerProvider,Q.instance());return r&&this._proxyTracerProvider.setDelegate(e),r}getTracerProvider(){return _e(Fl)||this._proxyTracerProvider}getTracer(e,r){return this.getTracerProvider().getTracer(e,r)}disable(){Qe(Fl,Q.instance()),this._proxyTracerProvider=new rr}}});var Ll,C_=E(()=>{N_();Ll=Ho.getInstance()});var D_={};fs(D_,{DiagConsoleLogger:()=>wo,DiagLogLevel:()=>te,INVALID_SPANID:()=>es,INVALID_SPAN_CONTEXT:()=>Ao,INVALID_TRACEID:()=>ts,ProxyTracer:()=>Xr,ProxyTracerProvider:()=>rr,ROOT_CONTEXT:()=>bo,SamplingDecision:()=>Do,SpanKind:()=>Fo,SpanStatusCode:()=>Lo,TraceFlags:()=>Wr,ValueType:()=>To,baggageEntryMetadataFromString:()=>Jh,context:()=>Al,createContextKey:()=>$r,createNoopMeter:()=>Zh,createTraceState:()=>E_,default:()=>iA,defaultTextMapGetter:()=>Io,defaultTextMapSetter:()=>vo,diag:()=>Ml,isSpanContextValid:()=>Hr,isValidSpanId:()=>bl,isValidTraceId:()=>yl,metrics:()=>kl,propagation:()=>Dl,trace:()=>Ll});var iA,F_=E(()=>{tl();Jn();Qh();So();gl();e_();ml();Il();vl();c_();u_();l_();_l();S_();No();Mo();y_();b_();v_();x_();C_();iA={context:Al,diag:Ml,metrics:kl,propagation:Dl,trace:Ll}});function nE(t){if(!t.startsWith("mcp__"))return null;let e=t.split("__");if(e.length<3)return null;let r=e[1].toLowerCase();return!r.includes("memindex")&&!r.includes("agent-mem")&&!r.includes("agent_mem")&&!r.includes("mcp-search")&&!r.includes("mcp_search")?null:e.slice(2).join("__")}function Gr(t){if(!t)return!1;if(t.startsWith("memory_")||t==="mem_search"||t==="get_summaries")return!0;let e=nE(t);return e!==null&&JA.has(e)}function ea(t){return t==="save_memory"||nE(t)==="save_memory"}var JA,ta=E(()=>{"use strict";JA=new Set(["mem_search","search","timeline","get_observations","get_summaries","get_tool_uses","session_start_context","observation_search","observation_context","memory_search","memory_context"])});function zl(t){return typeof t=="string"&&t.length>0}var us,SE=E(()=>{"use strict";us=class extends Error{constructor(r){super(`adapter rejected input: ${r}`);this.reason=r;this.name="AdapterRejectedInput"}reason}});var hM,yE,bE,_M,EM,wE,TE=E(()=>{"use strict";SE();Bt();hM=128,yE=t=>typeof t=="string"&&t.length>0&&t.length<=hM?t:void 0,bE=t=>typeof t=="string"?t:void 0,_M=t=>t.hook_event_name==="PostToolUseFailure"?{error:t.error,is_interrupt:t.is_interrupt===!0}:void 0,EM=t=>{if(typeof t!="object"||t===null)return;let e=t;if(!Object.prototype.hasOwnProperty.call(e,"submitted_prompt"))return;let r=e.submitted_prompt;return typeof r!="string"?null:r.trim()?r:null},wE={normalizeInput(t){let e=t??{},r=e.cwd??process.cwd();if(!zl(r))throw new us("invalid_cwd");let n=Nf(r);if(!zl(n))throw new us("invalid_cwd");let s=e.source;return{sessionId:e.session_id??e.id??e.sessionId,hookEventName:bE(e.hook_event_name),cwd:n,sessionSource:s==="startup"||s==="resume"||s==="clear"||s==="compact"?s:void 0,prompt:e.prompt,submittedPrompt:EM(e),toolName:e.tool_name,toolInput:e.tool_input,toolResponse:e.tool_response??_M(e),toolUseId:typeof e.tool_use_id=="string"?e.tool_use_id:void 0,transcriptPath:e.transcript_path,reason:bE(e.reason),agentId:yE(e.agent_id),agentType:yE(e.agent_type)}},formatOutput(t){let e=t??{};if(e.hookSpecificOutput){let n={hookSpecificOutput:t.hookSpecificOutput};return e.systemMessage&&(n.systemMessage=e.systemMessage),n}let r={};return e.systemMessage&&(r.systemMessage=e.systemMessage),r}}});function IE(t,e){return De("observation",{contentSessionId:t.sessionId,platformSource:e,toolName:t.toolName,toolInput:t.toolInput,toolResponse:t.toolResponse,cwd:t.cwd,agentId:t.agentId,agentType:t.agentType,toolUseId:t.toolUseId},t.spoolAtEpochMs),{continue:!0,suppressOutput:!0}}var vE,RE=E(()=>{"use strict";Tr();A();Wc();He();Sr();ki();it();mn();ut();br();yr();ta();vE={async execute(t){let{sessionId:e,cwd:r,toolName:n,toolInput:s,toolResponse:i}=t,o=G(t.platform);if(!n)return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};if(Gr(n))return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};let a=Eg(f.formatTool(n,s));if(f.dataIn("HOOK",`PostToolUse: ${a}`,{}),!r)throw new Error(`Missing cwd in PostToolUse hook input for session ${e}, tool ${n}`);if(!Ge(r))return f.debug("HOOK","Project excluded from tracking, skipping observation",{cwd:r,toolName:n}),{continue:!0,suppressOutput:!0};let c=vr(t.agentId,t.agentType,K());if(c.skip)return f.debug("HOOK",`Skipping observation: ${c.reason}`,{toolName:n,agentId:t.agentId,agentType:t.agentType}),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};if(ea(n))return IE(t,o);let u=xe();if(u.runtime==="server"){if(vt(n,K().MEMINDEX_SKIP_TOOLS))return f.debug("HOOK","Server runtime: tool excluded by MEMINDEX_SKIP_TOOLS",{toolName:n}),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};let l={projectId:u.projectId,contentSessionId:e,platformSource:o,sourceType:"hook",eventType:"tool_use",occurredAtEpoch:Date.now(),payload:{tool_name:n,tool_input:s,tool_response:i,cwd:r,agentId:t.agentId,agentType:t.agentType,platformSource:o,tool_use_id:t.toolUseId}};try{return await u.client.recordEvent(l),f.debug("HOOK","Observation sent successfully via server",{toolName:n}),{continue:!0,suppressOutput:!0}}catch(d){if(Tt(d)&&d.isFallbackEligible())It(d.kind,{status:d.status,message:d.message,route:"/v1/events"});else return f.error("HOOK","Server event failed (non-recoverable)",{error:d instanceof Error?d.message:String(d)}),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS}}}return IE(t,o)}}});function bM(t,e,r){let n=0;for(;n<e.length;){let s=(0,Ue.readSync)(t,e,n,e.length-n,r+n);if(s===0)break;n+=s}return n}function*wM(t,e){let r=Math.max(1,e.maxChunkBytes??AE),n=Math.min(r,Math.max(1,e.initialBytes??SM)),s=(0,Ue.openSync)(t,"r");try{let i=(0,Ue.fstatSync)(s).size,o=Buffer.alloc(0);for(;i>0;){let a=Math.max(0,i-n),c=Buffer.alloc(i-a),u=bM(s,c,a),l=u===c.length?c:c.subarray(0,u),d=o.length?Buffer.concat([l,o]):l;if(a===0){yield{text:d.toString("utf-8"),byteLength:l.length,isFirstChunkOfFile:!0};return}let p=d.indexOf(10);p===-1?(o=d,yield{text:"",byteLength:l.length,isFirstChunkOfFile:!1}):(o=d.subarray(0,p),yield{text:d.subarray(p+1).toString("utf-8"),byteLength:l.length,isFirstChunkOfFile:!1}),i=a,n=Math.min(n*4,r)}o.length&&(yield{text:o.toString("utf-8"),byteLength:0,isFirstChunkOfFile:!0})}finally{(0,Ue.closeSync)(s)}}function ME(t,e,r={}){if(!t||!(0,Ue.existsSync)(t)){f.warn("PARSER",`Transcript path missing or file does not exist: ${t}`);return}let n=!1;for(let s of wM(t,r)){!n&&s.text.trim()&&(n=!0);let i=e(s.text,s.isFirstChunkOfFile,s.byteLength);if(i!==void 0)return i}n||f.warn("PARSER",`Transcript file exists but is empty: ${t}`)}function*Vl(t){let e=t.split(`
|
|
24
|
-
`);for(let r=e.length-1;r>=0;r--){let n=e[r];if(!n)continue;let s;try{s=JSON.parse(n)}catch{continue}yield s}}function
|
|
25
|
-
`):null}function
|
|
14
|
+
`)}else ct(p+`
|
|
15
|
+
`)}debug(e,r,n,s){this.log(0,e,r,n,s)}info(e,r,n,s){this.log(1,e,r,n,s)}warn(e,r,n,s){this.log(2,e,r,n,s)}setErrorSink(e){Ca=e}error(e,r,n,s){this.log(3,e,r,n,s),this.routeErrorToSink(r,n,s)}routeErrorToSink(e,r,n){try{if(!Ca||!(n instanceof Error))return;Ca(n)}catch{}}dataIn(e,r,n,s){this.info(e,`\u2192 ${r}`,n,s)}dataOut(e,r,n,s){this.info(e,`\u2190 ${r}`,n,s)}success(e,r,n,s){this.info(e,`\u2713 ${r}`,n,s)}failure(e,r,n,s){this.error(e,`\u2717 ${r}`,n,s)}},f=new Fa});function Hd(t){try{return new URL(t).hostname.toLowerCase()==="openrouter.ai"}catch{return!1}}var Xd=E(()=>{"use strict";O()});function Xt(t){let e=(0,ke.resolve)(t),r=[],n=e;for(;;)try{return(0,ke.join)(Gd.realpathSync.native(n),...r.reverse())}catch{let s=(0,ke.dirname)(n);if(s===n)return e;r.push((0,ke.basename)(n)),n=s}}function Ty(t,e){return Xt(t)===Xt(e)}function Iy(t,e){let r=Xt(e);return t===r||t.startsWith(r.endsWith(ke.sep)?r:r+ke.sep)}function vy(t,e=(0,Kt.homedir)()){let r=Xt(t),n=Xt(e);return(process.platform==="win32"?[(0,Kt.tmpdir)()]:[(0,Kt.tmpdir)(),...wy]).some(o=>Xt(o)!==n&&Iy(r,o))}function un(t=process.env,e=(0,Kt.homedir)()){return t.MEMINDEX_TEST_FORBIDDEN_DATA_DIR?!0:vy(an(t,e),e)}function La(){return 38700+(process.getuid?.()??77)%100}function Ua(t){let e=(0,Kd.createHash)("sha256").update(Xt(t)).digest();return yy+e.readUInt32BE(0)%by}function Vd(t=process.env,e=(0,Kt.homedir)()){return un(t,e)?Ua(an(t,e)):La()}function Yd(t,e){return typeof t!="string"||t.length===0?"unknown":Ty(t,e)?"same":"foreign"}var Kd,Gd,Kt,ke,yy,by,wy,zd,$a=E(()=>{"use strict";Kd=require("crypto"),Gd=require("fs"),Kt=require("os"),ke=require("path");ka();yy=4e4,by=9e3,wy=["/tmp","/private/tmp","/var/folders","/private/var/folders"],zd="60"});function Ay(t){return typeof t=="boolean"?String(t):t}function Oy(t){let e=t.MEMINDEX_OPENROUTER_MODEL;if(typeof e!="string"||!Ry.has(e.trim()))return!1;let r=typeof t.MEMINDEX_OPENROUTER_BASE_URL=="string"?t.MEMINDEX_OPENROUTER_BASE_URL.trim():"";return r===""||Hd(r)}function Zd(t,e){return(0,vt.join)((0,vt.dirname)(t),`.${(0,vt.basename)(t)}.${e.markerTag}`)}function Ba(t,e){try{(0,Gt.writeFileSync)(Zd(t,e),new Date().toISOString(),{encoding:"utf-8",mode:384})}catch{}}var Gt,vt,ln,Ry,qd,Jd,Qd,V,dt=E(()=>{"use strict";Gt=require("fs"),vt=require("path"),ln=require("os");xe();se();Xd();on();ks();$a();Ry=new Set(["xiaomi/mimo-v2-flash:free"]);qd=18e4,Jd=[{key:"MEMINDEX_LLM_TIMEOUT_MS",legacy:"30000",markerTag:"llm-timeout-migrated-v1"},{key:"MEMINDEX_FIELD_OPTIMIZE_TIMEOUT_MS",legacy:"30000",markerTag:"field-optimize-timeout-migrated-v1"}];Qd=new Set,V=class{static DEFAULTS={MEMINDEX_MEMORY_SEARCH_HOOK_ENABLED:"true",MEMINDEX_MEMORY_INSTRUCTIONS_ENABLED:"true",MEMINDEX_MEMORY_WATCH_ROOTS:"",MEMINDEX_MODEL:"claude-haiku-4-5-20251001",MEMINDEX_CONTEXT_OBSERVATIONS:"50",MEMINDEX_SESSION_START_INCLUDE_ALL_SOURCES:"false",MEMINDEX_WORKER_PORT:String(Vd()),MEMINDEX_WORKER_HOST:"127.0.0.1",MEMINDEX_ALLOWED_ORIGINS:"",MEMINDEX_PUBLIC_URL:"",MEMINDEX_API_TIMEOUT_MS:String(ze(Q.API_REQUEST)),MEMINDEX_SESSION_INIT_TIMEOUT_MS:String(cn()),MEMINDEX_IDLE_EXIT_SEC:un()?zd:"0",MEMINDEX_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",MEMINDEX_SKIP_BASH_PATTERNS:"",MEMINDEX_SKIP_SUBAGENT_OBSERVATIONS:"false",MEMINDEX_SKIP_AGENT_TYPES:"",MEMINDEX_CAPTURE_ADVISOR_CALLS:"false",MEMINDEX_PROVIDER:"claude",MEMINDEX_CODEX_MODEL:"",MEMINDEX_CODEX_PATH:"codex",MEMINDEX_CODEX_REASONING_EFFORT:"low",MEMINDEX_CODEX_MAX_CONCURRENT_AGENTS:"2",MEMINDEX_CODEX_OBSERVATION_BATCH_SIZE:"8",MEMINDEX_CODEX_OBSERVATION_BATCH_MAX_CHARS:"32000",MEMINDEX_CLAUDE_AUTH_METHOD:"subscription",MEMINDEX_GEMINI_API_KEY:"",MEMINDEX_GEMINI_API_KEYS:"",MEMINDEX_GEMINI_MODEL:"gemini-flash-latest",MEMINDEX_GEMINI_RATE_LIMITING_ENABLED:"true",MEMINDEX_OPENROUTER_API_KEY:"",MEMINDEX_OPENROUTER_API_KEYS:"",MEMINDEX_OPENROUTER_MODEL:"cohere/north-mini-code:free",MEMINDEX_OPENROUTER_BASE_URL:"",MEMINDEX_OPENROUTER_TEMPERATURE:"",MEMINDEX_OPENROUTER_SITE_URL:"",MEMINDEX_OPENROUTER_APP_NAME:"memindex",MEMINDEX_OPENROUTER_EXTRA_BODY:"",MEMINDEX_OPENROUTER_REASONING_EFFORT:"",MEMINDEX_OPENAI_COMPAT_PRESET:"",MEMINDEX_OPENAI_COMPAT_API_KEY:"",MEMINDEX_OPENAI_COMPAT_API_KEYS:"",MEMINDEX_OPENAI_COMPAT_BASE_URL:"",MEMINDEX_OPENAI_COMPAT_MODEL:"",MEMINDEX_QUOTA_FALLBACK_PROVIDER:"claude",MEMINDEX_QUOTA_FALLBACK_MODEL:"",MEMINDEX_QUOTA_THRESHOLD_FIVE_HOUR:"0.95",MEMINDEX_QUOTA_THRESHOLD_SEVEN_DAY:"0.93",MEMINDEX_QUOTA_THRESHOLD_SEVEN_DAY_OPUS:"0.93",MEMINDEX_QUOTA_THRESHOLD_SEVEN_DAY_SONNET:"0.92",MEMINDEX_QUOTA_THRESHOLD_OVERAGE:"0.95",MEMINDEX_DATA_DIR:(0,vt.join)((0,ln.homedir)(),".memindex"),MEMINDEX_SNAPSHOT_ENABLED:"true",MEMINDEX_SNAPSHOT_INTERVAL_HOURS:"24",MEMINDEX_SNAPSHOT_KEEP:"7",MEMINDEX_LOG_LEVEL:"INFO",MEMINDEX_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",MEMINDEX_CLAUDE_CONFIG_DIR:"",MEMINDEX_OBSERVER_CLAUDE_CONFIG_DIR:"",MEMINDEX_MODE:"code",MEMINDEX_CONTEXT_SHOW_READ_TOKENS:"false",MEMINDEX_CONTEXT_SHOW_WORK_TOKENS:"false",MEMINDEX_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",MEMINDEX_CONTEXT_SHOW_SAVINGS_PERCENT:"true",MEMINDEX_CONTEXT_OBSERVATION_TYPES:"",MEMINDEX_CONTEXT_OBSERVATION_CONCEPTS:"",MEMINDEX_CONTEXT_FULL_COUNT:"0",MEMINDEX_CONTEXT_FULL_FIELD:"narrative",MEMINDEX_CONTEXT_SESSION_COUNT:"10",MEMINDEX_CONTEXT_SHOW_LAST_SUMMARY:"true",MEMINDEX_CONTEXT_SHOW_LAST_MESSAGE:"false",MEMINDEX_CONTEXT_MAIN_AGENT_ONLY:"true",MEMINDEX_REINFORCE_ALPHA:"0",MEMINDEX_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",MEMINDEX_WELCOME_HINT_ENABLED:"true",MEMINDEX_WORK_STATE_ENABLED:"true",MEMINDEX_FILE_READ_GATE_ENABLED:"true",MEMINDEX_ENDLESS_MODE_ENABLED:"true",MEMINDEX_FOLDER_CLAUDEMD_ENABLED:"false",MEMINDEX_FOLDER_USE_LOCAL_MD:"false",MEMINDEX_TRANSCRIPTS_ENABLED:"true",MEMINDEX_TRANSCRIPTS_CONFIG_PATH:(0,vt.join)((0,ln.homedir)(),".memindex","transcript-watch.json"),MEMINDEX_CODEX_TRANSCRIPT_INGESTION:"false",MEMINDEX_CODEX_SUBAGENT_INGESTION:"false",MEMINDEX_MAX_CONCURRENT_AGENTS:"2",MEMINDEX_OBSERVER_MAX_CONVERSATION_CHARS:"400000",MEMINDEX_OBSERVER_CONTEXT_WINDOW:"",MEMINDEX_OBSERVER_MAX_OUTPUT_TOKENS:"4096",MEMINDEX_OBSERVE_BARE_PROMPTS:"false",MEMINDEX_HOOK_FAIL_LOUD_THRESHOLD:"3",MEMINDEX_REDACT_ENABLED:"false",MEMINDEX_REDACT_DISABLED_BUILTINS:"",MEMINDEX_REDACT_CUSTOM_PATTERNS:"[]",MEMINDEX_REDACT_LOG_MATCHES:"false",MEMINDEX_EXCLUDED_PROJECTS:"",MEMINDEX_PROJECT_ENVIRONMENTS:"[]",MEMINDEX_FOLDER_MD_EXCLUDE:"[]",MEMINDEX_FOLDER_MD_SKELETON_DENYLIST:"[]",MEMINDEX_SEMANTIC_INJECT:"auto",MEMINDEX_SEMANTIC_INJECT_LIMIT:"5",MEMINDEX_SEMANTIC_INJECT_FORMAT:"narrative",MEMINDEX_TIER_ROUTING_ENABLED:"true",MEMINDEX_TIER_SIMPLE_MODEL:"haiku",MEMINDEX_TIER_SUMMARY_MODEL:"",MEMINDEX_TIER_FAST_MODEL:"haiku",MEMINDEX_TIER_SMART_MODEL:"sonnet",MEMINDEX_CHROMA_ENABLED:"true",MEMINDEX_CHROMA_MODE:"local",MEMINDEX_CHROMA_HOST:"127.0.0.1",MEMINDEX_CHROMA_PORT:"8000",MEMINDEX_CHROMA_SSL:"false",MEMINDEX_CHROMA_API_KEY:"",MEMINDEX_CHROMA_TENANT:"default_tenant",MEMINDEX_CHROMA_DATABASE:"default_database",MEMINDEX_CHROMA_PREWARM_TIMEOUT_MS:"120000",MEMINDEX_CHROMA_MUTATION_TIMEOUT_MS:"600000",MEMINDEX_CHROMA_MAX_PENDING_MUTATIONS:"5000",MEMINDEX_CHROMA_MEMORY_LIMIT_MB:"2048",MEMINDEX_CHROMA_EMBEDDING_FUNCTION:"default",MEMINDEX_CHROMA_UVX_PATH:"",MEMINDEX_SEARCH_RECENCY_DAYS:"90",MEMINDEX_HOSTING_OFFER:"true",MEMINDEX_CLOUD_SYNC_TOKEN:"",MEMINDEX_CLOUD_SYNC_USER_ID:"",MEMINDEX_CLOUD_SYNC_HUB_URL:"",MEMINDEX_CLOUD_SYNC_DEVICE_ID:"",MEMINDEX_CLOUD_SYNC_DEVICE_NAME:(0,ln.hostname)(),MEMINDEX_CLOUD_SYNC_WS:"true",MEMINDEX_CLOUD_SYNC_CONTENT_BATCH_SIZE:"40",MEMINDEX_CLOUD_SYNC_REQUEST_TIMEOUT_MS:"90000",MEMINDEX_LLM_TIMEOUT_MS:String(qd),MEMINDEX_LLM_STREAM_IDLE_TIMEOUT_MS:"90000",MEMINDEX_FIELD_OPTIMIZE_TIMEOUT_MS:String(qd),MEMINDEX_TV_TOKEN:"",MEMINDEX_AUTH_MODE:"api-key",MEMINDEX_RUNTIME:"worker",MEMINDEX_SERVER_URL:`http://127.0.0.1:${process.env.MEMINDEX_SERVER_PORT??String(38877+(process.getuid?.()??77)%100)}`,MEMINDEX_SERVER_API_KEY:"",MEMINDEX_SERVER_PROJECT_ID:"",MEMINDEX_SERVER_BETA_URL:`http://127.0.0.1:${process.env.MEMINDEX_SERVER_PORT??String(38877+(process.getuid?.()??77)%100)}`,MEMINDEX_SERVER_BETA_API_KEY:"",MEMINDEX_SERVER_BETA_PROJECT_ID:"",MEMINDEX_DEDUP_ENABLED:"false",MEMINDEX_DEDUP_COSINE_THRESHOLD:"0.80",MEMINDEX_DEDUP_IDF_VETO_DF:"10",MEMINDEX_DEDUP_MIN_SHARED_TOKENS:"2",MEMINDEX_DEDUP_MIN_PROJECT_DOCS:"10",MEMINDEX_DEDUP_MAX_SCAN:"2000",MEMINDEX_DEDUP_MAX_BACKFILL_ROWS:"50000",MEMINDEX_TOOL_USES_RETENTION_DAYS:"0",MEMINDEX_WORKER_AUTOSTART:"true",MEMINDEX_PROJECT_NAME_SOURCE:"path"};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){let r=process.env[e]??this.DEFAULTS[e];return e==="MEMINDEX_WORKER_HOST"?this.normalizeWorkerHost(r):r}static normalizeWorkerHost(e){return e==="localhost"?"127.0.0.1":e}static finalizeSettings(e,r){let n=r?this.applyEnvOverrides(e):e;return n.MEMINDEX_WORKER_HOST=this.normalizeWorkerHost(n.MEMINDEX_WORKER_HOST),n}static getInt(e){let r=this.get(e);return parseInt(r,10)}static applyEnvOverrides(e){let r={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(r[n]=process.env[n]);return r}static loadFromFile(e,r=!0,n={}){try{if(!(0,Gt.existsSync)(e)){let p=this.getAllDefaults();if(!n.readOnly)try{U(e,p,{mode:384});for(let g of Jd)Ba(e,g);console.warn("[SETTINGS] Created settings file with defaults:",e)}catch(g){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,g instanceof Error?g.message:String(g))}return this.finalizeSettings(p,r)}let s=(0,Gt.readFileSync)(e,"utf-8"),o=jt(s),i=_r(o),a=i!==o,c=Ms(i),u=Nd(o),l=a&&Object.keys(u).some(p=>p!=="env");if(a&&!l&&!n.readOnly)try{U(e,c,{mode:384}),console.warn("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(p){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,p instanceof Error?p.message:String(p))}if(Oy(c)){let p=String(c.MEMINDEX_OPENROUTER_MODEL).trim();if(c={...c,MEMINDEX_OPENROUTER_MODEL:this.DEFAULTS.MEMINDEX_OPENROUTER_MODEL},!n.readOnly)try{U(e,l?{...u,env:c}:c,{mode:384}),console.warn(`[SETTINGS] Migrated OpenRouter model off the retired default ${p} to ${this.DEFAULTS.MEMINDEX_OPENROUTER_MODEL}:`,e)}catch(g){console.warn("[SETTINGS] Failed to migrate the retired OpenRouter model:",e,g instanceof Error?g.message:String(g))}}for(let p of Jd)if(!(0,Gt.existsSync)(Zd(e,p))){if(c[p.key]!==p.legacy){n.readOnly||Ba(e,p);continue}if(c={...c,[p.key]:this.DEFAULTS[p.key]},!n.readOnly)try{U(e,l?{...u,env:c}:c,{mode:384}),Ba(e,p),console.warn(`[SETTINGS] Migrated ${p.key} off the old ${p.legacy}ms default to ${this.DEFAULTS[p.key]}ms:`,e)}catch(g){let m=`${p.key}\0${e}`;Qd.has(m)||(Qd.add(m),console.warn(`[SETTINGS] Failed to migrate ${p.key}; using the new default in memory (reported once per process):`,e,g instanceof Error?g.message:String(g)))}}let d={...this.DEFAULTS};for(let p of Object.keys(this.DEFAULTS))c[p]!==void 0&&(d[p]=Ay(c[p]));return this.finalizeSettings(d,r)}catch(s){console.warn("[SETTINGS] Failed to load settings, using defaults:",e,s instanceof Error?s.message:String(s));let o=this.getAllDefaults();return this.finalizeSettings(o,r)}}}});function ff(t=N()){let e=(0,$.openSync)((0,Ls.join)(t,pf),$.constants.O_RDONLY|($.constants.O_NOFOLLOW??0));try{let r=(0,$.fstatSync)(e);if(!r.isFile()||process.getuid&&r.uid!==process.getuid()||process.platform!=="win32"&&(r.mode&63)!==0)throw new Error("Worker secret must be an owner-only file");let n=(0,$.readFileSync)(e,"utf8");if(!Ly.test(n))throw new Error("Invalid worker secret");return n}finally{(0,$.closeSync)(e)}}function gf(t=N()){(0,$.mkdirSync)(t,{recursive:!0,mode:448});let e=(0,Ls.join)(t,pf);try{return ff(t)}catch(s){if(s.code!=="ENOENT")throw s}let r=(0,Ls.join)(t,`.worker-secret-${(0,Xa.randomBytes)(16).toString("hex")}`),n=(0,$.openSync)(r,"wx",384);try{(0,$.fchmodSync)(n,384),(0,$.writeFileSync)(n,(0,Xa.randomBytes)(32).toString("hex")),(0,$.fsyncSync)(n)}finally{(0,$.closeSync)(n)}try{try{(0,$.linkSync)(r,e)}catch(s){if(s.code!=="EEXIST")throw s}}finally{(0,$.unlinkSync)(r)}return ff(t)}function gn(t,e=N()){if(!["POST","PUT","PATCH","DELETE"].includes((t.method??"GET").toUpperCase()))return t;let r=new Headers(t.headers);return r.set(Fy,gf(e)),{...t,headers:r,redirect:"error"}}var Xa,$,Ls,Fy,pf,Ly,Ka=E(()=>{"use strict";Xa=require("node:crypto"),$=require("node:fs"),Ls=require("node:path");C();Fy="X-Memindex-Secret",pf="worker-secret",Ly=/^[a-f0-9]{64}$/});async function*$y(t){if(!(t instanceof ReadableStream)){yield*t;return}let e=t.getReader(),r=!1;try{for(;;){let{done:n,value:s}=await e.read();if(n){r=!0;return}yield s}}finally{try{r||await e.cancel()}finally{e.releaseLock()}}}function By(t,e){if(t.length===1)return t[0];let r=new Uint8Array(e),n=0;for(let s of t)r.set(s,n),n+=s.length;return r}async function*_f(t,e={}){let r=e.maxEventBytes??1048576,n=new TextDecoder,s=[],o=0,i=!1,a=0,c=null,u,l=null,d=!1,p=m=>{if(a+m>r)throw new Ga(r)},g=m=>{if(m.length===0){let T=c!==null||l!==null?{event:c||"message",data:(l??[]).join(`
|
|
16
|
+
`),...u!==void 0?{id:u}:{}}:null;return c=null,u=void 0,l=null,a=0,T}if(m[0]===Uy)return e.onActivity?.(),null;p(m.length),a+=m.length;let h=n.decode(m),_=h.indexOf(":"),S=_===-1?h:h.slice(0,_),b=_===-1?"":h.slice(_+1);return b.startsWith(" ")&&(b=b.slice(1)),S==="event"?c=b:S==="data"?(l??=[]).push(b):S==="id"&&(u=b),null};for await(let m of $y(t)){let h=0;for(let _=0;_<m.length;_++){let S=m[_];if(i&&(i=!1,S===hf)){h=_+1;continue}if(S!==mf&&S!==hf)continue;s.push(m.subarray(h,_));let b=By(s,o+(_-h));s=[],o=0;let w=g(b);w&&(e.terminalEventNames?.includes(w.event)&&(d=!0),yield w),i=S===mf,h=_+1}if(h<m.length){let _=m.slice(h);s.push(_),o+=_.length,p(o)}}if(e.terminalEventNames&&e.terminalEventNames.length>0&&!d)throw new za(e.terminalEventNames)}var Ga,za,mf,hf,Uy,Ef=E(()=>{"use strict";Ga=class extends Error{constructor(r){super(`SSE event exceeded ${r} bytes`);this.maxEventBytes=r;this.name="SseEventTooLargeError"}maxEventBytes},za=class extends Error{constructor(r){super(`SSE stream ended before a terminal event (${r.join(", ")})`);this.terminalEventNames=r;this.name="StreamEndedEarlyError"}terminalEventNames},mf=13,hf=10,Uy=58});function G(){return Us!==null||(Us=V.loadFromFile(_e)),Us}var Us,ft=E(()=>{"use strict";dt();C();Us=null});function $s(t){return(t.MEMINDEX_WORKER_AUTOSTART??"true").trim().toLowerCase()==="false"}var Sf=E(()=>{"use strict"});var yf=E(()=>{"use strict"});function Va(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}var Ya=E(()=>{"use strict"});function Ja(t,e,r){return(0,qa.spawn)(t,e??[],{...r,windowsHide:!0})}var qa,Wy,jy,xx,Qa=E(()=>{"use strict";qa=require("node:child_process");Wy=new Set([".cmd",".bat"]),jy=new Set([".exe",".com"]),xx=new Set([...jy,...Wy])});function pt(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(Gy.has(r)){e[r]=n;continue}Xy.has(r)||Hy.some(s=>r.startsWith(s))||(e[r]=n)}return e}var Hy,Xy,Ky,Gy,mn=E(()=>{"use strict";Hy=["CLAUDECODE_","CLAUDE_CODE_"],Xy=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),Ky=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy","npm_config_noproxy"]),Gy=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_TMPDIR","CLAUDE_CODE_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS",...Ky])});function Tf(t,e,r){if(r.status!==0)return null;if(typeof r.stdout!="string")return f.warn("SYSTEM","captureProcessStartToken: start-token probe returned no stdout",{pid:e,source:t,status:r.status}),null;let n=r.stdout.trim();return n.length>0?n:null}function Vy(t){Za+=1;let e=(0,ec.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...pt(process.env),LC_ALL:"C",LANG:"C"}});return Tf("powershell-cim",t,e)}function Yy(t,e=!1){if(!e){let n=bf.get(t);if(n&&(t===process.pid||Date.now()-n.capturedAtMs<zy))return n.token}let r=null;try{r=Vy(t)}catch(n){f.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:t,error:n instanceof Error?n.message:String(n)}),r=null}return(r!==null||t!==process.pid)&&bf.set(t,{token:r,capturedAtMs:Date.now()}),r}function If(t,e){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux"){Za+=1;try{let r=(0,wf.readFileSync)(`/proc/${t}/stat`,"utf-8"),n=r.lastIndexOf(") ");if(n<0)return null;let o=r.slice(n+2).split(" ")[19];return o&&/^\d+$/.test(o)?o:null}catch(r){return f.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}if(process.platform==="win32")return Yy(t,e);Za+=1;try{let r=(0,ec.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...pt(process.env),LC_ALL:"C",LANG:"C"}});return Tf("ps-lstart",t,r)}catch(r){return f.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:t,error:r instanceof Error?r.message:String(r)}),null}}function Ye(t){return If(t,!1)}function Ce(t,e){if(e===null)return!0;let r=If(t,!0);return r===null?!0:r===e}var ec,wf,zy,bf,Za,Bs=E(()=>{"use strict";ec=require("child_process"),wf=require("fs");O();mn();zy=5e3,bf=new Map,Za=0});async function we(t,e={}){let r=e.signalMode==="immediate",n=e.expectedStartToken!==void 0?e.expectedStartToken:Ye(t),s=()=>Ce(t,n);if(!s()){f.warn("PROCESS","Skipping tree-kill: root PID was reused since it was captured",{pid:t});return}if(f.debug("PROCESS",`Killing process tree rooted at PID ${t}`,{immediate:r}),process.platform==="win32"){try{await tc("taskkill",["/PID",String(t),"/T","/F"],{timeout:5e3,windowsHide:!0})}catch(o){let i=o.code,a=String(o.stderr??""),c=o instanceof Error?o.message:String(o);if(i===qy||Jy.test(`${a} ${c}`)){f.debug("PROCESS","taskkill reported the process was already gone",{pid:t});return}throw new Ws(t,`taskkill failed for PID ${t} (exit ${String(i)}): ${a.trim()||c}`,{cause:o})}return}try{let o=r?"SIGKILL":"SIGTERM",i=await js(t);for(let u of i){if(!Ce(u.pid,u.startToken)){f.debug("PROCESS",`Skipping ${o}: descendant PID was reused since enumeration`,{pid:u.pid,rootPid:t});continue}try{process.kill(u.pid,o)}catch{}}if(s())try{process.kill(t,o)}catch(u){let l=u instanceof Error?u:new Error(String(u)),d=l.code;d!=="ESRCH"&&f.debug("PROCESS",`Failed to ${o} PID ${t}`,{code:d},l)}else f.warn("PROCESS","Skipping root signal: PID was reused during descendant enumeration",{pid:t,signal:o});r||await new Promise(u=>setTimeout(u,500));let a=s()?await js(t):[],c=new Map;for(let u of i)c.set(u.pid,u.startToken);for(let u of a)c.set(u.pid,u.startToken);for(let[u,l]of c){if(!Ce(u,l)){f.debug("PROCESS","Skipping SIGKILL: descendant PID was reused since the scan",{pid:u,rootPid:t});continue}try{process.kill(u,"SIGKILL")}catch{}}if(!r&&s())try{process.kill(t,"SIGKILL")}catch{}}catch(o){throw new Ws(t,`tree-kill failed for PID ${t}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}}async function Qy(){return process.platform==="win32"?tb():process.platform==="linux"?Zy():eb()}function Zy(){let t=[],e;try{e=(0,Hs.readdirSync)("/proc")}catch(r){return f.warn("PROCESS","Cannot read /proc \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),t}for(let r of e){if(!/^\d+$/.test(r))continue;let n;try{n=(0,Hs.readFileSync)(`/proc/${r}/stat`,"utf-8")}catch{continue}let s=n.lastIndexOf(") ");if(s<0)continue;let o=n.slice(s+2).split(" "),i=Number.parseInt(o[1]??"",10),a=o[19];Number.isFinite(i)&&t.push({pid:Number.parseInt(r,10),ppid:i,startToken:a&&/^\d+$/.test(a)?a:null})}return t}async function eb(){let t;try{t=(await tc("ps",["-eo","pid=,ppid=,lstart="],{timeout:1e4,maxBuffer:33554432,env:{...process.env,LC_ALL:"C",LANG:"C"}})).stdout}catch(r){return f.warn("PROCESS","Cannot enumerate the process table \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),[]}let e=[];for(let r of t.split(`
|
|
17
|
+
`)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);if(!n)continue;let s=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:s.length>0?s:null})}return e}async function tb(){let t;try{t=(await tc("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,@{Name='StartToken';Expression={$_.CreationDate.ToString('yyyyMMddHHmmss.ffffff')}} | ConvertTo-Csv -NoTypeInformation"],{timeout:3e4,windowsHide:!0,maxBuffer:33554432})).stdout}catch(r){return f.warn("PROCESS","Cannot enumerate the Windows process table \u2014 tree-kill degrades to a single-PID kill",{error:r instanceof Error?r.message:String(r)}),[]}let e=[];for(let r of t.split(/\r?\n/).slice(1)){let n=r.match(/^"(\d+)","(\d+)","(.*)"$/);if(!n)continue;let s=n[3].trim();e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),startToken:s.length>0?s:null})}return e}async function js(t){let e=await Qy(),r=new Map;for(let i of e){let a=r.get(i.ppid);a?a.push(i):r.set(i.ppid,[i])}let n=new Set([t]),s=[],o=i=>{for(let a of r.get(i)??[])n.has(a.pid)||(n.add(a.pid),o(a.pid),s.push({pid:a.pid,startToken:a.startToken}))};return o(t),s}var vf,Hs,Rf,tc,qy,Jy,Ws,yr=E(()=>{"use strict";vf=require("child_process"),Hs=require("fs"),Rf=require("util");O();Bs();tc=(0,Rf.promisify)(vf.execFile),qy=128,Jy=/not found|no running instance|no tasks/i,Ws=class extends Error{pid;constructor(e,r,n){super(r,n),this.name="ProcessTreeKillError",this.pid=e}}});function Y(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){if(e instanceof Error){let r=e.code;return r==="EPERM"?!0:(f.debug("SYSTEM","PID check failed",{pid:t,code:r}),!1)}return f.warn("SYSTEM","PID check threw non-Error",{pid:t,error:String(e)}),!1}}async function Xs(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!Y(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function Of(t){if(!t||!Y(t.pid))return!1;if(!t.startToken)return!0;let e=Ye(t.pid);if(e===null)return!0;let r=e===t.startToken;return r||f.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:t.pid,stored:t.startToken,current:e}),r}function Ks(t,e=ab){if(!Of(t))return!1;if(t.startToken||e.platform!=="linux")return!0;let r;try{r=e.readCommandLine(t.pid)}catch(s){return f.debug("SYSTEM","Could not read the command line of a token-less worker PID; trusting the live PID",{pid:t.pid,error:s instanceof Error?s.message:String(s)}),!0}let n=r.split("\0").some(s=>Af.default.basename(s)==="worker-service.cjs");return n||f.debug("SYSTEM","Token-less worker PID now belongs to another program (PID reused)",{pid:t.pid}),n}function gt(t=K.workerPid()){if(!(0,Vt.existsSync)(t))return null;let e;try{e=JSON.parse((0,Vt.readFileSync)(t,"utf-8"))}catch{return null}return e!==null&&Ks(e)?e:null}function Gs(){return rc||(rc=new sc),rc}function nc(){let t=cb.shift();t&&t.notify()}var Vt,Af,nb,sb,ob,ib,ab,sc,rc,qx,cb,mt=E(()=>{"use strict";Qa();Vt=require("fs"),Af=be(require("path"),1);O();se();mn();C();Bs();yr();nb=5e3,sb=1e3,ob=K.supervisorRegistry(),ib=null;ab={platform:process.platform,readCommandLine:t=>(0,Vt.readFileSync)(`/proc/${t}/cmdline`,"utf-8")};sc=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(e=ob){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,!(0,Vt.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Vt.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[s,o]of Object.entries(n))this.entries.set(s,o)}catch(r){r instanceof Error?f.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r):f.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(r)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&f.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}retainSupersededEntry(e,r){let n=this.entries.get(e);if(!n||n.pid===r||!Y(n.pid))return;let s=`${e}#superseded:${n.pid}`;this.entries.set(s,n);let o=this.runtimeProcesses.get(e);o&&(this.runtimeProcesses.set(s,o),this.runtimeProcesses.delete(e)),f.warn("SYSTEM","Registry id reused while the previous process was still alive; kept it for reaping",{id:e,supersededId:s,supersededPid:n.pid,incomingPid:r})}register(e,r,n){this.initialize(),this.retainSupersededEntry(e,r.pid),this.entries.set(e,r),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e,r){this.initialize();let n=e,s=this.entries.get(n);r!==void 0&&s?.pid!==r&&(n=`${e}#superseded:${r}`,s=this.entries.get(n),s?.pid!==r)||s&&(this.entries.delete(n),this.runtimeProcesses.delete(n),this.persist(),s?.type==="sdk"&&nc())}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let n=Date.parse(e.startedAt),s=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(s)?0:s)})}getBySession(e){let r=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}pruneDeadEntries(){this.initialize();let e=0,r=0;for(let[n,s]of this.entries)Y(s.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,s.type==="sdk"&&(r+=1));e>0&&this.persist();for(let n=0;n<r;n+=1)nc();return e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;f.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:n,pids:r.map(a=>a.pid)});let s=r.filter(a=>Y(a.pid)),o=new Map(s.map(a=>[a.pid,Ye(a.pid)]));for(let a of s)try{process.platform==="win32"?await we(a.pid,{expectedStartToken:o.get(a.pid)??null}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGTERM"):process.kill(a.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&f.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},c):f.warn("SYSTEM",`Failed to SIGTERM session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(c)})}await Xs(s,nb);let i=s.filter(a=>Y(a.pid));for(let a of i){f.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,pgid:a.pgid,sessionId:n});let c=o.get(a.pid)??null;if(!Ce(a.pid,c)){f.warn("SYSTEM","Skipping SIGKILL: session process PID was reused during the grace window",{pid:a.pid,sessionId:n});continue}try{process.platform==="win32"?await we(a.pid,{expectedStartToken:c}):typeof a.pgid=="number"?process.kill(-a.pgid,"SIGKILL"):process.kill(a.pid,"SIGKILL")}catch(u){u instanceof Error?u.code!=="ESRCH"&&f.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid,pgid:a.pgid},u):f.warn("SYSTEM",`Failed to SIGKILL session process PID ${a.pid} (non-Error)`,{pid:a.pid,pgid:a.pgid,error:String(u)})}}if(i.length>0){let a=Date.now()+sb;for(;Date.now()<a&&i.filter(u=>Y(u.pid)).length!==0;)await new Promise(u=>setTimeout(u,100))}for(let a of r)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);this.persist();for(let a of r)a.type==="sdk"&&nc();return f.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:n,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};try{U(this.registryPath,e),this.persistDegraded=!1}catch(r){this.reportPersistFailure(r)}}reportPersistFailure(e){if(this.persistDegraded)return;this.persistDegraded=!0;let r=e instanceof Error?e:new Error(String(e));f.warn("SYSTEM","Failed to persist supervisor registry; keeping it in memory",{path:this.registryPath},r);try{ib?.({errorCategory:r.code??"unknown"})}catch{}}},rc=null;qx=180*1e3,cb=[]});async function Mf(t){let e=t.currentPid??process.pid,r=t.pidFilePath??ub,n=t.registry.getAll(),s=[...n].filter(c=>c.pid!==e).sort((c,u)=>Date.parse(u.startedAt)-Date.parse(c.startedAt)),o=new Map,i=new Map;for(let c of s){if(!Y(c.pid)){t.registry.unregister(c.id);continue}i.set(c.id,Ye(c.pid)),o.set(c.id,await js(c.pid));try{await Pf(c,"SIGTERM")}catch(u){u instanceof Error?f.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:c.pid,pgid:c.pgid,type:c.type},u):f.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(u)})}}await Xs(s,5e3);let a=s.filter(c=>Y(c.pid)||(o.get(c.id)??[]).some(u=>Y(u.pid)));for(let c of a){let u=Ce(c.pid,i.get(c.id)??null);u||f.warn("SYSTEM","Skipping tree-kill: root PID was reused during the grace window",{pid:c.pid,type:c.type});try{u&&await Pf(c,"SIGKILL")}catch(l){l instanceof Error?f.debug("SYSTEM","Failed to force kill child process",{pid:c.pid,pgid:c.pgid,type:c.type},l):f.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:c.pid,pgid:c.pgid,type:c.type,error:String(l)})}finally{lb(o.get(c.id)??[],c.pid)}}await Xs(a,1e3);for(let c of s)t.registry.unregister(c.id);for(let c of n.filter(u=>u.pid===e))t.registry.unregister(c.id);xf(r,e),t.registry.pruneDeadEntries()}function xf(t,e,r=!1){if(!(0,br.existsSync)(t))return;let n=null;try{let i=JSON.parse((0,br.readFileSync)(t,"utf-8"));n=typeof i.pid=="number"?i.pid:null}catch(i){f.debug("SYSTEM","PID file unreadable \u2014 leaving it (cannot prove ownership)",{pidFilePath:t,error:i instanceof Error?i.message:String(i)});return}let s=e!==null&&n===e,o=n===null||!Y(n);if(!s&&!(r&&o)){f.debug("SYSTEM","PID file not owned by this process \u2014 leaving it for its owner (restart successor?)",{pidFilePath:t,recordedPid:n,currentPid:e});return}try{(0,br.rmSync)(t,{force:!0})}catch(i){i instanceof Error?f.debug("SYSTEM","Failed to remove PID file",{pidFilePath:t},i):f.warn("SYSTEM","Failed to remove PID file (non-Error)",{pidFilePath:t,error:String(i)})}}function lb(t,e){for(let{pid:r,startToken:n}of t)if(!(r===e||!Y(r))){if(!Ce(r,n)){f.debug("SYSTEM","Skipping reap: PID was recycled during the grace window",{pid:r,rootPid:e});continue}try{process.kill(r,"SIGKILL"),f.debug("SYSTEM","Reaped orphaned descendant during shutdown cascade",{pid:r,rootPid:e})}catch(s){let o=s instanceof Error?s.code:void 0;o!=="ESRCH"&&f.warn("SYSTEM","Failed to reap orphaned descendant during shutdown cascade",{pid:r,rootPid:e,errno:o})}}}async function Pf(t,e){let{pid:r,pgid:n}=t;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}if(e==="SIGKILL"){await we(r,{signalMode:"immediate"});return}try{process.kill(r,e)}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}return}await we(r)}var br,ub,oc=E(()=>{"use strict";br=require("fs");O();mt();C();yr();ub=K.workerPid()});function db(){let e=Gs().pruneDeadEntries();e>0&&f.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function Nf(){wr===null&&(wr=setInterval(db,kf),wr.unref(),f.debug("SYSTEM","Health checker started",{intervalMs:kf}))}function Cf(){wr!==null&&(clearInterval(wr),wr=null,f.debug("SYSTEM","Health checker stopped"))}var kf,wr,Df=E(()=>{"use strict";O();mt();kf=3e4,wr=null});function gb(t){let e=[];for(let r of t.split(`
|
|
18
|
+
`)){let n=r.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);n&&e.push({pid:Number.parseInt(n[1],10),ppid:Number.parseInt(n[2],10),command:n[3].trim()})}return e}async function mb(){let t=await fb("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return gb(t.stdout)}function hb(t,e){let r=t.filter(i=>pb.test(i.command)&&i.pid!==e.selfPid),n=new Set(r.map(i=>i.pid)),s=r.filter(i=>!n.has(i.ppid)),o=s.filter(i=>i.ppid===e.selfPid?!1:i.ppid===1?!0:!e.isAlive(i.ppid));return{matched:r,roots:s,orphans:o}}async function Uf(t={}){let e=t.platform??process.platform,r={matched:0,trees:0,orphans:0,killed:0,failed:0,unregistered:0,skipped:null};if(e==="win32")return r.skipped="windows",r;let n=t.readTable??mb,s=t.isAlive??Y,o=t.killTree??(g=>we(g,{signalMode:"graceful"})),i=t.selfPid??process.pid,a;try{a=await n()}catch(g){return f.warn("PROCESS","Orphaned chroma-mcp sweep skipped: cannot read the process table",{error:g instanceof Error?g.message:String(g)}),r.skipped="unreadable",r}let{matched:c,roots:u,orphans:l}=hb(a,{isAlive:s,selfPid:i});if(r.matched=c.length,r.trees=u.length,r.orphans=l.length,l.length===0)return f.debug("PROCESS","No orphaned chroma-mcp trees found",{matched:r.matched,trees:r.trees}),r;f.warn("PROCESS","Reaping orphaned chroma-mcp trees left by dead workers",{orphans:l.length,roots:l.map(g=>g.pid)});let d=new Set,p=8;for(let g=0;g<l.length;g+=p){let m=l.slice(g,g+p);(await Promise.allSettled(m.map(_=>o(_.pid)))).forEach((_,S)=>{let b=m[S];_.status==="fulfilled"?(r.killed+=1,d.add(b.pid)):(r.failed+=1,f.warn("PROCESS","Failed to reap an orphaned chroma-mcp tree",{pid:b.pid,ppid:b.ppid,error:_.reason instanceof Error?_.reason.message:String(_.reason)}))})}if(t.registry)for(let g of t.registry.getAll())g.type==="chroma"&&d.has(g.pid)&&(t.registry.unregister(g.id),r.unregistered+=1);return f.info("PROCESS","Orphaned chroma-mcp sweep finished",{orphans:r.orphans,killed:r.killed,failed:r.failed,unregistered:r.unregistered}),r}var Ff,Lf,fb,pb,$f=E(()=>{"use strict";Ff=require("child_process"),Lf=require("util");O();yr();mt();fb=(0,Lf.promisify)(Ff.execFile),pb=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/});function Bf(t={}){let e=t.pidFilePath??_b;if(!(0,Yt.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,Yt.readFileSync)(e,"utf-8"))}catch(s){return s instanceof Error?f.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},s):f.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(s)}),(0,Yt.rmSync)(e,{force:!0}),"invalid"}return Ks(r)&&r?((t.logAlive??!0)&&f.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(t.removeStale===!1||(f.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:r?.pid,port:r?.port,startedAt:r?.startedAt}),(0,Yt.rmSync)(e,{force:!0})),"stale")}var Yt,_b,ic,hk,hn=E(()=>{"use strict";Yt=require("fs");O();mt();oc();Df();$f();C();mt();_b=K.workerPid(),ic=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(),Bf({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,Uf({registry:this.registry}).catch(r=>{f.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),Nf()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){f.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,f.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(s){s instanceof Error?f.error("SYSTEM","Error during shutdown",{},s):f.error("SYSTEM","Error during shutdown (non-Error)",{error:String(s)});try{await this.stop()}catch(o){o instanceof Error?f.debug("SYSTEM","Supervisor shutdown fallback failed",{},o):f.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(o)})}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{f.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}Cf(),this.stopPromise=Mf({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,n){this.registry.register(e,r,n)}unregisterProcess(e,r){this.registry.unregister(e,r)}getRegistry(){return this.registry}},hk=new ic(Gs())});function Wf(t,e){if(!(0,zs.existsSync)(t))return e;try{return jt((0,zs.readFileSync)(t,"utf-8"))}catch(r){throw new Error(`Corrupt JSON file, refusing to overwrite: ${t}: ${r instanceof Error?r.message:String(r)}`)}}var zs,jf=E(()=>{"use strict";zs=require("fs");se()});function Eb(t){let e=t.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function Sb(t,e){if(Eb(t))return{enabled:!1,source:"DO_NOT_TRACK"};let r=t.MEMINDEX_TELEMETRY?.toLowerCase();return r==="0"||r==="false"||r==="off"?{enabled:!1,source:"env"}:t.MEMINDEX_TELEMETRY_KEY?r==="1"||r==="true"||r==="on"?{enabled:!0,source:"env"}:e?.enabled===!0?{enabled:!0,source:"config"}:e?.enabled===!1?{enabled:!1,source:"config"}:{enabled:!1,source:"default"}:{enabled:!1,source:"no-key"}}function Ys(t,e){return Sb(t,e).enabled}function Kf(t){let e=t.MEMINDEX_TELEMETRY_ERRORS?.toLowerCase();return!(e==="0"||e==="false"||e==="off")}function yb(){return(0,ac.join)(N(),Xf)}function _n(){let t;try{t=Wf(yb(),null)}catch(e){let r=e instanceof Error?e:new Error(String(e));return f.warn("SYSTEM","Telemetry: corrupt telemetry.json; treating as no recorded consent",void 0,r),null}return!t||typeof t!="object"||typeof t.installId!="string"||t.enabled!==void 0&&typeof t.enabled!="boolean"?null:{enabled:t.enabled,installId:t.installId,decidedAt:typeof t.decidedAt=="string"?t.decidedAt:""}}function bb(t){let e=N();(0,Vs.mkdirSync)(e,{recursive:!0}),(0,Vs.writeFileSync)((0,ac.join)(e,Xf),JSON.stringify(t,null,2)+`
|
|
19
|
+
`)}function qs(){let t=_n();if(t?.installId)return t.installId;let e=(0,Hf.randomUUID)();return bb({installId:e,decidedAt:""}),e}var ac,Vs,Hf,Xf,cc=E(()=>{"use strict";ac=require("path"),Vs=require("fs"),Hf=require("crypto");C();jf();O();Xf="telemetry.json"});function Yf(t){try{if(typeof t!="string"){if(t==null)return"";try{t=String(t)}catch(r){let n=r instanceof Error?r:new Error(String(r));return f.warn("SYSTEM","error-scrub: String() coercion of non-string input failed",void 0,n),""}}let e=t;return e.length>zf?e.slice(0,zf):e}catch{return""}}function uc(t){if(typeof t!="string"||t.length===0)return t??"";let e="";try{e=Vf.default.homedir()||""}catch(n){let s=n instanceof Error?n:new Error(String(n));f.warn("SYSTEM","error-scrub: os.homedir() failed; skipping home-dir redaction",void 0,s),e=""}if(!e)return t;let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");try{return t.replace(new RegExp(r,"g"),"~")}catch(n){let s=n instanceof Error?n:new Error(String(n));return f.warn("SYSTEM","error-scrub: home-dir RegExp replace failed; using split/join fallback",void 0,s),t.split(e).join("~")}}function lc(t){return typeof t!="string"||t.length===0?t??"":t.replace(/(?<![~\w])\/(?:[^\s/:"'()]+\/)+([^\s/:"'()]+)/g,"$1").replace(/[A-Za-z]:\\(?:[^\s\\:"'()]+\\)*([^\s\\:"'()]+)/g,"$1").replace(/\\\\[^\s\\:"'()]+(?:\\[^\s\\:"'()]+)*\\([^\s\\:"'()]+)/g,"$1")}function wb(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\b[A-Za-z][A-Za-z0-9+.-]*:\/\/[^\s"'()]+/g,e=>/^https?:\/\/hooks\.slack\.com\/services\//i.test(e)?e.replace(/^(https?:\/\/hooks\.slack\.com\/services\/)[^\s"'()]+/i,`$1${Te}`):e.replace(/[?#].*$/,"").replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/@\s]+@/,`$1${Te}@`))}function Tb(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\?[^\s"'()]*/g,"")}function Ib(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\b(?:access[_-]?token|api[_-]?key|auth(?:orization)?|secret|password|passwd|jwt|session[_-]?id|token)=[^\s"'&]+/gi,e=>{let r=e.indexOf("=");return`${e.slice(0,r+1)}${Te}`})}function vb(t){if(typeof t!="string"||t.length===0)return t??"";let e=t;return e=e.replace(/[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}/g,Te),e=e.replace(/\b[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\b/g,Te),e=e.replace(/\b(?:sk|pk|rk|ak|phc|phx|ph|ghp|gho|ghs|xox[bpasr])[-_][A-Za-z0-9_-]{8,512}\b/gi,Te),e=e.replace(/\bBearer\s+[A-Za-z0-9._-]{8,512}\b/gi,Te),e=e.replace(/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g,Te),e=e.replace(/\b[0-9a-fA-F]{24,4096}\b/g,Te),e=e.replace(/\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/g,Te),e=e.replace(/\b(?=[A-Za-z0-9+/_-]{0,4096}\d)[A-Za-z0-9+/_-]{32,4096}={0,2}\b/g,Te),e=e.replace(/\b(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}\b/g,Te),e}function Rb(t){return typeof t!="string"||t.length===0?t??"":t.replace(/[ \t\f\v]+/g," ").replace(/ *\n */g,`
|
|
20
|
+
`).trim()}function dc(t){let e=Yf(t);return e.length===0?"":(e=uc(e),e=wb(e),e=lc(e),e=Tb(e),e=Ib(e),e=vb(e),e)}function qf(t){try{let e=Rb(dc(Yf(t)));return e.length>Gf?e.slice(0,Gf):e}catch(e){let r=e instanceof Error?e:new Error(String(e));return f.warn("SYSTEM","error-scrub: message scrub failed; emitting empty message",void 0,r),""}}function Jf(t){return(typeof t=="string"?t:"").replace(/\[REDACTED\]/g,"\xA7").replace(/'[^']*'/g,"'\xA7'").replace(/"[^"]*"/g,'"\xA7"').replace(/\b\d+\b/g,"\xA7").replace(/[ \t]+/g," ").trim().slice(0,200)}var Vf,Gf,zf,Te,fc=E(()=>{"use strict";Vf=be(require("os"),1);O();Gf=500,zf=8192,Te="[REDACTED]"});function Ob(t,e){if(!(!t||typeof t!="object"))for(let r of Object.keys(t)){if(!Ab.has(r))continue;let n=t[r];if(typeof n=="string"){let s=n.length>Qf?n.slice(0,Qf):n;e[r]=dc(s)}else(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(e[r]=n)}}function Js(t){let e={};try{Ob(t,e)}catch{}return e}var Ab,Qf,pc=E(()=>{"use strict";fc();Ab=new Set(["version","os","os_version","is_wsl","arch","runtime","runtime_version","node_version","duration_ms","outcome","error_category","locale","is_ci","endpoint","ide","provider","runtime_mode","trigger","count","has_summary","is_update","phase","install_method","interactive","provider_source","bun_version","uv_version","claude_code_version","observation_count","session_count","timeline_depth_days","has_session_summary","obs_type_bugfix","obs_type_discovery","obs_type_decision","obs_type_refactor","obs_type_other","tokens_injected","tokens_saved_vs_naive","mode","search_strategy","observation_type","hook","compression_ms","tokens_input","tokens_output","compression_ratio","model","cost_usd","endpoint_class","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs","result_count","chroma_available","fallback_reason","invalid_output_class","consecutive_invalid_outputs","respawn_triggered","abort_reason","previous_shutdown","previous_uptime_seconds","uptime_seconds","shutdown_reason","process_rss_mb","heap_used_mb","hook_type","error_mode","consecutive_failures","threshold_tripped","limit_window","overage_status","is_using_overage","resets_in_minutes","discovery_tokens","read_tokens","summary_count","prompt_count","project_count","backfilled","first_active_date","session_completed_count","session_failed_count","sessions_claude_count","sessions_codex_count","sessions_gemini_count","sessions_other_platform_count","subagent_obs_count","total_tokens_input","total_tokens_output","total_cost_usd","avg_duration_ms","avg_compression_ms","outcomes_ok","outcomes_error","outcomes_aborted","outcomes_aborted_deadline_exceeded","outcomes_invalid_output","top_model","top_abort_reason","observed_model","observed_billing","window_start_ts","rollup_reason","window_seq","total_tokens","avg_tokens","skill_id","skill_source","skill_trigger","observations_created","total_observations_injected","total_tokens_saved_vs_naive"]),Qf=200});function Qs(){return process.env.MEMINDEX_TELEMETRY_KEY??""}function Zs(){return process.env.MEMINDEX_TELEMETRY_HOST||Mb}function eo(t){let e={};for(let r of xb)t[r]!==void 0&&(e[r]=t[r]);return e}function kb(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||gc.default.release().toLowerCase().includes("microsoft")}catch(t){let e=t instanceof Error?t:new Error(String(t));return f.warn("SYSTEM","Telemetry: WSL detection failed; reporting is_wsl=false",void 0,e),!1}}function to(){return{version:Pb,os:process.platform,os_version:gc.default.release(),is_wsl:kb(),arch:process.arch,runtime:process.versions.bun?"bun":"node",runtime_version:process.versions.bun??process.versions.node,node_version:process.versions.node,is_ci:!!process.env.CI,locale:Intl.DateTimeFormat().resolvedOptions().locale}}var gc,Pb,Mb,xb,mc=E(()=>{"use strict";gc=be(require("os"),1);O();Pb="1.1.0",Mb="https://us.i.posthog.com";xb=["version","os","os_version","is_wsl","arch","runtime","locale","ide","provider","runtime_mode","install_method","claude_code_version","first_active_date","db_observation_count","db_session_count","db_summary_count","db_project_count","db_size_mb","install_age_days","obs_count_7d","obs_count_30d","days_since_last_obs"]});async function Zf(t,e,r){try{if(!Ys(process.env,_n()))return;let n=Js({...to(),...e??{}});if(r?.person?n.$set=eo(n):n.$process_person_profile=!1,process.env.MEMINDEX_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:t,properties:n})+`
|
|
21
|
+
`);return}let s=Qs(),o=new AbortController,i=setTimeout(()=>o.abort(),Nb);try{await Cb(s,t,n,o.signal)}finally{clearTimeout(i)}}catch{}}async function Cb(t,e,r,n){await fetch(`${Zs()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:t,event:e,distinct_id:qs(),properties:r}),signal:n})}var Nb,ep=E(()=>{"use strict";cc();pc();mc();Nb=2e3});var tp=E(()=>{"use strict";O()});var rp=E(()=>{"use strict";O();tp()});function no(t){return t.error?.name==="ETIMEDOUT"}function so(t,e,r=np){let n=`git -C ${t} ${e.join(" ")}`,s=Date.now();return new Promise(o=>{let i=!1,a=!1,c="",u="",l=g=>{if(i)return;i=!0,clearTimeout(p);let m=Date.now()-s;m>1e3&&f.debug("GIT",`Slow git operation: ${n} took ${m}ms`),o(g)},d=(0,ro.spawn)("git",["-C",t,...e],{stdio:["ignore","pipe","pipe"],windowsHide:!0}),p=setTimeout(()=>{a=!0,d.kill("SIGTERM"),d.stdout?.destroy(),d.stderr?.destroy();let g=Object.assign(new Error(`git timed out after ${r}ms`),{name:"ETIMEDOUT"});f.warn("GIT",`Git operation failed: ${n}`,{error:g.message,timedOut:!0}),l({status:null,stdout:"",error:g})},r);d.stdout?.setEncoding("utf8"),d.stderr?.setEncoding("utf8"),d.stdout?.on("data",g=>{c+=g}),d.stderr?.on("data",g=>{u+=g}),d.once("error",g=>{f.warn("GIT",`Git operation failed: ${n}`,{error:g.message,timedOut:!1}),l({status:null,stdout:"",error:g})}),d.once("close",(g,m)=>{if(!a){if(g!==0){f.debug("GIT",`Git returned non-zero exit code ${g??m}: ${n}`,{stderr:u.trim()}),l({status:g,stdout:"",error:void 0});return}l({status:g,stdout:c.trim(),error:void 0})}})})}function hc(t,e,r=np){let n=(0,ro.spawnSync)("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:Math.min(r,Db),windowsHide:!0});return n.error?{status:null,stdout:"",error:n.error}:n.status!==0?{status:n.status,stdout:"",error:void 0}:{status:0,stdout:(n.stdout??"").trim(),error:void 0}}var ro,np,Db,_c=E(()=>{"use strict";ro=require("child_process");O();np=5e3,Db=5e3});function sp(t){let e=Rt.default.join(t,".git"),r;try{r=(0,oo.statSync)(e)}catch(c){return c instanceof Error&&c.code!=="ENOENT"&&f.warn("GIT","Unexpected error checking .git",{error:c instanceof Error?c.message:String(c)}),En}if(!r.isFile())return En;let n;try{n=(0,oo.readFileSync)(e,"utf-8").trim()}catch(c){return f.warn("GIT","Failed to read .git file",{error:c instanceof Error?c.message:String(c)}),En}let s=n.match(/^gitdir:\s*(.+)$/);if(!s)return En;let o=Rt.default.resolve(Rt.default.dirname(e),s[1]),i=o.match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(i){let c=i[1];return{isWorktree:!0,isSubmodule:!1,worktreeName:Rt.default.basename(t),parentRepoPath:c,parentProjectName:Rt.default.basename(c)}}let a=o.match(/^(.+)[/\\]\.git[/\\]modules[/\\](.+)$/);if(a){let c=a[1];return{isWorktree:!1,isSubmodule:!0,worktreeName:Rt.default.basename(t),parentRepoPath:c,parentProjectName:Rt.default.basename(c)}}return En}var oo,Rt,En,op=E(()=>{"use strict";oo=require("fs"),Rt=be(require("path"),1);O();En={isWorktree:!1,isSubmodule:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null}});function ip(t){let e=he(t.replace(/\\/g,"/"));e=e.replace(/\\/g,"/");let r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return r=r.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<<GLOBSTAR>>>/g,".*"),new RegExp(`^${r}$`)}function Sc(t,e){if(!e.length)return!1;let r=t.replace(/\\/g,"/"),n=(0,Ec.basename)(r);for(let s of e){let o=s.trim();if(o)try{let i=ip(o);if(i.test(r)||i.test(n))return!0}catch(i){f.warn("PROJECT_NAME","Invalid glob pattern",{pattern:o,error:i instanceof Error?i.message:String(i)});continue}}return!1}function io(t,e){if(!e||!e.trim())return!1;let r=t.replace(/\\/g,"/"),n=(0,Ec.basename)(r),s=e.split(",").map(o=>o.trim()).filter(Boolean);for(let o of s)try{let i=ip(o);if(i.test(r)||i.test(n))return!0}catch(i){f.warn("PROJECT_NAME","Invalid exclusion pattern",{pattern:o,error:i instanceof Error?i.message:String(i)});continue}return!1}var Ec,Sn=E(()=>{"use strict";Ec=require("path");Wt();O()});function cp(t){let e=t;if(typeof e=="string"){if(!e.trim())return[];try{e=JSON.parse(e)}catch(n){return f.warn("PROJECT_NAME","MEMINDEX_PROJECT_ENVIRONMENTS is not valid JSON; ignoring it",{error:n instanceof Error?n.message:String(n)}),[]}}if(!Array.isArray(e))return e!=null&&f.warn("PROJECT_NAME","MEMINDEX_PROJECT_ENVIRONMENTS must be an array; ignoring it",{}),[];let r=[];for(let n of e){let s=typeof n?.name=="string"?n.name.trim():"",o=Array.isArray(n?.patterns)?n.patterns.filter(i=>typeof i=="string"&&i.trim()!==""):[];if(!s||o.length===0){f.warn("PROJECT_NAME","Ignoring a project environment without a name or patterns",{name:s});continue}r.push({name:s,patterns:o})}return r}function Fb(t){try{return(0,ap.realpathSync)(t)}catch{return t}}function yc(t,e){if(e.length===0)return null;let r=[...new Set([t,Fb(t)])].flatMap(n=>[n,`${n.replace(/[\\/]+$/,"")}/`]);for(let n of e)if(r.some(s=>Sc(s,n.patterns)))return n.name;return null}var ap,up=E(()=>{"use strict";ap=require("fs");Sn();O()});function fp(t){let e=process.env[Lb]?.trim();return e||(!t||t.trim()===""?null:t)}function pp(t){return gp(t,hc(t,["rev-parse","--show-toplevel"]))}async function Bb(t){let e=Date.now(),r=Tr.get(t);if(r&&e-r.at<Ub)return(await r.answer).root;Tr.size>=$b&&Tr.clear();let n=so(t,["rev-parse","--show-toplevel"]).then(a=>({root:gp(t,a),kept:!no(a)})),s={at:e,answer:n};Tr.set(t,s);let{root:o,kept:i}=await n;return!i&&Tr.get(t)===s&&Tr.delete(t),o}function gp(t,e){return e.status===0&&e.stdout?e.stdout:(f.debug("PROJECT_NAME","git rev-parse failed, falling back to non-git root",{dir:t},e.error),null)}function mp(t){try{return(0,vr.realpathSync)(t)}catch{return t}}function Hb(t,e){let r=ue.default.relative(e,t);return r===""||!r.startsWith("..")&&!ue.default.isAbsolute(r)}function Xb(){return[(0,uo.homedir)(),(0,uo.tmpdir)(),lt].flatMap(t=>{let e=ue.default.resolve(t);return[e,mp(e)]})}function hp(t){let e=Xb(),r=ue.default.resolve(t);if([ue.default.resolve(lt),mp(ue.default.resolve(lt))].some(s=>Hb(r,s)))return null;for(let s=0;s<jb;s++){if(e.includes(r))return null;let o=ue.default.dirname(r);if(o===r)return null;if(Wb.some(i=>(0,vr.existsSync)(ue.default.join(r,i))))return r;r=o}return null}function bc(t,e){let r=ue.default.basename(e);if(r===""){if(process.platform==="win32"){let s=t.match(/^([A-Z]):\\/i);if(s){let i=`drive-${s[1].toUpperCase()}`;return f.info("PROJECT_NAME","Drive root detected",{cwd:t,projectName:i}),i}}return f.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:t}),wc}return r}function lp(){try{return(0,vr.statSync)(_e).mtimeMs}catch{return-1}}function _p(){let t=lp();if(t===-1)return V.getAllDefaults();if(ao&&ao.mtimeMs===t)return ao.settings;let e=V.loadFromFile(_e);return ao={mtimeMs:lp(),settings:e},e}function Ep(){let t=process.env[Kb]??_p().MEMINDEX_PROJECT_NAME_SOURCE;return String(t??"path").trim().toLowerCase()==="git-remote"}function Sp(){let t=process.env[Gb]??_p().MEMINDEX_PROJECT_ENVIRONMENTS;return(!co||co.raw!==t)&&(co={raw:t,environments:cp(t)}),co.environments}function zb(t){let e=(t??"").trim();if(!e||/^file:/i.test(e)||e.startsWith("/")||e.startsWith(".")||e.startsWith("~")||e.startsWith("\\\\")||/^[a-z]:[\\/]/i.test(e))return null;let n=e.replace(/\/+$/,"").replace(/\.git$/i,""),s=n.match(/^[a-z][a-z0-9+.-]*:\/\/[^/]+\/(.+)$/i),o=s?null:n.match(/^(?:[^/@\s]+@)?[^:/\s]+:(?!\/\/)(.+)$/),i=s?.[1]??o?.[1];if(!i)return null;let a=i.split("/").filter(c=>c&&c!=="_git");return a.length>=2?a.slice(-2).join("/"):a.length===1?a[0]:null}function yp(t,e){return e.status===0&&e.stdout?zb(e.stdout):(f.debug("PROJECT_NAME","No usable origin remote, keeping the path-based name",{repoRoot:t},e.error),null)}function bp(t){return Ep()?(Ir.has(t)||Ir.set(t,yp(t,hc(t,["remote","get-url","origin"]))),Ir.get(t)??null):null}async function Vb(t){if(!Ep())return null;if(!Ir.has(t)){let e=await so(t,["remote","get-url","origin"]);if(no(e))return null;Ir.set(t,yp(t,e))}return Ir.get(t)??null}function Yb(t,e=process.platform){if(!t||t.trim()==="")return f.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),wc;let r=he(t,e),n=yc(r,Sp());if(n)return n;let s=pp(r),o=s?bp(s):null;if(o)return o;let i=s??hp(r)??r;return bc(t,i)}function wp(t,e){return e===t?t:`${t}/${e}`}function qb(t,e){if(!t.isSubmodule||!t.parentRepoPath)return null;let r=ue.default.relative(t.parentRepoPath,e);return!r||r.startsWith("..")||ue.default.isAbsolute(r)?null:r.split(ue.default.sep).join("/")}function lo(t,e=process.platform){if(!t||t.trim()==="")return Tp(t,e);let r=he(t,e),n=pp(r),s=n?bp(n):null;return Ip(t,r,n,s)}async function yn(t,e=process.platform){if(!t||t.trim()==="")return Tp(t,e);let r=he(t,e),n=await Bb(r),s=n?await Vb(n):null;return Ip(t,r,n,s)}function Tp(t,e){let r=Yb(t,e);return{primary:r,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[r],keySource:"path"}}function Ip(t,e,r,n){let s=Jb(t,e,r),o=n?dp(s,n,"git-remote"):s,i=yc(e,Sp());return i?dp(o,i,"environment"):o}function dp(t,e,r){return{primary:e,parent:null,isWorktree:t.isWorktree,isSubmodule:t.isSubmodule,allProjects:[...t.allProjects.filter(n=>n!==e),e],keySource:r}}function Jb(t,e,r){let n=r?null:hp(e),s=bc(t,r??n??e),o=r??e,i=sp(o);if((i.isWorktree||i.isSubmodule)&&i.parentProjectName){let a=i.parentProjectName,c,u;return i.isSubmodule?(c=`${a}/${qb(i,o)??s}`,u=s!==a?[s]:[]):(c=wp(a,s),u=c===a?[`${a}/${s}`]:[]),{primary:c,parent:a,isWorktree:i.isWorktree,isSubmodule:i.isSubmodule,allProjects:[...new Set([a,...u,c])].filter(l=>l!==c).concat(c),keySource:"path"}}if(n&&ue.default.resolve(n)!==ue.default.resolve(e)){let a=bc(t,e);if(a!==s&&a!==wc)return{primary:s,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[a,s],keySource:"path"}}return{primary:s,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[s],keySource:"path"}}var ue,vr,uo,Lb,wc,Ub,$b,Tr,Wb,jb,Kb,ao,Gb,co,Ir,qt=E(()=>{"use strict";ue=be(require("path"),1),vr=require("fs"),uo=require("os");Wt();C();dt();O();_c();op();up();Lb="CLAUDE_PROJECT_DIR",wc="unknown-project";Ub=3e4,$b=500,Tr=new Map;Wb=[".memindex-project",".memindex.json"],jb=64;Kb="MEMINDEX_PROJECT_NAME_SOURCE",ao=null;Gb="MEMINDEX_PROJECT_ENVIRONMENTS",co=null;Ir=new Map});function Zb(t){return t===void 0?vp:Math.max(1,Math.min(vp,t))}function tw(t){try{return(0,Ee.realpathSync)(t)}catch{return null}}function Tc(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function rw(t,e){let r=e==="win32"?"where.exe":"which",n=[t],s;try{s=(0,fo.execFileSync)(r,n,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",windowsHide:!0})}catch(i){return i instanceof Error?f.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r,args:n},i):f.debug("SYSTEM",`Binary lookup failed for ${t}`,{command:r,args:n},new Error(String(i))),null}return s.split(/\r?\n/).map(i=>i.trim()).find(i=>i.length>0)||null}function po(t={}){let e=Object.keys(t).length===0;if(e&&Ic!==void 0)return Ic;let r=nw(t);return e&&r!==null&&(Ic=r),r}function Rp(t,e){let r=t?.trim();return r?e==="win32"?[ge.default.join(r,"bin","bun.exe"),ge.default.join(r,"bin","bun"),ge.default.join(r,"bun.exe")]:[ge.default.join(r,"bin","bun"),ge.default.join(r,"bun")]:[]}function nw(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(Tc(r))return r;let n=t.env??process.env,s=t.homeDirectory??(0,vc.homedir)(),o=t.pathExists??Ee.existsSync,i=t.lookupInPath??rw,a=t.realpath??tw,c=e==="win32"?[n.BUN,n.BUN_PATH,...Rp(n.BUN_INSTALL,e),ge.default.join(s,".bun","bin","bun.exe"),ge.default.join(s,".bun","bin","bun"),n.USERPROFILE?ge.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?ge.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?ge.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0,n.npm_config_prefix?ge.default.join(n.npm_config_prefix,"bun.exe"):void 0]:[n.BUN,n.BUN_PATH,...Rp(n.BUN_INSTALL,e),ge.default.join(s,".bun","bin","bun"),"/usr/local/bin/bun","/opt/homebrew/bin/bun","/home/linuxbrew/.linuxbrew/bin/bun","/usr/bin/bun","/snap/bin/bun",n.npm_config_prefix?ge.default.join(n.npm_config_prefix,"bin","bun"):void 0];for(let d of c){let p=d?.trim();if(p&&(Tc(p)&&o(p)||p.toLowerCase()==="bun"))return p}let u=i("bun",e)?.trim();if(!u||!Tc(u))return null;let l=a(u)??u;return o(l)?l:null}function Rc(){let t=K.dataDir();return(0,Ee.mkdirSync)(t,{recursive:!0}),t}function sw(t,e,r=Rc()){let n=s=>s.replace(/'/g,"''");return`Start-Process -FilePath '${n(t)}' -ArgumentList @('"${n(e)}"','--daemon') -WorkingDirectory '${n(r)}' -WindowStyle Hidden`}function ow(t=process.env){let e=t.SystemRoot||t.SYSTEMROOT;return e?`${e}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`:"powershell.exe"}function iw(t,e,r=Rc()){return["-NoProfile","-WindowStyle","Hidden","-EncodedCommand",Buffer.from(sw(t,e,r),"utf16le").toString("base64")]}function go(t,e,r,n=process.platform,s){if(n==="win32"){let l=ow(r),d=iw(t,e),p=Zb(s);try{let g=(0,fo.spawnSync)(l,d,{stdio:"ignore",windowsHide:!0,env:r,timeout:p,killSignal:"SIGTERM"});if(g.error)throw g.error;if(g.signal)throw new Error(`powershell Start-Process killed by signal=${g.signal} after ${p}ms`);if(g.status!==0)throw new Error(`powershell Start-Process exited ${g.status??"null"}`);return 0}catch(g){let m=g instanceof Error?g:new Error(String(g));f.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:t,powershell:l},m);return}}let o="/usr/bin/setsid",i=(0,Ee.existsSync)(o),a=i?o:t,u=Ja(a,i?[t,e,"--daemon"]:[e,"--daemon"],{detached:!0,stdio:"ignore",cwd:Rc(),env:r});if(u.on("error",l=>{f.error("SYSTEM",ew,{runtimePath:t,execPath:a},l)}),u.pid!==void 0)return u.unref(),u.pid}var ge,vc,Ee,fo,vp,y0,b0,ew,Ic,Ac=E(()=>{"use strict";ge=be(require("path"),1),vc=require("os"),Ee=require("fs"),fo=require("child_process");Qa();O();mn();oc();hn();rp();qt();_c();C();xe();mt();vp=ze(Q.POWERSHELL_COMMAND);y0=K.dataDir(),b0=K.workerPid(),ew="Bun runtime not found \u2014 install from https://bun.sh and ensure it is on PATH, under ~/.bun/bin, or set BUN / BUN_PATH / BUN_INSTALL. The worker daemon requires Bun because it uses bun:sqlite."});function Ap(t){let e=t?.code;return e==="EACCES"||e==="EADDRNOTAVAIL"}var Oc,Pc=E(()=>{"use strict";Oc="Set MEMINDEX_WORKER_PORT to a port between 1024 and 65535 and MEMINDEX_WORKER_HOST to an address of this machine (127.0.0.1 by default) in memindex settings"});function Mc(){return V.loadFromFile(_e).MEMINDEX_WORKER_HOST}function Pp(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}async function Mp(t,e,r="GET",n=Jt){let s={method:r,signal:AbortSignal.timeout(Math.max(1,n))},o=await fetch(`http://${Pp(Mc())}:${t}${e}`,r==="GET"||r==="HEAD"?s:gn(s)),i="";try{i=await o.text()}catch{}return{ok:o.ok,statusCode:o.status,body:i}}async function xp(t,e=Jt){let r=Date.now()+e;if(process.platform==="win32")try{let s=await fetch(`http://${Pp(Mc())}:${t}/api/health`,{signal:AbortSignal.timeout(Math.max(1,r-Date.now()))});if(s.ok)return!0;f.debug("SYSTEM","Windows health check returned non-ok; falling through to socket probe",{port:t,status:s.status})}catch(s){s instanceof Error?f.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:t,message:s.message}):f.debug("SYSTEM","Windows health check threw; falling through to socket probe",{port:t,error:String(s)})}let n=await mo(t,Math.max(1,r-Date.now()));return n==="occupied"||n==="indeterminate"}async function mo(t,e=Jt){return(await aw(t,e)).occupancy}function aw(t,e=Jt){return e<=0?Promise.resolve({occupancy:"indeterminate"}):new Promise(r=>{let n=!1,s=!1,o=!1,i;try{i=Op.default.createServer()}catch{r({occupancy:"indeterminate"});return}let a=l=>{if(o){l?.();return}o=!0;try{i.close(l)}catch(d){l?.(d instanceof Error?d:new Error(String(d)))}},c=setTimeout(()=>{if(s)a();else try{i.close()}catch{}u({occupancy:"indeterminate"})},e),u=l=>{n||(n=!0,clearTimeout(c),r(l))};i.once("error",l=>{if(s)a();else try{i.close()}catch{}l.code==="EADDRINUSE"?u({occupancy:"occupied"}):Ap(l)?u({occupancy:"unbindable",bindErrorCode:l.code}):u({occupancy:"indeterminate"})}),i.once("listening",()=>{if(s=!0,n){a();return}try{a(l=>u({occupancy:l?"indeterminate":"free"}))}catch{u({occupancy:"indeterminate"})}});try{i.listen(t,Mc())}catch{try{i.close()}catch{}u({occupancy:"indeterminate"})}})}async function cw(t,e,r,n){let s=Date.now()+r;for(;Date.now()<s;){try{let i=s-Date.now();if((await Mp(t,e,"GET",Math.min(Jt,i))).ok)return!0}catch(i){i instanceof Error?f.debug("SYSTEM",n,{},i):f.debug("SYSTEM",n,{error:String(i)})}let o=Math.min(500,s-Date.now());o>0&&await new Promise(i=>setTimeout(i,o))}return!1}function kp(t,e=3e4){return cw(t,"/api/health",e,"Service not ready yet, will retry")}async function uw(t,e=Jt){try{let r=await Mp(t,"/api/health","GET",e);return r.ok?JSON.parse(r.body).version:null}catch{return f.debug("SYSTEM","Could not fetch worker version",{}),null}}async function Np(t,e,r=Jt){let n=e??"unknown",s=await uw(t,r);return!s||n==="unknown"?{matches:!0,pluginVersion:n,workerVersion:s}:{matches:n===s,pluginVersion:n,workerVersion:s}}var Op,Jt,ho=E(()=>{"use strict";Op=be(require("net"),1);O();dt();C();Pc();Ka();Jt=5e3});var Cp=E(()=>{"use strict";O();hn()});var Dp=E(()=>{"use strict";Ac();ho();Cp()});function Up(){return(0,_o.join)(N(),"spawn.lock")}function Fp(t){try{let e=JSON.parse((0,oe.readFileSync)(t,"utf-8"));return typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0?null:e.pid}catch{return null}}function lw(t){if(t===null)return null;try{return process.kill(t,0),!0}catch(e){return e?.code==="EPERM"}}function Eo(){let t=Up(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return(0,oe.mkdirSync)((0,_o.dirname)(t),{recursive:!0}),(0,oe.writeFileSync)(t,e,{flag:"wx"}),!0}catch(n){let s=n instanceof Error?n:new Error(String(n)),o=s.code;if(o!=="EEXIST")return f.warn("SYSTEM","Spawn lock write failed for a non-contention reason; failing open (spawning unlocked)",{lockPath:t,code:o},s),!0;if(r>0)return!1;let i;try{i=(0,oe.statSync)(t).mtimeMs}catch{continue}let a=Fp(t),c=null;if(a===null)try{c=(0,oe.readFileSync)(t,"utf-8")}catch{continue}if(Date.now()-i<=Lp&&lw(a)!==!1)return!1;let l;try{l=(0,oe.statSync)(t).mtimeMs}catch{continue}if(l!==i)return!1;if(a!==null){if(Fp(t)!==a)return!1}else try{if((0,oe.readFileSync)(t,"utf-8")!==c)return!1}catch{continue}try{(0,oe.unlinkSync)(t)}catch{return!1}}return!1}function bn(){let t=Up();try{if(JSON.parse((0,oe.readFileSync)(t,"utf-8")).pid!==process.pid)return;(0,oe.unlinkSync)(t)}catch{}}var _o,oe,Lp,W0,$p=E(()=>{"use strict";_o=require("path"),oe=require("fs");C();O();Lp=9e4,W0=Lp/3});function Bp(t){return dw.test(t.trim())}function fw(t,e){if(!t)return!1;let r=t.toLowerCase().replace(/\\/g,"/"),n=r.indexOf("--data-dir");if(n<0)return!1;let s=r.slice(n+10).trim();if(s.startsWith('"')){let i=s.indexOf('"',1);s=i<0?s.slice(1):s.slice(1,i)}let o=e.toLowerCase().replace(/\\/g,"/");return s===o||s.startsWith(o)&&s[o.length]==="/"}function yo(t,e){return e===void 0?t:Math.max(1,Math.min(t,e))}async function pw(t){try{let e=await So("powershell.exe",["-NoProfile","-NonInteractive","-Command","Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name,CommandLine,@{Name='StartToken';Expression={$_.CreationDate.ToString('yyyyMMddHHmmss.ffffff')}} | ConvertTo-Json -Compress"],{timeout:yo(3e4,t),windowsHide:!0,maxBuffer:33554432}),r=JSON.parse(e.stdout),n=Array.isArray(r)?r:r===null?[]:[r],s=[];for(let o of n){let i=typeof o.Name=="string"?o.Name.trim():"";if(!i)continue;let a=typeof o.ProcessId=="number"?o.ProcessId:Number.parseInt(String(o.ProcessId),10),c=typeof o.ParentProcessId=="number"?o.ParentProcessId:Number.parseInt(String(o.ParentProcessId),10);!Number.isInteger(a)||!Number.isInteger(c)||s.push({pid:a,ppid:c,name:i,cmdline:typeof o.CommandLine=="string"?o.CommandLine:null,startToken:typeof o.StartToken=="string"&&o.StartToken.length>0?o.StartToken:null})}return s}catch(e){return f.warn("PROCESS","Cannot enumerate the Windows process table with names \u2014 ghost-port reclaim disabled",{error:e instanceof Error?e.message:String(e)}),null}}async function gw(t,e){try{let r=await So("netstat",["-ano"],{timeout:yo(15e3,e),windowsHide:!0,maxBuffer:16777216});return Ew(r.stdout,t)}catch(r){return f.warn("PROCESS","netstat failed \u2014 ghost-port reclaim disabled for this attempt",{port:t,error:r instanceof Error?r.message:String(r)}),null}}async function mw(t,e){try{let r=await So("lsof",["-nP",`-iTCP:${t}`,"-sTCP:LISTEN","-t"],{timeout:yo(1e4,e),maxBuffer:1048576});return hw(r.stdout)}catch(r){let n=r;return n.code===1&&typeof n.stdout=="string"&&n.stdout.trim()===""?[]:(f.warn("PROCESS","lsof failed \u2014 cannot verify the worker port owner",{port:t,error:r instanceof Error?r.message:String(r)}),null)}}function hw(t){let e=new Set;for(let r of t.split(/\r?\n/)){let n=Number.parseInt(r.trim(),10);Number.isInteger(n)&&n>0&&e.add(n)}return[...e]}async function _w(t,e){try{let n=(await So("ps",["-p",String(t),"-o","command="],{timeout:yo(5e3,e)})).stdout.trim();return n.length>0?n:null}catch{return null}}function Ew(t,e){let r=new Set,n=`:${e}`;for(let s of t.split(/\r?\n/)){let o=s.trim();if(!/^TCP\b/i.test(o))continue;let i=o.split(/\s+/);if(!i[1]?.endsWith(n)||i[3]!=="LISTENING")continue;let c=Number.parseInt(i[4]??"",10);Number.isInteger(c)&&c>0&&r.add(c)}return[...r]}async function yw(t,e){let r=e.readOwnedWorker();if(r===null||r.port!==t)return null;let n=(u,l={})=>(f.info("PROCESS","Wedged-worker reclaim declined",{port:t,pid:r.pid,reason:u,...l}),{reclaimed:!1,reason:u,killedPids:[]}),s=(e.now()-Date.parse(r.startedAt))/1e3;if(!Number.isFinite(s)||s<e.minOwnerAgeSeconds)return n("owner-booting",{ageSeconds:s,minOwnerAgeSeconds:e.minOwnerAgeSeconds});for(let u=0;u<2;u++)if(u>0&&await e.sleep(Kp),await e.probeHealth(t))return n("owner-responding");let o=await e.listOwners(t);if(o===null)return n("netstat-unreadable");if(!o.includes(r.pid))return f.info("PROCESS","Wedged-worker reclaim: our worker does not own the port \u2014 deferring to the ghost-listener check",{port:t,pid:r.pid,listeners:o}),null;let i=await e.readIdentity(r.pid),a=r.startToken!==void 0&&i.startToken!==null&&i.startToken!==r.startToken;if(a||i.cmdline===null||!Sw.test(i.cmdline))return n("owner-identity-mismatch",{tokenMismatch:a,hasCmdline:i.cmdline!==null});if(!e.hasKillBudget())return n("out-of-budget");f.warn("PROCESS","Reclaiming wedged worker: past its boot grace, silent on two health probes, and still holding the port",{port:t,pid:r.pid,ageSeconds:Math.round(s)});try{await e.killTree(r.pid,{expectedStartToken:i.startToken??r.startToken??void 0,signalMode:"graceful"})}catch(u){return f.error("PROCESS","Wedged-worker reclaim tree-kill failed",{port:t,pid:r.pid},u instanceof Error?u:new Error(String(u))),{reclaimed:!1,reason:"kill-failed",killedPids:[]}}let c=await e.listOwners(t);return c!==null&&c.length===0?(f.info("PROCESS","Wedged worker reclaimed \u2014 port is free again",{port:t,killedPids:[r.pid]}),{reclaimed:!0,killedPids:[r.pid]}):(f.warn("PROCESS","Wedged-worker reclaim killed the worker but the port is still bound",{port:t,pid:r.pid,stillOwnedBy:c}),{reclaimed:!1,reason:"still-bound",killedPids:[r.pid]})}async function bw(t,e,r,n){let s=Ye(t),o=e?(await r(n))?.find(i=>i.pid===t)?.cmdline??null:await _w(t,n);return Ce(t,s)?{startToken:s,cmdline:o}:{startToken:null,cmdline:null}}async function Gp(t,e={}){let r=e.isWin32??(()=>process.platform==="win32"),n=e.now??Date.now,s=e.deadlineAt??null,o=I=>s!==null&&s-n()<I,i=()=>s===null?void 0:Math.max(1,s-n());if(o(Wp))return f.info("PROCESS","Port reclaim skipped: not enough of the hook budget is left to finish one",{port:t,remainingMs:i(),neededMs:Wp}),{reclaimed:!1,reason:"out-of-budget",killedPids:[]};let a=e.listOwners??((I,M)=>r()?gw(I,M):mw(I,M)),c=I=>a(I,i()),u=e.readTable??pw,l=()=>u(i()),d=e.killTree??((I,M)=>we(I,M)),p=e.dataDir??(()=>W),g=e.readIdentity??((I,M)=>bw(I,r(),u,M)),m=await yw(t,{listOwners:c,killTree:d,readOwnedWorker:e.readOwnedWorker??gt,probeHealth:e.probeHealth??(I=>kp(I,Xp)),readIdentity:I=>g(I,i()),minOwnerAgeSeconds:e.minOwnerAgeSeconds??Bd(),now:n,sleep:e.sleep??(I=>new Promise(M=>setTimeout(M,I))),hasKillBudget:()=>!o(xc)});if(m!==null)return m;if(!r())return{reclaimed:!1,reason:"not-supported",killedPids:[]};let h=await c(t);if(h===null)return{reclaimed:!1,reason:"netstat-unreadable",killedPids:[]};if(h.length===0)return{reclaimed:!1,reason:"no-listener",killedPids:[]};let _=await l();if(_===null)return{reclaimed:!1,reason:"table-unreadable",killedPids:[]};if(h.filter(I=>Y(I)).length>0)return{reclaimed:!1,reason:"owner-alive",killedPids:[]};let b=new Map;for(let I of _){let M=b.get(I.ppid);M?M.push(I):b.set(I.ppid,[I])}let w=new Map,T=new Set,y=I=>{for(let M of b.get(I)??[])T.has(M.pid)||(T.add(M.pid),y(M.pid),Bp(M.name)&&w.set(M.pid,M))};for(let I of h)y(I);let A=p();if(A)for(let I of _)w.has(I.pid)||Bp(I.name)&&fw(I.cmdline,A)&&w.set(I.pid,I);if(w.size===0)return f.info("PROCESS","Ghost listener owner is dead but no chroma-sidecar descendants found",{port:t,deadOwners:h,processTableRows:_.length,dataDir:A??"(unresolved)"}),{reclaimed:!1,reason:"no-chroma-descendants",killedPids:[]};f.warn("PROCESS","Reclaiming ghost listener: killing dead worker's surviving chroma sidecar chain",{port:t,deadOwners:h,targets:[...w.values()].map(I=>({pid:I.pid,name:I.name}))});let v=[];for(let I of w.values()){if(o(xc))return f.info("PROCESS","Ghost-listener reclaim stopped before a kill: the hook budget is spent",{port:t,killedPids:v}),{reclaimed:!1,reason:"out-of-budget",killedPids:v};try{await d(I.pid,{expectedStartToken:I.startToken,signalMode:"immediate"}),v.push(I.pid)}catch(M){return f.error("PROCESS","Ghost-port reclaim tree-kill failed",{port:t,pid:I.pid},M instanceof Error?M:new Error(String(M))),{reclaimed:!1,reason:"kill-failed",killedPids:v}}}let R=await c(t);return R!==null&&R.length===0?(f.info("PROCESS","Ghost listener reclaimed \u2014 port is free again",{port:t,killedPids:v}),{reclaimed:!0,killedPids:v}):(f.warn("PROCESS","Ghost-port reclaim killed the sidecar chain but the port is still bound",{port:t,killedPids:v,stillOwnedBy:R}),{reclaimed:!1,reason:"still-bound",killedPids:v})}var jp,Hp,So,dw,Sw,Xp,Kp,xc,Wp,zp=E(()=>{"use strict";jp=require("node:child_process"),Hp=require("node:util");O();yr();mt();hn();ho();Bs();xe();C();So=(0,Hp.promisify)(jp.execFile),dw=/^(uv|uvx|python|chroma-mcp)(\.exe)?$/i;Sw=/worker-service/i,Xp=1500,Kp=1e3,xc=5500,Wp=2*Xp+Kp+xc});function Vp(t){try{return(0,Rr.realpathSync)(t)}catch{return t}}function Tw(t,e){let r=At.default.relative(e,t);return r!==""&&!r.startsWith("..")&&!At.default.isAbsolute(r)}function qp(t){let e;try{let s=JSON.parse((0,Rr.readFileSync)(At.default.join(t,"package.json"),"utf-8"));e=Object.keys(s?.dependencies??{})}catch{return[]}if(e.length===0)return[];let r=At.default.join(t,"node_modules"),n=e.filter(s=>!(0,Rr.existsSync)(At.default.join(r,...s.split("/"),"package.json")));if(e.includes("zod")&&!n.includes("zod")){let s=(0,Yp.createRequire)(At.default.join(r,"noop.js")),o=Vp(At.default.join(r,"zod"));for(let i of ww)try{let a=s.resolve(i,{paths:[r]});Tw(Vp(a),o)||n.push(i)}catch{n.push(i)}}return n}var Rr,Yp,At,ww,Jp=E(()=>{"use strict";Rr=require("fs"),Yp=require("module"),At=be(require("path"),1),ww=["zod/v3","zod/v4","zod/v4-mini"]});function eg(){return bo.default.join(N(),"worker-standby.json")}function Cc(){return bo.default.join(N(),"worker-standby-attempt.json")}function Dc(){return bo.default.join(N(),"worker-standby-failure.json")}function Fc(t){try{return JSON.parse((0,wo.readFileSync)(t,"utf-8"))}catch{return null}}function Lc(t){try{(0,wo.unlinkSync)(t)}catch(e){e.code!=="ENOENT"&&f.debug("SYSTEM","Could not remove worker standby file",{path:t,error:e instanceof Error?e.message:String(e)})}}function To(){let t=Fc(eg());return!t||typeof t.pid!="number"||!Number.isInteger(t.pid)||t.pid<=0||typeof t.port!="number"||!Number.isInteger(t.port)||t.port<=0||typeof t.version!="string"?null:{pid:t.pid,port:t.port,version:t.version,startedAt:typeof t.startedAt=="string"?t.startedAt:""}}function Io(t){if(t!==void 0){let e=To();if(e!==null&&e.pid!==t)return}Lc(eg())}function Iw(){let t=Fc(Dc());return!t||typeof t.buildKey!="string"||typeof t.failedAt!="string"?null:{buildKey:t.buildKey,failedAt:t.failedAt,reason:typeof t.reason=="string"?t.reason:""}}function tg(t,e,r=new Date){try{U(Dc(),{buildKey:t,failedAt:r.toISOString(),reason:e})}catch(n){f.warn("SYSTEM","Could not save the failed worker update attempt",{error:n instanceof Error?n.message:String(n)})}}function rg(){Lc(Dc())}function ng(t,e=Date.now()){if(t===null)return null;let r=Iw();if(r===null||r.buildKey!==t)return null;let n=Date.parse(r.failedAt);return!Number.isFinite(n)||e-n>=Nc?null:r}function sg(){let t=Fc(Cc());return!t||typeof t.buildKey!="string"||typeof t.launchedAtMs!="number"||!Number.isFinite(t.launchedAtMs)?null:{buildKey:t.buildKey,launchedAtMs:t.launchedAtMs}}function og(t){try{U(Cc(),t)}catch(e){f.debug("SYSTEM","Could not save the worker update attempt",{error:e instanceof Error?e.message:String(e)})}}function ig(){Lc(Cc())}var bo,wo,Qp,kc,Zp,Nc,ag=E(()=>{"use strict";bo=be(require("path"),1),wo=require("fs");C();se();O();Qp="MEMINDEX_WORKER_STANDBY",kc=12e4,Zp=2e4,Nc=10*6e4});function jc(t,e,r){let n=process.env[t];if(n){let s=parseInt(n,10);if(Number.isFinite(s)&&s>=r.min&&s<=r.max)return s;f.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max})}return e}function yg(t=process.env){let e=t.MEMINDEX_FETCH_VERBOSE;if(e===void 0)return!1;let r=e.trim().toLowerCase();return r==="1"||r==="true"||r==="on"||r==="yes"}function Ow(t){return yg()?{...t,verbose:!0}:t}function Pw(t){let e={},r=t;for(let n=0;r&&n<4;n++){let s=n===0?"error":`cause${n}`;if(r instanceof Error){let o=r;e[s]={name:r.name,message:r.message,...o.code!==void 0?{code:o.code}:{}},r=r.cause;continue}e[s]=String(r);break}return e}function Mw(t,e,r){let n=typeof e.method=="string"?e.method:"GET",s=Pw(r),o=JSON.stringify(s);f.warn("SYSTEM","Worker IPC fetch failed",{url:t,method:n},o),ct(`[memindex] fetch verbose: ${n} ${t} ${o}
|
|
22
|
+
`)}async function Xc(t,e={}){let r=Ow(e);try{return await fetch(t,r)}catch(n){throw yg()&&Mw(t,e,n),n}}async function In(t,e={},r){try{return await Xc(t,{...e,signal:AbortSignal.timeout(r)})}catch(n){throw n instanceof DOMException&&n.name==="TimeoutError"?new Error(`Request timed out after ${r}ms`):n}}function xw(t,e){let r=new AbortController,n=null,s=null,o=null,i=!1,a=()=>{s!==null&&(clearTimeout(s),s=null)},c=()=>{i=!0,a(),o!==null&&(clearTimeout(o),o=null)},u=d=>{i||(n=d,c(),r.abort(d))},l=()=>{i||(a(),s=setTimeout(()=>u(new Error(`Request timed out after ${t.idleTimeoutMs}ms idle`)),t.idleTimeoutMs))};if(t.absoluteCapMs!==void 0&&t.absoluteCapMs>0){let d=t.absoluteCapMs;o=setTimeout(()=>u(new Error(`Request timed out after ${d}ms`)),d)}return l(),{signal:e?AbortSignal.any([e,r.signal]):r.signal,touch:l,pause:a,dispose:c,translate:d=>n??d}}async function bg(t,e,r){let n=xw(r,e.signal),s;try{s=await Xc(t,{...e,signal:n.signal})}catch(u){throw n.dispose(),n.translate(u)}n.touch();let o=s.body,i=o?o.getReader():null,a=!1;async function*c(){if(!i){a=!0,n.dispose();return}try{for(;;){n.touch();let u;try{u=await i.read()}catch(l){throw a=!0,n.translate(l)}if(u.done){a=!0;return}n.pause(),r.onChunk?.(u.value),yield u.value}}finally{n.dispose(),a||await i.cancel()}}return{status:s.status,statusText:s.statusText,ok:s.ok,headers:s.headers,chunks:c(),cancel:async()=>{n.dispose(),i&&!a&&(a=!0,await i.cancel())}}}async function kw(t,e,r){let n=await bg(t,e,r),s=new TextDecoder,o="";for await(let i of n.chunks)o+=s.decode(i,{stream:!0});return o+=s.decode(),{status:n.status,statusText:n.statusText,ok:n.ok,headers:n.headers,text:o}}function cg(){return L.default.join(V.get("MEMINDEX_DATA_DIR"),"settings.json")}function Kc(t={}){return t.readOnly?V.loadFromFile(cg(),!0,t):(vo!==null||(vo=V.loadFromFile(cg())),vo)}function ug(t,e){if(!t)return null;let r=parseInt(t,10);return Number.isFinite(r)&&r>=e.min&&r<=e.max?r:null}function wg(t,e,r){let n=process.env[t];if(n!==void 0){let i=ug(n,r);return i!==null?i:(f.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max}),e)}let s=Kc()[t],o=ug(s,r);return o!==null?o:(f.warn("SYSTEM",`Invalid ${t} in settings.json, using default`,{value:s,min:r.min,max:r.max}),e)}function ie(t={}){if(!t.readOnly&&Uc!==null)return Uc;let e=parseInt(Kc(t).MEMINDEX_WORKER_PORT,10),r=e===La()&&un()?Ua(N()):e;return t.readOnly||(Uc=r),r}function Gc(t={}){if(!t.readOnly&&$c!==null)return $c;let e=Kc(t).MEMINDEX_WORKER_HOST;return t.readOnly||($c=e),e}function Nw(){return Ro!==null||(Ro=wg("MEMINDEX_API_TIMEOUT_MS",ze(Q.API_REQUEST),Rw)),Ro}function Tg(){return Ao!==null||(Ao=Math.min(wg("MEMINDEX_SESSION_INIT_TIMEOUT_MS",cn(),Aw),Wd())),Ao}function ko(t){return t===null?null:Math.max(0,t-Date.now())}function Mo(t){let e=ko(t);return e!==null&&e<Hc}function De(t,e){let r=ko(e);return r===null?t:Math.max(1,Math.min(t,r))}function Ig(t){return`http://${Va(Gc())}:${ie()}${t}`}function le(t,e={}){let r=e.method??"GET",n=Ig(t),s={method:r};e.headers&&(s.headers=e.headers),e.body&&(s.body=e.body);let o=gn(s);if(e.idleTimeoutMs!==void 0&&e.idleTimeoutMs>0)return kw(n,o,{idleTimeoutMs:e.idleTimeoutMs,absoluteCapMs:e.timeoutMs}).then(a=>new Response(a.text.length>0?a.text:null,{status:a.status,statusText:a.statusText,headers:a.headers}));let i=e.timeoutMs??Nw();return i>0?In(n,o,i):Xc(n,o)}async function Cw(t){return(await le("/api/health",{timeoutMs:t})).ok}async function lg(t=qe){return(await le("/api/readiness",{timeoutMs:t})).ok}function vg(t){let e=(0,x.existsSync)(L.default.join(t,"plugin","scripts"))?L.default.join(t,"plugin"):t;return L.default.join(e,"scripts","worker-service.cjs")}function Dw(t,e){let r=d=>{let p=d.split("-")[0].split(".");return[parseInt(p[0],10)||0,parseInt(p[1],10)||0,parseInt(p[2],10)||0]},[n,s,o]=r(t),[i,a,c]=r(e);if(i!==n)return i-n;if(a!==s)return a-s;if(c!==o)return c-o;let u=t.includes("-")?1:0,l=e.includes("-")?1:0;return u!==l?u-l:t<e?1:t>e?-1:0}function Fw(t=L.default.join(L.default.dirname(L.default.dirname(Er)),"cache","memindex","memindex")){try{return(0,x.readdirSync)(t).filter(e=>/^\d/.test(e)).map(e=>L.default.join(t,e)).filter(e=>{try{if(!(0,x.statSync)(e).isDirectory())return!1}catch{return!1}return!(0,x.existsSync)(L.default.join(e,".orphaned_at"))}).map(e=>({scriptPath:vg(e),version:L.default.basename(e)}))}catch{return[]}}function dg(t){try{let e=JSON.parse((0,x.readFileSync)(t,"utf-8"));return typeof e.version=="string"?e.version:null}catch(e){let r=e.code;return r!=="ENOENT"&&f.debug("SYSTEM","Could not read package version for worker resolution",{packageJsonPath:t,code:r}),null}}function Lw(){return{cacheRoot:L.default.join(L.default.dirname(L.default.dirname(Er)),"cache","memindex","memindex"),marketplaceRoot:Er,cwd:process.cwd()}}function zc(t=Lw()){let e=process.env.MEMINDEX_WORKER_SCRIPT_PATH?.trim();if(e){if((0,x.existsSync)(e))return{scriptPath:e,version:null};f.debug("SYSTEM","Ignoring missing MEMINDEX_WORKER_SCRIPT_PATH override",{override:e})}let r=[...Fw(t.cacheRoot),{scriptPath:vg(L.default.join(t.marketplaceRoot,"plugin")),version:dg(L.default.join(t.marketplaceRoot,"package.json"))},{scriptPath:L.default.join(t.cwd,"plugin","scripts","worker-service.cjs"),version:dg(L.default.join(t.cwd,"package.json"))}];return Bw(r)}function Uw(t){return L.default.dirname(L.default.dirname(t))}function $w(t){return qp(Uw(t.scriptPath)).length===0}function Bw(t,e=$w){let r=t.filter(n=>(0,x.existsSync)(n.scriptPath));return r.length===0?null:(r.sort((n,s)=>n.version===null&&s.version===null?0:n.version===null?1:s.version===null?-1:Dw(n.version,s.version)),r.find(e)??r[0])}function Ww(){return zc()?.scriptPath??null}async function jw(t){let e=t.deadlineAt??null,r=t.backoffMs;for(let n=1;n<=t.attempts;n++){if(Mo(e))return!1;if(await Cg(e??Number.POSITIVE_INFINITY))return!0;n<t.attempts&&(await new Promise(s=>setTimeout(s,De(r,e))),r*=2)}return!1}function fg(t){return t instanceof Error&&/^Request timed out after \d+ms idle$/.test(t.message)}function pg(t){return t instanceof Error&&/^Request timed out after \d+ms$/.test(t.message)}async function Hw(t){let e;try{e=await bg(Ig("/api/ready"),{method:"GET"},{idleTimeoutMs:vw,absoluteCapMs:Math.max(1,t)})}catch(o){return fg(o)?{outcome:"unresponsive",detail:"no response headers within the idle window"}:pg(o)?{outcome:"still_booting",detail:"budget spent before response headers"}:(f.debug("SYSTEM","Worker /api/ready connection failed",{error:o instanceof Error?o.message:String(o)}),{outcome:"not_running"})}let r=()=>e.cancel().catch(o=>{f.debug("SYSTEM","Releasing the /api/ready body failed",{error:o instanceof Error?o.message:String(o)})}),n=e.headers?.get("content-type")??"";if(!e.ok||!n.includes("text/event-stream"))return xo(),await r(),{outcome:"unsupported"};let s=null;try{for await(let o of _f(e.chunks)){if(o.event!=="phase")continue;let i=JSON.parse(o.data);if(s=typeof i.phase=="string"?i.phase:null,s==="ready")return xo(),await r(),{outcome:"ready"};if(s==="failed")return await r(),{outcome:"failed",detail:typeof i.message=="string"?i.message:"unknown init failure"}}}catch(o){return pg(o)?(xo(),{outcome:"still_booting",detail:`last phase ${s??"none"}`}):fg(o)?{outcome:"unresponsive",detail:`silent past the idle window after response headers (last phase ${s??"none"})`}:{outcome:"wedged",detail:`stream error: ${o instanceof Error?o.message:String(o)} (last phase ${s??"none"})`}}return{outcome:"wedged",detail:`stream closed before ready/failed (last phase ${s??"none"})`}}async function Xw(t){if(t<=0)try{return await lg()?{outcome:"ready"}:{outcome:"still_booting"}}catch(r){return f.debug("SYSTEM","Worker readiness check threw",{},r instanceof Error?r:new Error(String(r))),{outcome:"still_booting"}}let e=Date.now();do{let r=t-(Date.now()-e);try{if(await lg(Math.max(1,Math.min(qe,r))))return{outcome:"ready"}}catch(s){f.debug("SYSTEM","Worker readiness check threw",{error:s instanceof Error?s.message:String(s)})}let n=t-(Date.now()-e);if(n<=0)break;await new Promise(s=>setTimeout(s,Math.min(250,n)))}while(Date.now()-e<t);return{outcome:"still_booting",detail:"legacy /api/readiness never reported ready"}}async function Zt(t=Ar){let e=t>0?t:qe,r=await Hw(e);return r.outcome==="ready"&&Jw(),r.outcome!=="unsupported"?r:(f.debug("SYSTEM","Worker has no /api/ready stream; falling back to /api/readiness"),Xw(t))}async function Kw(t=qe){try{let r=await(await le("/api/health",{timeoutMs:t})).json();return typeof r.version=="string"?r.version:null}catch(e){let r=e instanceof Error?e:new Error(String(e));return f.debug("SYSTEM","Worker health-version fetch failed",{},r),null}}async function Gw(t=5e3){let e=Date.now()+t;for(;;){let r=e-Date.now();if(r<=0)return!1;if(await mo(ie(),Math.min(1e3,r))==="free")return!0;let n=Math.min(200,e-Date.now());n>0&&await new Promise(s=>setTimeout(s,n))}}function Rg(t,e){if(!t)return null;try{let r=(0,x.statSync)(t.scriptPath);return JSON.stringify([t.scriptPath,e,r.size,r.mtimeMs,r.ctimeMs])}catch{return null}}function Ag(){return L.default.join(N(),"worker-version-recycle.json")}function zw(t,e){if(t===null||e===null)return!1;try{let r=JSON.parse((0,x.readFileSync)(Ag(),"utf-8"));return r?.buildKey===t&&r?.workerVersion===e}catch{return!1}}async function gg(t,e=null,r=qe){let n=await Kw(r);if(n!==null&&n!==t){if(e!==null)try{U(Ag(),{buildKey:e,workerVersion:n})}catch(s){f.warn("SYSTEM","Could not persist the failed worker version recycle",{error:s instanceof Error?s.message:String(s)})}f.warn("SYSTEM","Worker is ready but still reports a stale version; rebuild or reinstall the worker bundle before retrying",{pluginVersion:t,workerVersion:n})}}function Vc(){return L.default.join(N(),"worker-unresponsive.json")}function Vw(){try{let t=JSON.parse((0,x.readFileSync)(Vc(),"utf-8"));return typeof t?.pid!="number"||typeof t?.firstUnresponsiveAtEpochMs!="number"?null:{pid:t.pid,firstUnresponsiveAtEpochMs:t.firstUnresponsiveAtEpochMs}}catch{return null}}function xo(){let t=Vc();if((0,x.existsSync)(t))try{(0,x.unlinkSync)(t)}catch(e){f.debug("SYSTEM","Could not clear the unresponsive-worker record",{error:e instanceof Error?e.message:String(e)})}}function Yw(t=Date.now()){let e=gt()?.pid??null;if(e===null)return!1;let r=Vw();if(r!==null&&r.pid===e)return t-r.firstUnresponsiveAtEpochMs>=Og;try{U(Vc(),{pid:e,firstUnresponsiveAtEpochMs:t})}catch(n){f.warn("SYSTEM","Could not persist the unresponsive-worker record",{error:n instanceof Error?n.message:String(n)})}return!1}function Yc(){return L.default.join(N(),"worker-never-ready-recycle.json")}function qw(){try{let t=JSON.parse((0,x.readFileSync)(Yc(),"utf-8"));return typeof t?.buildKey!="string"||typeof t?.failureMessage!="string"?null:{buildKey:t.buildKey,failureMessage:t.failureMessage,refusalLogged:t.refusalLogged===!0}}catch{return null}}function Pg(t){try{U(Yc(),t)}catch(e){f.warn("SYSTEM","Could not persist the never-ready worker recycle",{error:e instanceof Error?e.message:String(e)})}}function Jw(){let t=Yc();if((0,x.existsSync)(t))try{(0,x.unlinkSync)(t)}catch(e){f.debug("SYSTEM","Could not clear the never-ready worker recycle record",{error:e instanceof Error?e.message:String(e)})}}function Mg(t){return Rg(t,t?.version??"unknown")??"unresolved-worker-bundle"}function xg(t){return t.outcome==="failed"?t.detail??"unknown init failure":t.outcome}function kg(t,e){if(t.outcome==="unresponsive"&&!Yw())return f.warn("SYSTEM","Worker went silent on /api/ready; skipping this hook without killing it",{detail:t.detail,wedgedAfterMs:Og}),!1;let r=xg(t),n=qw();return n!==null&&n.buildKey===e&&n.failureMessage===r?(n.refusalLogged?f.debug("SYSTEM","Never-ready worker recycle already refused for this bundle and failure",{failureMessage:r}):(f.error("SYSTEM","Worker keeps failing to start the same way after a recycle; not recycling again. Run `npx memindex doctor` and check the worker logs",{outcome:t.outcome,failureMessage:r,logsDir:L.default.join(N(),"logs")}),Pg({...n,refusalLogged:!0})),!1):!0}function Ng(t,e){Pg({buildKey:e,failureMessage:xg(t)}),xo()}async function Cg(t=Number.POSITIVE_INFINITY){let e=t-Date.now();if(e<=0)return!1;let r;try{r=await Cw(Math.min(qe,e))}catch(n){return f.debug("SYSTEM","Worker health check threw",{error:n instanceof Error?n.message:String(n)}),!1}return r}async function qc(t,e){let r=gt();if(r===null||r.port!==ie())return f.error("SYSTEM","Stale worker is serving the port but the PID file does not identify it; kill the memindex worker process manually",{port:ie(),pidFilePid:r?.pid??null,pidFilePort:r?.port??null}),!1;if(e("stale-worker recycle"))return!1;try{await we(r.pid,{signalMode:"immediate"})}catch(n){return f.error("SYSTEM","Could not kill stale worker",{pid:r.pid,port:r.port},n instanceof Error?n:new Error(String(n))),!1}return await Gw(De(5e3,t))?!0:(e("stale port release")||(er=ie(),f.error("SYSTEM","Stale worker port still open after SIGKILL; skipping spawn this hook event",{pid:r.pid,port:ie(),fix:No})),!1)}function Dg(t,e){return`http://127.0.0.1:${t}${e}`}async function Fg(t,e){if(e<=0)return{answered:!1,version:null};try{let n=await(await In(Dg(t.port,"/api/health"),{},e)).json();return n.pid!==t.pid||n.standby!==!0?{answered:!1,version:null}:{answered:!0,version:typeof n.version=="string"?n.version:null}}catch{return{answered:!1,version:null}}}function Lg(t){try{process.kill(t.pid,"SIGKILL")}catch(e){f.debug("SYSTEM","Could not stop the standby worker",{pid:t.pid,error:e instanceof Error?e.message:String(e)})}Io(t.pid)}async function Qw(t,e,r,n){let s=await Zw(t,e,r,n);return s.kind!=="out-of-budget"&&ig(),s}async function Zw(t,e,r,n){let s=To(),o=s===null?null:await Fg(s,De(qe,n));if(s!==null&&o!==null&&o.answered&&o.version===e)return f.info("SYSTEM","Found the updated worker already waiting to take over",{pid:s.pid,port:s.port}),{kind:"ready",record:s};let i={kind:"failed",reason:`it did not answer its health check within ${Math.round(wn/1e3)} seconds; the worker log has the reason`};if(s!==null&&o!==null)if(o.answered)Lg(s);else{let d=Date.parse(s.startedAt);if((Number.isFinite(d)?Date.now()-d:Number.POSITIVE_INFINITY)<kc&&Y(s.pid)){let g=Math.min(d+kc,Math.max(d+wn,Date.now()+2e3)),m=await Bc(e,g,n,i);return m.kind==="failed"&&Io(s.pid),m}Io(s.pid)}let a=r===null?null:sg();if(a!==null&&a.buildKey===r)return Date.now()-a.launchedAtMs>=wn?i:Bc(e,a.launchedAtMs+wn,n,i);let c=po();if(!c)return{kind:"failed",reason:"Bun, which runs the worker, was not found"};if(!t)return{kind:"failed",reason:"the new worker program (worker-service.cjs) was not found"};f.info("SYSTEM","Starting the updated worker next to the running one",{runtimePath:c,scriptPath:t});let u;try{u=go(c,t,pt({...process.env,MEMINDEX_WORKER_PORT:String(ie()),[Qp]:"1"}),process.platform,ko(n)??void 0)}catch(d){return{kind:"failed",reason:`it could not be launched (${d instanceof Error?d.message:String(d)})`}}if(u===void 0)return{kind:"failed",reason:"it could not be launched"};let l=Date.now();return r!==null&&og({buildKey:r,launchedAtMs:l}),Bc(e,l+wn,n,i)}async function Bc(t,e,r,n){let s=Math.min(e,r??Number.POSITIVE_INFINITY);for(;Date.now()<s;){let o=To();if(o!==null){let a=await Fg(o,Math.min(1e3,s-Date.now()));if(a.answered)return a.version===t?{kind:"ready",record:o}:(Lg(o),{kind:"failed",reason:`it reports version ${a.version??"unknown"} instead of ${t}; the installed files are mislabelled`})}let i=Math.min(200,s-Date.now());i>0&&await new Promise(a=>setTimeout(a,i))}return Date.now()<e?{kind:"out-of-budget"}:n}async function eT(t,e){try{let r=await In(Dg(t.port,"/api/admin/promote"),gn({method:"POST"}),e);if(r.ok)return null;let n=await r.json().catch(()=>({}));return typeof n.message=="string"?n.message:`HTTP ${r.status}`}catch(r){return r instanceof Error?r.message:String(r)}}async function tT(t){let{scriptPath:e,pluginVersion:r,workerVersion:n,buildKey:s,deadlineAt:o,outOfBudget:i}=t,a=n??"unknown",c=ng(s);if(c!==null)return f.debug("SYSTEM","Keeping the running worker: this update failed to start a short while ago",{pluginVersion:r,workerVersion:n,failedAt:c.failedAt,reason:c.reason}),"kept-old";let u=gt();if(u===null||u.port!==ie())return f.error("SYSTEM","Stale worker is serving the port but the PID file does not identify it; kill the memindex worker process manually",{port:ie(),pidFilePid:u?.pid??null,pidFilePort:u?.port??null}),"failed";if(!Eo())return f.info("SYSTEM","Another launcher is starting the updated worker; the running worker keeps serving meanwhile"),"kept-old";let l=!1;try{let d=await Qw(e,r,s,o);if(d.kind==="out-of-budget")return f.info("SYSTEM","The updated worker is still starting; the running worker keeps serving until a later hook hands over",{pluginVersion:r,workerVersion:n}),"kept-old";if(d.kind==="failed")return s!==null&&tg(s,d.reason),f.error("SYSTEM",`The updated MemIndex worker (version ${r}) did not start, so the running worker (version ${a}) keeps serving: ${d.reason}. MemIndex tries the update again in ${Math.round(Nc/6e4)} minutes, or as soon as the plugin is reinstalled.`,{pluginVersion:r,workerVersion:n,scriptPath:e}),"kept-old";if(i("stale-worker recycle"))return"kept-old";if(!await qc(o,i))return"failed";l=!0;let p=await eT(d.record,De(1e4,o));return p===null?(rg(),f.info("SYSTEM","The updated worker took over from the old one",{from:n,to:r,pid:d.record.pid}),"promoted"):(f.warn("SYSTEM","The updated worker could not take over the worker port; starting a new worker the usual way",{pluginVersion:r,reason:p}),"old-stopped")}finally{l||bn()}}async function Or(t){let e=t===void 0?null:Date.now()+t,r=S=>Mo(e)?(f.warn("SYSTEM","Worker check ran out of the hook budget; skipping the rest this hook event",{step:S,budgetMs:t}),!0):!1,n=()=>e===null?void 0:De(qe,e),s=Math.min(Date.now()+5e3,e??Number.POSITIVE_INFINITY),o=zc(),i=null,a=null,c=!1,u=!1,l=!1,d=null,p=null,g=$s(G());if(r("health probe"))return!1;if(await Cg(s)){if(r("version probe"))return!1;let{matches:S,pluginVersion:b,workerVersion:w}=await Np(ie(),o?.version??null,n());if(b!=="unknown"&&(i=b),S){if(r("readiness wait"))return!1;let T=await Zt(De(Ar,e));if(T.outcome==="ready")return i!==null&&!Mo(e)&&await gg(i,null,n()),!0;if(T.outcome==="still_booting"||T.outcome==="not_running")return f.warn("SYSTEM","Worker is healthy but not ready yet; skipping hook API call",{outcome:T.outcome,detail:T.detail}),!1;if(g)return f.warn("SYSTEM","Worker will never become ready; MEMINDEX_WORKER_AUTOSTART=false, so leaving it to whatever manages it",{outcome:T.outcome,detail:T.detail}),!1;if(p=Mg(o),!kg(T,p))return!1;d=T,f.info("SYSTEM","Worker will never become ready \u2014 recycling wedged worker",{outcome:T.outcome,detail:T.detail,version:w})}else{if(g)return f.warn("SYSTEM","Worker version differs from the installed plugin; MEMINDEX_WORKER_AUTOSTART=false, so using it as is",{pluginVersion:b,workerVersion:w}),r("readiness wait")?!1:(await Zt(De(Ar,e))).outcome==="ready";if(a=Rg(o,b),zw(a,w))return f.warn("SYSTEM","Skipping repeated worker recycle: the unchanged bundle still reports a stale version; rebuild or reinstall it",{pluginVersion:b,workerVersion:w,scriptPath:o?.scriptPath}),r("readiness wait")?!1:(await Zt(De(Ar,e))).outcome==="ready";f.info("SYSTEM","Worker version changed \u2014 starting the new worker before stopping the old one",{pluginVersion:b,workerVersion:w});let T=await tT({scriptPath:o?.scriptPath??null,pluginVersion:b,workerVersion:w,buildKey:a,deadlineAt:e,outOfBudget:r});if(T==="failed")return!1;if(T==="kept-old")return r("readiness wait")?!1:(await Zt(De(Ar,e))).outcome==="ready";u=!0,l=T==="promoted"}if(!u&&!await qc(e,r))return!1;d!==null&&p!==null&&Ng(d,p),c=!0}if(g)return f.debug("SYSTEM","Worker not running and MEMINDEX_WORKER_AUTOSTART=false \u2014 not lazy-spawning"),!1;let m=o?.scriptPath??null;if(r("lazy spawn"))return u&&bn(),!1;let h=u||Eo();try{if(h&&!l){if(!c&&!await rT(s,e))return!1;let b=po();if(!b)return f.warn("SYSTEM","Cannot lazy-spawn worker: Bun runtime not found (PATH, BUN / BUN_PATH / BUN_INSTALL, or ~/.bun/bin)"),!1;if(!m)return f.warn("SYSTEM","Cannot lazy-spawn worker: worker-service.cjs not found in plugin/scripts"),!1;f.info("SYSTEM","Worker not running \u2014 lazy-spawning",{runtimePath:b,scriptPath:m});try{if(go(b,m,pt({...process.env,MEMINDEX_WORKER_PORT:String(ie())}),process.platform,ko(e)??void 0)===void 0)return!1}catch(w){return w instanceof Error?f.error("SYSTEM","Lazy-spawn of worker failed",{runtimePath:b,scriptPath:m},w):f.error("SYSTEM","Lazy-spawn of worker failed (non-Error)",{runtimePath:b,scriptPath:m,error:String(w)}),!1}}else h||f.info("SYSTEM","Another launcher holds the spawn lock \u2014 skipping lazy-spawn and waiting for its worker");if(!await jw({attempts:6,backoffMs:500,deadlineAt:e}))return r("cold-boot port wait")||(f.warn("SYSTEM",h?"Worker port did not open after lazy-spawn within the cold-boot wait (~15s)":"Spawn-lock holder's worker port did not open within the cold-boot wait (~15s)"),gt()===null&&await xp(ie(),e===null?void 0:De(5e3,e))&&(er=ie(),f.error("SYSTEM","Worker port is occupied by an unreachable process that no PID file claims (likely an orphaned OS socket); every lazy-spawn on this port will be silently refused",{port:er,fix:No}))),!1}finally{h&&bn()}if(r("readiness wait"))return!1;let _=await Zt(De(Ar,e));return _.outcome!=="ready"?(f.warn("SYSTEM","Worker lazy-spawned but did not become ready before hook readiness timeout",{outcome:_.outcome,detail:_.detail}),!1):(i!==null&&!Mo(e)&&await gg(i,a,n()),!0)}async function rT(t,e){let r=ie(),n=t-Date.now();if(n<=0)return!1;let s=await mo(r,n);if(s==="free")return!0;if(s==="unbindable")return Wc=r,f.error("SYSTEM","Worker port cannot be bound (EACCES or EADDRNOTAVAIL) \u2014 skipping lazy-spawn",{port:r,host:Gc(),fix:Oc}),!1;if(s==="indeterminate")return f.warn("SYSTEM","Worker port state could not be determined in time \u2014 skipping lazy-spawn",{port:r}),!1;let o=await Gp(r,{deadlineAt:e});return o.reclaimed?(f.info("SYSTEM","Reclaimed the worker port before lazy-spawn",{port:r,killedPids:o.killedPids}),!0):(gt()===null&&(er=r),f.warn("SYSTEM","Worker port is held by a listener that does not answer health \u2014 skipping lazy-spawn",{port:r,reclaimReason:o.reason,...er===r?{fix:No}:{}}),!1)}async function nT(t){if(Qt!==void 0)return Qt;try{let r=await(await le("/api/health",{timeoutMs:t})).json();Qt=Yd(r.dataDir,N())==="foreign"?String(r.dataDir):null}catch(e){f.debug("SYSTEM","Could not read the worker data folder; treating the worker as ours",{error:e instanceof Error?e.message:String(e)}),Qt=null}return Qt!==null&&f.warn("SYSTEM","The worker on this port writes to another data folder; observations wait in the hook spool and prompts and context are not delivered until it is gone",{workerDataDir:Qt,dataDir:N(),port:ie()}),Qt}async function sT(t){return Oo!==null||(Oo=await Or(t)),Oo}async function oT(t){let e=Date.now()+t,r=()=>e-Date.now(),n=u=>r()>=Hc?!1:(f.debug("SYSTEM","Bounded worker startup ran out of budget",{step:u,budgetMs:t}),!0),s=await Zt(Math.max(1,r()));if(s.outcome==="ready")return!0;if(s.outcome==="still_booting")return f.warn("SYSTEM","Worker is still booting; bounded startup budget spent, skipping this call",{detail:s.detail,budgetMs:t}),!1;if(!!$s(G()))return mg(e);let i=po(),a=Ww();if(!i||!a)return!1;if(s.outcome==="failed"||s.outcome==="wedged"||s.outcome==="unresponsive"){let u=Mg(zc());if(!kg(s,u)||(f.info("SYSTEM","Worker will never become ready \u2014 recycling wedged worker",{outcome:s.outcome,detail:s.detail}),!await qc(e,n)))return!1;Ng(s,u)}let c=Eo();try{return c&&go(i,a,pt({...process.env,MEMINDEX_WORKER_PORT:String(ie())}),process.platform,Math.max(1,r()))===void 0?!1:await mg(e)}catch(u){return f.debug("SYSTEM","Bounded worker startup failed",{error:u instanceof Error?u.message:String(u)}),!1}finally{c&&bn()}}async function mg(t){for(;t-Date.now()>0;){let e=await Zt(Math.max(1,t-Date.now()));if(e.outcome==="ready")return!0;if(e.outcome!=="not_running")return f.debug("SYSTEM","Bounded worker startup did not reach ready",{outcome:e.outcome,detail:e.detail}),!1;let r=Math.min(100,t-Date.now());r>0&&await new Promise(n=>setTimeout(n,r))}return!1}function Co(){return L.default.join(W,"state")}function Wg(){return L.default.join(Co(),"hook-failures.json")}function jg(){return L.default.join(Co(),"hook-failures.lock")}async function Jc(t=$g){let e=Co(),r=jg(),n=(0,Sg.randomUUID)(),s=JSON.stringify({pid:process.pid,token:n}),o=Date.now()+t;for(;Date.now()<=o;)try{return(0,x.mkdirSync)(e,{recursive:!0}),(0,x.writeFileSync)(r,s,{flag:"wx"}),n}catch(i){let a=i instanceof Error?i:new Error(String(i)),c=a.code;if(c!=="EEXIST")return f.warn("SYSTEM","Hook-failure lock unavailable; skipping failure-state update",{lockPath:r,code:c},a),null;let u;try{u=(0,x.statSync)(r).mtimeMs}catch{continue}if(Date.now()-u>Bg){let l;try{l=(0,x.statSync)(r).mtimeMs}catch{continue}if(l===u)try{(0,x.unlinkSync)(r);continue}catch{}}await new Promise(l=>setTimeout(l,aT))}return f.warn("SYSTEM","Timed out waiting for hook-failure lock; skipping failure-state update",{lockPath:r,waitMs:t}),null}function Qc(t){let e=jg();try{if(JSON.parse((0,x.readFileSync)(e,"utf-8")).token!==t)return;(0,x.unlinkSync)(e)}catch{}}function uT(t){let e=JSON.parse(t);return{consecutiveFailures:typeof e.consecutiveFailures=="number"&&Number.isFinite(e.consecutiveFailures)?Math.max(0,Math.floor(e.consecutiveFailures)):0,lastFailureAt:typeof e.lastFailureAt=="number"&&Number.isFinite(e.lastFailureAt)?e.lastFailureAt:0,thresholdTripped:e.thresholdTripped===!0,notifiedSessionIds:Array.isArray(e.notifiedSessionIds)?e.notifiedSessionIds.filter(r=>typeof r=="string").slice(-Ug):void 0}}function Tn(){try{return uT((0,x.readFileSync)(Wg(),"utf-8"))}catch{return{consecutiveFailures:0,lastFailureAt:0,thresholdTripped:!1}}}function Zc(t){let e=Co(),r=Wg(),n=`${r}.tmp`;try{return(0,x.existsSync)(e)||(0,x.mkdirSync)(e,{recursive:!0}),(0,x.writeFileSync)(n,JSON.stringify(t),"utf-8"),(0,x.renameSync)(n,r),!0}catch(s){return f.debug("SYSTEM","Failed to persist hook-failure counter",{error:s instanceof Error?s.message:String(s)}),!1}}function lT(){try{let e=G().MEMINDEX_HOOK_FAIL_LOUD_THRESHOLD,r=parseInt(e,10);if(Number.isFinite(r)&&r>=1)return r}catch{}return iT}function Hg(t){let e=Wc!==null?`The worker cannot bind port ${Wc} on ${Gc()}: the system refuses it (EACCES or EADDRNOTAVAIL). ${Oc}.`:er!==null?`Port ${er} is held by an unreachable process that no PID file claims, so the worker cannot bind it. ${No}.`:"Run `npx memindex restart`; if it keeps failing, run `npx memindex doctor`.";return`memindex worker unreachable for ${t} consecutive hooks \u2014 memory features are degraded, but your prompts are not blocked. ${e}`}async function Po(){if(dT){if(_g)return Tn().consecutiveFailures;_g=!0}let t=await Jc();if(t===null)return Tn().consecutiveFailures;let e,r=!1;try{let n=Tn();e={consecutiveFailures:n.consecutiveFailures+1,lastFailureAt:Date.now(),thresholdTripped:n.thresholdTripped,notifiedSessionIds:n.notifiedSessionIds};let s=lT();r=e.consecutiveFailures>=s&&!e.thresholdTripped,r&&(e.thresholdTripped=!0);let o=Zc(e);r=r&&o}finally{Qc(t)}return r&&(await Zf("hook_failed",{...hg!==null?{hook_type:hg}:{},error_mode:"worker_unavailable",consecutive_failures:e.consecutiveFailures,threshold_tripped:!0}),ct(`${Hg(e.consecutiveFailures)}
|
|
23
|
+
`)),e.consecutiveFailures}async function Xg(t){if(!t)return null;let e=await Jc();if(e===null)return null;try{let r=Tn(),n=r.notifiedSessionIds??[];return!r.thresholdTripped||n.includes(t)?null:Zc({...r,notifiedSessionIds:[...n,t].slice(-Ug)})?Hg(r.consecutiveFailures):null}finally{Qc(e)}}async function Eg(){let t=await Jc(cT);if(t!==null)try{let e=Tn();if(e.consecutiveFailures===0&&!e.thresholdTripped)return;Zc({consecutiveFailures:0,lastFailureAt:0,thresholdTripped:!1})}finally{Qc(t)}}function Kg(t){return typeof t=="object"&&t!==null&&t[Ot]===!0}async function Gg(t,e,r,n={}){let s=Date.now(),o=n.workerStartupTimeoutMs!==void 0;if(!(o?await oT(n.workerStartupTimeoutMs):await sT(n.timeoutMs)))return $s(G())?{continue:!0,reason:"worker_autostart_disabled",[Ot]:!0}:(o||await Po(),{continue:!0,reason:"worker_unreachable",[Ot]:!0});let a=n.timeoutMs===void 0?qe:Math.max(1,Math.min(qe,n.timeoutMs-(Date.now()-s)));if(await nT(a)!==null)return await Po(),{continue:!0,reason:"worker_foreign_data_dir",[Ot]:!0};let c={method:e};if(r!==void 0&&(c.headers={"Content-Type":"application/json"},c.body=JSON.stringify(r)),n.timeoutMs!==void 0){let d=o?n.timeoutMs:n.timeoutMs-(Date.now()-s);if(d<Hc)return f.debug("SYSTEM","Hook budget spent before the worker request; skipping it",{url:t}),o||await Po(),{continue:!0,reason:"worker_budget_exhausted",[Ot]:!0};c.timeoutMs=d}let u;try{u=await le(t,c)}catch(d){if(!o)throw d;return f.debug("SYSTEM","Worker unavailable for best-effort hook call",{error:d instanceof Error?d.message:String(d)}),{continue:!0,reason:"worker_unreachable",[Ot]:!0}}if(!u.ok){let d=await u.text().catch(()=>"");if(await Eg(),u.status===429||u.status>=500)return f.warn("SYSTEM",`Worker API ${e} ${t} returned ${u.status}; skipping hook API call`,{body:d.substring(0,200)}),{continue:!0,reason:`worker_api_${u.status}`,[Ot]:!0};let p=d;try{p=JSON.parse(d)}catch{}return p}let l;try{l=await u.text()}catch(d){return f.debug("SYSTEM","Worker response body could not be read; treating the worker as unreachable",{error:d instanceof Error?d.message:String(d)}),o||await Po(),{continue:!0,reason:"worker_body_read_failed",[Ot]:!0}}if(await Eg(),l.length!==0)try{return JSON.parse(l)}catch{return l}}var L,Sg,x,qe,Ar,wn,vw,Rw,Aw,Hc,Uc,$c,vo,Ro,Ao,Og,No,er,Wc,Oo,Qt,iT,Ug,$g,aT,Bg,cT,hg,dT,_g,Ot,Pt=E(()=>{"use strict";Ka();L=be(require("path"),1),Sg=require("crypto"),x=require("fs");O();xe();Ef();dt();C();ft();Sf();yf();Ya();$a();hn();mt();xs();ep();Dp();ho();Pc();Ac();$p();zp();mn();yr();se();Jp();ag();Ya();qe=jc("MEMINDEX_HEALTH_TIMEOUT_MS",ze(Q.HEALTH_CHECK),{min:500,max:3e5}),Ar=jc("MEMINDEX_HOOK_READINESS_TIMEOUT_MS",ze(Q.HOOK_READINESS_WAIT),{min:0,max:3e5}),wn=jc("MEMINDEX_WORKER_STANDBY_WAIT_MS",Zp,{min:500,max:3e5}),vw=5e3,Rw={min:500,max:3e5},Aw={min:500,max:Q.SESSION_INIT_REQUEST_MAX},Hc=100;Uc=null,$c=null,vo=null,Ro=null,Ao=null;Og=3e4;No="Set MEMINDEX_WORKER_PORT to a different port in memindex settings, or reboot to release the stuck port",er=null,Wc=null;Oo=null;iT=3,Ug=20,$g=1e3,aT=10,Bg=5e3,cT=Bg+$g;hg=null;dT=!1,_g=!1;Ot=Symbol.for("memindex/worker-fallback")});function eu(t,e){let r=(0,Je.normalize)(t),n=(0,Je.normalize)(e);if(r===n)return!0;let s=(0,Je.relative)(n,r);return s.length>0&&!s.startsWith("..")&&!(0,Je.isAbsolute)(s)}function Qe(t){if(process.env.MEMINDEX_INTERNAL==="1")return!1;if(!t)return!0;if(eu(t,Ns)||eu(t,_T)||eu(t,ET))return!1;let e=G();return!io(t,e.MEMINDEX_EXCLUDED_PROJECTS)}var Je,fT,pT,gT,mT,hT,_T,ET,Pr=E(()=>{"use strict";Je=require("path");Sn();ft();C();fT="plugins",pT="cache",gT="memindex",mT="memindex",hT="plugin",_T=(0,Je.join)(lt,fT,pT,gT,mT),ET=(0,Je.join)(Er,hT)});function ST(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function z(t){if(!t)return zg;let e=ST(t);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e.includes("kimi")?"kimi":e==="pi-mono"?"pi":e==="agy"||e==="antigravity"||e.startsWith("antigravity-")?"antigravity-cli":e:zg}var zg,ht=E(()=>{"use strict";zg="claude"});var Vg=E(()=>{"use strict"});function ru(t){return new RegExp(`${t}${yT}`,"gi")}function nu(t,e){if(!e.enabled||t.length===0)return{redacted:t,counts:{},oversize:!1};if(t.length>wT)return f.warn("REDACT","field exceeds the 1M-char redaction cap; replaced by an oversize marker",void 0,{inputLength:t.length}),{redacted:TT,counts:{oversize:1},oversize:!0};let r=new Set(e.disabledBuiltinPatterns??[]),n={},s=t,o=[];for(let a of e.customPatterns??[]){if(!a.name||a.name.length===0){f.warn("REDACT","custom pattern skipped: missing name",void 0,{pattern:a});continue}try{o.push({name:a.name,regex:new RegExp(a.regex,"g")})}catch(c){f.warn("REDACT","custom pattern skipped: invalid regex",{name:a.name},c instanceof Error?c:new Error(String(c)))}}let i=[...o,...bT];for(let a of i)r.has(a.name)||(a.regex.lastIndex=0,s=s.replace(a.regex,()=>(n[a.name]=(n[a.name]??0)+1,`<redacted type='${a.name}'/>`)));return e.logMatches&&Object.keys(n).length>0&&f.debug("REDACT","patterns matched",void 0,{counts:n}),{redacted:s,counts:n,oversize:!1}}function IT(t){if(!t||t.trim()==="")return[];try{let e=JSON.parse(t);return Array.isArray(e)?e.filter(r=>r&&typeof r.name=="string"&&typeof r.regex=="string"):(f.warn("REDACT","MEMINDEX_REDACT_CUSTOM_PATTERNS is not a JSON array, ignoring"),[])}catch(e){return f.warn("REDACT","failed to parse MEMINDEX_REDACT_CUSTOM_PATTERNS as JSON",void 0,e instanceof Error?e:new Error(String(e))),[]}}function vT(t){return{enabled:t.MEMINDEX_REDACT_ENABLED==="true",disabledBuiltinPatterns:(t.MEMINDEX_REDACT_DISABLED_BUILTINS??"").split(",").map(e=>e.trim()).filter(Boolean),customPatterns:IT(t.MEMINDEX_REDACT_CUSTOM_PATTERNS??"[]"),logMatches:t.MEMINDEX_REDACT_LOG_MATCHES==="true"}}function PT(t){if(!(0,Do.existsSync)(t))return null;try{return(0,Do.readFileSync)(t,"utf-8")}catch{return""}}function MT(t){if(t===null)return!1;try{let e=JSON.parse(Ma(t));return e===null||typeof e!="object"||Array.isArray(e)}catch{return!0}}function xT(t,e,r){return process.env.MEMINDEX_REDACT_ENABLED==="false"||!(Rn?.enabled===!0||OT.test(e))?r:(qg||(qg=!0,f.warn("REDACT","settings.json could not be read; secret redaction stays on until it is repaired",{settingsPath:t,using:Rn?.enabled?"the last configuration that loaded":"the built-in patterns"})),Rn?.enabled?Rn:AT)}function su(t=_e){let e=Date.now();if(vn&&e-Yg<RT)return vn;let r=V.loadFromFile(t),n=vT(r),s=n.enabled?null:PT(t);return MT(s)?vn=xT(t,s,n):(vn=n,Rn=n),Yg=e,vn}function Jg(t){return nu(t,su()).redacted}var Do,tu,yT,bT,wT,TT,vn,Yg,RT,Rn,qg,AT,OT,ou=E(()=>{"use strict";Do=require("fs");O();dt();C();se();tu=String.raw`[A-Za-z0-9_.\-+/=~@#$%^*!?]`,yT=`(?=${tu}{8})${tu}*[A-Za-z]${tu}*`;bT=[{name:"aws_access_key",regex:/AKIA[0-9A-Z]{16}/g},{name:"aws_secret_key",regex:/(?<=AWS_SECRET_ACCESS_KEY\s*[=:]\s*['"]?)[A-Za-z0-9/+=]{40}/g},{name:"github_pat",regex:/\bgh[oprs]_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{82}\b/g},{name:"openai_key",regex:/\bsk-(?!ant-)[A-Za-z0-9_-]{20,}\b/g},{name:"anthropic_key",regex:/\bsk-ant-[A-Za-z0-9_-]{20,}\b/g},{name:"slack_token",regex:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g},{name:"jwt",regex:/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g},{name:"private_key_pem",regex:/-----BEGIN (?:RSA |DSA |EC |OPENSSH |PGP )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |DSA |EC |OPENSSH |PGP )?PRIVATE KEY-----/g},{name:"stripe_key",regex:/\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]{24,}\b/g},{name:"google_api_key",regex:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:"memindex_key",regex:new RegExp("\\bmi_[A-Za-z0-9_-]{32,}","g")},{name:"generic_password",regex:ru(String.raw`(?<=\b\w*_?(?:password|passwd|pwd)\\{0,2}["']?\s*[=:]\s*\\{0,2}["']?)`)},{name:"generic_token",regex:ru(String.raw`(?<=\b\w*_(?:token|secret|api_key)\\{0,2}["']?\s*[=:]\s*\\{0,2}["']?)`)},{name:"bearer_token",regex:ru(String.raw`(?<=\bAuthorization\s*:\s*Bearer\s*)`)}],wT=1024*1024,TT="<redacted type='oversize'/>";vn=null,Yg=0,RT=5e3,Rn=null,qg=!1,AT={enabled:!0,disabledBuiltinPatterns:[],customPatterns:[],logMatches:!1},OT=/"(?:MEMINDEX|AGENT_MEM)_REDACT_ENABLED"\s*:\s*"true"/});function NT(t){let e=Object.fromEntries(iu.map(l=>[l,0])),r=t.length,n=new Int32Array(r+1);n[r]=r;for(let l=r-1;l>=0;l--)n[l]=t.charCodeAt(l)===62?l:n[l+1];let s=new Map,o=[],i=0,a=0;for(;a<r;){if(t.charCodeAt(a)!==60){a+=1;continue}Zg.lastIndex=a;let l=Zg.exec(t);if(l){let p=l[1],g=s.get(p),m=g&&g.head<g.items.length?g.items[g.head]:void 0;m&&a>=m.attrEnd&&(g.head+=1,o.push([m.start,a+l[0].length]),e[p]+=1,i+=1),a+=l[0].length;continue}Qg.lastIndex=a;let d=Qg.exec(t);if(d&&kT.has(d[1])){let p=d[1],g=a+d[0].length,m={start:a,attrEnd:n[g]},h=s.get(p);h?h.items.push(m):s.set(p,{items:[m],head:0}),a=g;continue}a+=1}o.sort((l,d)=>l[0]-d[0]);let c="",u=0;for(let[l,d]of o)l>u&&(c+=t.slice(u,l)),d>u&&(u=d);return c+=t.slice(u),{text:c,counts:e,total:i}}function CT(t){let{text:e,counts:r,total:n}=NT(t);return n>em&&f.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:n,maxAllowed:em,contentLength:t.length}),{stripped:nu(e.trim(),su()).redacted,counts:r}}function Ie(t){return CT(t).stripped}function An(t){let e=r=>typeof r=="string"?DT.test(r)?Ie(r):r:Array.isArray(r)?r.map(e):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).map(([n,s])=>[n,e(s)])):r;return e(t)}function Lo(t){return!t||t.length>UT?!1:LT.test(t)}function tm(t){let e=t.trimStart();return $T.some(r=>r.test(e))}var iu,kT,Qg,Zg,Fo,em,DT,FT,LT,UT,$T,Ze=E(()=>{"use strict";O();ou();iu=["private","memindex-context","agent-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],kT=new Set(iu),Qg=/<([A-Za-z_][A-Za-z0-9_-]*)/y,Zg=/<\/([A-Za-z_][A-Za-z0-9_-]*)\s*>/y;Fo=/<system-reminder>[\s\S]*?<\/system-reminder>/g,em=100;DT=new RegExp(`<(${iu.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`);FT=["task-notification"],LT=new RegExp(`^\\s*<(${FT.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),UT=256*1024;$T=[/^You are a helpful assistant\. You will be presented with a user prompt, and your job is to provide a short title/,/^## Memory Writing Agent: Phase 2 \(Consolidation\)/,/^# Overview\r?\n(?:\r?\n)?Generate 0 to 3 hyperpersonalized suggestions/]});function Fe(t){return t instanceof _t}function WT(t){return t.replace(/\/+$/,"")}function Uo(t){return typeof t=="string"?z(t):null}function jT(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}var BT,_t,$o,tr=E(()=>{"use strict";Pt();xe();ht();Ze();BT=ze(Q.API_REQUEST),_t=class extends Error{kind;status;cause;constructor(e,r,n={}){super(r),this.name="ServerClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},$o=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=WT(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??BT}async startSession(e,r={}){let n=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",n,r)}async recordEvent(e,r={}){let n=this.buildEventPayload(e),s=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",s,n,r)}async endSession(e,r={}){if(!e.sessionId)throw new _t("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{},r)}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e,r={}){let n={projectId:e.projectId};return e.query!==void 0&&(n.query=e.query),e.limit!==void 0&&(n.limit=e.limit),e.summaryLimit!==void 0&&(n.summaryLimit=e.summaryLimit),e.platformSource!==void 0&&(n.platformSource=Uo(e.platformSource)),e.folderProjects&&e.folderProjects.length>0&&(n.folderProjects=e.folderProjects),e.excludeSubagents!==void 0&&(n.excludeSubagents=e.excludeSubagents),this.request("POST","/v1/context",n,r)}async getJobStatus(e){if(!e)throw new _t("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,n=e.kind??"manual",s=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,content:r,...s?{title:s}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.platformSource!==void 0?{platformSource:e.platformSource}:{},...e.metadata!==void 0?{metadata:e.metadata}:{},...e.generationKey!==void 0?{generationKey:e.generationKey}:{},...e.createdAtEpoch!==void 0?{createdAtEpoch:e.createdAtEpoch}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:Uo(e.platformSource)}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:Uo(e.platformSource)}:{},...e.metadata!==void 0?{metadata:An(e.metadata)}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.platformSource!==void 0?{platformSource:Uo(e.platformSource)}:{},...e.payload!==void 0?{payload:An(e.payload)}:{}}}async request(e,r,n,s={}){if(!this.apiKey||!this.apiKey.trim())throw new _t("missing_api_key","Server API key is not configured (MEMINDEX_SERVER_API_KEY).");let o=`${this.baseUrl}${r}`,i={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(i.body=JSON.stringify(n));let a=d=>{let p=d instanceof Error?d.message:String(d),g=/timed out|timeout/i.test(p)||d instanceof Error&&(d.name==="TimeoutError"||d.name==="AbortError");return new _t(g?"timeout":"transport",`Server ${e} ${r} failed: ${p}`,{cause:d})},c,u=s.timeoutMs??this.timeoutMs;try{c=await In(o,i,u)}catch(d){throw a(d)}if(!c.ok){let d=await c.text().catch(()=>"");throw new _t("http_error",`Server ${e} ${r} returned ${c.status}: ${jT(d,200)}`,{status:c.status})}let l;try{l=await c.text()}catch(d){throw a(d)}if(!l||l.length===0)return{};try{return JSON.parse(l)}catch(d){let p=d instanceof Error?d:new Error(String(d));throw new _t("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:p})}}}});function HT(){let e=(G().MEMINDEX_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function XT(){let t=G(),e=(...r)=>{for(let n of r){let s=(n??"").trim();if(s.length>0)return s}return""};return{serverBaseUrl:e(t.MEMINDEX_SERVER_URL,t.MEMINDEX_SERVER_BETA_URL),apiKey:e(t.MEMINDEX_SERVER_API_KEY,t.MEMINDEX_SERVER_BETA_API_KEY),projectId:e(t.MEMINDEX_SERVER_PROJECT_ID,t.MEMINDEX_SERVER_BETA_PROJECT_ID)}}function KT(){let{serverBaseUrl:t,apiKey:e,projectId:r}=XT();if(!t)return f.warn("HOOK","[server-fallback] reason=missing_base_url"),null;if(!e)return f.warn("HOOK","[server-fallback] reason=missing_api_key"),null;if(!r)return f.warn("HOOK","[server-fallback] reason=missing_project_id"),null;let n={serverBaseUrl:t,apiKey:e};return{runtime:"server",client:new $o(n),projectId:r,serverBaseUrl:t}}function Le(){if(HT()!=="server")return{runtime:"worker"};let t=KT();return t||{runtime:"worker"}}function Ue(t,e){f.warn("HOOK",`[server-fallback] reason=${t}`,e??{})}var Mr=E(()=>{"use strict";ft();O();tr()});function qT(t){let e=t.trim().replace(/\/+$/,"");try{let r=new URL(e);return`${r.protocol}//${r.host}${r.pathname.replace(/\/+$/,"")}${r.search}`}catch{return e}}function $e(t){let e=(0,lu.createHash)("sha256").update(qT(t.serverBaseUrl)).update("\0").update(t.projectId).digest("hex").slice(0,16);return(0,Mt.join)(N(),"state","server-outbox",e)}function du(t){return(0,Mt.join)(t,"outage.json")}function Et(t){return Fe(t)&&t.isFallbackEligible()&&t.kind!=="missing_api_key"}function JT(){return au=Math.max(Date.now(),au+1),au}function QT(t,e){let r=(0,lu.createHash)("sha256").update(JSON.stringify(e)).digest("hex").slice(0,16);return`${String(t).padStart(15,"0")}-${e.op}-${r}.json`}function xt(t,e){(0,H.mkdirSync)(e,{recursive:!0});let r=An(t),n=JT(),s=(0,Mt.join)(e,QT(n,r));return U(s,{version:1,heldAtEpochMs:n,entry:r}),f.warn("HOOK","Hosted server unreachable; capture held on this computer until it is back",{op:t.op,path:s}),s}function sm(t){return(0,H.existsSync)(t)?(0,H.readdirSync)(t).filter(e=>e.endsWith(".json")&&e!=="outage.json").sort():[]}function uu(t){try{return sm(t).length}catch{return 0}}function ZT(t){for(let e of(0,H.readdirSync)(t)){if(!e.endsWith(`.json${cu}`))continue;let r=(0,Mt.join)(t,e);try{if(Date.now()-(0,H.statSync)(r).mtimeMs<GT)continue;(0,H.renameSync)(r,r.slice(0,-cu.length))}catch{}}}async function fu(t,e,r=()=>({}),n=()=>{}){let s=e;if(!s.serverSessionId){let i=await t.startSession({projectId:e.projectId,externalSessionId:e.contentSessionId,contentSessionId:e.contentSessionId,platformSource:e.platformSource},r());s={...s,serverSessionId:i.session.id},n(s)}let o=s.serverSessionId;s.eventRecorded||(await t.recordEvent({projectId:e.projectId,serverSessionId:o,contentSessionId:e.contentSessionId,platformSource:e.platformSource,sourceType:"hook",eventType:"assistant_message",occurredAtEpoch:e.occurredAtEpoch,payload:{last_assistant_message:e.lastAssistantMessage,platformSource:e.platformSource}},r()),s={...s,eventRecorded:!0},n(s)),await t.endSession({sessionId:o},r())}async function eI(t,e,r,n){let s=()=>({timeoutMs:Math.max(1,r-Date.now())});e.op==="event"?await t.recordEvent(e.request,s()):e.op==="session_start"?await t.startSession(e.request,s()):await fu(t,e.request,s,n)}function nm(t,e,r){try{(0,H.mkdirSync)((0,Mt.join)(t,rm),{recursive:!0}),(0,H.renameSync)(e,(0,Mt.join)(t,rm,r))}catch(n){f.error("HOOK","Could not move a rejected held capture aside",{name:r},n instanceof Error?n:new Error(String(n)))}}async function xr(t,e,r={}){let n=r.maxEntries??VT,s=Date.now()+(r.budgetMs??YT),o={delivered:0,remaining:0,rejected:0};try{if(!(0,H.existsSync)(e))return o;ZT(e);let i=sm(e),a=0;for(let c of i){if(a>=n||Date.now()>=s)break;let u=(0,Mt.join)(e,c),l=`${u}${cu}`;try{(0,H.renameSync)(u,l)}catch{continue}try{let p=new Date;(0,H.utimesSync)(l,p,p)}catch{}a++;let d;try{if(d=JSON.parse((0,H.readFileSync)(l,"utf-8")),d?.version!==1||!d.entry?.op)throw new Error("unrecognised held capture")}catch(p){f.error("HOOK","Held capture is unreadable; moved aside",{name:c},p instanceof Error?p:new Error(String(p))),nm(e,l,c),o.rejected++;continue}try{let p=m=>{try{U(l,{...d,entry:{op:"summarize",request:m}})}catch{}},g=a===1?Math.max(s,Date.now()+Q.API_REQUEST):s;await eI(t,d.entry,g,p),(0,H.unlinkSync)(l),o.delivered++}catch(p){if(Et(p)){(0,H.renameSync)(l,u);break}f.error("HOOK","Hosted server refused a held capture; moved aside",{name:c,op:d.entry.op,status:Fe(p)?p.status:null},p instanceof Error?p:new Error(String(p))),nm(e,l,c),o.rejected++}}o.remaining=uu(e),o.delivered>0&&f.info("HOOK","Sent held captures to the hosted server",{...o}),o.remaining===0&&rI(e)}catch(i){f.warn("HOOK","Could not send held captures; they stay on this computer",{},i instanceof Error?i:new Error(String(i))),o.remaining=uu(e)}return o}function tI(t){try{let e=JSON.parse((0,H.readFileSync)(du(t),"utf-8"));return{notifiedSessionIds:Array.isArray(e.notifiedSessionIds)?e.notifiedSessionIds:[]}}catch{return{notifiedSessionIds:[]}}}function rI(t){try{(0,H.unlinkSync)(du(t))}catch{}}function nI(t){return`MemIndex can't reach your hosted memory server. ${t===1?"1 capture from this computer is":`${t} captures from this computer are`} saved and will be sent automatically when it's back. Recall from hosted memory is paused until then.`}function om(t,e){if(!t)return null;let r=uu(e);if(r===0)return null;let n=tI(e);if(n.notifiedSessionIds.includes(t))return null;try{U(du(e),{notifiedSessionIds:[...n.notifiedSessionIds,t].slice(-zT)})}catch{}return nI(r)}var lu,H,Mt,cu,rm,GT,zT,VT,YT,au,On=E(()=>{"use strict";lu=require("crypto"),H=require("fs"),Mt=require("path");se();C();xe();O();Ze();tr();cu=".sending",rm="rejected",GT=120*1e3,zT=50,VT=20,YT=1500;au=0});function Wo(t){return pI.run(t,!0)}function gI(t,e,r,n,s,o){return{projectId:t.projectId,externalSessionId:r,contentSessionId:r,agentId:e.agentId??null,agentType:e.agentType??null,platformSource:n,metadata:{project:s,prompt:o}}}async function mI(t,e,r){await t.client.startSession(e,{timeoutMs:r}),f.info("HOOK","session-init: server session started",{contentSessionId:e.contentSessionId,project:e.metadata?.project})}function hI(t){let e=t.replace(cI," ").toLowerCase().match(/[\p{L}\p{N}_]{4,}/gu)??[],r=[...new Set(e)].slice(0,aI);return r.length>0?r.join(" or "):null}async function _I(t,e,r,n,s,o,i){if(e.length<20||e==="[media prompt]")return"";let a=hI(e);if(!a)return"";let c=pu(o,i);if(c<Bo)return f.warn("HOOK","session-init: skipping server semantic injection because the prompt budget is spent",{remainingMs:c}),"";try{let u=await t.client.contextObservations({projectId:t.projectId,query:a,limit:Math.min(200,yI(s.MEMINDEX_SEMANTIC_INJECT_LIMIT||"5")),platformSource:n,...r.length>0?{folderProjects:r.slice(0,20)}:{}},{timeoutMs:c}),l=Array.isArray(u?.observations)?u.observations.length:0;return f.debug("HOOK",`Server semantic injection: ${l} observations for prompt`,{count:l}),typeof u?.context=="string"?u.context.slice(0,uI):""}catch(u){return f.warn("HOOK","session-init: server semantic context unavailable",{error:u instanceof Error?u.message:String(u)}),""}}function EI(t){let e=String(t.MEMINDEX_SEMANTIC_INJECT).toLowerCase();return e==="auto"?String(t.MEMINDEX_MODE).toLowerCase()==="personal":e==="true"}function SI(t){let e=String(t.MEMINDEX_READ_ONLY??"").toLowerCase();return e==="1"||e==="true"}async function im(t,e,r,n,s,o,i){if(!e||e.length<20||e==="[media prompt]")return"";let a=pu(o,i);if(a<Bo)return f.warn("HOOK","session-init: skipping semantic injection because the prompt budget is spent",{project:r,remainingMs:a}),"";let c=await de.executeWithWorkerFallback("/api/context/semantic","POST",{q:e,project:r,projects:n,limit:t.MEMINDEX_SEMANTIC_INJECT_LIMIT||"5",format:t.MEMINDEX_SEMANTIC_INJECT_FORMAT,platformSource:s},am(s,a));return de.isWorkerFallback(c)||!c?.context?"":(f.debug("HOOK",`Semantic injection: ${c.count} matches for prompt`,{project:r,count:c.count}),c.context)}function yI(t){let e=typeof t=="number"?t:Number.parseInt(t,10);return!Number.isFinite(e)||e<=0?5:e}function pu(t,e){return Math.max(0,e-(Date.now()-t))}function am(t,e){return t==="codex"?{workerStartupTimeoutMs:Q.POST_SPAWN_WAIT,timeoutMs:Math.min(lI,e)}:{timeoutMs:e}}var oI,de,iI,aI,cI,uI,Bo,lI,kr,dI,fI,pI,gu=E(()=>{"use strict";Pt();qt();O();xe();Pr();ft();ht();Vg();Ze();Mr();tr();On();oI={executeWithWorkerFallback:Gg,getSessionInitRequestTimeoutMs:Tg,isWorkerFallback:Kg,consumeWorkerOutageNotice:Xg,loadFromFileOnce:G,resolveRuntimeContext:Le,logServerFallback:Ue,holdForServer:xt,consumeServerOutageNotice:om,shouldTrackProject:Qe,readHookEnvironment:()=>process.env},de=oI,iI=2,aI=12,cI=/<private\b[^>]*>[\s\S]*?<\/private\s*>/gi,uI=1e4,Bo=500,lI=2e3,kr=class extends Error{constructor(r){super(`session-init did not record the prompt (${r})`);this.reason=r;this.name="SessionPromptNotRecordedError"}reason};dI=t=>t?t.replace(/\\/g,"/").includes("/.qwen/"):!1,fI=(t,e=process.env)=>t?e.QWEN_PROJECT_DIR?!0:dI(t):!1,pI={async run(t,e){let{sessionId:r,prompt:n,submittedPrompt:s}=t,o=t.cwd??process.cwd();if(!r)return f.warn("HOOK","session-init: No sessionId provided, skipping (Codex CLI or unknown platform)"),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};if(!de.shouldTrackProject(o))return f.info("HOOK","Project excluded from tracking",{cwd:o}),{continue:!0,suppressOutput:!0};if(n&&Lo(n))return f.debug("HOOK","session-init: skipping internal protocol payload",{preview:n.slice(0,80)}),{continue:!0,suppressOutput:!0};if(n&&z(t.platform)==="codex"&&tm(n))return f.debug("HOOK","session-init: skipping a Codex internal helper prompt",{reason:"internal_system_prompt",preview:n.slice(0,80)}),{continue:!0,suppressOutput:!0};if(s===null)return f.debug("HOOK","session-init: host reported no user-submitted text; not storing a prompt",{sessionId:r}),{continue:!0,suppressOutput:!0};if(s===void 0&&!n?.trim()&&fI(t.transcriptPath,de.readHookEnvironment()))return f.debug("HOOK","session-init: Qwen send carried no submitted_prompt and no prompt text; not storing a prompt",{sessionId:r}),{continue:!0,suppressOutput:!0};let i=s??n,a=!i||!i.trim()?"[media prompt]":i,c=lo(o),u=c.primary,l=z(t.platform),d=de.loadFromFileOnce(),p=EI(d),g=de.resolveRuntimeContext(),m=Date.now(),h=de.getSessionInitRequestTimeoutMs();if(g.runtime==="server"){let y=gI(g,t,r,l,u,a);try{await mI(g,y,Math.max(Bo,Math.floor(h/iI)));let A=p?await _I(g,a,c.allProjects,l,d,m,h):"";return A?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:A}}:{continue:!0,suppressOutput:!0}}catch(A){if(Et(A)){de.logServerFallback(A.kind,{status:A.status,message:A.message,route:"/v1/sessions/start",held:!0});let v=$e(g);de.holdForServer({op:"session_start",request:y},v);let R=de.consumeServerOutageNotice(r,v);return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS,...R?{systemMessage:R,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:R}}:{}}}if(Fe(A)&&A.isFallbackEligible())de.logServerFallback(A.kind,{status:A.status,message:A.message,route:"/v1/sessions/start"});else return f.error("HOOK","Server session-start failed (non-recoverable)",{error:A instanceof Error?A.message:String(A)}),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS}}}if(SI(de.readHookEnvironment())){let y=p?await im(d,a,u,c.allProjects,l,m,h):"";return y?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:y}}:{continue:!0,suppressOutput:!0}}f.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:r,project:u});let _=pu(m,h);if(_<Bo){if(f.warn("HOOK","session-init: skipping the worker call because the prompt budget is spent",{contentSessionId:r,project:u,remainingMs:_}),e)throw new kr("budget_exhausted");return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS}}let S=await de.executeWithWorkerFallback("/api/sessions/init","POST",{contentSessionId:r,project:u,prompt:a,platformSource:l,cwd:o,projectKeySource:c.keySource},am(l,_));if(de.isWorkerFallback(S)){if(e)throw new kr("reason"in S?S.reason:"worker_fallback");let y=await de.consumeWorkerOutageNotice(r);return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS,...y?{systemMessage:y}:{}}}if(typeof S?.sessionDbId!="number")return f.failure("HOOK","Session initialization returned malformed response",{contentSessionId:r,project:u}),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};let b=S.sessionDbId,w=S.promptNumber;if(f.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:b,promptNumber:w,skipped:S.skipped,contextInjected:S.contextInjected}),f.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${r} | prompt#=${w} | sessionDbId=${b}`),S.skipped&&S.reason==="private")return f.info("HOOK",`INIT_COMPLETE | sessionDbId=${b} | promptNumber=${w} | skipped=true | reason=private`,{sessionId:b}),{continue:!0,suppressOutput:!0};let T=p?await im(d,a,u,c.allProjects,l,m,h):"";return f.info("HOOK",`INIT_COMPLETE | sessionDbId=${b} | promptNumber=${w} | project=${u}`,{sessionId:b}),T?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:T}}:{continue:!0,suppressOutput:!0}}}});var cm=E(()=>{"use strict";Wt();C()});function Ko(){return(0,Be.join)(N(),"state","hook-spool")}function Ho(t){if(t===null||typeof t!="object")return JSON.stringify(t)??"null";if(Array.isArray(t))return`[${t.map(Ho).join(",")}]`;let e=t;return`{${Object.keys(e).filter(n=>e[n]!==void 0).sort().map(n=>`${JSON.stringify(n)}:${Ho(e[n])}`).join(",")}}`}function RI(t,e){if(t==="summarize"&&e.turnId){let n=e;return(0,jo.createHash)("sha256").update(Ho({contentSessionId:n.contentSessionId,platformSource:z(n.platformSource),turnId:n.turnId,lastAssistantMessage:n.lastAssistantMessage})).digest("hex")}let r=e.toolUseId;return typeof r=="string"&&dm.test(r)?`${(0,jo.createHash)("sha256").update(e.contentSessionId).update("\0").update(z(e.platformSource)).digest("hex")}-${r}`:(0,jo.createHash)("sha256").update(t).update("\0").update(e.contentSessionId).update("\0").update(Ho(e)).digest("hex")}function lm(t){return typeof t=="string"&&t.length>0}function mu(t){let e;try{e=JSON.parse(t)}catch(o){return{corruptReason:`invalid JSON: ${o instanceof Error?o.message:String(o)}`}}if(e===null||typeof e!="object")return{corruptReason:"not an object"};let r=e;if(!bI.includes(r.kind))return{corruptReason:`unknown kind ${JSON.stringify(r.kind)}`};if(typeof r.enqueuedAtEpochMs!="number"||!Number.isFinite(r.enqueuedAtEpochMs))return{corruptReason:"missing enqueuedAtEpochMs"};let n=r.payload;if(n===null||typeof n!="object"||!lm(n.contentSessionId))return{corruptReason:"payload missing contentSessionId"};let s=r.kind;return(s==="observation"||s==="file_edit")&&!lm(n.toolName)?{corruptReason:"observation payload missing toolName"}:s==="summarize"&&typeof n.lastAssistantMessage!="string"?{corruptReason:"summarize payload missing lastAssistantMessage"}:s==="advisor_calls"&&(!Array.isArray(n.calls)||n.calls.length===0)?{corruptReason:"advisor_calls payload has no calls"}:{kind:s,payload:{...n,platformSource:z(n.platformSource)},enqueuedAtEpochMs:r.enqueuedAtEpochMs}}function AI(){return hu=Math.max(Date.now(),hu+1),hu}var jo,te,Be,bI,wI,dm,TI,II,um,vI,hu,Xo,_u=E(()=>{"use strict";jo=require("crypto"),te=require("fs"),Be=require("path");se();C();ht();O();cm();bI=["observation","file_edit","summarize","session_end","advisor_calls"],wI=/^[a-z_]+-[A-Za-z0-9_-]+\.json$/,dm=/^[A-Za-z0-9_-]{1,128}$/,TI="corrupt",II="expired",um=10080*60*1e3,vI=300*1e3;hu=0;Xo=class{constructor(e=Ko()){this.directory=e}directory;get corruptDirectory(){return(0,Be.join)(this.directory,TI)}get expiredDirectory(){return(0,Be.join)(this.directory,II)}enqueue(e,r,n){let s={...r,platformSource:z(r.platformSource)},o=(0,Be.join)(this.directory,`${e}-${RI(e,s)}.json`),i=s.toolUseId;if(typeof i=="string"&&dm.test(i)){let c=(0,Be.join)(this.directory,`${e}-${i}.json`);try{let u=mu((0,te.readFileSync)(c,"utf8"));!("corruptReason"in u)&&u.kind===e&&u.payload.contentSessionId===s.contentSessionId&&u.payload.platformSource===s.platformSource&&(o=c)}catch{}}let a=this.existingEnqueuedAt(o)??n??AI();return U(o,{kind:e,payload:s,enqueuedAtEpochMs:a}),o}entries(){return this.readEntries().files.map(e=>e.entry)}async drain(e,r){let{files:n,quarantined:s}=this.readEntries(),o=0,i=0,a=0;r?.pruneConsumedBefore(Date.now()-um);let c=new Set;for(let u of n){let l=u.filename.replace(/\.json$/,""),d=u.entry.kind==="summarize"&&!!u.entry.payload.turnId;if(r?.isConsumed(l)){f.info("HOOK","Hook spool entry was already handed to ingest before a restart; removing it without ingesting again",{kind:u.entry.kind,contentSessionId:u.entry.payload.contentSessionId,file:u.filename}),this.unlinkEntry(u)?(d||r.clearConsumed(l),o++):i++;continue}let p=JSON.stringify([u.entry.payload.contentSessionId,u.entry.payload.platformSource]);if((u.entry.kind==="summarize"||u.entry.kind==="session_end")&&c.has(p)){i++;continue}let g=!1,m=()=>{if(!g){g=!0;try{r?.markConsumed(l,Date.now())}catch(_){f.error("HOOK","Could not record a hook spool hand-off marker; a crash before the file is removed would ingest it twice",{kind:u.entry.kind,contentSessionId:u.entry.payload.contentSessionId,file:u.filename},_ instanceof Error?_:new Error(String(_)))}}},h;try{h=await e(u.entry,m)}catch(_){f.warn("HOOK",g?"Hook spool entry failed after ingest accepted it; removing it (a retry would send it twice)":"Hook spool entry failed to ingest; keeping it for the next drain",{kind:u.entry.kind,contentSessionId:u.entry.payload.contentSessionId,file:u.filename},_ instanceof Error?_:new Error(String(_))),h=!1}if(g&&(h=!0),h==="expired"){this.expireIfPastWindow(u,vI,"unknown-session grace window")?a++:i++;continue}if(!h){this.expireIfPastWindow(u,um,"retry window")?a++:((u.entry.kind==="observation"||u.entry.kind==="file_edit")&&c.add(p),i++);continue}this.unlinkEntry(u)?(d||r?.clearConsumed(l),o++):i++}return{drained:o,retained:i,quarantined:s,expired:a}}unlinkEntry(e){try{return(0,te.unlinkSync)(e.path),!0}catch(r){return r.code==="ENOENT"?!0:(f.warn("HOOK","Hook spool entry was ingested but could not be removed",{kind:e.entry.kind,file:e.filename},r instanceof Error?r:new Error(String(r))),!1)}}expireIfPastWindow(e,r,n){let s=Date.now()-e.entry.enqueuedAtEpochMs;if(s<=r)return!1;let o={kind:e.entry.kind,contentSessionId:e.entry.payload.contentSessionId,ageMinutes:Math.round(s/6e4),ageHours:Math.round(s/36e5),file:e.filename,expiredDirectory:this.expiredDirectory};try{(0,te.mkdirSync)(this.expiredDirectory,{recursive:!0}),(0,te.renameSync)(e.path,(0,Be.join)(this.expiredDirectory,e.filename))}catch(i){return f.error("HOOK",`Hook spool entry is past its ${n} but could not be moved to expired/; keeping it`,o,i instanceof Error?i:new Error(String(i))),!1}return f.error("HOOK",`Hook spool entry was never accepted within its ${n}; moved to expired/`,o),!0}existingEnqueuedAt(e){if(!(0,te.existsSync)(e))return null;try{let r=mu((0,te.readFileSync)(e,"utf-8"));return"corruptReason"in r?null:r.enqueuedAtEpochMs}catch(r){return f.debug("HOOK","Could not read existing hook spool entry; writing a fresh one",{entryPath:e},r instanceof Error?r:new Error(String(r))),null}}quarantine(e,r){let n=(0,Be.join)(this.directory,e);try{return(0,te.mkdirSync)(this.corruptDirectory,{recursive:!0}),(0,te.renameSync)(n,(0,Be.join)(this.corruptDirectory,e)),f.error("HOOK","Quarantined corrupt hook spool entry",{file:e,reason:r,corruptDirectory:this.corruptDirectory}),!0}catch(s){return f.error("HOOK","Corrupt hook spool entry could not be quarantined; leaving it in place",{file:e,reason:r},s instanceof Error?s:new Error(String(s))),!1}}readEntries(){if(!(0,te.existsSync)(this.directory))return{files:[],quarantined:0};let e;try{e=(0,te.readdirSync)(this.directory).filter(s=>wI.test(s))}catch(s){return f.warn("HOOK","Could not list hook spool entries",{directory:this.directory},s instanceof Error?s:new Error(String(s))),{files:[],quarantined:0}}let r=[],n=0;for(let s of e){let o=(0,Be.join)(this.directory,s),i;try{i=(0,te.readFileSync)(o,"utf-8")}catch(c){c.code!=="ENOENT"&&f.warn("HOOK","Could not read hook spool entry; will retry",{file:s},c instanceof Error?c:new Error(String(c)));continue}let a=mu(i);if("corruptReason"in a){this.quarantine(s,a.corruptReason)&&n++;continue}r.push({entry:a,path:o,filename:s})}return r.sort((s,o)=>s.entry.enqueuedAtEpochMs-o.entry.enqueuedAtEpochMs||s.filename.localeCompare(o.filename)),{files:r,quarantined:n}}}});var gm={};As(gm,{SPOOL_NUDGE_TIMEOUT_MS:()=>fm,nudgeWorkerToDrainHookSpool:()=>pm,settleHookSpoolNudges:()=>OI,spoolHookEvent:()=>We});function pm(){if(Pn)return Pn;let t=(async()=>{try{await(await le("/api/spool/nudge",{method:"POST",timeoutMs:fm})).body?.cancel()}catch(e){f.debug("HOOK","Hook spool nudge not delivered (worker will pick the entry up on its own)",{error:e instanceof Error?e.message:String(e)})}})();return Pn=t,Eu.add(t),t.finally(()=>{Eu.delete(t),Pn===t&&(Pn=null)}),t}async function OI(){await Promise.all([...Eu])}function We(t,e,r){let n=new Xo().enqueue(t,e,r);return f.debug("HOOK","Hook event spooled for the worker",{kind:t,entryPath:n}),pm(),n}var fm,Eu,Pn,Nr=E(()=>{"use strict";_u();Pt();O();fm=250,Eu=new Set,Pn=null});function kt(t,e){return e?new Set(e.split(",").map(n=>n.trim().toLowerCase()).filter(Boolean)).has(t.toLowerCase()):!1}var Mn=E(()=>{"use strict"});function wm(t,e){return!!t&&!!e}var Tm=E(()=>{"use strict"});function CI(t){return new Set((t??"").split(",").map(e=>e.trim()).filter(Boolean))}function Dr(t,e,r){return wm(t,e)?r.MEMINDEX_SKIP_SUBAGENT_OBSERVATIONS==="true"?{skip:!0,reason:"subagent_observation"}:e&&CI(r.MEMINDEX_SKIP_AGENT_TYPES).has(e)?{skip:!0,reason:"agent_type_excluded"}:Im:Im}var Im,zo=E(()=>{"use strict";Tm();Im={skip:!1}});var Tt,Tl=E(()=>{Tt="1.9.1"});function WA(t){let e=new Set([t]),r=new Set,n=t.match(v_);if(!n)return()=>!1;let s={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(s.prerelease!=null)return function(c){return c===t};function o(a){return r.add(a),!1}function i(a){return e.add(a),!0}return function(c){if(e.has(c))return!0;if(r.has(c))return!1;let u=c.match(v_);if(!u)return o(c);let l={major:+u[1],minor:+u[2],patch:+u[3],prerelease:u[4]};return l.prerelease!=null||s.major!==l.major?o(c):s.major===0?s.minor===l.minor&&s.patch<=l.patch?i(c):o(c):s.minor<=l.minor?i(c):o(c)}}var v_,R_,A_=E(()=>{Tl();v_=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;R_=WA(Tt)});function st(t,e,r,n=!1){var s;let o=ls[us]=(s=ls[us])!==null&&s!==void 0?s:{version:Tt};if(!n&&o[t]){let i=new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${t}`);return r.error(i.stack||i.message),!1}if(o.version!==Tt){let i=new Error(`@opentelemetry/api: Registration of version v${o.version} for ${t} does not match previously registered API v${Tt}`);return r.error(i.stack||i.message),!1}return o[t]=e,r.debug(`@opentelemetry/api: Registered a global for ${t} v${Tt}.`),!0}function ye(t){var e,r;let n=(e=ls[us])===null||e===void 0?void 0:e.version;if(!(!n||!R_(n)))return(r=ls[us])===null||r===void 0?void 0:r[t]}function ot(t,e){e.debug(`@opentelemetry/api: Unregistering a global for ${t} v${Tt}.`);let r=ls[us];r&&delete r[t]}var jA,us,ls,dr=E(()=>{Tl();A_();jA=Tt.split(".")[0],us=Symbol.for(`opentelemetry.js.api.${jA}`),ls=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{}});function ds(t,e,r){let n=ye("diag");if(n)return n[t](e,...r)}var Ni,O_=E(()=>{dr();Ni=class{constructor(e){this._namespace=e.namespace||"DiagComponentLogger"}debug(...e){return ds("debug",this._namespace,e)}error(...e){return ds("error",this._namespace,e)}info(...e){return ds("info",this._namespace,e)}warn(...e){return ds("warn",this._namespace,e)}verbose(...e){return ds("verbose",this._namespace,e)}}});var ne,Ci=E(()=>{(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(ne||(ne={}))});function P_(t,e){t<ne.NONE?t=ne.NONE:t>ne.ALL&&(t=ne.ALL),e=e||{};function r(n,s){let o=e[n];return typeof o=="function"&&t>=s?o.bind(e):function(){}}return{error:r("error",ne.ERROR),warn:r("warn",ne.WARN),info:r("info",ne.INFO),debug:r("debug",ne.DEBUG),verbose:r("verbose",ne.VERBOSE)}}var M_=E(()=>{Ci()});var HA,ee,fr=E(()=>{O_();M_();Ci();dr();HA="diag",ee=class t{static instance(){return this._instance||(this._instance=new t),this._instance}constructor(){function e(s){return function(...o){let i=ye("diag");if(i)return i[s](...o)}}let r=this,n=(s,o={logLevel:ne.INFO})=>{var i,a,c;if(s===r){let d=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((i=d.stack)!==null&&i!==void 0?i:d.message),!1}typeof o=="number"&&(o={logLevel:o});let u=ye("diag"),l=P_((a=o.logLevel)!==null&&a!==void 0?a:ne.INFO,s);if(u&&!o.suppressOverrideMessage){let d=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";u.warn(`Current logger will be overwritten from ${d}`),l.warn(`Current logger will overwrite one already registered from ${d}`)}return st("diag",l,r,!0)};r.setLogger=n,r.disable=()=>{ot(HA,r)},r.createComponentLogger=s=>new Ni(s),r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error")}}});var Di,x_=E(()=>{Di=class t{constructor(e){this._entries=e?new Map(e):new Map}getEntry(e){let r=this._entries.get(e);if(r)return Object.assign({},r)}getAllEntries(){return Array.from(this._entries.entries())}setEntry(e,r){let n=new t(this._entries);return n._entries.set(e,r),n}removeEntry(e){let r=new t(this._entries);return r._entries.delete(e),r}removeEntries(...e){let r=new t(this._entries);for(let n of e)r._entries.delete(n);return r}clear(){return new t}}});var k_,N_=E(()=>{k_=Symbol("BaggageEntryMetadata")});function C_(t={}){return new Di(new Map(Object.entries(t)))}function D_(t){return typeof t!="string"&&(XA.error(`Cannot create baggage metadata from unknown type: ${typeof t}`),t=""),{__TYPE__:k_,toString(){return t}}}var XA,Il=E(()=>{fr();x_();N_();XA=ee.instance()});function Yr(t){return Symbol.for(t)}var vl,Fi,fs=E(()=>{vl=class t{constructor(e){let r=this;r._currentContext=e?new Map(e):new Map,r.getValue=n=>r._currentContext.get(n),r.setValue=(n,s)=>{let o=new t(r._currentContext);return o._currentContext.set(n,s),o},r.deleteValue=n=>{let s=new t(r._currentContext);return s._currentContext.delete(n),s}}},Fi=new vl});var Rl,Al,Li,F_=E(()=>{Rl=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}],Al={};if(typeof console<"u"){let t=["error","warn","info","debug","trace","log"];for(let e of t)typeof console[e]=="function"&&(Al[e]=console[e])}Li=class{constructor(){function e(r){return function(...n){let s=Al[r];if(typeof s!="function"&&(s=Al.log),typeof s!="function"&&console&&(s=console[r],typeof s!="function"&&(s=console.log)),typeof s=="function")return s.apply(console,n)}}for(let r=0;r<Rl.length;r++)this[Rl[r].n]=e(Rl[r].c)}}});function L_(){return Fl}var Ol,qr,Pl,Ml,xl,kl,ps,Nl,Cl,Dl,Fl,KA,GA,zA,VA,YA,qA,JA,Ll=E(()=>{Ol=class{constructor(){}createGauge(e,r){return GA}createHistogram(e,r){return zA}createCounter(e,r){return KA}createUpDownCounter(e,r){return VA}createObservableGauge(e,r){return qA}createObservableCounter(e,r){return YA}createObservableUpDownCounter(e,r){return JA}addBatchObservableCallback(e,r){}removeBatchObservableCallback(e){}},qr=class{},Pl=class extends qr{add(e,r){}},Ml=class extends qr{add(e,r){}},xl=class extends qr{record(e,r){}},kl=class extends qr{record(e,r){}},ps=class{addCallback(e){}removeCallback(e){}},Nl=class extends ps{},Cl=class extends ps{},Dl=class extends ps{},Fl=new Ol,KA=new Pl,GA=new xl,zA=new kl,VA=new Ml,YA=new Nl,qA=new Cl,JA=new Dl});var Ui,U_=E(()=>{(function(t){t[t.INT=0]="INT",t[t.DOUBLE=1]="DOUBLE"})(Ui||(Ui={}))});var $i,Bi,Ul=E(()=>{$i={get(t,e){if(t!=null)return t[e]},keys(t){return t==null?[]:Object.keys(t)}},Bi={set(t,e,r){t!=null&&(t[e]=r)}}});var Wi,$_=E(()=>{fs();Wi=class{active(){return Fi}with(e,r,n,...s){return r.call(n,...s)}bind(e,r){return r}enable(){return this}disable(){return this}}});var $l,QA,it,gs=E(()=>{$_();dr();fr();$l="context",QA=new Wi,it=class t{constructor(){}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalContextManager(e){return st($l,e,ee.instance())}active(){return this._getContextManager().active()}with(e,r,n,...s){return this._getContextManager().with(e,r,n,...s)}bind(e,r){return this._getContextManager().bind(e,r)}_getContextManager(){return ye($l)||QA}disable(){this._getContextManager().disable(),ot($l,ee.instance())}}});var Jr,Bl=E(()=>{(function(t){t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED"})(Jr||(Jr={}))});var ms,hs,ji,Hi=E(()=>{Bl();ms="0000000000000000",hs="00000000000000000000000000000000",ji={traceId:hs,spanId:ms,traceFlags:Jr.NONE}});var at,Xi=E(()=>{Hi();at=class{constructor(e=ji){this._spanContext=e}spanContext(){return this._spanContext}setAttribute(e,r){return this}setAttributes(e){return this}addEvent(e,r){return this}addLink(e){return this}addLinks(e){return this}setStatus(e){return this}updateName(e){return this}end(e){}isRecording(){return!1}recordException(e,r){}}});function Ki(t){return t.getValue(Wl)||void 0}function B_(){return Ki(it.getInstance().active())}function _s(t,e){return t.setValue(Wl,e)}function W_(t){return t.deleteValue(Wl)}function j_(t,e){return _s(t,new at(e))}function Gi(t){var e;return(e=Ki(t))===null||e===void 0?void 0:e.spanContext()}var Wl,jl=E(()=>{fs();Xi();gs();Wl=Yr("OpenTelemetry Context Key SPAN")});function H_(t,e){if(typeof t!="string"||t.length!==e)return!1;let r=0;for(let n=0;n<t.length;n+=4)r+=(zi[t.charCodeAt(n)]|0)+(zi[t.charCodeAt(n+1)]|0)+(zi[t.charCodeAt(n+2)]|0)+(zi[t.charCodeAt(n+3)]|0);return r===e}function Hl(t){return H_(t,32)&&t!==hs}function Xl(t){return H_(t,16)&&t!==ms}function Qr(t){return Hl(t.traceId)&&Xl(t.spanId)}function X_(t){return new at(t)}var zi,Vi=E(()=>{Hi();Xi();zi=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1])});function ZA(t){return t!==null&&typeof t=="object"&&"spanId"in t&&typeof t.spanId=="string"&&"traceId"in t&&typeof t.traceId=="string"&&"traceFlags"in t&&typeof t.traceFlags=="number"}var Kl,Zr,Gl=E(()=>{gs();jl();Xi();Vi();Kl=it.getInstance(),Zr=class{startSpan(e,r,n=Kl.active()){if(!!r?.root)return new at;let o=n&&Gi(n);return ZA(o)&&Qr(o)?new at(o):new at}startActiveSpan(e,r,n,s){let o,i,a;if(arguments.length<2)return;arguments.length===2?a=r:arguments.length===3?(o=r,a=n):(o=r,i=n,a=s);let c=i??Kl.active(),u=this.startSpan(e,o,c),l=_s(c,u);return Kl.with(l,a,void 0,u)}}});var eO,en,zl=E(()=>{Gl();eO=new Zr,en=class{constructor(e,r,n,s){this._provider=e,this.name=r,this.version=n,this.options=s}startSpan(e,r,n){return this._getTracer().startSpan(e,r,n)}startActiveSpan(e,r,n,s){let o=this._getTracer();return Reflect.apply(o.startActiveSpan,o,arguments)}_getTracer(){if(this._delegate)return this._delegate;let e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):eO}}});var Yi,K_=E(()=>{Gl();Yi=class{getTracer(e,r,n){return new Zr}}});var tO,pr,Vl=E(()=>{zl();K_();tO=new Yi,pr=class{getTracer(e,r,n){var s;return(s=this.getDelegateTracer(e,r,n))!==null&&s!==void 0?s:new en(this,e,r,n)}getDelegate(){var e;return(e=this._delegate)!==null&&e!==void 0?e:tO}setDelegate(e){this._delegate=e}getDelegateTracer(e,r,n){var s;return(s=this._delegate)===null||s===void 0?void 0:s.getTracer(e,r,n)}}});var qi,G_=E(()=>{(function(t){t[t.NOT_RECORD=0]="NOT_RECORD",t[t.RECORD=1]="RECORD",t[t.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"})(qi||(qi={}))});var Ji,z_=E(()=>{(function(t){t[t.INTERNAL=0]="INTERNAL",t[t.SERVER=1]="SERVER",t[t.CLIENT=2]="CLIENT",t[t.PRODUCER=3]="PRODUCER",t[t.CONSUMER=4]="CONSUMER"})(Ji||(Ji={}))});var Qi,V_=E(()=>{(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(Qi||(Qi={}))});function Y_(t){return sO.test(t)}function q_(t){return oO.test(t)&&!iO.test(t)}var Yl,rO,nO,sO,oO,iO,J_=E(()=>{Yl="[_0-9a-z-*/]",rO=`[a-z]${Yl}{0,255}`,nO=`[a-z0-9]${Yl}{0,240}@[a-z]${Yl}{0,13}`,sO=new RegExp(`^(?:${rO}|${nO})$`),oO=/^[ -~]{0,255}[!-~]$/,iO=/,|=/});var Q_,aO,Z_,eE,Zi,tE=E(()=>{J_();Q_=32,aO=512,Z_=",",eE="=",Zi=class t{constructor(e){this._internalState=new Map,e&&this._parse(e)}set(e,r){let n=this._clone();return n._internalState.has(e)&&n._internalState.delete(e),n._internalState.set(e,r),n}unset(e){let r=this._clone();return r._internalState.delete(e),r}get(e){return this._internalState.get(e)}serialize(){return Array.from(this._internalState.keys()).reduceRight((e,r)=>(e.push(r+eE+this.get(r)),e),[]).join(Z_)}_parse(e){e.length>aO||(this._internalState=e.split(Z_).reduceRight((r,n)=>{let s=n.trim(),o=s.indexOf(eE);if(o!==-1){let i=s.slice(0,o),a=s.slice(o+1,n.length);Y_(i)&&q_(a)&&r.set(i,a)}return r},new Map),this._internalState.size>Q_&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,Q_))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let e=new t;return e._internalState=new Map(this._internalState),e}}});function rE(t){return new Zi(t)}var nE=E(()=>{tE()});var ql,sE=E(()=>{gs();ql=it.getInstance()});var Jl,oE=E(()=>{fr();Jl=ee.instance()});var Ql,iE,aE=E(()=>{Ll();Ql=class{getMeter(e,r,n){return Fl}},iE=new Ql});var Zl,ea,cE=E(()=>{aE();dr();fr();Zl="metrics",ea=class t{constructor(){}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalMeterProvider(e){return st(Zl,e,ee.instance())}getMeterProvider(){return ye(Zl)||iE}getMeter(e,r,n){return this.getMeterProvider().getMeter(e,r,n)}disable(){ot(Zl,ee.instance())}}});var ed,uE=E(()=>{cE();ed=ea.getInstance()});var ta,lE=E(()=>{ta=class{inject(e,r){}extract(e,r){return e}fields(){return[]}}});function rd(t){return t.getValue(td)||void 0}function dE(){return rd(it.getInstance().active())}function fE(t,e){return t.setValue(td,e)}function pE(t){return t.deleteValue(td)}var td,gE=E(()=>{gs();fs();td=Yr("OpenTelemetry Baggage Key")});var nd,cO,ra,mE=E(()=>{dr();lE();Ul();gE();Il();fr();nd="propagation",cO=new ta,ra=class t{constructor(){this.createBaggage=C_,this.getBaggage=rd,this.getActiveBaggage=dE,this.setBaggage=fE,this.deleteBaggage=pE}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalPropagator(e){return st(nd,e,ee.instance())}inject(e,r,n=Bi){return this._getGlobalPropagator().inject(e,r,n)}extract(e,r,n=$i){return this._getGlobalPropagator().extract(e,r,n)}fields(){return this._getGlobalPropagator().fields()}disable(){ot(nd,ee.instance())}_getGlobalPropagator(){return ye(nd)||cO}}});var sd,hE=E(()=>{mE();sd=ra.getInstance()});var od,na,_E=E(()=>{dr();Vl();Vi();jl();fr();od="trace",na=class t{constructor(){this._proxyTracerProvider=new pr,this.wrapSpanContext=X_,this.isSpanContextValid=Qr,this.deleteSpan=W_,this.getSpan=Ki,this.getActiveSpan=B_,this.getSpanContext=Gi,this.setSpan=_s,this.setSpanContext=j_}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalTracerProvider(e){let r=st(od,this._proxyTracerProvider,ee.instance());return r&&this._proxyTracerProvider.setDelegate(e),r}getTracerProvider(){return ye(od)||this._proxyTracerProvider}getTracer(e,r){return this.getTracerProvider().getTracer(e,r)}disable(){ot(od,ee.instance()),this._proxyTracerProvider=new pr}}});var id,EE=E(()=>{_E();id=na.getInstance()});var SE={};As(SE,{DiagConsoleLogger:()=>Li,DiagLogLevel:()=>ne,INVALID_SPANID:()=>ms,INVALID_SPAN_CONTEXT:()=>ji,INVALID_TRACEID:()=>hs,ProxyTracer:()=>en,ProxyTracerProvider:()=>pr,ROOT_CONTEXT:()=>Fi,SamplingDecision:()=>qi,SpanKind:()=>Ji,SpanStatusCode:()=>Qi,TraceFlags:()=>Jr,ValueType:()=>Ui,baggageEntryMetadataFromString:()=>D_,context:()=>ql,createContextKey:()=>Yr,createNoopMeter:()=>L_,createTraceState:()=>rE,default:()=>uO,defaultTextMapGetter:()=>$i,defaultTextMapSetter:()=>Bi,diag:()=>Jl,isSpanContextValid:()=>Qr,isValidSpanId:()=>Xl,isValidTraceId:()=>Hl,metrics:()=>ed,propagation:()=>sd,trace:()=>id});var uO,yE=E(()=>{Il();fs();F_();Ci();Ll();U_();Ul();zl();Vl();G_();z_();V_();Bl();nE();Vi();Hi();sE();oE();uE();hE();EE();uO={context:ql,diag:Jl,metrics:ed,propagation:sd,trace:id}});function WE(t){if(!t.startsWith("mcp__"))return null;let e=t.split("__");if(e.length<3)return null;let r=e[1].toLowerCase();return!r.includes("memindex")&&!r.includes("agent-mem")&&!r.includes("agent_mem")&&!r.includes("mcp-search")&&!r.includes("mcp_search")?null:e.slice(2).join("__")}function rn(t){if(!t)return!1;if(t.startsWith("memory_")||t==="mem_search"||t==="get_summaries")return!0;let e=WE(t);return e!==null&&tP.has(e)}function ma(t){return t==="save_memory"||WE(t)==="save_memory"}var tP,ha=E(()=>{"use strict";tP=new Set(["mem_search","search","timeline","get_observations","get_summaries","get_tool_uses","session_start_context","observation_search","observation_context","memory_search","memory_context"])});function hd(t){return typeof t=="string"&&t.length>0}var Is,nS=E(()=>{"use strict";Is=class extends Error{constructor(r){super(`adapter rejected input: ${r}`);this.reason=r;this.name="AdapterRejectedInput"}reason}});var yP,sS,_d,bP,wP,oS,iS=E(()=>{"use strict";nS();qt();yP=128,sS=t=>typeof t=="string"&&t.length>0&&t.length<=yP?t:void 0,_d=t=>typeof t=="string"?t:void 0,bP=t=>t.hook_event_name==="PostToolUseFailure"?{error:t.error,is_interrupt:t.is_interrupt===!0}:void 0,wP=t=>{if(typeof t!="object"||t===null)return;let e=t;if(!Object.prototype.hasOwnProperty.call(e,"submitted_prompt"))return;let r=e.submitted_prompt;return typeof r!="string"?null:r.trim()?r:null},oS={normalizeInput(t){let e=t??{},r=e.cwd??process.cwd();if(!hd(r))throw new Is("invalid_cwd");let n=fp(r);if(!hd(n))throw new Is("invalid_cwd");let s=e.source;return{sessionId:e.session_id??e.id??e.sessionId,hookEventName:_d(e.hook_event_name),cwd:n,sessionSource:s==="startup"||s==="resume"||s==="clear"||s==="compact"?s:void 0,prompt:e.prompt,submittedPrompt:wP(e),toolName:e.tool_name,toolInput:e.tool_input,toolResponse:e.tool_response??bP(e),toolUseId:typeof e.tool_use_id=="string"?e.tool_use_id:void 0,transcriptPath:e.transcript_path,lastAssistantMessage:_d(e.last_assistant_message),reason:_d(e.reason),agentId:sS(e.agent_id),agentType:sS(e.agent_type)}},formatOutput(t){let e=t??{};if(e.hookSpecificOutput){let n={hookSpecificOutput:t.hookSpecificOutput};return e.systemMessage&&(n.systemMessage=e.systemMessage),n}let r={};return e.systemMessage&&(r.systemMessage=e.systemMessage),r}}});function aS(t,e){return We("observation",{contentSessionId:t.sessionId,platformSource:e,toolName:t.toolName,toolInput:t.toolInput,toolResponse:t.toolResponse,cwd:t.cwd,agentId:t.agentId,agentType:t.agentType,toolUseId:t.toolUseId},t.spoolAtEpochMs),{continue:!0,suppressOutput:!0}}var cS,uS=E(()=>{"use strict";Nr();O();ou();xe();Pr();zo();ft();Mn();ht();Mr();tr();On();ha();cS={async execute(t){let{sessionId:e,cwd:r,toolName:n,toolInput:s,toolResponse:o}=t,i=z(t.platform);if(!n)return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};if(rn(n))return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};let a=Jg(f.formatTool(n,s));if(f.dataIn("HOOK",`PostToolUse: ${a}`,{}),!r)throw new Error(`Missing cwd in PostToolUse hook input for session ${e}, tool ${n}`);if(!Qe(r))return f.debug("HOOK","Project excluded from tracking, skipping observation",{cwd:r,toolName:n}),{continue:!0,suppressOutput:!0};let c=Dr(t.agentId,t.agentType,G());if(c.skip)return f.debug("HOOK",`Skipping observation: ${c.reason}`,{toolName:n,agentId:t.agentId,agentType:t.agentType}),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};if(ma(n))return aS(t,i);let u=Le();if(u.runtime==="server"){if(kt(n,G().MEMINDEX_SKIP_TOOLS))return f.debug("HOOK","Server runtime: tool excluded by MEMINDEX_SKIP_TOOLS",{toolName:n}),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};let l={projectId:u.projectId,contentSessionId:e,platformSource:i,sourceType:"hook",eventType:"tool_use",occurredAtEpoch:Date.now(),payload:{tool_name:n,tool_input:s,tool_response:o,cwd:r,agentId:t.agentId,agentType:t.agentType,platformSource:i,tool_use_id:t.toolUseId}};try{return await u.client.recordEvent(l),f.debug("HOOK","Observation sent successfully via server",{toolName:n}),await xr(u.client,$e(u)),{continue:!0,suppressOutput:!0}}catch(d){if(Et(d))return Ue(d.kind,{status:d.status,message:d.message,route:"/v1/events",held:!0}),xt({op:"event",request:l},$e(u)),{continue:!0,suppressOutput:!0};if(Fe(d)&&d.isFallbackEligible())Ue(d.kind,{status:d.status,message:d.message,route:"/v1/events"});else return f.error("HOOK","Server event failed (non-recoverable)",{error:d instanceof Error?d.message:String(d)}),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS}}}return aS(t,i)}}});function vP(t,e,r){let n=0;for(;n<e.length;){let s=(0,Xe.readSync)(t,e,n,e.length-n,r+n);if(s===0)break;n+=s}return n}function*RP(t,e){let r=Math.max(1,e.maxChunkBytes??lS),n=Math.min(r,Math.max(1,e.initialBytes??TP)),s=(0,Xe.openSync)(t,"r");try{let o=(0,Xe.fstatSync)(s).size,i=Buffer.alloc(0);for(;o>0;){let a=Math.max(0,o-n),c=Buffer.alloc(o-a),u=vP(s,c,a),l=u===c.length?c:c.subarray(0,u),d=i.length?Buffer.concat([l,i]):l;if(a===0){yield{text:d.toString("utf-8"),byteLength:l.length,isFirstChunkOfFile:!0};return}let p=d.indexOf(10);p===-1?(i=d,yield{text:"",byteLength:l.length,isFirstChunkOfFile:!1}):(i=d.subarray(0,p),yield{text:d.subarray(p+1).toString("utf-8"),byteLength:l.length,isFirstChunkOfFile:!1}),o=a,n=Math.min(n*4,r)}i.length&&(yield{text:i.toString("utf-8"),byteLength:0,isFirstChunkOfFile:!0})}finally{(0,Xe.closeSync)(s)}}function dS(t,e,r={}){if(!t||!(0,Xe.existsSync)(t)){f.warn("PARSER",`Transcript path missing or file does not exist: ${t}`);return}let n=!1;for(let s of RP(t,r)){!n&&s.text.trim()&&(n=!0);let o=e(s.text,s.isFirstChunkOfFile,s.byteLength);if(o!==void 0)return o}n||f.warn("PARSER",`Transcript file exists but is empty: ${t}`)}function*Ed(t){let e=t.split(`
|
|
24
|
+
`);for(let r=e.length-1;r>=0;r--){let n=e[r];if(!n)continue;let s;try{s=JSON.parse(n)}catch{continue}yield s}}function AP(t,e,r,n,s){let o,i=null,a,c,u=!1,l=0,d=Math.max(0,s?.modelSearchBudgetBytes??IP),p=dS(t,(g,m,h)=>{if(s?.includeTurnId&&!u)for(let b of Ed(g)){if(b.type!=="assistant"&&b.message?.role!=="assistant")continue;u=!0;let w=b.uuid??b.message?.id;typeof w=="string"&&w&&(c=w);break}if(o!==void 0&&(l+=h),n&&a===void 0&&(a=gS(g)),o===void 0){let b=kP(g,e,r);b.kind==="text"?o=b.text:b.kind!=="none"&&i===null&&(i=b.text)}let _=!n||a!==void 0||l>=d;if(o!==void 0&&_||m)return{text:o??i??"",model:a,turnId:c}},s);return p?n?p:{text:p.text}:{text:""}}function Sd(t,e=!1,r){let n=AP(t,"assistant",e,!0,r);return{text:n.text,...n.model===void 0?{}:{model:n.model},...n.turnId===void 0?{}:{turnId:n.turnId}}}function fS(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>!!e&&typeof e=="object"&&typeof e.text=="string"&&(e.type===void 0||e.type==="text")).map(e=>e.text).join(`
|
|
25
|
+
`):null}function PP(t){if(t?.type==="context.append_message"){let e=t.message?.role;return e==="user"||e==="assistant"?e:void 0}if(t?.type==="context.append_loop_event"&&t.event?.type==="content.part"&&t.event?.part?.type==="text")return"assistant"}function MP(t,e){if(e==="user"&&t?.type==="context.append_message")return fS(t.message?.content)??"";if(e==="assistant"&&t?.type==="context.append_loop_event"){let r=t.event?.part?.text;return typeof r=="string"?r:""}return""}function xP(t){let e=t.filter(n=>n?.type==="tool_use");return e.length===0?"":`[Session ended mid-task. Last tools used: ${e.map(n=>{let s=n.name??"unknown",o=n.input??{};return o.file_path?`${s}(${o.file_path})`:o.command?`${s}(${String(o.command).slice(0,60)})`:s}).join(", ")}]`}function kP(t,e,r){let n=!1,s=null,o="blank";for(let i of Ed(t)){let a=PP(i),c=typeof i.type=="string"?OP[i.type]:void 0;if((a??c??i.type??i.role)!==e)continue;n=!0;let l,d;if(a!==void 0)l=MP(i,e);else{if(d=c!==void 0?i.content:i.message?.content,d==null)continue;let p=fS(d);if(p===null)continue;l=p}if(r&&(l=l.replace(Fo,""),l=l.replace(/\n{3,}/g,`
|
|
26
26
|
|
|
27
|
-
`).trim()),l&&l.trim())return{kind:"text",text:l};if(s===null&&(s=l,!s.trim()&&Array.isArray(d))){let p=
|
|
28
|
-
`):""}function
|
|
29
|
-
`),s=null,
|
|
27
|
+
`).trim()),l&&l.trim())return{kind:"text",text:l};if(s===null&&(s=l,!s.trim()&&Array.isArray(d))){let p=xP(d);p&&(s=p,o="synthesized")}}return n?{kind:o,text:s??""}:{kind:"none",text:""}}function pS(t,e){if(!(!t||!(0,Xe.existsSync)(t)))return dS(t,r=>gS(r),e)}function gS(t){for(let e of Ed(t)){if((e.type??e.role)!=="assistant")continue;let r=e.message?.model;if(typeof r=="string"&&r)return r}}var Xe,TP,lS,IP,OP,mS=E(()=>{"use strict";Xe=require("fs");O();Ze();TP=256*1024,lS=64*1024*1024,IP=lS;OP={USER_INPUT:"user",PLANNER_RESPONSE:"assistant"}});function CP(t){return NP.has(t)}function DP(t=process.env){return t.CLAUDE_CONFIG_DIR?(0,yd.join)(t.CLAUDE_CONFIG_DIR,".claude.json"):(0,yd.join)((0,hS.homedir)(),".claude.json")}function Ta(t){if(!t)return!1;let e=t.trim().toLowerCase();return e!==""&&e!=="0"&&e!=="false"}function FP(t){if(!t||typeof t!="object")return{};let{oauthAccount:e,customApiKeyResponses:r}=t;return{oauthAccount:e?{organizationType:e.organizationType}:void 0,customApiKeyResponses:r?{approved:r.approved}:void 0}}function LP(t){if(!(0,Ia.existsSync)(t))return{};let e;try{e=jt((0,Ia.readFileSync)(t,"utf-8"))}catch(r){return f.debug("HOOK","observed-billing: could not read or parse .claude.json, treating as no account",{errorName:r instanceof Error?r.name:"unknown"}),{}}return FP(e)}function UP(t,e){let r=t.customApiKeyResponses?.approved;return Array.isArray(r)&&r.includes(e.slice(-20))}function $P(t){let e=t.oauthAccount?.organizationType;if(typeof e!="string")return;let r=e.replace(/^claude_/,"");return CP(r)?r:"subscription"}function _S(t=process.env,e=DP(t)){if(Ta(t.CLAUDE_CODE_USE_BEDROCK))return"bedrock";if(Ta(t.CLAUDE_CODE_USE_VERTEX))return"vertex";if(Ta(t.CLAUDE_CODE_USE_FOUNDRY))return"foundry";let r=LP(e),n=!!r.oauthAccount,s=t.ANTHROPIC_API_KEY||t.ANTHROPIC_AUTH_TOKEN;if(s&&(!n||UP(r,s)))return"api_key";let o=$P(r);return o||(n||Ta(t.CLAUDE_CODE_OAUTH_TOKEN)?"subscription":"unknown")}var Ia,yd,hS,NP,ES=E(()=>{"use strict";Ia=require("fs"),yd=require("path"),hS=require("os");O();se();NP=new Set(["max","pro","team","enterprise"])});function jP(t){let e=WP.test(t)?t:`sha256-${(0,SS.createHash)("sha256").update(t).digest("hex")}`;return(0,bd.join)(N(),"state",BP,e)}function yS(t){try{(0,vs.rmSync)(jP(t),{force:!0})}catch(e){f.warn("HOOK","kimi-context-gate: clearInjected failed open",{error:e instanceof Error?e.message:String(e)})}}var vs,SS,bd,BP,WP,bS=E(()=>{"use strict";vs=require("fs"),SS=require("crypto"),bd=require("path");C();O();BP="kimi-context-injected",WP=/^[A-Za-z0-9_-]{1,128}$/});function XP(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>!!e&&typeof e=="object"&&e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(`
|
|
28
|
+
`):""}function wS(t){if(typeof t!="string")return null;let e=Date.parse(t);return Number.isFinite(e)?e:null}function KP(t,e){let r=(0,Ke.openSync)(t,"r");try{let n=(0,Ke.fstatSync)(r).size,s=Math.max(0,n-e),o=Buffer.alloc(n-s);if((0,Ke.readSync)(r,o,0,o.length,s),s===0)return{text:o.toString("utf-8"),startOffset:0};let i=Buffer.alloc(1);if((0,Ke.readSync)(r,i,0,1,s-1)===1&&i[0]===10)return{text:o.toString("utf-8"),startOffset:s};let a=o.indexOf(10);return a===-1?{text:"",startOffset:n}:{text:o.subarray(a+1).toString("utf-8"),startOffset:s+a+1}}finally{(0,Ke.closeSync)(r)}}function TS(t,e={}){if(!t||!(0,Ke.existsSync)(t))return[];let{text:r,startOffset:n}=KP(t,e.maxTailBytes??HP);return r.trim()?GP(r,e,n):[]}function GP(t,e={},r=0){let n=t.split(`
|
|
29
|
+
`),s=null,o=0,i=new Map,a=[],c=r;for(let u=0;u<n.length;u++){let l=n[u],d=c;if(c+=Buffer.byteLength(l,"utf-8")+1,!l||!l.trim())continue;let p;try{p=JSON.parse(l)}catch{continue}if(p?.isSidechain===!0)continue;let g=p?.type??p?.message?.role,m=p?.message?.content;if(g==="user"){let h=XP(m).replace(Fo,"").replace(/\n{3,}/g,`
|
|
30
30
|
|
|
31
|
-
`).trim(),_=Array.isArray(m)&&m.some(S=>S&&typeof S=="object"&&(S.type==="image"||S.type==="document"));(h||_)&&(s=h||null,
|
|
32
|
-
`):""}function
|
|
33
|
-
`);if(s.dryRun)i.log(` summary ${ds(h.last.timestampMs)} ${iS(T)}`);else{let y=td({session_id:g,cwd:e,hook_event_name:"Stop",last_assistant_message:T});y.lastAssistantMessage=T,y.spoolAtEpochMs=b(),y.turnId=h.uuid,await o.check(),await i.sendSummary(y),_++,u.add(h.uuid),S()}a.summaries++};for(let T=0;T<t.events.length;T++){let y=t.events[T];if(y.kind==="prompt"){await w();let P=Vr(y.text),v=l.get(y.uuid)??null,R=c.has(y.uuid),I=v?r.prompts.find(O=>O.createdAtEpochMs>v.createdAtEpochMs):void 0;if(h={uuid:y.uuid,summaryOwed:R&&!u.has(y.uuid),anchor:v?{atEpochMs:v.createdAtEpochMs,beforeEpochMs:I?.createdAtEpochMs??Number.POSITIVE_INFINITY}:null,anchored:0,capturedLive:v!==null&&!R,last:null},v){ir(y.timestampMs,s)&&a.alreadyRecorded++;continue}if(R&&nd(y.text)){h.skippedByWorker=!0,h.summaryOwed=!1,ir(y.timestampMs,s)&&a.alreadyRecorded++;continue}if(h.summaryOwed=!1,!ir(y.timestampMs,s))continue;if(s.dryRun)i.log(` prompt ${ds(y.timestampMs)} ${iS(y.text)||Zl}`);else{await o.check(!0);let O=(m.get(P)??Number.NEGATIVE_INFINITY)+gP-i.now();O>0&&await i.sleep(O),_>0&&await fP(i,g),_=0,c.add(y.uuid),S(),await pP(i,td({session_id:g,cwd:e,hook_event_name:"UserPromptSubmit",prompt:y.text,transcript_path:t.transcriptPath})),m.set(P,i.now())}if(nd(y.text)){h.skippedByWorker=!0,a.prompts++;continue}d.some(O=>O>T)&&(a.outOfOrder++,i.log(` note: the prompt at ${ds(y.timestampMs)} is added after later turns memory already holds, so it is numbered after them`)),h.summaryOwed=!u.has(y.uuid),a.prompts++;continue}if(y.kind==="assistant"){if(!h)continue;h.last&&h.last.messageId===y.messageId?h.last.text.push(y.text):h.last={messageId:y.messageId,text:[y.text],timestampMs:y.timestampMs},y.timestampMs!==null&&(h.last.timestampMs=y.timestampMs);continue}if(ir(y.timestampMs,s)&&!h?.skippedByWorker){if(r.toolUseIds.has(y.toolUseId)||p&&(!h||h.capturedLive)){a.alreadyRecorded++;continue}if(!i.isDropped(y)){if(s.dryRun){let P=y.agentId?` (subagent ${y.agentType??y.agentId})`:"";i.log(` tool use ${ds(y.timestampMs)} ${y.toolName} ${y.toolUseId}${y.failed?" failed":""}${P}`)}else{let P=td(oP(g,e,y));P.spoolAtEpochMs=b(),await i.sendToolUse(P),_++,r.toolUseIds.add(y.toolUseId),await o.check()}a.toolUses++}}}return await w(),a}async function hP(t,e=uS()){let r={sessionsScanned:0,sessionsWithWork:0,sessionsExcluded:0,prompts:0,toolUses:0,summaries:0,alreadyRecorded:0,outOfOrder:0};if(!(0,Nt.existsSync)(t.projectDir))return r.error=`no transcripts folder at ${t.projectDir}`,r;if(!t.dryRun&&e.usesServerRuntime())return r.error="the hooks send to the hosted server, and an import can only check what the local worker already holds; switch the runtime to worker first",r;if(!t.dryRun&&!await e.ensureWorker())return r.error="the MemIndex worker is not running and could not be started",r;let n=rS(t.projectDir).filter(o=>t.sinceMs===null||o.lastModifiedMs>=t.sinceMs),s=!1,i=lP(e);for(let o of n){r.sessionsScanned++;let a;try{a=await tS(o,p=>ir(p,t))}catch(p){e.log(`Skipped ${o.transcriptPath}: ${p instanceof Error?p.message:String(p)}`);continue}if(!a.events.some(p=>ir(p.timestampMs,t)))continue;let c=a.projectDir;if(!c||!e.shouldTrack(c)){r.sessionsExcluded++;continue}let u=await e.readRecorded(a.sessionId);if(u===null){if(!t.dryRun){r.error=`could not read what the worker already holds for session ${a.sessionId}; stopped so nothing is sent twice`;break}s||(e.log("The worker is not answering, so this preview cannot leave out what it already holds."),s=!0)}let l=e.projectOf(c);t.dryRun&&e.log(`Session ${a.sessionId} project ${l} (${c})`);let d;try{d=await aP(c,()=>mP(a,c,u??{prompts:[],toolUseIds:new Set,hasObservations:!1},e.readLedger(a.sessionId),t,e,i))}catch(p){r.error=`session ${a.sessionId}: ${p instanceof Error?p.message:String(p)}`;break}r.prompts+=d.prompts,r.toolUses+=d.toolUses,r.summaries+=d.summaries,r.alreadyRecorded+=d.alreadyRecorded,r.outOfOrder+=d.outOfOrder,d.prompts+d.toolUses+d.summaries>0&&(r.sessionsWithWork++,t.dryRun||e.log(`Session ${a.sessionId} (${l}): ${d.prompts} prompts, ${d.toolUses} tool uses, ${d.summaries} summaries sent`))}return r}function _P(t,e){return[`${e?"Would send":"Sent"} ${t.prompts} prompts, ${t.toolUses} tool uses and ${t.summaries} summaries from ${t.sessionsWithWork} sessions`,`(${t.sessionsScanned} sessions read, ${t.alreadyRecorded} events already in MemIndex, ${t.sessionsExcluded} sessions in excluded folders${t.outOfOrder>0?`, ${t.outOfOrder} prompts numbered after later turns memory already held`:""}).`].join(" ")}async function la(t){let e=await fe(t,{timeoutMs:nP});if(!e.ok)throw new Error(`${t} answered ${e.status}`);return e.json()}async function EP(t){let e=encodeURIComponent(t);try{let r=[];for(let i=0;;i+=100){let o=await la(`/api/prompts?contentSessionId=${e}&limit=100&offset=${i}`);for(let a of o.items??[])typeof a.prompt_text=="string"&&typeof a.created_at_epoch=="number"&&r.push({text:a.prompt_text,createdAtEpochMs:a.created_at_epoch});if(!o.hasMore)break}r.sort((i,o)=>i.createdAtEpochMs-o.createdAtEpochMs);let n=new Set;for(let i=0;;i+=500){let a=(await la(`/api/tool-uses?session=${e}&limit=500&offset=${i}&orderBy=date_asc`)).toolUses??[];for(let c of a)typeof c.tool_use_id=="string"&&n.add(c.tool_use_id);if(a.length<500)break}let s=await la(`/api/observations?contentSessionId=${e}&limit=1`);return{prompts:r,toolUseIds:n,hasObservations:(s.items?.length??0)>0}}catch{return null}}function cS(t){return(0,fa.join)(U(),"state","transcript-import",`${t.replace(/[^A-Za-z0-9_-]/g,"_")}.json`)}function SP(t){try{let e=JSON.parse((0,Nt.readFileSync)(cS(t),"utf8")),r=n=>Array.isArray(n)?n.filter(s=>typeof s=="string"):[];return{prompts:r(e.prompts),summaries:r(e.summaries)}}catch{return{prompts:[],summaries:[]}}}function yP(t){let e=Pi(),r=0;for(let n of(()=>{try{return(0,Nt.readdirSync)(e)}catch{return[]}})())if(n.endsWith(".json"))try{JSON.parse((0,Nt.readFileSync)((0,fa.join)(e,n),"utf8")).payload?.contentSessionId===t&&r++}catch{}return r}function bP(){try{return(0,Nt.readdirSync)(Pi()).filter(t=>t.endsWith(".json")).length}catch{return 0}}async function wP(){try{let t=await la("/api/processing-status");return(typeof t.queueDepth=="number"?t.queueDepth:0)+bP()}catch{return null}}function uS(t=()=>{}){return{async sendPrompt(e){await vi(e)},async sendToolUse(e){await vE.execute(e)},async sendSummary(e){await KE.execute(e)},readRecorded:EP,readLedger:SP,pendingSpoolFor:yP,saveLedger:(e,r)=>X(cS(e),r),usesServerRuntime:()=>xe().runtime==="server",now:()=>Date.now(),backlog:wP,ensureWorker:()=>Er(),sleep:e=>new Promise(r=>setTimeout(r,e)),log:t,projectOf:e=>qs(e).primary,shouldTrack:Ge,isDropped(e){let r=K();return Gr(e.toolName)||vt(e.toolName,r.MEMINDEX_SKIP_TOOLS)||vr(e.agentId,e.agentType,r).skip}}}var Nt,fa,oS,rd,eP,da,tP,rP,nP,sS,iP,uP,dP,gP,dS=E(()=>{"use strict";Nt=require("fs"),fa=require("path");TE();Kc();RE();GE();Vc();ie();N();zE();br();it();mn();ta();N();ki();Sr();wt();lt();YE();Bt();nS();oS="claude-code",rd=40,eP=3e3,da=15*6e4,tP=5,rP=2e3,nP=15e3,sS=100;iP="Usage: memindex transcript import [--since <ISO time>] [--until <ISO time>] [--project-dir <folder>] [--dry-run]";uP=20;dP=500;gP=11e3});Yr();var pS=require("fs");N();st();var Lt=require("fs"),Id=require("os"),bs=require("path");ie();N();var ur=j.transcriptsConfig(),ws=j.transcriptsState(),WS={version:1,schemas:{},watches:[],stateFile:ws};function vd(t){let e=typeof t.schema=="string"?t.schema:t.schema?.name;if(!(t.name==="codex"||e==="codex")||!t.path)return!1;let n=oe(t.path).replace(/\\/g,"/"),s=(0,bs.join)((0,Id.homedir)(),".codex","sessions").replace(/\\/g,"/");return n===`${s}/**/*.jsonl`}function Rd(t){let e=typeof t.schema=="string"?t.schema:t.schema?.name,r=t.name==="codex"&&(!e||e==="codex");return t.context?.mode==="agents"&&r&&vd(t)}var HS={path:"payload.source.subagent.thread_spawn"};function Ad(t,e){if(e.MEMINDEX_CODEX_TRANSCRIPT_INGESTION==="true")return{config:t,scoped:0,removed:0};let r=e.MEMINDEX_CODEX_SUBAGENT_INGESTION==="true"&&e.MEMINDEX_SKIP_SUBAGENT_OBSERVATIONS!=="true",n=0,s=0,i=[];for(let o of t.watches)vd(o)?r?(n+=1,i.push({...o,subagentOnly:!0,subagentSource:{...HS}})):s+=1:i.push(o);return{config:{...t,watches:i},scoped:n,removed:s}}function oe(t){return t&&fd(t)}var Pe=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Td={session_init:!0,session_context:!0,user_message:!0,assistant_message:!0,tool_use:!0,tool_result:!0,observation:!0,file_edit:!0,session_end:!0};function C(t,e,r){if(!t)throw new Error(`${e} ${r}`)}function Jr(t,e){C(t===void 0||typeof t=="string",e,"must be a string")}function ys(t,e){C(typeof t=="string"&&t.trim().length>0,e,"must be a non-empty string")}function Md(t,e){C(t===void 0||typeof t=="boolean",e,"must be true or false")}function Pd(t,e){typeof t!="string"&&(C(Pe(t),e,"must be a path string or an object"),Jr(t.path,`${e}.path`),t.coalesce!==void 0&&(C(Array.isArray(t.coalesce),`${e}.coalesce`,"must be an array"),t.coalesce.forEach((r,n)=>Pd(r,`${e}.coalesce[${n}]`))))}function Od(t,e){C(Pe(t),e,"must be an object");for(let r of["path","regex","contains","not_contains","starts_with","not_starts_with"])Jr(t[r],`${e}.${r}`);if(typeof t.regex=="string")try{new RegExp(t.regex)}catch{C(!1,`${e}.regex`,"must be a valid regular expression")}Md(t.exists,`${e}.exists`);for(let r of["in","not_in"])C(t[r]===void 0||Array.isArray(t[r]),`${e}.${r}`,"must be an array");for(let r of["all","any"]){let n=t[r];n!==void 0&&(C(Array.isArray(n),`${e}.${r}`,"must be an array"),n.forEach((s,i)=>Od(s,`${e}.${r}[${i}]`)))}}function wa(t,e){C(Pe(t),e,"must be an object"),ys(t.name,`${e}.name`);for(let r of["eventTypePath","sessionIdPath","cwdPath","projectPath"])Jr(t[r],`${e}.${r}`);C(Array.isArray(t.events),`${e}.events`,"must be an array"),t.events.forEach((r,n)=>{let s=`${e}.events[${n}]`;if(C(Pe(r),s,"must be an object"),C(typeof r.name=="string",`${s}.name`,"must be a string"),C(typeof r.action=="string"&&Object.hasOwn(Td,r.action),`${s}.action`,`must be one of ${Object.keys(Td).join(", ")}`),r.match!==void 0&&Od(r.match,`${s}.match`),r.fields!==void 0){C(Pe(r.fields),`${s}.fields`,"must be an object");for(let[i,o]of Object.entries(r.fields))Pd(o,`${s}.fields.${i}`)}})}function jS(t,e,r){C(Pe(t),e,"must be an object"),ys(t.name,`${e}.name`),ys(t.path,`${e}.path`);for(let o of["workspace","project","agentId"])Jr(t[o],`${e}.${o}`);for(let o of["startAtEnd","subagentOnly"])Md(t[o],`${e}.${o}`);let{subagentSource:n,context:s}=t;if(n!==void 0&&(C(Pe(n),`${e}.subagentSource`,"must be an object"),C(typeof n.path=="string",`${e}.subagentSource.path`,"must be a string")),s!==void 0&&(C(Pe(s),`${e}.context`,"must be an object"),C(s.mode==="agents",`${e}.context.mode`,'must be "agents"'),Jr(s.path,`${e}.context.path`),s.updateOn!==void 0&&(C(Array.isArray(s.updateOn),`${e}.context.updateOn`,"must be an array"),s.updateOn.forEach((o,a)=>C(o==="session_start"||o==="session_end",`${e}.context.updateOn[${a}]`,'must be "session_start" or "session_end"')))),typeof t.schema!="string"){C(Pe(t.schema),`${e}.schema`,"must be a schema name or an inline schema object"),wa(t.schema,`${e}.schema`);return}ys(t.schema,`${e}.schema`);let i=r?.[t.schema];i!==void 0&&wa(i,`schemas.${t.schema}`)}function XS(t){C(Pe(t),"the top level","must be an object"),C(t.version===1,"version","must be 1");let{stateFile:e,schemas:r,watches:n}=t;if(C(e==null||typeof e=="string","stateFile","must be a string"),r!==void 0){C(Pe(r),"schemas","must be an object");for(let[s,i]of Object.entries(r))wa(i,`schemas.${s}`)}C(Array.isArray(n),"watches","must be an array"),n.forEach((s,i)=>jS(s,`watches[${i}]`,r))}function Ta(t=ur){let e=oe(t);if(!(0,Lt.existsSync)(e))throw new Error(`Transcript watch config not found: ${e}`);let r=rt(e);try{XS(r)}catch(n){let s=n instanceof Error?n.message:String(n);throw new Error(`Invalid transcript watch config: ${e} (${s})`,{cause:n})}return r.stateFile||(r.stateFile=ws),r}function Ia(t=ur){let e=oe(t),r=(0,bs.dirname)(e);(0,Lt.existsSync)(r)||(0,Lt.mkdirSync)(r,{recursive:!0}),(0,Lt.writeFileSync)(e,JSON.stringify(WS,null,2))}var mE=require("crypto"),H=require("fs"),hE=require("fs/promises"),q=require("path");A();var Qr=require("fs"),xd=require("path");A();ie();function je(t,e){return typeof t!="object"||t===null||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(r=>e(r[1])))}function Nd(t){try{if(!(0,Qr.existsSync)(t))return{offsets:{}};let e=rt(t);if(!e||typeof e!="object"||Array.isArray(e))return{offsets:{}};let r=o=>typeof o=="number"&&Number.isSafeInteger(o)&&o>=0,n=o=>typeof o=="string",s={offsets:je(e.offsets,r)},i=o=>Object.fromEntries(Object.entries(o).filter(([a])=>Object.hasOwn(s.offsets,a)));if(e.partials!==void 0&&(s.partials=i(je(e.partials,n))),e.partialBytes!==void 0&&(s.partialBytes=i(je(e.partialBytes,o=>typeof o=="string"&&o.length>0&&Buffer.from(o,"base64").toString("base64")===o))),e.frameLines!==void 0&&(s.frameLines=i(je(e.frameLines,r))),e.fileIdentities!==void 0&&(s.fileIdentities=i(je(e.fileIdentities,n))),e.checkpointFingerprints!==void 0&&(s.checkpointFingerprints=i(je(e.checkpointFingerprints,n))),e.pendingTools!==void 0){let o=c=>typeof c=="object"&&c!==null&&!Array.isArray(c),a=c=>o(c)&&typeof c.toolName=="string"&&c.toolName.length>0;s.pendingTools=Object.fromEntries(Object.entries(i(je(e.pendingTools,o))).map(([c,u])=>[c,Object.fromEntries(Object.entries(je(u,o)).map(([l,d])=>[l,je(d,a)]))]))}return e.cwds!==void 0&&(s.cwds=je(e.cwds,n)),s}catch(e){return f.warn("TRANSCRIPT","Failed to load watch state, starting fresh",{statePath:t,error:e instanceof Error?e.message:String(e)}),{offsets:{}}}}var KS=64*1024,kd=new WeakMap;function GS(t){let e=kd.get(t);return e||(e=(t.toolInput===void 0?0:Buffer.byteLength(JSON.stringify(t.toolInput)??""))<=KS?t:{toolName:t.toolName},kd.set(t,e)),e}function zS(t){let e={};for(let[r,n]of Object.entries(t)){e[r]={};for(let[s,i]of Object.entries(n)){e[r][s]={};for(let[o,a]of Object.entries(i))e[r][s][o]=GS(a)}}return e}function Zr(t,e){try{let r=(0,xd.dirname)(t);(0,Qr.existsSync)(r)||(0,Qr.mkdirSync)(r,{recursive:!0});let n=e.pendingTools?{...e,pendingTools:zS(e.pendingTools)}:e;X(t,n,{mode:384})}catch(r){f.warn("TRANSCRIPT","Failed to save watch state",{statePath:t,error:r instanceof Error?r.message:String(r)})}}var is=Ee(require("path"),1);Kc();Tr();A();He();ut();Sr();br();yr();it();mn();var qc="write_file",kg={async execute(t){let{sessionId:e,cwd:r,filePath:n,edits:s}=t,i=G(t.platform);if(!n)throw new Error("fileEditHandler requires filePath");if(f.dataIn("HOOK",`FileEdit: ${n}`,{editCount:s?.length??0}),!r)throw new Error(`Missing cwd in FileEdit hook input for session ${e}, file ${n}`);if(!Ge(r))return f.debug("HOOK","Project excluded from tracking, skipping file edit observation",{cwd:r,filePath:n}),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};let o={filePath:n,edits:s},a={success:!0},c=xe();if(c.runtime==="server"){if(vt(qc,K().MEMINDEX_SKIP_TOOLS))return f.debug("HOOK","Server runtime: file edit excluded by MEMINDEX_SKIP_TOOLS",{filePath:n}),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};let u={projectId:c.projectId,contentSessionId:e,platformSource:i,sourceType:"hook",eventType:"tool_use",occurredAtEpoch:Date.now(),payload:{tool_name:qc,tool_input:o,tool_response:a,cwd:r,platformSource:i}};try{return await c.client.recordEvent(u),f.debug("HOOK","File edit sent successfully via server",{filePath:n}),{continue:!0,suppressOutput:!0}}catch(l){if(Tt(l)&&l.isFallbackEligible())It(l.kind,{status:l.status,message:l.message,route:"/v1/events"});else return f.error("HOOK","Server file edit failed (non-recoverable)",{error:l instanceof Error?l.message:String(l)}),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS}}}return De("file_edit",{contentSessionId:e,platformSource:i,toolName:qc,toolInput:o,toolResponse:a,cwd:r}),f.debug("HOOK","File edit observation spooled",{filePath:n}),{continue:!0,suppressOutput:!0}}};wt();N();A();Bt();var Fe=require("fs"),Oi=require("path");A();A();st();wt();N();on();var Jc="<memindex-context>",Qc="</memindex-context>",AT=["agent-mem-context"].map(t=>({open:`<${t}>`,close:`</${t}>`}));function xg(t){return[{open:Jc,close:Qc},...AT].reduce((e,r)=>e??MT(t,r.open,r.close),null)}function MT(t,e,r){let n=t.indexOf(e);if(n===-1)return null;let s=t.indexOf(r,n+e.length);return s===-1?null:{start:t.lastIndexOf(e,s),end:s+r.length}}var DN=j.settings();function Ng(t,e){let r=`${Jc}
|
|
31
|
+
`).trim(),_=Array.isArray(m)&&m.some(S=>S&&typeof S=="object"&&(S.type==="image"||S.type==="document"));(h||_)&&(s=h||null,o=u+1);continue}if(!(g!=="assistant"||!Array.isArray(m))){for(let h of m)if(!(!h||typeof h!="object")){if(h.type==="server_tool_use"&&h.name==="advisor"&&typeof h.id=="string"){i.set(h.id,{advisorModel:typeof p.advisorModel=="string"?p.advisorModel:null,occurredAtEpoch:wS(p.timestamp)??0,transcriptByteOffset:d,lastUserMessage:s,userTurnLine:o});continue}if(h.type==="advisor_tool_result"&&typeof h.tool_use_id=="string"){let _=i.get(h.tool_use_id);if(!_)continue;i.delete(h.tool_use_id);let S=h.content;if(!S||typeof S!="object"||S.type!=="advisor_result")continue;let b=typeof S.text=="string"?S.text.trim():"";if(!b)continue;a.push({call:{toolUseId:h.tool_use_id,advisorModel:_.advisorModel,advice:b,occurredAtEpoch:_.occurredAtEpoch||(wS(p.timestamp)??Date.now()),transcriptByteOffset:_.transcriptByteOffset,lastUserMessage:_.lastUserMessage},userTurnLine:_.userTurnLine})}}}}return a.filter(u=>!e.currentTurnOnly||u.userTurnLine===o).map(u=>u.call)}var Ke,HP,IS=E(()=>{"use strict";Ke=require("fs");Ze();HP=2*1024*1024});function VP(t,e,r,n){if(!e||G().MEMINDEX_CAPTURE_ADVISOR_CALLS!=="true"||Le().runtime==="server")return;let s=TS(e,{currentTurnOnly:!0});if(s.length!==0){f.debug("HOOK","Stop: spooling advisor calls",{count:s.length});for(let o=0;o<s.length;o+=vS)We("advisor_calls",{contentSessionId:t,platformSource:n,cwd:r,transcriptPath:e,calls:s.slice(o,o+vS).map(i=>({toolUseId:i.toolUseId,advice:i.advice,advisorModel:i.advisorModel,occurredAtEpoch:i.occurredAtEpoch,lastUserMessage:i.lastUserMessage,transcriptByteOffset:i.transcriptByteOffset}))})}}async function YP(t,e,r){return await fu(t.client,e,void 0,r),f.debug("HOOK","Summary request queued via server"),await xr(t.client,$e(t)),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS}}var RS,AS,vS,OS,PS=E(()=>{"use strict";Nr();O();mS();RS=require("crypto"),AS=require("path");ES();Ze();xe();Pt();ht();Pr();bS();Mr();tr();On();IS();ft();vS=50;OS={async execute(t){if(t.cwd&&!Qe(t.cwd))return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};if(t.stopHookActive===!0)return f.debug("HOOK","Skipping summary: Stop hook re-entry detected (stop_hook_active)",{sessionId:t.sessionId}),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};if(t.agentId)return f.debug("HOOK","Skipping summary: subagent context detected",{sessionId:t.sessionId,agentId:t.agentId,agentType:t.agentType}),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};let{sessionId:e,transcriptPath:r}=t;if(!e)return f.warn("HOOK","summarize: No sessionId provided, skipping"),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};t.platform==="kimi"&&t.hookEventName==="PreCompact"&&yS(e);try{VP(e,r,t.cwd,z(t.platform))}catch(d){f.warn("HOOK","Advisor-call capture failed; continuing with summary",{sessionId:e,error:d instanceof Error?d.message:String(d)})}let n="",s,o=t.turnId,i={includeTurnId:t.platform==="claude-code"};if(t.lastAssistantMessage?.trim()){n=Ie(t.lastAssistantMessage);try{if(r&&t.platform==="claude-code"&&!o){let d=Sd(r,!0,i);s=d.model,o=d.turnId}else s=r?pS(r):void 0}catch(d){f.warn("HOOK",`Stop hook: could not read observed model from transcript for session ${e}: ${d instanceof Error?d.message:d}`)}}else{if(!r)return f.debug("HOOK",`No transcriptPath in Stop hook input for session ${e} - skipping summary`),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};try{let d=Sd(r,!0,i);n=Ie(d.text),s=d.model,o??=d.turnId}catch(d){return f.warn("HOOK",`Stop hook: failed to extract last assistant message for session ${e}: ${d instanceof Error?d.message:d}`),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS}}}if(!n||!n.trim())return f.debug("HOOK","No assistant message available - skipping summary",{sessionId:e,transcriptPath:r}),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};f.dataIn("HOOK","Stop: Requesting summary",{hasLastAssistantMessage:!!n});let a=z(t.platform),c=t.platform==="claude-code"?_S():void 0,u=Le();if(u.runtime==="server"){let d={projectId:u.projectId,contentSessionId:e,platformSource:a,lastAssistantMessage:n,occurredAtEpoch:Date.now()},p=d;try{return await YP(u,d,g=>{p=g})}catch(g){if(Et(g))return Ue(g.kind,{status:g.status,message:g.message,route:"/v1/sessions/end",held:!0}),xt({op:"summarize",request:p},$e(u)),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};if(Fe(g)&&g.isFallbackEligible())Ue(g.kind,{status:g.status,message:g.message,route:"/v1/sessions/end"});else return f.error("HOOK","Server summarize failed (non-recoverable)",{error:g instanceof Error?g.message:String(g)}),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS}}}t.platform==="claude-code"&&(o??=(0,RS.randomUUID)());let l=We("summarize",{contentSessionId:e,platformSource:a,lastAssistantMessage:n,observedModel:s,observedBilling:c,...o?{turnId:o}:{}},t.spoolAtEpochMs);if(t.platform==="claude-code"&&t.hookEventName==="PreCompact")try{let d=await le("/api/spool/nudge",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({waitForSummary:!0,contentSessionId:e,platformSource:a,captureKey:(0,AS.basename)(l,".json")}),timeoutMs:9e4}),p=await d.json();(!d.ok||p.status!=="settled")&&f.warn("HOOK","PreCompact summary did not settle before the deadline",{sessionId:e,status:p.status})}catch(d){f.warn("HOOK","PreCompact summary wait unavailable; capture remains in the normal pipeline",{sessionId:e,error:d instanceof Error?d.message:String(d)})}return f.debug("HOOK","Summary request spooled, exiting hook"),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS}}}});var MS=E(()=>{"use strict"});function xS(t){let e=t.trim(),n=Ie(t).trim()||e;return n.length<=wd?n:(f.debug("DB","Truncated stored prompt text to the configured cap",{originalLength:n.length,storedLength:wd}),`${n.slice(0,wd-1)}\u2026`)}var wd,Td,kS=E(()=>{"use strict";Ze();O();wd=4e3,Td="[media prompt]"});function qP(t){if(typeof t!="string")return null;let e=Date.parse(t);return Number.isFinite(e)?e:null}function LS(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>It(e)&&e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(`
|
|
32
|
+
`):""}function QP(t){if(t.type!=="user"||t.isSidechain===!0||t.isMeta===!0||t.isCompactSummary===!0)return null;let e=It(t.message)?t.message:null;if(!e)return null;let r=e.content;if(Array.isArray(r)&&r.some(i=>It(i)&&i.type==="tool_result"))return null;let n=It(t.origin)?t.origin:null;if(n){if(n.kind!=="human")return null}else if(typeof t.promptSource=="string"&&t.promptSource!=="typed"&&t.promptSource!=="queued")return null;let s=LS(r),o=s.trimStart();return!n&&JP.some(i=>o.startsWith(i))||!s.trim()&&!Array.isArray(r)?null:s}function ZP(t){return typeof t=="string"?t:LS(t)}async function*eM(t){let e=(0,FS.createInterface)({input:(0,Ge.createReadStream)(t,{encoding:"utf8"}),crlfDelay:1/0});for await(let r of e)if(r.trim())try{let n=JSON.parse(r);It(n)&&(yield n)}catch{}}async function NS(t,e={}){let r=[],n=new Map,s=null,o=e.agentId!==void 0,i=0;for await(let a of eM(t)){i++,s===null&&typeof a.cwd=="string"&&a.cwd.trim()&&(s=a.cwd);let c=qP(a.timestamp),u=It(a.message)?a.message:null;if(a.type==="assistant"&&u&&Array.isArray(u.content)){for(let l of u.content)It(l)&&(l.type==="tool_use"&&typeof l.id=="string"&&typeof l.name=="string"?n.set(l.id,{name:l.name,input:l.input}):!o&&l.type==="text"&&typeof l.text=="string"&&l.text.trim()&&r.push({kind:"assistant",timestampMs:c,messageId:typeof u.id=="string"?u.id:String(a.uuid??""),text:l.text}));continue}if(!(a.type!=="user"||!u)){if(Array.isArray(u.content))for(let l of u.content){if(!It(l)||l.type!=="tool_result"||typeof l.tool_use_id!="string")continue;let d=n.get(l.tool_use_id);if(!d||(n.delete(l.tool_use_id),e.keepToolAt&&!e.keepToolAt(c)))continue;let p=l.is_error===!0,g=ZP(l.content);r.push({kind:"tool",timestampMs:c,toolUseId:l.tool_use_id,toolName:d.name,toolInput:d.input,toolResponse:p?void 0:a.toolUseResult??l.content,failed:p,error:p?g:void 0,interrupted:p&&g.includes("[Request interrupted by user"),agentId:e.agentId,agentType:e.agentType})}if(!o){let l=QP(a);if(l!==null){let d=typeof a.uuid=="string"&&a.uuid?a.uuid:`${(0,$t.basename)(t)}:${i}`;r.push({kind:"prompt",timestampMs:c,uuid:d,text:l})}}}}return{events:r,firstCwd:s}}function tM(t){try{let e=JSON.parse((0,Ge.readFileSync)(t,"utf8"));return It(e)&&typeof e.agentType=="string"&&e.agentType?e.agentType:void 0}catch{return}}async function US(t,e){let r=await NS(t.transcriptPath,{keepToolAt:e}),n=r.events.map((i,a)=>({event:i,source:0,index:a}));for(let i=0;i<t.subagentPaths.length;i++){let a=t.subagentPaths[i],c=(0,$t.basename)(a,".jsonl").replace(/^agent-/,""),u=tM(a.replace(/\.jsonl$/,".meta.json"));(await NS(a,{agentId:c,agentType:u,keepToolAt:e})).events.forEach((d,p)=>n.push({event:d,source:i+1,index:p}))}let s=Number.NEGATIVE_INFINITY,o=n.map(i=>(i.event.timestampMs!==null&&(s=i.event.timestampMs),{...i,sortTime:i.event.timestampMs??s}));return o.sort((i,a)=>i.sortTime-a.sortTime||i.source-a.source||i.index-a.index),{sessionId:t.sessionId,transcriptPath:t.transcriptPath,projectDir:r.firstCwd,events:o.map(i=>i.event)}}function CS(t){try{return(0,Ge.statSync)(t).mtimeMs}catch{return 0}}function Id(t){try{return(0,Ge.readdirSync)(t)}catch{return[]}}function DS(t){let e=[];for(let r of Id(t).sort()){let n=rM.exec(r);if(!n)continue;let s=n[1],o=(0,$t.join)(t,r),i=(0,$t.join)(t,s,"subagents"),a=(0,Ge.existsSync)(i)?Id(i).filter(u=>u.startsWith("agent-")&&u.endsWith(".jsonl")).sort().map(u=>(0,$t.join)(i,u)):[],c=Math.max(CS(o),...a.map(CS));e.push({sessionId:s,transcriptPath:o,subagentPaths:a,lastModifiedMs:c})}return e}function $S(t){let e=DS(t);return e.length>0?e:Id(t).sort().map(r=>(0,$t.join)(t,r)).filter(r=>{try{return(0,Ge.statSync)(r).isDirectory()}catch{return!1}}).flatMap(DS)}var Ge,$t,FS,It,JP,rM,BS=E(()=>{"use strict";Ge=require("fs"),$t=require("path"),FS=require("readline"),It=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);JP=["<command-name>","<command-message>","<local-command-stdout>","<local-command-stderr>","<local-command-caveat>"];rM=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i});var zS={};As(zS,{BACKLOG_HIGH_WATER:()=>Rd,CLAUDE_CODE_PLATFORM:()=>HS,TRANSCRIPT_IMPORT_USAGE:()=>uM,defaultTranscriptImportDeps:()=>GS,formatTranscriptImportResult:()=>bM,isPromptSkippedByWorker:()=>Ad,isoOf:()=>Rs,matchRecordedPrompts:()=>XS,parseTranscriptImportArgs:()=>cM,promptKey:()=>sn,runTranscriptImport:()=>yM});function cM(t){let e=null,r=null,n=(0,Aa.join)(lt,"projects"),s=!1;for(let o=0;o<t.length;o++){let i=t[o],a=()=>{let c=t[o+1];return c===void 0||c.startsWith("--")?null:(o++,c)};if(i==="--dry-run")s=!0;else if(i==="--since"||i==="--until"){let c=a(),u=c===null?Number.NaN:Date.parse(c);if(!Number.isFinite(u))return`${i} needs a date and time, for example 2026-10-14T10:54:00Z`;i==="--since"?e=u:r=u}else if(i==="--project-dir"){let c=a();if(c===null)return"--project-dir needs a folder";n=c}else return`Unknown option: ${i}`}return e!==null&&r!==null&&e>r?"--since is after --until":{sinceMs:e,untilMs:r,projectDir:n,dryRun:s}}function hr(t,e){return e.sinceMs===null&&e.untilMs===null?!0:!(t===null||e.sinceMs!==null&&t<e.sinceMs||e.untilMs!==null&&t>e.untilMs)}function sn(t){return xS(Ie(t.trim()?t:Td))}function jS(t){let e=t.replace(/\s+/g," ").trim();return e.length>WS?`${e.slice(0,WS-1)}\u2026`:e}function Rs(t){return t===null?"(no time)":new Date(t).toISOString()}function XS(t,e,r){let n=e.map(c=>sn(c.text)),s=new Set,o=new Map;for(let c of[...t].reverse()){if(!r.has(c.uuid))continue;let u=sn(c.text);for(let l=e.length-1;l>=0;l--)if(!(s.has(l)||n[l]!==u)){s.add(l),o.set(c.uuid,e[l]);break}}let i=[];t.forEach((c,u)=>{if(r.has(c.uuid))return;let l=sn(c.text);e.forEach((d,p)=>{if(s.has(p)||n[p]!==l)return;let g=c.timestampMs===null?Number.POSITIVE_INFINITY:Math.abs(d.createdAtEpochMs-c.timestampMs);i.push({turn:u,row:p,distance:g})})}),i.sort((c,u)=>c.distance-u.distance||c.turn-u.turn||c.row-u.row);let a=new Set;for(let c of i)a.has(c.turn)||s.has(c.row)||(a.add(c.turn),s.add(c.row),o.set(t[c.turn].uuid,e[c.row]));return o}function vd(t){let e=oS.normalizeInput(t);return e.platform=HS,e}function lM(t,e,r){return{session_id:t,cwd:e,hook_event_name:r.failed?"PostToolUseFailure":"PostToolUse",tool_name:r.toolName,tool_input:r.toolInput,tool_use_id:r.toolUseId,...r.failed?{error:r.error??"",is_interrupt:r.interrupted}:{tool_response:r.toolResponse},...r.agentId?{agent_id:r.agentId}:{},...r.agentType?{agent_type:r.agentType}:{}}}async function dM(t,e){let r=process.env.CLAUDE_PROJECT_DIR;process.env.CLAUDE_PROJECT_DIR=t;try{return await e()}finally{r===void 0?delete process.env.CLAUDE_PROJECT_DIR:process.env.CLAUDE_PROJECT_DIR=r}}async function fM(t){let e=await t.backlog();if(e===null||e<=Rd)return;let r=Date.now(),n=e,s=0;for(;e!==null&&e>Rd;)if(Date.now()-s>=3e4&&(t.log(` waiting for the worker to catch up (${e} items queued)`),s=Date.now()),await t.sleep(sM),e=await t.backlog(),e!==n)n=e??n,r=Date.now();else if(Date.now()-r>Ra)throw new Error(`the worker has not taken any queued work for ${Math.round(Ra/6e4)} minutes (${e} items queued)`)}function gM(t){let e=0;return{async check(r=!1){e++,!(!r&&e<pM)&&(e=0,await fM(t))}}}async function hM(t,e){let r=t.pendingSpoolFor(e),n=t.now(),s=r,o=!1;for(;r>0;)if(!o&&t.now()-n>=1e4&&(t.log(` waiting for the worker to take ${r} queued events of this session`),o=!0),await t.sleep(mM),r=t.pendingSpoolFor(e),r!==s)s=r,n=t.now();else if(t.now()-n>Ra)throw new Error(`the worker has not taken this session's queued events for ${Math.round(Ra/6e4)} minutes (${r} waiting)`)}function Ad(t){return Lo(t)||t.trim()!==""&&Ie(t).trim()===""}async function _M(t,e){for(let r=1;;r++)try{await t.sendPrompt(e);return}catch(n){if(!(n instanceof kr)||r>=oM)throw n;await t.sleep(iM*r)}}async function SM(t,e,r,n,s,o,i){let a={prompts:0,toolUses:0,summaries:0,alreadyRecorded:0,outOfOrder:0},c=new Set(n.prompts),u=new Set(n.summaries),l=XS(t.events.filter(T=>T.kind==="prompt"),r.prompts,c),d=t.events.flatMap((T,y)=>T.kind==="prompt"&&l.has(T.uuid)&&!c.has(T.uuid)?[y]:[]),p=r.hasObservations&&r.prompts.length>0&&r.toolUseIds.size===0,g=t.sessionId,m=new Map;for(let T of r.prompts){let y=sn(T.text);m.set(y,Math.max(m.get(y)??Number.NEGATIVE_INFINITY,T.createdAtEpochMs))}let h=null,_=0,S=()=>{s.dryRun||(n.prompts=[...c],n.summaries=[...u],o.saveLedger(g,n))},b=()=>{let T=h?.anchor;if(!T)return;let y=T.atEpochMs+1+h.anchored;return y>=T.beforeEpochMs?Math.max(T.atEpochMs,T.beforeEpochMs-1):(h.anchored++,y)},w=async()=>{if(!h?.summaryOwed||!h.last||!hr(h.last.timestampMs,s))return;let T=h.last.text.join(`
|
|
33
|
+
`);if(s.dryRun)o.log(` summary ${Rs(h.last.timestampMs)} ${jS(T)}`);else{let y=vd({session_id:g,cwd:e,hook_event_name:"Stop",last_assistant_message:T});y.lastAssistantMessage=T,y.spoolAtEpochMs=b(),y.turnId=h.uuid,await i.check(),await o.sendSummary(y),_++,u.add(h.uuid),S()}a.summaries++};for(let T=0;T<t.events.length;T++){let y=t.events[T];if(y.kind==="prompt"){await w();let A=sn(y.text),v=l.get(y.uuid)??null,R=c.has(y.uuid),I=v?r.prompts.find(M=>M.createdAtEpochMs>v.createdAtEpochMs):void 0;if(h={uuid:y.uuid,summaryOwed:R&&!u.has(y.uuid),anchor:v?{atEpochMs:v.createdAtEpochMs,beforeEpochMs:I?.createdAtEpochMs??Number.POSITIVE_INFINITY}:null,anchored:0,capturedLive:v!==null&&!R,last:null},v){hr(y.timestampMs,s)&&a.alreadyRecorded++;continue}if(R&&Ad(y.text)){h.skippedByWorker=!0,h.summaryOwed=!1,hr(y.timestampMs,s)&&a.alreadyRecorded++;continue}if(h.summaryOwed=!1,!hr(y.timestampMs,s))continue;if(s.dryRun)o.log(` prompt ${Rs(y.timestampMs)} ${jS(y.text)||Td}`);else{await i.check(!0);let M=(m.get(A)??Number.NEGATIVE_INFINITY)+EM-o.now();M>0&&await o.sleep(M),_>0&&await hM(o,g),_=0,c.add(y.uuid),S(),await _M(o,vd({session_id:g,cwd:e,hook_event_name:"UserPromptSubmit",prompt:y.text,transcript_path:t.transcriptPath})),m.set(A,o.now())}if(Ad(y.text)){h.skippedByWorker=!0,a.prompts++;continue}d.some(M=>M>T)&&(a.outOfOrder++,o.log(` note: the prompt at ${Rs(y.timestampMs)} is added after later turns memory already holds, so it is numbered after them`)),h.summaryOwed=!u.has(y.uuid),a.prompts++;continue}if(y.kind==="assistant"){if(!h)continue;h.last&&h.last.messageId===y.messageId?h.last.text.push(y.text):h.last={messageId:y.messageId,text:[y.text],timestampMs:y.timestampMs},y.timestampMs!==null&&(h.last.timestampMs=y.timestampMs);continue}if(hr(y.timestampMs,s)&&!h?.skippedByWorker){if(r.toolUseIds.has(y.toolUseId)||p&&(!h||h.capturedLive)){a.alreadyRecorded++;continue}if(!o.isDropped(y)){if(s.dryRun){let A=y.agentId?` (subagent ${y.agentType??y.agentId})`:"";o.log(` tool use ${Rs(y.timestampMs)} ${y.toolName} ${y.toolUseId}${y.failed?" failed":""}${A}`)}else{let A=vd(lM(g,e,y));A.spoolAtEpochMs=b(),await o.sendToolUse(A),_++,r.toolUseIds.add(y.toolUseId),await i.check()}a.toolUses++}}}return await w(),a}async function yM(t,e=GS()){let r={sessionsScanned:0,sessionsWithWork:0,sessionsExcluded:0,prompts:0,toolUses:0,summaries:0,alreadyRecorded:0,outOfOrder:0};if(!(0,Bt.existsSync)(t.projectDir))return r.error=`no transcripts folder at ${t.projectDir}`,r;if(!t.dryRun&&e.usesServerRuntime())return r.error="the hooks send to the hosted server, and an import can only check what the local worker already holds; switch the runtime to worker first",r;if(!t.dryRun&&!await e.ensureWorker())return r.error="the MemIndex worker is not running and could not be started",r;let n=$S(t.projectDir).filter(i=>t.sinceMs===null||i.lastModifiedMs>=t.sinceMs),s=!1,o=gM(e);for(let i of n){r.sessionsScanned++;let a;try{a=await US(i,p=>hr(p,t))}catch(p){e.log(`Skipped ${i.transcriptPath}: ${p instanceof Error?p.message:String(p)}`);continue}if(!a.events.some(p=>hr(p.timestampMs,t)))continue;let c=a.projectDir;if(!c||!e.shouldTrack(c)){r.sessionsExcluded++;continue}let u=await e.readRecorded(a.sessionId);if(u===null){if(!t.dryRun){r.error=`could not read what the worker already holds for session ${a.sessionId}; stopped so nothing is sent twice`;break}s||(e.log("The worker is not answering, so this preview cannot leave out what it already holds."),s=!0)}let l=e.projectOf(c);t.dryRun&&e.log(`Session ${a.sessionId} project ${l} (${c})`);let d;try{d=await dM(c,()=>SM(a,c,u??{prompts:[],toolUseIds:new Set,hasObservations:!1},e.readLedger(a.sessionId),t,e,o))}catch(p){r.error=`session ${a.sessionId}: ${p instanceof Error?p.message:String(p)}`;break}r.prompts+=d.prompts,r.toolUses+=d.toolUses,r.summaries+=d.summaries,r.alreadyRecorded+=d.alreadyRecorded,r.outOfOrder+=d.outOfOrder,d.prompts+d.toolUses+d.summaries>0&&(r.sessionsWithWork++,t.dryRun||e.log(`Session ${a.sessionId} (${l}): ${d.prompts} prompts, ${d.toolUses} tool uses, ${d.summaries} summaries sent`))}return r}function bM(t,e){return[`${e?"Would send":"Sent"} ${t.prompts} prompts, ${t.toolUses} tool uses and ${t.summaries} summaries from ${t.sessionsWithWork} sessions`,`(${t.sessionsScanned} sessions read, ${t.alreadyRecorded} events already in MemIndex, ${t.sessionsExcluded} sessions in excluded folders${t.outOfOrder>0?`, ${t.outOfOrder} prompts numbered after later turns memory already held`:""}).`].join(" ")}async function va(t){let e=await le(t,{timeoutMs:aM});if(!e.ok)throw new Error(`${t} answered ${e.status}`);return e.json()}async function wM(t){let e=encodeURIComponent(t);try{let r=[];for(let o=0;;o+=100){let i=await va(`/api/prompts?contentSessionId=${e}&limit=100&offset=${o}`);for(let a of i.items??[])typeof a.prompt_text=="string"&&typeof a.created_at_epoch=="number"&&r.push({text:a.prompt_text,createdAtEpochMs:a.created_at_epoch});if(!i.hasMore)break}r.sort((o,i)=>o.createdAtEpochMs-i.createdAtEpochMs);let n=new Set;for(let o=0;;o+=500){let a=(await va(`/api/tool-uses?session=${e}&limit=500&offset=${o}&orderBy=date_asc`)).toolUses??[];for(let c of a)typeof c.tool_use_id=="string"&&n.add(c.tool_use_id);if(a.length<500)break}let s=await va(`/api/observations?contentSessionId=${e}&limit=1`);return{prompts:r,toolUseIds:n,hasObservations:(s.items?.length??0)>0}}catch{return null}}function KS(t){return(0,Aa.join)(N(),"state","transcript-import",`${t.replace(/[^A-Za-z0-9_-]/g,"_")}.json`)}function TM(t){try{let e=JSON.parse((0,Bt.readFileSync)(KS(t),"utf8")),r=n=>Array.isArray(n)?n.filter(s=>typeof s=="string"):[];return{prompts:r(e.prompts),summaries:r(e.summaries)}}catch{return{prompts:[],summaries:[]}}}function IM(t){let e=Ko(),r=0;for(let n of(()=>{try{return(0,Bt.readdirSync)(e)}catch{return[]}})())if(n.endsWith(".json"))try{JSON.parse((0,Bt.readFileSync)((0,Aa.join)(e,n),"utf8")).payload?.contentSessionId===t&&r++}catch{}return r}function vM(){try{return(0,Bt.readdirSync)(Ko()).filter(t=>t.endsWith(".json")).length}catch{return 0}}async function RM(){try{let t=await va("/api/processing-status");return(typeof t.queueDepth=="number"?t.queueDepth:0)+vM()}catch{return null}}function GS(t=()=>{}){return{async sendPrompt(e){await Wo(e)},async sendToolUse(e){await cS.execute(e)},async sendSummary(e){await OS.execute(e)},readRecorded:wM,readLedger:TM,pendingSpoolFor:IM,saveLedger:(e,r)=>U(KS(e),r),usesServerRuntime:()=>Le().runtime==="server",now:()=>Date.now(),backlog:RM,ensureWorker:()=>Or(),sleep:e=>new Promise(r=>setTimeout(r,e)),log:t,projectOf:e=>lo(e).primary,shouldTrack:Qe,isDropped(e){let r=G();return rn(e.toolName)||kt(e.toolName,r.MEMINDEX_SKIP_TOOLS)||Dr(e.agentId,e.agentType,r).skip}}}var Bt,Aa,HS,Rd,sM,Ra,oM,iM,aM,WS,uM,pM,mM,EM,VS=E(()=>{"use strict";Bt=require("fs"),Aa=require("path");iS();gu();uS();PS();_u();se();C();MS();Mr();ft();Mn();ha();C();zo();Pr();Pt();Ze();kS();qt();BS();HS="claude-code",Rd=40,sM=3e3,Ra=15*6e4,oM=5,iM=2e3,aM=15e3,WS=100;uM="Usage: memindex transcript import [--since <ISO time>] [--until <ISO time>] [--project-dir <folder>] [--dry-run]";pM=20;mM=500;EM=11e3});on();var qS=require("fs");C();dt();var zt=require("fs"),tf=require("os"),Ds=require("path");se();C();var Sr=K.transcriptsConfig(),Fs=K.transcriptsState(),Py={version:1,schemas:{},watches:[],stateFile:Fs};function rf(t){let e=typeof t.schema=="string"?t.schema:t.schema?.name;if(!(t.name==="codex"||e==="codex")||!t.path)return!1;let n=ce(t.path).replace(/\\/g,"/"),s=(0,Ds.join)((0,tf.homedir)(),".codex","sessions").replace(/\\/g,"/");return n===`${s}/**/*.jsonl`}function nf(t){let e=typeof t.schema=="string"?t.schema:t.schema?.name,r=t.name==="codex"&&(!e||e==="codex");return t.context?.mode==="agents"&&r&&rf(t)}var My={path:"payload.source.subagent.thread_spawn"};function sf(t,e){if(e.MEMINDEX_CODEX_TRANSCRIPT_INGESTION==="true")return{config:t,scoped:0,removed:0};let r=e.MEMINDEX_CODEX_SUBAGENT_INGESTION==="true"&&e.MEMINDEX_SKIP_SUBAGENT_OBSERVATIONS!=="true",n=0,s=0,o=[];for(let i of t.watches)rf(i)?r?(n+=1,o.push({...i,subagentOnly:!0,subagentSource:{...My}})):s+=1:o.push(i);return{config:{...t,watches:o},scoped:n,removed:s}}function ce(t){return t&&Ud(t)}var Ne=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),ef={session_init:!0,session_context:!0,user_message:!0,assistant_message:!0,tool_use:!0,tool_result:!0,observation:!0,file_edit:!0,session_end:!0};function F(t,e,r){if(!t)throw new Error(`${e} ${r}`)}function dn(t,e){F(t===void 0||typeof t=="string",e,"must be a string")}function Cs(t,e){F(typeof t=="string"&&t.trim().length>0,e,"must be a non-empty string")}function of(t,e){F(t===void 0||typeof t=="boolean",e,"must be true or false")}function af(t,e){typeof t!="string"&&(F(Ne(t),e,"must be a path string or an object"),dn(t.path,`${e}.path`),t.coalesce!==void 0&&(F(Array.isArray(t.coalesce),`${e}.coalesce`,"must be an array"),t.coalesce.forEach((r,n)=>af(r,`${e}.coalesce[${n}]`))))}function cf(t,e){F(Ne(t),e,"must be an object");for(let r of["path","regex","contains","not_contains","starts_with","not_starts_with"])dn(t[r],`${e}.${r}`);if(typeof t.regex=="string")try{new RegExp(t.regex)}catch{F(!1,`${e}.regex`,"must be a valid regular expression")}of(t.exists,`${e}.exists`);for(let r of["in","not_in"])F(t[r]===void 0||Array.isArray(t[r]),`${e}.${r}`,"must be an array");for(let r of["all","any"]){let n=t[r];n!==void 0&&(F(Array.isArray(n),`${e}.${r}`,"must be an array"),n.forEach((s,o)=>cf(s,`${e}.${r}[${o}]`)))}}function Wa(t,e){F(Ne(t),e,"must be an object"),Cs(t.name,`${e}.name`);for(let r of["eventTypePath","sessionIdPath","cwdPath","projectPath"])dn(t[r],`${e}.${r}`);F(Array.isArray(t.events),`${e}.events`,"must be an array"),t.events.forEach((r,n)=>{let s=`${e}.events[${n}]`;if(F(Ne(r),s,"must be an object"),F(typeof r.name=="string",`${s}.name`,"must be a string"),F(typeof r.action=="string"&&Object.hasOwn(ef,r.action),`${s}.action`,`must be one of ${Object.keys(ef).join(", ")}`),r.match!==void 0&&cf(r.match,`${s}.match`),r.fields!==void 0){F(Ne(r.fields),`${s}.fields`,"must be an object");for(let[o,i]of Object.entries(r.fields))af(i,`${s}.fields.${o}`)}})}function xy(t,e,r){F(Ne(t),e,"must be an object"),Cs(t.name,`${e}.name`),Cs(t.path,`${e}.path`);for(let i of["workspace","project","agentId"])dn(t[i],`${e}.${i}`);for(let i of["startAtEnd","subagentOnly"])of(t[i],`${e}.${i}`);let{subagentSource:n,context:s}=t;if(n!==void 0&&(F(Ne(n),`${e}.subagentSource`,"must be an object"),F(typeof n.path=="string",`${e}.subagentSource.path`,"must be a string")),s!==void 0&&(F(Ne(s),`${e}.context`,"must be an object"),F(s.mode==="agents",`${e}.context.mode`,'must be "agents"'),dn(s.path,`${e}.context.path`),s.updateOn!==void 0&&(F(Array.isArray(s.updateOn),`${e}.context.updateOn`,"must be an array"),s.updateOn.forEach((i,a)=>F(i==="session_start"||i==="session_end",`${e}.context.updateOn[${a}]`,'must be "session_start" or "session_end"')))),typeof t.schema!="string"){F(Ne(t.schema),`${e}.schema`,"must be a schema name or an inline schema object"),Wa(t.schema,`${e}.schema`);return}Cs(t.schema,`${e}.schema`);let o=r?.[t.schema];o!==void 0&&Wa(o,`schemas.${t.schema}`)}function ky(t){F(Ne(t),"the top level","must be an object"),F(t.version===1,"version","must be 1");let{stateFile:e,schemas:r,watches:n}=t;if(F(e==null||typeof e=="string","stateFile","must be a string"),r!==void 0){F(Ne(r),"schemas","must be an object");for(let[s,o]of Object.entries(r))Wa(o,`schemas.${s}`)}F(Array.isArray(n),"watches","must be an array"),n.forEach((s,o)=>xy(s,`watches[${o}]`,r))}function ja(t=Sr){let e=ce(t);if(!(0,zt.existsSync)(e))throw new Error(`Transcript watch config not found: ${e}`);let r=ut(e);try{ky(r)}catch(n){let s=n instanceof Error?n.message:String(n);throw new Error(`Invalid transcript watch config: ${e} (${s})`,{cause:n})}return r.stateFile||(r.stateFile=Fs),r}function Ha(t=Sr){let e=ce(t),r=(0,Ds.dirname)(e);(0,zt.existsSync)(r)||(0,zt.mkdirSync)(r,{recursive:!0}),(0,zt.writeFileSync)(e,JSON.stringify(Py,null,2))}var ZE=require("crypto"),X=require("fs"),eS=require("fs/promises"),J=require("path");O();var fn=require("fs"),lf=require("path");O();se();function Ve(t,e){return typeof t!="object"||t===null||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(r=>e(r[1])))}function df(t){try{if(!(0,fn.existsSync)(t))return{offsets:{}};let e=ut(t);if(!e||typeof e!="object"||Array.isArray(e))return{offsets:{}};let r=i=>typeof i=="number"&&Number.isSafeInteger(i)&&i>=0,n=i=>typeof i=="string",s={offsets:Ve(e.offsets,r)},o=i=>Object.fromEntries(Object.entries(i).filter(([a])=>Object.hasOwn(s.offsets,a)));if(e.partials!==void 0&&(s.partials=o(Ve(e.partials,n))),e.partialBytes!==void 0&&(s.partialBytes=o(Ve(e.partialBytes,i=>typeof i=="string"&&i.length>0&&Buffer.from(i,"base64").toString("base64")===i))),e.frameLines!==void 0&&(s.frameLines=o(Ve(e.frameLines,r))),e.fileIdentities!==void 0&&(s.fileIdentities=o(Ve(e.fileIdentities,n))),e.checkpointFingerprints!==void 0&&(s.checkpointFingerprints=o(Ve(e.checkpointFingerprints,n))),e.pendingTools!==void 0){let i=c=>typeof c=="object"&&c!==null&&!Array.isArray(c),a=c=>i(c)&&typeof c.toolName=="string"&&c.toolName.length>0;s.pendingTools=Object.fromEntries(Object.entries(o(Ve(e.pendingTools,i))).map(([c,u])=>[c,Object.fromEntries(Object.entries(Ve(u,i)).map(([l,d])=>[l,Ve(d,a)]))]))}return e.cwds!==void 0&&(s.cwds=Ve(e.cwds,n)),s}catch(e){return f.warn("TRANSCRIPT","Failed to load watch state, starting fresh",{statePath:t,error:e instanceof Error?e.message:String(e)}),{offsets:{}}}}var Ny=64*1024,uf=new WeakMap;function Cy(t){let e=uf.get(t);return e||(e=(t.toolInput===void 0?0:Buffer.byteLength(JSON.stringify(t.toolInput)??""))<=Ny?t:{toolName:t.toolName},uf.set(t,e)),e}function Dy(t){let e={};for(let[r,n]of Object.entries(t)){e[r]={};for(let[s,o]of Object.entries(n)){e[r][s]={};for(let[i,a]of Object.entries(o))e[r][s][i]=Cy(a)}}return e}function pn(t,e){try{let r=(0,lf.dirname)(t);(0,fn.existsSync)(r)||(0,fn.mkdirSync)(r,{recursive:!0});let n=e.pendingTools?{...e,pendingTools:Dy(e.pendingTools)}:e;U(t,n,{mode:384})}catch(r){f.warn("TRANSCRIPT","Failed to save watch state",{statePath:t,error:r instanceof Error?r.message:String(r)})}}var ys=be(require("path"),1);gu();Nr();O();xe();ht();Pr();Mr();tr();On();ft();Mn();var Su="write_file",mm={async execute(t){let{sessionId:e,cwd:r,filePath:n,edits:s}=t,o=z(t.platform);if(!n)throw new Error("fileEditHandler requires filePath");if(f.dataIn("HOOK",`FileEdit: ${n}`,{editCount:s?.length??0}),!r)throw new Error(`Missing cwd in FileEdit hook input for session ${e}, file ${n}`);if(!Qe(r))return f.debug("HOOK","Project excluded from tracking, skipping file edit observation",{cwd:r,filePath:n}),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};let i={filePath:n,edits:s},a={success:!0},c=Le();if(c.runtime==="server"){if(kt(Su,G().MEMINDEX_SKIP_TOOLS))return f.debug("HOOK","Server runtime: file edit excluded by MEMINDEX_SKIP_TOOLS",{filePath:n}),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};let u={projectId:c.projectId,contentSessionId:e,platformSource:o,sourceType:"hook",eventType:"tool_use",occurredAtEpoch:Date.now(),payload:{tool_name:Su,tool_input:i,tool_response:a,cwd:r,platformSource:o}};try{return await c.client.recordEvent(u),f.debug("HOOK","File edit sent successfully via server",{filePath:n}),await xr(c.client,$e(c)),{continue:!0,suppressOutput:!0}}catch(l){if(Et(l))return Ue(l.kind,{status:l.status,message:l.message,route:"/v1/events",held:!0}),xt({op:"event",request:u},$e(c)),{continue:!0,suppressOutput:!0};if(Fe(l)&&l.isFallbackEligible())Ue(l.kind,{status:l.status,message:l.message,route:"/v1/events"});else return f.error("HOOK","Server file edit failed (non-recoverable)",{error:l instanceof Error?l.message:String(l)}),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS}}}return We("file_edit",{contentSessionId:e,platformSource:o,toolName:Su,toolInput:i,toolResponse:a,cwd:r}),f.debug("HOOK","File edit observation spooled",{filePath:n}),{continue:!0,suppressOutput:!0}}};Pt();C();O();qt();var je=require("fs"),Go=require("path");O();O();dt();Pt();C();Sn();var yu="<memindex-context>",bu="</memindex-context>",xI=["agent-mem-context"].map(t=>({open:`<${t}>`,close:`</${t}>`}));function hm(t){return[{open:yu,close:bu},...xI].reduce((e,r)=>e??kI(t,r.open,r.close),null)}function kI(t,e,r){let n=t.indexOf(e);if(n===-1)return null;let s=t.indexOf(r,n+e.length);return s===-1?null:{start:t.lastIndexOf(e,s),end:s+r.length}}var dD=K.settings();function _m(t,e){let r=`${yu}
|
|
34
34
|
${e}
|
|
35
|
-
${
|
|
35
|
+
${bu}`;if(!t)return r;let n=hm(t);return n?t.substring(0,n.start)+r+t.substring(n.end):t+`
|
|
36
36
|
|
|
37
|
-
${r}`}
|
|
37
|
+
${r}`}O();function Em(t,e){if(!t)return;let r=(0,Go.resolve)(t);if(r.includes("/.git/")||r.includes("\\.git\\")||r.endsWith("/.git")||r.endsWith("\\.git"))return;let n=(0,Go.dirname)(t);(0,je.existsSync)(n)||(0,je.mkdirSync)(n,{recursive:!0});let s="";(0,je.existsSync)(t)&&(s=(0,je.readFileSync)(t,"utf-8"));let o=`# Memory Context
|
|
38
38
|
|
|
39
|
-
${e}`,o=Ng(s,i),a=`${t}.tmp`;try{(0,Fe.writeFileSync)(a,o),(0,Fe.renameSync)(a,t)}catch(c){f.error("AGENTS_MD","Failed to write AGENTS.md",{agentsPath:t},c instanceof Error?c:new Error(String(c)))}}A();function PT(t){let e=t.trim().replace(/^\$\.?/,"");if(!e)return[];let r=[],n=e.split(".");for(let s of n){let i=/([^[\]]+)|\[(\d+)\]/g,o;for(;(o=i.exec(s))!==null;)o[1]?r.push(o[1]):o[2]&&r.push(parseInt(o[2],10))}return r}function hn(t,e){if(!e)return;let r=PT(e),n=t;for(let s of r){if(n==null)return;n=n[s]}return n}function Dg(t){return t==null||t===""}function Fg(t,e){if(t.startsWith("$watch.")){let r=t.slice(7);return e.watch[r]}if(t.startsWith("$schema.")){let r=t.slice(8);return e.schema[r]}if(t.startsWith("$session.")){let r=t.slice(9);return e.session?e.session[r]:void 0}if(t==="$cwd")return e.watch.workspace;if(t==="$project")return e.watch.project}function Ir(t,e,r){if(t!==void 0){if(typeof t=="string"){let n=Fg(t,r);return n!==void 0?n:hn(e,t)}if(t.coalesce&&Array.isArray(t.coalesce))for(let n of t.coalesce){let s=Ir(n,e,r);if(!Dg(s))return s}if(t.path){let n=Fg(t.path,r);if(n!==void 0)return n;let s=hn(e,t.path);if(!Dg(s))return s}if(t.value!==void 0)return t.value;if(t.default!==void 0)return t.default}}function Lg(t,e,r){let n={};if(!t)return n;for(let[s,i]of Object.entries(t))n[s]=Ir(i,e,r);return n}function _n(t,e,r){if(!e)return!0;if(e.all!==void 0){if(!Array.isArray(e.all))return!1;for(let o of e.all)if(!_n(t,o,r))return!1}if(e.any!==void 0&&(!Array.isArray(e.any)||!e.any.some(o=>_n(t,o,r))))return!1;let n=e.path||r.eventTypePath||"type",s=n?hn(t,n):void 0,i=s==null||s==="";if(e.exists!==void 0&&(e.exists&&i||!e.exists&&!i)||e.equals!==void 0&&s!==e.equals||e.not_equals!==void 0&&s===e.not_equals||e.in&&Array.isArray(e.in)&&!e.in.includes(s)||e.not_in&&Array.isArray(e.not_in)&&e.not_in.includes(s)||e.contains!==void 0&&(typeof s!="string"||!s.includes(e.contains))||e.not_contains!==void 0&&typeof s=="string"&&s.includes(e.not_contains)||e.starts_with!==void 0&&(typeof s!="string"||!s.startsWith(e.starts_with))||e.not_starts_with!==void 0&&typeof s=="string"&&s.startsWith(e.not_starts_with))return!1;if(e.regex)try{if(!new RegExp(e.regex).test(String(s??"")))return!1}catch(o){return f.debug("WORKER","Invalid regex in match rule",{regex:e.regex},o instanceof Error?o:void 0),!1}return!0}ut();Tr();A();lt();on();ki();mn();st();N();var Kt=require("path");N();function kT(t=j.dataDir()){return(0,Kt.join)(t,"bottles")}function Wg(t,e){let r=(0,Kt.resolve)(kT(e));return(0,Kt.resolve)(t).startsWith(r+Kt.sep)}Bt();ut();A();var xi=class{static checkUserPromptPrivacy(e,r,n,s,i,o){let a=e.getUserPrompt(r,n,i);return a===null?(f.warn("HOOK",`${s}: no user_prompts row for prompt #${n} \u2014 ingesting anyway (session-init likely raced worker boot; see #2794/#2795)`,{sessionId:i,contentSessionId:r,promptNumber:n,...o}),{allow:!0,prompt:""}):a.trim()===""?(f.debug("HOOK",`Skipping ${s} - user prompt was entirely private`,{sessionId:i,promptNumber:n,...o}),{allow:!1,reason:"private"}):{allow:!0,prompt:a}}};var Rr=require("path");function jg(){let t=xT();return async e=>{for(let r of e)r.module=t(r.filename);return e}}function xT(t=process.argv[1]?(0,Rr.dirname)(process.argv[1]):process.cwd(),e=Rr.sep==="\\"){let r=e?Hg(t):t;return n=>{if(!n)return;let s=e?Hg(n):n,{dir:i,base:o,ext:a}=Rr.posix.parse(s);(a===".js"||a===".mjs"||a===".cjs")&&(o=o.slice(0,-1*a.length));let c=decodeURIComponent(o);i||(i=".");let u=i.lastIndexOf("/node_modules");if(u>-1)return`${i.slice(u+14).replace(/\//g,".")}:${c}`;if(i.startsWith(r)){let l=i.slice(r.length+1).replace(/\//g,".");return l?`${l}:${c}`:c}return c}}function Hg(t){return t.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var J={};fs(J,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>Vi,DOMExceptionCoercer:()=>hu,EXCEPTION_STEP_INTERNAL_FIELDS:()=>An,ErrorCoercer:()=>Tn,ErrorEventCoercer:()=>_u,ErrorPropertiesBuilder:()=>wn,EventCoercer:()=>Eu,ExceptionStepsBuffer:()=>wu,ObjectCoercer:()=>vn,PrimitiveCoercer:()=>Rn,PromiseRejectionEventCoercer:()=>Su,ReduceableCache:()=>yu,StringCoercer:()=>In,chromeStackLineParser:()=>fu,createDefaultStackParser:()=>mu,createStackParser:()=>Nm,geckoStackLineParser:()=>pu,getInjectedReleaseId:()=>GI,getUtf8ByteLength:()=>Dm,nodeStackLineParser:()=>Am,opera10StackLineParser:()=>Im,opera11StackLineParser:()=>vm,resolveExceptionStepsConfig:()=>bu,reverseAndStripFrames:()=>xm,stripReservedExceptionStepFields:()=>jI,winjsStackLineParser:()=>Tm});var pe=(function(t){return t.AnonymousId="anonymous_id",t.DistinctId="distinct_id",t.Props="props",t.EnablePersonProcessing="enable_person_processing",t.PersonMode="person_mode",t.FeatureFlagDetails="feature_flag_details",t.FeatureFlags="feature_flags",t.FeatureFlagPayloads="feature_flag_payloads",t.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",t.BootstrapFeatureFlags="bootstrap_feature_flags",t.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",t.OverrideFeatureFlags="override_feature_flags",t.Queue="queue",t.AiQueue="ai_queue",t.AiCaptureQueue="ai_capture_queue",t.LogsQueue="logs_queue",t.OptedOut="opted_out",t.SessionId="session_id",t.SessionStartTimestamp="session_start_timestamp",t.SessionLastTimestamp="session_timestamp",t.PersonProperties="person_properties",t.GroupProperties="group_properties",t.InstalledAppBuild="installed_app_build",t.InstalledAppVersion="installed_app_version",t.SessionReplay="session_replay",t.PushRegistered="push_registered",t.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",t.SurveyLastSeenDate="survey_last_seen_date",t.SurveysInProgress="surveys_in_progress",t.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({});function Rt(t){let e=[];return JSON.stringify(t,function(r,n){if(typeof n=="bigint")return n.toString();if(!(typeof n=="function"||typeof n=="symbol")){if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(n&&typeof n=="object"){for(;e.length>0&&e[e.length-1]!==this;)e.pop();if(e.includes(n))return"[Circular]";e.push(n)}return n}})??"null"}var NT=Array.isArray,Kg=Object.prototype,rC=Kg.hasOwnProperty,Ni=Kg.toString,he=NT||function(t){return Ni.call(t)==="[object Array]"};var En=t=>t===Object(t)&&!he(t);var ft=t=>t===void 0,se=t=>Ni.call(t)=="[object String]",Zc=t=>se(t)&&t.trim().length===0,eu=t=>t===null,Le=t=>ft(t)||eu(t),Ar=t=>Ni.call(t)=="[object Number]"&&t===t;var Gg=t=>Ni.call(t)==="[object Boolean]";function Ci(t){return t===null||typeof t!="object"}function Gt(t,e){return Object.prototype.toString.call(t)===`[object ${e}]`}function At(t){switch(Object.prototype.toString.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Yg(t,Error)}}function zg(t){return Gt(t,"ErrorEvent")}function Mr(t){return"u">typeof Event&&Yg(t,Event)}function Vg(t){return Gt(t,"Object")}function Yg(t,e){try{return t instanceof e}catch{return!1}}var CT=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterestbot","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],Di=new Map,DT=256;function FT(t,e){let r="";for(let n=0;n<e.length;n++){let s=e[n];r+=s.length+":"+s}return t.length+":"+t+"|"+e.length+":"+r}var qg=function(t,e=[]){if(!t)return!1;let r=FT(t,e),n=Di.get(r);if(n!==void 0)return n;let s=t.toLowerCase(),i=CT.concat(e).some(o=>s.indexOf(o.toLowerCase())!==-1);return Di.size>=DT&&Di.clear(),Di.set(r,i),i};function Sn(t,e,r,n,s){return e>r&&(n.warn("min cannot be greater than max."),e=r),Ar(t)?t>r?(n.warn(" cannot be greater than max: "+r+". Using max value instead."),r):t<e?(n.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(n.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+s),Sn(s??r,e,r,n))}var LT=864e5,UT=1,$T=10;function Jg(t={}){return{refillRate:t.exceptionRateLimiterRefillRate??t.__exceptionRateLimiterRefillRate??UT,bucketSize:t.exceptionRateLimiterBucketSize??t.__exceptionRateLimiterBucketSize??$T}}var Fi=class{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=Sn(e.bucketSize,0,100,e._logger),this._refillRate=Sn(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=Sn(e.refillInterval,0,LT,e._logger)}_applyRefill(e,r){let n=r-e.lastAccess,s=Math.floor(n/this._refillInterval);if(s>0){let i=s*this._refillRate;e.tokens=Math.min(e.tokens+i,this._bucketSize),e.lastAccess=e.lastAccess+s*this._refillInterval}}consumeRateLimit(e){let r=Date.now(),n=String(e),s=this._buckets[n];return s?this._applyRefill(s,r):(s={tokens:this._bucketSize,lastAccess:r},this._buckets[n]=s),s.tokens===0?!0:(s.tokens--,s.tokens===0&&this._onBucketRateLimited?.(e),s.tokens===0)}stop(){this._buckets={}}};var Li="0123456789abcdef",Ui=class t{constructor(e){this.bytes=e}static ofInner(e){if(e.length===16)return new t(e);throw new TypeError("not 128-bit length")}static fromFieldsV7(e,r,n,s){if(!Number.isInteger(e)||!Number.isInteger(r)||!Number.isInteger(n)||!Number.isInteger(s)||e<0||r<0||n<0||s<0||e>0xffffffffffff||r>4095||n>1073741823||s>4294967295)throw new RangeError("invalid field value");let i=new Uint8Array(16);return i[0]=e/2**40,i[1]=e/2**32,i[2]=e/2**24,i[3]=e/2**16,i[4]=e/256,i[5]=e,i[6]=112|r>>>8,i[7]=r,i[8]=128|n>>>24,i[9]=n>>>16,i[10]=n>>>8,i[11]=n,i[12]=s>>>24,i[13]=s>>>16,i[14]=s>>>8,i[15]=s,new t(i)}static parse(e){let r;switch(e.length){case 32:r=/^[0-9a-f]{32}$/i.exec(e)?.[0];break;case 36:r=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;case 38:r=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e)?.slice(1,6).join("");break;case 45:r=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;default:break}if(r){let n=new Uint8Array(16);for(let s=0;s<16;s+=4){let i=parseInt(r.substring(2*s,2*s+8),16);n[s+0]=i>>>24,n[s+1]=i>>>16,n[s+2]=i>>>8,n[s+3]=i}return new t(n)}throw new SyntaxError("could not parse UUID string")}toString(){let e="";for(let r=0;r<this.bytes.length;r++)e+=Li.charAt(this.bytes[r]>>>4),e+=Li.charAt(15&this.bytes[r]),(r===3||r===5||r===7||r===9)&&(e+="-");return e}toHex(){let e="";for(let r=0;r<this.bytes.length;r++)e+=Li.charAt(this.bytes[r]>>>4),e+=Li.charAt(15&this.bytes[r]);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw new Error("unreachable");if(e<=7)return this.bytes.every(r=>r===0)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every(r=>r===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new t(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let r=0;r<16;r++){let n=this.bytes[r]-e.bytes[r];if(n!==0)return Math.sign(n)}return 0}},tu=class{constructor(e){this.timestamp=0,this.counter=0,this.random=e??BT()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,r){let n=this.generateOrAbortCore(e,r);return n===void 0&&(this.timestamp=0,n=this.generateOrAbortCore(e,r)),n}generateOrAbortCore(e,r){if(!Number.isInteger(e)||e<1||e>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(r<0||r>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+r>=this.timestamp))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter())}return Ui.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,Ui.ofInner(e)}},BT=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),Qg,ue=()=>WT().toString(),WT=()=>(Qg||(Qg=new tu)).generate();var $i=class{add(e){let r=ue(),n=++this.nextId;return this.promiseByIds[r]={id:n,promise:e},e.catch(()=>{}).finally(()=>{delete this.promiseByIds[r]}),e}async join(){let e=Object.values(this.promiseByIds).map(n=>n.promise),r=e.length;for(;r>0;)await Promise.all(e),e=Object.values(this.promiseByIds).map(n=>n.promise),r=e.length}getPromises(e=[],r=this.nextId){let n=new Set(e);return Object.values(this.promiseByIds).filter(s=>s.id<=r&&!n.has(s.promise)).map(s=>s.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}};function HT(t=console){return{log:t.log.bind(t),warn:t.warn.bind(t),error:t.error.bind(t),debug:t.debug.bind(t)}}var Zg=(t,e,r)=>{function n(i,...o){e(()=>{let a=r[i];a(t,...o)})}return{debug:(...i)=>{n("debug",...i)},info:(...i)=>{n("log",...i)},warn:(...i)=>{n("warn",...i)},error:(...i)=>{n("error",...i)},critical:(...i)=>{r.error(t,...i)},createLogger:i=>Zg(`${t} ${i}`,e,r)}},jT=t=>t();function em(t,e=jT){return Zg(t,e,HT())}var Or="Mobile",Wi="iOS",Pr="Android",im="Tablet",_C=Pr+" "+im;var KT="Apple",EC=KT+" Watch",om="Safari",Hi="BlackBerry",am="Samsung",GT=am+"Browser",zT=am+" Internet",ji="Chrome",VT=ji+" OS",YT=ji+" "+Wi,cm="Internet Explorer",qT=cm+" "+Or,su="Opera",SC=su+" Mini",um="Edge",JT="Microsoft "+um,iu="Firefox",QT=iu+" "+Wi,ou="Nintendo",au="PlayStation",Bi="Xbox",ZT=Pr+" "+Or,eI=Or+" "+om,yn="Windows",tI=yn+" Phone";var lm="Generic",yC=lm+" "+Or.toLowerCase(),bC=lm+" "+im.toLowerCase(),rI="Konqueror",nI="Oculus Browser",tm="Vivaldi",sI="Yandex",rm="Whale",iI="DuckDuckGo",oI="Pale Moon",nm="Waterfox",sm="Brave",dm="Claude",fm="Codex",pm="ChatGPT",aI="Google Search App",B="(\\d+(\\.\\d+)?)",ru=new RegExp("Version/"+B),nu=new RegExp("("+dm+"|"+fm+"|"+pm+")\\/"+B);var wC=new RegExp(Bi,"i"),TC=new RegExp(au+" \\w+","i"),IC=new RegExp(ou+" \\w+","i"),cI=new RegExp(Hi+"|PlayBook|BB10","i"),uI={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000","5.1":"XP","5.2":"XP","6.0":"Vista","6.1":"7","6.2":"8","6.3":"8.1","6.4":"10","10.0":"10"};var vC={[qT]:[new RegExp("rv:"+B)],[JT]:[new RegExp(um+"?\\/"+B)],[ji]:[new RegExp("("+ji+"|CrMo)\\/"+B)],[YT]:[new RegExp("CriOS\\/"+B)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+B)],[om]:[ru],[eI]:[ru],[su]:[new RegExp("("+su+"|OPR)\\/"+B)],[iu]:[new RegExp(iu+"\\/"+B)],[QT]:[new RegExp("FxiOS\\/"+B)],[rI]:[new RegExp("Konqueror[:/]?"+B,"i")],[Hi]:[new RegExp(Hi+" "+B),ru],[ZT]:[new RegExp("android\\s"+B,"i")],[zT]:[new RegExp(GT+"\\/"+B)],[nI]:[new RegExp("OculusBrowser\\/"+B)],[tm]:[new RegExp(tm+"\\/"+B)],[sI]:[new RegExp("YaBrowser\\/"+B)],[rm]:[new RegExp(rm+"\\/"+B)],[sm]:[new RegExp(sm+"\\/"+B)],[dm]:[nu],[fm]:[nu],[pm]:[nu],[iI]:[new RegExp("(DuckDuckGo|Ddg)\\/"+B)],[oI]:[new RegExp("PaleMoon\\/"+B)],[nm]:[new RegExp(nm+"\\/"+B)],[aI]:[new RegExp("GSA\\/"+B)],[cm]:[new RegExp("(rv:|MSIE )"+B)],Mozilla:[new RegExp("rv:"+B)]};var RC=[[new RegExp(Bi+"; "+Bi+" (.*?)[);]","i"),t=>[Bi,t&&t[1]||""]],[new RegExp(ou,"i"),[ou,""]],[new RegExp(au,"i"),[au,""]],[cI,[Hi,""]],[new RegExp(yn,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[tI,""];if(new RegExp(Or).test(e)&&!/IEMobile\b/.test(e))return[yn+" "+Or,""];let r=/Windows NT ([0-9.]+)/i.exec(e);if(r&&r[1]){let n=r[1],s=uI[n]||"";return/arm/i.test(e)&&(s="RT"),[yn,s]}return[yn,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>{if(t&&t[3]){let e=[t[3],t[4],t[5]||"0"];return[Wi,e.join(".")]}return[Wi,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{let e="";return t&&t.length>=3&&(e=ft(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Pr+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Pr+")","i"),t=>{if(t&&t[2]){let e=[t[2],t[3],t[4]||"0"];return[Pr,e.join(".")]}return[Pr,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{let e=["Mac OS X",""];if(t&&t[1]){let r=[t[1],t[2],t[3]||"0"];e[1]=r.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[VT,""]],[/Linux|debian/i,["Linux",""]]];var Xi="[Circular]",Ki="[Truncated]",Te="[Unserializable]",gm="[Function]",PC=Date.prototype.getTime,OC=Date.prototype.toISOString;function ze(t){let e="";for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(n>=55296&&n<=56319){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=t[r]+t[r+1],r++):e+="\uFFFD"}else e+=n>=56320&&n<=57343?"\uFFFD":t[r]}return e}function pt(t,e){if(!e)return t;let r=[];try{r=Object.keys(e)}catch{r=[]}for(let n of r){let s;try{s=e[n]}catch{s=Te}Object.defineProperty(t,n,{value:s,enumerable:!0,writable:!0,configurable:!0})}return t}function cu(t,e=Date.now()){if(typeof t!="string"||!t)return;let r=t.trim(),n=/^\d+\s*,/.test(r)?r.slice(0,r.indexOf(",")).trim():r;if(/^\d+$/.test(n)){let o=1e3*Math.min(Number(n),300);return o>0?o:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(n))return;let s=/^\w{3} \w{3} /.test(n)?n+" GMT":n,i=Date.parse(s)-e;if(!(!Number.isFinite(i)||i<=0))return Math.min(i,3e5)}var zt=class{record(e){if(e.kind==="too-large")return;if(e.kind!=="retry-later")return void this.reset();if(!e.retryAfterMs)return;let r=this.isOpen(),n=Date.now(),s=Math.min(e.retryAfterMs,3e5);if(!r){this._installedAt=n,this._until=n+s;return}this._until=Math.max(this._until,Math.min(n+s,this._installedAt+3e5))}remainingMs(){let e=Date.now();if(e<this._installedAt-5e3)return this.reset(),0;let r=Math.min(3e5,Math.max(0,this._until-e));return r===0&&this.reset(),r}isOpen(){return this.remainingMs()>0}reset(){this._until=0,this._installedAt=0}constructor(){this._until=0,this._installedAt=0}};var mm="utf8",lI=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function dI(t){return typeof t=="string"&&lI.test(t)}function Vt(t,e){return dI(t)?t:e()}function kr(t,e){let r=new Error(e);try{Object.defineProperty(r,"name",{value:t,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function hm(t){return t?.replace(/\/+$/,"")}async function _m(t,e){let r=null;for(let n=0;n<e.retryCount+1;n++){n>0&&await new Promise(s=>setTimeout(s,e.retryDelay));try{return await t()}catch(s){if(r=s,!e.retryCheck(s))throw s}}throw r}function uu(){return new Date().toISOString()}function le(t,e){let r=setTimeout(t,e);return r?.unref&&r?.unref(),r}async function Mt(t,e,r){let n;try{return await Promise.race([t,new Promise((s,i)=>{n=le(()=>{try{r?.(),s()}catch(o){i(o)}},e)})])}finally{clearTimeout(n)}}var Em=t=>t&&typeof t.then=="function";function bn(t){return Promise.all(t.map(e=>(e??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var lu,Sm,ym,xr;function wm(t){let e=globalThis._posthogChunkIds,r=globalThis._debugIds;if(!e&&!r)return;let n=e?Object.keys(e):[],s=r?Object.keys(r):[];if(xr&&bm(e,n,Sm)&&bm(r,s,ym))return xr;Sm=e?{...e}:void 0,ym=r?{...r}:void 0,xr={},lu??={};let i=(o,a)=>{for(let c of o){let u=a[c];if(!u)continue;let l=lu?.[c];if(l){xr[l]=u;continue}let d=t(c);for(let p=d.length-1;p>=0;p--){let g=d[p]?.filename;if(g){xr[g]=u,lu[c]=g;break}}}};return r&&i(s,r),e&&i(n,e),xr}function bm(t,e,r){return!t||!r?t===r:e.length===Object.keys(r).length&&e.every(n=>t[n]===r[n])}var du=50,fI=1e3,pI=100,gI=4,wn=class{constructor(e,r,n=[]){this.coercers=e,this.stackParser=r,this.modifiers=n}buildFromUnknown(e,r={}){let s=r&&r.mechanism||{handled:!0,type:"generic"},o=this.buildCoercingContext(s,r,0).apply(e),a=this.buildParsingContext(r),c=this.parseStacktrace(o,a);return{$exception_list:this.convertToExceptionList(c,s),$exception_level:"error"}}async modifyFrames(e){for(let r of e)r.stacktrace&&r.stacktrace.frames&&he(r.stacktrace.frames)&&(r.stacktrace.frames=await this.applyModifiers(r.stacktrace.frames));return e}coerceFallback(e){return{type:"Error",value:"Unknown error",stack:e.syntheticException?.stack,synthetic:!0}}parseStacktrace(e,r){let n;e.cause!=null&&(n=this.parseStacktrace(e.cause,r));let s;if(e.stack!=""&&e.stack!=null)try{s=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?r.skipFirstLines:0),r.chunkIdMap)}catch{}return{...e,cause:n,stack:s,errors:e.errors?.map(i=>this.parseStacktrace(i,r))}}applyChunkIds(e,r){return e.map(n=>(n.filename&&r&&(n.chunk_id=r[n.filename]),n))}applyCoercers(e,r){for(let n of this.coercers)if(n.match(e))return n.coerce(e,r);return this.coerceFallback(r)}async applyModifiers(e){let r=e;for(let n of this.modifiers)r=await n(r);return r}convertToExceptionList(e,r){let n=[],s=(i,o,a)=>{let c=n.length,u=o===void 0?{type:typeof r.type=="string"&&r.type.length>0?r.type:"generic",...typeof r.handled=="boolean"?{handled:r.handled}:r.handled===void 0?{handled:!0}:{},synthetic:typeof r.synthetic=="boolean"?r.synthetic:i.synthetic,exception_id:c}:{type:"chained",source:a,synthetic:i.synthetic,exception_id:c,parent_id:o},l={type:i.type,value:i.value,mechanism:u};i.stack&&(l.stacktrace={type:"raw",frames:i.stack}),n.push(l),i.cause&&s(i.cause,c,"cause");for(let d of i.errors??[])s(d,c,"member")};return s(e),n}buildParsingContext(e){return{chunkIdMap:wm(this.stackParser),skipFirstLines:e.skipFirstLines??1}}getAggregateErrors(e){try{if(At(e)){let r=Object.getPrototypeOf(e);for(let n=0;r&&n<pI;n++){let s=Object.getOwnPropertyDescriptor(r,"constructor")?.value;if(typeof s=="function"&&s.name==="AggregateError"){let i=e.errors;return he(i)?i:void 0}r=Object.getPrototypeOf(r)}}}catch{}}buildCoercingContext(e,r,n=0){let s=0,i=0,o=!1,a=new Set,c=[],u={},l=(g,m,h=0)=>{let _=d(m,h),S=_.apply;if(_.apply=v=>{c.push(g);try{return S(v)}finally{c.pop()}},h>gI||h>0&&c.indexOf(g)!==-1)return this.coerceFallback(_);let b=typeof g=="object"&&g!==null||typeof g=="function";if(h===0&&s>=du||b&&a.has(g))return;b&&a.add(g),h===0&&s++;let w=this.getAggregateErrors(g);o||=!!w;let T;try{if(T=this.applyCoercers(g,_),!T)throw u}catch(v){if(v===u){h===0&&s--;return}if(!o)throw v;T=this.coerceFallback(_)}if(!w||s>=du)return T;let y;try{y=w.length}catch{return T}if(!Number.isInteger(y)||y<0||y>4294967295)return T;let P=[];for(let v=0;s<du&&i<fI&&v<y;v++){i++;let R;try{R=_.next(w[v])}catch{s++,R=this.coerceFallback(d(m+1))}R&&P.push(R)}return{...T,errors:P}},d=(g,m=0)=>({...r,syntheticException:g==0?r.syntheticException:void 0,mechanism:g==0?e:{},apply:h=>{let _=l(h,g,m+1);if(!_)throw u;return _},next:h=>l(h,g+1)}),p=d(n);return{...p,apply:g=>l(g,n)??this.coerceFallback(p)}}};var ee="?",mI="<anonymous>",hI=/^([a-z][a-z0-9.+-]+):/i,_I=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function EI(t){if(!t||t===mI)return!1;let e=hI.exec(t);return!e||_I.includes(e[1].toLowerCase())}function Ve(t,e,r,n,s){let i={platform:t,filename:e,function:r==="<anonymous>"?ee:r,in_app:EI(e)};return ft(n)||(i.lineno=n),ft(s)||(i.colno=s),i}var Gi=(t,e)=>{let r=t.indexOf("safari-extension")!==-1,n=t.indexOf("safari-web-extension")!==-1;return r||n?[t.indexOf("@")!==-1?t.split("@")[0]:ee,r?`safari-extension:${e}`:`safari-web-extension:${e}`]:[t,e]};var SI=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,yI=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,bI=/\((\S*)(?::(\d+))(?::(\d+))\)/,fu=(t,e)=>{let r=SI.exec(t);if(r){let[,s,i,o]=r;return Ve(e,s,ee,+i,+o)}let n=yI.exec(t);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=bI.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}let[i,o]=Gi(n[1]||ee,n[2]);return Ve(e,o,i,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var wI=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,TI=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,pu=(t,e)=>{let r=wI.exec(t);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let o=TI.exec(r[3]);o&&(r[1]=r[1]||"eval",r[3]=o[1],r[4]=o[2],r[5]="")}let s=r[3],i=r[1]||ee;return[i,s]=Gi(i,s),Ve(e,s,i,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var II=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,Tm=(t,e)=>{let r=II.exec(t);return r?Ve(e,r[2],r[1]||ee,+r[3],r[4]?+r[4]:void 0):void 0};var vI=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,Im=(t,e)=>{let r=vI.exec(t);return r?Ve(e,r[2],r[3]||ee,+r[1]):void 0},RI=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,vm=(t,e)=>{let r=RI.exec(t);return r?Ve(e,r[5],r[3]||r[4]||ee,+r[1],+r[2]):void 0};var AI=/^\s*[-]{4,}$/,MI=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,PI=/^Promise\.(?:all|any)$/,OI=/^index \d+$/,kI="node:internal/promise",Am=(t,e)=>{let r=t.match(MI);if(r){let n,s,i,o,a;if(r[1]){i=r[1];let l=i.lastIndexOf(".");if(i[l-1]==="."&&l--,l>0){n=i.slice(0,l),s=i.slice(l+1);let d=n.indexOf(".Module");d>0&&(i=i.slice(d+1),n=n.slice(0,d))}o=void 0}s&&(o=n,a=s),s==="<anonymous>"&&(a=void 0,i=void 0),i===void 0&&(a=a||ee,i=o?`${o}.${a}`:a);let c=r[2]?.startsWith("file://")?r[2].slice(7):r[2],u=r[5]==="native";return c?.match(/\/[A-Z]:/)&&(c=c.slice(1)),!c&&r[5]&&!u&&(c=r[5]),PI.test(i)&&OI.test(c||"")&&(c=kI),{filename:c?decodeURI(c):void 0,module:void 0,function:i,lineno:Rm(r[3]),colno:Rm(r[4]),in_app:xI(c||"",u),platform:e}}if(t.match(AI))return{filename:t,platform:e}};function xI(t,e=!1){return!(e||t&&!t.startsWith("/")&&!t.match(/^[A-Z]:/)&&!t.startsWith(".")&&!t.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&t!==void 0&&!t.includes("node_modules/")}function Rm(t){return parseInt(t||"",10)||void 0}var Mm=/\(error: (.*)\)/,Pm=50,NI=10,CI=1e3;function gu(t,e){return t.filename===e.filename&&t.function===e.function&&t.module===e.module&&t.lineno===e.lineno&&t.colno===e.colno}function DI(t){for(let e=1;e<=NI;e++){let r=t.length-2*e;if(r<0)break;let n=!0;for(let s=0;s<e;s++){let i=t[r+s];if(!gu(i,t[r+e+s])){n=!1;break}}if(n){for(let s=0;s<e;s++)t[r+s]=t[r+e+s];return t.length=r+e,{start:r,length:e}}}}function FI(t,e){let r=e.start+e.length,n=km(t,e);n&&t.splice(r+n===t.length?r:e.start,n)}function Om(t,e){let r=e.start;for(;r>0&&gu(t[r-1],t[r-1+e.length]);)r--;return e.start-r}function km(t,e){let r=e.start+e.length,n=r;for(;n<t.length&&gu(t[n],t[n-e.length]);)n++;return n-r}function LI(t,e){let r=e[0],n=t.length-(r?Om(t,r):0);for(let s of e)n-=km(t,s);return n}function UI(t){let e=t.map(n=>`${n.function}|${n.filename}|${n.lineno}|${n.colno}|${n.module}`),r=0;for(let n=1;n<e.length;n++)$I(e,n,r)&&(r=n);t.push(...t.splice(0,r))}function $I(t,e,r){for(let n=0;n<t.length;n++){let s=t[(e+n)%t.length],i=t[(r+n)%t.length];if(s!==i)return s<i}return!1}function xm(t){if(!t.length)return[];let e=Array.from(t);return e.reverse(),e.slice(0,Pm).map(r=>({...r,filename:r.filename||BI(e).filename,function:r.function||ee}))}function BI(t){return t[t.length-1]||{}}function mu(){return Nm("web:javascript",fu,pu)}function Nm(t,...e){return(r,n=0)=>{let s=[],i=r.split(`
|
|
40
|
-
`),
|
|
41
|
-
at ${r.filename}:${n}:${s}`}};var WI=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,In=class{match(e){return typeof e=="string"}coerce(e,r){let[n,s]=this.getInfos(e);return{type:n??"Error",value:s??e,stack:r.syntheticException?.stack,synthetic:!0}}getInfos(e){let r="Error",n=e,s=e.match(WI);return s&&(r=s[1],n=s[2]),[r,n]}};var Cm=["fatal","error","warning","log","info","debug"];function zi(t,e=40){let r=Object.keys(t);if(r.sort(),!r.length)return"[object has no keys]";for(let n=r.length;n>0;n--){let s=r.slice(0,n).join(", ");if(!(s.length>e))return n===r.length||s.length<=e?s:`${s.slice(0,e)}...`}return""}var vn=class{match(e){return typeof e=="object"&&e!==null}coerce(e,r){let n=this.getErrorPropertyFromObject(e);return n?r.apply(n):{type:this.getType(e),value:this.getValue(e),stack:this.getStack(e)??r.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){if(Mr(e))return e.constructor.name;let r="name"in e?e.name:void 0;return se(r)&&!Zc(r)?r:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){let s=`'${e.name}' captured as exception`;return"message"in e&&typeof e.message=="string"&&(s+=` with message: '${e.message}'`),s}if("message"in e&&typeof e.message=="string")return e.message;let r=this.getObjectClassName(e),n=zi(e);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(e){return se(e)&&!Zc(e)&&Cm.indexOf(e)>=0}getStack(e){try{return se(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:se(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)){let n=e[r];if(At(n))return n}}getObjectClassName(e){try{let r=Object.getPrototypeOf(e);return r?r.constructor.name:void 0}catch{return}}};var Eu=class{match(e){return Mr(e)}coerce(e,r){let n=e.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${zi(e)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Rn=class{match(e){return Ci(e)}coerce(e,r){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Su=class{match(e){return Gt(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Mr(e))return!1;try{let r=e.detail;return r!=null&&typeof r=="object"&&"reason"in r}catch{return!1}}coerce(e,r){let n=this.getUnhandledRejectionReason(e);return Ci(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(n)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}};var yu=class{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let r=this._cache.get(e);if(r!==void 0)return this._cache.delete(e),this._cache.set(e,r),r}set(e,r){this._cache.set(e,r)}reduce(){for(;this._cache.size>=this._maxSize;){let e=this._cache.keys().next().value;e&&this._cache.delete(e)}}};var An={MESSAGE:"$message",TIMESTAMP:"$timestamp"},HI=new Set([An.MESSAGE,An.TIMESTAMP]),Vi={enabled:!0,max_bytes:32768};function bu(t){return t?{enabled:t.enabled??Vi.enabled,max_bytes:XI(t.max_bytes,Vi.max_bytes)}:{...Vi}}function jI(t){if(!t)return{sanitizedProperties:{},droppedKeys:[]};let e=[];return{sanitizedProperties:Object.keys(t).reduce((n,s)=>HI.has(s)?(e.push(s),n):(n[s]=t[s],n),{}),droppedKeys:e}}var wu=class{constructor(e){this._entries=[],this._totalBytes=0,this._config=bu(e)}setConfig(e){this._config=bu(e),this._trimToMaxBytes()}add(e){let r=KI(e);if(!r)return;let n=Dm(r.json);n>this._config.max_bytes||(this._entries.push({step:r.step,bytes:n}),this._totalBytes+=n,this._trimToMaxBytes())}getAttachable(){return this._entries.map(e=>e.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let e=this._entries.shift();e&&(this._totalBytes-=e.bytes)}}};function XI(t,e){if(!Ar(t)||t===1/0||t===-1/0)return e;let r=Math.floor(t);return r<0?e:r}function KI(t){let e;try{e=Rt(t)}catch{return}try{let r=JSON.parse(e);if(!En(r))return;let n=r,s=n[An.MESSAGE],i=n[An.TIMESTAMP];return!se(s)||s.trim().length===0||!se(i)&&!Ar(i)?void 0:{step:n,json:e}}catch{return}}function Dm(t){if("u">typeof TextEncoder)return new TextEncoder().encode(t).length;let e=encodeURIComponent(t),r=0;for(let n=0;n<e.length;n++)e[n]==="%"?(r+=1,n+=2):r+=1;return r}function GI(){if("u">typeof process){let e=process.env.POSTHOG_RELEASE_ID?.trim();if(e)return e}let t=globalThis._posthogReleaseId;return typeof t=="string"&&t.length>0?t:void 0}var Tu=t=>{if("flags"in t){let e=Fm(t.flags),r=Lm(t.flags);return{...t,featureFlags:e,featureFlagPayloads:r}}{let e=t.featureFlags??{},r=Object.fromEntries(Object.entries(t.featureFlagPayloads||{}).map(([s,i])=>[s,Nr(i)])),n=Object.fromEntries(Object.entries(e).map(([s,i])=>[s,zI(s,i,r[s])]));return{...t,featureFlags:e,featureFlagPayloads:r,flags:n}}};function zI(t,e,r){return{key:t,enabled:typeof e=="string"?!0:e,variant:typeof e=="string"?e:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:r?JSON.stringify(r):void 0,description:void 0}}}var Fm=t=>Object.fromEntries(Object.entries(t??{}).map(([e,r])=>[e,Mn(r)]).filter(([,e])=>e!==void 0)),Lm=t=>{let e=t??{};return Object.fromEntries(Object.keys(e).filter(r=>{let n=e[r];return n.enabled&&n.metadata&&n.metadata.payload!==void 0}).map(r=>{let n=e[r].metadata?.payload;return[r,n?Nr(n):void 0]}))},Mn=t=>t===void 0?void 0:t.variant??t.enabled,Nr=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};var Um=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","bfcid","irclid","_kx"],VI=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain",...Um,"$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Pn=(t,e=[])=>{let r={},n=s=>{t[s]!==void 0&&(r[s]=t[s])};return VI.forEach(n),e.forEach(n),r};var Yi=class{constructor(){this.events={},this.events={}}on(e,r){return this.events[e]||(this.events[e]=[]),this.events[e].push(r),()=>{this.events[e]=this.events[e].filter(n=>n!==r)}}emit(e,r){for(let n of this.events[e]||[])n(r);for(let n of this.events["*"]||[])n(e,r)}};function Iu(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var qI="NativeGzipValidationError",JI=31,QI=139,ZI=8,ev=t=>t.length>=2&&t[0]===JI&&t[1]===QI;var On,tv=()=>{if(On)return On;On=[];for(let t=0;t<256;t++){let e=t;for(let r=0;r<8;r++)e=1&e?3988292384^e>>>1:e>>>1;On[t]=e>>>0}return On},rv=t=>{let e=tv(),r=4294967295;for(let n=0;n<t.length;n++)r=e[(r^t[n])&255]^r>>>8;return(4294967295^r)>>>0},qi=t=>{throw kr(qI,`Native gzip produced invalid output: ${t}`)},nv=async(t,e)=>{t.size<18&&qi("too-short");let r=new Uint8Array(await t.slice(0,10).arrayBuffer());(!ev(r)||r[2]!==ZI)&&qi("invalid-header");let n=new DataView(await t.slice(t.size-8).arrayBuffer());n.getUint32(0,!0)!==rv(e)&&qi("invalid-crc");let s=e.length>>>0;n.getUint32(4,!0)!==s&&qi("invalid-size")};async function kn(t,e=!0,r){try{let n=new TextEncoder().encode(t),s=new globalThis.CompressionStream("gzip"),i=s.writable.getWriter(),o=i.write(n).then(()=>i.close()).catch(async u=>{try{await i.abort(u)}catch{}throw u}),a=new Response(s.readable).blob(),[c]=await Promise.all([a,o]);return await nv(c,n),c}catch(n){if(r?.rethrow)throw n;return e&&console.error("Failed to gzip compress data",n),null}}var Ie=class extends Error{constructor(e,r,n,s){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+r),this.response=e,this.reqByteLength=r,this.responseBodyDeadline=n,this.abortController=s,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return cu(this.response.headers?.get("retry-after"))}catch{return}}get bodyReadTimedOut(){return this._bodyReadTimedOut}get text(){if(!this.responseBodyTextPromise)if(Date.now()>=this.responseBodyDeadline){this._bodyReadTimedOut=!0;let e=kr("AbortError","Response body read timed out");this.cancelResponseBody(e),this.responseBodyTextPromise=Promise.reject(e)}else{let e=new Promise((n,s)=>{this.responseBodyTimer=le(()=>{this._bodyReadTimedOut=!0;let i=kr("AbortError","Response body read timed out");s(i),this.cancelResponseBody(i)},this.responseBodyDeadline-Date.now())}),r;try{r=Promise.resolve(this.response.text())}catch(n){r=Promise.reject(n)}this.responseBodyTextPromise=Promise.race([r,e]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then(e=>JSON.parse(e))}cancelResponseBody(e){clearTimeout(this.responseBodyTimer),this.abortController.signal.aborted||this.abortController.abort(e),(async()=>{try{await this.response.body?.cancel()}catch{}})()}},gt=class extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}};var sv=(t,e)=>{for(let r of Object.keys(e))(r.startsWith("$feature/")||r==="$active_feature_flags")&&(t[r]=e[r])};async function $m(t){if(t instanceof Ie){let e="";try{e=await t.text}catch{t.bodyReadTimedOut&&(e="<response body read timed out>")}console.error(`Error while flushing PostHog: message=${t.message}, response body=${e}`,t)}else console.error("Error while flushing PostHog",t);return Promise.resolve()}function iv(t){return typeof t=="object"&&(t instanceof Ie||jm(t))}function jm(t){return t instanceof gt}function ov(t){if(t instanceof Ie)return t.status===502||t.status===504;if(!(t instanceof gt))return!1;let e=t.error;return(e?.code??e?.cause?.code)!=="ECONNREFUSED"}var Bm=10485760;function Wm(t){try{return typeof t!="string"?t instanceof Uint8Array?t.byteLength:t.size:"u">typeof Buffer?Buffer.byteLength(t,mm):new TextEncoder().encode(t).length}catch{return 0}}function Cr(t){return typeof t=="object"&&t instanceof Ie&&t.status===413}function Ji(t){return t instanceof Ie?t.status===408||t.status===429||t.status>=500:jm(t)}function Hm(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var vu="default",xn=class{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new wn([new Tn,new vn,new In,new Rn],mu())}getEvaluationRuntime(){}constructor(e,r={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new $i,this._events=new Yi,this._isInitialized=!1;let n=typeof e=="string"?e.trim():"",s=typeof r.host=="string"?r.host.trim():"",i=!n;this._logger=em("[PostHog]",this.logMsgIfDebug.bind(this)),i&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=n,this.host=hm(s||"https://us.i.posthog.com"),this.flushAt=r.flushAt?Math.max(r.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,r.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,r.maxQueueSize??1e3),this.flushInterval=r.flushInterval??1e4,this.preloadFeatureFlags=r.preloadFeatureFlags??!0,this.defaultOptIn=r.defaultOptIn??!0,this.disableSurveys=r.disableSurveys??!1,this._retryOptions={retryCount:r.fetchRetryCount??3,retryDelay:r.fetchRetryDelay??3e3,retryCheck:Ji},this.requestTimeout=r.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=r.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=r.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=r.disableGeoip??!0,this.disabled=(r.disabled??!1)||i,this.historicalMigration=r?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=r?.evaluationContexts??r?.evaluationEnvironments,r?.evaluationEnvironments&&!r?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!Iu()||(r?.disableCompression??!1)}logMsgIfDebug(e){this.isDebug&&e()}wrap(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return e();this._initPromise.then(()=>e())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(pe.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(pe.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(pe.OptedOut,!0)})}on(e,r){return this._events.on(e,r)}debug(e=!0){if(this.removeDebugCallback?.(),e){let r=this.on("*",(n,s)=>this._logger.info(n,s));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let r=e.properties||{},n=this.mergeCommonEventProperties(r);return sv(n,r),e.event==="$feature_flag_called"&&n.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled()&&(n=Pn(n)),{distinct_id:e.distinct_id,event:e.event,properties:n}}mergeCommonEventProperties(e){return{...e,...this.getCommonEventProperties()}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,r,n){this.wrap(()=>{let s={...this.buildPayload({distinct_id:e,event:"$identify",properties:r})};this.enqueue("identify",s,n)})}async identifyStatelessImmediate(e,r,n){let s={...this.buildPayload({distinct_id:e,event:"$identify",properties:r})};await this.sendImmediate("identify",s,n)}captureStateless(e,r,n,s){this.wrap(()=>{let i=this.buildPayload({distinct_id:e,event:r,properties:n});this.enqueue("capture",i,s)})}async captureStatelessImmediate(e,r,n,s){let i=this.buildPayload({distinct_id:e,event:r,properties:n});await this.sendImmediate("capture",i,s)}aliasStateless(e,r,n,s){this.wrap(()=>{let i=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:e}});this.enqueue("alias",i,s)})}async aliasStatelessImmediate(e,r,n,s){let i=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:e}});await this.sendImmediate("alias",i,s)}groupIdentifyStateless(e,r,n,s,i,o){this.wrap(()=>{let a=this.buildPayload({distinct_id:i||`$${e}_${r}`,event:"$groupidentify",properties:{$group_type:e,$group_key:r,$group_set:n||{},...o||{}}});this.enqueue("capture",a,s)})}async groupIdentifyStatelessImmediate(e,r,n,s,i,o){let a=this.buildPayload({distinct_id:i||`$${e}_${r}`,event:"$groupidentify",properties:{$group_type:e,$group_key:r,$group_set:n||{},...o||{}}});await this.sendImmediate("capture",a,s)}async getRemoteConfig(){await this._initPromise;let e=this.host;e==="https://us.i.posthog.com"?e="https://us-assets.i.posthog.com":e==="https://eu.i.posthog.com"&&(e="https://eu-assets.i.posthog.com");let r=`${e}/array/${this.apiKey}/config`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(r,n,{type:"required",consume:s=>s.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).catch(s=>{this._logger.error("Remote config could not be loaded",s),this._events.emit("error",s)})}async getFlags(e,r={},n={},s={},i={},o=!1){await this._initPromise;let a=o?"&config=true":"",c=`${this.host}/flags/?v=2${a}`,u={token:this.apiKey,distinct_id:e,groups:r,person_properties:n,group_properties:s,...i};n.$device_id&&(u.$device_id=n.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(u.evaluation_contexts=this.evaluationContexts);let l=this.getEvaluationRuntime();l&&(u.evaluation_runtime=l);let d={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(u)};return this._logger.info("Flags URL",c),this.fetchWithRetry(c,d,{type:"required",consume:p=>p.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:ov},this.featureFlagsRequestTimeoutMs).then(p=>({success:!0,response:Tu(p)})).catch(p=>(this._events.emit("error",p),{success:!1,error:this.categorizeRequestError(p)}))}categorizeRequestError(e){if(e instanceof Ie)return{type:"api_error",statusCode:e.status};if(e instanceof gt){let r=e.error;return r instanceof Error&&(r.name==="AbortError"||r.name==="TimeoutError")?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,r,n={},s={},i={},o){await this._initPromise;let a=await this.getFeatureFlagDetailStateless(e,r,n,s,i,o);if(a===void 0)return{response:void 0,requestId:void 0};let c=Mn(a.response);return c===void 0&&(c=!1),{response:c,requestId:a.requestId}}async getFeatureFlagDetailStateless(e,r,n={},s={},i={},o){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(r,n,s,i,o,[e]);return a===void 0?void 0:{response:a.flags[e],requestId:a.requestId,evaluatedAt:a.evaluatedAt}}async getFeatureFlagPayloadStateless(e,r,n={},s={},i={},o){await this._initPromise;let a=await this.getFeatureFlagPayloadsStateless(r,n,s,i,o,[e]);if(!a)return;let c=a[e];return c===void 0?null:c}async getFeatureFlagPayloadsStateless(e,r={},n={},s={},i,o){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,r,n,s,i,o)).payloads}async getFeatureFlagsStateless(e,r={},n={},s={},i,o){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,r,n,s,i,o)}async getFeatureFlagsAndPayloadsStateless(e,r={},n={},s={},i,o){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(e,r,n,s,i,o);return a?{flags:a.featureFlags,payloads:a.featureFlagPayloads,requestId:a.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(e,r={},n={},s={},i,o){await this._initPromise;let a={geoip_disable:i??this.disableGeoip};o&&(a.flag_keys_to_evaluate=o);let c=await this.getFlags(e,r,n,s,a);if(!c.success)return;let u=c.response;return u.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),u.quotaLimited?.includes("feature_flags")?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:u?.requestId,quotaLimited:u.quotaLimited}):u}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let e=`${this.host}/api/surveys/?token=${this.apiKey}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},s=(await this.fetchWithRetry(e,r,{type:"required",consume:i=>{if(i.status!==200||!i.json){let o=`Surveys API could not be loaded: ${i.status}`,a=new Error(o);return this._logger.error(a),this._events.emit("error",new Error(o)),Promise.resolve(void 0)}return i.json()}}).catch(i=>{this._logger.error("Surveys API could not be loaded",i),this._events.emit("error",i)}))?.surveys;return s&&this._logger.info("Surveys fetched from API: ",JSON.stringify(s)),s??[]}get props(){return this._props||(this._props=this.getPersistedProperty(pe.Props)),this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(pe.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(pe.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return vu}persistedQueueKeyForRoute(e){return pe.Queue}getActiveQueueRoutes(){return[vu]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,r,n,s){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(r,n);if(i=this.processBeforeEnqueue(i),i===null)return;i=this.normalizeMessage(i);let o=this.persistedQueueKeyForRoute(s??this.getQueueRouteKey(i)),a=this.getPersistedProperty(o)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),a.push({message:i}),this.setPersistedProperty(o,a),this._events.emit(e,i),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=le(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(e,r,n,s){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(r,n);if(i=this.processBeforeEnqueue(i),i!==null){i=this.normalizeMessage(i);try{await this.sendBatch([i],void 0,s??this.getQueueRouteKey(i))}catch(o){this._events.emit("error",o)}}}normalizeMessage(e){let{type:r,library:n,library_version:s,...i}=e,o=Hm(i.properties)?i.properties:void 0;return n!==void 0&&o?.$lib===void 0&&(o={...o||{},$lib:n}),s!==void 0&&o?.$lib_version===void 0&&(o={...o||{},$lib_version:s}),o&&(i.properties=o),i.uuid=Vt(i.uuid,ue),i}normalizeTimestampForWire(e){let r=e instanceof Date?e:typeof e=="string"?new Date(e):null;if(!r||Number.isNaN(r.getTime()))return e;let n=r.toISOString(),s=typeof e=="string"?e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return s&&s.length>3?n.replace(/\.\d{3}Z$/,`.${s}Z`):n}prepareMessage(e,r){let n={...e,timestamp:r?.timestamp?r?.timestamp:uu(),uuid:Vt(r?.uuid,ue)};return(r?.disableGeoip??this.disableGeoip)&&(Hm(n.properties)||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId),n}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flushAutomatic().catch(async e=>{await $m(e)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(e,r=[]){let n=r.filter(i=>!!i),s=0;for(;;){let i=this.promiseQueue.getPromises([...n,...this.flushPromises],e);if(i.length===0)return;s>0&&this._logger.debug(`flush() re-checking ${i.length} pending promise(s) before flushing`),await Promise.all(i.map(o=>o.catch(()=>{}))),s++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(e){if(this.disabled)return Promise.resolve();if(!e&&this.pendingFlushPromise)return this.pendingFlushPromise;let r=this.flushPromise,n=this.promiseQueue.maxId,s=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(n,[r,s])}).then(()=>bn([r])).then(()=>(this.pendingFlushPromise===s&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=s,this.flushPromise=s,this.flushPromises.add(s),this.addPendingPromise(s),bn([s]).then(()=>{this.flushPromises.delete(s),this.pendingFlushPromise===s&&(this.pendingFlushPromise=null),this.flushPromise===s&&(this.flushPromise=null)}),s}getCustomHeaders(){let e=this.getCustomUserAgent(),r={};return e&&e!==""&&(r["User-Agent"]=e),r}compressPayload(e){return kn(e,this.isDebug)}getBatchEndpointPath(e){return"/batch/"}async sendBatch(e,r,n=vu){let s={api_key:this.apiKey,batch:e.map(u=>{if(!u)return u;let l=this.normalizeTimestampForWire(u.timestamp);return l===u.timestamp?u:{...u,timestamp:l}}),sent_at:uu()};this.historicalMigration&&(s.historical_migration=!0);let i=Rt(s),o=`${this.host}${this.getBatchEndpointPath(n)}`,a=this.disableCompression?null:await this.compressPayload(i),c={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...a!==null&&{"Content-Encoding":"gzip"}},body:a||i};await this.fetchWithRetry(o,c,{type:"successful-write"},r)}async _flush(){this.clearFlushTimer(),await this._initPromise;let e=this.getActiveQueueRoutes();if(!e.some(s=>this.getRouteQueue(s).length>0))return;let r=[],n;for(let s of e)try{await this._flushRoute(s,r)}catch(i){n===void 0&&(n=i)}if(n!==void 0)throw n;this._events.emit("flush",r)}async _flushRoute(e,r){let n=this.persistedQueueKeyForRoute(e),s=this.getPersistedProperty(n)||[];if(!s.length)return;let i=s.length,o=0;for(;s.length>0&&o<i;){let a=s.slice(0,this.maxBatchSize),c=a.map(d=>d.message===void 0?d.message:this.normalizeMessage(d.message)),u=async()=>{let d=this.getPersistedProperty(n)||[],p=[...a],g=d.filter(m=>{let h=m.message?.uuid,_=p.findIndex(S=>S===m||typeof h=="string"&&h.length>0&&S.message?.uuid===h);return _===-1?!0:(p.splice(_,1),!1)});this.setPersistedProperty(n,g),s=g,this._dequeuedMessagesCount+=a.length,await this.flushStorage()},l={retryCheck:d=>Cr(d)?!1:Ji(d)};try{await this.sendBatch(c,l,e)}catch(d){if(Cr(d)&&c.length>1){this.maxBatchSize=Math.max(1,Math.floor(c.length/2)),this._logger.warn(`Received 413 when sending batch of size ${c.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw d instanceof gt||await u(),this._events.emit("error",d),d}await u(),r.push(...c),o+=c.length}}async _sendOtlpBatch({path:e,auth:r,payload:n}){if(this.disabled)return{kind:"fatal",error:new Error("The client is disabled")};let s;try{s=JSON.stringify(n)}catch(l){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${e} batch; reporting it as too large`,l)),{kind:"too-large",measuredLocally:!0}}let i=Wm(s);if(i>Bm)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${e} batch of ${i} bytes: the endpoint accepts at most ${Bm}`)),{kind:"too-large",measuredLocally:!0};let o=r==="bearer"?`${this.host}/i/v1/${e}`:`${this.host}/i/v1/${e}?token=${encodeURIComponent(this.apiKey)}`,a=this.disableCompression?null:await this.compressPayload(s),c=a||s,u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...r==="bearer"&&{Authorization:`Bearer ${this.apiKey}`},...a!==null&&{"Content-Encoding":"gzip"}},body:c};try{return await this.fetchWithRetry(o,u,{type:"successful-write"},{retryCheck:l=>Cr(l)||l instanceof Ie&&l.retryAfterMs!==void 0?!1:Ji(l)}),{kind:"ok"}}catch(l){if(Cr(l))return{kind:"too-large"};if(Ji(l)){let d=l instanceof Ie?l.retryAfterMs:void 0;return{kind:"retry-later",error:l,...d!==void 0&&{retryAfterMs:d}}}return{kind:"fatal",error:l}}}async _sendLogsBatch(e){return this._sendOtlpBatch({path:"logs",auth:"query-token",payload:e})}async _sendMetricsBatch(e){return this._sendOtlpBatch({path:"metrics",auth:"query-token",payload:e})}async _sendTracesBatch(e){return this._sendOtlpBatch({path:"traces",auth:"bearer",payload:e})}async fetchWithRetry(e,r,n,s,i){let o=r.body?r.body:"",a=Wm(o),c={...this._retryOptions,...s},u=0;return await _m(async()=>{u++;let l=new AbortController,d=i??this.requestTimeout,p=Date.now()+d,g,m=new Promise((w,T)=>{g=le(()=>{let y=kr("AbortError",`Request timed out after ${d}ms`);T(y),l.abort(y)},d)}),h,_=!1,S,b=()=>S??=(async()=>{try{await h?.body?.cancel()}catch{}})();try{let w;try{w=this.fetch(e,{signal:l.signal,...r})}catch(P){throw new gt(P)}w.then(P=>{l.signal.aborted&&!_&&Promise.resolve(P.body?.cancel()).catch(()=>{})}).catch(()=>{});try{h=await Promise.race([w,m]),_=!0}catch(P){throw new gt(P)}let T=r.mode==="no-cors",y=n.type==="successful-write"?300:400;if(!T&&(h.status<200||h.status>=y))throw new Ie(h,a,p,l);if(n.type==="successful-write"){try{await Promise.race([b(),m])}catch{}return}try{return await Promise.race([n.consume(h),m])}catch(P){throw l.signal.aborted?new gt(P):P}}finally{clearTimeout(g),l.signal.aborted&&h&&b()}},{...c,retryCheck:l=>{let d=c.retryCheck(l);return d&&u<=c.retryCount&&l instanceof Ie&&l.cancelResponseBody(),d}})}async _shutdown(e=3e4){await this._initPromise;let r=!1;return this.clearFlushTimer(),this.disabled?void 0:Mt((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(o=>this.getRouteQueue(o).length>0);){let i=this._dequeuedMessagesCount;if(await this.flush(),r)break;if(this._dequeuedMessagesCount===i){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(s){if(!iv(s))throw s;await $m(s)}})(),e,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:e}),r=!0})}async shutdown(e=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}};var dv=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi;var FF=new RegExp(dv.source,"i"),Xm=/[a-z][a-z0-9+.-]{0,63}:\/\//i,LF=new RegExp(`^${Xm.source}`,"i"),UF=new RegExp(Xm.source,"gi");var fv=["is_not","is_set"],pv=1152921504606847e3,M=class t extends Error{constructor(e){super(e),this.name=this.constructor.name,Object.setPrototypeOf(this,t.prototype)}};function Ru(t){if(typeof t=="boolean")return!0;if(typeof t=="string"){let e=t.toLowerCase();return e==="true"||e==="false"}if(!Array.isArray(t))return!1;for(let e=0;e<t.length;e++)if(!Ru(e in t?t[e]:null))return!1;return!0}function Au(t){if(typeof t=="boolean")return t;if(typeof t=="string")return t.toLowerCase()==="true";if(!Array.isArray(t))return!1;for(let e=0;e<t.length;e++)if(!Au(e in t?t[e]:null))return!1;return!0}function Nn(t){for(let e=0;e<t.length;e++){let r=t.charCodeAt(e);if(r>=55296&&r<=56319){let n=t.charCodeAt(e+1);if(e+1>=t.length||n<56320||n>57343)throw new M("Cannot stringify an unpaired surrogate like the flags service");e++}else if(r>=56320&&r<=57343)throw new M("Cannot stringify an unpaired surrogate like the flags service")}}function Zi(t,e=new Set){if(!(t===null||typeof t=="boolean")){if(typeof t=="string")return void Nn(t);if(typeof t=="number"){if(!Number.isFinite(t))throw new M(`Cannot represent non-finite number ${t} like the flags service`);return}if(Array.isArray(t)){if(e.has(t))throw new M("Cannot represent a circular array during local evaluation");e.add(t);try{for(let r=0;r<t.length;r++)r in t&&Zi(t[r],e)}finally{e.delete(t)}return}if(typeof t=="object"){let r=Object.getPrototypeOf(t);if(r!==Object.prototype&&r!==null)throw new M("Cannot represent a non-JSON object like the flags service");if(e.has(t))throw new M("Cannot represent a circular object during local evaluation");e.add(t);try{for(let n of Object.keys(t))Nn(n),Zi(t[n],e)}finally{e.delete(t)}return}throw new M(`Cannot represent ${typeof t} like the flags service`)}}function gv(t,e){let r=0,n=0;for(;r<t.length&&n<e.length;){let s=t.charCodeAt(r),i=e.charCodeAt(n),o=s>=55296&&s<=56319,a=i>=55296&&i<=56319,c=o?t.charCodeAt(r+1):0,u=a?e.charCodeAt(n+1):0,l=o?(s-55296)*1024+c-56320+65536:s,d=a?(i-55296)*1024+u-56320+65536:i;if(l!==d)return l-d;r+=o?2:1,n+=a?2:1}return t.length-e.length}function Mu(t,e=new Set){if(t===null)return"null";if(typeof t=="string")return Nn(t),JSON.stringify(t);if(typeof t=="boolean")return t?"true":"false";if(typeof t=="number"){if(!Number.isFinite(t))throw new M(`Cannot stringify non-finite number ${t} like the flags service`);if(Number.isInteger(t))throw new M(`Cannot distinguish integer ${t} from an integral JSON float during local evaluation`);return String(t)}if(Array.isArray(t)){if(e.has(t))throw new M("Cannot stringify a circular array during local evaluation");e.add(t);try{let r=[];for(let n=0;n<t.length;n++)r.push(n in t?Mu(t[n],e):"null");return`[${r.join(",")}]`}finally{e.delete(t)}}if(typeof t=="object"){let r=Object.getPrototypeOf(t);if(r!==Object.prototype&&r!==null)throw new M("Cannot stringify a non-JSON object like the flags service");if(e.has(t))throw new M("Cannot stringify a circular object during local evaluation");e.add(t);try{let n=Object.keys(t);return n.forEach(Nn),`{${n.sort(gv).map(s=>`${JSON.stringify(s)}:${Mu(t[s],e)}`).join(",")}}`}finally{e.delete(t)}}throw new M(`Cannot stringify ${typeof t} like the flags service`)}function Qi(t){return typeof t=="string"?(Nn(t),t):Mu(t)}function Km(t){try{return new RegExp(t),!0}catch{return!1}}function ve(t){return String(t).replace(/[A-Z]/g,e=>e.toLowerCase())}function zm(t,e,r){if(!/^\d+$/.test(t)||r==="strict"&&t.length>1&&t[0]==="0")throw new M(`Invalid semver: ${e}`);return parseInt(t,10)}function Y(t,e="strict"){let n=String(t).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!n||n.startsWith("."))throw new M(`Invalid semver: ${t}`);let s=n.split("."),i=o=>o===void 0||o===""?0:zm(o,t,e);return[i(s[0]),i(s[1]),i(s[2])]}function Re(t,e){for(let r=0;r<3;r++){if(t[r]<e[r])return-1;if(t[r]>e[r])return 1}return 0}function mv(t,e){let r=Y(t,e);return{lower:[r[0],r[1],r[2]],upper:[r[0],r[1]+1,0]}}function hv(t,e){let[r,n,s]=Y(t,e),i=[r,n,s],o;return o=r>0?[r+1,0,0]:n>0?[0,n+1,0]:[0,0,s+1],{lower:i,upper:o}}function _v(t,e){let n=String(t).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!n)throw new M(`Invalid wildcard semver: ${t}`);let s=n.split("."),i=c=>{if(e==="legacy-permissive"){let u=parseInt(c,10);if(!isNaN(u))return u}else try{return zm(c,t,e)}catch{}throw new M(`Invalid wildcard semver: ${t}`)},o=i(s[0]);if(s.length===1)return{lower:[o,0,0],upper:[o+1,0,0]};let a=i(s[1]);return{lower:[o,a,0],upper:[o,a+1,0]}}function Gm(t){if(t instanceof Date)return t;if(typeof t=="string"||typeof t=="number"){let e=new Date(t);if(!isNaN(e.valueOf()))return e;throw new M(`${t} is in an invalid date format`)}throw new M(`The date provided ${t} must be a string, number, or date object`)}function Pu(t){let e=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=t.match(e),n=new Date(new Date().toISOString());if(!r||!r.groups)return null;let s=parseInt(r.groups.number);if(s>=1e4)return null;let i=r.groups.interval;if(i==="h")n.setUTCHours(n.getUTCHours()-s);else if(i==="d")n.setUTCDate(n.getUTCDate()-s);else if(i==="w")n.setUTCDate(n.getUTCDate()-7*s);else if(i==="m")n.setUTCMonth(n.getUTCMonth()-s);else{if(i!=="y")return null;n.setUTCFullYear(n.getUTCFullYear()-s)}return n}function Ou(t,e,r={}){let n=t.key,s=t.value,i=t.operator||"exact",o=r.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(e,n)){if(i==="is_not_set")return!1;if(i==="is_set")return!0}else throw new M(`Property ${n} not found in propertyValues`);let c=e[n];if(c===void 0)return r.warnFunction?.(`Property ${n} cannot have a value of undefined with the ${i} operator`),i==="is_not";if(c===null&&!fv.includes(i)&&i!=="exact"&&i!=="is_not")return r.warnFunction?.(`Property ${n} cannot have a value of null with the ${i} operator`),!1;let u=(d,p)=>{if(r.propertyMatchingVersion!==2&&Ru(d)||Array.isArray(d)&&d.length===0)return Zi(p),Au(d)===Au(p);if(r.propertyMatchingVersion===2&&typeof p=="number"&&Ru(d))return Zi(p),!1;if(Array.isArray(d)){let g=Qi(p).toLowerCase();return d.some(m=>Qi(m).toLowerCase()===g)}return Qi(d).toLowerCase()===Qi(p).toLowerCase()},l=(d,p,g)=>{if(g==="gt")return d>p;if(g==="gte")return d>=p;if(g==="lt")return d<p;if(g==="lte")return d<=p;throw new Error(`Invalid operator: ${g}`)};switch(i){case"exact":return u(s,c);case"is_not":return!u(s,c);case"is_set":return!0;case"icontains":return ve(c).includes(ve(s));case"not_icontains":return!ve(c).includes(ve(s));case"starts_with":return ve(c).startsWith(ve(s));case"not_starts_with":return!ve(c).startsWith(ve(s));case"ends_with":return ve(c).endsWith(ve(s));case"not_ends_with":return!ve(c).endsWith(ve(s));case"regex":return Km(String(s))&&String(c).match(String(s))!==null;case"not_regex":return Km(String(s))&&String(c).match(String(s))===null;case"gt":case"gte":case"lt":case"lte":{let d=typeof s=="number"?s:parseFloat(String(s)),p=typeof c=="number"?c:c!=null?parseFloat(String(c)):NaN;return Number.isFinite(d)&&Number.isFinite(p)?l(p,d,i):l(String(c),String(s),i)}case"is_date_after":case"is_date_before":{if(typeof s=="boolean")throw new M("Date operations cannot be performed on boolean values");let d=Pu(String(s));d==null&&(d=Gm(s));let p=Gm(c);return i==="is_date_before"?p<d:p>d}case"semver_eq":return Re(Y(String(c),o),Y(String(s),o))===0;case"semver_neq":return Re(Y(String(c),o),Y(String(s),o))!==0;case"semver_gt":return Re(Y(String(c),o),Y(String(s),o))>0;case"semver_gte":return Re(Y(String(c),o),Y(String(s),o))>=0;case"semver_lt":return Re(Y(String(c),o),Y(String(s),o))<0;case"semver_lte":return Re(Y(String(c),o),Y(String(s),o))<=0;case"semver_tilde":{let d=Y(String(c),o),{lower:p,upper:g}=mv(String(s),o);return Re(d,p)>=0&&Re(d,g)<0}case"semver_caret":{let d=Y(String(c),o),{lower:p,upper:g}=hv(String(s),o);return Re(d,p)>=0&&Re(d,g)<0}case"semver_wildcard":{let d=Y(String(c),o),{lower:p,upper:g}=_v(String(s),o);return Re(d,p)>=0&&Re(d,g)<0}default:throw new M(`Unknown operator: ${i}`)}}async function Vm(t){let e=globalThis.crypto?.subtle;if(!e)throw new Error("SubtleCrypto API not available");let r=await e.digest("SHA-1",new TextEncoder().encode(t));return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}async function Cn(t,e,r="",n="."){let s=await Vm(`${t}${n}${e}${r}`);return parseInt(s.slice(0,15),16)/pv}async function ku(t,e){if(t==null||t.id==null||t.exclusion_percentage==null)return;let r=Number(t.exclusion_percentage);if(!Number.isFinite(r))return;let n=Math.min(Math.max(r,0),100);if(!(n!==100&&await Cn("holdout",e,"","-")>n/100))return`holdout-${t.id}`}function eo(t){let e=[],r=0;for(let n of t){let s=r+n.rollout_percentage/100;e.push({valueMin:r,valueMax:s,key:n.key}),r=s}return e}async function xu(t,e,r){let n=await Cn(t,e,"variant");return eo(r).find(s=>n>=s.valueMin&&n<s.valueMax)?.key}function Nu(t,e){if(e===!1||e==null||!t)return null;let r=typeof e=="boolean"?e.toString():e,n=t[r]||null;return n==null?null:Nr(n)}var Ym=9223372036854776e3,Ev="9223372036854775808",Sv=Object.prototype.propertyIsEnumerable;function yv(){return{ancestors:new WeakSet,remainingNodes:1e4}}function Ye(t,e){try{return qm(t,e,yv(),0)}catch{return[]}}function bv(t,e){let r=t.toString(),n=BigInt(Ev);return t>=n||t<-n?(e?.debug(`Attribute ${r} is outside the int64 range; encoding it as a string`),{stringValue:r}):{intValue:r}}function Fu(t,e,r,n){if(r.remainingNodes<=0)return{stringValue:Ki};if(r.remainingNodes--,Gg(t))return{boolValue:t};if(typeof t=="bigint")return bv(t,e);if(typeof t=="number"){if(!Number.isFinite(t))return{stringValue:String(t)};if(Number.isInteger(t)){if(Number.isSafeInteger(t))return{intValue:String(t)};if("u"<typeof BigInt)return{stringValue:String(t)};let s=BigInt(t).toString();return t>=Ym||t<-Ym?(e?.debug(`Attribute ${s} is outside the int64 range; encoding it as a string`),{stringValue:s}):{intValue:s}}return{doubleValue:t}}if(typeof t=="string")return{stringValue:ze(t)};if(typeof t=="function")return{stringValue:gm};if(typeof t=="symbol")return{stringValue:String(t)};if(typeof t=="object"&&t!==null){if(r.ancestors.has(t))return{stringValue:Xi};if(n>=20)return{stringValue:Ki};if(t instanceof Date){let s=t.getTime(),i=Number.isFinite(s)?t.toISOString():String(t);return{stringValue:typeof i=="string"?ze(i):String(i)}}r.ancestors.add(t);try{try{let s=t.toJSON;if(typeof s=="function")return Fu(s.call(t),e,r,n+1)}catch{}return he(t)?{arrayValue:{values:wv(t,e,r,n+1)}}:{kvlistValue:{values:qm(t,e,r,n+1)}}}finally{r.ancestors.delete(t)}}return{stringValue:ze(String(t))}}function wv(t,e,r,n){let s=[],i=Math.min(t.length,1e3),o=0;for(;o<i&&r.remainingNodes>0;o++)try{let a=o in t?t[o]:void 0;if(Le(a))continue;s.push(Fu(a,e,r,n))}catch{s.push({stringValue:Te})}return t.length>o&&s.push({stringValue:Ki}),s}function qm(t,e,r,n){let s=[];for(let i in t)if(Sv.call(t,i)){if(!i){e?.debug("Dropping an attribute with an empty key");continue}if(s.length>=1e3||r.remainingNodes<=0){e?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let o=t[i];if(eu(o)||ft(o))continue;s.push({key:ze(i),value:Fu(o,e,r,n)})}catch{s.push({key:ze(i),value:{stringValue:Te}})}}return s}function Fn(t,e,r){return{...pt({},t.resourceAttributes),"service.name":t.serviceName||"unknown_service",...t.environment&&{"deployment.environment":t.environment},...t.serviceVersion&&{"service.version":t.serviceVersion},"telemetry.sdk.name":e,"telemetry.sdk.version":r}}var Tv=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function Ln(t,e){let r=pt({},t),n={};for(let s of Tv)Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s],delete r[s]);return[...Ye(r,e),...Ye(n,e)]}var Jm={darwin:"macOS",win32:"Windows",cygwin:"Windows",linux:"Linux",android:"Android",freebsd:"FreeBSD",openbsd:"OpenBSD",netbsd:"NetBSD",sunos:"SunOS",aix:"AIX",haiku:"Haiku","Mac OS X":"macOS"};function Iv(t){if(t)return Object.prototype.hasOwnProperty.call(Jm,t)?Jm[t]:t}function Lu(t,e){let r=Iv(t);return{...r?{"os.name":r}:{},...e?{"os.version":e}:{}}}var vv={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},eL=vv.info;var Yt=class{constructor(e){this._onFire=e,this._firesAt=0}get pending(){return!!this._timer}arm(e){this.clear(),this._firesAt=Date.now()+e,this._timer=le(()=>{this._timer=void 0,this._onFire()},e)}armNoEarlierThan(e){this._timer&&Date.now()+e<=this._firesAt||this.arm(e)}clear(){this._timer&&(clearTimeout(this._timer),this._timer=void 0)}};function Un(){return 1-.25+Math.random()*.25*2}var Ae=1;function $n(t,e,r,n){let s=Math.min(Math.max(0,e-1),6),i=t*2**s,o=n===void 0?i:Math.min(i,Math.max(n,t));return Math.round(o*r)}var Uu="0000000000000000",Pv=Uu+Uu,Ov=/^[0-9a-f]+$/;function kv(t){let e=new Uint8Array(t),r=globalThis.crypto;if(r&&typeof r.getRandomValues=="function")try{return r.getRandomValues(e),e}catch{}for(let n=0;n<t;n++)e[n]=Math.floor(256*Math.random());return e}function xv(t){let e="";for(let r=0;r<t.length;r++)e+=t[r].toString(16).padStart(2,"0");return e}function Qm(t){let e=xv(kv(t));return/[^0]/.test(e)?e:e.slice(0,-1)+"1"}function Zm(){return Qm(16)}function eh(){return Qm(8)}function th(t,e,r){return typeof t=="string"&&t.length===e&&t!==r&&Ov.test(t)}function rh(t){return th(t,32,Pv)}function nh(t){return th(t,16,Uu)}var Nv=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function ro(t){let e=sh(t);return e&&{traceId:e.traceId,spanId:e.spanId,flags:Cv(e.flags)}}function Cv(t){return 1&parseInt(t,16)?Dr:Dv}function sh(t){if(typeof t!="string")return;let e=Nv.exec(t.trim());if(!e)return;let[,r,n,s,i,o]=e;if(r!=="ff"&&!(r==="00"&&o)&&!(!rh(n)||!nh(s)))return{version:r,traceId:n,spanId:s,flags:i}}function ih(t){return sh(t)&&t.trim()}function no(t){return Array.isArray(t)&&t.length===1?t[0]:t}var Dr="01",Dv="00";function oh(t,e,r=Dr){return`00-${t}-${e}-${r}`}var Fv=32,$u=512;function so(t){if(typeof t!="string")return;let e=t.trim();if(!e||/[^\x20-\x7e\t]/.test(e))return;let r=e.split(",");if(!(r.length>Fv)){for(let n of r)if(n.trim()&&!n.includes("="))return;return e.length<=$u?e:Uv(r)}}var Lv=128;function Uv(t){let e=[...t],r=()=>e.reduce((n,s)=>n+s.length,0)+e.length-1;for(let n=e.length-1;n>=0&&r()>$u;n--)e[n].length>Lv&&e.splice(n,1);for(;e.length&&r()>$u;)e.pop();return e.length?e.join(","):void 0}var Bn=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function io(t){return String(t)+"000000"}function Bu(t,e,r,n){let s="";return n&&(s=Object.keys(n).sort().map(o=>`${JSON.stringify(o)}:${JSON.stringify(n[o])}`).join(",")),`${t}\0${e}\0${r??""}\0${s}`}function ah(t,e){for(let r=0;r<e.length;r++)if(t<=e[r])return r;return e.length}function Wu(t,e,r){return Fn(t,e,r)}function Hu(t,e,r,n){return{resourceMetrics:[{resource:{attributes:Ln(e)},scopeMetrics:[{scope:{name:r,version:n},metrics:t}]}]}}function oo(t){let e=t?.resourceAttributes;return{serviceName:e?.["service.name"]??t?.serviceName,serviceVersion:e?.["service.version"]??t?.serviceVersion,environment:e?.["deployment.environment"]??t?.environment,resourceAttributes:e,beforeSend:t?.beforeSend,flushIntervalMs:t?.flushIntervalMs??1e4,maxSeriesPerFlush:t?.maxSeriesPerFlush??1e3}}var ch=1,Wn=class{constructor(e,r,n){this._instance=e,this._config=r,this._logger=n,this._series=new Map,this._flushTimer=new Yt(()=>this.flush().catch(s=>{this._logger.error("Metrics flush failed:",s)})),this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._retryAfter=new zt,this._consecutiveFlushFailures=0,this._flushJitter=Ae,this._generation=0}count(e,r=1,n){this._capture({name:e,type:"count",value:r,unit:n?.unit,attributes:n?.attributes})}gauge(e,r,n){this._capture({name:e,type:"gauge",value:r,unit:n?.unit,attributes:n?.attributes})}histogram(e,r,n){this._capture({name:e,type:"histogram",value:r,unit:n?.unit,attributes:n?.attributes})}flush(){let e=this._flushPromise,n=(async()=>{e&&await e.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===n&&(this._flushPromise=null)});return this._flushPromise=n,n}drainWindow(){if(this._series.size===0)return null;let e=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(e)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=Ae,this._flushTimer.clear(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(e){if(this._instance.isDisabled||this._instance.optedOut)return;let r=this._runBeforeSend(e);if(r===null)return;if(!r.name||typeof r.name!="string")return void this._logger.warn("Dropping metric with empty name");if(typeof r.value!="number"||!Number.isFinite(r.value))return void this._logger.warn(`Dropping metric '${r.name}': value must be a finite number`);if(r.type==="count"&&r.value<0)return void this._logger.warn(`Dropping count '${r.name}': counters are monotonic, value must be >= 0`);let n,s;try{n=r.attributes?{...r.attributes}:void 0,s=Bu(r.type,r.name,r.unit,n)}catch(c){this._logger.warn(`Dropping metric '${r.name}': attributes could not be serialized`,c);return}let i=this._series.get(s);if(!i){if(!this._admitNewSeries())return;i={name:r.name,type:r.type,unit:r.unit,attributes:n,windowStartMs:Date.now()},this._series.set(s,i)}let o=this._typeByName.get(r.name);o===void 0?this._typeByName.set(r.name,r.type):o!==r.type&&!this._typeCollisionWarned.has(r.name)&&(this._typeCollisionWarned.add(r.name),this._logger.warn(`Metric name '${r.name}' is already used as a ${o}; recording it as a ${r.type} too will blend both series in charts. Use a distinct name.`)),this._fold(i,r.value);let a=this._activeTraceContext();a&&(i.exemplar={...a,value:r.value,timeMs:Date.now()}),this._armFlushTimer()}_activeTraceContext(){try{let e=ro(this._instance.getActiveSpan?.()?.traceparent());if(e&&e.flags===Dr)return{traceId:e.traceId,spanId:e.spanId}}catch{}}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush?!0:(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_fold(e,r){switch(e.type){case"count":e.total=(e.total??0)+r;break;case"gauge":e.last=r;break;case"histogram":{e.hist||(e.hist={count:0,sum:0,min:r,max:r,bucketCounts:new Array(Bn.length+1).fill(0)});let n=e.hist;n.count+=1,n.sum+=r,n.min=Math.min(n.min,r),n.max=Math.max(n.max,r),n.bucketCounts[ah(r,Bn)]+=1;break}}}_runBeforeSend(e){let r=this._config.beforeSend;if(!r)return e;let n=he(r)?r:[r],s=e;for(let i of n)try{let o=i(s);if(!o)return this._logger.info("Metric was rejected in beforeSend function"),null;s=o}catch(o){return this._logger.error("Error in beforeSend function for metric:",o),null}return s}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max($n(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),this._series.size===0)return;let e=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let r=this._generation,n=await this._instance._sendMetricsBatch(this._buildPayload(e));if(r===this._generation)switch(this._retryAfter.record(n),n.kind==="retry-later"?(this._consecutiveFlushFailures++,this._flushJitter=Un()):(this._consecutiveFlushFailures=0,this._flushJitter=Ae),this._flushTimer.pending&&this._flushTimer.arm(this._nextFlushDelay()),n.kind){case"ok":return;case"retry-later":this._mergeWindowBack(e),this._flushTimer.armNoEarlierThan(this._nextFlushDelay());return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",n.error);return}}_buildPayload(e){return Hu(this._buildMetrics(e),Wu(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(e){let r=io(Date.now()),n=new Map;for(let s of e.values()){let i=Bu(s.type,s.name,s.unit,void 0),o=n.get(i);o||(o={name:s.name,...s.unit&&{unit:s.unit}},s.type==="count"?o.sum={aggregationTemporality:ch,isMonotonic:!0,dataPoints:[]}:s.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:ch,dataPoints:[]},n.set(i,o));let a=Ye(s.attributes??{},this._logger),c=io(s.windowStartMs),u=$v(s.exemplar);if(s.type==="count"){let l={attributes:a,startTimeUnixNano:c,timeUnixNano:r,asDouble:s.total??0,...u};o.sum.dataPoints.push(l)}else if(s.type==="gauge"){let l={attributes:a,timeUnixNano:r,asDouble:s.last??0,...u};o.gauge.dataPoints.push(l)}else if(s.hist){let l={attributes:a,startTimeUnixNano:c,timeUnixNano:r,count:s.hist.count,sum:s.hist.sum,min:s.hist.min,max:s.hist.max,bucketCounts:s.hist.bucketCounts,explicitBounds:Bn,...u};o.histogram.dataPoints.push(l)}}return Array.from(n.values())}_mergeWindowBack(e){for(let[r,n]of e){let s=this._series.get(r);if(!s){this._admitNewSeries()&&this._series.set(r,n);continue}switch(s.windowStartMs=Math.min(s.windowStartMs,n.windowStartMs),s.exemplar=s.exemplar??n.exemplar,s.type){case"count":s.total=(s.total??0)+(n.total??0);break;case"gauge":break;case"histogram":if(n.hist)if(s.hist){s.hist.count+=n.hist.count,s.hist.sum+=n.hist.sum,s.hist.min=Math.min(s.hist.min,n.hist.min),s.hist.max=Math.max(s.hist.max,n.hist.max);for(let i=0;i<s.hist.bucketCounts.length;i++)s.hist.bucketCounts[i]+=n.hist.bucketCounts[i]}else s.hist=n.hist;break}}}};function $v(t){return t?{exemplars:[{filteredAttributes:[],timeUnixNano:io(t.timeMs),asDouble:t.value,traceId:t.traceId,spanId:t.spanId}]}:{}}var uh="unknown";function qt(t,e,r,n){return typeof t=="string"&&t.trim()?t.length>r?t.slice(0,r):t:(n?.debug(`${e} must be a non-empty string; using "${uh}"`),uh)}function Fr(t){if(t==null)return;let e=t;if(t instanceof Date)try{e=t.getTime()}catch{return}if(!(typeof e!="number"||!Number.isFinite(e))&&!(e<0||e>9223372036854))return e}function lh(t,e,r){let n=Fr(t);return n===void 0?(t!==void 0&&r?.debug("Span startTime is out of range or not a valid time; using the current time"),e):(e-n>864e5?r?.debug("Span startTime is more than 24 hours in the past; the server will clamp it to receive time and keep the original in $originalTimestamp"):n>e&&r?.debug("Span startTime is in the future; the span may export with a zero duration"),n)}function ao(t,e){return t<e?e:t}function Hn(t,e,r,n){let s=Fr(t);return s===void 0?(t!==void 0&&n?.debug(`Span ${r} is out of range or not a valid time; using the derived time`),e):s}function uo(){let t=globalThis.performance;return typeof t?.now=="function"?t.now():void 0}var Lr=class{constructor(e,r,n){this._onEnd=r,this._logger=n,this._events=[],this._ended=!1,this._userAttributeCount=0,this._userEventCount=0,this._droppedAttributes=0,this._droppedEvents=0,this._traceId=e.traceId,this._spanId=e.spanId,this._parentSpanId=e.parentSpanId,this._traceState=e.traceState,this._traceFlags=e.traceFlags??Dr,this._parentIsRemote=e.parentIsRemote??!1,this._name=e.name,this._kind=e.kind,this._autoKeys=new Set(e.autoAttributeKeys),this._maxAttributes=e.maxAttributes,this._maxEvents=e.maxEvents,this._maxAttributesPerEvent=e.maxAttributesPerEvent,this._maxAttributeValueLength=e.maxAttributeValueLength,this._attributes=Object.create(null);for(let s of Object.keys(e.attributes))this._writeAttribute(s,e.attributes[s]);this._startMono=e.backdated?void 0:uo(),this._startTime=e.clockAnchor&&this._startMono!==void 0?e.clockAnchor.wall+(this._startMono-e.clockAnchor.mono):e.startTime,this._startMono!==void 0&&(this._clockAnchor=e.clockAnchor??{wall:this._startTime,mono:this._startMono})}_now(){if(this._startMono!==void 0){let e=uo();if(e!==void 0)return this._startTime+Math.max(0,e-this._startMono)}return Date.now()}_mutable(e){return this._ended?(this._logger?.debug(`Ignoring ${e} on a span that has already ended`),!1):!0}_writeAttribute(e,r){if(Le(r)){e in this._attributes&&!this._autoKeys.has(e)&&this._userAttributeCount--,delete this._attributes[e];return}if(!this._autoKeys.has(e)&&!(e in this._attributes)){if(this._userAttributeCount>=this._maxAttributes)return void this._droppedAttributes++;this._userAttributeCount++}this._attributes[e]=fo(r,this._maxAttributeValueLength)}setAttribute(e,r){return this._mutable("setAttribute")&&this._writeAttribute(e,r),this}setAttributes(e){if(this._mutable("setAttributes")){let r=pt({},e);for(let n of Object.keys(r))this._writeAttribute(n,r[n])}return this}addEvent(e,r,n){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let s=r&&gh(r,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:qt(e,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:Hn(n,this._now(),"event timestamp",this._logger),...s&&{attributes:s.attributes,...s.dropped&&{droppedAttributesCount:s.dropped}}})}return this}setStatus(e,r){if(this._mutable("setStatus")){if(e!=="ok"&&e!=="error")return this._logger?.debug(`Ignoring unknown span status "${String(e)}"; expected "ok" or "error"`),this;this._status={code:e,...r&&{message:ju(r,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(e){if(!this._mutable("recordException"))return this;let{type:r,message:n,stack:s}=Xu(e);return this.addEvent(Bv,{"exception.type":r,"exception.message":n,...s&&{"exception.stacktrace":s}}),this.setStatus("error",n)}updateName(e){return this._mutable("updateName")&&(this._name=qt(e,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return oh(this._traceId,this._spanId,this._traceFlags)}tracestate(){return this._traceState??null}childContext(){return{traceId:this._traceId,parentSpanId:this._spanId,traceState:this._traceState,traceFlags:this._traceFlags,clockAnchor:this._clockAnchor}}end(e){if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let r=this._now(),n=Hn(e,r,"end time",this._logger);this._onEnd({traceId:this._traceId,spanId:this._spanId,...this._parentSpanId&&{parentSpanId:this._parentSpanId},...this._traceState&&{traceState:this._traceState},traceFlags:this._traceFlags,parentIsRemote:this._parentIsRemote,name:this._name,kind:this._kind,...this._status&&{status:this._status},attributes:{...this._attributes},events:this._events,startTime:this._startTime,endTime:ao(n,this._startTime),...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}},Bv="exception",Wv=4294967295;function Hv(t){try{return typeof t=="string"?t:String(t)}catch{return Te}}function Jt(t){return typeof t!="number"||!Number.isFinite(t)||t<=0?0:Math.min(Math.floor(t),Wv)}function jv(t,e){if(!e.length)return Object.keys(t);let r=e.filter(s=>Object.prototype.propertyIsEnumerable.call(t,s)),n=new Set(r);return[...r,...Object.keys(t).filter(s=>!n.has(s))]}function fh(t,e,r,n,s,i,o=[]){let a=0,c=0,u={};for(let g of jv(t.attributes,o)){let m=t.attributes[g];if(!Le(m)){if(!e.has(g)){if(a>=r){c++;continue}a++}Object.defineProperty(u,g,{value:fo(m,i),enumerable:!0,writable:!0,configurable:!0})}}t.attributes=u,c&&(t.droppedAttributesCount=Jt(t.droppedAttributesCount)+c);let l=0,d=0,p=[];for(let g of t.events){if(l>=n){d++;continue}if(l++,g.attributes){let m=gh(g.attributes,s,i);g.attributes=m.attributes,m.dropped&&(g.droppedAttributesCount=Jt(g.droppedAttributesCount)+m.dropped)}p.push(g)}t.events=p,d&&(t.droppedEventsCount=Jt(t.droppedEventsCount)+d),t.status?.message&&(t.status={...t.status,message:ju(Hv(t.status.message),i)})}var lo=class{setAttribute(){return this}setAttributes(){return this}addEvent(){return this}setStatus(){return this}recordException(){return this}updateName(){return this}traceparent(){return null}tracestate(){return null}end(){}},ph=new lo,jn=class extends lo{constructor(e,r){super(),this._traceparent=e,this._tracestate=r}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}};function Xv(t){try{let e=t.stack;return typeof e=="string"&&e?{stack:e}:{}}catch{return{}}}function Pt(t,e){let r=no(t?.parent)??e,n=typeof r=="string"||r==null?r:dh(r,"traceparent"),s=ih(n);if(!s)return ph;let i=typeof r=="string"||r==null?t?.tracestate:dh(r,"tracestate");return new jn(s,so(i))}function dh(t,e){try{let r=t[e];return typeof r=="function"?r.call(t):void 0}catch{return}}function ju(t,e){return t.length>e?t.slice(0,e):t}function fo(t,e){return co(t,e,{ancestors:new WeakSet,remainingNodes:1e4},0)}function co(t,e,r,n){if(t===null||typeof t!="object")return Le(t)||r.remainingNodes<=0?t:(r.remainingNodes--,typeof t=="string"?ju(t,e):t);if(r.ancestors.has(t))return Xi;if(r.remainingNodes<=0||n>=20)return t;r.remainingNodes--,r.ancestors.add(t);try{if(t instanceof Date)return t;let s=Kv(t);if(s.selfDescribed)return Le(s.value)?String(s.value):co(s.value,e,r,n+1);if(he(t)){let a=Math.min(t.length,1e3),c=[];for(let u=0;u<a;u++)try{c.push(co(t[u],e,r,n+1))}catch{c.push(Te)}return t.length>a&&(c.length=t.length),c}let i={},o=0;for(let a of Object.keys(t)){if(o>=1e3)break;let c;try{c=co(t[a],e,r,n+1)}catch{c=Te}a&&!Le(c)&&o++,Object.defineProperty(i,a,{value:c,enumerable:!0,writable:!0,configurable:!0})}return i}catch{return t}finally{r.ancestors.delete(t)}}function Kv(t){try{let e=t.toJSON;if(typeof e=="function")return{selfDescribed:!0,value:e.call(t)}}catch{}return{selfDescribed:!1}}function gh(t,e,r){let n;try{n=Object.keys(t)}catch{return{attributes:{},dropped:0}}let s={},i=0,o=0;for(let a of n){if(i>=e){o++;continue}let c;try{c=fo(t[a],r)}catch{c=Te}Le(c)||(i++,Object.defineProperty(s,a,{value:c,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:s,dropped:o}}function mh(t,e){for(let r of Object.keys(t))t[r]=fo(t[r],e);return t}function Xn(t,e,r){return e===ph?r(e):t.with(e,()=>r(e))}function Xu(t){try{let e=Xv(t);if(At(t))return{type:t.name||"Error",message:t.message||"",...e};if(typeof t=="string")return{type:"string",message:t};if(t&&typeof t=="object"){let r=t;if(typeof r.message=="string")return{type:typeof r.name=="string"?r.name:"Object",message:r.message,...e}}return{type:typeof t,message:String(t)}}catch{return{type:typeof t,message:""}}}var Ku={internal:1,server:2,client:3,producer:4,consumer:5},Gv={ok:1,error:2},zv=1,Vv=256,Yv=512;function qv(t){let e=parseInt(t.traceFlags,16);return(Number.isFinite(e)?255&e:zv)|Vv|(t.parentIsRemote?Yv:0)}function po(t){if(typeof t=="string")return ze(t);try{return ze(String(t))}catch{return Te}}function Jv(t){return t&&Object.prototype.hasOwnProperty.call(Ku,t)?Ku[t]:Ku.internal}function Gu(t){let e=Math.floor(t),r=Math.round((t-e)*1e6);return r>=1e6&&(e+=1,r=0),String(e)+String(r).padStart(6,"0")}function Qv(t,e){let r={name:po(t.name),timeUnixNano:Gu(t.timestamp)};if(t.attributes){let s=Ye(t.attributes,e);s.length&&(r.attributes=s)}let n=Jt(t.droppedAttributesCount);return n&&(r.droppedAttributesCount=n),r}function hh(t,e){let r={traceId:t.traceId,spanId:t.spanId,name:po(t.name),kind:Jv(t.kind),startTimeUnixNano:Gu(t.startTime),endTimeUnixNano:Gu(t.endTime),flags:qv(t)};t.parentSpanId&&(r.parentSpanId=t.parentSpanId),t.traceState&&(r.traceState=po(t.traceState));let n=Ye(t.attributes,e);n.length&&(r.attributes=n),t.events.length&&(r.events=t.events.map(o=>Qv(o,e)));let s=Jt(t.droppedAttributesCount);s&&(r.droppedAttributesCount=s);let i=Jt(t.droppedEventsCount);return i&&(r.droppedEventsCount=i),t.status&&(r.status={code:Gv[t.status.code],...t.status.message&&{message:po(t.status.message)}}),r}function _h(t,e,r){return Fn(t,e,r)}function Eh(t,e,r,n,s){return{resourceSpans:[{resource:{attributes:Ln(e,s)},scopeSpans:[{scope:{name:r,version:n},spans:t}]}]}}var Sh=8;function go(){return uo()??Date.now()}function zu(t){try{return t instanceof Lr}catch{return!1}}function yh(t,e){let r=ro(t);if(r)return{traceId:r.traceId,parentSpanId:r.spanId,traceState:so(e),traceFlags:r.flags,isRemote:!0}}function Zv(t){try{return typeof t.traceparent=="function"}catch{return!1}}function eR(t){return!!t.attributes&&typeof t.attributes=="object"&&!Array.isArray(t.attributes)&&Array.isArray(t.events)&&t.name!==void 0&&t.kind!==void 0&&t.startTime!==void 0&&t.endTime!==void 0}function mo(t,e,r){t[e]!==r&&(t[e]=r)}function tR(t,e){try{let r=Object.getOwnPropertyDescriptors(t);for(let n of["traceId","spanId","parentSpanId","traceState"])r[n]={value:e[n],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(t),r)}catch{return t}}var Kn=class{constructor(e,r,n,s,i,o){this._instance=e,this._config=r,this._logger=n,this._getContext=s,this._contextManager=i,this._onSpanQueued=o,this._queue=[],this._flushTimer=new Yt(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=Ae,this._retryAfter=new zt,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=r.maxExportBatchSize}startSpan(e,r){if(this._instance.isDisabled||this._instance.optedOut)return Pt(r,this._contextManager.active());let n=no(r?.parent);if(n&&typeof n!="string"&&!zu(n)){if(Zv(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),Pt(r,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let s=this._resolveParent(n,r);if(this._liveSpans.size>=this._config.maxLiveSpans&&this._evictAgedSpans(),this._liveSpans.size>=this._config.maxLiveSpans)return this._recordDrop(1,`the live-span limit (${this._config.maxLiveSpans}) was reached \u2014 spans are being started and never ended`),Pt(r,this._contextManager.active());let i=Date.now(),o=lh(r?.startTime,i,this._logger),a=eh();this._liveSpans.set(a,go());let c=this._autoContextAttributes();return new Lr({traceId:s?.traceId??Zm(),spanId:a,parentSpanId:s?.parentSpanId,traceState:s?.traceState,traceFlags:s?.traceFlags,parentIsRemote:s?.isRemote,name:qt(e,"Span name",this._config.maxAttributeValueLength,this._logger),kind:r?.kind??"internal",attributes:pt({...c},r?.attributes),autoAttributeKeys:Object.keys(c),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:o,backdated:o!==i,clockAnchor:Fr(r?.startTime)===void 0?s?.clockAnchor:void 0},(u,l)=>this._onSpanEnd(u,l),this._logger)}withSpan(e,r,n){let s=typeof r=="function"?void 0:r,i=typeof r=="function"?r:n,o=this.startSpan(e,s);try{let a=Xn(this._contextManager,o,i);return Em(a)?a.then(c=>(o.end(),c),c=>{throw this._recordCallbackError(o,c),o.end(),c}):(o.end(),a)}catch(a){throw this._recordCallbackError(o,a),o.end(),a}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;)if(!this._queue.length||!await(this._flushPromise??this._startFlush()))return}_startFlush(){this._flushTimer.clear();let e=this._generation,r=Promise.resolve().then(()=>e===this._generation?this._flushInner():0).finally(()=>{this._flushPromise===r&&(this._flushPromise=null),this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=r,r}reset(){this._flushTimer.clear(),this._queue.length&&this._logger.critical(`Discarding ${this._queue.length} span(s) that were still queued when tracing was shut down. Raise the shutdown timeout or flush earlier if they matter.`),this._queue=[],this._liveSpans.clear(),this._flushPromise=null,this._generation++,this._maxExportBatchSize=this._config.maxExportBatchSize,this._droppedSinceWarning=0,this._dropReasons.clear(),this._lastDropWarningAt=0,this._consecutiveFlushFailures=0,this._flushJitter=Ae,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(e,r){if(typeof e=="string"){let s=yh(e,r?.tracestate);return s||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),s}if(zu(e))return e.childContext();let n=this._contextManager.active();if(zu(n))return n.childContext();if(n instanceof jn)return yh(n.traceparent(),n.tracestate()??void 0)}_autoContextAttributes(){let e;try{e=this._getContext()}catch(n){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",n),{}}let r={};return e.distinctId&&(r.posthogDistinctId=e.distinctId),e.sessionId&&(r.sessionId=e.sessionId),e.currentUrl&&(r["url.full"]=e.currentUrl),e.screenName&&(r["screen.name"]=e.screenName),e.appState&&(r["app.state"]=e.appState),r}_recordCallbackError(e,r){if(!(e instanceof Lr))return;let{type:n,message:s,stack:i}=Xu(r);e.addEvent("exception",{"exception.type":n,"exception.message":s,...i&&{"exception.stacktrace":i}}),e.statusIsExplicitlyOk||e.setStatus("error",s)}_evictAgedSpans(){let e=go()-this._config.maxSpanAgeMs,r=0;for(let[n,s]of this._liveSpans){if(s>e)break;this._liveSpans.delete(n),r++}r&&this._recordDrop(r,`they were still live after ${this._config.maxSpanAgeMs}ms`)}_onSpanEnd(e,r){if(!this._liveSpans.delete(e.spanId))return;if(this._instance.isDisabled||this._instance.optedOut)return void this._recordDrop(1,"the user has opted out");let n=this._runBeforeSpanSend(e,r);if(n){if(this._reportLimitDrops(n),this._queue.length>=this._config.maxQueueSize)return void this._recordDrop(1,`the queue is full (${this._config.maxQueueSize}) \u2014 raise the flush frequency or reduce span volume`);this._queue.push(n);try{this._onSpanQueued?.()}catch(s){this._logger.debug("Span queue notification failed",s)}!(this._queue.length>=this._maxExportBatchSize)||this._consecutiveFlushFailures||this._retryAfter.isOpen()?this._armFlushTimerIfQueued():this._flushInBackground()}}_reportLimitDrops(e){let r=e.droppedAttributesCount??0,n=e.droppedEventsCount??0,s=0;for(let i of e.events)s+=i.droppedAttributesCount??0;(r||n||s)&&this._logger.debug(`Span limits discarded data from "${e.name}": ${r} attributes, ${n} events, ${s} event attributes`)}_runBeforeSpanSend(e,r){if(!this._config.beforeSpanSend.length)return e;let n={traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId,traceState:e.traceState},s={startTime:e.startTime,endTime:e.endTime},i={attributes:e.droppedAttributesCount,events:e.droppedEventsCount},o=Object.keys(e.attributes),a={traceFlags:e.traceFlags,parentIsRemote:e.parentIsRemote},c=e.status&&{...e.status},u=e,l=e;try{for(let g of this._config.beforeSpanSend){let m=g(u);if(!m)return this._recordDrop(1,"beforeSpanSend dropped it"),null;u=this._keepSpanIdentity(m,n)}if(l={traceId:n.traceId,spanId:n.spanId,parentSpanId:n.parentSpanId,traceState:n.traceState,name:u.name,kind:u.kind,status:u.status,attributes:u.attributes,events:u.events,startTime:u.startTime,endTime:u.endTime,traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote,droppedAttributesCount:i.attributes,droppedEventsCount:i.events},!eR(l))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;l.name=qt(l.name,"Span name",this._config.maxAttributeValueLength,this._logger),l.status&&l.status.code!=="ok"&&l.status.code!=="error"&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),l.status=c),l.startTime=Fr(l.startTime)??s.startTime,l.endTime=ao(Fr(l.endTime)??s.endTime,l.startTime);let p=[];for(let g of l.events)try{p.push({...g,name:qt(g.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:Hn(g.timestamp,l.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return l.events=p,fh(l,r,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,o),l}catch(d){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",d),this._recordDrop(1,"beforeSpanSend failed"),null}}_keepSpanIdentity(e,r){(e.traceId!==r.traceId||e.spanId!==r.spanId||e.parentSpanId!==r.parentSpanId)&&this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");try{mo(e,"traceId",r.traceId),mo(e,"spanId",r.spanId),mo(e,"parentSpanId",r.parentSpanId),mo(e,"traceState",r.traceState)}catch{return tR(e,r)}return e}_recordDrop(e,r){this._droppedSinceWarning+=e,this._dropReasons.add(r),Date.now()-this._lastDropWarningAt>=this._config.flushIntervalMs&&this._warnAboutDrops()}_warnAboutDrops(){this._droppedSinceWarning&&(this._lastDropWarningAt=Date.now(),this._logger.warn(`Dropping ${this._droppedSinceWarning} span(s): ${[...this._dropReasons].join("; ")}`),this._droppedSinceWarning=0,this._dropReasons.clear())}_encodeBatch(e){let r=[];for(let n of e)try{r.push(hh(n,this._logger))}catch(s){this._logger.debug("Failed to encode a span; dropping it",s),this._recordDrop(1,"its attributes could not be encoded")}return r}_discardQueueIfConsentWithdrawn(){if(!this._instance.isDisabled&&!this._instance.optedOut)return 0;let e=this._queue.length;return this._queue=[],this._resetHeadBatchBudget(),this._recordDrop(e,"the user has opted out"),this._warnAboutDrops(),e}async _flushInner(){if(!this._queue.length)return 0;let e=this._discardQueueIfConsentWithdrawn();if(e)return e;let r=mh(_h(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._config.maxAttributeValueLength),n=this._instance.getLibraryId(),s=this._instance.getLibraryVersion(),i=this._queue.length,o=0,a=1/0,c=this._generation;try{for(;i>0&&this._queue.length>0;){let u=this._discardQueueIfConsentWithdrawn();if(u)return o+u;let l=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,d=Math.max(1,Math.min(l,a,i,this._queue.length)),p=this._queue.slice(0,d),g=this._encodeBatch(p);if(!g.length){this._queue.splice(0,d),i-=d,o+=d,this._resetHeadBatchBudget();continue}let m=go()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),h=await this._instance._sendTracesBatch(Eh(g,r,n,s,this._logger));if(c!==this._generation)break;if(this._retryAfter.record(h),h.kind==="ok"){this._consecutiveFlushFailures=0,this._flushJitter=Ae,this._resetHeadBatchBudget(),this._queue.splice(0,d),i-=d,o+=d,this._maxExportBatchSize<this._config.maxExportBatchSize&&this._maxExportBatchSize++;continue}if(h.kind==="too-large"){if(d===1){this._queue.splice(0,1),i-=1,o+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=Ae,this._resetHeadBatchBudget();continue}let _=Math.max(1,Math.floor(d/2));h.measuredLocally?a=_:this._maxExportBatchSize=_,this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${_}`);continue}if(h.kind==="retry-later"){if(this._consecutiveFlushFailures++,this._flushJitter=Un(),this._headBatchSize=d,m&&(this._headBatchFailures++,this._headBatchChargeableAt=go()+this._nextFlushDelay()),this._headBatchFailures<Sh)return this._logger.debug("Span export failed; retrying on the next flush",h.error),o;if(this._queue.splice(0,d),i-=d,o+=d,this._consecutiveFlushFailures=0,this._flushJitter=Ae,this._resetHeadBatchBudget(),this._recordDrop(d,`the ingestion endpoint failed ${Sh} times in a row`),this._retryAfter.isOpen())return o;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",h.error),this._queue.splice(0,d),i-=d,o+=d,this._consecutiveFlushFailures=0,this._flushJitter=Ae,this._resetHeadBatchBudget(),this._recordDrop(d,"the ingestion endpoint rejected the batch")}return o}finally{this._warnAboutDrops()}}_flushInBackground(){this._backgroundFlush||(this._backgroundFlush=this.flush().catch(e=>{this._logger.debug("Background span flush failed",e)}).finally(()=>{this._backgroundFlush=void 0,this._armFlushTimerIfQueuedNoEarlierThan()}))}_armFlushTimerIfQueued(){this._flushTimer.pending||!this._queue.length||this._flushTimer.arm(this._nextFlushDelay())}_armFlushTimerIfQueuedNoEarlierThan(){this._queue.length&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())}_nextFlushDelay(){return Math.max($n(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}};var Gn=class{active(){return this._active}with(e,r){let n=this._active;this._active=e;try{return r()}finally{this._active=n}}};var rR=5e3,nR=512,sR=2048,iR=128,oR=128,aR=128,cR=8192,uR=1e4,lR=36e5;function Ot(t,e){return typeof t=="number"&&Number.isInteger(t)&&t>=1?t:e}var bh=["service.name","service.version","deployment.environment"];function dR(t){if(!(!t||typeof t!="object"||Array.isArray(t)))try{if(bh.every(r=>!(r in t)||typeof t[r]=="string"))return t;let e={...t};for(let r of bh)r in e&&typeof e[r]!="string"&&delete e[r];return e}catch{return}}function fR(t,e){if(!t)return[];let r=[t].flat().filter(s=>!!s),n=r.filter(s=>typeof s=="function");return n.length!==r.length&&e?.critical(`beforeSpanSend: ignoring ${r.length-n.length} of ${r.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`),n}function Vu(t,e,r){let n=pt({...e},dR(t?.resourceAttributes)),s=Ot(t?.maxExportBatchSize,nR);return{serviceName:n?.["service.name"]??t?.serviceName,serviceVersion:n?.["service.version"]??t?.serviceVersion,environment:n?.["deployment.environment"]??t?.environment,resourceAttributes:n,beforeSpanSend:fR(t?.beforeSpanSend,r),maxAttributesPerSpan:Ot(t?.maxAttributesPerSpan,iR),maxEventsPerSpan:Ot(t?.maxEventsPerSpan,oR),maxAttributesPerEvent:aR,maxAttributeValueLength:Ot(t?.maxAttributeValueLength,cR),flushIntervalMs:Ot(t?.flushIntervalMs,rR),maxExportBatchSize:s,maxQueueSize:Math.max(Ot(t?.maxQueueSize,sR),s),maxLiveSpans:Ot(t?.maxLiveSpans,uR),maxSpanAgeMs:Ot(t?.maxSpanAgeMs,lR)}}var Yu=require("node:fs"),Ih=require("node:fs/promises"),Ju=require("node:path"),vh=require("node:readline"),ho=new J.ReduceableCache(25),zn=new J.ReduceableCache(20),Qu=7,pR=1e3,gR=1e4,qu=10485760;async function Rh(t,e=Ih.open,r){let n={},s;try{s=process.cwd()}catch{}for(let a=t.length-1;a>=0;a--){let c=t[a],u=c?.filename;if(!c||typeof u!="string"||typeof c.lineno!="number"||SR(u)||yR(c)||!(0,Ju.isAbsolute)(u)&&s===void 0)continue;n[u]||(n[u]=[]),n[u].push(c.lineno)}let i=Object.keys(n);if(i.length==0)return t;let o=[];for(let a of i){let c=Ah(a,s);if(c===void 0||zn.get(c))continue;let u=n[a];if(!u)continue;u.sort((p,g)=>p-g);let l=wR(u);if(l.every(p=>bR(c,p)))continue;let d=TR(ho,c,{});o.push(hR(a,l,d,c,e,r))}return await Promise.all(o).catch(()=>{}),t&&t.length>0&&_R(t,ho,s),ho.reduce(),t}async function mR(t,e,r){let n,s=!1;try{n=await e(t,Yu.constants.O_RDONLY|Yu.constants.O_NONBLOCK);let i=await n.stat();return i.isFile()?i.size>qu?void r?.debug(`Skipping source context for oversized file ${t}: ${i.size} bytes exceeds ${qu}`):(s=!0,n):void 0}catch{return}finally{n&&!s&&await n.close().catch(()=>{})}}async function hR(t,e,r,n,s,i){let o=await mR(t,s,i);if(o===void 0)return void zn.set(n,1);let a=o;return new Promise(c=>{let u=!1;function l(w){u||(u=!0,w?.destroy(),a.close().then(c,c))}let d;try{d=a.createReadStream({autoClose:!1,start:0,end:qu-1})}catch{zn.set(n,1),l();return}let p;try{p=(0,vh.createInterface)({input:d})}catch{zn.set(n,1),l(d);return}let g=0,m=0,h=e[m];if(h===void 0)return void l(d);let _=h[0],S=h[1];function b(){zn.set(n,1),p.close(),p.removeAllListeners(),l(d)}d.on("error",b),p.on("error",b),p.on("close",()=>l(d)),p.on("line",w=>{if(g++,!(g<_)&&(r[g]=IR(w,0),g>=S)){if(m===e.length-1){p.close(),p.removeAllListeners();return}m++;let T=e[m];if(T===void 0){p.close(),p.removeAllListeners();return}_=T[0],S=T[1]}})})}function _R(t,e,r){for(let n of t)if(n.filename&&n.context_line===void 0&&typeof n.lineno=="number"){let s=Ah(n.filename,r),i=s===void 0?void 0:e.get(s);if(i===void 0)continue;ER(n.lineno,n,i)}}function ER(t,e,r){if(e.lineno===void 0||r===void 0)return;e.pre_context=[];for(let s=Mh(t);s<t;s++){let i=r[s];if(i===void 0)return void wh(e);e.pre_context.push(i)}if(r[t]===void 0)return void wh(e);e.context_line=r[t];let n=Ph(t);e.post_context=[];for(let s=t+1;s<=n;s++){let i=r[s];if(i===void 0)break;e.post_context.push(i)}}function wh(t){delete t.pre_context,delete t.context_line,delete t.post_context}function SR(t){return t.startsWith("node:")||t.endsWith(".min.js")||t.endsWith(".min.cjs")||t.endsWith(".min.mjs")||t.startsWith("data:")}function yR(t){return t.lineno!==void 0&&t.lineno>gR||t.colno!==void 0&&t.colno>pR}function Ah(t,e){return(0,Ju.isAbsolute)(t)?JSON.stringify([null,t]):e===void 0?void 0:JSON.stringify([e,t])}function bR(t,e){let r=ho.get(t);if(r===void 0)return!1;for(let n=e[0];n<=e[1];n++)if(r[n]===void 0)return!1;return!0}function wR(t){if(!t.length)return[];let e=0,r=t[0];if(typeof r!="number")return[];let n=Th(r),s=[];for(;;){if(e===t.length-1){s.push(n);break}let i=t[e+1];if(typeof i!="number")break;i<=n[1]?n[1]=i+Qu:(s.push(n),n=Th(i)),e++}return s}function Th(t){return[Mh(t),Ph(t)]}function Mh(t){return Math.max(1,t-Qu)}function Ph(t){return t+Qu}function TR(t,e,r){let n=t.get(e);return n===void 0?(t.set(e,r),r):n}function IR(t,e){let r=t,n=r.length;if(n<=150)return r;e>n&&(e=n);let s=Math.max(e-60,0);s<5&&(s=0);let i=Math.min(s+140,n);return i>n-5&&(i=n),i===n&&(s=Math.max(i-140,0)),r=r.slice(s,i),s>0&&(r=`...${r}`),i<n&&(r+="..."),r}var Ur=require("path");function Oh(t=process.cwd()){let e=Ur.sep==="\\",r=s=>e?s.replace(/\\/g,"/"):s,n=r(t);return async s=>{for(let i of s)!i.filename||i.filename.startsWith("node:")||i.filename.startsWith("data:")||(0,Ur.isAbsolute)(i.filename)&&(i.filename=r((0,Ur.relative)(n,r(i.filename))));return s}}var kh="5.56.2";var mt={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var kt=class t{constructor(e){this._host=e.host,this._distinctId=e.distinctId,this._groups=e.groups,this._disableGeoip=e.disableGeoip,this._flags=e.flags,this._requestId=e.requestId,this._evaluatedAt=e.evaluatedAt,this._flagDefinitionsLoadedAt=e.flagDefinitionsLoadedAt,this._errorsWhileComputing=e.errorsWhileComputing??!1,this._quotaLimited=e.quotaLimited??!1,this._accessed=e.accessed??new Set,this._isSlice=e.isSlice??!1}isEnabled(e,r={}){let n=this._flags[e];return this._recordAccess(e),n?.enabled??r.defaultValue??!1}getFlag(e){let r=this._flags[e];if(this._recordAccess(e),!!r)return r.enabled?r.variant??!0:!1}getFlagPayload(e){return this._flags[e]?.payload}onlyAccessed(){let e={};for(let r of this._accessed){let n=this._flags[r];n&&(e[r]=n)}return this._cloneWith(e)}only(e){let r={},n=[];for(let s of e){let i=this._flags[s];i?r[s]=i:n.push(s)}return n.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${n.join(", ")}`),this._cloneWith(r)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let e={},r=[];for(let[n,s]of Object.entries(this._flags)){let i=s.enabled===!1?!1:s.variant??!0;e[`$feature/${n}`]=i,s.enabled&&r.push(n)}return r.length>0&&(r.sort(),e.$active_feature_flags=r),e}_cloneWith(e){return new t({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:e,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(e){if(this._accessed.add(e),this._distinctId===""||this._isSlice&&!(e in this._flags))return;let r=this._flags[e],n=r===void 0?void 0:r.enabled===!1?!1:r.variant??!0,s={$feature_flag:e,$feature_flag_response:n,$feature_flag_id:r?.id,$feature_flag_version:r?.version,$feature_flag_reason:r?.reason,locally_evaluated:r?.locallyEvaluated??!1,[`$feature/${e}`]:n,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:r?.locallyEvaluated?Date.now():this._evaluatedAt};r?.hasExperiment!==void 0&&(s.$feature_flag_has_experiment=r.hasExperiment),r?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0&&(s.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let i=[];this._errorsWhileComputing&&i.push(mt.ERRORS_WHILE_COMPUTING),this._quotaLimited&&i.push(mt.QUOTA_LIMITED),r===void 0&&i.push(mt.FLAG_MISSING),i.length>0&&(s.$feature_flag_error=i.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:n,groups:this._groups,disableGeoip:this._disableGeoip,properties:s})}};var vR=6e4;function xh(t){return t==="client"||t==="server"?t:"all"}function RR(t,e){return t===e||t==="all"||e==="all"}var Qt=class t extends Error{constructor(e){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,t.prototype)}};function AR(t,e){t.name=e.name,Error.captureStackTrace(t,e),Object.setPrototypeOf(t,e.prototype)}var qe=class t extends Error{constructor(e){super(e),AR(this,t)}},_o=class{constructor({pollingInterval:e,personalApiKey:r,projectApiKey:n,timeout:s,host:i,customHeaders:o,...a}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollerStopped=!1,this.filteredOutFlagKeys=new Set,this.pollingInterval=e,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=s,this.projectApiKey=n,this.host=i,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=o,this.onLoad=a.onLoad,this.onMinimalFlagCalledEvents=a.onMinimalFlagCalledEvents,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.evaluationContexts=a.evaluationContexts,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){this.debugMode&&e()}withEvaluationSnapshot(e){return e.definitions?e:{...e,evaluationCache:{},definitions:{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}}createEvaluationContext(e,r={},n={},s={},i={}){return{distinctId:e,groups:r,personProperties:n,groupProperties:s,evaluationCache:i}}async getFeatureFlag(e,r,n={},s={},i={}){await this.loadFeatureFlags();let o,a;if(!this.loadedSuccessfullyOnce)return o;if(a=this.featureFlagsByKey[e],a!==void 0){let c=this.createEvaluationContext(r,n,s,i);try{o=(await this.computeFlagAndPayloadLocally(a,c)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${o}`))}catch(u){u instanceof qe||u instanceof M?this.logMsgIfDebug(()=>console.debug(`${u.name} when computing flag locally: ${e}: ${u.message}`)):u instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${e}: ${u}`))}}return o}async getAllFlagsAndPayloads(e,r){await this.loadFeatureFlags();let n={},s={},i=this.featureFlags.length==0,o=r?r.map(c=>this.featureFlagsByKey[c]).filter(Boolean):this.featureFlags,a=this.withEvaluationSnapshot({...e,definitions:void 0});return await Promise.all(o.map(async c=>{try{let{value:u,payload:l}=await this.computeFlagAndPayloadLocally(c,a,{skipLoadCheck:!0});n[c.key]=u,l&&(s[c.key]=l)}catch(u){u instanceof qe||u instanceof M?this.logMsgIfDebug(()=>console.debug(`${u.name} when computing flag locally: ${c.key}: ${u.message}`)):u instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${c.key}: ${u}`)),i=!0}})),{response:n,payloads:s,fallbackToFlags:i}}async computeFlagAndPayloadLocally(e,r,n={}){let{matchValue:s,skipLoadCheck:i=!1}=n;if(this.loadedSuccessfullyOnce&&(r=this.withEvaluationSnapshot(r)),i||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};r=this.withEvaluationSnapshot(r),e=r.definitions.featureFlagsByKey[e.key]??e;let o;o=s!==void 0?s:await this.computeFlagValueLocally(e,r);let a=Nu(e.filters?.payloads,o);return{value:o,payload:a}}async computeFlagValueLocally(e,r){let{distinctId:n,groups:s,personProperties:i,groupProperties:o}=r;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new M("Flag has experience continuity enabled");let c=(e.filters||{}).aggregation_group_type_index;if(c!=null){let u=r.definitions.groupTypeMapping[String(c)];if(!u)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${e.key}`)),new M("Flag has unknown group type index");if(!(u in s))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;e.bucketing_identifier==="device_id"&&(i?.$device_id===void 0||i?.$device_id===null||i?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let l=o[u];return await this.matchFeatureFlagProperties(e,s[u],l,r)}{let u=this.getBucketingValueForFlag(e,n,i);if(u===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new M(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,u,i,r)}}getBucketingValueForFlag(e,r,n){if(e.filters?.aggregation_group_type_index!=null)return r;if(e.bucketing_identifier==="device_id"){let s=n?.$device_id;return s==null||s===""?void 0:s}return r}async evaluateFlagDependency(e,r,n){let{evaluationCache:s}=n,i=e.key;if(!n.definitions.featureFlagsByKey)throw new M("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new M(`Flag dependency property for '${i}' is missing required 'dependency_chain' field`);let o=e.dependency_chain;if(!Array.isArray(o))throw new M(`Flag dependency property for '${i}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new M(`Circular dependency detected for flag '${i}' (empty dependency chain)`);for(let c of o){if(!(c in s)){let l=n.definitions.featureFlagsByKey[c];if(l)if(l.active)try{let d=await this.computeFlagValueLocally(l,n);s[c]=d}catch(d){throw new M(`Error evaluating flag dependency '${c}' for flag '${i}': ${d}`)}else s[c]=!1;else if(n.definitions.filteredOutFlagKeys.has(c))s[c]=!1;else throw new M(`Missing flag dependency '${c}' for flag '${i}'`)}if(s[c]==null)throw new M(`Dependency '${c}' could not be evaluated`)}let a=s[i];return this.flagEvaluatesToExpectedValue(e.value,a)}flagEvaluatesToExpectedValue(e,r){return typeof e=="boolean"?e===r||typeof r=="string"&&r!==""&&e===!0:typeof e=="string"?r===e:!1}async matchFeatureFlagProperties(e,r,n,s){s=this.withEvaluationSnapshot(s);let i=e.filters||{},o=await ku(i.holdout,r);if(o!==void 0)return o;let a=i.groups||[],c=i.aggregation_group_type_index,u=i.early_exit??!1,{groups:l,groupProperties:d}=s,p=!1,g;for(let m of a)try{let h=m.aggregation_group_type_index!==void 0?m.aggregation_group_type_index:c,_=n,S=r;if(h!==c&&h!=null){let w=s.definitions.groupTypeMapping[String(h)];if(!w||!(w in l)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${h} not available`));continue}if(!(w in d)){p=!0;continue}_=d[w],S=l[w]}let b=await this.isConditionMatch(e,S,m,_,s);if(b==="match"){let w=m.variant,T=i.multivariate?.variants||[];g=w&&T.some(y=>y.key===w)?w:await this.getMatchingVariant(e,S)||!0;break}if(u&&b==="out_of_rollout_bound"){if(p)break;return!1}}catch(h){if(h instanceof qe)throw h;if(h instanceof M)p=!0;else throw h}if(g!==void 0)return g;if(p)throw new M("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,r,n,s,i){i=this.withEvaluationSnapshot(i);let o=i.definitions,a=n.rollout_percentage,c=u=>{this.logMsgIfDebug(()=>console.warn(u))};if((n.properties||[]).length>0){for(let u of n.properties){let l=u.type,d=!1;if(l==="cohort"){let p=await Ch(u,s,o.cohorts,this.debugMode,g=>this.evaluateFlagDependency(g,s,i),o.propertyMatchingVersion);d=u.operator==="not_in"?!p:p}else d=l==="flag"?await this.evaluateFlagDependency(u,s,i):Nh(u,s,c,o.propertyMatchingVersion);if(!d)return"no_match"}if(a==null)return"match"}return a!=null&&await Cn(e.key,r)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(e,r){return xu(e.key,r,e.filters?.multivariate?.variants||[])}variantLookupTable(e){return eo(e.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(e){if(!this.evaluationContexts||this.evaluationContexts.length===0)return e;let r=new Set(this.evaluationContexts);return e.filter(n=>{let s=n.evaluation_contexts??n.evaluation_tags;return!s||s.length===0?!0:s.some(i=>r.has(i))})}getEvaluationRuntimeForFlag(e){let r=this.featureFlagsByKey[e];return r?xh(r.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(e){return this.featureFlags.filter(r=>RR(xh(r.evaluation_runtime),e)).map(r=>r.key)}updateFlagState(e){let r=this.filterFlagsByEvaluationContexts(e.flags),n=r.reduce((o,a)=>(o[a.key]=a,o),{}),s=new Set(r.map(o=>o.key)),i=new Set(e.flags.filter(o=>!s.has(o.key)).map(o=>o.key));this.featureFlags=r,this.featureFlagsByKey=n,this.filteredOutFlagKeys=i,this.groupTypeMapping=e.group_type_mapping??e.groupTypeMapping??{},this.cohorts=e.cohorts,this.propertyMatchingVersion=e.property_matching_version??e.propertyMatchingVersion,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.((e.minimal_flag_called_events??e.minimalFlagCalledEvents)===!0)}warnAboutExperienceContinuityFlags(e){if(this.strictLocalEvaluation)return;let r=e.filter(n=>n.ensure_experience_continuity);r.length>0&&console.warn(`[PostHog] You are using local evaluation but ${r.length} flag(s) have experience continuity enabled: ${r.map(n=>n.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(e){if(!this.cacheProvider)return!1;try{let r=await this.cacheProvider.getFlagDefinitions();return r?(this.updateFlagState(r),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${r.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags),!0):!1}catch(r){return this.onError?.(new Error(`Failed to load from cache: ${r}`)),!1}}async loadFeatureFlags(e=!1){if(!(this.loadedSuccessfullyOnce&&!e))return!e&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(r=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${r}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){let e=this.pollingInterval??3e4;return this.shouldBeginExponentialBackoff?Math.min(vR,e*2**this.backOffCount):e}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0);try{if(this.cacheProvider&&!this.personalApiKey)return void await this.loadFromCache("Loaded flags from cache (cache-only reader)");let e=!0;if(this.cacheProvider)try{e=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(n){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${n}`))}if(!e&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let r=await this._requestFeatureFlagDefinitions();if(!r)return;switch(r.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=r.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new Qt(`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.filteredOutFlagKeys=new Set,this.groupTypeMapping={},this.cohorts={},this.propertyMatchingVersion=void 0,this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new Qt(`Your secret key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new Qt(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let n=await r.json()??{};if(!("flags"in n))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(n)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let s=n.group_type_mapping||{},i=n.minimal_flag_called_events===!0,o={flags:n.flags??[],group_type_mapping:s,cohorts:n.cohorts||{},minimal_flag_called_events:i,property_matching_version:n.property_matching_version,propertyMatchingVersion:n.property_matching_version,groupTypeMapping:s,minimalFlagCalledEvents:i};if(this.updateFlagState(o),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(o)}catch(a){this.onError?.(new Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags);break}default:return}}catch(e){e instanceof Qt&&this.onError?.(e)}finally{!this.pollerStopped&&this.pollingInterval!==null&&(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}getPersonalApiKeyRequestOptions(e="GET",r){let n={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(n["If-None-Match"]=r),{method:e,headers:n}}async _requestFeatureFlagDefinitions(){if(!this.personalApiKey)throw new Qt("A secretKey or personalApiKey is required to fetch feature flag definitions from PostHog.");let e=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let i=new AbortController;n=le(()=>{i.abort()},this.timeout),r.signal=i.signal}let s=()=>clearTimeout(n);try{let i=this.fetch,o=await i(e,r);return o.status!==200?(s(),o):{status:o.status,headers:o.headers,body:o.body,text:async()=>{try{return await o.text()}finally{s()}},json:async()=>{try{return await o.json()}finally{s()}}}}catch(i){throw s(),i}}async stopPoller(e=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await Mt(r,e,()=>{throw new Error(`Cache shutdown timeout after ${e}ms`)})}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};function Nh(t,e,r,n){return Ou(t,e,{warnFunction:r,propertyMatchingVersion:n})}function MR(t,e){if(!(t in e))throw new qe(`cohort ${t} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function Ch(t,e,r,n=!1,s,i){let o=String(t.value);MR(o,r);let a=r[o];return Dh(a,e,r,n,s,i)}async function Dh(t,e,r,n=!1,s,i){if(!t)return!0;let o=t.type,a=t.values;if(!a||a.length===0)return!0;let c=!1;if("values"in a[0]){for(let u of a)try{let l=await Dh(u,e,r,n,s,i);if(o==="AND"){if(!l)return!1}else if(l)return!0}catch(l){if(l instanceof qe)throw l;if(l instanceof M)n&&console.debug(`Failed to compute property ${u} locally: ${l}`),c=!0;else throw l}if(c)throw new M("Can't match cohort without a given cohort property value");return o==="AND"}for(let u of a)try{let l;if(u.type==="cohort")l=await Ch(u,e,r,n,s,i);else if(u.type==="flag"){if(!s)throw new M(`Flag dependency '${u.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);l=await s(u)}else l=Nh(u,e,void 0,i);let d=u.negation||!1;if(o==="AND"){if(!l&&!d||l&&d)return!1}else if(l&&!d||!l&&d)return!0}catch(l){if(l instanceof qe)throw l;if(l instanceof M)n&&console.debug(`Failed to compute property ${u} locally: ${l}`),c=!0;else throw l}if(c)throw new M("can't match cohort without a given cohort property value");return o==="AND"}var PR=["--unhandled-rejections","--unhandled_rejections"],OR=new Set(["throw","strict","warn","warn-with-error-code","none"]),kR=[...globalThis.process?.execArgv??[]],xR=globalThis.process?.env?.NODE_OPTIONS;function NR(t){let e=[],r="",n=!1;for(let s=0;s<t.length;s++){let i=t[s];i==="\\"&&n&&s+1<t.length?r+=t[++s]:i!==" "||n?i==='"'?n=!n:r+=i:r&&(e.push(r),r="")}return r&&e.push(r),e}function Fh(t){let e;for(let r=0;r<t.length;r++){let n=t[r],s=PR.find(o=>n===o||n.startsWith(`${o}=`));if(!s)continue;let i=n===s?t[++r]:n.slice(s.length+1);OR.has(i)&&(e=i)}return e}function CR(t=kR,e=xR){return Fh(t)??Fh(NR(e??""))??"throw"}var Lh=CR();function Uh(t,e,r){t(e,{mechanism:{type:r==="unhandledRejection"?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function DR(t,e){let r=!1;return Object.assign((n,s)=>{let i=global.process.listeners("uncaughtException").filter(o=>o.name!=="domainUncaughtExceptionClear"&&o._posthogErrorHandler!==!0).length;Uh(t,n,s),!r&&i===0&&(r=!0,e(n))},{_posthogErrorHandler:!0})}function $h(t,e,r=Lh){let n=globalThis.process;if(n){if(r==="strict")return void n.on("uncaughtExceptionMonitor",(s,i)=>Uh(t,s,i));n.on("uncaughtException",DR(t,e))}}function Bh(t,e=Lh){let r=globalThis.process;!r||e==="throw"||e==="strict"||e==="warn-with-error-code"||r.on("unhandledRejection",n=>{t(n,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var FR=2e3,Zu=class t{constructor(e,r,n){this.client=e,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new Fi({...Jg(r),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return En(e)&&"__posthog_previously_captured_error"in e&&e.__posthog_previously_captured_error===!0}static async buildEventMessage(e,r,n,s,i){let o={...i},a=e.buildFromUnknown(r,n);a.$exception_list=await e.modifyFrames(a.$exception_list);let c=J.getInjectedReleaseId();return c&&(o.$release_id=c),{event:"$exception",distinctId:s,properties:{...a,...o},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&($h(this.onException.bind(this),this.onFatalError.bind(this)),Bh(this.onException.bind(this)))}onException(e,r){this.client.addPendingPromise((async()=>{if(!t.isPreviouslyCapturedError(e)){let n=await t.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,r),i=n.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(i)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:i}):this.client._capturePreparedEvent(n,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(FR),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}},Zt=Zu;var oA=/^[0-9a-f]{32}$/i,aA=/^[0-9a-f]{16}$/i,cA;async function L_(){try{let e=(await(cA??=Promise.resolve().then(()=>(F_(),D_)))).trace.getActiveSpan()?.spanContext(),r=e?.traceId,n=e?.spanId;if(typeof r=="string"&&typeof n=="string"&&oA.test(r)&&aA.test(n)&&!/^0+$/.test(r)&&!/^0+$/.test(n))return{$trace_id:r.toLowerCase(),$span_id:n.toLowerCase()}}catch{}return{}}var jo=class{getProperty(e){return this._memoryStorage[e]}setProperty(e,r){this._memoryStorage[e]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};function uA(t){return t==="v0"||t==="v1"}function U_(){let t="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return uA(t)?t:"v0"}var lA="$ai_",ns="analytics";function $_(t){return typeof t.event=="string"&&t.event.startsWith(lA)}var Kr=class t extends Error{constructor({requestId:e,drops:r,retryExhausted:n,cause:s}){super(t.buildMessage(e,r,n,s)),this.name="CaptureV1Error",this.requestId=e,this.drops=r,this.retryExhausted=n,this.cause=s}static buildMessage(e,r,n,s){let i=`Capture V1 batch ${e} did not fully deliver: ${r.length} dropped, ${n.length} undelivered`;return s instanceof Error&&(i+=` (${s.message})`),i}};function Ul(t){if(typeof t=="boolean")return t;if(typeof t=="number")return t!==0;if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true"||e==="1")return!0;if(e==="false"||e==="0")return!1}}function dA(t){return typeof t=="string"?t:void 0}var fA=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:Ul},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:Ul},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:Ul},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:dA}],pA=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function gA(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function mA(t){if(typeof t=="string"){let r=new Date(t);if(Number.isNaN(r.getTime()))return new Date().toISOString();let n=r.toISOString(),s=t.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return s&&s.length>3?n.replace(/\.\d{3}Z$/,`.${s}Z`):n}if(t instanceof Date)return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString();let e=t==null?new Date:new Date(t);return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString()}function B_(t,e,r){r!==void 0&&!(e in t)&&(t[e]=r)}function hA(t){let r={...gA(t.properties)?t.properties:{}},n={};for(let{property:i,optionKey:o,coerce:a}of fA)if(i in r){let c=a(r[i]);c!==void 0&&(n[o]=c),delete r[i]}let s={};for(let{property:i,field:o}of pA)if(i in r){let a=r[i];typeof a=="string"&&(s[o]=a),delete r[i]}return delete r.$lib,delete r.$lib_version,B_(r,"$set",t.$set),B_(r,"$set_once",t.$set_once),{event:String(t.event??""),uuid:String(t.uuid??""),distinct_id:String(t.distinct_id??""),timestamp:mA(t.timestamp),...s,options:n,properties:r}}function W_(t,{createdAt:e,historicalMigration:r}){let n={created_at:e,batch:t.map(hA)};return r&&(n.historical_migration=!0),n}var _A="/i/v1/analytics/events",EA=3e4,SA=new Set([408,500,502,503,504]),Xo=class{constructor(e,r){this.config=e,this.maxBackoffMs=e.maxBackoffMs??EA,this.fetchFn=r.fetch,this.onError=r.onError,this.now=r.now??Date.now,this.sleep=r.sleep??(n=>new Promise(s=>le(s,n))),this.generateRequestId=r.generateRequestId??ue,this.compress=r.compress??kn}async sendV1Batch(e){if(e.length===0)return;let r=this.generateRequestId(),n=new Date(this.now()).toISOString(),{batch:s}=W_(e,{createdAt:n,historicalMigration:this.config.historicalMigration}),i=`${this.config.host}${_A}`,o=[],a=s,c=Math.max(1,this.config.maxAttempts);for(let u=1;u<=c;u++){let l=u===c,d=Rt({created_at:n,...this.config.historicalMigration?{historical_migration:!0}:{},batch:a}),p,g;try{p=await this.sendOnce(i,d,u,r);let{response:m,signal:h}=p,{status:_}=m;if(_<200||_>=300)if(!l&&SA.has(_)){let S=this.parseRetryAfter(m);await p.waitFor(p.cancelBody()).catch(()=>{}),g=this.backoffDelay(u,S)}else{let S=await this.buildHttpError(m,_,p.waitFor);return this.surfaceBatchFailure(r,o,a,S)}else{let S;try{S=await p.waitFor(this.parseResponse(m))}catch(T){if(h.aborted)throw T;return this.surfaceBatchFailure(r,o,a,new Error(`Capture V1 returned an unparseable ${_} response body`))}let b=this.classify(a,S,o);if(b.length===0)return this.surfacePartialDrops(r,o);if(l)return void this.onError(new Kr({requestId:r,drops:o,retryExhausted:b.map(T=>T.uuid)}));a=b;let w=this.parseRetryAfter(m);g=this.backoffDelay(u,w)}}catch(m){if(p&&!p.signal.aborted)throw m;if(l)return this.surfaceBatchFailure(r,o,a,m);g=this.backoffDelay(u)}finally{p?.cleanup()}g!==void 0&&await this.sleep(g)}}async sendOnce(e,r,n,s){let i=this.buildHeaders(n,s),o=r;if(this.config.compressionEnabled){let d=await this.compress(r,this.config.isDebug);d!==null&&(o=d,i["Content-Encoding"]="gzip")}let a=new AbortController,c="waiting for response headers",u,l=new Promise((d,p)=>{u=le(()=>{let g=new Error(`Capture V1 request timed out ${c} after ${this.config.requestTimeoutMs}ms`);g.name="AbortError",p(g),a.abort(g)},this.config.requestTimeoutMs)});try{let d=this.fetchFn(e,{method:"POST",headers:i,body:o,signal:a.signal}),p=!1;d.then(S=>{a.signal.aborted&&!p&&this.cancelBody(S)}).catch(()=>{});let g=await Promise.race([d,l]);p=!0,c="while reading the response body";let m=!1,h,_=()=>h??=this.cancelBody(g);return{response:g,signal:a.signal,waitFor:S=>Promise.race([S,l]),cancelBody:_,cleanup:()=>{m||(m=!0,clearTimeout(u),a.signal.aborted&&_())}}}catch(d){throw clearTimeout(u),d}}buildHeaders(e,r){let n=`${this.config.libraryId}/${this.config.libraryVersion}`,s={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":n,"PostHog-Attempt":String(e),"PostHog-Request-Id":r,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(s["User-Agent"]=this.config.userAgent),s}classify(e,r,n){let s=r.results??{},i=[];for(let o of e){let a=s[o.uuid];a&&(a.result==="drop"?n.push({uuid:o.uuid,details:a.details??void 0}):a.result==="retry"&&i.push(o))}return i}backoffDelay(e,r){let n=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);return r===void 0?n:Math.max(n,Math.min(r,this.maxBackoffMs))}parseRetryAfter(e){let r=e.headers?.get("Retry-After");if(!r)return;let n=r.trim();if(/^\d+$/.test(n)){let o=parseInt(n,10);return Number.isFinite(o)&&o>0?1e3*o:void 0}let s=Date.parse(n);if(Number.isNaN(s))return;let i=s-this.now();return i>0?i:void 0}async parseResponse(e){let r=await e.text(),n=JSON.parse(r);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("unexpected response shape");let s=n.results;if(s!==void 0&&(typeof s!="object"||s===null||Array.isArray(s)))throw new Error("unexpected results shape");return{results:s??{}}}async buildHttpError(e,r,n){let s="";try{s=(await n(e.text())).slice(0,512)}catch{}let i=s?`: ${s}`:"";return new Error(`Capture V1 request failed with HTTP ${r}${i}`)}surfaceBatchFailure(e,r,n,s){this.onError(new Kr({requestId:e,drops:r,retryExhausted:n.map(i=>i.uuid),cause:s}))}surfacePartialDrops(e,r){r.length>0&&this.onError(new Kr({requestId:e,drops:r,retryExhausted:[]}))}async cancelBody(e){try{await e.body?.cancel()}catch{}}};var nr="ai-capture",Ko="/i/v0/ai/batch/";var bA=new TextEncoder;function Bl(t){return bA.encode(Rt(t)).length}function H_(t,e=8388608,r=5242880){let n=[],s=[],i=[],o=0;for(let a of t){if(a===void 0)continue;let c=Bl(a);if(c>e){s.push({event:typeof a.event=="string"?a.event:"unknown",bytes:c});continue}i.length>0&&o+c>r&&(n.push(i),i=[],o=0),i.push(a),o+=c}return i.length>0&&n.push(i),{batches:n,dropped:s}}var wA=100,j_=3e4,TA=5e4,IA=50,vA=500,RA="https://us.i.posthog.com",X_=new Set;function zo(t,e){X_.has(t)||(X_.add(t),console.warn(`[PostHog] ${e}`))}function AA(t){return typeof t=="string"?t.trim():""}function MA(t){return(typeof t=="string"?t.trim():"")||void 0}function PA(t){return(typeof t=="string"?t.trim():"")||RA}function OA(t){return(Array.isArray(t)?t:[t]).filter(r=>typeof r=="string"&&r.trim().length>0)}function kA(t){if(!t)return{};let e={};for(let[n,s]of Object.entries(t))e[`$feature/${n}`]=s;let r=Object.keys(t).filter(n=>t[n]!==!1).sort();return r.length>0&&(e.$active_feature_flags=r),e}var Vo=class extends xn{get distinctIdHasSentFlagCalls(){return Object.fromEntries(this._distinctIdHasSentFlagCalls)}set distinctIdHasSentFlagCalls(e){this._distinctIdHasSentFlagCalls=new Map(Object.entries(e??{}))}constructor(e,r={}){let n=AA(e),s={...r,maxQueueSize:r.maxQueueSize??1e4,flushInterval:r.flushInterval??5e3,host:PA(r.host),personalApiKey:MA(r.secretKey??r.personalApiKey)};if(super(n,s),this._memoryStorage=new jo,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=s,this.captureMode=U_(),this.enableFullAiCapture=s.enableFullAiCapture===!0,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof s.featureFlagsPollingInterval=="number"?Math.max(s.featureFlagsPollingInterval,wA):s.featureFlagsPollingInterval===null?null:j_,typeof s.waitUntilDebounceMs=="number"&&(this.options.waitUntilDebounceMs=Math.max(s.waitUntilDebounceMs,0)),typeof s.waitUntilMaxWaitMs=="number"&&(this.options.waitUntilMaxWaitMs=Math.max(s.waitUntilMaxWaitMs,0)),!this.disabled&&(s.personalApiKey||s.flagDefinitionCacheProvider)){if(s.personalApiKey?.includes("phc_"))throw new Error('A project API key ("phc_...") was provided as secretKey or personalApiKey. Pass the project API key as the first constructor argument. For local evaluation, set secretKey (or the deprecated personalApiKey alias) to a server-only Project Secret API Key ("phs_...") or Personal API Key ("phx_...") with feature flag read access.');s.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new _o({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:s.personalApiKey,projectApiKey:n,timeout:s.requestTimeout??1e4,host:this.host,fetch:s.fetch,onError:o=>{this._events.emit("error",o)},onLoad:o=>{this._events.emit("localEvaluationFlagsLoaded",o)},onMinimalFlagCalledEvents:o=>{this._minimalFlagCalledEvents=o},customHeaders:this.getCustomHeaders(),cacheProvider:s.flagDefinitionCacheProvider,strictLocalEvaluation:s.strictLocalEvaluation,evaluationContexts:s.evaluationContexts??s.evaluationEnvironments}))}this.errorTracking=new Zt(this,s,this._logger),this._distinctIdHasSentFlagCalls=new Map,this.maxCacheSize=s.maxCacheSize||TA}enqueue(e,r,n,s){super.enqueue(e,r,n,s),this.scheduleDebouncedFlush()}_flushEventsAndSpans(e=!1){let r=this.flushWithPendingPromises();return!this._traces||e&&this._traces.throttled?r:bn([r,this._traces.flush().catch(()=>{})]).then(([n])=>{if(n.status==="rejected")throw n.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this._flushKeepingRuntimeAlive(!1)}_flushKeepingRuntimeAlive(e){let r=this._flushEventsAndSpans(e),n=this.options.waitUntil;if(n&&!this._waitUntilCycle)try{n(r.catch(()=>{}))}catch{}return r}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let o,a=new Promise(c=>{o=c});try{e(a)}catch{return}this._waitUntilCycle={resolve:o,startedAt:Date.now(),timer:void 0}}let r=Date.now()-this._waitUntilCycle.startedAt,n=this.options.waitUntilMaxWaitMs??vA,s=r>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),s)return void this.resolveWaitUntilFlush();let i=this.options.waitUntilDebounceMs??IA;this._waitUntilCycle.timer=le(()=>{this.resolveWaitUntilFlush()},i)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;return e&&(clearTimeout(e.timer),this._waitUntilCycle=void 0),e?.resolve}async resolveWaitUntilFlush(){let e=this._consumeWaitUntilCycle();try{await this._flushEventsAndSpans()}catch{}finally{e?.()}}getPersistedProperty(e){return this._memoryStorage.getProperty(e)}setPersistedProperty(e,r){return this._memoryStorage.setProperty(e,r)}fetch(e,r){return this.options.fetch?this.options.fetch(e,r):fetch(e,r)}getQueueRouteKey(e){return this.captureMode==="v1"&&$_(e)?"ai":ns}persistedQueueKeyForRoute(e){return e===nr?pe.AiCaptureQueue:e==="ai"?pe.AiQueue:pe.Queue}getActiveQueueRoutes(){let e=this.captureMode==="v1"?[ns,"ai"]:[ns];return this._aiCaptureRouteActive&&e.push(nr),e}getBatchEndpointPath(e){return e===nr?Ko:super.getBatchEndpointPath(e)}async sendBatch(e,r,n=ns){if(n===nr)return this.sendAiCaptureBatch(e,r);if(this.captureMode!=="v1"||n==="ai")return super.sendBatch(e,r,n);let s=e.filter(i=>i!==void 0);await this.getV1Sender().sendV1Batch(s)}async sendAiCaptureBatch(e,r){let{batches:n,dropped:s}=H_(e);for(let{event:i,bytes:o}of s){let a=`Event ${i} (${o} bytes) exceeds the ${8388608/1048576}MiB limit for ${Ko}, dropping.`;this._logger.error(a),this._events.emit("error",new Error(a))}for(let i of n)await this.sendAiSubBatch(i,r)}async sendAiSubBatch(e,r){try{await super.sendBatch(e,r,nr)}catch(n){if(!Cr(n))throw n;if(e.length===1){let[i]=e,a=`Event ${typeof i.event=="string"?i.event:"unknown"} (${Bl(i)} bytes) was rejected with 413 by ${Ko} on its own, dropping.`;this._logger.error(a),this._events.emit("error",new Error(a));return}let s=Math.ceil(e.length/2);await this.sendAiSubBatch(e.slice(0,s),r),await this.sendAiSubBatch(e.slice(s),r)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new Xo({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3e3,isDebug:this.isDebug},{fetch:(e,r)=>this.fetch(e,r),onError:e=>this._events.emit("error",e),compress:e=>this.compressPayload(e)})),this._v1Sender}getLibraryVersion(){return kh}get metrics(){return this._metrics||(this._metrics=new Wn(this,oo(this.options.metrics),this._logger)),this._metrics}initializeSpanContextManager(){return new Gn}hostResourceAttributes(){return{}}get _spanContextManager(){return this._spanContext||(this._spanContext=this.initializeSpanContextManager()),this._spanContext}get _tracesPipeline(){if(this.options.traces)return this._traces||(this._traces=new Kn(this,Vu(this.options.traces,this.hostResourceAttributes(),this._logger),this._logger,()=>this._tracingContext(),this._spanContextManager,()=>this.scheduleDebouncedFlush())),this._traces}_tracingContext(){let e=this.context?.get();return{distinctId:e?.distinctId,sessionId:e?.sessionId}}startSpan(e,r){return this._tracesPipeline?.startSpan(e,r)??Pt(r,this._spanContextManager.active())}withSpan(e,r,n){let s=typeof r=="function"?void 0:r,i=typeof r=="function"?r:n,o=this._tracesPipeline;return o?s?o.withSpan(e,s,i):o.withSpan(e,i):Xn(this._spanContextManager,Pt(s,this._spanContextManager.active()),i)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getEvaluationRuntime(){return"server"}getCommonEventProperties(){let e=super.getCommonEventProperties();return(this.options.isServer??!0)&&(e.$is_server=!0),e}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}_warnIfInvalidCapture(e,r,n){typeof e=="string"&&this._logger.warn(r),e.event==="$exception"&&!e._originatedFromCaptureException&&this._logger.warn(n)}_sendPreparedEvent(e,r,n,s,i){return this.addPendingPromise(this._prepareEventMessage(r,s).then(({distinctId:o,event:a,properties:c,options:u})=>{let l={timestamp:u.timestamp,disableGeoip:u.disableGeoip,uuid:u.uuid},d={distinctId:o,event:a,properties:{...c,...this.getCommonEventProperties()}};return n?this.sendImmediate(e,d,l,i):this.enqueue(e,d,l,i)}).catch(o=>{o&&console.error(o)}))}_capturePreparedEvent(e,r){return this._sendPreparedEvent("capture",e,r)}capture(e){this._warnIfInvalidCapture(e,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(e,!1)}async captureImmediate(e){return this._warnIfInvalidCapture(e,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(e,!0)}captureAi(e){if(this.disabled)return;let r=Vt(e.uuid,ue);return this._sendPreparedAiEvent({...e,uuid:r},!1),r}async captureAiImmediate(e){if(this.disabled)return;let r=Vt(e.uuid,ue);return await this._sendPreparedAiEvent({...e,uuid:r},!0),r}_sendPreparedAiEvent(e,r){return typeof e?.event=="string"&&!e.event.startsWith("$ai_")&&this._logger.debug(`captureAi called with non-AI event ${e.event}; routing it to the AI endpoint anyway.`),this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",e,r,void 0,nr)}identify({distinctId:e,properties:r={},disableGeoip:n}){let{$set:s,$set_once:i,$anon_distinct_id:o,...a}=r,l={$set:s||a,$set_once:i||{},$anon_distinct_id:o??void 0};this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:l,disableGeoip:n},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:r={},disableGeoip:n}){let{$set:s,$set_once:i,$anon_distinct_id:o,...a}=r,l={$set:s||a,$set_once:i||{},$anon_distinct_id:o??void 0};await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:l,disableGeoip:n},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:r={},propertiesOnce:n={}}){if(Object.keys(r).length===0&&Object.keys(n).length===0)return;let s={};Object.keys(r).length>0&&(s.$set=r),Object.keys(n).length>0&&(s.$set_once=n),this.capture({distinctId:e,event:"$set",properties:s})}unsetPersonProperties({distinctId:e,properties:r}){let n=OA(r);n.length!==0&&this.capture({distinctId:e,event:"$set",properties:{$unset:n}})}alias(e){this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(e){await this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}getFeatureFlagEvaluationRuntime(e){return this.featureFlagsPoller?.getEvaluationRuntimeForFlag(e)}getFeatureFlagKeysByEvaluationRuntime(e){return this.featureFlagsPoller?.getFlagKeysByEvaluationRuntime(e)??[]}async waitForLocalEvaluationReady(e=j_){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let n=setTimeout(()=>{s(),r(!1)},e),s=this._events.on("localEvaluationFlagsLoaded",i=>{clearTimeout(n),s(),r(i>0)})})}_resolveDistinctId(e,r){return typeof e=="string"?{distinctId:e,options:r}:{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,r,n={},s){if(this.disabled)return void this._logger.warn("The client is disabled");let i=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&e in this._flagOverrides){let v=this._flagOverrides[e];if(v===void 0)return;let R=this._payloadOverrides?.[e];return{key:e,enabled:v!==!1,variant:typeof v=="string"?v:void 0,payload:R}}let{groups:o,disableGeoip:a}=n,{onlyEvaluateLocally:c,personProperties:u,groupProperties:l}=n,d=this.addLocalPersonAndGroupProperties(r,o,u,l);u=d.allPersonProperties,l=d.allGroupProperties;let p=this.createFeatureFlagEvaluationContext(r,o,this.personPropertiesForLocalEvaluation(r,u),l);c==null&&(c=this.options.strictLocalEvaluation??!1);let g,m=!1,h,_,S,b,w,T,y;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let v=this.featureFlagsPoller?.featureFlagsByKey[e];if(v)try{let R=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(v,p,{matchValue:s});if(R){m=!0;let I=R.value;b=v.id,T="Evaluated locally",y=v.has_experiment,g={key:e,enabled:I!==!1,variant:typeof I=="string"?I:void 0,payload:R.payload??void 0,reason:T,reasonCode:v.active===!1?"flag_disabled":void 0}}}catch(R){if(R instanceof qe||R instanceof M)this._logger?.info(`${R.name} when computing flag locally: ${e}: ${R.message}`);else throw R}}if(!m&&!c){let v=await super.getFeatureFlagDetailsStateless(p.distinctId,p.groups,u,l,a,[e]);if(v===void 0)S=mt.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=v.minimalFlagCalledEvents===!0,h=v.requestId,_=v.evaluatedAt;let R=[];v.errorsWhileComputingFlags&&R.push(mt.ERRORS_WHILE_COMPUTING),v.quotaLimited?.includes("feature_flags")&&R.push(mt.QUOTA_LIMITED);let I=v.flags[e];if(I===void 0)R.push(mt.FLAG_MISSING);else{b=I.metadata?.id,w=I.metadata?.version,T=I.reason?.description??I.reason?.code,y=I.metadata?.has_experiment;let O;if(I.metadata?.payload!==void 0)try{O=JSON.parse(I.metadata.payload)}catch{O=I.metadata.payload}g={key:e,enabled:I.enabled,variant:I.variant??void 0,payload:O,reason:T,reasonCode:I.reason?.code}}R.length>0&&(S=R.join(","))}}if(i){let v=g===void 0?void 0:g.enabled===!1?!1:g.variant??!0,R={$feature_flag:e,$feature_flag_response:v,$feature_flag_id:b,$feature_flag_version:w,$feature_flag_reason:T,locally_evaluated:m,[`$feature/${e}`]:v,$feature_flag_request_id:h,$feature_flag_evaluated_at:m?Date.now():_};if(y!==void 0&&(R.$feature_flag_has_experiment=y),m&&this.featureFlagsPoller){let I=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();I!==void 0&&(R.$feature_flag_definitions_loaded_at=I)}S&&(R.$feature_flag_error=S),this._captureFlagCalledEventIfNeeded({distinctId:r,key:e,response:v,groups:o,disableGeoip:a,properties:R})}return g!==void 0&&this._payloadOverrides!==void 0&&e in this._payloadOverrides&&(g={...g,payload:this._payloadOverrides[e]}),g}async getFeatureFlag(e,r,n){zo("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let s=await this._getFeatureFlagResult(e,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(s!==void 0)return s.enabled===!1?!1:s.variant??!0}async getFeatureFlagPayload(e,r,n,s){if(zo("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request."),this._payloadOverrides!==void 0&&e in this._payloadOverrides)return this._payloadOverrides[e];let i=await this._getFeatureFlagResult(e,r,{...s,sendFeatureFlagEvents:!1},n);if(i!==void 0)return i.payload??null}async getFeatureFlagResult(e,r,n){let{distinctId:s,options:i}=this._resolveDistinctId(r,n);return s?this._getFeatureFlagResult(e,s,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()")}async getRemoteConfigPayload(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let r=await this._requestRemoteConfigPayload(e);if(!r)return;let n=await r.json();if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}async isFeatureEnabled(e,r,n){zo("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let s=await this._getFeatureFlagResult(e,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return s===void 0?void 0:s.enabled===!1?!1:!!(s.variant??!0)||!1}async getAllFlags(e,r){let{distinctId:n,options:s}=this._resolveDistinctId(e,r);return n?(await this.getAllFlagsAndPayloads(n,s)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(e,r){let{distinctId:n,options:s}=this._resolveDistinctId(e,r);if(!n)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:i,disableGeoip:o,flagKeys:a}=s||{},{onlyEvaluateLocally:c,personProperties:u,groupProperties:l}=s||{},d=this.addLocalPersonAndGroupProperties(n,i,u,l);u=d.allPersonProperties,l=d.allGroupProperties;let p=this.createFeatureFlagEvaluationContext(n,i,this.personPropertiesForLocalEvaluation(n,u),l);c==null&&(c=this.options.strictLocalEvaluation??!1);let g=await this.featureFlagsPoller?.getAllFlagsAndPayloads(p,a),m={},h={},_=!0;if(g&&(m=g.response,h=g.payloads,_=g.fallbackToFlags),_&&!c){let S=await super.getFeatureFlagsAndPayloadsStateless(p.distinctId,p.groups,u,l,o,a);m={...m,...S.flags||{}},h={...h,...S.payloads||{}}}return this._flagOverrides!==void 0&&(m={...m,...this._flagOverrides}),this._payloadOverrides!==void 0&&(h={...h,...this._payloadOverrides}),{featureFlags:m,featureFlagPayloads:h}}async evaluateFlags(e,r){let{distinctId:n,options:s}=this._resolveDistinctId(e,r);if(!n)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new kt({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new kt({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,flags:{}});let{groups:i,disableGeoip:o}=s||{},a=s?.flagKeys??void 0;if(a?.length===0)return new kt({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:i,disableGeoip:o,flags:{}});let{onlyEvaluateLocally:c,personProperties:u,groupProperties:l}=s||{},d=this.addLocalPersonAndGroupProperties(n,i,u,l);u=d.allPersonProperties,l=d.allGroupProperties;let p=this.createFeatureFlagEvaluationContext(n,i,this.personPropertiesForLocalEvaluation(n,u),l);c==null&&(c=this.options.strictLocalEvaluation??!1);let g=a?new Set(a):void 0,m={},h,_,S=!1,b=!1,w=await this.featureFlagsPoller?.getAllFlagsAndPayloads(p,a),T=new Set;if(w)for(let[v,R]of Object.entries(w.response)){let I=this.featureFlagsPoller?.featureFlagsByKey[v];m[v]={key:v,enabled:R!==!1,variant:typeof R=="string"?R:void 0,payload:w.payloads[v],id:I?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:I?.has_experiment},T.add(v)}let y=g!==void 0&&Array.from(g).some(v=>this.featureFlagsPoller?.featureFlagsByKey[v]===void 0);if((w?w.fallbackToFlags||y:!0)&&!c){let v=await super.getFeatureFlagDetailsStateless(p.distinctId,p.groups,u,l,o,a);if(v){this._minimalFlagCalledEvents=v.minimalFlagCalledEvents===!0,h=v.requestId,_=v.evaluatedAt,S=!!v.errorsWhileComputingFlags,b=Array.isArray(v.quotaLimited)&&v.quotaLimited.includes("feature_flags");for(let[R,I]of Object.entries(v.flags)){if(T.has(R))continue;let O;if(I.metadata?.payload!==void 0)try{O=JSON.parse(I.metadata.payload)}catch{O=I.metadata.payload}m[R]={key:R,enabled:I.enabled,variant:I.variant,payload:O,id:I.metadata?.id,version:I.metadata?.version,reason:I.reason?.description??I.reason?.code,locallyEvaluated:!1,hasExperiment:I.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[v,R]of Object.entries(this._flagOverrides)){if(R===void 0){delete m[v];continue}let I=m[v];m[v]={key:v,enabled:R!==!1,variant:typeof R=="string"?R:void 0,payload:I?.payload,id:I?.id,version:I?.version,reason:I?.reason,locallyEvaluated:I?.locallyEvaluated??!1,hasExperiment:I?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[v,R]of Object.entries(this._payloadOverrides)){let I=m[v];I&&(m[v]={...I,payload:R})}if(g!==void 0)for(let v of Object.keys(m))g.has(v)||delete m[v];return new kt({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:i,disableGeoip:o,flags:m,requestId:h,evaluatedAt:_,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:S,quotaLimited:b})}_shouldSendMinimalFlagCalledEvent(e,r){return e==="$feature_flag_called"&&this._minimalFlagCalledEvents&&r.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(e){let{distinctId:r,key:n,response:s,groups:i,disableGeoip:o,properties:a}=e,c=i&&Object.keys(i).length>0?`_${JSON.stringify(Object.entries(i).sort(([d],[p])=>d<p?-1:d>p?1:0))}`:"",u=`${n}_${s}${c}`,l=this._distinctIdHasSentFlagCalls.get(r)??new Set;if(this._distinctIdHasSentFlagCalls.delete(r),this._distinctIdHasSentFlagCalls.set(r,l),!l.has(u)){for(l.add(u);this._distinctIdHasSentFlagCalls.size>Math.max(this.maxCacheSize,1);){let d=this._distinctIdHasSentFlagCalls.keys().next().value;if(d===void 0)break;this._distinctIdHasSentFlagCalls.delete(d)}this.capture({distinctId:r,event:"$feature_flag_called",properties:a,groups:i,disableGeoip:o})}}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:e=>this._captureFlagCalledEventIfNeeded(e),logWarning:e=>{this.options.featureFlagsLogWarnings!==!1&&console.warn(`[PostHog] ${e}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:e,groupKey:r,properties:n,distinctId:s,disableGeoip:i}){this._sendPreparedEvent("capture",{distinctId:s||`$${e}_${r}`,event:"$groupidentify",properties:{$group_type:e,$group_key:r,$group_set:n||{}},disableGeoip:i},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:r,properties:n,distinctId:s,disableGeoip:i}){await this._sendPreparedEvent("capture",{distinctId:s||`$${e}_${r}`,event:"$groupidentify",properties:{$group_type:e,$group_key:r,$group_set:n||{}},disableGeoip:i},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let r=n=>Object.fromEntries(n.map(s=>[s,!0]));if(e===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=r(e);return}if(this._isFeatureFlagOverrideOptions(e)){"flags"in e&&(e.flags===!1?this._flagOverrides=void 0:Array.isArray(e.flags)?this._flagOverrides=r(e.flags):e.flags!==void 0&&(this._flagOverrides={...e.flags})),"payloads"in e&&(e.payloads===!1?this._payloadOverrides=void 0:e.payloads!==void 0&&(this._payloadOverrides={...e.payloads}));return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let r=e;if("flags"in r){let n=r.flags;if(n===!1||Array.isArray(n)||typeof n=="object"&&n!==null)return!0}if("payloads"in r){let n=r.payloads;if(n===!1||typeof n=="object"&&n!==null)return!0}return!1}withContext(e,r,n){return this.context?this.context.run(e,r,n):r()}getContext(){return this.context?.get()}enterContext(e,r){this.context?.enter(e,r)}async _shutdown(e){let r=Date.now()+(e??3e4),n=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics&&(await Mt(this._metrics.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._metrics.reset()),this._traces&&(await Mt(this._traces.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._traces.reset());try{return await super._shutdown(Math.max(0,r-Date.now()))}finally{this._distinctIdHasSentFlagCalls.clear(),n?.()}}async _requestRemoteConfigPayload(e){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},s=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let i=new AbortController;s=le(()=>{i.abort()},this.options.requestTimeout),n.signal=i.signal}try{return await this.fetch(r,n)}catch(i){this._events.emit("error",i);return}finally{s&&clearTimeout(s)}}extractPropertiesFromEvent(e,r){if(!e)return{personProperties:{},groupProperties:{}};let n={},s={};for(let[i,o]of Object.entries(e))if(Vg(o)&&r&&i in r){let a={};for(let[c,u]of Object.entries(o))a[String(c)]=String(u);s[String(i)]=a}else n[String(i)]=String(o);return{personProperties:n,groupProperties:s}}async getFeatureFlagsForEvent(e,r,n,s){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let i=s?.personProperties||{},o=s?.groupProperties||{},a=s?.flagKeys;if(s?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let u={};for(let[l,d]of Object.entries(r||{}))u[l]=String(d);return await this.getAllFlags(e,{groups:u,personProperties:i,groupProperties:o,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let u={};for(let[l,d]of Object.entries(r||{}))u[l]=String(d);return await this.getAllFlags(e,{groups:u,personProperties:i,groupProperties:o,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(e,r,i,o,n)).flags}addLocalPersonAndGroupProperties(e,r,n,s){let i={...n||{}},o={};if(r)for(let a of Object.keys(r))o[a]={$group_key:r[a],...s?.[a]||{}};return{allPersonProperties:i,allGroupProperties:o}}personPropertiesForLocalEvaluation(e,r){return{distinct_id:e,...r||{}}}createFeatureFlagEvaluationContext(e,r,n,s){return{distinctId:e,groups:r||{},personProperties:n||{},groupProperties:s||{},evaluationCache:{}}}captureException(e,r,n,s,i){if(!Zt.isPreviouslyCapturedError(e)){let o=new Error("PostHog syntheticException");this.addPendingPromise(Zt.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:o},r,n).then(a=>this._capturePreparedEvent({...a,uuid:s,flags:i},!1)))}}async captureExceptionImmediate(e,r,n,s){if(!Zt.isPreviouslyCapturedError(e)){let i=new Error("PostHog syntheticException");return this.addPendingPromise(Zt.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:i},r,n).then(o=>this.captureImmediate({...o,flags:s})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,r={}){let{distinctId:n,event:s,properties:i,groups:o,flags:a,sendFeatureFlags:c,timestamp:u,disableGeoip:l,uuid:d}=e,p=this.context?.get(),g=r.includeContextProperties??!0,m=n||p?.distinctId,h=g?{...this.props,...p?.properties||{},...i||{}}:{...i||{}};s==="$exception"&&!("$trace_id"in h||"$span_id"in h)&&Object.assign(h,await L_()),m||(m=ue(),h.$process_person_profile=!1),g&&p?.sessionId&&!h.$session_id&&(h.$session_id=p.sessionId);let _=this._shouldSendMinimalFlagCalledEvent(s,h)?Pn(h):h,S=this._runBeforeSend({distinctId:m,event:s,properties:_,groups:o,flags:a,sendFeatureFlags:c,timestamp:u,disableGeoip:l,uuid:d});if(!S)return Promise.reject(null);let b=await Promise.resolve().then(async()=>{if(a)return c&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),a._getEventProperties();if(c){zo("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead \u2014 it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let w=typeof c=="object"?c:void 0,T=await this.getFeatureFlagsForEvent(S.distinctId,o,l,w);return kA(T)}return{}}).catch(()=>({})).then(w=>{let T=S.groups||o;return{...w,...S.properties||{},...T!==void 0&&Object.keys(T).length>0?{$groups:T}:{}}});return S.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof b.$raw_user_agent=="string"&&qg(b.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(S.event="$bot_pageview",b.$browser_type="bot"),{distinctId:S.distinctId,event:S.event,properties:b,options:{timestamp:S.timestamp,disableGeoip:S.disableGeoip,uuid:S.uuid}}}_runBeforeSend(e){let r=this.options.before_send;if(!r)return e;let n=Array.isArray(r)?r:[r],s=e;for(let i of n)try{if(s=i(s),!s)return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!s.properties||Object.keys(s.properties).length===0){let o=`Event '${s.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(o)}}catch(o){return this._logger.error(`Error in before_send function for event '${e.event}':`,o),null}return s}};var K_=require("node:async_hooks"),Yo=class{constructor(){this.storage=new K_.AsyncLocalStorage}get(){return this.storage.getStore()}run(e,r,n){return this.storage.run(this.resolve(e,n),r)}enter(e,r){this.storage.enterWith(this.resolve(e,r))}resolve(e,r){if(r?.fresh===!0)return e;let n=this.get()||{};return{distinctId:e.distinctId??n.distinctId,sessionId:e.sessionId??n.sessionId,properties:{...n.properties||{},...e.properties||{}}}}};var G_=require("node:async_hooks"),qo=class{active(){return this._storage.getStore()}with(e,r){return this._storage.run(e,r)}constructor(){this._storage=new G_.AsyncLocalStorage}};var z_=require("node:zlib"),V_=require("node:util"),xA=(0,V_.promisify)(z_.gzip);async function Y_(t,e=!0){try{let r=await xA(t);return new Uint8Array(r)}catch(r){return e&&console.error("Failed to gzip compress data",r),null}}var Jo=require("node:os");function q_(){let t,e;try{t=(0,Jo.platform)(),e=(0,Jo.release)()}catch{}return Lu(t,e)}var J_="posthog-node";function NA(t,{organization:e,projectId:r,prefix:n,severityAllowList:s=["error"],sendExceptionsToPostHog:i=!0}={}){return o=>{if(!(s==="*"||s.includes(o.level)))return o;o.tags||(o.tags={});let c=o.tags[Wl.POSTHOG_ID_TAG];if(c===void 0)return o;let u=t.options.host??"https://us.i.posthog.com",l=new URL(`/project/${t.apiKey}/person/${c}`,u).toString();o.tags["PostHog Person URL"]=l;let d=o.exception?.values||[],p=d.map(h=>({...h,stacktrace:h.stacktrace?{...h.stacktrace,type:"raw",frames:(h.stacktrace.frames||[]).map(_=>({..._,platform:"node:javascript"}))}:void 0})),g={$exception_message:d[0]?.value||o.message,$exception_type:d[0]?.type,$exception_level:o.level,$exception_list:p,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:d[0]?.value||o.message,$sentry_exception_type:d[0]?.type,$sentry_tags:o.tags},m=J.getInjectedReleaseId();return m&&(g.$release_id=m),e&&r&&(g.$sentry_url=(n||"https://sentry.io/organizations/")+e+"/issues/?project="+r+"&query="+o.event_id),i&&t.capture({event:"$exception",distinctId:c,properties:g}),o}}var Wl=class{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(e,r,n,s,i){this.name=J_,this.name=J_,this.setupOnce=function(o,a){let c=a()?.getClient()?.getDsn()?.projectId;o(NA(e,{organization:r,projectId:c,prefix:n,severityAllowList:s,sendExceptionsToPostHog:i??!0}))}}};var Qo=class extends Vo{getLibraryId(){return"posthog-node"}compressPayload(e){return Y_(e,this.isDebug)}initializeContext(){return new Yo}initializeSpanContextManager(){return new qo}hostResourceAttributes(){return q_()}createErrorPropertiesBuilder(){return new J.ErrorPropertiesBuilder([new J.EventCoercer,new J.ErrorCoercer,new J.ObjectCoercer,new J.StringCoercer,new J.PrimitiveCoercer],J.createStackParser("node:javascript",J.nodeStackLineParser),[jg(),e=>Rh(e,void 0,this._logger),Oh()])}};ja();Va();za();qa();var wH=300*1e3,TH=3600*1e3;A();var jl=null,CA=!1,DA=3e4,Zo=null;function Z_(){let t=Date.now();if(Zo&&t<Zo.expiresAt)return Zo.value;let e=Ds(process.env,nn());return Zo={value:e,expiresAt:t+DA},e}var FA=!1;function LA(){if(!jl){let t=FA&&gf(process.env)&&Z_();jl=new Qo(Us(),{host:$s(),flushAt:20,flushInterval:1e4,disableGeoip:!1,enableExceptionAutocapture:t,before_send:GA})}return jl}var UA=6e4,$A=500,ss=new Map;function BA(t,e,r){let n="";try{let s=(r||"").split(`
|
|
42
|
-
`).map(
|
|
43
|
-
`);return}LA().capture({distinctId:Fs(),event:t,properties:n})}var VA=["agent-cost-report","babysit","design-is","do","handoff","how-it-works","knowledge-agent","learn-codebase","make-plan","mem-search","mode-creator","oh-my-issues","pathfinder","screenpipe","smart-explore","standup","timeline-report","weekly-digests","what-the","wowerpoint"],YA=new Set(VA),eE={skill_id:"other",skill_source:"third_party"};function tE(t){let e=qA(t);return e&&YA.has(e)?{skill_id:e,skill_source:"first_party"}:eE}function rE(t,e){if(t==="Skill"&&!(!e||typeof e!="object"))return e.skill}function qA(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase();if(!e)return null;e=e.replace(/^\/+/,"");let r=e.lastIndexOf(":");return r!==-1&&(e=e.slice(r+1).replace(/^\/+/,"")),e||null}ta();var sE=null,QA=new Set(["SetTodoList","TodoList","TaskList","TaskOutput","TaskStop","CronCreate","CronList","CronDelete"]),iE=new Map;function ZA(t){let e=iE.get(t);if(e!==void 0)return e;let r=null;try{r=new RegExp(t)}catch(n){f.warn("INGEST","Invalid MEMINDEX_SKIP_BASH_PATTERNS regex \u2014 ignoring",{pattern:t,error:n instanceof Error?n.message:String(n)})}return iE.set(t,r),r}function eM(t,e){if(!e||typeof e!="object")return"";let r=e,n=t==="exec_command"?r.cmd:t==="Bash"||t==="PowerShell"?r.command:void 0;return typeof n=="string"?n:""}function tM(){if(!sE)throw new Error("ingest helpers used before setIngestContext() \u2014 wiring bug");return sE}async function oE(t,e={}){if(Gr(t.toolName))return{ok:!0,status:"skipped",reason:"memory_retrieval"};let{sessionManager:r,dbManager:n,eventBroadcaster:s,ensureGeneratorRunning:i}=tM(),o=G(t.platformSource),a=typeof t.cwd=="string"?t.cwd:"",c=a.trim()?await an(a):null,u=c?.primary||"unknown",l=z.loadFromFile(ge);if(a&&Gs(a,l.MEMINDEX_EXCLUDED_PROJECTS))return{ok:!0,status:"skipped",reason:"project_excluded"};if(vt(t.toolName,l.MEMINDEX_SKIP_TOOLS)){if(t.toolName==="Skill"){let{skill_id:y,skill_source:P}=tE(rE(t.toolName,t.toolInput));Hl("skill_invoked",{skill_id:y,skill_source:P,skill_trigger:"tool",ide:o})}return{ok:!0,status:"skipped",reason:"tool_excluded"}}if(o==="kimi"&&QA.has(t.toolName))return{ok:!0,status:"skipped",reason:"tool_excluded"};let d=l.MEMINDEX_SKIP_BASH_PATTERNS.trim(),p=d?eM(t.toolName,t.toolInput):"";if(p){let y=ZA(d);if(y&&y.test(p))return{ok:!0,status:"skipped",reason:"bash_pattern_excluded"}}let g=vr(t.agentId,t.agentType,l);if(g.skip)return{ok:!0,status:"skipped",reason:g.reason};if(new Set(["Edit","Write","Read","NotebookEdit"]).has(t.toolName)&&t.toolInput&&typeof t.toolInput=="object"){let y=t.toolInput,P=y.file_path||y.notebook_path;if(P&&P.includes("session-memory"))return{ok:!0,status:"skipped",reason:"session_memory_meta"};if(P&&Wg(P))return{ok:!0,status:"skipped",reason:"endless_mode_bottle"}}let h=n.getSessionStore(),_,S;try{_=h.createSDKSession(t.contentSessionId,u,"",void 0,o),a&&h.setSessionCwd(_,a,c?.keySource),S=h.getPromptNumberFromUserPrompts(t.contentSessionId,_,t.enqueuedAtEpochMs)}catch(y){let P=y instanceof Error?y.message:String(y);return f.error("INGEST","Observation session resolution failed",{contentSessionId:t.contentSessionId,toolName:t.toolName},y instanceof Error?y:new Error(P)),{ok:!1,reason:P,status:500}}if(!xi.checkUserPromptPrivacy(h,t.contentSessionId,S,"observation",_,{tool_name:t.toolName}).allow)return{ok:!0,status:"skipped",reason:"private"};let w=t.toolInput!==void 0?we(JSON.stringify(t.toolInput)):"{}",T=t.toolResponse!==void 0?we(JSON.stringify(t.toolResponse)):"{}";if(t.toolUseId)try{h.upsertToolUse({toolUseId:t.toolUseId,contentSessionId:t.contentSessionId,sessionDbId:_,project:u,platformSource:o,toolName:t.toolName,toolInput:w,toolResponse:T,cwd:a||null,promptNumber:S,agentType:typeof t.agentType=="string"?t.agentType:null,agentId:typeof t.agentId=="string"?t.agentId:null,orGenerationId:typeof t.orGenerationId=="string"?t.orGenerationId:null,orSessionId:typeof t.orSessionId=="string"?t.orSessionId:null})}catch(y){f.warn("INGEST","tool_uses backup write failed (observation still queued)",{sessionId:_,toolName:t.toolName,toolUseId:t.toolUseId},y instanceof Error?y:new Error(String(y)))}return ea(t.toolName)?{ok:!0,status:"skipped",reason:"explicit_memory_write"}:(r.queueObservation(_,{tool_name:t.toolName,tool_input:w,tool_response:T,prompt_number:S,cwd:a||(f.error("INGEST","Missing cwd when ingesting observation",{sessionId:_,toolName:t.toolName}),""),agentId:typeof t.agentId=="string"?t.agentId:void 0,agentType:typeof t.agentType=="string"?t.agentType:void 0,toolUseId:typeof t.toolUseId=="string"?t.toolUseId:void 0},t.enqueuedAtEpochMs),e.markHandedOff?.(),await i?.(_,"observation"),s.broadcastObservationQueued(_),{ok:!0,sessionDbId:_})}var rM=/agent-transcripts[/\\]([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:[/\\]|$)/i;function nM(t){let e=typeof t.agentId=="string"?t.agentId.trim():"";return e&&e!=="*"?e:t.path.match(rM)?.[1]}var os=class extends Error{constructor(e,r){super(`session init failed for transcript session ${e}: ${r instanceof Error?r.message:String(r)}`),this.name="TranscriptAnchorError",this.cause=r}},as=class extends Error{constructor(e,r){super(`observation not accepted for transcript session ${e}: ${r instanceof Error?r.message:String(r)}`),this.name="TranscriptObservationError",this.cause=r}},sr=class extends Error{constructor(e,r){super(`transcript event not persisted for session ${e}: ${r instanceof Error?r.message:String(r)}`),this.name="TranscriptSpoolError",this.cause=r}},sM=4096,iM=64,ra=class{constructor(e="in-process"){this.observationTransport=e}observationTransport;sessions=new Map;fileContexts=new Set;fileSessionKeys=new WeakMap;registerFileContext(e){this.fileContexts.add(e)}pendingToolOwners=new WeakMap;subagentSessionKeys=new Set;resetFileContext(e){for(let r of this.sessionKeysOf(e)){let n=this.sessions.get(r);n&&n.cwd===e.cwd&&(n.cwd=void 0)}this.retireFileContext(e),e.cwd=void 0,e.sessionId=void 0}retireFileContext(e){for(let r of this.sessionKeysOf(e)){let n=this.sessions.get(r)?.pendingTools;for(let[s,i]of n??[])this.pendingToolOwners.get(i)===e&&n.delete(s)}this.fileContexts.delete(e),this.fileSessionKeys.delete(e),e.pendingTools={}}sessionKeysOf(e){return new Set([...Object.keys(e.pendingTools??{}),...this.fileSessionKeys.get(e)??[]])}async processEntry(e,r,n,s,i){i&&this.registerFileContext(i);for(let o of n.events)_n(e,o.match,n)&&await this.handleEvent(e,r,n,o,s??void 0,i)}getSessionKey(e,r){return`${e.name}:${r}`}getOrCreateSession(e,r){let n=this.getSessionKey(e,r),s=this.sessions.get(n);return s||(s={sessionId:r,platformSource:G(e.name),...this.subagentSessionKeys.has(n)?{isSubagent:!0}:{}},this.sessions.set(n,s)),s}rememberSubagentSession(e){if(this.subagentSessionKeys.delete(e),this.subagentSessionKeys.add(e),this.subagentSessionKeys.size>sM){let r=this.subagentSessionKeys.values().next().value;r!==void 0&&this.subagentSessionKeys.delete(r)}}async primeSessionContext(e,r,n,s,i){for(let o of n.events)o.action!=="session_context"||!_n(e,o.match,n)||await this.handleEvent(e,r,n,o,s??void 0,i)}resolveSessionId(e,r,n,s,i){let o={watch:r,schema:n},a=s.fields?.sessionId??(n.sessionIdPath?{path:n.sessionIdPath}:void 0),c=Ir(a,e,o);return typeof c=="string"&&c.trim()?c:typeof c=="number"?String(c):i&&i.trim()?i:null}resolveCwd(e,r,n,s,i){let o={watch:r,schema:n,session:i},a=s.fields?.cwd??(n.cwdPath?{path:n.cwdPath}:void 0),c=Ir(a,e,o);return typeof c=="string"&&c.trim()?c:r.workspace?r.workspace:i.cwd}resolveProjectWithoutGit(e,r,n,s,i){let o={watch:r,schema:n,session:i},a=s.fields?.project??(n.projectPath?{path:n.projectPath}:void 0),c=Ir(a,e,o);return typeof c=="string"&&c.trim()?c:r.project}async lookUpProjectFromGit(e,r,n,s,i,o){let a=this.sessions.get(this.getSessionKey(r,i)),c={...a,cwd:a?.cwd??o?.cwd};if(this.resolveProjectWithoutGit(e,r,n,s,c))return;let u=this.resolveCwd(e,r,n,s,c);return u?(await an(u)).primary:void 0}async handleEvent(e,r,n,s,i,o){let a=this.resolveSessionId(e,r,n,s,o?.sessionId??i);if(!a){f.debug("TRANSCRIPT","Skipping event without sessionId",{event:s.name,watch:r.name});return}o&&(o.sessionId=a);let c=await this.lookUpProjectFromGit(e,r,n,s,a,o),u=this.getOrCreateSession(r,a),l=this.getSessionKey(r,a);if(o){let m=this.fileSessionKeys.get(o)??new Set;m.add(l),this.fileSessionKeys.set(o,m)}if(o?.pendingTools?.[l]){u.pendingTools??=new Map;for(let[m,h]of Object.entries(o.pendingTools[l]))this.pendingToolOwners.set(h,o),u.pendingTools.has(m)||u.pendingTools.set(m,h)}!u.cwd&&o?.cwd&&(u.cwd=o.cwd);let d=this.resolveCwd(e,r,n,s,u);d&&(u.cwd=d);let p=this.resolveProjectWithoutGit(e,r,n,s,u)??(u.cwd?c:u.project);if(p&&(u.project=p),r.subagentSource&&!u.isSubagent){let m=hn(e,r.subagentSource.path);m!=null&&(u.isSubagent=!0,this.rememberSubagentSession(this.getSessionKey(r,a)))}if(r.subagentOnly&&!u.isSubagent&&s.action!=="session_context"&&s.action!=="session_end")return;let g=Lg(s.fields,e,{watch:r,schema:n,session:u});s.action==="session_context"&&this.applySessionContext(u,g),o&&u.cwd&&(o.cwd=u.cwd);try{switch(s.action){case"session_context":break;case"session_init":await this.handleSessionInit(u,g),r.context?.updateOn?.includes("session_start")&&await this.updateContext(u,r);break;case"user_message":{let m=this.resolveMessageText(g.message)??this.resolveMessageText(g.prompt);m&&await this.anchorUserPrompt(u,m);break}case"assistant_message":u.lastAssistantMessage=this.resolveMessageText(g.message)??u.lastAssistantMessage;break;case"tool_use":await this.handleToolUse(u,r,g,o);break;case"tool_result":await this.handleToolResult(u,r,g,o);break;case"observation":await this.sendObservation(u,r,g);break;case"file_edit":await this.sendFileEdit(u,g);break;case"session_end":await this.handleSessionEnd(u,r);break;default:break}}finally{o&&this.snapshotPendingTools(o,u,l,s.action==="session_end")}}snapshotPendingTools(e,r,n,s){let i=s?{}:{...e.pendingTools?.[n]};for(let[a,c]of r.pendingTools??[])this.pendingToolOwners.get(c)===e&&(i[a]=c);e.pendingTools={...e.pendingTools,[n]:i},Object.keys(i).length===0&&delete e.pendingTools[n];let o=Object.entries(e.pendingTools).flatMap(([a,c])=>Object.keys(c).map(u=>[a,u]));for(let[a,c]of o.slice(0,Math.max(0,o.length-iM))){let u=e.pendingTools[a],l=u[c];delete u[c],Object.keys(u).length===0&&delete e.pendingTools[a];let d=this.sessions.get(a)?.pendingTools;d?.get(c)===l&&d.delete(c)}}applySessionContext(e,r){let n=typeof r.cwd=="string"?r.cwd:void 0,s=typeof r.project=="string"?r.project:void 0;n&&(e.cwd=n),s&&(e.project=s)}resolveMessageText(e){if(typeof e=="string")return e;if(!Array.isArray(e))return;let r=[];for(let n of e)n&&typeof n=="object"&&typeof n.text=="string"&&r.push(n.text);return r.length>0?r.join(`
|
|
44
|
-
`):void 0}async handleSessionInit(e,r){let n=typeof r.prompt=="string"?r.prompt:"";await this.anchorUserPrompt(e,n)}async anchorUserPrompt(e,r){r&&(e.lastUserMessage=r);let n=e.cwd;if(!n){this.skipWithoutCwd(e,"user prompt");return}try{await
|
|
45
|
-
`);for(let s of n){let
|
|
46
|
-
`);return s<0?null:n.slice(0,s)}async function pM(t,e,r){try{let n=await _E(t,e,r);if(n===null)return null;let s=JSON.parse(n);for(let i of["timestamp","time","createdAt"]){let o=s?.[i],a=typeof o=="number"?o<1e12?o*1e3:o:typeof o=="string"?Date.parse(o):Number.NaN;if(Number.isFinite(a)&&a>0)return a}return null}catch{return null}}function ia(t){return`${t.dev}:${t.ino}`}function gM(t){try{return(0,H.statSync)(t),!1}catch(e){let r=e.code;return r==="ENOENT"||r==="ENOTDIR"}}var mM=4096;function Gl(t,e,r){let n;try{if(n=(0,H.openSync)(t,"r"),ia((0,H.fstatSync)(n))!==r)return null;let s=Math.max(0,e-mM),i=Buffer.alloc(e-s);return(0,H.readSync)(n,i,0,i.length,s)<i.length?null:(0,mE.createHash)("sha256").update(i).digest("hex")}catch(s){return f.debug("TRANSCRIPT","Could not fingerprint a transcript checkpoint",{file:t},s instanceof Error?s:void 0),null}finally{n!==void 0&&(0,H.closeSync)(n)}}function EE(t,e,r,n,s){return r<n?!1:s===void 0?!0:Gl(t,n,e)===s}async function oa(t,e,r){let n=await(0,hE.open)(t,"r");try{let s=Buffer.alloc(r),{bytesRead:i}=await n.read(s,0,r,e);return s.subarray(0,i)}finally{await n.close()}}var Kl=class{constructor(e,r,n,s,i="",o=0,a,c,u,l){this.filePath=e;this.onLine=n;this.onOffset=s;this.onReset=u;this.fileIdentity=a,this.checkpointFingerprint=c,this.isZstd=e.endsWith(sa),this.zstdPartialBytes=this.isZstd&&l?Buffer.from(l,"base64"):void 0,this.tailState={offset:r,readOffset:r,partial:this.isZstd?i:""},this.frameLinesDone=this.isZstd?o:0}filePath;onLine;onOffset;onReset;watcher=null;tailState;readTask=null;readPending=!1;closed=!1;isZstd;pendingRecord=Buffer.alloc(0);frameLinesDone;zstdPartialBytes;fileIdentity;checkpointFingerprint;start(){this.requestRead();try{this.watcher=(0,H.watch)(this.filePath,{persistent:!0},()=>{this.requestRead()})}catch(e){f.debug("WORKER","Failed to watch transcript file",{file:this.filePath},e instanceof Error?e:void 0),this.watcher=null}}close(){this.closed=!0,this.watcher?.close(),this.watcher=null}poke(){this.requestRead()}requestRead(){if(!this.closed){if(this.readTask){this.readPending=!0;return}this.readTask=this.drainReads().finally(()=>{this.readTask=null,this.readPending&&this.requestRead()})}}async drainReads(){do this.readPending=!1,await this.readNewData().catch(()=>{}),this.readPending&&await cs();while(this.readPending&&!this.closed)}async readNewData(){if(!(0,H.existsSync)(this.filePath))return;let e=0,r;try{let o=(0,H.statSync)(this.filePath);e=o.size,r=ia(o)}catch(o){f.debug("WORKER","Failed to stat transcript file",{file:this.filePath},o instanceof Error?o:void 0);return}let n=r!==this.fileIdentity,s=!1;n&&this.fileIdentity!==void 0&&(EE(this.filePath,r,e,this.tailState.offset,this.checkpointFingerprint)?(this.tailState.readOffset=this.tailState.offset,this.pendingRecord=Buffer.alloc(0)):s=!0),this.fileIdentity=r;let i=s||e<this.tailState.readOffset;if(i&&(this.onReset?.(),this.tailState.offset=0,this.tailState.readOffset=0,this.tailState.partial="",this.zstdPartialBytes=void 0,this.pendingRecord=Buffer.alloc(0),this.frameLinesDone=0),e===this.tailState.readOffset){(n||i)&&this.checkpoint(this.tailState.offset,this.tailState.partial);return}this.isZstd?await this.readNewZstdFrames(e):await this.readNewJsonl(e)}checkpoint(e,r="",n=this.zstdPartialBytes){this.zstdPartialBytes=n,this.tailState.offset=e,this.tailState.partial=r,this.checkpointFingerprint=this.fileIdentity===void 0?void 0:Gl(this.filePath,e,this.fileIdentity)??void 0,this.onOffset(e,r,this.frameLinesDone,this.fileIdentity,this.checkpointFingerprint,this.zstdPartialBytes?.toString("base64"))}async readNewJsonl(e){let r=this.tailState.readOffset,n;try{n=await oa(this.filePath,r,Math.min(e-r,fE))}catch(c){f.debug("WORKER","Failed to read transcript file",{file:this.filePath},c instanceof Error?c:void 0);return}if(n.length===0)return;this.tailState.readOffset=r+n.length;let s=this.pendingRecord.length>0?Buffer.concat([this.pendingRecord,n]):n,i=this.tailState.offset,o=0,a=0;for(let c=s.indexOf(10);c!==-1;c=s.indexOf(10,o)){if(this.closed){this.checkpoint(i+o);return}let u=s.toString("utf8",o,c).trim();if(u)try{await this.onLine(u)}catch{this.pendingRecord=Buffer.alloc(0),this.tailState.readOffset=i+o,this.checkpoint(i+o);return}o=c+1,this.tailState.offset=i+o,u&&++a%pE===0&&(this.checkpoint(this.tailState.offset),await cs())}this.pendingRecord=Buffer.from(s.subarray(o)),this.checkpoint(i+o),this.tailState.readOffset<e&&(this.readPending=!0)}async readNewZstdFrames(e){let r=this.tailState.offset,n,s;try{if(n=na(this.filePath,r,e,fE),n.frames.length===0)return;let o=n.frames[n.frames.length-1].end;if(s=await oa(this.filePath,r,o-r),s.length<o-r)return}catch(o){f.warn("TRANSCRIPT","Failed to read zstd transcript frames",{file:this.filePath,error:o instanceof Error?o.message:String(o)});return}let i=0;for(let o of n.frames){let a;try{a=Xl(s,{start:o.start-r,end:o.end-r})}catch{this.checkpoint(this.tailState.offset,this.tailState.partial);return}let c=this.tailState.partial,u=this.zstdPartialBytes,l=Buffer.concat([u??Buffer.from(c,"utf8"),a]),d=[],p=0;for(let _=l.indexOf(10);_!==-1;_=l.indexOf(10,p))d.push(l.toString("utf8",p,_)),p=_+1;let g=l.subarray(p),m=g.toString("utf8"),h=Buffer.from(m,"utf8").equals(g)?void 0:Buffer.from(g);for(let _=this.frameLinesDone;_<d.length;_++){if(this.closed){this.frameLinesDone=_,this.checkpoint(o.start,c,u);return}let S=d[_].trim();if(S){try{await this.onLine(S)}catch{this.frameLinesDone=_,this.tailState.readOffset=o.start,this.checkpoint(o.start,c,u);return}++i%pE===0&&await cs()}}this.frameLinesDone=0,this.tailState.offset=o.end,this.tailState.readOffset=o.end,this.tailState.partial=h?"":m,this.zstdPartialBytes=h}this.checkpoint(this.tailState.offset,this.tailState.partial),n.tornStart===null&&this.tailState.offset<e&&(this.readPending=!0)}},aa=class{constructor(e,r,n="in-process"){this.config=e;this.statePath=r;this.processor=new ra(n),this.state=Nd(r)}config;statePath;processor;tailers=new Map;state;fileContexts=new Map;retirementCandidates=new Set;retirementTimer=null;missingTranscriptGraceMs=cM;rootWatchers=[];rootWatchSettleTimers=new Set;startedAtMs=0;warnedZstdUnsupported=!1;startingTailers=new Set;stopped=!1;async start(){this.stopped=!1,this.startedAtMs=Date.now();for(let e of this.config.watches)await this.setupWatch(e);if(!this.stopped)for(let e of Object.keys(this.state.pendingTools??{}))this.tailers.has(e)||this.scheduleRetirementCheck(e)}stop(){this.stopped=!0;for(let e of this.tailers.values())e.close();this.tailers.clear();for(let e of this.rootWatchers)e.close();this.rootWatchers=[];for(let e of this.rootWatchSettleTimers)clearTimeout(e);this.rootWatchSettleTimers.clear(),this.retirementTimer&&clearTimeout(this.retirementTimer),this.retirementTimer=null,this.retirementCandidates.clear()}async setupWatch(e){let r=this.resolveSchema(e);if(!r){f.warn("TRANSCRIPT","Missing schema for watch",{watch:e.name});return}let n=oe(e.path),s=this.resolveWatchFiles(n);for(let o of s)this.getFileContext(o);let i={stateChanged:!1};for(let o of s)await this.addTailer(o,e,r,!1,i),await cs();i.stateChanged&&Zr(this.statePath,this.state),this.watchTranscriptRoot(n,e,r)}watchTranscriptRoot(e,r,n,s=!1){let i=this.selectWatchRoot(e);if(!i){f.debug("TRANSCRIPT","Watch root does not exist, skipping fs.watch",{watch:r.name,path:e});return}let{root:o,recursive:a}=i;try{let c=(0,H.watch)(o,{recursive:a,persistent:!0},(u,l)=>{a?this.handleRootWatchEvent(o,e,r,n,l):this.handleAncestorWatchEvent(c,o,e,r,n,l)});this.rootWatchers.push(c),(s||!a)&&this.settleRootWatch(c,o,a,e,r,n),f.info("TRANSCRIPT",a?"Watching transcript root recursively":"Transcript root does not exist yet; watching its closest existing directory",{watch:r.name,watchRoot:o})}catch(c){f.warn("TRANSCRIPT","Failed to start fs.watch on transcript root",{watch:r.name,watchRoot:o},c instanceof Error?c:void 0)}}handleRootWatchEvent(e,r,n,s,i){if(!i)return;let o=(0,q.resolve)(e,i).replace(/\\/g,"/"),a=this.tailers.get(o);if(a){if(!(0,H.existsSync)(o)){a.close(),this.tailers.delete(o),this.scheduleRetirementCheck(o);return}a.poke();return}this.touchesLiteralPrefix(o,r)&&this.addDiscoveredTailers(r,n,s)}handleAncestorWatchEvent(e,r,n,s,i,o){if(this.stopped||!this.rootWatchers.includes(e)||o&&!this.touchesLiteralPrefix((0,q.resolve)(r,o),n))return;let a=this.selectWatchRoot(n);a&&a.root===r&&!a.recursive||(e.close(),this.rootWatchers=this.rootWatchers.filter(c=>c!==e),this.watchTranscriptRoot(n,s,i,!0),this.addDiscoveredTailers(n,s,i))}settleRootWatch(e,r,n,s,i,o){let a=setTimeout(()=>{this.rootWatchSettleTimers.delete(a),!(this.stopped||!this.rootWatchers.includes(e))&&(n?this.addDiscoveredTailers(s,i,o):this.handleAncestorWatchEvent(e,r,s,i,o,null))},dM);this.rootWatchSettleTimers.add(a)}getFileContext(e){let r=this.fileContexts.get(e);return r||(r={cwd:this.state.cwds?.[e],pendingTools:this.state.pendingTools?.[e],isCurrent:()=>this.isCheckpointedFile(e)},this.fileContexts.set(e,r)),this.processor.registerFileContext(r),r}isCheckpointedFile(e){try{let r=(0,H.statSync)(e);return ia(r)===this.state.fileIdentities?.[e]&&r.size>=(this.state.offsets[e]??0)}catch{return!1}}scheduleRetirementCheck(e){this.retirementCandidates.add(e),this.retirementTimer??=setTimeout(()=>this.retireMissingTranscripts(),this.missingTranscriptGraceMs)}retireMissingTranscripts(){this.retirementTimer=null;let e=[...this.retirementCandidates];if(this.retirementCandidates.clear(),this.stopped)return;let r=!1;for(let n of e){if(this.tailers.has(n)||!gM(n))continue;let s=this.fileContexts.get(n);s&&this.processor.retireFileContext(s),this.fileContexts.delete(n),this.state.pendingTools?.[n]&&(delete this.state.pendingTools[n],r=!0)}r&&Zr(this.statePath,this.state)}forgetReplacedTranscript(e,r){this.processor.resetFileContext(r),delete this.state.pendingTools?.[e],delete this.state.cwds?.[e]}addDiscoveredTailers(e,r,n){for(let s of this.resolveWatchFiles(e))this.tailers.has(s)||this.addTailer(s,r,n,!0).catch(i=>{f.debug("TRANSCRIPT","Failed to add transcript tailer",{file:s,watch:r.name},i instanceof Error?i:void 0)})}touchesLiteralPrefix(e,r){let n=e.replace(/\\/g,"/"),s=(0,q.resolve)(this.literalWatchPrefix(r)).replace(/\\/g,"/"),i=(o,a)=>o.startsWith(a.endsWith("/")?a:a+"/");return n===s||i(n,s)||i(s,n)}literalWatchPrefix(e){let r=e;if(this.hasGlob(e)){let n=e.split(/[/\\]/),s=[];for(let i of n){if(/[*?[\]{}()]/.test(i))break;s.push(i)}if(s.length===0||s.length===1&&s[0]==="")return"";r=s.join(q.sep)}return r}selectWatchRoot(e){let r=this.literalWatchPrefix(e);if(!r)return null;let n=(0,q.resolve)(r);try{return{root:(0,H.statSync)(n).isDirectory()?n:(0,q.resolve)(n,".."),recursive:!0}}catch{}for(let s=(0,q.resolve)(n,"..");(0,q.resolve)(s,"..")!==s;s=(0,q.resolve)(s,".."))try{if((0,H.statSync)(s).isDirectory())return{root:s,recursive:!1}}catch{}return null}resolveSchema(e){return typeof e.schema=="string"?this.config.schemas?.[e.schema]??null:e.schema}resolveWatchFiles(e){if(this.hasGlob(e))return this.scanGlob(this.normalizeGlobPattern(e));if((0,H.existsSync)(e))try{return(0,H.statSync)(e).isDirectory()?[...this.scanGlob(this.normalizeGlobPattern((0,q.join)(e,"**","*.jsonl"))),...this.scanGlob(this.normalizeGlobPattern((0,q.join)(e,"**",`*${sa}`)))]:[e]}catch(r){return f.debug("WORKER","Failed to stat watch path",{path:e},r instanceof Error?r:void 0),[]}return[]}scanGlob(e){try{return Array.from(new Bun.Glob(e).scanSync({absolute:!0,onlyFiles:!0,dot:!0}))}catch(r){let n=r?.code;if(n==="ENOENT"||n==="ENOTDIR")return[];throw r}}normalizeGlobPattern(e){return e.replace(/\\/g,"/")}hasGlob(e){return/[*?[\]{}()]/.test(e)}async addTailer(e,r,n,s=!1,i){if(e=oe(e),!(this.tailers.has(e)||this.startingTailers.has(e))){this.startingTailers.add(e);try{await this.startTailer(e,r,n,s,i)}finally{this.startingTailers.delete(e)}}}async startTailer(e,r,n,s,i){let o=e.endsWith(sa);if(o&&!uE()){this.warnedZstdUnsupported||(this.warnedZstdUnsupported=!0,f.warn("TRANSCRIPT","Skipping zstd transcripts: this runtime has no zlib.zstdDecompressSync (update Bun or Node)",{file:e}));return}let a=this.extractSessionIdFromPath(e),c=this.getFileContext(e),u=this.state.offsets[e],l=u??0,d=!1;if(u===void 0&&r.startAtEnd)try{let m=(0,H.statSync)(e);if(s&&m.mtimeMs>=this.startedAtMs-dE&&await this.startedAfterThisWatcher(e,o,m.size)||(l=o?await fM(e,m.size):m.size),this.stopped)return;this.state.offsets[e]=l,d=!0}catch(m){f.debug("WORKER","Failed to stat file for startAtEnd offset",{file:e},m instanceof Error?m:void 0),l=0}try{let m=(0,H.statSync)(e),h=ia(m),_=this.state.fileIdentities?.[e],S=u!==void 0&&_!==void 0&&!EE(e,h,m.size,u,this.state.checkpointFingerprints?.[e]);if(S&&(l=0,this.state.offsets[e]=0,delete this.state.partials?.[e],delete this.state.partialBytes?.[e],delete this.state.frameLines?.[e],this.forgetReplacedTranscript(e,c)),S||h!==_){(this.state.fileIdentities??={})[e]=h;let b=Gl(e,l,h);b!==null?(this.state.checkpointFingerprints??={})[e]=b:delete this.state.checkpointFingerprints?.[e],d=!0}}catch(m){f.debug("WORKER","Failed to stat transcript file for its identity",{file:e},m instanceof Error?m:void 0)}d&&(s?Zr(this.statePath,this.state):i&&(i.stateChanged=!0));let p=l>0&&(!!n.sessionIdPath||!!r.subagentSource||!c.cwd),g=new Kl(e,l,async m=>{try{p&&(p=!1,await this.primeFromFirstLine(e,l,r,n,a,c)),await this.handleLine(m,r,n,e,a,c)}finally{c.pendingTools&&((this.state.pendingTools??={})[e]=c.pendingTools),c.cwd&&c.cwd!==this.state.cwds?.[e]&&((this.state.cwds??={})[e]=c.cwd)}},(m,h,_,S,b,w)=>{S!==void 0&&((this.state.fileIdentities??={})[e]=S),b!==void 0?(this.state.checkpointFingerprints??={})[e]=b:this.state.checkpointFingerprints&&delete this.state.checkpointFingerprints[e],this.state.offsets[e]=m,h?(this.state.partials??={})[e]=h:this.state.partials&&delete this.state.partials[e],w?(this.state.partialBytes??={})[e]=w:this.state.partialBytes&&delete this.state.partialBytes[e],_>0?(this.state.frameLines??={})[e]=_:this.state.frameLines&&delete this.state.frameLines[e],Zr(this.statePath,this.state)},this.state.partials?.[e]??"",this.state.frameLines?.[e]??0,this.state.fileIdentities?.[e],this.state.checkpointFingerprints?.[e],()=>this.forgetReplacedTranscript(e,c),this.state.partialBytes?.[e]);g.start(),this.tailers.set(e,g),f.info("TRANSCRIPT","Watching transcript file",{file:e,watch:r.name,schema:n.name})}async startedAfterThisWatcher(e,r,n){let s=await pM(e,r,n);return s!==null?s>=this.startedAtMs-dE:n<=uM}async primeFromFirstLine(e,r,n,s,i,o){try{let a=await _E(e,e.endsWith(sa),r);if(a===null)return;await this.processor.primeSessionContext(JSON.parse(a),n,s,i,o)}catch(a){f.debug("TRANSCRIPT","Could not read the first line of a resumed transcript",{watch:n.name,file:(0,q.basename)(e)},a instanceof Error?a:void 0)}}async handleLine(e,r,n,s,i,o){try{let a=JSON.parse(e);await this.processor.processEntry(a,r,n,i??void 0,o)}catch(a){if(a instanceof os||a instanceof as||a instanceof sr)throw f.warn("TRANSCRIPT","Transcript event not accepted; it is retried from its own line",{watch:r.name,file:(0,q.basename)(s),error:a.message}),a;a instanceof Error?f.debug("TRANSCRIPT","Failed to parse transcript line",{watch:r.name,file:(0,q.basename)(s)},a):f.warn("TRANSCRIPT","Failed to parse transcript line (non-Error thrown)",{watch:r.name,file:(0,q.basename)(s),error:String(a)})}}extractSessionIdFromPath(e){let r=e.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i);return r?r[0]:null}};function sd(t,e){let r=t.indexOf(e);return r===-1?null:t[r+1]??null}function fS(t){(0,pS.existsSync)(oe(t))||(Ia(t),console.log(`Created sample config: ${oe(t)}`))}async function gS(t,e){switch(t){case"init":{let r=sd(e,"--config")??ur;return Ia(r),console.log(`Created sample config: ${oe(r)}`),0}case"watch":{let r=sd(e,"--config")??ur;fS(r);let n=z.loadFromFile(ge),{config:s,scoped:i,removed:o}=Ad(Ta(r),n);if(i>0&&console.log(`Scoped ${i} Codex transcript watch(es) to subagent sessions (MEMINDEX_CODEX_SUBAGENT_INGESTION=true); native hooks capture top-level sessions.`),o>0&&console.log(`Skipped ${o} Codex transcript watch(es): native hooks capture top-level Codex sessions, and subagent capture is opt-in (MEMINDEX_CODEX_SUBAGENT_INGESTION=true).`),s.watches.length===0)return console.log(`No active transcript watches in ${oe(r)}; nothing to watch.`),1;let a=oe(s.stateFile??ws),c=new aa(s,a,"spool");await c.start(),console.log("Transcript watcher running. Press Ctrl+C to stop.");let u=()=>{c.stop(),process.exit(0)};return process.on("SIGINT",u),process.on("SIGTERM",u),await new Promise(()=>{})}case"validate":{let r=sd(e,"--config")??ur;return fS(r),Ta(r),console.log(`Config OK: ${oe(r)}`),0}case"import":return TP(e);default:return console.log("Usage: memindex transcript <init|watch|validate> [--config <path>]"),console.log(" memindex transcript import [--since <ISO time>] [--until <ISO time>] [--project-dir <folder>] [--dry-run]"),1}}async function TP(t){let{defaultTranscriptImportDeps:e,formatTranscriptImportResult:r,isoOf:n,parseTranscriptImportArgs:s,runTranscriptImport:i,TRANSCRIPT_IMPORT_USAGE:o}=await Promise.resolve().then(()=>(dS(),lS)),{settleHookSpoolNudges:a}=await Promise.resolve().then(()=>(Tr(),Og)),c=s(t);if(typeof c=="string")return console.error(c),console.error(o),1;console.log(`${c.dryRun?"Previewing":"Importing"} Claude Code transcripts from ${c.projectDir}${c.sinceMs!==null?` since ${n(c.sinceMs)}`:""}${c.untilMs!==null?` until ${n(c.untilMs)}`:""}`);let u=await i(c,e(l=>console.log(l)));return await a(),console.log(r(u,c.dryRun)),u.error?(console.error(`Stopped: ${u.error}. Run the same command again to carry on; nothing already sent is sent twice.`),1):0}var IP=process.argv[2],vP=process.argv.slice(3);gS(IP,vP).then(t=>{process.exit(t)}).catch(t=>{console.error(t),process.exit(1)});
|
|
39
|
+
${e}`,i=_m(s,o),a=`${t}.tmp`;try{(0,je.writeFileSync)(a,i),(0,je.renameSync)(a,t)}catch(c){f.error("AGENTS_MD","Failed to write AGENTS.md",{agentsPath:t},c instanceof Error?c:new Error(String(c)))}}O();function NI(t){let e=t.trim().replace(/^\$\.?/,"");if(!e)return[];let r=[],n=e.split(".");for(let s of n){let o=/([^[\]]+)|\[(\d+)\]/g,i;for(;(i=o.exec(s))!==null;)i[1]?r.push(i[1]):i[2]&&r.push(parseInt(i[2],10))}return r}function xn(t,e){if(!e)return;let r=NI(e),n=t;for(let s of r){if(n==null)return;n=n[s]}return n}function Sm(t){return t==null||t===""}function ym(t,e){if(t.startsWith("$watch.")){let r=t.slice(7);return e.watch[r]}if(t.startsWith("$schema.")){let r=t.slice(8);return e.schema[r]}if(t.startsWith("$session.")){let r=t.slice(9);return e.session?e.session[r]:void 0}if(t==="$cwd")return e.watch.workspace;if(t==="$project")return e.watch.project}function Cr(t,e,r){if(t!==void 0){if(typeof t=="string"){let n=ym(t,r);return n!==void 0?n:xn(e,t)}if(t.coalesce&&Array.isArray(t.coalesce))for(let n of t.coalesce){let s=Cr(n,e,r);if(!Sm(s))return s}if(t.path){let n=ym(t.path,r);if(n!==void 0)return n;let s=xn(e,t.path);if(!Sm(s))return s}if(t.value!==void 0)return t.value;if(t.default!==void 0)return t.default}}function bm(t,e,r){let n={};if(!t)return n;for(let[s,o]of Object.entries(t))n[s]=Cr(o,e,r);return n}function kn(t,e,r){if(!e)return!0;if(e.all!==void 0){if(!Array.isArray(e.all))return!1;for(let i of e.all)if(!kn(t,i,r))return!1}if(e.any!==void 0&&(!Array.isArray(e.any)||!e.any.some(i=>kn(t,i,r))))return!1;let n=e.path||r.eventTypePath||"type",s=n?xn(t,n):void 0,o=s==null||s==="";if(e.exists!==void 0&&(e.exists&&o||!e.exists&&!o)||e.equals!==void 0&&s!==e.equals||e.not_equals!==void 0&&s===e.not_equals||e.in&&Array.isArray(e.in)&&!e.in.includes(s)||e.not_in&&Array.isArray(e.not_in)&&e.not_in.includes(s)||e.contains!==void 0&&(typeof s!="string"||!s.includes(e.contains))||e.not_contains!==void 0&&typeof s=="string"&&s.includes(e.not_contains)||e.starts_with!==void 0&&(typeof s!="string"||!s.startsWith(e.starts_with))||e.not_starts_with!==void 0&&typeof s=="string"&&s.startsWith(e.not_starts_with))return!1;if(e.regex)try{if(!new RegExp(e.regex).test(String(s??"")))return!1}catch(i){return f.debug("WORKER","Invalid regex in match rule",{regex:e.regex},i instanceof Error?i:void 0),!1}return!0}ht();Nr();O();Ze();Sn();zo();Mn();dt();C();var rr=require("path");C();function DI(t=K.dataDir()){return(0,rr.join)(t,"bottles")}function vm(t,e){let r=(0,rr.resolve)(DI(e));return(0,rr.resolve)(t).startsWith(r+rr.sep)}qt();ht();O();var Vo=class{static checkUserPromptPrivacy(e,r,n,s,o,i){let a=e.getUserPrompt(r,n,o);return a===null?(f.warn("HOOK",`${s}: no user_prompts row for prompt #${n} \u2014 ingesting anyway (session-init likely raced worker boot; see #2794/#2795)`,{sessionId:o,contentSessionId:r,promptNumber:n,...i}),{allow:!0,prompt:""}):a.trim()===""?(f.debug("HOOK",`Skipping ${s} - user prompt was entirely private`,{sessionId:o,promptNumber:n,...i}),{allow:!1,reason:"private"}):{allow:!0,prompt:a}}};var Fr=require("path");function Am(){let t=FI();return async e=>{for(let r of e)r.module=t(r.filename);return e}}function FI(t=process.argv[1]?(0,Fr.dirname)(process.argv[1]):process.cwd(),e=Fr.sep==="\\"){let r=e?Rm(t):t;return n=>{if(!n)return;let s=e?Rm(n):n,{dir:o,base:i,ext:a}=Fr.posix.parse(s);(a===".js"||a===".mjs"||a===".cjs")&&(i=i.slice(0,-1*a.length));let c=decodeURIComponent(i);o||(o=".");let u=o.lastIndexOf("/node_modules");if(u>-1)return`${o.slice(u+14).replace(/\//g,".")}:${c}`;if(o.startsWith(r)){let l=o.slice(r.length+1).replace(/\//g,".");return l?`${l}:${c}`:c}return c}}function Rm(t){return t.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var Z={};As(Z,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>li,DOMExceptionCoercer:()=>$u,EXCEPTION_STEP_INTERNAL_FIELDS:()=>jn,ErrorCoercer:()=>Un,ErrorEventCoercer:()=>Bu,ErrorPropertiesBuilder:()=>Ln,EventCoercer:()=>Wu,ExceptionStepsBuffer:()=>Ku,ObjectCoercer:()=>Bn,PrimitiveCoercer:()=>Wn,PromiseRejectionEventCoercer:()=>ju,ReduceableCache:()=>Hu,StringCoercer:()=>$n,chromeStackLineParser:()=>Du,createDefaultStackParser:()=>Uu,createStackParser:()=>_h,geckoStackLineParser:()=>Fu,getInjectedReleaseId:()=>qv,getUtf8ByteLength:()=>Sh,nodeStackLineParser:()=>dh,opera10StackLineParser:()=>ch,opera11StackLineParser:()=>uh,resolveExceptionStepsConfig:()=>Xu,reverseAndStripFrames:()=>hh,stripReservedExceptionStepFields:()=>zv,winjsStackLineParser:()=>ah});var me=(function(t){return t.AnonymousId="anonymous_id",t.DistinctId="distinct_id",t.Props="props",t.EnablePersonProcessing="enable_person_processing",t.PersonMode="person_mode",t.FeatureFlagDetails="feature_flag_details",t.FeatureFlags="feature_flags",t.FeatureFlagPayloads="feature_flag_payloads",t.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",t.BootstrapFeatureFlags="bootstrap_feature_flags",t.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",t.OverrideFeatureFlags="override_feature_flags",t.Queue="queue",t.AiQueue="ai_queue",t.AiCaptureQueue="ai_capture_queue",t.LogsQueue="logs_queue",t.OptedOut="opted_out",t.SessionId="session_id",t.SessionStartTimestamp="session_start_timestamp",t.SessionLastTimestamp="session_timestamp",t.PersonProperties="person_properties",t.GroupProperties="group_properties",t.InstalledAppBuild="installed_app_build",t.InstalledAppVersion="installed_app_version",t.SessionReplay="session_replay",t.PushRegistered="push_registered",t.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",t.SurveyLastSeenDate="survey_last_seen_date",t.SurveysInProgress="surveys_in_progress",t.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t})({});function Nt(t){let e=[];return JSON.stringify(t,function(r,n){if(typeof n=="bigint")return n.toString();if(!(typeof n=="function"||typeof n=="symbol")){if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(n&&typeof n=="object"){for(;e.length>0&&e[e.length-1]!==this;)e.pop();if(e.includes(n))return"[Circular]";e.push(n)}return n}})??"null"}var LI=Array.isArray,Pm=Object.prototype,kD=Pm.hasOwnProperty,Yo=Pm.toString,Se=LI||function(t){return Yo.call(t)==="[object Array]"};var Nn=t=>t===Object(t)&&!Se(t);var St=t=>t===void 0,ae=t=>Yo.call(t)=="[object String]",wu=t=>ae(t)&&t.trim().length===0,Tu=t=>t===null,He=t=>St(t)||Tu(t),Lr=t=>Yo.call(t)=="[object Number]"&&t===t;var Mm=t=>Yo.call(t)==="[object Boolean]";function qo(t){return t===null||typeof t!="object"}function nr(t,e){return Object.prototype.toString.call(t)===`[object ${e}]`}function Ct(t){switch(Object.prototype.toString.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Nm(t,Error)}}function xm(t){return nr(t,"ErrorEvent")}function Ur(t){return"u">typeof Event&&Nm(t,Event)}function km(t){return nr(t,"Object")}function Nm(t,e){try{return t instanceof e}catch{return!1}}var UI=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterestbot","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],Jo=new Map,$I=256;function BI(t,e){let r="";for(let n=0;n<e.length;n++){let s=e[n];r+=s.length+":"+s}return t.length+":"+t+"|"+e.length+":"+r}var Cm=function(t,e=[]){if(!t)return!1;let r=BI(t,e),n=Jo.get(r);if(n!==void 0)return n;let s=t.toLowerCase(),o=UI.concat(e).some(i=>s.indexOf(i.toLowerCase())!==-1);return Jo.size>=$I&&Jo.clear(),Jo.set(r,o),o};function Cn(t,e,r,n,s){return e>r&&(n.warn("min cannot be greater than max."),e=r),Lr(t)?t>r?(n.warn(" cannot be greater than max: "+r+". Using max value instead."),r):t<e?(n.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(n.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+s),Cn(s??r,e,r,n))}var WI=864e5,jI=1,HI=10;function Dm(t={}){return{refillRate:t.exceptionRateLimiterRefillRate??t.__exceptionRateLimiterRefillRate??jI,bucketSize:t.exceptionRateLimiterBucketSize??t.__exceptionRateLimiterBucketSize??HI}}var Qo=class{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=Cn(e.bucketSize,0,100,e._logger),this._refillRate=Cn(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=Cn(e.refillInterval,0,WI,e._logger)}_applyRefill(e,r){let n=r-e.lastAccess,s=Math.floor(n/this._refillInterval);if(s>0){let o=s*this._refillRate;e.tokens=Math.min(e.tokens+o,this._bucketSize),e.lastAccess=e.lastAccess+s*this._refillInterval}}consumeRateLimit(e){let r=Date.now(),n=String(e),s=this._buckets[n];return s?this._applyRefill(s,r):(s={tokens:this._bucketSize,lastAccess:r},this._buckets[n]=s),s.tokens===0?!0:(s.tokens--,s.tokens===0&&this._onBucketRateLimited?.(e),s.tokens===0)}stop(){this._buckets={}}};var Zo="0123456789abcdef",ei=class t{constructor(e){this.bytes=e}static ofInner(e){if(e.length===16)return new t(e);throw new TypeError("not 128-bit length")}static fromFieldsV7(e,r,n,s){if(!Number.isInteger(e)||!Number.isInteger(r)||!Number.isInteger(n)||!Number.isInteger(s)||e<0||r<0||n<0||s<0||e>0xffffffffffff||r>4095||n>1073741823||s>4294967295)throw new RangeError("invalid field value");let o=new Uint8Array(16);return o[0]=e/2**40,o[1]=e/2**32,o[2]=e/2**24,o[3]=e/2**16,o[4]=e/256,o[5]=e,o[6]=112|r>>>8,o[7]=r,o[8]=128|n>>>24,o[9]=n>>>16,o[10]=n>>>8,o[11]=n,o[12]=s>>>24,o[13]=s>>>16,o[14]=s>>>8,o[15]=s,new t(o)}static parse(e){let r;switch(e.length){case 32:r=/^[0-9a-f]{32}$/i.exec(e)?.[0];break;case 36:r=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;case 38:r=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e)?.slice(1,6).join("");break;case 45:r=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;default:break}if(r){let n=new Uint8Array(16);for(let s=0;s<16;s+=4){let o=parseInt(r.substring(2*s,2*s+8),16);n[s+0]=o>>>24,n[s+1]=o>>>16,n[s+2]=o>>>8,n[s+3]=o}return new t(n)}throw new SyntaxError("could not parse UUID string")}toString(){let e="";for(let r=0;r<this.bytes.length;r++)e+=Zo.charAt(this.bytes[r]>>>4),e+=Zo.charAt(15&this.bytes[r]),(r===3||r===5||r===7||r===9)&&(e+="-");return e}toHex(){let e="";for(let r=0;r<this.bytes.length;r++)e+=Zo.charAt(this.bytes[r]>>>4),e+=Zo.charAt(15&this.bytes[r]);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw new Error("unreachable");if(e<=7)return this.bytes.every(r=>r===0)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every(r=>r===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new t(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let r=0;r<16;r++){let n=this.bytes[r]-e.bytes[r];if(n!==0)return Math.sign(n)}return 0}},Iu=class{constructor(e){this.timestamp=0,this.counter=0,this.random=e??XI()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,r){let n=this.generateOrAbortCore(e,r);return n===void 0&&(this.timestamp=0,n=this.generateOrAbortCore(e,r)),n}generateOrAbortCore(e,r){if(!Number.isInteger(e)||e<1||e>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(r<0||r>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+r>=this.timestamp))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter())}return ei.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,ei.ofInner(e)}},XI=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),Fm,fe=()=>KI().toString(),KI=()=>(Fm||(Fm=new Iu)).generate();var ti=class{add(e){let r=fe(),n=++this.nextId;return this.promiseByIds[r]={id:n,promise:e},e.catch(()=>{}).finally(()=>{delete this.promiseByIds[r]}),e}async join(){let e=Object.values(this.promiseByIds).map(n=>n.promise),r=e.length;for(;r>0;)await Promise.all(e),e=Object.values(this.promiseByIds).map(n=>n.promise),r=e.length}getPromises(e=[],r=this.nextId){let n=new Set(e);return Object.values(this.promiseByIds).filter(s=>s.id<=r&&!n.has(s.promise)).map(s=>s.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}};function GI(t=console){return{log:t.log.bind(t),warn:t.warn.bind(t),error:t.error.bind(t),debug:t.debug.bind(t)}}var Lm=(t,e,r)=>{function n(o,...i){e(()=>{let a=r[o];a(t,...i)})}return{debug:(...o)=>{n("debug",...o)},info:(...o)=>{n("log",...o)},warn:(...o)=>{n("warn",...o)},error:(...o)=>{n("error",...o)},critical:(...o)=>{r.error(t,...o)},createLogger:o=>Lm(`${t} ${o}`,e,r)}},zI=t=>t();function Um(t,e=zI){return Lm(t,e,GI())}var Br="Mobile",ni="iOS",$r="Android",Hm="Tablet",zD=$r+" "+Hm;var YI="Apple",VD=YI+" Watch",Xm="Safari",si="BlackBerry",Km="Samsung",qI=Km+"Browser",JI=Km+" Internet",oi="Chrome",QI=oi+" OS",ZI=oi+" "+ni,Gm="Internet Explorer",ev=Gm+" "+Br,Au="Opera",YD=Au+" Mini",zm="Edge",tv="Microsoft "+zm,Ou="Firefox",rv=Ou+" "+ni,Pu="Nintendo",Mu="PlayStation",ri="Xbox",nv=$r+" "+Br,sv=Br+" "+Xm,Dn="Windows",ov=Dn+" Phone";var Vm="Generic",qD=Vm+" "+Br.toLowerCase(),JD=Vm+" "+Hm.toLowerCase(),iv="Konqueror",av="Oculus Browser",$m="Vivaldi",cv="Yandex",Bm="Whale",uv="DuckDuckGo",lv="Pale Moon",Wm="Waterfox",jm="Brave",Ym="Claude",qm="Codex",Jm="ChatGPT",dv="Google Search App",B="(\\d+(\\.\\d+)?)",vu=new RegExp("Version/"+B),Ru=new RegExp("("+Ym+"|"+qm+"|"+Jm+")\\/"+B);var QD=new RegExp(ri,"i"),ZD=new RegExp(Mu+" \\w+","i"),eF=new RegExp(Pu+" \\w+","i"),fv=new RegExp(si+"|PlayBook|BB10","i"),pv={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000","5.1":"XP","5.2":"XP","6.0":"Vista","6.1":"7","6.2":"8","6.3":"8.1","6.4":"10","10.0":"10"};var tF={[ev]:[new RegExp("rv:"+B)],[tv]:[new RegExp(zm+"?\\/"+B)],[oi]:[new RegExp("("+oi+"|CrMo)\\/"+B)],[ZI]:[new RegExp("CriOS\\/"+B)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+B)],[Xm]:[vu],[sv]:[vu],[Au]:[new RegExp("("+Au+"|OPR)\\/"+B)],[Ou]:[new RegExp(Ou+"\\/"+B)],[rv]:[new RegExp("FxiOS\\/"+B)],[iv]:[new RegExp("Konqueror[:/]?"+B,"i")],[si]:[new RegExp(si+" "+B),vu],[nv]:[new RegExp("android\\s"+B,"i")],[JI]:[new RegExp(qI+"\\/"+B)],[av]:[new RegExp("OculusBrowser\\/"+B)],[$m]:[new RegExp($m+"\\/"+B)],[cv]:[new RegExp("YaBrowser\\/"+B)],[Bm]:[new RegExp(Bm+"\\/"+B)],[jm]:[new RegExp(jm+"\\/"+B)],[Ym]:[Ru],[qm]:[Ru],[Jm]:[Ru],[uv]:[new RegExp("(DuckDuckGo|Ddg)\\/"+B)],[lv]:[new RegExp("PaleMoon\\/"+B)],[Wm]:[new RegExp(Wm+"\\/"+B)],[dv]:[new RegExp("GSA\\/"+B)],[Gm]:[new RegExp("(rv:|MSIE )"+B)],Mozilla:[new RegExp("rv:"+B)]};var rF=[[new RegExp(ri+"; "+ri+" (.*?)[);]","i"),t=>[ri,t&&t[1]||""]],[new RegExp(Pu,"i"),[Pu,""]],[new RegExp(Mu,"i"),[Mu,""]],[fv,[si,""]],[new RegExp(Dn,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[ov,""];if(new RegExp(Br).test(e)&&!/IEMobile\b/.test(e))return[Dn+" "+Br,""];let r=/Windows NT ([0-9.]+)/i.exec(e);if(r&&r[1]){let n=r[1],s=pv[n]||"";return/arm/i.test(e)&&(s="RT"),[Dn,s]}return[Dn,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>{if(t&&t[3]){let e=[t[3],t[4],t[5]||"0"];return[ni,e.join(".")]}return[ni,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{let e="";return t&&t.length>=3&&(e=St(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+$r+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+$r+")","i"),t=>{if(t&&t[2]){let e=[t[2],t[3],t[4]||"0"];return[$r,e.join(".")]}return[$r,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{let e=["Mac OS X",""];if(t&&t[1]){let r=[t[1],t[2],t[3]||"0"];e[1]=r.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[QI,""]],[/Linux|debian/i,["Linux",""]]];var ii="[Circular]",ai="[Truncated]",ve="[Unserializable]",Qm="[Function]",oF=Date.prototype.getTime,iF=Date.prototype.toISOString;function et(t){let e="";for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(n>=55296&&n<=56319){let s=t.charCodeAt(r+1);s>=56320&&s<=57343?(e+=t[r]+t[r+1],r++):e+="\uFFFD"}else e+=n>=56320&&n<=57343?"\uFFFD":t[r]}return e}function yt(t,e){if(!e)return t;let r=[];try{r=Object.keys(e)}catch{r=[]}for(let n of r){let s;try{s=e[n]}catch{s=ve}Object.defineProperty(t,n,{value:s,enumerable:!0,writable:!0,configurable:!0})}return t}function xu(t,e=Date.now()){if(typeof t!="string"||!t)return;let r=t.trim(),n=/^\d+\s*,/.test(r)?r.slice(0,r.indexOf(",")).trim():r;if(/^\d+$/.test(n)){let i=1e3*Math.min(Number(n),300);return i>0?i:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(n))return;let s=/^\w{3} \w{3} /.test(n)?n+" GMT":n,o=Date.parse(s)-e;if(!(!Number.isFinite(o)||o<=0))return Math.min(o,3e5)}var sr=class{record(e){if(e.kind==="too-large")return;if(e.kind!=="retry-later")return void this.reset();if(!e.retryAfterMs)return;let r=this.isOpen(),n=Date.now(),s=Math.min(e.retryAfterMs,3e5);if(!r){this._installedAt=n,this._until=n+s;return}this._until=Math.max(this._until,Math.min(n+s,this._installedAt+3e5))}remainingMs(){let e=Date.now();if(e<this._installedAt-5e3)return this.reset(),0;let r=Math.min(3e5,Math.max(0,this._until-e));return r===0&&this.reset(),r}isOpen(){return this.remainingMs()>0}reset(){this._until=0,this._installedAt=0}constructor(){this._until=0,this._installedAt=0}};var Zm="utf8",gv=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function mv(t){return typeof t=="string"&&gv.test(t)}function or(t,e){return mv(t)?t:e()}function Wr(t,e){let r=new Error(e);try{Object.defineProperty(r,"name",{value:t,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function eh(t){return t?.replace(/\/+$/,"")}async function th(t,e){let r=null;for(let n=0;n<e.retryCount+1;n++){n>0&&await new Promise(s=>setTimeout(s,e.retryDelay));try{return await t()}catch(s){if(r=s,!e.retryCheck(s))throw s}}throw r}function ku(){return new Date().toISOString()}function pe(t,e){let r=setTimeout(t,e);return r?.unref&&r?.unref(),r}async function Dt(t,e,r){let n;try{return await Promise.race([t,new Promise((s,o)=>{n=pe(()=>{try{r?.(),s()}catch(i){o(i)}},e)})])}finally{clearTimeout(n)}}var rh=t=>t&&typeof t.then=="function";function Fn(t){return Promise.all(t.map(e=>(e??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var Nu,nh,sh,jr;function ih(t){let e=globalThis._posthogChunkIds,r=globalThis._debugIds;if(!e&&!r)return;let n=e?Object.keys(e):[],s=r?Object.keys(r):[];if(jr&&oh(e,n,nh)&&oh(r,s,sh))return jr;nh=e?{...e}:void 0,sh=r?{...r}:void 0,jr={},Nu??={};let o=(i,a)=>{for(let c of i){let u=a[c];if(!u)continue;let l=Nu?.[c];if(l){jr[l]=u;continue}let d=t(c);for(let p=d.length-1;p>=0;p--){let g=d[p]?.filename;if(g){jr[g]=u,Nu[c]=g;break}}}};return r&&o(s,r),e&&o(n,e),jr}function oh(t,e,r){return!t||!r?t===r:e.length===Object.keys(r).length&&e.every(n=>t[n]===r[n])}var Cu=50,hv=1e3,_v=100,Ev=4,Ln=class{constructor(e,r,n=[]){this.coercers=e,this.stackParser=r,this.modifiers=n}buildFromUnknown(e,r={}){let s=r&&r.mechanism||{handled:!0,type:"generic"},i=this.buildCoercingContext(s,r,0).apply(e),a=this.buildParsingContext(r),c=this.parseStacktrace(i,a);return{$exception_list:this.convertToExceptionList(c,s),$exception_level:"error"}}async modifyFrames(e){for(let r of e)r.stacktrace&&r.stacktrace.frames&&Se(r.stacktrace.frames)&&(r.stacktrace.frames=await this.applyModifiers(r.stacktrace.frames));return e}coerceFallback(e){return{type:"Error",value:"Unknown error",stack:e.syntheticException?.stack,synthetic:!0}}parseStacktrace(e,r){let n;e.cause!=null&&(n=this.parseStacktrace(e.cause,r));let s;if(e.stack!=""&&e.stack!=null)try{s=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?r.skipFirstLines:0),r.chunkIdMap)}catch{}return{...e,cause:n,stack:s,errors:e.errors?.map(o=>this.parseStacktrace(o,r))}}applyChunkIds(e,r){return e.map(n=>(n.filename&&r&&(n.chunk_id=r[n.filename]),n))}applyCoercers(e,r){for(let n of this.coercers)if(n.match(e))return n.coerce(e,r);return this.coerceFallback(r)}async applyModifiers(e){let r=e;for(let n of this.modifiers)r=await n(r);return r}convertToExceptionList(e,r){let n=[],s=(o,i,a)=>{let c=n.length,u=i===void 0?{type:typeof r.type=="string"&&r.type.length>0?r.type:"generic",...typeof r.handled=="boolean"?{handled:r.handled}:r.handled===void 0?{handled:!0}:{},synthetic:typeof r.synthetic=="boolean"?r.synthetic:o.synthetic,exception_id:c}:{type:"chained",source:a,synthetic:o.synthetic,exception_id:c,parent_id:i},l={type:o.type,value:o.value,mechanism:u};o.stack&&(l.stacktrace={type:"raw",frames:o.stack}),n.push(l),o.cause&&s(o.cause,c,"cause");for(let d of o.errors??[])s(d,c,"member")};return s(e),n}buildParsingContext(e){return{chunkIdMap:ih(this.stackParser),skipFirstLines:e.skipFirstLines??1}}getAggregateErrors(e){try{if(Ct(e)){let r=Object.getPrototypeOf(e);for(let n=0;r&&n<_v;n++){let s=Object.getOwnPropertyDescriptor(r,"constructor")?.value;if(typeof s=="function"&&s.name==="AggregateError"){let o=e.errors;return Se(o)?o:void 0}r=Object.getPrototypeOf(r)}}}catch{}}buildCoercingContext(e,r,n=0){let s=0,o=0,i=!1,a=new Set,c=[],u={},l=(g,m,h=0)=>{let _=d(m,h),S=_.apply;if(_.apply=v=>{c.push(g);try{return S(v)}finally{c.pop()}},h>Ev||h>0&&c.indexOf(g)!==-1)return this.coerceFallback(_);let b=typeof g=="object"&&g!==null||typeof g=="function";if(h===0&&s>=Cu||b&&a.has(g))return;b&&a.add(g),h===0&&s++;let w=this.getAggregateErrors(g);i||=!!w;let T;try{if(T=this.applyCoercers(g,_),!T)throw u}catch(v){if(v===u){h===0&&s--;return}if(!i)throw v;T=this.coerceFallback(_)}if(!w||s>=Cu)return T;let y;try{y=w.length}catch{return T}if(!Number.isInteger(y)||y<0||y>4294967295)return T;let A=[];for(let v=0;s<Cu&&o<hv&&v<y;v++){o++;let R;try{R=_.next(w[v])}catch{s++,R=this.coerceFallback(d(m+1))}R&&A.push(R)}return{...T,errors:A}},d=(g,m=0)=>({...r,syntheticException:g==0?r.syntheticException:void 0,mechanism:g==0?e:{},apply:h=>{let _=l(h,g,m+1);if(!_)throw u;return _},next:h=>l(h,g+1)}),p=d(n);return{...p,apply:g=>l(g,n)??this.coerceFallback(p)}}};var re="?",Sv="<anonymous>",yv=/^([a-z][a-z0-9.+-]+):/i,bv=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function wv(t){if(!t||t===Sv)return!1;let e=yv.exec(t);return!e||bv.includes(e[1].toLowerCase())}function tt(t,e,r,n,s){let o={platform:t,filename:e,function:r==="<anonymous>"?re:r,in_app:wv(e)};return St(n)||(o.lineno=n),St(s)||(o.colno=s),o}var ci=(t,e)=>{let r=t.indexOf("safari-extension")!==-1,n=t.indexOf("safari-web-extension")!==-1;return r||n?[t.indexOf("@")!==-1?t.split("@")[0]:re,r?`safari-extension:${e}`:`safari-web-extension:${e}`]:[t,e]};var Tv=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Iv=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,vv=/\((\S*)(?::(\d+))(?::(\d+))\)/,Du=(t,e)=>{let r=Tv.exec(t);if(r){let[,s,o,i]=r;return tt(e,s,re,+o,+i)}let n=Iv.exec(t);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=vv.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}let[o,i]=ci(n[1]||re,n[2]);return tt(e,i,o,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var Rv=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Av=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Fu=(t,e)=>{let r=Rv.exec(t);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let i=Av.exec(r[3]);i&&(r[1]=r[1]||"eval",r[3]=i[1],r[4]=i[2],r[5]="")}let s=r[3],o=r[1]||re;return[o,s]=ci(o,s),tt(e,s,o,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var Ov=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,ah=(t,e)=>{let r=Ov.exec(t);return r?tt(e,r[2],r[1]||re,+r[3],r[4]?+r[4]:void 0):void 0};var Pv=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,ch=(t,e)=>{let r=Pv.exec(t);return r?tt(e,r[2],r[3]||re,+r[1]):void 0},Mv=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,uh=(t,e)=>{let r=Mv.exec(t);return r?tt(e,r[5],r[3]||r[4]||re,+r[1],+r[2]):void 0};var xv=/^\s*[-]{4,}$/,kv=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,Nv=/^Promise\.(?:all|any)$/,Cv=/^index \d+$/,Dv="node:internal/promise",dh=(t,e)=>{let r=t.match(kv);if(r){let n,s,o,i,a;if(r[1]){o=r[1];let l=o.lastIndexOf(".");if(o[l-1]==="."&&l--,l>0){n=o.slice(0,l),s=o.slice(l+1);let d=n.indexOf(".Module");d>0&&(o=o.slice(d+1),n=n.slice(0,d))}i=void 0}s&&(i=n,a=s),s==="<anonymous>"&&(a=void 0,o=void 0),o===void 0&&(a=a||re,o=i?`${i}.${a}`:a);let c=r[2]?.startsWith("file://")?r[2].slice(7):r[2],u=r[5]==="native";return c?.match(/\/[A-Z]:/)&&(c=c.slice(1)),!c&&r[5]&&!u&&(c=r[5]),Nv.test(o)&&Cv.test(c||"")&&(c=Dv),{filename:c?decodeURI(c):void 0,module:void 0,function:o,lineno:lh(r[3]),colno:lh(r[4]),in_app:Fv(c||"",u),platform:e}}if(t.match(xv))return{filename:t,platform:e}};function Fv(t,e=!1){return!(e||t&&!t.startsWith("/")&&!t.match(/^[A-Z]:/)&&!t.startsWith(".")&&!t.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&t!==void 0&&!t.includes("node_modules/")}function lh(t){return parseInt(t||"",10)||void 0}var fh=/\(error: (.*)\)/,ph=50,Lv=10,Uv=1e3;function Lu(t,e){return t.filename===e.filename&&t.function===e.function&&t.module===e.module&&t.lineno===e.lineno&&t.colno===e.colno}function $v(t){for(let e=1;e<=Lv;e++){let r=t.length-2*e;if(r<0)break;let n=!0;for(let s=0;s<e;s++){let o=t[r+s];if(!Lu(o,t[r+e+s])){n=!1;break}}if(n){for(let s=0;s<e;s++)t[r+s]=t[r+e+s];return t.length=r+e,{start:r,length:e}}}}function Bv(t,e){let r=e.start+e.length,n=mh(t,e);n&&t.splice(r+n===t.length?r:e.start,n)}function gh(t,e){let r=e.start;for(;r>0&&Lu(t[r-1],t[r-1+e.length]);)r--;return e.start-r}function mh(t,e){let r=e.start+e.length,n=r;for(;n<t.length&&Lu(t[n],t[n-e.length]);)n++;return n-r}function Wv(t,e){let r=e[0],n=t.length-(r?gh(t,r):0);for(let s of e)n-=mh(t,s);return n}function jv(t){let e=t.map(n=>`${n.function}|${n.filename}|${n.lineno}|${n.colno}|${n.module}`),r=0;for(let n=1;n<e.length;n++)Hv(e,n,r)&&(r=n);t.push(...t.splice(0,r))}function Hv(t,e,r){for(let n=0;n<t.length;n++){let s=t[(e+n)%t.length],o=t[(r+n)%t.length];if(s!==o)return s<o}return!1}function hh(t){if(!t.length)return[];let e=Array.from(t);return e.reverse(),e.slice(0,ph).map(r=>({...r,filename:r.filename||Xv(e).filename,function:r.function||re}))}function Xv(t){return t[t.length-1]||{}}function Uu(){return _h("web:javascript",Du,Fu)}function _h(t,...e){return(r,n=0)=>{let s=[],o=r.split(`
|
|
40
|
+
`),i=Math.min(o.length,n+Uv),a=[];for(let l=n;l<i;l++){let d=o[l];if(d.length>1024)continue;let p=fh.test(d)?d.replace(fh,"$1"):d;if(!p.match(/\S*Error: /)){for(let g of e){let m=g(p,t);if(m){s.push(m);let h=$v(s);if(h){for(let _=a.length-1;_>=0;_--){let S=a[_];if(S.start+S.length<=h.start)break;a.pop()}a.push(h)}break}}if(Wv(s,a)>=ph)break}}let c=[...a].sort((l,d)=>d.start-l.start),u=c[c.length-1];if(u){let l=gh(s,u);s.splice(u.start-l,l);for(let d of c)d.start-=l}for(let l of c)Bv(s,l);return a.some(l=>l.start===0&&s.length===l.length)&&jv(s),hh(s)}}var $u=class{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,r){let n=ae(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:n?e.stack:void 0,cause:e.cause?r.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){let r=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${r}: ${e.message}`:r}isDOMException(e){return nr(e,"DOMException")}isDOMError(e){return nr(e,"DOMError")}};var Un=class{match(e){return Ct(e)}coerce(e,r){let n=this.getStack(e),s=n===void 0?r.syntheticException?.stack:void 0,o=!!s;return{type:this.getType(e),value:this.getMessage(e,r),stack:n??s,cause:e.cause?r.next(e.cause):void 0,synthetic:o}}getType(e){return e.name||e.constructor.name}getMessage(e,r){let n=e.message;return n.error&&typeof n.error.message=="string"?String(n.error.message):String(n)}getStack(e){try{let r=e.stacktrace;if(typeof r=="string"&&r.length>0)return r;let n=e.stack;return typeof n=="string"&&n.length>0?n:void 0}catch{return}}};var Bu=class{match(e){if(!xm(e))return!1;let r=e;return r.error!=null||this._hasUsableMessage(r)}coerce(e,r){if(e.error!=null)return r.apply(e.error);let n=r.apply(e.message);return{...n,stack:this._buildLocationStack(e)??n.stack,synthetic:!0}}_hasUsableMessage(e){return ae(e.message)&&e.message.length>0}_buildLocationStack(e){let r=e,n=r.lineno??0,s=r.colno??0;if(!(!ae(r.filename)||r.filename.length===0)&&n!==0)return`Error
|
|
41
|
+
at ${r.filename}:${n}:${s}`}};var Kv=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,$n=class{match(e){return typeof e=="string"}coerce(e,r){let[n,s]=this.getInfos(e);return{type:n??"Error",value:s??e,stack:r.syntheticException?.stack,synthetic:!0}}getInfos(e){let r="Error",n=e,s=e.match(Kv);return s&&(r=s[1],n=s[2]),[r,n]}};var Eh=["fatal","error","warning","log","info","debug"];function ui(t,e=40){let r=Object.keys(t);if(r.sort(),!r.length)return"[object has no keys]";for(let n=r.length;n>0;n--){let s=r.slice(0,n).join(", ");if(!(s.length>e))return n===r.length||s.length<=e?s:`${s.slice(0,e)}...`}return""}var Bn=class{match(e){return typeof e=="object"&&e!==null}coerce(e,r){let n=this.getErrorPropertyFromObject(e);return n?r.apply(n):{type:this.getType(e),value:this.getValue(e),stack:this.getStack(e)??r.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){if(Ur(e))return e.constructor.name;let r="name"in e?e.name:void 0;return ae(r)&&!wu(r)?r:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){let s=`'${e.name}' captured as exception`;return"message"in e&&typeof e.message=="string"&&(s+=` with message: '${e.message}'`),s}if("message"in e&&typeof e.message=="string")return e.message;let r=this.getObjectClassName(e),n=ui(e);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(e){return ae(e)&&!wu(e)&&Eh.indexOf(e)>=0}getStack(e){try{return ae(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:ae(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)){let n=e[r];if(Ct(n))return n}}getObjectClassName(e){try{let r=Object.getPrototypeOf(e);return r?r.constructor.name:void 0}catch{return}}};var Wu=class{match(e){return Ur(e)}coerce(e,r){let n=e.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${ui(e)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Wn=class{match(e){return qo(e)}coerce(e,r){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var ju=class{match(e){return nr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Ur(e))return!1;try{let r=e.detail;return r!=null&&typeof r=="object"&&"reason"in r}catch{return!1}}coerce(e,r){let n=this.getUnhandledRejectionReason(e);return qo(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:r.syntheticException?.stack,synthetic:!0}:r.apply(n)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}};var Hu=class{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let r=this._cache.get(e);if(r!==void 0)return this._cache.delete(e),this._cache.set(e,r),r}set(e,r){this._cache.set(e,r)}reduce(){for(;this._cache.size>=this._maxSize;){let e=this._cache.keys().next().value;e&&this._cache.delete(e)}}};var jn={MESSAGE:"$message",TIMESTAMP:"$timestamp"},Gv=new Set([jn.MESSAGE,jn.TIMESTAMP]),li={enabled:!0,max_bytes:32768};function Xu(t){return t?{enabled:t.enabled??li.enabled,max_bytes:Vv(t.max_bytes,li.max_bytes)}:{...li}}function zv(t){if(!t)return{sanitizedProperties:{},droppedKeys:[]};let e=[];return{sanitizedProperties:Object.keys(t).reduce((n,s)=>Gv.has(s)?(e.push(s),n):(n[s]=t[s],n),{}),droppedKeys:e}}var Ku=class{constructor(e){this._entries=[],this._totalBytes=0,this._config=Xu(e)}setConfig(e){this._config=Xu(e),this._trimToMaxBytes()}add(e){let r=Yv(e);if(!r)return;let n=Sh(r.json);n>this._config.max_bytes||(this._entries.push({step:r.step,bytes:n}),this._totalBytes+=n,this._trimToMaxBytes())}getAttachable(){return this._entries.map(e=>e.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let e=this._entries.shift();e&&(this._totalBytes-=e.bytes)}}};function Vv(t,e){if(!Lr(t)||t===1/0||t===-1/0)return e;let r=Math.floor(t);return r<0?e:r}function Yv(t){let e;try{e=Nt(t)}catch{return}try{let r=JSON.parse(e);if(!Nn(r))return;let n=r,s=n[jn.MESSAGE],o=n[jn.TIMESTAMP];return!ae(s)||s.trim().length===0||!ae(o)&&!Lr(o)?void 0:{step:n,json:e}}catch{return}}function Sh(t){if("u">typeof TextEncoder)return new TextEncoder().encode(t).length;let e=encodeURIComponent(t),r=0;for(let n=0;n<e.length;n++)e[n]==="%"?(r+=1,n+=2):r+=1;return r}function qv(){if("u">typeof process){let e=process.env.POSTHOG_RELEASE_ID?.trim();if(e)return e}let t=globalThis._posthogReleaseId;return typeof t=="string"&&t.length>0?t:void 0}var Gu=t=>{if("flags"in t){let e=yh(t.flags),r=bh(t.flags);return{...t,featureFlags:e,featureFlagPayloads:r}}{let e=t.featureFlags??{},r=Object.fromEntries(Object.entries(t.featureFlagPayloads||{}).map(([s,o])=>[s,Hr(o)])),n=Object.fromEntries(Object.entries(e).map(([s,o])=>[s,Jv(s,o,r[s])]));return{...t,featureFlags:e,featureFlagPayloads:r,flags:n}}};function Jv(t,e,r){return{key:t,enabled:typeof e=="string"?!0:e,variant:typeof e=="string"?e:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:r?JSON.stringify(r):void 0,description:void 0}}}var yh=t=>Object.fromEntries(Object.entries(t??{}).map(([e,r])=>[e,Hn(r)]).filter(([,e])=>e!==void 0)),bh=t=>{let e=t??{};return Object.fromEntries(Object.keys(e).filter(r=>{let n=e[r];return n.enabled&&n.metadata&&n.metadata.payload!==void 0}).map(r=>{let n=e[r].metadata?.payload;return[r,n?Hr(n):void 0]}))},Hn=t=>t===void 0?void 0:t.variant??t.enabled,Hr=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};var wh=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","bfcid","irclid","_kx"],Qv=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain",...wh,"$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Xn=(t,e=[])=>{let r={},n=s=>{t[s]!==void 0&&(r[s]=t[s])};return Qv.forEach(n),e.forEach(n),r};var di=class{constructor(){this.events={},this.events={}}on(e,r){return this.events[e]||(this.events[e]=[]),this.events[e].push(r),()=>{this.events[e]=this.events[e].filter(n=>n!==r)}}emit(e,r){for(let n of this.events[e]||[])n(r);for(let n of this.events["*"]||[])n(e,r)}};function zu(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var eR="NativeGzipValidationError",tR=31,rR=139,nR=8,sR=t=>t.length>=2&&t[0]===tR&&t[1]===rR;var Kn,oR=()=>{if(Kn)return Kn;Kn=[];for(let t=0;t<256;t++){let e=t;for(let r=0;r<8;r++)e=1&e?3988292384^e>>>1:e>>>1;Kn[t]=e>>>0}return Kn},iR=t=>{let e=oR(),r=4294967295;for(let n=0;n<t.length;n++)r=e[(r^t[n])&255]^r>>>8;return(4294967295^r)>>>0},fi=t=>{throw Wr(eR,`Native gzip produced invalid output: ${t}`)},aR=async(t,e)=>{t.size<18&&fi("too-short");let r=new Uint8Array(await t.slice(0,10).arrayBuffer());(!sR(r)||r[2]!==nR)&&fi("invalid-header");let n=new DataView(await t.slice(t.size-8).arrayBuffer());n.getUint32(0,!0)!==iR(e)&&fi("invalid-crc");let s=e.length>>>0;n.getUint32(4,!0)!==s&&fi("invalid-size")};async function Gn(t,e=!0,r){try{let n=new TextEncoder().encode(t),s=new globalThis.CompressionStream("gzip"),o=s.writable.getWriter(),i=o.write(n).then(()=>o.close()).catch(async u=>{try{await o.abort(u)}catch{}throw u}),a=new Response(s.readable).blob(),[c]=await Promise.all([a,i]);return await aR(c,n),c}catch(n){if(r?.rethrow)throw n;return e&&console.error("Failed to gzip compress data",n),null}}var Re=class extends Error{constructor(e,r,n,s){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+r),this.response=e,this.reqByteLength=r,this.responseBodyDeadline=n,this.abortController=s,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return xu(this.response.headers?.get("retry-after"))}catch{return}}get bodyReadTimedOut(){return this._bodyReadTimedOut}get text(){if(!this.responseBodyTextPromise)if(Date.now()>=this.responseBodyDeadline){this._bodyReadTimedOut=!0;let e=Wr("AbortError","Response body read timed out");this.cancelResponseBody(e),this.responseBodyTextPromise=Promise.reject(e)}else{let e=new Promise((n,s)=>{this.responseBodyTimer=pe(()=>{this._bodyReadTimedOut=!0;let o=Wr("AbortError","Response body read timed out");s(o),this.cancelResponseBody(o)},this.responseBodyDeadline-Date.now())}),r;try{r=Promise.resolve(this.response.text())}catch(n){r=Promise.reject(n)}this.responseBodyTextPromise=Promise.race([r,e]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then(e=>JSON.parse(e))}cancelResponseBody(e){clearTimeout(this.responseBodyTimer),this.abortController.signal.aborted||this.abortController.abort(e),(async()=>{try{await this.response.body?.cancel()}catch{}})()}},bt=class extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}};var cR=(t,e)=>{for(let r of Object.keys(e))(r.startsWith("$feature/")||r==="$active_feature_flags")&&(t[r]=e[r])};async function Th(t){if(t instanceof Re){let e="";try{e=await t.text}catch{t.bodyReadTimedOut&&(e="<response body read timed out>")}console.error(`Error while flushing PostHog: message=${t.message}, response body=${e}`,t)}else console.error("Error while flushing PostHog",t);return Promise.resolve()}function uR(t){return typeof t=="object"&&(t instanceof Re||Ah(t))}function Ah(t){return t instanceof bt}function lR(t){if(t instanceof Re)return t.status===502||t.status===504;if(!(t instanceof bt))return!1;let e=t.error;return(e?.code??e?.cause?.code)!=="ECONNREFUSED"}var Ih=10485760;function vh(t){try{return typeof t!="string"?t instanceof Uint8Array?t.byteLength:t.size:"u">typeof Buffer?Buffer.byteLength(t,Zm):new TextEncoder().encode(t).length}catch{return 0}}function Xr(t){return typeof t=="object"&&t instanceof Re&&t.status===413}function pi(t){return t instanceof Re?t.status===408||t.status===429||t.status>=500:Ah(t)}function Rh(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Vu="default",zn=class{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new Ln([new Un,new Bn,new $n,new Wn],Uu())}getEvaluationRuntime(){}constructor(e,r={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new ti,this._events=new di,this._isInitialized=!1;let n=typeof e=="string"?e.trim():"",s=typeof r.host=="string"?r.host.trim():"",o=!n;this._logger=Um("[PostHog]",this.logMsgIfDebug.bind(this)),o&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=n,this.host=eh(s||"https://us.i.posthog.com"),this.flushAt=r.flushAt?Math.max(r.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,r.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,r.maxQueueSize??1e3),this.flushInterval=r.flushInterval??1e4,this.preloadFeatureFlags=r.preloadFeatureFlags??!0,this.defaultOptIn=r.defaultOptIn??!0,this.disableSurveys=r.disableSurveys??!1,this._retryOptions={retryCount:r.fetchRetryCount??3,retryDelay:r.fetchRetryDelay??3e3,retryCheck:pi},this.requestTimeout=r.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=r.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=r.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=r.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=r.disableGeoip??!0,this.disabled=(r.disabled??!1)||o,this.historicalMigration=r?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=r?.evaluationContexts??r?.evaluationEnvironments,r?.evaluationEnvironments&&!r?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!zu()||(r?.disableCompression??!1)}logMsgIfDebug(e){this.isDebug&&e()}wrap(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return e();this._initPromise.then(()=>e())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(me.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(me.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(me.OptedOut,!0)})}on(e,r){return this._events.on(e,r)}debug(e=!0){if(this.removeDebugCallback?.(),e){let r=this.on("*",(n,s)=>this._logger.info(n,s));this.removeDebugCallback=()=>{r(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let r=e.properties||{},n=this.mergeCommonEventProperties(r);return cR(n,r),e.event==="$feature_flag_called"&&n.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled()&&(n=Xn(n)),{distinct_id:e.distinct_id,event:e.event,properties:n}}mergeCommonEventProperties(e){return{...e,...this.getCommonEventProperties()}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,r,n){this.wrap(()=>{let s={...this.buildPayload({distinct_id:e,event:"$identify",properties:r})};this.enqueue("identify",s,n)})}async identifyStatelessImmediate(e,r,n){let s={...this.buildPayload({distinct_id:e,event:"$identify",properties:r})};await this.sendImmediate("identify",s,n)}captureStateless(e,r,n,s){this.wrap(()=>{let o=this.buildPayload({distinct_id:e,event:r,properties:n});this.enqueue("capture",o,s)})}async captureStatelessImmediate(e,r,n,s){let o=this.buildPayload({distinct_id:e,event:r,properties:n});await this.sendImmediate("capture",o,s)}aliasStateless(e,r,n,s){this.wrap(()=>{let o=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:e}});this.enqueue("alias",o,s)})}async aliasStatelessImmediate(e,r,n,s){let o=this.buildPayload({event:"$create_alias",distinct_id:r,properties:{...n||{},distinct_id:r,alias:e}});await this.sendImmediate("alias",o,s)}groupIdentifyStateless(e,r,n,s,o,i){this.wrap(()=>{let a=this.buildPayload({distinct_id:o||`$${e}_${r}`,event:"$groupidentify",properties:{$group_type:e,$group_key:r,$group_set:n||{},...i||{}}});this.enqueue("capture",a,s)})}async groupIdentifyStatelessImmediate(e,r,n,s,o,i){let a=this.buildPayload({distinct_id:o||`$${e}_${r}`,event:"$groupidentify",properties:{$group_type:e,$group_key:r,$group_set:n||{},...i||{}}});await this.sendImmediate("capture",a,s)}async getRemoteConfig(){await this._initPromise;let e=this.host;e==="https://us.i.posthog.com"?e="https://us-assets.i.posthog.com":e==="https://eu.i.posthog.com"&&(e="https://eu-assets.i.posthog.com");let r=`${e}/array/${this.apiKey}/config`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(r,n,{type:"required",consume:s=>s.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).catch(s=>{this._logger.error("Remote config could not be loaded",s),this._events.emit("error",s)})}async getFlags(e,r={},n={},s={},o={},i=!1){await this._initPromise;let a=i?"&config=true":"",c=`${this.host}/flags/?v=2${a}`,u={token:this.apiKey,distinct_id:e,groups:r,person_properties:n,group_properties:s,...o};n.$device_id&&(u.$device_id=n.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(u.evaluation_contexts=this.evaluationContexts);let l=this.getEvaluationRuntime();l&&(u.evaluation_runtime=l);let d={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(u)};return this._logger.info("Flags URL",c),this.fetchWithRetry(c,d,{type:"required",consume:p=>p.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:lR},this.featureFlagsRequestTimeoutMs).then(p=>({success:!0,response:Gu(p)})).catch(p=>(this._events.emit("error",p),{success:!1,error:this.categorizeRequestError(p)}))}categorizeRequestError(e){if(e instanceof Re)return{type:"api_error",statusCode:e.status};if(e instanceof bt){let r=e.error;return r instanceof Error&&(r.name==="AbortError"||r.name==="TimeoutError")?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,r,n={},s={},o={},i){await this._initPromise;let a=await this.getFeatureFlagDetailStateless(e,r,n,s,o,i);if(a===void 0)return{response:void 0,requestId:void 0};let c=Hn(a.response);return c===void 0&&(c=!1),{response:c,requestId:a.requestId}}async getFeatureFlagDetailStateless(e,r,n={},s={},o={},i){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(r,n,s,o,i,[e]);return a===void 0?void 0:{response:a.flags[e],requestId:a.requestId,evaluatedAt:a.evaluatedAt}}async getFeatureFlagPayloadStateless(e,r,n={},s={},o={},i){await this._initPromise;let a=await this.getFeatureFlagPayloadsStateless(r,n,s,o,i,[e]);if(!a)return;let c=a[e];return c===void 0?null:c}async getFeatureFlagPayloadsStateless(e,r={},n={},s={},o,i){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,r,n,s,o,i)).payloads}async getFeatureFlagsStateless(e,r={},n={},s={},o,i){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,r,n,s,o,i)}async getFeatureFlagsAndPayloadsStateless(e,r={},n={},s={},o,i){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(e,r,n,s,o,i);return a?{flags:a.featureFlags,payloads:a.featureFlagPayloads,requestId:a.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(e,r={},n={},s={},o,i){await this._initPromise;let a={geoip_disable:o??this.disableGeoip};i&&(a.flag_keys_to_evaluate=i);let c=await this.getFlags(e,r,n,s,a);if(!c.success)return;let u=c.response;return u.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),u.quotaLimited?.includes("feature_flags")?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:u?.requestId,quotaLimited:u.quotaLimited}):u}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let e=`${this.host}/api/surveys/?token=${this.apiKey}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},s=(await this.fetchWithRetry(e,r,{type:"required",consume:o=>{if(o.status!==200||!o.json){let i=`Surveys API could not be loaded: ${o.status}`,a=new Error(i);return this._logger.error(a),this._events.emit("error",new Error(i)),Promise.resolve(void 0)}return o.json()}}).catch(o=>{this._logger.error("Surveys API could not be loaded",o),this._events.emit("error",o)}))?.surveys;return s&&this._logger.info("Surveys fetched from API: ",JSON.stringify(s)),s??[]}get props(){return this._props||(this._props=this.getPersistedProperty(me.Props)),this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(me.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(me.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return Vu}persistedQueueKeyForRoute(e){return me.Queue}getActiveQueueRoutes(){return[Vu]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,r,n,s){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let o=this.prepareMessage(r,n);if(o=this.processBeforeEnqueue(o),o===null)return;o=this.normalizeMessage(o);let i=this.persistedQueueKeyForRoute(s??this.getQueueRouteKey(o)),a=this.getPersistedProperty(i)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),a.push({message:o}),this.setPersistedProperty(i,a),this._events.emit(e,o),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=pe(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(e,r,n,s){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let o=this.prepareMessage(r,n);if(o=this.processBeforeEnqueue(o),o!==null){o=this.normalizeMessage(o);try{await this.sendBatch([o],void 0,s??this.getQueueRouteKey(o))}catch(i){this._events.emit("error",i)}}}normalizeMessage(e){let{type:r,library:n,library_version:s,...o}=e,i=Rh(o.properties)?o.properties:void 0;return n!==void 0&&i?.$lib===void 0&&(i={...i||{},$lib:n}),s!==void 0&&i?.$lib_version===void 0&&(i={...i||{},$lib_version:s}),i&&(o.properties=i),o.uuid=or(o.uuid,fe),o}normalizeTimestampForWire(e){let r=e instanceof Date?e:typeof e=="string"?new Date(e):null;if(!r||Number.isNaN(r.getTime()))return e;let n=r.toISOString(),s=typeof e=="string"?e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return s&&s.length>3?n.replace(/\.\d{3}Z$/,`.${s}Z`):n}prepareMessage(e,r){let n={...e,timestamp:r?.timestamp?r?.timestamp:ku(),uuid:or(r?.uuid,fe)};return(r?.disableGeoip??this.disableGeoip)&&(Rh(n.properties)||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId),n}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flushAutomatic().catch(async e=>{await Th(e)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(e,r=[]){let n=r.filter(o=>!!o),s=0;for(;;){let o=this.promiseQueue.getPromises([...n,...this.flushPromises],e);if(o.length===0)return;s>0&&this._logger.debug(`flush() re-checking ${o.length} pending promise(s) before flushing`),await Promise.all(o.map(i=>i.catch(()=>{}))),s++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(e){if(this.disabled)return Promise.resolve();if(!e&&this.pendingFlushPromise)return this.pendingFlushPromise;let r=this.flushPromise,n=this.promiseQueue.maxId,s=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(n,[r,s])}).then(()=>Fn([r])).then(()=>(this.pendingFlushPromise===s&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=s,this.flushPromise=s,this.flushPromises.add(s),this.addPendingPromise(s),Fn([s]).then(()=>{this.flushPromises.delete(s),this.pendingFlushPromise===s&&(this.pendingFlushPromise=null),this.flushPromise===s&&(this.flushPromise=null)}),s}getCustomHeaders(){let e=this.getCustomUserAgent(),r={};return e&&e!==""&&(r["User-Agent"]=e),r}compressPayload(e){return Gn(e,this.isDebug)}getBatchEndpointPath(e){return"/batch/"}async sendBatch(e,r,n=Vu){let s={api_key:this.apiKey,batch:e.map(u=>{if(!u)return u;let l=this.normalizeTimestampForWire(u.timestamp);return l===u.timestamp?u:{...u,timestamp:l}}),sent_at:ku()};this.historicalMigration&&(s.historical_migration=!0);let o=Nt(s),i=`${this.host}${this.getBatchEndpointPath(n)}`,a=this.disableCompression?null:await this.compressPayload(o),c={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...a!==null&&{"Content-Encoding":"gzip"}},body:a||o};await this.fetchWithRetry(i,c,{type:"successful-write"},r)}async _flush(){this.clearFlushTimer(),await this._initPromise;let e=this.getActiveQueueRoutes();if(!e.some(s=>this.getRouteQueue(s).length>0))return;let r=[],n;for(let s of e)try{await this._flushRoute(s,r)}catch(o){n===void 0&&(n=o)}if(n!==void 0)throw n;this._events.emit("flush",r)}async _flushRoute(e,r){let n=this.persistedQueueKeyForRoute(e),s=this.getPersistedProperty(n)||[];if(!s.length)return;let o=s.length,i=0;for(;s.length>0&&i<o;){let a=s.slice(0,this.maxBatchSize),c=a.map(d=>d.message===void 0?d.message:this.normalizeMessage(d.message)),u=async()=>{let d=this.getPersistedProperty(n)||[],p=[...a],g=d.filter(m=>{let h=m.message?.uuid,_=p.findIndex(S=>S===m||typeof h=="string"&&h.length>0&&S.message?.uuid===h);return _===-1?!0:(p.splice(_,1),!1)});this.setPersistedProperty(n,g),s=g,this._dequeuedMessagesCount+=a.length,await this.flushStorage()},l={retryCheck:d=>Xr(d)?!1:pi(d)};try{await this.sendBatch(c,l,e)}catch(d){if(Xr(d)&&c.length>1){this.maxBatchSize=Math.max(1,Math.floor(c.length/2)),this._logger.warn(`Received 413 when sending batch of size ${c.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw d instanceof bt||await u(),this._events.emit("error",d),d}await u(),r.push(...c),i+=c.length}}async _sendOtlpBatch({path:e,auth:r,payload:n}){if(this.disabled)return{kind:"fatal",error:new Error("The client is disabled")};let s;try{s=JSON.stringify(n)}catch(l){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${e} batch; reporting it as too large`,l)),{kind:"too-large",measuredLocally:!0}}let o=vh(s);if(o>Ih)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${e} batch of ${o} bytes: the endpoint accepts at most ${Ih}`)),{kind:"too-large",measuredLocally:!0};let i=r==="bearer"?`${this.host}/i/v1/${e}`:`${this.host}/i/v1/${e}?token=${encodeURIComponent(this.apiKey)}`,a=this.disableCompression?null:await this.compressPayload(s),c=a||s,u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...r==="bearer"&&{Authorization:`Bearer ${this.apiKey}`},...a!==null&&{"Content-Encoding":"gzip"}},body:c};try{return await this.fetchWithRetry(i,u,{type:"successful-write"},{retryCheck:l=>Xr(l)||l instanceof Re&&l.retryAfterMs!==void 0?!1:pi(l)}),{kind:"ok"}}catch(l){if(Xr(l))return{kind:"too-large"};if(pi(l)){let d=l instanceof Re?l.retryAfterMs:void 0;return{kind:"retry-later",error:l,...d!==void 0&&{retryAfterMs:d}}}return{kind:"fatal",error:l}}}async _sendLogsBatch(e){return this._sendOtlpBatch({path:"logs",auth:"query-token",payload:e})}async _sendMetricsBatch(e){return this._sendOtlpBatch({path:"metrics",auth:"query-token",payload:e})}async _sendTracesBatch(e){return this._sendOtlpBatch({path:"traces",auth:"bearer",payload:e})}async fetchWithRetry(e,r,n,s,o){let i=r.body?r.body:"",a=vh(i),c={...this._retryOptions,...s},u=0;return await th(async()=>{u++;let l=new AbortController,d=o??this.requestTimeout,p=Date.now()+d,g,m=new Promise((w,T)=>{g=pe(()=>{let y=Wr("AbortError",`Request timed out after ${d}ms`);T(y),l.abort(y)},d)}),h,_=!1,S,b=()=>S??=(async()=>{try{await h?.body?.cancel()}catch{}})();try{let w;try{w=this.fetch(e,{signal:l.signal,...r})}catch(A){throw new bt(A)}w.then(A=>{l.signal.aborted&&!_&&Promise.resolve(A.body?.cancel()).catch(()=>{})}).catch(()=>{});try{h=await Promise.race([w,m]),_=!0}catch(A){throw new bt(A)}let T=r.mode==="no-cors",y=n.type==="successful-write"?300:400;if(!T&&(h.status<200||h.status>=y))throw new Re(h,a,p,l);if(n.type==="successful-write"){try{await Promise.race([b(),m])}catch{}return}try{return await Promise.race([n.consume(h),m])}catch(A){throw l.signal.aborted?new bt(A):A}}finally{clearTimeout(g),l.signal.aborted&&h&&b()}},{...c,retryCheck:l=>{let d=c.retryCheck(l);return d&&u<=c.retryCount&&l instanceof Re&&l.cancelResponseBody(),d}})}async _shutdown(e=3e4){await this._initPromise;let r=!1;return this.clearFlushTimer(),this.disabled?void 0:Dt((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(i=>this.getRouteQueue(i).length>0);){let o=this._dequeuedMessagesCount;if(await this.flush(),r)break;if(this._dequeuedMessagesCount===o){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(s){if(!uR(s))throw s;await Th(s)}})(),e,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:e}),r=!0})}async shutdown(e=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}};var mR=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi;var fU=new RegExp(mR.source,"i"),Oh=/[a-z][a-z0-9+.-]{0,63}:\/\//i,pU=new RegExp(`^${Oh.source}`,"i"),gU=new RegExp(Oh.source,"gi");var hR=["is_not","is_set"],_R=1152921504606847e3,P=class t extends Error{constructor(e){super(e),this.name=this.constructor.name,Object.setPrototypeOf(this,t.prototype)}};function Yu(t){if(typeof t=="boolean")return!0;if(typeof t=="string"){let e=t.toLowerCase();return e==="true"||e==="false"}if(!Array.isArray(t))return!1;for(let e=0;e<t.length;e++)if(!Yu(e in t?t[e]:null))return!1;return!0}function qu(t){if(typeof t=="boolean")return t;if(typeof t=="string")return t.toLowerCase()==="true";if(!Array.isArray(t))return!1;for(let e=0;e<t.length;e++)if(!qu(e in t?t[e]:null))return!1;return!0}function Vn(t){for(let e=0;e<t.length;e++){let r=t.charCodeAt(e);if(r>=55296&&r<=56319){let n=t.charCodeAt(e+1);if(e+1>=t.length||n<56320||n>57343)throw new P("Cannot stringify an unpaired surrogate like the flags service");e++}else if(r>=56320&&r<=57343)throw new P("Cannot stringify an unpaired surrogate like the flags service")}}function mi(t,e=new Set){if(!(t===null||typeof t=="boolean")){if(typeof t=="string")return void Vn(t);if(typeof t=="number"){if(!Number.isFinite(t))throw new P(`Cannot represent non-finite number ${t} like the flags service`);return}if(Array.isArray(t)){if(e.has(t))throw new P("Cannot represent a circular array during local evaluation");e.add(t);try{for(let r=0;r<t.length;r++)r in t&&mi(t[r],e)}finally{e.delete(t)}return}if(typeof t=="object"){let r=Object.getPrototypeOf(t);if(r!==Object.prototype&&r!==null)throw new P("Cannot represent a non-JSON object like the flags service");if(e.has(t))throw new P("Cannot represent a circular object during local evaluation");e.add(t);try{for(let n of Object.keys(t))Vn(n),mi(t[n],e)}finally{e.delete(t)}return}throw new P(`Cannot represent ${typeof t} like the flags service`)}}function ER(t,e){let r=0,n=0;for(;r<t.length&&n<e.length;){let s=t.charCodeAt(r),o=e.charCodeAt(n),i=s>=55296&&s<=56319,a=o>=55296&&o<=56319,c=i?t.charCodeAt(r+1):0,u=a?e.charCodeAt(n+1):0,l=i?(s-55296)*1024+c-56320+65536:s,d=a?(o-55296)*1024+u-56320+65536:o;if(l!==d)return l-d;r+=i?2:1,n+=a?2:1}return t.length-e.length}function Ju(t,e=new Set){if(t===null)return"null";if(typeof t=="string")return Vn(t),JSON.stringify(t);if(typeof t=="boolean")return t?"true":"false";if(typeof t=="number"){if(!Number.isFinite(t))throw new P(`Cannot stringify non-finite number ${t} like the flags service`);if(Number.isInteger(t))throw new P(`Cannot distinguish integer ${t} from an integral JSON float during local evaluation`);return String(t)}if(Array.isArray(t)){if(e.has(t))throw new P("Cannot stringify a circular array during local evaluation");e.add(t);try{let r=[];for(let n=0;n<t.length;n++)r.push(n in t?Ju(t[n],e):"null");return`[${r.join(",")}]`}finally{e.delete(t)}}if(typeof t=="object"){let r=Object.getPrototypeOf(t);if(r!==Object.prototype&&r!==null)throw new P("Cannot stringify a non-JSON object like the flags service");if(e.has(t))throw new P("Cannot stringify a circular object during local evaluation");e.add(t);try{let n=Object.keys(t);return n.forEach(Vn),`{${n.sort(ER).map(s=>`${JSON.stringify(s)}:${Ju(t[s],e)}`).join(",")}}`}finally{e.delete(t)}}throw new P(`Cannot stringify ${typeof t} like the flags service`)}function gi(t){return typeof t=="string"?(Vn(t),t):Ju(t)}function Ph(t){try{return new RegExp(t),!0}catch{return!1}}function Ae(t){return String(t).replace(/[A-Z]/g,e=>e.toLowerCase())}function xh(t,e,r){if(!/^\d+$/.test(t)||r==="strict"&&t.length>1&&t[0]==="0")throw new P(`Invalid semver: ${e}`);return parseInt(t,10)}function q(t,e="strict"){let n=String(t).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!n||n.startsWith("."))throw new P(`Invalid semver: ${t}`);let s=n.split("."),o=i=>i===void 0||i===""?0:xh(i,t,e);return[o(s[0]),o(s[1]),o(s[2])]}function Oe(t,e){for(let r=0;r<3;r++){if(t[r]<e[r])return-1;if(t[r]>e[r])return 1}return 0}function SR(t,e){let r=q(t,e);return{lower:[r[0],r[1],r[2]],upper:[r[0],r[1]+1,0]}}function yR(t,e){let[r,n,s]=q(t,e),o=[r,n,s],i;return i=r>0?[r+1,0,0]:n>0?[0,n+1,0]:[0,0,s+1],{lower:o,upper:i}}function bR(t,e){let n=String(t).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!n)throw new P(`Invalid wildcard semver: ${t}`);let s=n.split("."),o=c=>{if(e==="legacy-permissive"){let u=parseInt(c,10);if(!isNaN(u))return u}else try{return xh(c,t,e)}catch{}throw new P(`Invalid wildcard semver: ${t}`)},i=o(s[0]);if(s.length===1)return{lower:[i,0,0],upper:[i+1,0,0]};let a=o(s[1]);return{lower:[i,a,0],upper:[i,a+1,0]}}function Mh(t){if(t instanceof Date)return t;if(typeof t=="string"||typeof t=="number"){let e=new Date(t);if(!isNaN(e.valueOf()))return e;throw new P(`${t} is in an invalid date format`)}throw new P(`The date provided ${t} must be a string, number, or date object`)}function Qu(t){let e=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=t.match(e),n=new Date(new Date().toISOString());if(!r||!r.groups)return null;let s=parseInt(r.groups.number);if(s>=1e4)return null;let o=r.groups.interval;if(o==="h")n.setUTCHours(n.getUTCHours()-s);else if(o==="d")n.setUTCDate(n.getUTCDate()-s);else if(o==="w")n.setUTCDate(n.getUTCDate()-7*s);else if(o==="m")n.setUTCMonth(n.getUTCMonth()-s);else{if(o!=="y")return null;n.setUTCFullYear(n.getUTCFullYear()-s)}return n}function Zu(t,e,r={}){let n=t.key,s=t.value,o=t.operator||"exact",i=r.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(e,n)){if(o==="is_not_set")return!1;if(o==="is_set")return!0}else throw new P(`Property ${n} not found in propertyValues`);let c=e[n];if(c===void 0)return r.warnFunction?.(`Property ${n} cannot have a value of undefined with the ${o} operator`),o==="is_not";if(c===null&&!hR.includes(o)&&o!=="exact"&&o!=="is_not")return r.warnFunction?.(`Property ${n} cannot have a value of null with the ${o} operator`),!1;let u=(d,p)=>{if(r.propertyMatchingVersion!==2&&Yu(d)||Array.isArray(d)&&d.length===0)return mi(p),qu(d)===qu(p);if(r.propertyMatchingVersion===2&&typeof p=="number"&&Yu(d))return mi(p),!1;if(Array.isArray(d)){let g=gi(p).toLowerCase();return d.some(m=>gi(m).toLowerCase()===g)}return gi(d).toLowerCase()===gi(p).toLowerCase()},l=(d,p,g)=>{if(g==="gt")return d>p;if(g==="gte")return d>=p;if(g==="lt")return d<p;if(g==="lte")return d<=p;throw new Error(`Invalid operator: ${g}`)};switch(o){case"exact":return u(s,c);case"is_not":return!u(s,c);case"is_set":return!0;case"icontains":return Ae(c).includes(Ae(s));case"not_icontains":return!Ae(c).includes(Ae(s));case"starts_with":return Ae(c).startsWith(Ae(s));case"not_starts_with":return!Ae(c).startsWith(Ae(s));case"ends_with":return Ae(c).endsWith(Ae(s));case"not_ends_with":return!Ae(c).endsWith(Ae(s));case"regex":return Ph(String(s))&&String(c).match(String(s))!==null;case"not_regex":return Ph(String(s))&&String(c).match(String(s))===null;case"gt":case"gte":case"lt":case"lte":{let d=typeof s=="number"?s:parseFloat(String(s)),p=typeof c=="number"?c:c!=null?parseFloat(String(c)):NaN;return Number.isFinite(d)&&Number.isFinite(p)?l(p,d,o):l(String(c),String(s),o)}case"is_date_after":case"is_date_before":{if(typeof s=="boolean")throw new P("Date operations cannot be performed on boolean values");let d=Qu(String(s));d==null&&(d=Mh(s));let p=Mh(c);return o==="is_date_before"?p<d:p>d}case"semver_eq":return Oe(q(String(c),i),q(String(s),i))===0;case"semver_neq":return Oe(q(String(c),i),q(String(s),i))!==0;case"semver_gt":return Oe(q(String(c),i),q(String(s),i))>0;case"semver_gte":return Oe(q(String(c),i),q(String(s),i))>=0;case"semver_lt":return Oe(q(String(c),i),q(String(s),i))<0;case"semver_lte":return Oe(q(String(c),i),q(String(s),i))<=0;case"semver_tilde":{let d=q(String(c),i),{lower:p,upper:g}=SR(String(s),i);return Oe(d,p)>=0&&Oe(d,g)<0}case"semver_caret":{let d=q(String(c),i),{lower:p,upper:g}=yR(String(s),i);return Oe(d,p)>=0&&Oe(d,g)<0}case"semver_wildcard":{let d=q(String(c),i),{lower:p,upper:g}=bR(String(s),i);return Oe(d,p)>=0&&Oe(d,g)<0}default:throw new P(`Unknown operator: ${o}`)}}async function kh(t){let e=globalThis.crypto?.subtle;if(!e)throw new Error("SubtleCrypto API not available");let r=await e.digest("SHA-1",new TextEncoder().encode(t));return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}async function Yn(t,e,r="",n="."){let s=await kh(`${t}${n}${e}${r}`);return parseInt(s.slice(0,15),16)/_R}async function el(t,e){if(t==null||t.id==null||t.exclusion_percentage==null)return;let r=Number(t.exclusion_percentage);if(!Number.isFinite(r))return;let n=Math.min(Math.max(r,0),100);if(!(n!==100&&await Yn("holdout",e,"","-")>n/100))return`holdout-${t.id}`}function hi(t){let e=[],r=0;for(let n of t){let s=r+n.rollout_percentage/100;e.push({valueMin:r,valueMax:s,key:n.key}),r=s}return e}async function tl(t,e,r){let n=await Yn(t,e,"variant");return hi(r).find(s=>n>=s.valueMin&&n<s.valueMax)?.key}function rl(t,e){if(e===!1||e==null||!t)return null;let r=typeof e=="boolean"?e.toString():e,n=t[r]||null;return n==null?null:Hr(n)}var Nh=9223372036854776e3,wR="9223372036854775808",TR=Object.prototype.propertyIsEnumerable;function IR(){return{ancestors:new WeakSet,remainingNodes:1e4}}function rt(t,e){try{return Ch(t,e,IR(),0)}catch{return[]}}function vR(t,e){let r=t.toString(),n=BigInt(wR);return t>=n||t<-n?(e?.debug(`Attribute ${r} is outside the int64 range; encoding it as a string`),{stringValue:r}):{intValue:r}}function ol(t,e,r,n){if(r.remainingNodes<=0)return{stringValue:ai};if(r.remainingNodes--,Mm(t))return{boolValue:t};if(typeof t=="bigint")return vR(t,e);if(typeof t=="number"){if(!Number.isFinite(t))return{stringValue:String(t)};if(Number.isInteger(t)){if(Number.isSafeInteger(t))return{intValue:String(t)};if("u"<typeof BigInt)return{stringValue:String(t)};let s=BigInt(t).toString();return t>=Nh||t<-Nh?(e?.debug(`Attribute ${s} is outside the int64 range; encoding it as a string`),{stringValue:s}):{intValue:s}}return{doubleValue:t}}if(typeof t=="string")return{stringValue:et(t)};if(typeof t=="function")return{stringValue:Qm};if(typeof t=="symbol")return{stringValue:String(t)};if(typeof t=="object"&&t!==null){if(r.ancestors.has(t))return{stringValue:ii};if(n>=20)return{stringValue:ai};if(t instanceof Date){let s=t.getTime(),o=Number.isFinite(s)?t.toISOString():String(t);return{stringValue:typeof o=="string"?et(o):String(o)}}r.ancestors.add(t);try{try{let s=t.toJSON;if(typeof s=="function")return ol(s.call(t),e,r,n+1)}catch{}return Se(t)?{arrayValue:{values:RR(t,e,r,n+1)}}:{kvlistValue:{values:Ch(t,e,r,n+1)}}}finally{r.ancestors.delete(t)}}return{stringValue:et(String(t))}}function RR(t,e,r,n){let s=[],o=Math.min(t.length,1e3),i=0;for(;i<o&&r.remainingNodes>0;i++)try{let a=i in t?t[i]:void 0;if(He(a))continue;s.push(ol(a,e,r,n))}catch{s.push({stringValue:ve})}return t.length>i&&s.push({stringValue:ai}),s}function Ch(t,e,r,n){let s=[];for(let o in t)if(TR.call(t,o)){if(!o){e?.debug("Dropping an attribute with an empty key");continue}if(s.length>=1e3||r.remainingNodes<=0){e?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let i=t[o];if(Tu(i)||St(i))continue;s.push({key:et(o),value:ol(i,e,r,n)})}catch{s.push({key:et(o),value:{stringValue:ve}})}}return s}function Jn(t,e,r){return{...yt({},t.resourceAttributes),"service.name":t.serviceName||"unknown_service",...t.environment&&{"deployment.environment":t.environment},...t.serviceVersion&&{"service.version":t.serviceVersion},"telemetry.sdk.name":e,"telemetry.sdk.version":r}}var AR=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function Qn(t,e){let r=yt({},t),n={};for(let s of AR)Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s],delete r[s]);return[...rt(r,e),...rt(n,e)]}var Dh={darwin:"macOS",win32:"Windows",cygwin:"Windows",linux:"Linux",android:"Android",freebsd:"FreeBSD",openbsd:"OpenBSD",netbsd:"NetBSD",sunos:"SunOS",aix:"AIX",haiku:"Haiku","Mac OS X":"macOS"};function OR(t){if(t)return Object.prototype.hasOwnProperty.call(Dh,t)?Dh[t]:t}function il(t,e){let r=OR(t);return{...r?{"os.name":r}:{},...e?{"os.version":e}:{}}}var PR={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},MU=PR.info;var ir=class{constructor(e){this._onFire=e,this._firesAt=0}get pending(){return!!this._timer}arm(e){this.clear(),this._firesAt=Date.now()+e,this._timer=pe(()=>{this._timer=void 0,this._onFire()},e)}armNoEarlierThan(e){this._timer&&Date.now()+e<=this._firesAt||this.arm(e)}clear(){this._timer&&(clearTimeout(this._timer),this._timer=void 0)}};function Zn(){return 1-.25+Math.random()*.25*2}var Pe=1;function es(t,e,r,n){let s=Math.min(Math.max(0,e-1),6),o=t*2**s,i=n===void 0?o:Math.min(o,Math.max(n,t));return Math.round(i*r)}var al="0000000000000000",NR=al+al,CR=/^[0-9a-f]+$/;function DR(t){let e=new Uint8Array(t),r=globalThis.crypto;if(r&&typeof r.getRandomValues=="function")try{return r.getRandomValues(e),e}catch{}for(let n=0;n<t;n++)e[n]=Math.floor(256*Math.random());return e}function FR(t){let e="";for(let r=0;r<t.length;r++)e+=t[r].toString(16).padStart(2,"0");return e}function Fh(t){let e=FR(DR(t));return/[^0]/.test(e)?e:e.slice(0,-1)+"1"}function Lh(){return Fh(16)}function Uh(){return Fh(8)}function $h(t,e,r){return typeof t=="string"&&t.length===e&&t!==r&&CR.test(t)}function Bh(t){return $h(t,32,NR)}function Wh(t){return $h(t,16,al)}var LR=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function Ei(t){let e=jh(t);return e&&{traceId:e.traceId,spanId:e.spanId,flags:UR(e.flags)}}function UR(t){return 1&parseInt(t,16)?Kr:$R}function jh(t){if(typeof t!="string")return;let e=LR.exec(t.trim());if(!e)return;let[,r,n,s,o,i]=e;if(r!=="ff"&&!(r==="00"&&i)&&!(!Bh(n)||!Wh(s)))return{version:r,traceId:n,spanId:s,flags:o}}function Hh(t){return jh(t)&&t.trim()}function Si(t){return Array.isArray(t)&&t.length===1?t[0]:t}var Kr="01",$R="00";function Xh(t,e,r=Kr){return`00-${t}-${e}-${r}`}var BR=32,cl=512;function yi(t){if(typeof t!="string")return;let e=t.trim();if(!e||/[^\x20-\x7e\t]/.test(e))return;let r=e.split(",");if(!(r.length>BR)){for(let n of r)if(n.trim()&&!n.includes("="))return;return e.length<=cl?e:jR(r)}}var WR=128;function jR(t){let e=[...t],r=()=>e.reduce((n,s)=>n+s.length,0)+e.length-1;for(let n=e.length-1;n>=0&&r()>cl;n--)e[n].length>WR&&e.splice(n,1);for(;e.length&&r()>cl;)e.pop();return e.length?e.join(","):void 0}var ts=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function bi(t){return String(t)+"000000"}function ul(t,e,r,n){let s="";return n&&(s=Object.keys(n).sort().map(i=>`${JSON.stringify(i)}:${JSON.stringify(n[i])}`).join(",")),`${t}\0${e}\0${r??""}\0${s}`}function Kh(t,e){for(let r=0;r<e.length;r++)if(t<=e[r])return r;return e.length}function ll(t,e,r){return Jn(t,e,r)}function dl(t,e,r,n){return{resourceMetrics:[{resource:{attributes:Qn(e)},scopeMetrics:[{scope:{name:r,version:n},metrics:t}]}]}}function wi(t){let e=t?.resourceAttributes;return{serviceName:e?.["service.name"]??t?.serviceName,serviceVersion:e?.["service.version"]??t?.serviceVersion,environment:e?.["deployment.environment"]??t?.environment,resourceAttributes:e,beforeSend:t?.beforeSend,flushIntervalMs:t?.flushIntervalMs??1e4,maxSeriesPerFlush:t?.maxSeriesPerFlush??1e3}}var Gh=1,rs=class{constructor(e,r,n){this._instance=e,this._config=r,this._logger=n,this._series=new Map,this._flushTimer=new ir(()=>this.flush().catch(s=>{this._logger.error("Metrics flush failed:",s)})),this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._retryAfter=new sr,this._consecutiveFlushFailures=0,this._flushJitter=Pe,this._generation=0}count(e,r=1,n){this._capture({name:e,type:"count",value:r,unit:n?.unit,attributes:n?.attributes})}gauge(e,r,n){this._capture({name:e,type:"gauge",value:r,unit:n?.unit,attributes:n?.attributes})}histogram(e,r,n){this._capture({name:e,type:"histogram",value:r,unit:n?.unit,attributes:n?.attributes})}flush(){let e=this._flushPromise,n=(async()=>{e&&await e.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===n&&(this._flushPromise=null)});return this._flushPromise=n,n}drainWindow(){if(this._series.size===0)return null;let e=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(e)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=Pe,this._flushTimer.clear(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(e){if(this._instance.isDisabled||this._instance.optedOut)return;let r=this._runBeforeSend(e);if(r===null)return;if(!r.name||typeof r.name!="string")return void this._logger.warn("Dropping metric with empty name");if(typeof r.value!="number"||!Number.isFinite(r.value))return void this._logger.warn(`Dropping metric '${r.name}': value must be a finite number`);if(r.type==="count"&&r.value<0)return void this._logger.warn(`Dropping count '${r.name}': counters are monotonic, value must be >= 0`);let n,s;try{n=r.attributes?{...r.attributes}:void 0,s=ul(r.type,r.name,r.unit,n)}catch(c){this._logger.warn(`Dropping metric '${r.name}': attributes could not be serialized`,c);return}let o=this._series.get(s);if(!o){if(!this._admitNewSeries())return;o={name:r.name,type:r.type,unit:r.unit,attributes:n,windowStartMs:Date.now()},this._series.set(s,o)}let i=this._typeByName.get(r.name);i===void 0?this._typeByName.set(r.name,r.type):i!==r.type&&!this._typeCollisionWarned.has(r.name)&&(this._typeCollisionWarned.add(r.name),this._logger.warn(`Metric name '${r.name}' is already used as a ${i}; recording it as a ${r.type} too will blend both series in charts. Use a distinct name.`)),this._fold(o,r.value);let a=this._activeTraceContext();a&&(o.exemplar={...a,value:r.value,timeMs:Date.now()}),this._armFlushTimer()}_activeTraceContext(){try{let e=Ei(this._instance.getActiveSpan?.()?.traceparent());if(e&&e.flags===Kr)return{traceId:e.traceId,spanId:e.spanId}}catch{}}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush?!0:(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_fold(e,r){switch(e.type){case"count":e.total=(e.total??0)+r;break;case"gauge":e.last=r;break;case"histogram":{e.hist||(e.hist={count:0,sum:0,min:r,max:r,bucketCounts:new Array(ts.length+1).fill(0)});let n=e.hist;n.count+=1,n.sum+=r,n.min=Math.min(n.min,r),n.max=Math.max(n.max,r),n.bucketCounts[Kh(r,ts)]+=1;break}}}_runBeforeSend(e){let r=this._config.beforeSend;if(!r)return e;let n=Se(r)?r:[r],s=e;for(let o of n)try{let i=o(s);if(!i)return this._logger.info("Metric was rejected in beforeSend function"),null;s=i}catch(i){return this._logger.error("Error in beforeSend function for metric:",i),null}return s}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(es(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),this._series.size===0)return;let e=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let r=this._generation,n=await this._instance._sendMetricsBatch(this._buildPayload(e));if(r===this._generation)switch(this._retryAfter.record(n),n.kind==="retry-later"?(this._consecutiveFlushFailures++,this._flushJitter=Zn()):(this._consecutiveFlushFailures=0,this._flushJitter=Pe),this._flushTimer.pending&&this._flushTimer.arm(this._nextFlushDelay()),n.kind){case"ok":return;case"retry-later":this._mergeWindowBack(e),this._flushTimer.armNoEarlierThan(this._nextFlushDelay());return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",n.error);return}}_buildPayload(e){return dl(this._buildMetrics(e),ll(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(e){let r=bi(Date.now()),n=new Map;for(let s of e.values()){let o=ul(s.type,s.name,s.unit,void 0),i=n.get(o);i||(i={name:s.name,...s.unit&&{unit:s.unit}},s.type==="count"?i.sum={aggregationTemporality:Gh,isMonotonic:!0,dataPoints:[]}:s.type==="gauge"?i.gauge={dataPoints:[]}:i.histogram={aggregationTemporality:Gh,dataPoints:[]},n.set(o,i));let a=rt(s.attributes??{},this._logger),c=bi(s.windowStartMs),u=HR(s.exemplar);if(s.type==="count"){let l={attributes:a,startTimeUnixNano:c,timeUnixNano:r,asDouble:s.total??0,...u};i.sum.dataPoints.push(l)}else if(s.type==="gauge"){let l={attributes:a,timeUnixNano:r,asDouble:s.last??0,...u};i.gauge.dataPoints.push(l)}else if(s.hist){let l={attributes:a,startTimeUnixNano:c,timeUnixNano:r,count:s.hist.count,sum:s.hist.sum,min:s.hist.min,max:s.hist.max,bucketCounts:s.hist.bucketCounts,explicitBounds:ts,...u};i.histogram.dataPoints.push(l)}}return Array.from(n.values())}_mergeWindowBack(e){for(let[r,n]of e){let s=this._series.get(r);if(!s){this._admitNewSeries()&&this._series.set(r,n);continue}switch(s.windowStartMs=Math.min(s.windowStartMs,n.windowStartMs),s.exemplar=s.exemplar??n.exemplar,s.type){case"count":s.total=(s.total??0)+(n.total??0);break;case"gauge":break;case"histogram":if(n.hist)if(s.hist){s.hist.count+=n.hist.count,s.hist.sum+=n.hist.sum,s.hist.min=Math.min(s.hist.min,n.hist.min),s.hist.max=Math.max(s.hist.max,n.hist.max);for(let o=0;o<s.hist.bucketCounts.length;o++)s.hist.bucketCounts[o]+=n.hist.bucketCounts[o]}else s.hist=n.hist;break}}}};function HR(t){return t?{exemplars:[{filteredAttributes:[],timeUnixNano:bi(t.timeMs),asDouble:t.value,traceId:t.traceId,spanId:t.spanId}]}:{}}var zh="unknown";function ar(t,e,r,n){return typeof t=="string"&&t.trim()?t.length>r?t.slice(0,r):t:(n?.debug(`${e} must be a non-empty string; using "${zh}"`),zh)}function Gr(t){if(t==null)return;let e=t;if(t instanceof Date)try{e=t.getTime()}catch{return}if(!(typeof e!="number"||!Number.isFinite(e))&&!(e<0||e>9223372036854))return e}function Vh(t,e,r){let n=Gr(t);return n===void 0?(t!==void 0&&r?.debug("Span startTime is out of range or not a valid time; using the current time"),e):(e-n>864e5?r?.debug("Span startTime is more than 24 hours in the past; the server will clamp it to receive time and keep the original in $originalTimestamp"):n>e&&r?.debug("Span startTime is in the future; the span may export with a zero duration"),n)}function Ti(t,e){return t<e?e:t}function ns(t,e,r,n){let s=Gr(t);return s===void 0?(t!==void 0&&n?.debug(`Span ${r} is out of range or not a valid time; using the derived time`),e):s}function vi(){let t=globalThis.performance;return typeof t?.now=="function"?t.now():void 0}var zr=class{constructor(e,r,n){this._onEnd=r,this._logger=n,this._events=[],this._ended=!1,this._userAttributeCount=0,this._userEventCount=0,this._droppedAttributes=0,this._droppedEvents=0,this._traceId=e.traceId,this._spanId=e.spanId,this._parentSpanId=e.parentSpanId,this._traceState=e.traceState,this._traceFlags=e.traceFlags??Kr,this._parentIsRemote=e.parentIsRemote??!1,this._name=e.name,this._kind=e.kind,this._autoKeys=new Set(e.autoAttributeKeys),this._maxAttributes=e.maxAttributes,this._maxEvents=e.maxEvents,this._maxAttributesPerEvent=e.maxAttributesPerEvent,this._maxAttributeValueLength=e.maxAttributeValueLength,this._attributes=Object.create(null);for(let s of Object.keys(e.attributes))this._writeAttribute(s,e.attributes[s]);this._startMono=e.backdated?void 0:vi(),this._startTime=e.clockAnchor&&this._startMono!==void 0?e.clockAnchor.wall+(this._startMono-e.clockAnchor.mono):e.startTime,this._startMono!==void 0&&(this._clockAnchor=e.clockAnchor??{wall:this._startTime,mono:this._startMono})}_now(){if(this._startMono!==void 0){let e=vi();if(e!==void 0)return this._startTime+Math.max(0,e-this._startMono)}return Date.now()}_mutable(e){return this._ended?(this._logger?.debug(`Ignoring ${e} on a span that has already ended`),!1):!0}_writeAttribute(e,r){if(He(r)){e in this._attributes&&!this._autoKeys.has(e)&&this._userAttributeCount--,delete this._attributes[e];return}if(!this._autoKeys.has(e)&&!(e in this._attributes)){if(this._userAttributeCount>=this._maxAttributes)return void this._droppedAttributes++;this._userAttributeCount++}this._attributes[e]=Ai(r,this._maxAttributeValueLength)}setAttribute(e,r){return this._mutable("setAttribute")&&this._writeAttribute(e,r),this}setAttributes(e){if(this._mutable("setAttributes")){let r=yt({},e);for(let n of Object.keys(r))this._writeAttribute(n,r[n])}return this}addEvent(e,r,n){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let s=r&&Qh(r,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:ar(e,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:ns(n,this._now(),"event timestamp",this._logger),...s&&{attributes:s.attributes,...s.dropped&&{droppedAttributesCount:s.dropped}}})}return this}setStatus(e,r){if(this._mutable("setStatus")){if(e!=="ok"&&e!=="error")return this._logger?.debug(`Ignoring unknown span status "${String(e)}"; expected "ok" or "error"`),this;this._status={code:e,...r&&{message:fl(r,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(e){if(!this._mutable("recordException"))return this;let{type:r,message:n,stack:s}=pl(e);return this.addEvent(XR,{"exception.type":r,"exception.message":n,...s&&{"exception.stacktrace":s}}),this.setStatus("error",n)}updateName(e){return this._mutable("updateName")&&(this._name=ar(e,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return Xh(this._traceId,this._spanId,this._traceFlags)}tracestate(){return this._traceState??null}childContext(){return{traceId:this._traceId,parentSpanId:this._spanId,traceState:this._traceState,traceFlags:this._traceFlags,clockAnchor:this._clockAnchor}}end(e){if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let r=this._now(),n=ns(e,r,"end time",this._logger);this._onEnd({traceId:this._traceId,spanId:this._spanId,...this._parentSpanId&&{parentSpanId:this._parentSpanId},...this._traceState&&{traceState:this._traceState},traceFlags:this._traceFlags,parentIsRemote:this._parentIsRemote,name:this._name,kind:this._kind,...this._status&&{status:this._status},attributes:{...this._attributes},events:this._events,startTime:this._startTime,endTime:Ti(n,this._startTime),...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}},XR="exception",KR=4294967295;function GR(t){try{return typeof t=="string"?t:String(t)}catch{return ve}}function cr(t){return typeof t!="number"||!Number.isFinite(t)||t<=0?0:Math.min(Math.floor(t),KR)}function zR(t,e){if(!e.length)return Object.keys(t);let r=e.filter(s=>Object.prototype.propertyIsEnumerable.call(t,s)),n=new Set(r);return[...r,...Object.keys(t).filter(s=>!n.has(s))]}function qh(t,e,r,n,s,o,i=[]){let a=0,c=0,u={};for(let g of zR(t.attributes,i)){let m=t.attributes[g];if(!He(m)){if(!e.has(g)){if(a>=r){c++;continue}a++}Object.defineProperty(u,g,{value:Ai(m,o),enumerable:!0,writable:!0,configurable:!0})}}t.attributes=u,c&&(t.droppedAttributesCount=cr(t.droppedAttributesCount)+c);let l=0,d=0,p=[];for(let g of t.events){if(l>=n){d++;continue}if(l++,g.attributes){let m=Qh(g.attributes,s,o);g.attributes=m.attributes,m.dropped&&(g.droppedAttributesCount=cr(g.droppedAttributesCount)+m.dropped)}p.push(g)}t.events=p,d&&(t.droppedEventsCount=cr(t.droppedEventsCount)+d),t.status?.message&&(t.status={...t.status,message:fl(GR(t.status.message),o)})}var Ri=class{setAttribute(){return this}setAttributes(){return this}addEvent(){return this}setStatus(){return this}recordException(){return this}updateName(){return this}traceparent(){return null}tracestate(){return null}end(){}},Jh=new Ri,ss=class extends Ri{constructor(e,r){super(),this._traceparent=e,this._tracestate=r}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}};function VR(t){try{let e=t.stack;return typeof e=="string"&&e?{stack:e}:{}}catch{return{}}}function Ft(t,e){let r=Si(t?.parent)??e,n=typeof r=="string"||r==null?r:Yh(r,"traceparent"),s=Hh(n);if(!s)return Jh;let o=typeof r=="string"||r==null?t?.tracestate:Yh(r,"tracestate");return new ss(s,yi(o))}function Yh(t,e){try{let r=t[e];return typeof r=="function"?r.call(t):void 0}catch{return}}function fl(t,e){return t.length>e?t.slice(0,e):t}function Ai(t,e){return Ii(t,e,{ancestors:new WeakSet,remainingNodes:1e4},0)}function Ii(t,e,r,n){if(t===null||typeof t!="object")return He(t)||r.remainingNodes<=0?t:(r.remainingNodes--,typeof t=="string"?fl(t,e):t);if(r.ancestors.has(t))return ii;if(r.remainingNodes<=0||n>=20)return t;r.remainingNodes--,r.ancestors.add(t);try{if(t instanceof Date)return t;let s=YR(t);if(s.selfDescribed)return He(s.value)?String(s.value):Ii(s.value,e,r,n+1);if(Se(t)){let a=Math.min(t.length,1e3),c=[];for(let u=0;u<a;u++)try{c.push(Ii(t[u],e,r,n+1))}catch{c.push(ve)}return t.length>a&&(c.length=t.length),c}let o={},i=0;for(let a of Object.keys(t)){if(i>=1e3)break;let c;try{c=Ii(t[a],e,r,n+1)}catch{c=ve}a&&!He(c)&&i++,Object.defineProperty(o,a,{value:c,enumerable:!0,writable:!0,configurable:!0})}return o}catch{return t}finally{r.ancestors.delete(t)}}function YR(t){try{let e=t.toJSON;if(typeof e=="function")return{selfDescribed:!0,value:e.call(t)}}catch{}return{selfDescribed:!1}}function Qh(t,e,r){let n;try{n=Object.keys(t)}catch{return{attributes:{},dropped:0}}let s={},o=0,i=0;for(let a of n){if(o>=e){i++;continue}let c;try{c=Ai(t[a],r)}catch{c=ve}He(c)||(o++,Object.defineProperty(s,a,{value:c,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:s,dropped:i}}function Zh(t,e){for(let r of Object.keys(t))t[r]=Ai(t[r],e);return t}function os(t,e,r){return e===Jh?r(e):t.with(e,()=>r(e))}function pl(t){try{let e=VR(t);if(Ct(t))return{type:t.name||"Error",message:t.message||"",...e};if(typeof t=="string")return{type:"string",message:t};if(t&&typeof t=="object"){let r=t;if(typeof r.message=="string")return{type:typeof r.name=="string"?r.name:"Object",message:r.message,...e}}return{type:typeof t,message:String(t)}}catch{return{type:typeof t,message:""}}}var gl={internal:1,server:2,client:3,producer:4,consumer:5},qR={ok:1,error:2},JR=1,QR=256,ZR=512;function eA(t){let e=parseInt(t.traceFlags,16);return(Number.isFinite(e)?255&e:JR)|QR|(t.parentIsRemote?ZR:0)}function Oi(t){if(typeof t=="string")return et(t);try{return et(String(t))}catch{return ve}}function tA(t){return t&&Object.prototype.hasOwnProperty.call(gl,t)?gl[t]:gl.internal}function ml(t){let e=Math.floor(t),r=Math.round((t-e)*1e6);return r>=1e6&&(e+=1,r=0),String(e)+String(r).padStart(6,"0")}function rA(t,e){let r={name:Oi(t.name),timeUnixNano:ml(t.timestamp)};if(t.attributes){let s=rt(t.attributes,e);s.length&&(r.attributes=s)}let n=cr(t.droppedAttributesCount);return n&&(r.droppedAttributesCount=n),r}function e_(t,e){let r={traceId:t.traceId,spanId:t.spanId,name:Oi(t.name),kind:tA(t.kind),startTimeUnixNano:ml(t.startTime),endTimeUnixNano:ml(t.endTime),flags:eA(t)};t.parentSpanId&&(r.parentSpanId=t.parentSpanId),t.traceState&&(r.traceState=Oi(t.traceState));let n=rt(t.attributes,e);n.length&&(r.attributes=n),t.events.length&&(r.events=t.events.map(i=>rA(i,e)));let s=cr(t.droppedAttributesCount);s&&(r.droppedAttributesCount=s);let o=cr(t.droppedEventsCount);return o&&(r.droppedEventsCount=o),t.status&&(r.status={code:qR[t.status.code],...t.status.message&&{message:Oi(t.status.message)}}),r}function t_(t,e,r){return Jn(t,e,r)}function r_(t,e,r,n,s){return{resourceSpans:[{resource:{attributes:Qn(e,s)},scopeSpans:[{scope:{name:r,version:n},spans:t}]}]}}var n_=8;function Pi(){return vi()??Date.now()}function hl(t){try{return t instanceof zr}catch{return!1}}function s_(t,e){let r=Ei(t);if(r)return{traceId:r.traceId,parentSpanId:r.spanId,traceState:yi(e),traceFlags:r.flags,isRemote:!0}}function nA(t){try{return typeof t.traceparent=="function"}catch{return!1}}function sA(t){return!!t.attributes&&typeof t.attributes=="object"&&!Array.isArray(t.attributes)&&Array.isArray(t.events)&&t.name!==void 0&&t.kind!==void 0&&t.startTime!==void 0&&t.endTime!==void 0}function Mi(t,e,r){t[e]!==r&&(t[e]=r)}function oA(t,e){try{let r=Object.getOwnPropertyDescriptors(t);for(let n of["traceId","spanId","parentSpanId","traceState"])r[n]={value:e[n],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(t),r)}catch{return t}}var is=class{constructor(e,r,n,s,o,i){this._instance=e,this._config=r,this._logger=n,this._getContext=s,this._contextManager=o,this._onSpanQueued=i,this._queue=[],this._flushTimer=new ir(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=Pe,this._retryAfter=new sr,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=r.maxExportBatchSize}startSpan(e,r){if(this._instance.isDisabled||this._instance.optedOut)return Ft(r,this._contextManager.active());let n=Si(r?.parent);if(n&&typeof n!="string"&&!hl(n)){if(nA(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),Ft(r,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let s=this._resolveParent(n,r);if(this._liveSpans.size>=this._config.maxLiveSpans&&this._evictAgedSpans(),this._liveSpans.size>=this._config.maxLiveSpans)return this._recordDrop(1,`the live-span limit (${this._config.maxLiveSpans}) was reached \u2014 spans are being started and never ended`),Ft(r,this._contextManager.active());let o=Date.now(),i=Vh(r?.startTime,o,this._logger),a=Uh();this._liveSpans.set(a,Pi());let c=this._autoContextAttributes();return new zr({traceId:s?.traceId??Lh(),spanId:a,parentSpanId:s?.parentSpanId,traceState:s?.traceState,traceFlags:s?.traceFlags,parentIsRemote:s?.isRemote,name:ar(e,"Span name",this._config.maxAttributeValueLength,this._logger),kind:r?.kind??"internal",attributes:yt({...c},r?.attributes),autoAttributeKeys:Object.keys(c),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:i,backdated:i!==o,clockAnchor:Gr(r?.startTime)===void 0?s?.clockAnchor:void 0},(u,l)=>this._onSpanEnd(u,l),this._logger)}withSpan(e,r,n){let s=typeof r=="function"?void 0:r,o=typeof r=="function"?r:n,i=this.startSpan(e,s);try{let a=os(this._contextManager,i,o);return rh(a)?a.then(c=>(i.end(),c),c=>{throw this._recordCallbackError(i,c),i.end(),c}):(i.end(),a)}catch(a){throw this._recordCallbackError(i,a),i.end(),a}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;)if(!this._queue.length||!await(this._flushPromise??this._startFlush()))return}_startFlush(){this._flushTimer.clear();let e=this._generation,r=Promise.resolve().then(()=>e===this._generation?this._flushInner():0).finally(()=>{this._flushPromise===r&&(this._flushPromise=null),this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=r,r}reset(){this._flushTimer.clear(),this._queue.length&&this._logger.critical(`Discarding ${this._queue.length} span(s) that were still queued when tracing was shut down. Raise the shutdown timeout or flush earlier if they matter.`),this._queue=[],this._liveSpans.clear(),this._flushPromise=null,this._generation++,this._maxExportBatchSize=this._config.maxExportBatchSize,this._droppedSinceWarning=0,this._dropReasons.clear(),this._lastDropWarningAt=0,this._consecutiveFlushFailures=0,this._flushJitter=Pe,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(e,r){if(typeof e=="string"){let s=s_(e,r?.tracestate);return s||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),s}if(hl(e))return e.childContext();let n=this._contextManager.active();if(hl(n))return n.childContext();if(n instanceof ss)return s_(n.traceparent(),n.tracestate()??void 0)}_autoContextAttributes(){let e;try{e=this._getContext()}catch(n){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",n),{}}let r={};return e.distinctId&&(r.posthogDistinctId=e.distinctId),e.sessionId&&(r.sessionId=e.sessionId),e.currentUrl&&(r["url.full"]=e.currentUrl),e.screenName&&(r["screen.name"]=e.screenName),e.appState&&(r["app.state"]=e.appState),r}_recordCallbackError(e,r){if(!(e instanceof zr))return;let{type:n,message:s,stack:o}=pl(r);e.addEvent("exception",{"exception.type":n,"exception.message":s,...o&&{"exception.stacktrace":o}}),e.statusIsExplicitlyOk||e.setStatus("error",s)}_evictAgedSpans(){let e=Pi()-this._config.maxSpanAgeMs,r=0;for(let[n,s]of this._liveSpans){if(s>e)break;this._liveSpans.delete(n),r++}r&&this._recordDrop(r,`they were still live after ${this._config.maxSpanAgeMs}ms`)}_onSpanEnd(e,r){if(!this._liveSpans.delete(e.spanId))return;if(this._instance.isDisabled||this._instance.optedOut)return void this._recordDrop(1,"the user has opted out");let n=this._runBeforeSpanSend(e,r);if(n){if(this._reportLimitDrops(n),this._queue.length>=this._config.maxQueueSize)return void this._recordDrop(1,`the queue is full (${this._config.maxQueueSize}) \u2014 raise the flush frequency or reduce span volume`);this._queue.push(n);try{this._onSpanQueued?.()}catch(s){this._logger.debug("Span queue notification failed",s)}!(this._queue.length>=this._maxExportBatchSize)||this._consecutiveFlushFailures||this._retryAfter.isOpen()?this._armFlushTimerIfQueued():this._flushInBackground()}}_reportLimitDrops(e){let r=e.droppedAttributesCount??0,n=e.droppedEventsCount??0,s=0;for(let o of e.events)s+=o.droppedAttributesCount??0;(r||n||s)&&this._logger.debug(`Span limits discarded data from "${e.name}": ${r} attributes, ${n} events, ${s} event attributes`)}_runBeforeSpanSend(e,r){if(!this._config.beforeSpanSend.length)return e;let n={traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId,traceState:e.traceState},s={startTime:e.startTime,endTime:e.endTime},o={attributes:e.droppedAttributesCount,events:e.droppedEventsCount},i=Object.keys(e.attributes),a={traceFlags:e.traceFlags,parentIsRemote:e.parentIsRemote},c=e.status&&{...e.status},u=e,l=e;try{for(let g of this._config.beforeSpanSend){let m=g(u);if(!m)return this._recordDrop(1,"beforeSpanSend dropped it"),null;u=this._keepSpanIdentity(m,n)}if(l={traceId:n.traceId,spanId:n.spanId,parentSpanId:n.parentSpanId,traceState:n.traceState,name:u.name,kind:u.kind,status:u.status,attributes:u.attributes,events:u.events,startTime:u.startTime,endTime:u.endTime,traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote,droppedAttributesCount:o.attributes,droppedEventsCount:o.events},!sA(l))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;l.name=ar(l.name,"Span name",this._config.maxAttributeValueLength,this._logger),l.status&&l.status.code!=="ok"&&l.status.code!=="error"&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),l.status=c),l.startTime=Gr(l.startTime)??s.startTime,l.endTime=Ti(Gr(l.endTime)??s.endTime,l.startTime);let p=[];for(let g of l.events)try{p.push({...g,name:ar(g.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:ns(g.timestamp,l.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return l.events=p,qh(l,r,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,i),l}catch(d){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",d),this._recordDrop(1,"beforeSpanSend failed"),null}}_keepSpanIdentity(e,r){(e.traceId!==r.traceId||e.spanId!==r.spanId||e.parentSpanId!==r.parentSpanId)&&this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");try{Mi(e,"traceId",r.traceId),Mi(e,"spanId",r.spanId),Mi(e,"parentSpanId",r.parentSpanId),Mi(e,"traceState",r.traceState)}catch{return oA(e,r)}return e}_recordDrop(e,r){this._droppedSinceWarning+=e,this._dropReasons.add(r),Date.now()-this._lastDropWarningAt>=this._config.flushIntervalMs&&this._warnAboutDrops()}_warnAboutDrops(){this._droppedSinceWarning&&(this._lastDropWarningAt=Date.now(),this._logger.warn(`Dropping ${this._droppedSinceWarning} span(s): ${[...this._dropReasons].join("; ")}`),this._droppedSinceWarning=0,this._dropReasons.clear())}_encodeBatch(e){let r=[];for(let n of e)try{r.push(e_(n,this._logger))}catch(s){this._logger.debug("Failed to encode a span; dropping it",s),this._recordDrop(1,"its attributes could not be encoded")}return r}_discardQueueIfConsentWithdrawn(){if(!this._instance.isDisabled&&!this._instance.optedOut)return 0;let e=this._queue.length;return this._queue=[],this._resetHeadBatchBudget(),this._recordDrop(e,"the user has opted out"),this._warnAboutDrops(),e}async _flushInner(){if(!this._queue.length)return 0;let e=this._discardQueueIfConsentWithdrawn();if(e)return e;let r=Zh(t_(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._config.maxAttributeValueLength),n=this._instance.getLibraryId(),s=this._instance.getLibraryVersion(),o=this._queue.length,i=0,a=1/0,c=this._generation;try{for(;o>0&&this._queue.length>0;){let u=this._discardQueueIfConsentWithdrawn();if(u)return i+u;let l=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,d=Math.max(1,Math.min(l,a,o,this._queue.length)),p=this._queue.slice(0,d),g=this._encodeBatch(p);if(!g.length){this._queue.splice(0,d),o-=d,i+=d,this._resetHeadBatchBudget();continue}let m=Pi()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),h=await this._instance._sendTracesBatch(r_(g,r,n,s,this._logger));if(c!==this._generation)break;if(this._retryAfter.record(h),h.kind==="ok"){this._consecutiveFlushFailures=0,this._flushJitter=Pe,this._resetHeadBatchBudget(),this._queue.splice(0,d),o-=d,i+=d,this._maxExportBatchSize<this._config.maxExportBatchSize&&this._maxExportBatchSize++;continue}if(h.kind==="too-large"){if(d===1){this._queue.splice(0,1),o-=1,i+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=Pe,this._resetHeadBatchBudget();continue}let _=Math.max(1,Math.floor(d/2));h.measuredLocally?a=_:this._maxExportBatchSize=_,this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${_}`);continue}if(h.kind==="retry-later"){if(this._consecutiveFlushFailures++,this._flushJitter=Zn(),this._headBatchSize=d,m&&(this._headBatchFailures++,this._headBatchChargeableAt=Pi()+this._nextFlushDelay()),this._headBatchFailures<n_)return this._logger.debug("Span export failed; retrying on the next flush",h.error),i;if(this._queue.splice(0,d),o-=d,i+=d,this._consecutiveFlushFailures=0,this._flushJitter=Pe,this._resetHeadBatchBudget(),this._recordDrop(d,`the ingestion endpoint failed ${n_} times in a row`),this._retryAfter.isOpen())return i;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",h.error),this._queue.splice(0,d),o-=d,i+=d,this._consecutiveFlushFailures=0,this._flushJitter=Pe,this._resetHeadBatchBudget(),this._recordDrop(d,"the ingestion endpoint rejected the batch")}return i}finally{this._warnAboutDrops()}}_flushInBackground(){this._backgroundFlush||(this._backgroundFlush=this.flush().catch(e=>{this._logger.debug("Background span flush failed",e)}).finally(()=>{this._backgroundFlush=void 0,this._armFlushTimerIfQueuedNoEarlierThan()}))}_armFlushTimerIfQueued(){this._flushTimer.pending||!this._queue.length||this._flushTimer.arm(this._nextFlushDelay())}_armFlushTimerIfQueuedNoEarlierThan(){this._queue.length&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(es(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}};var as=class{active(){return this._active}with(e,r){let n=this._active;this._active=e;try{return r()}finally{this._active=n}}};var iA=5e3,aA=512,cA=2048,uA=128,lA=128,dA=128,fA=8192,pA=1e4,gA=36e5;function Lt(t,e){return typeof t=="number"&&Number.isInteger(t)&&t>=1?t:e}var o_=["service.name","service.version","deployment.environment"];function mA(t){if(!(!t||typeof t!="object"||Array.isArray(t)))try{if(o_.every(r=>!(r in t)||typeof t[r]=="string"))return t;let e={...t};for(let r of o_)r in e&&typeof e[r]!="string"&&delete e[r];return e}catch{return}}function hA(t,e){if(!t)return[];let r=[t].flat().filter(s=>!!s),n=r.filter(s=>typeof s=="function");return n.length!==r.length&&e?.critical(`beforeSpanSend: ignoring ${r.length-n.length} of ${r.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`),n}function _l(t,e,r){let n=yt({...e},mA(t?.resourceAttributes)),s=Lt(t?.maxExportBatchSize,aA);return{serviceName:n?.["service.name"]??t?.serviceName,serviceVersion:n?.["service.version"]??t?.serviceVersion,environment:n?.["deployment.environment"]??t?.environment,resourceAttributes:n,beforeSpanSend:hA(t?.beforeSpanSend,r),maxAttributesPerSpan:Lt(t?.maxAttributesPerSpan,uA),maxEventsPerSpan:Lt(t?.maxEventsPerSpan,lA),maxAttributesPerEvent:dA,maxAttributeValueLength:Lt(t?.maxAttributeValueLength,fA),flushIntervalMs:Lt(t?.flushIntervalMs,iA),maxExportBatchSize:s,maxQueueSize:Math.max(Lt(t?.maxQueueSize,cA),s),maxLiveSpans:Lt(t?.maxLiveSpans,pA),maxSpanAgeMs:Lt(t?.maxSpanAgeMs,gA)}}var El=require("node:fs"),c_=require("node:fs/promises"),yl=require("node:path"),u_=require("node:readline"),xi=new Z.ReduceableCache(25),cs=new Z.ReduceableCache(20),bl=7,_A=1e3,EA=1e4,Sl=10485760;async function l_(t,e=c_.open,r){let n={},s;try{s=process.cwd()}catch{}for(let a=t.length-1;a>=0;a--){let c=t[a],u=c?.filename;if(!c||typeof u!="string"||typeof c.lineno!="number"||TA(u)||IA(c)||!(0,yl.isAbsolute)(u)&&s===void 0)continue;n[u]||(n[u]=[]),n[u].push(c.lineno)}let o=Object.keys(n);if(o.length==0)return t;let i=[];for(let a of o){let c=d_(a,s);if(c===void 0||cs.get(c))continue;let u=n[a];if(!u)continue;u.sort((p,g)=>p-g);let l=RA(u);if(l.every(p=>vA(c,p)))continue;let d=AA(xi,c,{});i.push(yA(a,l,d,c,e,r))}return await Promise.all(i).catch(()=>{}),t&&t.length>0&&bA(t,xi,s),xi.reduce(),t}async function SA(t,e,r){let n,s=!1;try{n=await e(t,El.constants.O_RDONLY|El.constants.O_NONBLOCK);let o=await n.stat();return o.isFile()?o.size>Sl?void r?.debug(`Skipping source context for oversized file ${t}: ${o.size} bytes exceeds ${Sl}`):(s=!0,n):void 0}catch{return}finally{n&&!s&&await n.close().catch(()=>{})}}async function yA(t,e,r,n,s,o){let i=await SA(t,s,o);if(i===void 0)return void cs.set(n,1);let a=i;return new Promise(c=>{let u=!1;function l(w){u||(u=!0,w?.destroy(),a.close().then(c,c))}let d;try{d=a.createReadStream({autoClose:!1,start:0,end:Sl-1})}catch{cs.set(n,1),l();return}let p;try{p=(0,u_.createInterface)({input:d})}catch{cs.set(n,1),l(d);return}let g=0,m=0,h=e[m];if(h===void 0)return void l(d);let _=h[0],S=h[1];function b(){cs.set(n,1),p.close(),p.removeAllListeners(),l(d)}d.on("error",b),p.on("error",b),p.on("close",()=>l(d)),p.on("line",w=>{if(g++,!(g<_)&&(r[g]=OA(w,0),g>=S)){if(m===e.length-1){p.close(),p.removeAllListeners();return}m++;let T=e[m];if(T===void 0){p.close(),p.removeAllListeners();return}_=T[0],S=T[1]}})})}function bA(t,e,r){for(let n of t)if(n.filename&&n.context_line===void 0&&typeof n.lineno=="number"){let s=d_(n.filename,r),o=s===void 0?void 0:e.get(s);if(o===void 0)continue;wA(n.lineno,n,o)}}function wA(t,e,r){if(e.lineno===void 0||r===void 0)return;e.pre_context=[];for(let s=f_(t);s<t;s++){let o=r[s];if(o===void 0)return void i_(e);e.pre_context.push(o)}if(r[t]===void 0)return void i_(e);e.context_line=r[t];let n=p_(t);e.post_context=[];for(let s=t+1;s<=n;s++){let o=r[s];if(o===void 0)break;e.post_context.push(o)}}function i_(t){delete t.pre_context,delete t.context_line,delete t.post_context}function TA(t){return t.startsWith("node:")||t.endsWith(".min.js")||t.endsWith(".min.cjs")||t.endsWith(".min.mjs")||t.startsWith("data:")}function IA(t){return t.lineno!==void 0&&t.lineno>EA||t.colno!==void 0&&t.colno>_A}function d_(t,e){return(0,yl.isAbsolute)(t)?JSON.stringify([null,t]):e===void 0?void 0:JSON.stringify([e,t])}function vA(t,e){let r=xi.get(t);if(r===void 0)return!1;for(let n=e[0];n<=e[1];n++)if(r[n]===void 0)return!1;return!0}function RA(t){if(!t.length)return[];let e=0,r=t[0];if(typeof r!="number")return[];let n=a_(r),s=[];for(;;){if(e===t.length-1){s.push(n);break}let o=t[e+1];if(typeof o!="number")break;o<=n[1]?n[1]=o+bl:(s.push(n),n=a_(o)),e++}return s}function a_(t){return[f_(t),p_(t)]}function f_(t){return Math.max(1,t-bl)}function p_(t){return t+bl}function AA(t,e,r){let n=t.get(e);return n===void 0?(t.set(e,r),r):n}function OA(t,e){let r=t,n=r.length;if(n<=150)return r;e>n&&(e=n);let s=Math.max(e-60,0);s<5&&(s=0);let o=Math.min(s+140,n);return o>n-5&&(o=n),o===n&&(s=Math.max(o-140,0)),r=r.slice(s,o),s>0&&(r=`...${r}`),o<n&&(r+="..."),r}var Vr=require("path");function g_(t=process.cwd()){let e=Vr.sep==="\\",r=s=>e?s.replace(/\\/g,"/"):s,n=r(t);return async s=>{for(let o of s)!o.filename||o.filename.startsWith("node:")||o.filename.startsWith("data:")||(0,Vr.isAbsolute)(o.filename)&&(o.filename=r((0,Vr.relative)(n,r(o.filename))));return s}}var m_="5.56.2";var wt={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var Ut=class t{constructor(e){this._host=e.host,this._distinctId=e.distinctId,this._groups=e.groups,this._disableGeoip=e.disableGeoip,this._flags=e.flags,this._requestId=e.requestId,this._evaluatedAt=e.evaluatedAt,this._flagDefinitionsLoadedAt=e.flagDefinitionsLoadedAt,this._errorsWhileComputing=e.errorsWhileComputing??!1,this._quotaLimited=e.quotaLimited??!1,this._accessed=e.accessed??new Set,this._isSlice=e.isSlice??!1}isEnabled(e,r={}){let n=this._flags[e];return this._recordAccess(e),n?.enabled??r.defaultValue??!1}getFlag(e){let r=this._flags[e];if(this._recordAccess(e),!!r)return r.enabled?r.variant??!0:!1}getFlagPayload(e){return this._flags[e]?.payload}onlyAccessed(){let e={};for(let r of this._accessed){let n=this._flags[r];n&&(e[r]=n)}return this._cloneWith(e)}only(e){let r={},n=[];for(let s of e){let o=this._flags[s];o?r[s]=o:n.push(s)}return n.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${n.join(", ")}`),this._cloneWith(r)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let e={},r=[];for(let[n,s]of Object.entries(this._flags)){let o=s.enabled===!1?!1:s.variant??!0;e[`$feature/${n}`]=o,s.enabled&&r.push(n)}return r.length>0&&(r.sort(),e.$active_feature_flags=r),e}_cloneWith(e){return new t({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:e,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(e){if(this._accessed.add(e),this._distinctId===""||this._isSlice&&!(e in this._flags))return;let r=this._flags[e],n=r===void 0?void 0:r.enabled===!1?!1:r.variant??!0,s={$feature_flag:e,$feature_flag_response:n,$feature_flag_id:r?.id,$feature_flag_version:r?.version,$feature_flag_reason:r?.reason,locally_evaluated:r?.locallyEvaluated??!1,[`$feature/${e}`]:n,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:r?.locallyEvaluated?Date.now():this._evaluatedAt};r?.hasExperiment!==void 0&&(s.$feature_flag_has_experiment=r.hasExperiment),r?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0&&(s.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let o=[];this._errorsWhileComputing&&o.push(wt.ERRORS_WHILE_COMPUTING),this._quotaLimited&&o.push(wt.QUOTA_LIMITED),r===void 0&&o.push(wt.FLAG_MISSING),o.length>0&&(s.$feature_flag_error=o.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:n,groups:this._groups,disableGeoip:this._disableGeoip,properties:s})}};var PA=6e4;function h_(t){return t==="client"||t==="server"?t:"all"}function MA(t,e){return t===e||t==="all"||e==="all"}var ur=class t extends Error{constructor(e){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,t.prototype)}};function xA(t,e){t.name=e.name,Error.captureStackTrace(t,e),Object.setPrototypeOf(t,e.prototype)}var nt=class t extends Error{constructor(e){super(e),xA(this,t)}},ki=class{constructor({pollingInterval:e,personalApiKey:r,projectApiKey:n,timeout:s,host:o,customHeaders:i,...a}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollerStopped=!1,this.filteredOutFlagKeys=new Set,this.pollingInterval=e,this.personalApiKey=r,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=s,this.projectApiKey=n,this.host=o,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=i,this.onLoad=a.onLoad,this.onMinimalFlagCalledEvents=a.onMinimalFlagCalledEvents,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.evaluationContexts=a.evaluationContexts,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){this.debugMode&&e()}withEvaluationSnapshot(e){return e.definitions?e:{...e,evaluationCache:{},definitions:{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}}createEvaluationContext(e,r={},n={},s={},o={}){return{distinctId:e,groups:r,personProperties:n,groupProperties:s,evaluationCache:o}}async getFeatureFlag(e,r,n={},s={},o={}){await this.loadFeatureFlags();let i,a;if(!this.loadedSuccessfullyOnce)return i;if(a=this.featureFlagsByKey[e],a!==void 0){let c=this.createEvaluationContext(r,n,s,o);try{i=(await this.computeFlagAndPayloadLocally(a,c)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${i}`))}catch(u){u instanceof nt||u instanceof P?this.logMsgIfDebug(()=>console.debug(`${u.name} when computing flag locally: ${e}: ${u.message}`)):u instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${e}: ${u}`))}}return i}async getAllFlagsAndPayloads(e,r){await this.loadFeatureFlags();let n={},s={},o=this.featureFlags.length==0,i=r?r.map(c=>this.featureFlagsByKey[c]).filter(Boolean):this.featureFlags,a=this.withEvaluationSnapshot({...e,definitions:void 0});return await Promise.all(i.map(async c=>{try{let{value:u,payload:l}=await this.computeFlagAndPayloadLocally(c,a,{skipLoadCheck:!0});n[c.key]=u,l&&(s[c.key]=l)}catch(u){u instanceof nt||u instanceof P?this.logMsgIfDebug(()=>console.debug(`${u.name} when computing flag locally: ${c.key}: ${u.message}`)):u instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${c.key}: ${u}`)),o=!0}})),{response:n,payloads:s,fallbackToFlags:o}}async computeFlagAndPayloadLocally(e,r,n={}){let{matchValue:s,skipLoadCheck:o=!1}=n;if(this.loadedSuccessfullyOnce&&(r=this.withEvaluationSnapshot(r)),o||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};r=this.withEvaluationSnapshot(r),e=r.definitions.featureFlagsByKey[e.key]??e;let i;i=s!==void 0?s:await this.computeFlagValueLocally(e,r);let a=rl(e.filters?.payloads,i);return{value:i,payload:a}}async computeFlagValueLocally(e,r){let{distinctId:n,groups:s,personProperties:o,groupProperties:i}=r;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new P("Flag has experience continuity enabled");let c=(e.filters||{}).aggregation_group_type_index;if(c!=null){let u=r.definitions.groupTypeMapping[String(c)];if(!u)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${c} for feature flag ${e.key}`)),new P("Flag has unknown group type index");if(!(u in s))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;e.bucketing_identifier==="device_id"&&(o?.$device_id===void 0||o?.$device_id===null||o?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let l=i[u];return await this.matchFeatureFlagProperties(e,s[u],l,r)}{let u=this.getBucketingValueForFlag(e,n,o);if(u===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new P(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,u,o,r)}}getBucketingValueForFlag(e,r,n){if(e.filters?.aggregation_group_type_index!=null)return r;if(e.bucketing_identifier==="device_id"){let s=n?.$device_id;return s==null||s===""?void 0:s}return r}async evaluateFlagDependency(e,r,n){let{evaluationCache:s}=n,o=e.key;if(!n.definitions.featureFlagsByKey)throw new P("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new P(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let i=e.dependency_chain;if(!Array.isArray(i))throw new P(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof i})`);if(i.length===0)throw new P(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let c of i){if(!(c in s)){let l=n.definitions.featureFlagsByKey[c];if(l)if(l.active)try{let d=await this.computeFlagValueLocally(l,n);s[c]=d}catch(d){throw new P(`Error evaluating flag dependency '${c}' for flag '${o}': ${d}`)}else s[c]=!1;else if(n.definitions.filteredOutFlagKeys.has(c))s[c]=!1;else throw new P(`Missing flag dependency '${c}' for flag '${o}'`)}if(s[c]==null)throw new P(`Dependency '${c}' could not be evaluated`)}let a=s[o];return this.flagEvaluatesToExpectedValue(e.value,a)}flagEvaluatesToExpectedValue(e,r){return typeof e=="boolean"?e===r||typeof r=="string"&&r!==""&&e===!0:typeof e=="string"?r===e:!1}async matchFeatureFlagProperties(e,r,n,s){s=this.withEvaluationSnapshot(s);let o=e.filters||{},i=await el(o.holdout,r);if(i!==void 0)return i;let a=o.groups||[],c=o.aggregation_group_type_index,u=o.early_exit??!1,{groups:l,groupProperties:d}=s,p=!1,g;for(let m of a)try{let h=m.aggregation_group_type_index!==void 0?m.aggregation_group_type_index:c,_=n,S=r;if(h!==c&&h!=null){let w=s.definitions.groupTypeMapping[String(h)];if(!w||!(w in l)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${h} not available`));continue}if(!(w in d)){p=!0;continue}_=d[w],S=l[w]}let b=await this.isConditionMatch(e,S,m,_,s);if(b==="match"){let w=m.variant,T=o.multivariate?.variants||[];g=w&&T.some(y=>y.key===w)?w:await this.getMatchingVariant(e,S)||!0;break}if(u&&b==="out_of_rollout_bound"){if(p)break;return!1}}catch(h){if(h instanceof nt)throw h;if(h instanceof P)p=!0;else throw h}if(g!==void 0)return g;if(p)throw new P("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,r,n,s,o){o=this.withEvaluationSnapshot(o);let i=o.definitions,a=n.rollout_percentage,c=u=>{this.logMsgIfDebug(()=>console.warn(u))};if((n.properties||[]).length>0){for(let u of n.properties){let l=u.type,d=!1;if(l==="cohort"){let p=await E_(u,s,i.cohorts,this.debugMode,g=>this.evaluateFlagDependency(g,s,o),i.propertyMatchingVersion);d=u.operator==="not_in"?!p:p}else d=l==="flag"?await this.evaluateFlagDependency(u,s,o):__(u,s,c,i.propertyMatchingVersion);if(!d)return"no_match"}if(a==null)return"match"}return a!=null&&await Yn(e.key,r)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(e,r){return tl(e.key,r,e.filters?.multivariate?.variants||[])}variantLookupTable(e){return hi(e.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(e){if(!this.evaluationContexts||this.evaluationContexts.length===0)return e;let r=new Set(this.evaluationContexts);return e.filter(n=>{let s=n.evaluation_contexts??n.evaluation_tags;return!s||s.length===0?!0:s.some(o=>r.has(o))})}getEvaluationRuntimeForFlag(e){let r=this.featureFlagsByKey[e];return r?h_(r.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(e){return this.featureFlags.filter(r=>MA(h_(r.evaluation_runtime),e)).map(r=>r.key)}updateFlagState(e){let r=this.filterFlagsByEvaluationContexts(e.flags),n=r.reduce((i,a)=>(i[a.key]=a,i),{}),s=new Set(r.map(i=>i.key)),o=new Set(e.flags.filter(i=>!s.has(i.key)).map(i=>i.key));this.featureFlags=r,this.featureFlagsByKey=n,this.filteredOutFlagKeys=o,this.groupTypeMapping=e.group_type_mapping??e.groupTypeMapping??{},this.cohorts=e.cohorts,this.propertyMatchingVersion=e.property_matching_version??e.propertyMatchingVersion,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.((e.minimal_flag_called_events??e.minimalFlagCalledEvents)===!0)}warnAboutExperienceContinuityFlags(e){if(this.strictLocalEvaluation)return;let r=e.filter(n=>n.ensure_experience_continuity);r.length>0&&console.warn(`[PostHog] You are using local evaluation but ${r.length} flag(s) have experience continuity enabled: ${r.map(n=>n.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(e){if(!this.cacheProvider)return!1;try{let r=await this.cacheProvider.getFlagDefinitions();return r?(this.updateFlagState(r),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${r.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags),!0):!1}catch(r){return this.onError?.(new Error(`Failed to load from cache: ${r}`)),!1}}async loadFeatureFlags(e=!1){if(!(this.loadedSuccessfullyOnce&&!e))return!e&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(r=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${r}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){let e=this.pollingInterval??3e4;return this.shouldBeginExponentialBackoff?Math.min(PA,e*2**this.backOffCount):e}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0);try{if(this.cacheProvider&&!this.personalApiKey)return void await this.loadFromCache("Loaded flags from cache (cache-only reader)");let e=!0;if(this.cacheProvider)try{e=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(n){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${n}`))}if(!e&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let r=await this._requestFeatureFlagDefinitions();if(!r)return;switch(r.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=r.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new ur(`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.filteredOutFlagKeys=new Set,this.groupTypeMapping={},this.cohorts={},this.propertyMatchingVersion=void 0,this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new ur(`Your secret key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new ur(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let n=await r.json()??{};if(!("flags"in n))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(n)}`));this.flagsEtag=r.headers?.get("ETag")??void 0;let s=n.group_type_mapping||{},o=n.minimal_flag_called_events===!0,i={flags:n.flags??[],group_type_mapping:s,cohorts:n.cohorts||{},minimal_flag_called_events:o,property_matching_version:n.property_matching_version,propertyMatchingVersion:n.property_matching_version,groupTypeMapping:s,minimalFlagCalledEvents:o};if(this.updateFlagState(i),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(i)}catch(a){this.onError?.(new Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags);break}default:return}}catch(e){e instanceof ur&&this.onError?.(e)}finally{!this.pollerStopped&&this.pollingInterval!==null&&(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}getPersonalApiKeyRequestOptions(e="GET",r){let n={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return r&&(n["If-None-Match"]=r),{method:e,headers:n}}async _requestFeatureFlagDefinitions(){if(!this.personalApiKey)throw new ur("A secretKey or personalApiKey is required to fetch feature flag definitions from PostHog.");let e=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,r=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let o=new AbortController;n=pe(()=>{o.abort()},this.timeout),r.signal=o.signal}let s=()=>clearTimeout(n);try{let o=this.fetch,i=await o(e,r);return i.status!==200?(s(),i):{status:i.status,headers:i.headers,body:i.body,text:async()=>{try{return await i.text()}finally{s()}},json:async()=>{try{return await i.json()}finally{s()}}}}catch(o){throw s(),o}}async stopPoller(e=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let r=this.cacheProvider.shutdown();r instanceof Promise&&await Dt(r,e,()=>{throw new Error(`Cache shutdown timeout after ${e}ms`)})}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};function __(t,e,r,n){return Zu(t,e,{warnFunction:r,propertyMatchingVersion:n})}function kA(t,e){if(!(t in e))throw new nt(`cohort ${t} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function E_(t,e,r,n=!1,s,o){let i=String(t.value);kA(i,r);let a=r[i];return S_(a,e,r,n,s,o)}async function S_(t,e,r,n=!1,s,o){if(!t)return!0;let i=t.type,a=t.values;if(!a||a.length===0)return!0;let c=!1;if("values"in a[0]){for(let u of a)try{let l=await S_(u,e,r,n,s,o);if(i==="AND"){if(!l)return!1}else if(l)return!0}catch(l){if(l instanceof nt)throw l;if(l instanceof P)n&&console.debug(`Failed to compute property ${u} locally: ${l}`),c=!0;else throw l}if(c)throw new P("Can't match cohort without a given cohort property value");return i==="AND"}for(let u of a)try{let l;if(u.type==="cohort")l=await E_(u,e,r,n,s,o);else if(u.type==="flag"){if(!s)throw new P(`Flag dependency '${u.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);l=await s(u)}else l=__(u,e,void 0,o);let d=u.negation||!1;if(i==="AND"){if(!l&&!d||l&&d)return!1}else if(l&&!d||!l&&d)return!0}catch(l){if(l instanceof nt)throw l;if(l instanceof P)n&&console.debug(`Failed to compute property ${u} locally: ${l}`),c=!0;else throw l}if(c)throw new P("can't match cohort without a given cohort property value");return i==="AND"}var NA=["--unhandled-rejections","--unhandled_rejections"],CA=new Set(["throw","strict","warn","warn-with-error-code","none"]),DA=[...globalThis.process?.execArgv??[]],FA=globalThis.process?.env?.NODE_OPTIONS;function LA(t){let e=[],r="",n=!1;for(let s=0;s<t.length;s++){let o=t[s];o==="\\"&&n&&s+1<t.length?r+=t[++s]:o!==" "||n?o==='"'?n=!n:r+=o:r&&(e.push(r),r="")}return r&&e.push(r),e}function y_(t){let e;for(let r=0;r<t.length;r++){let n=t[r],s=NA.find(i=>n===i||n.startsWith(`${i}=`));if(!s)continue;let o=n===s?t[++r]:n.slice(s.length+1);CA.has(o)&&(e=o)}return e}function UA(t=DA,e=FA){return y_(t)??y_(LA(e??""))??"throw"}var b_=UA();function w_(t,e,r){t(e,{mechanism:{type:r==="unhandledRejection"?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function $A(t,e){let r=!1;return Object.assign((n,s)=>{let o=global.process.listeners("uncaughtException").filter(i=>i.name!=="domainUncaughtExceptionClear"&&i._posthogErrorHandler!==!0).length;w_(t,n,s),!r&&o===0&&(r=!0,e(n))},{_posthogErrorHandler:!0})}function T_(t,e,r=b_){let n=globalThis.process;if(n){if(r==="strict")return void n.on("uncaughtExceptionMonitor",(s,o)=>w_(t,s,o));n.on("uncaughtException",$A(t,e))}}function I_(t,e=b_){let r=globalThis.process;!r||e==="throw"||e==="strict"||e==="warn-with-error-code"||r.on("unhandledRejection",n=>{t(n,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var BA=2e3,wl=class t{constructor(e,r,n){this.client=e,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new Qo({...Dm(r),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return Nn(e)&&"__posthog_previously_captured_error"in e&&e.__posthog_previously_captured_error===!0}static async buildEventMessage(e,r,n,s,o){let i={...o},a=e.buildFromUnknown(r,n);a.$exception_list=await e.modifyFrames(a.$exception_list);let c=Z.getInjectedReleaseId();return c&&(i.$release_id=c),{event:"$exception",distinctId:s,properties:{...a,...i},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(T_(this.onException.bind(this),this.onFatalError.bind(this)),I_(this.onException.bind(this)))}onException(e,r){this.client.addPendingPromise((async()=>{if(!t.isPreviouslyCapturedError(e)){let n=await t.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,r),o=n.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(o)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:o}):this.client._capturePreparedEvent(n,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(BA),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}},lr=wl;var lO=/^[0-9a-f]{32}$/i,dO=/^[0-9a-f]{16}$/i,fO;async function bE(){try{let e=(await(fO??=Promise.resolve().then(()=>(yE(),SE)))).trace.getActiveSpan()?.spanContext(),r=e?.traceId,n=e?.spanId;if(typeof r=="string"&&typeof n=="string"&&lO.test(r)&&dO.test(n)&&!/^0+$/.test(r)&&!/^0+$/.test(n))return{$trace_id:r.toLowerCase(),$span_id:n.toLowerCase()}}catch{}return{}}var sa=class{getProperty(e){return this._memoryStorage[e]}setProperty(e,r){this._memoryStorage[e]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};function pO(t){return t==="v0"||t==="v1"}function wE(){let t="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return pO(t)?t:"v0"}var gO="$ai_",Es="analytics";function TE(t){return typeof t.event=="string"&&t.event.startsWith(gO)}var tn=class t extends Error{constructor({requestId:e,drops:r,retryExhausted:n,cause:s}){super(t.buildMessage(e,r,n,s)),this.name="CaptureV1Error",this.requestId=e,this.drops=r,this.retryExhausted=n,this.cause=s}static buildMessage(e,r,n,s){let o=`Capture V1 batch ${e} did not fully deliver: ${r.length} dropped, ${n.length} undelivered`;return s instanceof Error&&(o+=` (${s.message})`),o}};function ad(t){if(typeof t=="boolean")return t;if(typeof t=="number")return t!==0;if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true"||e==="1")return!0;if(e==="false"||e==="0")return!1}}function mO(t){return typeof t=="string"?t:void 0}var hO=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:ad},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:ad},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:ad},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:mO}],_O=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function EO(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function SO(t){if(typeof t=="string"){let r=new Date(t);if(Number.isNaN(r.getTime()))return new Date().toISOString();let n=r.toISOString(),s=t.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return s&&s.length>3?n.replace(/\.\d{3}Z$/,`.${s}Z`):n}if(t instanceof Date)return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString();let e=t==null?new Date:new Date(t);return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString()}function IE(t,e,r){r!==void 0&&!(e in t)&&(t[e]=r)}function yO(t){let r={...EO(t.properties)?t.properties:{}},n={};for(let{property:o,optionKey:i,coerce:a}of hO)if(o in r){let c=a(r[o]);c!==void 0&&(n[i]=c),delete r[o]}let s={};for(let{property:o,field:i}of _O)if(o in r){let a=r[o];typeof a=="string"&&(s[i]=a),delete r[o]}return delete r.$lib,delete r.$lib_version,IE(r,"$set",t.$set),IE(r,"$set_once",t.$set_once),{event:String(t.event??""),uuid:String(t.uuid??""),distinct_id:String(t.distinct_id??""),timestamp:SO(t.timestamp),...s,options:n,properties:r}}function vE(t,{createdAt:e,historicalMigration:r}){let n={created_at:e,batch:t.map(yO)};return r&&(n.historical_migration=!0),n}var bO="/i/v1/analytics/events",wO=3e4,TO=new Set([408,500,502,503,504]),oa=class{constructor(e,r){this.config=e,this.maxBackoffMs=e.maxBackoffMs??wO,this.fetchFn=r.fetch,this.onError=r.onError,this.now=r.now??Date.now,this.sleep=r.sleep??(n=>new Promise(s=>pe(s,n))),this.generateRequestId=r.generateRequestId??fe,this.compress=r.compress??Gn}async sendV1Batch(e){if(e.length===0)return;let r=this.generateRequestId(),n=new Date(this.now()).toISOString(),{batch:s}=vE(e,{createdAt:n,historicalMigration:this.config.historicalMigration}),o=`${this.config.host}${bO}`,i=[],a=s,c=Math.max(1,this.config.maxAttempts);for(let u=1;u<=c;u++){let l=u===c,d=Nt({created_at:n,...this.config.historicalMigration?{historical_migration:!0}:{},batch:a}),p,g;try{p=await this.sendOnce(o,d,u,r);let{response:m,signal:h}=p,{status:_}=m;if(_<200||_>=300)if(!l&&TO.has(_)){let S=this.parseRetryAfter(m);await p.waitFor(p.cancelBody()).catch(()=>{}),g=this.backoffDelay(u,S)}else{let S=await this.buildHttpError(m,_,p.waitFor);return this.surfaceBatchFailure(r,i,a,S)}else{let S;try{S=await p.waitFor(this.parseResponse(m))}catch(T){if(h.aborted)throw T;return this.surfaceBatchFailure(r,i,a,new Error(`Capture V1 returned an unparseable ${_} response body`))}let b=this.classify(a,S,i);if(b.length===0)return this.surfacePartialDrops(r,i);if(l)return void this.onError(new tn({requestId:r,drops:i,retryExhausted:b.map(T=>T.uuid)}));a=b;let w=this.parseRetryAfter(m);g=this.backoffDelay(u,w)}}catch(m){if(p&&!p.signal.aborted)throw m;if(l)return this.surfaceBatchFailure(r,i,a,m);g=this.backoffDelay(u)}finally{p?.cleanup()}g!==void 0&&await this.sleep(g)}}async sendOnce(e,r,n,s){let o=this.buildHeaders(n,s),i=r;if(this.config.compressionEnabled){let d=await this.compress(r,this.config.isDebug);d!==null&&(i=d,o["Content-Encoding"]="gzip")}let a=new AbortController,c="waiting for response headers",u,l=new Promise((d,p)=>{u=pe(()=>{let g=new Error(`Capture V1 request timed out ${c} after ${this.config.requestTimeoutMs}ms`);g.name="AbortError",p(g),a.abort(g)},this.config.requestTimeoutMs)});try{let d=this.fetchFn(e,{method:"POST",headers:o,body:i,signal:a.signal}),p=!1;d.then(S=>{a.signal.aborted&&!p&&this.cancelBody(S)}).catch(()=>{});let g=await Promise.race([d,l]);p=!0,c="while reading the response body";let m=!1,h,_=()=>h??=this.cancelBody(g);return{response:g,signal:a.signal,waitFor:S=>Promise.race([S,l]),cancelBody:_,cleanup:()=>{m||(m=!0,clearTimeout(u),a.signal.aborted&&_())}}}catch(d){throw clearTimeout(u),d}}buildHeaders(e,r){let n=`${this.config.libraryId}/${this.config.libraryVersion}`,s={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":n,"PostHog-Attempt":String(e),"PostHog-Request-Id":r,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(s["User-Agent"]=this.config.userAgent),s}classify(e,r,n){let s=r.results??{},o=[];for(let i of e){let a=s[i.uuid];a&&(a.result==="drop"?n.push({uuid:i.uuid,details:a.details??void 0}):a.result==="retry"&&o.push(i))}return o}backoffDelay(e,r){let n=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);return r===void 0?n:Math.max(n,Math.min(r,this.maxBackoffMs))}parseRetryAfter(e){let r=e.headers?.get("Retry-After");if(!r)return;let n=r.trim();if(/^\d+$/.test(n)){let i=parseInt(n,10);return Number.isFinite(i)&&i>0?1e3*i:void 0}let s=Date.parse(n);if(Number.isNaN(s))return;let o=s-this.now();return o>0?o:void 0}async parseResponse(e){let r=await e.text(),n=JSON.parse(r);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("unexpected response shape");let s=n.results;if(s!==void 0&&(typeof s!="object"||s===null||Array.isArray(s)))throw new Error("unexpected results shape");return{results:s??{}}}async buildHttpError(e,r,n){let s="";try{s=(await n(e.text())).slice(0,512)}catch{}let o=s?`: ${s}`:"";return new Error(`Capture V1 request failed with HTTP ${r}${o}`)}surfaceBatchFailure(e,r,n,s){this.onError(new tn({requestId:e,drops:r,retryExhausted:n.map(o=>o.uuid),cause:s}))}surfacePartialDrops(e,r){r.length>0&&this.onError(new tn({requestId:e,drops:r,retryExhausted:[]}))}async cancelBody(e){try{await e.body?.cancel()}catch{}}};var gr="ai-capture",ia="/i/v0/ai/batch/";var vO=new TextEncoder;function ud(t){return vO.encode(Nt(t)).length}function RE(t,e=8388608,r=5242880){let n=[],s=[],o=[],i=0;for(let a of t){if(a===void 0)continue;let c=ud(a);if(c>e){s.push({event:typeof a.event=="string"?a.event:"unknown",bytes:c});continue}o.length>0&&i+c>r&&(n.push(o),o=[],i=0),o.push(a),i+=c}return o.length>0&&n.push(o),{batches:n,dropped:s}}var RO=100,AE=3e4,AO=5e4,OO=50,PO=500,MO="https://us.i.posthog.com",OE=new Set;function ca(t,e){OE.has(t)||(OE.add(t),console.warn(`[PostHog] ${e}`))}function xO(t){return typeof t=="string"?t.trim():""}function kO(t){return(typeof t=="string"?t.trim():"")||void 0}function NO(t){return(typeof t=="string"?t.trim():"")||MO}function CO(t){return(Array.isArray(t)?t:[t]).filter(r=>typeof r=="string"&&r.trim().length>0)}function DO(t){if(!t)return{};let e={};for(let[n,s]of Object.entries(t))e[`$feature/${n}`]=s;let r=Object.keys(t).filter(n=>t[n]!==!1).sort();return r.length>0&&(e.$active_feature_flags=r),e}var ua=class extends zn{get distinctIdHasSentFlagCalls(){return Object.fromEntries(this._distinctIdHasSentFlagCalls)}set distinctIdHasSentFlagCalls(e){this._distinctIdHasSentFlagCalls=new Map(Object.entries(e??{}))}constructor(e,r={}){let n=xO(e),s={...r,maxQueueSize:r.maxQueueSize??1e4,flushInterval:r.flushInterval??5e3,host:NO(r.host),personalApiKey:kO(r.secretKey??r.personalApiKey)};if(super(n,s),this._memoryStorage=new sa,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=s,this.captureMode=wE(),this.enableFullAiCapture=s.enableFullAiCapture===!0,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof s.featureFlagsPollingInterval=="number"?Math.max(s.featureFlagsPollingInterval,RO):s.featureFlagsPollingInterval===null?null:AE,typeof s.waitUntilDebounceMs=="number"&&(this.options.waitUntilDebounceMs=Math.max(s.waitUntilDebounceMs,0)),typeof s.waitUntilMaxWaitMs=="number"&&(this.options.waitUntilMaxWaitMs=Math.max(s.waitUntilMaxWaitMs,0)),!this.disabled&&(s.personalApiKey||s.flagDefinitionCacheProvider)){if(s.personalApiKey?.includes("phc_"))throw new Error('A project API key ("phc_...") was provided as secretKey or personalApiKey. Pass the project API key as the first constructor argument. For local evaluation, set secretKey (or the deprecated personalApiKey alias) to a server-only Project Secret API Key ("phs_...") or Personal API Key ("phx_...") with feature flag read access.');s.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new ki({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:s.personalApiKey,projectApiKey:n,timeout:s.requestTimeout??1e4,host:this.host,fetch:s.fetch,onError:i=>{this._events.emit("error",i)},onLoad:i=>{this._events.emit("localEvaluationFlagsLoaded",i)},onMinimalFlagCalledEvents:i=>{this._minimalFlagCalledEvents=i},customHeaders:this.getCustomHeaders(),cacheProvider:s.flagDefinitionCacheProvider,strictLocalEvaluation:s.strictLocalEvaluation,evaluationContexts:s.evaluationContexts??s.evaluationEnvironments}))}this.errorTracking=new lr(this,s,this._logger),this._distinctIdHasSentFlagCalls=new Map,this.maxCacheSize=s.maxCacheSize||AO}enqueue(e,r,n,s){super.enqueue(e,r,n,s),this.scheduleDebouncedFlush()}_flushEventsAndSpans(e=!1){let r=this.flushWithPendingPromises();return!this._traces||e&&this._traces.throttled?r:Fn([r,this._traces.flush().catch(()=>{})]).then(([n])=>{if(n.status==="rejected")throw n.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this._flushKeepingRuntimeAlive(!1)}_flushKeepingRuntimeAlive(e){let r=this._flushEventsAndSpans(e),n=this.options.waitUntil;if(n&&!this._waitUntilCycle)try{n(r.catch(()=>{}))}catch{}return r}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let i,a=new Promise(c=>{i=c});try{e(a)}catch{return}this._waitUntilCycle={resolve:i,startedAt:Date.now(),timer:void 0}}let r=Date.now()-this._waitUntilCycle.startedAt,n=this.options.waitUntilMaxWaitMs??PO,s=r>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),s)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??OO;this._waitUntilCycle.timer=pe(()=>{this.resolveWaitUntilFlush()},o)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;return e&&(clearTimeout(e.timer),this._waitUntilCycle=void 0),e?.resolve}async resolveWaitUntilFlush(){let e=this._consumeWaitUntilCycle();try{await this._flushEventsAndSpans()}catch{}finally{e?.()}}getPersistedProperty(e){return this._memoryStorage.getProperty(e)}setPersistedProperty(e,r){return this._memoryStorage.setProperty(e,r)}fetch(e,r){return this.options.fetch?this.options.fetch(e,r):fetch(e,r)}getQueueRouteKey(e){return this.captureMode==="v1"&&TE(e)?"ai":Es}persistedQueueKeyForRoute(e){return e===gr?me.AiCaptureQueue:e==="ai"?me.AiQueue:me.Queue}getActiveQueueRoutes(){let e=this.captureMode==="v1"?[Es,"ai"]:[Es];return this._aiCaptureRouteActive&&e.push(gr),e}getBatchEndpointPath(e){return e===gr?ia:super.getBatchEndpointPath(e)}async sendBatch(e,r,n=Es){if(n===gr)return this.sendAiCaptureBatch(e,r);if(this.captureMode!=="v1"||n==="ai")return super.sendBatch(e,r,n);let s=e.filter(o=>o!==void 0);await this.getV1Sender().sendV1Batch(s)}async sendAiCaptureBatch(e,r){let{batches:n,dropped:s}=RE(e);for(let{event:o,bytes:i}of s){let a=`Event ${o} (${i} bytes) exceeds the ${8388608/1048576}MiB limit for ${ia}, dropping.`;this._logger.error(a),this._events.emit("error",new Error(a))}for(let o of n)await this.sendAiSubBatch(o,r)}async sendAiSubBatch(e,r){try{await super.sendBatch(e,r,gr)}catch(n){if(!Xr(n))throw n;if(e.length===1){let[o]=e,a=`Event ${typeof o.event=="string"?o.event:"unknown"} (${ud(o)} bytes) was rejected with 413 by ${ia} on its own, dropping.`;this._logger.error(a),this._events.emit("error",new Error(a));return}let s=Math.ceil(e.length/2);await this.sendAiSubBatch(e.slice(0,s),r),await this.sendAiSubBatch(e.slice(s),r)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new oa({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3e3,isDebug:this.isDebug},{fetch:(e,r)=>this.fetch(e,r),onError:e=>this._events.emit("error",e),compress:e=>this.compressPayload(e)})),this._v1Sender}getLibraryVersion(){return m_}get metrics(){return this._metrics||(this._metrics=new rs(this,wi(this.options.metrics),this._logger)),this._metrics}initializeSpanContextManager(){return new as}hostResourceAttributes(){return{}}get _spanContextManager(){return this._spanContext||(this._spanContext=this.initializeSpanContextManager()),this._spanContext}get _tracesPipeline(){if(this.options.traces)return this._traces||(this._traces=new is(this,_l(this.options.traces,this.hostResourceAttributes(),this._logger),this._logger,()=>this._tracingContext(),this._spanContextManager,()=>this.scheduleDebouncedFlush())),this._traces}_tracingContext(){let e=this.context?.get();return{distinctId:e?.distinctId,sessionId:e?.sessionId}}startSpan(e,r){return this._tracesPipeline?.startSpan(e,r)??Ft(r,this._spanContextManager.active())}withSpan(e,r,n){let s=typeof r=="function"?void 0:r,o=typeof r=="function"?r:n,i=this._tracesPipeline;return i?s?i.withSpan(e,s,o):i.withSpan(e,o):os(this._spanContextManager,Ft(s,this._spanContextManager.active()),o)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getEvaluationRuntime(){return"server"}getCommonEventProperties(){let e=super.getCommonEventProperties();return(this.options.isServer??!0)&&(e.$is_server=!0),e}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}_warnIfInvalidCapture(e,r,n){typeof e=="string"&&this._logger.warn(r),e.event==="$exception"&&!e._originatedFromCaptureException&&this._logger.warn(n)}_sendPreparedEvent(e,r,n,s,o){return this.addPendingPromise(this._prepareEventMessage(r,s).then(({distinctId:i,event:a,properties:c,options:u})=>{let l={timestamp:u.timestamp,disableGeoip:u.disableGeoip,uuid:u.uuid},d={distinctId:i,event:a,properties:{...c,...this.getCommonEventProperties()}};return n?this.sendImmediate(e,d,l,o):this.enqueue(e,d,l,o)}).catch(i=>{i&&console.error(i)}))}_capturePreparedEvent(e,r){return this._sendPreparedEvent("capture",e,r)}capture(e){this._warnIfInvalidCapture(e,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(e,!1)}async captureImmediate(e){return this._warnIfInvalidCapture(e,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(e,!0)}captureAi(e){if(this.disabled)return;let r=or(e.uuid,fe);return this._sendPreparedAiEvent({...e,uuid:r},!1),r}async captureAiImmediate(e){if(this.disabled)return;let r=or(e.uuid,fe);return await this._sendPreparedAiEvent({...e,uuid:r},!0),r}_sendPreparedAiEvent(e,r){return typeof e?.event=="string"&&!e.event.startsWith("$ai_")&&this._logger.debug(`captureAi called with non-AI event ${e.event}; routing it to the AI endpoint anyway.`),this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",e,r,void 0,gr)}identify({distinctId:e,properties:r={},disableGeoip:n}){let{$set:s,$set_once:o,$anon_distinct_id:i,...a}=r,l={$set:s||a,$set_once:o||{},$anon_distinct_id:i??void 0};this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:l,disableGeoip:n},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:r={},disableGeoip:n}){let{$set:s,$set_once:o,$anon_distinct_id:i,...a}=r,l={$set:s||a,$set_once:o||{},$anon_distinct_id:i??void 0};await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:l,disableGeoip:n},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:r={},propertiesOnce:n={}}){if(Object.keys(r).length===0&&Object.keys(n).length===0)return;let s={};Object.keys(r).length>0&&(s.$set=r),Object.keys(n).length>0&&(s.$set_once=n),this.capture({distinctId:e,event:"$set",properties:s})}unsetPersonProperties({distinctId:e,properties:r}){let n=CO(r);n.length!==0&&this.capture({distinctId:e,event:"$set",properties:{$unset:n}})}alias(e){this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(e){await this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}getFeatureFlagEvaluationRuntime(e){return this.featureFlagsPoller?.getEvaluationRuntimeForFlag(e)}getFeatureFlagKeysByEvaluationRuntime(e){return this.featureFlagsPoller?.getFlagKeysByEvaluationRuntime(e)??[]}async waitForLocalEvaluationReady(e=AE){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(r=>{let n=setTimeout(()=>{s(),r(!1)},e),s=this._events.on("localEvaluationFlagsLoaded",o=>{clearTimeout(n),s(),r(o>0)})})}_resolveDistinctId(e,r){return typeof e=="string"?{distinctId:e,options:r}:{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,r,n={},s){if(this.disabled)return void this._logger.warn("The client is disabled");let o=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&e in this._flagOverrides){let v=this._flagOverrides[e];if(v===void 0)return;let R=this._payloadOverrides?.[e];return{key:e,enabled:v!==!1,variant:typeof v=="string"?v:void 0,payload:R}}let{groups:i,disableGeoip:a}=n,{onlyEvaluateLocally:c,personProperties:u,groupProperties:l}=n,d=this.addLocalPersonAndGroupProperties(r,i,u,l);u=d.allPersonProperties,l=d.allGroupProperties;let p=this.createFeatureFlagEvaluationContext(r,i,this.personPropertiesForLocalEvaluation(r,u),l);c==null&&(c=this.options.strictLocalEvaluation??!1);let g,m=!1,h,_,S,b,w,T,y;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let v=this.featureFlagsPoller?.featureFlagsByKey[e];if(v)try{let R=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(v,p,{matchValue:s});if(R){m=!0;let I=R.value;b=v.id,T="Evaluated locally",y=v.has_experiment,g={key:e,enabled:I!==!1,variant:typeof I=="string"?I:void 0,payload:R.payload??void 0,reason:T,reasonCode:v.active===!1?"flag_disabled":void 0}}}catch(R){if(R instanceof nt||R instanceof P)this._logger?.info(`${R.name} when computing flag locally: ${e}: ${R.message}`);else throw R}}if(!m&&!c){let v=await super.getFeatureFlagDetailsStateless(p.distinctId,p.groups,u,l,a,[e]);if(v===void 0)S=wt.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=v.minimalFlagCalledEvents===!0,h=v.requestId,_=v.evaluatedAt;let R=[];v.errorsWhileComputingFlags&&R.push(wt.ERRORS_WHILE_COMPUTING),v.quotaLimited?.includes("feature_flags")&&R.push(wt.QUOTA_LIMITED);let I=v.flags[e];if(I===void 0)R.push(wt.FLAG_MISSING);else{b=I.metadata?.id,w=I.metadata?.version,T=I.reason?.description??I.reason?.code,y=I.metadata?.has_experiment;let M;if(I.metadata?.payload!==void 0)try{M=JSON.parse(I.metadata.payload)}catch{M=I.metadata.payload}g={key:e,enabled:I.enabled,variant:I.variant??void 0,payload:M,reason:T,reasonCode:I.reason?.code}}R.length>0&&(S=R.join(","))}}if(o){let v=g===void 0?void 0:g.enabled===!1?!1:g.variant??!0,R={$feature_flag:e,$feature_flag_response:v,$feature_flag_id:b,$feature_flag_version:w,$feature_flag_reason:T,locally_evaluated:m,[`$feature/${e}`]:v,$feature_flag_request_id:h,$feature_flag_evaluated_at:m?Date.now():_};if(y!==void 0&&(R.$feature_flag_has_experiment=y),m&&this.featureFlagsPoller){let I=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();I!==void 0&&(R.$feature_flag_definitions_loaded_at=I)}S&&(R.$feature_flag_error=S),this._captureFlagCalledEventIfNeeded({distinctId:r,key:e,response:v,groups:i,disableGeoip:a,properties:R})}return g!==void 0&&this._payloadOverrides!==void 0&&e in this._payloadOverrides&&(g={...g,payload:this._payloadOverrides[e]}),g}async getFeatureFlag(e,r,n){ca("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let s=await this._getFeatureFlagResult(e,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(s!==void 0)return s.enabled===!1?!1:s.variant??!0}async getFeatureFlagPayload(e,r,n,s){if(ca("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request."),this._payloadOverrides!==void 0&&e in this._payloadOverrides)return this._payloadOverrides[e];let o=await this._getFeatureFlagResult(e,r,{...s,sendFeatureFlagEvents:!1},n);if(o!==void 0)return o.payload??null}async getFeatureFlagResult(e,r,n){let{distinctId:s,options:o}=this._resolveDistinctId(r,n);return s?this._getFeatureFlagResult(e,s,{...o,sendFeatureFlagEvents:o?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()")}async getRemoteConfigPayload(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let r=await this._requestRemoteConfigPayload(e);if(!r)return;let n=await r.json();if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}async isFeatureEnabled(e,r,n){ca("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let s=await this._getFeatureFlagResult(e,r,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return s===void 0?void 0:s.enabled===!1?!1:!!(s.variant??!0)||!1}async getAllFlags(e,r){let{distinctId:n,options:s}=this._resolveDistinctId(e,r);return n?(await this.getAllFlagsAndPayloads(n,s)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(e,r){let{distinctId:n,options:s}=this._resolveDistinctId(e,r);if(!n)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:o,disableGeoip:i,flagKeys:a}=s||{},{onlyEvaluateLocally:c,personProperties:u,groupProperties:l}=s||{},d=this.addLocalPersonAndGroupProperties(n,o,u,l);u=d.allPersonProperties,l=d.allGroupProperties;let p=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,u),l);c==null&&(c=this.options.strictLocalEvaluation??!1);let g=await this.featureFlagsPoller?.getAllFlagsAndPayloads(p,a),m={},h={},_=!0;if(g&&(m=g.response,h=g.payloads,_=g.fallbackToFlags),_&&!c){let S=await super.getFeatureFlagsAndPayloadsStateless(p.distinctId,p.groups,u,l,i,a);m={...m,...S.flags||{}},h={...h,...S.payloads||{}}}return this._flagOverrides!==void 0&&(m={...m,...this._flagOverrides}),this._payloadOverrides!==void 0&&(h={...h,...this._payloadOverrides}),{featureFlags:m,featureFlagPayloads:h}}async evaluateFlags(e,r){let{distinctId:n,options:s}=this._resolveDistinctId(e,r);if(!n)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new Ut({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new Ut({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,flags:{}});let{groups:o,disableGeoip:i}=s||{},a=s?.flagKeys??void 0;if(a?.length===0)return new Ut({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:i,flags:{}});let{onlyEvaluateLocally:c,personProperties:u,groupProperties:l}=s||{},d=this.addLocalPersonAndGroupProperties(n,o,u,l);u=d.allPersonProperties,l=d.allGroupProperties;let p=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,u),l);c==null&&(c=this.options.strictLocalEvaluation??!1);let g=a?new Set(a):void 0,m={},h,_,S=!1,b=!1,w=await this.featureFlagsPoller?.getAllFlagsAndPayloads(p,a),T=new Set;if(w)for(let[v,R]of Object.entries(w.response)){let I=this.featureFlagsPoller?.featureFlagsByKey[v];m[v]={key:v,enabled:R!==!1,variant:typeof R=="string"?R:void 0,payload:w.payloads[v],id:I?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:I?.has_experiment},T.add(v)}let y=g!==void 0&&Array.from(g).some(v=>this.featureFlagsPoller?.featureFlagsByKey[v]===void 0);if((w?w.fallbackToFlags||y:!0)&&!c){let v=await super.getFeatureFlagDetailsStateless(p.distinctId,p.groups,u,l,i,a);if(v){this._minimalFlagCalledEvents=v.minimalFlagCalledEvents===!0,h=v.requestId,_=v.evaluatedAt,S=!!v.errorsWhileComputingFlags,b=Array.isArray(v.quotaLimited)&&v.quotaLimited.includes("feature_flags");for(let[R,I]of Object.entries(v.flags)){if(T.has(R))continue;let M;if(I.metadata?.payload!==void 0)try{M=JSON.parse(I.metadata.payload)}catch{M=I.metadata.payload}m[R]={key:R,enabled:I.enabled,variant:I.variant,payload:M,id:I.metadata?.id,version:I.metadata?.version,reason:I.reason?.description??I.reason?.code,locallyEvaluated:!1,hasExperiment:I.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[v,R]of Object.entries(this._flagOverrides)){if(R===void 0){delete m[v];continue}let I=m[v];m[v]={key:v,enabled:R!==!1,variant:typeof R=="string"?R:void 0,payload:I?.payload,id:I?.id,version:I?.version,reason:I?.reason,locallyEvaluated:I?.locallyEvaluated??!1,hasExperiment:I?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[v,R]of Object.entries(this._payloadOverrides)){let I=m[v];I&&(m[v]={...I,payload:R})}if(g!==void 0)for(let v of Object.keys(m))g.has(v)||delete m[v];return new Ut({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:i,flags:m,requestId:h,evaluatedAt:_,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:S,quotaLimited:b})}_shouldSendMinimalFlagCalledEvent(e,r){return e==="$feature_flag_called"&&this._minimalFlagCalledEvents&&r.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(e){let{distinctId:r,key:n,response:s,groups:o,disableGeoip:i,properties:a}=e,c=o&&Object.keys(o).length>0?`_${JSON.stringify(Object.entries(o).sort(([d],[p])=>d<p?-1:d>p?1:0))}`:"",u=`${n}_${s}${c}`,l=this._distinctIdHasSentFlagCalls.get(r)??new Set;if(this._distinctIdHasSentFlagCalls.delete(r),this._distinctIdHasSentFlagCalls.set(r,l),!l.has(u)){for(l.add(u);this._distinctIdHasSentFlagCalls.size>Math.max(this.maxCacheSize,1);){let d=this._distinctIdHasSentFlagCalls.keys().next().value;if(d===void 0)break;this._distinctIdHasSentFlagCalls.delete(d)}this.capture({distinctId:r,event:"$feature_flag_called",properties:a,groups:o,disableGeoip:i})}}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:e=>this._captureFlagCalledEventIfNeeded(e),logWarning:e=>{this.options.featureFlagsLogWarnings!==!1&&console.warn(`[PostHog] ${e}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:e,groupKey:r,properties:n,distinctId:s,disableGeoip:o}){this._sendPreparedEvent("capture",{distinctId:s||`$${e}_${r}`,event:"$groupidentify",properties:{$group_type:e,$group_key:r,$group_set:n||{}},disableGeoip:o},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:r,properties:n,distinctId:s,disableGeoip:o}){await this._sendPreparedEvent("capture",{distinctId:s||`$${e}_${r}`,event:"$groupidentify",properties:{$group_type:e,$group_key:r,$group_set:n||{}},disableGeoip:o},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let r=n=>Object.fromEntries(n.map(s=>[s,!0]));if(e===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=r(e);return}if(this._isFeatureFlagOverrideOptions(e)){"flags"in e&&(e.flags===!1?this._flagOverrides=void 0:Array.isArray(e.flags)?this._flagOverrides=r(e.flags):e.flags!==void 0&&(this._flagOverrides={...e.flags})),"payloads"in e&&(e.payloads===!1?this._payloadOverrides=void 0:e.payloads!==void 0&&(this._payloadOverrides={...e.payloads}));return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let r=e;if("flags"in r){let n=r.flags;if(n===!1||Array.isArray(n)||typeof n=="object"&&n!==null)return!0}if("payloads"in r){let n=r.payloads;if(n===!1||typeof n=="object"&&n!==null)return!0}return!1}withContext(e,r,n){return this.context?this.context.run(e,r,n):r()}getContext(){return this.context?.get()}enterContext(e,r){this.context?.enter(e,r)}async _shutdown(e){let r=Date.now()+(e??3e4),n=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics&&(await Dt(this._metrics.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._metrics.reset()),this._traces&&(await Dt(this._traces.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._traces.reset());try{return await super._shutdown(Math.max(0,r-Date.now()))}finally{this._distinctIdHasSentFlagCalls.clear(),n?.()}}async _requestRemoteConfigPayload(e){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let r=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},s=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let o=new AbortController;s=pe(()=>{o.abort()},this.options.requestTimeout),n.signal=o.signal}try{return await this.fetch(r,n)}catch(o){this._events.emit("error",o);return}finally{s&&clearTimeout(s)}}extractPropertiesFromEvent(e,r){if(!e)return{personProperties:{},groupProperties:{}};let n={},s={};for(let[o,i]of Object.entries(e))if(km(i)&&r&&o in r){let a={};for(let[c,u]of Object.entries(i))a[String(c)]=String(u);s[String(o)]=a}else n[String(o)]=String(i);return{personProperties:n,groupProperties:s}}async getFeatureFlagsForEvent(e,r,n,s){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let o=s?.personProperties||{},i=s?.groupProperties||{},a=s?.flagKeys;if(s?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let u={};for(let[l,d]of Object.entries(r||{}))u[l]=String(d);return await this.getAllFlags(e,{groups:u,personProperties:o,groupProperties:i,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let u={};for(let[l,d]of Object.entries(r||{}))u[l]=String(d);return await this.getAllFlags(e,{groups:u,personProperties:o,groupProperties:i,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(e,r,o,i,n)).flags}addLocalPersonAndGroupProperties(e,r,n,s){let o={...n||{}},i={};if(r)for(let a of Object.keys(r))i[a]={$group_key:r[a],...s?.[a]||{}};return{allPersonProperties:o,allGroupProperties:i}}personPropertiesForLocalEvaluation(e,r){return{distinct_id:e,...r||{}}}createFeatureFlagEvaluationContext(e,r,n,s){return{distinctId:e,groups:r||{},personProperties:n||{},groupProperties:s||{},evaluationCache:{}}}captureException(e,r,n,s,o){if(!lr.isPreviouslyCapturedError(e)){let i=new Error("PostHog syntheticException");this.addPendingPromise(lr.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:i},r,n).then(a=>this._capturePreparedEvent({...a,uuid:s,flags:o},!1)))}}async captureExceptionImmediate(e,r,n,s){if(!lr.isPreviouslyCapturedError(e)){let o=new Error("PostHog syntheticException");return this.addPendingPromise(lr.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:o},r,n).then(i=>this.captureImmediate({...i,flags:s})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,r={}){let{distinctId:n,event:s,properties:o,groups:i,flags:a,sendFeatureFlags:c,timestamp:u,disableGeoip:l,uuid:d}=e,p=this.context?.get(),g=r.includeContextProperties??!0,m=n||p?.distinctId,h=g?{...this.props,...p?.properties||{},...o||{}}:{...o||{}};s==="$exception"&&!("$trace_id"in h||"$span_id"in h)&&Object.assign(h,await bE()),m||(m=fe(),h.$process_person_profile=!1),g&&p?.sessionId&&!h.$session_id&&(h.$session_id=p.sessionId);let _=this._shouldSendMinimalFlagCalledEvent(s,h)?Xn(h):h,S=this._runBeforeSend({distinctId:m,event:s,properties:_,groups:i,flags:a,sendFeatureFlags:c,timestamp:u,disableGeoip:l,uuid:d});if(!S)return Promise.reject(null);let b=await Promise.resolve().then(async()=>{if(a)return c&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),a._getEventProperties();if(c){ca("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead \u2014 it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let w=typeof c=="object"?c:void 0,T=await this.getFeatureFlagsForEvent(S.distinctId,i,l,w);return DO(T)}return{}}).catch(()=>({})).then(w=>{let T=S.groups||i;return{...w,...S.properties||{},...T!==void 0&&Object.keys(T).length>0?{$groups:T}:{}}});return S.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof b.$raw_user_agent=="string"&&Cm(b.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(S.event="$bot_pageview",b.$browser_type="bot"),{distinctId:S.distinctId,event:S.event,properties:b,options:{timestamp:S.timestamp,disableGeoip:S.disableGeoip,uuid:S.uuid}}}_runBeforeSend(e){let r=this.options.before_send;if(!r)return e;let n=Array.isArray(r)?r:[r],s=e;for(let o of n)try{if(s=o(s),!s)return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!s.properties||Object.keys(s.properties).length===0){let i=`Event '${s.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(i)}}catch(i){return this._logger.error(`Error in before_send function for event '${e.event}':`,i),null}return s}};var PE=require("node:async_hooks"),la=class{constructor(){this.storage=new PE.AsyncLocalStorage}get(){return this.storage.getStore()}run(e,r,n){return this.storage.run(this.resolve(e,n),r)}enter(e,r){this.storage.enterWith(this.resolve(e,r))}resolve(e,r){if(r?.fresh===!0)return e;let n=this.get()||{};return{distinctId:e.distinctId??n.distinctId,sessionId:e.sessionId??n.sessionId,properties:{...n.properties||{},...e.properties||{}}}}};var ME=require("node:async_hooks"),da=class{active(){return this._storage.getStore()}with(e,r){return this._storage.run(e,r)}constructor(){this._storage=new ME.AsyncLocalStorage}};var xE=require("node:zlib"),kE=require("node:util"),FO=(0,kE.promisify)(xE.gzip);async function NE(t,e=!0){try{let r=await FO(t);return new Uint8Array(r)}catch(r){return e&&console.error("Failed to gzip compress data",r),null}}var fa=require("node:os");function CE(){let t,e;try{t=(0,fa.platform)(),e=(0,fa.release)()}catch{}return il(t,e)}var DE="posthog-node";function LO(t,{organization:e,projectId:r,prefix:n,severityAllowList:s=["error"],sendExceptionsToPostHog:o=!0}={}){return i=>{if(!(s==="*"||s.includes(i.level)))return i;i.tags||(i.tags={});let c=i.tags[ld.POSTHOG_ID_TAG];if(c===void 0)return i;let u=t.options.host??"https://us.i.posthog.com",l=new URL(`/project/${t.apiKey}/person/${c}`,u).toString();i.tags["PostHog Person URL"]=l;let d=i.exception?.values||[],p=d.map(h=>({...h,stacktrace:h.stacktrace?{...h.stacktrace,type:"raw",frames:(h.stacktrace.frames||[]).map(_=>({..._,platform:"node:javascript"}))}:void 0})),g={$exception_message:d[0]?.value||i.message,$exception_type:d[0]?.type,$exception_level:i.level,$exception_list:p,$sentry_event_id:i.event_id,$sentry_exception:i.exception,$sentry_exception_message:d[0]?.value||i.message,$sentry_exception_type:d[0]?.type,$sentry_tags:i.tags},m=Z.getInjectedReleaseId();return m&&(g.$release_id=m),e&&r&&(g.$sentry_url=(n||"https://sentry.io/organizations/")+e+"/issues/?project="+r+"&query="+i.event_id),o&&t.capture({event:"$exception",distinctId:c,properties:g}),i}}var ld=class{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(e,r,n,s,o){this.name=DE,this.name=DE,this.setupOnce=function(i,a){let c=a()?.getClient()?.getDsn()?.projectId;i(LO(e,{organization:r,projectId:c,prefix:n,severityAllowList:s,sendExceptionsToPostHog:o??!0}))}}};var pa=class extends ua{getLibraryId(){return"posthog-node"}compressPayload(e){return NE(e,this.isDebug)}initializeContext(){return new la}initializeSpanContextManager(){return new da}hostResourceAttributes(){return CE()}createErrorPropertiesBuilder(){return new Z.ErrorPropertiesBuilder([new Z.EventCoercer,new Z.ErrorCoercer,new Z.ObjectCoercer,new Z.StringCoercer,new Z.PrimitiveCoercer],Z.createStackParser("node:javascript",Z.nodeStackLineParser),[Am(),e=>l_(e,void 0,this._logger),g_()])}};cc();pc();fc();mc();var QH=300*1e3,ZH=3600*1e3;O();var fd=null,UO=!1,$O=3e4,ga=null;function LE(){let t=Date.now();if(ga&&t<ga.expiresAt)return ga.value;let e=Ys(process.env,_n());return ga={value:e,expiresAt:t+$O},e}var BO=!1;function WO(){if(!fd){let t=BO&&Kf(process.env)&&LE();fd=new pa(Qs(),{host:Zs(),flushAt:20,flushInterval:1e4,disableGeoip:!1,enableExceptionAutocapture:t,before_send:qO})}return fd}var jO=6e4,HO=500,Ss=new Map;function XO(t,e,r){let n="";try{let s=(r||"").split(`
|
|
42
|
+
`).map(o=>o.trim()).filter(Boolean);n=s.find(o=>o.startsWith("at "))??s[1]??""}catch(s){let o=s instanceof Error?s:new Error(String(s));f.warn("SYSTEM","Telemetry: stack parse failed while fingerprinting; using empty top frame",void 0,o),n=""}return`${t}::${Jf(e)}::${n}`.slice(0,400)}function KO(t,e){try{return GO(t,e)}catch(r){let n=r instanceof Error?r:new Error(String(r));return f.warn("SYSTEM","Telemetry: error rate-limit bookkeeping failed; failing closed (event dropped)",void 0,n),{send:!1,count:0}}}function GO(t,e){let r=Ss.get(t);if(!r){if(Ss.size>=HO){let n=null,s=1/0;for(let[o,i]of Ss){let a=Math.max(i.lastSentTs,i.firstTs);a<s&&(s=a,n=o)}n!==null&&Ss.delete(n)}return r={count:1,firstTs:e,lastSentTs:e},Ss.set(t,r),{send:!0,count:1}}if(r.count+=1,e-r.lastSentTs>=jO){r.lastSentTs=e;let n=r.count;return r.count=0,{send:!0,count:n}}return{send:!1,count:r.count}}var FE="__cm_rate_limited";function zO(t){try{return typeof t!="string"||t.length===0?"":lc(uc(t))}catch(e){let r=e instanceof Error?e:new Error(String(e));return f.warn("SYSTEM","Telemetry: frame filename redaction failed; stripping value entirely",void 0,r),""}}function VO(t){let e=t.$exception_list;if(Array.isArray(e))for(let r of e){if(!r||typeof r!="object")continue;let n=r;typeof n.value=="string"&&(n.value=qf(n.value));let o=n.stacktrace?.frames;if(Array.isArray(o))for(let i of o){if(!i||typeof i!="object")continue;let a=i;delete a.context_line,delete a.pre_context,delete a.post_context,typeof a.filename=="string"&&(a.filename=zO(a.filename))}}}function YO(t){try{let e=[],r=o=>{typeof o=="string"&&e.push(o)};r(t.$exception_message),r(t.$exception_type),r(t.error_message),r(t.error_type);let n=t.$exception_list;if(Array.isArray(n))for(let o of n)o&&typeof o=="object"&&(r(o.value),r(o.type));let s=e.join(" ");return/chdir/i.test(s)?/\b(?:EPERM|EACCES)\b|operation not permitted|permission denied/i.test(s):!1}catch{return!1}}function qO(t){try{if(!t||typeof t!="object")return t;let e=t;if(e.event!=="$exception")return t;let r=e.properties??{};if(YO(r))return null;if(r[FE]){try{delete r[FE],e.properties=r}catch{}return t}VO(r),r.$process_person_profile=!1,e.properties=r;let n="Error",s="",o="";try{let c=r.$exception_list;if(Array.isArray(c)&&c[0]&&typeof c[0]=="object"){let u=c[0];typeof u.type=="string"&&(n=u.type),typeof u.value=="string"&&(s=u.value);let l=u.stacktrace?.frames;Array.isArray(l)&&l.length>0&&(o="at "+JSON.stringify(l[l.length-1]).slice(0,200))}}catch{}typeof r.$exception_type=="string"&&(n=r.$exception_type),typeof r.$exception_message=="string"&&(s=r.$exception_message);let i=XO(n,s,o),a=KO(i,Date.now());if(!a.send)return null;try{r.occurrence_count=a.count,e.properties=r}catch{}return t}catch{return null}}function dd(t,e,r){try{JO(t,e,r)}catch(n){let s=n instanceof Error?n:new Error(String(n));f.warn("SYSTEM","Telemetry: captureEvent failed; event dropped",{event:t},s)}}function JO(t,e,r){if(UO||!LE())return;let n=Js({...to(),...e??{}});if(r?.person?n.$set=eo(n):n.$process_person_profile=!1,process.env.MEMINDEX_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:t,properties:n})+`
|
|
43
|
+
`);return}WO().capture({distinctId:qs(),event:t,properties:n})}var QO=["agent-cost-report","babysit","cloud-sync","design-is","do","handoff","how-it-works","knowledge-agent","learn-codebase","make-plan","mem-search","mode-creator","oh-my-issues","pathfinder","screenpipe","smart-explore","standup","timeline-report","weekly-digests","what-the","wowerpoint"],ZO=new Set(QO),UE={skill_id:"other",skill_source:"third_party"};function $E(t){let e=eP(t);return e&&ZO.has(e)?{skill_id:e,skill_source:"first_party"}:UE}function BE(t,e){if(t==="Skill"&&!(!e||typeof e!="object"))return e.skill}function eP(t){if(typeof t!="string")return null;let e=t.trim().toLowerCase();if(!e)return null;e=e.replace(/^\/+/,"");let r=e.lastIndexOf(":");return r!==-1&&(e=e.slice(r+1).replace(/^\/+/,"")),e||null}ha();var jE=null,rP=new Set(["SetTodoList","TodoList","TaskList","TaskOutput","TaskStop","CronCreate","CronList","CronDelete"]),HE=new Map;function nP(t){let e=HE.get(t);if(e!==void 0)return e;let r=null;try{r=new RegExp(t)}catch(n){f.warn("INGEST","Invalid MEMINDEX_SKIP_BASH_PATTERNS regex \u2014 ignoring",{pattern:t,error:n instanceof Error?n.message:String(n)})}return HE.set(t,r),r}function sP(t,e){if(!e||typeof e!="object")return"";let r=e,n=t==="exec_command"?r.cmd:t==="Bash"||t==="PowerShell"?r.command:void 0;return typeof n=="string"?n:""}function oP(){if(!jE)throw new Error("ingest helpers used before setIngestContext() \u2014 wiring bug");return jE}async function XE(t,e={}){if(rn(t.toolName))return{ok:!0,status:"skipped",reason:"memory_retrieval"};let{sessionManager:r,dbManager:n,eventBroadcaster:s,ensureGeneratorRunning:o}=oP(),i=z(t.platformSource),a=typeof t.cwd=="string"?t.cwd:"",c=a.trim()?await yn(a):null,u=c?.primary||"unknown",l=V.loadFromFile(_e);if(a&&io(a,l.MEMINDEX_EXCLUDED_PROJECTS))return{ok:!0,status:"skipped",reason:"project_excluded"};if(kt(t.toolName,l.MEMINDEX_SKIP_TOOLS)){if(t.toolName==="Skill"){let{skill_id:y,skill_source:A}=$E(BE(t.toolName,t.toolInput));dd("skill_invoked",{skill_id:y,skill_source:A,skill_trigger:"tool",ide:i})}return{ok:!0,status:"skipped",reason:"tool_excluded"}}if(i==="kimi"&&rP.has(t.toolName))return{ok:!0,status:"skipped",reason:"tool_excluded"};let d=l.MEMINDEX_SKIP_BASH_PATTERNS.trim(),p=d?sP(t.toolName,t.toolInput):"";if(p){let y=nP(d);if(y&&y.test(p))return{ok:!0,status:"skipped",reason:"bash_pattern_excluded"}}let g=Dr(t.agentId,t.agentType,l);if(g.skip)return{ok:!0,status:"skipped",reason:g.reason};if(new Set(["Edit","Write","Read","NotebookEdit"]).has(t.toolName)&&t.toolInput&&typeof t.toolInput=="object"){let y=t.toolInput,A=y.file_path||y.notebook_path;if(A&&A.includes("session-memory"))return{ok:!0,status:"skipped",reason:"session_memory_meta"};if(A&&vm(A))return{ok:!0,status:"skipped",reason:"endless_mode_bottle"}}let h=n.getSessionStore(),_,S;try{_=h.createSDKSession(t.contentSessionId,u,"",void 0,i),a&&h.setSessionCwd(_,a,c?.keySource),S=h.getPromptNumberFromUserPrompts(t.contentSessionId,_,t.enqueuedAtEpochMs)}catch(y){let A=y instanceof Error?y.message:String(y);return f.error("INGEST","Observation session resolution failed",{contentSessionId:t.contentSessionId,toolName:t.toolName},y instanceof Error?y:new Error(A)),{ok:!1,reason:A,status:500}}if(!Vo.checkUserPromptPrivacy(h,t.contentSessionId,S,"observation",_,{tool_name:t.toolName}).allow)return{ok:!0,status:"skipped",reason:"private"};let w=t.toolInput!==void 0?Ie(JSON.stringify(t.toolInput)):"{}",T=t.toolResponse!==void 0?Ie(JSON.stringify(t.toolResponse)):"{}";if(t.toolUseId)try{h.upsertToolUse({toolUseId:t.toolUseId,contentSessionId:t.contentSessionId,sessionDbId:_,project:u,platformSource:i,toolName:t.toolName,toolInput:w,toolResponse:T,cwd:a||null,promptNumber:S,agentType:typeof t.agentType=="string"?t.agentType:null,agentId:typeof t.agentId=="string"?t.agentId:null,orGenerationId:typeof t.orGenerationId=="string"?t.orGenerationId:null,orSessionId:typeof t.orSessionId=="string"?t.orSessionId:null})}catch(y){f.warn("INGEST","tool_uses backup write failed (observation still queued)",{sessionId:_,toolName:t.toolName,toolUseId:t.toolUseId},y instanceof Error?y:new Error(String(y)))}return ma(t.toolName)?{ok:!0,status:"skipped",reason:"explicit_memory_write"}:(r.queueObservation(_,{tool_name:t.toolName,tool_input:w,tool_response:T,prompt_number:S,cwd:a||(f.error("INGEST","Missing cwd when ingesting observation",{sessionId:_,toolName:t.toolName}),""),agentId:typeof t.agentId=="string"?t.agentId:void 0,agentType:typeof t.agentType=="string"?t.agentType:void 0,toolUseId:typeof t.toolUseId=="string"?t.toolUseId:void 0},t.enqueuedAtEpochMs),e.markHandedOff?.(),await o?.(_,"observation"),s.broadcastObservationQueued(_),{ok:!0,sessionDbId:_})}var iP=/agent-transcripts[/\\]([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:[/\\]|$)/i;function aP(t){let e=typeof t.agentId=="string"?t.agentId.trim():"";return e&&e!=="*"?e:t.path.match(iP)?.[1]}var bs=class extends Error{constructor(e,r){super(`session init failed for transcript session ${e}: ${r instanceof Error?r.message:String(r)}`),this.name="TranscriptAnchorError",this.cause=r}},ws=class extends Error{constructor(e,r){super(`observation not accepted for transcript session ${e}: ${r instanceof Error?r.message:String(r)}`),this.name="TranscriptObservationError",this.cause=r}},mr=class extends Error{constructor(e,r){super(`transcript event not persisted for session ${e}: ${r instanceof Error?r.message:String(r)}`),this.name="TranscriptSpoolError",this.cause=r}},cP=4096,uP=64,_a=class{constructor(e="in-process"){this.observationTransport=e}observationTransport;sessions=new Map;fileContexts=new Set;fileSessionKeys=new WeakMap;registerFileContext(e){this.fileContexts.add(e)}pendingToolOwners=new WeakMap;subagentSessionKeys=new Set;resetFileContext(e){for(let r of this.sessionKeysOf(e)){let n=this.sessions.get(r);n&&n.cwd===e.cwd&&(n.cwd=void 0)}this.retireFileContext(e),e.cwd=void 0,e.sessionId=void 0}retireFileContext(e){for(let r of this.sessionKeysOf(e)){let n=this.sessions.get(r)?.pendingTools;for(let[s,o]of n??[])this.pendingToolOwners.get(o)===e&&n.delete(s)}this.fileContexts.delete(e),this.fileSessionKeys.delete(e),e.pendingTools={}}sessionKeysOf(e){return new Set([...Object.keys(e.pendingTools??{}),...this.fileSessionKeys.get(e)??[]])}async processEntry(e,r,n,s,o){o&&this.registerFileContext(o);for(let i of n.events)kn(e,i.match,n)&&await this.handleEvent(e,r,n,i,s??void 0,o)}getSessionKey(e,r){return`${e.name}:${r}`}getOrCreateSession(e,r){let n=this.getSessionKey(e,r),s=this.sessions.get(n);return s||(s={sessionId:r,platformSource:z(e.name),...this.subagentSessionKeys.has(n)?{isSubagent:!0}:{}},this.sessions.set(n,s)),s}rememberSubagentSession(e){if(this.subagentSessionKeys.delete(e),this.subagentSessionKeys.add(e),this.subagentSessionKeys.size>cP){let r=this.subagentSessionKeys.values().next().value;r!==void 0&&this.subagentSessionKeys.delete(r)}}async primeSessionContext(e,r,n,s,o){for(let i of n.events)i.action!=="session_context"||!kn(e,i.match,n)||await this.handleEvent(e,r,n,i,s??void 0,o)}resolveSessionId(e,r,n,s,o){let i={watch:r,schema:n},a=s.fields?.sessionId??(n.sessionIdPath?{path:n.sessionIdPath}:void 0),c=Cr(a,e,i);return typeof c=="string"&&c.trim()?c:typeof c=="number"?String(c):o&&o.trim()?o:null}resolveCwd(e,r,n,s,o){let i={watch:r,schema:n,session:o},a=s.fields?.cwd??(n.cwdPath?{path:n.cwdPath}:void 0),c=Cr(a,e,i);return typeof c=="string"&&c.trim()?c:r.workspace?r.workspace:o.cwd}resolveProjectWithoutGit(e,r,n,s,o){let i={watch:r,schema:n,session:o},a=s.fields?.project??(n.projectPath?{path:n.projectPath}:void 0),c=Cr(a,e,i);return typeof c=="string"&&c.trim()?c:r.project}async lookUpProjectFromGit(e,r,n,s,o,i){let a=this.sessions.get(this.getSessionKey(r,o)),c={...a,cwd:a?.cwd??i?.cwd};if(this.resolveProjectWithoutGit(e,r,n,s,c))return;let u=this.resolveCwd(e,r,n,s,c);return u?(await yn(u)).primary:void 0}async handleEvent(e,r,n,s,o,i){let a=this.resolveSessionId(e,r,n,s,i?.sessionId??o);if(!a){f.debug("TRANSCRIPT","Skipping event without sessionId",{event:s.name,watch:r.name});return}i&&(i.sessionId=a);let c=await this.lookUpProjectFromGit(e,r,n,s,a,i),u=this.getOrCreateSession(r,a),l=this.getSessionKey(r,a);if(i){let m=this.fileSessionKeys.get(i)??new Set;m.add(l),this.fileSessionKeys.set(i,m)}if(i?.pendingTools?.[l]){u.pendingTools??=new Map;for(let[m,h]of Object.entries(i.pendingTools[l]))this.pendingToolOwners.set(h,i),u.pendingTools.has(m)||u.pendingTools.set(m,h)}!u.cwd&&i?.cwd&&(u.cwd=i.cwd);let d=this.resolveCwd(e,r,n,s,u);d&&(u.cwd=d);let p=this.resolveProjectWithoutGit(e,r,n,s,u)??(u.cwd?c:u.project);if(p&&(u.project=p),r.subagentSource&&!u.isSubagent){let m=xn(e,r.subagentSource.path);m!=null&&(u.isSubagent=!0,this.rememberSubagentSession(this.getSessionKey(r,a)))}if(r.subagentOnly&&!u.isSubagent&&s.action!=="session_context"&&s.action!=="session_end")return;let g=bm(s.fields,e,{watch:r,schema:n,session:u});s.action==="session_context"&&this.applySessionContext(u,g),i&&u.cwd&&(i.cwd=u.cwd);try{switch(s.action){case"session_context":break;case"session_init":await this.handleSessionInit(u,g),r.context?.updateOn?.includes("session_start")&&await this.updateContext(u,r);break;case"user_message":{let m=this.resolveMessageText(g.message)??this.resolveMessageText(g.prompt);m&&await this.anchorUserPrompt(u,m);break}case"assistant_message":u.lastAssistantMessage=this.resolveMessageText(g.message)??u.lastAssistantMessage;break;case"tool_use":await this.handleToolUse(u,r,g,i);break;case"tool_result":await this.handleToolResult(u,r,g,i);break;case"observation":await this.sendObservation(u,r,g);break;case"file_edit":await this.sendFileEdit(u,g);break;case"session_end":await this.handleSessionEnd(u,r);break;default:break}}finally{i&&this.snapshotPendingTools(i,u,l,s.action==="session_end")}}snapshotPendingTools(e,r,n,s){let o=s?{}:{...e.pendingTools?.[n]};for(let[a,c]of r.pendingTools??[])this.pendingToolOwners.get(c)===e&&(o[a]=c);e.pendingTools={...e.pendingTools,[n]:o},Object.keys(o).length===0&&delete e.pendingTools[n];let i=Object.entries(e.pendingTools).flatMap(([a,c])=>Object.keys(c).map(u=>[a,u]));for(let[a,c]of i.slice(0,Math.max(0,i.length-uP))){let u=e.pendingTools[a],l=u[c];delete u[c],Object.keys(u).length===0&&delete e.pendingTools[a];let d=this.sessions.get(a)?.pendingTools;d?.get(c)===l&&d.delete(c)}}applySessionContext(e,r){let n=typeof r.cwd=="string"?r.cwd:void 0,s=typeof r.project=="string"?r.project:void 0;n&&(e.cwd=n),s&&(e.project=s)}resolveMessageText(e){if(typeof e=="string")return e;if(!Array.isArray(e))return;let r=[];for(let n of e)n&&typeof n=="object"&&typeof n.text=="string"&&r.push(n.text);return r.length>0?r.join(`
|
|
44
|
+
`):void 0}async handleSessionInit(e,r){let n=typeof r.prompt=="string"?r.prompt:"";await this.anchorUserPrompt(e,n)}async anchorUserPrompt(e,r){r&&(e.lastUserMessage=r);let n=e.cwd;if(!n){this.skipWithoutCwd(e,"user prompt");return}try{await Wo({sessionId:e.sessionId,cwd:n,prompt:r,platform:e.platformSource})}catch(s){throw new bs(e.sessionId,s)}}skipWithoutCwd(e,r){f.debug("TRANSCRIPT",`Skipping a ${r}: the session has no known working directory yet`,{sessionId:e.sessionId})}async handleToolUse(e,r,n,s){let o=typeof n.toolId=="string"?n.toolId:void 0,i=typeof n.toolName=="string"?n.toolName:void 0,a=this.maybeParseJson(n.toolInput),c=this.maybeParseJson(n.toolResponse);if(i==="apply_patch"&&typeof a=="string"){let u=this.parseApplyPatchFiles(a);for(let l of u)await this.sendFileEdit(e,{filePath:l,edits:[{type:"apply_patch",patch:a}]})}if(i&&c!==void 0)await this.sendObservation(e,r,{toolName:i,toolInput:a,toolResponse:c,toolUseId:o});else if(i&&o){e.pendingTools||(e.pendingTools=new Map);let u={toolName:i,toolInput:a};s&&this.pendingToolOwners.set(u,s),e.pendingTools.set(o,u)}}async handleToolResult(e,r,n,s){let o=typeof n.toolId=="string"?n.toolId:void 0,i=typeof n.toolName=="string"?n.toolName:void 0,a=this.maybeParseJson(n.toolResponse),c=this.maybeParseJson(n.toolInput),u=s?.pendingTools?.[this.getSessionKey(r,e.sessionId)],l=o?e.pendingTools?.get(o):void 0,d=s,p=s?(o?u?.[o]:void 0)??(l&&this.pendingToolOwners.get(l)===s?l:void 0):l;if(!p&&s&&o){let g=Array.from(this.fileContexts).flatMap(m=>{let h=m.pendingTools?.[this.getSessionKey(r,e.sessionId)]?.[o];return h&&m.isCurrent?.()!==!1?[{context:m,tool:h}]:[]});g.length===1&&(d=g[0].context,p=g[0].tool)}if(p&&(i||(i=p.toolName),c===void 0&&(c=p.toolInput)),i){if(await this.sendObservation(e,r,{toolName:i,toolInput:c,toolResponse:a,toolUseId:o}),o){e.pendingTools&&e.pendingTools.get(o)===p&&e.pendingTools.delete(o);let g=d?.pendingTools?.[this.getSessionKey(r,e.sessionId)];g&&delete g[o]}}else f.debug("TRANSCRIPT","Dropping tool_result with no resolvable toolName",{sessionId:e.sessionId,toolId:o})}async sendObservation(e,r,n){let s=typeof n.toolName=="string"?n.toolName:void 0;if(!s)return;if(!e.cwd){this.skipWithoutCwd(e,"observation");return}let o={contentSessionId:e.sessionId,cwd:e.cwd,toolName:s,toolInput:this.maybeParseJson(n.toolInput),toolResponse:this.maybeParseJson(n.toolResponse),platformSource:e.platformSource,toolUseId:typeof n.toolUseId=="string"?n.toolUseId:void 0,agentId:aP(r)};if(this.observationTransport==="spool"){try{We("observation",o)}catch(a){throw new mr(e.sessionId,a)}return}let i=!1;try{let a=await XE(o,{markHandedOff:()=>{i=!0}});if(!a.ok)throw new Error(a.reason)}catch(a){if(i){f.warn("TRANSCRIPT","Observation accepted before generator kick failed",{sessionId:e.sessionId},a instanceof Error?a:void 0);return}throw new ws(e.sessionId,a)}}async sendFileEdit(e,r){let n=typeof r.filePath=="string"?r.filePath:void 0;if(n){if(!e.cwd){this.skipWithoutCwd(e,"file edit");return}try{await mm.execute({sessionId:e.sessionId,cwd:e.cwd,filePath:n,edits:Array.isArray(r.edits)?r.edits:void 0,platform:e.platformSource})}catch(s){throw new mr(e.sessionId,s)}}}maybeParseJson(e){if(typeof e!="string")return e;let r=e.trim();if(!r||!(r.startsWith("{")||r.startsWith("[")))return e;try{return JSON.parse(r)}catch(n){return f.debug("TRANSCRIPT","Field looked like JSON but did not parse; using raw string",{preview:r.slice(0,120)},n instanceof Error?n:void 0),e}}parseApplyPatchFiles(e){let r=[],n=e.split(`
|
|
45
|
+
`);for(let s of n){let o=s.trim();if(o.startsWith("*** Update File: "))r.push(o.replace("*** Update File: ","").trim());else if(o.startsWith("*** Add File: "))r.push(o.replace("*** Add File: ","").trim());else if(o.startsWith("*** Delete File: "))r.push(o.replace("*** Delete File: ","").trim());else if(o.startsWith("*** Move to: "))r.push(o.replace("*** Move to: ","").trim());else if(o.startsWith("+++ ")){let i=o.replace("+++ ","").replace(/^b\//,"").trim();i&&i!=="/dev/null"&&r.push(i)}}return Array.from(new Set(r))}async handleSessionEnd(e,r){(!r.subagentOnly||e.isSubagent)&&(await this.queueSummary(e),await this.updateContext(e,r)),e.pendingTools?.clear();let n=this.getSessionKey(r,e.sessionId);this.sessions.delete(n)}async queueSummary(e){if(this.observationTransport==="spool"){try{We("summarize",{contentSessionId:e.sessionId,platformSource:e.platformSource,lastAssistantMessage:e.lastAssistantMessage??"",...e.cwd?{cwd:e.cwd}:{}})}catch(o){throw new mr(e.sessionId,o)}return}if(!await Or())return;let n=e.lastAssistantMessage??"",s=JSON.stringify({contentSessionId:e.sessionId,last_assistant_message:n,platformSource:e.platformSource,...e.cwd?{cwd:e.cwd}:{}});try{await le("/api/sessions/summarize",{method:"POST",headers:{"Content-Type":"application/json"},body:s})}catch(o){f.warn("TRANSCRIPT","Summary request failed",{error:o instanceof Error?o.message:String(o)})}}async updateContext(e,r){if(!r.context||r.context.mode!=="agents"||nf(r)||!await Or())return;let s=e.cwd??r.workspace;if(!s)return;let i=(await yn(s)).allProjects.join(","),a=`/api/context/inject?projects=${encodeURIComponent(i)}&platformSource=${encodeURIComponent(e.platformSource)}`,c=ce(r.context.path??`${s}/AGENTS.md`),u=ys.default.resolve(c),l=[ys.default.resolve(s),ys.default.resolve(W)];if(!l.some(m=>u.startsWith(m+ys.default.sep)||u===m)){f.warn("SECURITY","Rejected path traversal attempt in watch.context.path",{original:r.context.path,resolved:u,allowedRoots:l});return}let p;try{p=await le(a)}catch(m){f.warn("TRANSCRIPT","Failed to fetch AGENTS.md context",{error:m instanceof Error?m.message:String(m)});return}if(!p.ok)return;let g=(await p.text()).trim();g&&(Em(c,g),f.debug("TRANSCRIPT","Updated AGENTS.md context",{agentsPath:c,watch:r.name}))}};var KE=be(require("node:zlib"),1),nn=require("node:fs");O();function GE(){let t=KE.zstdDecompressSync;return typeof t=="function"?t:void 0}function zE(){return GE()!==void 0}var lP=4247762216,dP=64*1024;function Ea(t,e,r,n=Number.POSITIVE_INFINITY){let s=(0,nn.openSync)(t,"r");try{let o=Buffer.alloc(0),i=0,a=(l,d)=>{if(l+d>r)return null;if(l<i||l+d>i+o.length){let p=Math.min(Math.max(d,dP),r-l),g=Buffer.alloc(p);if(o=g.subarray(0,(0,nn.readSync)(s,g,0,p,l)),i=l,o.length<d)return null}return o.subarray(l-i,l-i+d)},c=[],u=e;for(;u<r&&(c.length===0||u-e<n);){let l=u,d=a(u,4);if(!d)return{frames:c,tornStart:l};if(d.readUInt32LE(0)!==lP)throw new Error(`invalid Zstandard frame magic at byte ${u}`);u+=4;let p=a(u,1);if(!p)return{frames:c,tornStart:l};let g=p.readUInt8(0);if(u+=1,(g&8)!==0)throw new Error(`reserved Zstandard frame-header bit at byte ${u-1}`);let m=g>>>6,h=(g&32)!==0,_=(g&4)!==0,S=g&3,b=S===3?4:S,w=m===0?h?1:0:1<<m,T=(h?0:1)+b+w;if(u+T>r)return{frames:c,tornStart:l};for(u+=T;;){let y=a(u,3);if(!y)return{frames:c,tornStart:l};let A=y.readUIntLE(0,3);u+=3;let v=(A&1)!==0,R=A>>>1&3,I=A>>>3;if(R===3)throw new Error(`reserved Zstandard block type at byte ${u-3}`);let M=R===1?1:I;if(u+M>r)return{frames:c,tornStart:l};if(u+=M,v)break}if(_){if(u+4>r)return{frames:c,tornStart:l};u+=4}c.push({start:l,end:u})}return{frames:c,tornStart:null}}finally{(0,nn.closeSync)(s)}}function pd(t,e){try{let r=GE();if(!r)throw new Error("this runtime cannot decode Zstandard (zlib.zstdDecompressSync is missing)");return r(t.subarray(e.start,e.end))}catch(r){throw f.warn("TRANSCRIPT","Failed to decompress Zstandard frame",{start:e.start,end:e.end,error:r instanceof Error?r.message:String(r)}),r}}function VE(t,e){return pd(t,e).toString("utf8")}var YE=2e3,fP=1e3,pP=256*1024,qE=4*1024*1024,gP=16*1024*1024,mP=100,JE=100;function Ts(){return new Promise(t=>setImmediate(t))}var Sa=".jsonl.zstd";async function hP(t,e){try{let r=0;for(;r<e;){let n=Ea(t,r,e,gP);if(n.tornStart!==null)return n.tornStart;if(n.frames.length===0)break;r=n.frames[n.frames.length-1].end,await Ts()}return r}catch{return e}}var QE=1024*1024;async function tS(t,e,r){let n;if(e){let{frames:o}=Ea(t,0,Math.min(r,QE),1);if(o.length===0)return null;n=VE(await ba(t,0,o[0].end),o[0])}else n=(await ba(t,0,Math.min(r,QE))).toString("utf8");let s=n.indexOf(`
|
|
46
|
+
`);return s<0?null:n.slice(0,s)}async function _P(t,e,r){try{let n=await tS(t,e,r);if(n===null)return null;let s=JSON.parse(n);for(let o of["timestamp","time","createdAt"]){let i=s?.[o],a=typeof i=="number"?i<1e12?i*1e3:i:typeof i=="string"?Date.parse(i):Number.NaN;if(Number.isFinite(a)&&a>0)return a}return null}catch{return null}}function ya(t){return`${t.dev}:${t.ino}`}function EP(t){try{return(0,X.statSync)(t),!1}catch(e){let r=e.code;return r==="ENOENT"||r==="ENOTDIR"}}var SP=4096;function md(t,e,r){let n;try{if(n=(0,X.openSync)(t,"r"),ya((0,X.fstatSync)(n))!==r)return null;let s=Math.max(0,e-SP),o=Buffer.alloc(e-s);return(0,X.readSync)(n,o,0,o.length,s)<o.length?null:(0,ZE.createHash)("sha256").update(o).digest("hex")}catch(s){return f.debug("TRANSCRIPT","Could not fingerprint a transcript checkpoint",{file:t},s instanceof Error?s:void 0),null}finally{n!==void 0&&(0,X.closeSync)(n)}}function rS(t,e,r,n,s){return r<n?!1:s===void 0?!0:md(t,n,e)===s}async function ba(t,e,r){let n=await(0,eS.open)(t,"r");try{let s=Buffer.alloc(r),{bytesRead:o}=await n.read(s,0,r,e);return s.subarray(0,o)}finally{await n.close()}}var gd=class{constructor(e,r,n,s,o="",i=0,a,c,u,l){this.filePath=e;this.onLine=n;this.onOffset=s;this.onReset=u;this.fileIdentity=a,this.checkpointFingerprint=c,this.isZstd=e.endsWith(Sa),this.zstdPartialBytes=this.isZstd&&l?Buffer.from(l,"base64"):void 0,this.tailState={offset:r,readOffset:r,partial:this.isZstd?o:""},this.frameLinesDone=this.isZstd?i:0}filePath;onLine;onOffset;onReset;watcher=null;tailState;readTask=null;readPending=!1;closed=!1;isZstd;pendingRecord=Buffer.alloc(0);frameLinesDone;zstdPartialBytes;fileIdentity;checkpointFingerprint;start(){this.requestRead();try{this.watcher=(0,X.watch)(this.filePath,{persistent:!0},()=>{this.requestRead()})}catch(e){f.debug("WORKER","Failed to watch transcript file",{file:this.filePath},e instanceof Error?e:void 0),this.watcher=null}}close(){this.closed=!0,this.watcher?.close(),this.watcher=null}poke(){this.requestRead()}requestRead(){if(!this.closed){if(this.readTask){this.readPending=!0;return}this.readTask=this.drainReads().finally(()=>{this.readTask=null,this.readPending&&this.requestRead()})}}async drainReads(){do this.readPending=!1,await this.readNewData().catch(()=>{}),this.readPending&&await Ts();while(this.readPending&&!this.closed)}async readNewData(){if(!(0,X.existsSync)(this.filePath))return;let e=0,r;try{let i=(0,X.statSync)(this.filePath);e=i.size,r=ya(i)}catch(i){f.debug("WORKER","Failed to stat transcript file",{file:this.filePath},i instanceof Error?i:void 0);return}let n=r!==this.fileIdentity,s=!1;n&&this.fileIdentity!==void 0&&(rS(this.filePath,r,e,this.tailState.offset,this.checkpointFingerprint)?(this.tailState.readOffset=this.tailState.offset,this.pendingRecord=Buffer.alloc(0)):s=!0),this.fileIdentity=r;let o=s||e<this.tailState.readOffset;if(o&&(this.onReset?.(),this.tailState.offset=0,this.tailState.readOffset=0,this.tailState.partial="",this.zstdPartialBytes=void 0,this.pendingRecord=Buffer.alloc(0),this.frameLinesDone=0),e===this.tailState.readOffset){(n||o)&&this.checkpoint(this.tailState.offset,this.tailState.partial);return}this.isZstd?await this.readNewZstdFrames(e):await this.readNewJsonl(e)}checkpoint(e,r="",n=this.zstdPartialBytes){this.zstdPartialBytes=n,this.tailState.offset=e,this.tailState.partial=r,this.checkpointFingerprint=this.fileIdentity===void 0?void 0:md(this.filePath,e,this.fileIdentity)??void 0,this.onOffset(e,r,this.frameLinesDone,this.fileIdentity,this.checkpointFingerprint,this.zstdPartialBytes?.toString("base64"))}async readNewJsonl(e){let r=this.tailState.readOffset,n;try{n=await ba(this.filePath,r,Math.min(e-r,qE))}catch(c){f.debug("WORKER","Failed to read transcript file",{file:this.filePath},c instanceof Error?c:void 0);return}if(n.length===0)return;this.tailState.readOffset=r+n.length;let s=this.pendingRecord.length>0?Buffer.concat([this.pendingRecord,n]):n,o=this.tailState.offset,i=0,a=0;for(let c=s.indexOf(10);c!==-1;c=s.indexOf(10,i)){if(this.closed){this.checkpoint(o+i);return}let u=s.toString("utf8",i,c).trim();if(u)try{await this.onLine(u)}catch{this.pendingRecord=Buffer.alloc(0),this.tailState.readOffset=o+i,this.checkpoint(o+i);return}i=c+1,this.tailState.offset=o+i,u&&++a%JE===0&&(this.checkpoint(this.tailState.offset),await Ts())}this.pendingRecord=Buffer.from(s.subarray(i)),this.checkpoint(o+i),this.tailState.readOffset<e&&(this.readPending=!0)}async readNewZstdFrames(e){let r=this.tailState.offset,n,s;try{if(n=Ea(this.filePath,r,e,qE),n.frames.length===0)return;let i=n.frames[n.frames.length-1].end;if(s=await ba(this.filePath,r,i-r),s.length<i-r)return}catch(i){f.warn("TRANSCRIPT","Failed to read zstd transcript frames",{file:this.filePath,error:i instanceof Error?i.message:String(i)});return}let o=0;for(let i of n.frames){let a;try{a=pd(s,{start:i.start-r,end:i.end-r})}catch{this.checkpoint(this.tailState.offset,this.tailState.partial);return}let c=this.tailState.partial,u=this.zstdPartialBytes,l=Buffer.concat([u??Buffer.from(c,"utf8"),a]),d=[],p=0;for(let _=l.indexOf(10);_!==-1;_=l.indexOf(10,p))d.push(l.toString("utf8",p,_)),p=_+1;let g=l.subarray(p),m=g.toString("utf8"),h=Buffer.from(m,"utf8").equals(g)?void 0:Buffer.from(g);for(let _=this.frameLinesDone;_<d.length;_++){if(this.closed){this.frameLinesDone=_,this.checkpoint(i.start,c,u);return}let S=d[_].trim();if(S){try{await this.onLine(S)}catch{this.frameLinesDone=_,this.tailState.readOffset=i.start,this.checkpoint(i.start,c,u);return}++o%JE===0&&await Ts()}}this.frameLinesDone=0,this.tailState.offset=i.end,this.tailState.readOffset=i.end,this.tailState.partial=h?"":m,this.zstdPartialBytes=h}this.checkpoint(this.tailState.offset,this.tailState.partial),n.tornStart===null&&this.tailState.offset<e&&(this.readPending=!0)}},wa=class{constructor(e,r,n="in-process"){this.config=e;this.statePath=r;this.processor=new _a(n),this.state=df(r)}config;statePath;processor;tailers=new Map;state;fileContexts=new Map;retirementCandidates=new Set;retirementTimer=null;missingTranscriptGraceMs=fP;rootWatchers=[];rootWatchSettleTimers=new Set;startedAtMs=0;warnedZstdUnsupported=!1;startingTailers=new Set;stopped=!1;async start(){this.stopped=!1,this.startedAtMs=Date.now();for(let e of this.config.watches)await this.setupWatch(e);if(!this.stopped)for(let e of Object.keys(this.state.pendingTools??{}))this.tailers.has(e)||this.scheduleRetirementCheck(e)}stop(){this.stopped=!0;for(let e of this.tailers.values())e.close();this.tailers.clear();for(let e of this.rootWatchers)e.close();this.rootWatchers=[];for(let e of this.rootWatchSettleTimers)clearTimeout(e);this.rootWatchSettleTimers.clear(),this.retirementTimer&&clearTimeout(this.retirementTimer),this.retirementTimer=null,this.retirementCandidates.clear()}async setupWatch(e){let r=this.resolveSchema(e);if(!r){f.warn("TRANSCRIPT","Missing schema for watch",{watch:e.name});return}let n=ce(e.path),s=this.resolveWatchFiles(n);for(let i of s)this.getFileContext(i);let o={stateChanged:!1};for(let i of s)await this.addTailer(i,e,r,!1,o),await Ts();o.stateChanged&&pn(this.statePath,this.state),this.watchTranscriptRoot(n,e,r)}watchTranscriptRoot(e,r,n,s=!1){let o=this.selectWatchRoot(e);if(!o){f.debug("TRANSCRIPT","Watch root does not exist, skipping fs.watch",{watch:r.name,path:e});return}let{root:i,recursive:a}=o;try{let c=(0,X.watch)(i,{recursive:a,persistent:!0},(u,l)=>{a?this.handleRootWatchEvent(i,e,r,n,l):this.handleAncestorWatchEvent(c,i,e,r,n,l)});this.rootWatchers.push(c),(s||!a)&&this.settleRootWatch(c,i,a,e,r,n),f.info("TRANSCRIPT",a?"Watching transcript root recursively":"Transcript root does not exist yet; watching its closest existing directory",{watch:r.name,watchRoot:i})}catch(c){f.warn("TRANSCRIPT","Failed to start fs.watch on transcript root",{watch:r.name,watchRoot:i},c instanceof Error?c:void 0)}}handleRootWatchEvent(e,r,n,s,o){if(!o)return;let i=(0,J.resolve)(e,o).replace(/\\/g,"/"),a=this.tailers.get(i);if(a){if(!(0,X.existsSync)(i)){a.close(),this.tailers.delete(i),this.scheduleRetirementCheck(i);return}a.poke();return}this.touchesLiteralPrefix(i,r)&&this.addDiscoveredTailers(r,n,s)}handleAncestorWatchEvent(e,r,n,s,o,i){if(this.stopped||!this.rootWatchers.includes(e)||i&&!this.touchesLiteralPrefix((0,J.resolve)(r,i),n))return;let a=this.selectWatchRoot(n);a&&a.root===r&&!a.recursive||(e.close(),this.rootWatchers=this.rootWatchers.filter(c=>c!==e),this.watchTranscriptRoot(n,s,o,!0),this.addDiscoveredTailers(n,s,o))}settleRootWatch(e,r,n,s,o,i){let a=setTimeout(()=>{this.rootWatchSettleTimers.delete(a),!(this.stopped||!this.rootWatchers.includes(e))&&(n?this.addDiscoveredTailers(s,o,i):this.handleAncestorWatchEvent(e,r,s,o,i,null))},mP);this.rootWatchSettleTimers.add(a)}getFileContext(e){let r=this.fileContexts.get(e);return r||(r={cwd:this.state.cwds?.[e],pendingTools:this.state.pendingTools?.[e],isCurrent:()=>this.isCheckpointedFile(e)},this.fileContexts.set(e,r)),this.processor.registerFileContext(r),r}isCheckpointedFile(e){try{let r=(0,X.statSync)(e);return ya(r)===this.state.fileIdentities?.[e]&&r.size>=(this.state.offsets[e]??0)}catch{return!1}}scheduleRetirementCheck(e){this.retirementCandidates.add(e),this.retirementTimer??=setTimeout(()=>this.retireMissingTranscripts(),this.missingTranscriptGraceMs)}retireMissingTranscripts(){this.retirementTimer=null;let e=[...this.retirementCandidates];if(this.retirementCandidates.clear(),this.stopped)return;let r=!1;for(let n of e){if(this.tailers.has(n)||!EP(n))continue;let s=this.fileContexts.get(n);s&&this.processor.retireFileContext(s),this.fileContexts.delete(n),this.state.pendingTools?.[n]&&(delete this.state.pendingTools[n],r=!0)}r&&pn(this.statePath,this.state)}forgetReplacedTranscript(e,r){this.processor.resetFileContext(r),delete this.state.pendingTools?.[e],delete this.state.cwds?.[e]}addDiscoveredTailers(e,r,n){for(let s of this.resolveWatchFiles(e))this.tailers.has(s)||this.addTailer(s,r,n,!0).catch(o=>{f.debug("TRANSCRIPT","Failed to add transcript tailer",{file:s,watch:r.name},o instanceof Error?o:void 0)})}touchesLiteralPrefix(e,r){let n=e.replace(/\\/g,"/"),s=(0,J.resolve)(this.literalWatchPrefix(r)).replace(/\\/g,"/"),o=(i,a)=>i.startsWith(a.endsWith("/")?a:a+"/");return n===s||o(n,s)||o(s,n)}literalWatchPrefix(e){let r=e;if(this.hasGlob(e)){let n=e.split(/[/\\]/),s=[];for(let o of n){if(/[*?[\]{}()]/.test(o))break;s.push(o)}if(s.length===0||s.length===1&&s[0]==="")return"";r=s.join(J.sep)}return r}selectWatchRoot(e){let r=this.literalWatchPrefix(e);if(!r)return null;let n=(0,J.resolve)(r);try{return{root:(0,X.statSync)(n).isDirectory()?n:(0,J.resolve)(n,".."),recursive:!0}}catch{}for(let s=(0,J.resolve)(n,"..");(0,J.resolve)(s,"..")!==s;s=(0,J.resolve)(s,".."))try{if((0,X.statSync)(s).isDirectory())return{root:s,recursive:!1}}catch{}return null}resolveSchema(e){return typeof e.schema=="string"?this.config.schemas?.[e.schema]??null:e.schema}resolveWatchFiles(e){if(this.hasGlob(e))return this.scanGlob(this.normalizeGlobPattern(e));if((0,X.existsSync)(e))try{return(0,X.statSync)(e).isDirectory()?[...this.scanGlob(this.normalizeGlobPattern((0,J.join)(e,"**","*.jsonl"))),...this.scanGlob(this.normalizeGlobPattern((0,J.join)(e,"**",`*${Sa}`)))]:[e]}catch(r){return f.debug("WORKER","Failed to stat watch path",{path:e},r instanceof Error?r:void 0),[]}return[]}scanGlob(e){try{return Array.from(new Bun.Glob(e).scanSync({absolute:!0,onlyFiles:!0,dot:!0}))}catch(r){let n=r?.code;if(n==="ENOENT"||n==="ENOTDIR")return[];throw r}}normalizeGlobPattern(e){return e.replace(/\\/g,"/")}hasGlob(e){return/[*?[\]{}()]/.test(e)}async addTailer(e,r,n,s=!1,o){if(e=ce(e),!(this.tailers.has(e)||this.startingTailers.has(e))){this.startingTailers.add(e);try{await this.startTailer(e,r,n,s,o)}finally{this.startingTailers.delete(e)}}}async startTailer(e,r,n,s,o){let i=e.endsWith(Sa);if(i&&!zE()){this.warnedZstdUnsupported||(this.warnedZstdUnsupported=!0,f.warn("TRANSCRIPT","Skipping zstd transcripts: this runtime has no zlib.zstdDecompressSync (update Bun or Node)",{file:e}));return}let a=this.extractSessionIdFromPath(e),c=this.getFileContext(e),u=this.state.offsets[e],l=u??0,d=!1;if(u===void 0&&r.startAtEnd)try{let m=(0,X.statSync)(e);if(s&&m.mtimeMs>=this.startedAtMs-YE&&await this.startedAfterThisWatcher(e,i,m.size)||(l=i?await hP(e,m.size):m.size),this.stopped)return;this.state.offsets[e]=l,d=!0}catch(m){f.debug("WORKER","Failed to stat file for startAtEnd offset",{file:e},m instanceof Error?m:void 0),l=0}try{let m=(0,X.statSync)(e),h=ya(m),_=this.state.fileIdentities?.[e],S=u!==void 0&&_!==void 0&&!rS(e,h,m.size,u,this.state.checkpointFingerprints?.[e]);if(S&&(l=0,this.state.offsets[e]=0,delete this.state.partials?.[e],delete this.state.partialBytes?.[e],delete this.state.frameLines?.[e],this.forgetReplacedTranscript(e,c)),S||h!==_){(this.state.fileIdentities??={})[e]=h;let b=md(e,l,h);b!==null?(this.state.checkpointFingerprints??={})[e]=b:delete this.state.checkpointFingerprints?.[e],d=!0}}catch(m){f.debug("WORKER","Failed to stat transcript file for its identity",{file:e},m instanceof Error?m:void 0)}d&&(s?pn(this.statePath,this.state):o&&(o.stateChanged=!0));let p=l>0&&(!!n.sessionIdPath||!!r.subagentSource||!c.cwd),g=new gd(e,l,async m=>{try{p&&(p=!1,await this.primeFromFirstLine(e,l,r,n,a,c)),await this.handleLine(m,r,n,e,a,c)}finally{c.pendingTools&&((this.state.pendingTools??={})[e]=c.pendingTools),c.cwd&&c.cwd!==this.state.cwds?.[e]&&((this.state.cwds??={})[e]=c.cwd)}},(m,h,_,S,b,w)=>{S!==void 0&&((this.state.fileIdentities??={})[e]=S),b!==void 0?(this.state.checkpointFingerprints??={})[e]=b:this.state.checkpointFingerprints&&delete this.state.checkpointFingerprints[e],this.state.offsets[e]=m,h?(this.state.partials??={})[e]=h:this.state.partials&&delete this.state.partials[e],w?(this.state.partialBytes??={})[e]=w:this.state.partialBytes&&delete this.state.partialBytes[e],_>0?(this.state.frameLines??={})[e]=_:this.state.frameLines&&delete this.state.frameLines[e],pn(this.statePath,this.state)},this.state.partials?.[e]??"",this.state.frameLines?.[e]??0,this.state.fileIdentities?.[e],this.state.checkpointFingerprints?.[e],()=>this.forgetReplacedTranscript(e,c),this.state.partialBytes?.[e]);g.start(),this.tailers.set(e,g),f.info("TRANSCRIPT","Watching transcript file",{file:e,watch:r.name,schema:n.name})}async startedAfterThisWatcher(e,r,n){let s=await _P(e,r,n);return s!==null?s>=this.startedAtMs-YE:n<=pP}async primeFromFirstLine(e,r,n,s,o,i){try{let a=await tS(e,e.endsWith(Sa),r);if(a===null)return;await this.processor.primeSessionContext(JSON.parse(a),n,s,o,i)}catch(a){f.debug("TRANSCRIPT","Could not read the first line of a resumed transcript",{watch:n.name,file:(0,J.basename)(e)},a instanceof Error?a:void 0)}}async handleLine(e,r,n,s,o,i){try{let a=JSON.parse(e);await this.processor.processEntry(a,r,n,o??void 0,i)}catch(a){if(a instanceof bs||a instanceof ws||a instanceof mr)throw f.warn("TRANSCRIPT","Transcript event not accepted; it is retried from its own line",{watch:r.name,file:(0,J.basename)(s),error:a.message}),a;a instanceof Error?f.debug("TRANSCRIPT","Failed to parse transcript line",{watch:r.name,file:(0,J.basename)(s)},a):f.warn("TRANSCRIPT","Failed to parse transcript line (non-Error thrown)",{watch:r.name,file:(0,J.basename)(s),error:String(a)})}}extractSessionIdFromPath(e){let r=e.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i);return r?r[0]:null}};function Od(t,e){let r=t.indexOf(e);return r===-1?null:t[r+1]??null}function YS(t){(0,qS.existsSync)(ce(t))||(Ha(t),console.log(`Created sample config: ${ce(t)}`))}async function JS(t,e){switch(t){case"init":{let r=Od(e,"--config")??Sr;return Ha(r),console.log(`Created sample config: ${ce(r)}`),0}case"watch":{let r=Od(e,"--config")??Sr;YS(r);let n=V.loadFromFile(_e),{config:s,scoped:o,removed:i}=sf(ja(r),n);if(o>0&&console.log(`Scoped ${o} Codex transcript watch(es) to subagent sessions (MEMINDEX_CODEX_SUBAGENT_INGESTION=true); native hooks capture top-level sessions.`),i>0&&console.log(`Skipped ${i} Codex transcript watch(es): native hooks capture top-level Codex sessions, and subagent capture is opt-in (MEMINDEX_CODEX_SUBAGENT_INGESTION=true).`),s.watches.length===0)return console.log(`No active transcript watches in ${ce(r)}; nothing to watch.`),1;let a=ce(s.stateFile??Fs),c=new wa(s,a,"spool");await c.start(),console.log("Transcript watcher running. Press Ctrl+C to stop.");let u=()=>{c.stop(),process.exit(0)};return process.on("SIGINT",u),process.on("SIGTERM",u),await new Promise(()=>{})}case"validate":{let r=Od(e,"--config")??Sr;return YS(r),ja(r),console.log(`Config OK: ${ce(r)}`),0}case"import":return AM(e);default:return console.log("Usage: memindex transcript <init|watch|validate> [--config <path>]"),console.log(" memindex transcript import [--since <ISO time>] [--until <ISO time>] [--project-dir <folder>] [--dry-run]"),1}}async function AM(t){let{defaultTranscriptImportDeps:e,formatTranscriptImportResult:r,isoOf:n,parseTranscriptImportArgs:s,runTranscriptImport:o,TRANSCRIPT_IMPORT_USAGE:i}=await Promise.resolve().then(()=>(VS(),zS)),{settleHookSpoolNudges:a}=await Promise.resolve().then(()=>(Nr(),gm)),c=s(t);if(typeof c=="string")return console.error(c),console.error(i),1;console.log(`${c.dryRun?"Previewing":"Importing"} Claude Code transcripts from ${c.projectDir}${c.sinceMs!==null?` since ${n(c.sinceMs)}`:""}${c.untilMs!==null?` until ${n(c.untilMs)}`:""}`);let u=await o(c,e(l=>console.log(l)));return await a(),console.log(r(u,c.dryRun)),u.error?(console.error(`Stopped: ${u.error}. Run the same command again to carry on; nothing already sent is sent twice.`),1):0}var OM=process.argv[2],PM=process.argv.slice(3);JS(OM,PM).then(t=>{process.exit(t)}).catch(t=>{console.error(t),process.exit(1)});
|
|
47
47
|
/*! Bundled license information:
|
|
48
48
|
|
|
49
49
|
@posthog/core/dist/vendor/uuidv7.mjs:
|