memindex 1.3.0 → 1.4.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.
Files changed (43) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.codex-plugin/plugin.json +1 -1
  4. package/.qoder-plugin/plugin.json +1 -1
  5. package/README.md +84 -41
  6. package/dist/bug-report/index.js +55 -55
  7. package/dist/npx-cli/index.js +392 -323
  8. package/dist/opencode-plugin/index.js +34 -34
  9. package/dist/pi-extension/index.js +6 -6
  10. package/integrations/dsh/lib/index.js +24 -24
  11. package/integrations/dsh/package.json +1 -1
  12. package/integrations/hermes/memindex/client.py +11 -6
  13. package/integrations/omp/hooks/memindex.ts +5 -1
  14. package/integrations/openclaw/TESTING.md +1 -1
  15. package/integrations/openclaw/dist/index.js +9 -9
  16. package/integrations/openclaw/e2e-verify.sh +8 -1
  17. package/integrations/openclaw/openclaw.plugin.json +1 -1
  18. package/integrations/openclaw/src/index.test.ts +3 -1
  19. package/integrations/openclaw/src/index.ts +15 -5
  20. package/package.json +1 -1
  21. package/plugin/.claude-plugin/plugin.json +1 -1
  22. package/plugin/.codex-plugin/plugin.json +1 -1
  23. package/plugin/.qoder-plugin/plugin.json +1 -1
  24. package/plugin/hooks.json +1 -13
  25. package/plugin/package.json +1 -1
  26. package/plugin/scripts/context-generator.cjs +48 -47
  27. package/plugin/scripts/context-generator.cjs.map +3 -3
  28. package/plugin/scripts/mcp-server.cjs +77 -77
  29. package/plugin/scripts/mcp-server.cjs.map +2 -2
  30. package/plugin/scripts/statusline.cjs +1 -0
  31. package/plugin/scripts/transcript-watcher.cjs +34 -34
  32. package/plugin/scripts/transcript-watcher.cjs.map +3 -3
  33. package/plugin/scripts/worker-service.cjs +561 -550
  34. package/plugin/scripts/worker-service.cjs.map +3 -3
  35. package/plugin/skills/cloud-sync/SKILL.md +5 -2
  36. package/plugin/skills/mode-creator/SKILL.md +1 -1
  37. package/plugin/skills/timeline-report/SKILL.md +8 -5
  38. package/plugin/skills/weekly-digests/SKILL.md +5 -2
  39. package/plugin/sqlite/SessionStore.js +93 -93
  40. package/plugin/sqlite/SessionStore.js.map +2 -2
  41. package/plugin/ui/tv.html +55 -28
  42. package/plugin/ui/viewer-bundle.js +22 -15
  43. package/plugin/ui/viewer.html +72 -0
@@ -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 Ry=Object.create;var ma=Object.defineProperty;var Ay=Object.getOwnPropertyDescriptor;var Oy=Object.getOwnPropertyNames;var My=Object.getPrototypeOf,Py=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 Ts=(t,e)=>{for(var r in e)ma(t,r,{get:e[r],enumerable:!0})},xy=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Oy(e))!Py.call(t,s)&&s!==r&&ma(t,s,{get:()=>e[s],enumerable:!(n=Ay(e,s))||n.enumerable});return t};var _e=(t,e,r)=>(r=t!=null?Ry(My(t)):{},xy(e||!t||!t.__esModule?ma(r,"default",{value:t,enumerable:!0}):r,t));function ha(t){return t.startsWith(Is)||vs.some(e=>t.startsWith(e))}function Ny(t=process.env){for(let e of vs)for(let r of Object.keys(t)){if(!r.startsWith(e))continue;let n=Is+r.slice(e.length);t[n]===void 0&&(t[n]=t[r])}}function Rs(t){let e=null;for(let r of vs)for(let n of Object.keys(t)){if(!n.startsWith(r))continue;let s=Is+n.slice(r.length);(e??t)[s]===void 0&&(e??={...t},e[s]=t[n])}return e??t}var Is,ky,vs,rn=E(()=>{"use strict";Is="MEMINDEX_",ky="AGENT_MEM_",vs=[ky];Ny()});function Ee(t,e=process.platform,r=(0,hd.homedir)()){return typeof t!="string"||t.length===0?t:t==="~"?r:t.startsWith("~/")||e==="win32"&&t.startsWith("~\\")?(0,_d.join)(r,t.slice(2)):t}var hd,_d,Ht=E(()=>{"use strict";hd=require("os"),_d=require("path")});function Dy(t){return(Cy??process.stderr.write.bind(process.stderr))(t)}function ct(t){Dy(t)}var Cy,P0,As=E(()=>{"use strict";Cy=null;P0=Promise.resolve()});function _a(t){return t.replace(/^\uFEFF/,"")}function Xt(t){return JSON.parse(_a(t))}function ut(t){return Xt((0,k.readFileSync)(t,"utf-8"))}function Ly(t){(0,k.existsSync)(t)||(0,k.mkdirSync)(t,{recursive:!0})}function U(t,e,r={}){Uy(t,JSON.stringify(e,null,2)+`
5
- `,r)}function Uy(t,e,r={}){let n=t,s=new Set;try{for(;(0,k.lstatSync)(n).isSymbolicLink();){let d=(0,xe.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,xe.resolve)((0,xe.dirname)(n),m)}}}catch(d){if(d.code!=="ENOENT")throw d}Ly((0,xe.dirname)(n));let o=(0,xe.dirname)(n),i=(0,xe.basename)(n),a=(0,xe.join)(o,`.${i}.${process.pid}.${(0,Ed.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),!Fy){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,Ed,xe,Fy,ne=E(()=>{"use strict";k=require("fs"),Ed=require("crypto"),xe=require("path");As();Fy=process.platform==="win32"});function Sd(t){let e=t.env;return $y(e)&&Object.keys(e).some(ha)?"nested":"flat"}function _r(t){return Sd(t)==="nested"?t.env:t}function yd(t){return Sd(t)!=="nested"?t:Object.fromEntries(Object.entries(t).filter(([e])=>!ha(e)))}var $y,Os=E(()=>{"use strict";ne();rn();$y=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)});function nn(t=process.env,e=(0,wd.homedir)()){if(t.MEMINDEX_DATA_DIR)return Ee(t.MEMINDEX_DATA_DIR,process.platform,e);let r=(0,Ea.join)(e,".memindex"),n=(0,Ea.join)(r,"settings.json");try{if((0,bd.existsSync)(n)){let s=ut(n);if(s===null||typeof s!="object"||Array.isArray(s))return r;let o=Rs(_r(s));if(typeof o.MEMINDEX_DATA_DIR=="string"&&o.MEMINDEX_DATA_DIR)return Ee(o.MEMINDEX_DATA_DIR,process.platform,e)}}catch{}return r}var bd,wd,Ea,Sa=E(()=>{"use strict";bd=require("fs"),wd=require("os"),Ea=require("path");ne();rn();Ht();Os()});function By(){return typeof __CM_DIRNAME__<"u"?__CM_DIRNAME__:(0,j.dirname)((0,Td.fileURLToPath)(Ky.url))}function Wy(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 Wy(nn())}function vd(t,e=(0,ya.homedir)(),r=process.platform){return Ee(t,r,e)}var j,ya,Td,Ky,K0,W,jy,lt,Er,Hy,ge,Id,G0,Ms,Xy,G,C=E(()=>{"use strict";j=require("path"),ya=require("os"),Td=require("url");Ht();Sa();Ht();Ky={};K0=By();W=N(),jy=(0,j.join)((0,ya.homedir)(),".claude"),lt=process.env.CLAUDE_CONFIG_DIR||jy,Er=(0,j.join)(lt,"plugins","marketplaces","memindex"),Hy=(0,j.join)(W,"logs"),ge=(0,j.join)(W,"settings.json"),Id="memindex.db",G0=(0,j.join)(W,Id),Ms=(0,j.join)(W,"observer-sessions"),Xy=(0,j.basename)(Ms);G={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,Id),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:()=>Hy}});function Ad(t=process.env){let e=Number.parseInt(t.MEMINDEX_WEDGED_WORKER_UPTIME_S??"",10);return Number.isFinite(e)&&e>=Rd.min&&e<=Rd.max?e:Gy}function zy(t=process.platform){return t==="win32"?8e3:5e3}function sn(t=process.platform){return Z.SESSION_INIT_HOOK_CAP-zy(t)}function Od(t=process.platform){return t==="win32"?sn(t):Z.SESSION_INIT_REQUEST_MAX}function Ye(t){return process.platform==="win32"?Math.round(t*Z.WINDOWS_MULTIPLIER):t}var Z,Gy,Rd,D,ke=E(()=>{"use strict";Z={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},Gy=300,Rd={min:60,max:86400};D={SUCCESS:0}});var Kt,Md,wa,ba,Ta,f,O=E(()=>{"use strict";Kt=require("fs"),Md=require("path");C();As();ne();Os();wa=(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))(wa||{}),ba=null,Ta=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=G.logsDir();(0,Kt.existsSync)(n)||(0,Kt.mkdirSync)(n,{recursive:!0}),this.logFilePath=(0,Md.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=G.settings();if((0,Kt.existsSync)(e)){let r=_r(ut(e)),n=(r.MEMINDEX_LOG_LEVEL||r.AGENT_MEM_LOG_LEVEL||"INFO").toString().toUpperCase();this.level=wa[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}
4
+ "use strict";var Fy=Object.create;var ma=Object.defineProperty;var Ly=Object.getOwnPropertyDescriptor;var Uy=Object.getOwnPropertyNames;var $y=Object.getPrototypeOf,By=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 Is=(t,e)=>{for(var r in e)ma(t,r,{get:e[r],enumerable:!0})},jy=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Uy(e))!By.call(t,s)&&s!==r&&ma(t,s,{get:()=>e[s],enumerable:!(n=Ly(e,s))||n.enumerable});return t};var _e=(t,e,r)=>(r=t!=null?Fy($y(t)):{},jy(e||!t||!t.__esModule?ma(r,"default",{value:t,enumerable:!0}):r,t));function ha(t){return t.startsWith(vs)||Rs.some(e=>t.startsWith(e))}function Hy(t=process.env){for(let e of Rs)for(let r of Object.keys(t)){if(!r.startsWith(e))continue;let n=vs+r.slice(e.length);t[n]===void 0&&(t[n]=t[r])}}function As(t){let e=null;for(let r of Rs)for(let n of Object.keys(t)){if(!n.startsWith(r))continue;let s=vs+n.slice(r.length);(e??t)[s]===void 0&&(e??={...t},e[s]=t[n])}return e??t}var vs,Wy,Rs,sn=E(()=>{"use strict";vs="MEMINDEX_",Wy="AGENT_MEM_",Rs=[Wy];Hy()});function Ee(t,e=process.platform,r=(0,yd.homedir)()){return typeof t!="string"||t.length===0?t:t==="~"?r:t.startsWith("~/")||e==="win32"&&t.startsWith("~\\")?(0,bd.join)(r,t.slice(2)):t}var yd,bd,Xt=E(()=>{"use strict";yd=require("os"),bd=require("path")});function Ky(t){return(Xy??process.stderr.write.bind(process.stderr))(t)}function ut(t){Ky(t)}var Xy,Yx,Os=E(()=>{"use strict";Xy=null;Yx=Promise.resolve()});function _a(t){return t.replace(/^\uFEFF/,"")}function Kt(t){return JSON.parse(_a(t))}function lt(t){return Kt((0,k.readFileSync)(t,"utf-8"))}function zy(t){(0,k.existsSync)(t)||(0,k.mkdirSync)(t,{recursive:!0})}function U(t,e,r={}){Vy(t,JSON.stringify(e,null,2)+`
5
+ `,r)}function Vy(t,e,r={}){let n=t,s=new Set;try{for(;(0,k.lstatSync)(n).isSymbolicLink();){let d=(0,ke.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));ut(`memindex: realpathSync failed for ${n}, resolving symlink manually: ${g.message}
6
+ `);let m=(0,k.readlinkSync)(n);n=(0,ke.resolve)((0,ke.dirname)(n),m)}}}catch(d){if(d.code!=="ENOENT")throw d}zy((0,ke.dirname)(n));let o=(0,ke.dirname)(n),i=(0,ke.basename)(n),a=(0,ke.join)(o,`.${i}.${process.pid}.${(0,wd.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),!Gy){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));ut(`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,wd,ke,Gy,re=E(()=>{"use strict";k=require("fs"),wd=require("crypto"),ke=require("path");Os();Gy=process.platform==="win32"});function Td(t){let e=t.env;return Yy(e)&&Object.keys(e).some(ha)?"nested":"flat"}function Er(t){return Td(t)==="nested"?t.env:t}function Id(t){return Td(t)!=="nested"?t:Object.fromEntries(Object.entries(t).filter(([e])=>!ha(e)))}var Yy,Ms=E(()=>{"use strict";re();sn();Yy=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)});function on(t=process.env,e=(0,Rd.homedir)()){if(t.MEMINDEX_DATA_DIR)return Ee(t.MEMINDEX_DATA_DIR,process.platform,e);let r=(0,Ea.join)(e,".memindex"),n=(0,Ea.join)(r,"settings.json");try{if((0,vd.existsSync)(n)){let s=lt(n);if(s===null||typeof s!="object"||Array.isArray(s))return r;let o=As(Er(s));if(typeof o.MEMINDEX_DATA_DIR=="string"&&o.MEMINDEX_DATA_DIR)return Ee(o.MEMINDEX_DATA_DIR,process.platform,e)}}catch{}return r}var vd,Rd,Ea,Sa=E(()=>{"use strict";vd=require("fs"),Rd=require("os"),Ea=require("path");re();sn();Xt();Ms()});function qy(){return typeof __CM_DIRNAME__<"u"?__CM_DIRNAME__:(0,W.dirname)((0,Ad.fileURLToPath)(tb.url))}function Jy(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 C(){return Jy(on())}function Md(t,e=(0,ya.homedir)(),r=process.platform){return Ee(t,r,e)}var W,ya,Ad,tb,lk,j,Zy,Ne,Sr,Qy,ae,Od,dk,Ps,eb,G,N=E(()=>{"use strict";W=require("path"),ya=require("os"),Ad=require("url");Xt();Sa();Xt();tb={};lk=qy();j=C(),Zy=(0,W.join)((0,ya.homedir)(),".claude"),Ne=process.env.CLAUDE_CONFIG_DIR||Zy,Sr=(0,W.join)(Ne,"plugins","marketplaces","memindex"),Qy=(0,W.join)(j,"logs"),ae=(0,W.join)(j,"settings.json"),Od="memindex.db",dk=(0,W.join)(j,Od),Ps=(0,W.join)(j,"observer-sessions"),eb=(0,W.basename)(Ps);G={dataDir:()=>j,workerPid:()=>(0,W.join)(j,"worker.pid"),serverPid:()=>(0,W.join)(j,".server-beta.pid"),serverPort:()=>(0,W.join)(j,".server-beta.port"),serverRuntime:()=>(0,W.join)(j,".server-beta.runtime.json"),settings:()=>(0,W.join)(j,"settings.json"),database:()=>(0,W.join)(j,Od),chroma:()=>(0,W.join)(j,"chroma"),combinedCerts:()=>(0,W.join)(j,"combined_certs.pem"),transcriptsConfig:()=>(0,W.join)(j,"transcript-watch.json"),transcriptsState:()=>(0,W.join)(j,"transcript-watch-state.json"),corpora:()=>(0,W.join)(j,"corpora"),supervisorRegistry:()=>(0,W.join)(j,"supervisor.json"),envFile:()=>(0,W.join)(j,".env"),logsDir:()=>Qy}});function xd(t=process.env){let e=Number.parseInt(t.MEMINDEX_WEDGED_WORKER_UPTIME_S??"",10);return Number.isFinite(e)&&e>=Pd.min&&e<=Pd.max?e:rb}function nb(t=process.platform){return t==="win32"?8e3:5e3}function an(t=process.platform){return ne.SESSION_INIT_HOOK_CAP-nb(t)}function kd(t=process.platform){return t==="win32"?an(t):ne.SESSION_INIT_REQUEST_MAX}function wt(t){return process.platform==="win32"?Math.round(t*ne.WINDOWS_MULTIPLIER):t}var ne,rb,Pd,D,Ye=E(()=>{"use strict";ne={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,WINDOWS_MULTIPLIER:1.5},rb=300,Pd={min:60,max:86400};D={SUCCESS:0}});var Gt,Nd,wa,ba,Ta,f,O=E(()=>{"use strict";Gt=require("fs"),Nd=require("path");N();Os();re();Ms();wa=(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))(wa||{}),ba=null,Ta=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=G.logsDir();(0,Gt.existsSync)(n)||(0,Gt.mkdirSync)(n,{recursive:!0}),this.logFilePath=(0,Nd.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=G.settings();if((0,Gt.existsSync)(e)){let r=Er(lt(e)),n=(r.MEMINDEX_LOG_LEVEL||r.AGENT_MEM_LOG_LEVEL||"INFO").toString().toUpperCase();this.level=wa[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
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=wa[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
9
  ${o.message}
10
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,Kt.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}
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,Gt.appendFileSync)(this.logFilePath,p+`
12
+ `,"utf8")}catch(g){let m=g instanceof Error?g:new Error(String(g));ut(`[LOGGER] Failed to write to log file: ${m.message}
13
13
  ${m.stack??""}
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){ba=e}error(e,r,n,s){this.log(3,e,r,n,s),this.routeErrorToSink(r,n,s)}routeErrorToSink(e,r,n){try{if(!ba||!(n instanceof Error))return;ba(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 Ta});function Pd(t){try{return new URL(t).hostname.toLowerCase()==="openrouter.ai"}catch{return!1}}var xd=E(()=>{"use strict";O()});function Gt(t){let e=(0,Ne.resolve)(t),r=[],n=e;for(;;)try{return(0,Ne.join)(Nd.realpathSync.native(n),...r.reverse())}catch{let s=(0,Ne.dirname)(n);if(s===n)return e;r.push((0,Ne.basename)(n)),n=s}}function Jy(t,e){return Gt(t)===Gt(e)}function Qy(t,e){let r=Gt(e);return t===r||t.startsWith(r.endsWith(Ne.sep)?r:r+Ne.sep)}function Zy(t,e=(0,zt.homedir)()){let r=Gt(t),n=Gt(e);return(process.platform==="win32"?[(0,zt.tmpdir)()]:[(0,zt.tmpdir)(),...qy]).some(o=>Gt(o)!==n&&Qy(r,o))}function on(t=process.env,e=(0,zt.homedir)()){return t.MEMINDEX_TEST_FORBIDDEN_DATA_DIR?!0:Zy(nn(t,e),e)}function Ia(){return 38700+(process.getuid?.()??77)%100}function va(t){let e=(0,kd.createHash)("sha256").update(Gt(t)).digest();return Vy+e.readUInt32BE(0)%Yy}function Dd(t=process.env,e=(0,zt.homedir)()){return on(t,e)?va(nn(t,e)):Ia()}function Fd(t,e){return typeof t!="string"||t.length===0?"unknown":Jy(t,e)?"same":"foreign"}var kd,Nd,zt,Ne,Vy,Yy,qy,Cd,Ra=E(()=>{"use strict";kd=require("crypto"),Nd=require("fs"),zt=require("os"),Ne=require("path");Sa();Vy=4e4,Yy=9e3,qy=["/tmp","/private/tmp","/var/folders","/private/var/folders"],Cd="60"});function tb(t){return typeof t=="boolean"?String(t):t}function rb(t){let e=t.MEMINDEX_OPENROUTER_MODEL;if(typeof e!="string"||!eb.has(e.trim()))return!1;let r=typeof t.MEMINDEX_OPENROUTER_BASE_URL=="string"?t.MEMINDEX_OPENROUTER_BASE_URL.trim():"";return r===""||Pd(r)}function Bd(t,e){return(0,wt.join)((0,wt.dirname)(t),`.${(0,wt.basename)(t)}.${e.markerTag}`)}function Aa(t,e){try{(0,Vt.writeFileSync)(Bd(t,e),new Date().toISOString(),{encoding:"utf-8",mode:384})}catch{}}var Vt,wt,an,eb,Ld,Ud,$d,z,qe=E(()=>{"use strict";Vt=require("fs"),wt=require("path"),an=require("os");ke();ne();xd();rn();Os();Ra();eb=new Set(["xiaomi/mimo-v2-flash:free"]);Ld=18e4,Ud=[{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"}];$d=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(Dd()),MEMINDEX_WORKER_HOST:"127.0.0.1",MEMINDEX_ALLOWED_ORIGINS:"",MEMINDEX_PUBLIC_URL:"",MEMINDEX_API_TIMEOUT_MS:String(Ye(Z.API_REQUEST)),MEMINDEX_SESSION_INIT_TIMEOUT_MS:String(sn()),MEMINDEX_IDLE_EXIT_SEC:on()?Cd:"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,wt.join)((0,an.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_BRANCH_MEMORY_ENABLED:"true",MEMINDEX_SEND_BRANCH_TO_HOSTING:"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,wt.join)((0,an.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,an.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(Ld),MEMINDEX_LLM_STREAM_IDLE_TIMEOUT_MS:"90000",MEMINDEX_FIELD_OPTIMIZE_TIMEOUT_MS:String(Ld),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_JIRA_BASE_URL:"",MEMINDEX_JIRA_EMAIL:"",MEMINDEX_JIRA_API_TOKEN:"",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,Vt.existsSync)(e)){let p=this.getAllDefaults();if(!n.readOnly)try{U(e,p,{mode:384});for(let g of Ud)Aa(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,Vt.readFileSync)(e,"utf-8"),o=Xt(s),i=_r(o),a=i!==o,c=Rs(i),u=yd(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(rb(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 Ud)if(!(0,Vt.existsSync)(Bd(e,p))){if(c[p.key]!==p.legacy){n.readOnly||Aa(e,p);continue}if(c={...c,[p.key]:this.DEFAULTS[p.key]},!n.readOnly)try{U(e,l?{...u,env:c}:c,{mode:384}),Aa(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}`;$d.has(m)||($d.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]=tb(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 Qd(t=N()){let e=(0,$.openSync)((0,Ns.join)(t,Zd),$.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(!db.test(n))throw new Error("Invalid worker secret");return n}finally{(0,$.closeSync)(e)}}function ef(t=N()){(0,$.mkdirSync)(t,{recursive:!0,mode:448});let e=(0,Ns.join)(t,Zd);try{return Qd(t)}catch(s){if(s.code!=="ENOENT")throw s}let r=(0,Ns.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 Qd(t)}function dn(t,e=N()){if(!["POST","PUT","PATCH","DELETE"].includes((t.method??"GET").toUpperCase()))return t;let r=new Headers(t.headers);return r.set(lb,ef(e)),{...t,headers:r,redirect:"error"}}var xa,$,Ns,lb,Zd,db,ka=E(()=>{"use strict";xa=require("node:crypto"),$=require("node:fs"),Ns=require("node:path");C();lb="X-Memindex-Secret",Zd="worker-secret",db=/^[a-f0-9]{64}$/});async function*pb(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 gb(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*nf(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 Na(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]===fb)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 pb(t)){let h=0;for(let _=0;_<m.length;_++){let S=m[_];if(i&&(i=!1,S===rf)){h=_+1;continue}if(S!==tf&&S!==rf)continue;s.push(m.subarray(h,_));let b=gb(s,o+(_-h));s=[],o=0;let w=g(b);w&&(e.terminalEventNames?.includes(w.event)&&(d=!0),yield w),i=S===tf,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 Ca(e.terminalEventNames)}var Na,Ca,tf,rf,fb,sf=E(()=>{"use strict";Na=class extends Error{constructor(r){super(`SSE event exceeded ${r} bytes`);this.maxEventBytes=r;this.name="SseEventTooLargeError"}maxEventBytes},Ca=class extends Error{constructor(r){super(`SSE stream ended before a terminal event (${r.join(", ")})`);this.terminalEventNames=r;this.name="StreamEndedEarlyError"}terminalEventNames},tf=13,rf=10,fb=58});function K(){return Cs!==null||(Cs=z.loadFromFile(ge)),Cs}var Cs,Qe=E(()=>{"use strict";qe();C();Cs=null});function Ds(t){return(t.MEMINDEX_WORKER_AUTOSTART??"true").trim().toLowerCase()==="false"}var of=E(()=>{"use strict"});var af=E(()=>{"use strict"});function Da(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}var Fa=E(()=>{"use strict"});function Ua(t,e,r){return(0,La.spawn)(t,e??[],{...r,windowsHide:!0})}var La,mb,hb,Ox,$a=E(()=>{"use strict";La=require("node:child_process");mb=new Set([".cmd",".bat"]),hb=new Set([".exe",".com"]),Ox=new Set([...hb,...mb])});function dt(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(yb.has(r)){e[r]=n;continue}Eb.has(r)||_b.some(s=>r.startsWith(s))||(e[r]=n)}return e}var _b,Eb,Sb,yb,fn=E(()=>{"use strict";_b=["CLAUDECODE_","CLAUDE_CODE_"],Eb=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),Sb=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"]),yb=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",...Sb])});function lf(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 wb(t){Ba+=1;let e=(0,Wa.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:{...dt(process.env),LC_ALL:"C",LANG:"C"}});return lf("powershell-cim",t,e)}function Tb(t,e=!1){if(!e){let n=cf.get(t);if(n&&(t===process.pid||Date.now()-n.capturedAtMs<bb))return n.token}let r=null;try{r=wb(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)&&cf.set(t,{token:r,capturedAtMs:Date.now()}),r}function df(t,e){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux"){Ba+=1;try{let r=(0,uf.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 Tb(t,e);Ba+=1;try{let r=(0,Wa.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...dt(process.env),LC_ALL:"C",LANG:"C"}});return lf("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 Ze(t){return df(t,!1)}function De(t,e){if(e===null)return!0;let r=df(t,!0);return r===null?!0:r===e}var Wa,uf,bb,cf,Ba,Fs=E(()=>{"use strict";Wa=require("child_process"),uf=require("fs");O();fn();bb=5e3,cf=new Map,Ba=0});async function be(t,e={}){let r=e.signalMode==="immediate",n=e.expectedStartToken!==void 0?e.expectedStartToken:Ze(t),s=()=>De(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 ja("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===Ib||vb.test(`${a} ${c}`)){f.debug("PROCESS","taskkill reported the process was already gone",{pid:t});return}throw new Ls(t,`taskkill failed for PID ${t} (exit ${String(i)}): ${a.trim()||c}`,{cause:o})}return}try{let o=r?"SIGKILL":"SIGTERM",i=await Us(t);for(let u of i){if(!De(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 Us(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(!De(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 Ls(t,`tree-kill failed for PID ${t}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}}async function Rb(){return process.platform==="win32"?Mb():process.platform==="linux"?Ab():Ob()}function Ab(){let t=[],e;try{e=(0,$s.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,$s.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 Ob(){let t;try{t=(await ja("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 Mb(){let t;try{t=(await ja("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 Us(t){let e=await Rb(),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 ff,$s,pf,ja,Ib,vb,Ls,yr=E(()=>{"use strict";ff=require("child_process"),$s=require("fs"),pf=require("util");O();Fs();ja=(0,pf.promisify)(ff.execFile),Ib=128,vb=/not found|no running instance|no tasks/i,Ls=class extends Error{pid;constructor(e,r,n){super(r,n),this.name="ProcessTreeKillError",this.pid=e}}});function q(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 Bs(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!q(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function mf(t){if(!t||!q(t.pid))return!1;if(!t.startToken)return!0;let e=Ze(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 Ws(t,e=Db){if(!mf(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=>gf.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 ft(t=G.workerPid()){if(!(0,qt.existsSync)(t))return null;let e;try{e=JSON.parse((0,qt.readFileSync)(t,"utf-8"))}catch{return null}return e!==null&&Ws(e)?e:null}function js(){return Ha||(Ha=new Ka),Ha}function Xa(){let t=Fb.shift();t&&t.notify()}var qt,gf,xb,kb,Nb,Cb,Db,Ka,Ha,zx,Fb,pt=E(()=>{"use strict";$a();qt=require("fs"),gf=_e(require("path"),1);O();ne();fn();C();Fs();yr();xb=5e3,kb=1e3,Nb=G.supervisorRegistry(),Cb=null;Db={platform:process.platform,readCommandLine:t=>(0,qt.readFileSync)(`/proc/${t}/cmdline`,"utf-8")};Ka=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(e=Nb){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,!(0,qt.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,qt.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||!q(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"&&Xa())}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)q(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)Xa();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=>q(a.pid)),o=new Map(s.map(a=>[a.pid,Ze(a.pid)]));for(let a of s)try{process.platform==="win32"?await be(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 Bs(s,xb);let i=s.filter(a=>q(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(!De(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 be(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()+kb;for(;Date.now()<a&&i.filter(u=>q(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"&&Xa();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{Cb?.({errorCategory:r.code??"unknown"})}catch{}}},Ha=null;zx=180*1e3,Fb=[]});async function _f(t){let e=t.currentPid??process.pid,r=t.pidFilePath??Lb,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(!q(c.pid)){t.registry.unregister(c.id);continue}i.set(c.id,Ze(c.pid)),o.set(c.id,await Us(c.pid));try{await hf(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 Bs(s,5e3);let a=s.filter(c=>q(c.pid)||(o.get(c.id)??[]).some(u=>q(u.pid)));for(let c of a){let u=De(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 hf(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{Ub(o.get(c.id)??[],c.pid)}}await Bs(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);Ef(r,e),t.registry.pruneDeadEntries()}function Ef(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||!q(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 Ub(t,e){for(let{pid:r,startToken:n}of t)if(!(r===e||!q(r))){if(!De(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 hf(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 be(r,{signalMode:"immediate"});return}try{process.kill(r,e)}catch(s){if((s instanceof Error?s.code:void 0)!=="ESRCH")throw s}return}await be(r)}var br,Lb,Ga=E(()=>{"use strict";br=require("fs");O();pt();C();yr();Lb=G.workerPid()});function $b(){let e=js().pruneDeadEntries();e>0&&f.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function yf(){wr===null&&(wr=setInterval($b,Sf),wr.unref(),f.debug("SYSTEM","Health checker started",{intervalMs:Sf}))}function bf(){wr!==null&&(clearInterval(wr),wr=null,f.debug("SYSTEM","Health checker stopped"))}var Sf,wr,wf=E(()=>{"use strict";O();pt();Sf=3e4,wr=null});function jb(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 Hb(){let t=await Bb("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return jb(t.stdout)}function Xb(t,e){let r=t.filter(i=>Wb.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 vf(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??Hb,s=t.isAlive??q,o=t.killTree??(g=>be(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}=Xb(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 Tf,If,Bb,Wb,Rf=E(()=>{"use strict";Tf=require("child_process"),If=require("util");O();yr();pt();Bb=(0,If.promisify)(Tf.execFile),Wb=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/});function Af(t={}){let e=t.pidFilePath??Kb;if(!(0,Jt.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,Jt.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,Jt.rmSync)(e,{force:!0}),"invalid"}return Ws(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,Jt.rmSync)(e,{force:!0})),"stale")}var Jt,Kb,za,pk,pn=E(()=>{"use strict";Jt=require("fs");O();pt();Ga();wf();Rf();C();pt();Kb=G.workerPid(),za=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(),Af({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,vf({registry:this.registry}).catch(r=>{f.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),yf()}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}bf(),this.stopPromise=_f({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}},pk=new za(js())});function Of(t,e){if(!(0,Hs.existsSync)(t))return e;try{return Xt((0,Hs.readFileSync)(t,"utf-8"))}catch(r){throw new Error(`Corrupt JSON file, refusing to overwrite: ${t}: ${r instanceof Error?r.message:String(r)}`)}}var Hs,Mf=E(()=>{"use strict";Hs=require("fs");ne()});function Gb(t){let e=t.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function zb(t,e){if(Gb(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 Ks(t,e){return zb(t,e).enabled}function kf(t){let e=t.MEMINDEX_TELEMETRY_ERRORS?.toLowerCase();return!(e==="0"||e==="false"||e==="off")}function Vb(){return(0,Va.join)(N(),xf)}function gn(){let t;try{t=Of(Vb(),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 Yb(t){let e=N();(0,Xs.mkdirSync)(e,{recursive:!0}),(0,Xs.writeFileSync)((0,Va.join)(e,xf),JSON.stringify(t,null,2)+`
19
- `)}function Gs(){let t=gn();if(t?.installId)return t.installId;let e=(0,Pf.randomUUID)();return Yb({installId:e,decidedAt:""}),e}var Va,Xs,Pf,xf,Ya=E(()=>{"use strict";Va=require("path"),Xs=require("fs"),Pf=require("crypto");C();Mf();O();xf="telemetry.json"});function Ff(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>Cf?e.slice(0,Cf):e}catch{return""}}function qa(t){if(typeof t!="string"||t.length===0)return t??"";let e="";try{e=Df.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 Ja(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 qb(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${we}`):e.replace(/[?#].*$/,"").replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/@\s]+@/,`$1${we}@`))}function Jb(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\?[^\s"'()]*/g,"")}function Qb(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)}${we}`})}function Zb(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,we),e=e.replace(/\b[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\.[A-Za-z0-9_-]{10,512}\b/g,we),e=e.replace(/\b(?:sk|pk|rk|ak|phc|phx|ph|ghp|gho|ghs|xox[bpasr])[-_][A-Za-z0-9_-]{8,512}\b/gi,we),e=e.replace(/\bBearer\s+[A-Za-z0-9._-]{8,512}\b/gi,we),e=e.replace(/\b(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA|ANVA|AIPA)[0-9A-Z]{16}\b/g,we),e=e.replace(/\b[0-9a-fA-F]{24,4096}\b/g,we),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,we),e=e.replace(/\b(?=[A-Za-z0-9+/_-]{0,4096}\d)[A-Za-z0-9+/_-]{32,4096}={0,2}\b/g,we),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,we),e}function ew(t){return typeof t!="string"||t.length===0?t??"":t.replace(/[ \t\f\v]+/g," ").replace(/ *\n */g,`
20
- `).trim()}function Qa(t){let e=Ff(t);return e.length===0?"":(e=qa(e),e=qb(e),e=Ja(e),e=Jb(e),e=Qb(e),e=Zb(e),e)}function Lf(t){try{let e=ew(Qa(Ff(t)));return e.length>Nf?e.slice(0,Nf):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 Uf(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 Df,Nf,Cf,we,Za=E(()=>{"use strict";Df=_e(require("os"),1);O();Nf=500,Cf=8192,we="[REDACTED]"});function rw(t,e){if(!(!t||typeof t!="object"))for(let r of Object.keys(t)){if(!tw.has(r))continue;let n=t[r];if(typeof n=="string"){let s=n.length>$f?n.slice(0,$f):n;e[r]=Qa(s)}else(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(e[r]=n)}}function zs(t){let e={};try{rw(t,e)}catch{}return e}var tw,$f,ec=E(()=>{"use strict";Za();tw=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"]),$f=200});function Vs(){return process.env.MEMINDEX_TELEMETRY_KEY??""}function Ys(){return process.env.MEMINDEX_TELEMETRY_HOST||sw}function qs(t){let e={};for(let r of ow)t[r]!==void 0&&(e[r]=t[r]);return e}function iw(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||tc.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 Js(){return{version:nw,os:process.platform,os_version:tc.default.release(),is_wsl:iw(),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 tc,nw,sw,ow,rc=E(()=>{"use strict";tc=_e(require("os"),1);O();nw="1.3.0",sw="https://us.i.posthog.com";ow=["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 Bf(t,e,r){try{if(!Ks(process.env,gn()))return;let n=zs({...Js(),...e??{}});if(r?.person?n.$set=qs(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=Vs(),o=new AbortController,i=setTimeout(()=>o.abort(),aw);try{await cw(s,t,n,o.signal)}finally{clearTimeout(i)}}catch{}}async function cw(t,e,r,n){await fetch(`${Ys()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:t,event:e,distinct_id:Gs(),properties:r}),signal:n})}var aw,Wf=E(()=>{"use strict";Ya();ec();rc();aw=2e3});var jf=E(()=>{"use strict";O()});var Hf=E(()=>{"use strict";O();jf()});function mn(t){return t.error?.name==="ETIMEDOUT"}function hn(t,e,r=Xf){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,Qs.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 Tr(t,e,r=Xf){let n=(0,Qs.spawnSync)("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:Math.min(r,uw),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 Qs,Xf,uw,Zs=E(()=>{"use strict";Qs=require("child_process");O();Xf=5e3,uw=5e3});function Kf(t){let e=Tt.default.join(t,".git"),r;try{r=(0,eo.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)}),_n}if(!r.isFile())return _n;let n;try{n=(0,eo.readFileSync)(e,"utf-8").trim()}catch(c){return f.warn("GIT","Failed to read .git file",{error:c instanceof Error?c.message:String(c)}),_n}let s=n.match(/^gitdir:\s*(.+)$/);if(!s)return _n;let o=Tt.default.resolve(Tt.default.dirname(e),s[1]),i=o.match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(i){let c=i[1];return{isWorktree:!0,isSubmodule:!1,worktreeName:Tt.default.basename(t),parentRepoPath:c,parentProjectName:Tt.default.basename(c)}}let a=o.match(/^(.+)[/\\]\.git[/\\]modules[/\\](.+)$/);if(a){let c=a[1];return{isWorktree:!1,isSubmodule:!0,worktreeName:Tt.default.basename(t),parentRepoPath:c,parentProjectName:Tt.default.basename(c)}}return _n}var eo,Tt,_n,Gf=E(()=>{"use strict";eo=require("fs"),Tt=_e(require("path"),1);O();_n={isWorktree:!1,isSubmodule:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null}});function zf(t){let e=Ee(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,nc.basename)(r);for(let s of e){let o=s.trim();if(o)try{let i=zf(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 to(t,e){if(!e||!e.trim())return!1;let r=t.replace(/\\/g,"/"),n=(0,nc.basename)(r),s=e.split(",").map(o=>o.trim()).filter(Boolean);for(let o of s)try{let i=zf(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 nc,En=E(()=>{"use strict";nc=require("path");Ht();O()});function Yf(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 lw(t){try{return(0,Vf.realpathSync)(t)}catch{return t}}function oc(t,e){if(e.length===0)return null;let r=[...new Set([t,lw(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 Vf,qf=E(()=>{"use strict";Vf=require("fs");En();O()});function Zf(t){let e=process.env[dw]?.trim();return e||(!t||t.trim()===""?null:t)}function ep(t){return tp(t,Tr(t,["rev-parse","--show-toplevel"]))}async function gw(t){let e=Date.now(),r=Ir.get(t);if(r&&e-r.at<fw)return(await r.answer).root;Ir.size>=pw&&Ir.clear();let n=hn(t,["rev-parse","--show-toplevel"]).then(a=>({root:tp(t,a),kept:!mn(a)})),s={at:e,answer:n};Ir.set(t,s);let{root:o,kept:i}=await n;return!i&&Ir.get(t)===s&&Ir.delete(t),o}function tp(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 rp(t){try{return(0,Rr.realpathSync)(t)}catch{return t}}function _w(t,e){let r=ce.default.relative(e,t);return r===""||!r.startsWith("..")&&!ce.default.isAbsolute(r)}function Ew(){return[(0,so.homedir)(),(0,so.tmpdir)(),lt].flatMap(t=>{let e=ce.default.resolve(t);return[e,rp(e)]})}function np(t){let e=Ew(),r=ce.default.resolve(t);if([ce.default.resolve(lt),rp(ce.default.resolve(lt))].some(s=>_w(r,s)))return null;for(let s=0;s<hw;s++){if(e.includes(r))return null;let o=ce.default.dirname(r);if(o===r)return null;if(mw.some(i=>(0,Rr.existsSync)(ce.default.join(r,i))))return r;r=o}return null}function ic(t,e){let r=ce.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}),ac}return r}function Jf(){try{return(0,Rr.statSync)(ge).mtimeMs}catch{return-1}}function sp(){let t=Jf();if(t===-1)return z.getAllDefaults();if(ro&&ro.mtimeMs===t)return ro.settings;let e=z.loadFromFile(ge);return ro={mtimeMs:Jf(),settings:e},e}function op(){let t=process.env[Sw]??sp().MEMINDEX_PROJECT_NAME_SOURCE;return String(t??"path").trim().toLowerCase()==="git-remote"}function ip(){let t=process.env[yw]??sp().MEMINDEX_PROJECT_ENVIRONMENTS;return(!no||no.raw!==t)&&(no={raw:t,environments:Yf(t)}),no.environments}function bw(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 ap(t,e){return e.status===0&&e.stdout?bw(e.stdout):(f.debug("PROJECT_NAME","No usable origin remote, keeping the path-based name",{repoRoot:t},e.error),null)}function cp(t){return op()?(vr.has(t)||vr.set(t,ap(t,Tr(t,["remote","get-url","origin"]))),vr.get(t)??null):null}async function ww(t){if(!op())return null;if(!vr.has(t)){let e=await hn(t,["remote","get-url","origin"]);if(mn(e))return null;vr.set(t,ap(t,e))}return vr.get(t)??null}function Tw(t,e=process.platform){if(!t||t.trim()==="")return f.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),ac;let r=Ee(t,e),n=oc(r,ip());if(n)return n;let s=ep(r),o=s?cp(s):null;if(o)return o;let i=s??np(r)??r;return ic(t,i)}function up(t,e){return e===t?t:`${t}/${e}`}function Iw(t,e){if(!t.isSubmodule||!t.parentRepoPath)return null;let r=ce.default.relative(t.parentRepoPath,e);return!r||r.startsWith("..")||ce.default.isAbsolute(r)?null:r.split(ce.default.sep).join("/")}function oo(t,e=process.platform){if(!t||t.trim()==="")return lp(t,e);let r=Ee(t,e),n=ep(r),s=n?cp(n):null;return dp(t,r,n,s)}async function Sn(t,e=process.platform){if(!t||t.trim()==="")return lp(t,e);let r=Ee(t,e),n=await gw(r),s=n?await ww(n):null;return dp(t,r,n,s)}function lp(t,e){let r=Tw(t,e);return{primary:r,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[r],keySource:"path"}}function dp(t,e,r,n){let s=vw(t,e,r),o=n?Qf(s,n,"git-remote"):s,i=oc(e,ip());return i?Qf(o,i,"environment"):o}function Qf(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 vw(t,e,r){let n=r?null:np(e),s=ic(t,r??n??e),o=r??e,i=Kf(o);if((i.isWorktree||i.isSubmodule)&&i.parentProjectName){let a=i.parentProjectName,c,u;return i.isSubmodule?(c=`${a}/${Iw(i,o)??s}`,u=s!==a?[s]:[]):(c=up(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&&ce.default.resolve(n)!==ce.default.resolve(e)){let a=ic(t,e);if(a!==s&&a!==ac)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 ce,Rr,so,dw,ac,fw,pw,Ir,mw,hw,Sw,ro,yw,no,vr,Qt=E(()=>{"use strict";ce=_e(require("path"),1),Rr=require("fs"),so=require("os");Ht();C();qe();O();Zs();Gf();qf();dw="CLAUDE_PROJECT_DIR",ac="unknown-project";fw=3e4,pw=500,Ir=new Map;mw=[".memindex-project",".memindex.json"],hw=64;Sw="MEMINDEX_PROJECT_NAME_SOURCE",ro=null;yw="MEMINDEX_PROJECT_ENVIRONMENTS",no=null;vr=new Map});function Aw(t){return t===void 0?fp:Math.max(1,Math.min(fp,t))}function Mw(t){try{return(0,Se.realpathSync)(t)}catch{return null}}function cc(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function Pw(t,e){let r=e==="win32"?"where.exe":"which",n=[t],s;try{s=(0,io.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 ao(t={}){let e=Object.keys(t).length===0;if(e&&uc!==void 0)return uc;let r=xw(t);return e&&r!==null&&(uc=r),r}function pp(t,e){let r=t?.trim();return r?e==="win32"?[me.default.join(r,"bin","bun.exe"),me.default.join(r,"bin","bun"),me.default.join(r,"bun.exe")]:[me.default.join(r,"bin","bun"),me.default.join(r,"bun")]:[]}function xw(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(cc(r))return r;let n=t.env??process.env,s=t.homeDirectory??(0,lc.homedir)(),o=t.pathExists??Se.existsSync,i=t.lookupInPath??Pw,a=t.realpath??Mw,c=e==="win32"?[n.BUN,n.BUN_PATH,...pp(n.BUN_INSTALL,e),me.default.join(s,".bun","bin","bun.exe"),me.default.join(s,".bun","bin","bun"),n.USERPROFILE?me.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?me.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?me.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0,n.npm_config_prefix?me.default.join(n.npm_config_prefix,"bun.exe"):void 0]:[n.BUN,n.BUN_PATH,...pp(n.BUN_INSTALL,e),me.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?me.default.join(n.npm_config_prefix,"bin","bun"):void 0];for(let d of c){let p=d?.trim();if(p&&(cc(p)&&o(p)||p.toLowerCase()==="bun"))return p}let u=i("bun",e)?.trim();if(!u||!cc(u))return null;let l=a(u)??u;return o(l)?l:null}function dc(){let t=G.dataDir();return(0,Se.mkdirSync)(t,{recursive:!0}),t}function kw(t,e,r=dc()){let n=s=>s.replace(/'/g,"''");return`Start-Process -FilePath '${n(t)}' -ArgumentList @('"${n(e)}"','--daemon') -WorkingDirectory '${n(r)}' -WindowStyle Hidden`}function Nw(t=process.env){let e=t.SystemRoot||t.SYSTEMROOT;return e?`${e}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`:"powershell.exe"}function Cw(t,e,r=dc()){return["-NoProfile","-WindowStyle","Hidden","-EncodedCommand",Buffer.from(kw(t,e,r),"utf16le").toString("base64")]}function co(t,e,r,n=process.platform,s){if(n==="win32"){let l=Nw(r),d=Cw(t,e),p=Aw(s);try{let g=(0,io.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,Se.existsSync)(o),a=i?o:t,u=Ua(a,i?[t,e,"--daemon"]:[e,"--daemon"],{detached:!0,stdio:"ignore",cwd:dc(),env:r});if(u.on("error",l=>{f.error("SYSTEM",Ow,{runtimePath:t,execPath:a},l)}),u.pid!==void 0)return u.unref(),u.pid}var me,lc,Se,io,fp,_N,EN,Ow,uc,fc=E(()=>{"use strict";me=_e(require("path"),1),lc=require("os"),Se=require("fs"),io=require("child_process");$a();O();fn();Ga();pn();Hf();Qt();Zs();C();ke();pt();fp=Ye(Z.POWERSHELL_COMMAND);_N=G.dataDir(),EN=G.workerPid(),Ow="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 gp(t){let e=t?.code;return e==="EACCES"||e==="EADDRNOTAVAIL"}var pc,gc=E(()=>{"use strict";pc="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 z.loadFromFile(ge).MEMINDEX_WORKER_HOST}function hp(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}async function _p(t,e,r="GET",n=Zt){let s={method:r,signal:AbortSignal.timeout(Math.max(1,n))},o=await fetch(`http://${hp(mc())}:${t}${e}`,r==="GET"||r==="HEAD"?s:dn(s)),i="";try{i=await o.text()}catch{}return{ok:o.ok,statusCode:o.status,body:i}}async function Ep(t,e=Zt){let r=Date.now()+e;if(process.platform==="win32")try{let s=await fetch(`http://${hp(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 uo(t,Math.max(1,r-Date.now()));return n==="occupied"||n==="indeterminate"}async function uo(t,e=Zt){return(await Dw(t,e)).occupancy}function Dw(t,e=Zt){return e<=0?Promise.resolve({occupancy:"indeterminate"}):new Promise(r=>{let n=!1,s=!1,o=!1,i;try{i=mp.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"}):gp(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 Fw(t,e,r,n){let s=Date.now()+r;for(;Date.now()<s;){try{let i=s-Date.now();if((await _p(t,e,"GET",Math.min(Zt,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 Sp(t,e=3e4){return Fw(t,"/api/health",e,"Service not ready yet, will retry")}async function Lw(t,e=Zt){try{let r=await _p(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 yp(t,e,r=Zt){let n=e??"unknown",s=await Lw(t,r);return!s||n==="unknown"?{matches:!0,pluginVersion:n,workerVersion:s}:{matches:n===s,pluginVersion:n,workerVersion:s}}var mp,Zt,lo=E(()=>{"use strict";mp=_e(require("net"),1);O();qe();C();gc();ka();Zt=5e3});var bp=E(()=>{"use strict";O();pn()});var wp=E(()=>{"use strict";fc();lo();bp()});function vp(){return(0,fo.join)(N(),"spawn.lock")}function Tp(t){try{let e=JSON.parse((0,se.readFileSync)(t,"utf-8"));return typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0?null:e.pid}catch{return null}}function Uw(t){if(t===null)return null;try{return process.kill(t,0),!0}catch(e){return e?.code==="EPERM"}}function po(){let t=vp(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return(0,se.mkdirSync)((0,fo.dirname)(t),{recursive:!0}),(0,se.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,se.statSync)(t).mtimeMs}catch{continue}let a=Tp(t),c=null;if(a===null)try{c=(0,se.readFileSync)(t,"utf-8")}catch{continue}if(Date.now()-i<=Ip&&Uw(a)!==!1)return!1;let l;try{l=(0,se.statSync)(t).mtimeMs}catch{continue}if(l!==i)return!1;if(a!==null){if(Tp(t)!==a)return!1}else try{if((0,se.readFileSync)(t,"utf-8")!==c)return!1}catch{continue}try{(0,se.unlinkSync)(t)}catch{return!1}}return!1}function yn(){let t=vp();try{if(JSON.parse((0,se.readFileSync)(t,"utf-8")).pid!==process.pid)return;(0,se.unlinkSync)(t)}catch{}}var fo,se,Ip,UN,Rp=E(()=>{"use strict";fo=require("path"),se=require("fs");C();O();Ip=9e4,UN=Ip/3});function Ap(t){return $w.test(t.trim())}function Bw(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 mo(t,e){return e===void 0?t:Math.max(1,Math.min(t,e))}async function Ww(t){try{let e=await go("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:mo(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 jw(t,e){try{let r=await go("netstat",["-ano"],{timeout:mo(15e3,e),windowsHide:!0,maxBuffer:16777216});return Gw(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 Hw(t,e){try{let r=await go("lsof",["-nP",`-iTCP:${t}`,"-sTCP:LISTEN","-t"],{timeout:mo(1e4,e),maxBuffer:1048576});return Xw(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 Xw(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 Kw(t,e){try{let n=(await go("ps",["-p",String(t),"-o","command="],{timeout:mo(5e3,e)})).stdout.trim();return n.length>0?n:null}catch{return null}}function Gw(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 Vw(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||!zw.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 Yw(t,e,r,n){let s=Ze(t),o=e?(await r(n))?.find(i=>i.pid===t)?.cmdline??null:await Kw(t,n);return De(t,s)?{startToken:s,cmdline:o}:{startToken:null,cmdline:null}}async function Np(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(Op))return f.info("PROCESS","Port reclaim skipped: not enough of the hook budget is left to finish one",{port:t,remainingMs:i(),neededMs:Op}),{reclaimed:!1,reason:"out-of-budget",killedPids:[]};let a=e.listOwners??((I,P)=>r()?jw(I,P):Hw(I,P)),c=I=>a(I,i()),u=e.readTable??Ww,l=()=>u(i()),d=e.killTree??((I,P)=>be(I,P)),p=e.dataDir??(()=>W),g=e.readIdentity??((I,P)=>Yw(I,r(),u,P)),m=await Vw(t,{listOwners:c,killTree:d,readOwnedWorker:e.readOwnedWorker??ft,probeHealth:e.probeHealth??(I=>Sp(I,xp)),readIdentity:I=>g(I,i()),minOwnerAgeSeconds:e.minOwnerAgeSeconds??Ad(),now:n,sleep:e.sleep??(I=>new Promise(P=>setTimeout(P,I))),hasKillBudget:()=>!o(hc)});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=>q(I)).length>0)return{reclaimed:!1,reason:"owner-alive",killedPids:[]};let b=new Map;for(let I of _){let P=b.get(I.ppid);P?P.push(I):b.set(I.ppid,[I])}let w=new Map,T=new Set,y=I=>{for(let P of b.get(I)??[])T.has(P.pid)||(T.add(P.pid),y(P.pid),Ap(P.name)&&w.set(P.pid,P))};for(let I of h)y(I);let A=p();if(A)for(let I of _)w.has(I.pid)||Ap(I.name)&&Bw(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(hc))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(P){return f.error("PROCESS","Ghost-port reclaim tree-kill failed",{port:t,pid:I.pid},P instanceof Error?P:new Error(String(P))),{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 Mp,Pp,go,$w,zw,xp,kp,hc,Op,Cp=E(()=>{"use strict";Mp=require("node:child_process"),Pp=require("node:util");O();yr();pt();pn();lo();Fs();ke();C();go=(0,Pp.promisify)(Mp.execFile),$w=/^(uv|uvx|python|chroma-mcp)(\.exe)?$/i;zw=/worker-service/i,xp=1500,kp=1e3,hc=5500,Op=2*xp+kp+hc});function Dp(t){try{return(0,Ar.realpathSync)(t)}catch{return t}}function Jw(t,e){let r=It.default.relative(e,t);return r!==""&&!r.startsWith("..")&&!It.default.isAbsolute(r)}function Lp(t){let e;try{let s=JSON.parse((0,Ar.readFileSync)(It.default.join(t,"package.json"),"utf-8"));e=Object.keys(s?.dependencies??{})}catch{return[]}if(e.length===0)return[];let r=It.default.join(t,"node_modules"),n=e.filter(s=>!(0,Ar.existsSync)(It.default.join(r,...s.split("/"),"package.json")));if(e.includes("zod")&&!n.includes("zod")){let s=(0,Fp.createRequire)(It.default.join(r,"noop.js")),o=Dp(It.default.join(r,"zod"));for(let i of qw)try{let a=s.resolve(i,{paths:[r]});Jw(Dp(a),o)||n.push(i)}catch{n.push(i)}}return n}var Ar,Fp,It,qw,Up=E(()=>{"use strict";Ar=require("fs"),Fp=require("module"),It=_e(require("path"),1),qw=["zod/v3","zod/v4","zod/v4-mini"]});function Wp(){return ho.default.join(N(),"worker-standby.json")}function Sc(){return ho.default.join(N(),"worker-standby-attempt.json")}function yc(){return ho.default.join(N(),"worker-standby-failure.json")}function bc(t){try{return JSON.parse((0,_o.readFileSync)(t,"utf-8"))}catch{return null}}function wc(t){try{(0,_o.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 Eo(){let t=bc(Wp());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 So(t){if(t!==void 0){let e=Eo();if(e!==null&&e.pid!==t)return}wc(Wp())}function Qw(){let t=bc(yc());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 jp(t,e,r=new Date){try{U(yc(),{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 Hp(){wc(yc())}function Xp(t,e=Date.now()){if(t===null)return null;let r=Qw();if(r===null||r.buildKey!==t)return null;let n=Date.parse(r.failedAt);return!Number.isFinite(n)||e-n>=Ec?null:r}function Kp(){let t=bc(Sc());return!t||typeof t.buildKey!="string"||typeof t.launchedAtMs!="number"||!Number.isFinite(t.launchedAtMs)?null:{buildKey:t.buildKey,launchedAtMs:t.launchedAtMs}}function Gp(t){try{U(Sc(),t)}catch(e){f.debug("SYSTEM","Could not save the worker update attempt",{error:e instanceof Error?e.message:String(e)})}}function zp(){wc(Sc())}var ho,_o,$p,_c,Bp,Ec,Vp=E(()=>{"use strict";ho=_e(require("path"),1),_o=require("fs");C();ne();O();$p="MEMINDEX_WORKER_STANDBY",_c=12e4,Bp=2e4,Ec=10*6e4});function Ac(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 ag(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 rT(t){return ag()?{...t,verbose:!0}:t}function nT(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 sT(t,e,r){let n=typeof e.method=="string"?e.method:"GET",s=nT(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 Mc(t,e={}){let r=rT(e);try{return await fetch(t,r)}catch(n){throw ag()&&sT(t,e,n),n}}async function Tn(t,e={},r){try{return await Mc(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 oT(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 cg(t,e,r){let n=oT(r,e.signal),s;try{s=await Mc(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 iT(t,e,r){let n=await cg(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 Yp(){return L.default.join(z.get("MEMINDEX_DATA_DIR"),"settings.json")}function Pc(t={}){return t.readOnly?z.loadFromFile(Yp(),!0,t):(yo!==null||(yo=z.loadFromFile(Yp())),yo)}function qp(t,e){if(!t)return null;let r=parseInt(t,10);return Number.isFinite(r)&&r>=e.min&&r<=e.max?r:null}function ug(t,e,r){let n=process.env[t];if(n!==void 0){let i=qp(n,r);return i!==null?i:(f.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max}),e)}let s=Pc()[t],o=qp(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 oe(t={}){if(!t.readOnly&&Tc!==null)return Tc;let e=parseInt(Pc(t).MEMINDEX_WORKER_PORT,10),r=e===Ia()&&on()?va(N()):e;return t.readOnly||(Tc=r),r}function xc(t={}){if(!t.readOnly&&Ic!==null)return Ic;let e=Pc(t).MEMINDEX_WORKER_HOST;return t.readOnly||(Ic=e),e}function aT(){return bo!==null||(bo=ug("MEMINDEX_API_TIMEOUT_MS",Ye(Z.API_REQUEST),eT)),bo}function lg(){return wo!==null||(wo=Math.min(ug("MEMINDEX_SESSION_INIT_TIMEOUT_MS",sn(),tT),Od())),wo}function Ao(t){return t===null?null:Math.max(0,t-Date.now())}function vo(t){let e=Ao(t);return e!==null&&e<Oc}function Fe(t,e){let r=Ao(e);return r===null?t:Math.max(1,Math.min(t,r))}function dg(t){return`http://${Da(xc())}:${oe()}${t}`}function ue(t,e={}){let r=e.method??"GET",n=dg(t),s={method:r};e.headers&&(s.headers=e.headers),e.body&&(s.body=e.body);let o=dn(s);if(e.idleTimeoutMs!==void 0&&e.idleTimeoutMs>0)return iT(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??aT();return i>0?Tn(n,o,i):Mc(n,o)}async function cT(t){return(await ue("/api/health",{timeoutMs:t})).ok}async function Jp(t=et){return(await ue("/api/readiness",{timeoutMs:t})).ok}function fg(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 uT(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 lT(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:fg(e),version:L.default.basename(e)}))}catch{return[]}}function Qp(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 dT(){return{cacheRoot:L.default.join(L.default.dirname(L.default.dirname(Er)),"cache","memindex","memindex"),marketplaceRoot:Er,cwd:process.cwd()}}function kc(t=dT()){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=[...lT(t.cacheRoot),{scriptPath:fg(L.default.join(t.marketplaceRoot,"plugin")),version:Qp(L.default.join(t.marketplaceRoot,"package.json"))},{scriptPath:L.default.join(t.cwd,"plugin","scripts","worker-service.cjs"),version:Qp(L.default.join(t.cwd,"package.json"))}];return gT(r)}function fT(t){return L.default.dirname(L.default.dirname(t))}function pT(t){return Lp(fT(t.scriptPath)).length===0}function gT(t,e=pT){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:uT(n.version,s.version)),r.find(e)??r[0])}function mT(){return kc()?.scriptPath??null}async function hT(t){let e=t.deadlineAt??null,r=t.backoffMs;for(let n=1;n<=t.attempts;n++){if(vo(e))return!1;if(await bg(e??Number.POSITIVE_INFINITY))return!0;n<t.attempts&&(await new Promise(s=>setTimeout(s,Fe(r,e))),r*=2)}return!1}function Zp(t){return t instanceof Error&&/^Request timed out after \d+ms idle$/.test(t.message)}function eg(t){return t instanceof Error&&/^Request timed out after \d+ms$/.test(t.message)}async function _T(t){let e;try{e=await cg(dg("/api/ready"),{method:"GET"},{idleTimeoutMs:Zw,absoluteCapMs:Math.max(1,t)})}catch(o){return Zp(o)?{outcome:"unresponsive",detail:"no response headers within the idle window"}:eg(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 Ro(),await r(),{outcome:"unsupported"};let s=null;try{for await(let o of nf(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 Ro(),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 eg(o)?(Ro(),{outcome:"still_booting",detail:`last phase ${s??"none"}`}):Zp(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 ET(t){if(t<=0)try{return await Jp()?{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 Jp(Math.max(1,Math.min(et,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 tr(t=Or){let e=t>0?t:et,r=await _T(e);return r.outcome==="ready"&&vT(),r.outcome!=="unsupported"?r:(f.debug("SYSTEM","Worker has no /api/ready stream; falling back to /api/readiness"),ET(t))}async function ST(t=et){try{let r=await(await ue("/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 yT(t=5e3){let e=Date.now()+t;for(;;){let r=e-Date.now();if(r<=0)return!1;if(await uo(oe(),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 pg(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 gg(){return L.default.join(N(),"worker-version-recycle.json")}function bT(t,e){if(t===null||e===null)return!1;try{let r=JSON.parse((0,x.readFileSync)(gg(),"utf-8"));return r?.buildKey===t&&r?.workerVersion===e}catch{return!1}}async function tg(t,e=null,r=et){let n=await ST(r);if(n!==null&&n!==t){if(e!==null)try{U(gg(),{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 Nc(){return L.default.join(N(),"worker-unresponsive.json")}function wT(){try{let t=JSON.parse((0,x.readFileSync)(Nc(),"utf-8"));return typeof t?.pid!="number"||typeof t?.firstUnresponsiveAtEpochMs!="number"?null:{pid:t.pid,firstUnresponsiveAtEpochMs:t.firstUnresponsiveAtEpochMs}}catch{return null}}function Ro(){let t=Nc();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 TT(t=Date.now()){let e=ft()?.pid??null;if(e===null)return!1;let r=wT();if(r!==null&&r.pid===e)return t-r.firstUnresponsiveAtEpochMs>=mg;try{U(Nc(),{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 Cc(){return L.default.join(N(),"worker-never-ready-recycle.json")}function IT(){try{let t=JSON.parse((0,x.readFileSync)(Cc(),"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 hg(t){try{U(Cc(),t)}catch(e){f.warn("SYSTEM","Could not persist the never-ready worker recycle",{error:e instanceof Error?e.message:String(e)})}}function vT(){let t=Cc();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 _g(t){return pg(t,t?.version??"unknown")??"unresolved-worker-bundle"}function Eg(t){return t.outcome==="failed"?t.detail??"unknown init failure":t.outcome}function Sg(t,e){if(t.outcome==="unresponsive"&&!TT())return f.warn("SYSTEM","Worker went silent on /api/ready; skipping this hook without killing it",{detail:t.detail,wedgedAfterMs:mg}),!1;let r=Eg(t),n=IT();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")}),hg({...n,refusalLogged:!0})),!1):!0}function yg(t,e){hg({buildKey:e,failureMessage:Eg(t)}),Ro()}async function bg(t=Number.POSITIVE_INFINITY){let e=t-Date.now();if(e<=0)return!1;let r;try{r=await cT(Math.min(et,e))}catch(n){return f.debug("SYSTEM","Worker health check threw",{error:n instanceof Error?n.message:String(n)}),!1}return r}async function Dc(t,e){let r=ft();if(r===null||r.port!==oe())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:oe(),pidFilePid:r?.pid??null,pidFilePort:r?.port??null}),!1;if(e("stale-worker recycle"))return!1;try{await be(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 yT(Fe(5e3,t))?!0:(e("stale port release")||(rr=oe(),f.error("SYSTEM","Stale worker port still open after SIGKILL; skipping spawn this hook event",{pid:r.pid,port:oe(),fix:Oo})),!1)}function wg(t,e){return`http://127.0.0.1:${t}${e}`}async function Tg(t,e){if(e<=0)return{answered:!1,version:null};try{let n=await(await Tn(wg(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 Ig(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)})}So(t.pid)}async function RT(t,e,r,n){let s=await AT(t,e,r,n);return s.kind!=="out-of-budget"&&zp(),s}async function AT(t,e,r,n){let s=Eo(),o=s===null?null:await Tg(s,Fe(et,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(bn/1e3)} seconds; the worker log has the reason`};if(s!==null&&o!==null)if(o.answered)Ig(s);else{let d=Date.parse(s.startedAt);if((Number.isFinite(d)?Date.now()-d:Number.POSITIVE_INFINITY)<_c&&q(s.pid)){let g=Math.min(d+_c,Math.max(d+bn,Date.now()+2e3)),m=await vc(e,g,n,i);return m.kind==="failed"&&So(s.pid),m}So(s.pid)}let a=r===null?null:Kp();if(a!==null&&a.buildKey===r)return Date.now()-a.launchedAtMs>=bn?i:vc(e,a.launchedAtMs+bn,n,i);let c=ao();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=co(c,t,dt({...process.env,MEMINDEX_WORKER_PORT:String(oe()),[$p]:"1"}),process.platform,Ao(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&&Gp({buildKey:r,launchedAtMs:l}),vc(e,l+bn,n,i)}async function vc(t,e,r,n){let s=Math.min(e,r??Number.POSITIVE_INFINITY);for(;Date.now()<s;){let o=Eo();if(o!==null){let a=await Tg(o,Math.min(1e3,s-Date.now()));if(a.answered)return a.version===t?{kind:"ready",record:o}:(Ig(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 OT(t,e){try{let r=await Tn(wg(t.port,"/api/admin/promote"),dn({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 MT(t){let{scriptPath:e,pluginVersion:r,workerVersion:n,buildKey:s,deadlineAt:o,outOfBudget:i}=t,a=n??"unknown",c=Xp(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=ft();if(u===null||u.port!==oe())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:oe(),pidFilePid:u?.pid??null,pidFilePort:u?.port??null}),"failed";if(!po())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 RT(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&&jp(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(Ec/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 Dc(o,i))return"failed";l=!0;let p=await OT(d.record,Fe(1e4,o));return p===null?(Hp(),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||yn()}}async function Mr(t){let e=t===void 0?null:Date.now()+t,r=S=>vo(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:Fe(et,e),s=Math.min(Date.now()+5e3,e??Number.POSITIVE_INFINITY),o=kc(),i=null,a=null,c=!1,u=!1,l=!1,d=null,p=null,g=Ds(K());if(r("health probe"))return!1;if(await bg(s)){if(r("version probe"))return!1;let{matches:S,pluginVersion:b,workerVersion:w}=await yp(oe(),o?.version??null,n());if(b!=="unknown"&&(i=b),S){if(r("readiness wait"))return!1;let T=await tr(Fe(Or,e));if(T.outcome==="ready")return i!==null&&!vo(e)&&await tg(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=_g(o),!Sg(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 tr(Fe(Or,e))).outcome==="ready";if(a=pg(o,b),bT(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 tr(Fe(Or,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 MT({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 tr(Fe(Or,e))).outcome==="ready";u=!0,l=T==="promoted"}if(!u&&!await Dc(e,r))return!1;d!==null&&p!==null&&yg(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&&yn(),!1;let h=u||po();try{if(h&&!l){if(!c&&!await PT(s,e))return!1;let b=ao();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(co(b,m,dt({...process.env,MEMINDEX_WORKER_PORT:String(oe())}),process.platform,Ao(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 hT({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)"),ft()===null&&await Ep(oe(),e===null?void 0:Fe(5e3,e))&&(rr=oe(),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:rr,fix:Oo}))),!1}finally{h&&yn()}if(r("readiness wait"))return!1;let _=await tr(Fe(Or,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&&!vo(e)&&await tg(i,a,n()),!0)}async function PT(t,e){let r=oe(),n=t-Date.now();if(n<=0)return!1;let s=await uo(r,n);if(s==="free")return!0;if(s==="unbindable")return Rc=r,f.error("SYSTEM","Worker port cannot be bound (EACCES or EADDRNOTAVAIL) \u2014 skipping lazy-spawn",{port:r,host:xc(),fix:pc}),!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 Np(r,{deadlineAt:e});return o.reclaimed?(f.info("SYSTEM","Reclaimed the worker port before lazy-spawn",{port:r,killedPids:o.killedPids}),!0):(ft()===null&&(rr=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,...rr===r?{fix:Oo}:{}}),!1)}async function xT(t){if(er!==void 0)return er;try{let r=await(await ue("/api/health",{timeoutMs:t})).json();er=Fd(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)}),er=null}return er!==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:er,dataDir:N(),port:oe()}),er}async function kT(t){return To!==null||(To=await Mr(t)),To}async function NT(t){let e=Date.now()+t,r=()=>e-Date.now(),n=u=>r()>=Oc?!1:(f.debug("SYSTEM","Bounded worker startup ran out of budget",{step:u,budgetMs:t}),!0),s=await tr(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(!!Ds(K()))return rg(e);let i=ao(),a=mT();if(!i||!a)return!1;if(s.outcome==="failed"||s.outcome==="wedged"||s.outcome==="unresponsive"){let u=_g(kc());if(!Sg(s,u)||(f.info("SYSTEM","Worker will never become ready \u2014 recycling wedged worker",{outcome:s.outcome,detail:s.detail}),!await Dc(e,n)))return!1;yg(s,u)}let c=po();try{return c&&co(i,a,dt({...process.env,MEMINDEX_WORKER_PORT:String(oe())}),process.platform,Math.max(1,r()))===void 0?!1:await rg(e)}catch(u){return f.debug("SYSTEM","Bounded worker startup failed",{error:u instanceof Error?u.message:String(u)}),!1}finally{c&&yn()}}async function rg(t){for(;t-Date.now()>0;){let e=await tr(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 Mo(){return L.default.join(W,"state")}function Og(){return L.default.join(Mo(),"hook-failures.json")}function Mg(){return L.default.join(Mo(),"hook-failures.lock")}async function Fc(t=Rg){let e=Mo(),r=Mg(),n=(0,ig.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>Ag){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,DT))}return f.warn("SYSTEM","Timed out waiting for hook-failure lock; skipping failure-state update",{lockPath:r,waitMs:t}),null}function Lc(t){let e=Mg();try{if(JSON.parse((0,x.readFileSync)(e,"utf-8")).token!==t)return;(0,x.unlinkSync)(e)}catch{}}function LT(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(-vg):void 0}}function wn(){try{return LT((0,x.readFileSync)(Og(),"utf-8"))}catch{return{consecutiveFailures:0,lastFailureAt:0,thresholdTripped:!1}}}function Uc(t){let e=Mo(),r=Og(),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 UT(){try{let e=K().MEMINDEX_HOOK_FAIL_LOUD_THRESHOLD,r=parseInt(e,10);if(Number.isFinite(r)&&r>=1)return r}catch{}return CT}function Pg(t){let e=Rc!==null?`The worker cannot bind port ${Rc} on ${xc()}: the system refuses it (EACCES or EADDRNOTAVAIL). ${pc}.`:rr!==null?`Port ${rr} is held by an unreachable process that no PID file claims, so the worker cannot bind it. ${Oo}.`:"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 Io(){if($T){if(sg)return wn().consecutiveFailures;sg=!0}let t=await Fc();if(t===null)return wn().consecutiveFailures;let e,r=!1;try{let n=wn();e={consecutiveFailures:n.consecutiveFailures+1,lastFailureAt:Date.now(),thresholdTripped:n.thresholdTripped,notifiedSessionIds:n.notifiedSessionIds};let s=UT();r=e.consecutiveFailures>=s&&!e.thresholdTripped,r&&(e.thresholdTripped=!0);let o=Uc(e);r=r&&o}finally{Lc(t)}return r&&(await Bf("hook_failed",{...ng!==null?{hook_type:ng}:{},error_mode:"worker_unavailable",consecutive_failures:e.consecutiveFailures,threshold_tripped:!0}),ct(`${Pg(e.consecutiveFailures)}
23
- `)),e.consecutiveFailures}async function xg(t){if(!t)return null;let e=await Fc();if(e===null)return null;try{let r=wn(),n=r.notifiedSessionIds??[];return!r.thresholdTripped||n.includes(t)?null:Uc({...r,notifiedSessionIds:[...n,t].slice(-vg)})?Pg(r.consecutiveFailures):null}finally{Lc(e)}}async function og(){let t=await Fc(FT);if(t!==null)try{let e=wn();if(e.consecutiveFailures===0&&!e.thresholdTripped)return;Uc({consecutiveFailures:0,lastFailureAt:0,thresholdTripped:!1})}finally{Lc(t)}}function kg(t){return typeof t=="object"&&t!==null&&t[vt]===!0}async function Ng(t,e,r,n={}){let s=Date.now(),o=n.workerStartupTimeoutMs!==void 0;if(!(o?await NT(n.workerStartupTimeoutMs):await kT(n.timeoutMs)))return Ds(K())?{continue:!0,reason:"worker_autostart_disabled",[vt]:!0}:(o||await Io(),{continue:!0,reason:"worker_unreachable",[vt]:!0});let a=n.timeoutMs===void 0?et:Math.max(1,Math.min(et,n.timeoutMs-(Date.now()-s)));if(await xT(a)!==null)return await Io(),{continue:!0,reason:"worker_foreign_data_dir",[vt]:!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<Oc)return f.debug("SYSTEM","Hook budget spent before the worker request; skipping it",{url:t}),o||await Io(),{continue:!0,reason:"worker_budget_exhausted",[vt]:!0};c.timeoutMs=d}let u;try{u=await ue(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",[vt]:!0}}if(!u.ok){let d=await u.text().catch(()=>"");if(await og(),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}`,[vt]:!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 Io(),{continue:!0,reason:"worker_body_read_failed",[vt]:!0}}if(await og(),l.length!==0)try{return JSON.parse(l)}catch{return l}}var L,ig,x,et,Or,bn,Zw,eT,tT,Oc,Tc,Ic,yo,bo,wo,mg,Oo,rr,Rc,To,er,CT,vg,Rg,DT,Ag,FT,ng,$T,sg,vt,Rt=E(()=>{"use strict";ka();L=_e(require("path"),1),ig=require("crypto"),x=require("fs");O();ke();sf();qe();C();Qe();of();af();Fa();Ra();pn();pt();As();Wf();wp();lo();gc();fc();Rp();Cp();fn();yr();ne();Up();Vp();Fa();et=Ac("MEMINDEX_HEALTH_TIMEOUT_MS",Ye(Z.HEALTH_CHECK),{min:500,max:3e5}),Or=Ac("MEMINDEX_HOOK_READINESS_TIMEOUT_MS",Ye(Z.HOOK_READINESS_WAIT),{min:0,max:3e5}),bn=Ac("MEMINDEX_WORKER_STANDBY_WAIT_MS",Bp,{min:500,max:3e5}),Zw=5e3,eT={min:500,max:3e5},tT={min:500,max:Z.SESSION_INIT_REQUEST_MAX},Oc=100;Tc=null,Ic=null,yo=null,bo=null,wo=null;mg=3e4;Oo="Set MEMINDEX_WORKER_PORT to a different port in memindex settings, or reboot to release the stuck port",rr=null,Rc=null;To=null;CT=3,vg=20,Rg=1e3,DT=10,Ag=5e3,FT=Ag+Rg;ng=null;$T=!1,sg=!1;vt=Symbol.for("memindex/worker-fallback")});function $c(t,e){let r=(0,tt.normalize)(t),n=(0,tt.normalize)(e);if(r===n)return!0;let s=(0,tt.relative)(n,r);return s.length>0&&!s.startsWith("..")&&!(0,tt.isAbsolute)(s)}function rt(t){if(process.env.MEMINDEX_INTERNAL==="1")return!1;if(!t)return!0;if($c(t,Ms)||$c(t,KT)||$c(t,GT))return!1;let e=K();return!to(t,e.MEMINDEX_EXCLUDED_PROJECTS)}var tt,BT,WT,jT,HT,XT,KT,GT,Pr=E(()=>{"use strict";tt=require("path");En();Qe();C();BT="plugins",WT="cache",jT="memindex",HT="memindex",XT="plugin",KT=(0,tt.join)(lt,BT,WT,jT,HT),GT=(0,tt.join)(Er,XT)});function zT(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function V(t){if(!t)return Cg;let e=zT(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:Cg}var Cg,gt=E(()=>{"use strict";Cg="claude"});var Dg=E(()=>{"use strict"});function Wc(t){return new RegExp(`${t}${VT}`,"gi")}function jc(t,e){if(!e.enabled||t.length===0)return{redacted:t,counts:{},oversize:!1};if(t.length>qT)return f.warn("REDACT","field exceeds the 1M-char redaction cap; replaced by an oversize marker",void 0,{inputLength:t.length}),{redacted:JT,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,...YT];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 QT(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 ZT(t){return{enabled:t.MEMINDEX_REDACT_ENABLED==="true",disabledBuiltinPatterns:(t.MEMINDEX_REDACT_DISABLED_BUILTINS??"").split(",").map(e=>e.trim()).filter(Boolean),customPatterns:QT(t.MEMINDEX_REDACT_CUSTOM_PATTERNS??"[]"),logMatches:t.MEMINDEX_REDACT_LOG_MATCHES==="true"}}function nI(t){if(!(0,Po.existsSync)(t))return null;try{return(0,Po.readFileSync)(t,"utf-8")}catch{return""}}function sI(t){if(t===null)return!1;try{let e=JSON.parse(_a(t));return e===null||typeof e!="object"||Array.isArray(e)}catch{return!0}}function oI(t,e,r){return process.env.MEMINDEX_REDACT_ENABLED==="false"||!(vn?.enabled===!0||rI.test(e))?r:(Lg||(Lg=!0,f.warn("REDACT","settings.json could not be read; secret redaction stays on until it is repaired",{settingsPath:t,using:vn?.enabled?"the last configuration that loaded":"the built-in patterns"})),vn?.enabled?vn:tI)}function Hc(t=ge){let e=Date.now();if(In&&e-Fg<eI)return In;let r=z.loadFromFile(t),n=ZT(r),s=n.enabled?null:nI(t);return sI(s)?In=oI(t,s,n):(In=n,vn=n),Fg=e,In}function Ug(t){return jc(t,Hc()).redacted}var Po,Bc,VT,YT,qT,JT,In,Fg,eI,vn,Lg,tI,rI,Xc=E(()=>{"use strict";Po=require("fs");O();qe();C();ne();Bc=String.raw`[A-Za-z0-9_.\-+/=~@#$%^*!?]`,VT=`(?=${Bc}{8})${Bc}*[A-Za-z]${Bc}*`;YT=[{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:Wc(String.raw`(?<=\b\w*_?(?:password|passwd|pwd)\\{0,2}["']?\s*[=:]\s*\\{0,2}["']?)`)},{name:"generic_token",regex:Wc(String.raw`(?<=\b\w*_(?:token|secret|api_key)\\{0,2}["']?\s*[=:]\s*\\{0,2}["']?)`)},{name:"bearer_token",regex:Wc(String.raw`(?<=\bAuthorization\s*:\s*Bearer\s*)`)}],qT=1024*1024,JT="<redacted type='oversize'/>";In=null,Fg=0,eI=5e3,vn=null,Lg=!1,tI={enabled:!0,disabledBuiltinPatterns:[],customPatterns:[],logMatches:!1},rI=/"(?:MEMINDEX|AGENT_MEM)_REDACT_ENABLED"\s*:\s*"true"/});function aI(t){let e=Object.fromEntries(Kc.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}Bg.lastIndex=a;let l=Bg.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}$g.lastIndex=a;let d=$g.exec(t);if(d&&iI.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 cI(t){let{text:e,counts:r,total:n}=aI(t);return n>Wg&&f.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:n,maxAllowed:Wg,contentLength:t.length}),{stripped:jc(e.trim(),Hc()).redacted,counts:r}}function Te(t){return cI(t).stripped}function Rn(t){let e=r=>typeof r=="string"?uI.test(r)?Te(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 ko(t){return!t||t.length>fI?!1:dI.test(t)}function jg(t){let e=t.trimStart();return pI.some(r=>r.test(e))}var Kc,iI,$g,Bg,xo,Wg,uI,lI,dI,fI,pI,nt=E(()=>{"use strict";O();Xc();Kc=["private","memindex-context","agent-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],iI=new Set(Kc),$g=/<([A-Za-z_][A-Za-z0-9_-]*)/y,Bg=/<\/([A-Za-z_][A-Za-z0-9_-]*)\s*>/y;xo=/<system-reminder>[\s\S]*?<\/system-reminder>/g,Wg=100;uI=new RegExp(`<(${Kc.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`);lI=["task-notification"],dI=new RegExp(`^\\s*<(${lI.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),fI=256*1024;pI=[/^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 mI(t){return/unrecogni[sz]ed key[^]*\bbranch\b|\bbranch\b[^]*\b(unrecogni[sz]ed|unknown (field|key|property)|not allowed|unsupported|not supported)\b|additional propert[^]*\bbranch\b/i.test(t)}function Ue(t){return t instanceof Le}function hI(t){return t.replace(/\/+$/,"")}function No(t){return typeof t=="string"?V(t):null}function _I(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}var gI,Le,Co,nr=E(()=>{"use strict";Rt();ke();gt();nt();gI=Ye(Z.API_REQUEST),Le=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)}},Co=class{baseUrl;apiKey;timeoutMs;branchRejected=!1;constructor(e){this.baseUrl=hI(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??gI}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 Le("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 updateObservation(e,r){if(!e)throw new Le("invalid_response","id is required for updateObservation");await this.request("PATCH",`/v1/memories/${encodeURIComponent(e)}`,r)}async deleteObservation(e){if(!e)throw new Le("invalid_response","id is required for deleteObservation");await this.request("DELETE",`/v1/memories/${encodeURIComponent(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=No(e.platformSource)),e.folderProjects&&e.folderProjects.length>0&&(n.folderProjects=e.folderProjects),e.excludeSubagents!==void 0&&(n.excludeSubagents=e.excludeSubagents),e.branch&&(n.branch=e.branch),this.request("POST","/v1/context",n,r)}async getJobStatus(e){if(!e)throw new Le("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{...e.fields??{},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}:{},...e.branch?{branch:e.branch}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.branch?{branch:e.branch}:{},...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:No(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:No(e.platformSource)}:{},...e.metadata!==void 0?{metadata:Rn(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:No(e.platformSource)}:{},...e.payload!==void 0?{payload:Rn(e.payload)}:{},...e.branch?{branch:e.branch}:{}}}async request(e,r,n,s={}){if(!this.apiKey||!this.apiKey.trim())throw new Le("missing_api_key","Server API key is not configured (MEMINDEX_SERVER_API_KEY).");let o=typeof n=="object"&&n!==null&&"branch"in n;if(o&&this.branchRejected){let{branch:p,...g}=n;n=g}let i=`${this.baseUrl}${r}`,a={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(a.body=JSON.stringify(n));let c=p=>{let g=p instanceof Error?p.message:String(p),m=/timed out|timeout/i.test(g)||p instanceof Error&&(p.name==="TimeoutError"||p.name==="AbortError");return new Le(m?"timeout":"transport",`Server ${e} ${r} failed: ${g}`,{cause:p})},u,l=s.timeoutMs??this.timeoutMs;try{u=await Tn(i,a,l)}catch(p){throw c(p)}if(!u.ok){let p=await u.text().catch(()=>"");if(o&&!this.branchRejected&&(u.status===400||u.status===422)&&mI(p))return this.branchRejected=!0,this.request(e,r,n,s);throw new Le("http_error",`Server ${e} ${r} returned ${u.status}: ${_I(p,200)}`,{status:u.status})}let d;try{d=await u.text()}catch(p){throw c(p)}if(!d||d.length===0)return{};try{return JSON.parse(d)}catch(p){let g=p instanceof Error?p:new Error(String(p));throw new Le("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:g})}}}});function EI(){let e=(K().MEMINDEX_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function SI(){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 yI(){let{serverBaseUrl:t,apiKey:e,projectId:r}=SI();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 Co(n),projectId:r,serverBaseUrl:t}}function $e(){if(EI()!=="server")return{runtime:"worker"};let t=yI();return t||{runtime:"worker"}}function Be(t,e){f.warn("HOOK",`[server-fallback] reason=${t}`,e??{})}var xr=E(()=>{"use strict";Qe();O();nr()});function vI(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 We(t){let e=(0,Yc.createHash)("sha256").update(vI(t.serverBaseUrl)).update("\0").update(t.projectId).digest("hex").slice(0,16);return(0,At.join)(N(),"state","server-outbox",e)}function qc(t){return(0,At.join)(t,"outage.json")}function mt(t){return Ue(t)&&t.isFallbackEligible()&&t.kind!=="missing_api_key"}function RI(){return Gc=Math.max(Date.now(),Gc+1),Gc}function AI(t,e){let r=(0,Yc.createHash)("sha256").update(JSON.stringify(e)).digest("hex").slice(0,16);return`${String(t).padStart(15,"0")}-${e.op}-${r}.json`}function Ot(t,e){(0,H.mkdirSync)(e,{recursive:!0});let r=Rn(t),n=RI(),s=(0,At.join)(e,AI(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 Kg(t){return(0,H.existsSync)(t)?(0,H.readdirSync)(t).filter(e=>e.endsWith(".json")&&e!=="outage.json").sort():[]}function Vc(t){try{return Kg(t).length}catch{return 0}}function OI(t){for(let e of(0,H.readdirSync)(t)){if(!e.endsWith(`.json${zc}`))continue;let r=(0,At.join)(t,e);try{if(Date.now()-(0,H.statSync)(r).mtimeMs<bI)continue;(0,H.renameSync)(r,r.slice(0,-zc.length))}catch{}}}async function Jc(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 MI(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 Jc(t,e.request,s,n)}function Xg(t,e,r){try{(0,H.mkdirSync)((0,At.join)(t,Hg),{recursive:!0}),(0,H.renameSync)(e,(0,At.join)(t,Hg,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 kr(t,e,r={}){let n=r.maxEntries??TI,s=Date.now()+(r.budgetMs??II),o={delivered:0,remaining:0,rejected:0};try{if(!(0,H.existsSync)(e))return o;OI(e);let i=Kg(e),a=0;for(let c of i){if(a>=n||Date.now()>=s)break;let u=(0,At.join)(e,c),l=`${u}${zc}`;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))),Xg(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()+Z.API_REQUEST):s;await MI(t,d.entry,g,p),(0,H.unlinkSync)(l),o.delivered++}catch(p){if(mt(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:Ue(p)?p.status:null},p instanceof Error?p:new Error(String(p))),Xg(e,l,c),o.rejected++}}o.remaining=Vc(e),o.delivered>0&&f.info("HOOK","Sent held captures to the hosted server",{...o}),o.remaining===0&&xI(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=Vc(e)}return o}function PI(t){try{let e=JSON.parse((0,H.readFileSync)(qc(t),"utf-8"));return{notifiedSessionIds:Array.isArray(e.notifiedSessionIds)?e.notifiedSessionIds:[]}}catch{return{notifiedSessionIds:[]}}}function xI(t){try{(0,H.unlinkSync)(qc(t))}catch{}}function kI(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 Gg(t,e){if(!t)return null;let r=Vc(e);if(r===0)return null;let n=PI(e);if(n.notifiedSessionIds.includes(t))return null;try{U(qc(e),{notifiedSessionIds:[...n.notifiedSessionIds,t].slice(-wI)})}catch{}return kI(r)}var Yc,H,At,zc,Hg,bI,wI,TI,II,Gc,An=E(()=>{"use strict";Yc=require("crypto"),H=require("fs"),At=require("path");ne();C();ke();O();nt();nr();zc=".sending",Hg="rejected",bI=120*1e3,wI=50,TI=20,II=1500;Gc=0});function Fo(t){return jI.run(t,!0)}function HI(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 XI(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 KI(t){let e=t.replace(LI," ").toLowerCase().match(/[\p{L}\p{N}_]{4,}/gu)??[],r=[...new Set(e)].slice(0,FI);return r.length>0?r.join(" or "):null}async function GI(t,e,r,n,s,o,i){if(e.length<20||e==="[media prompt]")return"";let a=KI(e);if(!a)return"";let c=Qc(o,i);if(c<Do)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 zI(t){let e=String(t.MEMINDEX_SEMANTIC_INJECT).toLowerCase();return e==="auto"?String(t.MEMINDEX_MODE).toLowerCase()==="personal":e==="true"}function VI(t){let e=String(t.MEMINDEX_READ_ONLY??"").toLowerCase();return e==="1"||e==="true"}async function zg(t,e,r,n,s,o,i){if(!e||e.length<20||e==="[media prompt]")return"";let a=Qc(o,i);if(a<Do)return f.warn("HOOK","session-init: skipping semantic injection because the prompt budget is spent",{project:r,remainingMs:a}),"";let c=await le.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},Vg(s,a));return le.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 Qc(t,e){return Math.max(0,e-(Date.now()-t))}function Vg(t,e){return t==="codex"?{workerStartupTimeoutMs:Z.POST_SPAWN_WAIT,timeoutMs:Math.min($I,e)}:{timeoutMs:e}}var CI,le,DI,FI,LI,UI,Do,$I,Nr,BI,WI,jI,Zc=E(()=>{"use strict";Rt();Qt();O();ke();Pr();Qe();gt();Dg();nt();xr();nr();An();CI={executeWithWorkerFallback:Ng,getSessionInitRequestTimeoutMs:lg,isWorkerFallback:kg,consumeWorkerOutageNotice:xg,loadFromFileOnce:K,resolveRuntimeContext:$e,logServerFallback:Be,holdForServer:Ot,consumeServerOutageNotice:Gg,shouldTrackProject:rt,readHookEnvironment:()=>process.env},le=CI,DI=2,FI=12,LI=/<private\b[^>]*>[\s\S]*?<\/private\s*>/gi,UI=1e4,Do=500,$I=2e3,Nr=class extends Error{constructor(r){super(`session-init did not record the prompt (${r})`);this.reason=r;this.name="SessionPromptNotRecordedError"}reason};BI=t=>t?t.replace(/\\/g,"/").includes("/.qwen/"):!1,WI=(t,e=process.env)=>t?e.QWEN_PROJECT_DIR?!0:BI(t):!1,jI={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(!le.shouldTrackProject(o))return f.info("HOOK","Project excluded from tracking",{cwd:o}),{continue:!0,suppressOutput:!0};if(n&&ko(n))return f.debug("HOOK","session-init: skipping internal protocol payload",{preview:n.slice(0,80)}),{continue:!0,suppressOutput:!0};if(n&&V(t.platform)==="codex"&&jg(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()&&WI(t.transcriptPath,le.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=oo(o),u=c.primary,l=V(t.platform),d=le.loadFromFileOnce(),p=zI(d),g=le.resolveRuntimeContext(),m=Date.now(),h=le.getSessionInitRequestTimeoutMs();if(g.runtime==="server"){let y=HI(g,t,r,l,u,a);try{await XI(g,y,Math.max(Do,Math.floor(h/DI)));let A=p?await GI(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(mt(A)){le.logServerFallback(A.kind,{status:A.status,message:A.message,route:"/v1/sessions/start",held:!0});let v=We(g);le.holdForServer({op:"session_start",request:y},v);let R=le.consumeServerOutageNotice(r,v);return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS,...R?{systemMessage:R,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:R}}:{}}}if(Ue(A)&&A.isFallbackEligible())le.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(VI(le.readHookEnvironment())){let y=p?await zg(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 _=Qc(m,h);if(_<Do){if(f.warn("HOOK","session-init: skipping the worker call because the prompt budget is spent",{contentSessionId:r,project:u,remainingMs:_}),e)throw new Nr("budget_exhausted");return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS}}let S=await le.executeWithWorkerFallback("/api/sessions/init","POST",{contentSessionId:r,project:u,prompt:a,platformSource:l,cwd:o,projectKeySource:c.keySource},Vg(l,_));if(le.isWorkerFallback(S)){if(e)throw new Nr("reason"in S?S.reason:"worker_fallback");let y=await le.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 zg(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 Yg=E(()=>{"use strict";Ht();C()});function Bo(){return(0,je.join)(N(),"state","hook-spool")}function Uo(t){if(t===null||typeof t!="object")return JSON.stringify(t)??"null";if(Array.isArray(t))return`[${t.map(Uo).join(",")}]`;let e=t;return`{${Object.keys(e).filter(n=>e[n]!==void 0).sort().map(n=>`${JSON.stringify(n)}:${Uo(e[n])}`).join(",")}}`}function tv(t,e){if(t==="summarize"&&e.turnId){let n=e;return(0,Lo.createHash)("sha256").update(Uo({contentSessionId:n.contentSessionId,platformSource:V(n.platformSource),turnId:n.turnId,lastAssistantMessage:n.lastAssistantMessage})).digest("hex")}let r=e.toolUseId;return typeof r=="string"&&Qg.test(r)?`${(0,Lo.createHash)("sha256").update(e.contentSessionId).update("\0").update(V(e.platformSource)).digest("hex")}-${r}`:(0,Lo.createHash)("sha256").update(t).update("\0").update(e.contentSessionId).update("\0").update(Uo(e)).digest("hex")}function Jg(t){return typeof t=="string"&&t.length>0}function eu(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(!qI.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"||!Jg(n.contentSessionId))return{corruptReason:"payload missing contentSessionId"};let s=r.kind;return(s==="observation"||s==="file_edit")&&!Jg(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:V(n.platformSource)},enqueuedAtEpochMs:r.enqueuedAtEpochMs}}function rv(){return tu=Math.max(Date.now(),tu+1),tu}var Lo,te,je,qI,JI,Qg,QI,ZI,qg,ev,tu,$o,ru=E(()=>{"use strict";Lo=require("crypto"),te=require("fs"),je=require("path");ne();C();gt();O();Yg();qI=["observation","file_edit","summarize","session_end","advisor_calls"],JI=/^[a-z_]+-[A-Za-z0-9_-]+\.json$/,Qg=/^[A-Za-z0-9_-]{1,128}$/,QI="corrupt",ZI="expired",qg=10080*60*1e3,ev=300*1e3;tu=0;$o=class{constructor(e=Bo()){this.directory=e}directory;get corruptDirectory(){return(0,je.join)(this.directory,QI)}get expiredDirectory(){return(0,je.join)(this.directory,ZI)}enqueue(e,r,n){let s={...r,platformSource:V(r.platformSource)},o=(0,je.join)(this.directory,`${e}-${tv(e,s)}.json`),i=s.toolUseId;if(typeof i=="string"&&Qg.test(i)){let c=(0,je.join)(this.directory,`${e}-${i}.json`);try{let u=eu((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??rv();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()-qg);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,ev,"unknown-session grace window")?a++:i++;continue}if(!h){this.expireIfPastWindow(u,qg,"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,je.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=eu((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,je.join)(this.directory,e);try{return(0,te.mkdirSync)(this.corruptDirectory,{recursive:!0}),(0,te.renameSync)(n,(0,je.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=>JI.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,je.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=eu(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 tm={};Ts(tm,{SPOOL_NUDGE_TIMEOUT_MS:()=>Zg,nudgeWorkerToDrainHookSpool:()=>em,settleHookSpoolNudges:()=>nv,spoolHookEvent:()=>He});function em(){if(On)return On;let t=(async()=>{try{await(await ue("/api/spool/nudge",{method:"POST",timeoutMs:Zg})).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 On=t,nu.add(t),t.finally(()=>{nu.delete(t),On===t&&(On=null)}),t}async function nv(){await Promise.all([...nu])}function He(t,e,r){let n=new $o().enqueue(t,e,r);return f.debug("HOOK","Hook event spooled for the worker",{kind:t,entryPath:n}),em(),n}var Zg,nu,On,Cr=E(()=>{"use strict";ru();Rt();O();Zg=250,nu=new Set,On=null});function su(t){let e=(t??"").trim();return e?e.slice(0,sv):null}function lv(t){let e=sr.default.resolve(t);for(let r=0;r<av;r++){let n=sr.default.join(e,".git");if((0,ht.existsSync)(n)){try{if((0,ht.statSync)(n).isDirectory())return n;let o=(0,ht.readFileSync)(n,"utf8").match(/^gitdir:\s*(.+)$/m);if(o)return sr.default.resolve(e,o[1].trim())}catch{return null}return null}let s=sr.default.dirname(e);if(s===e)return null;e=s}return null}function dv(t){let e=t.trim();if(e.startsWith(nm))return su(e.slice(nm.length));if(cv.test(e))return e.slice(0,uv)}function fv(t){let e=lv(t);if(!e)return null;try{return dv((0,ht.readFileSync)(sr.default.join(e,"HEAD"),"utf8"))}catch{return}}function pv(t){let e=Tr(t,["rev-parse","--abbrev-ref","HEAD"],rm);if(e.status!==0||!e.stdout)return null;if(e.stdout!=="HEAD")return su(e.stdout);let r=Tr(t,["rev-parse","--short","HEAD"],rm);return r.status===0?su(r.stdout):null}function sm(t,e=Date.now()){if(!t||!sr.default.isAbsolute(t))return null;let r=fv(t);if(r!==void 0)return r;let n=Wo.get(t);if(n&&e-n.at<ov)return n.branch;let s=pv(t);return Wo.size>=iv&&Wo.clear(),Wo.set(t,{at:e,branch:s}),s}var ht,sr,sv,ov,iv,rm,av,nm,cv,uv,Wo,om=E(()=>{"use strict";ht=require("fs"),sr=_e(require("path"),1);Zs();sv=255,ov=5e3,iv=200,rm=1e3,av=64,nm="ref: refs/heads/",cv=/^[0-9a-f]{40}([0-9a-f]{24})?$/,uv=7,Wo=new Map});function gv(t=K()){return t.MEMINDEX_BRANCH_MEMORY_ENABLED!=="false"&&t.MEMINDEX_SEND_BRANCH_TO_HOSTING!=="false"}function jo(t){if(!gv())return{};let e=sm(t);return e?{branch:e}:{}}var ou=E(()=>{"use strict";om();Qe();qe();C()});function Mt(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 pm(t,e){return!!t&&!!e}var gm=E(()=>{"use strict"});function yv(t){return new Set((t??"").split(",").map(e=>e.trim()).filter(Boolean))}function Fr(t,e,r){return pm(t,e)?r.MEMINDEX_SKIP_SUBAGENT_OBSERVATIONS==="true"?{skip:!0,reason:"subagent_observation"}:e&&yv(r.MEMINDEX_SKIP_AGENT_TYPES).has(e)?{skip:!0,reason:"agent_type_excluded"}:mm:mm}var mm,Xo=E(()=>{"use strict";gm();mm={skip:!1}});var h_,__=E(()=>{h_=(function(t){return 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",t})({})});var Ft,ll=E(()=>{Ft="1.10.0"});function AO(t){let e=new Set([t]),r=new Set,n=t.match(E_);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(E_);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 E_,S_,y_=E(()=>{ll();E_=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;S_=AO(Ft)});function MO(){return Object.defineProperty({},"version",{value:Ft,enumerable:!0,writable:!1,configurable:!1})}function Me(t,e,r,n=!1){var s;let o=xi[Pi]=(s=xi[Pi])!==null&&s!==void 0?s:MO();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!=="1.10.0"){let i=new Error(`@opentelemetry/api: Registration of version v${o.version} for ${t} does not match previously registered API v${Ft}`);return r.error(i.stack||i.message),!1}return o[t]=e,r.debug(`@opentelemetry/api: Registered a global for ${t} v${Ft}.`),!0}function pe(t){let e=xi[Pi];if(e!=null){if(e!==b_){if(!e.version||!S_(e.version))return;b_=e}return e[t]}}function Pe(t,e){e.debug(`@opentelemetry/api: Unregistering a global for ${t} v${Ft}.`);let r=xi[Pi];r&&delete r[t]}var OO,Pi,xi,b_,Lt=E(()=>{ll();y_();OO=Ft.split(".")[0],Pi=Symbol.for(`opentelemetry.js.api.${OO}`),xi=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{}});function cs(t,e,r){let n=pe("diag");if(n)return n[t](e,...r)}var w_,T_=E(()=>{Lt();w_=class{constructor(t){this._namespace=t.namespace||"DiagComponentLogger"}debug(...t){return cs("debug",this._namespace,t)}error(...t){return cs("error",this._namespace,t)}info(...t){return cs("info",this._namespace,t)}warn(...t){return cs("warn",this._namespace,t)}verbose(...t){return cs("verbose",this._namespace,t)}}});function I_(t,e){t<0?t=0:t>9999&&(t=9999),e=e||{};function r(n,s){let o=e[n];return typeof o=="function"&&t>=s?o.bind(e):function(){}}return{error:r("error",30),warn:r("warn",50),info:r("info",60),debug:r("debug",70),verbose:r("verbose",80)}}var v_=E(()=>{});var PO,Y,Ut=E(()=>{Lt();T_();v_();PO="diag",Y=class R_{static instance(){return this._instance||(this._instance=new R_),this._instance}constructor(){function e(s){return function(...o){let i=pe("diag");if(i)return i[s](...o)}}let r=this,n=(s,o={logLevel:60})=>{var i;if(s===r){var a;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((a=d.stack)!==null&&a!==void 0?a:d.message),!1}typeof o=="number"&&(o={logLevel:o});let c=pe("diag"),u=I_((i=o.logLevel)!==null&&i!==void 0?i:60,s);if(c&&!o.suppressOverrideMessage){var l;let d=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";c.warn(`Current logger will be overwritten from ${d}`),u.warn(`Current logger will overwrite one already registered from ${d}`)}return Me("diag",u,r,!0)};r.setLogger=n,r.disable=()=>{Pe(PO,r)},r.createComponentLogger=s=>new w_(s),r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error")}}});var A_,O_=E(()=>{A_=class us{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 us(this._entries);return n._entries.set(e,r),n}removeEntry(e){let r=new us(this._entries);return r._entries.delete(e),r}removeEntries(...e){let r=new us(this._entries);for(let n of e)r._entries.delete(n);return r}clear(){return new us}}});var M_,P_=E(()=>{M_=Symbol("BaggageEntryMetadata")});function x_(t={}){return new A_(new Map(Object.entries(t)))}function k_(t){return typeof t!="string"&&(xO.error(`Cannot create baggage metadata from unknown type: ${typeof t}`),t=""),{__TYPE__:M_,toString(){return t}}}var xO,dl=E(()=>{Ut();O_();P_();xO=Y.instance()});function qr(t){return Symbol.for(t)}var ki,ls=E(()=>{ki=new class fl{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 fl(r._currentContext);return o._currentContext.set(n,s),o},r.deleteValue=n=>{let s=new fl(r._currentContext);return s._currentContext.delete(n),s}}}});var pl,gl,N_,C_=E(()=>{pl=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}],gl={};if(typeof console<"u")for(let t of["error","warn","info","debug","trace","log"])typeof console[t]=="function"&&(gl[t]=console[t]);N_=class{constructor(){function t(e){return function(...r){let n=gl[e];if(typeof n!="function"&&(n=gl.log),typeof n!="function"&&console&&(n=console[e],typeof n!="function"&&(n=console.log)),typeof n=="function")return n.apply(console,r)}}for(let e=0;e<pl.length;e++)this[pl[e].n]=t(pl[e].c)}}});function D_(){return hl}var kO,Ni,NO,CO,DO,FO,ml,LO,UO,$O,hl,BO,WO,jO,HO,XO,KO,GO,_l=E(()=>{kO=class{constructor(){}createGauge(t,e){return WO}createHistogram(t,e){return jO}createCounter(t,e){return BO}createUpDownCounter(t,e){return HO}createObservableGauge(t,e){return KO}createObservableCounter(t,e){return XO}createObservableUpDownCounter(t,e){return GO}addBatchObservableCallback(t,e){}removeBatchObservableCallback(t){}},Ni=class{},NO=class extends Ni{add(t,e){}},CO=class extends Ni{add(t,e){}},DO=class extends Ni{record(t,e){}},FO=class extends Ni{record(t,e){}},ml=class{addCallback(t){}removeCallback(t){}},LO=class extends ml{},UO=class extends ml{},$O=class extends ml{},hl=new kO,BO=new NO,WO=new DO,jO=new FO,HO=new CO,XO=new LO,KO=new UO,GO=new $O});var F_,L_=E(()=>{F_=(function(t){return t[t.INT=0]="INT",t[t.DOUBLE=1]="DOUBLE",t})({})});function U_(){return Sl}var El,Sl,Ci=E(()=>{El=class{emit(t){}enabled(){return!1}},Sl=new El});var $_,B_=E(()=>{$_=(function(t){return t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.TRACE=1]="TRACE",t[t.TRACE2=2]="TRACE2",t[t.TRACE3=3]="TRACE3",t[t.TRACE4=4]="TRACE4",t[t.DEBUG=5]="DEBUG",t[t.DEBUG2=6]="DEBUG2",t[t.DEBUG3=7]="DEBUG3",t[t.DEBUG4=8]="DEBUG4",t[t.INFO=9]="INFO",t[t.INFO2=10]="INFO2",t[t.INFO3=11]="INFO3",t[t.INFO4=12]="INFO4",t[t.WARN=13]="WARN",t[t.WARN2=14]="WARN2",t[t.WARN3=15]="WARN3",t[t.WARN4=16]="WARN4",t[t.ERROR=17]="ERROR",t[t.ERROR2=18]="ERROR2",t[t.ERROR3=19]="ERROR3",t[t.ERROR4=20]="ERROR4",t[t.FATAL=21]="FATAL",t[t.FATAL2=22]="FATAL2",t[t.FATAL3=23]="FATAL3",t[t.FATAL4=24]="FATAL4",t})({})});var Di,Fi,yl=E(()=>{Di={get(t,e){if(t!=null)return t[e]},keys(t){return t==null?[]:Object.keys(t)}},Fi={set(t,e,r){t!=null&&(t[e]=r)}}});var W_,j_=E(()=>{W_=(function(t){return t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED",t})({})});var bl,wl,Li,Tl=E(()=>{bl="0000000000000000",wl="00000000000000000000000000000000",Li={traceId:wl,spanId:bl,traceFlags:0}});var $t,Ui=E(()=>{Tl();$t=class{constructor(t=Li){this._spanContext=t}spanContext(){return this._spanContext}setAttribute(t,e){return this}setAttributes(t){return this}addEvent(t,e){return this}addLink(t){return this}addLinks(t){return this}setStatus(t){return this}updateName(t){return this}end(t){}isRecording(){return!1}recordException(t,e){}}});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+=($i[t.charCodeAt(n)]|0)+($i[t.charCodeAt(n+1)]|0)+($i[t.charCodeAt(n+2)]|0)+($i[t.charCodeAt(n+3)]|0);return r===e}function Il(t){return H_(t,32)&&t!=="00000000000000000000000000000000"}function vl(t){return H_(t,16)&&t!=="0000000000000000"}function Jr(t){return Il(t.traceId)&&vl(t.spanId)}function X_(t){return new $t(t)}var $i,Bi=E(()=>{Ui();$i=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])});var K_,G_=E(()=>{ls();K_=class{active(){return ki}with(t,e,r,...n){return e.call(r,...n)}bind(t,e){return e}enable(){return this}disable(){return this}attach(t){return{dispose(){}}}}});var Rl,zO,VO,Bt,ds=E(()=>{Lt();Ut();G_();Rl="context",zO=new K_,VO=Object.freeze({dispose:()=>{}}),Bt=class z_{constructor(){this._attachUnsupportedWarned=!1}static getInstance(){return this._instance||(this._instance=new z_),this._instance}setGlobalContextManager(e){return Me(Rl,e,Y.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)}attach(e){let r=this._getContextManager();return r.attach?r.attach(e):(this._attachUnsupportedWarned||(this._attachUnsupportedWarned=!0,Y.instance().warn("The current ContextManager does not implement attach(). The context will not be attached. Use a ContextManager that supports attach() (e.g. AsyncLocalStorageContextManager) or use with()/bind() instead.")),VO)}_getContextManager(){return pe(Rl)||zO}disable(){this._getContextManager().disable(),Pe(Rl,Y.instance())}}});function Wi(t){return t.getValue(Al)||void 0}function V_(){return Wi(Bt.getInstance().active())}function fs(t,e){return t.setValue(Al,e)}function Y_(t){return t.deleteValue(Al)}function q_(t,e){return fs(t,new $t(e))}function ji(t){var e;return(e=Wi(t))===null||e===void 0?void 0:e.spanContext()}var Al,Ol=E(()=>{ls();ds();Ui();Al=qr("OpenTelemetry Context Key SPAN")});function YO(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 Ml,Hi,Pl=E(()=>{ds();Ui();Ol();Bi();Ml=Bt.getInstance(),Hi=class{startSpan(t,e,r=Ml.active()){if(e?.root)return new $t;let n=r&&ji(r);return YO(n)&&Jr(n)?new $t(n):new $t}startActiveSpan(t,e,r,n){var s;let o,i,a;if(arguments.length<2)return;arguments.length===2?a=e:arguments.length===3?(o=e,a=r):(o=e,i=r,a=n);let c=(s=i)!==null&&s!==void 0?s:Ml.active(),u=this.startSpan(t,o,c),l=fs(c,u);return Ml.with(l,a,void 0,u)}}});var qO,Xi,xl=E(()=>{Pl();qO=new Hi,Xi=class{constructor(t,e,r,n){this._provider=t,this.name=e,this.version=r,this.options=n}startSpan(t,e,r){return this._getTracer().startSpan(t,e,r)}startActiveSpan(t,e,r,n){let s=this._getTracer();return Reflect.apply(s.startActiveSpan,s,arguments)}_getTracer(){if(this._delegate)return this._delegate;let t=this._provider.getDelegateTracer(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):qO}}});var J_,Q_=E(()=>{J_=(function(t){return 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",t})({})});var Z_,eE=E(()=>{Z_=(function(t){return t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR",t})({})});function tE(t){return JO.test(t)}function rE(t){return QO.test(t)&&!ZO.test(t)}var kl,JO,QO,ZO,nE=E(()=>{kl="[_0-9a-z-*/]",JO=new RegExp(`^(?:${`[a-z]${kl}{0,255}`}|${`[a-z0-9]${kl}{0,240}@[a-z]${kl}{0,13}`})$`),QO=/^[ -~]{0,255}[!-~]$/,ZO=/,|=/});var Nl,sE,oE,iE,aE,uE=E(()=>{nE();Nl=32,sE=512,oE=",",iE="=",aE=class cE{constructor(e){this._internalState=new Map,e&&this._parse(e)}set(e,r){let n=this._internalState.get(e),s=this.serialize().length;if(typeof n=="string")s+=r.length-n.length;else{if(this._internalState.size>=Nl)return this;s+=e.length+r.length+(this._internalState.size>0?2:1)}if(s>sE)return this;let o=this._clone();return o._internalState.has(e)&&o._internalState.delete(e),o._internalState.set(e,r),o}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+iE+this.get(r)),e),[]).join(oE)}_parse(e){e.length>sE||(this._internalState=e.split(oE).reduceRight((r,n)=>{let s=n.trim(),o=s.indexOf(iE);if(o!==-1){let i=s.slice(0,o),a=s.slice(o+1,n.length);tE(i)&&rE(a)&&r.set(i,a)}return r},new Map),this._internalState.size>Nl&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,Nl))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let e=new cE;return e._internalState=new Map(this._internalState),e}}});function lE(t){return new aE(t)}var dE=E(()=>{uE()});var fE,pE=E(()=>{Pl();fE=class{getTracer(t,e,r){return new Hi}}});var eM,ps,Cl=E(()=>{xl();pE();eM=new fE,ps=class{getTracer(t,e,r){var n;return(n=this.getDelegateTracer(t,e,r))!==null&&n!==void 0?n:new Xi(this,t,e,r)}getDelegate(){var t;return(t=this._delegate)!==null&&t!==void 0?t:eM}setDelegate(t){this._delegate=t}getDelegateTracer(t,e,r){var n;return(n=this._delegate)===null||n===void 0?void 0:n.getTracer(t,e,r)}}});var gE,mE=E(()=>{gE=(function(t){return t[t.NOT_RECORD=0]="NOT_RECORD",t[t.RECORD=1]="RECORD",t[t.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED",t})({})});var Dl,hE=E(()=>{ds();Dl=Bt.getInstance()});var Fl,_E=E(()=>{Ut();Fl=Y.instance()});var tM,EE,SE=E(()=>{Ci();tM=class{getLogger(t,e,r){return new El}},EE=new tM});var yE,bE=E(()=>{Ci();yE=class{constructor(t,e,r,n){this._provider=t,this.name=e,this.version=r,this.options=n}emit(t){this._getLogger().emit(t)}enabled(t){return this._getLogger().enabled(t)}_getLogger(){if(this._delegate)return this._delegate;let t=this._provider._getDelegateLogger(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):Sl}}});var Ll,wE=E(()=>{SE();bE();Ll=class{getLogger(t,e,r){var n;return(n=this._getDelegateLogger(t,e,r))!==null&&n!==void 0?n:new yE(this,t,e,r)}_getDelegate(){var t;return(t=this._delegate)!==null&&t!==void 0?t:EE}_setDelegate(t){this._delegate=t}_getDelegateLogger(t,e,r){var n;return(n=this._delegate)===null||n===void 0?void 0:n.getLogger(t,e,r)}}});var Ul,TE,vE=E(()=>{Lt();Ut();wE();Ul="logs",TE=class IE{constructor(){this._proxyLoggerProvider=new Ll}static getInstance(){return this._instance||(this._instance=new IE),this._instance}setGlobalLoggerProvider(e){let r=Me(Ul,e,Y.instance());return r&&this._proxyLoggerProvider._setDelegate(e),r}getLoggerProvider(){return pe(Ul)||this._proxyLoggerProvider}getLogger(e,r,n){return this.getLoggerProvider().getLogger(e,r,n)}disable(){Pe(Ul,Y.instance()),this._proxyLoggerProvider=new Ll}}});var $l,RE=E(()=>{vE();$l=TE.getInstance()});var rM,AE,OE=E(()=>{_l();rM=class{getMeter(t,e,r){return hl}},AE=new rM});var Bl,ME,xE=E(()=>{Lt();Ut();OE();Bl="metrics",ME=class PE{constructor(){}static getInstance(){return this._instance||(this._instance=new PE),this._instance}setGlobalMeterProvider(e){return Me(Bl,e,Y.instance())}getMeterProvider(){return pe(Bl)||AE}getMeter(e,r,n){return this.getMeterProvider().getMeter(e,r,n)}disable(){Pe(Bl,Y.instance())}}});var Wl,kE=E(()=>{xE();Wl=ME.getInstance()});var NE,CE=E(()=>{NE=class{inject(t,e){}extract(t,e){return t}fields(){return[]}}});function Hl(t){return t.getValue(jl)||void 0}function DE(){return Hl(Bt.getInstance().active())}function FE(t,e){return t.setValue(jl,e)}function LE(t){return t.deleteValue(jl)}var jl,UE=E(()=>{ls();ds();jl=qr("OpenTelemetry Baggage Key")});var Xl,nM,$E,WE=E(()=>{Lt();Ut();dl();yl();CE();UE();Xl="propagation",nM=new NE,$E=class BE{constructor(){this.createBaggage=x_,this.getBaggage=Hl,this.getActiveBaggage=DE,this.setBaggage=FE,this.deleteBaggage=LE}static getInstance(){return this._instance||(this._instance=new BE),this._instance}setGlobalPropagator(e){return Me(Xl,e,Y.instance())}inject(e,r,n=Fi){return this._getGlobalPropagator().inject(e,r,n)}extract(e,r,n=Di){return this._getGlobalPropagator().extract(e,r,n)}fields(){return this._getGlobalPropagator().fields()}disable(){Pe(Xl,Y.instance())}_getGlobalPropagator(){return pe(Xl)||nM}}});var Kl,jE=E(()=>{WE();Kl=$E.getInstance()});var Gl,HE,KE=E(()=>{Lt();Ut();Ol();Bi();Cl();Gl="trace",HE=class XE{constructor(){this._proxyTracerProvider=new ps,this.wrapSpanContext=X_,this.isSpanContextValid=Jr,this.deleteSpan=Y_,this.getSpan=Wi,this.getActiveSpan=V_,this.getSpanContext=ji,this.setSpan=fs,this.setSpanContext=q_}static getInstance(){return this._instance||(this._instance=new XE),this._instance}setGlobalTracerProvider(e){let r=Me(Gl,this._proxyTracerProvider,Y.instance());return r&&this._proxyTracerProvider.setDelegate(e),r}getTracerProvider(){return pe(Gl)||this._proxyTracerProvider}getTracer(e,r){return this.getTracerProvider().getTracer(e,r)}disable(){Pe(Gl,Y.instance()),this._proxyTracerProvider=new ps}}});var zl,GE=E(()=>{KE();zl=HE.getInstance()});var zE={};Ts(zE,{DiagConsoleLogger:()=>N_,DiagLogLevel:()=>h_,INVALID_SPANID:()=>bl,INVALID_SPAN_CONTEXT:()=>Li,INVALID_TRACEID:()=>wl,ProxyTracer:()=>Xi,ProxyTracerProvider:()=>ps,ROOT_CONTEXT:()=>ki,SamplingDecision:()=>gE,SeverityNumber:()=>$_,SpanKind:()=>J_,SpanStatusCode:()=>Z_,TraceFlags:()=>W_,ValueType:()=>F_,baggageEntryMetadataFromString:()=>k_,context:()=>Dl,createContextKey:()=>qr,createNoopLogger:()=>U_,createNoopMeter:()=>D_,createTraceState:()=>lE,default:()=>sM,defaultTextMapGetter:()=>Di,defaultTextMapSetter:()=>Fi,diag:()=>Fl,isSpanContextValid:()=>Jr,isValidSpanId:()=>vl,isValidTraceId:()=>Il,logs:()=>$l,metrics:()=>Wl,propagation:()=>Kl,trace:()=>zl});var sM,VE=E(()=>{__();dl();ls();C_();_l();L_();Ci();B_();yl();j_();Tl();Bi();xl();Q_();eE();dE();Cl();mE();hE();_E();RE();kE();jE();GE();sM={context:Dl,diag:Fl,logs:$l,metrics:Wl,propagation:Kl,trace:zl}});function mS(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 Zr(t){if(!t)return!1;if(t.startsWith("memory_")||t==="mem_search"||t==="get_summaries")return!0;let e=mS(t);return e!==null&&qM.has(e)}function ra(t){return t==="save_memory"||mS(t)==="save_memory"}var qM,na=E(()=>{"use strict";qM=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 nd(t){return typeof t=="string"&&t.length>0}var ys,xS=E(()=>{"use strict";ys=class extends Error{constructor(r){super(`adapter rejected input: ${r}`);this.reason=r;this.name="AdapterRejectedInput"}reason}});var mP,kS,sd,hP,_P,NS,CS=E(()=>{"use strict";xS();Qt();mP=128,kS=t=>typeof t=="string"&&t.length>0&&t.length<=mP?t:void 0,sd=t=>typeof t=="string"?t:void 0,hP=t=>t.hook_event_name==="PostToolUseFailure"?{error:t.error,is_interrupt:t.is_interrupt===!0}:void 0,_P=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},NS={normalizeInput(t){let e=t??{},r=e.cwd??process.cwd();if(!nd(r))throw new ys("invalid_cwd");let n=Zf(r);if(!nd(n))throw new ys("invalid_cwd");let s=e.source;return{sessionId:e.session_id??e.id??e.sessionId,hookEventName:sd(e.hook_event_name),cwd:n,sessionSource:s==="startup"||s==="resume"||s==="clear"||s==="compact"?s:void 0,prompt:e.prompt,submittedPrompt:_P(e),toolName:e.tool_name,toolInput:e.tool_input,toolResponse:e.tool_response??hP(e),toolUseId:typeof e.tool_use_id=="string"?e.tool_use_id:void 0,transcriptPath:e.transcript_path,lastAssistantMessage:sd(e.last_assistant_message),reason:sd(e.reason),agentId:kS(e.agent_id),agentType:kS(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 DS(t,e){return He("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 FS,LS=E(()=>{"use strict";Cr();O();Xc();ke();Pr();Xo();Qe();ou();Mn();gt();xr();nr();An();na();FS={async execute(t){let{sessionId:e,cwd:r,toolName:n,toolInput:s,toolResponse:o}=t,i=V(t.platform);if(!n)return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};if(Zr(n))return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};let a=Ug(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(!rt(r))return f.debug("HOOK","Project excluded from tracking, skipping observation",{cwd:r,toolName:n}),{continue:!0,suppressOutput:!0};let c=Fr(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(ra(n))return DS(t,i);let u=$e();if(u.runtime==="server"){if(Mt(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: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},...jo(r)};try{return await u.client.recordEvent(l),f.debug("HOOK","Observation sent successfully via server",{toolName:n}),await kr(u.client,We(u)),{continue:!0,suppressOutput:!0}}catch(d){if(mt(d))return Be(d.kind,{status:d.status,message:d.message,route:"/v1/events",held:!0}),Ot({op:"event",request:l},We(u)),{continue:!0,suppressOutput:!0};if(Ue(d)&&d.isFallbackEligible())Be(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 DS(t,i)}}});function yP(t,e,r){let n=0;for(;n<e.length;){let s=(0,Ge.readSync)(t,e,n,e.length-n,r+n);if(s===0)break;n+=s}return n}function*bP(t,e){let r=Math.max(1,e.maxChunkBytes??US),n=Math.min(r,Math.max(1,e.initialBytes??EP)),s=(0,Ge.openSync)(t,"r");try{let o=(0,Ge.fstatSync)(s).size,i=Buffer.alloc(0);for(;o>0;){let a=Math.max(0,o-n),c=Buffer.alloc(o-a),u=yP(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,Ge.closeSync)(s)}}function $S(t,e,r={}){if(!t||!(0,Ge.existsSync)(t)){f.warn("PARSER",`Transcript path missing or file does not exist: ${t}`);return}let n=!1;for(let s of bP(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*od(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 wP(t,e,r,n,s){let o,i=null,a,c,u=!1,l=0,d=Math.max(0,s?.modelSearchBudgetBytes??SP),p=$S(t,(g,m,h)=>{if(s?.includeTurnId&&!u)for(let b of od(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=jS(g)),o===void 0){let b=OP(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 id(t,e=!1,r){let n=wP(t,"assistant",e,!0,r);return{text:n.text,...n.model===void 0?{}:{model:n.model},...n.turnId===void 0?{}:{turnId:n.turnId}}}function BS(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 vP(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 RP(t,e){if(e==="user"&&t?.type==="context.append_message")return BS(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 AP(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 OP(t,e,r){let n=!1,s=null,o="blank";for(let i of od(t)){let a=vP(i),c=typeof i.type=="string"?TP[i.type]:void 0,u=typeof i.type=="string"?IP[i.type]:void 0;if((a??c??u??i.type??i.role)!==e)continue;n=!0;let d,p;if(a!==void 0)d=RP(i,e);else if(u!==void 0)d=typeof i.data?.content=="string"?i.data.content:"";else{if(p=c!==void 0?i.content:i.message?.content,p==null)continue;let g=BS(p);if(g===null)continue;d=g}if(r&&(d=d.replace(xo,""),d=d.replace(/\n{3,}/g,`
14
+ `)}else ut(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){ba=e}error(e,r,n,s){this.log(3,e,r,n,s),this.routeErrorToSink(r,n,s)}routeErrorToSink(e,r,n){try{if(!ba||!(n instanceof Error))return;ba(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 Ta});function Cd(t){try{return new URL(t).hostname.toLowerCase()==="openrouter.ai"}catch{return!1}}var Dd=E(()=>{"use strict";O()});function zt(t){let e=(0,Se.resolve)(t),r=[],n=e;for(;;)try{return(0,Se.join)(Fd.realpathSync.native(n),...r.reverse())}catch{let s=(0,Se.dirname)(n);if(s===n)return e;r.push((0,Se.basename)(n)),n=s}}function ab(t,e){return zt(t)===zt(e)}function cb(t,e){let r=zt(e);return t===r||t.startsWith(r.endsWith(Se.sep)?r:r+Se.sep)}function ub(t,e=(0,dt.homedir)()){let r=zt(t),n=zt(e);return(process.platform==="win32"?[(0,dt.tmpdir)()]:[(0,dt.tmpdir)(),...ib]).some(o=>zt(o)!==n&&cb(r,o))}function cn(t=process.env,e=(0,dt.homedir)()){return t.MEMINDEX_TEST_FORBIDDEN_DATA_DIR?!0:ub(on(t,e),e)}function $d(t){return(0,Ia.createHash)("sha256").update(Se.win32.resolve(t).toLowerCase()).digest().readUInt32BE(0)%lb}function va(t=process.platform,e=(0,dt.homedir)()){return t==="win32"?Ud+$d(e):38700+(process.getuid?.()??77)%100}function Ra(t=process.platform,e=(0,dt.homedir)()){return t==="win32"?Ud+db+$d(e):38877+(process.getuid?.()??77)%100}function Aa(t){let e=(0,Ia.createHash)("sha256").update(zt(t)).digest();return sb+e.readUInt32BE(0)%ob}function Bd(t=process.env,e=(0,dt.homedir)()){return cn(t,e)?Aa(on(t,e)):va(process.platform,e)}function jd(t,e){return typeof t!="string"||t.length===0?"unknown":ab(t,e)?"same":"foreign"}var Ia,Fd,dt,Se,sb,ob,ib,Ld,Ud,lb,db,Oa=E(()=>{"use strict";Ia=require("crypto"),Fd=require("fs"),dt=require("os"),Se=require("path");Sa();sb=4e4,ob=9e3,ib=["/tmp","/private/tmp","/var/folders","/private/var/folders"],Ld="60";Ud=39e3,lb=500,db=500});function pb(t){return typeof t=="boolean"?String(t):t}function gb(t){let e=t.MEMINDEX_OPENROUTER_MODEL;if(typeof e!="string"||!fb.has(e.trim()))return!1;let r=typeof t.MEMINDEX_OPENROUTER_BASE_URL=="string"?t.MEMINDEX_OPENROUTER_BASE_URL.trim():"";return r===""||Cd(r)}function Kd(t,e){return(0,Tt.join)((0,Tt.dirname)(t),`.${(0,Tt.basename)(t)}.${e.markerTag}`)}function Ma(t,e){try{(0,Vt.writeFileSync)(Kd(t,e),new Date().toISOString(),{encoding:"utf-8",mode:384})}catch{}}var Vt,Tt,un,fb,Wd,Hd,Xd,z,qe=E(()=>{"use strict";Vt=require("fs"),Tt=require("path"),un=require("os");Ye();re();Dd();sn();Ms();Oa();fb=new Set(["xiaomi/mimo-v2-flash:free"]);Wd=18e4,Hd=[{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"}];Xd=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(Bd()),MEMINDEX_WORKER_HOST:"127.0.0.1",MEMINDEX_ALLOWED_ORIGINS:"",MEMINDEX_PUBLIC_URL:"",MEMINDEX_API_TIMEOUT_MS:String(wt(ne.API_REQUEST)),MEMINDEX_SESSION_INIT_TIMEOUT_MS:String(an()),MEMINDEX_IDLE_EXIT_SEC:cn()?Ld:"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_PROVIDER_BY_SOURCE:"",MEMINDEX_OBSERVER_ENABLED:"true",MEMINDEX_DISABLE_SUMMARY:"false",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,Tt.join)((0,un.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_BRANCH_MEMORY_ENABLED:"true",MEMINDEX_SEND_BRANCH_TO_HOSTING:"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,Tt.join)((0,un.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,un.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(Wd),MEMINDEX_LLM_STREAM_IDLE_TIMEOUT_MS:"90000",MEMINDEX_FIELD_OPTIMIZE_TIMEOUT_MS:String(Wd),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(Ra())}`,MEMINDEX_SERVER_API_KEY:"",MEMINDEX_SERVER_PROJECT_ID:"",MEMINDEX_SERVER_BETA_URL:`http://127.0.0.1:${process.env.MEMINDEX_SERVER_PORT??String(Ra())}`,MEMINDEX_SERVER_BETA_API_KEY:"",MEMINDEX_SERVER_BETA_PROJECT_ID:"",MEMINDEX_JIRA_BASE_URL:"",MEMINDEX_JIRA_EMAIL:"",MEMINDEX_JIRA_API_TOKEN:"",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,Vt.existsSync)(e)){let p=this.getAllDefaults();if(!n.readOnly)try{U(e,p,{mode:384});for(let g of Hd)Ma(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,Vt.readFileSync)(e,"utf-8"),o=Kt(s),i=Er(o),a=i!==o,c=As(i),u=Id(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(gb(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 Hd)if(!(0,Vt.existsSync)(Kd(e,p))){if(c[p.key]!==p.legacy){n.readOnly||Ma(e,p);continue}if(c={...c,[p.key]:this.DEFAULTS[p.key]},!n.readOnly)try{U(e,l?{...u,env:c}:c,{mode:384}),Ma(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}`;Xd.has(m)||(Xd.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]=pb(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 Ca(t=C()){let e=(0,$.openSync)((0,Cs.join)(t,sf),$.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(!wb.test(n))throw new Error("Invalid worker secret");return n}finally{(0,$.closeSync)(e)}}function of(t=C()){(0,$.mkdirSync)(t,{recursive:!0,mode:448});let e=(0,Cs.join)(t,sf);try{return Ca(t)}catch(s){if(s.code!=="ENOENT")throw s}let r=(0,Cs.join)(t,`.worker-secret-${(0,Na.randomBytes)(16).toString("hex")}`),n=(0,$.openSync)(r,"wx",384);try{(0,$.fchmodSync)(n,384),(0,$.writeFileSync)(n,(0,Na.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 Ca(t)}function br(t,e=C()){let r=(t.method??"GET").toUpperCase(),n=r==="GET"||r==="HEAD",s=new Headers(t.headers);if(n)try{s.set(nf,Ca(e))}catch{return t}else s.set(nf,of(e));return{...t,headers:s,redirect:"error"}}var Na,$,Cs,nf,sf,wb,Da=E(()=>{"use strict";Na=require("node:crypto"),$=require("node:fs"),Cs=require("node:path");N();nf="X-Memindex-Secret",sf="worker-secret",wb=/^[a-f0-9]{64}$/});async function*Ib(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 vb(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*uf(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 Fa(r)},g=m=>{if(m.length===0){let R=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,R}if(m[0]===Tb)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 Ib(t)){let h=0;for(let _=0;_<m.length;_++){let S=m[_];if(i&&(i=!1,S===cf)){h=_+1;continue}if(S!==af&&S!==cf)continue;s.push(m.subarray(h,_));let b=vb(s,o+(_-h));s=[],o=0;let w=g(b);w&&(e.terminalEventNames?.includes(w.event)&&(d=!0),yield w),i=S===af,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 La(e.terminalEventNames)}var Fa,La,af,cf,Tb,lf=E(()=>{"use strict";Fa=class extends Error{constructor(r){super(`SSE event exceeded ${r} bytes`);this.maxEventBytes=r;this.name="SseEventTooLargeError"}maxEventBytes},La=class extends Error{constructor(r){super(`SSE stream ended before a terminal event (${r.join(", ")})`);this.terminalEventNames=r;this.name="StreamEndedEarlyError"}terminalEventNames},af=13,cf=10,Tb=58});function K(){return Ds!==null||(Ds=z.loadFromFile(ae)),Ds}var Ds,Ze=E(()=>{"use strict";qe();N();Ds=null});function Fs(t){return(t.MEMINDEX_WORKER_AUTOSTART??"true").trim().toLowerCase()==="false"}var df=E(()=>{"use strict"});var ff=E(()=>{"use strict"});function Ua(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}var $a=E(()=>{"use strict"});function ja(t,e,r){return(0,Ba.spawn)(t,e??[],{...r,windowsHide:!0})}var Ba,Rb,Ab,zk,Wa=E(()=>{"use strict";Ba=require("node:child_process");Rb=new Set([".cmd",".bat"]),Ab=new Set([".exe",".com"]),zk=new Set([...Ab,...Rb])});function ft(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(xb.has(r)){e[r]=n;continue}Mb.has(r)||Ob.some(s=>r.startsWith(s))||(e[r]=n)}return e}var Ob,Mb,Pb,xb,pn=E(()=>{"use strict";Ob=["CLAUDECODE_","CLAUDE_CODE_"],Mb=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),Pb=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"]),xb=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_TMPDIR","CLAUDE_CODE_PATH","CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS","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",...Pb])});function mf(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 Nb(t){Ha+=1;let e=(0,Xa.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:{...ft(process.env),LC_ALL:"C",LANG:"C"}});return mf("powershell-cim",t,e)}function Cb(t,e=!1){if(!e){let n=pf.get(t);if(n&&(t===process.pid||Date.now()-n.capturedAtMs<kb))return n.token}let r=null;try{r=Nb(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)&&pf.set(t,{token:r,capturedAtMs:Date.now()}),r}function hf(t,e){if(!Number.isInteger(t)||t<=0)return null;if(process.platform==="linux"){Ha+=1;try{let r=(0,gf.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 Cb(t,e);Ha+=1;try{let r=(0,Xa.spawnSync)("ps",["-p",String(t),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...ft(process.env),LC_ALL:"C",LANG:"C"}});return mf("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 Qe(t){return hf(t,!1)}function De(t,e){if(e===null)return!0;let r=hf(t,!0);return r===null?!0:r===e}var Xa,gf,kb,pf,Ha,Ls=E(()=>{"use strict";Xa=require("child_process"),gf=require("fs");O();pn();kb=5e3,pf=new Map,Ha=0});async function we(t,e={}){let r=e.signalMode==="immediate",n=e.expectedStartToken!==void 0?e.expectedStartToken:Qe(t),s=()=>De(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 Ka("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===Db||Fb.test(`${a} ${c}`)){f.debug("PROCESS","taskkill reported the process was already gone",{pid:t});return}throw new Us(t,`taskkill failed for PID ${t} (exit ${String(i)}): ${a.trim()||c}`,{cause:o})}return}try{let o=r?"SIGKILL":"SIGTERM",i=await $s(t);for(let u of i){if(!De(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 $s(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(!De(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 Us(t,`tree-kill failed for PID ${t}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}}async function Lb(){return process.platform==="win32"?Bb():process.platform==="linux"?Ub():$b()}function Ub(){let t=[],e;try{e=(0,Bs.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,Bs.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 $b(){let t;try{t=(await Ka("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 Bb(){let t;try{t=(await Ka("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 $s(t){let e=await Lb(),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 _f,Bs,Ef,Ka,Db,Fb,Us,wr=E(()=>{"use strict";_f=require("child_process"),Bs=require("fs"),Ef=require("util");O();Ls();Ka=(0,Ef.promisify)(_f.execFile),Db=128,Fb=/not found|no running instance|no tasks/i,Us=class extends Error{pid;constructor(e,r,n){super(r,n),this.name="ProcessTreeKillError",this.pid=e}}});function q(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 js(t,e){let r=Date.now()+e;for(;Date.now()<r;){if(t.every(n=>!q(n.pid)))return;await new Promise(n=>setTimeout(n,100))}}function yf(t){if(!t||!q(t.pid))return!1;if(!t.startToken)return!0;let e=Qe(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 Ws(t,e=Gb){if(!yf(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=>Sf.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 pt(t=G.workerPid()){if(!(0,qt.existsSync)(t))return null;let e;try{e=JSON.parse((0,qt.readFileSync)(t,"utf-8"))}catch{return null}return e!==null&&Ws(e)?e:null}function Hs(){return Ga||(Ga=new Va),Ga}function za(){let t=zb.shift();t&&t.notify()}var qt,Sf,Wb,Hb,Xb,Kb,Gb,Va,Ga,f0,zb,gt=E(()=>{"use strict";Wa();qt=require("fs"),Sf=_e(require("path"),1);O();re();pn();N();Ls();wr();Wb=5e3,Hb=1e3,Xb=G.supervisorRegistry(),Kb=null;Gb={platform:process.platform,readCommandLine:t=>(0,qt.readFileSync)(`/proc/${t}/cmdline`,"utf-8")};Va=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;persistDegraded=!1;constructor(e=Xb){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,!(0,qt.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,qt.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||!q(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"&&za())}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)q(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)za();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=>q(a.pid)),o=new Map(s.map(a=>[a.pid,Qe(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 js(s,Wb);let i=s.filter(a=>q(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(!De(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()+Hb;for(;Date.now()<a&&i.filter(u=>q(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"&&za();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{Kb?.({errorCategory:r.code??"unknown"})}catch{}}},Ga=null;f0=180*1e3,zb=[]});async function wf(t){let e=t.currentPid??process.pid,r=t.pidFilePath??Vb,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(!q(c.pid)){t.registry.unregister(c.id);continue}i.set(c.id,Qe(c.pid)),o.set(c.id,await $s(c.pid));try{await bf(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 js(s,5e3);let a=s.filter(c=>q(c.pid)||(o.get(c.id)??[]).some(u=>q(u.pid)));for(let c of a){let u=De(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 bf(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{Yb(o.get(c.id)??[],c.pid)}}await js(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);Tf(r,e),t.registry.pruneDeadEntries()}function Tf(t,e,r=!1){if(!(0,Tr.existsSync)(t))return;let n=null;try{let i=JSON.parse((0,Tr.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||!q(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,Tr.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 Yb(t,e){for(let{pid:r,startToken:n}of t)if(!(r===e||!q(r))){if(!De(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 bf(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 Tr,Vb,Ya=E(()=>{"use strict";Tr=require("fs");O();gt();N();wr();Vb=G.workerPid()});function qb(){let e=Hs().pruneDeadEntries();e>0&&f.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function vf(){Ir===null&&(Ir=setInterval(qb,If),Ir.unref(),f.debug("SYSTEM","Health checker started",{intervalMs:If}))}function Rf(){Ir!==null&&(clearInterval(Ir),Ir=null,f.debug("SYSTEM","Health checker stopped"))}var If,Ir,Af=E(()=>{"use strict";O();gt();If=3e4,Ir=null});function Qb(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 ew(){let t=await Jb("ps",["-eo","pid=,ppid=,command="],{timeout:1e4,maxBuffer:33554432});return Qb(t.stdout)}function tw(t,e){let r=t.filter(i=>Zb.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 Pf(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??ew,s=t.isAlive??q,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}=tw(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 Of,Mf,Jb,Zb,xf=E(()=>{"use strict";Of=require("child_process"),Mf=require("util");O();wr();gt();Jb=(0,Mf.promisify)(Of.execFile),Zb=/(?:^|\/)(?:uvx|uv|python[\d.]*)(?:\s|$).*chroma-mcp/});function kf(t={}){let e=t.pidFilePath??rw;if(!(0,Jt.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,Jt.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,Jt.rmSync)(e,{force:!0}),"invalid"}return Ws(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,Jt.rmSync)(e,{force:!0})),"stale")}var Jt,rw,qa,k0,gn=E(()=>{"use strict";Jt=require("fs");O();gt();Ya();Af();xf();N();gt();rw=G.workerPid(),qa=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(),kf({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,Pf({registry:this.registry}).catch(r=>{f.warn("PROCESS","Orphaned chroma-mcp sweep failed",{error:r instanceof Error?r.message:String(r)})}),vf()}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}Rf(),this.stopPromise=wf({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}},k0=new qa(Hs())});function Nf(t,e){if(!(0,Xs.existsSync)(t))return e;try{return Kt((0,Xs.readFileSync)(t,"utf-8"))}catch(r){throw new Error(`Corrupt JSON file, refusing to overwrite: ${t}: ${r instanceof Error?r.message:String(r)}`)}}var Xs,Cf=E(()=>{"use strict";Xs=require("fs");re()});function nw(t){let e=t.DO_NOT_TRACK;return e===void 0||e===""?!1:e!=="0"&&e!=="false"}function sw(t,e){if(nw(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 Gs(t,e){return sw(t,e).enabled}function Lf(t){let e=t.MEMINDEX_TELEMETRY_ERRORS?.toLowerCase();return!(e==="0"||e==="false"||e==="off")}function ow(){return(0,Ja.join)(C(),Ff)}function mn(){let t;try{t=Nf(ow(),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 iw(t){let e=C();(0,Ks.mkdirSync)(e,{recursive:!0}),(0,Ks.writeFileSync)((0,Ja.join)(e,Ff),JSON.stringify(t,null,2)+`
19
+ `)}function zs(){let t=mn();if(t?.installId)return t.installId;let e=(0,Df.randomUUID)();return iw({installId:e,decidedAt:""}),e}var Ja,Ks,Df,Ff,Za=E(()=>{"use strict";Ja=require("path"),Ks=require("fs"),Df=require("crypto");N();Cf();O();Ff="telemetry.json"});function jf(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>$f?e.slice(0,$f):e}catch{return""}}function Qa(t){if(typeof t!="string"||t.length===0)return t??"";let e="";try{e=Bf.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 ec(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 aw(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 cw(t){return typeof t!="string"||t.length===0?t??"":t.replace(/\?[^\s"'()]*/g,"")}function uw(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 lw(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 dw(t){return typeof t!="string"||t.length===0?t??"":t.replace(/[ \t\f\v]+/g," ").replace(/ *\n */g,`
20
+ `).trim()}function tc(t){let e=jf(t);return e.length===0?"":(e=Qa(e),e=aw(e),e=ec(e),e=cw(e),e=uw(e),e=lw(e),e)}function Wf(t){try{let e=dw(tc(jf(t)));return e.length>Uf?e.slice(0,Uf):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 Hf(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 Bf,Uf,$f,Te,rc=E(()=>{"use strict";Bf=_e(require("os"),1);O();Uf=500,$f=8192,Te="[REDACTED]"});function pw(t,e){if(!(!t||typeof t!="object"))for(let r of Object.keys(t)){if(!fw.has(r))continue;let n=t[r];if(typeof n=="string"){let s=n.length>Xf?n.slice(0,Xf):n;e[r]=tc(s)}else(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean")&&(e[r]=n)}}function Vs(t){let e={};try{pw(t,e)}catch{}return e}var fw,Xf,nc=E(()=>{"use strict";rc();fw=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"]),Xf=200});function Ys(){return process.env.MEMINDEX_TELEMETRY_KEY??""}function qs(){return process.env.MEMINDEX_TELEMETRY_HOST||mw}function Js(t){let e={};for(let r of hw)t[r]!==void 0&&(e[r]=t[r]);return e}function _w(){if(process.platform!=="linux")return!1;try{return!!process.env.WSL_DISTRO_NAME||sc.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 Zs(){return{version:gw,os:process.platform,os_version:sc.default.release(),is_wsl:_w(),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 sc,gw,mw,hw,oc=E(()=>{"use strict";sc=_e(require("os"),1);O();gw="1.4.0",mw="https://us.i.posthog.com";hw=["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 Kf(t,e,r){try{if(!Gs(process.env,mn()))return;let n=Vs({...Zs(),...e??{}});if(r?.person?n.$set=Js(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=Ys(),o=new AbortController,i=setTimeout(()=>o.abort(),Ew);try{await Sw(s,t,n,o.signal)}finally{clearTimeout(i)}}catch{}}async function Sw(t,e,r,n){await fetch(`${qs()}/capture/`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:t,event:e,distinct_id:zs(),properties:r}),signal:n})}var Ew,Gf=E(()=>{"use strict";Za();nc();oc();Ew=2e3});var zf=E(()=>{"use strict";O()});var Vf=E(()=>{"use strict";O();zf()});function hn(t){return t.error?.name==="ETIMEDOUT"}function _n(t,e,r=Yf){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,Qs.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 vr(t,e,r=Yf){let n=(0,Qs.spawnSync)("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:Math.min(r,yw),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 Qs,Yf,yw,eo=E(()=>{"use strict";Qs=require("child_process");O();Yf=5e3,yw=5e3});function qf(t){let e=It.default.join(t,".git"),r;try{r=(0,to.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,to.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=It.default.resolve(It.default.dirname(e),s[1]),i=o.match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(i){let c=i[1];return{isWorktree:!0,isSubmodule:!1,worktreeName:It.default.basename(t),parentRepoPath:c,parentProjectName:It.default.basename(c)}}let a=o.match(/^(.+)[/\\]\.git[/\\]modules[/\\](.+)$/);if(a){let c=a[1];return{isWorktree:!1,isSubmodule:!0,worktreeName:It.default.basename(t),parentRepoPath:c,parentProjectName:It.default.basename(c)}}return En}var to,It,En,Jf=E(()=>{"use strict";to=require("fs"),It=_e(require("path"),1);O();En={isWorktree:!1,isSubmodule:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null}});function Zf(t){let e=Ee(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 ac(t,e){if(!e.length)return!1;let r=t.replace(/\\/g,"/"),n=(0,ic.basename)(r);for(let s of e){let o=s.trim();if(o)try{let i=Zf(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 ro(t,e){if(!e||!e.trim())return!1;let r=t.replace(/\\/g,"/"),n=(0,ic.basename)(r),s=e.split(",").map(o=>o.trim()).filter(Boolean);for(let o of s)try{let i=Zf(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 ic,Sn=E(()=>{"use strict";ic=require("path");Xt();O()});function ep(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 bw(t){try{return(0,Qf.realpathSync)(t)}catch{return t}}function cc(t,e){if(e.length===0)return null;let r=[...new Set([t,bw(t)])].flatMap(n=>[n,`${n.replace(/[\\/]+$/,"")}/`]);for(let n of e)if(r.some(s=>ac(s,n.patterns)))return n.name;return null}var Qf,tp=E(()=>{"use strict";Qf=require("fs");Sn();O()});function sp(t){let e=process.env[ww]?.trim();return e||(!t||t.trim()===""?null:t)}function op(t){return ip(t,vr(t,["rev-parse","--show-toplevel"]))}async function vw(t){let e=Date.now(),r=Rr.get(t);if(r&&e-r.at<Tw)return(await r.answer).root;Rr.size>=Iw&&Rr.clear();let n=_n(t,["rev-parse","--show-toplevel"]).then(a=>({root:ip(t,a),kept:!hn(a)})),s={at:e,answer:n};Rr.set(t,s);let{root:o,kept:i}=await n;return!i&&Rr.get(t)===s&&Rr.delete(t),o}function ip(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 ap(t){try{return(0,Or.realpathSync)(t)}catch{return t}}function Ow(t,e){let r=ue.default.relative(e,t);return r===""||!r.startsWith("..")&&!ue.default.isAbsolute(r)}function Mw(){return[(0,oo.homedir)(),(0,oo.tmpdir)(),Ne].flatMap(t=>{let e=ue.default.resolve(t);return[e,ap(e)]})}function cp(t){let e=Mw(),r=ue.default.resolve(t);if([ue.default.resolve(Ne),ap(ue.default.resolve(Ne))].some(s=>Ow(r,s)))return null;for(let s=0;s<Aw;s++){if(e.includes(r))return null;let o=ue.default.dirname(r);if(o===r)return null;if(Rw.some(i=>(0,Or.existsSync)(ue.default.join(r,i))))return r;r=o}return null}function uc(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}),lc}return r}function rp(){try{return(0,Or.statSync)(ae).mtimeMs}catch{return-1}}function up(){let t=rp();if(t===-1)return z.getAllDefaults();if(no&&no.mtimeMs===t)return no.settings;let e=z.loadFromFile(ae);return no={mtimeMs:rp(),settings:e},e}function lp(){let t=process.env[Pw]??up().MEMINDEX_PROJECT_NAME_SOURCE;return String(t??"path").trim().toLowerCase()==="git-remote"}function dp(){let t=process.env[xw]??up().MEMINDEX_PROJECT_ENVIRONMENTS;return(!so||so.raw!==t)&&(so={raw:t,environments:ep(t)}),so.environments}function kw(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 fp(t,e){return e.status===0&&e.stdout?kw(e.stdout):(f.debug("PROJECT_NAME","No usable origin remote, keeping the path-based name",{repoRoot:t},e.error),null)}function pp(t){return lp()?(Ar.has(t)||Ar.set(t,fp(t,vr(t,["remote","get-url","origin"]))),Ar.get(t)??null):null}async function Nw(t){if(!lp())return null;if(!Ar.has(t)){let e=await _n(t,["remote","get-url","origin"]);if(hn(e))return null;Ar.set(t,fp(t,e))}return Ar.get(t)??null}function Cw(t,e=process.platform){if(!t||t.trim()==="")return f.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),lc;let r=Ee(t,e),n=cc(r,dp());if(n)return n;let s=op(r),o=s?pp(s):null;if(o)return o;let i=s??cp(r)??r;return uc(t,i)}function gp(t,e){return e===t?t:`${t}/${e}`}function Dw(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 io(t,e=process.platform){if(!t||t.trim()==="")return mp(t,e);let r=Ee(t,e),n=op(r),s=n?pp(n):null;return hp(t,r,n,s)}async function yn(t,e=process.platform){if(!t||t.trim()==="")return mp(t,e);let r=Ee(t,e),n=await vw(r),s=n?await Nw(n):null;return hp(t,r,n,s)}function mp(t,e){let r=Cw(t,e);return{primary:r,parent:null,isWorktree:!1,isSubmodule:!1,allProjects:[r],keySource:"path"}}function hp(t,e,r,n){let s=Fw(t,e,r),o=n?np(s,n,"git-remote"):s,i=cc(e,dp());return i?np(o,i,"environment"):o}function np(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 Fw(t,e,r){let n=r?null:cp(e),s=uc(t,r??n??e),o=r??e,i=qf(o);if((i.isWorktree||i.isSubmodule)&&i.parentProjectName){let a=i.parentProjectName,c,u;return i.isSubmodule?(c=`${a}/${Dw(i,o)??s}`,u=s!==a?[s]:[]):(c=gp(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=uc(t,e);if(a!==s&&a!==lc)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,Or,oo,ww,lc,Tw,Iw,Rr,Rw,Aw,Pw,no,xw,so,Ar,Zt=E(()=>{"use strict";ue=_e(require("path"),1),Or=require("fs"),oo=require("os");Xt();N();qe();O();eo();Jf();tp();ww="CLAUDE_PROJECT_DIR",lc="unknown-project";Tw=3e4,Iw=500,Rr=new Map;Rw=[".memindex-project",".memindex.json"],Aw=64;Pw="MEMINDEX_PROJECT_NAME_SOURCE",no=null;xw="MEMINDEX_PROJECT_ENVIRONMENTS",so=null;Ar=new Map});function $w(t){try{return(0,ye.realpathSync)(t)}catch{return null}}function dc(t){return t?/(^|[\\/])bun(\.exe)?$/i.test(t.trim()):!1}function Bw(t,e){let r=e==="win32"?"where.exe":"which",n=[t],s;try{s=(0,gc.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 ao(t={}){let e=Object.keys(t).length===0;if(e&&fc!==void 0)return fc;let r=jw(t);return e&&r!==null&&(fc=r),r}function _p(t,e){let r=t?.trim();return r?e==="win32"?[me.default.join(r,"bin","bun.exe"),me.default.join(r,"bin","bun"),me.default.join(r,"bun.exe")]:[me.default.join(r,"bin","bun"),me.default.join(r,"bun")]:[]}function jw(t){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(dc(r))return r;let n=t.env??process.env,s=t.homeDirectory??(0,pc.homedir)(),o=t.pathExists??ye.existsSync,i=t.lookupInPath??Bw,a=t.realpath??$w,c=e==="win32"?[n.BUN,n.BUN_PATH,..._p(n.BUN_INSTALL,e),me.default.join(s,".bun","bin","bun.exe"),me.default.join(s,".bun","bin","bun"),n.USERPROFILE?me.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?me.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?me.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0,n.npm_config_prefix?me.default.join(n.npm_config_prefix,"bun.exe"):void 0]:[n.BUN,n.BUN_PATH,..._p(n.BUN_INSTALL,e),me.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?me.default.join(n.npm_config_prefix,"bin","bun"):void 0];for(let d of c){let p=d?.trim();if(p&&(dc(p)&&o(p)||p.toLowerCase()==="bun"))return p}let u=i("bun",e)?.trim();if(!u||!dc(u))return null;let l=a(u)??u;return o(l)?l:null}function Ww(){let t=G.dataDir();return(0,ye.mkdirSync)(t,{recursive:!0}),t}function Hw(t,e,r,n=process.platform,s=(0,ye.existsSync)(Ep)){let o=n!=="win32"&&s;return{command:o?Ep:t,args:o?[t,e,"--daemon"]:[e,"--daemon"],options:{detached:!0,stdio:"ignore",cwd:Ww(),env:r}}}function co(t,e,r,n=process.platform){let{command:s,args:o,options:i}=Hw(t,e,r,n),a=ja(s,o,i);if(a.on("error",c=>{f.error("SYSTEM",Uw,{runtimePath:t,execPath:s},c)}),a.pid!==void 0)return a.unref(),a.pid}var me,pc,ye,gc,CN,DN,Uw,fc,Ep,mc=E(()=>{"use strict";me=_e(require("path"),1),pc=require("os"),ye=require("fs"),gc=require("child_process");Wa();O();pn();Ya();gn();Vf();Zt();eo();N();gt();CN=G.dataDir(),DN=G.workerPid(),Uw="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.";Ep="/usr/bin/setsid"});function Sp(t){let e=t?.code;return e==="EACCES"||e==="EADDRNOTAVAIL"}var hc,_c=E(()=>{"use strict";hc="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 Ec(){return z.loadFromFile(ae).MEMINDEX_WORKER_HOST}function bp(t){return t.startsWith("[")&&t.endsWith("]")?t:t.includes(":")?`[${t}]`:t}async function wp(t,e,r="GET",n=Qt){let s={method:r,signal:AbortSignal.timeout(Math.max(1,n))},o=await fetch(`http://${bp(Ec())}:${t}${e}`,r==="GET"||r==="HEAD"?s:br(s)),i="";try{i=await o.text()}catch{}return{ok:o.ok,statusCode:o.status,body:i}}async function Tp(t,e=Qt){let r=Date.now()+e;if(process.platform==="win32")try{let s=await fetch(`http://${bp(Ec())}:${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 uo(t,Math.max(1,r-Date.now()));return n==="occupied"||n==="indeterminate"}async function uo(t,e=Qt){return(await Xw(t,e)).occupancy}function Xw(t,e=Qt){return e<=0?Promise.resolve({occupancy:"indeterminate"}):new Promise(r=>{let n=!1,s=!1,o=!1,i;try{i=yp.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"}):Sp(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,Ec())}catch{try{i.close()}catch{}u({occupancy:"indeterminate"})}})}async function Kw(t,e,r,n){let s=Date.now()+r;for(;Date.now()<s;){try{let i=s-Date.now();if((await wp(t,e,"GET",Math.min(Qt,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 Ip(t,e=3e4){return Kw(t,"/api/health",e,"Service not ready yet, will retry")}async function Gw(t,e=Qt){try{let r=await wp(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 vp(t,e,r=Qt){let n=e??"unknown",s=await Gw(t,r);return!s||n==="unknown"?{matches:!0,pluginVersion:n,workerVersion:s}:{matches:n===s,pluginVersion:n,workerVersion:s}}var yp,Qt,lo=E(()=>{"use strict";yp=_e(require("net"),1);O();qe();N();_c();Da();Qt=5e3});var Rp=E(()=>{"use strict";O();gn()});var Ap=E(()=>{"use strict";mc();lo();Rp()});function Pp(){return(0,fo.join)(C(),"spawn.lock")}function Op(t){try{let e=JSON.parse((0,se.readFileSync)(t,"utf-8"));return typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0?null:e.pid}catch{return null}}function zw(t){if(t===null)return null;try{return process.kill(t,0),!0}catch(e){return e?.code==="EPERM"}}function po(){let t=Pp(),e=JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()});for(let r=0;r<2;r++)try{return(0,se.mkdirSync)((0,fo.dirname)(t),{recursive:!0}),(0,se.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,se.statSync)(t).mtimeMs}catch{continue}let a=Op(t),c=null;if(a===null)try{c=(0,se.readFileSync)(t,"utf-8")}catch{continue}if(Date.now()-i<=Mp&&zw(a)!==!1)return!1;let l;try{l=(0,se.statSync)(t).mtimeMs}catch{continue}if(l!==i)return!1;if(a!==null){if(Op(t)!==a)return!1}else try{if((0,se.readFileSync)(t,"utf-8")!==c)return!1}catch{continue}try{(0,se.unlinkSync)(t)}catch{return!1}}return!1}function bn(){let t=Pp();try{if(JSON.parse((0,se.readFileSync)(t,"utf-8")).pid!==process.pid)return;(0,se.unlinkSync)(t)}catch{}}var fo,se,Mp,tC,xp=E(()=>{"use strict";fo=require("path"),se=require("fs");N();O();Mp=9e4,tC=Mp/3});function kp(t){return Vw.test(t.trim())}function Yw(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 mo(t,e){return e===void 0?t:Math.max(1,Math.min(t,e))}async function qw(t){try{let e=await go("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:mo(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 Jw(t,e){try{let r=await go("netstat",["-ano"],{timeout:mo(15e3,e),windowsHide:!0,maxBuffer:16777216});return tT(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 Zw(t,e){try{let r=await go("lsof",["-nP",`-iTCP:${t}`,"-sTCP:LISTEN","-t"],{timeout:mo(1e4,e),maxBuffer:1048576});return Qw(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 Qw(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 eT(t,e){try{let n=(await go("ps",["-p",String(t),"-o","command="],{timeout:mo(5e3,e)})).stdout.trim();return n.length>0?n:null}catch{return null}}function tT(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 nT(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(Lp),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||!rT.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 sT(t,e,r,n){let s=Qe(t),o=e?(await r(n))?.find(i=>i.pid===t)?.cmdline??null:await eT(t,n);return De(t,s)?{startToken:s,cmdline:o}:{startToken:null,cmdline:null}}async function Up(t,e={}){let r=e.isWin32??(()=>process.platform==="win32"),n=e.now??Date.now,s=e.deadlineAt??null,o=T=>s!==null&&s-n()<T,i=()=>s===null?void 0:Math.max(1,s-n());if(o(Np))return f.info("PROCESS","Port reclaim skipped: not enough of the hook budget is left to finish one",{port:t,remainingMs:i(),neededMs:Np}),{reclaimed:!1,reason:"out-of-budget",killedPids:[]};let a=e.listOwners??((T,P)=>r()?Jw(T,P):Zw(T,P)),c=T=>a(T,i()),u=e.readTable??qw,l=()=>u(i()),d=e.killTree??((T,P)=>we(T,P)),p=e.dataDir??(()=>j),g=e.readIdentity??((T,P)=>sT(T,r(),u,P)),m=await nT(t,{listOwners:c,killTree:d,readOwnedWorker:e.readOwnedWorker??pt,probeHealth:e.probeHealth??(T=>Ip(T,Fp)),readIdentity:T=>g(T,i()),minOwnerAgeSeconds:e.minOwnerAgeSeconds??xd(),now:n,sleep:e.sleep??(T=>new Promise(P=>setTimeout(P,T))),hasKillBudget:()=>!o(Sc)});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(T=>q(T)).length>0)return{reclaimed:!1,reason:"owner-alive",killedPids:[]};let b=new Map;for(let T of _){let P=b.get(T.ppid);P?P.push(T):b.set(T.ppid,[T])}let w=new Map,R=new Set,v=T=>{for(let P of b.get(T)??[])R.has(P.pid)||(R.add(P.pid),v(P.pid),kp(P.name)&&w.set(P.pid,P))};for(let T of h)v(T);let y=p();if(y)for(let T of _)w.has(T.pid)||kp(T.name)&&Yw(T.cmdline,y)&&w.set(T.pid,T);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:y??"(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(T=>({pid:T.pid,name:T.name}))});let I=[];for(let T of w.values()){if(o(Sc))return f.info("PROCESS","Ghost-listener reclaim stopped before a kill: the hook budget is spent",{port:t,killedPids:I}),{reclaimed:!1,reason:"out-of-budget",killedPids:I};try{await d(T.pid,{expectedStartToken:T.startToken,signalMode:"immediate"}),I.push(T.pid)}catch(P){return f.error("PROCESS","Ghost-port reclaim tree-kill failed",{port:t,pid:T.pid},P instanceof Error?P:new Error(String(P))),{reclaimed:!1,reason:"kill-failed",killedPids:I}}}let A=await c(t);return A!==null&&A.length===0?(f.info("PROCESS","Ghost listener reclaimed \u2014 port is free again",{port:t,killedPids:I}),{reclaimed:!0,killedPids:I}):(f.warn("PROCESS","Ghost-port reclaim killed the sidecar chain but the port is still bound",{port:t,killedPids:I,stillOwnedBy:A}),{reclaimed:!1,reason:"still-bound",killedPids:I})}var Cp,Dp,go,Vw,rT,Fp,Lp,Sc,Np,$p=E(()=>{"use strict";Cp=require("node:child_process"),Dp=require("node:util");O();wr();gt();gn();lo();Ls();Ye();N();go=(0,Dp.promisify)(Cp.execFile),Vw=/^(uv|uvx|python|chroma-mcp)(\.exe)?$/i;rT=/worker-service/i,Fp=1500,Lp=1e3,Sc=5500,Np=2*Fp+Lp+Sc});function Bp(t){try{return(0,Mr.realpathSync)(t)}catch{return t}}function iT(t,e){let r=vt.default.relative(e,t);return r!==""&&!r.startsWith("..")&&!vt.default.isAbsolute(r)}function Wp(t){let e;try{let s=JSON.parse((0,Mr.readFileSync)(vt.default.join(t,"package.json"),"utf-8"));e=Object.keys(s?.dependencies??{})}catch{return[]}if(e.length===0)return[];let r=vt.default.join(t,"node_modules"),n=e.filter(s=>!(0,Mr.existsSync)(vt.default.join(r,...s.split("/"),"package.json")));if(e.includes("zod")&&!n.includes("zod")){let s=(0,jp.createRequire)(vt.default.join(r,"noop.js")),o=Bp(vt.default.join(r,"zod"));for(let i of oT)try{let a=s.resolve(i,{paths:[r]});iT(Bp(a),o)||n.push(i)}catch{n.push(i)}}return n}var Mr,jp,vt,oT,Hp=E(()=>{"use strict";Mr=require("fs"),jp=require("module"),vt=_e(require("path"),1),oT=["zod/v3","zod/v4","zod/v4-mini"]});function Gp(){return ho.default.join(C(),"worker-standby.json")}function wc(){return ho.default.join(C(),"worker-standby-attempt.json")}function Tc(){return ho.default.join(C(),"worker-standby-failure.json")}function Ic(t){try{return JSON.parse((0,_o.readFileSync)(t,"utf-8"))}catch{return null}}function vc(t){try{(0,_o.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 Eo(){let t=Ic(Gp());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 So(t){if(t!==void 0){let e=Eo();if(e!==null&&e.pid!==t)return}vc(Gp())}function aT(){let t=Ic(Tc());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 zp(t,e,r=new Date){try{U(Tc(),{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 Vp(){vc(Tc())}function Yp(t,e=Date.now()){if(t===null)return null;let r=aT();if(r===null||r.buildKey!==t)return null;let n=Date.parse(r.failedAt);return!Number.isFinite(n)||e-n>=bc?null:r}function qp(){let t=Ic(wc());return!t||typeof t.buildKey!="string"||typeof t.launchedAtMs!="number"||!Number.isFinite(t.launchedAtMs)?null:{buildKey:t.buildKey,launchedAtMs:t.launchedAtMs}}function Jp(t){try{U(wc(),t)}catch(e){f.debug("SYSTEM","Could not save the worker update attempt",{error:e instanceof Error?e.message:String(e)})}}function Zp(){vc(wc())}var ho,_o,Xp,yc,Kp,bc,Qp=E(()=>{"use strict";ho=_e(require("path"),1),_o=require("fs");N();re();O();Xp="MEMINDEX_WORKER_STANDBY",yc=12e4,Kp=2e4,bc=10*6e4});function Pc(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 fg(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 dT(t){return fg()?{...t,verbose:!0}:t}function fT(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 pT(t,e,r){let n=typeof e.method=="string"?e.method:"GET",s=fT(r),o=JSON.stringify(s);f.warn("SYSTEM","Worker IPC fetch failed",{url:t,method:n},o),ut(`[memindex] fetch verbose: ${n} ${t} ${o}
22
+ `)}async function kc(t,e={}){let r=dT(e);try{return await fetch(t,r)}catch(n){throw fg()&&pT(t,e,n),n}}async function In(t,e={},r){try{return await kc(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 gT(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 pg(t,e,r){let n=gT(r,e.signal),s;try{s=await kc(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 mT(t,e,r){let n=await pg(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 eg(){return L.default.join(z.get("MEMINDEX_DATA_DIR"),"settings.json")}function Nc(t={}){return t.readOnly?z.loadFromFile(eg(),!0,t):(yo!==null||(yo=z.loadFromFile(eg())),yo)}function tg(t,e){if(!t)return null;let r=parseInt(t,10);return Number.isFinite(r)&&r>=e.min&&r<=e.max?r:null}function gg(t,e,r){let n=process.env[t];if(n!==void 0){let i=tg(n,r);return i!==null?i:(f.warn("SYSTEM",`Invalid ${t}, using default`,{value:n,min:r.min,max:r.max}),e)}let s=Nc()[t],o=tg(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 oe(t={}){if(!t.readOnly&&Rc!==null)return Rc;let e=parseInt(Nc(t).MEMINDEX_WORKER_PORT,10),r=e===va()&&cn()?Aa(C()):e;return t.readOnly||(Rc=r),r}function Cc(t={}){if(!t.readOnly&&Ac!==null)return Ac;let e=Nc(t).MEMINDEX_WORKER_HOST;return t.readOnly||(Ac=e),e}function hT(){return bo!==null||(bo=gg("MEMINDEX_API_TIMEOUT_MS",wt(ne.API_REQUEST),uT)),bo}function mg(){return wo!==null||(wo=Math.min(gg("MEMINDEX_SESSION_INIT_TIMEOUT_MS",an(),lT),kd())),wo}function hg(t){return t===null?null:Math.max(0,t-Date.now())}function vo(t){let e=hg(t);return e!==null&&e<xc}function Fe(t,e){let r=hg(e);return r===null?t:Math.max(1,Math.min(t,r))}function _g(t){return`http://${Ua(Cc())}:${oe()}${t}`}function _T(t){let e=t.split("?")[0].toLowerCase().replace(/\/+$/,"");return e==="/api/health"||e==="/api/readiness"}function le(t,e={}){let r=e.method??"GET",n=_g(t),s={method:r};e.headers&&(s.headers=e.headers),e.body&&(s.body=e.body);let o=_T(t)?s:br(s);if(e.idleTimeoutMs!==void 0&&e.idleTimeoutMs>0)return mT(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??hT();return i>0?In(n,o,i):kc(n,o)}async function ET(t){return(await le("/api/health",{timeoutMs:t})).ok}async function rg(t=et){return(await le("/api/readiness",{timeoutMs:t})).ok}function Eg(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 ST(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 yT(t=L.default.join(L.default.dirname(L.default.dirname(Sr)),"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:Eg(e),version:L.default.basename(e)}))}catch{return[]}}function ng(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 bT(){return{cacheRoot:L.default.join(L.default.dirname(L.default.dirname(Sr)),"cache","memindex","memindex"),marketplaceRoot:Sr,cwd:process.cwd()}}function Dc(t=bT()){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=[...yT(t.cacheRoot),{scriptPath:Eg(L.default.join(t.marketplaceRoot,"plugin")),version:ng(L.default.join(t.marketplaceRoot,"package.json"))},{scriptPath:L.default.join(t.cwd,"plugin","scripts","worker-service.cjs"),version:ng(L.default.join(t.cwd,"package.json"))}];return IT(r)}function wT(t){return L.default.dirname(L.default.dirname(t))}function TT(t){return Wp(wT(t.scriptPath)).length===0}function IT(t,e=TT){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:ST(n.version,s.version)),r.find(e)??r[0])}function vT(){return Dc()?.scriptPath??null}async function RT(t){let e=t.deadlineAt??null,r=t.backoffMs;for(let n=1;n<=t.attempts;n++){if(vo(e))return!1;if(await Ag(e??Number.POSITIVE_INFINITY))return!0;n<t.attempts&&(await new Promise(s=>setTimeout(s,Fe(r,e))),r*=2)}return!1}function sg(t){return t instanceof Error&&/^Request timed out after \d+ms idle$/.test(t.message)}function og(t){return t instanceof Error&&/^Request timed out after \d+ms$/.test(t.message)}async function AT(t){let e;try{e=await pg(_g("/api/ready"),br({method:"GET"}),{idleTimeoutMs:cT,absoluteCapMs:Math.max(1,t)})}catch(o){return sg(o)?{outcome:"unresponsive",detail:"no response headers within the idle window"}:og(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 Ro(),await r(),{outcome:"unsupported"};let s=null;try{for await(let o of uf(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 Ro(),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 og(o)?(Ro(),{outcome:"still_booting",detail:`last phase ${s??"none"}`}):sg(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 OT(t){if(t<=0)try{return await rg()?{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 rg(Math.max(1,Math.min(et,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 tr(t=Pr){let e=t>0?t:et,r=await AT(e);return r.outcome==="ready"&&DT(),r.outcome!=="unsupported"?r:(f.debug("SYSTEM","Worker has no /api/ready stream; falling back to /api/readiness"),OT(t))}async function MT(t=et){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 PT(t=5e3){let e=Date.now()+t;for(;;){let r=e-Date.now();if(r<=0)return!1;if(await uo(oe(),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 Sg(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 yg(){return L.default.join(C(),"worker-version-recycle.json")}function xT(t,e){if(t===null||e===null)return!1;try{let r=JSON.parse((0,x.readFileSync)(yg(),"utf-8"));return r?.buildKey===t&&r?.workerVersion===e}catch{return!1}}async function ig(t,e=null,r=et){let n=await MT(r);if(n!==null&&n!==t){if(e!==null)try{U(yg(),{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 Fc(){return L.default.join(C(),"worker-unresponsive.json")}function kT(){try{let t=JSON.parse((0,x.readFileSync)(Fc(),"utf-8"));return typeof t?.pid!="number"||typeof t?.firstUnresponsiveAtEpochMs!="number"?null:{pid:t.pid,firstUnresponsiveAtEpochMs:t.firstUnresponsiveAtEpochMs}}catch{return null}}function Ro(){let t=Fc();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 NT(t=Date.now()){let e=pt()?.pid??null;if(e===null)return!1;let r=kT();if(r!==null&&r.pid===e)return t-r.firstUnresponsiveAtEpochMs>=bg;try{U(Fc(),{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 Lc(){return L.default.join(C(),"worker-never-ready-recycle.json")}function CT(){try{let t=JSON.parse((0,x.readFileSync)(Lc(),"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 wg(t){try{U(Lc(),t)}catch(e){f.warn("SYSTEM","Could not persist the never-ready worker recycle",{error:e instanceof Error?e.message:String(e)})}}function DT(){let t=Lc();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 Tg(t){return Sg(t,t?.version??"unknown")??"unresolved-worker-bundle"}function Ig(t){return t.outcome==="failed"?t.detail??"unknown init failure":t.outcome}function vg(t,e){if(t.outcome==="unresponsive"&&!NT())return f.warn("SYSTEM","Worker went silent on /api/ready; skipping this hook without killing it",{detail:t.detail,wedgedAfterMs:bg}),!1;let r=Ig(t),n=CT();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(C(),"logs")}),wg({...n,refusalLogged:!0})),!1):!0}function Rg(t,e){wg({buildKey:e,failureMessage:Ig(t)}),Ro()}async function Ag(t=Number.POSITIVE_INFINITY){let e=t-Date.now();if(e<=0)return!1;let r;try{r=await ET(Math.min(et,e))}catch(n){return f.debug("SYSTEM","Worker health check threw",{error:n instanceof Error?n.message:String(n)}),!1}return r}async function Uc(t,e){let r=pt();if(r===null||r.port!==oe())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:oe(),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 PT(Fe(5e3,t))?!0:(e("stale port release")||(rr=oe(),f.error("SYSTEM","Stale worker port still open after SIGKILL; skipping spawn this hook event",{pid:r.pid,port:oe(),fix:Ao})),!1)}function Og(t,e){return`http://127.0.0.1:${t}${e}`}async function Mg(t,e){if(e<=0)return{answered:!1,version:null};try{let n=await(await In(Og(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 Pg(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)})}So(t.pid)}async function FT(t,e,r,n){let s=await LT(t,e,r,n);return s.kind!=="out-of-budget"&&Zp(),s}async function LT(t,e,r,n){let s=Eo(),o=s===null?null:await Mg(s,Fe(et,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)Pg(s);else{let d=Date.parse(s.startedAt);if((Number.isFinite(d)?Date.now()-d:Number.POSITIVE_INFINITY)<yc&&q(s.pid)){let g=Math.min(d+yc,Math.max(d+wn,Date.now()+2e3)),m=await Oc(e,g,n,i);return m.kind==="failed"&&So(s.pid),m}So(s.pid)}let a=r===null?null:qp();if(a!==null&&a.buildKey===r)return Date.now()-a.launchedAtMs>=wn?i:Oc(e,a.launchedAtMs+wn,n,i);let c=ao();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=co(c,t,ft({...process.env,MEMINDEX_WORKER_PORT:String(oe()),[Xp]:"1"}),process.platform)}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&&Jp({buildKey:r,launchedAtMs:l}),Oc(e,l+wn,n,i)}async function Oc(t,e,r,n){let s=Math.min(e,r??Number.POSITIVE_INFINITY);for(;Date.now()<s;){let o=Eo();if(o!==null){let a=await Mg(o,Math.min(1e3,s-Date.now()));if(a.answered)return a.version===t?{kind:"ready",record:o}:(Pg(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 UT(t,e){try{let r=await In(Og(t.port,"/api/admin/promote"),br({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 $T(t){let{scriptPath:e,pluginVersion:r,workerVersion:n,buildKey:s,deadlineAt:o,outOfBudget:i}=t,a=n??"unknown",c=Yp(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=pt();if(u===null||u.port!==oe())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:oe(),pidFilePid:u?.pid??null,pidFilePort:u?.port??null}),"failed";if(!po())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 FT(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&&zp(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(bc/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 Uc(o,i))return"failed";l=!0;let p=await UT(d.record,Fe(1e4,o));return p===null?(Vp(),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 xr(t){let e=t===void 0?null:Date.now()+t,r=S=>vo(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:Fe(et,e),s=Math.min(Date.now()+5e3,e??Number.POSITIVE_INFINITY),o=Dc(),i=null,a=null,c=!1,u=!1,l=!1,d=null,p=null,g=Fs(K());if(r("health probe"))return!1;if(await Ag(s)){if(r("version probe"))return!1;let{matches:S,pluginVersion:b,workerVersion:w}=await vp(oe(),o?.version??null,n());if(b!=="unknown"&&(i=b),S){if(r("readiness wait"))return!1;let R=await tr(Fe(Pr,e));if(R.outcome==="ready")return i!==null&&!vo(e)&&await ig(i,null,n()),!0;if(R.outcome==="still_booting"||R.outcome==="not_running")return f.warn("SYSTEM","Worker is healthy but not ready yet; skipping hook API call",{outcome:R.outcome,detail:R.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:R.outcome,detail:R.detail}),!1;if(p=Tg(o),!vg(R,p))return!1;d=R,f.info("SYSTEM","Worker will never become ready \u2014 recycling wedged worker",{outcome:R.outcome,detail:R.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 tr(Fe(Pr,e))).outcome==="ready";if(a=Sg(o,b),xT(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 tr(Fe(Pr,e))).outcome==="ready";f.info("SYSTEM","Worker version changed \u2014 starting the new worker before stopping the old one",{pluginVersion:b,workerVersion:w});let R=await $T({scriptPath:o?.scriptPath??null,pluginVersion:b,workerVersion:w,buildKey:a,deadlineAt:e,outOfBudget:r});if(R==="failed")return!1;if(R==="kept-old")return r("readiness wait")?!1:(await tr(Fe(Pr,e))).outcome==="ready";u=!0,l=R==="promoted"}if(!u&&!await Uc(e,r))return!1;d!==null&&p!==null&&Rg(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||po();try{if(h&&!l){if(!c&&!await BT(s,e))return!1;let b=ao();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(co(b,m,ft({...process.env,MEMINDEX_WORKER_PORT:String(oe())}),process.platform)===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 RT({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)"),pt()===null&&await Tp(oe(),e===null?void 0:Fe(5e3,e))&&(rr=oe(),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:rr,fix:Ao}))),!1}finally{h&&bn()}if(r("readiness wait"))return!1;let _=await tr(Fe(Pr,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&&!vo(e)&&await ig(i,a,n()),!0)}async function BT(t,e){let r=oe(),n=t-Date.now();if(n<=0)return!1;let s=await uo(r,n);if(s==="free")return!0;if(s==="unbindable")return Mc=r,f.error("SYSTEM","Worker port cannot be bound (EACCES or EADDRNOTAVAIL) \u2014 skipping lazy-spawn",{port:r,host:Cc(),fix:hc}),!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 Up(r,{deadlineAt:e});return o.reclaimed?(f.info("SYSTEM","Reclaimed the worker port before lazy-spawn",{port:r,killedPids:o.killedPids}),!0):(pt()===null&&(rr=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,...rr===r?{fix:Ao}:{}}),!1)}async function jT(t){if(er!==void 0)return er;try{let r=await(await le("/api/health",{timeoutMs:t})).json();er=jd(r.dataDir,C())==="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)}),er=null}return er!==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:er,dataDir:C(),port:oe()}),er}async function WT(t){return To!==null||(To=await xr(t)),To}async function HT(t){let e=Date.now()+t,r=()=>e-Date.now(),n=u=>r()>=xc?!1:(f.debug("SYSTEM","Bounded worker startup ran out of budget",{step:u,budgetMs:t}),!0),s=await tr(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(!!Fs(K()))return ag(e);let i=ao(),a=vT();if(!i||!a)return!1;if(s.outcome==="failed"||s.outcome==="wedged"||s.outcome==="unresponsive"){let u=Tg(Dc());if(!vg(s,u)||(f.info("SYSTEM","Worker will never become ready \u2014 recycling wedged worker",{outcome:s.outcome,detail:s.detail}),!await Uc(e,n)))return!1;Rg(s,u)}let c=po();try{return c&&co(i,a,ft({...process.env,MEMINDEX_WORKER_PORT:String(oe())}),process.platform)===void 0?!1:await ag(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 ag(t){for(;t-Date.now()>0;){let e=await tr(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 Oo(){return L.default.join(j,"state")}function Cg(){return L.default.join(Oo(),"hook-failures.json")}function Dg(){return L.default.join(Oo(),"hook-failures.lock")}async function $c(t=kg){let e=Oo(),r=Dg(),n=(0,dg.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>Ng){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,KT))}return f.warn("SYSTEM","Timed out waiting for hook-failure lock; skipping failure-state update",{lockPath:r,waitMs:t}),null}function Bc(t){let e=Dg();try{if(JSON.parse((0,x.readFileSync)(e,"utf-8")).token!==t)return;(0,x.unlinkSync)(e)}catch{}}function zT(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(-xg):void 0}}function Tn(){try{return zT((0,x.readFileSync)(Cg(),"utf-8"))}catch{return{consecutiveFailures:0,lastFailureAt:0,thresholdTripped:!1}}}function jc(t){let e=Oo(),r=Cg(),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 VT(){try{let e=K().MEMINDEX_HOOK_FAIL_LOUD_THRESHOLD,r=parseInt(e,10);if(Number.isFinite(r)&&r>=1)return r}catch{}return XT}function Fg(t){let e=Mc!==null?`The worker cannot bind port ${Mc} on ${Cc()}: the system refuses it (EACCES or EADDRNOTAVAIL). ${hc}.`:rr!==null?`Port ${rr} is held by an unreachable process that no PID file claims, so the worker cannot bind it. ${Ao}.`:"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 Io(){if(YT){if(ug)return Tn().consecutiveFailures;ug=!0}let t=await $c();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=VT();r=e.consecutiveFailures>=s&&!e.thresholdTripped,r&&(e.thresholdTripped=!0);let o=jc(e);r=r&&o}finally{Bc(t)}return r&&(await Kf("hook_failed",{...cg!==null?{hook_type:cg}:{},error_mode:"worker_unavailable",consecutive_failures:e.consecutiveFailures,threshold_tripped:!0}),ut(`${Fg(e.consecutiveFailures)}
23
+ `)),e.consecutiveFailures}async function Lg(t){if(!t)return null;let e=await $c();if(e===null)return null;try{let r=Tn(),n=r.notifiedSessionIds??[];return!r.thresholdTripped||n.includes(t)?null:jc({...r,notifiedSessionIds:[...n,t].slice(-xg)})?Fg(r.consecutiveFailures):null}finally{Bc(e)}}async function lg(){let t=await $c(GT);if(t!==null)try{let e=Tn();if(e.consecutiveFailures===0&&!e.thresholdTripped)return;jc({consecutiveFailures:0,lastFailureAt:0,thresholdTripped:!1})}finally{Bc(t)}}function Ug(t){return typeof t=="object"&&t!==null&&t[Rt]===!0}async function $g(t,e,r,n={}){let s=Date.now(),o=n.workerStartupTimeoutMs!==void 0;if(!(o?await HT(n.workerStartupTimeoutMs):await WT(n.timeoutMs)))return Fs(K())?{continue:!0,reason:"worker_autostart_disabled",[Rt]:!0}:(o||await Io(),{continue:!0,reason:"worker_unreachable",[Rt]:!0});let a=n.timeoutMs===void 0?et:Math.max(1,Math.min(et,n.timeoutMs-(Date.now()-s)));if(await jT(a)!==null)return await Io(),{continue:!0,reason:"worker_foreign_data_dir",[Rt]:!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<xc)return f.debug("SYSTEM","Hook budget spent before the worker request; skipping it",{url:t}),o||await Io(),{continue:!0,reason:"worker_budget_exhausted",[Rt]:!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",[Rt]:!0}}if(!u.ok){let d=await u.text().catch(()=>"");if(await lg(),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}`,[Rt]:!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 Io(),{continue:!0,reason:"worker_body_read_failed",[Rt]:!0}}if(await lg(),l.length!==0)try{return JSON.parse(l)}catch{return l}}var L,dg,x,et,Pr,wn,cT,uT,lT,xc,Rc,Ac,yo,bo,wo,bg,Ao,rr,Mc,To,er,XT,xg,kg,KT,Ng,GT,cg,YT,ug,Rt,At=E(()=>{"use strict";Da();L=_e(require("path"),1),dg=require("crypto"),x=require("fs");O();Ye();lf();qe();N();Ze();df();ff();$a();Oa();gn();gt();Os();Gf();Ap();lo();_c();mc();xp();$p();pn();wr();re();Hp();Qp();$a();et=Pc("MEMINDEX_HEALTH_TIMEOUT_MS",wt(ne.HEALTH_CHECK),{min:500,max:3e5}),Pr=Pc("MEMINDEX_HOOK_READINESS_TIMEOUT_MS",wt(ne.HOOK_READINESS_WAIT),{min:0,max:3e5}),wn=Pc("MEMINDEX_WORKER_STANDBY_WAIT_MS",Kp,{min:500,max:3e5}),cT=5e3,uT={min:500,max:3e5},lT={min:500,max:ne.SESSION_INIT_REQUEST_MAX},xc=100;Rc=null,Ac=null,yo=null,bo=null,wo=null;bg=3e4;Ao="Set MEMINDEX_WORKER_PORT to a different port in memindex settings, or reboot to release the stuck port",rr=null,Mc=null;To=null;XT=3,xg=20,kg=1e3,KT=10,Ng=5e3,GT=Ng+kg;cg=null;YT=!1,ug=!1;Rt=Symbol.for("memindex/worker-fallback")});function Wc(t,e){let r=(0,tt.normalize)(t),n=(0,tt.normalize)(e);if(r===n)return!0;let s=(0,tt.relative)(n,r);return s.length>0&&!s.startsWith("..")&&!(0,tt.isAbsolute)(s)}function rt(t){if(process.env.MEMINDEX_INTERNAL==="1")return!1;if(!t)return!0;if(Wc(t,Ps)||Wc(t,tI)||Wc(t,rI))return!1;let e=K();return!ro(t,e.MEMINDEX_EXCLUDED_PROJECTS)}var tt,qT,JT,ZT,QT,eI,tI,rI,kr=E(()=>{"use strict";tt=require("path");Sn();Ze();N();qT="plugins",JT="cache",ZT="memindex",QT="memindex",eI="plugin",tI=(0,tt.join)(Ne,qT,JT,ZT,QT),rI=(0,tt.join)(Sr,eI)});function nI(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function V(t){if(!t)return Bg;let e=nI(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:Bg}var Bg,nt=E(()=>{"use strict";Bg="claude"});var jg=E(()=>{"use strict"});function Mo(t){return new RegExp(`${t}${sI}`,"gi")}function Xc(t,e){if(!e.enabled||t.length===0)return{redacted:t,counts:{},oversize:!1};if(t.length>iI)return f.warn("REDACT","field exceeds the 1M-char redaction cap; replaced by an oversize marker",void 0,{inputLength:t.length}),{redacted:aI,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,...oI];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 cI(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 uI(t){return{enabled:t.MEMINDEX_REDACT_ENABLED==="true",disabledBuiltinPatterns:(t.MEMINDEX_REDACT_DISABLED_BUILTINS??"").split(",").map(e=>e.trim()).filter(Boolean),customPatterns:cI(t.MEMINDEX_REDACT_CUSTOM_PATTERNS??"[]"),logMatches:t.MEMINDEX_REDACT_LOG_MATCHES==="true"}}function pI(t){if(!(0,Po.existsSync)(t))return null;try{return(0,Po.readFileSync)(t,"utf-8")}catch{return""}}function gI(t){if(t===null)return!1;try{let e=JSON.parse(_a(t));return e===null||typeof e!="object"||Array.isArray(e)}catch{return!0}}function mI(t,e,r){return process.env.MEMINDEX_REDACT_ENABLED==="false"||!(Rn?.enabled===!0||fI.test(e))?r:(Hg||(Hg=!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:dI)}function Kc(t=ae){let e=Date.now();if(vn&&e-Wg<lI)return vn;let r=z.loadFromFile(t),n=uI(r),s=n.enabled?null:pI(t);return gI(s)?vn=mI(t,s,n):(vn=n,Rn=n),Wg=e,vn}function Xg(t){return Xc(t,Kc()).redacted}var Po,Hc,sI,oI,iI,aI,vn,Wg,lI,Rn,Hg,dI,fI,Gc=E(()=>{"use strict";Po=require("fs");O();qe();N();re();Hc=String.raw`[A-Za-z0-9_.\-+/=~@#$%^*!?]`,sI=`(?=${Hc}{8})${Hc}*[A-Za-z]${Hc}*`;oI=[{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:"google_oauth_secret",regex:/\bGOCSPX-[A-Za-z0-9_-]{28}(?![\w-])/g},{name:"google_oauth_token",regex:/\bya29\.(?:c\.)?[0-9A-Za-z_-]{20,}(?![\w-])/g},{name:"databricks_token",regex:/\bdapi[a-f0-9]{32}(?:-\d)?(?!\w)/g},{name:"vault_token",regex:/\b(?:hvs\.[\w-]{24,}|hvb\.[\w-]{138,})(?![\w-])/g},{name:"supabase_token",regex:/\bsbp_[a-f0-9]{40}(?!\w)/g},{name:"sentry_token",regex:/\b(?:sntryu_[a-f0-9]{64}(?!\w)|sntrys_[A-Za-z0-9+/]{20,}={0,2}_[A-Za-z0-9+/]{43}(?![\w+/]))/g},{name:"linear_key",regex:/\blin_api_[A-Za-z0-9]{40}(?!\w)/g},{name:"notion_token",regex:/\b(?:ntn_[A-Za-z0-9]{46}|secret_[A-Za-z0-9]{43})(?!\w)/g},{name:"nvidia_key",regex:/\bnvapi-[A-Za-z0-9_-]{32,}(?![\w-])/g},{name:"perplexity_key",regex:/\bpplx-[A-Za-z0-9]{32,}(?!\w)/g},{name:"gitlab_token",regex:/\bgl(?:pat|ptt|rt|dt|cbt|ft|imt|agent|oas|soat)-[A-Za-z0-9_-]{20,}(?![\w-])/g},{name:"huggingface_token",regex:/\bhf_[A-Za-z0-9]{34,}(?!\w)/g},{name:"npm_token",regex:/\bnpm_[A-Za-z0-9]{36}(?!\w)/g},{name:"groq_key",regex:/\bgsk_[A-Za-z0-9]{40,}(?!\w)/g},{name:"xai_key",regex:/\bxai-[A-Za-z0-9]{40,}(?![\w-])/g},{name:"slack_webhook",regex:/https:\/\/hooks\.slack\.com\/(?:services|workflows|triggers)\/[A-Za-z0-9\/_-]{20,}/g},{name:"discord_webhook",regex:/https:\/\/(?:ptb\.|canary\.)?discord(?:app)?\.com\/api\/(?:v\d+\/)?webhooks\/\d{15,}\/[A-Za-z0-9_-]{40,}/g},{name:"stripe_webhook_secret",regex:/\bwhsec_[A-Za-z0-9]{24,}(?!\w)/g},{name:"pypi_token",regex:/\bpypi-AgEIcHlwaS5vcmc[A-Za-z0-9_-]{50,}(?![\w-])/g},{name:"sendgrid_key",regex:/\bSG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}(?![\w-])/g},{name:"digitalocean_token",regex:/\bdo[opr]_v1_[a-f0-9]{64}(?!\w)/g},{name:"shopify_token",regex:/\bshp(?:at|ca|pa|ss)_[a-fA-F0-9]{32}(?!\w)/g},{name:"docker_hub_token",regex:/\bdckr_pat_[A-Za-z0-9_-]{20,}(?![\w-])/g},{name:"aws_temp_access_key",regex:/\bASIA[0-9A-Z]{16}\b/g},{name:"aws_session_token",regex:/(?<=\bAWS_(?:SESSION|SECURITY)_TOKEN\\{0,2}["']?\s*[=:]\s*\\{0,2}["']?)[A-Za-z0-9\/+=]{100,}/gi},{name:"memindex_worker_secret",regex:/(?<=\bworker-secret=|\bX-Memindex-Secret\s*:\s*)[a-f0-9]{64}(?![a-f0-9])/gi},{name:"memindex_key",regex:new RegExp("\\bmi_[A-Za-z0-9_-]{32,}","g")},{name:"generic_password",regex:Mo(String.raw`(?<=\b\w*_?(?:password|passwd|pwd)\\{0,2}["']?\s*[=:]\s*\\{0,2}["']?)`)},{name:"generic_token",regex:Mo(String.raw`(?<=\b\w*_(?:token|secret|api_key)\\{0,2}["']?\s*[=:]\s*\\{0,2}["']?)`)},{name:"bearer_token",regex:Mo(String.raw`(?<=\bAuthorization\s*:\s*Bearer\s*)`)},{name:"basic_auth",regex:new RegExp(String.raw`(?<=\bAuthorization\s*:\s*Basic\s+)[A-Za-z0-9+/_-]{8,}={0,2}`,"gi")},{name:"cli_flag_secret",regex:new RegExp(String.raw`(?<=(?:^|\s)--(?:auth[-_]?token|access[-_]?token|api[-_]?key|client[-_]?secret|token|password|passwd|secret)(?:=|\s+)["']?)[^\s"'<>$%]{8,}`,"gi")},{name:"url_password",regex:/\b[A-Za-z][A-Za-z0-9+.-]{1,20}:\/\/[^\s\/:@'"<>]{1,128}:[^\s\/@'"<>]{1,256}(?=@)/g},{name:"bare_secret",regex:Mo(String.raw`(?<=\b(?:token|secret|api[_-]?key|apikey)\\{0,2}["']?\s*[=:]\s*\\{0,2}["']?)`)}],iI=1024*1024,aI="<redacted type='oversize'/>";vn=null,Wg=0,lI=5e3,Rn=null,Hg=!1,dI={enabled:!0,disabledBuiltinPatterns:[],customPatterns:[],logMatches:!1},fI=/"(?:MEMINDEX|AGENT_MEM)_REDACT_ENABLED"\s*:\s*"true"/});function _I(t){let e=Object.fromEntries(zc.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}Gg.lastIndex=a;let l=Gg.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}Kg.lastIndex=a;let d=Kg.exec(t);if(d&&hI.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 EI(t){let{text:e,counts:r,total:n}=_I(t);return n>zg&&f.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:n,maxAllowed:zg,contentLength:t.length}),{stripped:Xc(e.trim(),Kc()).redacted,counts:r}}function Ie(t){return EI(t).stripped}function An(t){let e=r=>typeof r=="string"?SI.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 ko(t){return!t||t.length>wI?!1:bI.test(t)}function Vg(t){let e=t.trimStart();return TI.some(r=>r.test(e))}var zc,hI,Kg,Gg,xo,zg,SI,yI,bI,wI,TI,st=E(()=>{"use strict";O();Gc();zc=["private","memindex-context","agent-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],hI=new Set(zc),Kg=/<([A-Za-z_][A-Za-z0-9_-]*)/y,Gg=/<\/([A-Za-z_][A-Za-z0-9_-]*)\s*>/y;xo=/<system-reminder>[\s\S]*?<\/system-reminder>/g,zg=100;SI=new RegExp(`<(${zc.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`);yI=["task-notification"],bI=new RegExp(`^\\s*<(${yI.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),wI=256*1024;TI=[/^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 vI(t){return/unrecogni[sz]ed key[^]*\bbranch\b|\bbranch\b[^]*\b(unrecogni[sz]ed|unknown (field|key|property)|not allowed|unsupported|not supported)\b|additional propert[^]*\bbranch\b/i.test(t)}function Ue(t){return t instanceof Le}function RI(t){return t.replace(/\/+$/,"")}function No(t){return typeof t=="string"?V(t):null}function AI(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}var II,Le,Co,nr=E(()=>{"use strict";At();Ye();nt();st();II=wt(ne.API_REQUEST),Le=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)}},Co=class{baseUrl;apiKey;timeoutMs;branchRejected=!1;constructor(e){this.baseUrl=RI(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??II}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 Le("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 updateObservation(e,r){if(!e)throw new Le("invalid_response","id is required for updateObservation");await this.request("PATCH",`/v1/memories/${encodeURIComponent(e)}`,r)}async deleteObservation(e){if(!e)throw new Le("invalid_response","id is required for deleteObservation");await this.request("DELETE",`/v1/memories/${encodeURIComponent(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=No(e.platformSource)),e.folderProjects&&e.folderProjects.length>0&&(n.folderProjects=e.folderProjects),e.excludeSubagents!==void 0&&(n.excludeSubagents=e.excludeSubagents),e.branch&&(n.branch=e.branch),this.request("POST","/v1/context",n,r)}async getJobStatus(e){if(!e)throw new Le("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{...e.fields??{},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}:{},...e.branch?{branch:e.branch}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.branch?{branch:e.branch}:{},...e.limit!==void 0?{limit:e.limit}:{},...e.platformSource!==void 0?{platformSource:No(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:No(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:No(e.platformSource)}:{},...e.payload!==void 0?{payload:An(e.payload)}:{},...e.branch?{branch:e.branch}:{}}}async request(e,r,n,s={}){if(!this.apiKey||!this.apiKey.trim())throw new Le("missing_api_key","Server API key is not configured (MEMINDEX_SERVER_API_KEY).");let o=typeof n=="object"&&n!==null&&"branch"in n;if(o&&this.branchRejected){let{branch:p,...g}=n;n=g}let i=`${this.baseUrl}${r}`,a={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(a.body=JSON.stringify(n));let c=p=>{let g=p instanceof Error?p.message:String(p),m=/timed out|timeout/i.test(g)||p instanceof Error&&(p.name==="TimeoutError"||p.name==="AbortError");return new Le(m?"timeout":"transport",`Server ${e} ${r} failed: ${g}`,{cause:p})},u,l=s.timeoutMs??this.timeoutMs;try{u=await In(i,a,l)}catch(p){throw c(p)}if(!u.ok){let p=await u.text().catch(()=>"");if(o&&!this.branchRejected&&(u.status===400||u.status===422)&&vI(p))return this.branchRejected=!0,this.request(e,r,n,s);throw new Le("http_error",`Server ${e} ${r} returned ${u.status}: ${AI(p,200)}`,{status:u.status})}let d;try{d=await u.text()}catch(p){throw c(p)}if(!d||d.length===0)return{};try{return JSON.parse(d)}catch(p){let g=p instanceof Error?p:new Error(String(p));throw new Le("invalid_response",`Server ${e} ${r} returned non-JSON response`,{cause:g})}}}});function OI(){let e=(K().MEMINDEX_RUNTIME??"worker").trim().toLowerCase();return e==="server"||e==="server-beta"?"server":"worker"}function MI(){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 PI(){let{serverBaseUrl:t,apiKey:e,projectId:r}=MI();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 Co(n),projectId:r,serverBaseUrl:t}}function $e(){if(OI()!=="server")return{runtime:"worker"};let t=PI();return t||{runtime:"worker"}}function Be(t,e){f.warn("HOOK",`[server-fallback] reason=${t}`,e??{})}var Nr=E(()=>{"use strict";Ze();O();nr()});function DI(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 je(t){let e=(0,Jc.createHash)("sha256").update(DI(t.serverBaseUrl)).update("\0").update(t.projectId).digest("hex").slice(0,16);return(0,Ot.join)(C(),"state","server-outbox",e)}function Zc(t){return(0,Ot.join)(t,"outage.json")}function mt(t){return Ue(t)&&t.isFallbackEligible()&&t.kind!=="missing_api_key"}function FI(){return Vc=Math.max(Date.now(),Vc+1),Vc}function LI(t,e){let r=(0,Jc.createHash)("sha256").update(JSON.stringify(e)).digest("hex").slice(0,16);return`${String(t).padStart(15,"0")}-${e.op}-${r}.json`}function Mt(t,e){(0,H.mkdirSync)(e,{recursive:!0});let r=An(t),n=FI(),s=(0,Ot.join)(e,LI(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 Jg(t){return(0,H.existsSync)(t)?(0,H.readdirSync)(t).filter(e=>e.endsWith(".json")&&e!=="outage.json").sort():[]}function qc(t){try{return Jg(t).length}catch{return 0}}function UI(t){for(let e of(0,H.readdirSync)(t)){if(!e.endsWith(`.json${Yc}`))continue;let r=(0,Ot.join)(t,e);try{if(Date.now()-(0,H.statSync)(r).mtimeMs<xI)continue;(0,H.renameSync)(r,r.slice(0,-Yc.length))}catch{}}}async function Qc(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 $I(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 Qc(t,e.request,s,n)}function qg(t,e,r){try{(0,H.mkdirSync)((0,Ot.join)(t,Yg),{recursive:!0}),(0,H.renameSync)(e,(0,Ot.join)(t,Yg,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 Cr(t,e,r={}){let n=r.maxEntries??NI,s=Date.now()+(r.budgetMs??CI),o={delivered:0,remaining:0,rejected:0};try{if(!(0,H.existsSync)(e))return o;UI(e);let i=Jg(e),a=0;for(let c of i){if(a>=n||Date.now()>=s)break;let u=(0,Ot.join)(e,c),l=`${u}${Yc}`;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))),qg(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()+ne.API_REQUEST):s;await $I(t,d.entry,g,p),(0,H.unlinkSync)(l),o.delivered++}catch(p){if(mt(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:Ue(p)?p.status:null},p instanceof Error?p:new Error(String(p))),qg(e,l,c),o.rejected++}}o.remaining=qc(e),o.delivered>0&&f.info("HOOK","Sent held captures to the hosted server",{...o}),o.remaining===0&&jI(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=qc(e)}return o}function BI(t){try{let e=JSON.parse((0,H.readFileSync)(Zc(t),"utf-8"));return{notifiedSessionIds:Array.isArray(e.notifiedSessionIds)?e.notifiedSessionIds:[]}}catch{return{notifiedSessionIds:[]}}}function jI(t){try{(0,H.unlinkSync)(Zc(t))}catch{}}function WI(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 Zg(t,e){if(!t)return null;let r=qc(e);if(r===0)return null;let n=BI(e);if(n.notifiedSessionIds.includes(t))return null;try{U(Zc(e),{notifiedSessionIds:[...n.notifiedSessionIds,t].slice(-kI)})}catch{}return WI(r)}var Jc,H,Ot,Yc,Yg,xI,kI,NI,CI,Vc,On=E(()=>{"use strict";Jc=require("crypto"),H=require("fs"),Ot=require("path");re();N();Ye();O();st();nr();Yc=".sending",Yg="rejected",xI=120*1e3,kI=50,NI=20,CI=1500;Vc=0});function Fo(t){return ZI.run(t,!0)}function QI(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 ev(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 tv(t){let e=t.replace(zI," ").toLowerCase().match(/[\p{L}\p{N}_]{4,}/gu)??[],r=[...new Set(e)].slice(0,GI);return r.length>0?r.join(" or "):null}async function rv(t,e,r,n,s,o,i){if(e.length<20||e==="[media prompt]")return"";let a=tv(e);if(!a)return"";let c=eu(o,i);if(c<Do)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,ov(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,VI):""}catch(u){return f.warn("HOOK","session-init: server semantic context unavailable",{error:u instanceof Error?u.message:String(u)}),""}}function nv(t){let e=String(t.MEMINDEX_SEMANTIC_INJECT).toLowerCase();return e==="auto"?String(t.MEMINDEX_MODE).toLowerCase()==="personal":e==="true"}function sv(t){let e=String(t.MEMINDEX_READ_ONLY??"").toLowerCase();return e==="1"||e==="true"}async function Qg(t,e,r,n,s,o,i){if(!e||e.length<20||e==="[media prompt]")return"";let a=eu(o,i);if(a<Do)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},em(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 ov(t){let e=typeof t=="number"?t:Number.parseInt(t,10);return!Number.isFinite(e)||e<=0?5:e}function eu(t,e){return Math.max(0,e-(Date.now()-t))}function em(t,e){return t==="codex"?{workerStartupTimeoutMs:ne.POST_SPAWN_WAIT,timeoutMs:Math.min(YI,e)}:{timeoutMs:e}}var XI,de,KI,GI,zI,VI,Do,YI,Dr,qI,JI,ZI,tu=E(()=>{"use strict";At();Zt();O();Ye();kr();Ze();nt();jg();st();Nr();nr();On();XI={executeWithWorkerFallback:$g,getSessionInitRequestTimeoutMs:mg,isWorkerFallback:Ug,consumeWorkerOutageNotice:Lg,loadFromFileOnce:K,resolveRuntimeContext:$e,logServerFallback:Be,holdForServer:Mt,consumeServerOutageNotice:Zg,shouldTrackProject:rt,readHookEnvironment:()=>process.env},de=XI,KI=2,GI=12,zI=/<private\b[^>]*>[\s\S]*?<\/private\s*>/gi,VI=1e4,Do=500,YI=2e3,Dr=class extends Error{constructor(r){super(`session-init did not record the prompt (${r})`);this.reason=r;this.name="SessionPromptNotRecordedError"}reason};qI=t=>t?t.replace(/\\/g,"/").includes("/.qwen/"):!1,JI=(t,e=process.env)=>t?e.QWEN_PROJECT_DIR?!0:qI(t):!1,ZI={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&&ko(n))return f.debug("HOOK","session-init: skipping internal protocol payload",{preview:n.slice(0,80)}),{continue:!0,suppressOutput:!0};if(n&&V(t.platform)==="codex"&&Vg(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()&&JI(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=io(o),u=c.primary,l=V(t.platform),d=de.loadFromFileOnce(),p=nv(d),g=de.resolveRuntimeContext(),m=Date.now(),h=de.getSessionInitRequestTimeoutMs();if(g.runtime==="server"){let v=QI(g,t,r,l,u,a);try{await ev(g,v,Math.max(Do,Math.floor(h/KI)));let y=p?await rv(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(mt(y)){de.logServerFallback(y.kind,{status:y.status,message:y.message,route:"/v1/sessions/start",held:!0});let I=je(g);de.holdForServer({op:"session_start",request:v},I);let A=de.consumeServerOutageNotice(r,I);return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS,...A?{systemMessage:A,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:A}}:{}}}if(Ue(y)&&y.isFallbackEligible())de.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}}}if(sv(de.readHookEnvironment())){let v=p?await Qg(d,a,u,c.allProjects,l,m,h):"";return v?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:v}}:{continue:!0,suppressOutput:!0}}f.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:r,project:u});let _=eu(m,h);if(_<Do){if(f.warn("HOOK","session-init: skipping the worker call because the prompt budget is spent",{contentSessionId:r,project:u,remainingMs:_}),e)throw new Dr("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},em(l,_));if(de.isWorkerFallback(S)){if(e)throw new Dr("reason"in S?S.reason:"worker_fallback");let v=await de.consumeWorkerOutageNotice(r);return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS,...v?{systemMessage:v}:{}}}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 R=p?await Qg(d,a,u,c.allProjects,l,m,h):"";return f.info("HOOK",`INIT_COMPLETE | sessionDbId=${b} | promptNumber=${w} | project=${u}`,{sessionId:b}),R?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:R}}:{continue:!0,suppressOutput:!0}}}});var tm=E(()=>{"use strict";Xt();N()});function Bo(){return(0,We.join)(C(),"state","hook-spool")}function Uo(t){if(t===null||typeof t!="object")return JSON.stringify(t)??"null";if(Array.isArray(t))return`[${t.map(Uo).join(",")}]`;let e=t;return`{${Object.keys(e).filter(n=>e[n]!==void 0).sort().map(n=>`${JSON.stringify(n)}:${Uo(e[n])}`).join(",")}}`}function dv(t,e){if(t==="summarize"&&e.turnId){let n=e;return(0,Lo.createHash)("sha256").update(Uo({contentSessionId:n.contentSessionId,platformSource:V(n.platformSource),turnId:n.turnId,lastAssistantMessage:n.lastAssistantMessage})).digest("hex")}let r=e.toolUseId;return typeof r=="string"&&sm.test(r)?`${(0,Lo.createHash)("sha256").update(e.contentSessionId).update("\0").update(V(e.platformSource)).digest("hex")}-${r}`:(0,Lo.createHash)("sha256").update(t).update("\0").update(e.contentSessionId).update("\0").update(Uo(e)).digest("hex")}function nm(t){return typeof t=="string"&&t.length>0}function ru(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(!iv.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"||!nm(n.contentSessionId))return{corruptReason:"payload missing contentSessionId"};let s=r.kind;return(s==="observation"||s==="file_edit")&&!nm(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:V(n.platformSource)},enqueuedAtEpochMs:r.enqueuedAtEpochMs}}function fv(){return nu=Math.max(Date.now(),nu+1),nu}var Lo,ee,We,iv,av,sm,cv,uv,rm,lv,nu,$o,su=E(()=>{"use strict";Lo=require("crypto"),ee=require("fs"),We=require("path");re();N();nt();O();tm();iv=["observation","file_edit","summarize","session_end","advisor_calls"],av=/^[a-z_]+-[A-Za-z0-9_-]+\.json$/,sm=/^[A-Za-z0-9_-]{1,128}$/,cv="corrupt",uv="expired",rm=10080*60*1e3,lv=300*1e3;nu=0;$o=class{constructor(e=Bo()){this.directory=e}directory;get corruptDirectory(){return(0,We.join)(this.directory,cv)}get expiredDirectory(){return(0,We.join)(this.directory,uv)}enqueue(e,r,n){let s={...r,platformSource:V(r.platformSource)},o=(0,We.join)(this.directory,`${e}-${dv(e,s)}.json`),i=s.toolUseId;if(typeof i=="string"&&sm.test(i)){let c=(0,We.join)(this.directory,`${e}-${i}.json`);try{let u=ru((0,ee.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??fv();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()-rm);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,lv,"unknown-session grace window")?a++:i++;continue}if(!h){this.expireIfPastWindow(u,rm,"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,ee.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,ee.mkdirSync)(this.expiredDirectory,{recursive:!0}),(0,ee.renameSync)(e.path,(0,We.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,ee.existsSync)(e))return null;try{let r=ru((0,ee.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,We.join)(this.directory,e);try{return(0,ee.mkdirSync)(this.corruptDirectory,{recursive:!0}),(0,ee.renameSync)(n,(0,We.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,ee.existsSync)(this.directory))return{files:[],quarantined:0};let e;try{e=(0,ee.readdirSync)(this.directory).filter(s=>av.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,We.join)(this.directory,s),i;try{i=(0,ee.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=ru(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 am={};Is(am,{SPOOL_NUDGE_TIMEOUT_MS:()=>om,nudgeWorkerToDrainHookSpool:()=>im,settleHookSpoolNudges:()=>pv,spoolHookEvent:()=>He});function im(){if(Mn)return Mn;let t=(async()=>{try{await(await le("/api/spool/nudge",{method:"POST",timeoutMs:om})).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 Mn=t,ou.add(t),t.finally(()=>{ou.delete(t),Mn===t&&(Mn=null)}),t}async function pv(){await Promise.all([...ou])}function He(t,e,r){let n=new $o().enqueue(t,e,r);return f.debug("HOOK","Hook event spooled for the worker",{kind:t,entryPath:n}),im(),n}var om,ou,Mn,Fr=E(()=>{"use strict";su();At();O();om=250,ou=new Set,Mn=null});function iu(t){let e=(t??"").trim();return e?e.slice(0,gv):null}function yv(t){let e=sr.default.resolve(t);for(let r=0;r<_v;r++){let n=sr.default.join(e,".git");if((0,ht.existsSync)(n)){try{if((0,ht.statSync)(n).isDirectory())return n;let o=(0,ht.readFileSync)(n,"utf8").match(/^gitdir:\s*(.+)$/m);if(o)return sr.default.resolve(e,o[1].trim())}catch{return null}return null}let s=sr.default.dirname(e);if(s===e)return null;e=s}return null}function bv(t){let e=t.trim();if(e.startsWith(um))return iu(e.slice(um.length));if(Ev.test(e))return e.slice(0,Sv)}function wv(t){let e=yv(t);if(!e)return null;try{return bv((0,ht.readFileSync)(sr.default.join(e,"HEAD"),"utf8"))}catch{return}}function Tv(t){let e=vr(t,["rev-parse","--abbrev-ref","HEAD"],cm);if(e.status!==0||!e.stdout)return null;if(e.stdout!=="HEAD")return iu(e.stdout);let r=vr(t,["rev-parse","--short","HEAD"],cm);return r.status===0?iu(r.stdout):null}function lm(t,e=Date.now()){if(!t||!sr.default.isAbsolute(t))return null;let r=wv(t);if(r!==void 0)return r;let n=jo.get(t);if(n&&e-n.at<mv)return n.branch;let s=Tv(t);return jo.size>=hv&&jo.clear(),jo.set(t,{at:e,branch:s}),s}var ht,sr,gv,mv,hv,cm,_v,um,Ev,Sv,jo,dm=E(()=>{"use strict";ht=require("fs"),sr=_e(require("path"),1);eo();gv=255,mv=5e3,hv=200,cm=1e3,_v=64,um="ref: refs/heads/",Ev=/^[0-9a-f]{40}([0-9a-f]{24})?$/,Sv=7,jo=new Map});function Iv(t=K()){return t.MEMINDEX_BRANCH_MEMORY_ENABLED!=="false"&&t.MEMINDEX_SEND_BRANCH_TO_HOSTING!=="false"}function Wo(t){if(!Iv())return{};let e=lm(t);return e?{branch:e}:{}}var au=E(()=>{"use strict";dm();Ze();qe();N()});function Pt(t,e){return e?new Set(e.split(",").map(n=>n.trim().toLowerCase()).filter(Boolean)).has(t.toLowerCase()):!1}var Pn=E(()=>{"use strict"});function Sm(t,e){return!!t&&!!e}var ym=E(()=>{"use strict"});function Pv(t){return new Set((t??"").split(",").map(e=>e.trim()).filter(Boolean))}function Ur(t,e,r){return Sm(t,e)?r.MEMINDEX_SKIP_SUBAGENT_OBSERVATIONS==="true"?{skip:!0,reason:"subagent_observation"}:e&&Pv(r.MEMINDEX_SKIP_AGENT_TYPES).has(e)?{skip:!0,reason:"agent_type_excluded"}:bm:bm}var bm,Xo=E(()=>{"use strict";ym();bm={skip:!1}});var w_,T_=E(()=>{w_=(function(t){return 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",t})({})});var Lt,fl=E(()=>{Lt="1.10.0"});function LO(t){let e=new Set([t]),r=new Set,n=t.match(I_);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(I_);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 I_,v_,R_=E(()=>{fl();I_=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;v_=LO(Lt)});function $O(){return Object.defineProperty({},"version",{value:Lt,enumerable:!0,writable:!1,configurable:!1})}function Pe(t,e,r,n=!1){var s;let o=xi[Pi]=(s=xi[Pi])!==null&&s!==void 0?s:$O();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!=="1.10.0"){let i=new Error(`@opentelemetry/api: Registration of version v${o.version} for ${t} does not match previously registered API v${Lt}`);return r.error(i.stack||i.message),!1}return o[t]=e,r.debug(`@opentelemetry/api: Registered a global for ${t} v${Lt}.`),!0}function ge(t){let e=xi[Pi];if(e!=null){if(e!==A_){if(!e.version||!v_(e.version))return;A_=e}return e[t]}}function xe(t,e){e.debug(`@opentelemetry/api: Unregistering a global for ${t} v${Lt}.`);let r=xi[Pi];r&&delete r[t]}var UO,Pi,xi,A_,Ut=E(()=>{fl();R_();UO=Lt.split(".")[0],Pi=Symbol.for(`opentelemetry.js.api.${UO}`),xi=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{}});function us(t,e,r){let n=ge("diag");if(n)return n[t](e,...r)}var O_,M_=E(()=>{Ut();O_=class{constructor(t){this._namespace=t.namespace||"DiagComponentLogger"}debug(...t){return us("debug",this._namespace,t)}error(...t){return us("error",this._namespace,t)}info(...t){return us("info",this._namespace,t)}warn(...t){return us("warn",this._namespace,t)}verbose(...t){return us("verbose",this._namespace,t)}}});function P_(t,e){t<0?t=0:t>9999&&(t=9999),e=e||{};function r(n,s){let o=e[n];return typeof o=="function"&&t>=s?o.bind(e):function(){}}return{error:r("error",30),warn:r("warn",50),info:r("info",60),debug:r("debug",70),verbose:r("verbose",80)}}var x_=E(()=>{});var BO,Y,$t=E(()=>{Ut();M_();x_();BO="diag",Y=class k_{static instance(){return this._instance||(this._instance=new k_),this._instance}constructor(){function e(s){return function(...o){let i=ge("diag");if(i)return i[s](...o)}}let r=this,n=(s,o={logLevel:60})=>{var i;if(s===r){var a;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((a=d.stack)!==null&&a!==void 0?a:d.message),!1}typeof o=="number"&&(o={logLevel:o});let c=ge("diag"),u=P_((i=o.logLevel)!==null&&i!==void 0?i:60,s);if(c&&!o.suppressOverrideMessage){var l;let d=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";c.warn(`Current logger will be overwritten from ${d}`),u.warn(`Current logger will overwrite one already registered from ${d}`)}return Pe("diag",u,r,!0)};r.setLogger=n,r.disable=()=>{xe(BO,r)},r.createComponentLogger=s=>new O_(s),r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error")}}});var N_,C_=E(()=>{N_=class ls{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 ls(this._entries);return n._entries.set(e,r),n}removeEntry(e){let r=new ls(this._entries);return r._entries.delete(e),r}removeEntries(...e){let r=new ls(this._entries);for(let n of e)r._entries.delete(n);return r}clear(){return new ls}}});var D_,F_=E(()=>{D_=Symbol("BaggageEntryMetadata")});function L_(t={}){return new N_(new Map(Object.entries(t)))}function U_(t){return typeof t!="string"&&(jO.error(`Cannot create baggage metadata from unknown type: ${typeof t}`),t=""),{__TYPE__:D_,toString(){return t}}}var jO,pl=E(()=>{$t();C_();F_();jO=Y.instance()});function Zr(t){return Symbol.for(t)}var ki,ds=E(()=>{ki=new class gl{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 gl(r._currentContext);return o._currentContext.set(n,s),o},r.deleteValue=n=>{let s=new gl(r._currentContext);return s._currentContext.delete(n),s}}}});var ml,hl,$_,B_=E(()=>{ml=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}],hl={};if(typeof console<"u")for(let t of["error","warn","info","debug","trace","log"])typeof console[t]=="function"&&(hl[t]=console[t]);$_=class{constructor(){function t(e){return function(...r){let n=hl[e];if(typeof n!="function"&&(n=hl.log),typeof n!="function"&&console&&(n=console[e],typeof n!="function"&&(n=console.log)),typeof n=="function")return n.apply(console,r)}}for(let e=0;e<ml.length;e++)this[ml[e].n]=t(ml[e].c)}}});function j_(){return El}var WO,Ni,HO,XO,KO,GO,_l,zO,VO,YO,El,qO,JO,ZO,QO,eM,tM,rM,Sl=E(()=>{WO=class{constructor(){}createGauge(t,e){return JO}createHistogram(t,e){return ZO}createCounter(t,e){return qO}createUpDownCounter(t,e){return QO}createObservableGauge(t,e){return tM}createObservableCounter(t,e){return eM}createObservableUpDownCounter(t,e){return rM}addBatchObservableCallback(t,e){}removeBatchObservableCallback(t){}},Ni=class{},HO=class extends Ni{add(t,e){}},XO=class extends Ni{add(t,e){}},KO=class extends Ni{record(t,e){}},GO=class extends Ni{record(t,e){}},_l=class{addCallback(t){}removeCallback(t){}},zO=class extends _l{},VO=class extends _l{},YO=class extends _l{},El=new WO,qO=new HO,JO=new KO,ZO=new GO,QO=new XO,eM=new zO,tM=new VO,rM=new YO});var W_,H_=E(()=>{W_=(function(t){return t[t.INT=0]="INT",t[t.DOUBLE=1]="DOUBLE",t})({})});function X_(){return bl}var yl,bl,Ci=E(()=>{yl=class{emit(t){}enabled(){return!1}},bl=new yl});var K_,G_=E(()=>{K_=(function(t){return t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.TRACE=1]="TRACE",t[t.TRACE2=2]="TRACE2",t[t.TRACE3=3]="TRACE3",t[t.TRACE4=4]="TRACE4",t[t.DEBUG=5]="DEBUG",t[t.DEBUG2=6]="DEBUG2",t[t.DEBUG3=7]="DEBUG3",t[t.DEBUG4=8]="DEBUG4",t[t.INFO=9]="INFO",t[t.INFO2=10]="INFO2",t[t.INFO3=11]="INFO3",t[t.INFO4=12]="INFO4",t[t.WARN=13]="WARN",t[t.WARN2=14]="WARN2",t[t.WARN3=15]="WARN3",t[t.WARN4=16]="WARN4",t[t.ERROR=17]="ERROR",t[t.ERROR2=18]="ERROR2",t[t.ERROR3=19]="ERROR3",t[t.ERROR4=20]="ERROR4",t[t.FATAL=21]="FATAL",t[t.FATAL2=22]="FATAL2",t[t.FATAL3=23]="FATAL3",t[t.FATAL4=24]="FATAL4",t})({})});var Di,Fi,wl=E(()=>{Di={get(t,e){if(t!=null)return t[e]},keys(t){return t==null?[]:Object.keys(t)}},Fi={set(t,e,r){t!=null&&(t[e]=r)}}});var z_,V_=E(()=>{z_=(function(t){return t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED",t})({})});var Tl,Il,Li,vl=E(()=>{Tl="0000000000000000",Il="00000000000000000000000000000000",Li={traceId:Il,spanId:Tl,traceFlags:0}});var Bt,Ui=E(()=>{vl();Bt=class{constructor(t=Li){this._spanContext=t}spanContext(){return this._spanContext}setAttribute(t,e){return this}setAttributes(t){return this}addEvent(t,e){return this}addLink(t){return this}addLinks(t){return this}setStatus(t){return this}updateName(t){return this}end(t){}isRecording(){return!1}recordException(t,e){}}});function Y_(t,e){if(typeof t!="string"||t.length!==e)return!1;let r=0;for(let n=0;n<t.length;n+=4)r+=($i[t.charCodeAt(n)]|0)+($i[t.charCodeAt(n+1)]|0)+($i[t.charCodeAt(n+2)]|0)+($i[t.charCodeAt(n+3)]|0);return r===e}function Rl(t){return Y_(t,32)&&t!=="00000000000000000000000000000000"}function Al(t){return Y_(t,16)&&t!=="0000000000000000"}function Qr(t){return Rl(t.traceId)&&Al(t.spanId)}function q_(t){return new Bt(t)}var $i,Bi=E(()=>{Ui();$i=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])});var J_,Z_=E(()=>{ds();J_=class{active(){return ki}with(t,e,r,...n){return e.call(r,...n)}bind(t,e){return e}enable(){return this}disable(){return this}attach(t){return{dispose(){}}}}});var Ol,nM,sM,jt,fs=E(()=>{Ut();$t();Z_();Ol="context",nM=new J_,sM=Object.freeze({dispose:()=>{}}),jt=class Q_{constructor(){this._attachUnsupportedWarned=!1}static getInstance(){return this._instance||(this._instance=new Q_),this._instance}setGlobalContextManager(e){return Pe(Ol,e,Y.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)}attach(e){let r=this._getContextManager();return r.attach?r.attach(e):(this._attachUnsupportedWarned||(this._attachUnsupportedWarned=!0,Y.instance().warn("The current ContextManager does not implement attach(). The context will not be attached. Use a ContextManager that supports attach() (e.g. AsyncLocalStorageContextManager) or use with()/bind() instead.")),sM)}_getContextManager(){return ge(Ol)||nM}disable(){this._getContextManager().disable(),xe(Ol,Y.instance())}}});function ji(t){return t.getValue(Ml)||void 0}function eE(){return ji(jt.getInstance().active())}function ps(t,e){return t.setValue(Ml,e)}function tE(t){return t.deleteValue(Ml)}function rE(t,e){return ps(t,new Bt(e))}function Wi(t){var e;return(e=ji(t))===null||e===void 0?void 0:e.spanContext()}var Ml,Pl=E(()=>{ds();fs();Ui();Ml=Zr("OpenTelemetry Context Key SPAN")});function oM(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 xl,Hi,kl=E(()=>{fs();Ui();Pl();Bi();xl=jt.getInstance(),Hi=class{startSpan(t,e,r=xl.active()){if(e?.root)return new Bt;let n=r&&Wi(r);return oM(n)&&Qr(n)?new Bt(n):new Bt}startActiveSpan(t,e,r,n){var s;let o,i,a;if(arguments.length<2)return;arguments.length===2?a=e:arguments.length===3?(o=e,a=r):(o=e,i=r,a=n);let c=(s=i)!==null&&s!==void 0?s:xl.active(),u=this.startSpan(t,o,c),l=ps(c,u);return xl.with(l,a,void 0,u)}}});var iM,Xi,Nl=E(()=>{kl();iM=new Hi,Xi=class{constructor(t,e,r,n){this._provider=t,this.name=e,this.version=r,this.options=n}startSpan(t,e,r){return this._getTracer().startSpan(t,e,r)}startActiveSpan(t,e,r,n){let s=this._getTracer();return Reflect.apply(s.startActiveSpan,s,arguments)}_getTracer(){if(this._delegate)return this._delegate;let t=this._provider.getDelegateTracer(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):iM}}});var nE,sE=E(()=>{nE=(function(t){return 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",t})({})});var oE,iE=E(()=>{oE=(function(t){return t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR",t})({})});function aE(t){return aM.test(t)}function cE(t){return cM.test(t)&&!uM.test(t)}var Cl,aM,cM,uM,uE=E(()=>{Cl="[_0-9a-z-*/]",aM=new RegExp(`^(?:${`[a-z]${Cl}{0,255}`}|${`[a-z0-9]${Cl}{0,240}@[a-z]${Cl}{0,13}`})$`),cM=/^[ -~]{0,255}[!-~]$/,uM=/,|=/});var Dl,lE,dE,fE,pE,mE=E(()=>{uE();Dl=32,lE=512,dE=",",fE="=",pE=class gE{constructor(e){this._internalState=new Map,e&&this._parse(e)}set(e,r){let n=this._internalState.get(e),s=this.serialize().length;if(typeof n=="string")s+=r.length-n.length;else{if(this._internalState.size>=Dl)return this;s+=e.length+r.length+(this._internalState.size>0?2:1)}if(s>lE)return this;let o=this._clone();return o._internalState.has(e)&&o._internalState.delete(e),o._internalState.set(e,r),o}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+fE+this.get(r)),e),[]).join(dE)}_parse(e){e.length>lE||(this._internalState=e.split(dE).reduceRight((r,n)=>{let s=n.trim(),o=s.indexOf(fE);if(o!==-1){let i=s.slice(0,o),a=s.slice(o+1,n.length);aE(i)&&cE(a)&&r.set(i,a)}return r},new Map),this._internalState.size>Dl&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,Dl))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let e=new gE;return e._internalState=new Map(this._internalState),e}}});function hE(t){return new pE(t)}var _E=E(()=>{mE()});var EE,SE=E(()=>{kl();EE=class{getTracer(t,e,r){return new Hi}}});var lM,gs,Fl=E(()=>{Nl();SE();lM=new EE,gs=class{getTracer(t,e,r){var n;return(n=this.getDelegateTracer(t,e,r))!==null&&n!==void 0?n:new Xi(this,t,e,r)}getDelegate(){var t;return(t=this._delegate)!==null&&t!==void 0?t:lM}setDelegate(t){this._delegate=t}getDelegateTracer(t,e,r){var n;return(n=this._delegate)===null||n===void 0?void 0:n.getTracer(t,e,r)}}});var yE,bE=E(()=>{yE=(function(t){return t[t.NOT_RECORD=0]="NOT_RECORD",t[t.RECORD=1]="RECORD",t[t.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED",t})({})});var Ll,wE=E(()=>{fs();Ll=jt.getInstance()});var Ul,TE=E(()=>{$t();Ul=Y.instance()});var dM,IE,vE=E(()=>{Ci();dM=class{getLogger(t,e,r){return new yl}},IE=new dM});var RE,AE=E(()=>{Ci();RE=class{constructor(t,e,r,n){this._provider=t,this.name=e,this.version=r,this.options=n}emit(t){this._getLogger().emit(t)}enabled(t){return this._getLogger().enabled(t)}_getLogger(){if(this._delegate)return this._delegate;let t=this._provider._getDelegateLogger(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):bl}}});var $l,OE=E(()=>{vE();AE();$l=class{getLogger(t,e,r){var n;return(n=this._getDelegateLogger(t,e,r))!==null&&n!==void 0?n:new RE(this,t,e,r)}_getDelegate(){var t;return(t=this._delegate)!==null&&t!==void 0?t:IE}_setDelegate(t){this._delegate=t}_getDelegateLogger(t,e,r){var n;return(n=this._delegate)===null||n===void 0?void 0:n.getLogger(t,e,r)}}});var Bl,ME,xE=E(()=>{Ut();$t();OE();Bl="logs",ME=class PE{constructor(){this._proxyLoggerProvider=new $l}static getInstance(){return this._instance||(this._instance=new PE),this._instance}setGlobalLoggerProvider(e){let r=Pe(Bl,e,Y.instance());return r&&this._proxyLoggerProvider._setDelegate(e),r}getLoggerProvider(){return ge(Bl)||this._proxyLoggerProvider}getLogger(e,r,n){return this.getLoggerProvider().getLogger(e,r,n)}disable(){xe(Bl,Y.instance()),this._proxyLoggerProvider=new $l}}});var jl,kE=E(()=>{xE();jl=ME.getInstance()});var fM,NE,CE=E(()=>{Sl();fM=class{getMeter(t,e,r){return El}},NE=new fM});var Wl,DE,LE=E(()=>{Ut();$t();CE();Wl="metrics",DE=class FE{constructor(){}static getInstance(){return this._instance||(this._instance=new FE),this._instance}setGlobalMeterProvider(e){return Pe(Wl,e,Y.instance())}getMeterProvider(){return ge(Wl)||NE}getMeter(e,r,n){return this.getMeterProvider().getMeter(e,r,n)}disable(){xe(Wl,Y.instance())}}});var Hl,UE=E(()=>{LE();Hl=DE.getInstance()});var $E,BE=E(()=>{$E=class{inject(t,e){}extract(t,e){return t}fields(){return[]}}});function Kl(t){return t.getValue(Xl)||void 0}function jE(){return Kl(jt.getInstance().active())}function WE(t,e){return t.setValue(Xl,e)}function HE(t){return t.deleteValue(Xl)}var Xl,XE=E(()=>{ds();fs();Xl=Zr("OpenTelemetry Baggage Key")});var Gl,pM,KE,zE=E(()=>{Ut();$t();pl();wl();BE();XE();Gl="propagation",pM=new $E,KE=class GE{constructor(){this.createBaggage=L_,this.getBaggage=Kl,this.getActiveBaggage=jE,this.setBaggage=WE,this.deleteBaggage=HE}static getInstance(){return this._instance||(this._instance=new GE),this._instance}setGlobalPropagator(e){return Pe(Gl,e,Y.instance())}inject(e,r,n=Fi){return this._getGlobalPropagator().inject(e,r,n)}extract(e,r,n=Di){return this._getGlobalPropagator().extract(e,r,n)}fields(){return this._getGlobalPropagator().fields()}disable(){xe(Gl,Y.instance())}_getGlobalPropagator(){return ge(Gl)||pM}}});var zl,VE=E(()=>{zE();zl=KE.getInstance()});var Vl,YE,JE=E(()=>{Ut();$t();Pl();Bi();Fl();Vl="trace",YE=class qE{constructor(){this._proxyTracerProvider=new gs,this.wrapSpanContext=q_,this.isSpanContextValid=Qr,this.deleteSpan=tE,this.getSpan=ji,this.getActiveSpan=eE,this.getSpanContext=Wi,this.setSpan=ps,this.setSpanContext=rE}static getInstance(){return this._instance||(this._instance=new qE),this._instance}setGlobalTracerProvider(e){let r=Pe(Vl,this._proxyTracerProvider,Y.instance());return r&&this._proxyTracerProvider.setDelegate(e),r}getTracerProvider(){return ge(Vl)||this._proxyTracerProvider}getTracer(e,r){return this.getTracerProvider().getTracer(e,r)}disable(){xe(Vl,Y.instance()),this._proxyTracerProvider=new gs}}});var Yl,ZE=E(()=>{JE();Yl=YE.getInstance()});var QE={};Is(QE,{DiagConsoleLogger:()=>$_,DiagLogLevel:()=>w_,INVALID_SPANID:()=>Tl,INVALID_SPAN_CONTEXT:()=>Li,INVALID_TRACEID:()=>Il,ProxyTracer:()=>Xi,ProxyTracerProvider:()=>gs,ROOT_CONTEXT:()=>ki,SamplingDecision:()=>yE,SeverityNumber:()=>K_,SpanKind:()=>nE,SpanStatusCode:()=>oE,TraceFlags:()=>z_,ValueType:()=>W_,baggageEntryMetadataFromString:()=>U_,context:()=>Ll,createContextKey:()=>Zr,createNoopLogger:()=>X_,createNoopMeter:()=>j_,createTraceState:()=>hE,default:()=>gM,defaultTextMapGetter:()=>Di,defaultTextMapSetter:()=>Fi,diag:()=>Ul,isSpanContextValid:()=>Qr,isValidSpanId:()=>Al,isValidTraceId:()=>Rl,logs:()=>jl,metrics:()=>Hl,propagation:()=>zl,trace:()=>Yl});var gM,eS=E(()=>{T_();pl();ds();B_();Sl();H_();Ci();G_();wl();V_();vl();Bi();Nl();sE();iE();_E();Fl();bE();wE();TE();kE();UE();VE();ZE();gM={context:Ll,diag:Ul,logs:jl,metrics:Hl,propagation:zl,trace:Yl}});function wS(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 tn(t){if(!t)return!1;if(t.startsWith("memory_")||t==="mem_search"||t==="get_summaries")return!0;let e=wS(t);return e!==null&&aP.has(e)}function ra(t){return t==="save_memory"||wS(t)==="save_memory"}var aP,na=E(()=>{"use strict";aP=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 od(t){return typeof t=="string"&&t.length>0}var bs,US=E(()=>{"use strict";bs=class extends Error{constructor(r){super(`adapter rejected input: ${r}`);this.reason=r;this.name="AdapterRejectedInput"}reason}});var RP,$S,id,AP,OP,BS,jS=E(()=>{"use strict";US();Zt();RP=128,$S=t=>typeof t=="string"&&t.length>0&&t.length<=RP?t:void 0,id=t=>typeof t=="string"?t:void 0,AP=t=>t.hook_event_name==="PostToolUseFailure"?{error:t.error,is_interrupt:t.is_interrupt===!0}:void 0,OP=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},BS={normalizeInput(t){let e=t??{},r=e.cwd??process.cwd();if(!od(r))throw new bs("invalid_cwd");let n=sp(r);if(!od(n))throw new bs("invalid_cwd");let s=e.source;return{sessionId:e.session_id??e.id??e.sessionId,hookEventName:id(e.hook_event_name),cwd:n,sessionSource:s==="startup"||s==="resume"||s==="clear"||s==="compact"?s:void 0,prompt:e.prompt,submittedPrompt:OP(e),toolName:e.tool_name,toolInput:e.tool_input,toolResponse:e.tool_response??AP(e),toolUseId:typeof e.tool_use_id=="string"?e.tool_use_id:void 0,transcriptPath:e.transcript_path,lastAssistantMessage:id(e.last_assistant_message),reason:id(e.reason),agentId:$S(e.agent_id),agentType:$S(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 WS(t,e){return He("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 HS,XS=E(()=>{"use strict";Fr();O();Gc();Ye();kr();Xo();Ze();au();Pn();nt();Nr();nr();On();na();HS={async execute(t){let{sessionId:e,cwd:r,toolName:n,toolInput:s,toolResponse:o}=t,i=V(t.platform);if(!n)return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};if(tn(n))return{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};let a=Xg(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(!rt(r))return f.debug("HOOK","Project excluded from tracking, skipping observation",{cwd:r,toolName:n}),{continue:!0,suppressOutput:!0};let c=Ur(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(ra(n))return WS(t,i);let u=$e();if(u.runtime==="server"){if(Pt(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: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},...Wo(r)};try{return await u.client.recordEvent(l),f.debug("HOOK","Observation sent successfully via server",{toolName:n}),await Cr(u.client,je(u)),{continue:!0,suppressOutput:!0}}catch(d){if(mt(d))return Be(d.kind,{status:d.status,message:d.message,route:"/v1/events",held:!0}),Mt({op:"event",request:l},je(u)),{continue:!0,suppressOutput:!0};if(Ue(d)&&d.isFallbackEligible())Be(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 WS(t,i)}}});function xP(t,e,r){let n=0;for(;n<e.length;){let s=(0,Ge.readSync)(t,e,n,e.length-n,r+n);if(s===0)break;n+=s}return n}function*kP(t,e){let r=Math.max(1,e.maxChunkBytes??KS),n=Math.min(r,Math.max(1,e.initialBytes??MP)),s=(0,Ge.openSync)(t,"r");try{let o=(0,Ge.fstatSync)(s).size,i=Buffer.alloc(0);for(;o>0;){let a=Math.max(0,o-n),c=Buffer.alloc(o-a),u=xP(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,Ge.closeSync)(s)}}function GS(t,e,r={}){if(!t||!(0,Ge.existsSync)(t)){f.warn("PARSER",`Transcript path missing or file does not exist: ${t}`);return}let n=!1;for(let s of kP(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*ad(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 NP(t,e,r,n,s){let o,i=null,a,c,u=!1,l=0,d=Math.max(0,s?.modelSearchBudgetBytes??PP),p=GS(t,(g,m,h)=>{if(s?.includeTurnId&&!u)for(let b of ad(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=YS(g)),o===void 0){let b=$P(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 cd(t,e=!1,r){let n=NP(t,"assistant",e,!0,r);return{text:n.text,...n.model===void 0?{}:{model:n.model},...n.turnId===void 0?{}:{turnId:n.turnId}}}function zS(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 FP(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 LP(t,e){if(e==="user"&&t?.type==="context.append_message")return zS(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 UP(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 $P(t,e,r){let n=!1,s=null,o="blank";for(let i of ad(t)){let a=FP(i),c=typeof i.type=="string"?CP[i.type]:void 0,u=typeof i.type=="string"?DP[i.type]:void 0;if((a??c??u??i.type??i.role)!==e)continue;n=!0;let d,p;if(a!==void 0)d=LP(i,e);else if(u!==void 0)d=typeof i.data?.content=="string"?i.data.content:"";else{if(p=c!==void 0?i.content:i.message?.content,p==null)continue;let g=zS(p);if(g===null)continue;d=g}if(r&&(d=d.replace(xo,""),d=d.replace(/\n{3,}/g,`
26
26
 
27
- `).trim()),d&&d.trim())return{kind:"text",text:d};if(s===null&&(s=d,!s.trim()&&Array.isArray(p))){let g=AP(p);g&&(s=g,o="synthesized")}}return n?{kind:o,text:s??""}:{kind:"none",text:""}}function WS(t,e){if(!(!t||!(0,Ge.existsSync)(t)))return $S(t,r=>jS(r),e)}function jS(t){for(let e of od(t)){if((e.type??e.role)!=="assistant")continue;let r=e.message?.model;if(typeof r=="string"&&r)return r}}var Ge,EP,US,SP,TP,IP,HS=E(()=>{"use strict";Ge=require("fs");O();nt();EP=256*1024,US=64*1024*1024,SP=US;TP={USER_INPUT:"user",PLANNER_RESPONSE:"assistant"},IP={"user.message":"user","assistant.message":"assistant"}});function PP(t){return MP.has(t)}function xP(t=process.env){return t.CLAUDE_CONFIG_DIR?(0,ad.join)(t.CLAUDE_CONFIG_DIR,".claude.json"):(0,ad.join)((0,XS.homedir)(),".claude.json")}function la(t){if(!t)return!1;let e=t.trim().toLowerCase();return e!==""&&e!=="0"&&e!=="false"}function kP(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 NP(t){if(!(0,da.existsSync)(t))return{};let e;try{e=Xt((0,da.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 kP(e)}function CP(t,e){let r=t.customApiKeyResponses?.approved;return Array.isArray(r)&&r.includes(e.slice(-20))}function DP(t){let e=t.oauthAccount?.organizationType;if(typeof e!="string")return;let r=e.replace(/^claude_/,"");return PP(r)?r:"subscription"}function KS(t=process.env,e=xP(t)){if(la(t.CLAUDE_CODE_USE_BEDROCK))return"bedrock";if(la(t.CLAUDE_CODE_USE_VERTEX))return"vertex";if(la(t.CLAUDE_CODE_USE_FOUNDRY))return"foundry";let r=NP(e),n=!!r.oauthAccount,s=t.ANTHROPIC_API_KEY||t.ANTHROPIC_AUTH_TOKEN;if(s&&(!n||CP(r,s)))return"api_key";let o=DP(r);return o||(n||la(t.CLAUDE_CODE_OAUTH_TOKEN)?"subscription":"unknown")}var da,ad,XS,MP,GS=E(()=>{"use strict";da=require("fs"),ad=require("path"),XS=require("os");O();ne();MP=new Set(["max","pro","team","enterprise"])});function UP(t){let e=LP.test(t)?t:`sha256-${(0,zS.createHash)("sha256").update(t).digest("hex")}`;return(0,cd.join)(N(),"state",FP,e)}function VS(t){try{(0,bs.rmSync)(UP(t),{force:!0})}catch(e){f.warn("HOOK","kimi-context-gate: clearInjected failed open",{error:e instanceof Error?e.message:String(e)})}}var bs,zS,cd,FP,LP,YS=E(()=>{"use strict";bs=require("fs"),zS=require("crypto"),cd=require("path");C();O();FP="kimi-context-injected",LP=/^[A-Za-z0-9_-]{1,128}$/});function BP(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 qS(t){if(typeof t!="string")return null;let e=Date.parse(t);return Number.isFinite(e)?e:null}function WP(t,e){let r=(0,ze.openSync)(t,"r");try{let n=(0,ze.fstatSync)(r).size,s=Math.max(0,n-e),o=Buffer.alloc(n-s);if((0,ze.readSync)(r,o,0,o.length,s),s===0)return{text:o.toString("utf-8"),startOffset:0};let i=Buffer.alloc(1);if((0,ze.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,ze.closeSync)(r)}}function JS(t,e={}){if(!t||!(0,ze.existsSync)(t))return[];let{text:r,startOffset:n}=WP(t,e.maxTailBytes??$P);return r.trim()?jP(r,e,n):[]}function jP(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=BP(m).replace(xo,"").replace(/\n{3,}/g,`
27
+ `).trim()),d&&d.trim())return{kind:"text",text:d};if(s===null&&(s=d,!s.trim()&&Array.isArray(p))){let g=UP(p);g&&(s=g,o="synthesized")}}return n?{kind:o,text:s??""}:{kind:"none",text:""}}function VS(t,e){if(!(!t||!(0,Ge.existsSync)(t)))return GS(t,r=>YS(r),e)}function YS(t){for(let e of ad(t)){if((e.type??e.role)!=="assistant")continue;let r=e.message?.model;if(typeof r=="string"&&r)return r}}var Ge,MP,KS,PP,CP,DP,qS=E(()=>{"use strict";Ge=require("fs");O();st();MP=256*1024,KS=64*1024*1024,PP=KS;CP={USER_INPUT:"user",PLANNER_RESPONSE:"assistant"},DP={"user.message":"user","assistant.message":"assistant"}});function jP(t){return BP.has(t)}function WP(t=process.env){return t.CLAUDE_CONFIG_DIR?(0,ud.join)(t.CLAUDE_CONFIG_DIR,".claude.json"):(0,ud.join)((0,JS.homedir)(),".claude.json")}function la(t){if(!t)return!1;let e=t.trim().toLowerCase();return e!==""&&e!=="0"&&e!=="false"}function HP(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 XP(t){if(!(0,da.existsSync)(t))return{};let e;try{e=Kt((0,da.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 HP(e)}function KP(t,e){let r=t.customApiKeyResponses?.approved;return Array.isArray(r)&&r.includes(e.slice(-20))}function GP(t){let e=t.oauthAccount?.organizationType;if(typeof e!="string")return;let r=e.replace(/^claude_/,"");return jP(r)?r:"subscription"}function ZS(t=process.env,e=WP(t)){if(la(t.CLAUDE_CODE_USE_BEDROCK))return"bedrock";if(la(t.CLAUDE_CODE_USE_VERTEX))return"vertex";if(la(t.CLAUDE_CODE_USE_FOUNDRY))return"foundry";let r=XP(e),n=!!r.oauthAccount,s=t.ANTHROPIC_API_KEY||t.ANTHROPIC_AUTH_TOKEN;if(s&&(!n||KP(r,s)))return"api_key";let o=GP(r);return o||(n||la(t.CLAUDE_CODE_OAUTH_TOKEN)?"subscription":"unknown")}var da,ud,JS,BP,QS=E(()=>{"use strict";da=require("fs"),ud=require("path"),JS=require("os");O();re();BP=new Set(["max","pro","team","enterprise"])});function YP(t){let e=VP.test(t)?t:`sha256-${(0,ey.createHash)("sha256").update(t).digest("hex")}`;return(0,ld.join)(C(),"state",zP,e)}function ty(t){try{(0,ws.rmSync)(YP(t),{force:!0})}catch(e){f.warn("HOOK","kimi-context-gate: clearInjected failed open",{error:e instanceof Error?e.message:String(e)})}}var ws,ey,ld,zP,VP,ry=E(()=>{"use strict";ws=require("fs"),ey=require("crypto"),ld=require("path");N();O();zP="kimi-context-injected",VP=/^[A-Za-z0-9_-]{1,128}$/});function JP(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 ny(t){if(typeof t!="string")return null;let e=Date.parse(t);return Number.isFinite(e)?e:null}function ZP(t,e){let r=(0,ze.openSync)(t,"r");try{let n=(0,ze.fstatSync)(r).size,s=Math.max(0,n-e),o=Buffer.alloc(n-s);if((0,ze.readSync)(r,o,0,o.length,s),s===0)return{text:o.toString("utf-8"),startOffset:0};let i=Buffer.alloc(1);if((0,ze.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,ze.closeSync)(r)}}function sy(t,e={}){if(!t||!(0,ze.existsSync)(t))return[];let{text:r,startOffset:n}=ZP(t,e.maxTailBytes??qP);return r.trim()?QP(r,e,n):[]}function QP(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=JP(m).replace(xo,"").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,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:qS(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||(qS(p.timestamp)??Date.now()),transcriptByteOffset:_.transcriptByteOffset,lastUserMessage:_.lastUserMessage},userTurnLine:_.userTurnLine})}}}}return a.filter(u=>!e.currentTurnOnly||u.userTurnLine===o).map(u=>u.call)}var ze,$P,QS=E(()=>{"use strict";ze=require("fs");nt();$P=2*1024*1024});function XP(t,e,r,n){if(!e||K().MEMINDEX_CAPTURE_ADVISOR_CALLS!=="true"||$e().runtime==="server")return;let s=JS(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+=ZS)He("advisor_calls",{contentSessionId:t,platformSource:n,cwd:r,transcriptPath:e,calls:s.slice(o,o+ZS).map(i=>({toolUseId:i.toolUseId,advice:i.advice,advisorModel:i.advisorModel,occurredAtEpoch:i.occurredAtEpoch,lastUserMessage:i.lastUserMessage,transcriptByteOffset:i.transcriptByteOffset}))})}}async function KP(t,e,r){return await Jc(t.client,e,void 0,r),f.debug("HOOK","Summary request queued via server"),await kr(t.client,We(t)),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS}}var ey,ty,ZS,ry,ny=E(()=>{"use strict";Cr();O();HS();ey=require("crypto"),ty=require("path");GS();nt();ke();Rt();gt();Pr();YS();xr();nr();An();QS();Qe();ZS=50;ry={async execute(t){if(t.cwd&&!rt(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"&&VS(e);try{XP(e,r,t.cwd,V(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=Te(t.lastAssistantMessage);try{if(r&&t.platform==="claude-code"&&!o){let d=id(r,!0,i);s=d.model,o=d.turnId}else s=r?WS(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=id(r,!0,i);n=Te(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=V(t.platform),c=t.platform==="claude-code"?KS():void 0,u=$e();if(u.runtime==="server"){let d={projectId:u.projectId,contentSessionId:e,platformSource:a,lastAssistantMessage:n,occurredAtEpoch:Date.now()},p=d;try{return await KP(u,d,g=>{p=g})}catch(g){if(mt(g))return Be(g.kind,{status:g.status,message:g.message,route:"/v1/sessions/end",held:!0}),Ot({op:"summarize",request:p},We(u)),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};if(Ue(g)&&g.isFallbackEligible())Be(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,ey.randomUUID)());let l=He("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 ue("/api/spool/nudge",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({waitForSummary:!0,contentSessionId:e,platformSource:a,captureKey:(0,ty.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 sy=E(()=>{"use strict"});function oy(t){let e=t.trim(),n=Te(t).trim()||e;return n.length<=ud?n:(f.debug("DB","Truncated stored prompt text to the configured cap",{originalLength:n.length,storedLength:ud}),`${n.slice(0,ud-1)}\u2026`)}var ud,ld,iy=E(()=>{"use strict";nt();O();ud=4e3,ld="[media prompt]"});function GP(t){if(typeof t!="string")return null;let e=Date.parse(t);return Number.isFinite(e)?e:null}function dy(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>bt(e)&&e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(`
32
- `):""}function YP(t){if(t.type!=="user"||t.isSidechain===!0||t.isMeta===!0||t.isCompactSummary===!0)return null;let e=bt(t.message)?t.message:null;if(!e)return null;let r=e.content;if(Array.isArray(r)&&r.some(i=>bt(i)&&i.type==="tool_result"))return null;let n=bt(t.origin)?t.origin:null;if(n){if(n.kind!=="human")return null}else if(typeof t.promptSource=="string"&&!VP.has(t.promptSource))return null;let s=dy(r),o=s.trimStart();return!n&&zP.some(i=>o.startsWith(i))||!s.trim()&&!Array.isArray(r)?null:s}function qP(t){return typeof t=="string"?t:dy(t)}async function*JP(t){let e=(0,ly.createInterface)({input:(0,Ve.createReadStream)(t,{encoding:"utf8"}),crlfDelay:1/0});for await(let r of e)if(r.trim())try{let n=JSON.parse(r);bt(n)&&(yield n)}catch{}}async function ay(t,e={}){let r=[],n=new Map,s=null,o=e.agentId!==void 0,i=0;for await(let a of JP(t)){i++,s===null&&typeof a.cwd=="string"&&a.cwd.trim()&&(s=a.cwd);let c=GP(a.timestamp),u=bt(a.message)?a.message:null;if(a.type==="assistant"&&u&&Array.isArray(u.content)){for(let l of u.content)bt(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(!bt(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=qP(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=YP(a);if(l!==null){let d=typeof a.uuid=="string"&&a.uuid?a.uuid:`${(0,Wt.basename)(t)}:${i}`;r.push({kind:"prompt",timestampMs:c,uuid:d,text:l})}}}}return{events:r,firstCwd:s}}function QP(t){try{let e=JSON.parse((0,Ve.readFileSync)(t,"utf8"));return bt(e)&&typeof e.agentType=="string"&&e.agentType?e.agentType:void 0}catch{return}}async function fy(t,e){let r=await ay(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,Wt.basename)(a,".jsonl").replace(/^agent-/,""),u=QP(a.replace(/\.jsonl$/,".meta.json"));(await ay(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 cy(t){try{return(0,Ve.statSync)(t).mtimeMs}catch{return 0}}function dd(t){try{return(0,Ve.readdirSync)(t)}catch{return[]}}function uy(t){let e=[];for(let r of dd(t).sort()){let n=ZP.exec(r);if(!n)continue;let s=n[1],o=(0,Wt.join)(t,r),i=(0,Wt.join)(t,s,"subagents"),a=(0,Ve.existsSync)(i)?dd(i).filter(u=>u.startsWith("agent-")&&u.endsWith(".jsonl")).sort().map(u=>(0,Wt.join)(i,u)):[],c=Math.max(cy(o),...a.map(cy));e.push({sessionId:s,transcriptPath:o,subagentPaths:a,lastModifiedMs:c})}return e}function py(t){let e=uy(t);return e.length>0?e:dd(t).sort().map(r=>(0,Wt.join)(t,r)).filter(r=>{try{return(0,Ve.statSync)(r).isDirectory()}catch{return!1}}).flatMap(uy)}var Ve,Wt,ly,bt,zP,VP,ZP,gy=E(()=>{"use strict";Ve=require("fs"),Wt=require("path"),ly=require("readline"),bt=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);zP=["<command-name>","<command-message>","<local-command-stdout>","<local-command-stderr>","<local-command-caveat>"],VP=new Set(["typed","queued","sdk"]);ZP=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i});var by={};Ts(by,{BACKLOG_HIGH_WATER:()=>pd,CLAUDE_CODE_PLATFORM:()=>_y,TRANSCRIPT_IMPORT_USAGE:()=>i0,defaultTranscriptImportDeps:()=>yy,formatTranscriptImportResult:()=>E0,isPromptSkippedByWorker:()=>gd,isoOf:()=>ws,matchRecordedPrompts:()=>Ey,parseTranscriptImportArgs:()=>o0,promptKey:()=>tn,runTranscriptImport:()=>_0});function o0(t){let e=null,r=null,n=(0,ga.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 tn(t){return oy(Te(t.trim()?t:ld))}function hy(t){let e=t.replace(/\s+/g," ").trim();return e.length>my?`${e.slice(0,my-1)}\u2026`:e}function ws(t){return t===null?"(no time)":new Date(t).toISOString()}function Ey(t,e,r){let n=e.map(c=>tn(c.text)),s=new Set,o=new Map;for(let c of[...t].reverse()){if(!r.has(c.uuid))continue;let u=tn(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=tn(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 fd(t){let e=NS.normalizeInput(t);return e.platform=_y,e}function a0(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 c0(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 u0(t){let e=await t.backlog();if(e===null||e<=pd)return;let r=Date.now(),n=e,s=0;for(;e!==null&&e>pd;)if(Date.now()-s>=3e4&&(t.log(` waiting for the worker to catch up (${e} items queued)`),s=Date.now()),await t.sleep(t0),e=await t.backlog(),e!==n)n=e??n,r=Date.now();else if(Date.now()-r>pa)throw new Error(`the worker has not taken any queued work for ${Math.round(pa/6e4)} minutes (${e} items queued)`)}function d0(t){let e=0;return{async check(r=!1){e++,!(!r&&e<l0)&&(e=0,await u0(t))}}}async function p0(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(f0),r=t.pendingSpoolFor(e),r!==s)s=r,n=t.now();else if(t.now()-n>pa)throw new Error(`the worker has not taken this session's queued events for ${Math.round(pa/6e4)} minutes (${r} waiting)`)}function gd(t){return ko(t)||t.trim()!==""&&Te(t).trim()===""}async function g0(t,e){for(let r=1;;r++)try{await t.sendPrompt(e);return}catch(n){if(!(n instanceof Nr)||r>=r0)throw n;await t.sleep(n0*r)}}async function h0(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=Ey(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=tn(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 ${ws(h.last.timestampMs)} ${hy(T)}`);else{let y=fd({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=tn(y.text),v=l.get(y.uuid)??null,R=c.has(y.uuid),I=v?r.prompts.find(P=>P.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&&gd(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 ${ws(y.timestampMs)} ${hy(y.text)||ld}`);else{await i.check(!0);let P=(m.get(A)??Number.NEGATIVE_INFINITY)+m0-o.now();P>0&&await o.sleep(P),_>0&&await p0(o,g),_=0,c.add(y.uuid),S(),await g0(o,fd({session_id:g,cwd:e,hook_event_name:"UserPromptSubmit",prompt:y.text,transcript_path:t.transcriptPath})),m.set(A,o.now())}if(gd(y.text)){h.skippedByWorker=!0,a.prompts++;continue}d.some(P=>P>T)&&(a.outOfOrder++,o.log(` note: the prompt at ${ws(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 ${ws(y.timestampMs)} ${y.toolName} ${y.toolUseId}${y.failed?" failed":""}${A}`)}else{let A=fd(a0(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 _0(t,e=yy()){let r={sessionsScanned:0,sessionsWithWork:0,sessionsExcluded:0,prompts:0,toolUses:0,summaries:0,alreadyRecorded:0,outOfOrder:0};if(!(0,jt.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=py(t.projectDir).filter(i=>t.sinceMs===null||i.lastModifiedMs>=t.sinceMs),s=!1,o=d0(e);for(let i of n){r.sessionsScanned++;let a;try{a=await fy(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 c0(c,()=>h0(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 E0(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 fa(t){let e=await ue(t,{timeoutMs:s0});if(!e.ok)throw new Error(`${t} answered ${e.status}`);return e.json()}async function S0(t){let e=encodeURIComponent(t);try{let r=[];for(let o=0;;o+=100){let i=await fa(`/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 fa(`/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 fa(`/api/observations?contentSessionId=${e}&limit=1`);return{prompts:r,toolUseIds:n,hasObservations:(s.items?.length??0)>0}}catch{return null}}function Sy(t){return(0,ga.join)(N(),"state","transcript-import",`${t.replace(/[^A-Za-z0-9_-]/g,"_")}.json`)}function y0(t){try{let e=JSON.parse((0,jt.readFileSync)(Sy(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 b0(t){let e=Bo(),r=0;for(let n of(()=>{try{return(0,jt.readdirSync)(e)}catch{return[]}})())if(n.endsWith(".json"))try{JSON.parse((0,jt.readFileSync)((0,ga.join)(e,n),"utf8")).payload?.contentSessionId===t&&r++}catch{}return r}function w0(){try{return(0,jt.readdirSync)(Bo()).filter(t=>t.endsWith(".json")).length}catch{return 0}}async function T0(){try{let t=await fa("/api/processing-status");return(typeof t.queueDepth=="number"?t.queueDepth:0)+w0()}catch{return null}}function yy(t=()=>{}){return{async sendPrompt(e){await Fo(e)},async sendToolUse(e){await FS.execute(e)},async sendSummary(e){await ry.execute(e)},readRecorded:S0,readLedger:y0,pendingSpoolFor:b0,saveLedger:(e,r)=>U(Sy(e),r),usesServerRuntime:()=>$e().runtime==="server",now:()=>Date.now(),backlog:T0,ensureWorker:()=>Mr(),sleep:e=>new Promise(r=>setTimeout(r,e)),log:t,projectOf:e=>oo(e).primary,shouldTrack:rt,isDropped(e){let r=K();return Zr(e.toolName)||Mt(e.toolName,r.MEMINDEX_SKIP_TOOLS)||Fr(e.agentId,e.agentType,r).skip}}}var jt,ga,_y,pd,t0,pa,r0,n0,s0,my,i0,l0,f0,m0,wy=E(()=>{"use strict";jt=require("fs"),ga=require("path");CS();Zc();LS();ny();ru();ne();C();sy();xr();Qe();Mn();na();C();Xo();Pr();Rt();nt();iy();Qt();gy();_y="claude-code",pd=40,t0=3e3,pa=15*6e4,r0=5,n0=2e3,s0=15e3,my=100;i0="Usage: memindex transcript import [--since <ISO time>] [--until <ISO time>] [--project-dir <folder>] [--dry-run]";l0=20;f0=500;m0=11e3});rn();var Iy=require("fs");C();qe();var Yt=require("fs"),jd=require("os"),xs=require("path");ne();C();var Sr=G.transcriptsConfig(),ks=G.transcriptsState(),nb={version:1,schemas:{},watches:[],stateFile:ks};function Hd(t){let e=typeof t.schema=="string"?t.schema:t.schema?.name;if(!(t.name==="codex"||e==="codex")||!t.path)return!1;let n=ae(t.path).replace(/\\/g,"/"),s=(0,xs.join)((0,jd.homedir)(),".codex","sessions").replace(/\\/g,"/");return n===`${s}/**/*.jsonl`}function Xd(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&&Hd(t)}var sb={path:"payload.source.subagent.thread_spawn"};function Kd(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)Hd(i)?r?(n+=1,o.push({...i,subagentOnly:!0,subagentSource:{...sb}})):s+=1:o.push(i);return{config:{...t,watches:o},scoped:n,removed:s}}function ae(t){return t&&vd(t)}var Ce=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Wd={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 cn(t,e){F(t===void 0||typeof t=="string",e,"must be a string")}function Ps(t,e){F(typeof t=="string"&&t.trim().length>0,e,"must be a non-empty string")}function Gd(t,e){F(t===void 0||typeof t=="boolean",e,"must be true or false")}function zd(t,e){typeof t!="string"&&(F(Ce(t),e,"must be a path string or an object"),cn(t.path,`${e}.path`),t.coalesce!==void 0&&(F(Array.isArray(t.coalesce),`${e}.coalesce`,"must be an array"),t.coalesce.forEach((r,n)=>zd(r,`${e}.coalesce[${n}]`))))}function Vd(t,e){F(Ce(t),e,"must be an object");for(let r of["path","regex","contains","not_contains","starts_with","not_starts_with"])cn(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")}Gd(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)=>Vd(s,`${e}.${r}[${o}]`)))}}function Oa(t,e){F(Ce(t),e,"must be an object"),Ps(t.name,`${e}.name`);for(let r of["eventTypePath","sessionIdPath","cwdPath","projectPath"])cn(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(Ce(r),s,"must be an object"),F(typeof r.name=="string",`${s}.name`,"must be a string"),F(typeof r.action=="string"&&Object.hasOwn(Wd,r.action),`${s}.action`,`must be one of ${Object.keys(Wd).join(", ")}`),r.match!==void 0&&Vd(r.match,`${s}.match`),r.fields!==void 0){F(Ce(r.fields),`${s}.fields`,"must be an object");for(let[o,i]of Object.entries(r.fields))zd(i,`${s}.fields.${o}`)}})}function ob(t,e,r){F(Ce(t),e,"must be an object"),Ps(t.name,`${e}.name`),Ps(t.path,`${e}.path`);for(let i of["workspace","project","agentId"])cn(t[i],`${e}.${i}`);for(let i of["startAtEnd","subagentOnly"])Gd(t[i],`${e}.${i}`);let{subagentSource:n,context:s}=t;if(n!==void 0&&(F(Ce(n),`${e}.subagentSource`,"must be an object"),F(typeof n.path=="string",`${e}.subagentSource.path`,"must be a string")),s!==void 0&&(F(Ce(s),`${e}.context`,"must be an object"),F(s.mode==="agents",`${e}.context.mode`,'must be "agents"'),cn(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(Ce(t.schema),`${e}.schema`,"must be a schema name or an inline schema object"),Oa(t.schema,`${e}.schema`);return}Ps(t.schema,`${e}.schema`);let o=r?.[t.schema];o!==void 0&&Oa(o,`schemas.${t.schema}`)}function ib(t){F(Ce(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(Ce(r),"schemas","must be an object");for(let[s,o]of Object.entries(r))Oa(o,`schemas.${s}`)}F(Array.isArray(n),"watches","must be an array"),n.forEach((s,o)=>ob(s,`watches[${o}]`,r))}function Ma(t=Sr){let e=ae(t);if(!(0,Yt.existsSync)(e))throw new Error(`Transcript watch config not found: ${e}`);let r=ut(e);try{ib(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=ks),r}function Pa(t=Sr){let e=ae(t),r=(0,xs.dirname)(e);(0,Yt.existsSync)(r)||(0,Yt.mkdirSync)(r,{recursive:!0}),(0,Yt.writeFileSync)(e,JSON.stringify(nb,null,2))}var AS=require("crypto"),X=require("fs"),OS=require("fs/promises"),Q=require("path");O();var un=require("fs"),qd=require("path");O();ne();function Je(t,e){return typeof t!="object"||t===null||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(r=>e(r[1])))}function Jd(t){try{if(!(0,un.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:Je(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(Je(e.partials,n))),e.partialBytes!==void 0&&(s.partialBytes=o(Je(e.partialBytes,i=>typeof i=="string"&&i.length>0&&Buffer.from(i,"base64").toString("base64")===i))),e.frameLines!==void 0&&(s.frameLines=o(Je(e.frameLines,r))),e.fileIdentities!==void 0&&(s.fileIdentities=o(Je(e.fileIdentities,n))),e.checkpointFingerprints!==void 0&&(s.checkpointFingerprints=o(Je(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(Je(e.pendingTools,i))).map(([c,u])=>[c,Object.fromEntries(Object.entries(Je(u,i)).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 ab=64*1024,Yd=new WeakMap;function cb(t){let e=Yd.get(t);return e||(e=(t.toolInput===void 0?0:Buffer.byteLength(JSON.stringify(t.toolInput)??""))<=ab?t:{toolName:t.toolName},Yd.set(t,e)),e}function ub(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]=cb(a)}}return e}function ln(t,e){try{let r=(0,qd.dirname)(t);(0,un.existsSync)(r)||(0,un.mkdirSync)(r,{recursive:!0});let n=e.pendingTools?{...e,pendingTools:ub(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 hs=_e(require("path"),1);Zc();Cr();O();ke();gt();Pr();xr();nr();An();Qe();ou();Mn();var iu="write_file",im={async execute(t){let{sessionId:e,cwd:r,filePath:n,edits:s}=t,o=V(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(!rt(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=$e();if(c.runtime==="server"){if(Mt(iu,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:o,sourceType:"hook",eventType:"tool_use",occurredAtEpoch:Date.now(),payload:{tool_name:iu,tool_input:i,tool_response:a,cwd:r,platformSource:o},...jo(r)};try{return await c.client.recordEvent(u),f.debug("HOOK","File edit sent successfully via server",{filePath:n}),await kr(c.client,We(c)),{continue:!0,suppressOutput:!0}}catch(l){if(mt(l))return Be(l.kind,{status:l.status,message:l.message,route:"/v1/events",held:!0}),Ot({op:"event",request:u},We(c)),{continue:!0,suppressOutput:!0};if(Ue(l)&&l.isFallbackEligible())Be(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 He("file_edit",{contentSessionId:e,platformSource:o,toolName:iu,toolInput:i,toolResponse:a,cwd:r}),f.debug("HOOK","File edit observation spooled",{filePath:n}),{continue:!0,suppressOutput:!0}}};Rt();C();O();Qt();var Xe=require("fs"),Ho=require("path");O();O();qe();Rt();C();En();var au="<memindex-context>",cu="</memindex-context>",_v=["agent-mem-context"].map(t=>({open:`<${t}>`,close:`</${t}>`}));function am(t){return[{open:au,close:cu},..._v].reduce((e,r)=>e??Ev(t,r.open,r.close),null)}function Ev(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 _F=G.settings();function cm(t,e){let r=`${au}
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:ny(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||(ny(p.timestamp)??Date.now()),transcriptByteOffset:_.transcriptByteOffset,lastUserMessage:_.lastUserMessage},userTurnLine:_.userTurnLine})}}}}return a.filter(u=>!e.currentTurnOnly||u.userTurnLine===o).map(u=>u.call)}var ze,qP,oy=E(()=>{"use strict";ze=require("fs");st();qP=2*1024*1024});function tx(t,e,r,n){if(!e||K().MEMINDEX_CAPTURE_ADVISOR_CALLS!=="true"||$e().runtime==="server")return;let s=sy(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+=iy)He("advisor_calls",{contentSessionId:t,platformSource:n,cwd:r,transcriptPath:e,calls:s.slice(o,o+iy).map(i=>({toolUseId:i.toolUseId,advice:i.advice,advisorModel:i.advisorModel,occurredAtEpoch:i.occurredAtEpoch,lastUserMessage:i.lastUserMessage,transcriptByteOffset:i.transcriptByteOffset}))})}}async function rx(t,e,r){return await Qc(t.client,e,void 0,r),f.debug("HOOK","Summary request queued via server"),await Cr(t.client,je(t)),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS}}var ay,cy,iy,uy,ly=E(()=>{"use strict";Fr();O();qS();ay=require("crypto"),cy=require("path");QS();st();Ye();At();nt();kr();ry();Nr();nr();On();oy();Ze();iy=50;uy={async execute(t){if(t.cwd&&!rt(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"&&ty(e);try{tx(e,r,t.cwd,V(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=cd(r,!0,i);s=d.model,o=d.turnId}else s=r?VS(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=cd(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=V(t.platform),c=t.platform==="claude-code"?ZS():void 0,u=$e();if(u.runtime==="server"){let d={projectId:u.projectId,contentSessionId:e,platformSource:a,lastAssistantMessage:n,occurredAtEpoch:Date.now()},p=d;try{return await rx(u,d,g=>{p=g})}catch(g){if(mt(g))return Be(g.kind,{status:g.status,message:g.message,route:"/v1/sessions/end",held:!0}),Mt({op:"summarize",request:p},je(u)),{continue:!0,suppressOutput:!0,exitCode:D.SUCCESS};if(Ue(g)&&g.isFallbackEligible())Be(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,ay.randomUUID)());let l=He("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,cy.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 dy=E(()=>{"use strict"});function fy(t){let e=t.trim(),n=Ie(t).trim()||e;return n.length<=dd?n:(f.debug("DB","Truncated stored prompt text to the configured cap",{originalLength:n.length,storedLength:dd}),`${n.slice(0,dd-1)}\u2026`)}var dd,fd,py=E(()=>{"use strict";st();O();dd=4e3,fd="[media prompt]"});function nx(t){if(typeof t!="string")return null;let e=Date.parse(t);return Number.isFinite(e)?e:null}function Ey(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>bt(e)&&e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(`
32
+ `):""}function ix(t){if(t.type!=="user"||t.isSidechain===!0||t.isMeta===!0||t.isCompactSummary===!0)return null;let e=bt(t.message)?t.message:null;if(!e)return null;let r=e.content;if(Array.isArray(r)&&r.some(i=>bt(i)&&i.type==="tool_result"))return null;let n=bt(t.origin)?t.origin:null;if(n){if(n.kind!=="human")return null}else if(typeof t.promptSource=="string"&&!ox.has(t.promptSource))return null;let s=Ey(r),o=s.trimStart();return!n&&sx.some(i=>o.startsWith(i))||!s.trim()&&!Array.isArray(r)?null:s}function ax(t){return typeof t=="string"?t:Ey(t)}async function*cx(t){let e=(0,_y.createInterface)({input:(0,Ve.createReadStream)(t,{encoding:"utf8"}),crlfDelay:1/0});for await(let r of e)if(r.trim())try{let n=JSON.parse(r);bt(n)&&(yield n)}catch{}}async function gy(t,e={}){let r=[],n=new Map,s=null,o=e.agentId!==void 0,i=0;for await(let a of cx(t)){i++,s===null&&typeof a.cwd=="string"&&a.cwd.trim()&&(s=a.cwd);let c=nx(a.timestamp),u=bt(a.message)?a.message:null;if(a.type==="assistant"&&u&&Array.isArray(u.content)){for(let l of u.content)bt(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(!bt(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=ax(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=ix(a);if(l!==null){let d=typeof a.uuid=="string"&&a.uuid?a.uuid:`${(0,Wt.basename)(t)}:${i}`;r.push({kind:"prompt",timestampMs:c,uuid:d,text:l})}}}}return{events:r,firstCwd:s}}function ux(t){try{let e=JSON.parse((0,Ve.readFileSync)(t,"utf8"));return bt(e)&&typeof e.agentType=="string"&&e.agentType?e.agentType:void 0}catch{return}}async function Sy(t,e){let r=await gy(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,Wt.basename)(a,".jsonl").replace(/^agent-/,""),u=ux(a.replace(/\.jsonl$/,".meta.json"));(await gy(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 my(t){try{return(0,Ve.statSync)(t).mtimeMs}catch{return 0}}function pd(t){try{return(0,Ve.readdirSync)(t)}catch{return[]}}function hy(t){let e=[];for(let r of pd(t).sort()){let n=lx.exec(r);if(!n)continue;let s=n[1],o=(0,Wt.join)(t,r),i=(0,Wt.join)(t,s,"subagents"),a=(0,Ve.existsSync)(i)?pd(i).filter(u=>u.startsWith("agent-")&&u.endsWith(".jsonl")).sort().map(u=>(0,Wt.join)(i,u)):[],c=Math.max(my(o),...a.map(my));e.push({sessionId:s,transcriptPath:o,subagentPaths:a,lastModifiedMs:c})}return e}function yy(t){let e=hy(t);return e.length>0?e:pd(t).sort().map(r=>(0,Wt.join)(t,r)).filter(r=>{try{return(0,Ve.statSync)(r).isDirectory()}catch{return!1}}).flatMap(hy)}var Ve,Wt,_y,bt,sx,ox,lx,by=E(()=>{"use strict";Ve=require("fs"),Wt=require("path"),_y=require("readline"),bt=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);sx=["<command-name>","<command-message>","<local-command-stdout>","<local-command-stderr>","<local-command-caveat>"],ox=new Set(["typed","queued","sdk"]);lx=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i});var gd=E(()=>{"use strict"});var wy=E(()=>{"use strict";gd()});var Ty=E(()=>{"use strict";gd()});var Iy,md,vy=E(()=>{"use strict";N();Iy=require("path");by();wy();Ty();md={id:"claude-code",label:"Claude Code",platform:"claude-code",defaultDir:()=>(0,Iy.join)(Ne,"projects"),find:yy,read:Sy}});var xy={};Is(xy,{BACKLOG_HIGH_WATER:()=>_d,CLAUDE_CODE_PLATFORM:()=>_x,TRANSCRIPT_IMPORT_USAGE:()=>Tx,defaultTranscriptImportDeps:()=>Py,formatTranscriptImportResult:()=>Lx,isPromptSkippedByWorker:()=>Ed,isoOf:()=>Ts,matchRecordedPrompts:()=>Oy,parseTranscriptImportArgs:()=>wx,promptKey:()=>nn,runTranscriptImport:()=>Fx});function wx(t){let e=null,r=null,n=(0,ga.join)(Ne,"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 nn(t){return fy(Ie(t.trim()?t:fd))}function Ay(t){let e=t.replace(/\s+/g," ").trim();return e.length>Ry?`${e.slice(0,Ry-1)}\u2026`:e}function Ts(t){return t===null?"(no time)":new Date(t).toISOString()}function Oy(t,e,r){let n=e.map(c=>nn(c.text)),s=new Set,o=new Map;for(let c of[...t].reverse()){if(!r.has(c.uuid))continue;let u=nn(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=nn(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 hd(t,e){let r=BS.normalizeInput(t);return r.platform=e,r}function vx(t){let e=r=>Math.min(Ix,(typeof r=="string"?r:JSON.stringify(r??"")).length);return e(t.toolInput)+e(t.failed?t.error:t.toolResponse)}function Rx(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 Ax(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 Ox(t){let e=await t.backlog();if(e===null||e<=_d)return;let r=Date.now(),n=e,s=0;for(;e!==null&&e>_d;)if(Date.now()-s>=3e4&&(t.log(` waiting for the worker to catch up (${e} items queued)`),s=Date.now()),await t.sleep(Ex),e=await t.backlog(),e!==n)n=e??n,r=Date.now();else if(Date.now()-r>pa)throw new Error(`the worker has not taken any queued work for ${Math.round(pa/6e4)} minutes (${e} items queued)`)}function Px(t){let e=0;return{async check(r=!1){e++,!(!r&&e<Mx)&&(e=0,await Ox(t))}}}async function kx(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(xx),r=t.pendingSpoolFor(e),r!==s)s=r,n=t.now();else if(t.now()-n>pa)throw new Error(`the worker has not taken this session's queued events for ${Math.round(pa/6e4)} minutes (${r} waiting)`)}function Ed(t){return ko(t)||t.trim()!==""&&Ie(t).trim()===""}async function Nx(t,e){for(let r=1;;r++)try{await t.sendPrompt(e);return}catch(n){if(!(n instanceof Dr)||r>=Sx)throw n;await t.sleep(yx*r)}}async function Dx(t,e,r,n,s,o,i,a){let c={prompts:0,toolUses:0,summaries:0,alreadyRecorded:0,outOfOrder:0,toolChars:0,summaryChars:0},u=new Set(n.prompts),l=new Set(n.summaries),d=Oy(t.events.filter(v=>v.kind==="prompt"),r.prompts,u),p=t.events.flatMap((v,y)=>v.kind==="prompt"&&d.has(v.uuid)&&!u.has(v.uuid)?[y]:[]),g=r.hasObservations&&r.prompts.length>0&&r.toolUseIds.size===0,m=t.sessionId,h=new Map;for(let v of r.prompts){let y=nn(v.text);h.set(y,Math.max(h.get(y)??Number.NEGATIVE_INFINITY,v.createdAtEpochMs))}let _=null,S=0,b=()=>{s.dryRun||(n.prompts=[...u],n.summaries=[...l],o.saveLedger(m,n))},w=()=>{let v=_?.anchor;if(!v)return;let y=v.atEpochMs+1+_.anchored;return y>=v.beforeEpochMs?Math.max(v.atEpochMs,v.beforeEpochMs-1):(_.anchored++,y)},R=async()=>{if(!_?.summaryOwed||!_.last||!hr(_.last.timestampMs,s))return;let v=_.last.text.join(`
33
+ `);if(s.dryRun)o.log(` summary ${Ts(_.last.timestampMs)} ${Ay(v)}`);else{let y=hd({session_id:m,cwd:e,hook_event_name:"Stop",last_assistant_message:v},a);y.lastAssistantMessage=v,y.spoolAtEpochMs=w(),y.turnId=_.uuid,await i.check(),await o.sendSummary(y),S++,l.add(_.uuid),b()}c.summaries++,c.summaryChars+=v.length};for(let v=0;v<t.events.length;v++){let y=t.events[v];if(y.kind==="prompt"){await R();let I=nn(y.text),A=d.get(y.uuid)??null,T=u.has(y.uuid),P=A?r.prompts.find(_r=>_r.createdAtEpochMs>A.createdAtEpochMs):void 0;if(_={uuid:y.uuid,summaryOwed:T&&!l.has(y.uuid),anchor:A?{atEpochMs:A.createdAtEpochMs,beforeEpochMs:P?.createdAtEpochMs??Number.POSITIVE_INFINITY}:null,anchored:0,capturedLive:A!==null&&!T,last:null},A){hr(y.timestampMs,s)&&c.alreadyRecorded++;continue}if(T&&Ed(y.text)){_.skippedByWorker=!0,_.summaryOwed=!1,hr(y.timestampMs,s)&&c.alreadyRecorded++;continue}if(_.summaryOwed=!1,!hr(y.timestampMs,s))continue;if(s.dryRun)o.log(` prompt ${Ts(y.timestampMs)} ${Ay(y.text)||fd}`);else{await i.check(!0);let _r=(h.get(I)??Number.NEGATIVE_INFINITY)+Cx-o.now();_r>0&&await o.sleep(_r),S>0&&await kx(o,m),S=0,u.add(y.uuid),b(),await Nx(o,hd({session_id:m,cwd:e,hook_event_name:"UserPromptSubmit",prompt:y.text,transcript_path:t.transcriptPath},a)),h.set(I,o.now())}if(Ed(y.text)){_.skippedByWorker=!0,c.prompts++;continue}p.some(_r=>_r>v)&&(c.outOfOrder++,o.log(` note: the prompt at ${Ts(y.timestampMs)} is added after later turns memory already holds, so it is numbered after them`)),_.summaryOwed=!l.has(y.uuid),c.prompts++;continue}if(y.kind==="assistant"){if(!_)continue;_.last&&_.last.messageId===y.messageId?_.last.text.push(y.text):_.last={messageId:y.messageId,text:[y.text],timestampMs:y.timestampMs},y.timestampMs!==null&&(_.last.timestampMs=y.timestampMs);continue}if(hr(y.timestampMs,s)&&!_?.skippedByWorker){if(r.toolUseIds.has(y.toolUseId)||g&&(!_||_.capturedLive)){c.alreadyRecorded++;continue}if(!o.isDropped(y)){if(s.dryRun){let I=y.agentId?` (subagent ${y.agentType??y.agentId})`:"";o.log(` tool use ${Ts(y.timestampMs)} ${y.toolName} ${y.toolUseId}${y.failed?" failed":""}${I}`)}else{let I=hd(Rx(m,e,y),a);I.spoolAtEpochMs=w(),await o.sendToolUse(I),S++,r.toolUseIds.add(y.toolUseId),await i.check()}c.toolUses++,c.toolChars+=vx(y)}}}return await R(),c}async function Fx(t,e=Py(),r=md){let n={sessionsScanned:0,sessionsWithWork:0,sessionsExcluded:0,prompts:0,toolUses:0,summaries:0,alreadyRecorded:0,outOfOrder:0,toolChars:0,summaryChars:0,sessionsWithoutFolder:0};if(!(0,Ht.existsSync)(t.projectDir))return n.error=`no ${r===md?"transcripts":`${r.label} chats`} folder at ${t.projectDir}`,n;if(!t.dryRun&&e.usesServerRuntime())return n.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",n;if(!t.dryRun&&!await e.ensureWorker())return n.error="the MemIndex worker is not running and could not be started",n;let s=r.find(t.projectDir).filter(a=>t.sinceMs===null||a.lastModifiedMs>=t.sinceMs),o=!1,i=Px(e);for(let a of s){n.sessionsScanned++;let c;try{c=await r.read(a,g=>hr(g,t))}catch(g){e.log(`Skipped ${a.transcriptPath}: ${g instanceof Error?g.message:String(g)}`);continue}if(!c.events.some(g=>hr(g.timestampMs,t)))continue;let u=c.projectDir;if(!u){n.sessionsWithoutFolder++;continue}if(!e.shouldTrack(u)){n.sessionsExcluded++;continue}let l=await e.readRecorded(c.sessionId);if(l===null){if(!t.dryRun){n.error=`could not read what the worker already holds for session ${c.sessionId}; stopped so nothing is sent twice`;break}o||(e.log("The worker is not answering, so this preview cannot leave out what it already holds."),o=!0)}let d=e.projectOf(u);t.dryRun&&e.log(`Session ${c.sessionId} project ${d} (${u})`);let p;try{p=await Ax(u,()=>Dx(c,u,l??{prompts:[],toolUseIds:new Set,hasObservations:!1},e.readLedger(c.sessionId),t,e,i,r.platform))}catch(g){n.error=`session ${c.sessionId}: ${g instanceof Error?g.message:String(g)}`;break}n.prompts+=p.prompts,n.toolUses+=p.toolUses,n.summaries+=p.summaries,n.alreadyRecorded+=p.alreadyRecorded,n.outOfOrder+=p.outOfOrder,n.toolChars+=p.toolChars,n.summaryChars+=p.summaryChars,p.prompts+p.toolUses+p.summaries>0&&(n.sessionsWithWork++,t.dryRun||e.log(`Session ${c.sessionId} (${d}): ${p.prompts} prompts, ${p.toolUses} tool uses, ${p.summaries} summaries sent`))}return n}function Lx(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 fa(t){let e=await le(t,{timeoutMs:bx});if(!e.ok)throw new Error(`${t} answered ${e.status}`);return e.json()}async function Ux(t){let e=encodeURIComponent(t);try{let r=[];for(let o=0;;o+=100){let i=await fa(`/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 fa(`/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 fa(`/api/observations?contentSessionId=${e}&limit=1`);return{prompts:r,toolUseIds:n,hasObservations:(s.items?.length??0)>0}}catch{return null}}function My(t){return(0,ga.join)(C(),"state","transcript-import",`${t.replace(/[^A-Za-z0-9_-]/g,"_")}.json`)}function $x(t){try{let e=JSON.parse((0,Ht.readFileSync)(My(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 Bx(t){let e=Bo(),r=0;for(let n of(()=>{try{return(0,Ht.readdirSync)(e)}catch{return[]}})())if(n.endsWith(".json"))try{JSON.parse((0,Ht.readFileSync)((0,ga.join)(e,n),"utf8")).payload?.contentSessionId===t&&r++}catch{}return r}function jx(){try{return(0,Ht.readdirSync)(Bo()).filter(t=>t.endsWith(".json")).length}catch{return 0}}async function Wx(){try{let t=await fa("/api/processing-status");return(typeof t.queueDepth=="number"?t.queueDepth:0)+jx()}catch{return null}}function Py(t=()=>{}){return{async sendPrompt(e){await Fo(e)},async sendToolUse(e){await HS.execute(e)},async sendSummary(e){await uy.execute(e)},readRecorded:Ux,readLedger:$x,pendingSpoolFor:Bx,saveLedger:(e,r)=>U(My(e),r),usesServerRuntime:()=>$e().runtime==="server",now:()=>Date.now(),backlog:Wx,ensureWorker:()=>xr(),sleep:e=>new Promise(r=>setTimeout(r,e)),log:t,projectOf:e=>io(e).primary,shouldTrack:rt,isDropped(e){let r=K();return tn(e.toolName)||Pt(e.toolName,r.MEMINDEX_SKIP_TOOLS)||Ur(e.agentId,e.agentType,r).skip}}}var Ht,ga,_x,_d,Ex,pa,Sx,yx,bx,Ry,Tx,Ix,Mx,xx,Cx,ky=E(()=>{"use strict";Ht=require("fs"),ga=require("path");jS();tu();XS();ly();su();re();N();dy();Nr();Ze();Pn();na();N();Xo();kr();At();st();py();Zt();vy();_x="claude-code",_d=40,Ex=3e3,pa=15*6e4,Sx=5,yx=2e3,bx=15e3,Ry=100;Tx="Usage: memindex transcript import [--since <ISO time>] [--until <ISO time>] [--project-dir <folder>] [--dry-run]";Ix=16e3;Mx=20;xx=500;Cx=11e3});sn();var Cy=require("fs");N();qe();var Yt=require("fs"),zd=require("os"),ks=require("path");re();N();var yr=G.transcriptsConfig(),Ns=G.transcriptsState(),mb={version:1,schemas:{},watches:[],stateFile:Ns};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=ce(t.path).replace(/\\/g,"/"),s=(0,ks.join)((0,zd.homedir)(),".codex","sessions").replace(/\\/g,"/");return n===`${s}/**/*.jsonl`}function Yd(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 hb={path:"payload.source.subagent.thread_spawn"};function qd(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)Vd(i)?r?(n+=1,o.push({...i,subagentOnly:!0,subagentSource:{...hb}})):s+=1:o.push(i);return{config:{...t,watches:o},scoped:n,removed:s}}function ce(t){return t&&Md(t)}var Ce=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Gd={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 ln(t,e){F(t===void 0||typeof t=="string",e,"must be a string")}function xs(t,e){F(typeof t=="string"&&t.trim().length>0,e,"must be a non-empty string")}function Jd(t,e){F(t===void 0||typeof t=="boolean",e,"must be true or false")}function Zd(t,e){typeof t!="string"&&(F(Ce(t),e,"must be a path string or an object"),ln(t.path,`${e}.path`),t.coalesce!==void 0&&(F(Array.isArray(t.coalesce),`${e}.coalesce`,"must be an array"),t.coalesce.forEach((r,n)=>Zd(r,`${e}.coalesce[${n}]`))))}function Qd(t,e){F(Ce(t),e,"must be an object");for(let r of["path","regex","contains","not_contains","starts_with","not_starts_with"])ln(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")}Jd(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)=>Qd(s,`${e}.${r}[${o}]`)))}}function Pa(t,e){F(Ce(t),e,"must be an object"),xs(t.name,`${e}.name`);for(let r of["eventTypePath","sessionIdPath","cwdPath","projectPath"])ln(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(Ce(r),s,"must be an object"),F(typeof r.name=="string",`${s}.name`,"must be a string"),F(typeof r.action=="string"&&Object.hasOwn(Gd,r.action),`${s}.action`,`must be one of ${Object.keys(Gd).join(", ")}`),r.match!==void 0&&Qd(r.match,`${s}.match`),r.fields!==void 0){F(Ce(r.fields),`${s}.fields`,"must be an object");for(let[o,i]of Object.entries(r.fields))Zd(i,`${s}.fields.${o}`)}})}function _b(t,e,r){F(Ce(t),e,"must be an object"),xs(t.name,`${e}.name`),xs(t.path,`${e}.path`);for(let i of["workspace","project","agentId"])ln(t[i],`${e}.${i}`);for(let i of["startAtEnd","subagentOnly"])Jd(t[i],`${e}.${i}`);let{subagentSource:n,context:s}=t;if(n!==void 0&&(F(Ce(n),`${e}.subagentSource`,"must be an object"),F(typeof n.path=="string",`${e}.subagentSource.path`,"must be a string")),s!==void 0&&(F(Ce(s),`${e}.context`,"must be an object"),F(s.mode==="agents",`${e}.context.mode`,'must be "agents"'),ln(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(Ce(t.schema),`${e}.schema`,"must be a schema name or an inline schema object"),Pa(t.schema,`${e}.schema`);return}xs(t.schema,`${e}.schema`);let o=r?.[t.schema];o!==void 0&&Pa(o,`schemas.${t.schema}`)}function Eb(t){F(Ce(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(Ce(r),"schemas","must be an object");for(let[s,o]of Object.entries(r))Pa(o,`schemas.${s}`)}F(Array.isArray(n),"watches","must be an array"),n.forEach((s,o)=>_b(s,`watches[${o}]`,r))}function xa(t=yr){let e=ce(t);if(!(0,Yt.existsSync)(e))throw new Error(`Transcript watch config not found: ${e}`);let r=lt(e);try{Eb(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=Ns),r}function ka(t=yr){let e=ce(t),r=(0,ks.dirname)(e);(0,Yt.existsSync)(r)||(0,Yt.mkdirSync)(r,{recursive:!0}),(0,Yt.writeFileSync)(e,JSON.stringify(mb,null,2))}var CS=require("crypto"),X=require("fs"),DS=require("fs/promises"),Z=require("path");O();var dn=require("fs"),tf=require("path");O();re();function Je(t,e){return typeof t!="object"||t===null||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(r=>e(r[1])))}function rf(t){try{if(!(0,dn.existsSync)(t))return{offsets:{}};let e=lt(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:Je(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(Je(e.partials,n))),e.partialBytes!==void 0&&(s.partialBytes=o(Je(e.partialBytes,i=>typeof i=="string"&&i.length>0&&Buffer.from(i,"base64").toString("base64")===i))),e.frameLines!==void 0&&(s.frameLines=o(Je(e.frameLines,r))),e.fileIdentities!==void 0&&(s.fileIdentities=o(Je(e.fileIdentities,n))),e.checkpointFingerprints!==void 0&&(s.checkpointFingerprints=o(Je(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(Je(e.pendingTools,i))).map(([c,u])=>[c,Object.fromEntries(Object.entries(Je(u,i)).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 Sb=64*1024,ef=new WeakMap;function yb(t){let e=ef.get(t);return e||(e=(t.toolInput===void 0?0:Buffer.byteLength(JSON.stringify(t.toolInput)??""))<=Sb?t:{toolName:t.toolName},ef.set(t,e)),e}function bb(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]=yb(a)}}return e}function fn(t,e){try{let r=(0,tf.dirname)(t);(0,dn.existsSync)(r)||(0,dn.mkdirSync)(r,{recursive:!0});let n=e.pendingTools?{...e,pendingTools:bb(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 _s=_e(require("path"),1);tu();Fr();O();Ye();nt();kr();Nr();nr();On();Ze();au();Pn();var cu="write_file",fm={async execute(t){let{sessionId:e,cwd:r,filePath:n,edits:s}=t,o=V(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(!rt(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=$e();if(c.runtime==="server"){if(Pt(cu,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:o,sourceType:"hook",eventType:"tool_use",occurredAtEpoch:Date.now(),payload:{tool_name:cu,tool_input:i,tool_response:a,cwd:r,platformSource:o},...Wo(r)};try{return await c.client.recordEvent(u),f.debug("HOOK","File edit sent successfully via server",{filePath:n}),await Cr(c.client,je(c)),{continue:!0,suppressOutput:!0}}catch(l){if(mt(l))return Be(l.kind,{status:l.status,message:l.message,route:"/v1/events",held:!0}),Mt({op:"event",request:u},je(c)),{continue:!0,suppressOutput:!0};if(Ue(l)&&l.isFallbackEligible())Be(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 He("file_edit",{contentSessionId:e,platformSource:o,toolName:cu,toolInput:i,toolResponse:a,cwd:r}),f.debug("HOOK","File edit observation spooled",{filePath:n}),{continue:!0,suppressOutput:!0}}};At();N();O();Zt();var Xe=require("fs"),Ho=require("path");O();O();qe();At();N();Sn();var uu="<memindex-context>",lu="</memindex-context>",Av=["agent-mem-context"].map(t=>({open:`<${t}>`,close:`</${t}>`}));function pm(t){return[{open:uu,close:lu},...Av].reduce((e,r)=>e??Ov(t,r.open,r.close),null)}function Ov(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 CF=G.settings();function gm(t,e){let r=`${uu}
34
34
  ${e}
35
- ${cu}`;if(!t)return r;let n=am(t);return n?t.substring(0,n.start)+r+t.substring(n.end):t+`
35
+ ${lu}`;if(!t)return r;let n=pm(t);return n?t.substring(0,n.start)+r+t.substring(n.end):t+`
36
36
 
37
- ${r}`}O();function um(t,e){if(!t)return;let r=(0,Ho.resolve)(t);if(r.includes("/.git/")||r.includes("\\.git\\")||r.endsWith("/.git")||r.endsWith("\\.git"))return;let n=(0,Ho.dirname)(t);(0,Xe.existsSync)(n)||(0,Xe.mkdirSync)(n,{recursive:!0});let s="";(0,Xe.existsSync)(t)&&(s=(0,Xe.readFileSync)(t,"utf-8"));let o=`# Memory Context
37
+ ${r}`}O();function mm(t,e){if(!t)return;let r=(0,Ho.resolve)(t);if(r.includes("/.git/")||r.includes("\\.git\\")||r.endsWith("/.git")||r.endsWith("\\.git"))return;let n=(0,Ho.dirname)(t);(0,Xe.existsSync)(n)||(0,Xe.mkdirSync)(n,{recursive:!0});let s="";(0,Xe.existsSync)(t)&&(s=(0,Xe.readFileSync)(t,"utf-8"));let o=`# Memory Context
38
38
 
39
- ${e}`,i=cm(s,o),a=`${t}.tmp`;try{(0,Xe.writeFileSync)(a,i),(0,Xe.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 Sv(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 Pn(t,e){if(!e)return;let r=Sv(e),n=t;for(let s of r){if(n==null)return;n=n[s]}return n}function lm(t){return t==null||t===""}function dm(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 Dr(t,e,r){if(t!==void 0){if(typeof t=="string"){let n=dm(t,r);return n!==void 0?n:Pn(e,t)}if(t.coalesce&&Array.isArray(t.coalesce))for(let n of t.coalesce){let s=Dr(n,e,r);if(!lm(s))return s}if(t.path){let n=dm(t.path,r);if(n!==void 0)return n;let s=Pn(e,t.path);if(!lm(s))return s}if(t.value!==void 0)return t.value;if(t.default!==void 0)return t.default}}function fm(t,e,r){let n={};if(!t)return n;for(let[s,o]of Object.entries(t))n[s]=Dr(o,e,r);return n}function xn(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(!xn(t,i,r))return!1}if(e.any!==void 0&&(!Array.isArray(e.any)||!e.any.some(i=>xn(t,i,r))))return!1;let n=e.path||r.eventTypePath||"type",s=n?Pn(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}gt();Cr();O();nt();En();Xo();Mn();qe();C();var or=require("path");C();function bv(t=G.dataDir()){return(0,or.join)(t,"bottles")}function hm(t,e){let r=(0,or.resolve)(bv(e));return(0,or.resolve)(t).startsWith(r+or.sep)}Qt();gt();O();var Ko=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 Lr=require("path");function Em(){let t=wv();return async e=>{for(let r of e)r.module=t(r.filename);return e}}function wv(t=process.argv[1]?(0,Lr.dirname)(process.argv[1]):process.cwd(),e=Lr.sep==="\\"){let r=e?_m(t):t;return n=>{if(!n)return;let s=e?_m(n):n,{dir:o,base:i,ext:a}=Lr.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 _m(t){return t.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var ee={};Ts(ee,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>ai,DOMExceptionCoercer:()=>Ru,EXCEPTION_STEP_INTERNAL_FIELDS:()=>Wn,ErrorCoercer:()=>Ln,ErrorEventCoercer:()=>Au,ErrorPropertiesBuilder:()=>Fn,EventCoercer:()=>Ou,ExceptionStepsBuffer:()=>ku,ObjectCoercer:()=>$n,PrimitiveCoercer:()=>Bn,PromiseRejectionEventCoercer:()=>Mu,ReduceableCache:()=>Pu,StringCoercer:()=>Un,chromeStackLineParser:()=>wu,createDefaultStackParser:()=>vu,createStackParser:()=>ch,geckoStackLineParser:()=>Tu,getInjectedReleaseId:()=>FR,getUtf8ByteLength:()=>lh,nodeStackLineParser:()=>rh,opera10StackLineParser:()=>Zm,opera11StackLineParser:()=>eh,resolveExceptionStepsConfig:()=>xu,reverseAndStripFrames:()=>ah,stripReservedExceptionStepFields:()=>NR,winjsStackLineParser:()=>Qm});var he=(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 Pt(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 Tv=Array.isArray,ym=Object.prototype,UF=ym.hasOwnProperty,Go=ym.toString,ye=Tv||function(t){return Go.call(t)==="[object Array]"};var kn=t=>t===Object(t)&&!ye(t);var _t=t=>t===void 0,ie=t=>Go.call(t)=="[object String]",uu=t=>ie(t)&&t.trim().length===0,lu=t=>t===null,Ke=t=>_t(t)||lu(t),Ur=t=>Go.call(t)=="[object Number]"&&t===t;var bm=t=>Go.call(t)==="[object Boolean]";function zo(t){return t===null||typeof t!="object"}function ir(t,e){return Object.prototype.toString.call(t)===`[object ${e}]`}function xt(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 Im(t,Error)}}function wm(t){return ir(t,"ErrorEvent")}function $r(t){return"u">typeof Event&&Im(t,Event)}function Tm(t){return ir(t,"Object")}function Im(t,e){try{return t instanceof e}catch{return!1}}var Iv=["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"],Vo=new Map,vv=256;function Rv(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 vm=function(t,e=[]){if(!t)return!1;let r=Rv(t,e),n=Vo.get(r);if(n!==void 0)return n;let s=t.toLowerCase(),o=Iv.concat(e).some(i=>s.indexOf(i.toLowerCase())!==-1);return Vo.size>=vv&&Vo.clear(),Vo.set(r,o),o};function Nn(t,e,r,n,s){return e>r&&(n.warn("min cannot be greater than max."),e=r),Ur(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),Nn(s??r,e,r,n))}var Av=864e5,Ov=1,Mv=10;function Rm(t={}){return{refillRate:t.exceptionRateLimiterRefillRate??t.__exceptionRateLimiterRefillRate??Ov,bucketSize:t.exceptionRateLimiterBucketSize??t.__exceptionRateLimiterBucketSize??Mv}}var Yo=class{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=Nn(e.bucketSize,0,100,e._logger),this._refillRate=Nn(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=Nn(e.refillInterval,0,Av,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 qo="0123456789abcdef",Jo=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+=qo.charAt(this.bytes[r]>>>4),e+=qo.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+=qo.charAt(this.bytes[r]>>>4),e+=qo.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}},du=class{constructor(e){this.timestamp=0,this.counter=0,this.random=e??Pv()}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 Jo.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,Jo.ofInner(e)}},Pv=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),Am,de=()=>xv().toString(),xv=()=>(Am||(Am=new du)).generate();var Qo=class{add(e){let r=de(),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 kv(t=console){return{log:t.log.bind(t),warn:t.warn.bind(t),error:t.error.bind(t),debug:t.debug.bind(t)}}var Om=(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=>Om(`${t} ${o}`,e,r)}},Nv=t=>t();function Mm(t,e=Nv){return Om(t,e,kv())}var Wr="Mobile",ei="iOS",Br="Android",Cm="Tablet",ZF=Br+" "+Cm;var Dv="Apple",eL=Dv+" Watch",Dm="Safari",ti="BlackBerry",Fm="Samsung",Fv=Fm+"Browser",Lv=Fm+" Internet",ri="Chrome",Uv=ri+" OS",$v=ri+" "+ei,Lm="Internet Explorer",Bv=Lm+" "+Wr,gu="Opera",tL=gu+" Mini",Um="Edge",Wv="Microsoft "+Um,mu="Firefox",jv=mu+" "+ei,hu="Nintendo",_u="PlayStation",Zo="Xbox",Hv=Br+" "+Wr,Xv=Wr+" "+Dm,Cn="Windows",Kv=Cn+" Phone";var $m="Generic",rL=$m+" "+Wr.toLowerCase(),nL=$m+" "+Cm.toLowerCase(),Gv="Konqueror",zv="Oculus Browser",Pm="Vivaldi",Vv="Yandex",xm="Whale",Yv="DuckDuckGo",qv="Pale Moon",km="Waterfox",Nm="Brave",Bm="Claude",Wm="Codex",jm="ChatGPT",Jv="Google Search App",B="(\\d+(\\.\\d+)?)",fu=new RegExp("Version/"+B),pu=new RegExp("("+Bm+"|"+Wm+"|"+jm+")\\/"+B);var sL=new RegExp(Zo,"i"),oL=new RegExp(_u+" \\w+","i"),iL=new RegExp(hu+" \\w+","i"),Qv=new RegExp(ti+"|PlayBook|BB10","i"),Zv={"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 aL={[Bv]:[new RegExp("rv:"+B)],[Wv]:[new RegExp(Um+"?\\/"+B)],[ri]:[new RegExp("("+ri+"|CrMo)\\/"+B)],[$v]:[new RegExp("CriOS\\/"+B)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+B)],[Dm]:[fu],[Xv]:[fu],[gu]:[new RegExp("("+gu+"|OPR)\\/"+B)],[mu]:[new RegExp(mu+"\\/"+B)],[jv]:[new RegExp("FxiOS\\/"+B)],[Gv]:[new RegExp("Konqueror[:/]?"+B,"i")],[ti]:[new RegExp(ti+" "+B),fu],[Hv]:[new RegExp("android\\s"+B,"i")],[Lv]:[new RegExp(Fv+"\\/"+B)],[zv]:[new RegExp("OculusBrowser\\/"+B)],[Pm]:[new RegExp(Pm+"\\/"+B)],[Vv]:[new RegExp("YaBrowser\\/"+B)],[xm]:[new RegExp(xm+"\\/"+B)],[Nm]:[new RegExp(Nm+"\\/"+B)],[Bm]:[pu],[Wm]:[pu],[jm]:[pu],[Yv]:[new RegExp("(DuckDuckGo|Ddg)\\/"+B)],[qv]:[new RegExp("PaleMoon\\/"+B)],[km]:[new RegExp(km+"\\/"+B)],[Jv]:[new RegExp("GSA\\/"+B)],[Lm]:[new RegExp("(rv:|MSIE )"+B)],Mozilla:[new RegExp("rv:"+B)]};var cL=[[new RegExp(Zo+"; "+Zo+" (.*?)[);]","i"),t=>[Zo,t&&t[1]||""]],[new RegExp(hu,"i"),[hu,""]],[new RegExp(_u,"i"),[_u,""]],[Qv,[ti,""]],[new RegExp(Cn,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Kv,""];if(new RegExp(Wr).test(e)&&!/IEMobile\b/.test(e))return[Cn+" "+Wr,""];let r=/Windows NT ([0-9.]+)/i.exec(e);if(r&&r[1]){let n=r[1],s=Zv[n]||"";return/arm/i.test(e)&&(s="RT"),[Cn,s]}return[Cn,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>{if(t&&t[3]){let e=[t[3],t[4],t[5]||"0"];return[ei,e.join(".")]}return[ei,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{let e="";return t&&t.length>=3&&(e=_t(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Br+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Br+")","i"),t=>{if(t&&t[2]){let e=[t[2],t[3],t[4]||"0"];return[Br,e.join(".")]}return[Br,""]}],[/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/,[Uv,""]],[/Linux|debian/i,["Linux",""]]];var ni="[Circular]",si="[Truncated]",Ie="[Unserializable]",Hm="[Function]",dL=Date.prototype.getTime,fL=Date.prototype.toISOString;function st(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 Et(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=Ie}Object.defineProperty(t,n,{value:s,enumerable:!0,writable:!0,configurable:!0})}return t}function Eu(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 ar=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 Xm="utf8",eR=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function tR(t){return typeof t=="string"&&eR.test(t)}function cr(t,e){return tR(t)?t:e()}function jr(t,e){let r=new Error(e);try{Object.defineProperty(r,"name",{value:t,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function Km(t){return t?.replace(/\/+$/,"")}async function Gm(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 Su(){return new Date().toISOString()}function fe(t,e){let r=setTimeout(t,e);return r?.unref&&r?.unref(),r}async function kt(t,e,r){let n;try{return await Promise.race([t,new Promise((s,o)=>{n=fe(()=>{try{r?.(),s()}catch(i){o(i)}},e)})])}finally{clearTimeout(n)}}var zm=t=>t&&typeof t.then=="function";function Dn(t){return Promise.all(t.map(e=>(e??Promise.resolve()).then(r=>({status:"fulfilled",value:r}),r=>({status:"rejected",reason:r}))))}var yu,Vm,Ym,Hr;function Jm(t){let e=globalThis._posthogChunkIds,r=globalThis._debugIds;if(!e&&!r)return;let n=e?Object.keys(e):[],s=r?Object.keys(r):[];if(Hr&&qm(e,n,Vm)&&qm(r,s,Ym))return Hr;Vm=e?{...e}:void 0,Ym=r?{...r}:void 0,Hr={},yu??={};let o=(i,a)=>{for(let c of i){let u=a[c];if(!u)continue;let l=yu?.[c];if(l){Hr[l]=u;continue}let d=t(c);for(let p=d.length-1;p>=0;p--){let g=d[p]?.filename;if(g){Hr[g]=u,yu[c]=g;break}}}};return r&&o(s,r),e&&o(n,e),Hr}function qm(t,e,r){return!t||!r?t===r:e.length===Object.keys(r).length&&e.every(n=>t[n]===r[n])}var bu=50,rR=1e3,nR=100,sR=4,Fn=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&&ye(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:Jm(this.stackParser),skipFirstLines:e.skipFirstLines??1}}getAggregateErrors(e){try{if(xt(e)){let r=Object.getPrototypeOf(e);for(let n=0;r&&n<nR;n++){let s=Object.getOwnPropertyDescriptor(r,"constructor")?.value;if(typeof s=="function"&&s.name==="AggregateError"){let o=e.errors;return ye(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>sR||h>0&&c.indexOf(g)!==-1)return this.coerceFallback(_);let b=typeof g=="object"&&g!==null||typeof g=="function";if(h===0&&s>=bu||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>=bu)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<bu&&o<rR&&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="?",oR="<anonymous>",iR=/^([a-z][a-z0-9.+-]+):/i,aR=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function cR(t){if(!t||t===oR)return!1;let e=iR.exec(t);return!e||aR.includes(e[1].toLowerCase())}function ot(t,e,r,n,s){let o={platform:t,filename:e,function:r==="<anonymous>"?re:r,in_app:cR(e)};return _t(n)||(o.lineno=n),_t(s)||(o.colno=s),o}var oi=(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 uR=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,lR=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,dR=/\((\S*)(?::(\d+))(?::(\d+))\)/,wu=(t,e)=>{let r=uR.exec(t);if(r){let[,s,o,i]=r;return ot(e,s,re,+o,+i)}let n=lR.exec(t);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=dR.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}let[o,i]=oi(n[1]||re,n[2]);return ot(e,i,o,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var fR=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,pR=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Tu=(t,e)=>{let r=fR.exec(t);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let i=pR.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]=oi(o,s),ot(e,s,o,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var gR=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,Qm=(t,e)=>{let r=gR.exec(t);return r?ot(e,r[2],r[1]||re,+r[3],r[4]?+r[4]:void 0):void 0};var mR=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,Zm=(t,e)=>{let r=mR.exec(t);return r?ot(e,r[2],r[3]||re,+r[1]):void 0},hR=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,eh=(t,e)=>{let r=hR.exec(t);return r?ot(e,r[5],r[3]||r[4]||re,+r[1],+r[2]):void 0};var _R=/^\s*[-]{4,}$/,ER=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,SR=/^Promise\.(?:all|any)$/,yR=/^index \d+$/,bR="node:internal/promise",rh=(t,e)=>{let r=t.match(ER);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]),SR.test(o)&&yR.test(c||"")&&(c=bR),{filename:c?decodeURI(c):void 0,module:void 0,function:o,lineno:th(r[3]),colno:th(r[4]),in_app:wR(c||"",u),platform:e}}if(t.match(_R))return{filename:t,platform:e}};function wR(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 th(t){return parseInt(t||"",10)||void 0}var nh=/\(error: (.*)\)/,sh=50,TR=10,IR=1e3;function Iu(t,e){return t.filename===e.filename&&t.function===e.function&&t.module===e.module&&t.lineno===e.lineno&&t.colno===e.colno}function vR(t){for(let e=1;e<=TR;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(!Iu(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 RR(t,e){let r=e.start+e.length,n=ih(t,e);n&&t.splice(r+n===t.length?r:e.start,n)}function oh(t,e){let r=e.start;for(;r>0&&Iu(t[r-1],t[r-1+e.length]);)r--;return e.start-r}function ih(t,e){let r=e.start+e.length,n=r;for(;n<t.length&&Iu(t[n],t[n-e.length]);)n++;return n-r}function AR(t,e){let r=e[0],n=t.length-(r?oh(t,r):0);for(let s of e)n-=ih(t,s);return n}function OR(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++)MR(e,n,r)&&(r=n);t.push(...t.splice(0,r))}function MR(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 ah(t){if(!t.length)return[];let e=Array.from(t);return e.reverse(),e.slice(0,sh).map(r=>({...r,filename:r.filename||PR(e).filename,function:r.function||re}))}function PR(t){return t[t.length-1]||{}}function vu(){return ch("web:javascript",wu,Tu)}function ch(t,...e){return(r,n=0)=>{let s=[],o=r.split(`
40
- `),i=Math.min(o.length,n+IR),a=[];for(let l=n;l<i;l++){let d=o[l];if(d.length>1024)continue;let p=nh.test(d)?d.replace(nh,"$1"):d;if(!p.match(/\S*Error: /)){for(let g of e){let m=g(p,t);if(m){s.push(m);let h=vR(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(AR(s,a)>=sh)break}}let c=[...a].sort((l,d)=>d.start-l.start),u=c[c.length-1];if(u){let l=oh(s,u);s.splice(u.start-l,l);for(let d of c)d.start-=l}for(let l of c)RR(s,l);return a.some(l=>l.start===0&&s.length===l.length)&&OR(s),ah(s)}}var Ru=class{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,r){let n=ie(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 ir(e,"DOMException")}isDOMError(e){return ir(e,"DOMError")}};var Ln=class{match(e){return xt(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 Au=class{match(e){if(!wm(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 ie(e.message)&&e.message.length>0}_buildLocationStack(e){let r=e,n=r.lineno??0,s=r.colno??0;if(!(!ie(r.filename)||r.filename.length===0)&&n!==0)return`Error
41
- at ${r.filename}:${n}:${s}`}};var xR=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,Un=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(xR);return s&&(r=s[1],n=s[2]),[r,n]}};var uh=["fatal","error","warning","log","info","debug"];function ii(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 $n=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($r(e))return e.constructor.name;let r="name"in e?e.name:void 0;return ie(r)&&!uu(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=ii(e);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(e){return ie(e)&&!uu(e)&&uh.indexOf(e)>=0}getStack(e){try{return ie(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:ie(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(xt(n))return n}}getObjectClassName(e){try{let r=Object.getPrototypeOf(e);return r?r.constructor.name:void 0}catch{return}}};var Ou=class{match(e){return $r(e)}coerce(e,r){let n=e.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${ii(e)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Bn=class{match(e){return zo(e)}coerce(e,r){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var Mu=class{match(e){return ir(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!$r(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 zo(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 Pu=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 Wn={MESSAGE:"$message",TIMESTAMP:"$timestamp"},kR=new Set([Wn.MESSAGE,Wn.TIMESTAMP]),ai={enabled:!0,max_bytes:32768};function xu(t){return t?{enabled:t.enabled??ai.enabled,max_bytes:CR(t.max_bytes,ai.max_bytes)}:{...ai}}function NR(t){if(!t)return{sanitizedProperties:{},droppedKeys:[]};let e=[];return{sanitizedProperties:Object.keys(t).reduce((n,s)=>kR.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=DR(e);if(!r)return;let n=lh(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 CR(t,e){if(!Ur(t)||t===1/0||t===-1/0)return e;let r=Math.floor(t);return r<0?e:r}function DR(t){let e;try{e=Pt(t)}catch{return}try{let r=JSON.parse(e);if(!kn(r))return;let n=r,s=n[Wn.MESSAGE],o=n[Wn.TIMESTAMP];return!ie(s)||s.trim().length===0||!ie(o)&&!Ur(o)?void 0:{step:n,json:e}}catch{return}}function lh(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 FR(){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 Nu=t=>{if("flags"in t){let e=dh(t.flags),r=fh(t.flags);return{...t,featureFlags:e,featureFlagPayloads:r}}{let e=t.featureFlags??{},r=Object.fromEntries(Object.entries(t.featureFlagPayloads||{}).map(([s,o])=>[s,Xr(o)])),n=Object.fromEntries(Object.entries(e).map(([s,o])=>[s,LR(s,o,r[s])]));return{...t,featureFlags:e,featureFlagPayloads:r,flags:n}}};function LR(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 dh=t=>Object.fromEntries(Object.entries(t??{}).map(([e,r])=>[e,jn(r)]).filter(([,e])=>e!==void 0)),fh=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?Xr(n):void 0]}))},jn=t=>t===void 0?void 0:t.variant??t.enabled,Xr=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};var ph=["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"],UR=["$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",...ph,"$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Hn=(t,e=[])=>{let r={},n=s=>{t[s]!==void 0&&(r[s]=t[s])};return UR.forEach(n),e.forEach(n),r};var ci=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 Cu(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var BR="NativeGzipValidationError",WR=31,jR=139,HR=8,XR=t=>t.length>=2&&t[0]===WR&&t[1]===jR;var Xn,KR=()=>{if(Xn)return Xn;Xn=[];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;Xn[t]=e>>>0}return Xn},GR=t=>{let e=KR(),r=4294967295;for(let n=0;n<t.length;n++)r=e[(r^t[n])&255]^r>>>8;return(4294967295^r)>>>0},ui=t=>{throw jr(BR,`Native gzip produced invalid output: ${t}`)},zR=async(t,e)=>{t.size<18&&ui("too-short");let r=new Uint8Array(await t.slice(0,10).arrayBuffer());(!XR(r)||r[2]!==HR)&&ui("invalid-header");let n=new DataView(await t.slice(t.size-8).arrayBuffer());n.getUint32(0,!0)!==GR(e)&&ui("invalid-crc");let s=e.length>>>0;n.getUint32(4,!0)!==s&&ui("invalid-size")};async function Kn(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 zR(c,n),c}catch(n){if(r?.rethrow)throw n;return e&&console.error("Failed to gzip compress data",n),null}}var ve=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 Eu(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=jr("AbortError","Response body read timed out");this.cancelResponseBody(e),this.responseBodyTextPromise=Promise.reject(e)}else{let e=new Promise((n,s)=>{this.responseBodyTimer=fe(()=>{this._bodyReadTimedOut=!0;let o=jr("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{}})()}},St=class extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}};var VR=(t,e)=>{for(let r of Object.keys(e))(r.startsWith("$feature/")||r==="$active_feature_flags")&&(t[r]=e[r])};async function gh(t){if(t instanceof ve){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 YR(t){return typeof t=="object"&&(t instanceof ve||Eh(t))}function Eh(t){return t instanceof St}function qR(t){if(t instanceof ve)return t.status===502||t.status===504;if(!(t instanceof St))return!1;let e=t.error;return(e?.code??e?.cause?.code)!=="ECONNREFUSED"}var mh=10485760;function hh(t){try{return typeof t!="string"?t instanceof Uint8Array?t.byteLength:t.size:"u">typeof Buffer?Buffer.byteLength(t,Xm):new TextEncoder().encode(t).length}catch{return 0}}function Kr(t){return typeof t=="object"&&t instanceof ve&&t.status===413}function li(t){return t instanceof ve?t.status===408||t.status===429||t.status>=500:Eh(t)}function _h(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Du="default",Gn=class{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new Fn([new Ln,new $n,new Un,new Bn],vu())}getEvaluationRuntime(){}constructor(e,r={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new Qo,this._events=new ci,this._isInitialized=!1;let n=typeof e=="string"?e.trim():"",s=typeof r.host=="string"?r.host.trim():"",o=!n;this._logger=Mm("[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=Km(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:li},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=!Cu()||(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(he.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(he.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(he.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 VR(n,r),e.event==="$feature_flag_called"&&n.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled()&&(n=Hn(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:qR},this.featureFlagsRequestTimeoutMs).then(p=>({success:!0,response:Nu(p)})).catch(p=>(this._events.emit("error",p),{success:!1,error:this.categorizeRequestError(p)}))}categorizeRequestError(e){if(e instanceof ve)return{type:"api_error",statusCode:e.status};if(e instanceof St){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=jn(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(he.Props)),this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(he.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(he.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return Du}persistedQueueKeyForRoute(e){return he.Queue}getActiveQueueRoutes(){return[Du]}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=fe(()=>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=_h(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=cr(o.uuid,de),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:Su(),uuid:cr(r?.uuid,de)};return(r?.disableGeoip??this.disableGeoip)&&(_h(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 gh(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(()=>Dn([r])).then(()=>(this.pendingFlushPromise===s&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=s,this.flushPromise=s,this.flushPromises.add(s),this.addPendingPromise(s),Dn([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=Du){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:Su()};this.historicalMigration&&(s.historical_migration=!0);let o=Pt(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=>Kr(d)?!1:li(d)};try{await this.sendBatch(c,l,e)}catch(d){if(Kr(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 St||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=hh(s);if(o>mh)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${e} batch of ${o} bytes: the endpoint accepts at most ${mh}`)),{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=>Kr(l)||l instanceof ve&&l.retryAfterMs!==void 0?!1:li(l)}),{kind:"ok"}}catch(l){if(Kr(l))return{kind:"too-large"};if(li(l)){let d=l instanceof ve?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=hh(i),c={...this._retryOptions,...s},u=0;return await Gm(async()=>{u++;let l=new AbortController,d=o??this.requestTimeout,p=Date.now()+d,g,m=new Promise((w,T)=>{g=fe(()=>{let y=jr("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 St(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 St(A)}let T=r.mode==="no-cors",y=n.type==="successful-write"?300:400;if(!T&&(h.status<200||h.status>=y))throw new ve(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 St(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 ve&&l.cancelResponseBody(),d}})}async _shutdown(e=3e4){await this._initPromise;let r=!1;return this.clearFlushTimer(),this.disabled?void 0:kt((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(!YR(s))throw s;await gh(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 tA=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi;var E$=new RegExp(tA.source,"i"),Sh=/[a-z][a-z0-9+.-]{0,63}:\/\//i,S$=new RegExp(`^${Sh.source}`,"i"),y$=new RegExp(Sh.source,"gi");var rA=["is_not","is_set"],nA=1152921504606847e3,M=class t extends Error{constructor(e){super(e),this.name=this.constructor.name,Object.setPrototypeOf(this,t.prototype)}};function Fu(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(!Fu(e in t?t[e]:null))return!1;return!0}function Lu(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(!Lu(e in t?t[e]:null))return!1;return!0}function zn(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 fi(t,e=new Set){if(!(t===null||typeof t=="boolean")){if(typeof t=="string")return void zn(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&&fi(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))zn(n),fi(t[n],e)}finally{e.delete(t)}return}throw new M(`Cannot represent ${typeof t} like the flags service`)}}function sA(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 Uu(t,e=new Set){if(t===null)return"null";if(typeof t=="string")return zn(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?Uu(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(zn),`{${n.sort(sA).map(s=>`${JSON.stringify(s)}:${Uu(t[s],e)}`).join(",")}}`}finally{e.delete(t)}}throw new M(`Cannot stringify ${typeof t} like the flags service`)}function di(t){return typeof t=="string"?(zn(t),t):Uu(t)}function yh(t){try{return new RegExp(t),!0}catch{return!1}}function Re(t){return String(t).replace(/[A-Z]/g,e=>e.toLowerCase())}function wh(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 J(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("."),o=i=>i===void 0||i===""?0:wh(i,t,e);return[o(s[0]),o(s[1]),o(s[2])]}function Ae(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 oA(t,e){let r=J(t,e);return{lower:[r[0],r[1],r[2]],upper:[r[0],r[1]+1,0]}}function iA(t,e){let[r,n,s]=J(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 aA(t,e){let n=String(t).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!n)throw new M(`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 wh(c,t,e)}catch{}throw new M(`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 bh(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 $u(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 Bu(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 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 ${o} operator`),o==="is_not";if(c===null&&!rA.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&&Fu(d)||Array.isArray(d)&&d.length===0)return fi(p),Lu(d)===Lu(p);if(r.propertyMatchingVersion===2&&typeof p=="number"&&Fu(d))return fi(p),!1;if(Array.isArray(d)){let g=di(p).toLowerCase();return d.some(m=>di(m).toLowerCase()===g)}return di(d).toLowerCase()===di(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 Re(c).includes(Re(s));case"not_icontains":return!Re(c).includes(Re(s));case"starts_with":return Re(c).startsWith(Re(s));case"not_starts_with":return!Re(c).startsWith(Re(s));case"ends_with":return Re(c).endsWith(Re(s));case"not_ends_with":return!Re(c).endsWith(Re(s));case"regex":return yh(String(s))&&String(c).match(String(s))!==null;case"not_regex":return yh(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 M("Date operations cannot be performed on boolean values");let d=$u(String(s));d==null&&(d=bh(s));let p=bh(c);return o==="is_date_before"?p<d:p>d}case"semver_eq":return Ae(J(String(c),i),J(String(s),i))===0;case"semver_neq":return Ae(J(String(c),i),J(String(s),i))!==0;case"semver_gt":return Ae(J(String(c),i),J(String(s),i))>0;case"semver_gte":return Ae(J(String(c),i),J(String(s),i))>=0;case"semver_lt":return Ae(J(String(c),i),J(String(s),i))<0;case"semver_lte":return Ae(J(String(c),i),J(String(s),i))<=0;case"semver_tilde":{let d=J(String(c),i),{lower:p,upper:g}=oA(String(s),i);return Ae(d,p)>=0&&Ae(d,g)<0}case"semver_caret":{let d=J(String(c),i),{lower:p,upper:g}=iA(String(s),i);return Ae(d,p)>=0&&Ae(d,g)<0}case"semver_wildcard":{let d=J(String(c),i),{lower:p,upper:g}=aA(String(s),i);return Ae(d,p)>=0&&Ae(d,g)<0}default:throw new M(`Unknown operator: ${o}`)}}async function Th(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 Vn(t,e,r="",n="."){let s=await Th(`${t}${n}${e}${r}`);return parseInt(s.slice(0,15),16)/nA}async function Wu(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 Vn("holdout",e,"","-")>n/100))return`holdout-${t.id}`}function pi(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 ju(t,e,r){let n=await Vn(t,e,"variant");return pi(r).find(s=>n>=s.valueMin&&n<s.valueMax)?.key}function Hu(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:Xr(n)}var Ih=9223372036854776e3,cA="9223372036854775808",uA=Object.prototype.propertyIsEnumerable;function lA(){return{ancestors:new WeakSet,remainingNodes:1e4}}function it(t,e){try{return vh(t,e,lA(),0)}catch{return[]}}function dA(t,e){let r=t.toString(),n=BigInt(cA);return t>=n||t<-n?(e?.debug(`Attribute ${r} is outside the int64 range; encoding it as a string`),{stringValue:r}):{intValue:r}}function Gu(t,e,r,n){if(r.remainingNodes<=0)return{stringValue:si};if(r.remainingNodes--,bm(t))return{boolValue:t};if(typeof t=="bigint")return dA(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>=Ih||t<-Ih?(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:st(t)};if(typeof t=="function")return{stringValue:Hm};if(typeof t=="symbol")return{stringValue:String(t)};if(typeof t=="object"&&t!==null){if(r.ancestors.has(t))return{stringValue:ni};if(n>=20)return{stringValue:si};if(t instanceof Date){let s=t.getTime(),o=Number.isFinite(s)?t.toISOString():String(t);return{stringValue:typeof o=="string"?st(o):String(o)}}r.ancestors.add(t);try{try{let s=t.toJSON;if(typeof s=="function")return Gu(s.call(t),e,r,n+1)}catch{}return ye(t)?{arrayValue:{values:fA(t,e,r,n+1)}}:{kvlistValue:{values:vh(t,e,r,n+1)}}}finally{r.ancestors.delete(t)}}return{stringValue:st(String(t))}}function fA(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(Ke(a))continue;s.push(Gu(a,e,r,n))}catch{s.push({stringValue:Ie})}return t.length>i&&s.push({stringValue:si}),s}function vh(t,e,r,n){let s=[];for(let o in t)if(uA.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(lu(i)||_t(i))continue;s.push({key:st(o),value:Gu(i,e,r,n)})}catch{s.push({key:st(o),value:{stringValue:Ie}})}}return s}function qn(t,e,r){return{...Et({},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 pA=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function Jn(t,e){let r=Et({},t),n={};for(let s of pA)Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s],delete r[s]);return[...it(r,e),...it(n,e)]}var Rh={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 gA(t){if(t)return Object.prototype.hasOwnProperty.call(Rh,t)?Rh[t]:t}function zu(t,e){let r=gA(t);return{...r?{"os.name":r}:{},...e?{"os.version":e}:{}}}var mA={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}},F$=mA.info;var ur=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=fe(()=>{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 Qn(){return 1-.25+Math.random()*.25*2}var Oe=1;function Zn(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 Vu="0000000000000000",SA=Vu+Vu,yA=/^[0-9a-f]+$/;function bA(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 wA(t){let e="";for(let r=0;r<t.length;r++)e+=t[r].toString(16).padStart(2,"0");return e}function Ah(t){let e=wA(bA(t));return/[^0]/.test(e)?e:e.slice(0,-1)+"1"}function Oh(){return Ah(16)}function Mh(){return Ah(8)}function Ph(t,e,r){return typeof t=="string"&&t.length===e&&t!==r&&yA.test(t)}function xh(t){return Ph(t,32,SA)}function kh(t){return Ph(t,16,Vu)}var TA=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function mi(t){let e=Nh(t);return e&&{traceId:e.traceId,spanId:e.spanId,flags:IA(e.flags)}}function IA(t){return 1&parseInt(t,16)?Gr:vA}function Nh(t){if(typeof t!="string")return;let e=TA.exec(t.trim());if(!e)return;let[,r,n,s,o,i]=e;if(r!=="ff"&&!(r==="00"&&i)&&!(!xh(n)||!kh(s)))return{version:r,traceId:n,spanId:s,flags:o}}function Ch(t){return Nh(t)&&t.trim()}function hi(t){return Array.isArray(t)&&t.length===1?t[0]:t}var Gr="01",vA="00";function Dh(t,e,r=Gr){return`00-${t}-${e}-${r}`}var RA=32,Yu=512;function _i(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>RA)){for(let n of r)if(n.trim()&&!n.includes("="))return;return e.length<=Yu?e:OA(r)}}var AA=128;function OA(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()>Yu;n--)e[n].length>AA&&e.splice(n,1);for(;e.length&&r()>Yu;)e.pop();return e.length?e.join(","):void 0}var es=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Ei(t){return String(t)+"000000"}function qu(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 Fh(t,e){for(let r=0;r<e.length;r++)if(t<=e[r])return r;return e.length}function Ju(t,e,r){return qn(t,e,r)}function Qu(t,e,r,n){return{resourceMetrics:[{resource:{attributes:Jn(e)},scopeMetrics:[{scope:{name:r,version:n},metrics:t}]}]}}function Si(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 Lh=1,ts=class{constructor(e,r,n){this._instance=e,this._config=r,this._logger=n,this._series=new Map,this._flushTimer=new ur(()=>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 ar,this._consecutiveFlushFailures=0,this._flushJitter=Oe,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=Oe,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=qu(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=mi(this._instance.getActiveSpan?.()?.traceparent());if(e&&e.flags===Gr)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(es.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[Fh(r,es)]+=1;break}}}_runBeforeSend(e){let r=this._config.beforeSend;if(!r)return e;let n=ye(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(Zn(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=Qn()):(this._consecutiveFlushFailures=0,this._flushJitter=Oe),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 Qu(this._buildMetrics(e),Ju(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(e){let r=Ei(Date.now()),n=new Map;for(let s of e.values()){let o=qu(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:Lh,isMonotonic:!0,dataPoints:[]}:s.type==="gauge"?i.gauge={dataPoints:[]}:i.histogram={aggregationTemporality:Lh,dataPoints:[]},n.set(o,i));let a=it(s.attributes??{},this._logger),c=Ei(s.windowStartMs),u=MA(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:es,...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 MA(t){return t?{exemplars:[{filteredAttributes:[],timeUnixNano:Ei(t.timeMs),asDouble:t.value,traceId:t.traceId,spanId:t.spanId}]}:{}}var Uh="unknown";function lr(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 zr(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 $h(t,e,r){let n=zr(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 yi(t,e){return t<e?e:t}function rs(t,e,r,n){let s=zr(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 wi(){let t=globalThis.performance;return typeof t?.now=="function"?t.now():void 0}var Vr=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??Gr,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:wi(),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=wi();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(Ke(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]=Ii(r,this._maxAttributeValueLength)}setAttribute(e,r){return this._mutable("setAttribute")&&this._writeAttribute(e,r),this}setAttributes(e){if(this._mutable("setAttributes")){let r=Et({},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&&Hh(r,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:lr(e,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:rs(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:Zu(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}=el(e);return this.addEvent(PA,{"exception.type":r,"exception.message":n,...s&&{"exception.stacktrace":s}}),this.setStatus("error",n)}updateName(e){return this._mutable("updateName")&&(this._name=lr(e,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return Dh(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=rs(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:yi(n,this._startTime),...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}},PA="exception",xA=4294967295;function kA(t){try{return typeof t=="string"?t:String(t)}catch{return Ie}}function dr(t){return typeof t!="number"||!Number.isFinite(t)||t<=0?0:Math.min(Math.floor(t),xA)}function NA(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 Wh(t,e,r,n,s,o,i=[]){let a=0,c=0,u={};for(let g of NA(t.attributes,i)){let m=t.attributes[g];if(!Ke(m)){if(!e.has(g)){if(a>=r){c++;continue}a++}Object.defineProperty(u,g,{value:Ii(m,o),enumerable:!0,writable:!0,configurable:!0})}}t.attributes=u,c&&(t.droppedAttributesCount=dr(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=Hh(g.attributes,s,o);g.attributes=m.attributes,m.dropped&&(g.droppedAttributesCount=dr(g.droppedAttributesCount)+m.dropped)}p.push(g)}t.events=p,d&&(t.droppedEventsCount=dr(t.droppedEventsCount)+d),t.status?.message&&(t.status={...t.status,message:Zu(kA(t.status.message),o)})}var Ti=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 Ti,ns=class extends Ti{constructor(e,r){super(),this._traceparent=e,this._tracestate=r}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}};function CA(t){try{let e=t.stack;return typeof e=="string"&&e?{stack:e}:{}}catch{return{}}}function Nt(t,e){let r=hi(t?.parent)??e,n=typeof r=="string"||r==null?r:Bh(r,"traceparent"),s=Ch(n);if(!s)return jh;let o=typeof r=="string"||r==null?t?.tracestate:Bh(r,"tracestate");return new ns(s,_i(o))}function Bh(t,e){try{let r=t[e];return typeof r=="function"?r.call(t):void 0}catch{return}}function Zu(t,e){return t.length>e?t.slice(0,e):t}function Ii(t,e){return bi(t,e,{ancestors:new WeakSet,remainingNodes:1e4},0)}function bi(t,e,r,n){if(t===null||typeof t!="object")return Ke(t)||r.remainingNodes<=0?t:(r.remainingNodes--,typeof t=="string"?Zu(t,e):t);if(r.ancestors.has(t))return ni;if(r.remainingNodes<=0||n>=20)return t;r.remainingNodes--,r.ancestors.add(t);try{if(t instanceof Date)return t;let s=DA(t);if(s.selfDescribed)return Ke(s.value)?String(s.value):bi(s.value,e,r,n+1);if(ye(t)){let a=Math.min(t.length,1e3),c=[];for(let u=0;u<a;u++)try{c.push(bi(t[u],e,r,n+1))}catch{c.push(Ie)}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=bi(t[a],e,r,n+1)}catch{c=Ie}a&&!Ke(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 DA(t){try{let e=t.toJSON;if(typeof e=="function")return{selfDescribed:!0,value:e.call(t)}}catch{}return{selfDescribed:!1}}function Hh(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=Ii(t[a],r)}catch{c=Ie}Ke(c)||(o++,Object.defineProperty(s,a,{value:c,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:s,dropped:i}}function Xh(t,e){for(let r of Object.keys(t))t[r]=Ii(t[r],e);return t}function ss(t,e,r){return e===jh?r(e):t.with(e,()=>r(e))}function el(t){try{let e=CA(t);if(xt(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 tl={internal:1,server:2,client:3,producer:4,consumer:5},FA={ok:1,error:2},LA=1,UA=256,$A=512;function BA(t){let e=parseInt(t.traceFlags,16);return(Number.isFinite(e)?255&e:LA)|UA|(t.parentIsRemote?$A:0)}function vi(t){if(typeof t=="string")return st(t);try{return st(String(t))}catch{return Ie}}function WA(t){return t&&Object.prototype.hasOwnProperty.call(tl,t)?tl[t]:tl.internal}function rl(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 jA(t,e){let r={name:vi(t.name),timeUnixNano:rl(t.timestamp)};if(t.attributes){let s=it(t.attributes,e);s.length&&(r.attributes=s)}let n=dr(t.droppedAttributesCount);return n&&(r.droppedAttributesCount=n),r}function Kh(t,e){let r={traceId:t.traceId,spanId:t.spanId,name:vi(t.name),kind:WA(t.kind),startTimeUnixNano:rl(t.startTime),endTimeUnixNano:rl(t.endTime),flags:BA(t)};t.parentSpanId&&(r.parentSpanId=t.parentSpanId),t.traceState&&(r.traceState=vi(t.traceState));let n=it(t.attributes,e);n.length&&(r.attributes=n),t.events.length&&(r.events=t.events.map(i=>jA(i,e)));let s=dr(t.droppedAttributesCount);s&&(r.droppedAttributesCount=s);let o=dr(t.droppedEventsCount);return o&&(r.droppedEventsCount=o),t.status&&(r.status={code:FA[t.status.code],...t.status.message&&{message:vi(t.status.message)}}),r}function Gh(t,e,r){return qn(t,e,r)}function zh(t,e,r,n,s){return{resourceSpans:[{resource:{attributes:Jn(e,s)},scopeSpans:[{scope:{name:r,version:n},spans:t}]}]}}var Vh=8;function Ri(){return wi()??Date.now()}function nl(t){try{return t instanceof Vr}catch{return!1}}function Yh(t,e){let r=mi(t);if(r)return{traceId:r.traceId,parentSpanId:r.spanId,traceState:_i(e),traceFlags:r.flags,isRemote:!0}}function HA(t){try{return typeof t.traceparent=="function"}catch{return!1}}function XA(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 Ai(t,e,r){t[e]!==r&&(t[e]=r)}function KA(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 os=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 ur(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=Oe,this._retryAfter=new ar,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 Nt(r,this._contextManager.active());let n=hi(r?.parent);if(n&&typeof n!="string"&&!nl(n)){if(HA(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),Nt(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`),Nt(r,this._contextManager.active());let o=Date.now(),i=$h(r?.startTime,o,this._logger),a=Mh();this._liveSpans.set(a,Ri());let c=this._autoContextAttributes();return new Vr({traceId:s?.traceId??Oh(),spanId:a,parentSpanId:s?.parentSpanId,traceState:s?.traceState,traceFlags:s?.traceFlags,parentIsRemote:s?.isRemote,name:lr(e,"Span name",this._config.maxAttributeValueLength,this._logger),kind:r?.kind??"internal",attributes:Et({...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:zr(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=ss(this._contextManager,i,o);return zm(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=Oe,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(nl(e))return e.childContext();let n=this._contextManager.active();if(nl(n))return n.childContext();if(n instanceof ns)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 Vr))return;let{type:n,message:s,stack:o}=el(r);e.addEvent("exception",{"exception.type":n,"exception.message":s,...o&&{"exception.stacktrace":o}}),e.statusIsExplicitlyOk||e.setStatus("error",s)}_evictAgedSpans(){let e=Ri()-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},!XA(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=lr(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=zr(l.startTime)??s.startTime,l.endTime=yi(zr(l.endTime)??s.endTime,l.startTime);let p=[];for(let g of l.events)try{p.push({...g,name:lr(g.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:rs(g.timestamp,l.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return l.events=p,Wh(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{Ai(e,"traceId",r.traceId),Ai(e,"spanId",r.spanId),Ai(e,"parentSpanId",r.parentSpanId),Ai(e,"traceState",r.traceState)}catch{return KA(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(Kh(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=Xh(Gh(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=Ri()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),h=await this._instance._sendTracesBatch(zh(g,r,n,s,this._logger));if(c!==this._generation)break;if(this._retryAfter.record(h),h.kind==="ok"){this._consecutiveFlushFailures=0,this._flushJitter=Oe,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=Oe,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=Qn(),this._headBatchSize=d,m&&(this._headBatchFailures++,this._headBatchChargeableAt=Ri()+this._nextFlushDelay()),this._headBatchFailures<Vh)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=Oe,this._resetHeadBatchBudget(),this._recordDrop(d,`the ingestion endpoint failed ${Vh} 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=Oe,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(Zn(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}};var is=class{active(){return this._active}with(e,r){let n=this._active;this._active=e;try{return r()}finally{this._active=n}}};var GA=5e3,zA=512,VA=2048,YA=128,qA=128,JA=128,QA=8192,ZA=1e4,eO=36e5;function Ct(t,e){return typeof t=="number"&&Number.isInteger(t)&&t>=1?t:e}var qh=["service.name","service.version","deployment.environment"];function tO(t){if(!(!t||typeof t!="object"||Array.isArray(t)))try{if(qh.every(r=>!(r in t)||typeof t[r]=="string"))return t;let e={...t};for(let r of qh)r in e&&typeof e[r]!="string"&&delete e[r];return e}catch{return}}function rO(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 sl(t,e,r){let n=Et({...e},tO(t?.resourceAttributes)),s=Ct(t?.maxExportBatchSize,zA);return{serviceName:n?.["service.name"]??t?.serviceName,serviceVersion:n?.["service.version"]??t?.serviceVersion,environment:n?.["deployment.environment"]??t?.environment,resourceAttributes:n,beforeSpanSend:rO(t?.beforeSpanSend,r),maxAttributesPerSpan:Ct(t?.maxAttributesPerSpan,YA),maxEventsPerSpan:Ct(t?.maxEventsPerSpan,qA),maxAttributesPerEvent:JA,maxAttributeValueLength:Ct(t?.maxAttributeValueLength,QA),flushIntervalMs:Ct(t?.flushIntervalMs,GA),maxExportBatchSize:s,maxQueueSize:Math.max(Ct(t?.maxQueueSize,VA),s),maxLiveSpans:Ct(t?.maxLiveSpans,ZA),maxSpanAgeMs:Ct(t?.maxSpanAgeMs,eO)}}var ol=require("node:fs"),Zh=require("node:fs/promises"),al=require("node:path"),e_=require("node:readline"),Oi=new ee.ReduceableCache(25),as=new ee.ReduceableCache(20),cl=7,nO=1e3,sO=1e4,il=10485760;async function t_(t,e=Zh.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"||uO(u)||lO(c)||!(0,al.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=r_(a,s);if(c===void 0||as.get(c))continue;let u=n[a];if(!u)continue;u.sort((p,g)=>p-g);let l=fO(u);if(l.every(p=>dO(c,p)))continue;let d=pO(Oi,c,{});i.push(iO(a,l,d,c,e,r))}return await Promise.all(i).catch(()=>{}),t&&t.length>0&&aO(t,Oi,s),Oi.reduce(),t}async function oO(t,e,r){let n,s=!1;try{n=await e(t,ol.constants.O_RDONLY|ol.constants.O_NONBLOCK);let o=await n.stat();return o.isFile()?o.size>il?void r?.debug(`Skipping source context for oversized file ${t}: ${o.size} bytes exceeds ${il}`):(s=!0,n):void 0}catch{return}finally{n&&!s&&await n.close().catch(()=>{})}}async function iO(t,e,r,n,s,o){let i=await oO(t,s,o);if(i===void 0)return void as.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:il-1})}catch{as.set(n,1),l();return}let p;try{p=(0,e_.createInterface)({input:d})}catch{as.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(){as.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]=gO(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 aO(t,e,r){for(let n of t)if(n.filename&&n.context_line===void 0&&typeof n.lineno=="number"){let s=r_(n.filename,r),o=s===void 0?void 0:e.get(s);if(o===void 0)continue;cO(n.lineno,n,o)}}function cO(t,e,r){if(e.lineno===void 0||r===void 0)return;e.pre_context=[];for(let s=n_(t);s<t;s++){let o=r[s];if(o===void 0)return void Jh(e);e.pre_context.push(o)}if(r[t]===void 0)return void Jh(e);e.context_line=r[t];let n=s_(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 Jh(t){delete t.pre_context,delete t.context_line,delete t.post_context}function uO(t){return t.startsWith("node:")||t.endsWith(".min.js")||t.endsWith(".min.cjs")||t.endsWith(".min.mjs")||t.startsWith("data:")}function lO(t){return t.lineno!==void 0&&t.lineno>sO||t.colno!==void 0&&t.colno>nO}function r_(t,e){return(0,al.isAbsolute)(t)?JSON.stringify([null,t]):e===void 0?void 0:JSON.stringify([e,t])}function dO(t,e){let r=Oi.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 fO(t){if(!t.length)return[];let e=0,r=t[0];if(typeof r!="number")return[];let n=Qh(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+cl:(s.push(n),n=Qh(o)),e++}return s}function Qh(t){return[n_(t),s_(t)]}function n_(t){return Math.max(1,t-cl)}function s_(t){return t+cl}function pO(t,e,r){let n=t.get(e);return n===void 0?(t.set(e,r),r):n}function gO(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 Yr=require("path");function o_(t=process.cwd()){let e=Yr.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,Yr.isAbsolute)(o.filename)&&(o.filename=r((0,Yr.relative)(n,r(o.filename))));return s}}var i_="5.56.2";var yt={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var Dt=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(yt.ERRORS_WHILE_COMPUTING),this._quotaLimited&&o.push(yt.QUOTA_LIMITED),r===void 0&&o.push(yt.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 mO=6e4;function a_(t){return t==="client"||t==="server"?t:"all"}function hO(t,e){return t===e||t==="all"||e==="all"}var fr=class t extends Error{constructor(e){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,t.prototype)}};function _O(t,e){t.name=e.name,Error.captureStackTrace(t,e),Object.setPrototypeOf(t,e.prototype)}var at=class t extends Error{constructor(e){super(e),_O(this,t)}},Mi=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 at||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 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 at||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}`)),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=Hu(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 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"&&(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 M(`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 M("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new M(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let i=e.dependency_chain;if(!Array.isArray(i))throw new M(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof i})`);if(i.length===0)throw new M(`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 M(`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 M(`Missing flag dependency '${c}' for flag '${o}'`)}if(s[c]==null)throw new M(`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 Wu(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 at)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,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 u_(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):c_(u,s,c,i.propertyMatchingVersion);if(!d)return"no_match"}if(a==null)return"match"}return a!=null&&await Vn(e.key,r)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(e,r){return ju(e.key,r,e.filters?.multivariate?.variants||[])}variantLookupTable(e){return pi(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?a_(r.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(e){return this.featureFlags.filter(r=>hO(a_(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(mO,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 fr(`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 fr(`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 fr(`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 fr&&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 fr("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=fe(()=>{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 kt(r,e,()=>{throw new Error(`Cache shutdown timeout after ${e}ms`)})}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};function c_(t,e,r,n){return Bu(t,e,{warnFunction:r,propertyMatchingVersion:n})}function EO(t,e){if(!(t in e))throw new at(`cohort ${t} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function u_(t,e,r,n=!1,s,o){let i=String(t.value);EO(i,r);let a=r[i];return l_(a,e,r,n,s,o)}async function l_(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 l_(u,e,r,n,s,o);if(i==="AND"){if(!l)return!1}else if(l)return!0}catch(l){if(l instanceof at)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 i==="AND"}for(let u of a)try{let l;if(u.type==="cohort")l=await u_(u,e,r,n,s,o);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=c_(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 at)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 i==="AND"}var SO=["--unhandled-rejections","--unhandled_rejections"],yO=new Set(["throw","strict","warn","warn-with-error-code","none"]),bO=[...globalThis.process?.execArgv??[]],wO=globalThis.process?.env?.NODE_OPTIONS;function TO(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 d_(t){let e;for(let r=0;r<t.length;r++){let n=t[r],s=SO.find(i=>n===i||n.startsWith(`${i}=`));if(!s)continue;let o=n===s?t[++r]:n.slice(s.length+1);yO.has(o)&&(e=o)}return e}function IO(t=bO,e=wO){return d_(t)??d_(TO(e??""))??"throw"}var f_=IO();function p_(t,e,r){t(e,{mechanism:{type:r==="unhandledRejection"?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function vO(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;p_(t,n,s),!r&&o===0&&(r=!0,e(n))},{_posthogErrorHandler:!0})}function g_(t,e,r=f_){let n=globalThis.process;if(n){if(r==="strict")return void n.on("uncaughtExceptionMonitor",(s,o)=>p_(t,s,o));n.on("uncaughtException",vO(t,e))}}function m_(t,e=f_){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 RO=2e3,ul=class t{constructor(e,r,n){this.client=e,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new Yo({...Rm(r),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return kn(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=ee.getInjectedReleaseId();return c&&(i.$release_id=c),{event:"$exception",distinctId:s,properties:{...a,...i},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(g_(this.onException.bind(this),this.onFatalError.bind(this)),m_(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(RO),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}},pr=ul;var oM=/^[0-9a-f]{32}$/i,iM=/^[0-9a-f]{16}$/i,aM;async function YE(){try{let e=(await(aM??=Promise.resolve().then(()=>(VE(),zE)))).trace.getActiveSpan()?.spanContext(),r=e?.traceId,n=e?.spanId;if(typeof r=="string"&&typeof n=="string"&&oM.test(r)&&iM.test(n)&&!/^0+$/.test(r)&&!/^0+$/.test(n))return{$trace_id:r.toLowerCase(),$span_id:n.toLowerCase()}}catch{}return{}}var Ki=class{getProperty(e){return this._memoryStorage[e]}setProperty(e,r){this._memoryStorage[e]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};function cM(t){return t==="v0"||t==="v1"}function qE(){let t="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return cM(t)?t:"v0"}var uM="$ai_",gs="analytics";function JE(t){return typeof t.event=="string"&&t.event.startsWith(uM)}var Qr=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 Vl(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 lM(t){return typeof t=="string"?t:void 0}var dM=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:Vl},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:Vl},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:Vl},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:lM}],fM=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function pM(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function gM(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 QE(t,e,r){r!==void 0&&!(e in t)&&(t[e]=r)}function mM(t){let r={...pM(t.properties)?t.properties:{}},n={};for(let{property:o,optionKey:i,coerce:a}of dM)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 fM)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,QE(r,"$set",t.$set),QE(r,"$set_once",t.$set_once),{event:String(t.event??""),uuid:String(t.uuid??""),distinct_id:String(t.distinct_id??""),timestamp:gM(t.timestamp),...s,options:n,properties:r}}function ZE(t,{createdAt:e,historicalMigration:r}){let n={created_at:e,batch:t.map(mM)};return r&&(n.historical_migration=!0),n}var hM="/i/v1/analytics/events",_M=3e4,EM=new Set([408,500,502,503,504]),Gi=class{constructor(e,r){this.config=e,this.maxBackoffMs=e.maxBackoffMs??_M,this.fetchFn=r.fetch,this.onError=r.onError,this.now=r.now??Date.now,this.sleep=r.sleep??(n=>new Promise(s=>fe(s,n))),this.generateRequestId=r.generateRequestId??de,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}=ZE(e,{createdAt:n,historicalMigration:this.config.historicalMigration}),o=`${this.config.host}${hM}`,i=[],a=s,c=Math.max(1,this.config.maxAttempts);for(let u=1;u<=c;u++){let l=u===c,d=Pt({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&&EM.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 Qr({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=fe(()=>{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 Qr({requestId:e,drops:r,retryExhausted:n.map(o=>o.uuid),cause:s}))}surfacePartialDrops(e,r){r.length>0&&this.onError(new Qr({requestId:e,drops:r,retryExhausted:[]}))}async cancelBody(e){try{await e.body?.cancel()}catch{}}};var gr="ai-capture",zi="/i/v0/ai/batch/";var yM=new TextEncoder;function ql(t){return yM.encode(Pt(t)).length}function eS(t,e=8388608,r=5242880){let n=[],s=[],o=[],i=0;for(let a of t){if(a===void 0)continue;let c=ql(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 bM=100,tS=3e4,wM=5e4,TM=50,IM=500,vM="https://us.i.posthog.com",rS=new Set;function Yi(t,e){rS.has(t)||(rS.add(t),console.warn(`[PostHog] ${e}`))}function RM(t){return typeof t=="string"?t.trim():""}function AM(t){return(typeof t=="string"?t.trim():"")||void 0}function OM(t){return(typeof t=="string"?t.trim():"")||vM}function MM(t){return(Array.isArray(t)?t:[t]).filter(r=>typeof r=="string"&&r.trim().length>0)}function PM(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 qi=class extends Gn{get distinctIdHasSentFlagCalls(){return Object.fromEntries(this._distinctIdHasSentFlagCalls)}set distinctIdHasSentFlagCalls(e){this._distinctIdHasSentFlagCalls=new Map(Object.entries(e??{}))}constructor(e,r={}){let n=RM(e),s={...r,maxQueueSize:r.maxQueueSize??1e4,flushInterval:r.flushInterval??5e3,host:OM(r.host),personalApiKey:AM(r.secretKey??r.personalApiKey)};if(super(n,s),this._memoryStorage=new Ki,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=s,this.captureMode=qE(),this.enableFullAiCapture=s.enableFullAiCapture===!0,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof s.featureFlagsPollingInterval=="number"?Math.max(s.featureFlagsPollingInterval,bM):s.featureFlagsPollingInterval===null?null:tS,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 Mi({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 pr(this,s,this._logger),this._distinctIdHasSentFlagCalls=new Map,this.maxCacheSize=s.maxCacheSize||wM}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:Dn([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??IM,s=r>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),s)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??TM;this._waitUntilCycle.timer=fe(()=>{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"&&JE(e)?"ai":gs}persistedQueueKeyForRoute(e){return e===gr?he.AiCaptureQueue:e==="ai"?he.AiQueue:he.Queue}getActiveQueueRoutes(){let e=this.captureMode==="v1"?[gs,"ai"]:[gs];return this._aiCaptureRouteActive&&e.push(gr),e}getBatchEndpointPath(e){return e===gr?zi:super.getBatchEndpointPath(e)}async sendBatch(e,r,n=gs){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}=eS(e);for(let{event:o,bytes:i}of s){let a=`Event ${o} (${i} bytes) exceeds the ${8388608/1048576}MiB limit for ${zi}, 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(!Kr(n))throw n;if(e.length===1){let[o]=e,a=`Event ${typeof o.event=="string"?o.event:"unknown"} (${ql(o)} bytes) was rejected with 413 by ${zi} 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 Gi({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 i_}get metrics(){return this._metrics||(this._metrics=new ts(this,Si(this.options.metrics),this._logger)),this._metrics}initializeSpanContextManager(){return new is}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 os(this,sl(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)??Nt(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):ss(this._spanContextManager,Nt(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=cr(e.uuid,de);return this._sendPreparedAiEvent({...e,uuid:r},!1),r}async captureAiImmediate(e){if(this.disabled)return;let r=cr(e.uuid,de);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=MM(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=tS){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 at||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=yt.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=v.minimalFlagCalledEvents===!0,h=v.requestId,_=v.evaluatedAt;let R=[];v.errorsWhileComputingFlags&&R.push(yt.ERRORS_WHILE_COMPUTING),v.quotaLimited?.includes("feature_flags")&&R.push(yt.QUOTA_LIMITED);let I=v.flags[e];if(I===void 0)R.push(yt.FLAG_MISSING);else{b=I.metadata?.id,w=I.metadata?.version,T=I.reason?.description??I.reason?.code,y=I.metadata?.has_experiment;let P;if(I.metadata?.payload!==void 0)try{P=JSON.parse(I.metadata.payload)}catch{P=I.metadata.payload}g={key:e,enabled:I.enabled,variant:I.variant??void 0,payload:P,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){Yi("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(Yi("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){Yi("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 Dt({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new Dt({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,flags:{}});let{groups:o,disableGeoip:i}=s||{},a=s?.flagKeys??void 0;if(a?.length===0)return new Dt({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 P;if(I.metadata?.payload!==void 0)try{P=JSON.parse(I.metadata.payload)}catch{P=I.metadata.payload}m[R]={key:R,enabled:I.enabled,variant:I.variant,payload:P,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 Dt({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 kt(this._metrics.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._metrics.reset()),this._traces&&(await kt(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=fe(()=>{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(Tm(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(!pr.isPreviouslyCapturedError(e)){let i=new Error("PostHog syntheticException");this.addPendingPromise(pr.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(!pr.isPreviouslyCapturedError(e)){let o=new Error("PostHog syntheticException");return this.addPendingPromise(pr.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 YE()),m||(m=de(),h.$process_person_profile=!1),g&&p?.sessionId&&!h.$session_id&&(h.$session_id=p.sessionId);let _=this._shouldSendMinimalFlagCalledEvent(s,h)?Hn(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){Yi("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 PM(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"&&vm(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 nS=require("node:async_hooks"),Ji=class{constructor(){this.storage=new nS.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 sS=require("node:async_hooks"),Qi=class{active(){return this._storage.getStore()}with(e,r){return this._storage.run(e,r)}constructor(){this._storage=new sS.AsyncLocalStorage}};var oS=require("node:zlib"),iS=require("node:util"),xM=(0,iS.promisify)(oS.gzip);async function aS(t,e=!0){try{let r=await xM(t);return new Uint8Array(r)}catch(r){return e&&console.error("Failed to gzip compress data",r),null}}var Zi=require("node:os");function cS(){let t,e;try{t=(0,Zi.platform)(),e=(0,Zi.release)()}catch{}return zu(t,e)}var uS="posthog-node";function kM(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[Jl.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=ee.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 Jl=class{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(e,r,n,s,o){this.name=uS,this.name=uS,this.setupOnce=function(i,a){let c=a()?.getClient()?.getDsn()?.projectId;i(kM(e,{organization:r,projectId:c,prefix:n,severityAllowList:s,sendExceptionsToPostHog:o??!0}))}}};var ea=class extends qi{getLibraryId(){return"posthog-node"}compressPayload(e){return aS(e,this.isDebug)}initializeContext(){return new Ji}initializeSpanContextManager(){return new Qi}hostResourceAttributes(){return cS()}createErrorPropertiesBuilder(){return new ee.ErrorPropertiesBuilder([new ee.EventCoercer,new ee.ErrorCoercer,new ee.ObjectCoercer,new ee.StringCoercer,new ee.PrimitiveCoercer],ee.createStackParser("node:javascript",ee.nodeStackLineParser),[Em(),e=>t_(e,void 0,this._logger),o_()])}};Ya();ec();Za();rc();var jX=300*1e3,HX=3600*1e3;O();var Zl=null,NM=!1,CM=3e4,ta=null;function dS(){let t=Date.now();if(ta&&t<ta.expiresAt)return ta.value;let e=Ks(process.env,gn());return ta={value:e,expiresAt:t+CM},e}var DM=!1;function FM(){if(!Zl){let t=DM&&kf(process.env)&&dS();Zl=new ea(Vs(),{host:Ys(),flushAt:20,flushInterval:1e4,disableGeoip:!1,enableExceptionAutocapture:t,before_send:KM})}return Zl}var LM=6e4,UM=500,ms=new Map;function $M(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}::${Uf(e)}::${n}`.slice(0,400)}function BM(t,e){try{return WM(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 WM(t,e){let r=ms.get(t);if(!r){if(ms.size>=UM){let n=null,s=1/0;for(let[o,i]of ms){let a=Math.max(i.lastSentTs,i.firstTs);a<s&&(s=a,n=o)}n!==null&&ms.delete(n)}return r={count:1,firstTs:e,lastSentTs:e},ms.set(t,r),{send:!0,count:1}}if(r.count+=1,e-r.lastSentTs>=LM){r.lastSentTs=e;let n=r.count;return r.count=0,{send:!0,count:n}}return{send:!1,count:r.count}}var lS="__cm_rate_limited";function jM(t){try{return typeof t!="string"||t.length===0?"":Ja(qa(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 HM(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=Lf(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=jM(a.filename))}}}function XM(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 KM(t){try{if(!t||typeof t!="object")return t;let e=t;if(e.event!=="$exception")return t;let r=e.properties??{};if(XM(r))return null;if(r[lS]){try{delete r[lS],e.properties=r}catch{}return t}HM(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=$M(n,s,o),a=BM(i,Date.now());if(!a.send)return null;try{r.occurrence_count=a.count,e.properties=r}catch{}return t}catch{return null}}function Ql(t,e,r){try{GM(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 GM(t,e,r){if(NM||!dS())return;let n=zs({...Js(),...e??{}});if(r?.person?n.$set=qs(n):n.$process_person_profile=!1,process.env.MEMINDEX_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:t,properties:n})+`
43
- `);return}FM().capture({distinctId:Gs(),event:t,properties:n})}var zM=["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"],VM=new Set(zM),fS={skill_id:"other",skill_source:"third_party"};function pS(t){let e=YM(t);return e&&VM.has(e)?{skill_id:e,skill_source:"first_party"}:fS}function gS(t,e){if(t==="Skill"&&!(!e||typeof e!="object"))return e.skill}function YM(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}na();var hS=null,JM=new Set(["SetTodoList","TodoList","TaskList","TaskOutput","TaskStop","CronCreate","CronList","CronDelete"]),_S=new Map;function QM(t){let e=_S.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 _S.set(t,r),r}function ZM(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 eP(){if(!hS)throw new Error("ingest helpers used before setIngestContext() \u2014 wiring bug");return hS}async function ES(t,e={}){if(Zr(t.toolName))return{ok:!0,status:"skipped",reason:"memory_retrieval"};let{sessionManager:r,dbManager:n,eventBroadcaster:s,ensureGeneratorRunning:o}=eP(),i=V(t.platformSource),a=typeof t.cwd=="string"?t.cwd:"",c=a.trim()?await Sn(a):null,u=c?.primary||"unknown",l=z.loadFromFile(ge);if(a&&to(a,l.MEMINDEX_EXCLUDED_PROJECTS))return{ok:!0,status:"skipped",reason:"project_excluded"};if(Mt(t.toolName,l.MEMINDEX_SKIP_TOOLS)){if(t.toolName==="Skill"){let{skill_id:y,skill_source:A}=pS(gS(t.toolName,t.toolInput));Ql("skill_invoked",{skill_id:y,skill_source:A,skill_trigger:"tool",ide:i})}return{ok:!0,status:"skipped",reason:"tool_excluded"}}if(i==="kimi"&&JM.has(t.toolName))return{ok:!0,status:"skipped",reason:"tool_excluded"};let d=l.MEMINDEX_SKIP_BASH_PATTERNS.trim(),p=d?ZM(t.toolName,t.toolInput):"";if(p){let y=QM(d);if(y&&y.test(p))return{ok:!0,status:"skipped",reason:"bash_pattern_excluded"}}let g=Fr(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&&hm(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(!Ko.checkUserPromptPrivacy(h,t.contentSessionId,S,"observation",_,{tool_name:t.toolName}).allow)return{ok:!0,status:"skipped",reason:"private"};let w=t.toolInput!==void 0?Te(JSON.stringify(t.toolInput)):"{}",T=t.toolResponse!==void 0?Te(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 ra(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 tP=/agent-transcripts[/\\]([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:[/\\]|$)/i;function rP(t){let e=typeof t.agentId=="string"?t.agentId.trim():"";return e&&e!=="*"?e:t.path.match(tP)?.[1]}var _s=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}},Es=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}},nP=4096,sP=64,sa=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)xn(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:V(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>nP){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"||!xn(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=Dr(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=Dr(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=Dr(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 Sn(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=Pn(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=fm(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-sP))){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 Fo({sessionId:e.sessionId,cwd:n,prompt:r,platform:e.platformSource})}catch(s){throw new _s(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:rP(r)};if(this.observationTransport==="spool"){try{He("observation",o)}catch(a){throw new mr(e.sessionId,a)}return}let i=!1;try{let a=await ES(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 Es(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 im.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{He("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 Mr())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 ue("/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"||Xd(r)||!await Mr())return;let s=e.cwd??r.workspace;if(!s)return;let i=(await Sn(s)).allProjects.join(","),a=`/api/context/inject?projects=${encodeURIComponent(i)}&platformSource=${encodeURIComponent(e.platformSource)}`,c=ae(r.context.path??`${s}/AGENTS.md`),u=hs.default.resolve(c),l=[hs.default.resolve(s),hs.default.resolve(W)];if(!l.some(m=>u.startsWith(m+hs.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 ue(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&&(um(c,g),f.debug("TRANSCRIPT","Updated AGENTS.md context",{agentsPath:c,watch:r.name}))}};var SS=_e(require("node:zlib"),1),en=require("node:fs");O();function yS(){let t=SS.zstdDecompressSync;return typeof t=="function"?t:void 0}function bS(){return yS()!==void 0}var oP=4247762216,iP=64*1024;function oa(t,e,r,n=Number.POSITIVE_INFINITY){let s=(0,en.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,iP),r-l),g=Buffer.alloc(p);if(o=g.subarray(0,(0,en.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)!==oP)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 P=R===1?1:I;if(u+P>r)return{frames:c,tornStart:l};if(u+=P,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,en.closeSync)(s)}}function ed(t,e){try{let r=yS();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 wS(t,e){return ed(t,e).toString("utf8")}var TS=2e3,aP=1e3,cP=256*1024,IS=4*1024*1024,uP=16*1024*1024,lP=100,vS=100;function Ss(){return new Promise(t=>setImmediate(t))}var ia=".jsonl.zstd";async function dP(t,e){try{let r=0;for(;r<e;){let n=oa(t,r,e,uP);if(n.tornStart!==null)return n.tornStart;if(n.frames.length===0)break;r=n.frames[n.frames.length-1].end,await Ss()}return r}catch{return e}}var RS=1024*1024;async function MS(t,e,r){let n;if(e){let{frames:o}=oa(t,0,Math.min(r,RS),1);if(o.length===0)return null;n=wS(await ca(t,0,o[0].end),o[0])}else n=(await ca(t,0,Math.min(r,RS))).toString("utf8");let s=n.indexOf(`
46
- `);return s<0?null:n.slice(0,s)}async function fP(t,e,r){try{let n=await MS(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 aa(t){return`${t.dev}:${t.ino}`}function pP(t){try{return(0,X.statSync)(t),!1}catch(e){let r=e.code;return r==="ENOENT"||r==="ENOTDIR"}}var gP=4096;function rd(t,e,r){let n;try{if(n=(0,X.openSync)(t,"r"),aa((0,X.fstatSync)(n))!==r)return null;let s=Math.max(0,e-gP),o=Buffer.alloc(e-s);return(0,X.readSync)(n,o,0,o.length,s)<o.length?null:(0,AS.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 PS(t,e,r,n,s){return r<n?!1:s===void 0?!0:rd(t,n,e)===s}async function ca(t,e,r){let n=await(0,OS.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 td=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(ia),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 Ss();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=aa(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&&(PS(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:rd(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 ca(this.filePath,r,Math.min(e-r,IS))}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%vS===0&&(this.checkpoint(this.tailState.offset),await Ss())}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=oa(this.filePath,r,e,IS),n.frames.length===0)return;let i=n.frames[n.frames.length-1].end;if(s=await ca(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=ed(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%vS===0&&await Ss()}}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)}},ua=class{constructor(e,r,n="in-process"){this.config=e;this.statePath=r;this.processor=new sa(n),this.state=Jd(r)}config;statePath;processor;tailers=new Map;state;fileContexts=new Map;retirementCandidates=new Set;retirementTimer=null;missingTranscriptGraceMs=aP;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=ae(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 Ss();o.stateChanged&&ln(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,Q.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,Q.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))},lP);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 aa(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)||!pP(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&&ln(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,Q.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(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,X.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,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,Q.join)(e,"**","*.jsonl"))),...this.scanGlob(this.normalizeGlobPattern((0,Q.join)(e,"**",`*${ia}`)))]:[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=ae(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(ia);if(i&&!bS()){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-TS&&await this.startedAfterThisWatcher(e,i,m.size)||(l=i?await dP(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=aa(m),_=this.state.fileIdentities?.[e],S=u!==void 0&&_!==void 0&&!PS(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=rd(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?ln(this.statePath,this.state):o&&(o.stateChanged=!0));let p=l>0&&(!!n.sessionIdPath||!!r.subagentSource||!c.cwd),g=new td(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],ln(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 fP(e,r,n);return s!==null?s>=this.startedAtMs-TS:n<=cP}async primeFromFirstLine(e,r,n,s,o,i){try{let a=await MS(e,e.endsWith(ia),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,Q.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 _s||a instanceof Es||a instanceof mr)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 md(t,e){let r=t.indexOf(e);return r===-1?null:t[r+1]??null}function Ty(t){(0,Iy.existsSync)(ae(t))||(Pa(t),console.log(`Created sample config: ${ae(t)}`))}async function vy(t,e){switch(t){case"init":{let r=md(e,"--config")??Sr;return Pa(r),console.log(`Created sample config: ${ae(r)}`),0}case"watch":{let r=md(e,"--config")??Sr;Ty(r);let n=z.loadFromFile(ge),{config:s,scoped:o,removed:i}=Kd(Ma(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 ${ae(r)}; nothing to watch.`),1;let a=ae(s.stateFile??ks),c=new ua(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=md(e,"--config")??Sr;return Ty(r),Ma(r),console.log(`Config OK: ${ae(r)}`),0}case"import":return I0(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 I0(t){let{defaultTranscriptImportDeps:e,formatTranscriptImportResult:r,isoOf:n,parseTranscriptImportArgs:s,runTranscriptImport:o,TRANSCRIPT_IMPORT_USAGE:i}=await Promise.resolve().then(()=>(wy(),by)),{settleHookSpoolNudges:a}=await Promise.resolve().then(()=>(Cr(),tm)),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 v0=process.argv[2],R0=process.argv.slice(3);vy(v0,R0).then(t=>{process.exit(t)}).catch(t=>{console.error(t),process.exit(1)});
39
+ ${e}`,i=gm(s,o),a=`${t}.tmp`;try{(0,Xe.writeFileSync)(a,i),(0,Xe.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 Mv(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=Mv(e),n=t;for(let s of r){if(n==null)return;n=n[s]}return n}function hm(t){return t==null||t===""}function _m(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 Lr(t,e,r){if(t!==void 0){if(typeof t=="string"){let n=_m(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=Lr(n,e,r);if(!hm(s))return s}if(t.path){let n=_m(t.path,r);if(n!==void 0)return n;let s=xn(e,t.path);if(!hm(s))return s}if(t.value!==void 0)return t.value;if(t.default!==void 0)return t.default}}function Em(t,e,r){let n={};if(!t)return n;for(let[s,o]of Object.entries(t))n[s]=Lr(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}nt();Fr();O();st();Sn();Xo();Pn();qe();N();var or=require("path");N();function xv(t=G.dataDir()){return(0,or.join)(t,"bottles")}function wm(t,e){let r=(0,or.resolve)(xv(e));return(0,or.resolve)(t).startsWith(r+or.sep)}Zt();nt();O();var Ko=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 $r=require("path");function Im(){let t=kv();return async e=>{for(let r of e)r.module=t(r.filename);return e}}function kv(t=process.argv[1]?(0,$r.dirname)(process.argv[1]):process.cwd(),e=$r.sep==="\\"){let r=e?Tm(t):t;return n=>{if(!n)return;let s=e?Tm(n):n,{dir:o,base:i,ext:a}=$r.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 Tm(t){return t.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var Q={};Is(Q,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>ai,DOMExceptionCoercer:()=>Ou,EXCEPTION_STEP_INTERNAL_FIELDS:()=>Wn,ErrorCoercer:()=>Un,ErrorEventCoercer:()=>Mu,ErrorPropertiesBuilder:()=>Ln,EventCoercer:()=>Pu,ExceptionStepsBuffer:()=>Cu,ObjectCoercer:()=>Bn,PrimitiveCoercer:()=>jn,PromiseRejectionEventCoercer:()=>xu,ReduceableCache:()=>ku,StringCoercer:()=>$n,chromeStackLineParser:()=>Iu,createDefaultStackParser:()=>Au,createStackParser:()=>gh,geckoStackLineParser:()=>vu,getInjectedReleaseId:()=>GR,getUtf8ByteLength:()=>hh,nodeStackLineParser:()=>ch,opera10StackLineParser:()=>oh,opera11StackLineParser:()=>ih,resolveExceptionStepsConfig:()=>Nu,reverseAndStripFrames:()=>ph,stripReservedExceptionStepFields:()=>HR,winjsStackLineParser:()=>sh});var he=(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 xt(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 Nv=Array.isArray,Rm=Object.prototype,tL=Rm.hasOwnProperty,Go=Rm.toString,be=Nv||function(t){return Go.call(t)==="[object Array]"};var Nn=t=>t===Object(t)&&!be(t);var _t=t=>t===void 0,ie=t=>Go.call(t)=="[object String]",du=t=>ie(t)&&t.trim().length===0,fu=t=>t===null,Ke=t=>_t(t)||fu(t),Br=t=>Go.call(t)=="[object Number]"&&t===t;var Am=t=>Go.call(t)==="[object Boolean]";function zo(t){return t===null||typeof t!="object"}function ir(t,e){return Object.prototype.toString.call(t)===`[object ${e}]`}function kt(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 Pm(t,Error)}}function Om(t){return ir(t,"ErrorEvent")}function jr(t){return"u">typeof Event&&Pm(t,Event)}function Mm(t){return ir(t,"Object")}function Pm(t,e){try{return t instanceof e}catch{return!1}}var Cv=["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"],Vo=new Map,Dv=256;function Fv(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 xm=function(t,e=[]){if(!t)return!1;let r=Fv(t,e),n=Vo.get(r);if(n!==void 0)return n;let s=t.toLowerCase(),o=Cv.concat(e).some(i=>s.indexOf(i.toLowerCase())!==-1);return Vo.size>=Dv&&Vo.clear(),Vo.set(r,o),o};function Cn(t,e,r,n,s){return e>r&&(n.warn("min cannot be greater than max."),e=r),Br(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 Lv=864e5,Uv=1,$v=10;function km(t={}){return{refillRate:t.exceptionRateLimiterRefillRate??t.__exceptionRateLimiterRefillRate??Uv,bucketSize:t.exceptionRateLimiterBucketSize??t.__exceptionRateLimiterBucketSize??$v}}var Yo=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,Lv,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 qo="0123456789abcdef",Jo=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+=qo.charAt(this.bytes[r]>>>4),e+=qo.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+=qo.charAt(this.bytes[r]>>>4),e+=qo.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}},pu=class{constructor(e){this.timestamp=0,this.counter=0,this.random=e??Bv()}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 Jo.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,Jo.ofInner(e)}},Bv=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),Nm,fe=()=>jv().toString(),jv=()=>(Nm||(Nm=new pu)).generate();var Zo=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 Wv(t=console){return{log:t.log.bind(t),warn:t.warn.bind(t),error:t.error.bind(t),debug:t.debug.bind(t)}}var Cm=(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=>Cm(`${t} ${o}`,e,r)}},Hv=t=>t();function Dm(t,e=Hv){return Cm(t,e,Wv())}var Hr="Mobile",ei="iOS",Wr="Android",Bm="Tablet",hL=Wr+" "+Bm;var Kv="Apple",_L=Kv+" Watch",jm="Safari",ti="BlackBerry",Wm="Samsung",Gv=Wm+"Browser",zv=Wm+" Internet",ri="Chrome",Vv=ri+" OS",Yv=ri+" "+ei,Hm="Internet Explorer",qv=Hm+" "+Hr,hu="Opera",EL=hu+" Mini",Xm="Edge",Jv="Microsoft "+Xm,_u="Firefox",Zv=_u+" "+ei,Eu="Nintendo",Su="PlayStation",Qo="Xbox",Qv=Wr+" "+Hr,eR=Hr+" "+jm,Dn="Windows",tR=Dn+" Phone";var Km="Generic",SL=Km+" "+Hr.toLowerCase(),yL=Km+" "+Bm.toLowerCase(),rR="Konqueror",nR="Oculus Browser",Fm="Vivaldi",sR="Yandex",Lm="Whale",oR="DuckDuckGo",iR="Pale Moon",Um="Waterfox",$m="Brave",Gm="Claude",zm="Codex",Vm="ChatGPT",aR="Google Search App",B="(\\d+(\\.\\d+)?)",gu=new RegExp("Version/"+B),mu=new RegExp("("+Gm+"|"+zm+"|"+Vm+")\\/"+B);var bL=new RegExp(Qo,"i"),wL=new RegExp(Su+" \\w+","i"),TL=new RegExp(Eu+" \\w+","i"),cR=new RegExp(ti+"|PlayBook|BB10","i"),uR={"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 IL={[qv]:[new RegExp("rv:"+B)],[Jv]:[new RegExp(Xm+"?\\/"+B)],[ri]:[new RegExp("("+ri+"|CrMo)\\/"+B)],[Yv]:[new RegExp("CriOS\\/"+B)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+B)],[jm]:[gu],[eR]:[gu],[hu]:[new RegExp("("+hu+"|OPR)\\/"+B)],[_u]:[new RegExp(_u+"\\/"+B)],[Zv]:[new RegExp("FxiOS\\/"+B)],[rR]:[new RegExp("Konqueror[:/]?"+B,"i")],[ti]:[new RegExp(ti+" "+B),gu],[Qv]:[new RegExp("android\\s"+B,"i")],[zv]:[new RegExp(Gv+"\\/"+B)],[nR]:[new RegExp("OculusBrowser\\/"+B)],[Fm]:[new RegExp(Fm+"\\/"+B)],[sR]:[new RegExp("YaBrowser\\/"+B)],[Lm]:[new RegExp(Lm+"\\/"+B)],[$m]:[new RegExp($m+"\\/"+B)],[Gm]:[mu],[zm]:[mu],[Vm]:[mu],[oR]:[new RegExp("(DuckDuckGo|Ddg)\\/"+B)],[iR]:[new RegExp("PaleMoon\\/"+B)],[Um]:[new RegExp(Um+"\\/"+B)],[aR]:[new RegExp("GSA\\/"+B)],[Hm]:[new RegExp("(rv:|MSIE )"+B)],Mozilla:[new RegExp("rv:"+B)]};var vL=[[new RegExp(Qo+"; "+Qo+" (.*?)[);]","i"),t=>[Qo,t&&t[1]||""]],[new RegExp(Eu,"i"),[Eu,""]],[new RegExp(Su,"i"),[Su,""]],[cR,[ti,""]],[new RegExp(Dn,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[tR,""];if(new RegExp(Hr).test(e)&&!/IEMobile\b/.test(e))return[Dn+" "+Hr,""];let r=/Windows NT ([0-9.]+)/i.exec(e);if(r&&r[1]){let n=r[1],s=uR[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[ei,e.join(".")]}return[ei,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{let e="";return t&&t.length>=3&&(e=_t(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Wr+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Wr+")","i"),t=>{if(t&&t[2]){let e=[t[2],t[3],t[4]||"0"];return[Wr,e.join(".")]}return[Wr,""]}],[/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/,[Vv,""]],[/Linux|debian/i,["Linux",""]]];var ni="[Circular]",si="[Truncated]",ve="[Unserializable]",Ym="[Function]",OL=Date.prototype.getTime,ML=Date.prototype.toISOString;function ot(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 Et(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 yu(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 ar=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 qm="utf8",lR=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function dR(t){return typeof t=="string"&&lR.test(t)}function cr(t,e){return dR(t)?t:e()}function Xr(t,e){let r=new Error(e);try{Object.defineProperty(r,"name",{value:t,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function Jm(t){return t?.replace(/\/+$/,"")}async function Zm(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 bu(){return new Date().toISOString()}function pe(t,e){let r=setTimeout(t,e);return r?.unref&&r?.unref(),r}async function Nt(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 Qm=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 wu,eh,th,Kr;function nh(t){let e=globalThis._posthogChunkIds,r=globalThis._debugIds;if(!e&&!r)return;let n=e?Object.keys(e):[],s=r?Object.keys(r):[];if(Kr&&rh(e,n,eh)&&rh(r,s,th))return Kr;eh=e?{...e}:void 0,th=r?{...r}:void 0,Kr={},wu??={};let o=(i,a)=>{for(let c of i){let u=a[c];if(!u)continue;let l=wu?.[c];if(l){Kr[l]=u;continue}let d=t(c);for(let p=d.length-1;p>=0;p--){let g=d[p]?.filename;if(g){Kr[g]=u,wu[c]=g;break}}}};return r&&o(s,r),e&&o(n,e),Kr}function rh(t,e,r){return!t||!r?t===r:e.length===Object.keys(r).length&&e.every(n=>t[n]===r[n])}var Tu=50,fR=1e3,pR=100,gR=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&&be(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:nh(this.stackParser),skipFirstLines:e.skipFirstLines??1}}getAggregateErrors(e){try{if(kt(e)){let r=Object.getPrototypeOf(e);for(let n=0;r&&n<pR;n++){let s=Object.getOwnPropertyDescriptor(r,"constructor")?.value;if(typeof s=="function"&&s.name==="AggregateError"){let o=e.errors;return be(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=I=>{c.push(g);try{return S(I)}finally{c.pop()}},h>gR||h>0&&c.indexOf(g)!==-1)return this.coerceFallback(_);let b=typeof g=="object"&&g!==null||typeof g=="function";if(h===0&&s>=Tu||b&&a.has(g))return;b&&a.add(g),h===0&&s++;let w=this.getAggregateErrors(g);i||=!!w;let R;try{if(R=this.applyCoercers(g,_),!R)throw u}catch(I){if(I===u){h===0&&s--;return}if(!i)throw I;R=this.coerceFallback(_)}if(!w||s>=Tu)return R;let v;try{v=w.length}catch{return R}if(!Number.isInteger(v)||v<0||v>4294967295)return R;let y=[];for(let I=0;s<Tu&&o<fR&&I<v;I++){o++;let A;try{A=_.next(w[I])}catch{s++,A=this.coerceFallback(d(m+1))}A&&y.push(A)}return{...R,errors:y}},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 te="?",mR="<anonymous>",hR=/^([a-z][a-z0-9.+-]+):/i,_R=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function ER(t){if(!t||t===mR)return!1;let e=hR.exec(t);return!e||_R.includes(e[1].toLowerCase())}function it(t,e,r,n,s){let o={platform:t,filename:e,function:r==="<anonymous>"?te:r,in_app:ER(e)};return _t(n)||(o.lineno=n),_t(s)||(o.colno=s),o}var oi=(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]:te,r?`safari-extension:${e}`:`safari-web-extension:${e}`]:[t,e]};var SR=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,yR=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,bR=/\((\S*)(?::(\d+))(?::(\d+))\)/,Iu=(t,e)=>{let r=SR.exec(t);if(r){let[,s,o,i]=r;return it(e,s,te,+o,+i)}let n=yR.exec(t);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=bR.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}let[o,i]=oi(n[1]||te,n[2]);return it(e,i,o,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var wR=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,TR=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,vu=(t,e)=>{let r=wR.exec(t);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let i=TR.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]||te;return[o,s]=oi(o,s),it(e,s,o,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var IR=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,sh=(t,e)=>{let r=IR.exec(t);return r?it(e,r[2],r[1]||te,+r[3],r[4]?+r[4]:void 0):void 0};var vR=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,oh=(t,e)=>{let r=vR.exec(t);return r?it(e,r[2],r[3]||te,+r[1]):void 0},RR=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,ih=(t,e)=>{let r=RR.exec(t);return r?it(e,r[5],r[3]||r[4]||te,+r[1],+r[2]):void 0};var AR=/^\s*[-]{4,}$/,OR=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,MR=/^Promise\.(?:all|any)$/,PR=/^index \d+$/,xR="node:internal/promise",ch=(t,e)=>{let r=t.match(OR);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||te,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]),MR.test(o)&&PR.test(c||"")&&(c=xR),{filename:c?decodeURI(c):void 0,module:void 0,function:o,lineno:ah(r[3]),colno:ah(r[4]),in_app:kR(c||"",u),platform:e}}if(t.match(AR))return{filename:t,platform:e}};function kR(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 ah(t){return parseInt(t||"",10)||void 0}var uh=/\(error: (.*)\)/,lh=50,NR=10,CR=1e3;function Ru(t,e){return t.filename===e.filename&&t.function===e.function&&t.module===e.module&&t.lineno===e.lineno&&t.colno===e.colno}function DR(t){for(let e=1;e<=NR;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(!Ru(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 FR(t,e){let r=e.start+e.length,n=fh(t,e);n&&t.splice(r+n===t.length?r:e.start,n)}function dh(t,e){let r=e.start;for(;r>0&&Ru(t[r-1],t[r-1+e.length]);)r--;return e.start-r}function fh(t,e){let r=e.start+e.length,n=r;for(;n<t.length&&Ru(t[n],t[n-e.length]);)n++;return n-r}function LR(t,e){let r=e[0],n=t.length-(r?dh(t,r):0);for(let s of e)n-=fh(t,s);return n}function UR(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++)$R(e,n,r)&&(r=n);t.push(...t.splice(0,r))}function $R(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 ph(t){if(!t.length)return[];let e=Array.from(t);return e.reverse(),e.slice(0,lh).map(r=>({...r,filename:r.filename||BR(e).filename,function:r.function||te}))}function BR(t){return t[t.length-1]||{}}function Au(){return gh("web:javascript",Iu,vu)}function gh(t,...e){return(r,n=0)=>{let s=[],o=r.split(`
40
+ `),i=Math.min(o.length,n+CR),a=[];for(let l=n;l<i;l++){let d=o[l];if(d.length>1024)continue;let p=uh.test(d)?d.replace(uh,"$1"):d;if(!p.match(/\S*Error: /)){for(let g of e){let m=g(p,t);if(m){s.push(m);let h=DR(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(LR(s,a)>=lh)break}}let c=[...a].sort((l,d)=>d.start-l.start),u=c[c.length-1];if(u){let l=dh(s,u);s.splice(u.start-l,l);for(let d of c)d.start-=l}for(let l of c)FR(s,l);return a.some(l=>l.start===0&&s.length===l.length)&&UR(s),ph(s)}}var Ou=class{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,r){let n=ie(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 ir(e,"DOMException")}isDOMError(e){return ir(e,"DOMError")}};var Un=class{match(e){return kt(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 Mu=class{match(e){if(!Om(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 ie(e.message)&&e.message.length>0}_buildLocationStack(e){let r=e,n=r.lineno??0,s=r.colno??0;if(!(!ie(r.filename)||r.filename.length===0)&&n!==0)return`Error
41
+ at ${r.filename}:${n}:${s}`}};var jR=/^(?:[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(jR);return s&&(r=s[1],n=s[2]),[r,n]}};var mh=["fatal","error","warning","log","info","debug"];function ii(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(jr(e))return e.constructor.name;let r="name"in e?e.name:void 0;return ie(r)&&!du(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=ii(e);return`${r&&r!=="Object"?`'${r}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(e){return ie(e)&&!du(e)&&mh.indexOf(e)>=0}getStack(e){try{return ie(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:ie(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(kt(n))return n}}getObjectClassName(e){try{let r=Object.getPrototypeOf(e);return r?r.constructor.name:void 0}catch{return}}};var Pu=class{match(e){return jr(e)}coerce(e,r){let n=e.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${ii(e)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var jn=class{match(e){return zo(e)}coerce(e,r){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:r.syntheticException?.stack,synthetic:!0}}};var xu=class{match(e){return ir(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!jr(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 zo(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 ku=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 Wn={MESSAGE:"$message",TIMESTAMP:"$timestamp"},WR=new Set([Wn.MESSAGE,Wn.TIMESTAMP]),ai={enabled:!0,max_bytes:32768};function Nu(t){return t?{enabled:t.enabled??ai.enabled,max_bytes:XR(t.max_bytes,ai.max_bytes)}:{...ai}}function HR(t){if(!t)return{sanitizedProperties:{},droppedKeys:[]};let e=[];return{sanitizedProperties:Object.keys(t).reduce((n,s)=>WR.has(s)?(e.push(s),n):(n[s]=t[s],n),{}),droppedKeys:e}}var Cu=class{constructor(e){this._entries=[],this._totalBytes=0,this._config=Nu(e)}setConfig(e){this._config=Nu(e),this._trimToMaxBytes()}add(e){let r=KR(e);if(!r)return;let n=hh(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 XR(t,e){if(!Br(t)||t===1/0||t===-1/0)return e;let r=Math.floor(t);return r<0?e:r}function KR(t){let e;try{e=xt(t)}catch{return}try{let r=JSON.parse(e);if(!Nn(r))return;let n=r,s=n[Wn.MESSAGE],o=n[Wn.TIMESTAMP];return!ie(s)||s.trim().length===0||!ie(o)&&!Br(o)?void 0:{step:n,json:e}}catch{return}}function hh(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 GR(){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 Du=t=>{if("flags"in t){let e=_h(t.flags),r=Eh(t.flags);return{...t,featureFlags:e,featureFlagPayloads:r}}{let e=t.featureFlags??{},r=Object.fromEntries(Object.entries(t.featureFlagPayloads||{}).map(([s,o])=>[s,Gr(o)])),n=Object.fromEntries(Object.entries(e).map(([s,o])=>[s,zR(s,o,r[s])]));return{...t,featureFlags:e,featureFlagPayloads:r,flags:n}}};function zR(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 _h=t=>Object.fromEntries(Object.entries(t??{}).map(([e,r])=>[e,Hn(r)]).filter(([,e])=>e!==void 0)),Eh=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?Gr(n):void 0]}))},Hn=t=>t===void 0?void 0:t.variant??t.enabled,Gr=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};var Sh=["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"],VR=["$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",...Sh,"$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 VR.forEach(n),e.forEach(n),r};var ci=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 Fu(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var qR="NativeGzipValidationError",JR=31,ZR=139,QR=8,eA=t=>t.length>=2&&t[0]===JR&&t[1]===ZR;var Kn,tA=()=>{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},rA=t=>{let e=tA(),r=4294967295;for(let n=0;n<t.length;n++)r=e[(r^t[n])&255]^r>>>8;return(4294967295^r)>>>0},ui=t=>{throw Xr(qR,`Native gzip produced invalid output: ${t}`)},nA=async(t,e)=>{t.size<18&&ui("too-short");let r=new Uint8Array(await t.slice(0,10).arrayBuffer());(!eA(r)||r[2]!==QR)&&ui("invalid-header");let n=new DataView(await t.slice(t.size-8).arrayBuffer());n.getUint32(0,!0)!==rA(e)&&ui("invalid-crc");let s=e.length>>>0;n.getUint32(4,!0)!==s&&ui("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 nA(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 yu(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=Xr("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=Xr("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{}})()}},St=class extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}};var sA=(t,e)=>{for(let r of Object.keys(e))(r.startsWith("$feature/")||r==="$active_feature_flags")&&(t[r]=e[r])};async function yh(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 oA(t){return typeof t=="object"&&(t instanceof Re||Ih(t))}function Ih(t){return t instanceof St}function iA(t){if(t instanceof Re)return t.status===502||t.status===504;if(!(t instanceof St))return!1;let e=t.error;return(e?.code??e?.cause?.code)!=="ECONNREFUSED"}var bh=10485760;function wh(t){try{return typeof t!="string"?t instanceof Uint8Array?t.byteLength:t.size:"u">typeof Buffer?Buffer.byteLength(t,qm):new TextEncoder().encode(t).length}catch{return 0}}function zr(t){return typeof t=="object"&&t instanceof Re&&t.status===413}function li(t){return t instanceof Re?t.status===408||t.status===429||t.status>=500:Ih(t)}function Th(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Lu="default",zn=class{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new Ln([new Un,new Bn,new $n,new jn],Au())}getEvaluationRuntime(){}constructor(e,r={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new Zo,this._events=new ci,this._isInitialized=!1;let n=typeof e=="string"?e.trim():"",s=typeof r.host=="string"?r.host.trim():"",o=!n;this._logger=Dm("[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=Jm(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:li},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=!Fu()||(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(he.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(he.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(he.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 sA(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:iA},this.featureFlagsRequestTimeoutMs).then(p=>({success:!0,response:Du(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 St){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(he.Props)),this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(he.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(he.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return Lu}persistedQueueKeyForRoute(e){return he.Queue}getActiveQueueRoutes(){return[Lu]}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=Th(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=cr(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:bu(),uuid:cr(r?.uuid,fe)};return(r?.disableGeoip??this.disableGeoip)&&(Th(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 yh(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=Lu){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:bu()};this.historicalMigration&&(s.historical_migration=!0);let o=xt(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=>zr(d)?!1:li(d)};try{await this.sendBatch(c,l,e)}catch(d){if(zr(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 St||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=wh(s);if(o>bh)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${e} batch of ${o} bytes: the endpoint accepts at most ${bh}`)),{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=>zr(l)||l instanceof Re&&l.retryAfterMs!==void 0?!1:li(l)}),{kind:"ok"}}catch(l){if(zr(l))return{kind:"too-large"};if(li(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=wh(i),c={...this._retryOptions,...s},u=0;return await Zm(async()=>{u++;let l=new AbortController,d=o??this.requestTimeout,p=Date.now()+d,g,m=new Promise((w,R)=>{g=pe(()=>{let v=Xr("AbortError",`Request timed out after ${d}ms`);R(v),l.abort(v)},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(y){throw new St(y)}w.then(y=>{l.signal.aborted&&!_&&Promise.resolve(y.body?.cancel()).catch(()=>{})}).catch(()=>{});try{h=await Promise.race([w,m]),_=!0}catch(y){throw new St(y)}let R=r.mode==="no-cors",v=n.type==="successful-write"?300:400;if(!R&&(h.status<200||h.status>=v))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(y){throw l.signal.aborted?new St(y):y}}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:Nt((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(!oA(s))throw s;await yh(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 dA=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi;var D$=new RegExp(dA.source,"i"),vh=/[a-z][a-z0-9+.-]{0,63}:\/\//i,F$=new RegExp(`^${vh.source}`,"i"),L$=new RegExp(vh.source,"gi");var fA=["is_not","is_set"],pA=1152921504606847e3,M=class t extends Error{constructor(e){super(e),this.name=this.constructor.name,Object.setPrototypeOf(this,t.prototype)}};function Uu(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(!Uu(e in t?t[e]:null))return!1;return!0}function $u(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(!$u(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 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 fi(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 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&&fi(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))Vn(n),fi(t[n],e)}finally{e.delete(t)}return}throw new M(`Cannot represent ${typeof t} like the flags service`)}}function gA(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 Bu(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 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?Bu(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(Vn),`{${n.sort(gA).map(s=>`${JSON.stringify(s)}:${Bu(t[s],e)}`).join(",")}}`}finally{e.delete(t)}}throw new M(`Cannot stringify ${typeof t} like the flags service`)}function di(t){return typeof t=="string"?(Vn(t),t):Bu(t)}function Rh(t){try{return new RegExp(t),!0}catch{return!1}}function Ae(t){return String(t).replace(/[A-Z]/g,e=>e.toLowerCase())}function Oh(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 J(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("."),o=i=>i===void 0||i===""?0:Oh(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 mA(t,e){let r=J(t,e);return{lower:[r[0],r[1],r[2]],upper:[r[0],r[1]+1,0]}}function hA(t,e){let[r,n,s]=J(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 _A(t,e){let n=String(t).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!n)throw new M(`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 Oh(c,t,e)}catch{}throw new M(`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 Ah(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 ju(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 Wu(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 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 ${o} operator`),o==="is_not";if(c===null&&!fA.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&&Uu(d)||Array.isArray(d)&&d.length===0)return fi(p),$u(d)===$u(p);if(r.propertyMatchingVersion===2&&typeof p=="number"&&Uu(d))return fi(p),!1;if(Array.isArray(d)){let g=di(p).toLowerCase();return d.some(m=>di(m).toLowerCase()===g)}return di(d).toLowerCase()===di(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 Rh(String(s))&&String(c).match(String(s))!==null;case"not_regex":return Rh(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 M("Date operations cannot be performed on boolean values");let d=ju(String(s));d==null&&(d=Ah(s));let p=Ah(c);return o==="is_date_before"?p<d:p>d}case"semver_eq":return Oe(J(String(c),i),J(String(s),i))===0;case"semver_neq":return Oe(J(String(c),i),J(String(s),i))!==0;case"semver_gt":return Oe(J(String(c),i),J(String(s),i))>0;case"semver_gte":return Oe(J(String(c),i),J(String(s),i))>=0;case"semver_lt":return Oe(J(String(c),i),J(String(s),i))<0;case"semver_lte":return Oe(J(String(c),i),J(String(s),i))<=0;case"semver_tilde":{let d=J(String(c),i),{lower:p,upper:g}=mA(String(s),i);return Oe(d,p)>=0&&Oe(d,g)<0}case"semver_caret":{let d=J(String(c),i),{lower:p,upper:g}=hA(String(s),i);return Oe(d,p)>=0&&Oe(d,g)<0}case"semver_wildcard":{let d=J(String(c),i),{lower:p,upper:g}=_A(String(s),i);return Oe(d,p)>=0&&Oe(d,g)<0}default:throw new M(`Unknown operator: ${o}`)}}async function Mh(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 Mh(`${t}${n}${e}${r}`);return parseInt(s.slice(0,15),16)/pA}async function Hu(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 pi(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 Yn(t,e,"variant");return pi(r).find(s=>n>=s.valueMin&&n<s.valueMax)?.key}function Ku(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:Gr(n)}var Ph=9223372036854776e3,EA="9223372036854775808",SA=Object.prototype.propertyIsEnumerable;function yA(){return{ancestors:new WeakSet,remainingNodes:1e4}}function at(t,e){try{return xh(t,e,yA(),0)}catch{return[]}}function bA(t,e){let r=t.toString(),n=BigInt(EA);return t>=n||t<-n?(e?.debug(`Attribute ${r} is outside the int64 range; encoding it as a string`),{stringValue:r}):{intValue:r}}function Vu(t,e,r,n){if(r.remainingNodes<=0)return{stringValue:si};if(r.remainingNodes--,Am(t))return{boolValue:t};if(typeof t=="bigint")return bA(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>=Ph||t<-Ph?(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:ot(t)};if(typeof t=="function")return{stringValue:Ym};if(typeof t=="symbol")return{stringValue:String(t)};if(typeof t=="object"&&t!==null){if(r.ancestors.has(t))return{stringValue:ni};if(n>=20)return{stringValue:si};if(t instanceof Date){let s=t.getTime(),o=Number.isFinite(s)?t.toISOString():String(t);return{stringValue:typeof o=="string"?ot(o):String(o)}}r.ancestors.add(t);try{try{let s=t.toJSON;if(typeof s=="function")return Vu(s.call(t),e,r,n+1)}catch{}return be(t)?{arrayValue:{values:wA(t,e,r,n+1)}}:{kvlistValue:{values:xh(t,e,r,n+1)}}}finally{r.ancestors.delete(t)}}return{stringValue:ot(String(t))}}function wA(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(Ke(a))continue;s.push(Vu(a,e,r,n))}catch{s.push({stringValue:ve})}return t.length>i&&s.push({stringValue:si}),s}function xh(t,e,r,n){let s=[];for(let o in t)if(SA.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(fu(i)||_t(i))continue;s.push({key:ot(o),value:Vu(i,e,r,n)})}catch{s.push({key:ot(o),value:{stringValue:ve}})}}return s}function Jn(t,e,r){return{...Et({},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 TA=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function Zn(t,e){let r=Et({},t),n={};for(let s of TA)Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s],delete r[s]);return[...at(r,e),...at(n,e)]}var kh={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 IA(t){if(t)return Object.prototype.hasOwnProperty.call(kh,t)?kh[t]:t}function Yu(t,e){let r=IA(t);return{...r?{"os.name":r}:{},...e?{"os.version":e}:{}}}var vA={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}},Q$=vA.info;var ur=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 Qn(){return 1-.25+Math.random()*.25*2}var Me=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 qu="0000000000000000",MA=qu+qu,PA=/^[0-9a-f]+$/;function xA(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 kA(t){let e="";for(let r=0;r<t.length;r++)e+=t[r].toString(16).padStart(2,"0");return e}function Nh(t){let e=kA(xA(t));return/[^0]/.test(e)?e:e.slice(0,-1)+"1"}function Ch(){return Nh(16)}function Dh(){return Nh(8)}function Fh(t,e,r){return typeof t=="string"&&t.length===e&&t!==r&&PA.test(t)}function Lh(t){return Fh(t,32,MA)}function Uh(t){return Fh(t,16,qu)}var NA=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function mi(t){let e=$h(t);return e&&{traceId:e.traceId,spanId:e.spanId,flags:CA(e.flags)}}function CA(t){return 1&parseInt(t,16)?Vr:DA}function $h(t){if(typeof t!="string")return;let e=NA.exec(t.trim());if(!e)return;let[,r,n,s,o,i]=e;if(r!=="ff"&&!(r==="00"&&i)&&!(!Lh(n)||!Uh(s)))return{version:r,traceId:n,spanId:s,flags:o}}function Bh(t){return $h(t)&&t.trim()}function hi(t){return Array.isArray(t)&&t.length===1?t[0]:t}var Vr="01",DA="00";function jh(t,e,r=Vr){return`00-${t}-${e}-${r}`}var FA=32,Ju=512;function _i(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>FA)){for(let n of r)if(n.trim()&&!n.includes("="))return;return e.length<=Ju?e:UA(r)}}var LA=128;function UA(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()>Ju;n--)e[n].length>LA&&e.splice(n,1);for(;e.length&&r()>Ju;)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 Ei(t){return String(t)+"000000"}function Zu(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 Wh(t,e){for(let r=0;r<e.length;r++)if(t<=e[r])return r;return e.length}function Qu(t,e,r){return Jn(t,e,r)}function el(t,e,r,n){return{resourceMetrics:[{resource:{attributes:Zn(e)},scopeMetrics:[{scope:{name:r,version:n},metrics:t}]}]}}function Si(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 Hh=1,rs=class{constructor(e,r,n){this._instance=e,this._config=r,this._logger=n,this._series=new Map,this._flushTimer=new ur(()=>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 ar,this._consecutiveFlushFailures=0,this._flushJitter=Me,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=Me,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=Zu(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=mi(this._instance.getActiveSpan?.()?.traceparent());if(e&&e.flags===Vr)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[Wh(r,ts)]+=1;break}}}_runBeforeSend(e){let r=this._config.beforeSend;if(!r)return e;let n=be(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=Qn()):(this._consecutiveFlushFailures=0,this._flushJitter=Me),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 el(this._buildMetrics(e),Qu(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(e){let r=Ei(Date.now()),n=new Map;for(let s of e.values()){let o=Zu(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:Hh,isMonotonic:!0,dataPoints:[]}:s.type==="gauge"?i.gauge={dataPoints:[]}:i.histogram={aggregationTemporality:Hh,dataPoints:[]},n.set(o,i));let a=at(s.attributes??{},this._logger),c=Ei(s.windowStartMs),u=$A(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 $A(t){return t?{exemplars:[{filteredAttributes:[],timeUnixNano:Ei(t.timeMs),asDouble:t.value,traceId:t.traceId,spanId:t.spanId}]}:{}}var Xh="unknown";function lr(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 "${Xh}"`),Xh)}function Yr(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 Kh(t,e,r){let n=Yr(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 yi(t,e){return t<e?e:t}function ns(t,e,r,n){let s=Yr(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 wi(){let t=globalThis.performance;return typeof t?.now=="function"?t.now():void 0}var qr=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??Vr,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:wi(),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=wi();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(Ke(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]=Ii(r,this._maxAttributeValueLength)}setAttribute(e,r){return this._mutable("setAttribute")&&this._writeAttribute(e,r),this}setAttributes(e){if(this._mutable("setAttributes")){let r=Et({},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&&Yh(r,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:lr(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:tl(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}=rl(e);return this.addEvent(BA,{"exception.type":r,"exception.message":n,...s&&{"exception.stacktrace":s}}),this.setStatus("error",n)}updateName(e){return this._mutable("updateName")&&(this._name=lr(e,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return jh(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:yi(n,this._startTime),...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}},BA="exception",jA=4294967295;function WA(t){try{return typeof t=="string"?t:String(t)}catch{return ve}}function dr(t){return typeof t!="number"||!Number.isFinite(t)||t<=0?0:Math.min(Math.floor(t),jA)}function HA(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 zh(t,e,r,n,s,o,i=[]){let a=0,c=0,u={};for(let g of HA(t.attributes,i)){let m=t.attributes[g];if(!Ke(m)){if(!e.has(g)){if(a>=r){c++;continue}a++}Object.defineProperty(u,g,{value:Ii(m,o),enumerable:!0,writable:!0,configurable:!0})}}t.attributes=u,c&&(t.droppedAttributesCount=dr(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=Yh(g.attributes,s,o);g.attributes=m.attributes,m.dropped&&(g.droppedAttributesCount=dr(g.droppedAttributesCount)+m.dropped)}p.push(g)}t.events=p,d&&(t.droppedEventsCount=dr(t.droppedEventsCount)+d),t.status?.message&&(t.status={...t.status,message:tl(WA(t.status.message),o)})}var Ti=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(){}},Vh=new Ti,ss=class extends Ti{constructor(e,r){super(),this._traceparent=e,this._tracestate=r}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}};function XA(t){try{let e=t.stack;return typeof e=="string"&&e?{stack:e}:{}}catch{return{}}}function Ct(t,e){let r=hi(t?.parent)??e,n=typeof r=="string"||r==null?r:Gh(r,"traceparent"),s=Bh(n);if(!s)return Vh;let o=typeof r=="string"||r==null?t?.tracestate:Gh(r,"tracestate");return new ss(s,_i(o))}function Gh(t,e){try{let r=t[e];return typeof r=="function"?r.call(t):void 0}catch{return}}function tl(t,e){return t.length>e?t.slice(0,e):t}function Ii(t,e){return bi(t,e,{ancestors:new WeakSet,remainingNodes:1e4},0)}function bi(t,e,r,n){if(t===null||typeof t!="object")return Ke(t)||r.remainingNodes<=0?t:(r.remainingNodes--,typeof t=="string"?tl(t,e):t);if(r.ancestors.has(t))return ni;if(r.remainingNodes<=0||n>=20)return t;r.remainingNodes--,r.ancestors.add(t);try{if(t instanceof Date)return t;let s=KA(t);if(s.selfDescribed)return Ke(s.value)?String(s.value):bi(s.value,e,r,n+1);if(be(t)){let a=Math.min(t.length,1e3),c=[];for(let u=0;u<a;u++)try{c.push(bi(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=bi(t[a],e,r,n+1)}catch{c=ve}a&&!Ke(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 KA(t){try{let e=t.toJSON;if(typeof e=="function")return{selfDescribed:!0,value:e.call(t)}}catch{}return{selfDescribed:!1}}function Yh(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=Ii(t[a],r)}catch{c=ve}Ke(c)||(o++,Object.defineProperty(s,a,{value:c,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:s,dropped:i}}function qh(t,e){for(let r of Object.keys(t))t[r]=Ii(t[r],e);return t}function os(t,e,r){return e===Vh?r(e):t.with(e,()=>r(e))}function rl(t){try{let e=XA(t);if(kt(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 nl={internal:1,server:2,client:3,producer:4,consumer:5},GA={ok:1,error:2},zA=1,VA=256,YA=512;function qA(t){let e=parseInt(t.traceFlags,16);return(Number.isFinite(e)?255&e:zA)|VA|(t.parentIsRemote?YA:0)}function vi(t){if(typeof t=="string")return ot(t);try{return ot(String(t))}catch{return ve}}function JA(t){return t&&Object.prototype.hasOwnProperty.call(nl,t)?nl[t]:nl.internal}function sl(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 ZA(t,e){let r={name:vi(t.name),timeUnixNano:sl(t.timestamp)};if(t.attributes){let s=at(t.attributes,e);s.length&&(r.attributes=s)}let n=dr(t.droppedAttributesCount);return n&&(r.droppedAttributesCount=n),r}function Jh(t,e){let r={traceId:t.traceId,spanId:t.spanId,name:vi(t.name),kind:JA(t.kind),startTimeUnixNano:sl(t.startTime),endTimeUnixNano:sl(t.endTime),flags:qA(t)};t.parentSpanId&&(r.parentSpanId=t.parentSpanId),t.traceState&&(r.traceState=vi(t.traceState));let n=at(t.attributes,e);n.length&&(r.attributes=n),t.events.length&&(r.events=t.events.map(i=>ZA(i,e)));let s=dr(t.droppedAttributesCount);s&&(r.droppedAttributesCount=s);let o=dr(t.droppedEventsCount);return o&&(r.droppedEventsCount=o),t.status&&(r.status={code:GA[t.status.code],...t.status.message&&{message:vi(t.status.message)}}),r}function Zh(t,e,r){return Jn(t,e,r)}function Qh(t,e,r,n,s){return{resourceSpans:[{resource:{attributes:Zn(e,s)},scopeSpans:[{scope:{name:r,version:n},spans:t}]}]}}var e_=8;function Ri(){return wi()??Date.now()}function ol(t){try{return t instanceof qr}catch{return!1}}function t_(t,e){let r=mi(t);if(r)return{traceId:r.traceId,parentSpanId:r.spanId,traceState:_i(e),traceFlags:r.flags,isRemote:!0}}function QA(t){try{return typeof t.traceparent=="function"}catch{return!1}}function eO(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 Ai(t,e,r){t[e]!==r&&(t[e]=r)}function tO(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 ur(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=Me,this._retryAfter=new ar,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 Ct(r,this._contextManager.active());let n=hi(r?.parent);if(n&&typeof n!="string"&&!ol(n)){if(QA(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),Ct(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`),Ct(r,this._contextManager.active());let o=Date.now(),i=Kh(r?.startTime,o,this._logger),a=Dh();this._liveSpans.set(a,Ri());let c=this._autoContextAttributes();return new qr({traceId:s?.traceId??Ch(),spanId:a,parentSpanId:s?.parentSpanId,traceState:s?.traceState,traceFlags:s?.traceFlags,parentIsRemote:s?.isRemote,name:lr(e,"Span name",this._config.maxAttributeValueLength,this._logger),kind:r?.kind??"internal",attributes:Et({...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:Yr(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 Qm(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=Me,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(e,r){if(typeof e=="string"){let s=t_(e,r?.tracestate);return s||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),s}if(ol(e))return e.childContext();let n=this._contextManager.active();if(ol(n))return n.childContext();if(n instanceof ss)return t_(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 qr))return;let{type:n,message:s,stack:o}=rl(r);e.addEvent("exception",{"exception.type":n,"exception.message":s,...o&&{"exception.stacktrace":o}}),e.statusIsExplicitlyOk||e.setStatus("error",s)}_evictAgedSpans(){let e=Ri()-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},!eO(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=lr(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=Yr(l.startTime)??s.startTime,l.endTime=yi(Yr(l.endTime)??s.endTime,l.startTime);let p=[];for(let g of l.events)try{p.push({...g,name:lr(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,zh(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{Ai(e,"traceId",r.traceId),Ai(e,"spanId",r.spanId),Ai(e,"parentSpanId",r.parentSpanId),Ai(e,"traceState",r.traceState)}catch{return tO(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(Jh(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=qh(Zh(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=Ri()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),h=await this._instance._sendTracesBatch(Qh(g,r,n,s,this._logger));if(c!==this._generation)break;if(this._retryAfter.record(h),h.kind==="ok"){this._consecutiveFlushFailures=0,this._flushJitter=Me,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=Me,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=Qn(),this._headBatchSize=d,m&&(this._headBatchFailures++,this._headBatchChargeableAt=Ri()+this._nextFlushDelay()),this._headBatchFailures<e_)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=Me,this._resetHeadBatchBudget(),this._recordDrop(d,`the ingestion endpoint failed ${e_} 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=Me,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 rO=5e3,nO=512,sO=2048,oO=128,iO=128,aO=128,cO=8192,uO=1e4,lO=36e5;function Dt(t,e){return typeof t=="number"&&Number.isInteger(t)&&t>=1?t:e}var r_=["service.name","service.version","deployment.environment"];function dO(t){if(!(!t||typeof t!="object"||Array.isArray(t)))try{if(r_.every(r=>!(r in t)||typeof t[r]=="string"))return t;let e={...t};for(let r of r_)r in e&&typeof e[r]!="string"&&delete e[r];return e}catch{return}}function fO(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 il(t,e,r){let n=Et({...e},dO(t?.resourceAttributes)),s=Dt(t?.maxExportBatchSize,nO);return{serviceName:n?.["service.name"]??t?.serviceName,serviceVersion:n?.["service.version"]??t?.serviceVersion,environment:n?.["deployment.environment"]??t?.environment,resourceAttributes:n,beforeSpanSend:fO(t?.beforeSpanSend,r),maxAttributesPerSpan:Dt(t?.maxAttributesPerSpan,oO),maxEventsPerSpan:Dt(t?.maxEventsPerSpan,iO),maxAttributesPerEvent:aO,maxAttributeValueLength:Dt(t?.maxAttributeValueLength,cO),flushIntervalMs:Dt(t?.flushIntervalMs,rO),maxExportBatchSize:s,maxQueueSize:Math.max(Dt(t?.maxQueueSize,sO),s),maxLiveSpans:Dt(t?.maxLiveSpans,uO),maxSpanAgeMs:Dt(t?.maxSpanAgeMs,lO)}}var al=require("node:fs"),o_=require("node:fs/promises"),ul=require("node:path"),i_=require("node:readline"),Oi=new Q.ReduceableCache(25),cs=new Q.ReduceableCache(20),ll=7,pO=1e3,gO=1e4,cl=10485760;async function a_(t,e=o_.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"||SO(u)||yO(c)||!(0,ul.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=c_(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=wO(u);if(l.every(p=>bO(c,p)))continue;let d=TO(Oi,c,{});i.push(hO(a,l,d,c,e,r))}return await Promise.all(i).catch(()=>{}),t&&t.length>0&&_O(t,Oi,s),Oi.reduce(),t}async function mO(t,e,r){let n,s=!1;try{n=await e(t,al.constants.O_RDONLY|al.constants.O_NONBLOCK);let o=await n.stat();return o.isFile()?o.size>cl?void r?.debug(`Skipping source context for oversized file ${t}: ${o.size} bytes exceeds ${cl}`):(s=!0,n):void 0}catch{return}finally{n&&!s&&await n.close().catch(()=>{})}}async function hO(t,e,r,n,s,o){let i=await mO(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:cl-1})}catch{cs.set(n,1),l();return}let p;try{p=(0,i_.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]=IO(w,0),g>=S)){if(m===e.length-1){p.close(),p.removeAllListeners();return}m++;let R=e[m];if(R===void 0){p.close(),p.removeAllListeners();return}_=R[0],S=R[1]}})})}function _O(t,e,r){for(let n of t)if(n.filename&&n.context_line===void 0&&typeof n.lineno=="number"){let s=c_(n.filename,r),o=s===void 0?void 0:e.get(s);if(o===void 0)continue;EO(n.lineno,n,o)}}function EO(t,e,r){if(e.lineno===void 0||r===void 0)return;e.pre_context=[];for(let s=u_(t);s<t;s++){let o=r[s];if(o===void 0)return void n_(e);e.pre_context.push(o)}if(r[t]===void 0)return void n_(e);e.context_line=r[t];let n=l_(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 n_(t){delete t.pre_context,delete t.context_line,delete t.post_context}function SO(t){return t.startsWith("node:")||t.endsWith(".min.js")||t.endsWith(".min.cjs")||t.endsWith(".min.mjs")||t.startsWith("data:")}function yO(t){return t.lineno!==void 0&&t.lineno>gO||t.colno!==void 0&&t.colno>pO}function c_(t,e){return(0,ul.isAbsolute)(t)?JSON.stringify([null,t]):e===void 0?void 0:JSON.stringify([e,t])}function bO(t,e){let r=Oi.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 wO(t){if(!t.length)return[];let e=0,r=t[0];if(typeof r!="number")return[];let n=s_(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+ll:(s.push(n),n=s_(o)),e++}return s}function s_(t){return[u_(t),l_(t)]}function u_(t){return Math.max(1,t-ll)}function l_(t){return t+ll}function TO(t,e,r){let n=t.get(e);return n===void 0?(t.set(e,r),r):n}function IO(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 Jr=require("path");function d_(t=process.cwd()){let e=Jr.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,Jr.isAbsolute)(o.filename)&&(o.filename=r((0,Jr.relative)(n,r(o.filename))));return s}}var f_="5.56.2";var yt={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var Ft=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(yt.ERRORS_WHILE_COMPUTING),this._quotaLimited&&o.push(yt.QUOTA_LIMITED),r===void 0&&o.push(yt.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 vO=6e4;function p_(t){return t==="client"||t==="server"?t:"all"}function RO(t,e){return t===e||t==="all"||e==="all"}var fr=class t extends Error{constructor(e){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,t.prototype)}};function AO(t,e){t.name=e.name,Error.captureStackTrace(t,e),Object.setPrototypeOf(t,e.prototype)}var ct=class t extends Error{constructor(e){super(e),AO(this,t)}},Mi=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 ct||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 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 ct||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}`)),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=Ku(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 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"&&(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 M(`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 M("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new M(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let i=e.dependency_chain;if(!Array.isArray(i))throw new M(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof i})`);if(i.length===0)throw new M(`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 M(`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 M(`Missing flag dependency '${c}' for flag '${o}'`)}if(s[c]==null)throw new M(`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 Hu(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,R=o.multivariate?.variants||[];g=w&&R.some(v=>v.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 ct)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,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 m_(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):g_(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 Xu(e.key,r,e.filters?.multivariate?.variants||[])}variantLookupTable(e){return pi(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?p_(r.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(e){return this.featureFlags.filter(r=>RO(p_(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(vO,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 fr(`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 fr(`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 fr(`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 fr&&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 fr("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 Nt(r,e,()=>{throw new Error(`Cache shutdown timeout after ${e}ms`)})}catch(r){this.onError?.(new Error(`Error during cache shutdown: ${r}`))}}};function g_(t,e,r,n){return Wu(t,e,{warnFunction:r,propertyMatchingVersion:n})}function OO(t,e){if(!(t in e))throw new ct(`cohort ${t} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function m_(t,e,r,n=!1,s,o){let i=String(t.value);OO(i,r);let a=r[i];return h_(a,e,r,n,s,o)}async function h_(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 h_(u,e,r,n,s,o);if(i==="AND"){if(!l)return!1}else if(l)return!0}catch(l){if(l instanceof ct)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 i==="AND"}for(let u of a)try{let l;if(u.type==="cohort")l=await m_(u,e,r,n,s,o);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=g_(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 ct)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 i==="AND"}var MO=["--unhandled-rejections","--unhandled_rejections"],PO=new Set(["throw","strict","warn","warn-with-error-code","none"]),xO=[...globalThis.process?.execArgv??[]],kO=globalThis.process?.env?.NODE_OPTIONS;function NO(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 __(t){let e;for(let r=0;r<t.length;r++){let n=t[r],s=MO.find(i=>n===i||n.startsWith(`${i}=`));if(!s)continue;let o=n===s?t[++r]:n.slice(s.length+1);PO.has(o)&&(e=o)}return e}function CO(t=xO,e=kO){return __(t)??__(NO(e??""))??"throw"}var E_=CO();function S_(t,e,r){t(e,{mechanism:{type:r==="unhandledRejection"?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function DO(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;S_(t,n,s),!r&&o===0&&(r=!0,e(n))},{_posthogErrorHandler:!0})}function y_(t,e,r=E_){let n=globalThis.process;if(n){if(r==="strict")return void n.on("uncaughtExceptionMonitor",(s,o)=>S_(t,s,o));n.on("uncaughtException",DO(t,e))}}function b_(t,e=E_){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 FO=2e3,dl=class t{constructor(e,r,n){this.client=e,this._exceptionAutocaptureEnabled=r.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new Yo({...km(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=Q.getInjectedReleaseId();return c&&(i.$release_id=c),{event:"$exception",distinctId:s,properties:{...a,...i},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(y_(this.onException.bind(this),this.onFatalError.bind(this)),b_(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(FO),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}},pr=dl;var mM=/^[0-9a-f]{32}$/i,hM=/^[0-9a-f]{16}$/i,_M;async function tS(){try{let e=(await(_M??=Promise.resolve().then(()=>(eS(),QE)))).trace.getActiveSpan()?.spanContext(),r=e?.traceId,n=e?.spanId;if(typeof r=="string"&&typeof n=="string"&&mM.test(r)&&hM.test(n)&&!/^0+$/.test(r)&&!/^0+$/.test(n))return{$trace_id:r.toLowerCase(),$span_id:n.toLowerCase()}}catch{}return{}}var Ki=class{getProperty(e){return this._memoryStorage[e]}setProperty(e,r){this._memoryStorage[e]=r!==null?r:void 0}constructor(){this._memoryStorage={}}};function EM(t){return t==="v0"||t==="v1"}function rS(){let t="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return EM(t)?t:"v0"}var SM="$ai_",ms="analytics";function nS(t){return typeof t.event=="string"&&t.event.startsWith(SM)}var en=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 ql(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 yM(t){return typeof t=="string"?t:void 0}var bM=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:ql},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:ql},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:ql},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:yM}],wM=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function TM(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function IM(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 sS(t,e,r){r!==void 0&&!(e in t)&&(t[e]=r)}function vM(t){let r={...TM(t.properties)?t.properties:{}},n={};for(let{property:o,optionKey:i,coerce:a}of bM)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 wM)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,sS(r,"$set",t.$set),sS(r,"$set_once",t.$set_once),{event:String(t.event??""),uuid:String(t.uuid??""),distinct_id:String(t.distinct_id??""),timestamp:IM(t.timestamp),...s,options:n,properties:r}}function oS(t,{createdAt:e,historicalMigration:r}){let n={created_at:e,batch:t.map(vM)};return r&&(n.historical_migration=!0),n}var RM="/i/v1/analytics/events",AM=3e4,OM=new Set([408,500,502,503,504]),Gi=class{constructor(e,r){this.config=e,this.maxBackoffMs=e.maxBackoffMs??AM,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}=oS(e,{createdAt:n,historicalMigration:this.config.historicalMigration}),o=`${this.config.host}${RM}`,i=[],a=s,c=Math.max(1,this.config.maxAttempts);for(let u=1;u<=c;u++){let l=u===c,d=xt({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&&OM.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(R){if(h.aborted)throw R;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 en({requestId:r,drops:i,retryExhausted:b.map(R=>R.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 en({requestId:e,drops:r,retryExhausted:n.map(o=>o.uuid),cause:s}))}surfacePartialDrops(e,r){r.length>0&&this.onError(new en({requestId:e,drops:r,retryExhausted:[]}))}async cancelBody(e){try{await e.body?.cancel()}catch{}}};var gr="ai-capture",zi="/i/v0/ai/batch/";var PM=new TextEncoder;function Zl(t){return PM.encode(xt(t)).length}function iS(t,e=8388608,r=5242880){let n=[],s=[],o=[],i=0;for(let a of t){if(a===void 0)continue;let c=Zl(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 xM=100,aS=3e4,kM=5e4,NM=50,CM=500,DM="https://us.i.posthog.com",cS=new Set;function Yi(t,e){cS.has(t)||(cS.add(t),console.warn(`[PostHog] ${e}`))}function FM(t){return typeof t=="string"?t.trim():""}function LM(t){return(typeof t=="string"?t.trim():"")||void 0}function UM(t){return(typeof t=="string"?t.trim():"")||DM}function $M(t){return(Array.isArray(t)?t:[t]).filter(r=>typeof r=="string"&&r.trim().length>0)}function BM(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 qi=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=FM(e),s={...r,maxQueueSize:r.maxQueueSize??1e4,flushInterval:r.flushInterval??5e3,host:UM(r.host),personalApiKey:LM(r.secretKey??r.personalApiKey)};if(super(n,s),this._memoryStorage=new Ki,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=s,this.captureMode=rS(),this.enableFullAiCapture=s.enableFullAiCapture===!0,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof s.featureFlagsPollingInterval=="number"?Math.max(s.featureFlagsPollingInterval,xM):s.featureFlagsPollingInterval===null?null:aS,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 Mi({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 pr(this,s,this._logger),this._distinctIdHasSentFlagCalls=new Map,this.maxCacheSize=s.maxCacheSize||kM}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??CM,s=r>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),s)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??NM;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"&&nS(e)?"ai":ms}persistedQueueKeyForRoute(e){return e===gr?he.AiCaptureQueue:e==="ai"?he.AiQueue:he.Queue}getActiveQueueRoutes(){let e=this.captureMode==="v1"?[ms,"ai"]:[ms];return this._aiCaptureRouteActive&&e.push(gr),e}getBatchEndpointPath(e){return e===gr?zi:super.getBatchEndpointPath(e)}async sendBatch(e,r,n=ms){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}=iS(e);for(let{event:o,bytes:i}of s){let a=`Event ${o} (${i} bytes) exceeds the ${8388608/1048576}MiB limit for ${zi}, 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(!zr(n))throw n;if(e.length===1){let[o]=e,a=`Event ${typeof o.event=="string"?o.event:"unknown"} (${Zl(o)} bytes) was rejected with 413 by ${zi} 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 Gi({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 f_}get metrics(){return this._metrics||(this._metrics=new rs(this,Si(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,il(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)??Ct(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,Ct(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=cr(e.uuid,fe);return this._sendPreparedAiEvent({...e,uuid:r},!1),r}async captureAiImmediate(e){if(this.disabled)return;let r=cr(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=$M(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=aS){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 I=this._flagOverrides[e];if(I===void 0)return;let A=this._payloadOverrides?.[e];return{key:e,enabled:I!==!1,variant:typeof I=="string"?I:void 0,payload:A}}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,R,v;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let I=this.featureFlagsPoller?.featureFlagsByKey[e];if(I)try{let A=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(I,p,{matchValue:s});if(A){m=!0;let T=A.value;b=I.id,R="Evaluated locally",v=I.has_experiment,g={key:e,enabled:T!==!1,variant:typeof T=="string"?T:void 0,payload:A.payload??void 0,reason:R,reasonCode:I.active===!1?"flag_disabled":void 0}}}catch(A){if(A instanceof ct||A instanceof M)this._logger?.info(`${A.name} when computing flag locally: ${e}: ${A.message}`);else throw A}}if(!m&&!c){let I=await super.getFeatureFlagDetailsStateless(p.distinctId,p.groups,u,l,a,[e]);if(I===void 0)S=yt.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=I.minimalFlagCalledEvents===!0,h=I.requestId,_=I.evaluatedAt;let A=[];I.errorsWhileComputingFlags&&A.push(yt.ERRORS_WHILE_COMPUTING),I.quotaLimited?.includes("feature_flags")&&A.push(yt.QUOTA_LIMITED);let T=I.flags[e];if(T===void 0)A.push(yt.FLAG_MISSING);else{b=T.metadata?.id,w=T.metadata?.version,R=T.reason?.description??T.reason?.code,v=T.metadata?.has_experiment;let P;if(T.metadata?.payload!==void 0)try{P=JSON.parse(T.metadata.payload)}catch{P=T.metadata.payload}g={key:e,enabled:T.enabled,variant:T.variant??void 0,payload:P,reason:R,reasonCode:T.reason?.code}}A.length>0&&(S=A.join(","))}}if(o){let I=g===void 0?void 0:g.enabled===!1?!1:g.variant??!0,A={$feature_flag:e,$feature_flag_response:I,$feature_flag_id:b,$feature_flag_version:w,$feature_flag_reason:R,locally_evaluated:m,[`$feature/${e}`]:I,$feature_flag_request_id:h,$feature_flag_evaluated_at:m?Date.now():_};if(v!==void 0&&(A.$feature_flag_has_experiment=v),m&&this.featureFlagsPoller){let T=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();T!==void 0&&(A.$feature_flag_definitions_loaded_at=T)}S&&(A.$feature_flag_error=S),this._captureFlagCalledEventIfNeeded({distinctId:r,key:e,response:I,groups:i,disableGeoip:a,properties:A})}return g!==void 0&&this._payloadOverrides!==void 0&&e in this._payloadOverrides&&(g={...g,payload:this._payloadOverrides[e]}),g}async getFeatureFlag(e,r,n){Yi("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(Yi("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){Yi("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 Ft({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new Ft({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,flags:{}});let{groups:o,disableGeoip:i}=s||{},a=s?.flagKeys??void 0;if(a?.length===0)return new Ft({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),R=new Set;if(w)for(let[I,A]of Object.entries(w.response)){let T=this.featureFlagsPoller?.featureFlagsByKey[I];m[I]={key:I,enabled:A!==!1,variant:typeof A=="string"?A:void 0,payload:w.payloads[I],id:T?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:T?.has_experiment},R.add(I)}let v=g!==void 0&&Array.from(g).some(I=>this.featureFlagsPoller?.featureFlagsByKey[I]===void 0);if((w?w.fallbackToFlags||v:!0)&&!c){let I=await super.getFeatureFlagDetailsStateless(p.distinctId,p.groups,u,l,i,a);if(I){this._minimalFlagCalledEvents=I.minimalFlagCalledEvents===!0,h=I.requestId,_=I.evaluatedAt,S=!!I.errorsWhileComputingFlags,b=Array.isArray(I.quotaLimited)&&I.quotaLimited.includes("feature_flags");for(let[A,T]of Object.entries(I.flags)){if(R.has(A))continue;let P;if(T.metadata?.payload!==void 0)try{P=JSON.parse(T.metadata.payload)}catch{P=T.metadata.payload}m[A]={key:A,enabled:T.enabled,variant:T.variant,payload:P,id:T.metadata?.id,version:T.metadata?.version,reason:T.reason?.description??T.reason?.code,locallyEvaluated:!1,hasExperiment:T.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[I,A]of Object.entries(this._flagOverrides)){if(A===void 0){delete m[I];continue}let T=m[I];m[I]={key:I,enabled:A!==!1,variant:typeof A=="string"?A:void 0,payload:T?.payload,id:T?.id,version:T?.version,reason:T?.reason,locallyEvaluated:T?.locallyEvaluated??!1,hasExperiment:T?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[I,A]of Object.entries(this._payloadOverrides)){let T=m[I];T&&(m[I]={...T,payload:A})}if(g!==void 0)for(let I of Object.keys(m))g.has(I)||delete m[I];return new Ft({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 Nt(this._metrics.flush().catch(()=>{}),Math.max(0,r-Date.now())),this._metrics.reset()),this._traces&&(await Nt(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(Mm(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(!pr.isPreviouslyCapturedError(e)){let i=new Error("PostHog syntheticException");this.addPendingPromise(pr.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(!pr.isPreviouslyCapturedError(e)){let o=new Error("PostHog syntheticException");return this.addPendingPromise(pr.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 tS()),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){Yi("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,R=await this.getFeatureFlagsForEvent(S.distinctId,i,l,w);return BM(R)}return{}}).catch(()=>({})).then(w=>{let R=S.groups||i;return{...w,...S.properties||{},...R!==void 0&&Object.keys(R).length>0?{$groups:R}:{}}});return S.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof b.$raw_user_agent=="string"&&xm(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 uS=require("node:async_hooks"),Ji=class{constructor(){this.storage=new uS.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 lS=require("node:async_hooks"),Zi=class{active(){return this._storage.getStore()}with(e,r){return this._storage.run(e,r)}constructor(){this._storage=new lS.AsyncLocalStorage}};var dS=require("node:zlib"),fS=require("node:util"),jM=(0,fS.promisify)(dS.gzip);async function pS(t,e=!0){try{let r=await jM(t);return new Uint8Array(r)}catch(r){return e&&console.error("Failed to gzip compress data",r),null}}var Qi=require("node:os");function gS(){let t,e;try{t=(0,Qi.platform)(),e=(0,Qi.release)()}catch{}return Yu(t,e)}var mS="posthog-node";function WM(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[Ql.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=Q.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 Ql=class{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(e,r,n,s,o){this.name=mS,this.name=mS,this.setupOnce=function(i,a){let c=a()?.getClient()?.getDsn()?.projectId;i(WM(e,{organization:r,projectId:c,prefix:n,severityAllowList:s,sendExceptionsToPostHog:o??!0}))}}};var ea=class extends qi{getLibraryId(){return"posthog-node"}compressPayload(e){return pS(e,this.isDebug)}initializeContext(){return new Ji}initializeSpanContextManager(){return new Zi}hostResourceAttributes(){return gS()}createErrorPropertiesBuilder(){return new Q.ErrorPropertiesBuilder([new Q.EventCoercer,new Q.ErrorCoercer,new Q.ObjectCoercer,new Q.StringCoercer,new Q.PrimitiveCoercer],Q.createStackParser("node:javascript",Q.nodeStackLineParser),[Im(),e=>a_(e,void 0,this._logger),d_()])}};Za();nc();rc();oc();var oK=300*1e3,iK=3600*1e3;O();var td=null,HM=!1,XM=3e4,ta=null;function _S(){let t=Date.now();if(ta&&t<ta.expiresAt)return ta.value;let e=Gs(process.env,mn());return ta={value:e,expiresAt:t+XM},e}var KM=!1;function GM(){if(!td){let t=KM&&Lf(process.env)&&_S();td=new ea(Ys(),{host:qs(),flushAt:20,flushInterval:1e4,disableGeoip:!1,enableExceptionAutocapture:t,before_send:tP})}return td}var zM=6e4,VM=500,hs=new Map;function YM(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}::${Hf(e)}::${n}`.slice(0,400)}function qM(t,e){try{return JM(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 JM(t,e){let r=hs.get(t);if(!r){if(hs.size>=VM){let n=null,s=1/0;for(let[o,i]of hs){let a=Math.max(i.lastSentTs,i.firstTs);a<s&&(s=a,n=o)}n!==null&&hs.delete(n)}return r={count:1,firstTs:e,lastSentTs:e},hs.set(t,r),{send:!0,count:1}}if(r.count+=1,e-r.lastSentTs>=zM){r.lastSentTs=e;let n=r.count;return r.count=0,{send:!0,count:n}}return{send:!1,count:r.count}}var hS="__cm_rate_limited";function ZM(t){try{return typeof t!="string"||t.length===0?"":ec(Qa(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 QM(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=Wf(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=ZM(a.filename))}}}function eP(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 tP(t){try{if(!t||typeof t!="object")return t;let e=t;if(e.event!=="$exception")return t;let r=e.properties??{};if(eP(r))return null;if(r[hS]){try{delete r[hS],e.properties=r}catch{}return t}QM(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=YM(n,s,o),a=qM(i,Date.now());if(!a.send)return null;try{r.occurrence_count=a.count,e.properties=r}catch{}return t}catch{return null}}function ed(t,e,r){try{rP(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 rP(t,e,r){if(HM||!_S())return;let n=Vs({...Zs(),...e??{}});if(r?.person?n.$set=Js(n):n.$process_person_profile=!1,process.env.MEMINDEX_TELEMETRY_DEBUG==="1"){process.stderr.write("[telemetry] "+JSON.stringify({event:t,properties:n})+`
43
+ `);return}GM().capture({distinctId:zs(),event:t,properties:n})}var nP=["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"],sP=new Set(nP),ES={skill_id:"other",skill_source:"third_party"};function SS(t){let e=oP(t);return e&&sP.has(e)?{skill_id:e,skill_source:"first_party"}:ES}function yS(t,e){if(t==="Skill"&&!(!e||typeof e!="object"))return e.skill}function oP(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}O();nt();function iP(t){return["false","0","off","no"].includes(String(t??"").trim().toLowerCase())}function bS(t){return!iP(t.MEMINDEX_OBSERVER_ENABLED)}na();var TS=null,cP=new Set(["SetTodoList","TodoList","TaskList","TaskOutput","TaskStop","CronCreate","CronList","CronDelete"]),IS=new Map;function uP(t){let e=IS.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 IS.set(t,r),r}function lP(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 dP(){if(!TS)throw new Error("ingest helpers used before setIngestContext() \u2014 wiring bug");return TS}async function vS(t,e={}){if(tn(t.toolName))return{ok:!0,status:"skipped",reason:"memory_retrieval"};if(!bS(z.loadFromFile(ae)))return{ok:!0,status:"skipped",reason:"observer_disabled"};let{sessionManager:r,dbManager:n,eventBroadcaster:s,ensureGeneratorRunning:o}=dP(),i=V(t.platformSource),a=typeof t.cwd=="string"?t.cwd:"",c=a.trim()?await yn(a):null,u=c?.primary||"unknown",l=z.loadFromFile(ae);if(a&&ro(a,l.MEMINDEX_EXCLUDED_PROJECTS))return{ok:!0,status:"skipped",reason:"project_excluded"};if(Pt(t.toolName,l.MEMINDEX_SKIP_TOOLS)){if(t.toolName==="Skill"){let{skill_id:v,skill_source:y}=SS(yS(t.toolName,t.toolInput));ed("skill_invoked",{skill_id:v,skill_source:y,skill_trigger:"tool",ide:i})}return{ok:!0,status:"skipped",reason:"tool_excluded"}}if(i==="kimi"&&cP.has(t.toolName))return{ok:!0,status:"skipped",reason:"tool_excluded"};let d=l.MEMINDEX_SKIP_BASH_PATTERNS.trim(),p=d?lP(t.toolName,t.toolInput):"";if(p){let v=uP(d);if(v&&v.test(p))return{ok:!0,status:"skipped",reason:"bash_pattern_excluded"}}let g=Ur(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 v=t.toolInput,y=v.file_path||v.notebook_path;if(y&&y.includes("session-memory"))return{ok:!0,status:"skipped",reason:"session_memory_meta"};if(y&&wm(y))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(v){let y=v instanceof Error?v.message:String(v);return f.error("INGEST","Observation session resolution failed",{contentSessionId:t.contentSessionId,toolName:t.toolName},v instanceof Error?v:new Error(y)),{ok:!1,reason:y,status:500}}if(!Ko.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)):"{}",R=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:R,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(v){f.warn("INGEST","tool_uses backup write failed (observation still queued)",{sessionId:_,toolName:t.toolName,toolUseId:t.toolUseId},v instanceof Error?v:new Error(String(v)))}return ra(t.toolName)?{ok:!0,status:"skipped",reason:"explicit_memory_write"}:(r.queueObservation(_,{tool_name:t.toolName,tool_input:w,tool_response:R,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 fP=/agent-transcripts[/\\]([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:[/\\]|$)/i;function pP(t){let e=typeof t.agentId=="string"?t.agentId.trim():"";return e&&e!=="*"?e:t.path.match(fP)?.[1]}var Es=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}},Ss=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}},gP=4096,mP=64,sa=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:V(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>gP){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=Lr(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=Lr(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=Lr(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=Em(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-mP))){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 Fo({sessionId:e.sessionId,cwd:n,prompt:r,platform:e.platformSource})}catch(s){throw new Es(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:pP(r)};if(this.observationTransport==="spool"){try{He("observation",o)}catch(a){throw new mr(e.sessionId,a)}return}let i=!1;try{let a=await vS(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 Ss(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 fm.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{He("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 xr())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"||Yd(r)||!await xr())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=_s.default.resolve(c),l=[_s.default.resolve(s),_s.default.resolve(j)];if(!l.some(m=>u.startsWith(m+_s.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&&(mm(c,g),f.debug("TRANSCRIPT","Updated AGENTS.md context",{agentsPath:c,watch:r.name}))}};var RS=_e(require("node:zlib"),1),rn=require("node:fs");O();function AS(){let t=RS.zstdDecompressSync;return typeof t=="function"?t:void 0}function OS(){return AS()!==void 0}var hP=4247762216,_P=64*1024;function oa(t,e,r,n=Number.POSITIVE_INFINITY){let s=(0,rn.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,_P),r-l),g=Buffer.alloc(p);if(o=g.subarray(0,(0,rn.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)!==hP)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,R=(h?0:1)+b+w;if(u+R>r)return{frames:c,tornStart:l};for(u+=R;;){let v=a(u,3);if(!v)return{frames:c,tornStart:l};let y=v.readUIntLE(0,3);u+=3;let I=(y&1)!==0,A=y>>>1&3,T=y>>>3;if(A===3)throw new Error(`reserved Zstandard block type at byte ${u-3}`);let P=A===1?1:T;if(u+P>r)return{frames:c,tornStart:l};if(u+=P,I)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,rn.closeSync)(s)}}function rd(t,e){try{let r=AS();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 MS(t,e){return rd(t,e).toString("utf8")}var PS=2e3,EP=1e3,SP=256*1024,xS=4*1024*1024,yP=16*1024*1024,bP=100,kS=100;function ys(){return new Promise(t=>setImmediate(t))}var ia=".jsonl.zstd";async function wP(t,e){try{let r=0;for(;r<e;){let n=oa(t,r,e,yP);if(n.tornStart!==null)return n.tornStart;if(n.frames.length===0)break;r=n.frames[n.frames.length-1].end,await ys()}return r}catch{return e}}var NS=1024*1024;async function FS(t,e,r){let n;if(e){let{frames:o}=oa(t,0,Math.min(r,NS),1);if(o.length===0)return null;n=MS(await ca(t,0,o[0].end),o[0])}else n=(await ca(t,0,Math.min(r,NS))).toString("utf8");let s=n.indexOf(`
46
+ `);return s<0?null:n.slice(0,s)}async function TP(t,e,r){try{let n=await FS(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 aa(t){return`${t.dev}:${t.ino}`}function IP(t){try{return(0,X.statSync)(t),!1}catch(e){let r=e.code;return r==="ENOENT"||r==="ENOTDIR"}}var vP=4096;function sd(t,e,r){let n;try{if(n=(0,X.openSync)(t,"r"),aa((0,X.fstatSync)(n))!==r)return null;let s=Math.max(0,e-vP),o=Buffer.alloc(e-s);return(0,X.readSync)(n,o,0,o.length,s)<o.length?null:(0,CS.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 LS(t,e,r,n,s){return r<n?!1:s===void 0?!0:sd(t,n,e)===s}async function ca(t,e,r){let n=await(0,DS.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 nd=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(ia),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 ys();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=aa(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&&(LS(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:sd(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 ca(this.filePath,r,Math.min(e-r,xS))}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%kS===0&&(this.checkpoint(this.tailState.offset),await ys())}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=oa(this.filePath,r,e,xS),n.frames.length===0)return;let i=n.frames[n.frames.length-1].end;if(s=await ca(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=rd(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%kS===0&&await ys()}}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)}},ua=class{constructor(e,r,n="in-process"){this.config=e;this.statePath=r;this.processor=new sa(n),this.state=rf(r)}config;statePath;processor;tailers=new Map;state;fileContexts=new Map;retirementCandidates=new Set;retirementTimer=null;missingTranscriptGraceMs=EP;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 ys();o.stateChanged&&fn(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,Z.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,Z.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))},bP);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 aa(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)||!IP(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&&fn(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,Z.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(Z.sep)}return r}selectWatchRoot(e){let r=this.literalWatchPrefix(e);if(!r)return null;let n=(0,Z.resolve)(r);try{return{root:(0,X.statSync)(n).isDirectory()?n:(0,Z.resolve)(n,".."),recursive:!0}}catch{}for(let s=(0,Z.resolve)(n,"..");(0,Z.resolve)(s,"..")!==s;s=(0,Z.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,Z.join)(e,"**","*.jsonl"))),...this.scanGlob(this.normalizeGlobPattern((0,Z.join)(e,"**",`*${ia}`)))]:[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(ia);if(i&&!OS()){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-PS&&await this.startedAfterThisWatcher(e,i,m.size)||(l=i?await wP(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=aa(m),_=this.state.fileIdentities?.[e],S=u!==void 0&&_!==void 0&&!LS(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=sd(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?fn(this.statePath,this.state):o&&(o.stateChanged=!0));let p=l>0&&(!!n.sessionIdPath||!!r.subagentSource||!c.cwd),g=new nd(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],fn(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 TP(e,r,n);return s!==null?s>=this.startedAtMs-PS:n<=SP}async primeFromFirstLine(e,r,n,s,o,i){try{let a=await FS(e,e.endsWith(ia),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,Z.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 Es||a instanceof Ss||a instanceof mr)throw f.warn("TRANSCRIPT","Transcript event not accepted; it is retried from its own line",{watch:r.name,file:(0,Z.basename)(s),error:a.message}),a;a instanceof Error?f.debug("TRANSCRIPT","Failed to parse transcript line",{watch:r.name,file:(0,Z.basename)(s)},a):f.warn("TRANSCRIPT","Failed to parse transcript line (non-Error thrown)",{watch:r.name,file:(0,Z.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 Ny(t){(0,Cy.existsSync)(ce(t))||(ka(t),console.log(`Created sample config: ${ce(t)}`))}async function Dy(t,e){switch(t){case"init":{let r=Sd(e,"--config")??yr;return ka(r),console.log(`Created sample config: ${ce(r)}`),0}case"watch":{let r=Sd(e,"--config")??yr;Ny(r);let n=z.loadFromFile(ae),{config:s,scoped:o,removed:i}=qd(xa(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??Ns),c=new ua(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")??yr;return Ny(r),xa(r),console.log(`Config OK: ${ce(r)}`),0}case"import":return Hx(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 Hx(t){let{defaultTranscriptImportDeps:e,formatTranscriptImportResult:r,isoOf:n,parseTranscriptImportArgs:s,runTranscriptImport:o,TRANSCRIPT_IMPORT_USAGE:i}=await Promise.resolve().then(()=>(ky(),xy)),{settleHookSpoolNudges:a}=await Promise.resolve().then(()=>(Fr(),am)),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 Xx=process.argv[2],Kx=process.argv.slice(3);Dy(Xx,Kx).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: